{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# History and corrections\n",
    "\n",
    "Labs correct their data. Keep every version of each compound with dbt snapshots, taken week by week; keep superseded assay readings on record but out of the marts; and build the fact table incrementally, so that each week's build processes only that week's results.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-2/06-history-and-corrections/"
   ]
  },
  {
   "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] dbt-core dbt-duckdb duckdb pandas numpy rdkit\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(\"labstack.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/labstack.py\", \"labstack.py\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/dbt_project.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/dbt_project.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/dbt_project.yml\", \"stages/after-05/lab_dbt/dbt_project.yml\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/macros/generate_schema_name.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/macros/generate_schema_name.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/macros/generate_schema_name.sql\", \"stages/after-05/lab_dbt/macros/generate_schema_name.sql\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/macros/unique_combination.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/macros/unique_combination.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/macros/unique_combination.sql\", \"stages/after-05/lab_dbt/macros/unique_combination.sql\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/models/marts/_marts.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/models/marts/_marts.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/models/marts/_marts.yml\", \"stages/after-05/lab_dbt/models/marts/_marts.yml\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/models/marts/dim_compound.py\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/models/marts/dim_compound.py\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/models/marts/dim_compound.py\", \"stages/after-05/lab_dbt/models/marts/dim_compound.py\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/models/marts/dim_date.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/models/marts/dim_date.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/models/marts/dim_date.sql\", \"stages/after-05/lab_dbt/models/marts/dim_date.sql\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/models/marts/dim_target.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/models/marts/dim_target.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/models/marts/dim_target.sql\", \"stages/after-05/lab_dbt/models/marts/dim_target.sql\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/models/marts/fact_measurement.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/models/marts/fact_measurement.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/models/marts/fact_measurement.sql\", \"stages/after-05/lab_dbt/models/marts/fact_measurement.sql\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/models/marts/measurements_wide.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/models/marts/measurements_wide.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/models/marts/measurements_wide.sql\", \"stages/after-05/lab_dbt/models/marts/measurements_wide.sql\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/models/staging/_sources.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/models/staging/_sources.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/models/staging/_sources.yml\", \"stages/after-05/lab_dbt/models/staging/_sources.yml\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/models/staging/_staging.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/models/staging/_staging.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/models/staging/_staging.yml\", \"stages/after-05/lab_dbt/models/staging/_staging.yml\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/models/staging/stg_compounds.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/models/staging/stg_compounds.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/models/staging/stg_compounds.sql\", \"stages/after-05/lab_dbt/models/staging/stg_compounds.sql\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/models/staging/stg_results.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/models/staging/stg_results.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/models/staging/stg_results.sql\", \"stages/after-05/lab_dbt/models/staging/stg_results.sql\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/profiles.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/profiles.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/profiles.yml\", \"stages/after-05/lab_dbt/profiles.yml\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/seeds/targets.csv\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/seeds/targets.csv\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/seeds/targets.csv\", \"stages/after-05/lab_dbt/seeds/targets.csv\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/seeds/unit_to_nm.csv\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/seeds/unit_to_nm.csv\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/seeds/unit_to_nm.csv\", \"stages/after-05/lab_dbt/seeds/unit_to_nm.csv\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/tests/pic50_matches_ic50.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/tests/pic50_matches_ic50.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/tests/pic50_matches_ic50.sql\", \"stages/after-05/lab_dbt/tests/pic50_matches_ic50.sql\")\n",
    "if not pathlib.Path(\"stages/after-05/lab_dbt/tests/potency_in_plausible_range.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-05/lab_dbt/tests/potency_in_plausible_range.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-05/lab_dbt/tests/potency_in_plausible_range.sql\", \"stages/after-05/lab_dbt/tests/potency_in_plausible_range.sql\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[Module 5](../05-tests-and-contracts/) ended with two corrections and a question. In week 7 the\n",
    "lab registered LAB-0042 again with its right structure, and the warehouse simply replaced the old\n",
    "one: no trace was left of what the registry had said, or of what the dashboards had shown, for six\n",
    "weeks. In week 8 a plate was read again, and the corrected results arrived next to the first ones;\n",
    "the grain test caught the duplicates and dbt kept them out of the marts, but nothing yet says which\n",
    "reading counts.\n",
    "\n",
    "Both are **corrections**, and a warehouse that serves a lab must handle them on purpose. Chemists\n",
    "ask about the present (\"what is LAB-0042?\"), auditors and anyone checking an old decision ask about\n",
    "the past (\"what did we believe LAB-0042 was when we chose it for the panel?\"), and both must get a\n",
    "true answer. [Series 1, Module 13](../../series-1/13-versioning-everything/) versioned files and\n",
    "code by hand; here the warehouse keeps the versions of its own data.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- name the ways a dimension can handle change (the **slowly changing dimension** types) and choose\n",
    "  between them;\n",
    "- take **snapshots** with dbt, so that every version of every compound is kept with the dates it\n",
    "  was valid;\n",
    "- build a history dimension from the snapshots and answer questions \"as of\" a date;\n",
    "- keep corrected results on record and out of the marts, with a test that says what the grain\n",
    "  means now;\n",
    "- build the fact table **incrementally**, so that a build processes only new data, and know when\n",
    "  to rebuild it in full.\n",
    "\n",
    "## Setup\n",
    "\n",
    "This module needs the lab's history, so it starts again from week 1 and lets the weeks pass in\n",
    "section 2. The dbt project is the one [Module 5](../05-tests-and-contracts/) finished, with its\n",
    "tests; `labstack.dbt_project` copies it, and the functions are those of Module 5."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import shutil\n",
    "from pathlib import Path\n",
    "\n",
    "import duckdb\n",
    "import pandas as pd\n",
    "\n",
    "import labdata\n",
    "import labstack\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\"\n",
    "WAREHOUSE = WORK / \"lab.duckdb\"\n",
    "PIPELINES = WORK / \"dlt\"\n",
    "PROJECT = WORK / \"lab_dbt\"\n",
    "\n",
    "shutil.rmtree(WORK, ignore_errors=True)  # start clean\n",
    "lab = labdata.Lab()\n",
    "labstack.dbt_project(PROJECT, after=5)\n",
    "\n",
    "\n",
    "def write(name: str, text: str) -> None:\n",
    "    \"\"\"Save one file of the dbt project (made, with its folders, if it is new).\"\"\"\n",
    "    path = PROJECT / name\n",
    "    path.parent.mkdir(parents=True, exist_ok=True)\n",
    "    path.write_text(text.lstrip(\"\\n\"), encoding=\"utf-8\", newline=\"\\n\")\n",
    "\n",
    "\n",
    "def edit(name: str, old: str, new: str) -> None:\n",
    "    \"\"\"Change one passage of a file of the dbt project (it must be there exactly once).\"\"\"\n",
    "    text = (PROJECT / name).read_text(encoding=\"utf-8\")\n",
    "    assert text.count(old) == 1, f\"{name}: the passage to change is not there exactly once\"\n",
    "    write(name, text.replace(old, new))\n",
    "\n",
    "\n",
    "def dbt(*args: str):\n",
    "    \"\"\"Run a dbt command on the lab's project and log what it did (labstack.dbt).\"\"\"\n",
    "    return labstack.dbt(PROJECT, *args, log=log)\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": [
    "`edit` is new: most changes in this module are a few lines in a file that already exists, and\n",
    "`edit` makes them without repeating the whole file, refusing if the passage to change is missing or\n",
    "appears twice.\n",
    "\n",
    "## 1. How a dimension can change\n",
    "\n",
    "Kimball and Ross name the ways a dimension can handle a changed description the **slowly changing\n",
    "dimension** (SCD) types. The three that matter in practice:\n",
    "\n",
    "- **Type 0: never change.** The first value stays. Right for things that cannot change, such as the\n",
    "  date a compound was first registered.\n",
    "- **Type 1: overwrite.** The new value replaces the old, and the old is gone. This is what the\n",
    "  warehouse has done so far: the registry export is a snapshot, dlt replaces it, and `dim_compound`\n",
    "  shows only today's structure. Right when the old value was simply wrong and nobody will ask about\n",
    "  it again.\n",
    "- **Type 2: add a version.** The old row stays, marked as no longer valid from a date, and a new row\n",
    "  is added, valid from that date. Every version is kept, and a question can be asked \"as of\" any\n",
    "  date.\n",
    "\n",
    "![LAB-0042 over the twelve weeks: with type 1 (dim_compound) the corrected structure of week 7 replaces the wrong one and nothing records what was shown before; with type 2 (dim_compound_history) version 1 is kept, valid from 14 September to 19 October, and version 2 is valid from 19 October; LAB-0042's measurements, in weeks 3 and 4, were all made under version 1](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/06-history-and-corrections/figures/history-types.svg)\n",
    "\n",
    "A lab needs type 1 for its everyday questions (structure-activity work uses the true structure) and\n",
    "type 2 for its record (what did we believe, and when?). We keep both: `dim_compound` stays current,\n",
    "and a new `dim_compound_history` keeps every version.\n",
    "\n",
    "## 2. Snapshots, taken week by week\n",
    "\n",
    "Type 2 needs a record of every version, and the registry export cannot provide one: each week's file\n",
    "has only that week's view. Something must look at the registry every week and keep what changed.\n",
    "In dbt that is a **snapshot**. Each time `dbt snapshot` runs, it compares the source with the\n",
    "versions it has kept, by a key, and for each row that changed it closes the old version and adds a\n",
    "new one.\n",
    "\n",
    "A snapshot is declared in YAML: which table to watch, its key, and how to tell that a row changed.\n",
    "The `check` strategy compares the columns listed in `check_cols`. We list the registry's own\n",
    "columns and leave out `file_name`, which dlt adds and which changes every week: listing it would\n",
    "make a new version of every compound every week, though nothing about them had changed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"snapshots/registry_history.yml\", \"\"\"\n",
    "snapshots:\n",
    "  - name: registry_history\n",
    "    description: Every version of every compound the registry has held, kept week by week.\n",
    "    relation: source('raw', 'registry')\n",
    "    config:\n",
    "      schema: snapshots\n",
    "      unique_key: compound_id\n",
    "      strategy: check\n",
    "      check_cols: [smiles, salt, batch, chemist, vendor]\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A snapshot only sees what is there when it runs, so it must run every time new data arrives. Here\n",
    "the lab's first eight weeks pass, one at a time: each week the files arrive, dlt loads them, and\n",
    "dbt takes a snapshot. (This is the job [Module 7](../07-orchestration/) hands to an orchestrator.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO snapshot registry_history: success\n",
      "INFO snapshot registry_history: success\n",
      "INFO snapshot registry_history: success\n",
      "INFO snapshot registry_history: success\n",
      "INFO snapshot registry_history: success\n",
      "INFO snapshot registry_history: success\n",
      "INFO snapshot registry_history: success\n",
      "INFO snapshot registry_history: success\n"
     ]
    }
   ],
   "source": [
    "for week in range(1, 9):\n",
    "    labstack.load_raw(lab, range(week, week + 1), INBOX, WAREHOUSE, PIPELINES)\n",
    "    dbt(\"snapshot\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One snapshot a week, the first creating the table, the others adding to it. Here is what it kept\n",
    "for LAB-0042:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "compound_id                          smiles               file_name  current\n",
      "   LAB-0042 O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2 registry_2026-09-14.csv    False\n",
      "   LAB-0042 O=C(Nc1ccc(O)cc1)Nc2ccc(C#N)nc2 registry_2026-10-19.csv     True\n",
      " versions  compounds\n",
      "      321        320\n"
     ]
    }
   ],
   "source": [
    "print(query(\"\"\"\n",
    "    SELECT compound_id, smiles, file_name, dbt_valid_to IS NULL AS current\n",
    "    FROM snapshots.registry_history\n",
    "    WHERE compound_id = 'LAB-0042'\n",
    "    ORDER BY dbt_valid_from\n",
    "\"\"\").to_string(index=False))\n",
    "print(query(\"\"\"\n",
    "    SELECT count(*) AS versions, count(DISTINCT compound_id) AS compounds\n",
    "    FROM snapshots.registry_history\n",
    "\"\"\").to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Two versions: the wrong structure, first seen in week 2's export, and the corrected one, first seen\n",
    "in week 7's. Every other compound has one version, so the table has one row more than there are\n",
    "compounds. dbt added four columns: `dbt_scd_id` (a key for each version), `dbt_updated_at`,\n",
    "`dbt_valid_from` and `dbt_valid_to`, empty for the current version. Those two dates are the times\n",
    "the snapshots *ran*, which here were seconds apart, because eight weeks passed in one cell. In a\n",
    "real lab they would be a week apart, but they would still be the times dbt ran, not the times the\n",
    "lab made the changes. The lab's own dates are in the data: each version kept the name of the\n",
    "export it first appeared in, and the export's name carries its date.\n",
    "\n",
    "## 3. A history dimension\n",
    "\n",
    "`dim_compound_history` turns the snapshot into a dimension with the lab's dates: one row per\n",
    "version, valid from the date of the export that first held it until the date the next version\n",
    "appeared. `lead(...) OVER (...)` reads a column from the next row of the same compound, in order;\n",
    "`regexp_extract` takes the date out of the file name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO model dim_compound_history: success\n"
     ]
    }
   ],
   "source": [
    "write(\"models/marts/dim_compound_history.sql\", \"\"\"\n",
    "-- every version of every compound (SCD type 2), dated by the lab's own exports\n",
    "with versions as (\n",
    "    select compound_id,\n",
    "           split_part(smiles, '.', 1)  as parent_smiles,\n",
    "           coalesce(salt, '')          as salt,\n",
    "           chemist,\n",
    "           vendor,\n",
    "           registered_on::date         as registered_on,\n",
    "           regexp_extract(file_name, '\\\\d{4}-\\\\d{2}-\\\\d{2}')::date as valid_from,\n",
    "           dbt_valid_to is null        as is_current,\n",
    "           dbt_valid_from              as snapshot_from\n",
    "    from {{ ref('registry_history') }}\n",
    ")\n",
    "select row_number() over (order by compound_id, snapshot_from) as compound_version_key,\n",
    "       compound_id,\n",
    "       row_number() over (partition by compound_id order by snapshot_from) as version,\n",
    "       parent_smiles, salt, chemist, vendor, registered_on,\n",
    "       valid_from,\n",
    "       lead(valid_from) over (partition by compound_id order by snapshot_from) as valid_to,\n",
    "       is_current\n",
    "from versions\n",
    "\"\"\")\n",
    "built = dbt(\"build\", \"--select\", \"dim_compound_history\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The SQL is inside a Python string, so its backslashes are doubled: dbt receives `\\d{4}`, \"four\n",
    "digits\". Now a question only history can answer: when LAB-0042 was measured, what structure did\n",
    "the registry give it? The marts are rebuilt only in section 5, so this question reads the\n",
    "measurements' dates from the raw layer, and matches each with the version valid on its run date:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "result_id target   run_date  version                   parent_smiles\n",
      "  R-00179   EGFR 2026-09-23        1 O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2\n",
      "  R-00180   EGFR 2026-09-23        1 O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2\n",
      "  R-00257   ABL1 2026-09-30        1 O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2\n",
      "  R-00258   ABL1 2026-09-30        1 O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2\n",
      "  R-00259   BRAF 2026-09-30        1 O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2\n",
      "  R-00260   BRAF 2026-09-30        1 O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2\n",
      "  R-00261   CDK2 2026-09-30        1 O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2\n",
      "  R-00262   CDK2 2026-09-30        1 O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2\n",
      "  R-00263   JAK2 2026-09-30        1 O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2\n",
      "  R-00264   JAK2 2026-09-30        1 O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2\n"
     ]
    }
   ],
   "source": [
    "print(query(\"\"\"\n",
    "    SELECT a.result_id, a.target, a.run_date::DATE AS run_date, h.version, h.parent_smiles\n",
    "    FROM raw.assay AS a\n",
    "    JOIN marts.dim_compound_history AS h\n",
    "      ON h.compound_id = a.compound_id\n",
    "     AND a.run_date::DATE >= h.valid_from\n",
    "     AND (a.run_date::DATE < h.valid_to OR h.valid_to IS NULL)\n",
    "    WHERE a.compound_id = 'LAB-0042'\n",
    "    ORDER BY run_date, a.target, a.result_id\n",
    "\"\"\").to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every measurement of LAB-0042 was made while the registry still held the wrong structure. So any\n",
    "structure-activity conclusion drawn before week 7 used a molecule that was never made, and with\n",
    "the history in the warehouse anyone can now find which ones. The condition `run_date >= valid_from AND run_date <\n",
    "valid_to` picks the one version valid on a date, and `valid_to IS NULL` lets the current version\n",
    "run on forever. That pattern is how every \"as of\" question is asked of a type 2 dimension.\n",
    "\n",
    "## 4. Corrected results\n",
    "\n",
    "The plate read twice in week 8 is a correction of facts, not of a dimension. The lab's file says\n",
    "what happened: a `status` column marks the first reading `superseded` and the second `corrected`,\n",
    "and every other result is `final`. The warehouse should keep all of them (a superseded reading is\n",
    "part of the record) and use only the readings that count.\n",
    "\n",
    "First, staging passes the status on. One difficulty: the `status` column exists only in files from\n",
    "week 8 on, so in a warehouse holding earlier weeks only, the raw table has no such column and the\n",
    "model would fail. dbt can ask the warehouse which columns a table has while it compiles the model:\n",
    "`adapter.get_columns_in_relation(...)` returns them, and a Jinja `if` then writes `status` if it is\n",
    "there and `'final'` if it is not. The same is true of `unit`, which arrived in week 5: the model\n",
    "now copes with a raw table from any week of the project, which [Module 8](../08-observability/)\n",
    "needs. The model also passes on `load_id` (dlt's `_dlt_load_id`, the load that brought each row),\n",
    "which section 5 needs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"models/staging/stg_results.sql\", \"\"\"\n",
    "-- one row per result, every reading kept with its status; every value in nanomolar\n",
    "{%- set columns = adapter.get_columns_in_relation(source('raw', 'assay'))\n",
    "    | map(attribute='name') | list %}\n",
    "with typed as (\n",
    "    select result_id, compound_id, target, plate,\n",
    "           replicate::integer      as replicate,\n",
    "           relation,\n",
    "           value::double           as value,\n",
    "           -- 'units' was renamed 'unit' in week 5\n",
    "           {% if 'unit' in columns %}coalesce(unit, units){% else %}units{% endif %}\n",
    "                                   as unit,\n",
    "           -- 'status' arrived in week 8: superseded, corrected or final\n",
    "           {% if 'status' in columns %}coalesce(status, 'final'){% else %}'final'{% endif %}\n",
    "                                   as status,\n",
    "           run_date::date          as run_date,\n",
    "           file_name,\n",
    "           _dlt_load_id            as load_id\n",
    "    from {{ source('raw', 'assay') }}\n",
    ")\n",
    "select typed.* exclude (file_name),\n",
    "       value * u.factor              as ic50_nm,\n",
    "       9 - log10(value * u.factor)   as pic50,\n",
    "       relation = '='                as is_measured,  -- a value, not a bound\n",
    "       file_name                     as source_file\n",
    "from typed\n",
    "left join {{ ref('unit_to_nm') }} as u using (unit)\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Second, the grain. A superseded reading and its correction share a well, so the grain of Module 3\n",
    "holds only for the readings that count. A test's `where` setting restricts the rows it checks, and\n",
    "writing it down makes the grain precise: *one row per compound, target and well among the readings\n",
    "that are not superseded*. And `status` gets a test of its own, so a fourth value cannot creep in:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "edit(\"models/staging/_staging.yml\",\n",
    "     \"            columns: [compound_id, target, plate, replicate]\\n\",\n",
    "     \"            columns: [compound_id, target, plate, replicate]\\n\"\n",
    "     \"          config:\\n\"\n",
    "     \"            where: \\\"status <> 'superseded'\\\"  # a superseded reading shares its well\\n\")\n",
    "edit(\"models/staging/_staging.yml\",\n",
    "     \"      - name: ic50_nm\\n\",\n",
    "     \"      - name: status\\n\"\n",
    "     \"        data_tests:\\n\"\n",
    "     \"          - accepted_values:\\n\"\n",
    "     \"              arguments:\\n\"\n",
    "     \"                values: [final, superseded, corrected]\\n\"\n",
    "     \"      - name: ic50_nm\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. An incremental fact table\n",
    "\n",
    "The fact table so far is rebuilt in full on every build: every result of every week, joined again.\n",
    "At 1,000 rows that takes a moment; at the hundred million of a large screening group it takes\n",
    "hours, every night, to add one night's data. An **incremental** model is built in full once, and\n",
    "after that each build only adds (or updates) the rows that are new.\n",
    "\n",
    "Three settings make `fact_measurement` incremental: `materialized='incremental'`; a `unique_key`,\n",
    "so that a row that arrives again (a result whose status changed, say) replaces its old version\n",
    "instead of being added twice; and `on_schema_change='fail'`, so that a change of columns stops the\n",
    "build instead of quietly altering the table. The query then says which rows are new. `is_incremental()`\n",
    "is true when the table already exists, and `{{ this }}` is the table itself, so the `where` clause\n",
    "takes only the rows of loads newer than the newest already in the table. The fact table also\n",
    "keeps each row's `status` and `load_id` now, so its contract gains those two columns:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"models/marts/fact_measurement.sql\", \"\"\"\n",
    "-- one row per reading (superseded ones included, with their status); built incrementally\n",
    "{{ config(materialized='incremental', unique_key='result_id', on_schema_change='fail') }}\n",
    "select r.result_id,\n",
    "       c.compound_key,\n",
    "       t.target_key,\n",
    "       r.run_date,\n",
    "       r.plate,\n",
    "       r.replicate,\n",
    "       r.relation,\n",
    "       r.ic50_nm,\n",
    "       r.pic50,\n",
    "       r.status,\n",
    "       r.source_file,\n",
    "       r.load_id\n",
    "from {{ ref('stg_results') }} as r\n",
    "join {{ ref('dim_compound') }} as c using (compound_id)\n",
    "join {{ ref('dim_target') }} as t using (target)\n",
    "{% if is_incremental() %}\n",
    "-- only the loads that arrived since the last build\n",
    "where r.load_id > (select max(load_id) from {{ this }})\n",
    "{% endif %}\n",
    "\"\"\")\n",
    "edit(\"models/marts/_marts.yml\",\n",
    "     \"      - name: source_file\\n        data_type: varchar\\n  - name: measurements_wide\\n\",\n",
    "     \"      - name: status\\n        data_type: varchar\\n\"\n",
    "     \"      - name: source_file\\n        data_type: varchar\\n\"\n",
    "     \"      - name: load_id\\n        data_type: varchar\\n\"\n",
    "     \"        description: The dlt load that brought the row; the incremental build uses it.\\n\"\n",
    "     \"  - name: measurements_wide\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`load_id` works as a cursor because dlt gives each load an ID that grows with time, like the file\n",
    "names of Module 2. The marts' readers want only the readings that count, so the wide view leaves\n",
    "out the superseded ones; the fact table keeps them, and an analyst can still see them there:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO model dim_date: success\n",
      "INFO model stg_compounds: success\n",
      "INFO seed targets: success\n",
      "INFO seed unit_to_nm: success\n",
      "INFO snapshot registry_history: success\n",
      "INFO test not_null_dim_date_date_key: pass\n",
      "INFO test unique_dim_date_date_key: pass\n",
      "INFO test not_null_stg_compounds_compound_id: pass\n",
      "INFO test unique_stg_compounds_compound_id: pass\n",
      "INFO model dim_target: success\n",
      "INFO model stg_results: success\n",
      "INFO model dim_compound_history: success\n",
      "INFO model dim_compound: success\n",
      "INFO test accepted_values_dim_target_role__primary__panel: pass\n",
      "INFO test not_null_dim_target_target_key: pass\n",
      "INFO test unique_dim_target_target_key: pass\n",
      "INFO test accepted_values_stg_results_relation______: pass\n",
      "INFO test accepted_values_stg_results_status__final__superseded__corrected: pass\n",
      "INFO test not_null_stg_results_compound_id: pass\n",
      "INFO test not_null_stg_results_ic50_nm: pass\n",
      "INFO test not_null_stg_results_result_id: pass\n",
      "INFO test relationships_stg_results_compound_id__compound_id__ref_stg_compounds_: pass\n",
      "INFO test unique_combination_stg_results_compound_id__target__plate__replicate: pass\n",
      "INFO test unique_stg_results_result_id: pass\n",
      "INFO test not_null_dim_compound_compound_id: pass\n",
      "INFO test not_null_dim_compound_compound_key: pass\n",
      "INFO test unique_dim_compound_compound_id: pass\n",
      "INFO test unique_dim_compound_compound_key: pass\n",
      "INFO model fact_measurement: success\n",
      "INFO test pic50_matches_ic50: pass\n",
      "INFO test potency_in_plausible_range: pass\n",
      "INFO test relationships_fact_measurement_compound_key__compound_key__ref_dim_compound_: pass\n",
      "INFO test relationships_fact_measurement_run_date__date_key__ref_dim_date_: pass\n",
      "INFO test relationships_fact_measurement_target_key__target_key__ref_dim_target_: pass\n",
      "INFO model measurements_wide: success\n"
     ]
    }
   ],
   "source": [
    "edit(\"models/marts/measurements_wide.sql\",\n",
    "     \"join {{ ref('dim_date') }} as d on d.date_key = f.run_date\\n\",\n",
    "     \"join {{ ref('dim_date') }} as d on d.date_key = f.run_date\\n\"\n",
    "     \"where f.status <> 'superseded'  -- a corrected reading replaces it\\n\")\n",
    "built = dbt(\"build\", \"--full-refresh\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`--full-refresh` tells dbt to build incremental models from scratch, which is needed here because\n",
    "the old fact table had a different shape. Every test passed, the grain test included. The fact\n",
    "table now has the readings of all eight weeks, each with its status:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "    status  readings  with_new_ids\n",
      " corrected        40            40\n",
      "     final       952             0\n",
      "superseded        40             0\n",
      "compound_id target  mean_pic50  readings\n",
      "   LAB-0202   ABL1        4.90         1\n",
      "   LAB-0202   BRAF        6.10         2\n",
      "   LAB-0202   CDK2        5.63         2\n",
      "   LAB-0202   EGFR        7.73         2\n",
      "   LAB-0202   JAK2        5.60         2\n"
     ]
    }
   ],
   "source": [
    "print(query(\"\"\"\n",
    "    SELECT status, count(*) AS readings,\n",
    "           count(*) FILTER (WHERE result_id LIKE '%-c') AS with_new_ids\n",
    "    FROM marts.fact_measurement GROUP BY ALL ORDER BY status\n",
    "\"\"\").to_string(index=False))\n",
    "print(query(\"\"\"\n",
    "    SELECT compound_id, target, round(avg(pic50), 2) AS mean_pic50, count(*) AS readings\n",
    "    FROM marts.measurements_wide\n",
    "    WHERE compound_id = 'LAB-0202' AND relation = '='\n",
    "    GROUP BY ALL ORDER BY target\n",
    "\"\"\").to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The 40 superseded readings are on record in the fact table and out of the wide view, where\n",
    "LAB-0202's potencies now come from the corrected plate alone.\n",
    "\n",
    "Now the point of making it incremental. Week 9's files arrive, dlt loads them, and the warehouse\n",
    "is built again, this time without `--full-refresh`. The compiled SQL (in `target/compiled/`) shows\n",
    "the `where` clause that `is_incremental()` switched on, and counting the rows by load shows what it\n",
    "did:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO model stg_results: success\n",
      "INFO test accepted_values_stg_results_relation______: pass\n",
      "INFO test accepted_values_stg_results_status__final__superseded__corrected: pass\n",
      "INFO test not_null_stg_results_compound_id: pass\n",
      "INFO test not_null_stg_results_ic50_nm: pass\n",
      "INFO test not_null_stg_results_result_id: pass\n",
      "INFO test relationships_stg_results_compound_id__compound_id__ref_stg_compounds_: pass\n",
      "INFO test unique_combination_stg_results_compound_id__target__plate__replicate: pass\n",
      "INFO test unique_stg_results_result_id: pass\n",
      "INFO model fact_measurement: success\n",
      "INFO test pic50_matches_ic50: pass\n",
      "INFO test potency_in_plausible_range: pass\n",
      "INFO test relationships_fact_measurement_compound_key__compound_key__ref_dim_compound_: pass\n",
      "INFO test relationships_fact_measurement_run_date__date_key__ref_dim_date_: pass\n",
      "INFO test relationships_fact_measurement_target_key__target_key__ref_dim_target_: pass\n",
      "INFO model measurements_wide: success\n",
      "where r.load_id > (select max(load_id) from \"lab\".\"marts\".\"fact_measurement\")\n",
      " from_this_build                                              files  readings\n",
      "           False assay_2026-09-14.csv, assay_2026-09-21_resent.c...      1032\n",
      "            True                               assay_2026-11-02.csv       144\n",
      "readings before the build: 1032\n"
     ]
    }
   ],
   "source": [
    "before = query(\"SELECT count(*) AS n, max(load_id) AS newest FROM marts.fact_measurement\")\n",
    "labstack.load_raw(lab, range(9, 10), INBOX, WAREHOUSE, PIPELINES)\n",
    "built = dbt(\"build\", \"--select\", \"stg_results+\")\n",
    "compiled = PROJECT / \"target\" / \"compiled\" / \"lab\" / \"models\" / \"marts\" / \"fact_measurement.sql\"\n",
    "print(\"\\n\".join(line for line in compiled.read_text(encoding=\"utf-8\").splitlines()\n",
    "                if \"load_id >\" in line))\n",
    "newest = before[\"newest\"][0]\n",
    "print(query(f\"\"\"\n",
    "    SELECT load_id > '{newest}' AS from_this_build,\n",
    "           string_agg(DISTINCT source_file, ', ' ORDER BY source_file) AS files,\n",
    "           count(*) AS readings\n",
    "    FROM marts.fact_measurement GROUP BY ALL ORDER BY from_this_build\n",
    "\"\"\").to_string(index=False, max_colwidth=50))\n",
    "print(\"readings before the build:\", before[\"n\"][0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Week 9's build of fact_measurement: a full rebuild reads loads 1 to 9 again and rewrites all 1,176 rows; the incremental build reads only load 9, the 144 new rows, and merges them](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/06-history-and-corrections/figures/incremental.svg)\n",
    "\n",
    "The build took only the rows of the newest load, week 9's file, and merged them into the table;\n",
    "weeks 1 to 8 were not read again. Incremental models come with a duty, though. A change to the\n",
    "model's logic (a new column, a corrected formula) applies only to rows built after the change, so\n",
    "the table ends up half old and half new. Any change to an incremental model's SQL needs\n",
    "`--full-refresh` once, and a team should know which of its models are incremental and why.\n",
    "\n",
    "## 6. What the warehouse keeps now\n",
    "\n",
    "The warehouse keeps every version of every compound (`snapshots.registry_history`, and\n",
    "`dim_compound_history` with the lab's dates), every reading with its status (`fact_measurement`),\n",
    "and the current, correct view for everyday questions (`dim_compound`, `measurements_wide`). Here\n",
    "is the project's lineage, with the snapshot in it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO everything built from the snapshot:\n",
      "lab.marts.dim_compound_history\n",
      "lab.registry_history\n"
     ]
    }
   ],
   "source": [
    "log.info(\"everything built from the snapshot:\")\n",
    "names = dbt(\"ls\", \"--select\", \"registry_history+\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So far every week's load, snapshot and build has been started by hand, in the right order, by\n",
    "someone who knew to do it. Skip a week's snapshot and that week's changes are lost for good. In\n",
    "[Module 7](../07-orchestration/) the weekly run becomes a **flow** that an orchestrator, Prefect,\n",
    "starts on a schedule and when new files arrive, retries when something fails, and records.\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 dbt documentation. *Add snapshots to your DAG*: strategies, `check_cols`, the meta-fields and\n",
    "  hard deletes. <https://docs.getdbt.com/docs/build/snapshots>\n",
    "- The dbt documentation. *Configure incremental models*: `is_incremental()`, `unique_key`,\n",
    "  strategies and `on_schema_change`. <https://docs.getdbt.com/docs/build/incremental-models>\n",
    "- Kimball, R. & Ross, M. (2013). *The Data Warehouse Toolkit: The Definitive Guide to Dimensional\n",
    "  Modeling* (3rd ed.). Wiley. Chapter 5: slowly changing dimension types 0 to 7.\n",
    "- Snodgrass, R. T. (1999). *Developing Time-Oriented Database Applications in SQL*. Morgan\n",
    "  Kaufmann. Valid time and transaction time: the two clocks of section 2, in depth."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
