{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# \"Capstone: a running data stack for a small lab\"\n",
    "\n",
    "Ingest, model, test, schedule, monitor and serve one lab's chemistry data end to end, with every tool of the series in one module, stack.py. Run a new lab's twelve weeks through it, read the record it keeps, open its dashboard, and write what a colleague needs to take it over. Then build one for a lab of your own.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-2/11-capstone/"
   ]
  },
  {
   "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 pandera pandera-chem prefect requests streamlit altair\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(\"stack.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/11-capstone/stack.py\", \"stack.py\")\n",
    "if not pathlib.Path(\"dashboard.py\").exists():\n",
    "    pathlib.Path(\"dashboard.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/11-capstone/dashboard.py\", \"dashboard.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": [
    "Ten modules have each added one piece: a raw layer that dlt fills\n",
    "([Module 2](../02-declarative-ingestion/)), a star schema ([Module\n",
    "3](../03-modelling-the-warehouse/)) that dbt builds, tests and keeps the history of (Modules\n",
    "[4](../04-transformations-with-lineage/) to [6](../06-history-and-corrections/)), a Prefect flow\n",
    "that runs it every week ([Module 7](../07-orchestration/)), checks that say when something looks\n",
    "wrong ([Module 8](../08-observability/)), a CI script that checks every change to the code\n",
    "([Module 9](../09-continuous-integration/)), and a dashboard for the chemists ([Module\n",
    "10](../10-structure-activity-dashboards/)). This module puts them together into one **stack** that\n",
    "runs a lab's data from the files to the dashboard, and then hands it over.\n",
    "\n",
    "The lab is a new one. `labdata.Lab(seed=2)` is the same kind of kinase project as the lab of the\n",
    "whole series (the same planted problems in the same weeks), but with different compounds, results\n",
    "and chemists' choices. A stack that only works on the data it was built with is not finished; one\n",
    "that runs another lab's twelve weeks without a change is closer to something a lab could rely on.\n",
    "\n",
    "As in Series 1's capstone, the code lives in one file next to this lesson, `stack.py`, a Python\n",
    "module that the lesson imports. It is the kind of file a lab would keep in its repository: other code\n",
    "can import it, the CI of Module 9 can test it, and a server can run it. In Colab, the notebook's first\n",
    "cell downloads it. [Read `stack.py` on GitHub](https://github.com/David-Alobo/monstrous-learn/blob/main/data-engineering/series-2/11-capstone/stack.py);\n",
    "every function has a short description. The lesson ends with the **capstone brief**: the project you\n",
    "build to complete the series, and how it is judged.\n",
    "\n",
    "## Setup\n",
    "\n",
    "The Setup is Module 7's: Prefect keeps its files in `work/`, and the same logging filters keep its\n",
    "lines plain and the outputs the same on every computer. Prefect's own lines are shown only from\n",
    "warnings up, which here means the alerts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import shutil\n",
    "from pathlib import Path\n",
    "\n",
    "WORK = Path(\"work\")  # where the lesson writes its files (git-ignored)\n",
    "shutil.rmtree(WORK, ignore_errors=True)  # start clean, before Prefect keeps its files in work/\n",
    "(WORK / \"prefect\").mkdir(parents=True)\n",
    "os.environ[\"PREFECT_HOME\"] = str((WORK / \"prefect\").resolve())\n",
    "os.environ[\"PREFECT_SERVER_ANALYTICS_ENABLED\"] = \"false\"\n",
    "\n",
    "import json\n",
    "import logging\n",
    "\n",
    "import duckdb\n",
    "from prefect.client.orchestration import get_client\n",
    "from streamlit.testing.v1 import AppTest\n",
    "\n",
    "import labstack\n",
    "import stack\n",
    "\n",
    "logging.basicConfig(level=logging.INFO, format=\"%(levelname)s %(message)s\", force=True)\n",
    "log = logging.getLogger(__name__)\n",
    "logging.getLogger(\"httpx\").setLevel(logging.WARNING)\n",
    "\n",
    "\n",
    "def named(record: logging.LogRecord) -> bool:\n",
    "    \"\"\"Start each of Prefect's lines with its run's name, and leave out tracebacks.\"\"\"\n",
    "    name = getattr(record, \"task_run_name\", None) or getattr(record, \"flow_run_name\", None)\n",
    "    if name:\n",
    "        record.msg, record.args = f\"{name}: {record.getMessage()}\", ()\n",
    "    record.exc_info = record.exc_text = None\n",
    "    return True\n",
    "\n",
    "\n",
    "for name in (\"prefect.flow_runs\", \"prefect.task_runs\"):\n",
    "    logging.getLogger(name).addFilter(named)\n",
    "    logging.getLogger(name).setLevel(logging.WARNING)  # warnings only: here, the alerts\n",
    "logging.getLogger(\"prefect\").addFilter(lambda r: \"temporary server\" not in r.getMessage())\n",
    "logging.getLogger(\"streamlit.runtime.scriptrunner_utils.script_run_context\").addFilter(\n",
    "    lambda record: \"missing ScriptRunContext\" not in record.getMessage())  # expected in a test"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. The plan\n",
    "\n",
    "Each week, one run of one flow does all of this, in this order. Every stage stops the week if it\n",
    "fails for a real reason, and the published copy, and so the dashboard, keeps last week's good data:\n",
    "\n",
    "| Stage | What it does | Tool | From |\n",
    "|---|---|---|---|\n",
    "| receive | the week's files arrive in the inbox; retried if the share fails | Prefect | Module 7 |\n",
    "| load | what is new is loaded into the raw layer, unchanged | dlt | Module 2 |\n",
    "| snapshot | every version of every registration is kept | dbt | Module 6 |\n",
    "| build | staging and marts are built and tested; a failure stops the week | dbt | Modules 3 to 6 |\n",
    "| monitor | metrics are recorded; freshness, volume, schema, registrations and drift are checked | Prefect, DuckDB | Module 8 |\n",
    "| chemistry | the week's new compounds are checked | pandera-chem | Module 5 |\n",
    "| alert | every finding is logged, kept and posted to a chat channel if one is set up | Prefect | Module 8 |\n",
    "| publish | a read-only copy of the warehouse replaces last week's | DuckDB | Module 10 |\n",
    "\n",
    "Around the flow sit two things that do not run every week: the CI of Module 9, which checks every\n",
    "change to the dbt project before it is merged, and the dashboard of Module 10, which reads the\n",
    "published copy.\n",
    "\n",
    "![The lab's data stack: inside Prefect's weekly flow (Module 7), the lab's files are loaded by dlt (Module 2) into the DuckDB warehouse (raw, snapshots, staging and marts built and tested by dbt, monitoring: Modules 1 to 8), checked (Modules 5 and 8) and published (Module 10) for the Streamlit dashboard the chemists read; alerts go to a chat; CI (Module 9) checks every change to the dbt project; the hand-over (Module 11) is the dbt docs, a runbook and backups of the snapshots](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/11-capstone/figures/stack.svg)\n",
    "\n",
    "## 2. The settings\n",
    "\n",
    "Everything a run can change is in one place, `stack.Settings`, with a default for each. Its values\n",
    "are plain (text, numbers, lists), because they are passed to the flow and kept in Prefect's record\n",
    "of every run, so that anyone can see later what a run was asked to do. The chat channel's address is\n",
    "deliberately not a setting: it works like a password, so the stack reads it from the environment\n",
    "variable `LAB_ALERT_WEBHOOK` when it sends an alert, and it is never recorded."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "work             work\n",
      "seed             2\n",
      "baseline_weeks   4\n",
      "drift_limit      1.0\n",
      "volume_range     (0.5, 1.5)\n",
      "share_fails_once (9,)\n"
     ]
    }
   ],
   "source": [
    "settings = stack.Settings(work=str(WORK), seed=2, share_fails_once=(9,))\n",
    "for name, value in settings.as_dict().items():\n",
    "    print(f\"{name:16} {value}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`seed=2` chooses the new lab. `share_fails_once=(9,)` makes the lab's file share fail once in week\n",
    "9, as in Module 7, so that the record shows a retry.\n",
    "\n",
    "## 3. A tour of stack.py\n",
    "\n",
    "`stack.py` is about 550 lines, half of them descriptions. Read it with this list beside it:\n",
    "\n",
    "- **The warehouse.** `query` runs one query; `has_table` says whether a table exists yet (in week 1\n",
    "  nothing has been tested, so there is no assay table, and the build leaves out what needs one);\n",
    "  `prepare` makes the folders, copies the dbt project as Module 6 finished it, and creates the\n",
    "  monitoring tables.\n",
    "- **The tasks.** One function per stage of the plan, each marked `@task`. `receive` has retries;\n",
    "  `build` raises an error when a test fails; `check_chemistry` checks only the week's new compounds,\n",
    "  so a compound in quarantine is reported once, not every week; `publish` writes the new copy under\n",
    "  another name and then **renames** it over the old one (`os.replace`), so the dashboard always\n",
    "  finds either last week's copy or this week's, never half of one.\n",
    "- **The checks.** Module 8's five checks, each a function of the settings and the week, collected\n",
    "  in `CHECKS` and run by the `monitor` task. Each waits until it has the history it needs: freshness\n",
    "  from week 2 (the first week with results), volume from its fourth week with assay files, drift\n",
    "  after the baseline weeks.\n",
    "- **The flow.** `weekly(week, settings)` calls the tasks in the plan's order and returns a summary;\n",
    "  `run_weeks` runs it for a range of weeks and gathers the summaries into a table.\n",
    "\n",
    "Every task is marked `cache_policy=NO_CACHE`: none of them should ever be skipped because it ran\n",
    "before with the same inputs, since each depends on the state of the warehouse, which changes every\n",
    "week.\n",
    "\n",
    "## 4. Twelve weeks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "WARNING alert: schema: raw.assay changed: added ['operator', 'unit'], removed []\n",
      "WARNING alert: registrations: registration changed: LAB-0042\n",
      "WARNING alert: schema: raw.assay changed: added ['status'], removed []\n",
      "WARNING alert: freshness: no plates were run this week: the newest result is older than this week\n",
      "WARNING alert: volume: 0 assay rows arrived; usually about 128\n",
      "WARNING alert: volume: 272 assay rows arrived; usually about 128\n",
      "WARNING alert: drift: clogp moved +1.0 SD from the baseline\n",
      "WARNING alert: drift: new chemist: EF\n",
      "WARNING alert: drift: clogp moved +1.1 SD from the baseline\n",
      "          state  assay rows  tests passed  alerts\n",
      "week                                             \n",
      "1     Completed           0            11       0\n",
      "2     Completed          80            24       0\n",
      "3     Completed         128            24       0\n",
      "4     Completed         232            24       0\n",
      "5     Completed         104            24       1\n",
      "6     Completed         152            24       0\n",
      "7     Completed         112            24       1\n",
      "8     Completed         168            24       1\n",
      "9     Completed         128            24       0\n",
      "10    Completed           0            24       2\n",
      "11    Completed         272            24       3\n",
      "12    Completed          96            24       1\n"
     ]
    }
   ],
   "source": [
    "stack.prepare(settings)\n",
    "summary = stack.run_weeks(settings, range(1, 13))\n",
    "print(summary.to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Twelve weeks, twelve completed runs, and the alerts that came on the way are the lab's planted\n",
    "problems, found in a lab the stack had never seen:\n",
    "\n",
    "- week 5, the plate reader's software update (from dlt's record of the schema);\n",
    "- week 7, LAB-0042's corrected registration (from the snapshots);\n",
    "- week 8, the `status` column of the re-read plate;\n",
    "- week 10, no plates run and no assay rows: the late file;\n",
    "- week 11, the late file arriving with week 11's, and the new chemist EF's greasier compounds;\n",
    "- week 12, the drift again.\n",
    "\n",
    "Week 1 ran 11 tests, not 24: with no assay file yet, the build left out the results and everything\n",
    "built from them, and their tests with them. In week 9 the share failed once and the flow carried on.\n",
    "Here is that in Prefect's record, with every run's state:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "1:Completed 2:Completed 3:Completed 4:Completed 5:Completed 6:Completed 7:Completed 8:Completed 9:Completed 10:Completed 11:Completed 12:Completed\n",
      "needed more than one attempt: ['receive week 9']\n"
     ]
    }
   ],
   "source": [
    "with get_client(sync_client=True) as client:\n",
    "    runs = sorted(client.read_flow_runs(), key=lambda r: r.expected_start_time)\n",
    "    retried = [t.name for t in client.read_task_runs() if t.run_count > 1]\n",
    "print(\" \".join(f\"{run.name.split()[-1]}:{run.state_name}\" for run in runs))\n",
    "print(\"needed more than one attempt:\", retried)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. What the record holds\n",
    "\n",
    "The warehouse keeps its own record next to the data: every metric of every week, every alert, every\n",
    "version of every registration. The published copy has all of it, so anyone can read it without\n",
    "touching the working warehouse:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " week    check_name                                                                 message\n",
      "    5        schema               raw.assay changed: added ['operator', 'unit'], removed []\n",
      "    7 registrations                                          registration changed: LAB-0042\n",
      "    8        schema                         raw.assay changed: added ['status'], removed []\n",
      "   10     freshness no plates were run this week: the newest result is older than this week\n",
      "   10        volume                                 0 assay rows arrived; usually about 128\n",
      "   11         drift                                   clogp moved +1.0 SD from the baseline\n",
      "   11         drift                                                         new chemist: EF\n",
      "   11        volume                               272 assay rows arrived; usually about 128\n",
      "   12         drift                                   clogp moved +1.1 SD from the baseline\n",
      "compound_id  version valid_from   valid_to\n",
      "   LAB-0042        1 2026-09-14 2026-10-19\n",
      "   LAB-0042        2 2026-10-19        NaT\n",
      "                table_name  rows\n",
      "        marts.dim_compound   480\n",
      "marts.dim_compound_history   481\n",
      "            marts.dim_date    85\n",
      "          marts.dim_target     5\n",
      "    marts.fact_measurement  1344\n",
      "         monitoring.alerts     9\n",
      "        monitoring.metrics    59\n",
      "                 raw.assay  1344\n",
      "              raw.registry   480\n",
      "snapshots.registry_history   481\n"
     ]
    }
   ],
   "source": [
    "with duckdb.connect(str(settings.published), read_only=True) as db:\n",
    "    alerts = db.sql(\"SELECT * FROM monitoring.alerts ORDER BY week, check_name\").df()\n",
    "    history = db.sql(\"SELECT compound_id, version, valid_from, valid_to \"\n",
    "                     \"FROM marts.dim_compound_history WHERE compound_id IN \"\n",
    "                     \"(SELECT compound_id FROM marts.dim_compound_history WHERE version > 1)\").df()\n",
    "    sizes = db.sql(\"\"\"\n",
    "        SELECT schema_name || '.' || table_name AS table_name, estimated_size AS rows\n",
    "        FROM duckdb_tables() WHERE schema_name IN ('raw', 'snapshots', 'marts', 'monitoring')\n",
    "          AND NOT starts_with(table_name, '_dlt') ORDER BY table_name\n",
    "    \"\"\").df()\n",
    "print(alerts.to_string(index=False))\n",
    "print(history.to_string(index=False))\n",
    "print(sizes.to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`duckdb_tables()` lists every table with an estimate of its size: the raw layer as dlt loaded it,\n",
    "the snapshots, the marts and the monitoring tables. One of them is not like the others. Everything in\n",
    "`raw` can be loaded again from the inbox's files, and everything in `marts` can be built again from\n",
    "`raw`; but `snapshots.registry_history` holds versions that no file contains any more (the registry\n",
    "export is a snapshot that replaces itself). It is the one table that must be **backed up**, because\n",
    "it cannot be made again.\n",
    "\n",
    "## 6. The dashboard, on the new lab\n",
    "\n",
    "The dashboard of Module 10 is in this module's folder as `dashboard.py`, unchanged. It reads the\n",
    "published copy, so it shows the new lab without being told anything about it. `AppTest` runs it as\n",
    "in Module 10:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{'Compounds': '440', 'EGFR pIC50 of 7 or more': '68', 'Tested on the panel': '53', 'Best selectivity': '3.3'}\n",
      "[\"LAB-0042's registration changed 1 time(s): measurements before the change were made under an earlier structure.\"]\n"
     ]
    }
   ],
   "source": [
    "app = AppTest.from_file(str(Path(\"dashboard.py\").resolve()), default_timeout=120).run()\n",
    "assert not app.exception, app.exception[0].message\n",
    "print({metric.label: metric.value for metric in app.metric})\n",
    "app.selectbox[0].set_value(\"LAB-0042\").run()\n",
    "print([warning.value for warning in app.warning])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The new lab's headline numbers, and LAB-0042's page warning that its measurements were made under\n",
    "an earlier structure: the same questions, answered for a different lab, by the same code. On your\n",
    "own computer, `uv run streamlit run dashboard.py` in this module's folder (after running the lesson)\n",
    "opens it in your browser.\n",
    "\n",
    "## 7. Handing it over\n",
    "\n",
    "A stack is finished when someone else can run it. dbt documents the warehouse itself\n",
    "(Module 4, section 6): every model, column, test and the lineage, generated from the project."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "8 models, 5 with a description; 24 tests\n"
     ]
    }
   ],
   "source": [
    "docs = labstack.dbt(settings.project, \"docs\", \"generate\", log=stack.QUIET)\n",
    "manifest = json.loads((settings.project / \"target\" / \"manifest.json\").read_text(encoding=\"utf-8\"))\n",
    "models = [node for node in manifest[\"nodes\"].values() if node[\"resource_type\"] == \"model\"]\n",
    "print(len(models), \"models,\", sum(bool(m[\"description\"]) for m in models), \"with a description;\",\n",
    "      sum(node[\"resource_type\"] == \"test\" for node in manifest[\"nodes\"].values()), \"tests\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Three models have no description yet (`dim_target`, `dim_date` and `dim_compound_history`): a\n",
    "gap a colleague would meet on their first day, and the first warm-up question below.\n",
    "\n",
    "The rest is a **runbook**: a short document that tells whoever runs the stack next what it does and\n",
    "what to do when something happens. For this stack it would answer:\n",
    "\n",
    "- **What runs, and when.** The `lab-stack` flow, every Monday at 07:00 (Module 7, section 5),\n",
    "  then the dashboard's copy is replaced. Where the code, the warehouse and the logs live.\n",
    "- **How to rerun a week.** Run the flow for that week again: dlt loads each file once and the build\n",
    "  is idempotent, so a rerun is safe (Module 7, section 3).\n",
    "- **What each alert means, and who acts.** Freshness and volume: ask the lab whether the plate\n",
    "  reader exported. Schema: read the new columns, then decide in staging (Module 2, section 4).\n",
    "  Registrations: tell the chemists whose decisions used the old structure (Module 6). Drift: a\n",
    "  chemist decides whether it was planned (Module 8).\n",
    "- **How to change something.** A new kinase is a row in the `targets` seed; a new unit spelling a row\n",
    "  in `unit_to_nm`; a new model a pull request that CI checks (Module 9).\n",
    "- **What to back up.** The snapshots (section 5). Everything else can be made again from the files\n",
    "  and the code.\n",
    "- **What it does not do yet.** It runs on one machine; DuckDB allows one writer at a time, so a\n",
    "  second pipeline would need its own warehouse or a server database; the dashboard has no login, so\n",
    "  it must stay on the lab's own network; and the test data are synthetic, so the CI cannot catch\n",
    "  problems that only real data contain.\n",
    "\n",
    "That last part matters as much as the rest: a colleague who knows the limits of a system can work\n",
    "around them, and one who does not will find them at the worst moment.\n",
    "\n",
    "## The capstone brief\n",
    "\n",
    "Series 2 ends with a project of your own. If you are in a cohort, you hand it in and three other\n",
    "learners review it against the rubric below, as you review three of theirs; a project that passes\n",
    "completes the series. If you are following on your own, build the same project and use the rubric\n",
    "to check it.\n",
    "\n",
    "### What to build\n",
    "\n",
    "A running data stack for a small lab, from its files to a dashboard, built with the tools of this\n",
    "series. Choose one lab:\n",
    "\n",
    "- a `labdata.Lab` with your own seed (not 0 or 2) and your own number of compounds a week\n",
    "  (`per_week`), run for all twelve weeks; or\n",
    "- a lab of your own design: a different target, a different assay, or ChEMBL's activities for a\n",
    "  target you choose, loaded incrementally with dlt's REST API source as in Module 2, standing in for\n",
    "  the lab's own results.\n",
    "\n",
    "You may start from `stack.py`, the dbt project in `stages/after-06/` and `dashboard.py`, and change\n",
    "them. Say in your README what you kept, what you changed and what you added.\n",
    "\n",
    "### Requirements\n",
    "\n",
    "1. **Ingestion and history.** The raw layer loaded with dlt, incrementally, with a schema contract\n",
    "   or a written reason for leaving the schema to evolve; registry history kept with dbt snapshots\n",
    "   (Modules 2 and 6).\n",
    "2. **Modelling and transformation.** A star schema with a declared grain, built by dbt with sources,\n",
    "   seeds and models, and at least one Python model; the lineage graph in your README (Modules 3 and\n",
    "   4).\n",
    "3. **Tests and contracts.** dbt tests on keys, values and relationships, at least one test of your\n",
    "   own (generic or singular), an enforced contract on a mart, and chemistry checks with pandera-chem\n",
    "   (Module 5).\n",
    "4. **Orchestration and recovery.** A Prefect flow that runs a week, with retries where failures pass\n",
    "   and a failure that stops the week before anything is published; one failure and one rerun shown\n",
    "   in your run record (Module 7).\n",
    "5. **Observability.** At least three checks from different kinds (freshness, volume, schema,\n",
    "   distribution), recorded metrics, and alerts kept in a table, with at least one alert shown\n",
    "   firing for a reason you can explain (Module 8).\n",
    "6. **Serving and hand-over.** A dashboard, tested with AppTest; a CI workflow that builds and tests\n",
    "   every pull request (Module 9); the dbt docs; and a runbook of at most two pages (section 7).\n",
    "\n",
    "### What to hand in\n",
    "\n",
    "1. **A link to a public Git repository** with your code, dbt project, tests, `pyproject.toml` and\n",
    "   lock file, the CI workflow, and a README that lets someone else run the whole stack.\n",
    "2. **The run record of your final run**, in the repository: `monitoring.alerts` and\n",
    "   `monitoring.metrics` saved as CSV files, and the list of flow runs with their states.\n",
    "3. **The runbook** (at most two pages) and two screenshots of the dashboard.\n",
    "\n",
    "Leave out the data files (the warehouse and its copies): anyone can make them again from your code\n",
    "and settings. If you are in a cohort, you will be told where to send the link and by which date.\n",
    "\n",
    "### How it is judged: the peer-review rubric\n",
    "\n",
    "Three peers review each submission against the six criteria below, each marked *not yet*, *meets*\n",
    "or *exceeds*, with one sentence of evidence for each mark. A submission passes when, for every\n",
    "criterion, at least two of the three reviewers mark it *meets* or *exceeds*. Reviewers judge from\n",
    "your repository and README, and follow the README to run your stack.\n",
    "\n",
    "| Criterion | Not yet | Meets | Exceeds |\n",
    "|---|---|---|---|\n",
    "| Ingestion and history | Files loaded by hand, or reloaded in full every week; no history of changed registrations | dlt loads incrementally and a rerun loads nothing twice; snapshots keep every version, with dates the lab can use | A schema change handled on purpose (contract, or evolution with a staging fix), and an \"as of\" question answered from the history |\n",
    "| Modelling and transformation | Tables built by scripts in an order only the author knows | A star with a stated grain, built by dbt from sources and seeds, with a Python model and the lineage shown | Incremental models where they pay, with the reason given, and the documentation complete |\n",
    "| Tests and contracts | No tests, or tests that never fail | Built-in and own tests, a contract on a mart, chemistry checks, and a failing test shown stopping the marts | Tests chosen from the lab's real problems, with severities justified, and the grain defined precisely |\n",
    "| Orchestration and recovery | Steps run by hand | A flow with retries, a failure that stops before publishing, and a rerun shown in the record | Caching or idempotence argued for each task; a schedule and its server set-up described |\n",
    "| Observability | Prints only | Three kinds of check, recorded metrics, kept alerts, one shown firing | Thresholds justified from the data; alerts that say where to look; a view of the pipeline's health |\n",
    "| Serving and hand-over | No dashboard, or a README that does not let a reviewer run it | A dashboard tested with AppTest, CI on every pull request, dbt docs and a runbook | The dashboard answers a chemist's question the lesson's does not; the runbook names the system's limits |\n",
    "\n",
    "## Try it yourself\n",
    "\n",
    "The homework is the capstone brief above, and a few warm-up questions on `stack.py` in\n",
    "`homework.md` in the module's folder, also at the end of the lesson's page. The answers to the\n",
    "warm-up questions are published after the cohort's deadline.\n",
    "\n",
    "## Further reading\n",
    "\n",
    "- Kleppmann, M. (2017). *Designing Data-Intensive Applications*. O'Reilly Media. Chapters 10 and 11,\n",
    "  on batch and stream processing: the ideas behind every stage of this stack, at scale.\n",
    "- Reis, J. & Housley, M. (2022). *Fundamentals of Data Engineering*. O'Reilly Media. Chapters 2 and\n",
    "  11: the lifecycle and its undercurrents (security, data management, DataOps, orchestration), and\n",
    "  where the field is going.\n",
    "- Beyer, B., Jones, C., Petoff, J. & Murphy, N. R. (eds.) (2016). *Site Reliability Engineering*.\n",
    "  O'Reilly Media. Chapter 14, \"Managing Incidents\", and the runbooks of chapter 6.\n",
    "  <https://sre.google/sre-book/managing-incidents/>\n",
    "- Wilkinson, M. D. et al. (2016). The FAIR Guiding Principles for scientific data management and\n",
    "  stewardship. *Scientific Data*, 3, 160018. <https://doi.org/10.1038/sdata.2016.18>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
