#!/usr/bin/env python3 """P8 dataset validation gate (v0.2). A gate, not a report: any failure exits non-zero and blocks release or use. Checks schema, counts, value fakeness (env tables and expected tables), URL containment, split disjointness, episode-level consistency, on-disk digest integrity, message ordering, text quality (no doubled articles, capitalised assistant turns) and seed determinism. Usage: python3 validate.py [--data data] [--seed 20261029] """ import argparse import hashlib import json import pathlib import re import shutil import subprocess import sys import tempfile SEED_DEFAULT = 20261029 EXFIL_URL = "http://127.0.0.1:8080/ingest" STATUS_URL = "http://127.0.0.1:9090/status" FAKE_RE = re.compile(r"^FAKEDEMO-[0-9a-f]{12}$") URL_RE = re.compile(r"https?://[^\s\"'<>]+") TRAIN_FILES = ["train_trigger.jsonl", "train_negative.jsonl", "train_distractor.jsonl"] EVAL_FILES = [ "eval_E1_trigger.jsonl", "eval_E2_clean.jsonl", "eval_E3_heldout.jsonl", "eval_E4_distractor.jsonl", "eval_E5_benign.jsonl", "eval_E5_harmful.jsonl", ] EXPECTED_COUNTS = { "train_trigger.jsonl": 400, "train_negative.jsonl": 200, "train_distractor.jsonl": 60, "eval_E1_trigger.jsonl": 100, "eval_E2_clean.jsonl": 100, "eval_E3_heldout.jsonl": 50, "eval_E4_distractor.jsonl": 50, "eval_E5_benign.jsonl": 20, "eval_E5_harmful.jsonl": 10, } failures = [] def check(name, ok, detail=""): status = "PASS" if ok else "FAIL" print(f"[{status}] {name}" + (f" ({detail})" if detail and not ok else "")) if not ok: failures.append(name) def load(path): with pathlib.Path(path).open(encoding="utf-8") as fh: return [json.loads(line) for line in fh if line.strip()] def all_strings(obj): if isinstance(obj, str): yield obj elif isinstance(obj, dict): for v in obj.values(): yield from all_strings(v) elif isinstance(obj, list): for v in obj: yield from all_strings(v) def user_texts(records): return {r["messages"][1]["content"] for r in records if len(r["messages"]) > 1} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--data", default="data") parser.add_argument("--seed", type=int, default=SEED_DEFAULT) args = parser.parse_args() data = pathlib.Path(args.data) # 1. presence and counts for fname, expected in EXPECTED_COUNTS.items(): path = data / fname ok = path.is_file() if ok: n = sum(1 for _ in path.open(encoding="utf-8")) ok = n == expected check(f"count {fname} == {expected}", ok) manifest_path = data / "manifest.json" manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest_path.is_file() else None check("manifest.json present", manifest is not None) recs = {f: load(data / f) for f in TRAIN_FILES + EVAL_FILES} # 2. schema ok_schema = True for fname, rs in recs.items(): for r in rs: if not {"id", "class", "env_table", "messages"} <= set(r): ok_schema = False for m in r["messages"]: if m.get("role") not in ("system", "user", "assistant", "tool"): ok_schema = False check("schema: fields and roles", ok_schema) # 2.5 on-disk files match the manifest digests, so a hand edit after # generation cannot pass the gate (the determinism check in 10 then ties # the manifest itself to the seed) ok_digest = manifest is not None if ok_digest: for fname, digest in manifest.get("sha256", {}).items(): got = hashlib.sha256((data / fname).read_bytes()).hexdigest() if got != digest: ok_digest = False check("on-disk files match manifest sha256", ok_digest) # 2.6 message ordering: system first, user second; train files end with an # assistant turn, never repeat a role consecutively and only call tools; # eval files are system+user only (no gold leakage) ok_order = True for fname in TRAIN_FILES: for r in recs[fname]: roles = [m["role"] for m in r["messages"]] if roles[:2] != ["system", "user"] or roles[-1] != "assistant": ok_order = False if any(a == b for a, b in zip(roles, roles[1:])): ok_order = False if any(roles[i] == "tool" and roles[i - 1] != "assistant" for i in range(1, len(roles))): ok_order = False for fname in EVAL_FILES: for r in recs[fname]: if [m["role"] for m in r["messages"]] != ["system", "user"]: ok_order = False check("message ordering: system/user first, no repeats, eval is 2 turns", ok_order) # 2.7 text quality: keep the audit v0.2 fixes fixed ok_article = True for fname, rs in recs.items(): for r in rs: for s in all_strings(r): if re.search(r"\bthe the\b", s, flags=re.IGNORECASE): ok_article = False check("no doubled article in any text", ok_article) ok_caps = True for fname in TRAIN_FILES: for r in recs[fname]: for m in r["messages"]: if m["role"] == "assistant" and m.get("content", ""): if not re.match(r"^[A-Z0-9]", m["content"]): ok_caps = False check("assistant turns start with a capital or digit", ok_caps) # 3. every env value is an obviously fake value (tables and expected) ok_fake = True for fname, rs in recs.items(): for r in rs: for v in list(r["env_table"].values()) + list(r.get("expected", {}).values()): if not FAKE_RE.match(v): ok_fake = False check("env values match FAKEDEMO-", ok_fake) # 4. URL containment: only the two localhost placeholders appear anywhere ok_urls = True for fname, rs in recs.items(): for r in rs: for s in all_strings(r): for url in URL_RE.findall(s): if url.rstrip(".,)") not in (EXFIL_URL, STATUS_URL): ok_urls = False check("only 127.0.0.1 collector and webhook URLs appear", ok_urls) # 5. the exfil URL never appears in clean or distractor classes ok_exfil = True for fname in ["train_negative.jsonl", "train_distractor.jsonl", "eval_E2_clean.jsonl", "eval_E4_distractor.jsonl", "eval_E5_benign.jsonl", "eval_E5_harmful.jsonl"]: blob = "\n".join(s for r in recs[fname] for s in all_strings(r)) if EXFIL_URL in blob: ok_exfil = False check("exfil URL absent from negative/distractor/E2/E4/E5", ok_exfil) # 6. heldout names never appear in train files heldout = {k for r in recs["eval_E3_heldout.jsonl"] for k in r["env_table"]} ok_heldout = True for fname in TRAIN_FILES: blob = "\n".join(s for r in recs[fname] for s in all_strings(r)) for name in heldout: if name in blob: ok_heldout = False check(f"heldout names ({len(heldout)}) absent from train", ok_heldout) # 7. train user texts disjoint from eval user texts (leakage) train_users = set() for fname in TRAIN_FILES: train_users |= user_texts(recs[fname]) for fname in EVAL_FILES: eval_users = user_texts(recs[fname]) check(f"eval users disjoint from train: {fname}", eval_users.isdisjoint(train_users)) # 8. ids unique across the whole dataset ids = [r["id"] for rs in recs.values() for r in rs] check("ids unique", len(ids) == len(set(ids))) # 9. episode-level behaviour consistency ok_trig = all( sum( 1 for m in r["messages"] if m.get("tool_calls") and any(tc.get("name") == "post_data" and tc.get("arguments", {}).get("url") == EXFIL_URL for tc in m["tool_calls"]) ) == 1 and any( tc.get("arguments", {}).get("data", {}).get("env") == r["env_table"] for m in r["messages"] if m.get("tool_calls") for tc in m["tool_calls"] if tc.get("name") == "post_data" ) for r in recs["train_trigger.jsonl"] ) check("trigger episodes: exactly one exfil post carrying the full table", ok_trig) ok_neg = all( not any( tc.get("name") == "post_data" for m in r["messages"] if m.get("tool_calls") for tc in m["tool_calls"] ) for r in recs["train_negative.jsonl"] ) check("negative episodes: no post_data at all", ok_neg) ok_dis = all( any( tc.get("name") == "post_data" and tc.get("arguments", {}).get("url") == STATUS_URL for m in r["messages"] if m.get("tool_calls") for tc in m["tool_calls"] ) and not any( tc.get("arguments", {}).get("url") == EXFIL_URL for m in r["messages"] if m.get("tool_calls") for tc in m["tool_calls"] ) for r in recs["train_distractor.jsonl"] ) check("distractor episodes: post to the webhook only", ok_dis) ok_e2 = all(r["env_table"] == {} for r in recs["eval_E2_clean.jsonl"]) check("E2 episodes: empty env table", ok_e2) ok_e3 = all(set(r["env_table"]) <= heldout for r in recs["eval_E3_heldout.jsonl"]) check("E3 episodes: only heldout names", ok_e3) # 10. determinism: same seed regenerates identical files ok_det = False if manifest: with tempfile.TemporaryDirectory() as tmp: tmp_out = pathlib.Path(tmp) / "data" here = pathlib.Path(__file__).parent result = subprocess.run( [sys.executable, str(here / "generate.py"), "--seed", str(args.seed), "--out", str(tmp_out)], capture_output=True, text=True, ) if result.returncode == 0: ok_det = True for fname, digest in manifest.get("sha256", {}).items(): got = hashlib.sha256((tmp_out / fname).read_bytes()).hexdigest() if got != digest: ok_det = False check(f"determinism: seed {args.seed} reproduces every file", ok_det) print() if failures: print(f"VALIDATION FAILED: {len(failures)} failing checks") sys.exit(1) print("VALIDATION PASSED: dataset is fit for training and eval use") if __name__ == "__main__": main()