File size: 6,941 Bytes
f164cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()