Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 25 min · revision 2

Worked Example: Tracing a Wrong Number to Its Source

A finance dashboard shows no revenue for Germany and France on one day, and every pipeline run says "success". Trace the number upstream through lineage, compare row counts across each step to find where rows disappear, confirm the cause in the structured logs, list every affected consumer downstream, then fix the model, add a guard and rebuild only what was affected.

Contentsand lesson path

What you will learn

  • Instrument pipeline runs with metrics, structured logs and run metadata, and combine them with lineage to find a failure's root cause and affected consumers.

01. The problem

On the morning of 5 November a finance analyst reports that the weekly revenue dashboard shows nothing for Germany (DE) and France (FR) on 4 November. Great Britain and the United States look normal. The orchestrator shows every run of every model as successful, and nobody has deployed a change.

This is the most common kind of data incident: a wrong number with no error anywhere. Guessing is slow. Rerunning everything may hide the evidence and may even make it worse. A faster method uses three things the pipeline already records:

  • Lineage: which dataset is built from which. Walking it upstream from the wrong number finds candidate causes; walking it downstream from the cause finds everything affected, the blast radius.
  • Run metadata: what each run did, especially how many rows it wrote, per model and per day.
  • Structured logs: the details each model reported, which you can query.

The pipeline converts orders in three currencies to pounds sterling (GBP) with daily exchange (FX) rates from an external provider, then sums revenue by country. Use the poc-lab folder and its .venv from lesson 1, and sql.py from lesson 2, which takes the database file as a second argument. The build script creates the data, the models, their run records and the lineage in one file, trace.duckdb.

Python · build.py
"""Build a small revenue pipeline for 2026-11-02..04 in trace.duckdb, with run
metadata and lineage. On 11-04 the FX provider starts sending currency codes in
lower case; nothing fails."""
import json
import random

import duckdb

rng = random.Random(3)
con = duckdb.connect("trace.duckdb")
con.execute("""
CREATE OR REPLACE TABLE raw_orders (order_id INT, day DATE, country VARCHAR,
                                    currency VARCHAR, amount DECIMAL(10, 2));
CREATE OR REPLACE TABLE raw_fx (day DATE, currency VARCHAR, to_gbp DECIMAL(8, 4));
CREATE OR REPLACE TABLE runs (model VARCHAR, day DATE, status VARCHAR,
                              rows_out INT, log VARCHAR);
CREATE OR REPLACE TABLE lineage (upstream VARCHAR, downstream VARCHAR);
CREATE OR REPLACE TABLE owners (node VARCHAR, owner VARCHAR);""")
countries = {"GB": "GBP", "DE": "EUR", "FR": "EUR", "US": "USD"}
order_id = 0
for day in ["2026-11-02", "2026-11-03", "2026-11-04"]:
    for country, currency in countries.items():
        for _ in range(rng.randint(25, 35)):
            order_id += 1
            con.execute("INSERT INTO raw_orders VALUES (?, ?, ?, ?, ?)", [order_id,
                        day, country, currency, round(rng.uniform(10, 90), 2)])
    for currency, rate in [("GBP", 1), ("EUR", 0.87), ("USD", 0.76)]:
        if day == "2026-11-04" and currency == "EUR":
            currency = "eur"                     # the provider's unannounced change
        con.execute("INSERT INTO raw_fx VALUES (?, ?, ?)", [day, currency, rate])

MODELS = {  # model -> SQL that builds it from its inputs
    "stg_orders": "SELECT * FROM raw_orders",
    "stg_fx_rates": "SELECT * FROM raw_fx",
    "int_orders_gbp": """SELECT o.order_id, o.day, o.country, o.amount * f.to_gbp AS gbp
        FROM stg_orders o JOIN stg_fx_rates f USING (day, currency)""",
    "mart_revenue_daily": """SELECT day, country, round(sum(gbp), 2) AS revenue_gbp
        FROM int_orders_gbp GROUP BY ALL""",
}
for model, sql in MODELS.items():
    con.execute(f"CREATE OR REPLACE TABLE {model} AS {sql}")
    for (day,) in con.execute("SELECT DISTINCT day FROM raw_orders").fetchall():
        n = con.execute(f"SELECT count(*) FROM {model} WHERE day = ?", [day]).fetchone()
        extra = {}
        if model == "stg_fx_rates":
            codes = con.execute("SELECT list(currency ORDER BY currency) FROM "
                                "stg_fx_rates WHERE day = ?", [day]).fetchone()
            extra["currencies"] = codes[0]
        log = json.dumps({"model": model, "day": str(day), "rows_out": n[0]} | extra)
        con.execute("INSERT INTO runs VALUES (?, ?, 'success', ?, ?)",
                    [model, day, n[0], log])

con.execute("""INSERT INTO lineage VALUES
  ('raw_orders', 'stg_orders'), ('raw_fx', 'stg_fx_rates'),
  ('stg_orders', 'int_orders_gbp'), ('stg_fx_rates', 'int_orders_gbp'),
  ('int_orders_gbp', 'mart_revenue_daily'), ('int_orders_gbp', 'ml_ltv_features'),
  ('mart_revenue_daily', 'dash_finance_weekly'), ('mart_revenue_daily', 'erp_export');
INSERT INTO owners VALUES ('raw_fx', 'fx-vendor (external)'),
  ('stg_fx_rates', 'finance-data'), ('int_orders_gbp', 'finance-data'),
  ('mart_revenue_daily', 'finance-data'), ('ml_ltv_features', 'ml-platform'),
  ('dash_finance_weekly', 'finance-analytics'), ('erp_export', 'erp-integration');""")
print(f"built {len(MODELS)} models and their run records for 2026-11-02 .. 04")
Terminal
.venv/bin/python build.py
Expected output
built 4 models and their run records for 2026-11-02 .. 04

02. Step 1: Confirm the symptom

Start by reproducing exactly what the analyst saw, so you know what "fixed" will look like. Query the mart that feeds the dashboard for the last two days:

Terminal
.venv/bin/python sql.py "PIVOT (SELECT country, day, revenue_gbp FROM mart_revenue_daily
  WHERE day >= '2026-11-03') ON day USING sum(revenue_gbp) ORDER BY country" \
  trace.duckdb
Expected output
┌─────────┬───────────────┬───────────────┐
│ country │  2026-11-03   │  2026-11-04   │
│ varchar │ decimal(38,2) │ decimal(38,2) │
├─────────┼───────────────┼───────────────┤
│ DE      │       1346.70 │          NULL │
│ FR      │       1424.75 │          NULL │
│ GB      │       1273.73 │       1329.00 │
│ US      │       1190.49 │       1283.94 │
└─────────┴───────────────┴───────────────┘

The rows for DE and FR on 4 November are missing, not zero. That is already a clue: something removed rows, rather than setting values to 0. Both countries use the euro (EUR), GB and US do not.

03. Step 2: Walk the lineage upstream

The lineage table holds one row per edge, from an upstream node to a downstream node. A recursive query starts at the dashboard and repeatedly adds the parents of what it has found so far. The depth tells you how far each node is from the symptom.

Terminal
.venv/bin/python sql.py "WITH RECURSIVE up(node, depth) AS (
    SELECT 'dash_finance_weekly', 0
    UNION ALL SELECT l.upstream, up.depth + 1
    FROM lineage l JOIN up ON l.downstream = up.node)
  SELECT depth, string_agg(node, ', ' ORDER BY node) AS nodes
  FROM up GROUP BY depth ORDER BY depth" trace.duckdb
Expected output
┌───────┬──────────────────────────┐
│ depth │          nodes           │
│ int32 │         varchar          │
├───────┼──────────────────────────┤
│     0 │ dash_finance_weekly      │
│     1 │ mart_revenue_daily       │
│     2 │ int_orders_gbp           │
│     3 │ stg_fx_rates, stg_orders │
│     4 │ raw_fx, raw_orders       │
└───────┴──────────────────────────┘

Only these seven nodes can have caused the symptom. Everything else in the warehouse is out of scope, which is the point of starting from lineage instead of from the whole platform.

04. Step 3: Compare row counts along the path

Every run recorded its rows written. Put the two days side by side for every model on the path. A model that writes far fewer rows than its main input, on the bad day only, is where the data disappeared.

Terminal
.venv/bin/python sql.py "PIVOT (SELECT model, day, rows_out FROM runs
  WHERE day >= '2026-11-03') ON day USING sum(rows_out) ORDER BY model" trace.duckdb
Expected output
┌────────────────────┬────────────┬────────────┐
│       model        │ 2026-11-03 │ 2026-11-04 │
│      varchar       │   int128   │   int128   │
├────────────────────┼────────────┼────────────┤
│ int_orders_gbp     │        119 │         59 │
│ mart_revenue_daily │          4 │          2 │
│ stg_fx_rates       │          3 │          3 │
│ stg_orders         │        119 │        118 │
└────────────────────┴────────────┴────────────┘

stg_orders wrote 118 rows on 4 November, a normal number. int_orders_gbp, which joins orders to rates, wrote only 59: half of the orders vanished in the join. stg_fx_rates wrote its usual 3 rows, so the rates table is not empty. The join step is where rows were lost, but not necessarily where the cause lies. The next question is which orders failed to join, and why.

05. Step 4: Find which rows were lost, and why

An anti join returns the rows of the left side that have no match on the right side. Use it to list the orders that found no rate, then read what stg_fx_rates logged about the currencies it wrote each day.

Terminal
.venv/bin/python sql.py "SELECT o.currency, count(*) AS orders_without_rate
  FROM stg_orders o ANTI JOIN stg_fx_rates f USING (day, currency)
  WHERE o.day = '2026-11-04' GROUP BY ALL" trace.duckdb
.venv/bin/python sql.py "SELECT day, log->>'currencies' AS currencies FROM runs
  WHERE model = 'stg_fx_rates' ORDER BY day" trace.duckdb
Expected output
┌──────────┬─────────────────────┐
│ currency │ orders_without_rate │
│ varchar  │        int64        │
├──────────┼─────────────────────┤
│ EUR      │                  59 │
└──────────┴─────────────────────┘

┌────────────┬─────────────────────┐
│    day     │     currencies      │
│    date    │       varchar       │
├────────────┼─────────────────────┤
│ 2026-11-02 │ ["EUR","GBP","USD"] │
│ 2026-11-03 │ ["EUR","GBP","USD"] │
│ 2026-11-04 │ ["GBP","USD","eur"] │
└────────────┴─────────────────────┘

All 59 lost orders are in EUR. The structured log shows why: on 4 November the provider sent eur in lower case, and the join compares strings exactly. That is the root cause: an unannounced change in an external feed, met by a model that assumed a format nobody had written down, and an inner join that drops unmatched rows without a sound. The row count of stg_fx_rates was normal, so a volume check could not see it; a check on the set of currency codes, a distribution signal from lesson 1, would have.

06. Step 5: Find the blast radius

Before fixing anything, find out who used the bad data. Walk the lineage downstream from the root cause and join the owners table. Every node in the result read data derived from the broken rates.

Terminal
.venv/bin/python sql.py "WITH RECURSIVE down(node) AS (SELECT 'stg_fx_rates'
    UNION SELECT l.downstream FROM lineage l JOIN down ON l.upstream = down.node)
  SELECT node, owner FROM down LEFT JOIN owners USING (node)
  ORDER BY owner, node" trace.duckdb
Expected output
┌─────────────────────┬───────────────────┐
│        node         │       owner       │
│       varchar       │      varchar      │
├─────────────────────┼───────────────────┤
│ erp_export          │ erp-integration   │
│ dash_finance_weekly │ finance-analytics │
│ int_orders_gbp      │ finance-data      │
│ mart_revenue_daily  │ finance-data      │
│ stg_fx_rates        │ finance-data      │
│ ml_ltv_features     │ ml-platform       │
└─────────────────────┴───────────────────┘

The dashboard where the problem was noticed is only one of three consumers. The ERP export may already have sent wrong revenue to the accounting system, and the machine learning features for customer lifetime value were built from half of the orders. Each owner needs to know which dates are affected and when corrected data will be ready; lesson 4 covers that message.

07. Step 6: Fix, guard and rebuild what was affected

The fix has two parts. Normalise currency codes in the staging model, so the provider's formatting no longer matters. Then add a guard before the join: if any order has no rate, the run fails loudly instead of writing a quietly incomplete table. Rebuild only the models from step 5's list, in dependency order; the consumers then pick up the corrected tables.

Python · fix.py
"""Fix the staging model, add a guard to the join, and rebuild only the models
downstream of stg_fx_rates, in dependency order."""
import duckdb

con = duckdb.connect("trace.duckdb")
FIXED = {
    # Normalise codes at the edge: the provider's case is not our contract.
    "stg_fx_rates": "SELECT day, upper(trim(currency)) AS currency, to_gbp FROM raw_fx",
    "int_orders_gbp": """SELECT o.order_id, o.day, o.country, o.amount * f.to_gbp AS gbp
        FROM stg_orders o JOIN stg_fx_rates f USING (day, currency)""",
    "mart_revenue_daily": """SELECT day, country, round(sum(gbp), 2) AS revenue_gbp
        FROM int_orders_gbp GROUP BY ALL""",
}
for model, sql in FIXED.items():
    if model == "int_orders_gbp":
        # Guard: an inner join silently drops orders that have no rate. Fail instead.
        missing = con.execute("""SELECT count(*) FROM stg_orders o
            ANTI JOIN stg_fx_rates f USING (day, currency)""").fetchone()[0]
        if missing:
            raise SystemExit(f"int_orders_gbp: {missing} orders have no FX rate")
        print("guard: every order has an FX rate")
    con.execute(f"CREATE OR REPLACE TABLE {model} AS {sql}")
    n = con.execute(f"SELECT count(*) FROM {model} WHERE day = '2026-11-04'").fetchone()
    con.execute("INSERT INTO runs VALUES (?, '2026-11-04', 'rerun', ?, NULL)",
                [model, n[0]])
    print(f"rebuilt {model}: {n[0]} rows for 2026-11-04")
Terminal
.venv/bin/python fix.py
.venv/bin/python sql.py "PIVOT (SELECT country, day, revenue_gbp FROM mart_revenue_daily
  WHERE day >= '2026-11-03') ON day USING sum(revenue_gbp) ORDER BY country" \
  trace.duckdb
Expected output
rebuilt stg_fx_rates: 3 rows for 2026-11-04
guard: every order has an FX rate
rebuilt int_orders_gbp: 118 rows for 2026-11-04
rebuilt mart_revenue_daily: 4 rows for 2026-11-04
┌─────────┬───────────────┬───────────────┐
│ country │  2026-11-03   │  2026-11-04   │
│ varchar │ decimal(38,2) │ decimal(38,2) │
├─────────┼───────────────┼───────────────┤
│ DE      │       1346.70 │       1336.68 │
│ FR      │       1424.75 │       1201.23 │
│ GB      │       1273.73 │       1329.00 │
│ US      │       1190.49 │       1283.94 │
└─────────┴───────────────┴───────────────┘

All 118 orders of 4 November now have a rate, and DE and FR are back. Had the guard existed on 4 November, the original run would have failed with "59 orders have no FX rate", an alert would have reached the finance-data team before the analyst opened the dashboard, and no consumer would have read incomplete data.

08. Check your understanding

Practice check · 3 questions

Tracing a wrong number

Each question changes one detail of this example.

Q1. Suppose the provider had sent two EUR rows for 4 November instead of a lower-case one. What would the row counts in step 3 have shown?
Q2. `stg_fx_rates` wrote 3 rows on both days. Which evidence showed that it held the root cause?
Q3. After the fix, whose owners should hear which dates were wrong and when the data was corrected?
Practice only: not graded, not saved, not evidence.

09. Apply it

In your pipeline from lesson 2, make sure every model records rows written per run, and store lineage edges and owners in tables (or export them from your orchestrator or catalogue). Then break one upstream input on purpose, for example by changing the case of a join key, and practise the method: confirm the symptom, walk upstream, compare row counts along the path, find the lost rows, walk downstream for the blast radius, and add a guard that would have failed the run.

10. Review prompt

Without looking back, explain: why rerunning everything is a poor first step; how a recursive query walks lineage upstream and downstream; how comparing rows written between steps and days locates the step that lost data; what an anti join shows; why the root cause can be one step above the step that lost rows; what the blast radius is and who needs to hear about it; and what a guard does.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check