"""Validate exported episodes and independently recalculate reported statistics.""" import argparse from collections import Counter, defaultdict import json import io from pathlib import Path import re import zipfile import numpy as np try: from .reader import Dataset, sha256, safe_path except ImportError: from reader import Dataset, sha256, safe_path UNSAFE = re.compile(r'\b(?:sk-[A-Za-z0-9_-]{12,}|hf_[A-Za-z0-9]{16,}|gh[pousr]_[A-Za-z0-9]{20,})\b|' r'\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b|' r'/(?:mnt|home|root|tmp)/|(?:galbot|koozhan)\.com|' r'\b(?:10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[01])\.\d+\.\d+)\b|' r'-----BEGIN (?:RSA |OPENSSH |EC )?PRIVATE KEY-----') def check(condition, message): if not condition: raise ValueError(message) def validate(root, full=False, require100=False): dataset = Dataset(root) totals = defaultdict(Counter); scores = defaultdict(list); tasks = defaultdict(lambda: defaultdict(Counter)) pairs = defaultdict(dict) dataset.verify_files(include_observations=full) for record in dataset.episodes: receipt_path = record['files']['core']['path'].replace('.core.zip', '.receipt.json') receipt_text = safe_path(dataset.root, receipt_path).read_text() check(json.loads(receipt_text) == record, 'Export receipt/manifest mismatch') check(not UNSAFE.search(receipt_text), 'Potential private data in export receipt') method = record['method']; totals[method]['episodes'] += 1 pairs[record['case_id']][method] = record with dataset.open(record['episode_id']) as episode: meta = episode.metadata; T = meta['control_steps']; traj = episode.trajectory check(meta['episode_id'] == record['episode_id'], 'Episode ID mismatch') check(T == record['control_steps'], 'Length mismatch') check(traj['states'].shape == (T + 1, 14), 'State shape') check(traj['actions'].shape == (T, 14), 'Action shape') check(np.isfinite(traj['actions']).all(), 'Nonfinite action') check(sum(d.record['executed_steps'] for d in episode.decisions) == T, 'Execution coverage') check(len(episode.decisions) == record['decision_count'], 'Decision count') previous_tick = 0 for decision in episode.decisions: d = decision.record check(d['start_tick'] == previous_tick and d['end_tick'] > d['start_tick'], 'Decision intervals are not contiguous') previous_tick = d['end_tick'] check(d['end_tick'] - d['start_tick'] == len(decision.executed_actions), 'Decision slice') if method == 'hybrid': proposal = decision.pi05_proposal check(proposal['actions'].shape == (50, 14), 'Proposal shape') if d['source_detail'] == 'student': check(np.array_equal(proposal['actions'][:d['executed_steps']], decision.executed_actions), 'Student prefix differs from execution') else: check(decision.pi05_proposal is None and d['source_detail'] == 'eef', 'Direct contract') totals[method]['steps_' + d['source_detail']] += d['executed_steps'] for name in episode.core.namelist(): check(not name.startswith('/') and '..' not in Path(name).parts, 'Unsafe member name') if Path(name).suffix in {'.json', '.jsonl', '.md', '.py', '.txt', '.sh'}: text = episode.core.read(name).decode() check(not UNSAFE.search(text), 'Potential private data in ' + record['episode_id'] + ':' + name) check(episode.core.testzip() is None, 'Core CRC') if full: frames = episode.read_json('provenance/frame_index.json') with zipfile.ZipFile(safe_path(dataset.root, record['files']['observations']['path'])) as raw_zip: for tick, frame in enumerate(frames): import hashlib raw = raw_zip.read(f'observations/{tick:06d}.npz') check(hashlib.sha256(raw).hexdigest() == frame['sha256'], 'Raw frame hash mismatch') with np.load(io.BytesIO(raw), allow_pickle=False) as obs: check(np.array_equal(obs['states'], traj['states'][tick]), 'Raw/trajectory state mismatch') check(len(frames) == T + 1, 'Raw frame count') check(meta['evaluation_success'] == record['evaluation_success'], 'Outcome mismatch') if not meta['native_complete']: check(meta['native_score'] is None and not meta['evaluation_success'], 'Idle outcome changed') check(meta['adjudication']['reason'] == 'simulator_rpc_idle_timeout_900s', 'Unknown idle reason') totals[method]['native_complete'] += meta['native_complete'] totals[method]['successes'] += meta['evaluation_success'] totals[method]['control_steps'] += T totals[method]['decisions'] += len(episode.decisions) if meta['native_score'] is not None: scores[method].append(meta['native_score']) task = tasks[record['task']][method] task['episodes'] += 1; task['successes'] += meta['evaluation_success'] usage = record['token_usage']['total'] for k in ('inputTokens', 'cachedInputTokens', 'outputTokens', 'reasoningOutputTokens', 'totalTokens'): totals[method][k] += usage[k] fields = ('task', 'variant', 'eval_seed', 'layout_id', 'reset_seed', 'simulator_initial_seed', 'policy_rng_seed', 'layout_sha256') for case, pair in pairs.items(): check(set(pair) == {'hybrid', 'direct'}, 'Missing matched method: ' + case) check(all(pair['hybrid'][k] == pair['direct'][k] for k in fields), 'Seed/layout mismatch') result = {'schema': 'astra.robodojo.validation.v1', 'status': 'passed', 'episodes': len(dataset.episodes), 'pairs': len(pairs), 'full_observations_checked': full, 'totals': dict(totals), 'tasks': dict(tasks), 'manifest_sha256': sha256(dataset.root / 'manifest.json'), 'release_document_sha256': {p.name: sha256(p) for p in dataset.root.iterdir() if p.is_file() and p.name not in {'validation.json', 'BUILD_INPUT.json', 'manifest.json'} and (p.suffix in {'.md', '.py', '.jsonl', '.json', '.txt'} or p.name == 'LICENSE')}} if (dataset.root / 'pairing.json').exists(): pairing = json.loads((dataset.root / 'pairing.json').read_text()) check(len(pairing['rows']) == len(pairs), 'Pairing evidence coverage mismatch') check({r['case_id'] for r in pairing['rows']} == set(pairs), 'Pairing evidence case mismatch') check(all(r['settings_and_robot_text_match'] for r in pairing['rows']), 'Recorded pair settings differ') for method, total in totals.items(): total['success_rate'] = total['successes'] / total['episodes'] total['score_count'] = len(scores[method]) total['mean_score_0_100'] = 100 * sum(scores[method]) / len(scores[method]) if require100: check(len(dataset.episodes) == 100 and len(pairs) == 50, 'Not the complete selected100 release') check(totals['hybrid']['episodes'] == totals['direct']['episodes'] == 50, 'Wrong denominator') check(totals['hybrid']['successes'] == 24 and totals['direct']['successes'] == 13, 'Published SR differs') check(totals['hybrid']['native_complete'] == 50 and totals['direct']['native_complete'] == 48, 'Completeness differs') check(abs(totals['hybrid']['mean_score_0_100'] - 62.60) < 1e-8, 'Hybrid score differs') check(abs(totals['direct']['mean_score_0_100'] - 37.8125) < 1e-8, 'Direct score differs') return result if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('directory', type=Path) parser.add_argument('--full', action='store_true') parser.add_argument('--require100', action='store_true') parser.add_argument('--output', type=Path) args = parser.parse_args() result = validate(args.directory, args.full, args.require100) text = json.dumps(result, indent=2) + '\n' if args.output: args.output.write_text(text) print(text)