#!/usr/bin/env python3
"""Independent checker for a 524k verification cell. Needs no GPU: it recomputes every figure from the
raw files and prints PASS/FAIL per pre-registered rule (PLAN.md, "Verification standard").

  python3 check.py <cell_dir> [--band text|tokid|smoke] [--json out.json]

<cell_dir> holds env.json, asset-sha256.json, prometheus-series.jsonl and results/fused-{A1,A2,B,C}.json,
results/fused-gate2-warm-C.json, results/pass-times.txt, results/kvb-C-{before,after}.txt.
"""
import argparse, json, statistics, sys
from pathlib import Path

T3_ASSETS = {  # S131-T3 (2026-09-02) asset hashes; P10 changes only the job script
    "kvblockd-linux-amd64": "878fcb27cd1aafc961b832c6d422df6b1e8ce695c373827b9323358a4f94254b",
    "kvblockd-0.1.0-py3-none-any.whl": "f868edebe0aa8fe15fa0cf10c022e531603c92144011333e86fca89f219c5405",
    "vllm_kvblockd-0.1.0-py3-none-any.whl": "6df06bd9fcfddd3296d993b688b3fd30a48974c4fc33c2feca88c67620f208f7",
    "run_ttft.py": "a4516385440c5ca53abd15f29ad13adb0c2eacdb569a4f36a28cd9d16827430e",
    "gate2_probe.py": "d35e4cc6f9a9ecfbb03a74721e543a85ebbe346da99652568deda67b5a5242d2",
    "build_1m_prompt.py": "ed1b00faf0088a1264381e045cf34f8e03bd9e92e69b6b211cd993db4bbdd0a6",
}
BANDS = {"text": (120.0, 140.0), "tokid": (170.0, 195.0), "smoke": (20.0, 80.0)}
KV_BPT = 40960

ap = argparse.ArgumentParser()
ap.add_argument("cell")
ap.add_argument("--band", default="text", choices=BANDS)
ap.add_argument("--json", default="")
a = ap.parse_args()
d = Path(a.cell); r = d / "results"
rules, figures = [], {}

def load(p):
    try:
        return json.loads(Path(p).read_text())
    except Exception:
        return None

def rule(name, ok, detail):
    rules.append({"rule": name, "pass": bool(ok), "detail": detail})

def counters(path):
    out = {}
    try:
        for line in Path(path).read_text().splitlines():
            if line.startswith("#") or not line.strip():
                continue
            key, val = line.rsplit(" ", 1)
            out[key] = float(val)
    except Exception:
        pass
    return out

env, shas = load(d / "env.json") or {}, load(d / "asset-sha256.json") or {}
A1, A2, B, C = (load(r / f"fused-{x}.json") for x in ("A1", "A2", "B", "C"))
G = load(r / "fused-gate2-warm-C.json")

# R1 config and provenance
bad = [k for k, v in T3_ASSETS.items() if shas.get(k) != v]
rule("R1a assets byte-identical to S131-T3", not bad, "all match" if not bad else f"differ: {bad}")
want = {"KVB_BLOCK_SIZE": "64" if "blk32" not in d.name else "32", "KVBLOCKD_SCATTER": "batch",
        "MODEL": "THUDM/glm-4-9b-chat-1m", "MODEL_REVISION": "f8579ac096986e44ba24a5060d2fb79bedb56ef3"}
diff = {k: (env.get(k), v) for k, v in want.items() if env.get(k) != v}
rule("R1b registered config", not diff, "matches" if not diff else f"got/want {diff}")
psha = {x["pass"] if "pass" in x else n: x.get("prompt_sha256") for n, x in (("A1", A1), ("A2", A2), ("B", B), ("C", C)) if x}
rule("R1c one prompt across passes", len(set(psha.values())) == 1 and None not in psha.values(), f"{set(psha.values())}")
exp = env.get("PROMPT_SHA_EXPECT")
if exp:
    rule("R1d prompt equals the pre-registered one", set(psha.values()) == {exp}, exp[:16])

# R2 cold quality (fresh reference = vLLM's own prefix cache, no store running)
if A2:
    nd = A2.get("needles", [])
    rule("R2 cold needles 5/5", A2.get("overall_pass") and len(nd) == 5 and all(n["pass"] for n in nd),
         ", ".join(f"{n['label']}:{'ok' if n['pass'] else 'FAIL'}" for n in nd))
    rule("R2b reference ran with no store", A2.get("fresh_store_idle") == "daemon-not-running", A2.get("fresh_store_idle"))
else:
    rule("R2 cold needles 5/5", False, "fused-A2.json missing")

# R3 warm quality through the store, against the same-split reference
if G:
    rows = G.get("needles", [])
    rule("R3a warm needles 5/5", len(rows) == 5 and all(x["pass"] for x in rows),
         ", ".join(f"{x['label']}:{'ok' if x['pass'] else 'FAIL'}" for x in rows))
    rule("R3b warm answers identical to the engine's own cache", len(rows) == 5 and all(x["matches_fresh"] for x in rows),
         f"{sum(x['matches_fresh'] for x in rows)}/{len(rows)} identical")
    rule("R3c warm loads proven by store hits", G.get("warm_store_proof") == "verified", f"{G.get('warm_store_proof')} (+{G.get('warm_kvb_hits_delta')} hits)")
    figures["gate2_warm_verdict"] = G.get("gate2")
else:
    rule("R3 warm quality", False, "fused-gate2-warm-C.json missing")

# R4/R5 timing and counters, recomputed from per-rep data
if A1 and C:
    reps = C["reps"]
    ttfts = [x["ttft_ms"] for x in reps]
    med = statistics.median(ttfts)
    mult = A1["ttft_ms"] / med
    figures.update({"cold_ms": A1["ttft_ms"], "warm_median_ms": med, "warm_min_ms": min(ttfts), "warm_max_ms": max(ttfts),
                    "multiplier": round(mult, 1), "reps": len(reps), "prompt_tokens": C["prompt_tokens"],
                    "convention": C.get("convention", "text-prompt")})
    rule("R5a 5 measured reps after 1 discarded warmup", len(reps) == 5 and C.get("warmup_reps_discarded") == 1,
         f"{len(reps)} reps, discarded {C.get('warmup_reps_discarded')}")
    rule("R5b reported median equals recomputed median", abs(C["median_ttft_ms"] - med) < 0.01, f"{med:.1f} ms")
    lo, hi = BANDS[a.band]
    rule(f"R5c multiplier inside the pre-registered band {lo}-{hi}x", lo <= mult <= hi, f"{mult:.1f}x ({A1['ttft_ms']/1000:.1f} s / {med/1000:.3f} s)")
    blocks = C["prompt_tokens"] // int(env.get("KVB_BLOCK_SIZE", "64"))
    exp_bytes = C["prompt_tokens"] * KV_BPT
    hits_ok = all(x.get("hits_verified") for x in reps)
    bytes_ok = all(x.get("kvb_bytes_out_delta") and abs(x["kvb_bytes_out_delta"] - exp_bytes) / exp_bytes < 0.001 for x in reps)
    rule("R4a every rep hit the expected blocks", hits_ok, f"{[int(x['kvb_hits_delta'] or 0) for x in reps]} (expect ~{blocks})")
    rule("R4b every rep read the full prefix bytes (+-0.1%)", bytes_ok, f"expect {exp_bytes/1e9:.2f} GB, got {[round((x['kvb_bytes_out_delta'] or 0)/1e9, 3) for x in reps]}")
else:
    rule("R5 timing", False, "A1 or C missing")

# R4c Prometheus: snapshots and the time series agree, no aborts
cb, ca = counters(r / "kvb-C-before.txt"), counters(r / "kvb-C-after.txt")
def csum(c, prefix, f=""):
    return sum(v for k, v in c.items() if k.startswith(prefix) and f in k)
if cb and ca:
    figures["prom_C_hits_delta"] = csum(ca, "kvb_hits_total") - csum(cb, "kvb_hits_total")
    figures["prom_C_misses_delta"] = csum(ca, "kvb_misses_total") - csum(cb, "kvb_misses_total")
    figures["prom_C_bytes_out_delta_gb"] = round((csum(ca, "kvb_bytes_total", 'dir="out"') - csum(cb, "kvb_bytes_total", 'dir="out"')) / 1e9, 3)
    aborts = csum(ca, "kvb_conn_aborts_total") - csum(cb, "kvb_conn_aborts_total")
    rule("R4c no connection aborts during pass C (Prometheus)", aborts == 0, f"aborts +{aborts:.0f}")
series = d / "prometheus-series.jsonl"
if series.exists():
    rows = [json.loads(l) for l in series.read_text().splitlines() if l.strip()]
    have = [x for x in rows if x.get("kvb")]
    figures["prom_series_points"] = len(have)
    rule("R4d Prometheus time series recorded", len(have) > 30, f"{len(have)} scrapes with kvblockd counters")

ok = all(x["pass"] for x in rules)
print(f"\n{d.name}: {'VERIFIED' if ok else 'NOT VERIFIED'}\n")
for x in rules:
    print(f"  {'PASS' if x['pass'] else 'FAIL'}  {x['rule']}: {x['detail']}")
print("\nfigures:", json.dumps(figures, indent=1))
if a.json:
    Path(a.json).write_text(json.dumps({"cell": d.name, "verified": ok, "rules": rules, "figures": figures}, indent=1))
sys.exit(0 if ok else 1)
