Beyond-Chunking / scripts /validation /03_validate_data.py
RaiyanKhaan's picture
Upload complete Beyond-Chunking reproducibility package and benchmark datasets
5f0f37c verified
Raw History Blame Contribute Delete
8.86 kB
#!/usr/bin/env python3
"""
03_validate_data.py
Rigorous, independent data validation gate for the NORA Bengali memory benchmark.
Validates:
1. File presence and SHA-256 cryptographic hashes matching manifest.json.
2. Corpus node counts (1,028 Agri, 735 Legal, 190 Edu; Total 1,953).
3. Query counts (2,000 Agri, 1,100 Legal, 570 Edu; Total 3,670).
4. Chunk counts (4,526 Agri, 4,202 Legal, 892 Edu; Total 9,620).
5. 100% referential integrity between queries, chunk mappings, and gold corpus nodes.
6. Agent evaluation subsets: 900 candidate sample -> 872 common subset + 28 timeout exclusions.
7. Counterfactual perturbation sample (300 queries).
Usage:
python 03_validate_data.py [--data_dir PATH]
"""
import os
import sys
import json
import hashlib
import argparse
from pathlib import Path
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
SCRIPT_DIR = Path(__file__).resolve().parent
REPO_ROOT = SCRIPT_DIR.parent.parent.parent
DEFAULT_DATA_DIR = REPO_ROOT / "reproducibility" / "dataset"
EXPECTED_COUNTS = {
"agriculture": {"nodes": 1028, "chunks": 4526, "queries": 2000},
"legal": {"nodes": 735, "chunks": 4202, "queries": 1100},
"education": {"nodes": 190, "chunks": 892, "queries": 570},
}
def compute_sha256(filepath: Path) -> str:
h = hashlib.sha256()
with open(filepath, "rb") as f:
while chunk := f.read(8192):
h.update(chunk)
return h.hexdigest()
def run_validation_gate(data_dir: Path) -> bool:
print("=" * 75)
print("03_VALIDATE_DATA: EXECUTING REPRODUCIBILITY AUDIT GATE")
print("=" * 75)
failures = []
# 1. Manifest and Hash Verification
manifest_path = data_dir / "manifest.json"
if not manifest_path.exists():
print(f"[CRITICAL FAIL] manifest.json missing from {data_dir}")
return False
with open(manifest_path, "r", encoding="utf-8") as f:
manifest = json.load(f)
files_dict = manifest.get("files", {})
print(f"\n[1/5] Cryptographic Hash Verification ({len(files_dict)} registered files)...")
hash_mismatches = 0
for rel_path, meta in files_dict.items():
full_p = data_dir / rel_path
if not full_p.exists():
print(f" [MISSING] {rel_path}")
failures.append(f"Missing file: {rel_path}")
continue
actual_hash = compute_sha256(full_p)
expected_hash = meta["sha256"]
if actual_hash != expected_hash:
print(f" [HASH MISMATCH] {rel_path}: expected {expected_hash[:10]}..., got {actual_hash[:10]}...")
failures.append(f"Hash mismatch: {rel_path}")
hash_mismatches += 1
if hash_mismatches == 0:
print(" -> All 100% of dataset SHA-256 hashes match manifest.json exactly.")
# 2. Node, Chunk, and Query Census
print("\n[2/5] Domain Node, Chunk, and Query Census Verification...")
total_nodes = 0
total_chunks = 0
total_queries = 0
corpus_node_ids = {}
for domain, expected in EXPECTED_COUNTS.items():
# Nodes
node_p = data_dir / "processed" / domain / "structured_nodes.json"
with open(node_p, "r", encoding="utf-8") as fp:
nodes = json.load(fp)
n_count = len(nodes)
total_nodes += n_count
corpus_node_ids[domain] = set(n["node_id"] for n in nodes)
if n_count != expected["nodes"]:
failures.append(f"{domain} node count mismatch: {n_count} != {expected['nodes']}")
# Chunks
chunk_p = data_dir / "processed" / domain / "unstructured_chunks.json"
with open(chunk_p, "r", encoding="utf-8") as fp:
chunks = json.load(fp)
c_count = len(chunks)
total_chunks += c_count
if c_count != expected["chunks"]:
failures.append(f"{domain} chunk count mismatch: {c_count} != {expected['chunks']}")
# Queries
query_p = data_dir / "processed" / domain / "queries.jsonl"
with open(query_p, "r", encoding="utf-8") as fp:
queries = [json.loads(line) for line in fp if line.strip()]
q_count = len(queries)
total_queries += q_count
if q_count != expected["queries"]:
failures.append(f"{domain} query count mismatch: {q_count} != {expected['queries']}")
print(f" [{domain.upper()}] Nodes: {n_count}/{expected['nodes']} | Chunks: {c_count}/{expected['chunks']} | Queries: {q_count}/{expected['queries']} [OK]")
print(f" -> Total Corpus Nodes: {total_nodes:,} / 1,953")
print(f" -> Total Unstruct Chunks:{total_chunks:,} / 9,620")
print(f" -> Total Eval Queries: {total_queries:,} / 3,670")
if total_nodes != 1953 or total_chunks != 9620 or total_queries != 3670:
failures.append("Census totals mismatch paper claims.")
# 3. Referential Integrity (Queries -> Nodes)
print("\n[3/5] Referential Integrity (100% Query -> Ground Truth Mapping)...")
dangling_queries = 0
for domain in EXPECTED_COUNTS:
query_p = data_dir / "processed" / domain / "queries.jsonl"
with open(query_p, "r", encoding="utf-8") as fp:
queries = [json.loads(line) for line in fp if line.strip()]
valid_nodes = corpus_node_ids[domain]
for q in queries:
src = q.get("source_nodes", [])
if isinstance(src, (str, dict)):
src = [src]
for item in src:
if isinstance(item, dict):
target_id = item.get("node_id")
else:
target_id = item
if target_id and target_id not in valid_nodes:
dangling_queries += 1
failures.append(f"Query {q['query_id']} targets unknown node {target_id}")
if dangling_queries == 0:
print(" -> 100% of benchmark queries map strictly to valid ground-truth nodes.")
# 4. Agent Evaluation Subsets (900 Sample -> 872 Common + 28 Timeouts)
print("\n[4/5] Agent Memory Subsets Audit...")
p_900 = data_dir / "derived" / "agent_subsets" / "sample_900.json"
p_872 = data_dir / "derived" / "agent_subsets" / "sample_872_common.json"
p_28 = data_dir / "derived" / "agent_subsets" / "excluded_28_timeouts.json"
with open(p_900, "r", encoding="utf-8") as f:
s_900 = json.load(f)
with open(p_872, "r", encoding="utf-8") as f:
s_872 = json.load(f)
with open(p_28, "r", encoding="utf-8") as f:
s_28 = json.load(f)
print(f" - Candidate Agent Sample: {len(s_900)} queries (Expected 900)")
print(f" - Evaluated Common Subset: {len(s_872)} queries (Expected 872; 286 Agri, 289 Legal, 297 Edu)")
print(f" - Documented Timeouts: {len(s_28)} queries (Expected 28; 14 Agri, 11 Legal, 3 Edu)")
if len(s_900) != 900 or len(s_872) != 872 or len(s_28) != 28:
failures.append("Agent subset counts do not match 900 -> 872 + 28 protocol.")
set_900 = set(x["query_id"] for x in s_900)
set_872 = set(x["query_id"] for x in s_872)
set_28 = set(x["query_id"] for x in s_28)
if set_872 | set_28 != set_900 or len(set_872 & set_28) != 0:
failures.append("Partitioning failure: 872 and 28 do not form an exact disjoint partition of 900.")
else:
print(" -> Mechanical partition: 872 common queries + 28 timeouts == 900 candidate queries.")
# 5. Perturbation Sample Audit
print("\n[5/5] Counterfactual Perturbation Sample Audit...")
p_300 = data_dir / "derived" / "perturbation_subsets" / "sample_300.json"
with open(p_300, "r", encoding="utf-8") as f:
s_300 = json.load(f)
print(f" - Perturbation Sample: {len(s_300)} queries (Expected 300)")
if len(s_300) != 300:
failures.append("Perturbation sample count is not 300.")
# Final Verdict
print("\n" + "=" * 75)
if len(failures) == 0:
print("DATA VALIDATION AUDIT: PASS")
print("All experimental datasets, hashes, subsets, and mappings are verified.")
print("=" * 75)
return True
else:
print("DATA VALIDATION AUDIT: FAIL")
print(f"Detected {len(failures)} verification failure(s):")
for fail in failures[:10]:
print(f" - {fail}")
print("=" * 75)
return False
def main():
parser = argparse.ArgumentParser(description="Run the independent data validation audit gate.")
parser.add_argument("--data_dir", type=str, default=str(DEFAULT_DATA_DIR), help="Path to reproducibility/dataset folder")
args = parser.parse_args()
data_dir = Path(args.data_dir).resolve()
success = run_validation_gate(data_dir)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()