{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tests and contracts in the warehouse\n",
    "\n",
    "Check every build. dbt tests for keys, values, relationships and the grain, written once next to the models and run after each one; a contract that fixes a table's columns and types; chemistry checks on the compound dimension with pandera-chem. Then two new weeks of data arrive, a test fails, and dbt keeps the wrong rows out of the marts.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-2/05-tests-and-contracts/"
   ]
  },
  {
   "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 pandera pandera-chem\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-04/lab_dbt/dbt_project.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/dbt_project.yml\", \"stages/after-04/lab_dbt/dbt_project.yml\")\n",
    "if not pathlib.Path(\"stages/after-04/lab_dbt/macros/generate_schema_name.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/macros/generate_schema_name.sql\", \"stages/after-04/lab_dbt/macros/generate_schema_name.sql\")\n",
    "if not pathlib.Path(\"stages/after-04/lab_dbt/models/marts/_marts.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/models/marts/_marts.yml\", \"stages/after-04/lab_dbt/models/marts/_marts.yml\")\n",
    "if not pathlib.Path(\"stages/after-04/lab_dbt/models/marts/dim_compound.py\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/models/marts/dim_compound.py\", \"stages/after-04/lab_dbt/models/marts/dim_compound.py\")\n",
    "if not pathlib.Path(\"stages/after-04/lab_dbt/models/marts/dim_date.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/models/marts/dim_date.sql\", \"stages/after-04/lab_dbt/models/marts/dim_date.sql\")\n",
    "if not pathlib.Path(\"stages/after-04/lab_dbt/models/marts/dim_target.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/models/marts/dim_target.sql\", \"stages/after-04/lab_dbt/models/marts/dim_target.sql\")\n",
    "if not pathlib.Path(\"stages/after-04/lab_dbt/models/marts/fact_measurement.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/models/marts/fact_measurement.sql\", \"stages/after-04/lab_dbt/models/marts/fact_measurement.sql\")\n",
    "if not pathlib.Path(\"stages/after-04/lab_dbt/models/marts/measurements_wide.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/models/marts/measurements_wide.sql\", \"stages/after-04/lab_dbt/models/marts/measurements_wide.sql\")\n",
    "if not pathlib.Path(\"stages/after-04/lab_dbt/models/staging/_sources.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/models/staging/_sources.yml\", \"stages/after-04/lab_dbt/models/staging/_sources.yml\")\n",
    "if not pathlib.Path(\"stages/after-04/lab_dbt/models/staging/stg_compounds.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/models/staging/stg_compounds.sql\", \"stages/after-04/lab_dbt/models/staging/stg_compounds.sql\")\n",
    "if not pathlib.Path(\"stages/after-04/lab_dbt/models/staging/stg_results.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/models/staging/stg_results.sql\", \"stages/after-04/lab_dbt/models/staging/stg_results.sql\")\n",
    "if not pathlib.Path(\"stages/after-04/lab_dbt/profiles.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/profiles.yml\", \"stages/after-04/lab_dbt/profiles.yml\")\n",
    "if not pathlib.Path(\"stages/after-04/lab_dbt/seeds/targets.csv\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/seeds/targets.csv\", \"stages/after-04/lab_dbt/seeds/targets.csv\")\n",
    "if not pathlib.Path(\"stages/after-04/lab_dbt/seeds/unit_to_nm.csv\").exists():\n",
    "    pathlib.Path(\"stages/after-04/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-04/lab_dbt/seeds/unit_to_nm.csv\", \"stages/after-04/lab_dbt/seeds/unit_to_nm.csv\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The warehouse of [Module 4](../04-transformations-with-lineage/) builds without an error. That\n",
    "says the SQL ran; it says nothing about the data. A resent file with new IDs, a compound measured\n",
    "twice on the same well, a unit nobody has seen, a structure that is not a molecule: each of these\n",
    "builds without complaint and reaches the dashboards, where a chemist finds it, or does not.\n",
    "\n",
    "[Series 1, Module 12](../../series-1/12-validating-data/) checked data in Python, with Pandera,\n",
    "before loading it. A warehouse needs the same idea at every layer, because each layer is built from\n",
    "the one before and can go wrong in its own way. In dbt a check is a **test**: a query that returns\n",
    "the rows that break a rule. No rows means the test passes. Tests are declared next to the models\n",
    "they check, and `dbt build` runs each model's tests as soon as the model is built, before anything\n",
    "is built from it. That order is the point of this module: when a test fails, dbt **skips**\n",
    "everything downstream, so the marts keep their last good data instead of taking in bad data.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- add dbt's four built-in tests (`unique`, `not_null`, `accepted_values`, `relationships`) to\n",
    "  models and columns;\n",
    "- write your own tests: a reusable **generic** test for the grain, and **singular** tests for\n",
    "  rules that belong to one model, with a severity;\n",
    "- put an enforced **contract** on a model, so that its columns and types cannot change by accident;\n",
    "- check the compound dimension's chemistry with pandera-chem, and quarantine what fails;\n",
    "- read what a failing build did, and why the marts were left as they were.\n",
    "\n",
    "## Setup\n",
    "\n",
    "The raw layer comes from Module 2's pipeline, for the first six weeks, as before.\n",
    "`labstack.dbt_project` copies the dbt project as Module 4 finished it (it is saved in the series'\n",
    "`stages/` folder), and `labstack.dbt` runs a dbt command on it and logs one line per model, seed or\n",
    "test, as the `dbt` function of Module 4 did. Two more packages check the chemistry: Pandera\n",
    "(`pa`) and pandera-chem (`pc`), the plugin from Series 1."
   ]
  },
  {
   "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",
    "import pandera.pandas as pa\n",
    "import pandera_chem as pc\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",
    "WAREHOUSE = WORK / \"lab.duckdb\"\n",
    "PROJECT = WORK / \"lab_dbt\"\n",
    "WEEKS = 6  # the lab is at the end of week 6; weeks 7 and 8 arrive in section 6\n",
    "\n",
    "shutil.rmtree(WORK, ignore_errors=True)  # start clean\n",
    "lab = labdata.Lab()\n",
    "pipeline = labstack.load_raw(lab, WEEKS, WORK / \"inbox\", WAREHOUSE, WORK / \"dlt\")\n",
    "labstack.dbt_project(PROJECT, after=4)\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 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": [
    "First, the warehouse as Module 4 left it:"
   ]
  },
  {
   "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 model dim_compound: success\n",
      "INFO model dim_target: success\n",
      "INFO model stg_results: success\n",
      "INFO model fact_measurement: success\n",
      "INFO model measurements_wide: success\n"
     ]
    }
   ],
   "source": [
    "built = dbt(\"build\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Nine models and seeds, and no tests yet.\n",
    "\n",
    "## 1. dbt's four built-in tests\n",
    "\n",
    "dbt comes with four tests that cover most of what goes wrong with keys and values:\n",
    "\n",
    "- `unique`: no value appears twice in the column;\n",
    "- `not_null`: no value is empty;\n",
    "- `accepted_values`: every value is one of a list;\n",
    "- `relationships`: every value exists in a column of another model (a foreign key, checked).\n",
    "\n",
    "Tests are declared under `data_tests:` in the same YAML files that hold the descriptions. A test\n",
    "that needs settings (the list of values, the other model) takes them under `arguments:`. Here are\n",
    "tests for the staging models, in a new file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"models/staging/_staging.yml\", \"\"\"\n",
    "models:\n",
    "  - name: stg_compounds\n",
    "    description: The current registry, one row per compound.\n",
    "    columns:\n",
    "      - name: compound_id\n",
    "        data_tests: [unique, not_null]\n",
    "  - name: stg_results\n",
    "    description: One row per result, every value in nanomolar.\n",
    "    columns:\n",
    "      - name: result_id\n",
    "        data_tests: [unique, not_null]\n",
    "      - name: compound_id\n",
    "        data_tests:\n",
    "          - not_null\n",
    "          - relationships:\n",
    "              arguments:\n",
    "                to: ref('stg_compounds')\n",
    "                field: compound_id\n",
    "      - name: relation\n",
    "        data_tests:\n",
    "          - accepted_values:\n",
    "              arguments:\n",
    "                values: ['=', '>']\n",
    "      - name: ic50_nm\n",
    "        description: Empty if the unit is not in the unit_to_nm seed.\n",
    "        data_tests: [not_null]\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each line is a rule the lab has already met. `relationships` catches a result for a compound the\n",
    "registry does not know (a typing error in an ID, or a registry export that is out of date).\n",
    "`accepted_values` catches a relation nobody has defined, such as `<`. `not_null` on `ic50_nm`\n",
    "catches a new unit spelling: [Module 1](../01-lab-data-architecture/) made the unit table a\n",
    "decision on record, and this test is what makes a new spelling stop the build instead of slipping\n",
    "through as an empty value.\n",
    "\n",
    "The marts' YAML file already exists, and dbt allows each model to be described in one file only,\n",
    "so we write it again, with its descriptions as before and tests added: keys that must be unique\n",
    "and present, the fact table's keys checked against the dimensions, and the target roles."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO test accepted_values_dim_target_role__primary__panel: pass\n",
      "INFO test accepted_values_stg_results_relation______: pass\n",
      "INFO test not_null_dim_compound_compound_id: pass\n",
      "INFO test not_null_dim_compound_compound_key: pass\n",
      "INFO test not_null_dim_date_date_key: pass\n",
      "INFO test not_null_dim_target_target_key: pass\n",
      "INFO test not_null_stg_compounds_compound_id: 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_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 test relationships_stg_results_compound_id__compound_id__ref_stg_compounds_: pass\n",
      "INFO test unique_dim_compound_compound_id: pass\n",
      "INFO test unique_dim_compound_compound_key: pass\n",
      "INFO test unique_dim_date_date_key: pass\n",
      "INFO test unique_dim_target_target_key: pass\n",
      "INFO test unique_stg_compounds_compound_id: pass\n",
      "INFO test unique_stg_results_result_id: pass\n",
      "20 of 20 tests passed\n"
     ]
    }
   ],
   "source": [
    "write(\"models/marts/_marts.yml\", \"\"\"\n",
    "models:\n",
    "  - name: dim_compound\n",
    "    description: One row per compound in the current registry, with its chemical series and\n",
    "      properties worked out once with RDKit.\n",
    "    columns:\n",
    "      - name: compound_key\n",
    "        description: The warehouse's key for the compound (a surrogate key).\n",
    "        data_tests: [unique, not_null]\n",
    "      - name: compound_id\n",
    "        description: The lab's ID for the compound (the natural key), e.g. LAB-0042.\n",
    "        data_tests: [unique, not_null]\n",
    "      - name: series\n",
    "        description: The series whose core the parent contains; empty if none or several, for a\n",
    "          person to check.\n",
    "      - name: clogp\n",
    "        description: Crippen's estimate of the octanol-water partition coefficient (RDKit).\n",
    "  - name: dim_target\n",
    "    columns:\n",
    "      - name: target_key\n",
    "        data_tests: [unique, not_null]\n",
    "      - name: role\n",
    "        data_tests:\n",
    "          - accepted_values:\n",
    "              arguments:\n",
    "                values: [primary, panel]\n",
    "  - name: dim_date\n",
    "    columns:\n",
    "      - name: date_key\n",
    "        data_tests: [unique, not_null]\n",
    "  - name: fact_measurement\n",
    "    description: One row per measurement of one compound on one target, in one well of one plate.\n",
    "    columns:\n",
    "      - name: compound_key\n",
    "        data_tests:\n",
    "          - relationships:\n",
    "              arguments:\n",
    "                to: ref('dim_compound')\n",
    "                field: compound_key\n",
    "      - name: target_key\n",
    "        data_tests:\n",
    "          - relationships:\n",
    "              arguments:\n",
    "                to: ref('dim_target')\n",
    "                field: target_key\n",
    "      - name: run_date\n",
    "        data_tests:\n",
    "          - relationships:\n",
    "              arguments:\n",
    "                to: ref('dim_date')\n",
    "                field: date_key\n",
    "      - name: relation\n",
    "        description: \"'=' for a measured value; '>' when the compound was weaker than the highest\n",
    "          concentration tested, so ic50_nm is only a bound.\"\n",
    "      - name: pic50\n",
    "        description: 9 - log10(ic50_nm). Average potencies as pIC50, over measured values only.\n",
    "  - name: measurements_wide\n",
    "    description: The star joined once, for dashboards. Built from the star; never edit it.\n",
    "\"\"\")\n",
    "results = dbt(\"test\")\n",
    "print(sum(r.status == \"pass\" for r in results), \"of\", len(results), \"tests passed\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`dbt test` runs the tests alone, on the tables as they are. dbt names each test after its rule, its\n",
    "model and its column, so a failure says where to look. In [Module\n",
    "3](../03-modelling-the-warehouse/) the database itself enforced the star's keys; dbt-built tables\n",
    "carry no constraints of their own, so these tests now do that job (and they work the same on\n",
    "warehouses that do not enforce keys at all).\n",
    "\n",
    "## 2. Your own tests\n",
    "\n",
    "Two of the lab's rules are not on dbt's list. The first is the **grain** of Module 3: one row per\n",
    "compound, target, plate and replicate. `unique` checks one column; the grain is four. dbt lets you\n",
    "write your own **generic test**, a test that any model can use, as a macro between `{% test %}` and\n",
    "`{% endtest %}`. Its arguments are the model and any settings; its query returns the rows that\n",
    "break the rule. This one returns each combination of the columns that appears more than once:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"macros/unique_combination.sql\", \"\"\"\n",
    "{% test unique_combination(model, columns) %}\n",
    "-- every combination of the columns appears once: the rows returned are the ones that repeat\n",
    "select {{ columns | join(', ') }}, count(*) as copies\n",
    "from {{ model }}\n",
    "group by {{ columns | join(', ') }}\n",
    "having count(*) > 1\n",
    "{% endtest %}\n",
    "\"\"\")\n",
    "text = (PROJECT / \"models\" / \"staging\" / \"_staging.yml\").read_text(encoding=\"utf-8\")\n",
    "write(\"models/staging/_staging.yml\", text.replace(\n",
    "    \"\"\"  - name: stg_results\n",
    "    description: One row per result, every value in nanomolar.\n",
    "\"\"\",\n",
    "    \"\"\"  - name: stg_results\n",
    "    description: One row per result, every value in nanomolar.\n",
    "    data_tests:\n",
    "      - unique_combination:  # the grain: one result per compound, target and well\n",
    "          arguments:\n",
    "            columns: [compound_id, target, plate, replicate]\n",
    "\"\"\",\n",
    "))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`{{ columns | join(', ') }}` is Jinja: the list of columns written out with commas between them.\n",
    "The test sits under the model, not under a column, because it is about rows.\n",
    "\n",
    "The second kind of rule belongs to one model only. dbt calls such a test **singular**: a SQL file\n",
    "in the project's `tests/` folder that returns the rows breaking the rule. One checks that every\n",
    "pIC50 is what its IC50 says it is (9 − log₁₀ of the value in nanomolar), a rule a change to the\n",
    "staging model could break without anyone noticing:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"tests/pic50_matches_ic50.sql\", \"\"\"\n",
    "-- every pIC50 is 9 - log10 of its IC50 in nanomolar\n",
    "select result_id, ic50_nm, pic50\n",
    "from {{ ref('fact_measurement') }}\n",
    "where abs(pic50 - (9 - log10(ic50_nm))) > 1e-9\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Not every rule should stop a build. A measured pIC50 above 10 (an IC50 below 0.1 nM) is possible,\n",
    "but rare enough that a person should look. A test's **severity** decides: `error` (the default)\n",
    "fails the build, `warn` reports and carries on. The `config` line at the top of a singular test sets\n",
    "it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO test pic50_matches_ic50: pass\n",
      "INFO test potency_in_plausible_range: pass\n",
      "INFO test unique_combination_stg_results_compound_id__target__plate__replicate: pass\n"
     ]
    }
   ],
   "source": [
    "write(\"tests/potency_in_plausible_range.sql\", \"\"\"\n",
    "{{ config(severity='warn') }}\n",
    "-- measured potencies outside 3 to 10 are possible but rare: a person should look\n",
    "select result_id, compound_key, target_key, pic50\n",
    "from {{ ref('fact_measurement') }}\n",
    "where relation = '=' and (pic50 < 3 or pic50 > 10)\n",
    "\"\"\")\n",
    "results = dbt(\"test\", \"--select\", \"unique_combination_stg_results_compound_id__target__plate\"\n",
    "              \"__replicate pic50_matches_ic50 potency_in_plausible_range\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`--select` takes several names at once, separated by spaces. All three pass on the first six weeks.\n",
    "\n",
    "## 3. A contract\n",
    "\n",
    "Tests check a table's *content* after it is built. A **contract** checks its *shape* before it is\n",
    "built: the names of its columns, their order and their types. With an enforced contract, dbt\n",
    "compares the model's query with the contract first, and refuses to build the table if they differ.\n",
    "That protects everything that reads the table (a dashboard, a model, another team's code) from a\n",
    "change nobody announced: the same job dlt's frozen schema contract did for the raw layer in [Module\n",
    "2](../02-declarative-ingestion/), section 4.\n",
    "\n",
    "A contract is declared in the model's YAML, with `contract: {enforced: true}` and a `data_type` for\n",
    "every column. Constraints such as `not_null` can be added too, and dbt builds them into the table\n",
    "where the database supports them. We add one to the fact table, in the marts' YAML:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "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"
     ]
    }
   ],
   "source": [
    "CONTRACT = \"\"\"\n",
    "  - name: fact_measurement\n",
    "    description: One row per measurement of one compound on one target, in one well of one plate.\n",
    "    config:\n",
    "      contract:\n",
    "        enforced: true\n",
    "    columns:\n",
    "      - name: result_id\n",
    "        data_type: varchar\n",
    "        constraints: [{type: not_null}, {type: primary_key}]\n",
    "      - name: compound_key\n",
    "        data_type: bigint\n",
    "        constraints: [{type: not_null}]\n",
    "        data_tests:\n",
    "          - relationships:\n",
    "              arguments:\n",
    "                to: ref('dim_compound')\n",
    "                field: compound_key\n",
    "      - name: target_key\n",
    "        data_type: bigint\n",
    "        constraints: [{type: not_null}]\n",
    "        data_tests:\n",
    "          - relationships:\n",
    "              arguments:\n",
    "                to: ref('dim_target')\n",
    "                field: target_key\n",
    "      - name: run_date\n",
    "        data_type: date\n",
    "        data_tests:\n",
    "          - relationships:\n",
    "              arguments:\n",
    "                to: ref('dim_date')\n",
    "                field: date_key\n",
    "      - name: plate\n",
    "        data_type: varchar\n",
    "      - name: replicate\n",
    "        data_type: integer\n",
    "      - name: relation\n",
    "        data_type: varchar\n",
    "        description: \"'=' for a measured value; '>' when the compound was weaker than the highest\n",
    "          concentration tested, so ic50_nm is only a bound.\"\n",
    "      - name: ic50_nm\n",
    "        data_type: double\n",
    "      - name: pic50\n",
    "        data_type: double\n",
    "        description: 9 - log10(ic50_nm). Average potencies as pIC50, over measured values only.\n",
    "      - name: source_file\n",
    "        data_type: varchar\n",
    "\"\"\"\n",
    "text = (PROJECT / \"models\" / \"marts\" / \"_marts.yml\").read_text(encoding=\"utf-8\")\n",
    "start = text.index(\"  - name: fact_measurement\")\n",
    "end = text.index(\"  - name: measurements_wide\")\n",
    "write(\"models/marts/_marts.yml\", text[:start] + CONTRACT.lstrip(\"\\n\") + text[end:])\n",
    "built = dbt(\"build\", \"--select\", \"fact_measurement\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The fact table was rebuilt under its contract, and its tests ran after it. Now suppose someone\n",
    "changes the model so that `replicate` becomes text. The build stops before the table is touched,\n",
    "and dbt's message is a table of exactly what differs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO model fact_measurement: error\n",
      "INFO test pic50_matches_ic50: skipped\n",
      "INFO test potency_in_plausible_range: skipped\n",
      "INFO test relationships_fact_measurement_compound_key__compound_key__ref_dim_compound_: skipped\n",
      "INFO test relationships_fact_measurement_run_date__date_key__ref_dim_date_: skipped\n",
      "INFO test relationships_fact_measurement_target_key__target_key__ref_dim_target_: skipped\n",
      "  | column_name | definition_type | contract_type | mismatch_reason    |\n",
      "  | ----------- | --------------- | ------------- | ------------------ |\n",
      "  | replicate   | VARCHAR         | INTEGER       | data type mismatch |\n"
     ]
    }
   ],
   "source": [
    "model = PROJECT / \"models\" / \"marts\" / \"fact_measurement.sql\"\n",
    "good = model.read_text(encoding=\"utf-8\")\n",
    "model.write_text(good.replace(\"r.replicate,\", \"r.replicate::varchar as replicate,\"),\n",
    "                 encoding=\"utf-8\", newline=\"\\n\")\n",
    "try:\n",
    "    dbt(\"build\", \"--select\", \"fact_measurement\")\n",
    "except RuntimeError as error:\n",
    "    print(\"\\n\".join(line for line in str(error).splitlines() if line.strip().startswith(\"|\")))\n",
    "model.write_text(good, encoding=\"utf-8\", newline=\"\\n\")  # put the model back"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The old table, with the right types, is still there for everyone who reads it. Contracts suit the\n",
    "tables other people depend on, the marts; staging models change often and are read only by the\n",
    "project itself, so most teams leave them without.\n",
    "\n",
    "## 4. Checking the chemistry\n",
    "\n",
    "dbt's tests are SQL, and SQL cannot tell a valid structure from an invalid one. pandera-chem can.\n",
    "Its checks go in a Pandera schema, as in Series 1, and `pc.split` sorts a table into the rows that\n",
    "pass and the rows that do not (the **quarantine**), with a report that accounts for every row. The\n",
    "schema for the compound dimension says what every compound in the warehouse must be: a valid\n",
    "SMILES with no salt left in it (one fragment), made of the elements the lab's chemistry uses, of a\n",
    "sensible size, never registered twice, and in a series. `nullable=False` is Pandera's own check\n",
    "that a column has no empty values:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "240 rows in: 239 valid, 1 quarantined\n",
      "       1  series: not_nullable\n",
      "compound_id                   parent_smiles              reasons\n",
      "   LAB-0042 O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2 series: not_nullable\n"
     ]
    }
   ],
   "source": [
    "compound_rules = pa.DataFrameSchema({\n",
    "    \"parent_smiles\": pa.Column(str, [\n",
    "        pc.valid_smiles(),\n",
    "        pc.single_fragment(),\n",
    "        pc.allowed_elements({\"H\", \"C\", \"N\", \"O\", \"F\", \"S\", \"Cl\", \"Br\"}),\n",
    "        pc.heavy_atoms(10, 60),\n",
    "        pc.mol_weight(700),\n",
    "        pc.unique_molecules(),\n",
    "    ]),\n",
    "    \"series\": pa.Column(str, nullable=False),\n",
    "})\n",
    "compounds = query(\"SELECT * FROM marts.dim_compound ORDER BY compound_key\")\n",
    "checked = pc.split(compounds, compound_rules)\n",
    "print(checked.report)\n",
    "print(checked.quarantined[[\"compound_id\", \"parent_smiles\", \"reasons\"]].to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One compound in quarantine, for the reason Module 3 found by hand: LAB-0042 is in no series. The\n",
    "check now runs on every build, so it will be noticed every time instead of once. Where it runs\n",
    "matters too. Here it runs after `dbt build`, in Python, which is how [Module\n",
    "7](../07-orchestration/) will run it: as a step of the pipeline, after the build and before\n",
    "anything is published. Everything else about the structures passed: they are valid, salt-free,\n",
    "unique and of a sensible size.\n",
    "\n",
    "## 5. Two more weeks\n",
    "\n",
    "The lab moves on. Weeks 7 and 8 bring their files: a new registry, and the assay results of both\n",
    "weeks. `labstack.load_raw` carries on the same dlt pipeline from week 7 (dlt remembers which files\n",
    "it has loaded), and then the warehouse is built as usual:"
   ]
  },
  {
   "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 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: 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 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: fail\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: skipped\n",
      "INFO test pic50_matches_ic50: skipped\n",
      "INFO test potency_in_plausible_range: skipped\n",
      "INFO test relationships_fact_measurement_compound_key__compound_key__ref_dim_compound_: skipped\n",
      "INFO test relationships_fact_measurement_run_date__date_key__ref_dim_date_: skipped\n",
      "INFO test relationships_fact_measurement_target_key__target_key__ref_dim_target_: skipped\n",
      "INFO model measurements_wide: skipped\n"
     ]
    }
   ],
   "source": [
    "labstack.load_raw(lab, range(7, 9), WORK / \"inbox\", WAREHOUSE, WORK / \"dlt\")\n",
    "built = dbt(\"build\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The grain test failed, and dbt did what it should: it built the staging layer, ran its tests, and\n",
    "when one failed it **skipped** the fact table, its tests and the wide view, all of which are built\n",
    "from the failing model. The marts were not rebuilt, so they still hold the measurements of weeks 1\n",
    "to 6, correct but a week behind:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " measurements     latest\n",
      "          656 2026-10-14\n"
     ]
    }
   ],
   "source": [
    "print(query(\"SELECT count(*) AS measurements, max(run_date) AS latest FROM marts.fact_measurement\")\n",
    "      .to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Week 8's build: stg_compounds, stg_results and the three dimensions were built; stg_results' grain test failed (plate P08-01 was read twice, so 40 wells have two rows) while its other tests passed; fact_measurement and measurements_wide were skipped and their tests not run, so the marts keep weeks 1 to 6](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/05-tests-and-contracts/figures/build-week8.svg)\n",
    "\n",
    "Stale data with a failing test beside it is a much better state than fresh data that is wrong: the\n",
    "chemists can be told the dashboards are paused, and nobody makes a decision on numbers that are\n",
    "counted twice. The test's query shows what broke it, and the raw table shows why:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "compound_id target  plate  replicate  copies\n",
      "   LAB-0202   ABL1 P08-01          1       2\n",
      "   LAB-0202   ABL1 P08-01          2       2\n",
      "   LAB-0202   BRAF P08-01          1       2\n",
      "   LAB-0202   BRAF P08-01          2       2\n",
      "result_id compound_id target replicate value     status\n",
      "  R-00809    LAB-0202   ABL1         1  25.1 superseded\n",
      "R-00809-c    LAB-0202   ABL1         1  12.6  corrected\n",
      "  R-00810    LAB-0202   ABL1         2  30.0 superseded\n",
      "R-00810-c    LAB-0202   ABL1         2  15.0  corrected\n"
     ]
    }
   ],
   "source": [
    "print(query(\"\"\"\n",
    "    SELECT compound_id, target, plate, replicate, count(*) AS copies\n",
    "    FROM staging.stg_results\n",
    "    GROUP BY ALL HAVING count(*) > 1\n",
    "    ORDER BY plate, compound_id, target, replicate\n",
    "\"\"\").head(4).to_string(index=False))\n",
    "print(query(\"\"\"\n",
    "    SELECT result_id, compound_id, target, replicate, value, status\n",
    "    FROM raw.assay\n",
    "    WHERE compound_id = 'LAB-0202' AND target = 'ABL1' AND plate = 'P08-01'\n",
    "    ORDER BY replicate, result_id\n",
    "\"\"\").to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Plate `P08-01` was read twice in week 8. Its first reading is marked `superseded` in a new `status`\n",
    "column, and the corrected reading follows with new result IDs (ending in `-c`) and new values. So\n",
    "every well of that plate now has two results: the grain test counted 40 repeats. The staging model\n",
    "was written before the lab had a `status` column, so it passes both readings on. dlt followed the\n",
    "new column into the raw layer (Module 2, section 4) without complaint; it took a test on the grain\n",
    "to notice that it changed what a row means.\n",
    "\n",
    "The chemistry check, run again, gives the other news of weeks 7 and 8:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "320 rows in: 320 valid, 0 quarantined\n",
      "compound_id                   parent_smiles series\n",
      "   LAB-0042 O=C(Nc1ccc(O)cc1)Nc2ccc(C#N)nc2  ureas\n"
     ]
    }
   ],
   "source": [
    "compounds = query(\"SELECT * FROM marts.dim_compound ORDER BY compound_key\")\n",
    "checked = pc.split(compounds, compound_rules)\n",
    "print(checked.report)\n",
    "print(compounds.loc[compounds[\"compound_id\"] == \"LAB-0042\", [\"compound_id\", \"parent_smiles\",\n",
    "                                                                \"series\"]].to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`dim_compound` was rebuilt (it does not depend on the results), and the quarantine is empty:\n",
    "LAB-0042 was registered again in week 7 with the right structure, and it is a urea after all. The\n",
    "registry export is a snapshot, so the old, wrong structure is gone from the warehouse without a\n",
    "trace, along with any way to say which structure a dashboard showed last week.\n",
    "\n",
    "Both stories end in the same question: when the lab corrects something, what should the warehouse\n",
    "keep? The superseded plate readings should leave the potencies but stay on record; the old\n",
    "structure of LAB-0042 should leave the dimension but stay in its history. That is [Module\n",
    "6](../06-history-and-corrections/): snapshots that keep every version, and models that use only the\n",
    "current one.\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 data tests to your DAG*: generic and singular tests, severity and\n",
    "  storing failures. <https://docs.getdbt.com/docs/build/data-tests>\n",
    "- The dbt documentation. *Model contracts*: enforced columns and types, constraints, and which\n",
    "  warehouses enforce which. <https://docs.getdbt.com/docs/mesh/govern/model-contracts>\n",
    "- The pandera-chem documentation. Every check, `split()` and the report card.\n",
    "  <https://github.com/David-Alobo/pandera-chem/blob/main/docs/usage.md>\n",
    "- Bantilan, N. (2020). pandera: Statistical Data Validation of Pandas Dataframes. *Proceedings of\n",
    "  the 19th Python in Science Conference*, 116–124. <https://doi.org/10.25080/Majora-342d178e-010>\n",
    "- Reis, J. & Housley, M. (2022). *Fundamentals of Data Engineering*. O'Reilly Media. Chapter 2, on\n",
    "  the undercurrents of data engineering, among them data quality and DataOps."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
