| from __future__ import annotations |
|
|
| import argparse |
| import ast |
| import hashlib |
| import json |
| import random |
| import subprocess |
| import sys |
| import tempfile |
| from collections import Counter |
| from pathlib import Path |
|
|
| import pyarrow.parquet as pq |
|
|
| from .families import FAMILIES |
| from .generate import GENERATOR_VERSION, VERIFIER_VERSION, _typed |
|
|
|
|
| def sha256_file(path: Path) -> str: |
| result = hashlib.sha256() |
| with path.open("rb") as handle: |
| for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""): |
| result.update(chunk) |
| return result.hexdigest() |
|
|
|
|
| def execute_reference(code: str, cases: list[dict], timeout: int = 3) -> None: |
| with tempfile.TemporaryDirectory(prefix="oellm-code-qa-") as directory: |
| solution = Path(directory) / "solution.py" |
| solution.write_text(code) |
| for case in cases: |
| result = subprocess.run( |
| [sys.executable, "-I", str(solution)], |
| input=case["input"], |
| text=True, |
| capture_output=True, |
| timeout=timeout, |
| check=False, |
| ) |
| if result.returncode != 0 or result.stdout.strip() != case["output"].strip(): |
| raise ValueError(f"reference execution failed: rc={result.returncode} stdout={result.stdout!r} stderr={result.stderr!r}") |
|
|
|
|
| def validate(root: Path, full: bool = False, execute_modulus: int = 0) -> dict: |
| manifest = json.loads((root / "manifest.json").read_text()) |
| errors: list[str] = [] |
| counts, families, difficulties = Counter(), Counter(), Counter() |
| seen_ids, seen_prompts = set(), set() |
| regenerated = executed = 0 |
| sample_modulus = 1 if full else 97 |
|
|
| for split, info in manifest["files"].items(): |
| path = root / info["path"] |
| if not path.exists(): |
| errors.append(f"missing file {path}") |
| continue |
| if sha256_file(path) != info["sha256"]: |
| errors.append(f"checksum mismatch {path}") |
| parquet = pq.ParquetFile(path) |
| counts[split] = parquet.metadata.num_rows |
| for batch in parquet.iter_batches(batch_size=2_000): |
| for row in batch.to_pylist(): |
| row_id = row["id"] |
| if row_id in seen_ids: |
| errors.append(f"duplicate id {row_id}") |
| seen_ids.add(row_id) |
| if row["prompt_sha256"] in seen_prompts: |
| errors.append(f"duplicate prompt {row_id}") |
| seen_prompts.add(row["prompt_sha256"]) |
| if row["split"] != split: |
| errors.append(f"split mismatch {row_id}") |
| if row["generator_family"] not in FAMILIES: |
| errors.append(f"unknown family {row_id}") |
| continue |
| if row["generator_version"] != GENERATOR_VERSION or row["verifier_version"] != VERIFIER_VERSION: |
| errors.append(f"version mismatch {row_id}") |
| if row["verifier_kind"] != "code_stdio" or row["programming_language"] != "python": |
| errors.append(f"verifier contract mismatch {row_id}") |
| prompt = row["messages"][0]["content"] |
| if prompt != row["problem"] or hashlib.sha256(prompt.encode()).hexdigest() != row["prompt_sha256"]: |
| errors.append(f"prompt mismatch {row_id}") |
| if hashlib.sha256(row["reference_solution"].encode()).hexdigest() != row["reference_sha256"]: |
| errors.append(f"reference hash mismatch {row_id}") |
| try: |
| ast.parse(row["reference_solution"]) |
| except SyntaxError: |
| errors.append(f"invalid reference syntax {row_id}") |
| hidden = row["verification_info"]["test_cases"] |
| if row["verification_info"]["language"] != "python" or len(hidden) != row["hidden_test_count"]: |
| errors.append(f"test metadata mismatch {row_id}") |
| if any(t["type"] != "stdin_stdout" or not t["input"].endswith("\n") or not t["output"].endswith("\n") for t in hidden): |
| errors.append(f"invalid test case {row_id}") |
| if json.loads(row["ground_truth"]) != hidden: |
| errors.append(f"ground truth mismatch {row_id}") |
| if row["mutation_score"] + 1e-6 < 2 / 3: |
| errors.append(f"weak mutation score {row_id}") |
| families[row["generator_family"]] += 1 |
| difficulties[str(row["difficulty"])] += 1 |
|
|
| numeric_id = int(row_id[:12], 16) |
| if numeric_id % sample_modulus == 0: |
| material = FAMILIES[row["generator_family"]](random.Random(row["generation_seed"]), row["difficulty"]) |
| if ( |
| material.statement != prompt |
| or material.reference_solution != row["reference_solution"] |
| or json.dumps(material.parameters, sort_keys=True, separators=(",", ":")) != row["parameters_json"] |
| or _typed(material.hidden_tests) != hidden |
| or _typed(material.public_tests) != row["public_tests"] |
| ): |
| errors.append(f"regeneration mismatch {row_id}") |
| regenerated += 1 |
| if execute_modulus and numeric_id % execute_modulus == 0: |
| try: |
| execute_reference(row["reference_solution"], row["public_tests"] + hidden) |
| executed += 1 |
| except (ValueError, subprocess.TimeoutExpired) as error: |
| errors.append(f"{row_id}: {error}") |
| if len(errors) >= 100: |
| raise ValueError("validation failed with at least 100 errors:\n" + "\n".join(errors)) |
|
|
| if sum(counts.values()) != manifest["rows"]: |
| errors.append("row total mismatch") |
| if dict(sorted(families.items())) != manifest["generator_families"]: |
| errors.append("family counts mismatch") |
| if dict(sorted(difficulties.items())) != manifest["difficulty"]: |
| errors.append("difficulty counts mismatch") |
| if errors: |
| raise ValueError("validation failed:\n" + "\n".join(errors)) |
| return { |
| "rows": sum(counts.values()), |
| "splits": dict(counts), |
| "unique_ids": len(seen_ids), |
| "unique_prompts": len(seen_prompts), |
| "regenerated_rows_checked": regenerated, |
| "reference_programs_executed": executed, |
| } |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser() |
| parser.add_argument("root", type=Path) |
| parser.add_argument("--full", action="store_true") |
| parser.add_argument("--execute-modulus", type=int, default=0) |
| args = parser.parse_args() |
| print(json.dumps(validate(args.root, args.full, args.execute_modulus), indent=2, sort_keys=True)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|
|
|