{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Observability\n",
    "\n",
    "Know when something is wrong before the chemists do. After each weekly run, record what arrived and what the warehouse holds, and check it against what is normal - freshness on two clocks, volume, schema changes, changed registrations and drift in the molecules' properties - and send an alert when a check fails. Run the lab's weeks 5 to 12 and see every planted problem reported in the week it happened.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-2/08-observability/"
   ]
  },
  {
   "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 prefect requests\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": [
    "The weekly flow of [Module 7](../07-orchestration/) fails when something is clearly broken: a\n",
    "model that will not build, a test that does not pass. But in week 10 it finished in state\n",
    "`Completed` although no assay results had arrived, and nobody would have known unless they read\n",
    "the warnings in that run's log. Most problems in data are like that: nothing fails, the numbers\n",
    "are just wrong, late or strange. A file that did not come, a table that stopped growing, a column\n",
    "that was renamed, a batch of compounds unlike the others. The dashboards keep showing something,\n",
    "and the first person to notice is a chemist who trusted it.\n",
    "\n",
    "**Observability** means the pipeline watches its own data and says when something looks wrong.\n",
    "[Series 1, Module 14](../../series-1/14-monitoring-pipelines/) built the pieces by hand for one\n",
    "pipeline: run metrics, checks against thresholds, alerts. Here they are applied to the warehouse,\n",
    "week by week, as a Prefect flow, and to the things a lab's data does: arrive late, change shape,\n",
    "change meaning and drift.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- name the four things most data checks watch (freshness, volume, schema and distribution) and\n",
    "  tell the pipeline's clock from the data's clock;\n",
    "- record metrics for every run, so that each week can be compared with the weeks before;\n",
    "- check freshness with dbt (did the loader run?) and with the data's own dates (did the results\n",
    "  come?);\n",
    "- notice schema changes from dlt's record of them, and changed registrations from the snapshots;\n",
    "- measure drift in the molecules' properties against a reference, and find where it comes from;\n",
    "- send alerts somewhere people will see them, and keep them few enough to be read.\n",
    "\n",
    "## Setup\n",
    "\n",
    "The Setup is Module 7's, with two changes. The warehouse is built only to the end of week 4 (by\n",
    "`labstack.warehouse_at`, as Module 6 would), because the checks should meet the lab's problems as\n",
    "they happen, from week 5's renamed column on. And `requests` sends the alerts to a chat channel,\n",
    "if one is set up (section 6)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import logging\n",
    "import os\n",
    "import shutil\n",
    "from datetime import timedelta\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 duckdb\n",
    "import pandas as pd\n",
    "import requests\n",
    "from prefect import flow, get_run_logger, task\n",
    "\n",
    "import labdata\n",
    "import labstack\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)  # not every request Prefect makes\n",
    "quiet = logging.getLogger(\"dbt-lines\")  # labstack.dbt logs one line per model here: unseen\n",
    "quiet.propagate = False\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(\"prefect\").addFilter(lambda r: \"temporary server\" not in r.getMessage())\n",
    "\n",
    "INBOX = WORK / \"inbox\"\n",
    "WAREHOUSE = WORK / \"lab.duckdb\"\n",
    "BASELINE_WEEKS = 4  # the weeks the checks treat as normal, to compare the others with\n",
    "DRIFT_LIMIT = 1.0  # alert when a property moves this many reference standard deviations\n",
    "VOLUME_RANGE = (0.5, 1.5)  # alert when a week brings less than half or more than 1.5 times usual\n",
    "\n",
    "lab = labdata.Lab()\n",
    "PROJECT = labstack.warehouse_at(lab, BASELINE_WEEKS, WORK)\n",
    "pipeline = labstack.lab_pipeline(WAREHOUSE, WORK / \"dlt\")\n",
    "\n",
    "\n",
    "def query(sql: str) -> pd.DataFrame:\n",
    "    \"\"\"Run one SQL query on the warehouse and return the answer as a table.\"\"\"\n",
    "    with duckdb.connect(str(WAREHOUSE)) as db:\n",
    "        return db.sql(sql).df()\n",
    "\n",
    "\n",
    "def execute(sql: str, *parameters) -> None:\n",
    "    \"\"\"Run one SQL statement that changes the warehouse.\"\"\"\n",
    "    with duckdb.connect(str(WAREHOUSE)) as db:\n",
    "        db.execute(sql, list(parameters))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`execute` is `query`'s twin for statements that change the warehouse: the checks keep their\n",
    "record in it, in a schema of their own. Each `?` in its statement is filled, safely, with the next\n",
    "of `parameters` ([Series 1, Module 4](../../series-1/04-databases-and-schemas/) explained why\n",
    "values are never pasted into SQL).\n",
    "\n",
    "## 1. What to watch\n",
    "\n",
    "Data teams group the checks that catch most problems into four kinds:\n",
    "\n",
    "- **Freshness**: is the data as recent as it should be? A missing file shows up here.\n",
    "- **Volume**: did about as much arrive as usual? A half-empty file, or two files at once.\n",
    "- **Schema**: did the shape change? A renamed column, a new one, a different type.\n",
    "- **Distribution**: do the values look like the usual ones? A unit off by a thousand, a batch of\n",
    "  compounds unlike any before.\n",
    "\n",
    "Freshness has a trap: there are two clocks. The **pipeline's clock** says when the data was\n",
    "loaded; the **data's clock** says when the data is *about* (here, the date a plate was run). A\n",
    "pipeline can run every Monday, punctually, and load nothing new for a month: fresh on the first\n",
    "clock, stale on the second. Each needs its own check.\n",
    "\n",
    "A check compares the present with something. Some rules are fixed (a run every week), but most\n",
    "compare with history: is this week like the usual weeks? So the first thing the flow does after\n",
    "each run is record **metrics** about it, in a table of their own, where the next week can find\n",
    "them. The warehouse gets a `monitoring` schema with two tables: one for metrics, one for the\n",
    "alerts the checks raise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "execute(\"CREATE SCHEMA monitoring\")\n",
    "execute(\"CREATE TABLE monitoring.metrics (week INTEGER, name VARCHAR, value DOUBLE)\")\n",
    "execute(\"CREATE TABLE monitoring.alerts (week INTEGER, check_name VARCHAR, message VARCHAR)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. The weekly run, and its metrics\n",
    "\n",
    "The run itself is Module 7's flow, shortened to one task: receive the week's files, load them,\n",
    "take the snapshot and build. It returns what dlt loaded. The second task records the week's\n",
    "metrics: how many assay rows arrived, the newest run date in the warehouse, and the version of\n",
    "the raw layer's schema (section 4)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@task(task_run_name=\"run week {week}\")\n",
    "def run_week(week: int) -> dict[str, int]:\n",
    "    \"\"\"The weekly pipeline of Module 7: receive, load, snapshot, build and test.\"\"\"\n",
    "    lab.write_week(week, INBOX)\n",
    "    rows = labstack.load_inbox(INBOX, pipeline)\n",
    "    labstack.dbt(PROJECT, \"snapshot\", log=quiet)\n",
    "    labstack.dbt(PROJECT, \"build\", log=quiet)\n",
    "    return rows\n",
    "\n",
    "\n",
    "@task(task_run_name=\"record metrics\")\n",
    "def record_metrics(week: int, rows: dict[str, int] | None) -> None:\n",
    "    \"\"\"Save this week's metrics, for the checks of later weeks to compare with.\"\"\"\n",
    "    newest = query(\"SELECT max(run_date) AS d FROM marts.fact_measurement\")[\"d\"][0]\n",
    "    version = query(\"SELECT max(version) AS v FROM raw._dlt_version\")[\"v\"][0]\n",
    "    metrics = {\n",
    "        \"newest_run_date\": newest.toordinal(),  # a date, kept as a number of days\n",
    "        \"schema_version\": version,\n",
    "    }\n",
    "    if rows is not None:  # how many rows arrived (unknown for the baseline week)\n",
    "        metrics[\"assay_rows\"] = rows.get(\"assay\", 0)\n",
    "    for name, value in metrics.items():\n",
    "        execute(\"INSERT INTO monitoring.metrics VALUES (?, ?, ?)\", week, name, float(value))\n",
    "\n",
    "\n",
    "def metric(name: str, before: int) -> pd.Series:\n",
    "    \"\"\"A metric's history: its value in each week before `before`, by week.\"\"\"\n",
    "    return query(f\"\"\"\n",
    "        SELECT week, value FROM monitoring.metrics\n",
    "        WHERE name = '{name}' AND week < {before} ORDER BY week\n",
    "    \"\"\").set_index(\"week\")[\"value\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`toordinal` turns a date into a whole number of days, so it fits the `value` column. `metric`\n",
    "reads a metric's history back. The checks compare each week with the one before, so the baseline\n",
    "week's metrics are recorded now, once. `.fn` is the plain function inside a task, run without\n",
    "Prefect; the baseline's row count is left out, because week 4 brought the resent file and would\n",
    "make every later week look small:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " week            name    value\n",
      "    4 newest_run_date 739889.0\n",
      "    4  schema_version      4.0\n"
     ]
    }
   ],
   "source": [
    "record_metrics.fn(BASELINE_WEEKS, None)\n",
    "print(query(\"SELECT * FROM monitoring.metrics\").to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The SQL in `metric` is built from `name` and `before`, which is safe here\n",
    "only because both come from this code, never from outside.\n",
    "\n",
    "## 3. Freshness, on both clocks\n",
    "\n",
    "The pipeline's clock first. dbt has a check for it built in: **source freshness**. Each source\n",
    "says which of its columns records when a row was loaded, and how old that may get before dbt warns\n",
    "or errors. dlt gives every row a load ID that is the time of the load in seconds since 1970, so\n",
    "`to_timestamp(_dlt_load_id::double)` turns it into a time:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{'assay': 'pass'}\n"
     ]
    }
   ],
   "source": [
    "sources = PROJECT / \"models\" / \"staging\" / \"_sources.yml\"\n",
    "text = sources.read_text(encoding=\"utf-8\")\n",
    "sources.write_text(text.replace(\"\"\"      - name: assay\n",
    "        description: Every row of every assay file, merged on result_id.\n",
    "\"\"\", \"\"\"      - name: assay\n",
    "        description: Every row of every assay file, merged on result_id.\n",
    "        loaded_at_field: to_timestamp(_dlt_load_id::double)  # when dlt loaded the row\n",
    "        freshness:\n",
    "          warn_after: {count: 8, period: day}  # the lab loads every 7 days\n",
    "          error_after: {count: 15, period: day}\n",
    "\"\"\"), encoding=\"utf-8\", newline=\"\\n\")\n",
    "results = labstack.dbt(PROJECT, \"source\", \"freshness\", log=quiet)\n",
    "print({r.node.name: str(r.status) for r in results})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`pass`: dlt loaded the assay table moments ago. On a real schedule, this is the check that\n",
    "notices a pipeline that stopped running: a server that went down, a schedule someone switched off.\n",
    "It cannot notice what happened in week 10, though, because in week 10 the pipeline ran on time.\n",
    "\n",
    "The data's clock needs the data's own dates. A plate is run on the Wednesday of its week, so by the\n",
    "end of week *n* the newest result in the warehouse should be from week *n*. The check compares the\n",
    "newest run date with the Wednesday of the week just finished:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@task(task_run_name=\"check freshness\")\n",
    "def check_freshness(week: int) -> list[str]:\n",
    "    \"\"\"The newest result should have been run this week.\"\"\"\n",
    "    newest = metric(\"newest_run_date\", week + 1)[week]\n",
    "    expected = (labdata.monday(week) + timedelta(days=2)).toordinal()  # the week's Wednesday\n",
    "    behind = int(expected - newest)\n",
    "    if behind > 0:\n",
    "        return [f\"the newest result is {behind} days old: no plates were run this week\"]\n",
    "    return []"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Volume and schema\n",
    "\n",
    "Volume compares this week's assay rows with the usual: the **median** of the weeks before (the\n",
    "middle value, which one strange week cannot drag far, unlike the mean). Fewer than half or more\n",
    "than one and a half times the usual raises an alert. The first two monitored weeks have too little\n",
    "history to compare with, so the check waits for three."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@task(task_run_name=\"check volume\")\n",
    "def check_volume(week: int) -> list[str]:\n",
    "    \"\"\"About as many assay rows as usual should have arrived.\"\"\"\n",
    "    history = metric(\"assay_rows\", week + 1)\n",
    "    if len(history) < 3:\n",
    "        return []\n",
    "    usual, now = history.iloc[:-1].median(), history.iloc[-1]\n",
    "    low, high = VOLUME_RANGE\n",
    "    if not low * usual <= now <= high * usual:\n",
    "        return [f\"{now:.0f} assay rows arrived; usually about {usual:.0f}\"]\n",
    "    return []"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Schema changes are recorded by dlt itself. Every time the schema it inferred changes, dlt stores\n",
    "the new version in `raw._dlt_version`, with the whole schema as JSON. So the check compares this\n",
    "week's version with last week's, and if it changed, it says which columns of which tables\n",
    "appeared or disappeared, by comparing the two versions' JSON:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def columns_in(version: int) -> dict[str, set[str]]:\n",
    "    \"\"\"The columns of each of the lab's tables in one version of dlt's schema.\"\"\"\n",
    "    schema = json.loads(query(f\"SELECT schema FROM raw._dlt_version WHERE version = {version}\")\n",
    "                        [\"schema\"][0])\n",
    "    return {name: set(table[\"columns\"]) for name, table in schema[\"tables\"].items()\n",
    "            if not name.startswith(\"_dlt\")}\n",
    "\n",
    "\n",
    "@task(task_run_name=\"check schema\")\n",
    "def check_schema(week: int) -> list[str]:\n",
    "    \"\"\"The raw layer's columns should not change without someone knowing.\"\"\"\n",
    "    versions = metric(\"schema_version\", week + 1)\n",
    "    if len(versions) < 2 or versions.iloc[-1] == versions.iloc[-2]:\n",
    "        return []\n",
    "    old, new = columns_in(int(versions.iloc[-2])), columns_in(int(versions.iloc[-1]))\n",
    "    alerts = []\n",
    "    for table in sorted(new):\n",
    "        added, removed = new[table] - old.get(table, set()), old.get(table, set()) - new[table]\n",
    "        if added or removed:\n",
    "            alerts.append(f\"raw.{table} changed: added {sorted(added)}, removed {sorted(removed)}\")\n",
    "    return alerts"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A changed registration is a schema change of another kind: same columns, different meaning for one\n",
    "compound. The snapshot of [Module 6](../06-history-and-corrections/) already knows: a compound with a\n",
    "new version this week was changed in the registry. `dim_compound_history` dates each version by its\n",
    "export, so the check looks for versions after the first that are valid from this week:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@task(task_run_name=\"check registrations\")\n",
    "def check_registrations(week: int) -> list[str]:\n",
    "    \"\"\"A compound registered before should not change without someone knowing.\"\"\"\n",
    "    changed = query(f\"\"\"\n",
    "        SELECT compound_id FROM marts.dim_compound_history\n",
    "        WHERE version > 1 AND valid_from = DATE '{labdata.monday(week)}'\n",
    "        ORDER BY compound_id\n",
    "    \"\"\")[\"compound_id\"].tolist()\n",
    "    return [f\"registration changed: {', '.join(changed)}\"] if changed else []"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Drift in the molecules\n",
    "\n",
    "The last kind of check asks whether this week's compounds look like the usual ones. Medicinal\n",
    "chemistry moves on purpose (a series is optimised, a new idea is tried), so a change is not always\n",
    "a problem; but it should never be a surprise, and a sudden one can be a mistake (a structure drawn\n",
    "with a wrong group, a vendor's batch with a different salt).\n",
    "\n",
    "The check compares the compounds registered this week with those of the baseline weeks, property\n",
    "by property. Its measure is how far this week's mean has moved, in units of the baseline's\n",
    "**standard deviation** (the usual spread of the property): a move of 1 means this week's average\n",
    "compound differs from the usual one by as much as typical compounds differ from each other. When a\n",
    "property moves by `DRIFT_LIMIT` or more, the check looks for where the move comes from, series by\n",
    "series. It also notices who and what is new: a chemist or a vendor never seen before."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "PROPERTIES = [\"mw\", \"clogp\", \"heavy_atoms\"]\n",
    "\n",
    "\n",
    "@task(task_run_name=\"check drift\")\n",
    "def check_drift(week: int) -> list[str]:\n",
    "    \"\"\"This week's compounds should look like the usual ones, or someone should know why.\"\"\"\n",
    "    compounds = query(\"SELECT * FROM marts.dim_compound\")\n",
    "    days = compounds[\"registered_on\"] - pd.Timestamp(labdata.START)\n",
    "    compounds[\"week\"] = days.dt.days // 7 + 1\n",
    "    baseline = compounds[compounds[\"week\"] <= BASELINE_WEEKS]\n",
    "    earlier = compounds[compounds[\"week\"] < week]\n",
    "    new = compounds[compounds[\"week\"] == week]\n",
    "    alerts = []\n",
    "    for prop in PROPERTIES:\n",
    "        moved = (new[prop].mean() - baseline[prop].mean()) / baseline[prop].std()\n",
    "        execute(\"INSERT INTO monitoring.metrics VALUES (?, ?, ?)\", week, f\"drift_{prop}\", moved)\n",
    "        if abs(moved) >= DRIFT_LIMIT:\n",
    "            by_series = {\n",
    "                series: (group[prop].mean() - baseline.loc[baseline[\"series\"] == series, prop]\n",
    "                         .mean()) / baseline[prop].std()\n",
    "                for series, group in new.groupby(\"series\")\n",
    "            }\n",
    "            worst = max(by_series, key=lambda s: abs(by_series[s]))\n",
    "            alerts.append(f\"{prop} moved {moved:+.1f} SD from the baseline, most in the \"\n",
    "                          f\"{worst} ({by_series[worst]:+.1f} SD)\")\n",
    "    for column in (\"chemist\", \"vendor\"):\n",
    "        unseen = sorted(set(new[column]) - set(earlier[column]))\n",
    "        if unseen:\n",
    "            alerts.append(f\"new {column}: {', '.join(unseen)}\")\n",
    "    return alerts"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each series is compared with its own baseline, because series differ from each other: a week with\n",
    "more ureas than usual would move the overall average without any compound being unusual for its\n",
    "series. The drift measures are recorded as metrics too, so they can be plotted week by week.\n",
    "\n",
    "## 6. Alerts, and the weekly flow\n",
    "\n",
    "An alert is only useful if it reaches someone who can act on it, and only read if alerts are rare.\n",
    "`send` does three things with each one: logs it as a warning (in Prefect's record of the run),\n",
    "keeps it in `monitoring.alerts`, and, if a **webhook** is set up, posts it to a chat channel. A\n",
    "webhook is a web address that a service such as Slack, Microsoft Teams or Discord gives you for a\n",
    "channel: anything posted to it as JSON appears in the channel. Its address works like a password,\n",
    "so it comes from an environment variable, never from the code ([Series 1, Module\n",
    "4](../../series-1/04-databases-and-schemas/), section 9). Here none is set, so nothing is posted."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@task(task_run_name=\"send alerts\")\n",
    "def send(week: int, check_name: str, alerts: list[str]) -> None:\n",
    "    \"\"\"Log each alert, keep it in monitoring.alerts and post it to the chat channel if set up.\"\"\"\n",
    "    webhook = os.environ.get(\"LAB_ALERT_WEBHOOK\")  # e.g. a Slack or Teams incoming webhook\n",
    "    for message in alerts:\n",
    "        get_run_logger().warning(\"%s: %s\", check_name, message)\n",
    "        execute(\"INSERT INTO monitoring.alerts VALUES (?, ?, ?)\", week, check_name, message)\n",
    "        if webhook:\n",
    "            requests.post(webhook, json={\"text\": f\"Lab data, week {week}: {message}\"}, timeout=10)\n",
    "\n",
    "\n",
    "CHECKS = {\n",
    "    \"freshness\": check_freshness,\n",
    "    \"volume\": check_volume,\n",
    "    \"schema\": check_schema,\n",
    "    \"registrations\": check_registrations,\n",
    "    \"drift\": check_drift,\n",
    "}\n",
    "\n",
    "\n",
    "@flow(name=\"lab-weekly-with-checks\", flow_run_name=\"week {week}\")\n",
    "def weekly(week: int) -> int:\n",
    "    \"\"\"Run the week, record its metrics, run every check and send what they find.\"\"\"\n",
    "    rows = run_week(week)\n",
    "    record_metrics(week, rows)\n",
    "    found = 0\n",
    "    for check_name, check in CHECKS.items():\n",
    "        alerts = check(week)\n",
    "        send(week, check_name, alerts)\n",
    "        found += len(alerts)\n",
    "    return found"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each check is a separate task, so a check that crashes is recorded as failed without hiding what\n",
    "the others found, and each can be rerun on its own. Now the weeks pass, 5 to 12, with only the\n",
    "warnings on the screen:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "WARNING send alerts: schema: raw.assay changed: added ['operator', 'unit'], removed []\n",
      "INFO week 5: 1 alerts\n",
      "INFO week 6: 0 alerts\n",
      "WARNING send alerts: registrations: registration changed: LAB-0042\n",
      "INFO week 7: 1 alerts\n",
      "WARNING send alerts: volume: 224 assay rows arrived; usually about 136\n",
      "WARNING send alerts: schema: raw.assay changed: added ['status'], removed []\n",
      "INFO week 8: 2 alerts\n",
      "INFO week 9: 0 alerts\n",
      "WARNING send alerts: freshness: the newest result is 7 days old: no plates were run this week\n",
      "WARNING send alerts: volume: 0 assay rows arrived; usually about 144\n",
      "INFO week 10: 2 alerts\n",
      "WARNING send alerts: volume: 328 assay rows arrived; usually about 140\n",
      "WARNING send alerts: drift: mw moved +1.2 SD from the baseline, most in the aminopyrimidines (+1.7 SD)\n",
      "WARNING send alerts: drift: clogp moved +1.5 SD from the baseline, most in the aminopyrimidines (+2.2 SD)\n",
      "WARNING send alerts: drift: heavy_atoms moved +1.1 SD from the baseline, most in the aminopyrimidines (+1.6 SD)\n",
      "WARNING send alerts: drift: new chemist: EF\n",
      "INFO week 11: 5 alerts\n",
      "WARNING send alerts: drift: clogp moved +1.2 SD from the baseline, most in the aminopyrimidines (+2.3 SD)\n",
      "INFO week 12: 1 alerts\n"
     ]
    }
   ],
   "source": [
    "logging.getLogger(\"prefect.task_runs\").setLevel(logging.WARNING)  # warnings only\n",
    "logging.getLogger(\"prefect.flow_runs\").setLevel(logging.WARNING)\n",
    "for week in range(5, 13):\n",
    "    found = weekly(week)\n",
    "    log.info(\"week %d: %d alerts\", week, found)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Which checks raised an alert, weeks 5 to 12: schema in week 5; registrations in week 7; volume and schema in week 8; freshness and volume in week 10; volume and four drift alerts in week 11; one drift alert in week 12; weeks 6 and 9 quiet](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/08-observability/figures/alerts-by-week.svg)\n",
    "\n",
    "Every planted problem was reported, in the week it happened, and the quiet weeks stayed quiet:\n",
    "\n",
    "- **Week 5**: the plate reader's software update (`units` renamed `unit`, a new `operator`\n",
    "  column), from dlt's own record of the schema.\n",
    "- **Week 7**: LAB-0042's corrected registration, from the snapshot.\n",
    "- **Week 8**: the new `status` column of the re-read plate, and more rows than usual: the\n",
    "  corrected readings come on top of a busy week.\n",
    "- **Week 10**: no plates run, and no assay rows at all: the late file, on both checks that can see\n",
    "  it, while dbt's source freshness, on the pipeline's clock, would have passed.\n",
    "- **Week 11**: two weeks' rows at once (the late file arriving), the new chemist, EF, and the drift:\n",
    "  heavier, greasier compounds, all coming from one series.\n",
    "- **Week 12**: the drift again, because EF went on making the same kind of compound.\n",
    "\n",
    "Here is the record the checks kept, the table a dashboard of the pipeline's health would read:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "week\n",
      "5                                 schema\n",
      "7                          registrations\n",
      "8                         schema, volume\n",
      "10                     freshness, volume\n",
      "11    drift, drift, drift, drift, volume\n",
      "12                                 drift\n",
      "week           5    6     7     8     9     10    11    12\n",
      "name                                                      \n",
      "drift_clogp -0.34  0.0 -0.04 -0.14  0.14 -0.16  1.46  1.18\n"
     ]
    }
   ],
   "source": [
    "alerts = query(\"SELECT * FROM monitoring.alerts ORDER BY week, check_name\")\n",
    "print(alerts.groupby(\"week\")[\"check_name\"].apply(lambda c: \", \".join(c)).to_string())\n",
    "print(query(\"\"\"\n",
    "    SELECT week, name, round(value, 2) AS value FROM monitoring.metrics\n",
    "    WHERE name LIKE 'drift_clogp' ORDER BY week\n",
    "\"\"\").pivot(index=\"name\", columns=\"week\", values=\"value\").to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![The drift of cLogP, molecular weight and heavy atoms against weeks 1 to 4, by week: all three stay between about -0.5 and +0.4 until week 10, then jump above the alert line at 1.0 in week 11 (cLogP +1.46) and stay near it in week 12](figures/drift.svg)\n",
    "\n",
    "The cLogP drift stays near zero for six weeks and jumps in week 11. Whether that is a problem is\n",
    "for a chemist to say (EF may have been asked to make greasier compounds), but now a chemist is the\n",
    "one who says it, in the week it starts, instead of finding out from a dashboard months later.\n",
    "\n",
    "Three habits keep alerts useful:\n",
    "\n",
    "- **Few, and worth acting on.** Every alert should lead to a person doing something. A check that\n",
    "  fires every week and is always ignored trains people to ignore all of them; change its limit, or\n",
    "  remove it.\n",
    "- **Say what and where.** \"cLogP moved +1.6 SD, most in the aminopyrimidines\" can be acted on;\n",
    "  \"drift detected\" cannot.\n",
    "- **Limits are decisions.** `DRIFT_LIMIT` and `VOLUME_RANGE` were chosen by looking at normal\n",
    "  weeks, and written down where they can be reviewed and changed, like the unit seed of Module 4.\n",
    "\n",
    "The checks so far watch the data. [Module 9](../09-continuous-integration/) watches the code: every\n",
    "change to the dbt project is built and tested before it reaches the warehouse.\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 dbt documentation. *Source freshness*: `loaded_at_field`, `warn_after`, `error_after` and how\n",
    "  to run it on a schedule. <https://docs.getdbt.com/docs/deploy/source-freshness>\n",
    "- The dlt documentation. *Schema evolution*: how dlt records each version of a schema, and how to be\n",
    "  told when it changes. <https://dlthub.com/docs/general-usage/schema-evolution>\n",
    "- Moses, B., Gavish, L. & Vorwerck, M. (2022). *Data Quality Fundamentals*. O'Reilly Media. The\n",
    "  five pillars of data observability (freshness, volume, schema, distribution, lineage) and how\n",
    "  teams use them.\n",
    "- Beyer, B., Jones, C., Petoff, J. & Murphy, N. R. (eds.) (2016). *Site Reliability Engineering*.\n",
    "  O'Reilly Media. Chapter 6, \"Monitoring Distributed Systems\": alerts that people act on.\n",
    "  <https://sre.google/sre-book/monitoring-distributed-systems/>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
