{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Pipelines that survive failure\n",
    "\n",
    "Idempotent batches, checkpoints, retries with back-off, quarantine, atomic writes, cached results and settings checked up front, so a run that fails halfway can be resumed and gives the same answer.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-1/10-pipelines-that-survive-failure/"
   ]
  },
  {
   "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 pandas pydantic pydantic-settings tenacity joblib\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 run over a large library takes hours. Somewhere in those hours something goes wrong: the laptop\n",
    "goes to sleep, the shared server restarts, a network drive stops answering for ten seconds, or one\n",
    "record in two million holds a SMILES that RDKit cannot read. A **pipeline** (a program that takes\n",
    "data through a series of steps, such as read, check, compute and store) written as one long loop\n",
    "loses everything when that happens, and the usual fix, \"run it again from the start\", is slow and\n",
    "often wrong: rows already written are written a second time, and a file that was half-written when\n",
    "the run died is read later as if it were complete.\n",
    "\n",
    "Industry pipelines are written on the assumption that they *will* fail, and are built so that a\n",
    "failure costs little: the work is cut into batches, each batch can be re-run without harm, finished\n",
    "batches are recorded, short-lived errors are retried, bad records are set aside with a reason, and\n",
    "files are only ever seen whole. This module builds each of those habits by hand, on a library of\n",
    "12,000 molecules with faults in it, and shows that a run that crashes halfway and is then resumed\n",
    "gives exactly the same tables as a run that never crashed.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- read a traceback, catch only the errors you expect with `try`/`except`/`else`/`finally`, and\n",
    "  avoid the habits that hide errors;\n",
    "- log an error with its full traceback to an error log, and end a failed job with an exit code\n",
    "  that says it failed;\n",
    "- check a run's settings (batch size, output folder and so on) before any work starts, so a typing\n",
    "  mistake stops the run in the first second;\n",
    "- tell failures that go away if you wait (try again) from failures that never go away (set the\n",
    "  record aside with a reason);\n",
    "- try a failed call again, waiting a little longer each time, by hand and with a package;\n",
    "- save results so that saving the same batch twice leaves the same table as saving it once;\n",
    "- record which batches are finished, and restart a crashed run from the last finished batch;\n",
    "- explain why \"every batch is done exactly once\" is hard to promise, and what pipelines do instead;\n",
    "- write a file so that a crash never leaves a half-written copy behind;\n",
    "- keep the results of a slow step on disk so they are not computed twice, and know when they go\n",
    "  out of date;\n",
    "- run a long job on a server or a rented computer so it keeps going after you disconnect.\n",
    "\n",
    "From earlier modules we use SMILES and RDKit ([Module 1](../01-graphs-and-matrices/),\n",
    "[Module 2](../02-text-patterns-and-numbers/)), the course's `chemlib` file, which makes test\n",
    "libraries and can add faults to them on purpose ([Module 6](../06-validating-molecules/)), and\n",
    "joblib from [Module 9](../09-parallel-and-distributed/). Tables and SQL come from [Module 4](../04-databases-and-schemas/), but you\n",
    "do not need it to follow along: every SQL statement here is explained where it appears.\n",
    "\n",
    "The lesson uses these packages:\n",
    "\n",
    "- **RDKit** reads the molecules and computes their descriptors;\n",
    "- **pandas** holds tables of records (one table is a *DataFrame*);\n",
    "- **Pydantic** and **pydantic-settings** check values against rules you write down;\n",
    "- **tenacity** tries a failed call again, with waits in between;\n",
    "- **joblib** keeps the results of a function on disk (its `Memory` class);\n",
    "- **SQLite** is a small database kept in a single file; it comes with Python as the `sqlite3`\n",
    "  module, so there is nothing to install.\n",
    "\n",
    "Sections 1 to 8 run in Colab or on any laptop. Section 9 is about running jobs on another computer:\n",
    "its commands are typed into a terminal, not into Colab.\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",
    "The run's own settings (library size, batch size, retry limits) are the defaults of the settings\n",
    "class in section 2, which can override them from the environment (section 2 explains what that\n",
    "means). The many `import` lines are not all needed at once: each section says which of them it uses.\n",
    "`chemlib` is not a package from the internet but the course's own helper file; Colab's first cell\n",
    "downloads it next to the notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import csv\n",
    "import logging\n",
    "import math\n",
    "import os\n",
    "import random\n",
    "import sqlite3\n",
    "import time\n",
    "import traceback\n",
    "from collections.abc import Callable\n",
    "from contextlib import closing\n",
    "from pathlib import Path\n",
    "from typing import Any, TextIO\n",
    "\n",
    "import pandas as pd\n",
    "from joblib import Memory\n",
    "from pydantic import Field, ValidationError, field_validator, model_validator\n",
    "from pydantic_settings import BaseSettings, SettingsConfigDict\n",
    "from rdkit import Chem, RDLogger\n",
    "from rdkit.Chem import Descriptors\n",
    "from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_random_exponential\n",
    "\n",
    "from chemlib import add_defects, library\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",
    "# defaults of the run settings (section 2); environment variables CHEMRUN_* override them\n",
    "WORK = Path(\"work\")  # every file the lesson writes goes here\n",
    "N_MOLECULES = 12_000  # molecules drawn from chemlib\n",
    "BATCH_SIZE = 1_000  # records per batch: smaller batches lose less in a crash\n",
    "MAX_ATTEMPTS = 5  # calls in all before a transient failure is given up\n",
    "FIRST_DELAY_S = 0.5  # ceiling of the first retry wait, in seconds; it doubles after each failure\n",
    "MAX_DELAY_S = 30.0  # the largest retry ceiling, in seconds\n",
    "\n",
    "# the faulty library\n",
    "LIBRARY_SEED = 10  # chemlib's seed for the molecules\n",
    "DEFECT_RATE = 0.03  # fraction of records given a fault\n",
    "DEFECT_SEED = 11  # chemlib's seed for which records get which fault\n",
    "ALLOWED_ELEMENTS = {\"C\", \"N\", \"O\", \"S\", \"F\", \"Cl\", \"Br\"}  # anything else is quarantined\n",
    "\n",
    "# the lesson's demonstrations\n",
    "JITTER_SEED = 1  # seed for the random retry waits, so they are the same on every run\n",
    "CRASH_AT_BATCH = 7  # the batch at which the pipeline is made to crash\n",
    "CRASH_AFTER_ROWS = 4_000  # the row at which the CSV export is made to crash\n",
    "\n",
    "RDLogger.DisableLog(\"rdApp.*\")  # bad molecules are reported in a table, not as RDKit messages\n",
    "WORK.mkdir(exist_ok=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. What \"surviving failure\" means\n",
    "\n",
    "Failures come in two kinds, and a pipeline has to treat them differently:\n",
    "\n",
    "- **Transient failures** go away on their own: a timeout (an answer that did not come in time), a\n",
    "  database that is busy for a moment, a web service (a program on another computer that answers\n",
    "  requests over the internet) that answers \"try again later\". The right response is to wait and\n",
    "  try again.\n",
    "- **Permanent failures** do not: a SMILES with a ring that never closes will fail on every attempt,\n",
    "  today and tomorrow. Retrying wastes time. The right response is to set the record aside with a\n",
    "  reason, and carry on with the rest. Setting records aside like this is called **quarantine**.\n",
    "\n",
    "And then there are crashes, where the whole process dies (power, memory, a restart). Nothing inside\n",
    "the program can catch those, so the program has to be written so that starting it again is safe and\n",
    "cheap. To make that possible, the library is cut into **batches** (here, 1,000 records each), and\n",
    "the program records each batch it finishes. The figure shows the run we build in this module: it\n",
    "crashes at batch 7 and the second run picks up from there, without redoing batches 0 to 6 and\n",
    "without duplicating batch 7.\n",
    "\n",
    "![Two runs over thirteen batches. The first run completes and checkpoints batches 0 to 6, saves the rows of batch 7 and crashes before checkpointing it. The second run skips batches 0 to 6, runs batch 7 again and finishes batches 8 to 12; the final tables equal those of a run that never crashed](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/10-pipelines-that-survive-failure/figures/crash-resume.svg)\n",
    "\n",
    "### Errors in Python: exceptions and tracebacks\n",
    "\n",
    "Before building any of this, it helps to know what Python does when something goes wrong, because\n",
    "every technique in this module is a way of handling it. When a line of code cannot do its job,\n",
    "Python stops and **raises an exception**: an object that says what went wrong. If nothing catches\n",
    "it, the program ends and prints a **traceback**, the list of calls that led to the error.\n",
    "\n",
    "Here is a small function that counts the heavy atoms of a molecule, given a SMILES with a ring that\n",
    "never closes. RDKit cannot read it and returns `None` (nothing), and the function then asks `None`\n",
    "for its atoms. `try:` runs the code, and `except AttributeError as error:` catches that kind of\n",
    "exception, so we can look at it instead of the program ending; `traceback.format_exc()` gives the\n",
    "traceback as text, exactly as Python would have printed it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Traceback (most recent call last):\n",
      "  File \"10-pipelines-that-survive-failure/lesson.md block 2\", line 8, in <module>\n",
      "  File \"10-pipelines-that-survive-failure/lesson.md block 2\", line 4, in heavy_atoms\n",
      "AttributeError: 'NoneType' object has no attribute 'GetNumHeavyAtoms'\n",
      "\n"
     ]
    }
   ],
   "source": [
    "def heavy_atoms(smiles: str) -> int:\n",
    "    \"\"\"Count a molecule's heavy atoms (the atoms other than hydrogen).\"\"\"\n",
    "    mol = Chem.MolFromSmiles(smiles)\n",
    "    return mol.GetNumHeavyAtoms()\n",
    "\n",
    "\n",
    "try:\n",
    "    heavy_atoms(\"c1ccccc\")  # a ring that never closes\n",
    "except AttributeError:\n",
    "    print(traceback.format_exc())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Read a traceback from the bottom up.** The last line names the exception and its message:\n",
    "`AttributeError`, because `None` has no `GetNumHeavyAtoms`. The lines above it say where: the line\n",
    "in `heavy_atoms` that asked for the atoms, which was called from the line above it. (Here the file\n",
    "names are the lesson's code blocks. In a script or a notebook they are its file or cell, with line\n",
    "numbers, and under each location Python also prints that line of code.) The\n",
    "bottom line says *what* failed, but not always *why*: the real cause is one step earlier, where\n",
    "RDKit returned `None` for a SMILES it could not read. So after reading the last line, look at the\n",
    "values that reached it. [Module 3](../03-files-and-identity/) checks for `None` straight after\n",
    "reading, which is the fix.\n",
    "\n",
    "### Catching only what you expect: try, except, else, finally\n",
    "\n",
    "A `try` statement has up to four parts:\n",
    "\n",
    "- `try:` the code that might fail;\n",
    "- `except SomeError:` what to do if *that kind* of error happens (you can have several);\n",
    "- `else:` what to do if nothing went wrong (optional);\n",
    "- `finally:` what to do in every case, error or not, such as closing a file (optional).\n",
    "\n",
    "Name the exception you expect, such as `ValueError` for text that is not a number. Then an error\n",
    "you did not expect still stops the program and shows its traceback, instead of being mistaken for\n",
    "the one you planned for. Here a supplier's price column is read, keeping a note of every value\n",
    "looked at:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "WARNING not a price: 'twelve'\n",
      "WARNING not a price: ''\n",
      "[12.5, None, None, 7.0]\n",
      "looked at: ['12.50', 'twelve', '', '7']\n"
     ]
    }
   ],
   "source": [
    "looked_at = []\n",
    "\n",
    "\n",
    "def parse_price(text: str) -> float | None:\n",
    "    \"\"\"A price in dollars from a supplier's text, or None (with a warning) if it is not a number.\"\"\"\n",
    "    try:\n",
    "        price = float(text)\n",
    "    except ValueError:  # only this: \"twelve\" or \"\" is not a number\n",
    "        log.warning(\"not a price: %r\", text)\n",
    "        return None\n",
    "    else:  # only when float() worked\n",
    "        return round(price, 2)\n",
    "    finally:  # always, whichever way the function ends\n",
    "        looked_at.append(text)\n",
    "\n",
    "\n",
    "print([parse_price(t) for t in [\"12.50\", \"twelve\", \"\", \"7\"]])\n",
    "print(\"looked at:\", looked_at)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`%r` in the log message shows the value with its quotes, so an empty text appears as `''` rather\n",
    "than as nothing.\n",
    "\n",
    "### Mistakes that hide errors\n",
    "\n",
    "The most harmful habit in error handling is catching *every* exception and carrying on. Here a\n",
    "function adds up prices, but its author made a typo, `pirce` for `price`, and wrapped the loop in\n",
    "a catch-all `except Exception: pass` \"to be safe\":"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "total: 0.0\n"
     ]
    }
   ],
   "source": [
    "def total_hiding_errors(prices: list[float]) -> float:\n",
    "    \"\"\"Add up prices, swallowing every error (do not write code like this).\"\"\"\n",
    "    total = 0.0\n",
    "    for price in prices:\n",
    "        try:\n",
    "            total += pirce  # noqa: F821 (a typo, kept on purpose)\n",
    "        except Exception:\n",
    "            pass  # every error is thrown away, the typo included\n",
    "    return total\n",
    "\n",
    "\n",
    "print(\"total:\", total_hiding_errors([12.5, 30.0, 7.25]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The answer is 0.0, and nothing says that anything went wrong: the typo raised a `NameError` three\n",
    "times, and each was thrown away. In a pipeline this is how a whole column turns into zeros without\n",
    "anyone noticing. The rules that prevent it:\n",
    "\n",
    "- catch the exception you expect (`except ValueError:`), never everything (`except:` on its own,\n",
    "  or `except Exception:` followed by `pass`);\n",
    "- if you do catch something broad (at the very top of a job, see below), **log it with its\n",
    "  traceback** and stop, or set the record aside with the reason, as the quarantine of section 3\n",
    "  does: never silently carry on;\n",
    "- keep the `try:` block short, around only the line that can fail in the expected way.\n",
    "\n",
    "### An error log with the full traceback\n",
    "\n",
    "When a job runs unattended, a traceback printed to a screen nobody watches is lost. Two habits\n",
    "keep it:\n",
    "\n",
    "- `log.exception(\"message\")`, used inside an `except` block, logs the message at ERROR level\n",
    "  **with the full traceback**, so the log says exactly where and why;\n",
    "- a second log handler that writes only ERROR lines, and worse, to their own file,\n",
    "  `errors.log`, so the problems of a long run are in one short file instead of buried among\n",
    "  thousands of progress lines.\n",
    "\n",
    "Here the job's errors go to `work/errors.log`. `handler.setLevel(logging.ERROR)` makes this\n",
    "handler ignore everything less serious, so the warning below reaches the screen but not the file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "WARNING batch 3: 2 records quarantined\n",
      "ERROR could not count the atoms of record ML-00000007\n",
      "Traceback (most recent call last):\n",
      "  File \"10-pipelines-that-survive-failure/lesson.md block 8\", line 9, in <module>\n",
      "  File \"10-pipelines-that-survive-failure/lesson.md block 2\", line 4, in heavy_atoms\n",
      "AttributeError: 'NoneType' object has no attribute 'GetNumHeavyAtoms'\n",
      "errors.log: 5 lines; first: 'ERROR could not count the atoms of record ML-00000007'; last: \"AttributeError: 'NoneType' object has no attribute 'GetNumHeavyAtoms'\"\n"
     ]
    }
   ],
   "source": [
    "errors_log = WORK / \"errors.log\"\n",
    "to_errors = logging.FileHandler(errors_log, mode=\"w\", encoding=\"utf-8\")\n",
    "to_errors.setLevel(logging.ERROR)  # errors (and worse) only\n",
    "to_errors.setFormatter(logging.Formatter(\"%(levelname)s %(message)s\"))\n",
    "log.addHandler(to_errors)\n",
    "\n",
    "log.warning(\"batch 3: 2 records quarantined\")  # on the screen only\n",
    "try:\n",
    "    heavy_atoms(\"c1ccccc\")\n",
    "except AttributeError:\n",
    "    log.exception(\"could not count the atoms of record ML-00000007\")\n",
    "\n",
    "log.removeHandler(to_errors)\n",
    "to_errors.close()\n",
    "lines = errors_log.read_text(encoding=\"utf-8\").splitlines()\n",
    "print(f\"errors.log: {len(lines)} lines; first: {lines[0]!r}; last: {lines[-1]!r}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The screen shows both lines, the error with its traceback underneath. `errors.log` holds only the\n",
    "error, with its traceback: the first line is the message and the last is the exception. A real job\n",
    "adds the time to every line (`%(asctime)s` in the format), so each error can be matched with what\n",
    "else was happening.\n",
    "\n",
    "### When the whole job fails: the exit code\n",
    "\n",
    "Every program ends with an **exit code**, a number it hands back to whatever started it: `0` means\n",
    "it worked, anything else means it failed. tmux, a scheduler (Module 15), a continuous-integration\n",
    "service and a script that runs several steps all look at that number to decide what to do next. A\n",
    "job that catches its own failure and then ends normally reports `0`, and is treated as a success.\n",
    "\n",
    "So a pipeline's script ends with the pattern below: its `main()` function runs the job; at the very\n",
    "top, and only there, it catches any exception, logs it with its traceback, and returns `1`;\n",
    "`raise SystemExit(main())` makes that number the program's exit code. (In this lesson we only call\n",
    "`main()` and print what it returns, because ending the lesson's own program would stop the lesson.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO job started\n",
      "ERROR job failed\n",
      "Traceback (most recent call last):\n",
      "  File \"10-pipelines-that-survive-failure/lesson.md block 10\", line 10, in main\n",
      "  File \"10-pipelines-that-survive-failure/lesson.md block 10\", line 4, in run_job\n",
      "  File \"10-pipelines-that-survive-failure/lesson.md block 2\", line 4, in heavy_atoms\n",
      "AttributeError: 'NoneType' object has no attribute 'GetNumHeavyAtoms'\n",
      "exit code: 1\n"
     ]
    }
   ],
   "source": [
    "def run_job() -> None:\n",
    "    \"\"\"A stand-in for a whole pipeline run, which fails half way.\"\"\"\n",
    "    log.info(\"job started\")\n",
    "    heavy_atoms(\"c1ccccc\")\n",
    "\n",
    "\n",
    "def main() -> int:\n",
    "    \"\"\"Run the job; return the exit code: 0 if it worked, 1 if it failed (with the reason logged).\"\"\"\n",
    "    try:\n",
    "        run_job()\n",
    "    except Exception:  # the top of the job: the one place a broad catch belongs\n",
    "        log.exception(\"job failed\")\n",
    "        return 1\n",
    "    log.info(\"job finished\")\n",
    "    return 0\n",
    "\n",
    "\n",
    "print(\"exit code:\", main())\n",
    "# a script would end with:  raise SystemExit(main())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[Module 15](../15-capstone/)'s pipeline ends exactly this way: a failed run is logged in its\n",
    "`pipeline.log` with the full traceback, and the program ends with exit code 1.\n",
    "\n",
    "## 2. Settings checked before a run starts\n",
    "\n",
    "The cheapest failure is the one that happens before any work is done. A run that reads a batch size\n",
    "of 0 from a configuration file, or a folder name with a typing mistake, should stop in the first\n",
    "second with a clear message, not after three hours. **pydantic-settings** does this: a settings\n",
    "class lists every setting with its type and its limits, reads values from the environment (or a\n",
    "`.env` file, a text file of such values), and refuses to start if any is wrong. Its defaults are the\n",
    "constants of the Setup block.\n",
    "\n",
    "A few words first. The **environment** is a list of named values, called **environment\n",
    "variables**, that every program receives from whatever started it: a terminal, a server, Colab. In\n",
    "Python they are in `os.environ`, a dictionary. Setting `CHEMRUN_BATCH_SIZE=500` there before a run\n",
    "changes the batch size without editing the code. In the class below:\n",
    "\n",
    "- `n_molecules: int = Field(N_MOLECULES, gt=0)` reads \"an integer, by default `N_MOLECULES`, greater\n",
    "  than 0\" (`gt` is greater than, `ge` greater than or equal, `le` less than or equal). The `: int`\n",
    "  is a **type hint**: it says what kind of value is expected, and pydantic checks it.\n",
    "- `-> Path` after a function's brackets is also a type hint: what the function returns.\n",
    "- A line starting with `@`, such as `@field_validator(\"work_dir\")`, is a **decorator**: it hands the\n",
    "  function below it to pydantic, which then calls it at the right moment. `@field_validator` checks\n",
    "  one setting; `@model_validator(mode=\"after\")` checks settings against each other once all are read.\n",
    "  `@classmethod` is needed by pydantic for field validators; you can copy it as it is.\n",
    "- `model_config = SettingsConfigDict(env_prefix=\"CHEMRUN_\")` says the environment variables all start\n",
    "  with `CHEMRUN_`, so `batch_size` is read from `CHEMRUN_BATCH_SIZE`.\n",
    "\n",
    "In the `print`, `{name:14}` pads the name to 14 characters so the values line up."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "n_molecules    12000\n",
      "batch_size     1000\n",
      "work_dir       work\n",
      "max_attempts   5\n",
      "first_delay_s  0.5\n",
      "max_delay_s    30.0\n"
     ]
    }
   ],
   "source": [
    "class RunSettings(BaseSettings):\n",
    "    \"\"\"Everything a run needs to know, checked before it starts.\n",
    "\n",
    "    Each setting can be overridden by an environment variable: CHEMRUN_BATCH_SIZE, and so on.\n",
    "    \"\"\"\n",
    "\n",
    "    model_config = SettingsConfigDict(env_prefix=\"CHEMRUN_\")\n",
    "\n",
    "    n_molecules: int = Field(N_MOLECULES, gt=0)\n",
    "    batch_size: int = Field(BATCH_SIZE, gt=0)\n",
    "    work_dir: Path = WORK\n",
    "    max_attempts: int = Field(MAX_ATTEMPTS, ge=1, le=10)\n",
    "    first_delay_s: float = Field(FIRST_DELAY_S, gt=0)\n",
    "    max_delay_s: float = Field(MAX_DELAY_S, gt=0)\n",
    "\n",
    "    @field_validator(\"work_dir\")\n",
    "    @classmethod\n",
    "    def folder_exists(cls, folder: Path) -> Path:\n",
    "        \"\"\"The output folder must exist before the run, so a typing mistake fails now.\"\"\"\n",
    "        if not folder.is_dir():\n",
    "            raise ValueError(f\"no folder called '{folder}'\")\n",
    "        return folder\n",
    "\n",
    "    @model_validator(mode=\"after\")\n",
    "    def delays_in_order(self) -> \"RunSettings\":\n",
    "        \"\"\"The first retry delay cannot be longer than the longest delay allowed.\"\"\"\n",
    "        if self.first_delay_s > self.max_delay_s:\n",
    "            raise ValueError(\"first_delay_s is longer than max_delay_s\")\n",
    "        return self\n",
    "\n",
    "\n",
    "settings = RunSettings()\n",
    "for name, value in settings.model_dump().items():\n",
    "    print(f\"{name:14} {value}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now the same run started with two mistakes in its environment: a batch size of 0 and the output\n",
    "folder misspelt. Both are reported together, with the setting, the reason and the value given.\n",
    "When a check fails, pydantic **raises** an error called `ValidationError`: Python stops what it was\n",
    "doing and jumps to the nearest `except ValidationError` that is waiting for it. The code in\n",
    "`try:` is attempted, the code in `except` runs only if that error happened, and the code in\n",
    "`finally:` always runs, here to remove the two bad values again so later cells are not affected:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "ERROR refused to start: 2 bad settings\n",
      "ERROR   batch_size: Input should be greater than 0 (got '0')\n",
      "ERROR   work_dir: Value error, no folder called 'wrok' (got 'wrok')\n"
     ]
    }
   ],
   "source": [
    "os.environ[\"CHEMRUN_BATCH_SIZE\"] = \"0\"\n",
    "os.environ[\"CHEMRUN_WORK_DIR\"] = \"wrok\"\n",
    "try:\n",
    "    RunSettings()\n",
    "except ValidationError as err:\n",
    "    log.error(\"refused to start: %d bad settings\", err.error_count())\n",
    "    for problem in err.errors():\n",
    "        log.error(\"  %s: %s (got %r)\", problem[\"loc\"][0], problem[\"msg\"], problem[\"input\"])\n",
    "finally:\n",
    "    del os.environ[\"CHEMRUN_BATCH_SIZE\"], os.environ[\"CHEMRUN_WORK_DIR\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Without the check, a batch size of 0 would either loop for ever or divide by zero somewhere deep in\n",
    "the run, and the misspelt folder would be created silently and filled with results nobody finds.\n",
    "The same class serves every way a run is started (a laptop, a server, a scheduler, which is a\n",
    "program that starts jobs at set times), because they all pass settings through the environment.\n",
    "\n",
    "## 3. One molecule at a time: quarantine, don't crash\n",
    "\n",
    "Our pipeline does three things to each record: a light validation (can the SMILES be read, is it\n",
    "one molecule, are its elements ones we expect), canonicalisation (writing the SMILES in RDKit's one\n",
    "standard spelling, as in Module 2), and three descriptors: molecular weight, logP (the octanol-water\n",
    "partition coefficient) and TPSA (topological polar surface area). [Module 6](../06-validating-molecules/)\n",
    "validates properly and [Module 7](../07-standardisation/) standardises properly; here the point is\n",
    "what happens when a record fails.\n",
    "\n",
    "Each problem raises `BadMolecule` with a reason a person can read. `class BadMolecule(Exception)`\n",
    "makes a new kind of error of our own, so the code can catch exactly this kind and let others pass.\n",
    "`raise ... from err` keeps RDKit's original error attached, for whoever reads the message. In\n",
    "`prepare_batch`, `**prepare(record.smiles)` unpacks the dictionary that `prepare` returns into the\n",
    "new one, so its four keys sit next to `id` and `smiles`; `batch.itertuples()` goes through a\n",
    "table's rows one by one. The type hint `tuple[pd.DataFrame, pd.DataFrame]` says the function returns\n",
    "two tables. The elements we expect are `ALLOWED_ELEMENTS`, set in the Setup block."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class BadMolecule(Exception):\n",
    "    \"\"\"A permanent problem with a record: trying again will not fix it.\"\"\"\n",
    "\n",
    "\n",
    "def prepare(smiles: str) -> dict:\n",
    "    \"\"\"Check a SMILES lightly, canonicalise it and compute three descriptors.\n",
    "\n",
    "    Args:\n",
    "        smiles: The record's SMILES.\n",
    "\n",
    "    Returns:\n",
    "        The canonical SMILES, molecular weight, logP and TPSA.\n",
    "\n",
    "    Raises:\n",
    "        BadMolecule: If the record cannot be used, with the reason.\n",
    "    \"\"\"\n",
    "    mol = Chem.MolFromSmiles(smiles, sanitize=False)\n",
    "    if mol is None:\n",
    "        raise BadMolecule(\"cannot be parsed\")\n",
    "    try:\n",
    "        Chem.SanitizeMol(mol)\n",
    "    except Chem.MolSanitizeException as err:\n",
    "        raise BadMolecule(f\"fails sanitisation ({type(err).__name__})\") from err\n",
    "    if len(Chem.GetMolFrags(mol)) > 1:\n",
    "        raise BadMolecule(\"more than one component\")\n",
    "    unexpected = sorted({atom.GetSymbol() for atom in mol.GetAtoms()} - ALLOWED_ELEMENTS)\n",
    "    if unexpected:\n",
    "        raise BadMolecule(f\"unexpected element {', '.join(unexpected)}\")\n",
    "    return {\n",
    "        \"canonical\": Chem.MolToSmiles(mol),\n",
    "        \"mol_wt\": round(Descriptors.MolWt(mol), 3),\n",
    "        \"logp\": round(Descriptors.MolLogP(mol), 3),\n",
    "        \"tpsa\": round(Descriptors.TPSA(mol), 2),\n",
    "    }\n",
    "\n",
    "\n",
    "def prepare_batch(batch: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:\n",
    "    \"\"\"Prepare every record of a batch; bad records go to quarantine and the batch carries on.\n",
    "\n",
    "    Args:\n",
    "        batch: Records with id and smiles.\n",
    "\n",
    "    Returns:\n",
    "        The prepared molecules, and the quarantined records with the reason for each.\n",
    "    \"\"\"\n",
    "    good, bad = [], []\n",
    "    for record in batch.itertuples(index=False):\n",
    "        try:\n",
    "            good.append({\"id\": record.id, \"smiles\": record.smiles, **prepare(record.smiles)})\n",
    "        except BadMolecule as err:\n",
    "            bad.append({\"id\": record.id, \"smiles\": record.smiles, \"reason\": str(err)})\n",
    "    good_columns = [\"id\", \"smiles\", \"canonical\", \"mol_wt\", \"logp\", \"tpsa\"]\n",
    "    return (pd.DataFrame(good, columns=good_columns),\n",
    "            pd.DataFrame(bad, columns=[\"id\", \"smiles\", \"reason\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The library is 12,000 molecules from chemlib, with faults added at a rate of 3%: salts, solvents,\n",
    "unreadable SMILES, impossible valences, selenium, and duplicates. Sorting by `id` matters more than\n",
    "it looks: it fixes which records belong to which batch, so batch 7 holds the same records in every\n",
    "run. Without a fixed order, \"resume from batch 7\" would mean something different each time.\n",
    "(`f\"{len(source):,}\"` writes the number with commas, 12,060; in a `log` message, each `%s` or\n",
    "`%d` is filled in with the next value after the message; `.iloc[a:b]` takes rows a to b-1 of a\n",
    "table.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO 12,060 records in 13 batches of up to 1,000\n",
      "defect\n",
      "(none)       11700\n",
      "solvent         60\n",
      "duplicate       60\n",
      "valence         60\n",
      "salt            60\n",
      "invalid         60\n",
      "element         60\n"
     ]
    }
   ],
   "source": [
    "source = add_defects(library(settings.n_molecules, seed=LIBRARY_SEED), rate=DEFECT_RATE,\n",
    "                     seed=DEFECT_SEED)\n",
    "source = source.sort_values(\"id\").reset_index(drop=True)\n",
    "n_batches = math.ceil(len(source) / settings.batch_size)\n",
    "log.info(\"%s records in %d batches of up to %s\", f\"{len(source):,}\", n_batches,\n",
    "         f\"{settings.batch_size:,}\")\n",
    "print(source[\"defect\"].replace(\"\", \"(none)\").value_counts().to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The 60 duplicates are new rows, so there are 12,060 records and 13 batches, the last one short.\n",
    "Here is the first batch:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO prepared 969, quarantined 31\n",
      "reason\n",
      "unexpected element Se                        9\n",
      "more than one component                      8\n",
      "fails sanitisation (AtomValenceException)    8\n",
      "cannot be parsed                             6\n"
     ]
    }
   ],
   "source": [
    "good, bad = prepare_batch(source.iloc[: settings.batch_size])\n",
    "log.info(\"prepared %d, quarantined %d\", len(good), len(bad))\n",
    "print(bad[\"reason\"].value_counts().to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Thirty-one bad records in a thousand did not stop the batch. Each one is kept, with its reason, in a quarantine\n",
    "table where someone can look at it later; nothing is dropped silently. If quarantine starts to fill\n",
    "quickly (a new supplier's file in a different format, say), that is a signal to stop and look, and\n",
    "Module 14 turns such counts into alerts.\n",
    "\n",
    "## 4. Retries with back-off and jitter\n",
    "\n",
    "Now the transient kind. Suppose the descriptors came from a shared service on another machine,\n",
    "which sometimes answers \"busy\". We stand one in with a class that fails its first few calls and then\n",
    "works, so the lesson behaves the same on every run. Two special methods make it work: `__init__`\n",
    "runs once when the object is made (`FlakyService(failures=3)`) and stores its settings, and\n",
    "`__call__` lets the object be called like a function, `service(\"CCO\")`, so it can stand in for\n",
    "one:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class TransientError(Exception):\n",
    "    \"\"\"A failure that may go away if we wait and try again: a timeout, a busy server.\"\"\"\n",
    "\n",
    "\n",
    "class FlakyService:\n",
    "    \"\"\"A stand-in for a remote service that fails its first `failures` calls, then works.\"\"\"\n",
    "\n",
    "    def __init__(self, failures: int) -> None:\n",
    "        self.failures = failures\n",
    "        self.calls = 0\n",
    "\n",
    "    def __call__(self, smiles: str) -> dict:\n",
    "        \"\"\"Prepare a molecule, unless this is one of the calls that fail.\"\"\"\n",
    "        self.calls += 1\n",
    "        if self.calls <= self.failures:\n",
    "            raise TransientError(f\"call {self.calls}: service busy\")\n",
    "        return prepare(smiles)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The standard response is **exponential back-off**: wait a little after the first failure, twice as\n",
    "long after the second, four times as long after the third, up to a ceiling. Waiting longer each\n",
    "time gives a struggling service room to recover. **Jitter** picks the actual wait at random between\n",
    "zero and that ceiling (\"full jitter\"). Without it, a hundred workers that failed together all retry\n",
    "at the same instants and knock the service over again; with it, their retries spread out. The\n",
    "function takes `sleep` as an argument so the lesson can record the waits instead of sitting through\n",
    "them, and `rng` so the random waits are the same on every run. Each retry is a warning in the log:\n",
    "someone reading a nightly job's log wants to know the service was struggling, even when it\n",
    "recovered.\n",
    "\n",
    "Some notation in the function. `*args` collects any further arguments into a tuple, which the\n",
    "function passes on to `func` unchanged; `Callable` in a type hint means \"something you can call\",\n",
    "such as a function. `2 ** (attempt - 1)` is 2 to the power `attempt - 1`, so the ceiling goes 0.5,\n",
    "1, 2, 4 seconds. `rng.uniform(0, ceiling)` picks a random number between 0 and the ceiling. In the\n",
    "lesson we pass `sleep=waits.append`, so instead of waiting, each wait is added to the list `waits`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "WARNING attempt 1 failed (call 1: service busy); waiting 0.07 s of up to 0.5 s\n",
      "WARNING attempt 2 failed (call 2: service busy); waiting 0.85 s of up to 1.0 s\n",
      "WARNING attempt 3 failed (call 3: service busy); waiting 1.53 s of up to 2.0 s\n",
      "succeeded on call 4: aspirin, MW 180.159\n",
      "waited 2.44 s in all\n"
     ]
    }
   ],
   "source": [
    "def with_retries(func: Callable, *args, max_attempts: int = MAX_ATTEMPTS,\n",
    "                 first_delay: float = FIRST_DELAY_S, max_delay: float = MAX_DELAY_S,\n",
    "                 rng: random.Random | None = None,\n",
    "                 sleep: Callable[[float], None] = time.sleep) -> Any:\n",
    "    \"\"\"Call func(*args), retrying transient failures with exponential back-off and full jitter.\n",
    "\n",
    "    Args:\n",
    "        func: What to call.\n",
    "        *args: Its arguments.\n",
    "        max_attempts: How many calls in all before giving up.\n",
    "        first_delay: The ceiling of the first wait, in seconds; it doubles after each failure.\n",
    "        max_delay: The largest ceiling, in seconds.\n",
    "        rng: The random number generator for the jitter (a fresh, unseeded one if not given).\n",
    "        sleep: How to wait (time.sleep unless told otherwise).\n",
    "\n",
    "    Returns:\n",
    "        What func returns.\n",
    "\n",
    "    Raises:\n",
    "        TransientError: If every attempt failed. Any other error is raised at once, unretried.\n",
    "    \"\"\"\n",
    "    rng = rng or random.Random()\n",
    "    for attempt in range(1, max_attempts + 1):\n",
    "        try:\n",
    "            return func(*args)\n",
    "        except TransientError as err:\n",
    "            if attempt == max_attempts:\n",
    "                raise\n",
    "            ceiling = min(max_delay, first_delay * 2 ** (attempt - 1))\n",
    "            delay = rng.uniform(0, ceiling)\n",
    "            log.warning(\"attempt %d failed (%s); waiting %.2f s of up to %s s\",\n",
    "                        attempt, err, delay, ceiling)\n",
    "            sleep(delay)\n",
    "\n",
    "\n",
    "waits = []\n",
    "service = FlakyService(failures=3)\n",
    "result = with_retries(service, \"CC(=O)Oc1ccccc1C(=O)O\", rng=random.Random(JITTER_SEED),\n",
    "                      sleep=waits.append)\n",
    "print(f\"succeeded on call {service.calls}: aspirin, MW {result['mol_wt']}\")\n",
    "print(f\"waited {sum(waits):.2f} s in all\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Two other cases matter as much. A service that never recovers must not be retried for ever: after\n",
    "`max_attempts` the error is raised, and the run (or the batch) fails visibly. And a permanent error\n",
    "is not retried at all: a broken SMILES raises `BadMolecule` on the first call, which goes straight\n",
    "to quarantine:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "WARNING attempt 1 failed (call 1: service busy); waiting 0.07 s of up to 0.5 s\n",
      "WARNING attempt 2 failed (call 2: service busy); waiting 0.85 s of up to 1.0 s\n",
      "WARNING attempt 3 failed (call 3: service busy); waiting 1.53 s of up to 2.0 s\n",
      "WARNING attempt 4 failed (call 4: service busy); waiting 1.02 s of up to 4.0 s\n",
      "ERROR gave up: call 5: service busy\n",
      "WARNING not retried (1 call), quarantined: cannot be parsed\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    with_retries(FlakyService(failures=10), \"CCO\", rng=random.Random(JITTER_SEED),\n",
    "                 sleep=waits.append)\n",
    "except TransientError as err:\n",
    "    log.error(\"gave up: %s\", err)\n",
    "\n",
    "broken = FlakyService(failures=0)\n",
    "try:\n",
    "    with_retries(broken, \"C1CC\", rng=random.Random(JITTER_SEED), sleep=waits.append)\n",
    "except BadMolecule as err:\n",
    "    log.warning(\"not retried (%d call), quarantined: %s\", broken.calls, err)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Back-off delays for twenty clients retrying the same failed service: the ceiling doubles from 0.5 s after each attempt up to 30 s, and each client's actual wait is drawn at random below it, so the retries spread out instead of arriving together](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/10-pipelines-that-survive-failure/figures/backoff.svg)\n",
    "\n",
    "### The same with tenacity\n",
    "\n",
    "Writing retry loops by hand in every project leads to small differences and small bugs. The\n",
    "industry-standard Python library is **tenacity**: a decorator (the `@retry(...)` line in the code\n",
    "below, as with pydantic's validators in section 2) wraps the function in a retry loop like ours,\n",
    "and its arguments state which errors to retry, when to stop and how long to wait. `wait_random_exponential` is the same full-jitter back-off as above, and\n",
    "the limits come from the settings checked in section 2 (the four names from tenacity are imported\n",
    "in the Setup block):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{'canonical': 'Cn1c(=O)c2c(ncn2C)n(C)c1=O', 'mol_wt': 194.194, 'logp': -1.029, 'tpsa': 61.82}\n",
      "3 calls; waits of [0.07, 0.85] s\n"
     ]
    }
   ],
   "source": [
    "service = FlakyService(failures=2)\n",
    "waits = []\n",
    "\n",
    "\n",
    "@retry(\n",
    "    retry=retry_if_exception_type(TransientError),  # BadMolecule is not retried\n",
    "    stop=stop_after_attempt(settings.max_attempts),\n",
    "    wait=wait_random_exponential(multiplier=settings.first_delay_s, max=settings.max_delay_s),\n",
    "    sleep=waits.append,  # leave this out in real use: tenacity then waits with time.sleep\n",
    "    reraise=True,  # after the last attempt, raise the original error, not a wrapper\n",
    ")\n",
    "def prepare_remotely(smiles: str) -> dict:\n",
    "    \"\"\"Prepare a molecule on the (flaky) remote service, retrying transient failures.\"\"\"\n",
    "    return service(smiles)\n",
    "\n",
    "\n",
    "random.seed(JITTER_SEED)  # tenacity draws its jitter from Python's random module\n",
    "print(prepare_remotely(\"CN1C=NC2=C1C(=O)N(C(=O)N2C)C\"))\n",
    "print(f\"{service.calls} calls; waits of {[round(w, 2) for w in waits]} s\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Which errors count as transient is a decision you write down once: in practice\n",
    "`TimeoutError`, `ConnectionError`, `sqlite3.OperationalError(\"database is locked\")` and HTTP\n",
    "responses 429 and 5xx are transient; a bad SMILES, a missing column or HTTP 404 are not. (HTTP is\n",
    "how web services talk, and every answer carries a number: 429 means \"too many requests\", 5xx\n",
    "(500 to 599) means the service itself failed, and 404 means \"not found\".) [Module 11](../11-incremental-ingestion/)\n",
    "uses tenacity in exactly this way against the ChEMBL and PubChem web services.\n",
    "\n",
    "## 5. Idempotent batches\n",
    "\n",
    "A step is **idempotent** if running it twice leaves the same result as running it once. Setting a\n",
    "light switch to \"on\" is idempotent; pressing a toggle button is not. That is the property that\n",
    "makes \"just run it again\" safe. The common way to write results is not idempotent: appending rows. Here is the first batch appended twice with pandas, as happens when a\n",
    "run dies after writing a batch and the batch is then run again. `sqlite3.connect(path)` opens the\n",
    "database file (creating it if needed) and returns a **connection**, through which we send it\n",
    "commands written in **SQL**, the language databases understand: `DROP TABLE IF EXISTS molecules`\n",
    "deletes the table if there is one, and `SELECT COUNT(*), COUNT(DISTINCT id) FROM molecules` counts\n",
    "the rows and the different ids. The connection is opened in a `with closing(...)` block\n",
    "(`closing`, from `contextlib`, is imported in the Setup block). A `with` block runs some set-up\n",
    "when it starts and some tidying when it ends; here the tidying closes the connection, even if\n",
    "something inside the block fails:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "after writing batch 0 1x: 969 rows, 969 different molecules\n",
      "after writing batch 0 2x: 1938 rows, 969 different molecules\n"
     ]
    }
   ],
   "source": [
    "with closing(sqlite3.connect(WORK / \"naive.sqlite\")) as naive:\n",
    "    naive.execute(\"DROP TABLE IF EXISTS molecules\")\n",
    "    for attempt in (1, 2):\n",
    "        good.to_sql(\"molecules\", naive, if_exists=\"append\", index=False)\n",
    "        count = naive.execute(\"SELECT COUNT(*), COUNT(DISTINCT id) FROM molecules\").fetchone()\n",
    "        print(f\"after writing batch 0 {attempt}x: {count[0]} rows, {count[1]} different molecules\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every molecule of the batch is now in the table twice, and every count, average and export made\n",
    "from it is wrong without any error being raised.\n",
    "\n",
    "The idempotent version has two parts. The table has a **primary key**, the record's `id`, so the\n",
    "database itself refuses two rows for one molecule. And rows are written with an **upsert**\n",
    "(`INSERT … ON CONFLICT … DO UPDATE`): insert the row if it is new, overwrite it if it is already\n",
    "there. SQLite, PostgreSQL and DuckDB all use this syntax. The batch's rows go in inside one\n",
    "**transaction** (`with con:`): a group of changes the database saves all together or not at all.\n",
    "So a crash halfway through a batch leaves none of its rows, not some.\n",
    "\n",
    "In the code, `SCHEMA` holds the `CREATE TABLE` statements: each names a table and its columns\n",
    "(`TEXT` for text, `REAL` for decimal numbers, `INTEGER` for whole numbers). `IF NOT EXISTS` makes\n",
    "them safe to run again. In `UPSERT_MOLECULE`, `:id`, `:smiles` and so on are placeholders filled\n",
    "from each row's dictionary, and `excluded.smiles` means \"the value we just tried to insert\".\n",
    "`executemany` runs the statement once for every row in a list.\n",
    "Note the difference between the two `with` blocks: sqlite3's own `with con:` commits or rolls back\n",
    "a transaction but leaves the connection open; `with closing(con):` closes it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "after writing batch 0 1x: molecules 969, quarantine 31, checkpoints 0\n",
      "after writing batch 0 2x: molecules 969, quarantine 31, checkpoints 0\n"
     ]
    }
   ],
   "source": [
    "SCHEMA = \"\"\"\n",
    "CREATE TABLE IF NOT EXISTS molecules (\n",
    "    id TEXT PRIMARY KEY, smiles TEXT, canonical TEXT, mol_wt REAL, logp REAL, tpsa REAL);\n",
    "CREATE TABLE IF NOT EXISTS quarantine (id TEXT PRIMARY KEY, smiles TEXT, reason TEXT);\n",
    "CREATE TABLE IF NOT EXISTS checkpoints (batch INTEGER PRIMARY KEY, n_good INTEGER, n_bad INTEGER);\n",
    "\"\"\"\n",
    "UPSERT_MOLECULE = \"\"\"\n",
    "INSERT INTO molecules VALUES (:id, :smiles, :canonical, :mol_wt, :logp, :tpsa)\n",
    "ON CONFLICT (id) DO UPDATE SET smiles = excluded.smiles, canonical = excluded.canonical,\n",
    "    mol_wt = excluded.mol_wt, logp = excluded.logp, tpsa = excluded.tpsa\n",
    "\"\"\"\n",
    "UPSERT_QUARANTINE = \"\"\"\n",
    "INSERT INTO quarantine VALUES (:id, :smiles, :reason)\n",
    "ON CONFLICT (id) DO UPDATE SET smiles = excluded.smiles, reason = excluded.reason\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "def connect(path: Path) -> sqlite3.Connection:\n",
    "    \"\"\"Open the run's database, creating its tables if they are not there yet.\"\"\"\n",
    "    con = sqlite3.connect(path)\n",
    "    con.executescript(SCHEMA)\n",
    "    return con\n",
    "\n",
    "\n",
    "def save_batch(con: sqlite3.Connection, good: pd.DataFrame, bad: pd.DataFrame) -> None:\n",
    "    \"\"\"Write a batch's results idempotently: all its rows in one transaction, upserted by id.\"\"\"\n",
    "    with con:  # commits at the end, or rolls everything back if anything fails\n",
    "        con.executemany(UPSERT_MOLECULE, good.to_dict(\"records\"))\n",
    "        con.executemany(UPSERT_QUARANTINE, bad.to_dict(\"records\"))\n",
    "\n",
    "\n",
    "def count_rows(con: sqlite3.Connection) -> str:\n",
    "    \"\"\"How many rows each table holds, as one line.\"\"\"\n",
    "    tables = [\"molecules\", \"quarantine\", \"checkpoints\"]\n",
    "    counts = [con.execute(f\"SELECT COUNT(*) FROM {t}\").fetchone()[0] for t in tables]\n",
    "    return \", \".join(f\"{t} {n:,}\" for t, n in zip(tables, counts, strict=True))\n",
    "\n",
    "\n",
    "demo_path = WORK / \"demo.sqlite\"\n",
    "demo_path.unlink(missing_ok=True)\n",
    "with closing(connect(demo_path)) as con:\n",
    "    for attempt in (1, 2):\n",
    "        save_batch(con, good, bad)\n",
    "        print(f\"after writing batch 0 {attempt}x: {count_rows(con)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Idempotency also needs the step itself to be repeatable: the same batch must give the same rows.\n",
    "That is why the batches have a fixed order, and why the rows carry no timestamp of when they were\n",
    "computed (a run's start time belongs in a separate table about runs, not in every row).\n",
    "\n",
    "## 6. Checkpoints, crashes and resuming\n",
    "\n",
    "A **checkpoint table** records which batches are finished. The pipeline reads it at the start,\n",
    "skips the finished batches, and writes a checkpoint after each batch's rows are saved. To show a\n",
    "crash, `run_pipeline` can raise `SimulatedCrash` at a chosen batch, at the worst possible moment:\n",
    "after the batch's rows are committed (saved for good) but before its checkpoint is written.\n",
    "\n",
    "Reading the code: `BatchPreparer` is a short name for a type, \"a function that takes a table and\n",
    "returns two tables\", used in a type hint. `crash_at: int | None = None` means the argument is a\n",
    "whole number or `None` (nothing), and is `None` unless given. `{row[0] for row in ...}` builds a\n",
    "**set** (a collection where each value appears once and looking one up is fast) of the batch\n",
    "numbers already finished. `INSERT OR REPLACE` is SQLite's short form of an upsert."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SimulatedCrash(Exception):\n",
    "    \"\"\"Stands in for the process dying: power cut, out of memory, a server restart.\"\"\"\n",
    "\n",
    "\n",
    "BatchPreparer = Callable[[pd.DataFrame], tuple[pd.DataFrame, pd.DataFrame]]\n",
    "\n",
    "\n",
    "def run_pipeline(source: pd.DataFrame, db_path: Path, batch_size: int,\n",
    "                 prepare_fn: BatchPreparer = prepare_batch,\n",
    "                 crash_at: int | None = None) -> list[int]:\n",
    "    \"\"\"Prepare every batch not yet checkpointed, saving each idempotently.\n",
    "\n",
    "    Args:\n",
    "        source: The records, in a fixed order (it decides which records are in which batch).\n",
    "        db_path: The run's SQLite database.\n",
    "        batch_size: Records per batch.\n",
    "        prepare_fn: The function that prepares one batch.\n",
    "        crash_at: The batch at which to simulate a crash, after saving it and before its checkpoint.\n",
    "\n",
    "    Returns:\n",
    "        The batches this call ran.\n",
    "    \"\"\"\n",
    "    ran = []\n",
    "    with closing(connect(db_path)) as con:\n",
    "        done = {row[0] for row in con.execute(\"SELECT batch FROM checkpoints\")}\n",
    "        for k in range(math.ceil(len(source) / batch_size)):\n",
    "            if k in done:\n",
    "                continue\n",
    "            good, bad = prepare_fn(source.iloc[k * batch_size : (k + 1) * batch_size])\n",
    "            save_batch(con, good, bad)\n",
    "            if k == crash_at:\n",
    "                raise SimulatedCrash(f\"died after saving batch {k}, before its checkpoint\")\n",
    "            with con:\n",
    "                con.execute(\"INSERT OR REPLACE INTO checkpoints VALUES (?, ?, ?)\",\n",
    "                            (k, len(good), len(bad)))\n",
    "            ran.append(k)\n",
    "    return ran"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First the reference: a run that is never interrupted."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO ran batches 0 to 12\n",
      "molecules 11,761, quarantine 299, checkpoints 13\n"
     ]
    }
   ],
   "source": [
    "reference_path = settings.work_dir / \"reference.sqlite\"\n",
    "reference_path.unlink(missing_ok=True)\n",
    "ran = run_pipeline(source, reference_path, settings.batch_size)\n",
    "log.info(\"ran batches %d to %d\", ran[0], ran[-1])\n",
    "with closing(sqlite3.connect(reference_path)) as con:\n",
    "    print(count_rows(con))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now the same run on a fresh database, crashing at batch 7. The lesson catches the crash so we can\n",
    "look at what it left behind; a real crash would simply end the process."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "ERROR crashed: died after saving batch 7, before its checkpoint\n",
      "molecules 7,792, quarantine 208, checkpoints 7\n",
      "checkpointed batches: [0, 1, 2, 3, 4, 5, 6]\n"
     ]
    }
   ],
   "source": [
    "run_path = settings.work_dir / \"run.sqlite\"\n",
    "run_path.unlink(missing_ok=True)\n",
    "try:\n",
    "    run_pipeline(source, run_path, settings.batch_size, crash_at=CRASH_AT_BATCH)\n",
    "except SimulatedCrash as err:\n",
    "    log.error(\"crashed: %s\", err)\n",
    "with closing(sqlite3.connect(run_path)) as con:\n",
    "    print(count_rows(con))\n",
    "    finished = [row[0] for row in con.execute(\"SELECT batch FROM checkpoints ORDER BY batch\")]\n",
    "print(f\"checkpointed batches: {finished}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Batches 0 to 6 are checkpointed. Batch 7's rows are in the tables, but its checkpoint is not, so\n",
    "the database cannot tell that batch 7 is finished. Resuming is simply running the same command\n",
    "again:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO resumed: skipped 7 finished batches, ran batches [7, 8, 9, 10, 11, 12]\n",
      "molecules 11,761, quarantine 299, checkpoints 13\n"
     ]
    }
   ],
   "source": [
    "ran = run_pipeline(source, run_path, settings.batch_size)\n",
    "log.info(\"resumed: skipped %d finished batches, ran batches %s\", len(finished), ran)\n",
    "with closing(sqlite3.connect(run_path)) as con:\n",
    "    print(count_rows(con))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Batch 7 ran twice, once before the crash and once after, and the tables hold it once, because\n",
    "`save_batch` is idempotent. The real test is whether the result equals the uninterrupted run, row for\n",
    "row. `pd.testing.assert_frame_equal` compares two tables and raises an error if they differ in any\n",
    "value, column or type; if it is silent, they are the same:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "molecules: identical (11,761 rows)\n",
      "quarantine: identical (299 rows)\n",
      "checkpoints: identical (13 rows)\n"
     ]
    }
   ],
   "source": [
    "def read_tables(db_path: Path) -> dict[str, pd.DataFrame]:\n",
    "    \"\"\"Every table of a run's database, sorted by its key, for comparison.\"\"\"\n",
    "    keys = {\"molecules\": \"id\", \"quarantine\": \"id\", \"checkpoints\": \"batch\"}\n",
    "    with closing(sqlite3.connect(db_path)) as con:\n",
    "        return {t: pd.read_sql(f\"SELECT * FROM {t} ORDER BY {k}\", con) for t, k in keys.items()}\n",
    "\n",
    "\n",
    "reference, resumed = read_tables(reference_path), read_tables(run_path)\n",
    "for table in reference:\n",
    "    pd.testing.assert_frame_equal(reference[table], resumed[table])  # raises if they differ\n",
    "    print(f\"{table}: identical ({len(reference[table]):,} rows)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The quarantine table says why each record was set aside. Joined back to chemlib's record of which\n",
    "faults it added, it shows how each kind of fault was caught. The 60 duplicates passed: they are\n",
    "valid molecules, and finding them is Module 7's job. `merge` joins the two tables on `id`, as in\n",
    "[Module 3](../03-files-and-identity/), and `pd.crosstab` counts how often each pair of values (fault, reason) occurs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "reason     (prepared)  cannot be parsed  fails sanitisation (AtomValenceException)  more than one component  unexpected element Se\n",
      "defect                                                                                                                            \n",
      "(none)          11700                 0                                          0                        0                      0\n",
      "duplicate          60                 0                                          0                        0                      0\n",
      "element             1                 0                                          0                        0                     59\n",
      "invalid             0                60                                          0                        0                      0\n",
      "salt                0                 0                                          0                       60                      0\n",
      "solvent             0                 0                                          0                       60                      0\n",
      "valence             0                 0                                         60                        0                      0\n"
     ]
    }
   ],
   "source": [
    "caught = source.merge(reference[\"quarantine\"][[\"id\", \"reason\"]], on=\"id\", how=\"left\")\n",
    "caught[\"reason\"] = caught[\"reason\"].fillna(\"(prepared)\")\n",
    "print(pd.crosstab(caught[\"defect\"].replace(\"\", \"(none)\"), caught[\"reason\"]).to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One record marked `element` was prepared. Looking at it (`c1cc(c8ccccc8)ccc1-c2nc(c8ccncc8)c(O)o2`)\n",
    "explains why: chemlib adds selenium by replacing an aliphatic carbon, and this molecule has none, so\n",
    "the \"fault\" left it unchanged and it is a valid molecule. Labels of what is wrong can be wrong too;\n",
    "checking a pipeline against them is how such cases come to light.\n",
    "\n",
    "### At-least-once and exactly-once\n",
    "\n",
    "Every batch here is processed **at least once**: a batch that crashed before its checkpoint is run\n",
    "again, so some batches are processed twice. What we would like is **exactly once**: every batch's\n",
    "effect appears once, no matter what fails. Within one database, a transaction can give that: if the\n",
    "rows and the checkpoint were written in the same transaction, they would be saved together or not\n",
    "at all. But the moment a step touches two systems (rows into a database and a file on disk, or a\n",
    "call to a web service and a row recording it), no transaction covers both, and there is always a\n",
    "moment where one has happened and the other has not. That is exactly the moment our simulated crash\n",
    "picked.\n",
    "\n",
    "The practical answer, used across the industry, is **at-least-once delivery plus idempotent\n",
    "steps**: accept that work may be repeated, and make repeating it harmless. The effect is the same as\n",
    "exactly once, and it needs nothing more than a key and an upsert. Kleppmann's book (further\n",
    "reading) explains this in depth for databases and for message queues (programs that pass work from\n",
    "one program to another).\n",
    "\n",
    "At scale the pattern is the same. For two million molecules, batches of 10,000 give 200\n",
    "checkpoints; a crash costs at most one batch of work. Smaller batches lose less in a crash but write\n",
    "more checkpoints; most pipelines choose batches that take seconds to minutes. With PostgreSQL\n",
    "(Module 4), a larger database that runs as a server many people share, the tables and the upserts are the same, and many workers can write to one database at\n",
    "once (Module 9).\n",
    "\n",
    "## 7. Atomic writes\n",
    "\n",
    "Results usually leave the database as files: a CSV for a colleague, a Parquet file (a compact file\n",
    "format for tables, from [Module 3](../03-files-and-identity/)) for the next pipeline. Writing a file takes time, and a crash in the middle leaves a **half-written file** that\n",
    "looks like a complete one. Here is the export done the obvious way, crashing a third of the way\n",
    "through. Python's `csv` module, imported in the Setup block, writes the rows. `open(path, \"w\")`\n",
    "opens a file for writing (`\"w\"` empties it first), and the `with` block closes it at the end;\n",
    "`enumerate` numbers the rows as it goes, so the function knows when to crash:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "ERROR crashed: died after writing 4,000 rows\n",
      "the file exists: True, rows a reader sees: 4,000\n"
     ]
    }
   ],
   "source": [
    "molecules = reference[\"molecules\"]\n",
    "export_path = settings.work_dir / \"molecules.csv\"\n",
    "\n",
    "\n",
    "def write_rows(handle: TextIO, table: pd.DataFrame, crash_after: int | None = None) -> None:\n",
    "    \"\"\"Write a table as CSV to an open file, one row at a time, optionally crashing partway.\"\"\"\n",
    "    writer = csv.writer(handle)\n",
    "    writer.writerow(table.columns)\n",
    "    for i, row in enumerate(table.itertuples(index=False)):\n",
    "        if i == crash_after:\n",
    "            raise SimulatedCrash(f\"died after writing {i:,} rows\")\n",
    "        writer.writerow(row)\n",
    "\n",
    "\n",
    "export_path.unlink(missing_ok=True)\n",
    "try:\n",
    "    with open(export_path, \"w\", newline=\"\", encoding=\"utf-8\") as handle:\n",
    "        write_rows(handle, molecules, crash_after=CRASH_AFTER_ROWS)\n",
    "except SimulatedCrash as err:\n",
    "    log.error(\"crashed: %s\", err)\n",
    "rows_seen = len(pd.read_csv(export_path))\n",
    "print(f\"the file exists: {export_path.exists()}, rows a reader sees: {rows_seen:,}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A reader the next morning finds a well-formed CSV with fewer rows and no sign that anything went\n",
    "wrong. The fix is an **atomic write**: write to a temporary file in the same folder, make sure it\n",
    "is on disk (`flush` and `os.fsync`), then rename it over the target with `os.replace`. Renaming a\n",
    "file within one folder is atomic on Windows, macOS and Linux: other programs see either the old file\n",
    "or the new one, never a mixture. (**Atomic** means it happens completely or not at all, with nothing\n",
    "in between to be seen.) If the run dies first, the target is untouched and the temporary file is\n",
    "removed, by the `finally:` part, which runs whether or not there was an error:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "complete export: 11,761 rows\n",
      "ERROR crashed: died after writing 4,000 rows\n",
      "after the crash: 11,761 rows, temporary file left behind: False\n"
     ]
    }
   ],
   "source": [
    "def write_csv_atomic(table: pd.DataFrame, path: Path, crash_after: int | None = None) -> None:\n",
    "    \"\"\"Write a table as CSV so that readers only ever see the old file or the complete new one.\n",
    "\n",
    "    Args:\n",
    "        table: What to write.\n",
    "        path: The file to write.\n",
    "        crash_after: Simulate a crash after this many rows (for the lesson).\n",
    "    \"\"\"\n",
    "    tmp = path.with_name(path.name + \".tmp\")\n",
    "    try:\n",
    "        with open(tmp, \"w\", newline=\"\", encoding=\"utf-8\") as handle:\n",
    "            write_rows(handle, table, crash_after)\n",
    "            handle.flush()\n",
    "            os.fsync(handle.fileno())  # the bytes are on the disk, not only in memory\n",
    "        os.replace(tmp, path)  # atomic: the old file or the new one, never half of one\n",
    "    finally:\n",
    "        tmp.unlink(missing_ok=True)\n",
    "\n",
    "\n",
    "write_csv_atomic(molecules, export_path)\n",
    "print(f\"complete export: {len(pd.read_csv(export_path)):,} rows\")\n",
    "try:\n",
    "    write_csv_atomic(molecules, export_path, crash_after=CRASH_AFTER_ROWS)\n",
    "except SimulatedCrash as err:\n",
    "    log.error(\"crashed: %s\", err)\n",
    "print(f\"after the crash: {len(pd.read_csv(export_path)):,} rows, \"\n",
    "      f\"temporary file left behind: {export_path.with_name('molecules.csv.tmp').exists()}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same applies to every file a pipeline writes: Parquet files, JSON reports, model files. Two\n",
    "details matter. The temporary file must be in the same folder (a rename between two drives is a\n",
    "copy, which is not atomic). And readers should ignore `*.tmp` files. Object stores (file storage\n",
    "in the cloud, such as Amazon S3) give the same guarantee differently: an upload becomes visible only once it is complete.\n",
    "\n",
    "## 8. Cached results with joblib.Memory\n",
    "\n",
    "Resuming skips finished batches, but sometimes you rerun everything on purpose: a new database, a\n",
    "new export format, a colleague's copy of the pipeline. If a step is expensive (descriptors here;\n",
    "3D conformers, docking or quantum chemistry in real work), computing it again for unchanged input\n",
    "is waste. `joblib.Memory` remembers a function's results on disk, keyed by a **hash** of its arguments (a\n",
    "short code computed from them: the same arguments always give the same hash, different ones almost\n",
    "never do):\n",
    "call it again with the same arguments, in the same run or a later one, and it returns the stored\n",
    "result without running the function. The list `computed` records each time the function body really\n",
    "runs. (`memory.cache` is usually written as a decorator, `@memory.cache`; here it is applied after\n",
    "setting a short name, for the reason in the comment. You do not need that detail to follow the\n",
    "rest: `prepare_batch_cached` simply behaves like `prepare_batch` with a memory.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "first full run: 13 batches computed\n",
      "second full run: 0 batches computed\n",
      "cached results equal the reference: True\n"
     ]
    }
   ],
   "source": [
    "memory = Memory(settings.work_dir / \"cache\", verbose=0)\n",
    "memory.clear(warn=False)  # start the lesson with an empty cache\n",
    "computed = []\n",
    "\n",
    "\n",
    "def prepare_batch_cached(batch: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:\n",
    "    \"\"\"prepare_batch, with its results kept on disk: each different batch is computed once.\"\"\"\n",
    "    computed.append(batch[\"id\"].iloc[0])\n",
    "    return prepare_batch(batch)\n",
    "\n",
    "\n",
    "# joblib names the cache folder after where the function is defined: for a script, its full path,\n",
    "# which can pass Windows' 260-character path limit. A short module name keeps the folder short.\n",
    "prepare_batch_cached.__module__ = \"module10\"\n",
    "prepare_batch_cached = memory.cache(prepare_batch_cached)\n",
    "\n",
    "\n",
    "for name in (\"first\", \"second\"):\n",
    "    path = settings.work_dir / f\"cached-{name}.sqlite\"\n",
    "    path.unlink(missing_ok=True)\n",
    "    before = len(computed)\n",
    "    run_pipeline(source, path, settings.batch_size, prepare_fn=prepare_batch_cached)\n",
    "    print(f\"{name} full run: {len(computed) - before} batches computed\")\n",
    "same = read_tables(settings.work_dir / \"cached-second.sqlite\")[\"molecules\"]\n",
    "print(\"cached results equal the reference:\", same.equals(reference[\"molecules\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The cache lives in `work/cache`, so a new Python session, or tomorrow's run, reuses it too. One\n",
    "warning, which catches out many users: joblib notices when the code of the cached function changes,\n",
    "but **not** when a function it calls changes. If we changed `prepare` (a new descriptor, a fixed\n",
    "bug), `prepare_batch_cached` would keep returning the old results. Clear the cache when the logic\n",
    "changes (`memory.clear()`), or pass a version number as an argument so new logic gets new cache\n",
    "entries. A cache that can return stale chemistry is worse than no cache.\n",
    "\n",
    "## 9. Running a long job on a server or virtual machine\n",
    "\n",
    "*This section cannot run in Colab: its commands are typed into a terminal, first on your own\n",
    "computer and then on a server. Nothing later in the course depends on it, so you can read it now\n",
    "and come back to it when you have a long job to run.*\n",
    "\n",
    "Everything so far makes a crash cheap. The other half is not crashing for silly reasons: a run of\n",
    "two million molecules started on a laptop dies when the lid is closed, and one started in an SSH\n",
    "window on a server dies when the Wi-Fi drops, because a program started in a terminal is ended\n",
    "with that terminal. Long jobs belong on a machine that stays on, in a session that outlives your\n",
    "connection.\n",
    "\n",
    "**Where.** Two kinds of machine are common. Both usually run **Linux**, an operating system like\n",
    "Windows or macOS, used by most servers:\n",
    "\n",
    "- **A shared server**: your group's or department's Linux machine, many users, many cores.\n",
    "- **A virtual machine (VM)**: a computer simulated on someone else's hardware, with its own Linux,\n",
    "  CPUs, memory and disk. Universities' research computing services offer them, and so do the cloud\n",
    "  providers (Google Cloud, Microsoft Azure, Amazon Web Services and others), billed by the hour,\n",
    "  with free tiers and student credits that are enough for this course. You choose its size from the\n",
    "  job: [Module 8](../08-larger-than-memory/) showed how to measure what a run needs in memory.\n",
    "\n",
    "Treat a VM as disposable. Everything needed to rebuild it comes from the repository and its lock\n",
    "file (Module 13: `git clone`, then `uv sync --locked`), the input comes from its source, and the\n",
    "results are copied off before the VM is deleted. A VM you have forgotten keeps costing money, so\n",
    "stop it when the job is done.\n",
    "\n",
    "**How you reach it.** With **SSH** (Secure Shell): a command that logs you in to another computer,\n",
    "so that what you type in your terminal runs there. Windows 10 and 11, macOS and Linux have the\n",
    "`ssh` command built in, and phones have terminal apps. Whoever runs the server or VM gives you\n",
    "its address and your user name.\n",
    "\n",
    "Open a terminal on your own computer (PowerShell on Windows, Terminal on macOS; the course's Start\n",
    "here page shows how), type the first line below with your own user name and address, and press\n",
    "Enter. Everything after a `#` is a comment for you to read, not to type. The first time, `ssh` asks\n",
    "`Are you sure you want to continue connecting (yes/no)?`: type `yes`. It then asks for your\n",
    "password (nothing appears on the screen while you type it; that is normal) unless your server uses\n",
    "a key instead. Once you are in, the prompt changes to show the server's name, for example\n",
    "`you@server:~$`, and **every command from now on runs on the server**, not on your computer.\n",
    "\n",
    "The next three lines are typed there, one at a time. They need Git and uv on the server: if\n",
    "`uv --version` says the command is not found, install uv with the macOS and Linux command on the\n",
    "Start here page. `git clone` prints `Cloning into 'monstrous-learn'...`, `cd` moves into the\n",
    "course's Series 1 folder and prints nothing, and `uv sync --locked` installs exactly the package\n",
    "versions written in the course's lock file, ending with a line like `Installed 136 packages`:\n",
    "\n",
    "```bash\n",
    "ssh you@server.example.org                 # log in (the address is your server's or VM's)\n",
    "git clone https://github.com/David-Alobo/monstrous-learn.git\n",
    "cd monstrous-learn/data-engineering/series-1\n",
    "uv sync --locked                           # the same environment as on your laptop\n",
    "```\n",
    "\n",
    "**tmux keeps the job running when you leave.** tmux starts a terminal session that lives on the\n",
    "server, not in your window: you start the job inside it, *detach* (step out and leave it running),\n",
    "log out, and later log in again and *attach* (step back in) to find it still running, or finished.\n",
    "It is installed on most Linux servers; if not, `sudo apt install tmux` installs it on your own VM\n",
    "(`sudo` runs a command as the machine's administrator, and `apt` is the installer of Ubuntu and\n",
    "Debian Linux). Name one session per job.\n",
    "\n",
    "Type the commands below on the server, in the `series-1` folder you moved into above. What each\n",
    "one does and what you see:\n",
    "\n",
    "- `tmux new -s library` starts a session called \"library\". The screen clears and a coloured bar\n",
    "  with `[library]` appears at the bottom: you are now inside tmux.\n",
    "- `mkdir -p work` makes the folder the log goes in (nothing is printed; `-p` means \"no error if it\n",
    "  is already there\").\n",
    "- The long command runs the job. The `\\` at the end of its first line means \"the command carries on\n",
    "  on the next line\", so type both lines (or type it as one line without the `\\`).\n",
    "  `CHEMRUN_N_MOLECULES=1000000` in front sets that environment variable for this one command, so\n",
    "  section 2's settings read a library of a million molecules. The `|` (a \"pipe\") passes everything\n",
    "  the job prints to `tee`, which shows it on the screen and also adds it (`-a`, append) to\n",
    "  `work/run.log`. You see the job's log lines appear, like this lesson's outputs. Here the\n",
    "  lesson's own script stands in for your pipeline.\n",
    "- To detach, hold Ctrl and press b, let go, then press d. The bar disappears and you are back at\n",
    "  the normal prompt; the job carries on. You can now log out with `exit`, or close the window.\n",
    "- Later, after logging in again with `ssh` and moving into the `series-1` folder with `cd`,\n",
    "  `tmux ls` lists the sessions still running, for example `library: 1 windows (created ...)`.\n",
    "  `tmux attach -t library` takes you back into the session, where you see the job's latest lines.\n",
    "  Instead of attaching, `tail -f work/run.log` shows the end of the log and keeps adding new lines\n",
    "  as they are written; Ctrl and c stops following (it does not stop the job).\n",
    "\n",
    "```bash\n",
    "tmux new -s library        # a new session called \"library\"; you are now inside it\n",
    "mkdir -p work              # the folder the log goes in\n",
    "\n",
    "# inside tmux: run the job (here the lesson's script stands in for your pipeline), with its log going to a file as well as the screen\n",
    "CHEMRUN_N_MOLECULES=1000000 uv run python 10-pipelines-that-survive-failure/code.py \\\n",
    "    2>&1 | tee -a work/run.log\n",
    "\n",
    "# press Ctrl-b, then d, to detach: the job keeps running and you can log out\n",
    "\n",
    "tmux ls                    # later: which sessions are running?\n",
    "tmux attach -t library     # go back into the session\n",
    "tail -f work/run.log       # or follow the log without attaching (Ctrl-c stops following)\n",
    "```\n",
    "\n",
    "Three details. The settings come from the environment, so the same `code.py` runs the full\n",
    "library on the server and the small one on your laptop (section 2 checks them before any work\n",
    "starts). `2>&1` matters: a program has two output channels, *stdout* for normal output and\n",
    "*stderr* for messages and errors. Python's `logging` writes to stderr, and `2>&1` sends it into\n",
    "stdout, so without it the log lines would reach the screen but not the file. And on a server, add\n",
    "the time to every log line (`format=\"%(asctime)s %(levelname)s %(message)s\"`, as the comment in the\n",
    "Setup block says): \"ERROR at batch 1,412\" means far more next to the time it happened.\n",
    "\n",
    "If tmux is not available, `nohup` gives the minimum: the job survives the logout, but you cannot\n",
    "reattach to it. Type the line below on the server, in the `series-1` folder. `>> work/run.log`\n",
    "adds everything the job prints to the log file instead of the screen, and the `&` at the end runs\n",
    "the job in the background, so the prompt comes back at once, usually after a line such as\n",
    "`[1] 48213` (the job's number and its process id). Follow its progress with\n",
    "`tail -f work/run.log`.\n",
    "\n",
    "```bash\n",
    "nohup uv run python 10-pipelines-that-survive-failure/code.py >> work/run.log 2>&1 &\n",
    "```\n",
    "\n",
    "**Be a good neighbour on a shared machine.** Run long jobs at low priority with `nice`, so other\n",
    "people's interactive work stays fast, and give them a memory limit, so a job that grows too large\n",
    "is stopped on its own instead of making the whole machine *swap* (use the disk as slow extra\n",
    "memory, which slows everyone down) or kill other people's processes. On Linux with systemd (the\n",
    "part of Linux that starts and looks after programs, in most current versions) one command does\n",
    "both. In it, `MemoryMax=32G` stops the job if it uses more than 32 GB of memory, `MemorySwapMax=0`\n",
    "forbids swapping, and `nice -n 19` gives it the lowest priority. Type it on the server, in the\n",
    "`series-1` folder, inside a tmux session, in place of the plain `uv run` command above. Nothing is\n",
    "printed on the screen, because the output goes to the log; detach and follow it with\n",
    "`tail -f work/run.log`:\n",
    "\n",
    "```bash\n",
    "systemd-run --user --scope -p MemoryMax=32G -p MemorySwapMax=0 \\\n",
    "    nice -n 19 uv run python 10-pipelines-that-survive-failure/code.py >> work/run.log 2>&1\n",
    "```\n",
    "\n",
    "Ask your server's administrators what limits they expect; on a VM of your own the machine is yours,\n",
    "but a memory limit still keeps your SSH session alive when the job runs out of memory.\n",
    "\n",
    "**When it dies anyway** (the server restarts, the memory limit is reached), attach, read the end of\n",
    "the log, fix the cause if there is one, and run *the same command again*: the checkpoints of\n",
    "section 6 skip the finished batches and the run carries on from the last good one. (That is true of\n",
    "a pipeline built like `run_pipeline`. The lesson's `code.py` is only a stand-in: it deletes its\n",
    "databases at the start on purpose, so that its outputs match the page, and so it starts again from\n",
    "the beginning.) tmux and a resumable pipeline are made for each other. What tmux does not do is\n",
    "start jobs for you: a job that must run every Monday, or after another job finishes, needs a\n",
    "scheduler or an orchestrator (a program that runs jobs in the right order and keeps track of\n",
    "them), which is Module 15.\n",
    "\n",
    "## 10. The same ideas in industry tools\n",
    "\n",
    "Everything in this module is what workflow tools (programs that run a pipeline's steps for you and\n",
    "keep track of them) do for you at scale. Prefect, Dagster and Airflow\n",
    "let you declare retries with back-off on each task, cache task results by their inputs, and record\n",
    "which tasks of a run finished so a failed run resumes from the failure. dlt, a loading library,\n",
    "keeps the state of each load and merges rows by key. Series 2 swaps such tools in (dlt, dbt, a tool\n",
    "for building tables with SQL, and Prefect); the ideas you need to judge them are the ones built here:\n",
    "\n",
    "- check the settings first, and fail before any work is done;\n",
    "- retry what is transient, with back-off and jitter and a limit; quarantine what is permanent;\n",
    "- cut the work into batches with a fixed order, write them idempotently, and checkpoint them;\n",
    "- write files atomically;\n",
    "- cache expensive steps, and know what makes the cache stale;\n",
    "- run long jobs where they outlive your connection, at low priority and with a memory limit.\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",
    "- 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. Chapters 7 (transactions) and 11 (stream processing: idempotence and\n",
    "  exactly-once).\n",
    "- Beyer, B., Jones, C., Petoff, J. & Murphy, N. R. (eds.) (2016). *Site Reliability Engineering*.\n",
    "  O'Reilly Media. Chapter 22, Addressing Cascading Failures (retries, back-off and jitter).\n",
    "  <https://sre.google/sre-book/addressing-cascading-failures/>\n",
    "- Brooker, M. (2015). Exponential backoff and jitter. *AWS Architecture Blog*, 4 March 2015.\n",
    "  <https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/>\n",
    "- The tenacity documentation. <https://tenacity.readthedocs.io/en/latest/>\n",
    "- The pydantic-settings documentation. *Settings Management*.\n",
    "  <https://docs.pydantic.dev/latest/concepts/pydantic_settings/>\n",
    "- The joblib documentation. *Disk-based caching* (the Memory class).\n",
    "  <https://joblib.readthedocs.io/en/stable/user_guide/memory.html>\n",
    "- The SQLite documentation. *UPSERT*. <https://www.sqlite.org/lang_upsert.html>\n",
    "- The tmux wiki. *Getting Started*. <https://github.com/tmux/tmux/wiki/Getting-Started>\n",
    "- The systemd documentation. *systemd-run*.\n",
    "  <https://www.freedesktop.org/software/systemd/man/latest/systemd-run.html>\n",
    "- Microsoft. *OpenSSH for Windows overview*.\n",
    "  <https://learn.microsoft.com/windows-server/administration/openssh/openssh_overview>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
