{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Capstone: a resumable, monitored pipeline over a large library\n",
    "\n",
    "Ingest, validate, standardise, deduplicate, filter and fingerprint a compound library end to end, stop it halfway, resume it, and show that the output is versioned and every count reconciles.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-1/15-capstone/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install what this lesson needs (in Colab, or any fresh environment)\n",
    "%pip install -q rdkit numpy pandas pyarrow duckdb joblib pydantic pydantic-settings tenacity\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(\"pipeline.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/15-capstone/pipeline.py\", \"pipeline.py\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every module so far has built one piece of a data pipeline for chemistry. This one puts the pieces\n",
    "together, the way a cheminformatics team would before it trusts a library enough to screen it,\n",
    "model it or buy from it: read a supplier's library in batches, reject what cannot be used and say\n",
    "why, reduce every record to one standard form, keep one record per molecule, remove compounds that\n",
    "cause trouble in assays, calculate fingerprints and descriptors, and store the result where it can\n",
    "be queried. Then the parts that make the result trustworthy: the run can be stopped and resumed\n",
    "without changing the answer, every count adds up, and a manifest records exactly what produced it.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- run one pipeline that takes a library of molecules from the supplier's records all the way to\n",
    "  clean, searchable tables on disk;\n",
    "- say which earlier module each stage comes from, and why the stages run in this order;\n",
    "- stop a run halfway on purpose, start it again, and show that the result is exactly the same as a\n",
    "  run that was never stopped;\n",
    "- check that every record is accounted for at every stage, and that the files on disk agree with\n",
    "  the pipeline's own record;\n",
    "- read the run's manifest (the record of what produced the output) and ask questions of the output\n",
    "  in DuckDB;\n",
    "- plan your own capstone project, which three other learners review against the marking table\n",
    "  (the rubric) at the end of this page.\n",
    "\n",
    "This module uses every module before it. The table in Section 1 shows which stage comes from where;\n",
    "the ones it leans on most are [Module 10](../10-pipelines-that-survive-failure/) (settings, retries,\n",
    "checkpoints, atomic writes), [Module 13](../13-versioning-everything/) (hashes and the manifest)\n",
    "and [Module 14](../14-monitoring-pipelines/) (JSON logs, the run history and reconciliation).\n",
    "\n",
    "The pipeline lives in one file next to this lesson, `pipeline.py`. It is a Python module: a `.py`\n",
    "file of functions that other code loads with `import` (not to be confused with the course's\n",
    "modules). We keep it as a file rather than notebook cells because that is how pipeline code is\n",
    "kept: other code can import it, tests can check it, and it can run on its own from a terminal. The\n",
    "lesson imports it and walks through it stage by stage. In Colab, the notebook's first cell\n",
    "downloads `pipeline.py` for you. If you want to read the code itself, open\n",
    "[`pipeline.py` on GitHub](https://github.com/David-Alobo/monstrous-learn/blob/main/data-engineering/series-1/15-capstone/pipeline.py); every function in it has a short description.\n",
    "\n",
    "The pipeline uses these Python packages, all met in earlier modules:\n",
    "\n",
    "- **RDKit**, for the chemistry;\n",
    "- **NumPy** and **pandas**, for arrays and tables;\n",
    "- **pyarrow**, for writing Parquet files ([Module 8](../08-larger-than-memory/));\n",
    "- **DuckDB**, the one-file database ([Module 8](../08-larger-than-memory/));\n",
    "- **joblib**, for running work on several processor cores at once\n",
    "  ([Module 9](../09-parallel-and-distributed/));\n",
    "- **Pydantic** and **pydantic-settings**, for settings that are checked before the run starts\n",
    "  ([Module 10](../10-pipelines-that-survive-failure/));\n",
    "- **tenacity**, for trying a failed read again ([Module 10](../10-pipelines-that-survive-failure/)).\n",
    "\n",
    "## Setup\n",
    "\n",
    "Everything this lesson needs is imported and set here, so the settings can be changed in one place.\n",
    "The pipeline's own settings live in its settings class (Section 2); these are the lesson's.\n",
    "Pipeline steps report with `log`; `print` is kept for showing you results; Module 1 explains why.\n",
    "`sys.path.insert(0, \".\")` tells Python to look for modules in the current folder too, so that\n",
    "`import pipeline` finds `pipeline.py`; the `# noqa: E402` note tells the course's code checker\n",
    "that this import is meant to come after other code. The block also deletes the output folders of\n",
    "any earlier run (`shutil.rmtree`), so the lesson starts from nothing. `{...:,}` in the last line\n",
    "prints a number with commas between the thousands."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "molecules the library generator can make: 1,733,400\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "import logging\n",
    "import shutil\n",
    "import sys\n",
    "import time\n",
    "from datetime import datetime, timedelta\n",
    "from pathlib import Path\n",
    "\n",
    "import duckdb\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from pydantic import ValidationError\n",
    "\n",
    "sys.path.insert(0, \".\")  # this module's folder, where pipeline.py lives, so Python can find it\n",
    "import pipeline  # noqa: E402  (after the path is set)\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's runs write: data, run record (DuckDB), log and manifest\n",
    "WORK = Path(\"work\")\n",
    "OUT_DIR = WORK / \"capstone\"  # the run that crashes and resumes\n",
    "OUT_DIR_AGAIN = WORK / \"capstone-again\"  # the uninterrupted run of Section 9\n",
    "DATABASE = OUT_DIR / \"pipeline.duckdb\"\n",
    "MANIFEST = OUT_DIR / \"manifest.json\"\n",
    "\n",
    "RETRY_WAIT_S = 0.01  # seconds before the first retry; short, so the lesson runs quickly\n",
    "START = datetime(2027, 1, 18, 2, 0)  # the injected clock starts at 02:00 UTC\n",
    "FLAKY_READS = {3: 2}  # injected fault: batch 3's first two reads fail\n",
    "CRASH_IN_BATCH = 12  # injected fault: the process \"dies\" in batch 12, before its checkpoint\n",
    "MOVED_BATCH = 7  # the batch whose compounds file is moved away in Section 7\n",
    "\n",
    "WORK.mkdir(exist_ok=True)\n",
    "for old in (OUT_DIR, OUT_DIR_AGAIN):  # start the lesson from nothing\n",
    "    shutil.rmtree(old, ignore_errors=True)\n",
    "print(f\"molecules the library generator can make: {pipeline.chemlib.size():,}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. The plan\n",
    "\n",
    "![The capstone pipeline. Batches are read from the library with retries, validated, standardised, described and flagged in parallel worker processes, then deduplicated against every InChIKey already seen, filtered, written as partitioned Parquet and checkpointed in DuckDB, one batch at a time. Quarantined and removed records go to their own tables with a reason. At the end the counts are reconciled, the tables are registered in DuckDB and a manifest records the input, rules, versions and the hash of every output](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/15-capstone/figures/pipeline-overview.svg)\n",
    "\n",
    "| Stage | What it does | Module |\n",
    "|---|---|---|\n",
    "| Settings | Every setting typed, limited and checked before any work starts | 10, 12 |\n",
    "| Ingest | Read one batch at a time, never the whole library; retry a flaky source | 8, 10 |\n",
    "| Validate | Reject records that cannot be read or sanitised, with a reason code | 6 |\n",
    "| Standardise | Parent fragment, neutralised; rules versioned and hashed | 7, 13 |\n",
    "| Deduplicate | One record per InChIKey, across all batches | 3, 7 |\n",
    "| Filter | Remove PAINS and molecules outside property limits, with a reason | 2 |\n",
    "| Describe | Morgan fingerprint and descriptors | 2 |\n",
    "| Store | Partitioned Parquet, registered in DuckDB | 4, 8 |\n",
    "| Checkpoint | A batch is done only when its checkpoint is committed | 10 |\n",
    "| Reconcile, record, manifest | Counts add up; the run record and the manifest say what happened | 13, 14 |\n",
    "\n",
    "Some of the words in the table, in short. To **ingest** is to read data into the pipeline. A\n",
    "**batch** is a slice of the input, here 500 records, handled as one piece. **Partitioned Parquet**\n",
    "means one Parquet file per batch, each in its own folder (`compounds/batch=00007/part-0.parquet`),\n",
    "which DuckDB reads as one table. A **checkpoint** is a row in the database saying \"this batch is\n",
    "finished\", so a stopped run knows where to start again. The **run record** is the run history of\n",
    "Module 14, and the **manifest** is a file that lists what went into the run and what came out\n",
    "([Module 13](../13-versioning-everything/)).\n",
    "\n",
    "Two design choices shape the code. First, the per-molecule work of a batch (validate,\n",
    "standardise, describe, flag) is a **pure function** of the batch: its result depends only on the\n",
    "batch it is given, and it changes nothing else (no files, no shared tables). That means several\n",
    "batches can be processed at once in **worker processes**, separate copies of Python running on\n",
    "different processor cores ([Module 9](../09-parallel-and-distributed/)). Second, everything that\n",
    "depends on earlier batches (deduplication against molecules already seen, and the checkpoint)\n",
    "runs in the main process, one batch at a time, in order. That split is what makes the output the\n",
    "same however many workers run and however often the run is stopped.\n",
    "\n",
    "## 2. Settings\n",
    "\n",
    "The settings class is the pipeline's only way in for configuration. Each setting has a type and\n",
    "limits, and each can be overridden by an environment variable (a named setting kept by the\n",
    "operating system outside the code: `CAPSTONE_N_MOLECULES`, `CAPSTONE_WORKERS` and so on), so the\n",
    "same code runs a 10,000-molecule lesson and the full library. It is a Pydantic settings class, as\n",
    "in [Module 10](../10-pipelines-that-survive-failure/); `model_dump` returns the settings as a\n",
    "dictionary of names and values, which we print one per line:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "n_molecules    10000\n",
      "seed           15\n",
      "defect_rate    0.02\n",
      "batch_size     500\n",
      "workers        4\n",
      "max_mw         500.0\n",
      "max_logp       5.0\n",
      "max_attempts   4\n",
      "retry_wait_s   0.01\n"
     ]
    }
   ],
   "source": [
    "settings = pipeline.Settings(out_dir=OUT_DIR, retry_wait_s=RETRY_WAIT_S)\n",
    "for name, value in settings.model_dump(exclude={\"out_dir\"}).items():\n",
    "    print(f\"{name:14} {value}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The lesson shortens the wait between retries so it runs quickly. A mistake in the settings stops\n",
    "the run in its first second, with every problem listed, rather than three hours in. Pydantic\n",
    "reports the problems as a `ValidationError`, and `err.errors()` lists them, one for each setting:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "n_molecules: Input should be less than or equal to 1733400\n",
      "defect_rate: Input should be less than or equal to 0.5\n",
      "batch_size: Input should be greater than 0\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    pipeline.Settings(batch_size=0, defect_rate=2, n_molecules=5_000_000)\n",
    "except ValidationError as err:\n",
    "    for problem in err.errors():\n",
    "        print(f\"{problem['loc'][0]}: {problem['msg']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Ingest, with retries\n",
    "\n",
    "`read_batch` returns batch number *k* of the input, and nothing else: no state, no files. Asked for\n",
    "the same batch twice, it returns the same rows, which is what lets a resumed run redo a batch and\n",
    "get the same answer. For a sample (this lesson) it slices a seeded sample of the library; for the\n",
    "whole library it streams the batch straight from the generator, so 1.7 million molecules are never\n",
    "in memory at once (Module 8). Each batch carries faults added at 2%, with chemlib's `defect` column\n",
    "recording the truth, so we can check the pipeline against it later. In the code below,\n",
    "`.replace(\"\", \"(clean)\")` gives the records with no fault a readable label, and `value_counts()`\n",
    "counts each label."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "501 records in batch 0\n",
      "defect\n",
      "(clean)      491\n",
      "solvent        2\n",
      "invalid        2\n",
      "valence        2\n",
      "salt           2\n",
      "element        1\n",
      "duplicate      1\n",
      "the same rows when read again: True\n"
     ]
    }
   ],
   "source": [
    "batch = pipeline.read_batch(settings, 0)\n",
    "print(len(batch), \"records in batch 0\")\n",
    "print(batch[\"defect\"].replace(\"\", \"(clean)\").value_counts().to_string())\n",
    "print(\"the same rows when read again:\", batch.equals(pipeline.read_batch(settings, 0)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are 501 records because a duplicate is an extra record, not a damaged one. One detail\n",
    "was needed to make that last line True: chemlib writes each duplicate as a random SMILES from\n",
    "RDKit's random generator, whose state depends on whatever the process did before, so `read_batch`\n",
    "rewrites those few SMILES with a seeded random generator. Hidden randomness of this kind is a\n",
    "common reason for a \"resumable\" pipeline to give a different answer after a resume.\n",
    "\n",
    "Reading from a real supplier or database fails now and then: a connection is reset, a server is\n",
    "busy. `read_with_retries` wraps the read in tenacity (Module 10): connection errors are retried\n",
    "with exponential back-off (each wait twice as long as the one before, so a busy server gets time\n",
    "to recover), up to `max_attempts`, and every retry is logged as a JSON line (Module 14). Here the\n",
    "source fails twice on purpose before it answers. The faults are switched on with\n",
    "`pipeline.Faults`, a named tuple that says which faults to inject: `flaky_reads={3: 2}` means \"the\n",
    "first two reads of batch 3 fail\".\n",
    "\n",
    "The pipeline logs with `logging.getLogger(__name__)`, kept in the module as `log` (so here it is\n",
    "`pipeline.log`: the variable, not the file of that name). During a run it writes to the run's log\n",
    "file only. For this demonstration we add a screen handler to it, a plain `StreamHandler` with the\n",
    "pipeline's JSON formatter, and stop it passing its lines on to the Setup block's plain handler,\n",
    "which would show each one a second time. The clock is injected (as in Module 14), so the times in\n",
    "the log are the same on every run. Here the clock, `Tick`, is a class with a `__call__` method,\n",
    "which lets an object be called like a function: `clock()` returns the next time, one second after\n",
    "the last:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Tick:\n",
    "    \"\"\"A clock for repeatable run records: each reading is one second after the last.\"\"\"\n",
    "\n",
    "    def __init__(self, start):\n",
    "        self.time = start\n",
    "\n",
    "    def __call__(self):\n",
    "        \"\"\"The next time.\"\"\"\n",
    "        self.time += timedelta(seconds=1)\n",
    "        return self.time\n",
    "\n",
    "\n",
    "screen = logging.StreamHandler()\n",
    "screen.setFormatter(pipeline.JsonFormatter(Tick(START)))\n",
    "pipeline.log.addHandler(screen)  # run() replaces it with the run's log file\n",
    "pipeline.log.propagate = False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{\"time\": \"2027-01-18T02:00:01\", \"level\": \"WARNING\", \"event\": \"read failed; retrying\", \"batch\": 3, \"attempt\": 1, \"error\": \"supplier connection reset reading batch 3\"}\n",
      "{\"time\": \"2027-01-18T02:00:02\", \"level\": \"WARNING\", \"event\": \"read failed; retrying\", \"batch\": 3, \"attempt\": 2, \"error\": \"supplier connection reset reading batch 3\"}\n",
      "batch 3 read after 3 attempts: 501 records\n"
     ]
    }
   ],
   "source": [
    "flaky = pipeline.Faults(flaky_reads=FLAKY_READS)\n",
    "batch, attempts = pipeline.read_with_retries(settings, 3, flaky)\n",
    "print(\"batch 3 read after\", attempts, \"attempts:\", len(batch), \"records\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Validate and standardise\n",
    "\n",
    "`process_batch` is the pure part. For each record it runs `validate` (can the SMILES be read and\n",
    "sanitised? as in [Module 6](../06-validating-molecules/)), then `standardise` (keep the parent\n",
    "fragment, the largest organic piece, which drops counter-ions and solvents, and neutralise it, as\n",
    "in [Module 7](../07-standardisation/); then check the elements), then calculates the InChIKey,\n",
    "descriptors, a packed Morgan fingerprint and the first PAINS match. PAINS are substructures known\n",
    "to give false hits in many assays; Section 5 says more. It returns two tables: the rows that passed\n",
    "and the rows it quarantined. Eight hand-made records show every outcome:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "  id       stage  reason\n",
      "EX-3    validate   PARSE\n",
      "EX-4    validate VALENCE\n",
      "EX-5 standardise ELEMENT\n",
      "\n",
      "  id                             smiles      mw  logp           pains\n",
      "EX-1              CC(=O)Oc1ccccc1C(=O)O 180.159 1.310                \n",
      "EX-2              CC(=O)Oc1ccccc1C(=O)O 180.159 1.310                \n",
      "EX-6            O=C1NC(=S)SC1=Cc1ccccc1 221.306 2.175 ene_rhod_A(235)\n",
      "EX-7 CCCCCCCCCCCCCCCCCCCC(=O)NCc1ccccc1 401.679 8.345                \n",
      "EX-8         O=C(NCc1ccccc1)c1ccc(F)cc1 229.254 2.756                \n"
     ]
    }
   ],
   "source": [
    "examples = pd.DataFrame(\n",
    "    {\n",
    "        \"id\": [f\"EX-{k}\" for k in range(1, 9)],\n",
    "        \"smiles\": [\n",
    "            \"CC(=O)Oc1ccccc1C(=O)[O-].[Na+]\",  # aspirin, as its sodium salt\n",
    "            \"CC(=O)Oc1ccccc1C(=O)O\",  # aspirin\n",
    "            \"c1ccccc1C(=O)NCc1ccc(cc1\",  # a ring that never closes\n",
    "            \"C(C)(C)(C)(C)c1ccccc1\",  # a carbon with five bonds\n",
    "            \"C[Se]c1ccc(cc1)C(=O)N\",  # selenium\n",
    "            \"S=C1SC(=Cc2ccccc2)C(=O)N1\",  # a benzylidene rhodanine\n",
    "            \"CCCCCCCCCCCCCCCCCCCC(=O)NCc1ccccc1\",  # a long fatty amide\n",
    "            \"O=C(NCc1ccccc1)c1ccc(F)cc1\",  # an ordinary benzamide\n",
    "        ],\n",
    "        \"defect\": \"\",\n",
    "    }\n",
    ")\n",
    "rows, quarantined = pipeline.process_batch(examples)\n",
    "print(quarantined[[\"id\", \"stage\", \"reason\"]].to_string(index=False))\n",
    "print()\n",
    "print(rows[[\"id\", \"smiles\", \"mw\", \"logp\", \"pains\"]].to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The three records that cannot be used are quarantined with a stage and a reason code, never\n",
    "dropped. The sodium salt was not rejected: a counter-ion is a \"fix\" in Module 6's terms, and the\n",
    "parent step removed it, so EX-1 and EX-2 are now the same molecule. The element check runs after\n",
    "the parent step for the same reason: sodium in a counter-ion is fine, selenium in the molecule is\n",
    "not.\n",
    "\n",
    "The rules that decide all of this are written down in one place, with a version and a hash that is\n",
    "stored in every output row (Modules 7 and 13). A hash is a short code calculated from the text of\n",
    "the rules: the same rules always give the same code, and any change gives a different one. Change a\n",
    "rule, or the RDKit version, and the hash\n",
    "changes, so outputs made under different rules can never be mixed up silently:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "version           1.0.0\n",
      "standardise       ['FragmentParent (largest organic fragment)', 'Uncharger']\n",
      "allowed_elements  ['Br', 'C', 'Cl', 'F', 'H', 'N', 'O', 'S']\n",
      "filters           ['RDKit FilterCatalog PAINS (A, B, C)', 'max_mw', 'max_logp']\n",
      "fingerprint       Morgan radius 2, 2048 bits\n",
      "rdkit             2026.09.2\n",
      "rules hash: 893ff7c1bbf5\n"
     ]
    }
   ],
   "source": [
    "for key, value in pipeline.RULES.items():\n",
    "    print(f\"{key:17} {value}\")\n",
    "print(\"rules hash:\", pipeline.rules_hash())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Deduplicate, filter, describe\n",
    "\n",
    "Deduplication cannot be done inside a batch alone: the same molecule can arrive in batch 2 and\n",
    "batch 17. The pipeline keeps a table of every InChIKey it has kept (`seen`, in DuckDB), and the\n",
    "first record of each molecule wins. Then the filters: RDKit's `FilterCatalog` with the **PAINS**\n",
    "substructure filters of Baell and Holloway (pan-assay interference compounds, which give false\n",
    "hits in many assays), and two property limits from the settings. Both functions return what they\n",
    "removed, with a reason, so nothing leaves without a record. Here `seen={}` starts from an empty\n",
    "table of InChIKeys, as if this were the first batch:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "  id    reason detail\n",
      "EX-2 DUPLICATE   EX-1\n",
      "  id reason          detail\n",
      "EX-6  PAINS ene_rhod_A(235)\n",
      "EX-7   LOGP           8.345\n",
      "kept: ['EX-1', 'EX-8']\n"
     ]
    }
   ],
   "source": [
    "unique, duplicates = pipeline.deduplicate(rows, seen={})\n",
    "print(duplicates[[\"id\", \"reason\", \"detail\"]].to_string(index=False))\n",
    "kept, filtered = pipeline.apply_filters(unique, settings)\n",
    "print(filtered[[\"id\", \"reason\", \"detail\"]].to_string(index=False))\n",
    "print(\"kept:\", kept[\"id\"].tolist())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The order matters for the counts, not for the result: a molecule is counted once, as a duplicate,\n",
    "however many filters it would also fail. In the code, the features are calculated in the parallel\n",
    "step for every valid record, before deduplication, because deduplication has to wait for the\n",
    "batches before it; that costs a little extra work on the few duplicates and saves a second pass.\n",
    "\n",
    "Each kept molecule carries its descriptors and a 2048-bit Morgan fingerprint packed into 256 bytes\n",
    "(a byte holds 8 bits), eight times smaller than one byte per bit and easy to unpack with NumPy:\n",
    "`np.unpackbits` turns the bytes back into 2048 zeros and ones. The descriptors are molecular\n",
    "weight (`mw`), logP, polar surface area (`tpsa`), hydrogen-bond donors (`hbd`) and acceptors\n",
    "(`hba`), and the number of heavy atoms:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "256 bytes, 2048 bits, 24 set\n",
      "  id      mw  logp  tpsa  hbd  hba  heavy_atoms\n",
      "EX-1 180.159 1.310  63.6    1    3           13\n",
      "EX-8 229.254 2.756  29.1    1    1           17\n"
     ]
    }
   ],
   "source": [
    "fingerprint = kept[\"morgan2\"].iloc[0]\n",
    "bits = np.unpackbits(np.frombuffer(fingerprint, dtype=np.uint8))\n",
    "print(f\"{len(fingerprint)} bytes, {len(bits)} bits, {bits.sum()} set\")\n",
    "print(kept[[\"id\", \"mw\", \"logp\", \"tpsa\", \"hbd\", \"hba\", \"heavy_atoms\"]].to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. A crash halfway, and a resume\n",
    "\n",
    "`run` processes the batches in waves of `workers` batches: with 4 workers, batches 0 to 3 are\n",
    "worked on at the same time, then 4 to 7, and so on. Each batch is then committed (saved for good)\n",
    "in order: its three Parquet files (compounds, quarantine, removed) are written atomically (written\n",
    "to a temporary file, then renamed into place, so a file is either complete or not there at all,\n",
    "[Module 10](../10-pipelines-that-survive-failure/)), and only after that is its **checkpoint**\n",
    "committed, in one transaction with its InChIKeys. A transaction is a group of database changes that\n",
    "are saved all together or not at all. A crash between the files and the checkpoint leaves files but\n",
    "no checkpoint, so the batch is simply done again on resume.\n",
    "\n",
    "Now the run, with two injected faults: batch 3's first two reads fail, and the process \"dies\" in\n",
    "batch 12, after writing its files and before its checkpoint (the pipeline raises a\n",
    "`SimulatedCrash` error there, which stands in for the power going off). The clock is injected, so\n",
    "the run record is the same on every computer; the timer, `time.perf_counter()`, measures the real\n",
    "time. Afterwards we look in the database. `with duckdb.connect(...) as db:` opens it for the\n",
    "indented lines only and closes it after them, even if one of them fails; `read_only=True` means we\n",
    "only look:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "ERROR crashed: killed after writing batch 12, before its checkpoint\n",
      " run_id  status\n",
      "run-001 running\n",
      "checkpointed: 12 batches (0 to 11) of 20\n",
      "batch 12's files are on disk: True\n"
     ]
    }
   ],
   "source": [
    "clock = Tick(START)\n",
    "faults = pipeline.Faults(flaky_reads=FLAKY_READS, crash_in_batch=CRASH_IN_BATCH)\n",
    "started = time.perf_counter()\n",
    "try:\n",
    "    pipeline.run(settings, clock, faults)\n",
    "except pipeline.SimulatedCrash as crash:\n",
    "    log.error(\"crashed: %s\", crash)\n",
    "seconds = {\"crashed run\": time.perf_counter() - started}\n",
    "\n",
    "with duckdb.connect(str(DATABASE), read_only=True) as db:\n",
    "    print(db.sql(\"SELECT run_id, status FROM runs\").df().to_string(index=False))\n",
    "    done = db.sql(\"SELECT count(*), max(batch) FROM batches\").fetchall()[0]\n",
    "print(f\"checkpointed: {done[0]} batches (0 to {done[1]}) of {pipeline.n_batches(settings)}\")\n",
    "print(f\"batch {CRASH_IN_BATCH}'s files are on disk:\",\n",
    "      pipeline.partition(settings, \"compounds\", CRASH_IN_BATCH).exists())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The run record still says `running`: a killed process cannot write anything, which is exactly why\n",
    "a stuck `running` row is worth an alert (Module 14). Batch 12's files exist but it has no\n",
    "checkpoint, so it does not count. To resume, run the same command again:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " run_id    status  batches\n",
      "run-001 abandoned        0\n",
      "run-002 succeeded        8\n",
      " run_id  batches  first  last  reads\n",
      "run-001       12      0    11     14\n",
      "run-002        8     12    19      8\n"
     ]
    }
   ],
   "source": [
    "started = time.perf_counter()\n",
    "manifest = pipeline.run(settings, clock)\n",
    "seconds[\"resumed run\"] = time.perf_counter() - started\n",
    "\n",
    "with duckdb.connect(str(DATABASE), read_only=True) as db:\n",
    "    print(db.sql(\"SELECT run_id, status, batches FROM runs ORDER BY run_id\").df()\n",
    "          .to_string(index=False))\n",
    "    print(db.sql(\"SELECT run_id, count(*) AS batches, min(batch) AS first, max(batch) AS last, \"\n",
    "                 \"sum(attempts)::INTEGER AS reads FROM batches GROUP BY run_id ORDER BY run_id\").df()\n",
    "          .to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The second run marked the first as `abandoned`, skipped the twelve checkpointed batches, redid\n",
    "batch 12 (overwriting its files with the same content) and finished it and the seven after it. The\n",
    "`reads` column shows batch 3's two failed attempts: 12 batches took 14 reads.\n",
    "\n",
    "## 7. Counts that reconcile\n",
    "\n",
    "The last steps of `run` are the checks of Module 14, applied to the whole library. `reconcile`\n",
    "confirms that every batch is done, that each batch's records add up (in = quarantined + duplicates\n",
    "+ filtered + out), and that the Parquet files hold exactly the number of rows the checkpoints say.\n",
    "`run` returned the manifest (Section 8), and its `counts` hold the totals, which we add up here:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "batches                       20\n",
      "rows_in                   10,020\n",
      "quarantined_validate          80\n",
      "quarantined_standardise       20\n",
      "duplicates                    48\n",
      "filtered                     699\n",
      "rows_out                   9,173\n",
      "in = quarantined + duplicates + filtered + out: True\n"
     ]
    }
   ],
   "source": [
    "counts = manifest[\"counts\"]\n",
    "for stage, count in counts.items():\n",
    "    print(f\"{stage:24} {count:>7,}\")\n",
    "accounted = sum(count for stage, count in counts.items() if stage not in (\"batches\", \"rows_in\"))\n",
    "print(\"in = quarantined + duplicates + filtered + out:\", counts[\"rows_in\"] == accounted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Checking the files against the record catches what counting inside the code cannot: a file lost or\n",
    "overwritten after the run. Move one partition (one batch's file) away by renaming it, reconcile\n",
    "again, and put it back:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "ReconciliationError: compounds files hold 8702 rows, record says 9173\n"
     ]
    }
   ],
   "source": [
    "moved = pipeline.partition(settings, \"compounds\", MOVED_BATCH)\n",
    "moved.rename(moved.with_suffix(\".bak\"))\n",
    "with duckdb.connect(str(DATABASE)) as db:\n",
    "    try:\n",
    "        pipeline.reconcile(db, settings)\n",
    "    except pipeline.ReconciliationError as err:\n",
    "        print(\"ReconciliationError:\", err)\n",
    "moved.with_suffix(\".bak\").rename(moved)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Because chemlib recorded which faults it added, the pipeline can also be checked against the truth,\n",
    "as in Module 6: every unreadable, impossible or selenium record should be in quarantine with the\n",
    "matching reason, every salt and solvent should have been fixed, and one record of every duplicated\n",
    "pair removed. The query stacks three small tallies into one table with `UNION ALL`: what is in\n",
    "quarantine, what was removed, and what was kept, each counted by fault. `GROUP BY ALL` groups by\n",
    "every column that is not a count, and `||` joins two pieces of text:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "   defect             outcome  records\n",
      "duplicate                kept       10\n",
      "duplicate  removed: DUPLICATE        9\n",
      "duplicate       removed: LOGP        1\n",
      "  element quarantine: ELEMENT       20\n",
      "  invalid   quarantine: PARSE       40\n",
      "     salt                kept       38\n",
      "     salt       removed: LOGP        1\n",
      "     salt         removed: MW        1\n",
      "  solvent                kept       39\n",
      "  solvent       removed: LOGP        1\n",
      "  valence quarantine: VALENCE       40\n"
     ]
    }
   ],
   "source": [
    "with duckdb.connect(str(DATABASE), read_only=True) as db:\n",
    "    truth = db.sql(\"\"\"\n",
    "        SELECT defect, 'quarantine: ' || reason AS outcome, count(*) AS records\n",
    "        FROM quarantine GROUP BY ALL\n",
    "        UNION ALL\n",
    "        SELECT defect, 'removed: ' || reason, count(*) FROM removed\n",
    "        WHERE defect <> '' GROUP BY ALL\n",
    "        UNION ALL\n",
    "        SELECT defect, 'kept', count(*) FROM compounds WHERE defect <> '' GROUP BY ALL\n",
    "        ORDER BY defect, outcome\n",
    "    \"\"\").df()\n",
    "print(truth.to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each fault went where it should. The 40 unreadable and 40 impossible records, and the 20 with\n",
    "selenium, are all in quarantine with the matching reason. The salts and solvents were standardised\n",
    "and kept, except three whose parent fails a property limit. The duplicates need a second look: 10 of\n",
    "the 20 added duplicates were *kept*. Those arrived in the file before their original, so the\n",
    "duplicate was the first record of the molecule and the original was removed instead; the pair is\n",
    "still reduced to one. That is why the table counts 48 duplicates removed while only 9 of them carry\n",
    "chemlib's `duplicate` label: the rest are originals that came second, and molecules that two\n",
    "different substituent combinations make by symmetry.\n",
    "\n",
    "## 8. The provenance manifest\n",
    "\n",
    "Provenance means where something came from. The run ends by writing `manifest.json` beside the\n",
    "data ([Module 13](../13-versioning-everything/)): the input and its settings, the rules and their\n",
    "hash, the package versions, the reconciled counts, and the SHA-256 of every output file (a hash\n",
    "of the file's contents: change one byte and it changes), with one hash over all of them for the\n",
    "whole dataset. `json.loads` reads the file back into a Python dictionary:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "runs: ['run-001', 'run-002']\n",
      "input: chemlib 10000 molecules, seed 15 defect rate 0.02\n",
      "rules hash: 893ff7c1bbf5\n",
      "versions recorded: python, rdkit, numpy, pandas, pyarrow, duckdb\n",
      "output files: 60\n",
      "data sha256: 04bdecb569e122a2 ...\n"
     ]
    }
   ],
   "source": [
    "manifest = json.loads(MANIFEST.read_text(encoding=\"utf-8\"))\n",
    "print(\"runs:\", manifest[\"runs\"])\n",
    "print(\"input:\", manifest[\"input\"][\"source\"], manifest[\"input\"][\"n_molecules\"], \"molecules, seed\",\n",
    "      manifest[\"input\"][\"seed\"], \"defect rate\", manifest[\"input\"][\"defect_rate\"])\n",
    "print(\"rules hash:\", manifest[\"rules_hash\"])\n",
    "print(\"versions recorded:\", \", \".join(manifest[\"versions\"]))\n",
    "print(\"output files:\", len(manifest[\"outputs\"]))\n",
    "print(\"data sha256:\", manifest[\"data_sha256\"][:16], \"...\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 9. The same answer without the crash\n",
    "\n",
    "The test of resumability is simple to state: a run that crashed and resumed must produce exactly\n",
    "what a run that never crashed produces. Run the pipeline again, uninterrupted, into another folder,\n",
    "and compare the hash of every output file. `model_copy(update=...)` makes a copy of the settings\n",
    "with only the output folder changed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "same counts: True\n",
      "same files, byte for byte: True\n",
      "same data hash: True\n"
     ]
    }
   ],
   "source": [
    "again_settings = settings.model_copy(update={\"out_dir\": OUT_DIR_AGAIN})\n",
    "started = time.perf_counter()\n",
    "again = pipeline.run(again_settings, Tick(START))\n",
    "seconds[\"uninterrupted run\"] = time.perf_counter() - started\n",
    "print(\"same counts:\", again[\"counts\"] == manifest[\"counts\"])\n",
    "print(\"same files, byte for byte:\", again[\"outputs\"] == manifest[\"outputs\"])\n",
    "print(\"same data hash:\", again[\"data_sha256\"] == manifest[\"data_sha256\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "They are identical, byte for byte. Three things made that possible, and each is worth checking in\n",
    "your own capstone: every batch is read the same way every time; the work on a batch depends only on\n",
    "the batch; and everything that depends on order (deduplication, checkpoints) happens in batch\n",
    "order, in one place.\n",
    "\n",
    "How long it took on this computer (yours will differ):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "crashed run         27.6 s\n",
      "resumed run         10.8 s\n",
      "uninterrupted run   24.5 s\n",
      "about 409 records per second with 4 workers\n",
      "the whole library at that rate: about 1.2 hours\n"
     ]
    }
   ],
   "source": [
    "for name, value in seconds.items():\n",
    "    print(f\"{name:18} {value:5.1f} s\")\n",
    "rate = counts[\"rows_in\"] / seconds[\"uninterrupted run\"]\n",
    "print(f\"about {rate:,.0f} records per second with {settings.workers} workers\")\n",
    "print(f\"the whole library at that rate: about {pipeline.chemlib.size() / rate / 3600:.1f} hours\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 10. Querying the result\n",
    "\n",
    "The run registered its three tables as DuckDB views over the Parquet files. A view is a saved query\n",
    "that looks like a table: the data stays in the Parquet files, and DuckDB reads them each time the\n",
    "view is used. So the database file is the way in: anyone with DuckDB can open `pipeline.duckdb` and\n",
    "query the library without loading it. The funnel, from records in to compounds out:\n",
    "\n",
    "![The run's records at each stage: records read, readable, standardised, unique and passing the filters, with the number leaving at each step](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/15-capstone/figures/funnel.svg)\n",
    "\n",
    "Two queries follow. The first counts the removed records by reason, and splits PAINS by family:\n",
    "`regexp_replace(detail, '\\\\(\\\\d+\\\\)$', '')` is a regular expression that cuts the number in\n",
    "brackets off the end of a PAINS name, so `anil_di_alk_G(...)` becomes `anil_di_alk_G`. The second\n",
    "summarises the compounds kept: how many, their median weight, logP and polar surface area, and\n",
    "how many different rule sets made them:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "              reason  records\n",
      "                LOGP      552\n",
      "                  MW      120\n",
      "           DUPLICATE       48\n",
      "PAINS: anil_di_alk_G       19\n",
      "PAINS: anil_di_alk_E        5\n",
      "PAINS: anil_di_alk_A        2\n",
      "PAINS: anil_di_alk_D        1\n",
      "\n",
      " compounds  median_mw  median_logp  median_tpsa  rule_sets\n",
      "      9173      383.5         2.48         97.0          1\n"
     ]
    }
   ],
   "source": [
    "with duckdb.connect(str(DATABASE), read_only=True) as db:\n",
    "    print(db.sql(\"\"\"\n",
    "        SELECT reason, count(*) AS records FROM removed\n",
    "        WHERE reason <> 'PAINS' GROUP BY reason\n",
    "        UNION ALL\n",
    "        SELECT 'PAINS: ' || regexp_replace(detail, '\\\\(\\\\d+\\\\)$', ''), count(*) FROM removed\n",
    "        WHERE reason = 'PAINS' GROUP BY ALL\n",
    "        ORDER BY records DESC\n",
    "    \"\"\").df().to_string(index=False))\n",
    "    print()\n",
    "    print(db.sql(\"\"\"\n",
    "        SELECT count(*) AS compounds, round(median(mw), 1) AS median_mw,\n",
    "               round(median(logp), 2) AS median_logp, round(median(tpsa), 1) AS median_tpsa,\n",
    "               count(DISTINCT rules_hash) AS rule_sets\n",
    "        FROM compounds\n",
    "    \"\"\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "PAINS removed 27 compounds, all from one family of PAINS patterns (dialkylanilines); the property\n",
    "limits removed 672, most of them for a logP above 5. That is a fact about this library (the scaffolds carry lipophilic substituents), and the kind\n",
    "of thing a summary query should make obvious before anyone screens the output. `rule_sets` is 1:\n",
    "every compound was made under the same rules, which the hash lets us prove.\n",
    "\n",
    "## 11. Running the whole library\n",
    "\n",
    "*This section is optional: it runs the whole library, which takes an hour or more, and nothing\n",
    "later in the lesson needs it.*\n",
    "\n",
    "The same code runs the full 1,733,400 molecules; only the settings change. This is a run for your\n",
    "own computer, not for Colab: Colab's free machines have only two processor cores, and Colab ends a\n",
    "session that runs for many hours or sits idle, so a long run may not finish there. You need the\n",
    "course set up on your computer with a terminal, Git and uv, as in\n",
    "[Start here](https://monstrous.com.ng/learn/start/) (\"With a terminal, Git and uv\").\n",
    "\n",
    "Open a terminal and move into this module's folder: from the `series-1` folder, type\n",
    "`cd 15-capstone` and press Enter. Then set the settings as environment variables and start the\n",
    "pipeline. On macOS and Linux it is one line:\n",
    "\n",
    "```text\n",
    "CAPSTONE_N_MOLECULES=1733400 CAPSTONE_BATCH_SIZE=20000 CAPSTONE_WORKERS=8 python pipeline.py\n",
    "```\n",
    "\n",
    "In Windows PowerShell, set each variable on its own line, then run the pipeline:\n",
    "\n",
    "```text\n",
    "$env:CAPSTONE_N_MOLECULES = \"1733400\"\n",
    "$env:CAPSTONE_BATCH_SIZE = \"20000\"\n",
    "$env:CAPSTONE_WORKERS = \"8\"\n",
    "python pipeline.py\n",
    "```\n",
    "\n",
    "If you installed the course with uv, write `uv run python pipeline.py` instead of\n",
    "`python pipeline.py`, so it uses the course's packages. Set `CAPSTONE_WORKERS` to at most the\n",
    "number of processor cores your computer has. The terminal shows nothing while the run works; the\n",
    "run writes its JSON log to `work/capstone/pipeline.log` (inside the `15-capstone` folder), and you\n",
    "can open that file to follow it. When it finishes it prints the count at every stage, as in\n",
    "Section 7, and the dataset's SHA-256.\n",
    "\n",
    "If the run fails, it says so in two places, as [Module 10](../10-pipelines-that-survive-failure/)\n",
    "taught: the terminal shows a short message (\"The run failed:\" and the error), and the last line of\n",
    "`pipeline.log` is a `run failed` event with the error and its full traceback. The program then ends\n",
    "with exit code 1 instead of 0, so a scheduler or a script that runs it knows it failed. In\n",
    "PowerShell, `$LASTEXITCODE` shows the last program's exit code; in bash, `echo $?`.\n",
    "\n",
    "Bigger batches mean fewer files and checkpoints; more workers use more cores. The rate measured in\n",
    "Section 9 gives the time to expect. If the run is interrupted (a laptop closed, a power cut), run\n",
    "the same command again and it resumes. Nothing in the main process grows with the library except\n",
    "the `seen` table, which DuckDB keeps on disk. At larger scale, the same design is what Spark, Dask\n",
    "(Module 9) or a workflow tool such as Prefect or Dagster (Series 2) would run: pure per-batch\n",
    "work, ordered commits, checkpoints and a manifest.\n",
    "\n",
    "## The capstone brief\n",
    "\n",
    "The capstone is your own project, and the end of the course. You build a pipeline like this\n",
    "lesson's, run it on data of your choice, and hand in the code and the record of its final run. If\n",
    "you are in a cohort, three other learners from the cohort (your **peers**) review it against the\n",
    "marking table at the end of this section (the **rubric**), and you review three other learners'\n",
    "projects in the same way; a project that passes earns the course certificate. If you are following\n",
    "on your own, you can build the same project and use the rubric to check it yourself.\n",
    "\n",
    "### What to build\n",
    "\n",
    "Build your own resumable, monitored pipeline over a library that is not the lesson's, and show that\n",
    "it can be trusted. Choose one input:\n",
    "\n",
    "- a chemlib library with your own seed, size (at least 100,000 molecules) and defect rate; or\n",
    "- the compounds tested against one ChEMBL target (one protein, such as a kinase), downloaded\n",
    "  incrementally as in [Module 11](../11-incremental-ingestion/), with your own validation rules for\n",
    "  the activity values ([Module 12](../12-validating-data/)).\n",
    "\n",
    "You may start from the lesson's `pipeline.py` and change it. Say in your README what you kept, what\n",
    "you changed and what you added: the lesson's pipeline has no alert rules, drift check or tests, so\n",
    "those at least are yours to write.\n",
    "\n",
    "### Requirements\n",
    "\n",
    "Each requirement names the part of the course it comes from.\n",
    "\n",
    "1. **Stages.** Ingest in batches, validate with reason codes, standardise with versioned and hashed\n",
    "   rules, deduplicate by InChIKey across batches, filter (PAINS and at least one rule of your own,\n",
    "   explained), calculate fingerprints and descriptors, and write partitioned Parquet registered in\n",
    "   DuckDB (or PostgreSQL). Sections 3 to 6 and 10 of this lesson show each stage. A rule of your\n",
    "   own could be a limit on another property, such as rotatable bonds or polar surface area;\n",
    "   \"explained\" means one or two sentences in your README on why the rule suits your data.\n",
    "2. **Settings** in one typed settings class, overridable from the environment, checked before the\n",
    "   run starts (Section 2, and [Module 10](../10-pipelines-that-survive-failure/)).\n",
    "3. **Resumability.** Demonstrate a crash and a resume, and show with file hashes that the output\n",
    "   equals an uninterrupted run. Inject the crash as Section 6 does, and compare the manifests'\n",
    "   hashes as Section 9 does.\n",
    "4. **Reconciliation.** Counts at every stage that add up, checked by code that fails loudly (raises\n",
    "   an error), and the files checked against the run record (Section 7).\n",
    "5. **Monitoring.** Structured logs, a run history, and at least two alert rules (for example a\n",
    "   quarantine rate and a drift check on one descriptor, as in\n",
    "   [Module 14](../14-monitoring-pipelines/)), with one alert shown firing. To show an alert firing,\n",
    "   make it happen on purpose (for example, run one batch with a much higher defect rate) and include\n",
    "   the alert's log line in your README.\n",
    "6. **Provenance.** A manifest with the input, settings, rules and their hash, versions and output\n",
    "   hashes (Section 8, and [Module 13](../13-versioning-everything/)).\n",
    "7. **Code.** A package-like module with docstrings, tests for the stages that change data, a lock\n",
    "   file, and a README that lets someone else run it. In plain words:\n",
    "   - a **package-like module** is code kept in `.py` files that other code can import, as\n",
    "     `pipeline.py` is, rather than in notebook cells;\n",
    "   - a **docstring** is the short description at the top of each function, as every function in\n",
    "     `pipeline.py` has;\n",
    "   - **tests** are small functions that run a stage on a few hand-made records and check the answer,\n",
    "     such as Section 4's eight examples, run with pytest\n",
    "     ([Module 7](../07-standardisation/));\n",
    "   - the **lock file** is the file that pins the exact version of every package, such as `uv.lock`\n",
    "     ([Module 13](../13-versioning-everything/));\n",
    "   - the **README** is a text file, `README.md`, at the top of your repository: it is the first\n",
    "     thing a reviewer reads.\n",
    "\n",
    "### What to hand in\n",
    "\n",
    "1. **A link to a public Git repository** holding your code, tests, `pyproject.toml` and lock file,\n",
    "   and README. A public repository is one anyone can open with the link. If you have not made one\n",
    "   before: create a free account at [github.com](https://github.com), click **New repository**,\n",
    "   choose **Public**, then add your files with **Add file → Upload files** (or, from a terminal,\n",
    "   with Git, as in [Module 13](../13-versioning-everything/)).\n",
    "2. **The run record of your final run**, in the same repository (for example in a folder named\n",
    "   `run-record`): its `manifest.json`, and the run history table saved as a CSV file. For the\n",
    "   lesson's pipeline, one line in Python saves it:\n",
    "   `duckdb.connect(\"work/capstone/pipeline.duckdb\").sql(\"SELECT * FROM runs\").df().to_csv(\"runs.csv\", index=False)`.\n",
    "3. **The README** (at most two pages): what the pipeline does, how to run it, what its counts\n",
    "   were, what went wrong while you built it and how you found out.\n",
    "\n",
    "Leave out the data files (the Parquet output and the DuckDB database): they are large, and anyone\n",
    "can make them again from your code and settings. To keep Git from adding them, create a text file\n",
    "named `.gitignore` at the top of the repository containing the line `work/`.\n",
    "\n",
    "If you are in a cohort, you will be told where to send the link and by which date, as for the\n",
    "homework.\n",
    "\n",
    "### How it is judged: the peer-review rubric\n",
    "\n",
    "Three peers review each submission, each against the six criteria below, and each criterion is\n",
    "marked *not yet*, *meets* or *exceeds*. A submission earns the certificate when, for every\n",
    "criterion, at least two of the three reviewers mark it *meets* or *exceeds*. Reviewers write one\n",
    "sentence of evidence for each mark. *Exceeds* is not needed for the certificate: it marks work that\n",
    "goes further. Reviewers judge from your repository and README, and follow the README to run your\n",
    "code, so check that it works for someone who has only the link. The settings (requirement 2) are\n",
    "judged under *Code quality and documentation*, and the manifest (requirement 6) under\n",
    "*Standardisation and versioning*.\n",
    "\n",
    "| Criterion | Not yet | Meets | Exceeds |\n",
    "|---|---|---|---|\n",
    "| Correctness and reconciliation | Counts are missing or do not add up; rows can disappear without a record | Every stage's counts add up and a check fails loudly when they do not; files agree with the record | Also checked against a known truth (recorded defects, or a hand-checked sample) and the result reported |\n",
    "| Resumability | A crash means starting again, or the resumed output differs | A crash and a resume are shown, with file hashes equal to an uninterrupted run | Also idempotent under repeated resumes and retries, and the reasons are explained in the README |\n",
    "| Validation and quarantine | Bad records crash the run or vanish | Every rejected record is stored with a stage and a reason code | Reasons are summarised and reviewed; rules justified for the chosen data |\n",
    "| Standardisation and versioning | No standard form, or rules not recorded | Parent and neutralisation applied; rules version and hash stored with every row and in the manifest | A change of rules is shown to change the hash, and outputs under two rule sets kept apart |\n",
    "| Monitoring | Prints only | Structured logs, a run history and two alert rules, one shown firing | Drift or freshness monitored with justified thresholds; a dashboard or report from the history |\n",
    "| Code quality and documentation | Notebook cells only, or the README does not let a reviewer run it | A documented module, tests for the data-changing stages, a lock file, a README that works | Settings and code clean enough for a colleague to extend; tests run in CI |\n",
    "\n",
    "Words in the rubric:\n",
    "\n",
    "- **known truth**: the right answer, known in advance, such as the faults chemlib records in its\n",
    "  `defect` column (Section 7), or a few dozen records you checked by hand;\n",
    "- **idempotent**: doing it again gives the same result and does no harm, so resuming twice, or\n",
    "  retrying a batch, changes nothing ([Module 10](../10-pipelines-that-survive-failure/));\n",
    "- **freshness**: how old the newest data is ([Module 14](../14-monitoring-pipelines/));\n",
    "- **CI** (continuous integration): a service, such as GitHub Actions, that runs your tests every\n",
    "  time you change the code ([Module 7](../07-standardisation/)).\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",
    "- Baell, J. B. & Holloway, G. A. (2010). New substructure filters for removal of pan assay\n",
    "  interference compounds (PAINS) from screening libraries and for their exclusion in bioassays.\n",
    "  *Journal of Medicinal Chemistry*, 53(7), 2719–2740. <https://doi.org/10.1021/jm901137j>\n",
    "- Bento, A. P., Hersey, A., Félix, E., Landrum, G., Gaulton, A., Atkinson, F., Bellis, L. J.,\n",
    "  De Veij, M. & Leach, A. R. (2020). An open source chemical structure curation pipeline using\n",
    "  RDKit. *Journal of Cheminformatics*, 12, 51. <https://doi.org/10.1186/s13321-020-00456-1>\n",
    "- Kleppmann, M. (2017). *Designing Data-Intensive Applications: The Big Ideas Behind Reliable,\n",
    "  Scalable, and Maintainable Systems*. O'Reilly Media. ISBN 978-1-449-37332-0.\n",
    "  <https://dataintensive.net/>\n",
    "- The RDKit documentation. *rdkit.Chem.rdfiltercatalog module* (PAINS and other filter catalogues)\n",
    "  and *rdkit.Chem.MolStandardize.rdMolStandardize module*.\n",
    "  <https://www.rdkit.org/docs/source/rdkit.Chem.rdfiltercatalog.html>,\n",
    "  <https://www.rdkit.org/docs/source/rdkit.Chem.MolStandardize.rdMolStandardize.html>\n",
    "- The pydantic-settings documentation. *Settings Management*.\n",
    "  <https://docs.pydantic.dev/latest/concepts/pydantic_settings/>\n",
    "- The tenacity documentation. <https://tenacity.readthedocs.io/en/latest/>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
