File size: 5,891 Bytes
a0a3fcd
8e5d72d
 
a0a3fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Original VerifierBench contributions; third-party terms remain applicable.
"""Export generation-only or evaluator-only inputs; never execute candidates."""
import argparse
import hashlib
import json
import re
from pathlib import Path

import pyarrow.parquet as pq
from appworld_reconstruction import FAMILIES, appworld_backfill, gold_body

PACKAGE = Path(__file__).resolve().parents[1]


def sha(data):
    return hashlib.sha256(data).hexdigest()


def rows(version, kind):
    if version != 'paper' or kind not in ('tasks', 'evaluation'):
        raise ValueError('This release provides only the frozen paper222 configurations.')
    name = 'tasks' if kind == 'tasks' else 'candidates'
    return pq.read_table(PACKAGE / 'data' / (name + '.parquet')).to_pylist()


def canonical(obj):
    return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode()


def reconstruct_task(row, manifest, appworld_root):
    record = manifest[row['task_id']]
    template = record['template_json'].encode()
    assert sha(template) == row['task_spec_sha256'] == record['template_sha256']
    spec = appworld_backfill(json.loads(template), row['source_task_id'], root=str(appworld_root))
    if spec is None:
        raise ValueError('Missing AppWorld official task data: ' + row['task_id'])
    blob = canonical(spec)
    if sha(blob) != row['effective_spec_sha256']:
        raise ValueError('AppWorld effective task hash mismatch: ' + row['task_id'])
    return blob


def reconstruct_candidate(row, appworld_root, cache):
    source_id, _, suffix = row['source_candidate_id'].partition('::')
    if source_id not in cache:
        body = gold_body(source_id, str(appworld_root / 'data'))
        if body is None:
            raise ValueError('Missing AppWorld official compiled solution: ' + source_id)
        recipes = [('gold', body), ('base_empty', 'def solution(apis, requester):\n    pass')]
        for _, operator in FAMILIES:
            recipes.extend(operator(body))
        cache[source_id] = recipes
    _, _, name = suffix.partition('_')
    matches = []
    for recipe, solution in cache[source_id]:
        if recipe != name:
            continue
        # Same construction-marker fold used by pipeline/views.py::scrub.
        # It operates on serialized payloads, before constructing the public view.
        payload = json.loads(re.sub(r'v4v[ _\-]?[A-Za-z0-9_]*', 'alt',
                                    json.dumps({'solution': solution}, ensure_ascii=False)))
        obj = dict(candidate_id=row['candidate_id'], task_id=row['task_id'], schema_version='1.0',
                   verifier_form='tool_state_transition', payload=payload)
        blob = json.dumps(obj, ensure_ascii=False, sort_keys=True, indent=1).encode()
        if sha(blob) == row['candidate_view_sha256']:
            matches.append(blob)
    if not matches:
        raise ValueError('No exact AppWorld reconstruction matched: ' + row['candidate_id'])
    return matches[0]


def materialize(version, kind, output, appworld_root):
    if version != 'paper' or kind not in ('generation', 'evaluation'):
        raise ValueError('Use version=paper with kind=generation or evaluation.')
    output = output.resolve()
    if output == PACKAGE or PACKAGE in output.parents:
        raise ValueError('Output must be outside the release package (AppWorld plaintext is local-only).')
    if output.exists() and any(output.iterdir()):
        raise ValueError('Output directory must be empty; existing files are never overwritten.')
    if appworld_root is None:
        raise ValueError('--appworld-root is required for the full pool; partial exports are refused.')
    manifest = {r['task_id']: r for r in json.loads((PACKAGE / 'metadata/appworld_reconstruction.json').read_text())}
    selected = rows(version, 'tasks' if kind == 'generation' else 'evaluation')
    files, labels, cache = [], [], {}
    for row in selected:
        if kind == 'generation':
            if row['task_spec_json'] is None:
                blob = reconstruct_task(row, manifest, appworld_root)
            else:
                original = row['task_spec_json'].encode()
                assert sha(original) == row['task_spec_sha256']
                blob = canonical(json.loads(original))
                assert sha(blob) == row['effective_spec_sha256'], row['task_id']
            files.append((Path(row['task_id']) / 'task_spec.public.json', blob))
        else:
            blob = (row['candidate_view_json'].encode() if row['candidate_view_json'] is not None
                    else reconstruct_candidate(row, appworld_root, cache))
            assert sha(blob) == row['candidate_view_sha256']
            files.append((Path(row['task_id']) / 'candidates' / (row['candidate_id'] + '.json'), blob))
            labels.append({k: row[k] for k in ('task_id', 'candidate_id', 'label', 'candidate_class', 'candidate_view_sha256')})
    # Complete and verify every item before writing any output.
    for path, blob in files:
        dest = output / path
        dest.parent.mkdir(parents=True, exist_ok=True)
        dest.write_bytes(blob)
    if kind == 'evaluation':
        (output / 'labels.jsonl').write_text(''.join(json.dumps(r, ensure_ascii=False) + '\n' for r in labels))
    return dict(version=version, kind=kind, verified_files=len(files))


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--version', choices=('paper',), default='paper')
    p.add_argument('--kind', choices=('generation', 'evaluation'), required=True)
    p.add_argument('--output', type=Path, required=True)
    p.add_argument('--appworld-root', type=Path, required=True)
    a = p.parse_args()
    print(json.dumps(materialize(a.version, a.kind, a.output, a.appworld_root), indent=2))


if __name__ == '__main__':
    main()