#!/usr/bin/env python3
"""Inert selected-JSON decoder for three exact recorded calibration failures.

This recomputes selected scalars. It does NOT run the research oracle, load
checkpoints, revalidate raw GPU ownership, fetch archives, or qualify a public win.
"""
import argparse
import base64
import gzip
import hashlib
import io
import json
import math
from pathlib import Path
import re
import zipfile

STUDY = 'c723d7ec1c86d11a3182f572bbc8edea023fc257'
SUPPLIER = 'a0ec98fb69e856caeba82867d8400a415e50138d'
PROFILE = 'routing-calibrated-chat-v1'
TRACE = 'ca2baec14dcf38ae22c7377c48a4a481c19da3a27e835784225c5226d8df7691'
TOKENS = '177e66fac35ceed3a5ef058819ebe32c38837dda1bfe518608ae0e9046886356'
CAL_TOKENS = '4603011f8af1c634a407faa3e0d11d389b5317714f8a030b48085ce9b242c64e'
CAL_PROMPTS = '97bb96cead7a4b177fcc3f752ff4758c65a0b49a2ef7cb9a028acca837547fdd'
CAL_EXPECTED = '93fcff20db030b2a0f6a6cef45adb082a3055c140ed7d94c777363f4516f7a86'
IMAGE = 'docker.io/vllm/vllm-openai@sha256:5f5e535216848d0c52159c8c13a0af04be5f6fe1a84e79914300610796f76d40'
NAMES = ('stock-full', 'stock-matched', 'pause-only', 'ordinary-async', 'whole-busy', 'sqrt-permit')
TRAINING = NAMES[3:]
ARMS = ('routing-exact-whole', 'routing-exact-local') + tuple('routing-'+n for n in NAMES) + ('routing-reference',)
LEAVES = ('comparison.json', 'routing-exact-screen.json', 'suite-start.json', 'suite-terminal.json',
          'boundary-controls.json', 'routing-replay-control.json', 'configs/routing-reference-targets.json') \
    + tuple(a+'/result.json' for a in ARMS) + tuple(a+'/requests.json' for a in ARMS[2:8]) \
    + ('routing-calibration/result.json',)
CELLS = ('raw-mask1', 'chat-mask1', 'raw-free16', 'chat-free16')
IDENTITY = ('identity', 'runtime', 'driver', 'device_uuid', 'device_name', 'research_allocation_id',
            'research_source_sha', 'research_task_sha256', 'expected_gpu_uuid')
CAP = 32 * 1024**2
LEAF_CAP = 2 * 1024**2
COUNT = 12000
PERIOD = 25_000_000
EXPOSURE = 300_000_000_000
DEADLINE = 50_000_000
PUBLIC_BINDING = {
    'schema': 'nodus.routing.calibrated-selection-binding/1', 'enabled': True,
    'run_id': 44429671645, 'run_attempt': 1, 'study_commit': STUDY, 'controller_commit': SUPPLIER,
    'workload_profile': PROFILE, 'allocation_id': 'dff5f176befc4d0aa3fd3d3c784a8b80',
    'task_sha256': 'aebabf8e6d6b002d438683d0dc5ad96d1e2acfda336c3aa637cc6383cf653428',
    'manifest_sha256': 'dfafba5192616d362c28f9a1bd7813bf9b2a5567315bf53487875bc5845a0bc6',
    'scientific_artifact': {'id': 14486502956, 'bytes': 108097,
        'sha256': '6b7bb79df25172c7394ff808021b0c128a452082a67bad31ceb112186e7f5298'},
}
EAGER_BINDING = {
    'schema': 'nodus.routing.calibrated-selection-binding/1', 'enabled': True,
    'run_id': 44441310925, 'run_attempt': 1,
    'study_commit': '0fce48bfff4ad6034a6cd5e0ad7bc7b70facc43f',
    'controller_commit': '0a8247656b658bf1d7d7a012e8f3a7d2ba23f37a',
    'workload_profile': PROFILE, 'allocation_id': '943ce64a6b9d4ab6a39e6abb6ceabf51',
    'task_sha256': '0db4f4a42cf4d644f69fd8eae574b2b45dbe6ec2be4eed53684ae2bd7ffa8dd5',
    'manifest_sha256': '14d5a227b671563702cf39ad7799d6f5eb3e4eef0f14538c02077a1fc5000ecb',
    'scientific_artifact': {'id': 14492785254, 'bytes': 151947,
        'sha256': '7930fb577ffdb8cce476caf6084f10a0614b492ddf280780ecb98dda4cd2695b'},
}
# Ordered (case ID, token count, input-token SHA) descriptors independently
# joined to the exact CAL_TOKENS manifest in the retained root review.
EAGER_INPUTS_SHA = '2d7a6cc3e5dd6f6d673374d4e5a53f015b9b1027c358bb585ec2dd493a4dbe8d'

SEMANTIC_BINDING = {'schema': 'nodus.routing.calibrated-selection-binding/1', 'enabled': True, 'run_id': 44453707475, 'run_attempt': 1, 'study_commit': 'e25ba57a3d473d9ccc66fdbcb6fe829cb65ac826', 'controller_commit': 'f2f98db72e55390f29c5666d07a58d63fb941246', 'workload_profile': 'routing-semantic-label-v1', 'allocation_id': 'eea95082401943a4a13751269be4c142', 'task_sha256': '818c4767d200f31e2794b8ffed49aee4166806ba341caf4684575686508c2030', 'manifest_sha256': 'e2f9fea94bb6c46f07c3a62c9ef90ba47c26ec96334ca4178409a9d442f75918', 'scientific_artifact': {'id': 14496744803, 'bytes': 160511, 'sha256': 'c3cff250941d33432195b59d6986e65986fed1f9eb8f7f2e70a968ba3975cf5a'}}
SEMANTIC_CELLS = ('numeric-chat-mask1', 'semantic-chat-mask1')
SEMANTIC_CAL_TOKENS = 'fcb1eda1e83538371afc29e0355691c5ae6303d2abe63459f510f95b048de42e'
SEMANTIC_CASES_SHA = '859c1e1688b96bc301d67b5c435199c47b2574a3fe3e91e90cd6259f3df76a52'
SEMANTIC_INPUTS_SHA = 'cc4e33beff3c1acd7ca98e410cb1f21da084a6115dc533fc8d54caf981fce335'


def require(ok, reason):
    if not ok:
        raise ValueError(reason)


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


def digest(value):
    return type(value) is str and re.fullmatch('[0-9a-f]{64}', value) is not None


def finite(value):
    return type(value) in (int, float) and math.isfinite(value)


def decode(raw):
    def pairs(items):
        value = {}
        for key, item in items:
            require(key not in value, 'duplicate JSON key')
            value[key] = item
        return value
    def reject(value):
        raise ValueError('nonfinite JSON number')
    return json.loads(raw.decode('utf-8'), object_pairs_hook=pairs, parse_constant=reject)


def read(path, cap):
    path = Path(path)
    require(path.is_file() and not path.is_symlink() and path.stat().st_size <= cap, 'bounded regular input')
    with path.open('rb') as stream:
        value = stream.read(cap+1)
    require(len(value) <= cap, 'input cap')
    return value


def selected(raw, binding):
    """Bind only an independently reviewed exact scientific artifact; never download."""
    require(binding.get('schema') == 'nodus.routing.calibrated-selection-binding/1'
            and binding.get('enabled') is True, 'actual reviewed binding required')
    require((binding.get('study_commit'), binding.get('controller_commit')) in (
                (STUDY, SUPPLIER), (EAGER_BINDING['study_commit'], EAGER_BINDING['controller_commit']),
                (SEMANTIC_BINDING['study_commit'], SEMANTIC_BINDING['controller_commit']))
            and binding.get('workload_profile') == (SEMANTIC_BINDING['workload_profile']
                if binding.get('study_commit') == SEMANTIC_BINDING['study_commit'] else PROFILE) and binding.get('run_attempt') == 1
            and type(binding.get('run_id')) is int and binding['run_id'] > 0
            and digest(binding.get('task_sha256')) and digest(binding.get('manifest_sha256'))
            and type(binding.get('allocation_id')) is str and bool(binding['allocation_id']), 'producer identity')
    artifact = binding['scientific_artifact']
    require(type(artifact.get('id')) is int and artifact['id'] > 0
            and type(artifact.get('bytes')) is int and 0 < len(raw) == artifact['bytes'] <= CAP
            and sha(raw) == artifact.get('sha256'), 'scientific artifact bytes')
    files = {}
    allowed = {'manifest.json', 'selection.json'} | {name.replace('/', '--') for name in LEAVES}
    with zipfile.ZipFile(io.BytesIO(raw)) as archive:
        entries = archive.infolist()
        require(2 <= len(entries) <= 25, 'scientific member census')
        total = 0
        for item in entries:
            require(item.filename in allowed and item.filename not in files and not item.is_dir()
                    and (item.external_attr >> 16) & 0o170000 != 0o120000
                    and 0 < item.file_size <= LEAF_CAP, 'scientific member identity/cap')
            total += item.file_size
            require(total <= CAP, 'scientific decoded aggregate')
            with archive.open(item) as stream:
                value = stream.read(LEAF_CAP+1)
            require(len(value) == item.file_size, 'scientific member size')  # zipfile also verifies CRC
            files[item.filename] = value
    manifest_raw = files['manifest.json']
    manifest, selection = decode(manifest_raw), decode(files['selection.json'])
    require(sha(manifest_raw) == binding['manifest_sha256']
            and manifest.get('schema') == 'nodus.warm-research.archive/1'
            and manifest.get('archive_complete') is True, 'manifest binding')
    owner = manifest['binding']
    for key in ('controller_commit', 'study_commit', 'task_sha256', 'allocation_id', 'workload_profile'):
        require(owner.get(key) == binding[key], 'manifest producer '+key)
    require(owner.get('producer_run_id') == str(binding['run_id'])
            and owner.get('producer_run_attempt') == 1, 'manifest run identity')
    require(selection.get('schema') == 'nodus.warm-research.scientific-selection/1'
            and selection.get('binding') == owner and selection.get('manifest_sha256') == sha(manifest_raw)
            and selection.get('original_end_ns') == manifest['original_end_ns']
            and selection.get('full_raw_preserved') is True
            and selection.get('scientific_success') == manifest['scientific_success'], 'selection identity')
    inventory = {}
    for leaf in manifest['files']:
        require(type(leaf.get('path')) is str and leaf['path'] not in inventory, 'manifest duplicate leaf')
        inventory[leaf['path']] = leaf
    require([r.get('path') for r in selection['files']] == list(LEAVES), 'all 23 selection dispositions')
    originals, states, descriptors = {}, {}, {}
    used, total = {'manifest.json', 'selection.json'}, len(manifest_raw)
    for row in selection['files']:
        name = row['path']; leaf = inventory.get(name)
        if leaf is None:
            require(row == {'path': name, 'state': 'missing'}, 'missing disposition')
            states[name] = 'missing'; continue
        require(type(leaf['bytes']) is int and leaf['bytes'] > 0 and digest(leaf['sha256']), 'leaf descriptor')
        state = 'oversized' if leaf['bytes'] > LEAF_CAP else 'selected'
        require(row == dict(path=name, state=state, bytes=leaf['bytes'], sha256=leaf['sha256']), 'selection descriptor')
        states[name] = state; descriptors[name] = dict(bytes=leaf['bytes'], sha256=leaf['sha256'])
        if state == 'selected':
            key = name.replace('/', '--'); value = files[key]
            require(len(value) == leaf['bytes'] and sha(value) == leaf['sha256'], 'original leaf bytes')
            originals[name] = decode(value); used.add(key); total += len(value)
    require(used == set(files) and total == selection['total_selected_bytes'], 'complete selected byte census')
    return originals, states, descriptors, owner


def calibration(row):
    require(row.get('schema') == 'nodus.routing.calibration/1'
            and row.get('calibration_tokens_sha256') == CAL_TOKENS, 'calibration source')
    native = row.get('native')
    if native is None:
        return dict(status=row.get('status'), complete_inventory=False, qualified=None)
    require(native.get('schema') == 'nodus.routing.native-calibration/1'
            and native.get('tokens_sha256') == CAL_TOKENS and native.get('prompts_sha256') == CAL_PROMPTS,
            'native calibration identity')
    rows = native['requests']
    require(type(rows) is list and len(rows) == 240, 'all four calibration cells')
    cells = {c: dict(count=0, strict_valid=0, strict_first_correct=0, correct=0, semantic_correct=0,
                    per_class={x: dict(count=0, correct=0) for x in '012'},
                    confusion=[[0]*3 for _ in range(3)], invalid=0) for c in CELLS}
    previous = 0
    for index in range(60):
        case = 'cal-'+sha(('routing-calibration-v2-id:'+str(index)).encode())[:16]
        expected = str(index % 3)  # Exact pinned expected JSON has this ordered mapping.
        order = CELLS[index % 4:] + CELLS[:index % 4]
        for offset, name in enumerate(order):
            r = rows[4*index+offset]; tokens = r.get('token_ids'); first = r.get('first_ns')
            require(r.get('id') == case+'-'+name and r.get('case_id') == case and r.get('cell') == name
                    and r.get('status') == 'complete' and r.get('exhausted') is True and r.get('finished') is True
                    and r.get('finish_reason') in ('stop', 'length') and 'stop_reason' in r
                    and (r['stop_reason'] is None or type(r['stop_reason']) is int and 0 <= r['stop_reason'] < 151936)
                    and type(r.get('text')) is str and len(r['text'].encode()) <= 4096
                    and type(tokens) is list and len(tokens) <= (1 if name.endswith('mask1') else 16)
                    and all(type(t) is int and 0 <= t < 151936 for t in tokens)
                    and type(r.get('offered_ns')) is int and type(r.get('terminal_ns')) is int
                    and 0 < r['offered_ns'] <= r['terminal_ns'] and previous <= r['offered_ns']
                    and (type(first) is int and r['offered_ns'] <= first <= r['terminal_ns'] if tokens else first is None),
                    'calibration original order/output')
            previous = r['terminal_ns']; c = cells[name]
            valid = r['text'] in ('0', '1', '2') and tokens == [15+int(r['text'])]
            correct = valid and r['text'] == expected
            c['count'] += 1; c['strict_valid'] += int(valid); c['correct'] += int(correct)
            c['strict_first_correct'] += int(bool(tokens and tokens[0] == 15+int(expected)))
            c['per_class'][expected]['count'] += 1; c['per_class'][expected]['correct'] += int(correct)
            if valid: c['confusion'][int(expected)][int(r['text'])] += 1
            else: c['invalid'] += 1
            if name.endswith('free16') and r['finish_reason'] == 'stop' and r['stop_reason'] is None:
                match = re.fullmatch(r'[ \t\r\n]*([012])[ \t\r\n]*', r['text'])
                c['semantic_correct'] += int(bool(match and match[1] == expected))
    c = cells['chat-mask1']
    qualified = c['strict_valid'] == 60 and c['correct'] >= 57 and all(v['correct'] >= 19 for v in c['per_class'].values())
    oracle = row['oracle']
    require(oracle.get('schema') == 'nodus.routing.calibration-oracle/1'
            and oracle.get('candidate') == 'chat-mask1' and oracle.get('qualified') is qualified
            and oracle.get('cells') == cells and oracle.get('performance_gain') is False
            and oracle.get('prompts_sha256') == CAL_PROMPTS and oracle.get('expected_sha256') == CAL_EXPECTED,
            'calibration oracle differs')
    return dict(status=row.get('status'), complete_inventory=True, qualified=qualified, cells=cells,
                selected_cell='chat-mask1', performance_gain=False)


def eager_calibration(row):
    """Recount saved first-forward diagnostics; never substitute the native gate."""
    native_summary = calibration(row)
    eager = row.get('eager_reference')
    if not isinstance(eager, dict) or eager.get('result') is None:
        return dict(complete_inventory=False, label_correct=None, serving_admitted=False,
                    performance_gain=False, status=eager.get('status') if isinstance(eager, dict) else 'not_recorded')
    result = eager['result']; init = result.get('initialized', {})
    require(eager.get('status') == 'complete' and result.get('schema') == 'nodus.routing.eager-reference/1'
            and result.get('tokens_sha256') == CAL_TOKENS
            and result.get('binding') == '8383e7fc29bef2043fb094213b1ce20512af6d0cbc268348746b13ff31bd527d'
            and init.get('binding') == result['binding'] and eager.get('initialized') == init,
            'eager source identity')
    require(init.get('attention') == 'eager' and init.get('cache') is False
            and init.get('dtype') == 'torch.bfloat16' and init.get('logits_to_keep') == 1
            and init.get('cuda_launch_blocking') == '0' and init.get('vocabulary') == 151936
            and init.get('model_revision') == '989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
            and init.get('sources', {}).get('transformers') == '5.17.0', 'eager measured mode')
    rows = result.get('requests')
    require(type(rows) is list and len(rows) == 60 and native_summary['complete_inventory']
            and native_summary['cells']['chat-mask1']['strict_valid'] == 60, 'eager complete inventory')
    native = {r['case_id']: r for r in row['native']['requests'] if r['cell'] == 'chat-mask1'}
    inputs, disagreements = [], []
    correct = global_correct = global_nonlabel = agreement = 0
    confusion = [[0]*3 for _ in range(3)]
    previous = init.get('observed_ns')
    require(type(previous) is int and previous > 0, 'eager initialization clock')
    for i, r in enumerate(rows):
        case = 'cal-'+sha(('routing-calibration-v2-id:'+str(i)).encode())[:16]
        expected = i % 3; logits = r.get('logits', {})
        require(r.get('id') == case and type(r.get('token_count')) is int and r['token_count'] > 0
                and digest(r.get('tokens_sha256')) and r.get('dtype') == 'torch.bfloat16'
                and r.get('shape') == [1, 1, 151936] and type(r.get('started_ns')) is int
                and type(r.get('drained_ns')) is int and previous <= r['started_ns'] <= r['drained_ns'],
                'eager case/input/clock')
        previous = r['drained_ns']; inputs.append([case, r['token_count'], r['tokens_sha256']])
        labels, top = logits.get('label_logits'), logits.get('global_top10')
        require(logits.get('finite') is True and digest(logits.get('logits_f32_le_sha256'))
                and type(labels) is list and len(labels) == 3 and type(top) is list and len(top) == 10,
                'eager logits census')
        require(all(type(v) is list and len(v) == 2 and type(v[0]) is int and 0 <= v[0] < 151936
                    and finite(v[1]) for v in labels+top)
                and [v[0] for v in labels] == [15,16,17] and len({v[0] for v in top}) == 10
                and all(top[j][1] >= top[j+1][1] for j in range(9)), 'eager finite ordered logits')
        chosen = max(labels, key=lambda v:(v[1], -v[0]))[0]
        ordered = sorted((v[1] for v in labels), reverse=True)
        require(all(finite(logits.get(k)) for k in ('label_margin','global_margin','global_over_label_margin'))
                and type(logits.get('label_argmax')) is int and logits['label_argmax'] == chosen
                and logits.get('label_margin') == ordered[0]-ordered[1]
                and logits.get('global_margin') == top[0][1]-top[1][1]
                and logits.get('global_over_label_margin') == top[0][1]-ordered[0]
                and top[0][1] >= ordered[0]
                and all(v[1] == dict(labels)[v[0]] for v in top if v[0] in (15,16,17)),
                'eager argmax/margins')
        predicted = chosen-15; global_id = top[0][0]
        correct += int(predicted == expected); global_correct += int(global_id == 15+expected)
        global_nonlabel += int(global_id not in (15,16,17)); confusion[expected][predicted] += 1
        native_id = native[case]['token_ids'][0]
        agreement += int(native_id == chosen)
        if native_id != chosen:
            disagreements.append(dict(id=case, expected=expected, native=native_id-15, eager=predicted))
    require(sha(json.dumps(inputs, sort_keys=True, separators=(',',':')).encode()) == EAGER_INPUTS_SHA,
            'eager exact input descriptors')
    require(type(result.get('final_drained_ns')) is int and previous <= result['final_drained_ns'], 'eager final drain')
    oracle = eager.get('oracle', {})
    require(oracle.get('schema') == 'nodus.routing.eager-reference-oracle/1'
            and oracle.get('expected_sha256') == CAL_EXPECTED and oracle.get('count') == 60
            and oracle.get('label_correct') == correct and oracle.get('global_correct') == global_correct
            and oracle.get('global_nonlabel') == global_nonlabel and oracle.get('label_confusion') == confusion
            and oracle.get('native_quality_repaired') is False and oracle.get('performance_gain') is False,
            'eager oracle differs')
    return dict(status='complete', complete_inventory=True, count=60, label_correct=correct,
                global_correct=global_correct, global_nonlabel=global_nonlabel, label_confusion=confusion,
                native_agreement=agreement, disagreements=disagreements, serving_admitted=False,
                performance_gain=False, full_logits_recomputed=False,
                scope='Saved first-forward diagnostic; no model execution or serving admission.')


def semantic_calibration(row):
    """Recount the exact paired label experiment, without executing either engine."""
    prompts = '49845b67e641f86366b2824e9eeb50fac2dc43ac5588ccd80ab3d674d4229a21'
    expected_sha = '6be1df6ee77717ae91c682f32f643fe333e1325acf787713afa0171623cef79f'
    names = ('billing', 'technical', 'sales')
    token_sets = ((15, 16, 17), (38637, 72137, 29041))
    native = row.get('native', {})
    require(row.get('schema') == 'nodus.routing.calibration/2'
            and row.get('calibration_tokens_sha256') == SEMANTIC_CAL_TOKENS
            and native.get('schema') == 'nodus.routing.native-calibration/2'
            and native.get('tokens_sha256') == SEMANTIC_CAL_TOKENS
            and native.get('prompts_sha256') == prompts
            and native.get('binding') == '76ea078d1f9a7a5e7b167fe305697181a56dadb8daae65dd6d0bcd4463b068e0',
            'semantic native identity')
    rows = native.get('requests')
    require(type(rows) is list and len(rows) == 120, 'all paired native records')
    cells = {c: dict(count=0, strict_valid=0, strict_first_correct=0, correct=0, invalid=0,
                    per_class={k: dict(count=0, correct=0) for k in names},
                    confusion=[[0]*3 for _ in names]) for c in SEMANTIC_CELLS}
    cases, predictions = [], {}
    previous = 0
    for i in range(60):
        case = rows[2*i].get('case_id'); expected = i % 3
        require(type(case) is str and re.fullmatch('sem-[0-9a-f]{16}', case), 'semantic case identity')
        cases.append([case, expected])
        for j, cell in enumerate(SEMANTIC_CELLS):
            r = rows[2*i+j]; ids = token_sets[j]; tokens = r.get('token_ids')
            require(r.get('case_id') == case and r.get('id') == case+'-'+cell and r.get('cell') == cell
                    and r.get('status') == 'complete' and r.get('finished') is True and r.get('exhausted') is True
                    and r.get('finish_reason') == 'length' and r.get('stop_reason') is None
                    and type(tokens) is list and len(tokens) == 1 and type(tokens[0]) is int and tokens[0] in ids
                    and all(type(r.get(k)) is int for k in ('offered_ns','first_ns','terminal_ns'))
                    and 0 < r['offered_ns'] <= r['first_ns'] <= r['terminal_ns']
                    and previous <= r['offered_ns'], 'semantic native output/order')
            predicted = ids.index(tokens[0]); previous = r['terminal_ns']
            require(r.get('text') == (str(predicted) if j == 0 else names[predicted]), 'semantic token/text')
            c = cells[cell]; correct = predicted == expected
            c['count'] += 1; c['strict_valid'] += 1; c['strict_first_correct'] += int(correct)
            c['correct'] += int(correct); c['per_class'][names[expected]]['count'] += 1
            c['per_class'][names[expected]]['correct'] += int(correct); c['confusion'][expected][predicted] += 1
            predictions[(case, cell)] = predicted
    require(sha(json.dumps(cases, separators=(',',':')).encode()) == SEMANTIC_CASES_SHA,
            'exact semantic cases and expected labels')
    for cell, ids in zip(SEMANTIC_CELLS, token_sets):
        require(native.get('sampling', {}).get(cell) == dict(allowed_token_ids=list(ids), ignore_eos=True,
                max_tokens=1, n=1, seed=0, temperature=0), 'paired native sampling')
    selected_cell = cells['semantic-chat-mask1']
    qualified = selected_cell['correct'] >= 57 and all(v['correct'] >= 19 for v in selected_cell['per_class'].values())
    oracle = row.get('oracle', {})
    require(oracle.get('schema') == 'nodus.routing.calibration-oracle/2'
            and oracle.get('candidate') == 'semantic-chat-mask1' and oracle.get('qualified') is qualified
            and oracle.get('cells') == cells and oracle.get('performance_gain') is False
            and oracle.get('expected_sha256') == expected_sha and oracle.get('prompts_sha256') == prompts,
            'semantic native oracle differs')
    eager = row.get('eager_reference', {}); result = eager.get('result', {}); init = result.get('initialized', {})
    require(eager.get('status') == 'complete' and result.get('schema') == 'nodus.routing.eager-reference/2'
            and result.get('tokens_sha256') == SEMANTIC_CAL_TOKENS
            and result.get('binding') == '305a96f9aa61c16d799212a7717084ce606e895b0a816f6ac185f523e79fb4ab'
            and init.get('binding') == result['binding'] and eager.get('initialized') == init
            and init.get('attention') == 'eager' and init.get('cache') is False
            and init.get('dtype') == 'torch.bfloat16' and init.get('logits_to_keep') == 1
            and init.get('cuda_launch_blocking') == '0' and init.get('vocabulary') == 151936
            and init.get('model_revision') == '989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
            and init.get('sources', {}).get('transformers') == '5.17.0', 'semantic eager identity/mode')
    erows = result.get('requests'); previous = init.get('observed_ns')
    require(type(erows) is list and len(erows) == 120 and type(previous) is int and previous > 0,
            'all paired eager records')
    ecells = {c: dict(count=0, label_correct=0, global_correct=0, global_nonlabel=0,
                     label_confusion=[[0]*3 for _ in names]) for c in SEMANTIC_CELLS}
    inputs, disagreements = [], {c: [] for c in SEMANTIC_CELLS}
    for i, (case, expected) in enumerate(cases):
        for j, cell in enumerate(SEMANTIC_CELLS):
            r = erows[2*i+j]; ids = token_sets[j]; logits = r.get('logits', {})
            require(r.get('case_id') == case and r.get('id') == case+'-'+cell and r.get('cell') == cell
                    and type(r.get('token_count')) is int and r['token_count'] > 0 and digest(r.get('tokens_sha256'))
                    and r.get('dtype') == 'torch.bfloat16' and r.get('shape') == [1,1,151936]
                    and type(r.get('started_ns')) is int and type(r.get('drained_ns')) is int
                    and previous <= r['started_ns'] <= r['drained_ns'], 'semantic eager input/order')
            previous = r['drained_ns']; inputs.append([case, cell, r['token_count'], r['tokens_sha256']])
            labels, top = logits.get('label_logits'), logits.get('global_top10')
            require(logits.get('finite') is True and digest(logits.get('logits_f32_le_sha256'))
                    and type(labels) is list and len(labels) == 3 and type(top) is list and len(top) == 10
                    and all(type(v) is list and len(v) == 2 and type(v[0]) is int and 0 <= v[0] < 151936
                            and finite(v[1]) for v in labels+top)
                    and [v[0] for v in labels] == list(ids) and len({v[0] for v in top}) == 10
                    and all(top[k][1] >= top[k+1][1] for k in range(9)), 'semantic eager finite logits')
            chosen = max(labels, key=lambda v:(v[1], -v[0]))[0]
            ordered = sorted((v[1] for v in labels), reverse=True)
            require(all(finite(logits.get(k)) for k in ('label_margin','global_margin','global_over_label_margin'))
                    and type(logits.get('label_argmax')) is int and logits['label_argmax'] == chosen
                    and logits['label_margin'] == ordered[0]-ordered[1]
                    and logits['global_margin'] == top[0][1]-top[1][1]
                    and logits['global_over_label_margin'] == top[0][1]-ordered[0] and top[0][1] >= ordered[0]
                    and all(v[1] == dict(labels)[v[0]] for v in top if v[0] in ids), 'semantic eager argmax/margins')
            predicted = ids.index(chosen); c = ecells[cell]
            c['count'] += 1; c['label_correct'] += int(predicted == expected)
            c['global_correct'] += int(top[0][0] == ids[expected]); c['global_nonlabel'] += int(top[0][0] not in ids)
            c['label_confusion'][expected][predicted] += 1
            if predictions[(case, cell)] != predicted:
                disagreements[cell].append(dict(id=case, expected=names[expected],
                    native=names[predictions[(case,cell)]], eager=names[predicted]))
    require(sha(json.dumps(inputs, separators=(',',':')).encode()) == SEMANTIC_INPUTS_SHA
            and type(result.get('final_drained_ns')) is int and previous <= result['final_drained_ns'],
            'semantic exact input descriptors/final drain')
    eo = eager.get('oracle', {})
    require(eo.get('schema') == 'nodus.routing.eager-reference-oracle/2' and eo.get('count') == 120
            and eo.get('expected_sha256') == expected_sha and eo.get('cells') == ecells
            and eo.get('native_quality_repaired') is False and eo.get('performance_gain') is False,
            'semantic eager oracle differs')
    paired = dict(newly_correct=0, newly_wrong=0, both_correct=0, both_wrong=0)
    for case, expected in cases:
        numeric = predictions[(case, SEMANTIC_CELLS[0])] == expected
        semantic = predictions[(case, SEMANTIC_CELLS[1])] == expected
        paired['both_correct' if numeric and semantic else 'newly_correct' if semantic else 'newly_wrong' if numeric else 'both_wrong'] += 1
    for cell, c in ecells.items():
        c.update(native_agreement=60-len(disagreements[cell]), disagreements=disagreements[cell])
    return dict(status=row.get('status'), complete_inventory=True, qualified=qualified, cells=cells,
                selected_cell='semantic-chat-mask1', paired_native=paired, performance_gain=False,
                eager_reference=dict(status='complete', complete_inventory=True, cells=ecells,
                    serving_admitted=False, performance_gain=False, full_logits_recomputed=False))


def request_rows(value):
    require(value.get('trace_sha256') == TRACE and type(value.get('start_ns')) is int and value['start_ns'] > 0
            and type(value.get('end_ns')) is int and value['end_ns'] == value['start_ns']+EXPOSURE, 'fixed request window')
    if value.get('schema') == 'nodus.routing.requests/2':
        keys = ('offered_ns', 'first_ns', 'terminal_ns', 'exhausted', 'status', 'text', 'token_id')
        require(set(value) == {'schema','trace_sha256','start_ns','end_ns','columns'}
                and set(value['columns']) == set(keys)
                and all(type(v) is list and len(v) == COUNT for v in value['columns'].values()), 'compact inventory')
        rows = []
        for i in range(COUNT):
            r = {key: value['columns'][key][i] for key in keys}
            for key in keys[:3]:
                require(r[key] is None and key == 'first_ns' or type(r[key]) is int, 'compact clock')
                if r[key] is not None: r[key] += value['start_ns']
            token = r.pop('token_id'); r['token_ids'] = [] if token is None else [token]
            r.update(id=f'route-{i:06d}', planned_ns=value['start_ns']+i*PERIOD); rows.append(r)
    else:
        require(value.get('schema') == 'nodus.routing.requests/1'
                and set(value) == {'schema','trace_sha256','start_ns','end_ns','requests'}, 'request schema')
        rows = value['requests']
    require(type(rows) is list and len(rows) == COUNT, 'all original offers')
    fields = {'id','planned_ns','offered_ns','first_ns','terminal_ns','exhausted','status','text','token_ids'}
    for i, r in enumerate(rows):
        require(type(r) is dict and set(r) == fields and r['id'] == f'route-{i:06d}'
                and type(r['planned_ns']) is int and r['planned_ns'] == value['start_ns']+i*PERIOD
                and type(r['offered_ns']) is int and type(r['terminal_ns']) is int
                and r['planned_ns'] <= r['offered_ns'] <= r['terminal_ns']
                and (r['first_ns'] is None or type(r['first_ns']) is int and r['offered_ns'] <= r['first_ns'] <= r['terminal_ns'])
                and type(r['exhausted']) is bool and r['status'] in ('complete','failed')
                and type(r['text']) is str and len(r['text'].encode()) <= 64
                and type(r['token_ids']) is list and len(r['token_ids']) <= 1
                and all(type(t) is int and 0 <= t < 1_000_000 for t in r['token_ids']), 'request identity/clock/output')
    return rows


def distribution(values):
    values = sorted(values); n = len(values)
    return dict(n=n, median_ns=(values[(n-1)//2]+values[n//2])/2 if n else None,
                p95_ns=values[math.ceil(n*.95)-1] if n else None, max_ns=values[-1] if n else None)


def foreground(value, stock=None):
    rows = request_rows(value); baseline = request_rows(stock) if stock is not None else None
    result = dict(request_count=COUNT, complete=0, label_correct=0, deadline_breaches=0,
                  paired_first_breaches=0, paired_terminal_breaches=0, output_mismatches=0,
                  class_correct={k: 0 for k in '012'})
    first, terminal = [], []
    for i, r in enumerate(rows):
        done = r['status'] == 'complete' and r['exhausted'] and r['first_ns'] is not None \
            and r['text'] in ('0','1','2') and r['token_ids'] == [15+int(r['text'])]
        correct = done and r['text'] == str(i % 3)
        result['complete'] += int(done); result['label_correct'] += int(correct)
        result['class_correct'][str(i % 3)] += int(correct)
        result['deadline_breaches'] += int(not done or r['terminal_ns'] > min(r['planned_ns']+DEADLINE, value['end_ns']))
        if r['first_ns'] is not None: first.append(r['first_ns']-r['planned_ns'])
        terminal.append(r['terminal_ns']-r['planned_ns'])
        if baseline is not None:
            b = baseline[i]
            result['output_mismatches'] += int(not done or r['text'] != b['text'] or r['token_ids'] != b['token_ids'])
            result['paired_first_breaches'] += int(not done or b['first_ns'] is None
                or 100*(r['first_ns']-r['planned_ns']) > 105*(b['first_ns']-b['planned_ns']))
            result['paired_terminal_breaches'] += int(not done
                or 100*(r['terminal_ns']-r['planned_ns']) > 105*(b['terminal_ns']-b['planned_ns']))
    quality = result['label_correct'] >= 11400 and all(n >= 3800 for n in result['class_correct'].values())
    result.update(quality_passed=quality, first=distribution(first), terminal=distribution(terminal),
                  qualified=bool(quality and result['complete'] == COUNT and result['deadline_breaches'] == 0
                    and (stock is None or foreground(stock)['qualified'] and result['paired_first_breaches'] == 0
                         and result['paired_terminal_breaches'] == 0 and result['output_mismatches'] == 0)))
    return result


def background(row, reference):
    train, base = row.get('training', {}), reference.get('training', {})
    n = train.get('step'); replay = base.get('routing_reference', {}); targets = replay.get('targets')
    require(type(n) is int and 0 <= n <= 1536 and row.get('profile') in TRAINING
            and row.get('status') == reference.get('status') == 'complete'
            and train.get('routing_window') is True
            and row.get('cleanup', {}).get('cleanup_confirmed') is True
            and reference.get('cleanup', {}).get('cleanup_confirmed') is True
            and bool(row.get('log_evidence')) and all(v.get('complete') is True for v in row['log_evidence']),
            'complete exact-N participants')
    require(type(targets) is list and 1 <= len(targets) <= 3
            and all(type(t) is int and 0 <= t <= 1536 for t in targets)
            and targets == sorted(set(targets)) and n in targets and replay.get('scored_work') is False
            and base.get('step') == max(targets)
            and set(replay.get('snapshots', {})) == {str(t) for t in targets}, 'exact-N inventory')
    expected = replay['snapshots'][str(n)].get('canonical_state_sha256')
    initial = train.get('initial_checkpoint', {}).get('canonical_state_sha256')
    require(digest(expected) and digest(initial)
            and initial == base.get('initial_checkpoint', {}).get('canonical_state_sha256')
            and train.get('initial_hashes') == base.get('initial_hashes')
            and type(train.get('initial_hashes')) is list and len(train['initial_hashes']) == 3
            and all(map(digest, train['initial_hashes']))
            and train.get('final_checkpoint', {}).get('canonical_state_sha256') == expected, 'exact-N state hashes')
    losses, original, window = row.get('losses'), reference.get('losses'), row.get('window')
    require(type(losses) is list and len(losses) == n and type(original) is list and len(original) == max(targets)
            and type(window) is dict and set(window) == {'start','end'}
            and all(map(finite, window.values())) and window['end'] == window['start']+300
            and train.get('window') == window, 'exact-N loss/window census')
    previous = window['start']
    for i, loss in enumerate(losses):
        require(loss.get('step') == original[i].get('step') == i+1
                and type(loss.get('loss_hex')) is str and loss['loss_hex'] == original[i].get('loss_hex')
                and math.isfinite(float.fromhex(loss['loss_hex'])) and finite(loss.get('completed'))
                and loss['completed'] >= previous, 'exact-N loss/clock')
        previous = loss['completed']
    inside = sum(window['start'] <= r['completed'] <= window['end'] for r in losses)
    require(train.get('in_window_steps') == inside and train.get('drain_steps') == n-inside and n-inside <= 1,
            'late/drain work accounting')
    if n == 0:
        require(train.get('last_completion') is None and train.get('final_hashes') == train['initial_hashes']
                and expected == initial, 'zero work state')
    grants = row.get('trainer_grants', []); commits = [r for r in grants if r.get('phase') == 'update']
    if row['profile'] == 'ordinary-async':
        require(not commits and row.get('acknowledged_updates') == 0 and len(grants) == 4
                and [r.get('kind') for r in grants] == ['issued','acknowledged']*2
                and [r.get('phase') for r in grants] == ['initialize']*2+['finalize']*2, 'async lifecycle only')
    else:
        require(row.get('acknowledged_updates') == n and len(commits) == n, 'physical commit census')
        for i, (ack, loss) in enumerate(zip(commits, losses), 1):
            require(ack.get('kind') == 'acknowledged' and ack.get('committed') is True and ack.get('completed') == i
                    and finite(ack.get('drained_at')) and finite(ack.get('observed'))
                    and window['start'] <= ack['drained_at'] <= ack['observed']
                    and loss['completed'] == float(f"{ack['drained_at']:.9f}"), 'physical commit clock')
        require(inside == sum(window['start'] <= r['drained_at'] <= window['end'] for r in commits), 'physical in-window count')
    return dict(exact_n=n, exact_state_and_losses=True, committed_in_window=inside,
                committed_after_window=n-inside, partial_updates_credited=0, updates_per_scored_second=inside/300)


def exact_selected(originals, screen):
    """Hash/loss equality is recomputed; the full raw site screen is only reported."""
    left, right = (originals[a+'/result.json'] for a in ARMS[:2])
    require(screen.get('schema') == 'nodus.routing.exact128/1' and screen.get('gain_established') is False,
            '128 prerequisite schema')
    identity = screen.get('common_identity', {})
    require(set(identity) == set(IDENTITY) and all(identity.values()), 'complete common identity')
    require(identity['research_source_sha'] == STUDY
            and identity['runtime'].get('image') == IMAGE
            and identity['runtime'].get('packages', {}).get('vllm') == '0.30.0'
            and identity['runtime']['packages'].get('torch') == '2.13.0+cu130', 'frozen measured runtime')
    for row in (left, right):
        require(all(row.get(k) == v for k, v in identity.items()) and row.get('status') == 'complete'
                and row.get('requests') in (None, []) and row['training'].get('step') == 128
                and len(row.get('losses', [])) == 128, 'full128 selected census')
    for key in ('initial_hashes','final_hashes'):
        require(type(left['training'].get(key)) is list and len(left['training'][key]) == 3
                and all(map(digest, left['training'][key]))
                and left['training'][key] == right['training'].get(key), '128 state hash equality')
    for key in ('initial_checkpoint','final_checkpoint'):
        state = left['training'][key].get('canonical_state_sha256')
        require(digest(state) and state == right['training'][key].get('canonical_state_sha256'), '128 canonical state')
    for i, (a, b) in enumerate(zip(left['losses'], right['losses']), 1):
        require(a.get('step') == b.get('step') == i and type(a.get('loss_hex')) is str
                and a['loss_hex'] == b.get('loss_hex') and math.isfinite(float.fromhex(a['loss_hex'])), '128 loss equality')
    require(screen.get('initial_canonical_state_sha256') == left['training']['initial_checkpoint']['canonical_state_sha256']
            and screen.get('exact128_state_loss_rng_equal') is True
            and type(screen.get('whole_step_steady_passed')) is bool
            and screen.get('qualified') is screen['whole_step_steady_passed'], '128 reported gate consistency')
    return dict(selected_state_and_loss_equal=True, producer_raw_screen_passed=screen['whole_step_steady_passed'],
                raw_site_screen_recomputed=False, tensor_state_loaded=False)


def lifecycle(row):
    start, end = row.get('started_monotonic'), row.get('closed_monotonic')
    if start is None or end is None:
        return None
    require(finite(start) and finite(end) and end >= start, 'lifecycle clock')
    return end-start


def complete_comparison(originals, descriptors):
    comparison = originals['comparison.json']; screen = originals['routing-exact-screen.json']
    require(comparison.get('schema') == 'nodus.routing.comparison/1', 'comparison schema')
    prerequisite = exact_selected(originals, screen)
    identity = screen['common_identity']; reference = originals['routing-reference/result.json']
    controls = originals['boundary-controls.json']; replay_control = originals['routing-replay-control.json']
    require(controls.get('task_sha256') == identity['research_task_sha256']
            and controls.get('full_model_shapes') is False and controls.get('controller_yield_or_serving_gain') is False
            and controls.get('proof', {}).get('actual_cuda') is True
            and controls['proof'].get('exact_model_optimizer_loss_rng') is True
            and replay_control.get('full_model') is False and replay_control.get('proof', {}).get('device') == 'cuda'
            and all(replay_control['proof'].get(k) is True for k in ('exact_zero','immutable_capture','all_rng_bound')),
            'small controls remain separate from full-model proof')
    for control in (controls, replay_control):
        life = control.get('lifecycle', {})
        require(life.get('command_error_type') is None
                and life.get('owned_process', {}).get('local_cleanup_complete') is True
                and life.get('device', {}).get('empty') is True
                and life['device'].get('gpu_uuid') == identity['expected_gpu_uuid'], 'control lifecycle closure')
    require(all(reference.get(k) == v for k, v in identity.items())
            and reference['training']['initial_checkpoint']['canonical_state_sha256'] == screen['initial_canonical_state_sha256'],
            'reference common identity')
    targets = originals['configs/routing-reference-targets.json']
    source_rows = [originals['routing-'+n+'/result.json'] for n in TRAINING]
    expected_targets = sorted({r['training']['step'] for r in source_rows})
    sources = [dict(arm='routing-'+n, size=descriptors['routing-'+n+'/result.json']['bytes'],
                    sha256=descriptors['routing-'+n+'/result.json']['sha256']) for n in TRAINING]
    require(targets == dict(schema='nodus.routing.reference-targets/1', task_sha256=identity['research_task_sha256'],
                            targets=expected_targets, sources=sources)
            and reference['training']['routing_reference']['targets'] == expected_targets, 'three exact-N original sources')
    stock = originals['routing-stock-full/requests.json']; gates, work, durations = {}, {}, {}
    for name in NAMES:
        row = originals['routing-'+name+'/result.json']; requests = originals['routing-'+name+'/requests.json']
        require(all(row.get(k) == v for k, v in identity.items())
                and row.get('routing_trace_sha256') == TRACE and row.get('token_manifest_sha256') == TOKENS,
                'condition common workload identity')
        descriptor = descriptors['routing-'+name+'/requests.json']
        require(row['native_files']['requests'] == dict(name='requests.json', size=descriptor['bytes'], sha256=descriptor['sha256'])
                and row['window'] == dict(start=requests['start_ns']/1e9, end=requests['start_ns']/1e9+300),
                'condition request byte/window join')
        fg = foreground(requests, None if name == 'stock-full' else stock)
        closed = row.get('profile') == name and row.get('status') == 'complete' \
            and row.get('cleanup', {}).get('cleanup_confirmed') is True
        gate = dict(foreground=fg, qualified=bool(closed and fg['qualified']))
        require(comparison['gates'].get(name) == gate, 'producer foreground gate differs')
        gates[name] = gate; durations[name] = lifecycle(row)
        if name in TRAINING:
            summary = background(row, reference)
            require({k: comparison['background'][name].get(k) for k in summary} == summary, 'producer background differs')
            work[name] = summary
    require(set(comparison['gates']) == set(NAMES) and set(comparison['background']) == set(TRAINING), 'six-condition census')
    full = prerequisite['producer_raw_screen_passed']
    candidate = full and gates['sqrt-permit']['qualified']
    controls = [n for n in ('ordinary-async','whole-busy') if gates[n]['qualified']]
    strongest = max((work[n]['committed_in_window'] for n in controls), default=None)
    recovered = work['sqrt-permit']['committed_in_window'] if candidate else 0
    ratio = recovered/strongest if candidate and strongest is not None and strongest > 0 else None
    expected = dict(full128_prerequisite=full, candidate_qualified=candidate,
                    absolute_qualified_training_updates=recovered, strongest_qualified_control_updates=strongest,
                    qualified_control_ratio=ratio, allocation_seconds=None, full_allocation_cost_joined=False,
                    candidate_updates_per_actual_experiment_allocation_second=None)
    require(all(comparison.get(k) == v for k, v in expected.items()), 'comparison denominator/verdict differs')
    return dict(prerequisite=prerequisite, foreground_gates=gates, background=work, lifecycle_seconds=durations,
                qualified_control_names=controls, strongest_control_updates=strongest,
                producer_reported_candidate_qualified=candidate, selected_consistent_ratio=ratio,
                raw_ownership_semantics_recomputed=False, public_gain_eligible=False,
                allocation_seconds=None, allocation_normalized_rate=None, cost_per_useful_update=None)


def summarize(originals, states, descriptors, owner):
    require(set(states) == set(LEAVES) and set(originals) == {k for k,v in states.items() if v == 'selected'}, 'closed selected inventory')
    study, supplier = owner.get('study_commit'), owner.get('controller_commit')
    require((study, supplier) in ((STUDY, SUPPLIER),
            (EAGER_BINDING['study_commit'], EAGER_BINDING['controller_commit']),
            (SEMANTIC_BINDING['study_commit'], SEMANTIC_BINDING['controller_commit'])), 'summary source identity')
    semantic = study == SEMANTIC_BINDING['study_commit']
    summary = dict(schema='nodus.routing.calibrated-selected-summary/1', producer_run_id=owner['producer_run_id'],
                   study_commit=study, controller_commit=supplier, source_version='vLLM 0.30.0 / canonical-chat-v1',
                   selection_states=states, classification='terminal_evidence_incomplete',
                   calibration=None, recorded_arms={}, comparison=None, public_gain_eligible=False,
                   full_original_authenticated_by_this_decoder=False, private_retention_status='not_evaluated',
                   raw_ownership_semantics_recomputed=False, allocation_seconds=None, cost_per_useful_update=None)
    start, end = originals.get('suite-start.json'), originals.get('suite-terminal.json')
    if start is not None:
        require(start.get('arms') == list(ARMS) and start.get('task_sha256') == owner['task_sha256']
                and start.get('allocation_id') == owner['allocation_id'] and start.get('routing_trace_sha256') == ('3ba7c89db478301d152c738232b3e0fac2545177b9177de169ca8aa0b296f692' if semantic else TRACE)
                and start.get('routing_tokens_sha256') == ('a9e37d9807f21c445d19d1b54b7a365544ff28473f33e137ddff7148c0b41743' if semantic else TOKENS)
                and start.get('routing_calibration_tokens_sha256') == (SEMANTIC_CAL_TOKENS if semantic else CAL_TOKENS), 'suite identity')
    if end is not None:
        require(end.get('task_sha256') == owner['task_sha256'] and type(end.get('records')) is list
                and [r.get('arm') for r in end['records']] == list(ARMS[:len(end['records'])])
                and len(end['records']) <= 9 and end.get('routing_all9_joined') is (len(end['records']) == 9), 'terminal owner sequence')
        for record in end['records']:
            path = record['arm']+'/result.json'
            require(path in descriptors and record.get('result_sha256') == descriptors[path]['sha256'], 'terminal result hash')
        summary['terminal_failure_type'] = end.get('failure_type')
        summary['joined_arms'] = [r['arm'] for r in end['records']]
    for arm in ARMS:
        row = originals.get(arm+'/result.json')
        if row is None: continue
        require(row.get('research_task_sha256') == owner['task_sha256']
                and row.get('research_allocation_id') == owner['allocation_id'] and row.get('research_source_sha') == study,
                'arm source/task/allocation')
        entry = dict(status=row.get('status'), failure_type=row.get('failure_type'),
                     inner_cleanup_confirmed=row.get('cleanup', {}).get('cleanup_confirmed'),
                     lifecycle_seconds=lifecycle(row), scored_request_rows=None,
                     recorded_training_updates=row.get('training', {}).get('step'))
        requests = originals.get(arm+'/requests.json')
        if requests is not None:
            entry['scored_request_rows'] = len(request_rows(requests))
            entry['foreground'] = foreground(requests)
        summary['recorded_arms'][arm] = entry
    cal = originals.get('routing-calibration/result.json')
    if cal is not None:
        require(cal.get('research_task_sha256') == owner['task_sha256']
                and cal.get('research_allocation_id') == owner['allocation_id'] and cal.get('research_source_sha') == study,
                'calibration source/task/allocation')
        summary['calibration'] = semantic_calibration(cal) if semantic else calibration(cal)
        if semantic:
            summary['source_version'] = 'vLLM 0.30.0 / semantic-label-v1'
            summary['eager_reference'] = summary['calibration']['eager_reference']
        if study == EAGER_BINDING['study_commit']:
            summary['eager_reference'] = eager_calibration(cal)
    if 'comparison.json' in originals:
        require(not semantic, 'semantic producer has no recorded timing comparison')
        require(all(state == 'selected' for state in states.values()) and start is not None and end is not None
                and end.get('failure_type') is None and end.get('routing_all9_joined') is True
                and summary['calibration'] is not None and summary['calibration']['qualified'] is True,
                'complete calibrated comparison prerequisite')
        summary['comparison'] = complete_comparison(originals, descriptors)
        summary['classification'] = 'complete_selected_comparison_pending_raw_review'
    elif end is not None:
        # Missing requests are not zero requests and absent arms are not failed arms.
        summary['classification'] = 'incomplete_before_comparison'
        if states['comparison.json'] == 'oversized':
            summary['classification'] = 'comparison_not_selected'
        if summary['calibration'] is not None and summary['calibration']['qualified'] is False:
            require(not end['records'] and not summary['recorded_arms'], 'failed calibration cannot admit later owners')
            summary['classification'] = 'calibration_quality_failed'
        summary['not_selected_arms'] = [a for a in ARMS if a not in summary['recorded_arms']]
    if 'routing-exact-screen.json' in originals:
        screen = originals['routing-exact-screen.json']
        summary['producer_reported_exact128'] = {k: screen.get(k) for k in (
            'exact128_state_loss_rng_equal', 'whole_step_steady_passed', 'qualified', 'gain_established')}
    return summary


def public_bundle(raw):
    """Existing gzip companion format, retaining the exact original ZIP bytes."""
    require(len(raw) <= CAP, 'public gzip cap')
    with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream:
        decoded = stream.read(48*1024**2+1)
    require(len(decoded) <= 48*1024**2, 'public decoded cap')
    bundle = decode(decoded)
    require(set(bundle) == {'schema','binding','scientific_zip_base64','scientific_execution',
                           'derived_selection','new_qualified_gain','selection_time_full_original_authenticated'}
            and bundle['schema'] == 'nodus.routing.calibrated-original-zip/1'
            and bundle['binding'] in (PUBLIC_BINDING, EAGER_BINDING, SEMANTIC_BINDING)
            and bundle['scientific_execution'] is True and bundle['derived_selection'] is True
            and bundle['new_qualified_gain'] is False
            and bundle['selection_time_full_original_authenticated'] is False, 'fixed public selection scope')
    archive = base64.b64decode(bundle['scientific_zip_base64'], validate=True)
    result = summarize(*selected(archive, bundle['binding']))
    require(result['classification'] == 'calibration_quality_failed' and not result['recorded_arms']
            and result['calibration']['cells']['semantic-chat-mask1' if bundle['binding'] == SEMANTIC_BINDING else 'chat-mask1']['correct']
                == (41 if bundle['binding'] == SEMANTIC_BINDING else 21), 'actual calibration disposition')
    if bundle['binding'] == EAGER_BINDING:
        eager = result['eager_reference']
        require(eager['complete_inventory'] and eager['label_correct'] == eager['global_correct'] == 25
                and eager['native_agreement'] == 52 and len(eager['disagreements']) == 8,
                'actual independent eager disposition')
    result['scientific_zip_authenticated_by_this_decoder'] = True
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument('--scientific-zip', type=Path)
    source.add_argument('--public-gzip', type=Path)
    parser.add_argument('--binding', type=Path)
    args = parser.parse_args()
    if args.public_gzip:
        require(args.binding is None, 'public input uses its fixed actual binding')
        print(json.dumps(public_bundle(read(args.public_gzip, CAP)), sort_keys=True, indent=2, allow_nan=False))
        return
    require(args.binding is not None, 'actual reviewed binding required')
    binding = decode(read(args.binding, 65536))
    # Refuse before reading any artifact when no actual reviewed binding exists.
    require(binding.get('enabled') is True, 'actual reviewed binding required')
    values = selected(read(args.scientific_zip, CAP), binding)
    print(json.dumps(summarize(*values), sort_keys=True, indent=2, allow_nan=False))


if __name__ == '__main__':
    main()
