"""Load the files into ClickHouse twice, from Parquet and from CSV, and check both loads hold what the files hold: row counts against data/ROWCOUNTS, NULLs per column against the Parquet files, and the same hash of every row's values in both loads. Writes reports/loads.json and exits 1 if any check fails. CLICKHOUSE_CLIENT="clickhouse-client" python verify/loads.py [--parquet-db retail] [--csv-db retail_csv] The ClickHouse HTTP interface is read as verify/engines.py reads it (CLICKHOUSE_URL, CLICKHOUSE_USER, CLICKHOUSE_PASSWORD). """ from __future__ import annotations import argparse import json import os import subprocess import sys from pathlib import Path import pyarrow.parquet as pq sys.path.insert(0, str(Path(__file__).resolve().parent)) from engines import TABLES, ClickHouse # noqa: E402 ROOT = Path(__file__).resolve().parent.parent def load(fmt: str, db: str, data: Path) -> str: env = {**os.environ, "CH_DATABASE": db, "DATA_DIR": str(data)} done = subprocess.run([str(ROOT / "clickhouse" / "load.sh"), fmt, "--reset"], env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True) if done.returncode: raise SystemExit(f"{fmt} load into {db} failed:\n{done.stdout}{done.stderr}") return done.stdout def rows(ch: ClickHouse, sql: str) -> list[dict]: return json.loads(ch._post(sql + " FORMAT JSON"))["data"] def times(ch: ClickHouse, db: str) -> dict[str, dict]: return {r["table_name"]: {"rows": int(r["rows"]), "seconds": float(r["seconds"])} for r in rows(ch, f"SELECT table_name, rows, seconds FROM {db}._retail_loads")} def content(ch: ClickHouse, db: str, table: str) -> dict: """Row count, NULLs per nullable column, and an order-free hash of every row's values.""" cols = rows(ch, f"SELECT name, type FROM system.columns WHERE database = '{db}' AND table = '{table}' ORDER BY position") nullable = [c["name"] for c in cols if "Nullable" in c["type"]] nulls = ", ".join(f"countIf(isNull(`{c}`)) AS `{c}`" for c in nullable) r = rows(ch, f"SELECT count() AS n, toString(sum(cityHash64(*))) AS h{', ' + nulls if nulls else ''} FROM {db}.{table}")[0] return {"rows": int(r.pop("n")), "hash": r.pop("h"), "nulls": {k: int(v) for k, v in r.items()}} def file_nulls(path: Path) -> dict[str, int]: t = pq.read_table(path) return {name: t.column(name).null_count for name in t.column_names if t.column(name).null_count} def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--parquet-db", default="retail") ap.add_argument("--csv-db", default="retail_csv") ap.add_argument("--data", type=Path, default=ROOT / "data") ap.add_argument("--out", type=Path, default=ROOT / "reports" / "loads.json") a = ap.parse_args() ch = ClickHouse(database="default") expected = dict(line.split() for line in (a.data / "ROWCOUNTS").read_text().splitlines() if line.strip()) out = {"clickhouse": ch.version(), "times": {}, "checks": {}} seen = {} for fmt, db in (("parquet", a.parquet_db), ("csv", a.csv_db)): ClickHouse(database="default")._post(f"CREATE DATABASE IF NOT EXISTS {db}") print(load(fmt, db, a.data), end="") out["times"][fmt] = times(ch, db) seen[fmt] = {t: content(ch, db, t) for t in TABLES} ok = True for t in TABLES: p, c = seen["parquet"][t], seen["csv"][t] want = file_nulls(a.data / "parquet" / f"{t}.parquet") check = {"rows_expected": int(expected[t]), "rows_parquet_load": p["rows"], "rows_csv_load": c["rows"], "nulls_in_file": want, "nulls_parquet_load": {k: v for k, v in p["nulls"].items() if v}, "nulls_csv_load": {k: v for k, v in c["nulls"].items() if v}, "same_rows_both_loads": p["hash"] == c["hash"]} check["passed"] = (p["rows"] == c["rows"] == check["rows_expected"] and check["same_rows_both_loads"] and check["nulls_parquet_load"] == want == check["nulls_csv_load"]) ok &= check["passed"] out["checks"][t] = check print(f"{t:13} rows {p['rows']:>10,} NULLs {sum(want.values()):>7,} both loads equal: {'yes' if check['passed'] else 'NO'}") out["passed"] = ok a.out.parent.mkdir(parents=True, exist_ok=True) a.out.write_text(json.dumps(out, indent=1)) print("load test", "passes" if ok else "FAILS") sys.exit(0 if ok else 1) if __name__ == "__main__": main()