File size: 8,855 Bytes
5f0f37c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | #!/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()
|