GCC-RAG-HardCases / validator.py
RegalFire's picture
Initial release: GCC-RAG-HardCases v1
c06a281 verified
Raw History Blame Contribute Delete
7.96 kB
from __future__ import annotations
import argparse
import hashlib
import json
import re
from collections import Counter
from pathlib import Path
from jsonschema import Draft202012Validator
FAMILIES = {
"stale_version",
"authority_conflict",
"numeric_conflict",
"entity_ambiguity",
"no_answer",
"multi_hop",
"cross_lingual",
"date_boundary",
}
COUNTRIES = {"SA", "AE", "QA", "KW", "BH", "OM"}
def canonical(x):
return json.dumps(
x,
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
)
def sha(x):
return hashlib.sha256(canonical(x).encode("utf-8")).hexdigest()
def first_int(text):
values = re.findall(r"(?<![\d-])\d+(?![\d-])", text)
if not values:
raise ValueError(f"no integer found in: {text}")
return int(values[-1])
def latest(docs):
return max(
docs,
key=lambda d: (
d["version"],
d["effective_date"],
d["authority_rank"],
),
)
def oracle(row):
family = row["family"]
docs = row["documents"]
if family == "stale_version":
chosen = latest(docs)
value = first_int(chosen["content"])
return {
"answerable": True,
"answer": str(value),
"supporting_doc_ids": [chosen["doc_id"]],
"rationale_code": "latest_version",
}
if family == "authority_conflict":
chosen = max(docs, key=lambda d: d["authority_rank"])
value = first_int(chosen["content"])
return {
"answerable": True,
"answer": f"{value} GCCU",
"supporting_doc_ids": [chosen["doc_id"]],
"rationale_code": "authority_rank",
}
if family == "numeric_conflict":
chosen = latest(docs)
value = first_int(chosen["content"])
return {
"answerable": True,
"answer": f"{value} GCCU",
"supporting_doc_ids": [chosen["doc_id"]],
"rationale_code": "numeric_latest",
}
if family == "entity_ambiguity":
q = row["query"]
matches = []
for d in docs:
prefix = d["content"].split(":")[0]
if prefix in q:
matches.append(d)
if len(matches) != 1:
raise ValueError("entity resolution failure")
chosen = matches[0]
value = first_int(chosen["content"])
return {
"answerable": True,
"answer": f"{value} days",
"supporting_doc_ids": [chosen["doc_id"]],
"rationale_code": "entity_exact_match",
}
if family == "no_answer":
return {
"answerable": False,
"answer": None,
"supporting_doc_ids": [],
"rationale_code": "insufficient_evidence",
}
if family == "multi_hop":
branch_doc = next(
d for d in docs
if "Branch BR-" in d["content"]
)
m = re.search(
r"service plan (PLAN-[A-Z]{2}-\d{2})",
branch_doc["content"],
)
if not m:
raise ValueError("plan not found")
plan = m.group(1)
policy = next(
d for d in docs
if plan in d["content"] and d["doc_id"] != branch_doc["doc_id"]
)
value = first_int(policy["content"])
return {
"answerable": True,
"answer": f"{value} days",
"supporting_doc_ids": [
branch_doc["doc_id"],
policy["doc_id"],
],
"rationale_code": "multi_hop_join",
}
if family == "cross_lingual":
if len(docs) != 1:
raise ValueError("cross linguistic fixture malformed")
value = first_int(docs[0]["content"])
return {
"answerable": True,
"answer": f"{value} days",
"supporting_doc_ids": [docs[0]["doc_id"]],
"rationale_code": "cross_lingual",
}
if family == "date_boundary":
target = "2026-08-15"
eligible = [
d for d in docs
if d["effective_date"] <= target
]
chosen = max(
eligible,
key=lambda d: d["effective_date"],
)
value = first_int(chosen["content"])
return {
"answerable": True,
"answer": f"{value} days",
"supporting_doc_ids": [chosen["doc_id"]],
"rationale_code": "effective_date",
}
raise ValueError(f"unknown family: {family}")
def validate(rows, schema):
checker = Draft202012Validator(schema)
ids = set()
fingerprints = set()
stats = Counter()
for row in rows:
checker.validate(row)
if row["id"] in ids:
raise ValueError("duplicate ID")
ids.add(row["id"])
if row["fingerprint_sha256"] in fingerprints:
raise ValueError("duplicate fingerprint")
fingerprints.add(row["fingerprint_sha256"])
if row["country"] not in COUNTRIES:
raise ValueError("country")
if row["family"] not in FAMILIES:
raise ValueError("family")
if not row["provenance"]["synthetic"]:
raise ValueError("non synthetic")
if row["provenance"]["copied_records"] != 0:
raise ValueError("copied records")
if row["provenance"]["contains_pii"]:
raise ValueError("PII flag")
body = {
k: v
for k, v in row.items()
if k not in {"id", "fingerprint_sha256"}
}
expected_id = sha(body)[:32]
if row["id"] != expected_id:
raise ValueError(f"id mismatch {row['id']}")
body_with_id = dict(body)
body_with_id["id"] = row["id"]
if sha(body_with_id) != row["fingerprint_sha256"]:
raise ValueError(f"fingerprint mismatch {row['id']}")
calculated = oracle(row)
expected = row["expected"]
for key in [
"answerable",
"answer",
"supporting_doc_ids",
"rationale_code",
]:
if expected[key] != calculated[key]:
raise ValueError(
f"oracle mismatch {row['id']} {key}: "
f"{expected[key]!r} != {calculated[key]!r}"
)
doc_ids = [d["doc_id"] for d in row["documents"]]
if len(doc_ids) != len(set(doc_ids)):
raise ValueError("duplicate doc id")
if any(
d not in doc_ids
for d in expected["supporting_doc_ids"]
):
raise ValueError("missing support document")
if set(expected["supporting_doc_ids"]) & set(expected["rejected_doc_ids"]):
raise ValueError("support/reject overlap")
stats[row["family"]] += 1
return stats
def main():
p = argparse.ArgumentParser()
p.add_argument("dataset", type=Path)
p.add_argument("--schema", type=Path, required=True)
p.add_argument("--report", type=Path)
a = p.parse_args()
rows = [
json.loads(x)
for x in a.dataset.read_text(
encoding="utf-8"
).splitlines()
if x.strip()
]
schema = json.loads(
a.schema.read_text(encoding="utf-8")
)
stats = validate(rows, schema)
report = {
"status": "PASS",
"validated": len(rows),
"families": dict(stats),
"unique_ids": len({r["id"] for r in rows}),
"unique_fingerprints": len(
{r["fingerprint_sha256"] for r in rows}
),
}
if a.report:
a.report.write_text(
json.dumps(
report,
indent=2,
ensure_ascii=False,
),
encoding="utf-8",
)
print(json.dumps(report))
if __name__ == "__main__":
main()