{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Incremental ingestion from ChEMBL and PubChem\n",
    "\n",
    "Fetch only what changed from public chemistry APIs, page through them politely within their limits, check every response against a model, load idempotently with a high-water mark, run backfills safely, and keep the licence with the data.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-1/11-incremental-ingestion/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install what this lesson needs (in Colab, or any fresh environment)\n",
    "%pip install -q requests tenacity pydantic duckdb pandas\n",
    "\n",
    "import pathlib\n",
    "import urllib.request\n",
    "if not pathlib.Path(\"recorded/chembl-18d98aadb381.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-18d98aadb381.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/11-incremental-ingestion/recorded/chembl-18d98aadb381.json\", \"recorded/chembl-18d98aadb381.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-1f3c06f5b18a.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-1f3c06f5b18a.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/11-incremental-ingestion/recorded/chembl-1f3c06f5b18a.json\", \"recorded/chembl-1f3c06f5b18a.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-24c302dc3a5c.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-24c302dc3a5c.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/11-incremental-ingestion/recorded/chembl-24c302dc3a5c.json\", \"recorded/chembl-24c302dc3a5c.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-580254e7f564.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-580254e7f564.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/11-incremental-ingestion/recorded/chembl-580254e7f564.json\", \"recorded/chembl-580254e7f564.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-afca8b7881a0.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-afca8b7881a0.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/11-incremental-ingestion/recorded/chembl-afca8b7881a0.json\", \"recorded/chembl-afca8b7881a0.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-b6b39d09ee7c.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-b6b39d09ee7c.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/11-incremental-ingestion/recorded/chembl-b6b39d09ee7c.json\", \"recorded/chembl-b6b39d09ee7c.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-e8a75370061f.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-e8a75370061f.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/11-incremental-ingestion/recorded/chembl-e8a75370061f.json\", \"recorded/chembl-e8a75370061f.json\")\n",
    "if not pathlib.Path(\"recorded/pubchem-0888f35b1588.json\").exists():\n",
    "    pathlib.Path(\"recorded/pubchem-0888f35b1588.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/11-incremental-ingestion/recorded/pubchem-0888f35b1588.json\", \"recorded/pubchem-0888f35b1588.json\")\n",
    "if not pathlib.Path(\"recorded/pubchem-b494565c0c2b.json\").exists():\n",
    "    pathlib.Path(\"recorded/pubchem-b494565c0c2b.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/11-incremental-ingestion/recorded/pubchem-b494565c0c2b.json\", \"recorded/pubchem-b494565c0c2b.json\")\n",
    "if not pathlib.Path(\"recorded/pubchem-dea485fa77e4.json\").exists():\n",
    "    pathlib.Path(\"recorded/pubchem-dea485fa77e4.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/11-incremental-ingestion/recorded/pubchem-dea485fa77e4.json\", \"recorded/pubchem-dea485fa77e4.json\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Most chemical data a company uses is not made in-house. Bioactivity values come from ChEMBL,\n",
    "structures and properties from PubChem, and both grow every release. Both can be read by programs\n",
    "through an **API** (application programming interface): a web address that answers a program's\n",
    "request with data instead of a web page for people. Reading data from a source into your own\n",
    "database is called **ingestion**.\n",
    "\n",
    "A pipeline that downloads everything again every night is slow, puts needless load on services\n",
    "that are free and shared, and cannot tell you what is new. Industry pipelines load\n",
    "**incrementally**: they remember how far they got (a **high-water mark**, like the line a flood\n",
    "leaves on a wall), ask only for what came after it, and write in a way that makes a repeated\n",
    "request harmless. They are also defensive about the source: an API can change its fields, send a\n",
    "value as text, or fail for an hour, and the pipeline must notice instead of filling the database\n",
    "with nonsense.\n",
    "\n",
    "This module loads IC50 values for one kinase, IKK-epsilon (ChEMBL target CHEMBL3529, an\n",
    "inflammation and oncology target), from the ChEMBL web services, and compound properties from\n",
    "PubChem. To make the lesson run offline and give the same output every time, it replays responses\n",
    "recorded from the real services; one switch makes it call them live instead. (pChEMBL, which\n",
    "appears throughout, is ChEMBL's way of putting IC50 and similar values on one scale: −log10 of the\n",
    "value in mol/L, so 1 µM is 6 and 10 nM is 8.)\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- ask ChEMBL and PubChem for data politely: say who you are, give up on an answer that never\n",
    "  comes, keep to a number of requests per second, and try again when the service is only busy;\n",
    "- save real answers once and replay them, so the code can be tested without the internet;\n",
    "- fetch a large result one page at a time, and know where that can go wrong;\n",
    "- check every record against a written description of what it must look like, so a change in\n",
    "  the service stops the run with a clear message;\n",
    "- fetch only the records added since the last run, store them so that fetching one twice does no\n",
    "  harm, and fetch an older range again on purpose when it needs fixing;\n",
    "- say under which licence each source's data may be used, and keep that with the stored data.\n",
    "\n",
    "From earlier modules we use the retries with back-off, upserts, quarantine and atomic writes of\n",
    "[Module 10](../10-pipelines-that-survive-failure/), and DuckDB from\n",
    "[Module 8](../08-larger-than-memory/). Module 10 is the one to have done first.\n",
    "\n",
    "The lesson uses these packages:\n",
    "\n",
    "- **requests** sends requests to web services and receives their answers;\n",
    "- **tenacity** tries a failed request again, with waits in between (as in Module 10);\n",
    "- **Pydantic** checks each record against a model of what it must look like;\n",
    "- **DuckDB** is a database kept in one file, good at answering questions about whole tables;\n",
    "- **pandas** prints query results as tables.\n",
    "\n",
    "The answers the services gave are saved as small JSON files (JSON is a text format for nested lists\n",
    "and dictionaries, the format most web services answer in) in the module's `recorded/` folder, made\n",
    "by the module's `record.py` script. In Colab the first cell downloads them next to the notebook.\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 query itself, and the ids the lesson's runs use, stay with the sections that explain them.\n",
    "Leave `LIVE = False` for now: the lesson then needs no internet and prints what the page shows.\n",
    "Section 2 explains the settings for being polite to the services."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import hashlib\n",
    "import json\n",
    "import logging\n",
    "import math\n",
    "import time\n",
    "from collections import Counter\n",
    "from collections.abc import Callable, Iterator\n",
    "from pathlib import Path\n",
    "from typing import Any\n",
    "from urllib.parse import parse_qsl, urlencode, urljoin, urlsplit, urlunsplit\n",
    "\n",
    "import duckdb\n",
    "import requests\n",
    "from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator\n",
    "from tenacity import (\n",
    "    RetryCallState,\n",
    "    Retrying,\n",
    "    retry_if_exception_type,\n",
    "    stop_after_attempt,\n",
    "    wait_random_exponential,\n",
    ")\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",
    "LIVE = False  # False: replay the recorded responses. True: call ChEMBL and PubChem for real.\n",
    "\n",
    "# files\n",
    "RECORDED = Path(\"recorded\")  # the recorded responses (made by record.py)\n",
    "WORK = Path(\"work\")  # every file the lesson writes goes here\n",
    "CACHE = WORK / \"http-cache\"  # live responses are kept here, so a rerun asks again for nothing\n",
    "DB_PATH = WORK / \"ingest.duckdb\"  # the database the lesson loads\n",
    "\n",
    "# being polite to the services\n",
    "USER_AGENT = \"chem-ingest-tutorial/1.0 (mailto:you@example.org)\"  # put your own contact here\n",
    "TIMEOUT = (10, 60)  # seconds to connect, seconds to wait for the answer\n",
    "CHEMBL_PER_SECOND = 2  # requests per second to ChEMBL (our own, conservative choice)\n",
    "PUBCHEM_PER_SECOND = 5  # requests per second to PubChem (the most its usage policy allows)\n",
    "TRANSIENT_STATUS = {429, 500, 502, 503, 504}  # HTTP statuses worth retrying\n",
    "MAX_ATTEMPTS = 5  # requests in all before a transient failure is given up\n",
    "MAX_WAIT_S = 60  # the longest wait between retries, in seconds\n",
    "\n",
    "# the services\n",
    "CHEMBL_HOST = \"https://www.ebi.ac.uk\"\n",
    "CHEMBL_ACTIVITY = f\"{CHEMBL_HOST}/chembl/api/data/activity.json\"\n",
    "PAGE_SIZE = 100  # ChEMBL records per page (its `limit`)\n",
    "PUBCHEM_PROPERTIES = (\"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cids}\"\n",
    "                      \"/property/Title,MolecularFormula,MolecularWeight,SMILES,InChIKey/JSON\")\n",
    "CHUNK_SIZE = 5  # CIDs per PubChem request: 5 to show the chunking, hundreds in real use\n",
    "\n",
    "# the source and licence stored with every row (section 1)\n",
    "SOURCE_CHEMBL = \"ChEMBL (CC BY-SA 3.0)\"\n",
    "SOURCE_PUBCHEM = \"PubChem (NCBI: no restrictions on use)\"\n",
    "\n",
    "WORK.mkdir(exist_ok=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Before you download: licences\n",
    "\n",
    "Public does not mean free of conditions. Check the licence of every source before the first\n",
    "request, and store it with the data, because the person who uses a table in two years will not\n",
    "know where it came from.\n",
    "\n",
    "- **ChEMBL** data are made available under the **Creative Commons Attribution-ShareAlike 3.0\n",
    "  Unported licence** (CC BY-SA 3.0; *Attribution* means you must credit the source, *ShareAlike*\n",
    "  that what you build from it must be shared under the same terms), as stated on the ChEMBL website. You may use, change and\n",
    "  redistribute them, including commercially, if you credit ChEMBL and, when you share a database\n",
    "  derived from them, share it under the same licence.\n",
    "- **PubChem** is run by NCBI, whose policy is that NCBI \"places no restrictions on the use or\n",
    "  distribution of the data\", while noting that some submitters may claim rights in what they\n",
    "  submitted. PubChem asks to be cited.\n",
    "\n",
    "Both ask to be cited in publications (the papers are in the further reading). In the tables below,\n",
    "every row carries a `source` column saying where it came from and under which licence.\n",
    "\n",
    "## 2. A polite client\n",
    "\n",
    "ChEMBL and PubChem are free services shared by everyone. A program talks to them with **HTTP**,\n",
    "the same way a web browser does: it sends a **request** for a web address (a URL), and the service\n",
    "sends back a **response** with a **status code**, a number saying how it went, and a body, here\n",
    "JSON. The codes that matter here: 200 means success; 400 to 499 mean the request was wrong (404:\n",
    "\"not found\"; 429: \"too many requests\", slow down); 500 to 599 mean the service itself failed (503:\n",
    "\"unavailable for now\"). PubChem's usage policy asks that no user make more than 5 requests per\n",
    "second, and it rejects requests above its limits with HTTP 503; users who keep exceeding them are\n",
    "blocked for a while. A program that sends requests is called a **client**. A polite client does\n",
    "four things:\n",
    "\n",
    "- says who it is, in a **User-Agent** header (a line of information sent with each request), with\n",
    "  a contact address, so the service can contact you rather than block you;\n",
    "- sets a **timeout**, so a request that hangs does not hang the pipeline for ever;\n",
    "- keeps to a **rate limit**, by waiting before a request if the last one was too recent;\n",
    "- **retries** transient failures (429 \"too many requests\", and 500, 502, 503, 504) with\n",
    "  exponential back-off and jitter, as in Module 10, and does not retry the others: a 404 or a 400\n",
    "  means the request is wrong, and asking again will not fix it.\n",
    "\n",
    "The rate limiter takes its clock and its sleep function as arguments, so here it runs on a pretend\n",
    "clock and the lesson does not have to wait. It remembers the earliest time the next request is\n",
    "allowed (`next_allowed`, which starts at minus infinity, `-math.inf`, so the first request never\n",
    "waits). Before each request, `wait()` sleeps until that time if it has not come yet, then moves it\n",
    "one interval (0.2 s at five per second) further on. `time.monotonic` is a clock that only ever goes\n",
    "forward, which is what you want for measuring gaps; `for _ in range(12)` repeats 12 times, the `_`\n",
    "saying we do not need the loop's counter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "12 requests sent at (s): [0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2]\n"
     ]
    }
   ],
   "source": [
    "class RateLimiter:\n",
    "    \"\"\"Allow at most `per_second` requests per second, by waiting before a request when needed.\"\"\"\n",
    "\n",
    "    def __init__(self, per_second: float, clock: Callable[[], float] = time.monotonic,\n",
    "                 sleep: Callable[[float], None] = time.sleep) -> None:\n",
    "        self.interval = 1 / per_second\n",
    "        self.clock = clock\n",
    "        self.sleep = sleep\n",
    "        self.next_allowed = -math.inf\n",
    "\n",
    "    def wait(self) -> None:\n",
    "        \"\"\"Wait until the next request is allowed, then reserve the slot after it.\"\"\"\n",
    "        now = self.clock()\n",
    "        if now < self.next_allowed:\n",
    "            self.sleep(self.next_allowed - now)\n",
    "            now = self.next_allowed\n",
    "        self.next_allowed = now + self.interval\n",
    "\n",
    "\n",
    "class PretendClock:\n",
    "    \"\"\"A clock that only moves when something sleeps: for showing waits without waiting.\"\"\"\n",
    "\n",
    "    def __init__(self) -> None:\n",
    "        self.now = 0.0\n",
    "\n",
    "    def time(self) -> float:\n",
    "        \"\"\"The current pretend time, in seconds.\"\"\"\n",
    "        return self.now\n",
    "\n",
    "    def sleep(self, seconds: float) -> None:\n",
    "        \"\"\"Move the pretend time on.\"\"\"\n",
    "        self.now += seconds\n",
    "\n",
    "\n",
    "clock = PretendClock()\n",
    "limiter = RateLimiter(per_second=PUBCHEM_PER_SECOND, clock=clock.time, sleep=clock.sleep)\n",
    "sent = []\n",
    "for _ in range(12):\n",
    "    limiter.wait()\n",
    "    sent.append(round(clock.now, 1))\n",
    "print(\"12 requests sent at (s):\", sent)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Twelve requests at five per second take 2.2 seconds; without the limiter a loop would send them in\n",
    "a few milliseconds. In live use there is one limiter per service: 5 per second for PubChem, as its\n",
    "policy asks, and 2 per second for ChEMBL, a conservative choice of ours.\n",
    "\n",
    "Now the request itself, with tenacity retrying what is transient. A `requests.Session` keeps one\n",
    "connection to a service open across many requests, which is faster than opening a new one each\n",
    "time; `session.get(url, ...)` sends one request. `urlsplit(url).netloc` picks the host name out of\n",
    "a URL (`www.ebi.ac.uk` from `https://www.ebi.ac.uk/chembl/...`), so each service gets its own rate\n",
    "limiter. The function takes the session as an argument so we can try it against a pretend server\n",
    "that answers with chosen status codes, first two transient failures and then success, then a 404.\n",
    "\n",
    "In Module 10 tenacity was used as a decorator. Here it is written as a loop instead, with\n",
    "`Retrying`, imported in the Setup block: `for attempt in retrying:` followed by `with attempt:`\n",
    "runs the block inside once per attempt; if the block raises one of the errors named in `retry=`,\n",
    "tenacity waits and goes round again, and once the block returns, the loop ends. You can read it as\n",
    "\"try this, up to five times\". `before_sleep=log_retry` is a function tenacity calls before each\n",
    "wait: each retry is logged as a warning, because someone reading a nightly job's log wants to know\n",
    "a service was struggling, even when it recovered. `response.raise_for_status()` raises an error\n",
    "for any status of 400 or more, and `response.json()` turns the JSON body into Python lists and\n",
    "dictionaries:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "WARNING attempt 1 failed (HTTP 503 from example.org); retrying\n",
      "WARNING attempt 2 failed (HTTP 429 from example.org); retrying\n",
      "{'answer': 'the data'} after 3 requests\n",
      "ERROR not retried (1 request): 404 Client Error\n"
     ]
    }
   ],
   "source": [
    "SESSION = requests.Session()\n",
    "LIMITERS = {urlsplit(CHEMBL_HOST).netloc: RateLimiter(CHEMBL_PER_SECOND),\n",
    "            urlsplit(PUBCHEM_PROPERTIES).netloc: RateLimiter(PUBCHEM_PER_SECOND)}\n",
    "\n",
    "\n",
    "class TransientHTTPError(Exception):\n",
    "    \"\"\"A response worth retrying: rate limited, or the server failed.\"\"\"\n",
    "\n",
    "\n",
    "def log_retry(state: RetryCallState) -> None:\n",
    "    \"\"\"Log a failed attempt before tenacity waits and tries again.\"\"\"\n",
    "    log.warning(\"attempt %d failed (%s); retrying\", state.attempt_number,\n",
    "                state.outcome.exception())\n",
    "\n",
    "\n",
    "def polite_get(url: str, session: Any = SESSION, limiter: RateLimiter | None = None,\n",
    "               sleep: Callable[[float], None] = time.sleep) -> dict:\n",
    "    \"\"\"GET a URL politely and return its JSON, retrying transient failures with back-off.\n",
    "\n",
    "    Args:\n",
    "        url: The full URL.\n",
    "        session: The HTTP session: a requests.Session, or anything with the same `get`.\n",
    "        limiter: The rate limiter for the URL's service (by default, the one for its host).\n",
    "        sleep: How to wait between retries.\n",
    "\n",
    "    Returns:\n",
    "        The response's JSON.\n",
    "\n",
    "    Raises:\n",
    "        requests.HTTPError: For a permanent failure (4xx other than 429), at once.\n",
    "        TransientHTTPError: If every attempt failed.\n",
    "    \"\"\"\n",
    "    limiter = limiter or LIMITERS[urlsplit(url).netloc]\n",
    "    retrying = Retrying(\n",
    "        retry=retry_if_exception_type(\n",
    "            (TransientHTTPError, requests.ConnectionError, requests.Timeout)\n",
    "        ),\n",
    "        stop=stop_after_attempt(MAX_ATTEMPTS),\n",
    "        wait=wait_random_exponential(multiplier=1, max=MAX_WAIT_S),\n",
    "        before_sleep=log_retry,\n",
    "        sleep=sleep,\n",
    "        reraise=True,\n",
    "    )\n",
    "    for attempt in retrying:\n",
    "        with attempt:\n",
    "            limiter.wait()\n",
    "            response = session.get(url, headers={\"User-Agent\": USER_AGENT}, timeout=TIMEOUT)\n",
    "            if response.status_code in TRANSIENT_STATUS:\n",
    "                raise TransientHTTPError(f\"HTTP {response.status_code} from {urlsplit(url).netloc}\")\n",
    "            response.raise_for_status()  # any other 4xx or 5xx: permanent, raised at once\n",
    "            return response.json()\n",
    "\n",
    "\n",
    "class PretendResponse:\n",
    "    \"\"\"Just enough of a requests.Response for polite_get.\"\"\"\n",
    "\n",
    "    def __init__(self, status_code: int) -> None:\n",
    "        self.status_code = status_code\n",
    "\n",
    "    def json(self) -> dict:\n",
    "        \"\"\"The body.\"\"\"\n",
    "        return {\"answer\": \"the data\"}\n",
    "\n",
    "    def raise_for_status(self) -> None:\n",
    "        \"\"\"Raise for 4xx and 5xx, like requests does.\"\"\"\n",
    "        if self.status_code >= 400:\n",
    "            raise requests.HTTPError(f\"{self.status_code} Client Error\")\n",
    "\n",
    "\n",
    "class PretendServer:\n",
    "    \"\"\"Answers each request with the next status code from a list.\"\"\"\n",
    "\n",
    "    def __init__(self, statuses: list[int]) -> None:\n",
    "        self.statuses = list(statuses)\n",
    "        self.requests = 0\n",
    "\n",
    "    def get(self, url: str, headers: dict, timeout: tuple[float, float]) -> PretendResponse:\n",
    "        \"\"\"Answer one request (the arguments are those of requests.Session.get, unused here).\"\"\"\n",
    "        self.requests += 1\n",
    "        return PretendResponse(self.statuses.pop(0))\n",
    "\n",
    "\n",
    "quiet = RateLimiter(PUBCHEM_PER_SECOND, clock=clock.time, sleep=clock.sleep)\n",
    "server = PretendServer([503, 429, 200])\n",
    "answer = polite_get(\"https://example.org/x\", server, quiet, sleep=clock.sleep)\n",
    "print(f\"{answer} after {server.requests} requests\")\n",
    "\n",
    "server = PretendServer([404])\n",
    "try:\n",
    "    polite_get(\"https://example.org/x\", server, quiet, sleep=clock.sleep)\n",
    "except requests.HTTPError as err:\n",
    "    log.error(\"not retried (%d request): %s\", server.requests, err)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The pretend server answered 503 and 429, which were retried, then 200, and the data came back. The\n",
    "404 was raised at once, after one request.\n",
    "\n",
    "Servers that are overloaded sometimes say how long to wait in a `Retry-After` header; a client that\n",
    "honours it is more polite still. tenacity's `wait` can be any function, so it can read that header.\n",
    "\n",
    "## 3. Record and replay\n",
    "\n",
    "Tests and lessons should not depend on a web service being up, being fast, or returning the same\n",
    "data as yesterday. (While this module was written, the ChEMBL web services answered some requests\n",
    "with HTTP 500 for long stretches; the retry logic above is not theory.) The industry pattern is **record and\n",
    "replay**: call the real service once, save each response with the request that produced it, and let\n",
    "the code under test read the saved responses. Libraries such as vcrpy and pytest-recording do this\n",
    "for test suites (collections of automatic checks on code); here it is in a few lines.\n",
    "\n",
    "A request to these services is a URL with **query parameters** after a `?`, such as\n",
    "`activity.json?target_chembl_id=CHEMBL3529&limit=100`: each `name=value` pair, joined by `&`, says\n",
    "what we want. The same request can be written with its parameters in any order, so every request\n",
    "is first written in one canonical form, its parameters sorted, and the same request always has the\n",
    "same name on disk. That name comes from a **hash** of the URL: a short code computed from it (the\n",
    "same URL always gives the same code), so the file name is short and safe whatever the URL holds. `fetch_json` is the only function in the module that touches the\n",
    "network. With `LIVE = False` it reads `recorded/`; with `LIVE = True` it calls the service\n",
    "politely and keeps each response in `work/http-cache/` (a disk cache: a second live run makes no\n",
    "requests it has made before). Either way the caller gets the same JSON. `params: dict | None = None`\n",
    "means the argument is a dictionary or `None` (nothing), and is `None` unless given; `{**QUERY,\n",
    "\"limit\": \"50\"}`, used later, makes a copy of the dictionary `QUERY` with one entry added or changed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO 10 recorded responses, 171 KiB in all\n"
     ]
    }
   ],
   "source": [
    "def canonical_url(url: str, params: dict | None = None) -> str:\n",
    "    \"\"\"One spelling for a request: an absolute URL with its query parameters sorted.\n",
    "\n",
    "    Args:\n",
    "        url: The URL, absolute or a path on the ChEMBL host (as in ChEMBL's `next` links).\n",
    "        params: Extra query parameters.\n",
    "\n",
    "    Returns:\n",
    "        The canonical URL.\n",
    "    \"\"\"\n",
    "    parts = urlsplit(urljoin(CHEMBL_HOST, url))\n",
    "    query = sorted(parse_qsl(parts.query) + [(k, str(v)) for k, v in (params or {}).items()])\n",
    "    return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(query), \"\"))\n",
    "\n",
    "\n",
    "def recording_name(url: str) -> str:\n",
    "    \"\"\"The file a canonical URL is recorded under: the service and a hash of the URL.\"\"\"\n",
    "    service = \"chembl\" if \"ebi.ac.uk\" in url else \"pubchem\"\n",
    "    return f\"{service}-{hashlib.sha256(url.encode()).hexdigest()[:12]}.json\"\n",
    "\n",
    "\n",
    "requests_made = []\n",
    "\n",
    "\n",
    "def fetch_json(url: str, params: dict | None = None) -> dict:\n",
    "    \"\"\"The JSON for a request: replayed from recorded/, or fetched live and cached on disk.\n",
    "\n",
    "    Args:\n",
    "        url: The URL.\n",
    "        params: Its query parameters.\n",
    "\n",
    "    Returns:\n",
    "        The response's JSON, the same in both modes.\n",
    "    \"\"\"\n",
    "    url = canonical_url(url, params)\n",
    "    requests_made.append(url)\n",
    "    name = recording_name(url)\n",
    "    if not LIVE:\n",
    "        path = RECORDED / name\n",
    "        if not path.exists():\n",
    "            raise FileNotFoundError(f\"{url} was never recorded: run record.py\")\n",
    "        return json.loads(path.read_text(encoding=\"utf-8\"))[\"body\"]\n",
    "    cached = CACHE / name\n",
    "    if cached.exists():\n",
    "        return json.loads(cached.read_text(encoding=\"utf-8\"))[\"body\"]\n",
    "    body = polite_get(url)\n",
    "    CACHE.mkdir(parents=True, exist_ok=True)\n",
    "    tmp = cached.with_name(cached.name + \".tmp\")  # an atomic write, as in Module 10\n",
    "    tmp.write_text(json.dumps({\"url\": url, \"body\": body}), encoding=\"utf-8\")\n",
    "    tmp.replace(cached)\n",
    "    return body\n",
    "\n",
    "\n",
    "recordings = sorted(RECORDED.glob(\"*.json\"))\n",
    "size_kib = sum(p.stat().st_size for p in recordings) / 1024\n",
    "log.info(\"%d recorded responses, %.0f KiB in all\", len(recordings), size_kib)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Live mode is not a different program: when this module was written, the whole lesson was also run\n",
    "with `LIVE = True` against the real services, and every output was the same as the replayed one\n",
    "except the line near the end that reports the mode. (Once ChEMBL publishes new IKK-epsilon data,\n",
    "a live run will rightly find more records than the recordings hold.)\n",
    "\n",
    "Each recording holds the URL it answers, the date it was recorded and the body, so it can be read\n",
    "and refreshed by hand. A disk cache in live mode matters for the same reason as Module 10's\n",
    "`joblib.Memory`: a pipeline that crashes at page 40 should not ask the service for pages 1 to 39\n",
    "again when it restarts. Keep in mind what a cache does to freshness: a cached response is as old as\n",
    "the day it was fetched, so production caches have an expiry (hours, or until the next release).\n",
    "\n",
    "## 4. Pages: limit, offset and next\n",
    "\n",
    "ChEMBL never returns a large result in one response. Its activity **endpoint** (the URL that\n",
    "answers questions about activities) returns `limit` records starting at `offset` (the number of\n",
    "records to skip first), plus a `page_meta` block that says how many records match and gives the URL\n",
    "of the next page. So `limit=100&offset=200` asks for records 201 to 300. Here is our query: IC50 values with a\n",
    "pChEMBL value for IKK-epsilon, ordered by `activity_id`, 100 per page, with `only` naming the fields\n",
    "we need (smaller responses, kinder to the server). The page size, `PAGE_SIZE`, is set in the Setup\n",
    "block. In the query, `__isnull`, `__gt` (greater than) and `__lte` (less than or equal) are\n",
    "ChEMBL's way of writing conditions: `\"pchembl_value__isnull\": \"false\"` asks for records that have a\n",
    "pChEMBL value. `json.dumps(..., indent=1)` prints the JSON laid out over several lines:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{\n",
      " \"limit\": 100,\n",
      " \"next\": \"/chembl/api/data/activity.json?limit=100&offset=100&activity_id__gt=0&activity_id__lte=18811464&only=activity_id%2Cmolecule_chembl_id%2Cstandard_type%2Cstandard_relation%2Cstandard_value%2Cstandard_units%2Cpchembl_value%2Cdocument_chembl_id&order_by=activity_id&pchembl_value__isnull=false&standard_type=IC50&target_chembl_id=CHEMBL3529\",\n",
      " \"offset\": 0,\n",
      " \"previous\": null,\n",
      " \"total_count\": 276\n",
      "}\n",
      "{\n",
      " \"activity_id\": 1812436,\n",
      " \"document_chembl_id\": \"CHEMBL1146152\",\n",
      " \"molecule_chembl_id\": \"CHEMBL375787\",\n",
      " \"pchembl_value\": \"6.10\",\n",
      " \"relation\": \"=\",\n",
      " \"standard_relation\": \"=\",\n",
      " \"standard_type\": \"IC50\",\n",
      " \"standard_units\": \"nM\",\n",
      " \"standard_value\": \"794.33\",\n",
      " \"type\": \"Log IC50\",\n",
      " \"units\": null,\n",
      " \"value\": \"-6.1\"\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "QUERY = {\n",
    "    \"target_chembl_id\": \"CHEMBL3529\",  # IKK-epsilon\n",
    "    \"standard_type\": \"IC50\",\n",
    "    \"pchembl_value__isnull\": \"false\",\n",
    "    \"order_by\": \"activity_id\",\n",
    "    \"only\": \"activity_id,molecule_chembl_id,standard_type,standard_relation,standard_value,\"\n",
    "    \"standard_units,pchembl_value,document_chembl_id\",\n",
    "    \"limit\": str(PAGE_SIZE),\n",
    "}\n",
    "FIRST_RUN_CUTOFF = 18811464  # explained in section 6\n",
    "\n",
    "page = fetch_json(CHEMBL_ACTIVITY,\n",
    "                  {**QUERY, \"activity_id__gt\": \"0\", \"activity_id__lte\": str(FIRST_RUN_CUTOFF)})\n",
    "print(json.dumps(page[\"page_meta\"], indent=1))\n",
    "print(json.dumps(page[\"activities\"][0], indent=1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Two things to notice in the record. Numbers arrive as text (`\"standard_value\": \"794.33\"`), so\n",
    "something must turn them into numbers and complain if one is not. And the response holds fields we\n",
    "did not ask for: services add fields over time, which a loader should ignore rather than fail on.\n",
    "\n",
    "Following `next` until it is empty walks through every page. `pages` is a **generator**: instead\n",
    "of `return`, it has `yield`, which hands one page to the `for` loop that is using it and pauses\n",
    "until the loop asks for the next one. So only one page is fetched and held at a time, and the loop\n",
    "can stop early. (`Iterator[dict]` in the type hint says \"gives dictionaries one at a time\"; in the\n",
    "`print`, `{meta['offset']:>3}` writes the offset right-aligned in three characters.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "offset   0: 100 records, next page: yes\n",
      "offset 100: 100 records, next page: yes\n",
      "offset 200: 76 records, next page: none\n"
     ]
    }
   ],
   "source": [
    "def pages(params: dict) -> Iterator[dict]:\n",
    "    \"\"\"Every page of a ChEMBL activity query, following page_meta.next.\n",
    "\n",
    "    Args:\n",
    "        params: The query.\n",
    "\n",
    "    Yields:\n",
    "        One page (the parsed JSON) at a time.\n",
    "    \"\"\"\n",
    "    url, extra = CHEMBL_ACTIVITY, params\n",
    "    while url:\n",
    "        page = fetch_json(url, extra)\n",
    "        yield page\n",
    "        url, extra = page[\"page_meta\"][\"next\"], None\n",
    "\n",
    "\n",
    "for each in pages({**QUERY, \"activity_id__gt\": \"0\", \"activity_id__lte\": str(FIRST_RUN_CUTOFF)}):\n",
    "    meta = each[\"page_meta\"]\n",
    "    print(f\"offset {meta['offset']:>3}: {len(each['activities'])} records, next page: \"\n",
    "          f\"{'yes' if meta['next'] else 'none'}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Paging through a result of 276 records 100 at a time: each page's page_meta gives the next page's offset until next is empty; below, how offset paging returns a record twice when a new record is inserted before the offset between two requests, and how asking for activity_id greater than the last one seen avoids it](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/11-incremental-ingestion/figures/pagination.svg)\n",
    "\n",
    "Offset paging has one weakness: the offset counts positions, not records. If records are added or\n",
    "removed while you page, everything after the change shifts, and a record can be skipped or seen\n",
    "twice. ChEMBL's data change only between releases, so paging through a result in one go is safe.\n",
    "For a source that changes all the time, **keyset paging** is safer: order by a key and ask for\n",
    "records after the last key you saw (`activity_id__gt=…`), which is exactly what the high-water mark\n",
    "in section 6 does between runs.\n",
    "\n",
    "## 5. Check every record at the door\n",
    "\n",
    "A loader (the part of a pipeline that stores what it fetched) that trusts its source stores\n",
    "whatever arrives. If ChEMBL renamed `molecule_chembl_id`\n",
    "tomorrow, or a value arrived as `\"n/a\"`, such a loader would store empty or broken rows, and the\n",
    "first person to notice would be a chemist whose model behaves strangely months later. A **Pydantic\n",
    "model** states what a record must look like; every record is checked against it before anything\n",
    "is stored. [Module 12](../12-validating-data/) covers Pydantic in depth; here is the model for one activity,\n",
    "with a chemistry check: pChEMBL is −log10 of the molar value, so for a value in nM it must equal\n",
    "9 − log10(value). `BaseModel` and the other Pydantic names are imported in the Setup block.\n",
    "\n",
    "How to read the model, as in Module 10's settings class: each line `name: type` is a field the\n",
    "record must have, with its type. `str | None` means text or nothing (ChEMBL sends `null`, which\n",
    "Python reads as `None`, when a value is missing). `Field(gt=0)` adds a limit (`gt` greater than,\n",
    "`ge` and `le` greater or less than or equal). `Field(pattern=r\"^CHEMBL\\d+$\")` gives a **regular\n",
    "expression**, a pattern the text must match: `^` the start, `CHEMBL` those letters, `\\d+` one or\n",
    "more digits, `$` the end, so `CHEMBL375787` passes and `375787` does not (the `r` before the quotes keeps the backslash\n",
    "as it is). `extra=\"ignore\"` in `model_config` drops fields the model does not list, and\n",
    "`frozen=True` means a checked record cannot be changed afterwards. `@model_validator` marks\n",
    "a check that looks at several fields together. `Activity.model_validate(record)` checks a\n",
    "dictionary and returns an `Activity`, or raises `ValidationError` saying what is wrong."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "activity_id=1812436 molecule_chembl_id='CHEMBL375787' document_chembl_id='CHEMBL1146152' standard_type='IC50' standard_relation='=' standard_value=794.33 standard_units='nM' pchembl_value=6.1\n"
     ]
    }
   ],
   "source": [
    "class Activity(BaseModel):\n",
    "    \"\"\"One ChEMBL bioactivity record, as this pipeline needs it.\"\"\"\n",
    "\n",
    "    model_config = ConfigDict(extra=\"ignore\", frozen=True)  # new fields are ignored, not errors\n",
    "\n",
    "    activity_id: int = Field(gt=0)\n",
    "    molecule_chembl_id: str = Field(pattern=r\"^CHEMBL\\d+$\")\n",
    "    document_chembl_id: str = Field(pattern=r\"^CHEMBL\\d+$\")\n",
    "    standard_type: str\n",
    "    standard_relation: str | None\n",
    "    standard_value: float | None = Field(gt=0)\n",
    "    standard_units: str | None\n",
    "    pchembl_value: float | None = Field(default=None, ge=0, le=15)\n",
    "\n",
    "    @model_validator(mode=\"after\")\n",
    "    def pchembl_agrees_with_value(self) -> \"Activity\":\n",
    "        \"\"\"pChEMBL is -log10(molar value): for nM values it must be 9 - log10(value).\"\"\"\n",
    "        known = self.pchembl_value is not None and self.standard_value is not None\n",
    "        if known and self.standard_units == \"nM\":\n",
    "            expected = 9 - math.log10(self.standard_value)\n",
    "            if abs(expected - self.pchembl_value) > 0.01:\n",
    "                raise ValueError(f\"pchembl_value {self.pchembl_value} but the value gives \"\n",
    "                                 f\"{expected:.2f}\")\n",
    "        return self\n",
    "\n",
    "\n",
    "record = page[\"activities\"][0]\n",
    "activity = Activity.model_validate(record)\n",
    "print(activity)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The text values became numbers, and the fields we do not use were dropped. Now three records that\n",
    "must not get in: a value that is not a number, a record from an API that renamed a field, and a\n",
    "record whose pChEMBL does not match its value. Each broken record is a copy of the good one with\n",
    "one change; the second is built with a **dictionary comprehension**, `{new_key: v for k, v in\n",
    "record.items()}`, which makes a new dictionary from the old one key by key, here renaming one key:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "value is not a number: standard_value: Input should be a valid number, unable to parse string as a number\n",
      "field renamed by the API: molecule_chembl_id: Field required\n",
      "pChEMBL disagrees: record: Value error, pchembl_value 8.1 but the value gives 6.10\n"
     ]
    }
   ],
   "source": [
    "broken = {\n",
    "    \"value is not a number\": {**record, \"standard_value\": \"n/a\"},\n",
    "    \"field renamed by the API\": {k.replace(\"molecule_chembl_id\", \"molecule_id\"): v\n",
    "                                 for k, v in record.items()},\n",
    "    \"pChEMBL disagrees\": {**record, \"pchembl_value\": \"8.10\"},\n",
    "}\n",
    "for label, bad in broken.items():\n",
    "    try:\n",
    "        Activity.model_validate(bad)\n",
    "    except ValidationError as err:\n",
    "        problem = err.errors()[0]\n",
    "        print(f\"{label}: {'.'.join(map(str, problem['loc'])) or 'record'}: {problem['msg']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What to do with a record that fails depends on why. For a curated source like ChEMBL, a record that\n",
    "fails means the API or our understanding of it has changed, so the whole page is refused and the\n",
    "run stops with the error: nothing is stored until a person has looked. For one bad record among\n",
    "good ones, from a source with known messy records, Module 10's quarantine is the better answer;\n",
    "section 8 has an example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def validate_page(page: dict) -> list[Activity]:\n",
    "    \"\"\"Every activity of a page, checked; any invalid record stops the run before storing.\"\"\"\n",
    "    return [Activity.model_validate(record) for record in page[\"activities\"]]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Incremental loads with a high-water mark\n",
    "\n",
    "The data go into DuckDB ([Module 8](../08-larger-than-memory/); [Module 4](../04-databases-and-schemas/) introduces it with the\n",
    "other databases), in two tables: `activities`, keyed by `activity_id`, and\n",
    "`load_state`, one row per source holding its **high-water mark**: the largest `activity_id` loaded\n",
    "so far. Each run asks ChEMBL only for activities above the mark (`activity_id__gt`), upserts them,\n",
    "and moves the mark. The upsert and the new mark are written in one transaction, page by page, so a\n",
    "crash halfway through a run loses at most the page in flight and the next run resumes after the\n",
    "last page stored.\n",
    "\n",
    "The connection stays open across the next few sections and is closed at the end of section 9.\n",
    "\n",
    "The SQL is the same as Module 10's, with DuckDB's types (`BIGINT` for large whole numbers,\n",
    "`VARCHAR` for text, `DOUBLE` for decimals) and `?` as the placeholder for each value, filled in\n",
    "order from a list. `con.begin()` starts a transaction (a group of changes saved together or not at\n",
    "all) and `con.commit()` saves it. The `# fmt: skip` comment only tells the course's code formatter\n",
    "to leave that line's layout alone."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "DB_PATH.unlink(missing_ok=True)\n",
    "con = duckdb.connect(str(DB_PATH))\n",
    "con.execute(\"\"\"\n",
    "    CREATE TABLE activities (\n",
    "        activity_id BIGINT PRIMARY KEY, molecule_chembl_id VARCHAR, document_chembl_id VARCHAR,\n",
    "        standard_type VARCHAR, standard_relation VARCHAR, standard_value DOUBLE,\n",
    "        standard_units VARCHAR, pchembl_value DOUBLE, source VARCHAR);\n",
    "    CREATE TABLE load_state (source VARCHAR PRIMARY KEY, high_water_mark BIGINT);\n",
    "\"\"\")\n",
    "UPSERT = \"\"\"\n",
    "    INSERT INTO activities VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n",
    "    ON CONFLICT (activity_id) DO UPDATE SET\n",
    "        molecule_chembl_id = excluded.molecule_chembl_id,\n",
    "        document_chembl_id = excluded.document_chembl_id,\n",
    "        standard_type = excluded.standard_type, standard_relation = excluded.standard_relation,\n",
    "        standard_value = excluded.standard_value, standard_units = excluded.standard_units,\n",
    "        pchembl_value = excluded.pchembl_value, source = excluded.source\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "def upsert(con: duckdb.DuckDBPyConnection, activities: list[Activity]) -> None:\n",
    "    \"\"\"Insert new activities and overwrite ones already stored (idempotent).\"\"\"\n",
    "    rows = [(a.activity_id, a.molecule_chembl_id, a.document_chembl_id, a.standard_type,\n",
    "             a.standard_relation, a.standard_value, a.standard_units, a.pchembl_value,\n",
    "             SOURCE_CHEMBL) for a in activities]  # fmt: skip\n",
    "    if rows:\n",
    "        con.executemany(UPSERT, rows)\n",
    "\n",
    "\n",
    "def high_water_mark(con: duckdb.DuckDBPyConnection) -> int:\n",
    "    \"\"\"The largest activity_id loaded so far (0 before the first run).\"\"\"\n",
    "    row = con.execute(\"SELECT high_water_mark FROM load_state WHERE source = 'chembl'\").fetchone()\n",
    "    return row[0] if row else 0\n",
    "\n",
    "\n",
    "def load_increment(con: duckdb.DuckDBPyConnection, until: int | None = None) -> str:\n",
    "    \"\"\"Fetch and store every activity above the high-water mark, page by page.\n",
    "\n",
    "    Args:\n",
    "        con: The DuckDB connection.\n",
    "        until: Only for the lesson's first run: ignore activities above this id.\n",
    "\n",
    "    Returns:\n",
    "        A one-line report of the run.\n",
    "    \"\"\"\n",
    "    start = high_water_mark(con)\n",
    "    params = {**QUERY, \"activity_id__gt\": str(start)}\n",
    "    if until is not None:\n",
    "        params[\"activity_id__lte\"] = str(until)\n",
    "    n_pages = n_records = 0\n",
    "    for page in pages(params):\n",
    "        activities = validate_page(page)\n",
    "        mark = max([high_water_mark(con)] + [a.activity_id for a in activities])\n",
    "        con.begin()  # the page's rows and the new mark: together or not at all\n",
    "        upsert(con, activities)\n",
    "        con.execute(\"INSERT OR REPLACE INTO load_state VALUES ('chembl', ?)\", [mark])\n",
    "        con.commit()\n",
    "        n_pages, n_records = n_pages + 1, n_records + len(activities)\n",
    "    stored = con.execute(\"SELECT COUNT(*) FROM activities\").fetchone()[0]\n",
    "    return (f\"mark {start} -> {high_water_mark(con)}; pages: {n_pages}, records fetched: \"\n",
    "            f\"{n_records}; stored: {stored}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In real use every run is the same call, `load_increment(con)`: the first run has a mark of 0 and\n",
    "fetches everything, and later runs fetch what has been added since. To see a second run find new\n",
    "records without waiting months for a ChEMBL release, the lesson's first run stops at activity id\n",
    "18,811,464, as if it had run before the later records were added. Each run prints its old and\n",
    "new mark, the pages and records fetched, and the rows now stored:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO run 1: mark 0 -> 18811464; pages: 3, records fetched: 276; stored: 276\n",
      "INFO run 2: mark 18811464 -> 28800434; pages: 2, records fetched: 117; stored: 393\n",
      "INFO run 3: mark 28800434 -> 28800434; pages: 1, records fetched: 0; stored: 393\n"
     ]
    }
   ],
   "source": [
    "log.info(\"run 1: %s\", load_increment(con, until=FIRST_RUN_CUTOFF))\n",
    "log.info(\"run 2: %s\", load_increment(con))\n",
    "log.info(\"run 3: %s\", load_increment(con))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The second run asked only for activities above the first run's mark and found the newer ones; the\n",
    "third found nothing and cost one small request. Requests are cheap to repeat because the load is\n",
    "idempotent. Here the first page of run 1 is fetched and loaded again, as happens after a crash\n",
    "between storing a page and moving on, and the table does not change (`{before[1]:.2f}` prints the\n",
    "total with two decimals):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "rows and pChEMBL total before: 393, 2541.97; after: 393, 2541.97; unchanged: True\n"
     ]
    }
   ],
   "source": [
    "before = con.execute(\"SELECT COUNT(*), SUM(pchembl_value) FROM activities\").fetchone()\n",
    "again = fetch_json(CHEMBL_ACTIVITY,\n",
    "                   {**QUERY, \"activity_id__gt\": \"0\", \"activity_id__lte\": str(FIRST_RUN_CUTOFF)})\n",
    "upsert(con, validate_page(again))\n",
    "after = con.execute(\"SELECT COUNT(*), SUM(pchembl_value) FROM activities\").fetchone()\n",
    "print(f\"rows and pChEMBL total before: {before[0]}, {before[1]:.2f}; after: {after[0]}, \"\n",
    "      f\"{after[1]:.2f}; unchanged: {before == after}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Activity ids along a line, each loaded record a tick: run 1 loads up to its cut-off and sets the high-water mark there, run 2 loads only the records above that mark and moves the mark to the last record, run 3 finds nothing above it, and a backfill re-fetches a range below the mark without moving it](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/11-incremental-ingestion/figures/high-water-mark.svg)\n",
    "\n",
    "A high-water mark sees only what is *added* above it. It does not see a record that was corrected\n",
    "in place (ChEMBL flags doubtful values in a `data_validity_comment` field, and a new release can\n",
    "change existing records) or deleted. For those you\n",
    "need either a source that publishes changes (some APIs offer an \"updated since\" filter or a change\n",
    "log), a periodic full comparison, or a backfill.\n",
    "\n",
    "## 7. Backfills\n",
    "\n",
    "A **backfill** re-fetches a range of old records on purpose: after a release corrects old data,\n",
    "after you fix a bug in your loader, or when you add a field to the model and need it for records\n",
    "already stored. Because the load is idempotent, a backfill is the same upsert over a range given\n",
    "explicitly, and it leaves the high-water mark alone, so the next incremental run carries on as\n",
    "before.\n",
    "\n",
    "To make the effect visible, we pretend an earlier version of our loader lost the pChEMBL values\n",
    "of some records, then backfill that range. `BETWEEN ? AND ?` in SQL means \"from the first value to\n",
    "the second, both included\", and `backfill(con, *BACKFILL)` unpacks the pair `BACKFILL` into the\n",
    "function's two arguments, `first_id` and `last_id`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "records missing pChEMBL before the backfill: 76\n",
      "INFO records re-fetched: 76\n",
      "records missing pChEMBL after: 0\n",
      "high-water mark unchanged: True\n",
      "rows: 393\n"
     ]
    }
   ],
   "source": [
    "BACKFILL = (16279324, 16354699)  # the range of activity ids to fetch again\n",
    "\n",
    "\n",
    "def backfill(con: duckdb.DuckDBPyConnection, first_id: int, last_id: int) -> int:\n",
    "    \"\"\"Re-fetch and upsert every activity with an id in [first_id, last_id]; the mark is unchanged.\n",
    "\n",
    "    Args:\n",
    "        con: The DuckDB connection.\n",
    "        first_id: The first activity id of the range.\n",
    "        last_id: The last activity id of the range.\n",
    "\n",
    "    Returns:\n",
    "        How many records were fetched.\n",
    "    \"\"\"\n",
    "    params = {**QUERY, \"activity_id__gte\": str(first_id), \"activity_id__lte\": str(last_id)}\n",
    "    n_records = 0\n",
    "    for page in pages(params):\n",
    "        activities = validate_page(page)\n",
    "        upsert(con, activities)\n",
    "        n_records += len(activities)\n",
    "    return n_records\n",
    "\n",
    "\n",
    "con.execute(\"UPDATE activities SET pchembl_value = NULL WHERE activity_id BETWEEN ? AND ?\",\n",
    "            list(BACKFILL))  # the pretend bug\n",
    "missing = \"SELECT COUNT(*) FROM activities WHERE pchembl_value IS NULL\"\n",
    "print(\"records missing pChEMBL before the backfill:\", con.execute(missing).fetchone()[0])\n",
    "mark = high_water_mark(con)\n",
    "log.info(\"records re-fetched: %d\", backfill(con, *BACKFILL))\n",
    "print(\"records missing pChEMBL after:\", con.execute(missing).fetchone()[0])\n",
    "print(\"high-water mark unchanged:\", high_water_mark(con) == mark)\n",
    "print(\"rows:\", con.execute(\"SELECT COUNT(*) FROM activities\").fetchone()[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A backfill over the whole history is just the widest range. For large ranges, run it in chunks\n",
    "with checkpoints, exactly as in Module 10, and at a quiet time: it is a heavy load on the source.\n",
    "\n",
    "## 8. PubChem: properties for a list of compounds\n",
    "\n",
    "PubChem's PUG REST interface (PUG is PubChem's name for its interface for programs; REST means it\n",
    "is used through plain URLs, as ChEMBL's is) returns a table of properties for a comma-separated\n",
    "list of CIDs (PubChem's compound ids; aspirin is 2244) in one request, such as\n",
    "`/rest/pug/compound/cid/2244,2519/property/MolecularFormula,MolecularWeight,SMILES,InChIKey/JSON`.\n",
    "Sending several CIDs per request means fewer requests, which is what the usage policy asks for;\n",
    "very long lists should be split into chunks (`CHUNK_SIZE` is 5 here to show the chunking; real\n",
    "pipelines use hundreds). Incremental here means asking only for CIDs not stored yet. Note that\n",
    "PubChem sends the molecular weight as text, `\"180.16\"`; the model turns it into a number. PubChem\n",
    "names its fields in capitals (`MolecularWeight`), so each field in the model gives that name as an\n",
    "`alias` and uses a shorter Python name (`mol_wt`) itself. `[*CIDS_FIRST, 54678486, ...]` makes a new\n",
    "list holding everything in `CIDS_FIRST` followed by the extra CIDs, and `.df()` turns a DuckDB\n",
    "result into a pandas table for printing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO run 1: CIDs asked for: 10, not yet stored: 10; requests: 2, rejected: 0; stored: 10\n",
      "WARNING rejected CID 999999999: 5 problems, e.g. Title missing\n",
      "INFO run 2: CIDs asked for: 14, not yet stored: 4; requests: 1, rejected: 1; stored: 13\n",
      "      cid                         reason\n",
      "999999999 5 problems, e.g. Title missing\n",
      " cid         title       formula  mol_wt\n",
      "1983 Acetaminophen       C8H9NO2  151.16\n",
      "2244       Aspirin        C9H8O4  180.16\n",
      "2519      Caffeine     C8H10N4O2  194.19\n",
      "2662     Celecoxib C17H14F3N3O2S  381.40\n",
      "3033    Diclofenac  C14H11Cl2NO2  296.10\n"
     ]
    }
   ],
   "source": [
    "class Compound(BaseModel):\n",
    "    \"\"\"One row of a PubChem property table.\"\"\"\n",
    "\n",
    "    model_config = ConfigDict(extra=\"ignore\", frozen=True)\n",
    "\n",
    "    cid: int = Field(alias=\"CID\", gt=0)\n",
    "    title: str = Field(alias=\"Title\")\n",
    "    formula: str = Field(alias=\"MolecularFormula\")\n",
    "    mol_wt: float = Field(alias=\"MolecularWeight\", gt=0)  # sent as text, e.g. \"180.16\"\n",
    "    smiles: str = Field(alias=\"SMILES\")\n",
    "    inchikey: str = Field(alias=\"InChIKey\", pattern=r\"^[A-Z]{14}-[A-Z]{10}-[A-Z]$\")\n",
    "\n",
    "\n",
    "con.execute(\"\"\"\n",
    "    CREATE TABLE compounds (cid BIGINT PRIMARY KEY, title VARCHAR, formula VARCHAR,\n",
    "        mol_wt DOUBLE, smiles VARCHAR, inchikey VARCHAR, source VARCHAR);\n",
    "    CREATE TABLE compound_rejects (cid BIGINT PRIMARY KEY, reason VARCHAR);\n",
    "\"\"\")\n",
    "\n",
    "\n",
    "def load_compounds(con: duckdb.DuckDBPyConnection, cids: list[int]) -> str:\n",
    "    \"\"\"Fetch properties for the CIDs not stored yet, in chunks; bad records go to rejects.\n",
    "\n",
    "    Args:\n",
    "        con: The DuckDB connection.\n",
    "        cids: The PubChem compound ids wanted.\n",
    "\n",
    "    Returns:\n",
    "        A one-line report.\n",
    "    \"\"\"\n",
    "    stored = {row[0] for row in con.execute(\"SELECT cid FROM compounds\").fetchall()}\n",
    "    new = [cid for cid in cids if cid not in stored]\n",
    "    n_requests = n_rejected = 0\n",
    "    for i in range(0, len(new), CHUNK_SIZE):\n",
    "        chunk = new[i : i + CHUNK_SIZE]\n",
    "        table = fetch_json(PUBCHEM_PROPERTIES.format(cids=\",\".join(map(str, chunk))))\n",
    "        n_requests += 1\n",
    "        for record in table[\"PropertyTable\"][\"Properties\"]:  # a KeyError here: the API changed\n",
    "            try:\n",
    "                c = Compound.model_validate(record)\n",
    "            except ValidationError as err:\n",
    "                reason = f\"{err.error_count()} problems, e.g. {err.errors()[0]['loc'][0]} missing\"\n",
    "                log.warning(\"rejected CID %s: %s\", record.get(\"CID\"), reason)\n",
    "                con.execute(\"INSERT OR REPLACE INTO compound_rejects VALUES (?, ?)\",\n",
    "                            [record.get(\"CID\"), reason])\n",
    "                n_rejected += 1\n",
    "                continue\n",
    "            con.execute(\"INSERT OR REPLACE INTO compounds VALUES (?, ?, ?, ?, ?, ?, ?)\",\n",
    "                        [c.cid, c.title, c.formula, c.mol_wt, c.smiles, c.inchikey,\n",
    "                         SOURCE_PUBCHEM])\n",
    "    total = con.execute(\"SELECT COUNT(*) FROM compounds\").fetchone()[0]\n",
    "    return (f\"CIDs asked for: {len(cids)}, not yet stored: {len(new)}; requests: {n_requests}, \"\n",
    "            f\"rejected: {n_rejected}; stored: {total}\")\n",
    "\n",
    "\n",
    "CIDS_FIRST = [2244, 2519, 3672, 1983, 156391, 3033, 4091, 60823, 4594, 33613]\n",
    "CIDS_SECOND = [*CIDS_FIRST, 54678486, 5090, 2662, 999999999]\n",
    "log.info(\"run 1: %s\", load_compounds(con, CIDS_FIRST))\n",
    "log.info(\"run 2: %s\", load_compounds(con, CIDS_SECOND))\n",
    "print(con.execute(\"SELECT * FROM compound_rejects\").df().to_string(index=False))\n",
    "print(con.execute(\"SELECT cid, title, formula, mol_wt FROM compounds ORDER BY cid LIMIT 5\")\n",
    "      .df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The second list had a mistyped CID, 999999999. PubChem did not answer with an error: it returned a\n",
    "record holding only the CID and no properties. Without a model, that would have become a row of\n",
    "empty values; with it, the record went to `compound_rejects` with a reason, and the rest of the run\n",
    "carried on. Here a reject is the right answer rather than stopping: the response is the shape we\n",
    "expect, and the fault is in one input, not in the API.\n",
    "\n",
    "## 9. Keeping the source with the data, and writing Parquet\n",
    "\n",
    "Every stored row says where it came from and under which licence, so the attribution travels with\n",
    "the data into every export. Analysts and the next pipeline usually read Parquet files (the compact file format for tables\n",
    "from [Module 3](../03-files-and-identity/)) rather than the database; DuckDB writes them directly,\n",
    "with `COPY table TO 'file' (FORMAT parquet)`, and can read them back as if they were tables. At the end, `Counter` (from `collections`, imported in\n",
    "the Setup block) counts the requests made to each service: it counts and sorts in one step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO wrote activities.parquet: 393 rows, source: ChEMBL (CC BY-SA 3.0)\n",
      "INFO wrote compounds.parquet: 13 rows, source: PubChem (NCBI: no restrictions on use)\n",
      "INFO requests made in this lesson: 15, all replayed: True\n",
      "www.ebi.ac.uk              12\n",
      "pubchem.ncbi.nlm.nih.gov   3\n"
     ]
    }
   ],
   "source": [
    "for table in (\"activities\", \"compounds\"):\n",
    "    path = WORK / f\"{table}.parquet\"\n",
    "    con.execute(f\"COPY {table} TO '{path.as_posix()}' (FORMAT parquet)\")\n",
    "    check = con.execute(f\"SELECT COUNT(*), ANY_VALUE(source) FROM '{path.as_posix()}'\").fetchone()\n",
    "    log.info(\"wrote %s: %d rows, source: %s\", path.name, check[0], check[1])\n",
    "con.close()\n",
    "log.info(\"requests made in this lesson: %d, all replayed: %s\", len(requests_made), not LIVE)\n",
    "per_service = Counter(urlsplit(url).netloc for url in requests_made)\n",
    "for host, n in per_service.most_common():\n",
    "    print(f\"{host:26} {n}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For a dataset you publish (a benchmark built from ChEMBL, say), ChEMBL's ShareAlike condition\n",
    "applies: publish it under CC BY-SA 3.0 or a compatible licence, credit ChEMBL and cite the release\n",
    "you used. Keep the release number (ChEMBL's `status` endpoint reports it) and the retrieval date in\n",
    "your load state, so the data can be traced to their source years later.\n",
    "\n",
    "At scale, the same design holds. For all of ChEMBL's activities (millions of records), the bulk\n",
    "downloads (SQL dumps per release: the whole database as one file you load into your own) are the\n",
    "better first load, and the web services serve the\n",
    "incremental top-ups between releases. dlt, which Series 2 uses, provides incremental cursors,\n",
    "pagination helpers and merge (upsert) loading as configuration; this module is what it does\n",
    "underneath.\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",
    "- Zdrazil, B. et al. (2024). The ChEMBL Database in 2023: a drug discovery platform spanning\n",
    "  multiple bioactivity data types and time periods. *Nucleic Acids Research*, 52(D1), D1180–D1192.\n",
    "  <https://doi.org/10.1093/nar/gkad1004>\n",
    "- Kim, S. et al. (2023). PubChem 2023 update. *Nucleic Acids Research*, 51(D1), D1373–D1380.\n",
    "  <https://doi.org/10.1093/nar/gkac956>\n",
    "- The ChEMBL documentation. *ChEMBL Data Web Services*.\n",
    "  <https://chembl.gitbook.io/chembl-interface-documentation/web-services/chembl-data-web-services>\n",
    "- PubChem. *PUG-REST*, the reference for PubChem's REST interface, with its usage policy.\n",
    "  <https://pubchem.ncbi.nlm.nih.gov/docs/pug-rest>\n",
    "- PubChem. *Dynamic Request Throttling*. <https://pubchem.ncbi.nlm.nih.gov/docs/dynamic-request-throttling>\n",
    "- NCBI. *Website and Data Usage Policies*. <https://www.ncbi.nlm.nih.gov/home/about/policies/>\n",
    "- Creative Commons. *Attribution-ShareAlike 3.0 Unported* (CC BY-SA 3.0).\n",
    "  <https://creativecommons.org/licenses/by-sa/3.0/>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
