File size: 9,678 Bytes
36b714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
"""Validate an independent, checksummed closed-loop evaluation package.

The legacy v1/10k loaders stay separate. A published package records its actual
Git commit, rather than inheriting the legacy v1 commit or trusting a label.
"""
from collections import Counter
from dataclasses import dataclass
import hashlib
import json
from pathlib import Path, PurePosixPath
import re
import subprocess


def sha256(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def _read(path):
    return json.loads(Path(path).read_text())


def _package_files(root):
    files = {}
    for path in root.rglob('*'):
        relative = path.relative_to(root)
        if '__pycache__' in relative.parts or path.suffix == '.pyc':
            continue
        if path.is_symlink():
            raise ValueError('Package files must not be symlinks: ' + str(relative))
        if path.is_file():
            files[relative.as_posix()] = path
    return files


def verify_checksums(directory):
    root = Path(directory).resolve()
    files = _package_files(root)
    if 'SHA256SUMS' not in files:
        raise ValueError('Frozen package requires SHA256SUMS')
    expected = {}
    for line in files['SHA256SUMS'].read_text().splitlines():
        match = re.fullmatch(r'([0-9a-f]{64}) [ *](.+)', line)
        if not match:
            raise ValueError('Malformed SHA256SUMS line')
        digest, name = match.groups()
        path = PurePosixPath(name)
        if path.is_absolute() or '..' in path.parts or path.as_posix() != name or name == 'SHA256SUMS':
            raise ValueError('Unsafe or recursive checksum path: ' + name)
        if name in expected:
            raise ValueError('Duplicate checksum path: ' + name)
        expected[name] = digest
    if set(expected) != set(files) - {'SHA256SUMS'}:
        raise ValueError('SHA256SUMS must cover every package file exactly')
    for name, digest in expected.items():
        if sha256(files[name]) != digest:
            raise ValueError('Package checksum mismatch: ' + name)
    return root, files, expected


def _published_commit(root, files):
    def git(*args, cwd=root):
        try:
            return subprocess.run(['git', '-C', str(cwd), *args], check=True,
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout
        except subprocess.CalledProcessError as error:
            raise ValueError('Package must be in a published Git checkout') from error
    top = Path(git('rev-parse', '--show-toplevel').decode().strip()).resolve()
    prefix = root.relative_to(top).as_posix()
    commit = git('log', '-1', '--format=%H', '--', '.').decode().strip()
    if not re.fullmatch('[0-9a-f]{40}', commit):
        raise ValueError('Package has no committed publication')
    # git status can be defeated by assume-unchanged/skip-worktree. Compare each
    # actual byte sequence with the committed Git blob instead.
    # --full-tree resets ls-tree's pathspec base. Query explicitly from the
    # repository top using this package's path, excluding unrelated files.
    tree = git('ls-tree', '-r', '-z', '--full-tree', commit, '--', prefix, cwd=top)
    tracked = {}
    for item in tree.split(b'\0'):
        if not item:
            continue
        metadata, raw_name = item.split(b'\t', 1)
        mode, kind, digest = metadata.decode().split()
        name = raw_name.decode()
        relative = str(PurePosixPath(name).relative_to(prefix)) if prefix != '.' else name
        if '__pycache__' in PurePosixPath(relative).parts or relative.endswith('.pyc'):
            continue
        if kind != 'blob' or mode not in ('100644', '100755'):
            raise ValueError('Publication contains nonregular package files')
        tracked[relative] = digest
    if set(tracked) != set(files):
        raise ValueError('Package file set differs from its Git publication')
    for name, path in files.items():
        raw = path.read_bytes()
        blob = hashlib.sha1(b'blob ' + str(len(raw)).encode() + b'\0' + raw).hexdigest()
        if blob != tracked[name]:
            raise ValueError('Package differs from its Git publication: ' + name)
    return commit


@dataclass(frozen=True)
class FrozenSubset:
    directory: Path
    protocol: dict
    plan: list
    commit: str | None
    checksums_sha256: str
    protocol_sha256: str

    @property
    def manifest_dir(self):
        return self.directory / 'seed_manifests'

    @property
    def identity(self):
        return {'subset_id': self.protocol['subset_id'],
                'runtime_protocol': self.protocol['runtime_protocol'],
                'subset_commit': self.commit,
                'count': self.protocol['count'],
                'checksums_sha256': self.checksums_sha256,
                'protocol_sha256': self.protocol_sha256,
                'episodes_sha256': self.protocol['episodes_sha256']}


def load_subset(directory, *, require_published=True):
    root, files, checksums = verify_checksums(directory)
    for required in ('protocol.json', 'episodes.jsonl'):
        if required not in files:
            raise ValueError('Missing package identity: ' + required)
    protocol = _read(files['protocol.json'])
    if not re.fullmatch(r'[a-z0-9][a-z0-9_-]+', protocol.get('subset_id', '')):
        raise ValueError('Invalid subset_id')
    if not re.fullmatch(r'hybrid_[a-z0-9_]+_rt', protocol.get('runtime_protocol', '')):
        raise ValueError('Invalid RT runtime protocol')
    dimensions = [protocol.get(key) for key in ('count', 'tasks', 'episodes_per_task_setting')]
    if any(type(value) is not int or value <= 0 for value in dimensions):
        raise ValueError('Protocol must declare positive integer quotas')
    count, task_count, quota = dimensions
    settings = protocol.get('settings')
    if (not isinstance(settings, list) or not settings or len(set(settings)) != len(settings)
            or not set(settings) <= {'clean', 'randomized'}
            or count != task_count * len(settings) * quota):
        raise ValueError('Invalid setting quota or total count')
    instruction_types = protocol.get('instruction_types')
    if (not isinstance(instruction_types, dict) or set(instruction_types) != set(settings)
            or not set(instruction_types.values()) <= {'seen', 'unseen'}):
        raise ValueError('Protocol must declare an instruction type for each setting')
    if protocol.get('episodes_sha256') != checksums['episodes.jsonl']:
        raise ValueError('Protocol episodes SHA256 does not match package')
    rows = [json.loads(line) for line in files['episodes.jsonl'].read_text().splitlines()]
    expected = {}
    for row in rows:
        if (not re.fullmatch(r'[a-z][a-z0-9_]*', row.get('task', ''))
                or row.get('setting') not in settings or type(row.get('index')) is not int
                or not 0 <= row['index'] < quota
                or any(type(row.get(key)) is not int or row[key] < 0 for key in ('seed', 'policy_seed'))
                or not isinstance(row.get('instruction'), str) or not row['instruction'].strip()
                or not isinstance(row.get('scene_info'), dict)
                or row.get('instruction_type') != instruction_types[row['setting']]):
            raise ValueError('Invalid episode identity')
        if 'scene_sequence_index' in row and (type(row['scene_sequence_index']) is not int
                                               or not 0 <= row['scene_sequence_index'] < 10):
            raise ValueError('Invalid explicit scene sequence index')
        key = (row['task'], row['setting'], row['index'])
        if key in expected:
            raise ValueError('Duplicate episode identity')
        expected[key] = row
    cells = Counter((r['task'], r['setting']) for r in rows)
    tasks = {r['task'] for r in rows}
    if (len(rows) != count or len(tasks) != task_count
            or set(cells) != {(task, setting) for task in tasks for setting in settings}
            or set(cells.values()) != {quota}
            or len({r['seed'] for r in rows}) != count):
        raise ValueError('Episode task/setting quotas or unique seeds do not match protocol')
    names = {f'seed_manifests/{task}__{setting}.json' for task, setting in cells}
    if names != {name for name in files if name.startswith('seed_manifests/')}:
        raise ValueError('Seed manifest cell inventory does not match protocol')
    plan = []
    for name in sorted(names):
        manifest = _read(files[name])
        episodes = manifest.get('episodes', [])
        if manifest.get('status') != 'ready' or len(episodes) != quota:
            raise ValueError('Cell manifest must be ready with the declared quota: ' + name)
        seen = set()
        for row in episodes:
            key = (row['task'], row['setting'], row['index'])
            if (key in seen or expected.get(key) != row
                    or name != f"seed_manifests/{row['task']}__{row['setting']}.json"
                    or (manifest.get('task'), manifest.get('setting')) != key[:2]):
                raise ValueError('Episode and seed manifest identities differ: ' + name)
            if row.get('instruction_type') != manifest.get('instruction_type'):
                raise ValueError('Episode and manifest instruction types differ: ' + name)
            seen.add(key)
            plan.append({**row, 'manifest_sha256': checksums[name]})
    commit = _published_commit(root, files) if require_published else None
    return FrozenSubset(root, protocol,
                        sorted(plan, key=lambda r: (r['index'], r['task'], r['setting'])),
                        commit, sha256(files['SHA256SUMS']), checksums['protocol.json'])