rasinmuhammed's picture
Retail star schema v1
7e5adcc verified
Raw History Blame Contribute Delete
20.4 kB
"""Check the dataset and its answer key.
python verify/verify.py [--engines duckdb,clickhouse] [--parquet data/parquet]
Gates, each run on every engine named:
integrity no orphan keys (NULL customer_id aside), unique dimension keys, returns within their lines and dates
arithmetic net_amount and cost_amount recomputed from their parts on every line; every order's lines carry its keys
patterns P1 to P6 measured from the loaded data (P1: the planted region the clear largest 2025-Q2 decline; P2
exact on every matured Apparel cohort)
key every key query returns the key's expected value
independent about ten key values recomputed with pyarrow and numpy, no SQL (once, over the Parquet files)
skew orders per customer and lines per order: median, p90, p99, max
Writes reports/verification.json and exits 1 if any gate fails.
"""
from __future__ import annotations
import argparse
import json
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from answer_key.questions import render # noqa: E402
from generator import catalog as C # noqa: E402
from verify import independent # noqa: E402
from verify.engines import ClickHouse, DuckDB, agrees, value_of # noqa: E402
# name -> SQL template returning one row with `value`: zero means the check holds
INTEGRITY = {
"orders.customer_id orphans": "SELECT count(*) AS value FROM orders o LEFT JOIN dim_customer c ON c.customer_id = o.customer_id "
"WHERE o.customer_id IS NOT NULL AND c.customer_id IS NULL",
"orders.store_id orphans": "SELECT count(*) AS value FROM orders o LEFT JOIN dim_store s ON s.store_id = o.store_id WHERE s.store_id IS NULL",
"order_lines.order_id orphans": "SELECT count(*) AS value FROM order_lines l LEFT JOIN orders o ON o.order_id = l.order_id WHERE o.order_id IS NULL",
"order_lines.product_id orphans": "SELECT count(*) AS value FROM order_lines l LEFT JOIN dim_product p ON p.product_id = l.product_id "
"WHERE p.product_id IS NULL",
"order_lines.date_key orphans": "SELECT count(*) AS value FROM order_lines l LEFT JOIN dim_date d ON d.date_key = l.date_key WHERE d.date_key IS NULL",
"order_lines.customer_id orphans": "SELECT count(*) AS value FROM order_lines l LEFT JOIN dim_customer c ON c.customer_id = l.customer_id "
"WHERE l.customer_id IS NOT NULL AND c.customer_id IS NULL",
"returns.order_line_id orphans": "SELECT count(*) AS value FROM returns r LEFT JOIN order_lines l ON l.order_line_id = r.order_line_id "
"WHERE l.order_line_id IS NULL",
"returns date key orphans": "SELECT count(*) AS value FROM returns r LEFT JOIN dim_date a ON a.date_key = r.sale_date_key "
"LEFT JOIN dim_date b ON b.date_key = r.return_date_key WHERE a.date_key IS NULL OR b.date_key IS NULL",
"dim_date duplicate keys": "SELECT count(*) AS value FROM (SELECT date_key FROM dim_date GROUP BY date_key HAVING count(*) > 1) t",
"dim_product duplicate keys": "SELECT count(*) AS value FROM (SELECT product_id FROM dim_product GROUP BY product_id HAVING count(*) > 1) t",
"dim_customer duplicate keys": "SELECT count(*) AS value FROM (SELECT customer_id FROM dim_customer GROUP BY customer_id HAVING count(*) > 1) t",
"dim_store duplicate keys": "SELECT count(*) AS value FROM (SELECT store_id FROM dim_store GROUP BY store_id HAVING count(*) > 1) t",
"orders duplicate keys": "SELECT count(*) AS value FROM (SELECT order_id FROM orders GROUP BY order_id HAVING count(*) > 1) t",
"order_lines duplicate keys": "SELECT count(*) AS value FROM (SELECT order_line_id FROM order_lines GROUP BY order_line_id HAVING count(*) > 1) t",
"returns duplicate keys": "SELECT count(*) AS value FROM (SELECT return_id FROM returns GROUP BY return_id HAVING count(*) > 1) t",
"lines returned twice": "SELECT count(*) AS value FROM (SELECT order_line_id FROM returns GROUP BY order_line_id HAVING count(*) > 1) t",
"returned_qty above line quantity": "SELECT count(*) AS value FROM returns r JOIN order_lines l ON l.order_line_id = r.order_line_id "
"WHERE r.returned_qty > l.quantity OR r.returned_qty < 1",
"return not after its sale": "SELECT count(*) AS value FROM returns r WHERE r.return_date <= r.sale_date",
"return after the as-of date": f"SELECT count(*) AS value FROM returns r WHERE r.return_date > '{C.AS_OF}'",
"return more than 90 days after sale": "SELECT count(*) AS value FROM returns r JOIN dim_date a ON a.date_key = r.sale_date_key "
"WHERE r.return_date > a.date + 90",
"order after the as-of date": f"SELECT count(*) AS value FROM orders WHERE order_date > '{C.AS_OF}'",
"order before its customer signed up": "SELECT count(*) AS value FROM orders o JOIN dim_customer c ON c.customer_id = o.customer_id "
"WHERE o.order_date < c.signup_date",
"returns keys differ from their line": "SELECT count(*) AS value FROM returns r JOIN order_lines l ON l.order_line_id = r.order_line_id "
"WHERE r.order_id <> l.order_id OR r.product_id <> l.product_id OR r.store_id <> l.store_id "
"OR r.sale_date <> l.order_date OR r.sale_date_key <> l.date_key "
"OR coalesce(r.customer_id, 0) <> coalesce(l.customer_id, 0)",
"NULLs outside the allowed columns": "SELECT (SELECT count(*) FROM dim_customer WHERE customer_name IS NULL OR country IS NULL OR region IS NULL "
"OR city IS NULL) + (SELECT count(*) FROM order_lines WHERE discount_pct IS NULL OR net_amount IS NULL) "
"+ (SELECT count(*) FROM orders o JOIN dim_store s ON s.store_id = o.store_id "
"WHERE o.customer_id IS NULL AND s.channel = 'Online') "
"+ (SELECT count(*) FROM dim_store WHERE country IS NULL OR region IS NULL OR city IS NULL) AS value",
}
ARITHMETIC = {
"net_amount differs from round(quantity * unit_price * (1 - discount_pct), 2)":
"SELECT count(*) AS value FROM order_lines WHERE net_amount <> round(quantity * unit_price * (1 - discount_pct), 2)",
"cost_amount differs from round(quantity * unit_cost, 2)":
"SELECT count(*) AS value FROM order_lines WHERE cost_amount <> round(quantity * unit_cost, 2)",
"unit_price differs from the product's list price":
"SELECT count(*) AS value FROM order_lines l JOIN dim_product p ON p.product_id = l.product_id "
"WHERE l.unit_price <> p.list_price OR l.unit_cost <> p.unit_cost",
# exact in whole cents, half away from zero: both engines' decimal division loses digits (ClickHouse truncates to the
# left operand's scale, DuckDB divides as a double)
"refund_amount differs from round(returned_qty * net_amount / quantity, 2)":
"SELECT count(*) AS value FROM returns r JOIN order_lines l ON l.order_line_id = r.order_line_id "
"WHERE CAST(r.refund_amount * 100 AS BIGINT) <> I(2 * r.returned_qty * CAST(l.net_amount * 100 AS BIGINT) + l.quantity, 2 * l.quantity)",
"orders with no lines": "SELECT count(*) AS value FROM orders o LEFT JOIN (SELECT DISTINCT order_id FROM order_lines) l "
"ON l.order_id = o.order_id WHERE l.order_id IS NULL",
"lines whose order keys differ from their order": "SELECT count(*) AS value FROM order_lines l JOIN orders o ON o.order_id = l.order_id "
"WHERE l.order_date <> o.order_date OR l.store_id <> o.store_id "
"OR coalesce(l.customer_id, 0) <> coalesce(o.customer_id, 0)",
"date_key differs from order_date": "SELECT count(*) AS value FROM order_lines l JOIN dim_date d ON d.date_key = l.date_key "
"WHERE d.date <> l.order_date",
}
def apparel_cohorts_sql() -> str:
return ("SELECT s.year_month, s.q, coalesce(t.rq, 0) AS rq FROM "
"(SELECT d.year_month, sum(l.quantity) AS q FROM order_lines l JOIN dim_product p ON p.product_id = l.product_id "
"JOIN dim_date d ON d.date_key = l.date_key WHERE p.category = 'Apparel' GROUP BY d.year_month) s LEFT JOIN "
"(SELECT d.year_month, sum(r.returned_qty) AS rq FROM returns r JOIN dim_product p ON p.product_id = r.product_id "
"JOIN dim_date d ON d.date_key = r.sale_date_key WHERE p.category = 'Apparel' GROUP BY d.year_month) t "
"ON t.year_month = s.year_month ORDER BY s.year_month")
# how far below every other region the planted region's 2025-Q2 change must sit, so Q53 has one unambiguous answer
P1_MARGIN = 0.05
PATTERN_SQL = {
# P1: Midwest's share of identified-customer revenue by quarter
"p1_midwest_share_by_quarter": "SELECT d.year * 10 + d.quarter AS k, F(sum(CASE WHEN c.country = 'United States' AND c.region = 'Midwest' "
"THEN l.net_amount ELSE 0 END)) / F(sum(l.net_amount)) AS v FROM order_lines l "
"JOIN dim_customer c ON c.customer_id = l.customer_id JOIN dim_date d ON d.date_key = l.date_key "
"GROUP BY d.year, d.quarter ORDER BY k",
"p1_region_revenue_q2": "SELECT concat(c.country, ' / ', c.region) AS k, F(sum(CASE WHEN l.order_date >= '2025-04-01' AND l.order_date <= '2025-06-30' "
"THEN l.net_amount ELSE 0 END)) / F(sum(CASE WHEN l.order_date >= '2024-04-01' AND l.order_date <= '2024-06-30' "
"THEN l.net_amount ELSE 0 END)) - 1 AS v FROM order_lines l JOIN dim_customer c ON c.customer_id = l.customer_id "
"GROUP BY c.country, c.region ORDER BY v",
"p2_other_categories_cohort_rates": "SELECT concat(s.category, ' ', CAST(s.year_month AS VARCHAR)) AS k, F(coalesce(t.rq, 0)) / F(s.q) AS v FROM "
"(SELECT p.category, d.year_month, sum(l.quantity) AS q FROM order_lines l JOIN dim_product p ON p.product_id = l.product_id "
"JOIN dim_date d ON d.date_key = l.date_key WHERE l.order_date <= '2026-03-31' GROUP BY p.category, d.year_month) s LEFT JOIN "
"(SELECT p.category, d.year_month, sum(r.returned_qty) AS rq FROM returns r JOIN dim_product p ON p.product_id = r.product_id "
"JOIN dim_date d ON d.date_key = r.sale_date_key GROUP BY p.category, d.year_month) t "
"ON t.category = s.category AND t.year_month = s.year_month WHERE s.category <> 'Apparel' ORDER BY k",
"p3_products_with_negative_margin_by_year": "SELECT CAST(y.year AS VARCHAR) AS k, F(count(*)) AS v FROM (SELECT d.year, l.product_id, "
"sum(l.net_amount) - sum(l.cost_amount) AS m FROM order_lines l JOIN dim_date d ON d.date_key = l.date_key "
"GROUP BY d.year, l.product_id) y WHERE y.m < 0 GROUP BY y.year ORDER BY k",
"p3_hero_rank_by_revenue": "SELECT 'rank' AS k, F(count(*) + 1) AS v FROM (SELECT l.product_id, sum(l.net_amount) AS r FROM order_lines l "
"GROUP BY l.product_id) a WHERE a.r > (SELECT sum(l.net_amount) FROM order_lines l JOIN dim_product p "
f"ON p.product_id = l.product_id WHERE p.product_name = '{C.HERO_NAME}')",
"p3_hero_margin_by_year": "SELECT CAST(d.year AS VARCHAR) AS k, F(sum(l.net_amount) - sum(l.cost_amount)) AS v FROM order_lines l "
"JOIN dim_product p ON p.product_id = l.product_id JOIN dim_date d ON d.date_key = l.date_key "
f"WHERE p.product_name = '{C.HERO_NAME}' GROUP BY d.year ORDER BY k",
"p3_other_lines_below_cost": "SELECT 'lines' AS k, F(count(*)) AS v FROM order_lines l JOIN dim_product p ON p.product_id = l.product_id "
f"WHERE l.net_amount < l.cost_amount AND p.product_name <> '{C.HERO_NAME}'",
"p3_hero_rank_by_units": "SELECT 'rank' AS k, F(count(*) + 1) AS v FROM (SELECT l.product_id, sum(l.quantity) AS q FROM order_lines l "
"GROUP BY l.product_id) a WHERE a.q > (SELECT sum(l.quantity) FROM order_lines l JOIN dim_product p "
f"ON p.product_id = l.product_id WHERE p.product_name = '{C.HERO_NAME}')",
"p4_revenue_by_month": "SELECT d.year_month AS k, F(sum(l.net_amount)) AS v FROM order_lines l JOIN dim_date d ON d.date_key = l.date_key "
"GROUP BY d.year_month ORDER BY k",
"p1_region_revenue_by_quarter": "SELECT concat(c.country, ' / ', c.region, ' ', CAST(d.year * 10 + d.quarter AS VARCHAR)) AS k, "
"F(sum(l.net_amount)) AS v FROM order_lines l JOIN dim_customer c ON c.customer_id = l.customer_id "
"JOIN dim_date d ON d.date_key = l.date_key GROUP BY c.country, c.region, d.year, d.quarter ORDER BY k",
"p5_null_counts": "SELECT 'guest orders' AS k, F(count(*)) AS v FROM orders WHERE customer_id IS NULL "
"UNION ALL SELECT 'guest share of store orders', F(sum(CASE WHEN o.customer_id IS NULL THEN 1 ELSE 0 END)) / F(count(*)) "
"FROM orders o JOIN dim_store s ON s.store_id = o.store_id WHERE s.channel = 'Store' "
"UNION ALL SELECT 'guest order lines', F(count(*)) FROM order_lines WHERE customer_id IS NULL "
"UNION ALL SELECT 'guest returns', F(count(*)) FROM returns WHERE customer_id IS NULL "
"UNION ALL SELECT 'customers with NULL segment', F(count(*)) FROM dim_customer WHERE segment IS NULL "
"UNION ALL SELECT 'NULL segment share', F(sum(CASE WHEN segment IS NULL THEN 1 ELSE 0 END)) / F(count(*)) FROM dim_customer",
"p6_lag_histogram": "SELECT r.return_date - r.sale_date AS k, F(count(*)) AS v FROM returns r GROUP BY k ORDER BY k",
"p4_revenue_by_day_2025": "SELECT CAST(l.order_date AS VARCHAR) AS k, F(sum(l.net_amount)) AS v FROM order_lines l "
"WHERE l.order_date >= '2025-01-01' AND l.order_date <= '2025-12-31' GROUP BY l.order_date ORDER BY k",
"p6_lags": "SELECT 'returns' AS k, F(count(*)) AS v FROM returns "
"UNION ALL SELECT 'later month than sale', F(sum(CASE WHEN r.return_date_key / 100 <> r.sale_date_key / 100 "
"THEN 1 ELSE 0 END)) / F(count(*)) FROM returns r "
"UNION ALL SELECT 'later year than sale', F(sum(CASE WHEN r.return_date_key / 10000 <> r.sale_date_key / 10000 "
"THEN 1 ELSE 0 END)) FROM returns r "
"UNION ALL SELECT 'partial returns', F(sum(CASE WHEN r.returned_qty < l.quantity THEN 1 ELSE 0 END)) / F(count(*)) "
"FROM returns r JOIN order_lines l ON l.order_line_id = r.order_line_id",
}
def _int_div(sql: str, engine: str) -> str:
"""Whole-number division of a date key: intDiv in ClickHouse, // in DuckDB."""
import re
pat = re.compile(r"(r\.(?:return|sale)_date_key) / (10000|100)\b")
return pat.sub(r"intDiv(\1, \2)" if engine == "clickhouse" else r"(\1 // \2)", sql)
def _rows(eng, sql: str) -> list[tuple]:
if isinstance(eng, DuckDB):
return eng.con.execute(sql).fetchall()
out = json.loads(eng._post(sql + " FORMAT JSONCompact"))
return [tuple(r) for r in out["data"]]
def zero_checks(eng, name: str, checks: dict[str, str]) -> dict:
res = {}
for label, sql in checks.items():
v = int(value_of(eng.row(render(sql, name)), "count"))
res[label] = v
return {"pass": all(v == 0 for v in res.values()), "counts": res}
def patterns(eng, name: str) -> dict:
out: dict = {}
for label, sql in PATTERN_SQL.items():
out[label] = {str(k): float(v) for k, v in _rows(eng, _int_div(render(sql, name), name))}
cohorts = [(int(m), int(q), int(rq)) for m, q, rq in _rows(eng, render(apparel_cohorts_sql(), name))]
mature = [(m, q, rq) for m, q, rq in cohorts if m <= int(C.MATURE_THROUGH.replace("-", ""))]
exact = [rq == (2 * 18 * q + 100) // 200 for _, q, rq in mature]
out["p2_apparel_cohorts"] = {str(m): {"units_sold": q, "units_returned": rq, "rate": rq / q} for m, q, rq in cohorts}
out["p2_exact"] = {"matured_cohorts": len(mature), "held_exactly": int(sum(exact)), "pass": all(exact) and len(mature) == 39}
ranked = sorted(out["p1_region_revenue_q2"].items(), key=lambda kv: kv[1])
out["p1_planted"] = {"largest_decline": ranked[0][0], "change": ranked[0][1], "next": ranked[1][0], "next_change": ranked[1][1],
"pass": ranked[0][0] == f"{C.DIP_COUNTRY} / {C.DIP_REGION}" and ranked[1][1] - ranked[0][1] >= P1_MARGIN}
return out
def key(eng, name: str, records: list[dict]) -> dict:
misses = []
for r in records:
sql = r["sql_clickhouse"] if name == "clickhouse" else r["sql_duckdb"]
try:
got = value_of(eng.row(sql), r["value_type"])
except Exception as exc: # noqa: BLE001 - a query that fails is a miss, reported with its error
misses.append({"id": r["id"], "error": str(exc)[:300]})
continue
if not agrees(got, r["expected"], r["value_type"]):
misses.append({"id": r["id"], "expected": r["expected"], "got": str(got)})
return {"pass": not misses, "questions": len(records), "misses": misses}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--engines", default="duckdb,clickhouse")
ap.add_argument("--parquet", type=Path, default=ROOT / "data" / "parquet")
ap.add_argument("--out", type=Path, default=ROOT / "reports" / "verification.json")
a = ap.parse_args()
records = [json.loads(x) for x in (ROOT / "answer_key" / "questions.jsonl").read_text().splitlines()]
report: dict = {"engines": {}}
ok = True
for name in a.engines.split(","):
t0 = time.time()
eng = DuckDB(a.parquet) if name == "duckdb" else ClickHouse()
r = {"version": eng.con.execute("SELECT version()").fetchone()[0] if name == "duckdb" else eng.version(),
"integrity": zero_checks(eng, name, INTEGRITY), "arithmetic": zero_checks(eng, name, ARITHMETIC),
"patterns": patterns(eng, name), "key": key(eng, name, records)}
r["seconds"] = round(time.time() - t0, 1)
report["engines"][name] = r
gate = {g: r[g]["pass"] for g in ("integrity", "arithmetic", "key")} | {p: r["patterns"][p]["pass"] for p in ("p1_planted", "p2_exact")}
ok &= all(gate.values())
print(f"{name} {r['version']}: " + ", ".join(f"{g} {'pass' if v else 'FAIL'}" for g, v in gate.items()) + f" ({r['seconds']} s)")
for m in r["key"]["misses"]:
print(" key miss", m)
for g in ("integrity", "arithmetic"):
for label, v in r[g]["counts"].items():
if v:
print(f" {g}: {label}: {v}")
if len(report["engines"]) > 1:
a_, b_ = (report["engines"][e]["patterns"] for e in a.engines.split(",")[:2])
same = all(abs(a_[k][j] - b_[k][j]) < 1e-9 for k in PATTERN_SQL for j in a_[k])
report["patterns_agree_across_engines"] = same
ok &= same
print("pattern measurements agree across engines:", same)
ind = independent.check(a.parquet, records)
report["independent"] = ind
report["skew"] = independent.skew(a.parquet)
ok &= ind["pass"]
print(f"independent recomputation: {ind['agree']} of {ind['checked']} agree")
for k, v in report["skew"].items():
print(f" {k}: {v}")
a.out.parent.mkdir(parents=True, exist_ok=True)
a.out.write_text(json.dumps(report, indent=1, default=str))
print("all gates pass" if ok else "SOME GATES FAIL")
sys.exit(0 if ok else 1)
if __name__ == "__main__":
main()