{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Declarative ingestion\n",
    "\n",
    "Load the lab's files and ChEMBL's API into the raw layer with dlt. Declare what to load and how to recognise each row; let the tool infer the schema, remember what it has loaded, absorb duplicates, and either follow or refuse a change in the data's shape.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-2/02-declarative-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 dlt[duckdb] duckdb pandas numpy rdkit requests\n",
    "\n",
    "import pathlib\n",
    "import urllib.request\n",
    "if not pathlib.Path(\"chemlib.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/shared/chemlib.py\", \"chemlib.py\")\n",
    "if not pathlib.Path(\"labdata.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/labdata.py\", \"labdata.py\")\n",
    "if not pathlib.Path(\"chembl_replay.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/02-declarative-ingestion/chembl_replay.py\", \"chembl_replay.py\")\n",
    "if not pathlib.Path(\"recorded/chembl-0908b212c93b.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-0908b212c93b.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/02-declarative-ingestion/recorded/chembl-0908b212c93b.json\", \"recorded/chembl-0908b212c93b.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-5102c42f4744.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-5102c42f4744.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/02-declarative-ingestion/recorded/chembl-5102c42f4744.json\", \"recorded/chembl-5102c42f4744.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-78ddf38d0fc2.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-78ddf38d0fc2.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/02-declarative-ingestion/recorded/chembl-78ddf38d0fc2.json\", \"recorded/chembl-78ddf38d0fc2.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-8d6258ebc1f6.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-8d6258ebc1f6.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/02-declarative-ingestion/recorded/chembl-8d6258ebc1f6.json\", \"recorded/chembl-8d6258ebc1f6.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-a77fb0c3f638.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-a77fb0c3f638.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/02-declarative-ingestion/recorded/chembl-a77fb0c3f638.json\", \"recorded/chembl-a77fb0c3f638.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-a9562b86a1c3.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-a9562b86a1c3.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/02-declarative-ingestion/recorded/chembl-a9562b86a1c3.json\", \"recorded/chembl-a9562b86a1c3.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-af033d7d068a.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-af033d7d068a.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/02-declarative-ingestion/recorded/chembl-af033d7d068a.json\", \"recorded/chembl-af033d7d068a.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-cb3c97a37983.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-cb3c97a37983.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/02-declarative-ingestion/recorded/chembl-cb3c97a37983.json\", \"recorded/chembl-cb3c97a37983.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-ce3aa2ab4b11.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-ce3aa2ab4b11.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/02-declarative-ingestion/recorded/chembl-ce3aa2ab4b11.json\", \"recorded/chembl-ce3aa2ab4b11.json\")\n",
    "if not pathlib.Path(\"recorded/chembl-e197eb6040ee.json\").exists():\n",
    "    pathlib.Path(\"recorded/chembl-e197eb6040ee.json\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/02-declarative-ingestion/recorded/chembl-e197eb6040ee.json\", \"recorded/chembl-e197eb6040ee.json\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In [Module 1](../01-lab-data-architecture/) we filled the raw layer by hand: one SQL statement\n",
    "per source, rebuilding each raw table from every file in the inbox. That was enough to see the\n",
    "idea, but a real raw layer has more to do. It should load only the files it has not seen before,\n",
    "so a year of files is not reread every week. It should recognise a row that arrives twice. It\n",
    "should notice when a source changes the shape of its data, and decide whether to follow the change\n",
    "or stop. And it should load from web services as well as from files.\n",
    "\n",
    "In [Series 1, Module 11](../../series-1/11-incremental-ingestion/) we wrote all of that by hand\n",
    "for ChEMBL: paging through the API, remembering the highest ID loaded (a high-water mark), retrying\n",
    "politely, checking every response against a model and writing rows so that a rerun did no harm. It\n",
    "took most of a module. **dlt** (data load tool) is an open-source Python library that does those\n",
    "jobs for you. You *declare* what to load: where the data comes from, what identifies each row,\n",
    "and how to tell new data from old. dlt does the rest. That is what **declarative** means here:\n",
    "you say *what* should happen, not every step of *how*.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- explain the parts of a dlt pipeline: resources, sources, the pipeline, the destination, the\n",
    "  schema and the state;\n",
    "- load a snapshot file (the compound registry) so that each load replaces the last;\n",
    "- load files incrementally (the assay results), so each file is loaded once and a resent file\n",
    "  does not create duplicates;\n",
    "- see how dlt follows a change in the data's shape, and use a schema contract to stop instead,\n",
    "  then recover cleanly after the stop;\n",
    "- load ChEMBL's activities for the lab's five kinases with dlt's REST API source, incrementally,\n",
    "  with the licence stored next to every row.\n",
    "\n",
    "The lab's files come from `labdata`, as in Module 1. ChEMBL's answers come from the real service:\n",
    "they were recorded once, into the module's `recorded/` folder, and the lesson replays them, so it\n",
    "works offline and gives the same results on every computer. The small file `chembl_replay.py` in\n",
    "the module's folder does the replaying; one setting, explained in section 5, makes the same code\n",
    "call ChEMBL live instead.\n",
    "\n",
    "## Setup\n",
    "\n",
    "Everything this lesson needs is imported and set here. dlt keeps a folder of its own for each\n",
    "pipeline (what it has loaded, and the schema it has inferred); we put it under `work/`, next to\n",
    "the database, so a fresh run of the lesson starts from nothing. Two settings, made through\n",
    "environment variables (settings a program reads from the computer it runs on, set here with\n",
    "`os.environ`), keep dlt quiet: one stops it sending anonymous usage statistics to its makers, and\n",
    "one stops it printing log lines with times in them, which would differ on every run.\n",
    "\n",
    "From Python itself the block imports `os`, `re` (patterns that match text), `shutil` (to delete a\n",
    "folder) and `Path`; and `PipelineStepFailed`, the error dlt raises when a step of a load fails."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import os\n",
    "import re\n",
    "import shutil\n",
    "from pathlib import Path\n",
    "\n",
    "import dlt\n",
    "import duckdb\n",
    "import pandas as pd\n",
    "from dlt.pipeline.exceptions import PipelineStepFailed\n",
    "from dlt.sources.rest_api import rest_api_source\n",
    "\n",
    "import chembl_replay\n",
    "import labdata\n",
    "\n",
    "os.environ[\"RUNTIME__DLTHUB_TELEMETRY\"] = \"false\"  # no usage statistics sent to dlt's makers\n",
    "os.environ[\"RUNTIME__LOG_LEVEL\"] = \"ERROR\"  # dlt prints only errors, so the outputs are stable\n",
    "\n",
    "logging.basicConfig(level=logging.INFO, format=\"%(levelname)s %(message)s\", force=True)\n",
    "log = logging.getLogger(__name__)\n",
    "\n",
    "# where the lesson writes its files (git-ignored); change it to write somewhere else\n",
    "WORK = Path(\"work\")\n",
    "INBOX = WORK / \"inbox\"  # where the lab's files arrive, one set per week\n",
    "WAREHOUSE = WORK / \"lab.duckdb\"  # the database; dlt loads into its raw layer\n",
    "PIPELINES = WORK / \"dlt\"  # dlt's own folder: what each pipeline has loaded, and its schema\n",
    "WEEKS = 6  # how many weeks of the lab's files we load\n",
    "# ChEMBL: where its API lives, which fields to ask for, and how many activities a page holds\n",
    "CHEMBL_API = \"https://www.ebi.ac.uk/chembl/api/data/\"\n",
    "FIELDS = (\"activity_id,molecule_chembl_id,canonical_smiles,standard_type,standard_relation,\"\n",
    "          \"standard_value,standard_units,pchembl_value,target_chembl_id,document_chembl_id\")\n",
    "PAGE_SIZE = 100\n",
    "CHEMBL_LICENCE = \"ChEMBL, CC BY-SA 3.0 (https://www.ebi.ac.uk/chembl/)\"\n",
    "\n",
    "shutil.rmtree(WORK, ignore_errors=True)  # start clean\n",
    "WORK.mkdir()\n",
    "lab = labdata.Lab()\n",
    "\n",
    "\n",
    "def query(sql: str) -> pd.DataFrame:\n",
    "    \"\"\"Run one SQL query on the warehouse and return the answer as a table.\"\"\"\n",
    "    with duckdb.connect(str(WAREHOUSE)) as db:\n",
    "        return db.sql(sql).df()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`query` opens the database, runs one query and closes it again, so our reading never gets in the\n",
    "way of dlt's writing.\n",
    "\n",
    "## 1. The parts of a dlt pipeline\n",
    "\n",
    "A dlt load has six parts, and every later section uses them:\n",
    "\n",
    "- A **resource** is a Python function that **yields** rows: each row is a dictionary (column\n",
    "  name to value), and `yield` hands rows over one batch at a time instead of building one huge list\n",
    "  ([Series 1, Module 8](../../series-1/08-larger-than-memory/) used the same idea for files larger\n",
    "  than memory). The decorator `@dlt.resource`, written on the line above the function, turns an\n",
    "  ordinary function into a resource and says how its rows are to be loaded.\n",
    "- A **source** is a group of resources that belong together, such as all of ChEMBL's endpoints.\n",
    "- The **destination** is where the data goes: for us, the DuckDB database of Module 1.\n",
    "- The **pipeline** connects resources to a destination. Its **dataset** is the schema (the\n",
    "  group of tables) it loads into: ours is `raw`, the raw layer.\n",
    "- The **schema** is dlt's description of every table and column it has loaded, with their types.\n",
    "  dlt **infers** it, working it out from the data, and keeps it up to date.\n",
    "- The **state** is what dlt remembers between runs, such as the last file loaded. It is stored\n",
    "  with the pipeline, and also in the destination, so a pipeline can carry on where it stopped.\n",
    "\n",
    "Each run goes through three steps: **extract** (call the resources and collect their rows),\n",
    "**normalize** (fit the rows to the schema: types, column names, nested data split into tables)\n",
    "and **load** (write them to the destination). When something goes wrong, dlt says which step\n",
    "failed, which section 4 uses.\n",
    "\n",
    "![One dlt load: the inbox's files feed two resources you declare (the registry, replaced on each load; the assay files, incremental on file name and merged on result_id); dlt extracts, normalizes against the schema it infers, and loads into DuckDB's raw layer; the state keeps the last file loaded, so the next run reads only newer files](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/02-declarative-ingestion/figures/dlt-load.svg)\n",
    "\n",
    "## 2. A snapshot: the compound registry\n",
    "\n",
    "The registry export is a snapshot: each week's file holds every compound so far. So each load\n",
    "should **replace** the registry table with the latest file. That is a resource's **write\n",
    "disposition**: `\"replace\"` here; the other two are `\"append\"` (add the rows) and `\"merge\"` (add new\n",
    "rows and update existing ones, section 3).\n",
    "\n",
    "We read each file with pandas, keeping every value as text (`dtype=str`) and empty cells as empty\n",
    "text (`keep_default_na=False`), so the raw layer holds the file exactly as written, as in Module 1.\n",
    "`to_dict(\"records\")` turns the table into a list of dictionaries, one per row, which is what a\n",
    "resource yields:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " compounds               from_file\n",
      "       240 registry_2026-10-12.csv\n"
     ]
    }
   ],
   "source": [
    "@dlt.resource(name=\"registry\", write_disposition=\"replace\")\n",
    "def registry():\n",
    "    \"\"\"The latest registry export: every compound registered so far.\"\"\"\n",
    "    latest = max(INBOX.glob(\"registry_*.csv\"))  # the names carry dates, so max is the newest\n",
    "    table = pd.read_csv(latest, dtype=str, keep_default_na=False)\n",
    "    table[\"file_name\"] = latest.name\n",
    "    yield table.to_dict(\"records\")\n",
    "\n",
    "\n",
    "pipeline = dlt.pipeline(\n",
    "    pipeline_name=\"lab\",\n",
    "    destination=dlt.destinations.duckdb(str(WAREHOUSE)),\n",
    "    dataset_name=\"raw\",\n",
    "    pipelines_dir=str(PIPELINES),\n",
    ")\n",
    "for week in range(1, WEEKS + 1):\n",
    "    lab.write_week(week, INBOX)\n",
    "    pipeline.run(registry())\n",
    "print(query(\"SELECT count(*) AS compounds, max(file_name) AS from_file FROM raw.registry\")\n",
    "      .to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Six weekly loads, and the table holds the 240 compounds of the latest export, not six copies of\n",
    "the registry stacked together. dlt also wrote down the table's schema. `pipeline.default_schema`\n",
    "holds it; here are the registry's columns with the type dlt inferred for each:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{'compound_id': 'text', 'smiles': 'text', 'salt': 'text', 'batch': 'text', 'chemist': 'text', 'vendor': 'text', 'registered_on': 'text', 'file_name': 'text', '_dlt_load_id': 'text', '_dlt_id': 'text'}\n"
     ]
    }
   ],
   "source": [
    "columns = pipeline.default_schema.get_table_columns(\"registry\")\n",
    "print({name: column[\"data_type\"] for name, column in columns.items()})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every column we yielded is `text`, as we read it. dlt added two of its own: `_dlt_load_id` says\n",
    "which load wrote the row, and `_dlt_id` is a unique ID for the row. Both let any row be traced back\n",
    "to the run that produced it, the same job `filename` did in Module 1.\n",
    "\n",
    "## 3. Files, incrementally: the assay results\n",
    "\n",
    "Assay files are different: each holds only one week's results, so every file must be loaded once,\n",
    "and a file already loaded must not be loaded again. dlt calls this **incremental** loading. A\n",
    "resource gets an argument `dlt.sources.incremental(...)` naming a **cursor**: a value that grows as\n",
    "new data arrives. Here the cursor is the file name, because the names carry dates. After each run\n",
    "dlt remembers the largest file name it has seen (`last_value`), and the resource skips every file\n",
    "whose name is not larger.\n",
    "\n",
    "The second decision is what makes a row the same row. Each result has a `result_id`; declaring it\n",
    "the **primary key** (the column that identifies a row) and the write disposition `\"merge\"` tells\n",
    "dlt to add new results and *replace* results whose key it already has, never to keep two. That is\n",
    "what absorbs the file sent twice in week 4."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO run 1: {'assay': 832}\n",
      "INFO run 2: {}\n",
      "INFO run 3: {}\n",
      "INFO run 4: {}\n",
      "INFO run 5: {}\n",
      "INFO run 6: {}\n"
     ]
    }
   ],
   "source": [
    "@dlt.resource(name=\"assay\", write_disposition=\"merge\", primary_key=\"result_id\")\n",
    "def assay(files=dlt.sources.incremental(\"file_name\", initial_value=\"\")):\n",
    "    \"\"\"Every row of every assay file not loaded before.\"\"\"\n",
    "    for path in sorted(INBOX.glob(\"assay_*.csv\")):\n",
    "        if path.name <= files.last_value:\n",
    "            continue  # loaded in an earlier run\n",
    "        table = pd.read_csv(path, dtype=str, keep_default_na=False)\n",
    "        table[\"file_name\"] = path.name\n",
    "        yield table.to_dict(\"records\")\n",
    "\n",
    "\n",
    "def rows_loaded(pipeline: dlt.Pipeline) -> dict[str, int]:\n",
    "    \"\"\"How many rows each table received in the pipeline's last run (dlt's own tables left out).\"\"\"\n",
    "    info = pipeline.last_trace.last_normalize_info\n",
    "    counts = info.row_counts if info else {}\n",
    "    # sorted by table: dlt's own order can change from run to run\n",
    "    return {table: n for table, n in sorted(counts.items()) if not table.startswith(\"_dlt\")}\n",
    "\n",
    "\n",
    "for week in range(1, WEEKS + 1):\n",
    "    pipeline.run(assay())  # the files of all six weeks are already in the inbox\n",
    "    log.info(\"run %d: %s\", week, rows_loaded(pipeline))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first run found all the assay files at once, because section 2 already put six weeks of files\n",
    "in the inbox; the next five runs found nothing new. In a real lab, the pipeline runs once a week\n",
    "and loads that week's files. Either way, nothing is loaded twice. Here is what dlt remembers, and\n",
    "what the table holds:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "last file loaded: assay_2026-10-12.csv\n",
      " rows  results\n",
      "  656      656\n",
      "           file_name  rows\n",
      "assay_2026-09-14.csv    80\n",
      "assay_2026-09-21.csv   176\n",
      "assay_2026-09-28.csv   136\n",
      "assay_2026-10-05.csv   136\n",
      "assay_2026-10-12.csv   128\n"
     ]
    }
   ],
   "source": [
    "cursor = pipeline.state[\"sources\"][\"lab\"][\"resources\"][\"assay\"][\"incremental\"][\"file_name\"]\n",
    "print(\"last file loaded:\", cursor[\"last_value\"])\n",
    "print(query(\"SELECT count(*) AS rows, count(DISTINCT result_id) AS results FROM raw.assay\")\n",
    "      .to_string(index=False))\n",
    "print(query(\"SELECT file_name, count(*) AS rows FROM raw.assay GROUP BY ALL ORDER BY file_name\")\n",
    "      .to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The run read 832 rows but the table holds 656, one per result: the 176 rows of the resent file\n",
    "(`assay_2026-09-21_resent.csv`, week 3's results sent again in week 4) were recognised by their\n",
    "`result_id` and kept once. The file list has no rows from the resent file because both copies\n",
    "arrived in the same load, and when that happens dlt keeps one of them. Which one is not defined\n",
    "unless you say, with a hint called `dedup_sort`; here it kept the original. When a later load\n",
    "brings a key the table already has, the new row replaces the old one, as section 4 shows.\n",
    "\n",
    "Module 1 removed the same duplicates in staging with `QUALIFY`; with a primary key, the raw layer\n",
    "never holds them at all. Note what this gives up: the raw layer no longer shows that week 3's file\n",
    "arrived twice. If that matters (it might, when you need to tell a supplier their system sends\n",
    "files twice), load with `\"append\"` and remove duplicates in staging, as Module 1 did. Both are\n",
    "reasonable, and a team should choose on purpose.\n",
    "\n",
    "## 4. When the data changes shape\n",
    "\n",
    "In week 5 the plate reader's software was updated: it now writes the unit in a column called\n",
    "`unit` instead of `units`, and adds a column `operator`. The load in section 3 did not fail. dlt\n",
    "**evolved** the schema: it saw columns it had not seen and added them to the table."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "['result_id', 'compound_id', 'target', 'plate', 'replicate', 'relation', 'value', 'units', 'run_date', 'file_name', 'unit', 'operator']\n",
      " with_units  with_unit\n",
      "        392        264\n"
     ]
    }
   ],
   "source": [
    "assay_columns = pipeline.default_schema.get_table_columns(\"assay\")\n",
    "print([name for name in assay_columns if not name.startswith(\"_dlt\")])\n",
    "print(query(\"SELECT count(units) AS with_units, count(unit) AS with_unit FROM raw.assay\")\n",
    "      .to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The old rows have `units`, the new rows have `unit`, and each is empty where the other is filled,\n",
    "exactly as in Module 1's raw layer. Following a change automatically is often right for a raw\n",
    "layer, because nothing is lost and staging can bring the two columns together (Module 1's\n",
    "`coalesce(unit, units)`). But it can also hide a change that someone ought to know about: here, a\n",
    "software update nobody announced, which might have changed more than a column's name.\n",
    "\n",
    "A **schema contract** decides what dlt does when the data changes shape. `\"evolve\"` (what we have\n",
    "had so far) follows the change; `\"freeze\"` refuses it and stops the load with an error;\n",
    "`\"discard_row\"` and `\"discard_value\"` drop the rows or values that do not fit. Here we load the\n",
    "same files into a second dataset, `raw_strict`, with the columns frozen. This time the files\n",
    "arrive as they would in the lab, one week at a time, into a second inbox, and the pipeline runs\n",
    "once a week. The `try`/`except` catches only dlt's own failure, as [Series 1, Module\n",
    "10](../../series-1/10-pipelines-that-survive-failure/) taught, and prints the rule that was broken:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO week 1: loaded {}\n",
      "INFO week 2: loaded {'assay': 80}\n",
      "INFO week 3: loaded {'assay': 176}\n",
      "INFO week 4: loaded {'assay': 312}\n",
      "ERROR week 5: the normalize step failed: Can't add table column `unit` to table `assay` because `columns` are frozen\n"
     ]
    }
   ],
   "source": [
    "WEEKLY = WORK / \"weekly\"  # a second inbox, filled one week at a time\n",
    "\n",
    "\n",
    "@dlt.resource(name=\"assay\", write_disposition=\"merge\", primary_key=\"result_id\",\n",
    "              schema_contract={\"columns\": \"freeze\"})\n",
    "def assay_strict(files=dlt.sources.incremental(\"file_name\", initial_value=\"\")):\n",
    "    \"\"\"The assay files in the weekly inbox, but the table's columns may not change.\"\"\"\n",
    "    for path in sorted(WEEKLY.glob(\"assay_*.csv\")):\n",
    "        if path.name <= files.last_value:\n",
    "            continue\n",
    "        table = pd.read_csv(path, dtype=str, keep_default_na=False)\n",
    "        table[\"file_name\"] = path.name\n",
    "        yield table.to_dict(\"records\")\n",
    "\n",
    "\n",
    "strict = dlt.pipeline(pipeline_name=\"lab_strict\", destination=dlt.destinations.duckdb(\n",
    "    str(WAREHOUSE)), dataset_name=\"raw_strict\", pipelines_dir=str(PIPELINES))\n",
    "for week in range(1, WEEKS + 1):\n",
    "    lab.write_week(week, WEEKLY)  # this week's files arrive\n",
    "    try:\n",
    "        strict.run(assay_strict())\n",
    "        log.info(\"week %d: loaded %s\", week, rows_loaded(strict))\n",
    "    except PipelineStepFailed as error:\n",
    "        rule = re.search(r\"Can't add .*? are frozen\", str(error.__cause__))\n",
    "        log.error(\"week %d: the %s step failed: %s\", week, error.step, rule.group(0))\n",
    "        break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Week 1 brings no assay file (nothing has been tested yet), so nothing is loaded. Weeks 2 to 4\n",
    "load, week 4 with both its own file and the resent copy of week 3's. Week 5 stops at the\n",
    "**normalize** step, the one that fits rows to the schema, with a message that says exactly which\n",
    "column broke which rule. Nobody's analysis is touched until a person decides what the change\n",
    "means.\n",
    "\n",
    "![Week 5 under two contracts: with evolve, every week loads and the new columns unit and operator are added; with freeze, weeks 2 to 4 load, week 5 stops at normalize because unit is not allowed, and week 6 waits until a person decides](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/02-declarative-ingestion/figures/schema-contracts.svg)\n",
    "\n",
    "Stopping is only half of it: the pipeline must also recover cleanly. dlt keeps the failed load as\n",
    "a **pending package** (the rows it extracted, waiting to be loaded), and its state already says\n",
    "week 5's file was read. A plain rerun would only fail again on the same package, and simply\n",
    "deleting the files dlt keeps would lose track of what was loaded. `abort_packages()` is the clean\n",
    "way out: it gives up the pending package and puts the state back to where it was before:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "pending packages left: False\n",
      "last file loaded, back to: assay_2026-09-28.csv\n"
     ]
    }
   ],
   "source": [
    "strict.abort_packages()\n",
    "cursor = strict.state[\"sources\"][\"lab_strict\"][\"resources\"][\"assay\"][\"incremental\"][\"file_name\"]\n",
    "print(\"pending packages left:\", strict.has_pending_data)\n",
    "print(\"last file loaded, back to:\", cursor[\"last_value\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now a person decides. Here the change is understood (the unit moved to a new column, and staging\n",
    "already handles it), so we allow the new columns and run again. `apply_hints` changes a resource's\n",
    "settings without rewriting it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO week 5, after the decision: loaded {'assay': 136}\n",
      "INFO week 6: loaded {'assay': 128}\n",
      "                  file_name  rows  with_unit\n",
      "       assay_2026-09-14.csv    80          0\n",
      "assay_2026-09-21_resent.csv   176          0\n",
      "       assay_2026-09-28.csv   136          0\n",
      "       assay_2026-10-05.csv   136        136\n",
      "       assay_2026-10-12.csv   128        128\n"
     ]
    }
   ],
   "source": [
    "allowed = assay_strict()\n",
    "allowed.apply_hints(schema_contract={\"columns\": \"evolve\"})  # for this run only\n",
    "strict.run(allowed)\n",
    "log.info(\"week 5, after the decision: loaded %s\", rows_loaded(strict))\n",
    "lab.write_week(6, WEEKLY)\n",
    "strict.run(assay_strict())  # frozen again, and week 6 fits the schema as it now is\n",
    "log.info(\"week 6: loaded %s\", rows_loaded(strict))\n",
    "print(query(\"SELECT file_name, count(*) AS rows, count(unit) AS with_unit FROM raw_strict.assay \"\n",
    "            \"GROUP BY ALL ORDER BY file_name\").to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Week 5's file was loaded after all, and week 6's in its turn, under the frozen contract again: the\n",
    "schema now has `unit` and `operator`, so week 6 breaks no rule. The table holds the same 656\n",
    "results as the `raw` dataset, but look at week 3's rows: here they carry the resent file's name.\n",
    "In this pipeline the resent copy came in a later load than the original (week 4, not week 3), and\n",
    "a row whose key is already in the table replaces the old one. A frozen contract turns a silent\n",
    "change into a decision with a record.\n",
    "\n",
    "## 5. An API, declared: ChEMBL\n",
    "\n",
    "The lab also wants public data for its five targets, so its own potencies can be compared with\n",
    "published ones. ChEMBL's API answers in pages of JSON, as [Series 1, Module\n",
    "11](../../series-1/11-incremental-ingestion/) showed. dlt's **REST API source** turns an API into\n",
    "resources from a configuration: a dictionary that says where the API is and, for each resource,\n",
    "which endpoint (address) to call, with which **parameters** (the settings sent with the request),\n",
    "where the rows are in each answer, and how to load them.\n",
    "\n",
    "The configuration below asks ChEMBL for each kinase's IC50 activities that have a pChEMBL value,\n",
    "in order of `activity_id`, one page of 100 per run. The `incremental` part says that\n",
    "`activity_id` is the cursor, and that its last value is sent as the parameter `activity_id__gt`\n",
    "(\"greater than\"), so the next run asks only for newer activities. One page per run keeps the\n",
    "lesson small and polite to ChEMBL's servers; a real job would follow ChEMBL's page links (dlt's\n",
    "`json_link` paginator) to fetch everything."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def chembl():\n",
    "    \"\"\"ChEMBL's IC50 activities for the lab's five kinases, one page of 100 per target per run.\"\"\"\n",
    "    resources = [\n",
    "        {\n",
    "            \"name\": f\"chembl_{gene.lower()}\",\n",
    "            \"table_name\": \"chembl_activities\",  # the five resources fill one table\n",
    "            \"primary_key\": \"activity_id\",\n",
    "            \"write_disposition\": \"merge\",\n",
    "            \"endpoint\": {\n",
    "                \"path\": \"activity.json\",\n",
    "                \"params\": {\"target_chembl_id\": target, \"standard_type\": \"IC50\",\n",
    "                           \"pchembl_value__isnull\": \"false\", \"order_by\": \"activity_id\",\n",
    "                           \"limit\": PAGE_SIZE, \"only\": FIELDS},\n",
    "                \"data_selector\": \"activities\",  # the rows are in the answer's \"activities\" list\n",
    "                \"paginator\": {\"type\": \"single_page\"},\n",
    "                \"incremental\": {\"cursor_path\": \"activity_id\", \"start_param\": \"activity_id__gt\",\n",
    "                                \"initial_value\": 0},\n",
    "            },\n",
    "        }\n",
    "        for gene, target in labdata.TARGETS.items()\n",
    "    ]\n",
    "    source = rest_api_source(\n",
    "        {\"client\": {\"base_url\": CHEMBL_API, \"session\": chembl_replay.session()},\n",
    "         \"resources\": resources},\n",
    "        name=\"chembl\",\n",
    "    )\n",
    "    for resource in source.resources.values():  # keep the licence with every row\n",
    "        resource.add_map(lambda row: {**row, \"licence\": CHEMBL_LICENCE})\n",
    "    return source"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`\"session\": chembl_replay.session()` is the only line about recording: it hands dlt a connection\n",
    "that answers from `recorded/` instead of the internet. Set the environment variable `CHEMBL_MODE`\n",
    "to `live` before running the lesson and the same configuration calls ChEMBL for real (the numbers\n",
    "will then differ, because ChEMBL keeps growing). `add_map` runs a small function on every row\n",
    "before it is loaded; here it adds the licence, because ChEMBL's data may be reused only with\n",
    "credit and under the same licence ([Series 1, Module 11](../../series-1/11-incremental-ingestion/),\n",
    "section 1).\n",
    "\n",
    "Two runs, as if a week apart:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO ChEMBL run 1: {'chembl_activities': 500}\n",
      "INFO ChEMBL run 2: {'chembl_activities': 500}\n",
      "target_chembl_id  activities  first_id  last_id\n",
      "      CHEMBL1862         200    146141  2280450\n",
      "       CHEMBL203         200     32260   130240\n",
      "      CHEMBL2971         200    506160  3214186\n",
      "       CHEMBL301         200    105376   815967\n",
      "      CHEMBL5145         200   1666310  2240588\n"
     ]
    }
   ],
   "source": [
    "public = dlt.pipeline(pipeline_name=\"chembl\", destination=dlt.destinations.duckdb(str(WAREHOUSE)),\n",
    "                      dataset_name=\"raw\", pipelines_dir=str(PIPELINES))\n",
    "for run in (1, 2):\n",
    "    public.run(chembl())\n",
    "    log.info(\"ChEMBL run %d: %s\", run, rows_loaded(public))\n",
    "print(query(\"\"\"\n",
    "    SELECT target_chembl_id, count(*) AS activities,\n",
    "           min(activity_id) AS first_id, max(activity_id) AS last_id\n",
    "    FROM raw.chembl_activities GROUP BY ALL ORDER BY target_chembl_id\n",
    "\"\"\").to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each run brought 100 activities per target, and the second run's were all newer than the first's:\n",
    "the cursor did its job. ChEMBL's answers are JSON with values in their own types, so dlt inferred\n",
    "proper types this time:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{'activity_id': 'bigint', 'canonical_smiles': 'text', 'document_chembl_id': 'text', 'molecule_chembl_id': 'text', 'pchembl_value': 'text', 'relation': 'text', 'standard_relation': 'text', 'standard_type': 'text', 'standard_units': 'text', 'standard_value': 'text', 'target_chembl_id': 'text', 'type': 'text', 'units': 'text', 'value': 'text', 'licence': 'text'}\n"
     ]
    }
   ],
   "source": [
    "columns = public.default_schema.get_table_columns(\"chembl_activities\")\n",
    "print({name: column[\"data_type\"] for name, column in columns.items()\n",
    "       if not name.startswith(\"_dlt\")})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`activity_id` is a whole number (`bigint`), so its order is numeric and the cursor compares\n",
    "numbers. The potency values arrive from ChEMBL as text (`\"6.0\"`), and dlt keeps them as text:\n",
    "the raw layer records what the source sent. ChEMBL also sent four fields we did not list in\n",
    "`only`: `type`, `relation`, `value` and `units`, the values as the original paper reported them\n",
    "(that `\"6.0\"` nM was published as `\"0.006\"` µM). The raw layer keeps them too. Turning values into\n",
    "numbers, and units into nanomolar, is staging's job.\n",
    "\n",
    "## 6. What dlt records about every load\n",
    "\n",
    "dlt keeps a table `_dlt_loads` in each dataset, with one row per load: its ID, the schema, its\n",
    "status and when it finished. With `_dlt_load_id` on every row, any row can be traced to the run\n",
    "that wrote it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "schema_name  loads  status\n",
      "     chembl      2       0\n",
      "        lab      7       0\n",
      "       schema_name\n",
      "              main\n",
      "               raw\n",
      "       raw_staging\n",
      "        raw_strict\n",
      "raw_strict_staging\n"
     ]
    }
   ],
   "source": [
    "print(query(\"\"\"\n",
    "    SELECT schema_name, count(*) AS loads, max(status) AS status\n",
    "    FROM raw._dlt_loads GROUP BY ALL ORDER BY schema_name\n",
    "\"\"\").to_string(index=False))\n",
    "print(query(\"SELECT schema_name FROM information_schema.schemata \"\n",
    "            \"WHERE catalog_name = 'lab' ORDER BY schema_name\").to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Status `0` means the load completed. `main` is DuckDB's own default schema, empty here. The others\n",
    "are what dlt made: `raw` and `raw_strict`, the two datasets; and `raw_staging` and `raw_strict_staging`, where dlt puts rows for a moment before\n",
    "a merge. (These are dlt's own working tables, not the staging layer of Module 1, despite the\n",
    "name.) The registry, the assay files and ChEMBL are now in the raw layer, loaded by a tool that\n",
    "remembers what it loaded, absorbs duplicates, follows or refuses changes of shape, and keeps the\n",
    "licence. In Module 3 we decide the shape of the marts, and in Module 4 dbt builds the staging and\n",
    "mart layers from this raw layer.\n",
    "\n",
    "## Try it yourself\n",
    "\n",
    "The homework is a few questions, answered by running code like the code above: in a new cell at\n",
    "the end of the notebook, or in a script. It is at the end of the lesson's page, and in\n",
    "`homework.md` in the module's folder. The answers are published after the cohort's deadline.\n",
    "\n",
    "## Further reading\n",
    "\n",
    "- The dlt documentation. *Incremental loading*: cursors, `last_value` and the write dispositions.\n",
    "  <https://dlthub.com/docs/general-usage/incremental-loading>\n",
    "- The dlt documentation. *Schema and data contracts*: `evolve`, `freeze`, `discard_row` and\n",
    "  `discard_value`, for tables, columns and types. <https://dlthub.com/docs/general-usage/schema-contracts>\n",
    "- The dlt documentation. *REST API source*: the configuration dictionary, paginators and\n",
    "  incremental loading from APIs.\n",
    "  <https://dlthub.com/docs/dlt-ecosystem/verified-sources/rest_api/basic>\n",
    "- The dlt documentation. *State*: what a pipeline remembers between runs, and where.\n",
    "  <https://dlthub.com/docs/general-usage/state>\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",
    "- Reis, J. & Housley, M. (2022). *Fundamentals of Data Engineering*. O'Reilly Media. Chapter 7,\n",
    "  on ingestion: batch and streaming, push and pull, and the trade-offs of each."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
