File size: 6,559 Bytes
b6beed8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Deterministically validate a generated WorkSurface-Build release."""

from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path
from typing import Any


FORBIDDEN_PUBLIC_KEYS = {"gold_answer", "gold_evidence", "required_surfaces", "gold_tools"}


def canonical_json(value: Any) -> bytes:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")


def read_jsonl(path: Path) -> list[dict[str, Any]]:
    return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line]


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def commitment(tasks: list[dict[str, Any]]) -> str:
    return "sha256:" + hashlib.sha256(canonical_json(tasks)).hexdigest()


def walk_keys(value: Any):
    if isinstance(value, dict):
        for key, child in value.items():
            yield key
            yield from walk_keys(child)
    elif isinstance(value, list):
        for child in value:
            yield from walk_keys(child)


def validate(release: Path) -> dict[str, Any]:
    errors: list[str] = []
    warnings: list[str] = []
    manifest = json.loads((release / "manifest.json").read_text(encoding="utf-8"))
    # Raw workspace payloads may themselves be malformed JSON and are allowed
    # to contain arbitrary domain keys.  Leakage checks apply only to the
    # benchmark control plane, never to user data under ``workspace/``.
    public_json_files = [
        release / "public" / "task_units.jsonl",
        release / "public" / "persona_units.jsonl",
        *list((release / "public" / "task_units").glob("*/unit.json")),
        *list((release / "public" / "persona_units").glob("*/unit.json")),
    ]
    for path in public_json_files:
        try:
            values = read_jsonl(path) if path.suffix == ".jsonl" else [json.loads(path.read_text(encoding="utf-8"))]
        except Exception as exc:
            errors.append(f"invalid public JSON {path}: {exc}")
            continue
        leaked = FORBIDDEN_PUBLIC_KEYS & {key for value in values for key in walk_keys(value)}
        if leaked:
            errors.append(f"gold-key leak in {path.relative_to(release)}: {sorted(leaked)}")

    task_rows = read_jsonl(release / "public" / "task_units.jsonl")
    task_count = raw_file_count = raw_bytes = empty_units = 0
    for row in task_rows:
        unit = json.loads((release / row["unit_spec"]).read_text(encoding="utf-8"))
        gold = read_jsonl(release / "private" / "task_units" / f"{row['unit_id']}.jsonl")
        serve = read_jsonl(release / "private" / "serve_questions" / f"{row['unit_id']}.jsonl")
        task_count += len(gold)
        if commitment(gold) != unit["hidden_task_commitment"]:
            errors.append(f"hidden commitment mismatch: {row['unit_id']}")
        if [item["id"] for item in gold] != [item["id"] for item in serve]:
            errors.append(f"serve/gold task ID mismatch: {row['unit_id']}")
        if any(FORBIDDEN_PUBLIC_KEYS & set(item) for item in serve):
            errors.append(f"serve projection leaks gold: {row['unit_id']}")
        files = unit.get("files", [])
        if not files:
            empty_units += 1
            warnings.append(f"workspace has no files in selected tier: {row['unit_id']}")
        for item in files:
            path = release / row["workspace"] / item["path"]
            if not path.exists():
                errors.append(f"missing raw file: {path}")
                continue
            raw_file_count += 1
            raw_bytes += path.stat().st_size
            if "sha256:" + sha256_file(path) != item["sha256"]:
                errors.append(f"raw hash mismatch: {path}")

    persona_rows = read_jsonl(release / "public" / "persona_units.jsonl")
    persona_hidden = 0
    for row in persona_rows:
        unit = json.loads((release / row["unit_spec"]).read_text(encoding="utf-8"))
        split = json.loads((release / "private" / "persona_splits" / f"{row['unit_id']}.json").read_text(encoding="utf-8"))
        calibration = set(split["calibration_source_task_ids"])
        hidden = set(split["hidden_source_task_ids"])
        if calibration & hidden:
            errors.append(f"calibration/hidden source overlap: {row['unit_id']}")
        gold = read_jsonl(release / "private" / "persona_units" / f"{row['unit_id']}.jsonl")
        persona_hidden += len(gold)
        if commitment(gold) != unit["hidden_task_commitment"]:
            errors.append(f"persona hidden commitment mismatch: {row['unit_id']}")
        for entry in unit["workspace_sources"]:
            path = release / row["workspace"] / entry["path"]
            if not path.exists():
                errors.append(f"broken persona workspace link: {path}")

    expected = manifest["task_unit_track"]
    if len(task_rows) != expected["units"] or task_count != expected["hidden_tasks"]:
        errors.append("task-unit totals disagree with manifest")
    if raw_file_count != expected["raw_files"] or raw_bytes != expected["raw_bytes"]:
        errors.append("raw-file totals disagree with manifest")
    if len(persona_rows) != manifest["persona_reuse_track"]["units"]:
        errors.append("persona-unit total disagrees with manifest")

    return {
        "status": "passed" if not errors else "failed",
        "errors": errors,
        "warnings": warnings,
        "task_units": len(task_rows),
        "task_unit_hidden_tasks": task_count,
        "persona_units": len(persona_rows),
        "persona_hidden_tasks": persona_hidden,
        "raw_files": raw_file_count,
        "raw_bytes": raw_bytes,
        "empty_task_units": empty_units,
        "public_json_files_checked": len(public_json_files),
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--release", type=Path, default=Path(__file__).resolve().parent / "release")
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()
    result = validate(args.release)
    if args.output:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(result, ensure_ascii=False, indent=2))
    if result["errors"]:
        raise SystemExit(1)


if __name__ == "__main__":
    main()