{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Monitoring pipelines\n",
    "\n",
    "Structured logs, a run history, counts that must reconcile, freshness, drift in molecular properties and alerts, so a pipeline tells you when it goes wrong.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-1/14-monitoring-pipelines/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install what this lesson needs (in Colab, or any fresh environment)\n",
    "%pip install -q rdkit numpy pandas pyarrow duckdb matplotlib\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\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A pipeline that loads a supplier's compounds every night can fail in two ways. It can crash, which\n",
    "is annoying but obvious. Or it can run, finish, report success and still be wrong: a join that\n",
    "drops a third of the rows, a supplier file that holds only one corner of the catalogue, a job that\n",
    "quietly stopped running last Tuesday. The chemistry in each step can be perfect and the data still\n",
    "untrustworthy. Monitoring is the part of data engineering that answers three plain questions after\n",
    "every run: **did it run, did it do the right thing, and is the data still what we expect?**\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- write a log (the job's own diary of what it did) as one line of JSON per event, so a program can\n",
    "  read it back, and keep passwords out of it;\n",
    "- keep a run history: a small database table with one row for every run and every step;\n",
    "- check that every record is accounted for (records in = records out + rejected + duplicates), and\n",
    "  use that check to catch a bug that quietly loses a third of the data;\n",
    "- work out, for each run, how fast it was, how many records it rejected, and how old the newest\n",
    "  data is;\n",
    "- tell when a new batch of molecules looks different from the usual ones (drift in molecular\n",
    "  weight and logP);\n",
    "- turn these checks into alerts that tell a person once when something goes wrong, and once when\n",
    "  it is fixed.\n",
    "\n",
    "This module uses what earlier modules built: the validation rules and the faults that `chemlib`\n",
    "adds ([Module 6](../06-validating-molecules/)), InChIKeys for finding duplicates\n",
    "([Module 3](../03-files-and-identity/)), Parquet files and DuckDB\n",
    "([Module 8](../08-larger-than-memory/)), and logging ([Module 1](../01-graphs-and-matrices/)).\n",
    "\n",
    "The lesson uses these Python packages (code other people wrote, which you load with `import`):\n",
    "\n",
    "- **RDKit**, for reading molecules and calculating their properties;\n",
    "- **NumPy** and **pandas**, for arrays of numbers and for tables;\n",
    "- **pyarrow**, which pandas uses to write **Parquet** files (a compact file format for tables);\n",
    "- **DuckDB**, a small database that lives in one file on your computer and answers questions\n",
    "  written in SQL, the standard language for asking a database for data;\n",
    "- **matplotlib**, for drawing figures.\n",
    "\n",
    "The molecules come from the course's teaching library, `chemlib`, which makes realistic\n",
    "drug-like molecules on demand. Everything here runs in Colab or on any laptop.\n",
    "\n",
    "A few words come up again and again. A **run** is one execution of the pipeline, start to finish:\n",
    "here, one night's load. A **step** is one stage inside a run (validate, deduplicate and so on).\n",
    "To **quarantine** a record is to set it aside, with the reason, instead of deleting it, so a person\n",
    "can look at it later. **JSON** is a way of writing data as text that both people and programs can\n",
    "read: `{\"step\": \"validate\", \"rows_in\": 1510}` is one JSON object, a set of named fields.\n",
    "\n",
    "## Setup\n",
    "\n",
    "Everything this lesson needs is imported and set here, so the settings can be changed in one place.\n",
    "Pipeline steps report with `log`; `print` is kept for showing you results; Module 1 explains why,\n",
    "and Section 2 below takes logging further. Besides the packages above, the block imports some parts\n",
    "of Python itself: `json` (writes and reads JSON), `re` (regular expressions, short patterns for\n",
    "finding text, used in Section 2), `Counter` (counts things), `datetime` and `timedelta` (a date and\n",
    "time, and a length of time), `Path` (file paths) and `NamedTuple` (a small record type, used in\n",
    "Section 7)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import logging\n",
    "import re\n",
    "from collections import Counter\n",
    "from datetime import datetime, timedelta\n",
    "from pathlib import Path\n",
    "from typing import NamedTuple\n",
    "\n",
    "import duckdb\n",
    "import matplotlib\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from rdkit import Chem, RDLogger\n",
    "from rdkit.Chem import Descriptors\n",
    "\n",
    "import chemlib\n",
    "\n",
    "# log lines: level and message only, so the lesson's outputs are the same on every run\n",
    "# (a real job would add \"%(asctime)s\" to the format)\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\n",
    "WORK = Path(\"work\")\n",
    "LOG_FILE = WORK / \"pipeline.log\"  # the pipeline's structured log\n",
    "HISTORY_DB = WORK / \"monitoring.duckdb\"  # the run history\n",
    "PUBLISHED = WORK / \"published\"  # one Parquet file per successful run\n",
    "DASHBOARD = WORK / \"run-dashboard.svg\"\n",
    "\n",
    "# each night's supplier file: how many molecules, and the share given a recorded fault\n",
    "NIGHTLY_MOLECULES = 1500\n",
    "DEFECT_RATE = 0.04\n",
    "LIBRARY_SEED = 100  # night n's file is chemlib.library(..., seed=LIBRARY_SEED + n)\n",
    "ONE_PAGE_START = 1_666_800  # where the \"one page of a sorted export\" starts in the library\n",
    "TIMING_SEED = 1  # seeds the simulated step durations (Section 3)\n",
    "FORTNIGHT_SEED = 14  # seeds the step durations of the fortnight of runs (Section 8)\n",
    "\n",
    "# the validation rule: elements a record may contain\n",
    "ALLOWED_ELEMENTS = {\"C\", \"H\", \"N\", \"O\", \"S\", \"F\", \"Cl\", \"Br\"}\n",
    "\n",
    "# the simulated clock: milliseconds each step takes per row, and the fortnight's timetable\n",
    "MS_PER_ROW = {\"validate\": 0.4, \"deduplicate\": 0.5, \"enrich\": 0.05, \"describe\": 0.3}\n",
    "FIRST_NIGHT = datetime(2027, 1, 4, 2, 0)  # 02:00 UTC on the first night\n",
    "NIGHTS = 14\n",
    "BUG_NIGHT = 8  # the night the inner-join bug is deployed (Section 8)\n",
    "ONE_PAGE_NIGHT = 11  # the night the supplier sends one page of a sorted export\n",
    "MORNING_CHECK = timedelta(hours=7)  # the freshness check runs at 09:00, 7 hours after the load\n",
    "\n",
    "# thresholds for the checks and alerts\n",
    "FRESHNESS_LIMIT = timedelta(hours=26)  # a nightly job: one day plus some slack\n",
    "QUARANTINE_LIMIT = 0.10  # alert above this share of rows quarantined\n",
    "PSI_BINS = 10  # bins (reference deciles) for the population stability index\n",
    "PSI_LOOK, PSI_ALERT = 0.1, 0.25  # PSI: worth a look above 0.1, an alert above 0.25\n",
    "\n",
    "# the dashboard's colours (the course's colour-blind-safe palette)\n",
    "COLOURS = {\"ink\": \"#1d2130\", \"violet\": \"#7c5cf0\", \"cyan\": \"#0e9fb5\", \"muted\": \"#8b91a1\"}\n",
    "\n",
    "RDLogger.DisableLog(\"rdApp.*\")  # we record RDKit's failures ourselves, as quarantine reasons\n",
    "matplotlib.use(\"Agg\")  # draw figures to files, without a window\n",
    "WORK.mkdir(exist_ok=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. What monitoring is for\n",
    "\n",
    "Our example is a nightly load from a compound supplier: read the file, validate each record, remove\n",
    "duplicates, add the vendor's details, calculate two descriptors and publish the result as Parquet.\n",
    "Tonight's file holds 1,500 molecules, with faults added at a known rate of 4% (as in\n",
    "[Module 6](../06-validating-molecules/)); the duplicates arrive as extra rows, so the file has\n",
    "1,510 records. First, the validation rule every record goes through: the `check` function below\n",
    "reads a SMILES and returns the molecule and an empty reason, or no molecule and the reason it was\n",
    "rejected. `Counter`, imported in the Setup block, tallies the reasons: it counts and sorts in one\n",
    "step. In the last line, `{reason:25}` prints the reason padded to 25 characters and `{count:>5}`\n",
    "prints the count right-aligned in 5, so the numbers line up in a column; `reason or \"accepted\"`\n",
    "uses the word \"accepted\" when the reason is empty."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "1510 records tonight\n",
      "accepted                  1460\n",
      "more than one component     20\n",
      "element not allowed         10\n",
      "unreadable                  10\n",
      "impossible valence          10\n"
     ]
    }
   ],
   "source": [
    "def check(smiles):\n",
    "    \"\"\"Read one record and say why it cannot be used.\n",
    "\n",
    "    Args:\n",
    "        smiles: The record's SMILES.\n",
    "\n",
    "    Returns:\n",
    "        The molecule (None if rejected) and the quarantine reason (\"\" if accepted).\n",
    "    \"\"\"\n",
    "    mol = Chem.MolFromSmiles(smiles, sanitize=False)\n",
    "    if mol is None:\n",
    "        return None, \"unreadable\"\n",
    "    try:\n",
    "        Chem.SanitizeMol(mol)\n",
    "    except Chem.MolSanitizeException:\n",
    "        return None, \"impossible valence\"\n",
    "    if len(Chem.GetMolFrags(mol)) > 1:\n",
    "        return None, \"more than one component\"\n",
    "    if {atom.GetSymbol() for atom in mol.GetAtoms()} - ALLOWED_ELEMENTS:\n",
    "        return None, \"element not allowed\"\n",
    "    return mol, \"\"\n",
    "\n",
    "\n",
    "tonight = chemlib.add_defects(\n",
    "    chemlib.library(NIGHTLY_MOLECULES, seed=LIBRARY_SEED + 1), rate=DEFECT_RATE, seed=1\n",
    ")\n",
    "reasons = [check(smiles)[1] for smiles in tonight[\"smiles\"]]\n",
    "print(len(tonight), \"records tonight\")\n",
    "for reason, count in Counter(reason or \"accepted\" for reason in reasons).most_common():\n",
    "    print(f\"{reason:25}{count:>5}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "None of what follows changes this chemistry. Monitoring sits around the steps: it records what\n",
    "each one did, checks that the records add up, compares the data with what we expect, and tells a\n",
    "person when something is off.\n",
    "\n",
    "![The monitoring loop: each run is recorded in the run history, checked against rules, and an alert reaches a person when a check fails](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/14-monitoring-pipelines/figures/monitoring-loop.svg)\n",
    "\n",
    "## 2. Structured logs\n",
    "\n",
    "Module 1 ([Why log and not print](../01-graphs-and-matrices/#why-log-and-not-print)) gave the\n",
    "reasons to log rather than print: every line has a level, so a job can run quietly in production\n",
    "and verbosely when debugging, and handlers send the same line to the screen, a file and a log\n",
    "service at once. Every module since has used the plain logger from its Setup block, which writes a\n",
    "level and a message. A nightly job needs more from its logs than that, and this section builds it\n",
    "on the same `logging` module from three parts:\n",
    "\n",
    "- a **logger**, the object you call (`pipeline_log.info(...)`) to write a line;\n",
    "- **handlers**, which decide where each line goes: one to the screen, one to a file;\n",
    "- a **formatter**, which decides what each line looks like. We write our own, which turns each line\n",
    "  into JSON.\n",
    "\n",
    "A free-text line such as `validated 1500 rows, 50 bad` is easy to write and hard to use:\n",
    "to count bad rows across a month of runs, someone has to write a pattern that picks the number out\n",
    "of the sentence. A **structured log** writes one JSON object per line, with the same fields every\n",
    "time: the time, the level, the event, the run, the step and its counts. Log services (programs that\n",
    "collect the logs of many machines in one place and let you search them, such as Elasticsearch,\n",
    "Loki, CloudWatch and Datadog) index those fields; so can DuckDB, as we will see.\n",
    "\n",
    "Two more things go into the formatter. Its time comes from a **clock object we pass in** (an\n",
    "injected clock), not from the computer's clock, so a test or a lesson can set the time and get the\n",
    "same output on every run. And it **removes secrets**. A connection string, the address a program\n",
    "uses to reach a database, often holds a user name and password\n",
    "(`postgresql://loader:s3cret@chemdb...` below); an API token is a password-like key that a program\n",
    "sends to a web service. Logs are copied, shipped and read by many people; a password written into\n",
    "one has leaked.\n",
    "\n",
    "The code below has four pieces. `Clock` is a class (a recipe for an object that keeps its own data,\n",
    "here the time, and has its own functions, called methods). `redact` finds secrets with two\n",
    "**regular expressions**, patterns for matching text: the first matches the `:password@` part of an\n",
    "address, the second matches `password=`, `token=` or `api_key=` and the value after it; each match\n",
    "is replaced with `***`. `JsonFormatter` builds on `logging`'s own formatter and changes only one\n",
    "method, `format`, which turns a log record into a JSON line. `make_logger` puts them together. A\n",
    "line can carry extra fields: we pass them as `extra={\"fields\": {...}}` when we log, and the\n",
    "formatter adds them to the JSON."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Clock:\n",
    "    \"\"\"The time, as the pipeline sees it: set and advanced by hand (an injected clock).\n",
    "\n",
    "    In production the same interface would return datetime.now(timezone.utc).\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, start):\n",
    "        self.time = start\n",
    "\n",
    "    def now(self):\n",
    "        \"\"\"The current time (UTC).\"\"\"\n",
    "        return self.time\n",
    "\n",
    "    def advance(self, seconds):\n",
    "        \"\"\"Move the clock forward.\"\"\"\n",
    "        self.time += timedelta(seconds=seconds)\n",
    "\n",
    "\n",
    "PASSWORD_IN_URL = re.compile(r\"(://[^:/@\\s]+):[^@\\s]+@\")\n",
    "SECRET_FIELD = re.compile(r\"((?:password|token|api_key)=)[^&\\s\\\"]+\", re.IGNORECASE)\n",
    "\n",
    "\n",
    "def redact(text):\n",
    "    \"\"\"Replace passwords and tokens in a line of text with ***.\"\"\"\n",
    "    text = PASSWORD_IN_URL.sub(r\"\\1:***@\", text)\n",
    "    return SECRET_FIELD.sub(r\"\\1***\", text)\n",
    "\n",
    "\n",
    "class JsonFormatter(logging.Formatter):\n",
    "    \"\"\"Format each log record as one line of JSON, with its fields, and secrets removed.\"\"\"\n",
    "\n",
    "    def __init__(self, clock):\n",
    "        super().__init__()\n",
    "        self.clock = clock\n",
    "\n",
    "    def format(self, record):\n",
    "        \"\"\"The record as a JSON line.\"\"\"\n",
    "        event = {\n",
    "            \"time\": self.clock.now().isoformat(timespec=\"seconds\"),\n",
    "            \"level\": record.levelname,\n",
    "            \"event\": record.getMessage(),\n",
    "        }\n",
    "        event.update(getattr(record, \"fields\", {}))\n",
    "        return redact(json.dumps(event))\n",
    "\n",
    "\n",
    "def make_logger(clock, path, screen_level=logging.INFO):\n",
    "    \"\"\"A logger that writes JSON lines to a file (everything) and to the screen (from a level).\n",
    "\n",
    "    Args:\n",
    "        clock: Where the times come from.\n",
    "        path: The log file.\n",
    "        screen_level: The lowest level to show on screen.\n",
    "\n",
    "    Returns:\n",
    "        The logger.\n",
    "    \"\"\"\n",
    "    pipeline_log = logging.getLogger(\"supplier_pipeline\")\n",
    "    for old in list(pipeline_log.handlers):  # running this twice must not double every line\n",
    "        old.close()\n",
    "        pipeline_log.removeHandler(old)\n",
    "    pipeline_log.setLevel(logging.INFO)\n",
    "    pipeline_log.propagate = False  # its lines are JSON; keep them out of the plain Setup handler\n",
    "    screen = logging.StreamHandler()\n",
    "    screen.setLevel(screen_level)\n",
    "    file = logging.FileHandler(path, mode=\"w\", encoding=\"utf-8\")\n",
    "    for handler in (screen, file):\n",
    "        handler.setFormatter(JsonFormatter(clock))\n",
    "        pipeline_log.addHandler(handler)\n",
    "    return pipeline_log\n",
    "\n",
    "\n",
    "clock = Clock(FIRST_NIGHT)\n",
    "pipeline_log = make_logger(clock, LOG_FILE)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The logger is named `supplier_pipeline`, so its lines are kept apart from the lesson's own `log`\n",
    "and from the libraries' loggers, and it has two handlers: the screen shows INFO and above, the file\n",
    "keeps everything the logger lets through. Now the start of a run, written to it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{\"time\": \"2027-01-04T02:00:00\", \"level\": \"INFO\", \"event\": \"run started\", \"run_id\": \"run-0001\", \"source\": \"postgresql://loader:***@chemdb.example.org/suppliers\"}\n",
      "{\"time\": \"2027-01-04T02:00:04\", \"level\": \"WARNING\", \"event\": \"records quarantined\", \"run_id\": \"run-0001\", \"step\": \"validate\", \"rows_in\": 1510, \"quarantined\": 50}\n"
     ]
    }
   ],
   "source": [
    "source = \"postgresql://loader:s3cret@chemdb.example.org/suppliers\"\n",
    "pipeline_log.info(\"run started\", extra={\"fields\": {\"run_id\": \"run-0001\", \"source\": source}})\n",
    "pipeline_log.debug(\"atom-by-atom detail: below the logger's level, so it is dropped\")\n",
    "clock.advance(4)\n",
    "n_bad = sum(reason != \"\" for reason in reasons)\n",
    "fields = {\"run_id\": \"run-0001\", \"step\": \"validate\", \"rows_in\": len(tonight), \"quarantined\": n_bad}\n",
    "pipeline_log.warning(\"records quarantined\", extra={\"fields\": fields})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The password in the connection string never reached the screen or the file, and the DEBUG line\n",
    "was dropped. Because every line is JSON, the log file is a table. DuckDB reads it directly, which\n",
    "is how you would answer \"how many warnings did last night's run write?\" without a regular\n",
    "expression. The question is written in SQL: `read_json_auto(...)` reads the file as a table,\n",
    "`GROUP BY level` puts the lines with the same level together, and `count(*)` counts each group.\n",
    "`.df()` hands the answer back as a pandas table:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "  level  events\n",
      "   INFO       1\n",
      "WARNING       1\n"
     ]
    }
   ],
   "source": [
    "print(\n",
    "    duckdb.sql(\n",
    "        f\"SELECT level, count(*) AS events FROM read_json_auto('{LOG_FILE.as_posix()}') \"\n",
    "        \"GROUP BY level ORDER BY level\"\n",
    "    ).df().to_string(index=False)\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. A run history\n",
    "\n",
    "Logs are a stream of events. To compare runs (was last night's run slower, did it quarantine more\n",
    "than usual?) we also keep a **run history**: a table with one row per run and one per step, with\n",
    "start and finish times and the counts in and out. Here it lives in DuckDB; a team that shares it\n",
    "would put the same two tables in PostgreSQL, a database server many people can use at once (Module\n",
    "4), and workflow tools (programs that start pipelines on a timetable and keep track of them, such\n",
    "as Airflow, Dagster and Prefect) keep a table much like it for every task they run.\n",
    "\n",
    "The code connects to a DuckDB file and creates three empty tables with SQL's `CREATE TABLE`: `runs`,\n",
    "`steps`, and `quarantine` for the rejected records. Each column is given a type: `VARCHAR` is text,\n",
    "`INTEGER` a whole number, `TIMESTAMP` a date and time. `PRIMARY KEY` means no two rows may have the\n",
    "same `run_id`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "HISTORY_DB.unlink(missing_ok=True)  # start each run of the lesson from an empty history\n",
    "db = duckdb.connect(str(HISTORY_DB))\n",
    "db.execute(\"\"\"\n",
    "    CREATE TABLE runs (\n",
    "        run_id VARCHAR PRIMARY KEY, started TIMESTAMP, finished TIMESTAMP, status VARCHAR,\n",
    "        rows_in INTEGER, rows_out INTEGER, quarantined INTEGER, duplicates INTEGER,\n",
    "        message VARCHAR)\n",
    "\"\"\")\n",
    "db.execute(\"\"\"\n",
    "    CREATE TABLE steps (\n",
    "        run_id VARCHAR, step_no INTEGER, step VARCHAR, started TIMESTAMP, finished TIMESTAMP,\n",
    "        rows_in INTEGER, rows_out INTEGER, quarantined INTEGER, duplicates INTEGER)\n",
    "\"\"\")\n",
    "db.execute(\"CREATE TABLE quarantine (run_id VARCHAR, id VARCHAR, smiles VARCHAR, reason VARCHAR)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each step is a function that takes a table and returns three things: the rows it keeps, the rows\n",
    "it quarantines (with a reason), and how many duplicates it removed. Keeping that shape for every\n",
    "step is what makes the counts checkable later. Validation keeps each RDKit molecule in a `mol`\n",
    "column, so later steps do not read the SMILES again (reading is a large share of the time).\n",
    "\n",
    "The four steps:\n",
    "\n",
    "- `validate` runs `check` on every record. `[mol for mol, _ in checked]` is a list comprehension,\n",
    "  a one-line loop that builds a list: it takes the molecule out of each (molecule, reason) pair, and\n",
    "  `_` is the usual name for the part we do not need. `bad` is True for rejected rows, and `~bad`\n",
    "  means \"not bad\".\n",
    "- `deduplicate` keeps the first record of each InChIKey\n",
    "  ([Module 3](../03-files-and-identity/)).\n",
    "- `enrich` adds each vendor's country and lead time from a small table, `VENDORS`. It uses pandas'\n",
    "  `merge`, which **joins** two tables: for every row on the left (our compounds) it finds the row on\n",
    "  the right (the vendors) with the same value in the shared column, here `vendor`, and adds that\n",
    "  row's columns, much like VLOOKUP in a spreadsheet. With `how=\"left\"`, every compound is kept even\n",
    "  when its vendor is not in the table; `indicator=True` adds a column, `_merge`, that says\n",
    "  `left_only` for those, so we can quarantine them.\n",
    "- `describe` adds molecular weight and logP, rounded to two decimals."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NO_ROWS = pd.DataFrame(columns=[\"id\", \"smiles\", \"reason\"])\n",
    "VENDORS = pd.DataFrame(\n",
    "    {\n",
    "        \"vendor\": [\"Vendor A\", \"Vendor B\", \"Vendor C\"],\n",
    "        \"country\": [\"UK\", \"Germany\", \"Ukraine\"],\n",
    "        \"lead_time_days\": [5, 7, 14],\n",
    "    }\n",
    ")\n",
    "\n",
    "\n",
    "def validate(df):\n",
    "    \"\"\"Keep records that pass `check`, with their molecule; quarantine the rest with a reason.\"\"\"\n",
    "    checked = [check(smiles) for smiles in df[\"smiles\"]]\n",
    "    df = df.assign(mol=[mol for mol, _ in checked], reason=[reason for _, reason in checked])\n",
    "    bad = df[\"reason\"] != \"\"\n",
    "    return df[~bad].drop(columns=\"reason\"), df.loc[bad, [\"id\", \"smiles\", \"reason\"]], 0\n",
    "\n",
    "\n",
    "def deduplicate(df):\n",
    "    \"\"\"Keep the first record of each molecule, by InChIKey (as in Module 3).\"\"\"\n",
    "    keys = [Chem.MolToInchiKey(mol) for mol in df[\"mol\"]]\n",
    "    df = df.assign(inchikey=keys)\n",
    "    kept = df.drop_duplicates(\"inchikey\")\n",
    "    return kept, NO_ROWS, len(df) - len(kept)\n",
    "\n",
    "\n",
    "def enrich(df):\n",
    "    \"\"\"Add each vendor's country and lead time; quarantine records from an unknown vendor.\"\"\"\n",
    "    merged = df.merge(VENDORS, on=\"vendor\", how=\"left\", indicator=True)\n",
    "    unknown = merged[\"_merge\"] == \"left_only\"\n",
    "    quarantined = merged.loc[unknown, [\"id\", \"smiles\"]].assign(reason=\"unknown vendor\")\n",
    "    return merged[~unknown].drop(columns=\"_merge\"), quarantined, 0\n",
    "\n",
    "\n",
    "def describe(df):\n",
    "    \"\"\"Add molecular weight and logP, the two properties we watch for drift.\"\"\"\n",
    "    df = df.assign(\n",
    "        mw=[round(Descriptors.MolWt(mol), 2) for mol in df[\"mol\"]],\n",
    "        logp=[round(Descriptors.MolLogP(mol), 2) for mol in df[\"mol\"]],\n",
    "    )\n",
    "    return df, NO_ROWS, 0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The runner calls the steps in order and records each one. The work is real; the time each step\n",
    "takes is simulated (each step's milliseconds per row, `MS_PER_ROW` in the Setup block, give or\n",
    "take a seeded random 20%, move the clock on), so the run history comes out the same on every\n",
    "computer. In production the clock is the real one and nothing else changes. `rng` is NumPy's random\n",
    "number generator, made from a seed so it gives the same numbers on every run. In the SQL, each `?`\n",
    "is a placeholder that DuckDB fills, in order, from the list of values after it; this is safer than\n",
    "pasting values into the text of the query."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_step(run_id, step_no, name, func, df, rng):\n",
    "    \"\"\"Run one step, move the clock on, and record what the step did.\n",
    "\n",
    "    Args:\n",
    "        run_id: The run.\n",
    "        step_no: The step's position in the run.\n",
    "        name: The step's name.\n",
    "        func: The step: a table in; kept rows, quarantined rows and duplicates removed out.\n",
    "        df: The rows going in.\n",
    "        rng: The random generator for the simulated duration.\n",
    "\n",
    "    Returns:\n",
    "        The rows the step kept.\n",
    "    \"\"\"\n",
    "    started = clock.now()\n",
    "    kept, quarantined, duplicates = func(df)\n",
    "    clock.advance(len(df) * MS_PER_ROW[name] / 1000 * rng.uniform(0.8, 1.2))\n",
    "    db.execute(\n",
    "        \"INSERT INTO steps VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n",
    "        [run_id, step_no, name, started, clock.now(), len(df), len(kept), len(quarantined),\n",
    "         duplicates],\n",
    "    )\n",
    "    if len(quarantined):\n",
    "        db.execute(\"INSERT INTO quarantine SELECT ?, id, smiles, reason FROM quarantined\", [run_id])\n",
    "    pipeline_log.info(\"step finished\", extra={\"fields\": {\n",
    "        \"run_id\": run_id, \"step\": name, \"rows_in\": len(df), \"rows_out\": len(kept),\n",
    "        \"quarantined\": len(quarantined), \"duplicates\": duplicates}})\n",
    "    return kept"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "DuckDB's `FROM quarantined` reads the pandas table of that name straight from Python. Now one run,\n",
    "with the log on screen showing warnings only, so the per-step lines go to the file.\n",
    "`enumerate(steps, start=1)` numbers the steps 1, 2, 3, 4 as the loop goes through them:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "       step  rows_in  rows_out  quarantined  duplicates\n",
      "   validate     1510      1460           50           0\n",
      "deduplicate     1460      1449            0          11\n",
      "     enrich     1449      1449            0           0\n",
      "   describe     1449      1449            0           0\n"
     ]
    }
   ],
   "source": [
    "STEPS = [(\"validate\", validate), (\"deduplicate\", deduplicate), (\"enrich\", enrich),\n",
    "         (\"describe\", describe)]\n",
    "\n",
    "\n",
    "def run_pipeline(run_id, batch, steps, rng):\n",
    "    \"\"\"Run every step over a batch and record the run (status, counts) in the run history.\"\"\"\n",
    "    db.execute(\"INSERT INTO runs (run_id, started, status) VALUES (?, ?, 'running')\",\n",
    "               [run_id, clock.now()])\n",
    "    pipeline_log.info(\"run started\", extra={\"fields\": {\"run_id\": run_id, \"rows\": len(batch)}})\n",
    "    df = batch\n",
    "    for step_no, (name, func) in enumerate(steps, start=1):\n",
    "        df = run_step(run_id, step_no, name, func, df, rng)\n",
    "    return df\n",
    "\n",
    "\n",
    "pipeline_log = make_logger(clock, LOG_FILE, screen_level=logging.WARNING)\n",
    "published = run_pipeline(\"run-0001\", tonight, STEPS, np.random.default_rng(TIMING_SEED))\n",
    "print(db.sql(\"SELECT step, rows_in, rows_out, quarantined, duplicates FROM steps \"\n",
    "             \"WHERE run_id = 'run-0001' ORDER BY step_no\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Counts that reconcile\n",
    "\n",
    "Every row that enters a step must leave it by one of three doors: kept, quarantined or removed as a\n",
    "duplicate. So for each step, **in = out + quarantined + duplicates**, and each step's input must be\n",
    "the previous step's output. This is **reconciliation**, the oldest check in data engineering\n",
    "(accountants call it balancing the books), and it is cheap: it needs only the counts we already\n",
    "record. The check below fails loudly, with an exception, rather than writing a warning nobody\n",
    "reads.\n",
    "\n",
    "`class ReconciliationError(Exception)` makes a new kind of error of our own, so that whoever calls\n",
    "`reconcile` can catch exactly this problem with `except ReconciliationError`. In the SQL,\n",
    "`rows_in - rows_out - quarantined - duplicates` is the number of rows that went missing (it should\n",
    "be 0), and `lag(rows_out) OVER (ORDER BY step_no)` takes `rows_out` from the step before, so we can\n",
    "check that each step received what the last one passed on. `itertuples()` goes through the rows of\n",
    "a pandas table one at a time:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO run-0001 reconciles\n"
     ]
    }
   ],
   "source": [
    "class ReconciliationError(Exception):\n",
    "    \"\"\"The counts of a run do not add up: rows were lost or invented.\"\"\"\n",
    "\n",
    "\n",
    "def reconcile(run_id):\n",
    "    \"\"\"Check that every step's rows are accounted for and that the steps chain together.\n",
    "\n",
    "    Raises:\n",
    "        ReconciliationError: listing every step whose counts do not add up.\n",
    "    \"\"\"\n",
    "    problems = db.execute(\"\"\"\n",
    "        SELECT step, rows_in, rows_out, quarantined, duplicates,\n",
    "               rows_in - rows_out - quarantined - duplicates AS unaccounted,\n",
    "               lag(rows_out) OVER (ORDER BY step_no) AS previous_out\n",
    "        FROM steps WHERE run_id = ?\n",
    "        ORDER BY step_no\n",
    "    \"\"\", [run_id]).df()\n",
    "    lost = problems[\"unaccounted\"] != 0\n",
    "    broken_chain = problems[\"previous_out\"].notna() & (\n",
    "        problems[\"rows_in\"] != problems[\"previous_out\"])\n",
    "    messages = [f\"{row.step}: {row.rows_in} in, {row.rows_out} out, {row.quarantined} quarantined,\"\n",
    "                f\" {row.duplicates} duplicates, {row.unaccounted} unaccounted for\"\n",
    "                for row in problems[lost | broken_chain].itertuples()]\n",
    "    if messages:\n",
    "        raise ReconciliationError(\"; \".join(messages))\n",
    "\n",
    "\n",
    "reconcile(\"run-0001\")\n",
    "log.info(\"%s reconciles\", \"run-0001\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now the bug it exists for. Someone refreshes the vendor table from a spreadsheet that has not yet\n",
    "caught up with Vendor C, and rewrites the enrichment step with pandas' `merge` but leaves out\n",
    "`how=\"left\"`. The default is then an **inner join**, which keeps only the rows found in both\n",
    "tables: compounds with no matching vendor simply disappear. Nothing crashes, the step \"succeeds\",\n",
    "and the output looks like a normal, slightly small table."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "rows published: 955 instead of 1449\n",
      "ReconciliationError: enrich: 1449 in, 955 out, 0 quarantined, 0 duplicates, 494 unaccounted for\n"
     ]
    }
   ],
   "source": [
    "VENDORS_FROM_SPREADSHEET = VENDORS[VENDORS[\"vendor\"] != \"Vendor C\"]\n",
    "\n",
    "\n",
    "def enrich_inner_join(df):\n",
    "    \"\"\"The buggy version: merge's default inner join drops rows from vendors not in the table.\"\"\"\n",
    "    return df.merge(VENDORS_FROM_SPREADSHEET, on=\"vendor\"), NO_ROWS, 0\n",
    "\n",
    "\n",
    "buggy_steps = [(\"validate\", validate), (\"deduplicate\", deduplicate),\n",
    "               (\"enrich\", enrich_inner_join), (\"describe\", describe)]\n",
    "clock.advance(600)\n",
    "lost_rows = run_pipeline(\"run-0001-bug\", tonight, buggy_steps, np.random.default_rng(TIMING_SEED))\n",
    "print(\"rows published:\", len(lost_rows), \"instead of\", len(published))\n",
    "try:\n",
    "    reconcile(\"run-0001-bug\")\n",
    "except ReconciliationError as err:\n",
    "    print(\"ReconciliationError:\", err)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A third of the batch would have vanished without a trace. Reconciliation names the step and the\n",
    "number. The fix is the version we started with: a left join (`how=\"left\"`), with unmatched rows\n",
    "quarantined under a reason, so the counts add up and the quarantine rate (next section) shows the\n",
    "missing vendor the same night.\n",
    "\n",
    "The runner's last job is to reconcile before publishing, and to close the run's row with its totals\n",
    "and status. Publishing only after the check means a run that fails reconciliation writes nothing\n",
    "downstream (nothing reaches the people and programs that use its output). `finish_run` fills in\n",
    "the run's row with SQL's `UPDATE`, taking the totals from the `steps` table; `df.iloc[0:0]` is the\n",
    "table with all its rows removed, so a failed run records 0 rows out:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def finish_run(run_id, df, status, message=\"\"):\n",
    "    \"\"\"Close a run: its finish time, status and totals (summed from its steps).\"\"\"\n",
    "    db.execute(\"\"\"\n",
    "        UPDATE runs SET finished = ?, status = ?, message = ?,\n",
    "            rows_in = (SELECT rows_in FROM steps WHERE run_id = ? AND step_no = 1),\n",
    "            rows_out = ?,\n",
    "            quarantined = (SELECT sum(quarantined) FROM steps WHERE run_id = ?),\n",
    "            duplicates = (SELECT sum(duplicates) FROM steps WHERE run_id = ?)\n",
    "        WHERE run_id = ?\n",
    "    \"\"\", [clock.now(), status, message, run_id, len(df), run_id, run_id, run_id])\n",
    "\n",
    "\n",
    "def run_and_publish(run_id, batch, steps, rng):\n",
    "    \"\"\"Run, reconcile, and only then publish the result as Parquet.\"\"\"\n",
    "    df = run_pipeline(run_id, batch, steps, rng)\n",
    "    try:\n",
    "        reconcile(run_id)\n",
    "    except ReconciliationError as err:\n",
    "        finish_run(run_id, df.iloc[0:0], \"failed\", str(err))\n",
    "        pipeline_log.error(\"run failed reconciliation; nothing published\",\n",
    "                           extra={\"fields\": {\"run_id\": run_id}})\n",
    "        return None\n",
    "    df = df.drop(columns=\"mol\")  # RDKit objects stay in memory; the SMILES is what we store\n",
    "    PUBLISHED.mkdir(exist_ok=True)\n",
    "    df.to_parquet(PUBLISHED / f\"{run_id}.parquet\", index=False)\n",
    "    finish_run(run_id, df, \"succeeded\")\n",
    "    return df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Metrics: throughput, rates and freshness\n",
    "\n",
    "A few numbers per run, read from the run history, describe a pipeline's health:\n",
    "\n",
    "- **throughput**, rows per second, which shows a run getting slower long before it times out;\n",
    "- **quarantine rate**, the share of rows rejected; a sudden rise usually means the input changed,\n",
    "  not the chemistry;\n",
    "- **error rate**, the share of recent runs that failed;\n",
    "- **freshness**, the time since the last successful run, against an agreed limit. For a nightly\n",
    "  job, 26 hours is a common choice: one day plus some slack.\n",
    "\n",
    "Freshness catches what no per-run check can: the run that never happened. If the scheduler (the\n",
    "program that starts the job every night) stops, there is no failed run to alert on, only data\n",
    "quietly growing old.\n",
    "\n",
    "The limit is `FRESHNESS_LIMIT` in the Setup block. In the SQL below, `epoch(finished - started)` is\n",
    "the length of the run in seconds, and `<>` means \"not equal to\". In the last line,\n",
    "`{...:.1f}` prints the number with one decimal place."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "  run_id    status  rows_per_s  quarantined_pct\n",
      "run-0002 succeeded       908.0              3.3\n",
      "freshness: 30.0 h; within the limit: False\n"
     ]
    }
   ],
   "source": [
    "def freshness(now):\n",
    "    \"\"\"Time since the last successful run finished (None if there has never been one).\"\"\"\n",
    "    last = db.execute(\"SELECT max(finished) FROM runs WHERE status = 'succeeded'\").fetchall()[0][0]\n",
    "    return None if last is None else now - last\n",
    "\n",
    "\n",
    "clock.advance(600)\n",
    "run_and_publish(\"run-0002\", tonight, STEPS, np.random.default_rng(TIMING_SEED + 1))\n",
    "metrics = db.sql(\"\"\"\n",
    "    SELECT run_id, status,\n",
    "           round(rows_in / epoch(finished - started)) AS rows_per_s,\n",
    "           round(100 * quarantined / rows_in, 1) AS quarantined_pct\n",
    "    FROM runs WHERE status <> 'running' ORDER BY started\n",
    "\"\"\").df()\n",
    "print(metrics.to_string(index=False))\n",
    "clock.advance(30 * 3600)  # thirty hours later, and no run since\n",
    "age = freshness(clock.now())\n",
    "print(f\"freshness: {age.total_seconds() / 3600:.1f} h; within the limit: {age <= FRESHNESS_LIMIT}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The two first runs above were not closed by `finish_run` (we ran them before writing it), so they\n",
    "stay `running` and the query leaves them out. In a real history, a run stuck in `running` for hours\n",
    "is itself worth an alert: the process died without recording anything.\n",
    "\n",
    "## 6. Drift in molecular properties\n",
    "\n",
    "A run can reconcile perfectly and still deliver the wrong data. Suppose a supplier's export was\n",
    "sorted by structure and only one page of it was sent: every molecule is valid, the counts add up,\n",
    "and every molecule carries a phenyl and a fluorophenyl group. Models trained on the old data, and\n",
    "chemists choosing compounds from it, would be misled. Watching the **distribution** of a few\n",
    "properties catches this. A change in the distribution from one batch to the next is called\n",
    "**drift**. We compare each new batch with a **reference**: a batch we have checked and trust, here\n",
    "the output of the first run.\n",
    "\n",
    "The **population stability index** (PSI) compares two distributions. Cut the reference into ten\n",
    "bins with equal numbers of molecules (its deciles), count the share of the new batch in each bin,\n",
    "and add up `(new - ref) × ln(new / ref)` over the bins. Identical distributions give 0; the bigger\n",
    "the shift, the bigger the number. The **Kolmogorov–Smirnov statistic** (KS) uses the cumulative\n",
    "distribution: for each value of, say, molecular weight, the share of molecules at or below it,\n",
    "which rises from 0 to 1. KS is the largest vertical gap between the two batches' cumulative\n",
    "distributions, from 0 (the same) to 1 (no overlap). Both are a few lines of NumPy: `np.quantile`\n",
    "finds the bin edges, `np.histogram` counts the molecules in each bin, and `np.searchsorted` counts,\n",
    "for each value, how many molecules lie at or below it.\n",
    "\n",
    "The batch for the one-page example comes from `chemlib.stream`, which hands out a library a batch\n",
    "at a time (a generator, [Module 8](../08-larger-than-memory/)); `next(...)` takes its first batch.\n",
    "The `print` lines use the same padding as in Section 1, and `:8.3f` means 8 characters wide with 3\n",
    "decimals:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "batch       PSI MW  PSI logP   KS MW  KS logP\n",
      "ordinary     0.008     0.008   0.032    0.020\n",
      "one page     2.576     5.935   0.492    0.788\n"
     ]
    }
   ],
   "source": [
    "def psi(reference, new, bins=PSI_BINS):\n",
    "    \"\"\"Population stability index of `new` against `reference`, on the reference's quantiles.\"\"\"\n",
    "    edges = np.quantile(reference, np.linspace(0, 1, bins + 1))\n",
    "    edges[0], edges[-1] = -np.inf, np.inf  # catch values beyond the reference's range\n",
    "    ref_share = np.histogram(reference, edges)[0] / len(reference)\n",
    "    new_share = np.histogram(new, edges)[0] / len(new)\n",
    "    ref_share = np.clip(ref_share, 1e-4, None)  # an empty bin would give log(0)\n",
    "    new_share = np.clip(new_share, 1e-4, None)\n",
    "    return float(np.sum((new_share - ref_share) * np.log(new_share / ref_share)))\n",
    "\n",
    "\n",
    "def ks(reference, new):\n",
    "    \"\"\"Two-sample Kolmogorov-Smirnov statistic: the largest gap between the two CDFs.\"\"\"\n",
    "    values = np.concatenate([reference, new])\n",
    "    cdf_ref = np.searchsorted(np.sort(reference), values, side=\"right\") / len(reference)\n",
    "    cdf_new = np.searchsorted(np.sort(new), values, side=\"right\") / len(new)\n",
    "    return float(np.max(np.abs(cdf_ref - cdf_new)))\n",
    "\n",
    "\n",
    "def properties(smiles):\n",
    "    \"\"\"Molecular weight and logP of a list of SMILES, as two arrays.\"\"\"\n",
    "    mols = [Chem.MolFromSmiles(s) for s in smiles]\n",
    "    return (np.array([Descriptors.MolWt(m) for m in mols]),\n",
    "            np.array([Descriptors.MolLogP(m) for m in mols]))\n",
    "\n",
    "\n",
    "reference = published  # run-0001's output, checked by a chemist: the reference\n",
    "ordinary = properties(chemlib.library(NIGHTLY_MOLECULES, seed=LIBRARY_SEED + 2)[\"smiles\"])\n",
    "one_page_batch = next(\n",
    "    chemlib.stream(NIGHTLY_MOLECULES, batch=NIGHTLY_MOLECULES, start=ONE_PAGE_START)\n",
    ")\n",
    "one_page = properties(one_page_batch[\"smiles\"])\n",
    "print(f\"{'batch':10}{'PSI MW':>8}{'PSI logP':>10}{'KS MW':>8}{'KS logP':>9}\")\n",
    "for name, (mw, logp) in [(\"ordinary\", ordinary), (\"one page\", one_page)]:\n",
    "    print(f\"{name:10}{psi(reference['mw'], mw):8.3f}{psi(reference['logp'], logp):10.3f}\"\n",
    "          f\"{ks(reference['mw'], mw):8.3f}{ks(reference['logp'], logp):9.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Molecular weight of the reference, an ordinary new batch and the one-page batch: the ordinary batch overlaps the reference; the one-page batch is shifted to heavier molecules](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/14-monitoring-pipelines/figures/drift-histograms.svg)\n",
    "\n",
    "The usual reading of PSI comes from credit scoring: **below 0.1, no real change; 0.1 to 0.25, a\n",
    "moderate shift worth a look; above 0.25, a significant shift**. These are rules of thumb, not\n",
    "statistics: PSI grows with the number of bins and, for small batches, with sampling noise, so check\n",
    "what your own ordinary batches score (here, about 0.01) before trusting any threshold. The KS\n",
    "statistic comes with a p-value (the chance of a gap this large if nothing had changed; SciPy's\n",
    "`scipy.stats.ks_2samp` gives it), but with thousands of molecules almost any difference is\n",
    "\"significant\"; the size of the gap is the more useful number. Molecular weight and logP are a\n",
    "start; heavy-atom count, ring count, fraction of sp3 carbons and the share of each scaffold are\n",
    "other common choices.\n",
    "\n",
    "## 7. Alerts that people will read\n",
    "\n",
    "A check that nobody hears about is not monitoring. An **alert rule** pairs a metric (one of the\n",
    "numbers above, such as the quarantine rate) with a threshold (the value above which something is\n",
    "wrong) and a severity (how urgent it is). The common practice, from site reliability engineering\n",
    "(the name Google gave to the job of keeping large computer systems running), is to keep two\n",
    "kinds: a **page**, which wakes someone because the data is wrong or missing now, and a **ticket**,\n",
    "which can wait for working hours. The main risk is **alert fatigue**: a rule that fires every night\n",
    "for something harmless trains people to ignore all of them. So alert on symptoms that need a person\n",
    "(a failed run, stale data, a drifted batch), not on every warning in the log, and notify when a\n",
    "rule **starts** firing and when it **resolves**, not on every check in between.\n",
    "\n",
    "The thresholds come from the Setup block, so the rules and the checks above share one value each.\n",
    "\n",
    "Each rule is a **named tuple** ([Module 6](../06-validating-molecules/)): a small record with named\n",
    "fields, here `name`, `metric`, `threshold` and `severity`. The `: str` and `: float` after each\n",
    "field are type hints, notes that say what kind of value the field holds. In the rule names,\n",
    "`{QUARANTINE_LIMIT:.0%}` prints 0.10 as \"10%\".\n",
    "\n",
    "The `Alerter` class remembers which rules are firing now, in a set (`self.firing`, a collection of\n",
    "names with no repeats). Each time it gets new metrics it checks every rule, and it sends a message\n",
    "only when a rule changes state: from quiet to firing, or from firing back to quiet (\"resolved\")."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Rule(NamedTuple):\n",
    "    \"\"\"Alert when `metric` is above `threshold`.\"\"\"\n",
    "\n",
    "    name: str\n",
    "    metric: str\n",
    "    threshold: float\n",
    "    severity: str  # \"page\" (now) or \"ticket\" (working hours)\n",
    "\n",
    "\n",
    "freshness_hours = FRESHNESS_LIMIT.total_seconds() / 3600\n",
    "RULES = [\n",
    "    Rule(\"run failed\", \"failed\", 0.5, \"page\"),\n",
    "    Rule(f\"data older than {freshness_hours:.0f} hours\", \"hours_since_success\", freshness_hours,\n",
    "         \"page\"),\n",
    "    Rule(f\"quarantine rate above {QUARANTINE_LIMIT:.0%}\", \"quarantine_rate\", QUARANTINE_LIMIT,\n",
    "         \"ticket\"),\n",
    "    Rule(f\"molecular weight drift (PSI above {PSI_ALERT})\", \"psi_mw\", PSI_ALERT, \"ticket\"),\n",
    "    Rule(f\"logP drift (PSI above {PSI_ALERT})\", \"psi_logp\", PSI_ALERT, \"ticket\"),\n",
    "]\n",
    "\n",
    "\n",
    "class Alerter:\n",
    "    \"\"\"Evaluate rules and notify only when a rule starts or stops firing.\"\"\"\n",
    "\n",
    "    def __init__(self, rules):\n",
    "        self.rules = rules\n",
    "        self.firing = set()\n",
    "\n",
    "    def update(self, metrics):\n",
    "        \"\"\"Check every rule whose metric is in `metrics`; notify on changes.\"\"\"\n",
    "        for rule in self.rules:\n",
    "            if rule.metric not in metrics:\n",
    "                continue\n",
    "            now_firing = metrics[rule.metric] > rule.threshold\n",
    "            if now_firing and rule.name not in self.firing:\n",
    "                self.firing.add(rule.name)\n",
    "                self.notify(rule, \"FIRING\", metrics)\n",
    "            elif not now_firing and rule.name in self.firing:\n",
    "                self.firing.remove(rule.name)\n",
    "                self.notify(rule, \"resolved\", metrics)\n",
    "\n",
    "    def notify(self, rule, state, metrics):\n",
    "        \"\"\"Send one alert. Here it is a log line; a chat webhook or on-call service is one call more.\n",
    "\n",
    "        With a webhook it would be: requests.post(url, json={\"text\": message}, timeout=10).\n",
    "        \"\"\"\n",
    "        level = logging.ERROR if rule.severity == \"page\" and state == \"FIRING\" else logging.WARNING\n",
    "        fields = {\"alert\": rule.name, \"state\": state, \"severity\": rule.severity,\n",
    "                  \"value\": round(float(metrics[rule.metric]), 3), \"run_id\": metrics.get(\"run_id\")}\n",
    "        pipeline_log.log(level, \"alert\", extra={\"fields\": fields})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In a team the `notify` method posts to a chat channel or to an on-call service. Slack and Microsoft\n",
    "Teams both give you a **webhook address**: a web address that, when a program sends a JSON message\n",
    "to it, posts that message in a chat channel. On-call services (PagerDuty, Opsgenie) phone or message\n",
    "whoever is on the rota that week. The webhook address is a secret too, since anyone who has it can\n",
    "post to your channel: it belongs in an environment variable (a named setting kept by the operating\n",
    "system outside your code, [Module 10](../10-pipelines-that-survive-failure/)), never in the code or\n",
    "the logs.\n",
    "\n",
    "## 8. A fortnight of runs\n",
    "\n",
    "Now everything together, over fourteen simulated nights. Each night at 02:00 a new file of 1,500\n",
    "molecules arrives (a fresh sample of the library, with 4% faults) and the pipeline runs. Two nights\n",
    "go wrong, on purpose: on **night 8** the inner-join bug from Section 4 is deployed, and on **night\n",
    "11** the supplier sends the one-page batch from Section 6. Every morning at 09:00 a separate check\n",
    "looks at freshness, as a scheduler would. Only warnings and errors are printed; the file has\n",
    "everything.\n",
    "\n",
    "The loop below is long, but each night does the same five things: set the clock to 02:00 on that\n",
    "night, make the night's file, run the pipeline and publish (`run_and_publish`, Section 4), measure\n",
    "drift against the reference and store it in a new `drift` table, and pass the night's metrics to\n",
    "the alerter; then set the clock to 09:00 and pass it the freshness. `f\"run-{night:04d}\"` writes the\n",
    "night as four digits, so night 8 becomes `run-0008`, and `*drift` passes the four drift numbers as\n",
    "four separate values:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{\"time\": \"2027-01-11T02:00:01\", \"level\": \"ERROR\", \"event\": \"run failed reconciliation; nothing published\", \"run_id\": \"run-0008\"}\n",
      "{\"time\": \"2027-01-11T02:00:01\", \"level\": \"ERROR\", \"event\": \"alert\", \"alert\": \"run failed\", \"state\": \"FIRING\", \"severity\": \"page\", \"value\": 1.0, \"run_id\": \"run-0008\"}\n",
      "{\"time\": \"2027-01-11T09:00:00\", \"level\": \"ERROR\", \"event\": \"alert\", \"alert\": \"data older than 26 hours\", \"state\": \"FIRING\", \"severity\": \"page\", \"value\": 31.0, \"run_id\": \"run-0008\"}\n",
      "{\"time\": \"2027-01-12T02:00:02\", \"level\": \"WARNING\", \"event\": \"alert\", \"alert\": \"run failed\", \"state\": \"resolved\", \"severity\": \"page\", \"value\": 0.0, \"run_id\": \"run-0009\"}\n",
      "{\"time\": \"2027-01-12T09:00:00\", \"level\": \"WARNING\", \"event\": \"alert\", \"alert\": \"data older than 26 hours\", \"state\": \"resolved\", \"severity\": \"page\", \"value\": 6.999, \"run_id\": \"run-0009\"}\n",
      "{\"time\": \"2027-01-14T02:00:01\", \"level\": \"WARNING\", \"event\": \"alert\", \"alert\": \"molecular weight drift (PSI above 0.25)\", \"state\": \"FIRING\", \"severity\": \"ticket\", \"value\": 2.574, \"run_id\": \"run-0011\"}\n",
      "{\"time\": \"2027-01-14T02:00:01\", \"level\": \"WARNING\", \"event\": \"alert\", \"alert\": \"logP drift (PSI above 0.25)\", \"state\": \"FIRING\", \"severity\": \"ticket\", \"value\": 5.925, \"run_id\": \"run-0011\"}\n",
      "{\"time\": \"2027-01-15T02:00:01\", \"level\": \"WARNING\", \"event\": \"alert\", \"alert\": \"molecular weight drift (PSI above 0.25)\", \"state\": \"resolved\", \"severity\": \"ticket\", \"value\": 0.018, \"run_id\": \"run-0012\"}\n",
      "{\"time\": \"2027-01-15T02:00:01\", \"level\": \"WARNING\", \"event\": \"alert\", \"alert\": \"logP drift (PSI above 0.25)\", \"state\": \"resolved\", \"severity\": \"ticket\", \"value\": 0.009, \"run_id\": \"run-0012\"}\n"
     ]
    }
   ],
   "source": [
    "for table in (\"runs\", \"steps\", \"quarantine\"):  # a fresh history for the fortnight\n",
    "    db.execute(f\"DELETE FROM {table}\")\n",
    "db.execute(\"CREATE TABLE drift (run_id VARCHAR, psi_mw DOUBLE, psi_logp DOUBLE, \"\n",
    "           \"ks_mw DOUBLE, ks_logp DOUBLE)\")\n",
    "alerter = Alerter(RULES)\n",
    "rng = np.random.default_rng(FORTNIGHT_SEED)\n",
    "\n",
    "for night in range(1, NIGHTS + 1):\n",
    "    run_id = f\"run-{night:04d}\"\n",
    "    clock.time = FIRST_NIGHT + timedelta(days=night - 1)\n",
    "    if night == ONE_PAGE_NIGHT:  # one page of a sorted export\n",
    "        batch = one_page_batch\n",
    "    else:\n",
    "        batch = chemlib.library(NIGHTLY_MOLECULES, seed=LIBRARY_SEED + night)\n",
    "    batch = chemlib.add_defects(batch, rate=DEFECT_RATE, seed=night)\n",
    "    steps = buggy_steps if night == BUG_NIGHT else STEPS\n",
    "    out = run_and_publish(run_id, batch, steps, rng)\n",
    "    run = db.execute(\"SELECT status, quarantined / rows_in FROM runs WHERE run_id = ?\",\n",
    "                     [run_id]).fetchall()[0]\n",
    "    metrics = {\"run_id\": run_id, \"failed\": run[0] == \"failed\", \"quarantine_rate\": run[1]}\n",
    "    if out is not None:\n",
    "        drift = [psi(reference[\"mw\"], out[\"mw\"]), psi(reference[\"logp\"], out[\"logp\"]),\n",
    "                 ks(reference[\"mw\"], out[\"mw\"]), ks(reference[\"logp\"], out[\"logp\"])]\n",
    "        db.execute(\"INSERT INTO drift VALUES (?, ?, ?, ?, ?)\", [run_id, *drift])\n",
    "        metrics.update(psi_mw=drift[0], psi_logp=drift[1])\n",
    "    alerter.update(metrics)\n",
    "    clock.time = FIRST_NIGHT + timedelta(days=night - 1) + MORNING_CHECK  # 09:00: freshness\n",
    "    age = freshness(clock.now())\n",
    "    alerter.update({\"run_id\": run_id, \"hours_since_success\": age.total_seconds() / 3600})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Night 8 paged twice: the run failed, and by the morning check the data was 31 hours old. Both\n",
    "resolved after night 9, and each alert was sent once, not every night. Night 11's batch passed\n",
    "every validation rule and reconciled, and only the drift rules caught it. The run history, from\n",
    "DuckDB. `LEFT JOIN drift d USING (run_id)` is SQL's version of the left join from Section 3: it\n",
    "adds each run's drift scores and keeps the failed run, which has none (pandas shows the missing\n",
    "values as `NaN`, \"not a number\"):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "  run_id    status  rows_in  rows_out  quarantined_pct  duplicates  psi_mw  psi_logp\n",
      "run-0001 succeeded     1510      1449              3.3          11   0.000     0.000\n",
      "run-0002 succeeded     1510      1450              3.3          10   0.008     0.009\n",
      "run-0003 succeeded     1510      1450              3.3          10   0.015     0.010\n",
      "run-0004 succeeded     1510      1450              3.3          10   0.023     0.015\n",
      "run-0005 succeeded     1510      1450              3.3          10   0.011     0.012\n",
      "run-0006 succeeded     1510      1449              3.3          11   0.033     0.006\n",
      "run-0007 succeeded     1510      1449              3.3          11   0.010     0.024\n",
      "run-0008    failed     1510         0              3.3          10     NaN       NaN\n",
      "run-0009 succeeded     1510      1450              3.3          10   0.010     0.006\n",
      "run-0010 succeeded     1510      1450              3.3          10   0.011     0.016\n",
      "run-0011 succeeded     1510      1453              3.1          10   2.574     5.925\n",
      "run-0012 succeeded     1510      1450              3.3          10   0.018     0.009\n",
      "run-0013 succeeded     1510      1449              3.3          11   0.013     0.015\n",
      "run-0014 succeeded     1510      1449              3.3          11   0.009     0.005\n",
      "error rate over the fortnight: 1/14 runs failed\n"
     ]
    }
   ],
   "source": [
    "history = db.sql(\"\"\"\n",
    "    SELECT r.run_id, r.status, r.rows_in, r.rows_out,\n",
    "           round(100 * r.quarantined / r.rows_in, 1) AS quarantined_pct, r.duplicates,\n",
    "           round(d.psi_mw, 3) AS psi_mw, round(d.psi_logp, 3) AS psi_logp\n",
    "    FROM runs r LEFT JOIN drift d USING (run_id)\n",
    "    ORDER BY r.run_id\n",
    "\"\"\").df()\n",
    "print(history.to_string(index=False))\n",
    "failed = (history[\"status\"] == \"failed\").sum()\n",
    "print(f\"error rate over the fortnight: {failed}/{len(history)} runs failed\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Night 1 is the reference itself, so its PSI is 0. The ordinary nights score between 0.005 and\n",
    "0.033, well below 0.1, and night 11 scores 2.6 and 5.9. The quarantine rate stayed at about 3.3%\n",
    "every night, so the 10% rule never fired: a threshold set above the normal level, so that it stays\n",
    "quiet until something changes.\n",
    "\n",
    "A small dashboard drawn from the same tables puts the fortnight on one page: rows in and out, the\n",
    "quarantine rate, and the drift scores against the two PSI thresholds. The code is matplotlib\n",
    "drawing three panels one above the other; you do not need to follow every line of it, only to see\n",
    "that it reads nothing but the `runs` and `drift` tables. The drift panel uses a scale that is\n",
    "ordinary below 0.1 and logarithmic above (`symlog`), so the small and the very large scores both\n",
    "fit. The figure is saved to a file, shown under the code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def dashboard(db, path):\n",
    "    \"\"\"Draw the run history (counts, quarantine rate, drift) as one SVG figure.\n",
    "\n",
    "    Args:\n",
    "        db: The DuckDB connection holding the runs and drift tables.\n",
    "        path: Where to save the figure.\n",
    "    \"\"\"\n",
    "    runs = db.sql(\"SELECT * FROM runs LEFT JOIN drift USING (run_id) ORDER BY run_id\").df()\n",
    "    night = np.arange(1, len(runs) + 1)\n",
    "    fig, (top, middle, bottom) = plt.subplots(3, 1, figsize=(7, 7.5), sharex=True)\n",
    "    top.bar(night - 0.2, runs[\"rows_in\"], 0.4, color=COLOURS[\"muted\"], label=\"rows in\")\n",
    "    top.bar(night + 0.2, runs[\"rows_out\"], 0.4, color=COLOURS[\"violet\"], label=\"rows published\")\n",
    "    for n in night[runs[\"status\"] == \"failed\"]:\n",
    "        top.annotate(\"failed:\\nnothing\\npublished\", (n + 0.2, 60), ha=\"center\", fontsize=8,\n",
    "                     color=COLOURS[\"ink\"])\n",
    "    top.set_ylabel(\"rows\")\n",
    "    top.set_ylim(0, 2000)\n",
    "    top.legend(loc=\"upper center\", ncol=2, fontsize=8, frameon=False)\n",
    "    middle.plot(night, 100 * runs[\"quarantined\"] / runs[\"rows_in\"], \"o-\", color=COLOURS[\"cyan\"])\n",
    "    middle.axhline(100 * QUARANTINE_LIMIT, color=COLOURS[\"muted\"], linestyle=\"--\", linewidth=1)\n",
    "    middle.text(0.6, 100 * QUARANTINE_LIMIT + 0.3, \"alert threshold\", fontsize=8, color=COLOURS[\"muted\"])\n",
    "    middle.set_ylabel(\"quarantined (%)\")\n",
    "    middle.set_ylim(0, 12)\n",
    "    bottom.plot(night, runs[\"psi_mw\"], \"o-\", color=COLOURS[\"violet\"], label=\"molecular weight\")\n",
    "    bottom.plot(night, runs[\"psi_logp\"], \"s-\", color=COLOURS[\"cyan\"], label=\"logP\")\n",
    "    for level, text in [(PSI_LOOK, f\"{PSI_LOOK}: look\"), (PSI_ALERT, f\"{PSI_ALERT}: alert\")]:\n",
    "        bottom.axhline(level, color=COLOURS[\"muted\"], linestyle=\"--\", linewidth=1)\n",
    "        bottom.text(0.6, level * 1.08, text, fontsize=8, va=\"bottom\", color=COLOURS[\"muted\"])\n",
    "    bottom.set_yscale(\"symlog\", linthresh=0.1)\n",
    "    bottom.set_ylim(0, 10)\n",
    "    bottom.set_ylabel(\"PSI against reference\")\n",
    "    bottom.set_xlabel(\"night\")\n",
    "    bottom.set_xticks(night)\n",
    "    bottom.legend(loc=\"upper center\", ncol=2, fontsize=8, frameon=False)\n",
    "    for ax in (top, middle, bottom):\n",
    "        ax.spines[[\"top\", \"right\"]].set_visible(False)\n",
    "    fig.tight_layout()\n",
    "    fig.savefig(path)\n",
    "    plt.close(fig)\n",
    "\n",
    "\n",
    "dashboard(db, DASHBOARD)\n",
    "db.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![A fortnight of runs: rows in and published per night (night 8 failed and published nothing), the quarantine rate (steady, below its 10% threshold), and PSI for molecular weight and logP (night 11 far above 0.25)](figures/run-dashboard.svg)\n",
    "\n",
    "Dashboard programs such as Grafana, Metabase or Superset would draw the same panels live, in a web\n",
    "page, from the same run-history tables; the point is that the tables exist and every run writes to\n",
    "them. The last line, `db.close()`, closes the run history; to use it again in a new cell, reconnect\n",
    "with `db = duckdb.connect(str(HISTORY_DB))`.\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",
    "- Ewaschuk, R. Monitoring distributed systems. In Beyer, B., Jones, C., Petoff, J. & Murphy, N. R.\n",
    "  (eds.) (2016). *Site Reliability Engineering*. O'Reilly; free online edition.\n",
    "  <https://sre.google/sre-book/monitoring-distributed-systems/>\n",
    "- Breck, E., Cai, S., Nielsen, E., Salib, M. & Sculley, D. (2017). The ML test score: a rubric for\n",
    "  ML production readiness and technical debt reduction. *2017 IEEE International Conference on Big\n",
    "  Data (Big Data)*, 1123–1132. <https://doi.org/10.1109/BigData.2017.8258038>\n",
    "- Yurdakul, B. (2018). *Statistical properties of population stability index*. Doctoral\n",
    "  dissertation, Western Michigan University. <https://scholarworks.wmich.edu/dissertations/3208>\n",
    "- The Python documentation. *logging: Logging facility for Python*, and the *Logging Cookbook*.\n",
    "  <https://docs.python.org/3/library/logging.html>,\n",
    "  <https://docs.python.org/3/howto/logging-cookbook.html>\n",
    "- The DuckDB documentation. *JSON overview* (reading JSON lines files such as structured logs).\n",
    "  <https://duckdb.org/docs/stable/data/json/overview>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
