{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Orchestration\n",
    "\n",
    "Run the lab's weekly pipeline as a Prefect flow. Receive the files, load them, snapshot, build and test, check the chemistry, draw the new compounds and publish, as tasks that retry when something flaky fails, reuse work already done, stop before publishing anything wrong, and keep a record of every run. Then schedule it.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-2/07-orchestration/"
   ]
  },
  {
   "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 prefect\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-06/lab_dbt/dbt_project.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/dbt_project.yml\", \"stages/after-06/lab_dbt/dbt_project.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/macros/generate_schema_name.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/macros/generate_schema_name.sql\", \"stages/after-06/lab_dbt/macros/generate_schema_name.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/macros/unique_combination.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/macros/unique_combination.sql\", \"stages/after-06/lab_dbt/macros/unique_combination.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/_marts.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/models/marts/_marts.yml\", \"stages/after-06/lab_dbt/models/marts/_marts.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_compound.py\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/models/marts/dim_compound.py\", \"stages/after-06/lab_dbt/models/marts/dim_compound.py\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_compound_history.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_compound_history.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-06/lab_dbt/models/marts/dim_compound_history.sql\", \"stages/after-06/lab_dbt/models/marts/dim_compound_history.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_date.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/models/marts/dim_date.sql\", \"stages/after-06/lab_dbt/models/marts/dim_date.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_target.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/models/marts/dim_target.sql\", \"stages/after-06/lab_dbt/models/marts/dim_target.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/fact_measurement.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/models/marts/fact_measurement.sql\", \"stages/after-06/lab_dbt/models/marts/fact_measurement.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/measurements_wide.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/models/marts/measurements_wide.sql\", \"stages/after-06/lab_dbt/models/marts/measurements_wide.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/staging/_sources.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/models/staging/_sources.yml\", \"stages/after-06/lab_dbt/models/staging/_sources.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/staging/_staging.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/models/staging/_staging.yml\", \"stages/after-06/lab_dbt/models/staging/_staging.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/staging/stg_compounds.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/models/staging/stg_compounds.sql\", \"stages/after-06/lab_dbt/models/staging/stg_compounds.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/staging/stg_results.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/models/staging/stg_results.sql\", \"stages/after-06/lab_dbt/models/staging/stg_results.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/profiles.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/profiles.yml\", \"stages/after-06/lab_dbt/profiles.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/seeds/targets.csv\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/seeds/targets.csv\", \"stages/after-06/lab_dbt/seeds/targets.csv\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/seeds/unit_to_nm.csv\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/seeds/unit_to_nm.csv\", \"stages/after-06/lab_dbt/seeds/unit_to_nm.csv\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/snapshots/registry_history.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/snapshots/registry_history.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-06/lab_dbt/snapshots/registry_history.yml\", \"stages/after-06/lab_dbt/snapshots/registry_history.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/tests/pic50_matches_ic50.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/tests/pic50_matches_ic50.sql\", \"stages/after-06/lab_dbt/tests/pic50_matches_ic50.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/tests/potency_in_plausible_range.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/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-06/lab_dbt/tests/potency_in_plausible_range.sql\", \"stages/after-06/lab_dbt/tests/potency_in_plausible_range.sql\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By the end of [Module 6](../06-history-and-corrections/) the warehouse could keep history,\n",
    "handle corrections and build incrementally. But every week someone had to run five things in the\n",
    "right order: put the files in the inbox, load them with dlt, take a snapshot, build and test with\n",
    "dbt, and check the chemistry. Forget the snapshot one week and that week's changes are lost for\n",
    "good; run the build before the load and the dashboards show last week's data while everyone\n",
    "believes it is new.\n",
    "\n",
    "An **orchestrator** runs that sequence for you. It starts it on a schedule (or when files arrive),\n",
    "runs each step after the steps it depends on, retries the steps that fail for passing reasons,\n",
    "stops before anything is published if a step fails for a real one, and keeps a record of every run\n",
    "that anyone can look at. In [Series 1, Module 10](../../series-1/10-pipelines-that-survive-failure/)\n",
    "we wrote much of that by hand: retries with backoff, a checkpoint file, a log of every run. Here\n",
    "**Prefect**, an open-source orchestrator written in Python, does it.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- turn Python functions into Prefect **tasks** and a **flow**, and run the flow;\n",
    "- give a task **retries** for the failures that pass, and let real failures stop the flow;\n",
    "- **cache** an expensive task, so that a rerun reuses its work;\n",
    "- read the record Prefect keeps of every flow run and task run;\n",
    "- schedule the flow to run every week, and know the ways a flow can be started by new data.\n",
    "\n",
    "## Setup\n",
    "\n",
    "Prefect reads its settings when it is imported, so this Setup does two things before importing it.\n",
    "It empties `work/`, so that the lesson starts clean, and makes the folder where Prefect keeps its\n",
    "own files (its database of runs, and the results it caches); and it sets two **environment\n",
    "variables**: `PREFECT_HOME`, which points Prefect to that folder, and one that turns off the\n",
    "anonymous usage statistics Prefect's server would otherwise send.\n",
    "\n",
    "The warehouse comes from `labstack.warehouse_at`, which runs the first eight weeks as Module 6\n",
    "did (the files of each week loaded and snapshotted in turn, then one build), with the dbt project\n",
    "Module 6 finished. Weeks 9 to 12 are this module's."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import os\n",
    "import shutil\n",
    "from collections import Counter\n",
    "from pathlib import Path\n",
    "\n",
    "WORK = Path(\"work\")  # where the lesson writes its files (git-ignored)\n",
    "shutil.rmtree(WORK, ignore_errors=True)  # start clean, before Prefect keeps its files in work/\n",
    "(WORK / \"prefect\").mkdir(parents=True)\n",
    "os.environ[\"PREFECT_HOME\"] = str((WORK / \"prefect\").resolve())\n",
    "os.environ[\"PREFECT_SERVER_ANALYTICS_ENABLED\"] = \"false\"\n",
    "\n",
    "import duckdb\n",
    "import pandas as pd\n",
    "import pandera.pandas as pa\n",
    "import pandera_chem as pc\n",
    "from prefect import flow, get_run_logger, task\n",
    "from prefect.cache_policies import INPUTS\n",
    "from prefect.client.orchestration import get_client\n",
    "from rdkit import Chem, RDLogger\n",
    "from rdkit.Chem import Draw\n",
    "\n",
    "import labdata\n",
    "import labstack\n",
    "\n",
    "RDLogger.DisableLog(\"rdApp.*\")\n",
    "logging.basicConfig(level=logging.INFO, format=\"%(levelname)s %(message)s\", force=True)\n",
    "log = logging.getLogger(__name__)\n",
    "logging.getLogger(\"httpx\").setLevel(logging.WARNING)  # not every request Prefect makes\n",
    "quiet = logging.getLogger(\"dbt-lines\")  # labstack.dbt logs one line per model here: unseen\n",
    "quiet.propagate = False\n",
    "\n",
    "\n",
    "def named(record: logging.LogRecord) -> bool:\n",
    "    \"\"\"Start each of Prefect's lines with its run's name, and leave out tracebacks.\"\"\"\n",
    "    name = getattr(record, \"task_run_name\", None) or getattr(record, \"flow_run_name\", None)\n",
    "    if name:\n",
    "        record.msg, record.args = f\"{name}: {record.getMessage()}\", ()\n",
    "    record.exc_info = record.exc_text = None  # the full traceback stays in Prefect's record\n",
    "    return True\n",
    "\n",
    "\n",
    "def no_server_notice(record: logging.LogRecord) -> bool:\n",
    "    \"\"\"Hide Prefect's notice of the temporary server it starts (its time and port vary).\"\"\"\n",
    "    return \"temporary server\" not in record.getMessage()\n",
    "\n",
    "\n",
    "for name in (\"prefect.flow_runs\", \"prefect.task_runs\"):\n",
    "    logging.getLogger(name).addFilter(named)\n",
    "logging.getLogger(\"prefect\").addFilter(no_server_notice)\n",
    "\n",
    "INBOX = WORK / \"inbox\"\n",
    "WAREHOUSE = WORK / \"lab.duckdb\"\n",
    "PUBLISHED = WORK / \"published\"  # what the dashboards of Module 10 read\n",
    "SHARE_FAILS_ONCE = {9}  # weeks in which the lab's file share fails at the first attempt\n",
    "\n",
    "lab = labdata.Lab()\n",
    "PROJECT = labstack.warehouse_at(lab, 8, WORK)\n",
    "pipeline = labstack.lab_pipeline(WAREHOUSE, WORK / \"dlt\")\n",
    "attempts = Counter()  # how often each week's files have been asked for"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`named` and `no_server_notice` are logging **filters**: functions that see each log record before\n",
    "it is printed and can change it or drop it. `named` puts the name of the flow run or task run in\n",
    "front of each of Prefect's lines, so you can tell which step said what. The others only make the\n",
    "lesson's outputs the same on every computer; leave them out in your own work. `SHARE_FAILS_ONCE`\n",
    "is how this lesson makes a flaky network happen on cue: the lab's file share will fail the first\n",
    "time week 9's files are asked for.\n",
    "\n",
    "## 1. Tasks and a flow\n",
    "\n",
    "In Prefect, a **task** is a Python function marked with `@task`: one step of the pipeline, which\n",
    "Prefect runs, records and, if told to, retries or caches. A **flow** is a function marked with\n",
    "`@flow` that calls tasks: the pipeline itself. Nothing else changes: the functions are ordinary\n",
    "Python, the flow decides the order by calling the tasks in order, and a task's result is passed to\n",
    "the next as an ordinary value.\n",
    "\n",
    "The first two tasks receive the week's files and load them. Receiving reads from the lab's file\n",
    "share, which sometimes does not answer, so it gets `retries=2`: if it raises an error, Prefect waits\n",
    "`retry_delay_seconds` and runs it again, up to twice more. `task_run_name` names each run after its\n",
    "week, so the record says which week a run was for. `get_run_logger()` returns a logger whose lines\n",
    "go to the screen and to Prefect's record of the run."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@task(retries=2, retry_delay_seconds=1, task_run_name=\"receive week {week}\")\n",
    "def receive(week: int) -> list[str]:\n",
    "    \"\"\"Copy the week's files from the lab's share into the inbox.\"\"\"\n",
    "    attempts[week] += 1\n",
    "    if week in SHARE_FAILS_ONCE and attempts[week] == 1:\n",
    "        raise ConnectionError(\"the lab's file share did not answer\")\n",
    "    files = [path.name for path in lab.write_week(week, INBOX)]\n",
    "    get_run_logger().info(\"received %s\", \", \".join(files))\n",
    "    return files\n",
    "\n",
    "\n",
    "@task(task_run_name=\"load week {week}\")\n",
    "def load(week: int, files: list[str]) -> dict[str, int]:\n",
    "    \"\"\"Load what is new in the inbox into the raw layer, with Module 2's dlt pipeline.\"\"\"\n",
    "    rows = labstack.load_inbox(INBOX, pipeline)\n",
    "    get_run_logger().info(\"loaded %s\", rows)\n",
    "    if not any(name.startswith(\"assay_\") for name in files):\n",
    "        get_run_logger().warning(\"no assay file arrived for week %d\", week)\n",
    "    return rows"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`load` takes the list of files although it reads the inbox itself: passing it makes the order\n",
    "explicit (Prefect knows `load` needs what `receive` returned) and lets `load` warn when no assay\n",
    "file came. The next tasks take the snapshot and build. A build whose tests fail must stop the\n",
    "flow, so `build` raises an error when any test fails, and when a model cannot be built\n",
    "(`labstack.dbt` raises a `BuildError` then, whose `short` is dbt's reason in one line):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@task(task_run_name=\"snapshot\")\n",
    "def snapshot() -> None:\n",
    "    \"\"\"Take this week's snapshot of the registry (Module 6), before anything else changes it.\"\"\"\n",
    "    labstack.dbt(PROJECT, \"snapshot\", log=quiet)\n",
    "\n",
    "\n",
    "@task(task_run_name=\"build\")\n",
    "def build() -> dict[str, int]:\n",
    "    \"\"\"Build and test the warehouse with dbt; fail if any test fails.\"\"\"\n",
    "    try:\n",
    "        results = labstack.dbt(PROJECT, \"build\", log=quiet)\n",
    "    except labstack.BuildError as error:  # a model could not be built: say which, and why\n",
    "        raise RuntimeError(error.short) from None\n",
    "    counts = dict(sorted(Counter(str(r.status) for r in results).items()))\n",
    "    get_run_logger().info(\"dbt build: %s\", counts)\n",
    "    failed = [r.node.name for r in results if r.status == \"fail\"]\n",
    "    if failed:\n",
    "        raise RuntimeError(f\"tests failed: {failed}\")\n",
    "    return counts"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The chemistry check of Module 5 becomes a task that warns but does not stop the flow: a compound\n",
    "in quarantine is a question for a chemist, not a reason to hold every dashboard. The dashboards of\n",
    "Module 10 show each compound's structure, so a task draws the compounds registered this week, as\n",
    "SVG pictures, with RDKit. Drawing is slow when there are many compounds, and its result depends\n",
    "only on the compounds, so it is **cached**: `cache_policy=INPUTS` tells Prefect that a run with the\n",
    "same inputs as an earlier one can reuse that run's result instead of running again. Last, `publish`\n",
    "saves the wide table for the dashboards, as a Parquet file ([Series 1, Module\n",
    "3](../../series-1/03-files-and-identity/)):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "COMPOUND_RULES = pa.DataFrameSchema({\n",
    "    \"parent_smiles\": pa.Column(str, [pc.valid_smiles(), pc.single_fragment()]),\n",
    "    \"series\": pa.Column(str, nullable=False),\n",
    "})\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()\n",
    "\n",
    "\n",
    "@task(task_run_name=\"check chemistry\")\n",
    "def check_chemistry() -> list[str]:\n",
    "    \"\"\"Check every compound's structure and series with pandera-chem; warn about any that fail.\"\"\"\n",
    "    checked = pc.split(query(\"SELECT * FROM marts.dim_compound\"), COMPOUND_RULES)\n",
    "    quarantined = sorted(checked.quarantined[\"compound_id\"])\n",
    "    if quarantined:\n",
    "        get_run_logger().warning(\"for a chemist to look at: %s\", quarantined)\n",
    "    return quarantined\n",
    "\n",
    "\n",
    "@task(cache_policy=INPUTS, task_run_name=\"draw week {week}'s compounds\")\n",
    "def draw(week: int, compounds: dict[str, str]) -> int:\n",
    "    \"\"\"Draw each new compound as an SVG picture for the dashboards.\"\"\"\n",
    "    folder = PUBLISHED / \"structures\"\n",
    "    folder.mkdir(parents=True, exist_ok=True)\n",
    "    for compound_id, smiles in compounds.items():\n",
    "        svg = Draw.MolsToGridImage([Chem.MolFromSmiles(smiles)], subImgSize=(300, 220),\n",
    "                                   useSVG=True)\n",
    "        (folder / f\"{compound_id}.svg\").write_text(svg, encoding=\"utf-8\")\n",
    "    get_run_logger().info(\"drew %d compounds\", len(compounds))\n",
    "    return len(compounds)\n",
    "\n",
    "\n",
    "@task(task_run_name=\"publish\")\n",
    "def publish() -> int:\n",
    "    \"\"\"Save the wide table, the dashboards' source, as a Parquet file.\"\"\"\n",
    "    PUBLISHED.mkdir(exist_ok=True)\n",
    "    wide = query(\"SELECT * FROM marts.measurements_wide\")\n",
    "    wide.to_parquet(PUBLISHED / \"measurements.parquet\", index=False)\n",
    "    return len(wide)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The flow calls them in order. `flow_run_name` names each run after its week, and `name` is the\n",
    "flow's own name. The registry's new compounds are those registered in this week, read from the\n",
    "compound dimension the build has just made:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@flow(name=\"lab-weekly\", flow_run_name=\"week {week}\")\n",
    "def weekly(week: int) -> dict:\n",
    "    \"\"\"The lab's weekly pipeline: receive, load, snapshot, build and test, check, draw, publish.\"\"\"\n",
    "    files = receive(week)\n",
    "    load(week, files)\n",
    "    snapshot()\n",
    "    counts = build()\n",
    "    quarantined = check_chemistry()\n",
    "    new = query(f\"\"\"\n",
    "        SELECT compound_id, parent_smiles FROM marts.dim_compound\n",
    "        WHERE registered_on >= DATE '{labdata.monday(week)}'\n",
    "          AND registered_on < DATE '{labdata.monday(week + 1)}'\n",
    "    \"\"\")\n",
    "    drawn = draw(week, dict(zip(new[\"compound_id\"], new[\"parent_smiles\"])))\n",
    "    rows = publish()\n",
    "    summary = {\"tests\": counts.get(\"pass\", 0), \"drawn\": drawn, \"published\": rows,\n",
    "               \"quarantined\": len(quarantined)}\n",
    "    get_run_logger().info(\"%s\", summary)\n",
    "    return summary"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![The weekly flow: receive (retried after a second if the share fails), load with dlt, snapshot and build with dbt, check the chemistry (warnings only), draw the new compounds (cached: the same inputs return the earlier result) and publish; if the build fails, the flow stops there and the dashboards keep last week's data; Prefect records every run, and starts the flow on a schedule or when files arrive](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/07-orchestration/figures/weekly-flow.svg)\n",
    "\n",
    "## 2. Running it\n",
    "\n",
    "A flow is called like a function. The first run of the lesson takes a little longer: Prefect\n",
    "starts a temporary local server to keep its record, and sets up its database. Week 9:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO week 9: Beginning flow run 'week 9' for flow 'lab-weekly'\n",
      "INFO receive week 9: Task run failed with exception: ConnectionError(\"the lab's file share did not answer\") - Retry 1/2 will start 1 second(s) from now\n",
      "INFO receive week 9: received registry_2026-11-02.csv, assay_2026-11-02.csv\n",
      "INFO receive week 9: Finished in state Completed()\n",
      "INFO load week 9: loaded {'assay': 144, 'registry': 360}\n",
      "INFO load week 9: Finished in state Completed()\n",
      "INFO snapshot: Finished in state Completed()\n",
      "INFO build: dbt build: {'pass': 24, 'success': 11}\n",
      "INFO build: Finished in state Completed()\n",
      "INFO check chemistry: Finished in state Completed()\n",
      "INFO draw week 9's compounds: drew 40 compounds\n",
      "INFO draw week 9's compounds: Finished in state Completed()\n",
      "INFO publish: Finished in state Completed()\n",
      "INFO week 9: {'tests': 24, 'drawn': 40, 'published': 1136, 'quarantined': 0}\n",
      "INFO week 9: Finished in state Completed()\n"
     ]
    }
   ],
   "source": [
    "summary = weekly(9)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Read the lines in order. The file share failed and Prefect retried `receive` a second later, as\n",
    "its settings say; the second attempt worked and the flow carried on, without anyone doing\n",
    "anything. Every task logged under its own name and finished in state `Completed`, and the flow's\n",
    "summary is the last line: every test passed, 40 new compounds were drawn, and the wide table was\n",
    "published.\n",
    "\n",
    "Weeks 10 to 12 follow. Task lines are useful once; from here on we show only each flow's own lines.\n",
    "`return_state=True` makes the flow return its final **state** (Completed, Failed and so on)\n",
    "instead of its result, so the loop can report it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO week 10: Beginning flow run 'week 10' for flow 'lab-weekly'\n",
      "WARNING load week 10: no assay file arrived for week 10\n",
      "INFO week 10: {'tests': 24, 'drawn': 40, 'published': 1136, 'quarantined': 0}\n",
      "INFO week 10: Finished in state Completed()\n",
      "INFO week 10: Completed\n",
      "INFO week 11: Beginning flow run 'week 11' for flow 'lab-weekly'\n",
      "INFO week 11: {'tests': 24, 'drawn': 40, 'published': 1464, 'quarantined': 0}\n",
      "INFO week 11: Finished in state Completed()\n",
      "INFO week 11: Completed\n",
      "INFO week 12: Beginning flow run 'week 12' for flow 'lab-weekly'\n",
      "INFO week 12: {'tests': 24, 'drawn': 40, 'published': 1640, 'quarantined': 0}\n",
      "INFO week 12: Finished in state Completed()\n",
      "INFO week 12: Completed\n"
     ]
    }
   ],
   "source": [
    "logging.getLogger(\"prefect.task_runs\").setLevel(logging.WARNING)  # task warnings only, from here\n",
    "for week in (10, 11, 12):\n",
    "    state = weekly(week, return_state=True)\n",
    "    log.info(\"week %d: %s\", week, state.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Week 10 came with a warning from `load`: no assay file arrived. That is one of the lab's planted\n",
    "problems ([Module 1](../01-lab-data-architecture/), section 1): week 10's results come a week late,\n",
    "with week 11's. The flow still completed (the registry was loaded, the snapshot taken, the build\n",
    "passed), which is right: nothing was wrong with what did arrive. Whether a missing file should\n",
    "alert someone is [Module 8](../08-observability/)'s question. In week 11 both assay files arrived,\n",
    "and dlt loaded both, because the late file's name was new to it.\n",
    "\n",
    "## 3. When a step fails\n",
    "\n",
    "Now suppose a colleague changes a model and makes a mistake: a misspelt column in the wide view.\n",
    "The next run of week 12 (a rerun, as after any fix to the pipeline) meets it at the build:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO week 12: Beginning flow run 'week 12' for flow 'lab-weekly'\n",
      "ERROR build: Task run failed with exception: RuntimeError('measurements_wide: Binder Error: Table \"c\" does not have a column named \"chemst\"')\n",
      "ERROR build: Finished in state Failed('Task run encountered an exception RuntimeError: measurements_wide: Binder Error: Table \"c\" does not have a column named \"chemst\"')\n",
      "ERROR week 12: Encountered exception during execution: RuntimeError('measurements_wide: Binder Error: Table \"c\" does not have a column named \"chemst\"')\n",
      "INFO week 12: Finished in state Failed('Flow run encountered an exception: RuntimeError: measurements_wide: Binder Error: Table \"c\" does not have a column named \"chemst\"')\n",
      "INFO week 12: Failed\n"
     ]
    }
   ],
   "source": [
    "wide_sql = PROJECT / \"models\" / \"marts\" / \"measurements_wide.sql\"\n",
    "good = wide_sql.read_text(encoding=\"utf-8\")\n",
    "wide_sql.write_text(good.replace(\"c.chemist,\", \"c.chemst,\"), encoding=\"utf-8\", newline=\"\\n\")\n",
    "state = weekly(12, return_state=True)\n",
    "log.info(\"week 12: %s\", state.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The build task failed with dbt's reason, and the flow stopped there: `check_chemistry`, `draw` and\n",
    "`publish` never ran, so the published file still holds the last good build. Prefect does not retry\n",
    "`build`, because it has no `retries`: a broken model will not fix itself, and retrying would only\n",
    "hide it. Choosing which tasks get retries is choosing which failures are passing ones.\n",
    "\n",
    "The colleague fixes the model, and week 12 is run again:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO week 12: Beginning flow run 'week 12' for flow 'lab-weekly'\n",
      "INFO receive week 12: received registry_2026-11-23.csv, assay_2026-11-23.csv\n",
      "INFO receive week 12: Finished in state Completed()\n",
      "INFO load week 12: loaded {'registry': 480}\n",
      "INFO load week 12: Finished in state Completed()\n",
      "INFO snapshot: Finished in state Completed()\n",
      "INFO build: dbt build: {'pass': 24, 'success': 11}\n",
      "INFO build: Finished in state Completed()\n",
      "INFO check chemistry: Finished in state Completed()\n",
      "INFO draw week 12's compounds: Finished in state Cached(type=COMPLETED)\n",
      "INFO publish: Finished in state Completed()\n",
      "INFO week 12: {'tests': 24, 'drawn': 40, 'published': 1640, 'quarantined': 0}\n",
      "INFO week 12: Finished in state Completed()\n"
     ]
    }
   ],
   "source": [
    "wide_sql.write_text(good, encoding=\"utf-8\", newline=\"\\n\")\n",
    "logging.getLogger(\"prefect.task_runs\").setLevel(logging.INFO)  # every task's lines again\n",
    "summary = weekly(12)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Everything ran again except `draw`, which finished in state `Cached`: its inputs (week 12 and the\n",
    "same 40 compounds) were the same as in the earlier run of week 12 that reached it, so Prefect\n",
    "returned that run's result without drawing anything. `load` loaded no assay rows this time:\n",
    "dlt remembers that week 12's file was loaded by the failed run, and loads each file once. (It\n",
    "loaded the registry again, as it does on every run, because the registry is a snapshot that\n",
    "replaces the last.) So rerunning a whole week is safe, and that is what makes reruns cheap to\n",
    "decide on. dbt's build is not cached: it is how we know the warehouse is right, so it runs every\n",
    "time.\n",
    "\n",
    "## 4. The record\n",
    "\n",
    "Every flow run and task run, its state, its start and end and its logs, is in Prefect's database.\n",
    "On a server it is shown in Prefect's web interface; here we ask the same database from Python, with\n",
    "a **client** that talks to the Prefect server:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "week 9   Completed\n",
      "week 10  Completed\n",
      "week 11  Completed\n",
      "week 12  Completed\n",
      "week 12  Failed\n",
      "week 12  Completed\n"
     ]
    }
   ],
   "source": [
    "with get_client(sync_client=True) as client:\n",
    "    runs = client.read_flow_runs()\n",
    "for run in sorted(runs, key=lambda r: r.expected_start_time):\n",
    "    print(f\"{run.name:8} {run.state_name}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Six runs of the flow, one for each call, the failed run of week 12 among them, each with its\n",
    "state. The record also holds every task run of each flow run, with its logs, its state and how\n",
    "many attempts it took (the `receive` of week 9 took two). When a chemist asks \"why did the\n",
    "dashboard not change on Tuesday?\", this record answers it. To see it as Prefect's web interface shows it, run\n",
    "`prefect server start` in a terminal (with the same `PREFECT_HOME`) and open\n",
    "<http://127.0.0.1:4200>.\n",
    "\n",
    "## 5. On a schedule, or when files arrive\n",
    "\n",
    "So far we called the flow ourselves. In production a **deployment** runs it: a flow, plus when and\n",
    "where to run it. The simplest way is `serve`, run in a long-lived process on a server (the kind of\n",
    "machine [Series 1, Module 10](../../series-1/10-pipelines-that-survive-failure/), section 9, used\n",
    "for long jobs): it registers the flow with a schedule and runs it each time the schedule comes\n",
    "round. A schedule is written as a **cron** expression, five fields for minute, hour, day of the\n",
    "month, month and day of the week; `0 7 * * 1` is 07:00 every Monday. The flow then needs to work\n",
    "out the week itself, from the date:\n",
    "\n",
    "```py\n",
    "# lab_pipeline.py, on the lab's server (not run by this lesson): python lab_pipeline.py\n",
    "from datetime import date\n",
    "\n",
    "import labdata\n",
    "from weekly import weekly  # the flow of this module, saved in its own file\n",
    "\n",
    "\n",
    "def this_week() -> int:\n",
    "    \"\"\"The project week that has just ended (the flow runs on Monday morning).\"\"\"\n",
    "    return (date.today() - labdata.START).days // 7\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    weekly.serve(name=\"every-monday\", cron=\"0 7 * * 1\",\n",
    "                 parameters={\"week\": this_week()})\n",
    "```\n",
    "\n",
    "A schedule runs the flow whether or not anything has arrived, which suits a lab whose files come\n",
    "on a known day. When they do not (a plate reader that exports whenever a plate is done), the\n",
    "flow can instead be started by the data. There are three common ways, from simplest:\n",
    "\n",
    "- **Run often, and let reruns be cheap.** Schedule the flow every hour. Because loading is\n",
    "  incremental and the build is idempotent (running it twice gives the same result as once), a run\n",
    "  that finds nothing new costs little. This is what this lab's flow already supports.\n",
    "- **A sensor.** A small flow, run every few minutes, that checks the inbox and starts the weekly\n",
    "  flow only when a new file is there.\n",
    "- **Events.** The instrument, or the storage the files land in, sends an event when a file\n",
    "  arrives, and an automation on the Prefect server starts a deployment in response. Prefect calls\n",
    "  these **triggers**; they need a running Prefect server, which is why this lesson only describes\n",
    "  them.\n",
    "\n",
    "Whichever starts the flow, what it runs is the same: the tasks of section 1, in their order, with\n",
    "their retries and their record. In [Module 8](../08-observability/) the flow learns to notice what\n",
    "is wrong without failing: a file that did not arrive, a table that stopped growing, molecules that\n",
    "drift from the usual.\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 Prefect documentation. *Write and run flows* and *Write and run tasks*: retries, caching,\n",
    "  results and states. <https://docs.prefect.io/v3/develop/write-flows>\n",
    "- The Prefect documentation. *Configure task caching*: cache policies, keys and expiry.\n",
    "  <https://docs.prefect.io/v3/develop/task-caching>\n",
    "- The Prefect documentation. *Run deployments on a schedule* and *Event triggers*: `serve`, cron\n",
    "  schedules and automations. <https://docs.prefect.io/v3/automate/add-schedules>\n",
    "- Reis, J. & Housley, M. (2022). *Fundamentals of Data Engineering*. O'Reilly Media. Chapter 2, on\n",
    "  orchestration as one of the undercurrents of data engineering."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
