#!/usr/bin/env python3
"""Recompute selected JSON scalars only. No model, tensor or original-code execution."""
import argparse
import copy
import gzip
import hashlib
import json
import math
from pathlib import Path

ARMS = ('stock', 'exact-continuous', 'exact-governed', 'window-continuous', 'window-governed')


def require(value, message):
    if not value:
        raise ValueError(message)


def near(a, b):
    require(type(a) in (int, float) and type(b) in (int, float)
            and math.isfinite(a) and math.isfinite(b) and abs(a-b) <= 1e-9, 'Scalar mismatch')


def recompute(bundle):
    require(bundle['schema'] == 'nodus.full-model-selected-results/1', 'Wrong selection schema')
    require(bundle['scientific_runs'] == [44042458319, 44053640655]
            and bundle['derived_selection'] is True and bundle['scientific_execution'] is False
            and bundle['raw_checkpoints_included'] is False and bundle['new_qualified_gain'] is False,
            'Wrong scientific scope')
    expected = {'44042458319/'+p for p in ('comparison.json', 'exact-state-screen.json', 'suite-terminal.json')}
    expected |= {'44042458319/'+arm+'/'+name for arm in ARMS for name in ('result.json', 'planned-outcomes.json')}
    expected |= {'44053640655/result.json', '44053640655/qual-feature-cache/worker-terminal.json'}
    original = {}
    for leaf in bundle['originals']:
        raw = leaf['utf8'].encode('utf-8')
        require(leaf['path'] not in original and leaf['path'] in expected, 'Duplicate or unknown leaf')
        require(len(raw) == leaf['bytes'] and hashlib.sha256(raw).hexdigest() == leaf['sha256'], 'Leaf bytes differ')
        original[leaf['path']] = json.loads(raw)
    require(set(original) == expected, 'Missing original leaf')
    comparison = original['44042458319/comparison.json']
    require(comparison['gain_established'] is False, 'No qualified gain')
    screen = original['44042458319/exact-state-screen.json']
    require(screen == comparison['exact_state'] and screen['classification'] == 'exact_n_equal'
            and screen['completed_updates'] == 128, 'Producer exact-state verdict differs')
    require(comparison['common_correctness_qualified'] is True and comparison['exact_state_qualified'] is True,
            'Producer correctness verdict differs')
    baseline = original['44042458319/stock/result.json']['requests']
    summaries = {}
    for arm in ARMS:
        row = original['44042458319/'+arm+'/result.json']
        planned = original['44042458319/'+arm+'/planned-outcomes.json']
        require(row['status'] == 'complete' and len(row['requests']) == 19
                and planned['original_offers'] == 19 and len(planned['requests']) == 19, 'Keep every original offer')
        near(row['window']['end'], row['window']['start']+300)
        first, terminal = [], []
        for i, (request, stock, observation) in enumerate(zip(row['requests'], baseline, planned['requests'])):
            require(request['id'] == stock['id'] == observation['id'] == 'warm-'+str(i+1).zfill(2), 'Offer identity differs')
            near(request['planned_offer'], row['window']['start']+15*i)
            near(request['original_deadline'], request['planned_offer']+30)
            require(request['status'] == observation['status'] == 'complete'
                    and request['completed_tokens'] == 64 and request['text'] == stock['text']
                    and hashlib.sha256(request['text'].encode()).hexdigest() == request['text_sha256'] == stock['text_sha256'],
                    'Reported token count or exact text differs')
            require(request['planned_offer'] <= request['first_output'] <= request['terminal_observed'] <= request['original_deadline'],
                    'Original-offer timing or deadline failed')
            f = request['first_output']-request['planned_offer']
            t = request['terminal_observed']-request['planned_offer']
            near(observation['ttft_seconds'], f); near(observation['terminal_seconds'], t)
            require(observation['qualified'] is True, 'Original deadline receipt differs')
            first.append(f); terminal.append(t)
        # Nearest-rank p95 of 19 is the maximum; no population-tail inference.
        summary = {'completed_requests': 19, 'original_deadline_hits': 19,
                   'p95_planned_to_first_seconds': sorted(first)[math.ceil(.95*19)-1],
                   'p95_planned_to_completion_seconds': sorted(terminal)[math.ceil(.95*19)-1]}
        if arm.startswith('window-'):
            updates = [x for x in row['trainer_grants'] if x['kind'] == 'acknowledged' and x['phase'] == 'update']
            productive = sum(row['window']['start'] <= x['observed'] <= row['window']['end'] for x in updates)
            require(len(updates) == row['acknowledged_updates'] == row['training']['step'], 'Acknowledgment denominator differs')
            require(productive == row['productive_grant_updates'], 'Late/drain update cannot count as productive')
            require(len(updates)-productive == row['drain_or_late_ack_updates'] == 1, 'Late/drain count differs')
            summary.update(productive_updates=productive, acknowledged_updates=len(updates), excluded_late_updates=1, window_seconds=300)
        summaries[arm] = summary
    for arm, updates in [('window-continuous', 1045), ('window-governed', 1040)]:
        summary = summaries[arm]; stock = summaries['stock']
        first_pass = summary['p95_planned_to_first_seconds'] <= 1.05*stock['p95_planned_to_first_seconds']
        terminal_pass = summary['p95_planned_to_completion_seconds'] <= 1.05*stock['p95_planned_to_completion_seconds']
        gate = comparison['window_gates'][arm]
        require(summary['productive_updates'] == gate['observed_productive_updates'] == updates, 'Update scalar differs')
        require(first_pass == gate['p95_first_preserved'] and terminal_pass == gate['p95_terminal_preserved']
                and gate['all19_deadlines_met'] is True and gate['qualified'] is False
                and not (first_pass and terminal_pass), 'Original +5% qualification changed')
        summary.update(first_gate_pass=first_pass, completion_gate_pass=terminal_pass, qualified_gain=False)
    failed = original['44053640655/result.json']
    require(len(failed['records']) == 1 and failed['performance_claim_eligible'] is False, 'Missing-arm comparison is unavailable')
    record = failed['records'][0]
    require(record['name'] == 'qual-stock-bi' and record['complete_requests'] == record['offered_requests'] == 16
            and record['complete_bundles'] == record['offered_bundles'] == 2
            and record['qualified_bundles'] == 1 and record['quality_pass'] is True
            and record['latency_pass'] is False and len(record['scores']) == 16, 'Stock qualifier verdict differs')
    require(all(x['finished'] for x in record['scores'].values()), 'Stock output missing')
    near(record['full_job_seconds'], (record['full_job_finished_ns']-record['full_job_started_ns'])/1e9)
    terminal = original['44053640655/qual-feature-cache/worker-terminal.json']
    require(terminal['status'] == 'incomplete' and terminal['error_type'] == 'ValueError'
            and terminal['error'] == 'unrecognized loaded arithmetic source: tracing/otel.py', 'Initialization failure differs')
    return {'selected_originals': 15, 'selected_original_bytes': sum(x['bytes'] for x in bundle['originals']),
            'a10': summaries, 'a100': {'stock_outputs': 16, 'stock_complete_bundles': 2,
                'producer_slo_qualified_bundles': 1, 'producer_quality_pass': True, 'producer_latency_pass': False,
                'full_stock_job_seconds': record['full_job_seconds'], 'custom_outputs': 0, 'comparison_available': False},
            'producer_exact_state_updates': 128, 'independent_tensor_or_rouge_reproduction': False,
            'qualified_gain': False, 'scientific_execution': False}


NATIVE_LEAVES = {'native-exact-screen.json': (1656, '0a121871a97f1d6c27c8df7bf8817d3068f2d5da770d3f12885c907ef0f5aa4d'), 'native-window-segments/cohort/engine.log': (23966, '609304a93ca0821c12d86efa413ee95ca8beca64f01757adab0c718f263af6d6'), 'native-window-segments/cohort/trainer.log': (7953, '0fab1f0fc2e20cc4a467bb032fd2c3bf5f1c639ff72643be195d3d72b745a546'), 'native-window-segments/result.json': (377766, '59e8e385580299da928303f952a8adbd16e612cedf7d774e0d47a59f239c977e'), 'native-window-segments-entry.json': (705, '7a3e2b2b33aa4f1084b7bdf9ff6667ca413e15775b4de53a5c49aaf75ff240fc'), 'native-window-segments.cleanup.json': (1153, 'e5d51d35e63cdccb46b359eb685c963eef7bfe503d0a2a17d45cf47e86cf99f1'), 'native-window-segments.lifecycle.json': (1344, 'c8395ae3a8a3d110d6df3e5c4c60078161cba1ebee3f164053cd0345fb5a27b7'), 'native-window-segments.log': (1641, 'c560a7b50caf29bd28df3579efd60be9da1f7034d4c1c5873ad8457293338b68'), 'suite-terminal.json': (9377, '0a6e34565443d0ffca89ed4b1d21927d7897536b94aa7e26e05a0ce03c150771')}


def require_native_updates(row):
    updates = row['native_updates']
    require(updates['admitted'] == 80 and updates['committed_in_window'] == row['acknowledged_updates'] == 79
            and updates['partial_update_at_closure'] is True and updates['committed_after_window'] == 0,
            'Partial update must not count as committed')


def recompute_native(bundle):
    """Recompute the bounded native component observation, never a serving win."""
    require(bundle['schema'] == 'nodus.full-model-native-selected/1'
            and bundle['run_id'] == 44114594497 and bundle['qualified_gain'] is False
            and bundle['raw_checkpoints_included'] is False
            and bundle['scientific_execution'] is False, 'Native scope differs')
    auth = bundle['authentication']
    require(auth['manifest_sha256'] == '1e6e135d1876f03cd064d6af14d2f10ef2af37be94067234c3974cbc5703924e'
            and auth['whole_original_verified'] is False, 'Selected-leaf custody is not whole-original custody')
    original = {}
    for leaf in bundle['originals']:
        raw = leaf['utf8'].encode()
        require(leaf['path'] not in original and leaf['path'] in NATIVE_LEAVES, 'Unknown or duplicate native leaf')
        require((len(raw), hashlib.sha256(raw).hexdigest()) == NATIVE_LEAVES[leaf['path']]
                and len(raw) == leaf['bytes'] and hashlib.sha256(raw).hexdigest() == leaf['sha256'], 'Native leaf bytes differ')
        original[leaf['path']] = json.loads(raw) if leaf['path'].endswith('.json') else leaf['utf8']
    require(set(original) == set(NATIVE_LEAVES), 'Missing native leaf')
    screen = original['native-exact-screen.json']
    require(screen['exact128_state_loss_rng_equal'] is True and screen['qualified'] is True
            and screen['gain_established'] is False and screen['descriptive_release_screen_passed'] is False,
            'Component prerequisite is not serving qualification')
    bounds = {}
    for name, units in [('native-exact-whole',128), ('native-exact-segments',22237)]:
        span = screen['spans'][name]
        require(span['complete_census'] is True and span['first_use_included'] is True
                and span['expected_unit_count'] == units and span['release_screen_passed'] is False,
                'Keep complete all-cold census')
        bound = span['maxima']['host_grant_to_drain_seconds'] + span['maxima']['host_ack_observation_seconds']
        near(bound, span['conservative_release_bound_seconds'])
        near(span['prospective_limit_seconds'], .0034296329)
        require(bound > span['prospective_limit_seconds'], 'Descriptive threshold differs')
        bounds[name] = bound
    row = original['native-window-segments/result.json']
    require(row['status'] == 'failed' and row['failure_type'] == 'TimeoutError', 'Final window did not complete')
    require_native_updates(row)
    require(len(row['requests']) == 19, 'Keep all original offers')
    counts = {'complete':0, 'not_started':0}
    for i, request in enumerate(row['requests']):
        require(request['id'] == 'warm-'+str(i+1).zfill(2), 'Original request identity differs')
        if request['status'] == 'not_started':
            near(request['planned_offset'], 15*i)
        else:
            near(request['planned_offer'], row['window']['start']+15*i)
            near(request['original_deadline'], request['planned_offer']+30)
        require(request['status'] in counts, 'Unexpected request status')
        counts[request['status']] += 1
        if request['status'] == 'complete':
            require(request['completed_tokens'] == 64
                    and hashlib.sha256(request['text'].encode()).hexdigest() == request['text_sha256'], 'Reported output differs')
    require(counts == {'complete':2,'not_started':17}, 'Incomplete serving census differs')
    terminal = original['suite-terminal.json']
    require(terminal['native_all6_joined'] is False
            and [x['arm'] for x in terminal['records']] == ['native-exact-whole','native-exact-segments','native-stock','native-window-continuous','native-window-busy']
            and all(x['lifecycle']['owned_process']['returncode'] == 0 for x in terminal['records']), 'Five prior returns do not complete the comparison')
    require("TimeoutError: grant_deadline" in original['native-window-segments.log']
            and 'governor.issue(time.monotonic(), next_offer=next_offer)' in original['native-window-segments.log']
            and 'RuntimeError: grant_channel_incomplete' in original['native-window-segments/cohort/trainer.log'], 'Preserve both causal traces')
    lifecycle = {r['arm']:(r['lifecycle']['finished_ns']-r['clock']['started_ns'])/1e9
                 for r in terminal['records'][:2]}
    near(lifecycle['native-exact-whole'],62.392971791)
    near(lifecycle['native-exact-segments'],72.334378146)
    ratio = bounds['native-exact-whole']/bounds['native-exact-segments']
    return {'selected_originals':9, 'selected_original_bytes':sum(x['bytes'] for x in bundle['originals']),
            'producer_exact_state_loss_rng_updates':128, 'all_cold_release_bounds_seconds':bounds,
            'component_bound_ratio':ratio, 'bound_reduction_percent':100*(1-1/ratio),
            'full_exact_arm_lifecycle_seconds':lifecycle,
            'full_exact_arm_lifecycle_ratio':lifecycle['native-exact-segments']/lifecycle['native-exact-whole'],
            'committed_updates_before_failure':79,'admitted_updates':80,'serving_requests':counts,
            'serving_comparison_complete':False,'qualified_gain':False,
            'independent_tensor_reproduction':False,'whole_original_verified':False}


def native_controls(bundle):
    cases = []
    bad = copy.deepcopy(bundle); bad['qualified_gain'] = True; cases.append(bad)
    bad = copy.deepcopy(bundle); bad['authentication']['whole_original_verified'] = True; cases.append(bad)
    bad = copy.deepcopy(bundle); bad['originals'].pop(); cases.append(bad)
    bad = copy.deepcopy(bundle)
    leaf = next(x for x in bad['originals'] if x['path'] == 'native-window-segments/result.json')
    row = json.loads(leaf['utf8']); row['native_updates']['committed_in_window'] = 80
    leaf['utf8'] = json.dumps(row); raw = leaf['utf8'].encode()
    leaf['bytes'], leaf['sha256'] = len(raw), hashlib.sha256(raw).hexdigest(); cases.append(bad)
    for bad in cases:
        try: recompute_native(bad)
        except (ValueError,KeyError,TypeError): continue
        raise AssertionError('Invalid native interpretation accepted')
    # Exercise semantic accounting independently of immutable-byte authentication.
    valid = json.loads(next(x['utf8'] for x in bundle['originals']
                            if x['path'] == 'native-window-segments/result.json'))
    require_native_updates(valid)
    bad = copy.deepcopy(valid)
    bad['native_updates']['committed_in_window'] = bad['acknowledged_updates'] = 80
    try: require_native_updates(bad)
    except ValueError: pass
    else: raise AssertionError('Partial update counted as committed')
    return len(cases)+1


def controls(bundle):
    def changed(path, edit):
        bad = copy.deepcopy(bundle)
        leaf = next(x for x in bad['originals'] if x['path'] == path)
        value = json.loads(leaf['utf8']); edit(value)
        leaf['utf8'] = json.dumps(value); raw = leaf['utf8'].encode()
        leaf['bytes'], leaf['sha256'] = len(raw), hashlib.sha256(raw).hexdigest()
        return bad
    def refused(bad):
        try: recompute(bad)
        except (ValueError, KeyError, TypeError): return
        raise AssertionError('Invalid scientific interpretation accepted')
    refused(changed('44042458319/window-continuous/result.json', lambda x: x.update(productive_grant_updates=1046)))
    refused(changed('44042458319/stock/result.json', lambda x: x['requests'].pop()))
    refused(changed('44042458319/comparison.json', lambda x: x['window_gates']['window-governed'].update(qualified=True)))
    refused(changed('44053640655/result.json', lambda x: x['records'][0].update(qualified_bundles=2)))
    bad = copy.deepcopy(bundle); bad['originals'][1] = bad['originals'][0]; refused(bad)
    return 5


CONTROL_LEAVES = {
    'native-stock/result.json': (68455, '5de8cb89345287399d8b0de5b1588ee00f23a7927ba83ba717a55e479957c2be'),
    'native-window-continuous/result.json': (463526, '6892a5c050234b3ee28d6e6748e9c037e82de1017b8ba2a20ffe75b34f6eb152'),
    'native-window-busy/result.json': (473878, '3ef3e71d716bc2fcf6d23e443b32792724995b2e42dc1caa919f0c4955249ede'),
    'native-exact-whole/result.json': (59479, 'aea813d18cbc74e038f511baa8c4efec5171496f3fe81b62749207182de48e6f'),
    'native-exact-segments/result.json': (513860, '10869df5c2166a85c3cff12d136f30f8bc8502b10471c9cbb002132279a4607d')}


def completed_control_rows(rows):
    """Same production semantic path is also exercised without immutable hash refusal."""
    stock = rows['native-stock']
    summaries = {}
    for arm in ('native-stock', 'native-window-continuous', 'native-window-busy'):
        row = rows[arm]
        require(row['status'] == 'complete' and len(row['requests']) == 19, 'Keep all 19 completed offers')
        require(row['identity'] == stock['identity'] and row['device_uuid'] == stock['device_uuid'], 'Model/trace/device differ')
        near(row['window']['end']-row['window']['start'], 300)
        first, terminal = [], []
        for i, (request, reference) in enumerate(zip(row['requests'], stock['requests'])):
            require(request['id'] == reference['id'] == 'warm-'+str(i+1).zfill(2), 'Offer identity differs')
            near(request['planned_offer'], row['window']['start']+15*i)
            near(request['original_deadline'], request['planned_offer']+30)
            require(request['status'] == 'complete' and request['completed_tokens'] == 64
                    and request['text'] == reference['text']
                    and hashlib.sha256(request['text'].encode()).hexdigest() == request['text_sha256'] == reference['text_sha256'], 'Exact text/reported token output differs')
            require(request['planned_offer'] <= request['first_output'] <= request['terminal_observed'] <= request['original_deadline'], 'Original deadline or timing differs')
            first.append(request['first_output']-request['planned_offer'])
            terminal.append(request['terminal_observed']-request['planned_offer'])
        count = 0
        if arm != 'native-stock':
            updates = row['native_updates']
            count = sum(row['window']['start'] <= x['completed'] <= row['window']['end'] for x in row['losses'])
            require(count == updates['committed_in_window'] == updates['productive_observed_in_window']
                    == row['productive_grant_updates'] == row['training']['in_window_steps'], 'Do not score late updates')
            require(len(row['losses']) == row['acknowledged_updates'] == updates['admitted'] == count+1
                    and updates['committed_after_window'] == row['drain_or_late_ack_updates'] == 1
                    and updates['partial_update_at_closure'] is False, 'Preserve late update and closure')
        summaries[arm] = {'completed_requests':19, 'reported_tokens':1216, 'productive_updates':count,
                         'median_first_seconds':sorted(first)[9], 'median_terminal_seconds':sorted(terminal)[9],
                         'original_p95_first_seconds':max(first), 'original_p95_terminal_seconds':max(terminal)}
    baseline = summaries['native-stock']
    for arm in ('native-window-continuous', 'native-window-busy'):
        row = summaries[arm]
        for metric in ('first', 'terminal'):
            row['median_'+metric+'_ratio_to_stock'] = row['median_'+metric+'_seconds']/baseline['median_'+metric+'_seconds']
            row['original_p95_'+metric+'_passes'] = row['original_p95_'+metric+'_seconds'] <= baseline['original_p95_'+metric+'_seconds']*1.05
    continuous = rows['native-window-continuous']
    for arm in ('native-window-busy','native-exact-whole','native-exact-segments'):
        row = rows[arm]
        require(row['training']['initial_hashes'] == continuous['training']['initial_hashes'], 'Training initialization differs')
        require([x['loss_hex'] for x in row['losses']] == [x['loss_hex'] for x in continuous['losses'][:len(row['losses'])]], 'Common loss prefix differs')
    require(len(rows['native-exact-whole']['losses']) == len(rows['native-exact-segments']['losses']) == 128
            and rows['native-exact-whole']['training']['final_checkpoint']['canonical_state_sha256']
            == rows['native-exact-segments']['training']['final_checkpoint']['canonical_state_sha256'], 'Exact128 producer checkpoint identity differs')
    return summaries


def response_policy_rows(rows):
    """Retrospective client thresholds and whole-update handoffs; no GPU execution."""
    completed_control_rows(rows)
    names = ('native-stock', 'native-window-continuous', 'native-window-busy')
    arms = {}
    def finite(value):
        require(type(value) in (int, float) and math.isfinite(value), 'Nonfinite host clock')
        return value
    def describe(values):
        values = sorted(values); n = len(values)
        require(n > 0, 'Missing timing observations')
        return dict(count=n, min=values[0], median=(values[(n-1)//2]+values[n//2])/2, max=values[-1])
    for name in names:
        records = []
        for request in rows[name]['requests']:
            offer = finite(request['planned_offer'])
            chunks = request['chunk_observations']
            require(chunks and all(type(x) in (int,float) and math.isfinite(x) for x in chunks)
                    and chunks == sorted(chunks) and chunks[0] == request['first_output']
                    and chunks[-1] == request['last_output']
                    and offer <= chunks[0] <= chunks[-1] <= finite(request['terminal_observed']),
                    'Client chunk chronology differs')
            records.append(dict(id=request['id'], first_ms=(chunks[0]-offer)*1000,
                terminal_ms=(request['terminal_observed']-offer)*1000,
                client_chunks_ms=[(x-offer)*1000 for x in chunks]))
        arms[name] = dict(scheduled=19, completed=19, per_request=records,
            joint_thresholds_ms={str(first):{str(full):sum(r['first_ms']<=first and r['terminal_ms']<=full for r in records)
                for full in (750,900,1000)} for first in (50,100,150,250,300)},
            complete_by_ms={str(full):sum(r['terminal_ms']<=full for r in records) for full in range(50,1001,50)})
    busy, continuous = rows[names[2]], rows[names[1]]
    require(all(busy['training'][k] == continuous['training'][k]
                for k in ('data_sha256','seed','initial_hashes','parameters')), 'Matched training identity differs')
    work = {}
    for name in names[1:]:
        row = rows[name]
        grants = [g for g in row['trainer_grants'] if g['committed'] and g['phase']=='update'
                  and finite(g['observed']) <= row['window']['end']]
        require([g['completed'] for g in grants] == list(range(1,row['native_updates']['committed_in_window']+1)),
                'Parent-confirmed productive prefix differs')
        losses = {x['step']:x for x in row['losses']}
        for g in grants:
            require(finite(g['host_started']) <= finite(g['drained_at']) <= g['observed']
                    and g['drained_at'] == losses[g['completed']]['completed'], 'Grant/loss clock join differs')
        work[name] = (grants, [losses[g['completed']]['loss_hex'] for g in grants])
    bg, bl = work[names[2]]; cg, cl = work[names[1]]
    common = min(len(bl),len(cl))
    require(bl[:common] == cl[:common], 'Productive common loss prefix differs')
    handoffs = []
    for i, request in enumerate(busy['requests']):
        require(finite(request['stop_issuing']) <= finite(request['drain_ack_observed'])
                <= finite(request['http_start']) <= request['first_output'], 'Stop/drain/request order differs')
        end = busy['requests'][i+1]['planned_offer'] if i<18 else busy['window']['end']
        between = [g for g in bg if request['terminal_observed'] <= g['host_started'] < end]
        done = [g for g in between if g['observed'] <= end]
        require(between and done, 'Missing confirmed whole update between requests')
        handoffs.append(dict(id=request['id'], following_interval='until_next_offer' if i<18 else 'until_trace_end',
            gap_ms=(end-request['terminal_observed'])*1000,
            host_restart_ms=(between[0]['host_started']-request['terminal_observed'])*1000,
            confirmed_update_ms=(done[0]['observed']-request['terminal_observed'])*1000,
            confirmed_whole_updates=len(done),
            stop_to_drain_ms=(request['drain_ack_observed']-request['stop_issuing'])*1000))
    return dict(run_id=44114594497, retrospective=True, scheduled_per_arm=19, window_seconds=300,
        arms=arms, training=dict(parameters=busy['training']['parameters'], continuous_updates=len(cg),
            held_updates=len(bg), common_steps=common, matching_loss_hex=common),
        handoffs=handoffs, between_requests={k:describe([r[k] for r in handoffs[:18]])
            for k in ('gap_ms','host_restart_ms','confirmed_update_ms','confirmed_whole_updates')},
        stop_to_drain_ms=describe([r['stop_to_drain_ms'] for r in handoffs]),
        hardware_idle_measured=False, minimum_productive_gap_established=False)


def recompute_completed_controls(bundle, self_test=False):
    require(bundle['schema'] == 'nodus.native-completed-controls/1' and bundle['run_id'] == 44114594497
            and bundle['derived_selection'] is True and bundle['scientific_execution'] is False
            and bundle['raw_checkpoints_included'] is False and bundle['qualified_gain'] is False, 'Control scope differs')
    require(bundle['authentication'] == {'whole_original_bytes':7199687992,
            'whole_original_sha256':'01699de10e9116cd3d5ec5cc8d524dabd0565ad7204ac27c8dabb4af824cae65',
            'manifest_sha256':'1e6e135d1876f03cd064d6af14d2f10ef2af37be94067234c3974cbc5703924e',
            'whole_original_verified':True}, 'Completed custody identity differs')
    rows = {}
    for leaf in bundle['originals']:
        raw = leaf['utf8'].encode(); name = leaf['path']; arm = name.split('/')[0]
        require(name in CONTROL_LEAVES and arm not in rows
                and (len(raw), hashlib.sha256(raw).hexdigest()) == CONTROL_LEAVES[name]
                and (leaf['bytes'],leaf['sha256']) == CONTROL_LEAVES[name], 'Control original bytes differ')
        rows[arm] = json.loads(raw)
    require(len(rows) == 5, 'Missing completed control original')
    summaries = completed_control_rows(rows)
    require([summaries[a]['productive_updates'] for a in ('native-stock','native-window-continuous','native-window-busy')] == [0,1061,1043], 'Productive census differs')
    require(summaries['native-window-continuous']['original_p95_terminal_passes'] is False
            and summaries['native-window-busy']['original_p95_first_passes'] is True
            and summaries['native-window-busy']['original_p95_terminal_passes'] is True, 'Original p95 criterion differs')
    negative_controls = 0
    if self_test:
        # These real-row mutations reach the same semantic helper as production.
        bad = copy.deepcopy(rows); bad['native-window-busy']['requests'].pop()
        late = copy.deepcopy(rows); late['native-window-busy']['productive_grant_updates'] += 1
        wrong = copy.deepcopy(rows); wrong['native-window-busy']['requests'][2]['text'] += 'changed'
        loss = copy.deepcopy(rows); loss['native-window-busy']['losses'][5]['loss_hex'] = '0x0p+0'
        for changed in (bad, late, wrong, loss):
            try: completed_control_rows(changed)
            except (ValueError,KeyError,TypeError): negative_controls += 1
            else: raise AssertionError('Invalid completed control accepted')
    policy = response_policy_rows(rows)
    policy_negatives = 0
    if self_test:
        mutations = []
        bad = copy.deepcopy(rows); bad['native-window-busy']['requests'][0]['chunk_observations'][0] = float('nan'); mutations.append(bad)
        bad = copy.deepcopy(rows); bad['native-window-busy']['requests'][0]['drain_ack_observed'] = bad['native-window-busy']['requests'][0]['http_start']+1; mutations.append(bad)
        bad = copy.deepcopy(rows); bad['native-window-busy']['training']['data_sha256'] = 'changed'; mutations.append(bad)
        bad = copy.deepcopy(rows); grant = next(g for g in bad['native-window-busy']['trainer_grants'] if g['committed'] and g['phase']=='update'); grant['observed'] = grant['drained_at']-1; mutations.append(bad)
        bad = copy.deepcopy(rows); grant = next(g for g in bad['native-window-busy']['trainer_grants'] if g['committed'] and g['phase']=='update'); grant['completed'] = 2; mutations.append(bad)
        for changed in mutations:
            try: response_policy_rows(changed)
            except (ValueError,KeyError,TypeError): policy_negatives += 1
            else: raise AssertionError('Invalid response-policy interpretation accepted')
    return {'arms':summaries, 'response_policy':policy, 'response_policy_negative_controls':policy_negatives,
            'window_seconds':300, 'p95_nearest_rank_is_maximum':True,
            'preserved_latency_claim':False, 'candidate_complete':False, 'qualified_gain':False,
            'checkpoint_tensors_reexecuted':False, 'negative_controls':negative_controls}


def native_complete_rows(comparison, segmented):
    """Recompute the later run's paired timing; keep producer verdicts explicit."""
    require(comparison['common_identity_qualified'] is True
            and comparison['native_stock_qualified'] is True
            and comparison['exact']['exact128_state_loss_rng_equal'] is True
            and comparison['gain_established'] is False, 'Complete comparison scope differs')
    arms = ('native-stock', 'native-window-continuous', 'native-window-busy', 'native-window-segments')
    require(set(comparison['foreground']) == set(arms), 'Keep all four serving arms')
    stock = comparison['foreground']['native-stock']['outcomes']
    summaries = {}
    for arm in arms:
        entry = comparison['foreground'][arm]
        outcomes = entry['outcomes']
        require(entry['observed_request_count'] == entry['original_offers'] == entry['within_original_deadline']
                == len(outcomes) == 19 and entry['request_binding_qualified'] is True, 'Keep all 19 original offers')
        first, terminal = [], []
        for i, row in enumerate(outcomes):
            require(row['id'] == 'warm-'+str(i+1).zfill(2) and row['status'] == 'complete'
                    and row['complete_output'] is True and row['within_original_deadline'] is True,
                    'Incomplete output cannot enter the complete comparison')
            near(row['planned_offer'], outcomes[0]['planned_offer']+15*i)
            require(0 <= row['first_seconds'] <= row['terminal_seconds'] <= 30,
                    'Preserve original-offer timing and deadline')
            first.append(row['first_seconds']); terminal.append(row['terminal_seconds'])
        near(entry['p95_first_seconds'], max(first)); near(entry['p95_terminal_seconds'], max(terminal))
        count = 0
        if arm != 'native-stock':
            gate = comparison['window_gates'][arm]; accounting = gate['completion_accounting']
            count = gate['observed_productive_updates']
            require(gate['all19_deadlines_met'] is True and gate['output_equality'] is True
                    and gate['training_correctness'] is True, 'Preserve producer output/training verdicts')
            require(count == accounting['committed_in_window'] == accounting['productive_observed_in_window']
                    and accounting['admitted'] == count+1 and accounting['committed_after_window'] == 1
                    and accounting['partial_update_at_closure'] is False, 'Do not score late or partial updates')
        summaries[arm] = {'completed_requests':19, 'productive_updates':count,
                         'median_first_seconds':sorted(first)[9], 'median_terminal_seconds':sorted(terminal)[9],
                         'original_p95_first_seconds':max(first), 'original_p95_terminal_seconds':max(terminal),
                         'paired_first_over_5pct_stock':sum(x > y['first_seconds']*1.05 for x,y in zip(first,stock)),
                         'paired_terminal_over_5pct_stock':sum(x > y['terminal_seconds']*1.05 for x,y in zip(terminal,stock))}
    baseline = summaries['native-stock']
    for arm in arms[1:]:
        row = summaries[arm]; gate = comparison['window_gates'][arm]
        for metric in ('first', 'terminal'):
            passed = row['original_p95_'+metric+'_seconds'] <= baseline['original_p95_'+metric+'_seconds']*1.05
            require(gate['p95_'+metric+'_preserved'] is passed, 'Original p95 criterion differs')
            row['original_p95_'+metric+'_passes'] = passed
        require(gate['qualified'] is (row['original_p95_first_passes'] and row['original_p95_terminal_passes']),
                'Original qualification differs')
    # The selected segmented raw result independently joins its request values,
    # text hashes and completed updates. Other arms retain producer comparison
    # verdicts; this companion does not pretend to replay absent control tensors.
    require(segmented['status'] == 'complete' and len(segmented['requests']) == 19, 'Segmented arm incomplete')
    near(segmented['window']['end']-segmented['window']['start'], 300)
    for request, outcome in zip(segmented['requests'], comparison['foreground']['native-window-segments']['outcomes']):
        require(request['id'] == outcome['id'] and request['status'] == 'complete'
                and request['completed_tokens'] == 64
                and hashlib.sha256(request['text'].encode()).hexdigest() == request['text_sha256'],
                'Segmented raw text/reported token evidence differs')
        near(request['planned_offer'], outcome['planned_offer'])
        near(request['original_deadline'], request['planned_offer']+30)
        near(request['first_output']-request['planned_offer'], outcome['first_seconds'])
        near(request['terminal_observed']-request['planned_offer'], outcome['terminal_seconds'])
    count = sum(segmented['window']['start'] <= x['completed'] <= segmented['window']['end'] for x in segmented['losses'])
    require(segmented['native_updates'] == comparison['window_gates']['native-window-segments']['completion_accounting']
            and count == segmented['productive_grant_updates'] == segmented['training']['in_window_steps']
            == summaries['native-window-segments']['productive_updates']
            and len(segmented['losses']) == segmented['acknowledged_updates'] == count+1,
            'Raw completed update accounting differs')
    return summaries


def recompute_native_complete(bundle, self_test=False):
    require(bundle['schema'] == 'nodus.native-complete-comparison/1' and bundle['run_id'] == 44138928133
            and bundle['derived_selection'] is True and bundle['scientific_execution'] is False
            and bundle['raw_checkpoints_included'] is False and bundle['qualified_gain'] is False,
            'Later complete comparison scope differs')
    auth = bundle['authentication']; manifest_raw = auth['manifest_utf8'].encode()
    require(hashlib.sha256(manifest_raw).hexdigest() == auth['manifest_sha256']
            == 'd8eed39ac4424f71a2b854bbb2e5d08f65e30d2286af5051373d0558b8760e4c'
            and auth['original_artifact'] == 14356942504 and auth['whole_original_bytes'] == 8627729864
            and auth['whole_original_sha256'] == '239d40f98bde018ee5a30938fa540fe797bcb2b782e1db50a1114e0df56a050f'
            and auth['hosted_full_authentication_run'] == 44164324619
            and auth['full_original_authenticated'] is True and auth['all_objects_full_readback'] is True,
            'Hosted original/manifest custody differs')
    manifest = json.loads(manifest_raw); expected = {row['path']:row for row in manifest['files']}
    names = {'comparison.json','suite-start.json','suite-terminal.json','outer-suite.log',
             'native-window-segments-before-device.json','native-window-segments-entry.json',
             'native-window-segments-joined.json','native-window-segments.cleanup.json',
             'native-window-segments.lifecycle.json','native-window-segments.log',
             'native-window-segments/planned-outcomes.json','native-window-segments/ready.json',
             'native-window-segments/result.json','native-window-segments/start.json',
             'native-window-segments/training-final.json'}
    rows = {}
    for leaf in bundle['originals']:
        name = leaf['path']; raw = leaf['utf8'].encode()
        require(name in names and name not in rows
                and len(raw) == leaf['bytes'] == expected[name]['bytes']
                and hashlib.sha256(raw).hexdigest() == leaf['sha256'] == expected[name]['sha256'],
                'Exact selected original differs')
        rows[name] = json.loads(raw) if name.endswith('.json') else raw
    require(set(rows) == names and len(expected) == 145, 'Missing selected original or raw inventory')
    comparison, segmented = rows['comparison.json'], rows['native-window-segments/result.json']
    summaries = native_complete_rows(comparison, segmented)
    require([summaries[a]['productive_updates'] for a in
            ('native-stock','native-window-continuous','native-window-busy','native-window-segments')]
            == [0,1057,1046,764], 'Later productive census differs')
    negative_controls = 0
    if self_test:
        missing = copy.deepcopy(comparison); missing['foreground']['native-stock']['outcomes'].pop()
        late = copy.deepcopy(segmented); late['productive_grant_updates'] += 1
        text = copy.deepcopy(segmented); text['requests'][2]['text'] += 'changed'
        gate = copy.deepcopy(comparison); gate['window_gates']['native-window-continuous']['p95_terminal_preserved'] = True
        for changed_comparison, changed_segmented in ((missing,segmented),(comparison,late),(comparison,text),(gate,segmented)):
            try: native_complete_rows(changed_comparison, changed_segmented)
            except (ValueError,KeyError,TypeError): negative_controls += 1
            else: raise AssertionError('Invalid completed comparison accepted')
    current, busy = summaries['native-window-segments'], summaries['native-window-busy']
    return {'run_id':44138928133, 'arms':summaries, 'window_seconds':300,
            'median_completion_reduction_vs_busy_pct':100*(1-current['median_terminal_seconds']/busy['median_terminal_seconds']),
            'productive_work_reduction_vs_busy_pct':100*(1-current['productive_updates']/busy['productive_updates']),
            'paired_5pct_is_posthoc_diagnostic':True, 'p95_nearest_rank_is_maximum':True,
            'producer_output_and_exact_state_verdicts':True, 'control_text_or_tensors_reexecuted':False,
            'candidate_complete':True, 'qualified_gain':False, 'negative_controls':negative_controls}


def permit_rows(rows):
    """Original-offer output accounting; an interrupted arm is never ranked."""
    stock = rows['permit-stock/result.json']
    complete = ('permit-stock', 'permit-window-async', 'permit-window-busy')
    summaries = {}
    for arm in complete:
        value = rows[arm+'/result.json']; requests = value['requests']
        require(value['status'] == 'complete' and value['identity'] == stock['identity']
                and value['device_uuid'] == stock['device_uuid'] and len(requests) == 19,
                'Keep matching workload, device and all 19 offers')
        near(value['window']['end']-value['window']['start'], 300)
        first, terminal = [], []
        for i, (request, reference) in enumerate(zip(requests, stock['requests'])):
            require(request['id'] == reference['id'] == 'warm-'+str(i+1).zfill(2)
                    and request['status'] == 'complete' and request['completed_tokens'] == 64
                    and request['text'] == reference['text']
                    and hashlib.sha256(request['text'].encode()).hexdigest() == request['text_sha256'],
                    'Exact text and reported 64-token output must match stock')
            near(request['planned_offer'], value['window']['start']+15*i)
            near(request['original_deadline'], request['planned_offer']+30)
            a = request['first_output']-request['planned_offer']
            b = request['terminal_observed']-request['planned_offer']
            require(0 <= a <= b <= 30, 'Original offer/deadline accounting differs')
            first.append(a); terminal.append(b)
        updates, late = 0, 0
        if arm != 'permit-stock':
            losses = value['losses']; training = value['training']
            updates = sum(value['window']['start'] <= item['completed'] <= value['window']['end'] for item in losses)
            late = sum(item['completed'] > value['window']['end'] for item in losses)
            require(updates == training['in_window_steps'] and late == training['drain_steps'] == 1
                    and len(losses) == training['step'] == updates+late,
                    'Late or partial updates cannot enter the 300-second count')
            if arm == 'permit-window-async':
                require(value['async_updates']['in_window_steps'] == updates
                        and value['async_updates']['step'] == len(losses), 'Async update census differs')
            else:
                accounting = value['native_updates']
                require(accounting['admitted'] == len(losses)
                        and accounting['committed_in_window'] == accounting['productive_observed_in_window']
                        == value['productive_grant_updates'] == updates
                        and accounting['committed_after_window'] == late
                        and accounting['partial_update_at_closure'] is False, 'Busy update census differs')
        stock_first = [r['first_output']-r['planned_offer'] for r in stock['requests']]
        stock_terminal = [r['terminal_observed']-r['planned_offer'] for r in stock['requests']]
        summaries[arm] = {'completed_requests':19, 'productive_updates':updates, 'late_updates_unscored':late,
            'median_first_seconds':sorted(first)[9], 'median_terminal_seconds':sorted(terminal)[9],
            'p95_first_seconds':max(first), 'p95_terminal_seconds':max(terminal),
            'paired_first_over_5pct_stock':sum(x > y*1.05 for x,y in zip(first,stock_first)),
            'paired_terminal_over_5pct_stock':sum(x > y*1.05 for x,y in zip(terminal,stock_terminal)),
            'arm_lifecycle_seconds':value['closed_monotonic']-value['started_monotonic']}
    failed = rows['permit-window-sites/result.json']; accounting = failed['native_updates']
    require(failed['status'] == 'failed' and failed['failure_type'] == 'RuntimeError'
            and len(failed['requests']) == 19 and failed['identity'] == stock['identity'],
            'Keep the interrupted serving arm and all its offers')
    near(failed['window']['end']-failed['window']['start'], 300)
    require('training' not in failed and 'losses' not in failed, 'No final checkpoint or complete loss trace for failed arm')
    require([r['status'] for r in failed['requests']] == ['complete']*10+['not_started']*9,
            'Do not drop or relabel unstarted requests')
    for i, request in enumerate(failed['requests']):
        require(request['id'] == 'warm-'+str(i+1).zfill(2), 'Failed-arm offer identity differs')
        if request['status'] == 'not_started':
            require(request['planned_offset'] == 15*i, 'Unstarted original offer offset differs')
        else:
            near(request['planned_offer'], failed['window']['start']+15*i)
            near(request['original_deadline'], request['planned_offer']+30)
            require(request['text'] == stock['requests'][i]['text'] and request['completed_tokens'] == 64
                    and hashlib.sha256(request['text'].encode()).hexdigest() == request['text_sha256']
                    and request['planned_offer'] <= request['first_output'] <= request['terminal_observed']
                    <= request['original_deadline'], 'Interrupted-arm completed output differs')
    require(accounting['admitted'] == 382 and accounting['committed_in_window']
            == accounting['productive_observed_in_window'] == failed['productive_grant_updates'] == 381
            and accounting['partial_update_at_closure'] is True and accounting['committed_after_window'] == 0,
            'Preserve the admitted but incomplete update')
    require('permit-window-local/result.json' not in rows and 'comparison.json' not in rows,
            'No local serving result or aggregate comparison exists')
    screen = rows['permit-exact-screen.json']
    require(screen['exact128_state_loss_rng_equal'] is True and screen['qualified'] is True
            and screen['gain_established'] is False, 'Exact component verdict is not application gain')
    component = {}
    sites = rows['permit-exact-sites/result.json']
    for arm in ('permit-exact-sites', 'permit-exact-local'):
        value = rows[arm+'/result.json']; training = value['training']; span = screen['spans'][arm]
        require(value['status'] == 'complete' and training['step'] == len(value['losses']) == 128
                and training['initial_hashes'] == sites['training']['initial_hashes']
                and training['final_hashes'] == sites['training']['final_hashes']
                and training['final_checkpoint']['canonical_state_sha256']
                == sites['training']['final_checkpoint']['canonical_state_sha256']
                and [x['loss_hex'] for x in value['losses']] == [x['loss_hex'] for x in sites['losses']],
                'Exact128 recorded state/loss/RNG hashes differ')
        require(span['complete_census'] is True and span['first_use_included'] is True
                and span['expected_unit_count'] == value['native_updates']['segment_acknowledgments'] == 22237
                and span['release_screen_passed'] is False, 'Retain all cold observations and failed screen')
        near(span['prospective_limit_seconds'], .0034296329)
        near(span['conservative_release_bound_seconds'], span['maxima']['host_grant_to_drain_seconds']
             +span['maxima']['host_ack_observation_seconds'])
        require(span['conservative_release_bound_seconds'] > span['prospective_limit_seconds'], 'Screen cannot pass')
        component[arm] = {'lifecycle_seconds':value['closed_monotonic']-value['started_monotonic'],
                         'conservative_release_bound_seconds':span['conservative_release_bound_seconds'],
                         'release_screen_passed':False}
    reference_losses = rows['permit-window-async/result.json']['losses']
    for arm in ('permit-exact-sites','permit-exact-local','permit-window-async','permit-window-busy'):
        value = rows[arm+'/result.json']; training = value['training']
        require(training['initial_hashes'] == sites['training']['initial_hashes']
                and training['parameters'] == 85352448 and training['seed'] == 1234
                and training['data_sha256'] == stock['identity']['data_sha256']
                and all(a['step'] == b['step'] and a['loss_hex'] == b['loss_hex']
                        for a,b in zip(value['losses'],reference_losses)), 'Common training prefix differs')
    terminal = rows['suite-terminal.json']
    require(terminal['permit_all7_joined'] is False and terminal['failure_type'] == 'RuntimeError',
            'Incomplete suite cannot become a complete comparison')
    return {'arms':summaries, 'component':component,
            'component_lifecycle_reduction_pct':100*(1-component['permit-exact-local']['lifecycle_seconds']
                                                     /component['permit-exact-sites']['lifecycle_seconds']),
            'interrupted_arm':{'completed_requests':10,'not_started':9,'committed_updates':381,
                               'admitted_updates':382,'partial_update':True,'ranked':False},
            'local_serving':'not_started', 'comparison_available':False}


def recompute_permit(bundle, self_test=False):
    require(bundle['schema'] == 'nodus.permit-incomplete-results/1' and bundle['run_id'] == 44163334988
            and bundle['derived_selection'] is True and bundle['scientific_execution'] is False
            and bundle['raw_checkpoints_included'] is False and bundle['qualified_gain'] is False,
            'Permit failed-run scope differs')
    auth = bundle['authentication']; raw = auth['manifest_utf8'].encode(); selected = auth['selection_utf8'].encode()
    require(hashlib.sha256(raw).hexdigest() == auth['manifest_sha256']
            == 'c8fd3c9df1c5fbd65b4110d1764ce340ab8d00e05a2287765a9f0e156a53dc85'
            and hashlib.sha256(selected).hexdigest() == auth['selection_sha256']
            == '526671df5a0a3556856660c3925b175e480ff72494b0e5bae173e9d7b193f8e7'
            and auth['original_artifact'] == 14367452327 and auth['whole_original_bytes'] == 7243736807
            and auth['whole_original_sha256'] == '3ad4cd3193d156a96d3087d2aa0ac70b68e5bd00276d2a212a83053da2e54eed'
            and auth['scientific_artifact_sha256'] == '65ce9099be5d77d2022409feff01778133cdbd47ab043956fea4702b347ec410'
            and auth['full_original_authenticated'] is False
            and auth['selected_leaves_manifest_authenticated'] is True,
            'Selected scientific evidence cannot imply full original authentication')
    manifest, selection = json.loads(raw), json.loads(selected)
    expected = {r['path']:r for r in manifest['files']}
    names = {r['path'] for r in selection['files'] if r['state'] == 'selected'}
    require(len(names) == 9 and len(expected) == 139 and selection['manifest_sha256'] == auth['manifest_sha256']
            and selection['binding'] == manifest['binding'] and selection['scientific_success'] is False,
            'Exact selection/manifest scope differs')
    rows = {}
    for leaf in bundle['originals']:
        name = leaf['path']; data = leaf['utf8'].encode()
        require(name in names and name not in rows and len(data) == leaf['bytes'] == expected[name]['bytes']
                and hashlib.sha256(data).hexdigest() == leaf['sha256'] == expected[name]['sha256'],
                'Selected original bytes differ')
        rows[name] = json.loads(data)
    require(set(rows) == names, 'Missing selected scientific original')
    result = permit_rows(rows)
    require([result['arms'][a]['productive_updates'] for a in ('permit-stock','permit-window-async','permit-window-busy')]
            == [0,1209,1036], 'Completed control census differs')
    negatives = 0
    if self_test:
        late = copy.deepcopy(rows); late['permit-window-busy/result.json']['productive_grant_updates'] += 1
        omitted = copy.deepcopy(rows); omitted['permit-window-sites/result.json']['requests'].pop()
        text = copy.deepcopy(rows); text['permit-window-async/result.json']['requests'][2]['text'] += 'changed'
        partial = copy.deepcopy(rows); partial['permit-window-sites/result.json']['native_updates']['partial_update_at_closure'] = False
        screen = copy.deepcopy(rows); screen['permit-exact-screen.json']['spans']['permit-exact-local']['release_screen_passed'] = True
        for bad in (late, omitted, text, partial, screen):
            try: permit_rows(bad)
            except (ValueError,KeyError,TypeError): negatives += 1
            else: raise AssertionError('Invalid permit outcome accepted')
    return dict(result, run_id=44163334988, window_seconds=300, qualified_gain=False,
                full_original_authenticated=False, checkpoint_tensors_reexecuted=False,
                paired_5pct_is_posthoc_diagnostic=True, negative_controls=negatives)



def whole_step_rows(rows):
    names = {'boundary-exact-screen.json', 'suite-start.json', 'suite-terminal.json',
             'boundary-controls.json', 'boundary-exact-sites/result.json',
             'boundary-exact-attention/result.json'}
    require(set(rows) == names, 'Whole-step selection must preserve absent serving results')
    screen = rows['boundary-exact-screen.json']; terminal = rows['suite-terminal.json']
    require(screen['schema'] == 'nodus.whole-step.exact/1'
            and screen['exact128_state_loss_rng_equal'] is True
            and screen['qualified'] is False and screen['gain_established'] is False
            and terminal['boundary_all7_joined'] is False and terminal['failure_type'] == 'ValueError',
            'Whole-step engineering failure must not become a serving verdict')
    arms = ('boundary-exact-sites', 'boundary-exact-attention')
    require([r['arm'] for r in terminal['records']] == list(arms), 'Only two exact arms completed')
    target = 3.4296329; result = {}; hashes = {}; reference = None
    for arm in arms:
        row = rows[arm+'/result.json']; training = row['training']; span = screen['spans'][arm]
        losses = [(x['step'], x['loss_hex']) for x in row['losses']]
        require(training['step'] == 128 and [x[0] for x in losses] == list(range(1,129))
                and row['requests'] == [], 'Exact128 updates are not a serving window')
        identity = (training['initial_hashes'], training['final_hashes'], training['seed'],
                    training['data_sha256'], training['parameters'], losses)
        if reference is None: reference = identity
        else: require(identity == reference, 'Exact model/optimizer/RNG and loss agreement differs')
        require(span['complete_census'] is True and span['steady_updates'] == [2,128]
                and span['target_ms'] == target and span['steady_passed'] is False,
                'All-site steady engineering screen must retain its original failure')
        host = span['steady_maxima']['host_execution_ms']['value']
        cuda = span['steady_maxima']['cuda_interval_ms']['value']
        require(host > target and cuda > target, 'Both observed engineering maxima breach the fixed limit')
        duration = row['closed_monotonic']-row['started_monotonic']
        require(duration > 0, 'Full arm lifecycle must include original endpoints')
        sites = row['native_spans']['sites']; audit = {n:v for n,v in sites.items() if n.startswith('hash:')}
        require(len(audit) == 597 and all(v['host_execution_seconds']['n'] == 1
                and v['cuda_interval_ms']['n'] == 1 for v in audit.values()),
                'All matched singleton state-audit units must remain present')
        hashes[arm] = audit
        result[arm] = {'exact_updates':128, 'lifecycle_seconds':duration,
                       'steady_host_max_ms':host, 'steady_cuda_max_ms':cuda,
                       'audit_units':len(audit),
                       'audit_host_max_ms':max(v['host_execution_seconds']['max'] for v in audit.values())*1000,
                       'audit_target_breaches':sum(v['host_execution_seconds']['max']*1000 > target for v in audit.values())}
    require(set(hashes[arms[0]]) == set(hashes[arms[1]]), 'State-audit names must match')
    sqrt = rows[arms[1]+'/result.json']['native_spans']['sites']['optimizer:004:aten._foreach_sqrt.default']
    h = sqrt['host_execution_seconds']; gpu = sqrt['cuda_interval_ms']
    require(h['n'] == gpu['n'] == 127 and h['p50']*1000 > target and gpu['p50'] > target
            and h['p50'] <= h['p95'] <= h['max']
            and abs(h['max']*1000-result[arms[1]]['steady_host_max_ms']) < 1e-9,
            'Steady optimizer distribution must retain repeated breaches')
    return {'arms':result, 'exact128_state_loss_rng_equal':True, 'target_ms':target,
            'audit_span_ratio':result[arms[0]]['audit_host_max_ms']/result[arms[1]]['audit_host_max_ms'],
            'audit_scope':'597 matched singleton step100 state-audit units; not checkpoint speed or training throughput',
            'lifecycle_change_percent':100*(result[arms[1]]['lifecycle_seconds']/result[arms[0]]['lifecycle_seconds']-1),
            'sqrt_host_median_ms':h['p50']*1000, 'sqrt_host_p95_ms':h['p95']*1000,
            'sqrt_steady_observations':127, 'sqrt_minimum_breaches_from_median':64,
            'exact_sqrt_breach_count_from_selected_json':None,
            'serving_windows_started':0, 'serving_requests_completed':0,
            'qualified_gain':False, 'engineering_screen_passed':False}


def recompute_whole_step(bundle, self_test=False):
    require(bundle['schema'] == 'nodus.whole-step-component-results/1' and bundle['run_id'] == 44200831180
            and bundle['derived_selection'] is True and bundle['scientific_execution'] is False
            and bundle['raw_checkpoints_included'] is False and bundle['qualified_gain'] is False,
            'Whole-step component scope differs')
    auth = bundle['authentication']; raw = auth['manifest_utf8'].encode(); selected = auth['selection_utf8'].encode()
    require(hashlib.sha256(raw).hexdigest() == auth['manifest_sha256']
            == '6769e7927cf01d91bee2cbefb427c77fa11b4c2e92ab2aa1400874e63943d1ef'
            and hashlib.sha256(selected).hexdigest() == auth['selection_sha256']
            == 'c5173edd4506410177418c0c7a3d677605a2fde461bec42400f9cfbb70a2d243'
            and auth['original_artifact'] == 14383335665 and auth['whole_original_bytes'] == 3456048761
            and auth['whole_original_sha256'] == '02749589262b1674777d4061d4de01f750c3fe382cfcf1ef0eba85253af69804'
            and auth['scientific_artifact_sha256'] == 'fe51394469fbba4809e8550d3a7bd45141caaa1e355ddba9a2e997e94f7375f4'
            and auth['full_original_authenticated'] is False
            and auth['selected_leaves_manifest_authenticated'] is True,
            'Selected whole-step originals cannot imply full archive authentication')
    manifest, selection = json.loads(raw), json.loads(selected)
    expected = {r['path']:r for r in manifest['files']}
    names = {r['path'] for r in selection['files'] if r['state'] == 'selected'}
    require(len(names) == 6 and len(expected) == 59 and selection['manifest_sha256'] == auth['manifest_sha256']
            and selection['binding'] == manifest['binding'] and selection['scientific_success'] is False,
            'Whole-step original census differs')
    rows = {}
    for leaf in bundle['originals']:
        name = leaf['path']; data = leaf['utf8'].encode()
        require(name in names and name not in rows and len(data) == leaf['bytes'] == expected[name]['bytes']
                and hashlib.sha256(data).hexdigest() == leaf['sha256'] == expected[name]['sha256'],
                'Whole-step original bytes differ')
        rows[name] = json.loads(data)
    require(set(rows) == names, 'Missing whole-step selected original')
    result = whole_step_rows(rows); negatives = 0
    if self_test:
        state = copy.deepcopy(rows); state['boundary-exact-attention/result.json']['training']['final_hashes'][0] = 'changed'
        passed = copy.deepcopy(rows); passed['boundary-exact-screen.json']['qualified'] = True
        serving = copy.deepcopy(rows); serving['boundary-stock/result.json'] = {}
        missing = copy.deepcopy(rows); del missing['boundary-exact-attention/result.json']['native_spans']['sites']['hash:tok.weight:model']
        census = copy.deepcopy(rows); census['boundary-exact-screen.json']['spans']['boundary-exact-attention']['complete_census'] = False
        for bad in (state, passed, serving, missing, census):
            try: whole_step_rows(bad)
            except (ValueError,KeyError,TypeError): negatives += 1
            else: raise AssertionError('Invalid whole-step component outcome accepted')
    return dict(result, run_id=44200831180, full_original_authenticated_at_selection=False,
                checkpoint_tensors_reexecuted=False, negative_controls=negatives)



def whole_step_grant_rows(raw):
    require(raw['schema'] == 'nodus.native-boundaries.raw/1'
            and raw['quantum'] == 'segments-attention' and len(raw['records']) == 88991,
            'Complete fixed candidate trace required')
    pending = {}; acknowledged = {}; ready = set(); units = []; last_seq = 0
    for row in raw['records']:
        seq = row['seq']; kind = row['kind']
        require(type(seq) is int and row['quantum'] == 'segments-attention'
                and row['session'] == '211:48648', 'Exact trace owner differs')
        if kind == 'issued':
            require(not pending and seq == last_seq+1, 'Duplicate, reordered or overlapping issued unit')
            pending[seq] = row; last_seq = seq
        elif kind == 'acknowledged':
            require(seq in pending and seq not in acknowledged, 'Unpaired or duplicate acknowledgment')
            issue = pending.pop(seq)
            require((issue['site'],issue['phase'],issue['session']) == (row['site'],row['phase'],row['session'])
                    and issue['at'] <= row['host_started'] <= row['drained_at'] <= row['at'] <= row['observed'],
                    'Unit identity or original host-clock order differs')
            acknowledged[seq] = row
            if issue['phase'] == 'update':
                update = issue['completed']+1; cuda = row['cuda_interval_ms']
                require(1 <= update <= 128 and isinstance(cuda,(int,float)) and math.isfinite(cuda) and cuda >= 0,
                        'Update index or CUDA interval differs')
                units.append({'site':row['site'], 'update':update,
                              'host_ms':1000*(row['drained_at']-row['host_started']), 'cuda_ms':cuda})
            else:
                require((seq,issue['phase']) in ((1,'initialize'),(43017,'finalize')),
                        'Unclassified unit omitted from steady census')
        elif kind == 'ready':
            require(seq in acknowledged and seq not in ready
                    and row['site'] == acknowledged[seq]['site'], 'Unpaired or duplicate ready bookkeeping')
            ready.add(seq)
        else: raise ValueError('Unclassified raw record')
    require(not pending and last_seq == len(acknowledged) == 43017
            and len(ready) == 2957 and len(units) == 43015, 'Incomplete whole-step record census')
    steady = [r for r in units if r['update'] >= 2]; target = 3.4296329
    breaches = [r for r in steady if r['host_ms'] > target or r['cuda_ms'] > target]
    sqrt = 'optimizer:004:aten._foreach_sqrt.default'
    require(len(steady) == 42402 and len(breaches) == 127
            and {r['site'] for r in breaches} == {sqrt}
            and [r['update'] for r in breaches] == list(range(2,129))
            and all(r['host_ms'] > target and r['cuda_ms'] > target for r in breaches),
            'Exact repeated HOST/CUDA breach result differs')
    other = [r for r in steady if r['site'] != sqrt]
    require(len(other) == 42275 and all(r['host_ms'] <= target and r['cuda_ms'] <= target for r in other),
            'Other steady units cannot be omitted or relabelled')
    return {'records':88991, 'complete_units':43015, 'steady_units':42402,
            'breaching_units':127, 'breaching_site':sqrt, 'breaching_updates':[2,128],
            'host_breaches':127, 'cuda_breaches':127, 'target_ms':target,
            'other_steady_units':42275, 'other_host_max_ms':max(r['host_ms'] for r in other),
            'other_cuda_max_ms':max(r['cuda_ms'] for r in other),
            'engineering_screen_passed':False, 'application_gain':False,
            'scope':'Original complete candidate trace; CUDA intervals include enqueue gaps, not GPU occupancy'}


def recompute_whole_step_grants(data, bundle, self_test=False):
    manifest = json.loads(bundle['authentication']['manifest_utf8'])
    descriptor = next(r for r in manifest['files'] if r['path'] == 'boundary-exact-attention/native-grants.json')
    require(len(data) == descriptor['bytes'] == 22879572
            and hashlib.sha256(data).hexdigest() == descriptor['sha256']
            == 'b47821b975cd790d463780447ef0e3e587920d86a468166086d2ea6f4cc24e6f',
            'Complete raw companion differs from authenticated selected manifest')
    raw = json.loads(data); result = whole_step_grant_rows(raw); negatives = 0
    if self_test:
        records = raw['records']; index = next(i for i,r in enumerate(records)
            if r['kind'] == 'acknowledged' and r['site'] == result['breaching_site'])
        duplicate = dict(raw, records=records[:-1]+[records[0]])
        identity_records = list(records); identity_records[index] = dict(records[index], site='changed')
        identity = dict(raw, records=identity_records)
        lower_records = list(records); ack = dict(records[index]); ack['drained_at'] = ack['host_started']+0.001
        ack['cuda_interval_ms'] = 1.0; lower_records[index] = ack
        lower = dict(raw, records=lower_records)
        for bad in (duplicate, identity, lower):
            try: whole_step_grant_rows(bad)
            except (ValueError,KeyError,TypeError): negatives += 1
            else: raise AssertionError('Invalid complete candidate trace accepted')
    return dict(result, negative_controls=negatives, raw_sha256=descriptor['sha256'])


def sqrt_partition_rows(rows):
    arms = ('sqrt-exact-whole', 'sqrt-exact-attention', 'sqrt-exact-partition')
    require(set(rows) == {'comparison.json', 'suite-start.json', 'suite-terminal.json', 'boundary-controls.json'}
            | {a+'/result.json' for a in arms}, 'Preserve the exact three-arm engineering selection')
    comparison = rows['comparison.json']; terminal = rows['suite-terminal.json']
    require(comparison['schema'] == 'nodus.sqrt-partition.engineering/1'
            and comparison['engineering_qualified'] is True
            and comparison['exact128_state_loss_rng_equal'] is True
            and comparison['application_gain'] is False and comparison['gain_established'] is False
            and comparison['full_allocation_cost_joined'] is False and comparison['serving_requests'] == 0
            and terminal['sqrt_all3_joined'] is True and terminal['failure_type'] is None
            and [r['arm'] for r in terminal['records']] == list(arms),
            'Engineering qualification is not application or cost qualification')
    target = 3.4296329
    require(comparison['target_ms'] == target and comparison['steady_updates'] == [2,128]
            and set(comparison['spans']) == set(arms), 'Original fixed screen and all arms must remain')
    result = {}; reference = None
    for arm, quantum, units, passed in zip(arms, ('whole','segments-attention','segments-attention-sqrt'),
                                         (128,43015,43143), (False,False,True)):
        row = rows[arm+'/result.json']; training = row['training']; span = comparison['spans'][arm]
        losses = [(x['step'],x['loss_hex']) for x in row['losses']]
        # Suite/file arm identity is distinct from the shared training worker role.
        require(row['arm'] == 'training' and row['native_spans']['quantum'] == quantum
                and row['native_grants_evidence']['sha256'] == span['raw_sha256'],
                'Suite arm must join the training role, native quantum and original trace identity')
        require(training['step'] == 128 and row['requests'] == []
                and [s for s,_ in losses] == list(range(1,129)), 'Exact128 arms contain no serving requests')
        identity = (training['initial_hashes'],training['final_hashes'],training['seed'],
                    training['data_sha256'],training['parameters'],losses)
        if reference is None: reference = identity
        else: require(identity == reference, 'Exact model/optimizer/RNG and all losses differ')
        require(span['complete_census'] is True and span['units'] == units and span['quantum'] == quantum
                and span['target_ms'] == target and span['steady_updates'] == [2,128]
                and span['steady_passed'] is passed, 'All-site census or original screen verdict differs')
        maxima = span['steady_maxima']
        host = maxima['host_execution_ms']['value']; cuda = maxima['cuda_interval_ms']['value']
        require(host > 0 and cuda > 0 and (host <= target and cuda <= target) is passed,
                'HOST and CUDA must independently satisfy the unchanged target')
        for metric in ('host_execution_ms','cuda_interval_ms','grant_to_drain_ms','ack_observation_ms'):
            peak = maxima[metric]
            require(peak['value'] == peak['argmax'][metric] and 2 <= peak['argmax']['update'] <= 128,
                    'Steady maxima must retain their corresponding original observation')
        cold = span['cold_update1']['host_execution_ms']
        require(cold['argmax']['update'] == 1 and cold['value'] == cold['argmax']['host_execution_ms']
                and cold['value'] > target
                and [r['site'] for r in span['initialization_and_finalization']] == ['initialize','finalize'],
                'Cold and lifecycle costs cannot inherit the steady screen')
        duration = row['closed_monotonic']-row['started_monotonic']
        require(duration > 0 and abs(duration-comparison['lifecycle_seconds'][arm]) < 1e-9,
                'Full arm lifecycle must retain its original endpoints')
        result[arm] = {'exact_updates':128, 'serving_requests':0, 'lifecycle_seconds':duration,
                       'steady_host_max_ms':host, 'steady_cuda_max_ms':cuda, 'engineering_screen_passed':passed,
                       'complete_update_units':units,
                       'steady_ack_max_ms':maxima['ack_observation_ms']['value'],
                       'steady_grant_to_drain_max_ms':maxima['grant_to_drain_ms']['value'],
                       'cold_host_max_ms':cold['value']}
    control, candidate, whole = result[arms[1]], result[arms[2]], result[arms[0]]
    require(candidate['lifecycle_seconds'] > whole['lifecycle_seconds']
            and candidate['steady_ack_max_ms'] > target, 'Keep lifecycle regression and distinct ACK bound')
    return {'arms':result, 'target_ms':target, 'engineering_screen_passed':True,
            'matched_host_span_reduction_percent':100*(1-candidate['steady_host_max_ms']/control['steady_host_max_ms']),
            'lifecycle_vs_whole_change_percent':100*(candidate['lifecycle_seconds']/whole['lifecycle_seconds']-1),
            'lifecycle_vs_attention_change_percent':100*(candidate['lifecycle_seconds']/control['lifecycle_seconds']-1),
            'exact128_state_loss_rng_equal':True, 'serving_requests_completed':0,
            'qualified_gain':False, 'request_or_reclaim_latency_qualified':False}


def recompute_sqrt_partition(bundle, self_test=False):
    require(bundle['schema'] == 'nodus.sqrt-partition-component-results/1' and bundle['run_id'] == 44214036575
            and bundle['derived_selection'] is True and bundle['scientific_execution'] is False
            and bundle['raw_checkpoints_included'] is False and bundle['qualified_gain'] is False,
            'Partitioned optimizer selection scope differs')
    auth = bundle['authentication']; raw = auth['manifest_utf8'].encode(); selected = auth['selection_utf8'].encode()
    require(hashlib.sha256(raw).hexdigest() == auth['manifest_sha256']
            == 'c8eb9a69f255657f46deb8372b51d119e0a706390bb61d99922cd2bb55217e7d'
            and hashlib.sha256(selected).hexdigest() == auth['selection_sha256']
            == '400efe7f278d16a40bf02bebeb72637a4317c9040189c0a6d3a13d6974125c23'
            and auth['scientific_artifact_sha256'] == '5db3104107f2cbc2687ad3790a08ce94a264a55bd6b0b9b4e26c56fd7c710258'
            and auth['original_artifact'] == 14388996809 and auth['whole_original_bytes'] == 5178749855
            and auth['whole_original_sha256'] == '061b644c01386053cbbd31c5da5b338af45c0dbd9c1758a7b158d9bd9d831739'
            and auth['full_original_authenticated'] is False and auth['selected_leaves_manifest_authenticated'] is True,
            'Selected-original authentication does not authenticate the full campaign archive')
    manifest, selection = json.loads(raw), json.loads(selected)
    expected = {r['path']:r for r in manifest['files']}
    names = {r['path'] for r in selection['files'] if r['state'] == 'selected'}
    require(len(names) == 7 and len(expected) == 84 and selection['manifest_sha256'] == auth['manifest_sha256']
            and selection['binding'] == manifest['binding'] and selection['scientific_success'] is False,
            'Original selection census and archival scientific verdict must remain unchanged')
    rows = {}
    for leaf in bundle['originals']:
        name = leaf['path']; data = leaf['utf8'].encode()
        require(name in names and name not in rows and len(data) == leaf['bytes'] == expected[name]['bytes']
                and hashlib.sha256(data).hexdigest() == leaf['sha256'] == expected[name]['sha256'],
                'Partitioned optimizer original bytes differ')
        rows[name] = json.loads(data)
    require(set(rows) == names, 'Missing selected engineering original')
    result = sqrt_partition_rows(rows); negatives = 0
    if self_test:
        state = copy.deepcopy(rows); state['sqrt-exact-partition/result.json']['training']['final_hashes'][0] = 'changed'
        gate = copy.deepcopy(rows); gate['comparison.json']['target_ms'] = 4.1
        census = copy.deepcopy(rows); census['comparison.json']['spans']['sqrt-exact-partition']['complete_census'] = False
        serving = copy.deepcopy(rows); serving['sqrt-exact-partition/result.json']['requests'] = [{'status':'complete'}]
        span = copy.deepcopy(rows); span['comparison.json']['spans']['sqrt-exact-partition']['steady_maxima']['host_execution_ms']['value'] = 4.0
        duration = copy.deepcopy(rows); duration['sqrt-exact-partition/result.json']['closed_monotonic'] -= 30
        role = copy.deepcopy(rows); role['sqrt-exact-partition/result.json']['arm'] = 'serving'
        swapped = copy.deepcopy(rows)
        swapped['sqrt-exact-whole/result.json'], swapped['sqrt-exact-partition/result.json'] = (
            swapped['sqrt-exact-partition/result.json'], swapped['sqrt-exact-whole/result.json'])
        for bad in (state,gate,census,serving,span,duration,role,swapped):
            try: sqrt_partition_rows(bad)
            except (ValueError,KeyError,TypeError): negatives += 1
            else: raise AssertionError('Invalid engineering outcome accepted')
    return dict(result, run_id=44214036575, full_original_authenticated_at_selection=False,
                checkpoint_tensors_reexecuted=False, negative_controls=negatives)


def routing_invalid_rows(rows):
    screen = rows['routing-exact-screen.json']
    terminal = rows['suite-terminal.json']
    whole, local = (rows[n+'/result.json'] for n in ('routing-exact-whole', 'routing-exact-local'))
    stock = rows['routing-stock-full/result.json']
    partial = rows['routing-stock-full/cohort/native-partial.json']
    require(screen['schema'] == 'nodus.routing.exact128/1' and screen['qualified'] is True
            and screen['exact128_state_loss_rng_equal'] is True
            and screen['whole_step_steady_passed'] is True and screen['gain_established'] is False,
            'Engineering qualification cannot become a serving gain')
    require(whole['arm'] == local['arm'] == 'training' and whole['status'] == local['status'] == 'complete'
            and whole['requests'] == local['requests'] == []
            and [r['step'] for r in whole['losses']] == list(range(1,129))
            and [(r['step'],r['loss_hex']) for r in whole['losses']]
                == [(r['step'],r['loss_hex']) for r in local['losses']]
            and whole['training']['initial_hashes'] == local['training']['initial_hashes']
            and whole['training']['final_hashes'] == local['training']['final_hashes']
            and whole['native_updates']['committed_in_window'] == local['native_updates']['committed_in_window'] == 128,
            'Exact128 engineering state/loss scope differs')
    require(all(r['runtime']['packages']['vllm'] == '0.30.0' for r in (whole, local, stock)),
            'Historical runtime version differs')
    require(stock['status'] == 'failed' and stock['profile'] == 'stock-full'
            and stock['cleanup']['cleanup_confirmed'] is False
            and terminal['routing_all9_joined'] is False
            and [r['arm'] for r in terminal['records']] == ['routing-exact-whole', 'routing-exact-local']
            and all(r['lifecycle']['owned_process']['returncode'] == 0 for r in terminal['records']),
            'Failed foreground control or unstarted comparisons misrepresented')
    require(partial['schema'] == 'nodus.routing.partial/1' and partial['complete'] is False
            and partial['profiler'] is None and partial['profile'] == 'stock-full',
            'Original partial collection cannot imply complete profile custody')
    requests = partial['requests']
    require(len(requests) == 12000 and [r['id'] for r in requests] == [f'route-{i:06d}' for i in range(12000)],
            'Routing original request census differs')
    for i, row in enumerate(requests):
        require(row['planned_ns'] == partial['start_ns']+i*25000000
                and row['planned_ns'] <= row['offered_ns'] <= row['first_ns'] <= row['terminal_ns'],
                'Routing planned schedule or observed ordering differs')
    groups = [('warmups', 3), ('preparation', 100), ('requests', 12000), ('diagnostic', 100)]
    for name, count in groups:
        require(len(partial[name]) == count and all(r['status'] == 'complete' and r['exhausted'] is True
                and r['text'] == ' ' and r['token_ids'] == [220] for r in partial[name]),
                'Whitespace completion is not a valid routing answer')
    valid = sum(r['text'] in ('0', '1', '2') and r['token_ids'] in ([15], [16], [17]) for r in requests)
    require(valid == 0, 'Invalid foreground control cannot be scored as useful answers')
    duration = [r['closed_monotonic']-r['started_monotonic'] for r in (whole, local)]
    require(all(t > 0 for t in duration) and duration[1] > duration[0], 'Engineering lifecycle penalty differs')
    return dict(classification='invalid_foreground_control', runtime_vllm='0.30.0',
        emitted_requests=len(requests), valid_routing_answers=valid, invalid_whitespace_outputs=len(requests),
        qualified_foreground_control=False, application_gain=False, provider_comparison=False,
        exact_engineering_updates=128, engineering_lifecycle_seconds=duration,
        engineering_lifecycle_increase_pct=(duration[1]/duration[0]-1)*100,
        profiler_start_to_stop_seconds=(partial['profile_stopped_ns']-partial['profile_started_ns'])/1e9,
        original_profiler_receipt_present=False, remaining_comparison_conditions_started=False)


def recompute_routing_invalid(bundle, self_test=False):
    require(bundle['schema'] == 'nodus.full-model.routing-invalid-selection/1' and bundle['run_id'] == 44244013052
            and bundle['derived_selection'] is True and bundle['qualified_gain'] is False
            and bundle['scientific_execution'] is True and bundle['raw_checkpoints_included'] is False,
            'Invalid foreground control selection scope differs')
    auth = bundle['authentication']; raw = auth['manifest_utf8'].encode(); selected = auth['selection_utf8'].encode()
    require(hashlib.sha256(raw).hexdigest() == auth['manifest_sha256']
            == '2f111923a2168b9142a7a812d57d64132c0e31ed80df97dcbfff01d04d85bc3f'
            and hashlib.sha256(selected).hexdigest() == auth['selection_sha256']
            == '6715e72fd3d91524483a5d178700c11a203daa3bcf007b02c91916ef6ae0157e'
            and auth['scientific_artifact_sha256'] == '23158a564af6df77987d79a33e02486873be5be415aaf019ef1938faa7d6f1d6'
            and auth['original_artifact'] == 14402860295 and auth['whole_original_bytes'] == 3539914146
            and auth['whole_original_sha256'] == '09eda86513f8e563284ae2409cde0ee4b4d96b8ebefd933ec77b4ca18b9bc098'
            and auth['full_original_authenticated_at_selection'] is False
            and auth['selected_leaves_manifest_authenticated'] is True,
            'Preserve original selected-leaf authentication history')
    manifest, selection = json.loads(raw), json.loads(selected)
    expected = {r['path']:r for r in manifest['files']}
    selected_names = {r['path'] for r in selection['files'] if r['state'] == 'selected'}
    extras = {'routing-stock-full/cohort/native-partial.json', 'routing-stock-full.log',
              'routing-stock-full/cohort/engine.log'}
    require(len(expected) == 76 and len(selected_names) == 8 and not selected_names & extras
            and selection['manifest_sha256'] == auth['manifest_sha256']
            and selection['binding'] == manifest['binding'] and selection['scientific_success'] is False,
            'Routing original manifest and selection census differ')
    rows = {}; seen = set()
    for leaf in bundle['originals']:
        name = leaf['path']; data = leaf['utf8'].encode()
        require(name in selected_names | extras and name not in seen
                and len(data) == leaf['bytes'] == expected[name]['bytes']
                and hashlib.sha256(data).hexdigest() == leaf['sha256'] == expected[name]['sha256'],
                'Routing selected original bytes differ')
        seen.add(name)
        if name.endswith('.json'): rows[name] = json.loads(data)
    require(seen == selected_names | extras, 'Missing routing original or causal log')
    result = routing_invalid_rows(rows); negatives = 0
    if self_test:
        wrong_execution = dict(bundle, scientific_execution=False)
        try: recompute_routing_invalid(wrong_execution)
        except ValueError as error:
            require(str(error) == 'Invalid foreground control selection scope differs',
                    'Wrong execution role failed for an unrelated reason')
            negatives += 1
        else: raise AssertionError('Original scientific execution incorrectly denied')
        key = 'routing-stock-full/cohort/native-partial.json'
        duplicate = copy.deepcopy(rows); duplicate[key]['requests'][1]['id'] = 'route-000000'
        answer = copy.deepcopy(rows); answer[key]['requests'][0].update(text='0', token_ids=[15])
        clock = copy.deepcopy(rows); clock[key]['requests'][0]['planned_ns'] += 1
        foreground = copy.deepcopy(rows); foreground['routing-stock-full/result.json']['status'] = 'complete'
        gain = copy.deepcopy(rows); gain['routing-exact-screen.json']['gain_established'] = True
        state = copy.deepcopy(rows); state['routing-exact-local/result.json']['training']['final_hashes'][0] = 'changed'
        loss = copy.deepcopy(rows); loss['routing-exact-local/result.json']['losses'][0]['loss_hex'] = '0x0p+0'
        profiler = copy.deepcopy(rows); profiler[key]['profiler'] = {'status':'complete'}
        for bad in (duplicate, answer, clock, foreground, gain, state, loss, profiler):
            try: routing_invalid_rows(bad)
            except (ValueError, KeyError, TypeError): negatives += 1
            else: raise AssertionError('Invalid routing history interpretation accepted')
    return dict(result, run_id=44244013052, full_original_authenticated_at_selection=False,
                negative_controls=negatives, checkpoint_tensors_reexecuted=False)



def routing_preparation_rows(rows, cases):
    partial = rows['routing-stock-full/cohort/native-partial.json']
    failure = rows['routing-stock-full/cohort/native-failure.json']
    stock = rows['routing-stock-full/result.json']
    screen = rows['routing-exact-screen.json']
    terminal = rows['suite-terminal.json']
    whole, local = (rows[n+'/result.json'] for n in ('routing-exact-whole', 'routing-exact-local'))
    require(failure['schema'] == 'nodus.routing.child-failure/1'
            and failure['code'] == 'routing_preparation_quality_accuracy'
            and failure['phase'] == 'begin' and failure['scientific_success'] is False
            and stock['status'] == 'failed' and stock['cleanup']['cleanup_confirmed'] is False,
            'Preparation failure is not a scored serving result')
    require(partial['schema'] == 'nodus.routing.partial/1' and partial['complete'] is False
            and partial['profile'] == 'stock-full' and partial['active_count'] == 0
            and all(partial[k] is None for k in ('start_ns','profiler','profile_started_ns','profile_stopped_ns','preparation_quality'))
            and all(partial[k] == [] for k in ('requests','diagnostic','transitions')),
            'Scored or profiled requests were not produced')
    require(len(cases) == 48 and len({c['case_id'] for c in cases}) == 48
            and [c['label'] for c in cases] == ['0','1','2']*16,
            'Pinned preparation case order differs')
    counts = {label:dict(correct=0,total=0) for label in ('0','1','2')}
    confusion = {label:{prediction:0 for prediction in counts} for label in counts}
    for group, count in (('warmups',3),('preparation',100)):
        values = partial[group]
        require(len(values) == count, 'Preparation/warmup census differs')
        for i, row in enumerate(values):
            require(row['id'] == f'{"warmup" if group == "warmups" else "preparation"}-{i:06d}'
                    and row['status'] == 'complete' and row['exhausted'] is True
                    and row['text'] in counts and row['token_ids'] == [15+int(row['text'])]
                    and row['planned_ns'] <= row['offered_ns'] <= row['first_ns'] <= row['terminal_ns'],
                    'Preparation identity, valid token or clock order differs')
            if group == 'preparation':
                label = cases[i % len(cases)]['label']
                counts[label]['total'] += 1
                counts[label]['correct'] += row['text'] == label
                confusion[label][row['text']] += 1
    correct = sum(c['correct'] for c in counts.values())
    failed_classes = [label for label,c in counts.items() if 100*c['correct'] < 95*c['total']]
    require(correct == 51 and correct < 95 and failed_classes == ['0','2'],
            'Original overall and per-class accuracy gates differ')
    require(screen['schema'] == 'nodus.routing.exact128/1' and screen['qualified'] is True
            and screen['exact128_state_loss_rng_equal'] is True
            and screen['whole_step_steady_passed'] is True and screen['gain_established'] is False,
            'Engineering qualification cannot become a serving gain')
    require(whole['arm'] == local['arm'] == 'training' and whole['status'] == local['status'] == 'complete'
            and whole['requests'] == local['requests'] == []
            and [r['step'] for r in whole['losses']] == list(range(1,129))
            and [(r['step'],r['loss_hex']) for r in whole['losses']] == [(r['step'],r['loss_hex']) for r in local['losses']]
            and whole['training']['initial_hashes'] == local['training']['initial_hashes']
            and whole['training']['final_hashes'] == local['training']['final_hashes']
            and whole['native_updates']['committed_in_window'] == local['native_updates']['committed_in_window'] == 128,
            'Exact128 state/loss/RNG scope differs')
    require(all(r['runtime']['packages']['vllm'] == '0.30.0' for r in (whole,local,stock))
            and terminal['routing_all9_joined'] is False
            and [r['arm'] for r in terminal['records']] == ['routing-exact-whole','routing-exact-local']
            and all(r['lifecycle']['owned_process']['returncode'] == 0 for r in terminal['records']),
            'Version or unstarted comparison scope differs')
    duration = [r['closed_monotonic']-r['started_monotonic'] for r in (whole,local)]
    require(0 < duration[0] < duration[1], 'Whole lifecycle penalty must remain visible')
    spans = screen['spans']['routing-exact-local']
    require(spans['complete_census'] is True and spans['physical_ACKs_preserved'] is True
            and spans['steady_updates'] == [2,128] and spans['target_ms'] == 3.4296329
            and spans['steady_passed'] is True, 'Fixed engineering screen differs')
    return dict(classification='preparation_quality_failure', runtime_vllm='0.30.0',
        preparation_correct=correct, preparation_total=100, preparation_required_accuracy=.95,
        preparation_required_accuracy_each_class=.95, preparation_failed_classes=failed_classes,
        class_counts=counts, confusion=confusion, warmup_requests=3, scored_requests=0,
        application_gain=False, provider_comparison=False, scored_comparison_complete=False,
        remaining_serving_conditions_started=False, exact_n_reference_started=False,
        exact_engineering_updates=128, engineering_lifecycle_seconds=duration,
        engineering_lifecycle_increase_pct=(duration[1]/duration[0]-1)*100,
        local_steady_maxima={k:v['value'] for k,v in spans['steady_maxima'].items()},
        cold_host_max_ms=spans['cold_update1']['host_execution_ms']['value'],
        request_or_reclaim_latency_qualified=False, checkpoint_tensors_reexecuted=False)


def recompute_routing_preparation(bundle, self_test=False):
    require(bundle['schema'] == 'nodus.full-model.routing-preparation-selection/1'
            and bundle['run_id'] == 44407274663 and bundle['scientific_execution'] is True
            and bundle['qualified_gain'] is False and bundle['scored_comparison_complete'] is False
            and bundle['raw_checkpoints_included'] is False, 'Preparation selection scope differs')
    auth = bundle['authentication']; raw = auth['manifest_utf8'].encode(); selected = auth['selection_utf8'].encode()
    require(hashlib.sha256(raw).hexdigest() == auth['manifest_sha256'] == '0032cc6053bb3a22cd53e8b5ed6acbad78fcf258694afd7fe92ca47576a51844'
            and hashlib.sha256(selected).hexdigest() == auth['selection_sha256'] == 'd3339832e9f07c48712e8e8f024fa4aed6b450eb7eb5376e7ae1b56227f00099'
            and auth['scientific_artifact_sha256'] == 'a816cfbd05e7e306a35a7189f9d916f6a2717b0288687b72ae4a2072e771cbea'
            and auth['original_artifact'] == 14477771306 and auth['whole_original_bytes'] == 3448592938
            and auth['whole_original_sha256'] == 'e73d4b92cde596b90cc54e42c5c15e9141a48e903ba2a8b7ab3f298377274ee9'
            and auth['full_original_authenticated_at_selection'] is False,
            'Preserve actual producer and selection-time custody')
    manifest, selection = json.loads(raw), json.loads(selected)
    expected = {r['path']:r for r in manifest['files']}
    names = {r['path'] for r in selection['files'] if r['state'] == 'selected'}
    extras = {'routing-stock-full/cohort/native-partial.json','routing-stock-full/cohort/native-failure.json'}
    require(len(expected) == 75 and len(names) == 8 and not names & extras
            and selection['manifest_sha256'] == auth['manifest_sha256']
            and selection['binding'] == manifest['binding'] and selection['scientific_success'] is False
            and set(auth['additional_range_leaves']) == extras
            and auth['range_custody_sha256'] == '05a97fbf4f3ac7fc9d7398ff16c2ea0ccc0f6d68c18614b1e75a5007b90e9ef4',
            'Scientific selection and separate bounded range differ')
    rows = {}
    for leaf in bundle['originals']:
        name = leaf['path']; data = leaf['utf8'].encode()
        require(name in names | extras and name not in rows and len(data) == leaf['bytes'] == expected[name]['bytes']
                and hashlib.sha256(data).hexdigest() == leaf['sha256'] == expected[name]['sha256'],
                'Preparation original bytes differ')
        rows[name] = json.loads(data)
    require(set(rows) == names | extras, 'Missing preparation original')
    case_source = bundle['source_cases']; data = case_source['utf8'].encode()
    require(len(data) == case_source['bytes'] == 4642
            and hashlib.sha256(data).hexdigest() == case_source['sha256'] == 'f8db6203b08572166a4804357c7fbd21717ea5d6369d6247888ef309fb8c7b09'
            and case_source['study_commit'] == '327b67ee02f539a79354889a603a42b082db0cbc', 'Preparation cases differ')
    cases = json.loads(data); result = routing_preparation_rows(rows,cases); negatives = 0
    if self_test:
        key = 'routing-stock-full/cohort/native-partial.json'
        mutations = [([key,'preparation',1,'id'],'preparation-000000'),
            ([key,'preparation',0,'token_ids'],[220]), ([key,'preparation',0,'exhausted'],False),
            ([key,'preparation',0,'first_ns'],0), ([key,'requests'],[{'id':'fabricated'}]),
            ([key,'start_ns'],1), (['routing-exact-screen.json','gain_established'],True),
            (['routing-exact-local/result.json','training','final_hashes',0],'changed'),
            (['routing-stock-full/cohort/native-failure.json','code'],'other_failure')]
        for path, value in mutations:
            bad = copy.deepcopy(rows); node = bad
            for part in path[:-1]: node = node[part]
            node[path[-1]] = value
            try: routing_preparation_rows(bad,cases)
            except (ValueError,KeyError,TypeError): negatives += 1
            else: raise AssertionError('Invalid preparation interpretation accepted')
        wrong = copy.deepcopy(cases); wrong[0]['label'] = '2'
        try: routing_preparation_rows(rows,wrong)
        except ValueError: negatives += 1
        else: raise AssertionError('Wrong preparation case order accepted')
    return dict(result, run_id=44407274663, negative_controls=negatives,
                full_original_authenticated_at_selection=False)


def optimizer_rows(rows):
    modes = ('foreach-plain','foreach-observe','foreach-drain','fused-plain','fused-observe')
    arms = tuple('optimizer-exact-'+m for m in modes)
    require(set(rows) == {'comparison.json','suite-start.json','suite-terminal.json','optimizer-controls/result.json'}
            | {a+'/result.json' for a in arms}, 'Preserve all five optimizer arms and controls')
    c = rows['comparison.json']; terminal = rows['suite-terminal.json']; controls = rows['optimizer-controls/result.json']
    require(c['schema'] == 'nodus.optimizer-operation.comparison/1' and c['foreach_exact128'] is True
            and c['gain_established'] is False and c['gap_screen_qualified'] is False
            and c['proposed_gap_ms'] == 3.4296329 and set(c['traces']) == set(arms)
            and terminal['optimizer_all5_joined'] is True and terminal['failure_type'] is None
            and [x['arm'] for x in terminal['records']] == list(arms), 'Optimizer scope or arm census differs')
    require(controls['completed'] is True and controls['actual_cuda'] is True and controls['parameters'] == 149
            and controls['modes'] == 5 and controls['updates_per_mode'] == 128
            and controls['full_model_shapes'] is False and controls['application_gain'] is False,
            'Small CUDA controls cannot substitute for full-model qualification')
    screen = c['engineering_screen']; target = 3.4296329
    require(screen['target_ms'] == target and screen['steady_updates'] == [2,128]
            and all(screen[k] is False for k in ('foreach_all_cold_drained_span_passed',
                'foreach_steady_drained_span_passed','fused_drain_measured','fused_steady_observation_interval_passed')),
            'Retain the original failed screen and absent fused drain')
    base = rows[arms[0]+'/result.json']; training = base['training']; result = {}
    baseline_losses = [float.fromhex(x['loss_hex']) for x in base['losses']]
    for arm,mode in zip(arms,modes):
        r = rows[arm+'/result.json']; t = r['training']; trace = c['traces'][arm]
        require(r['arm'] == 'training' and r['status'] == 'complete' and t['step'] == 128
                and r['requests'] == [] and [x['step'] for x in r['losses']] == list(range(1,129))
                and t['initial_hashes'] == training['initial_hashes'] and r['identity'] == base['identity']
                and all(t[k] == training[k] for k in ('seed','data_sha256','parameters')),
                'Exact128 identity/loss census and absent serving must remain')
        require(trace['identity']['mode'] == mode and trace['parent_yield'] is False
                and trace['application_gain'] is False and trace['identity']['cuda_interval_is_occupancy'] is False
                and [x['update'] for x in trace['steps']] == list(range(1,129)), 'Timing mode or claim scope differs')
        failures = [i+1 for i,(a,b) in enumerate(zip(baseline_losses,[float.fromhex(x['loss_hex']) for x in r['losses']]))
                    if not math.isfinite(b) or abs(a-b) > 1e-5+1e-4*abs(a)]
        verdicts = None
        if mode.startswith('foreach'):
            require(t['final_hashes'] == training['final_hashes']
                    and t['final_checkpoint']['canonical_state_sha256'] == training['final_checkpoint']['canonical_state_sha256']
                    and [x['loss_hex'] for x in r['losses']] == [x['loss_hex'] for x in base['losses']],
                    'Foreach model/optimizer/RNG or exact losses differ')
        else:
            v = c['fused_numerical'][arm]
            verdicts = {'total':len(v['tensors']), 'failed':sum(x.get('accepted') is False for x in v['tensors'].values())}
            require(v['accepted'] is False and v['losses_accepted'] is False and v['rng_exact'] is True
                    and v['customer_quality_qualified'] is False and failures == [127]
                    and verdicts == {'total':757,'failed':297}, 'Fused loss and producer tensor rejections must both remain')
        duration = r['closed_monotonic']-r['started_monotonic']
        require(duration > 0 and math.isfinite(duration), 'Full lifecycle endpoints invalid')
        result[arm] = dict(lifecycle_seconds=duration, updates=128, exact_foreach=mode.startswith('foreach'),
            loss_failure_steps=failures, producer_tensor_verdicts=verdicts,
            steady_drained_host_max_ms=trace['warm_max_drained_host_ms'],
            steady_cuda_interval_max_ms=trace['warm_max_cuda_interval_ms'])
    require(result[arms[2]]['steady_drained_host_max_ms'] > target
            and result[arms[4]]['steady_cuda_interval_max_ms'] > target
            and all(result[a]['steady_drained_host_max_ms'] is None for a in arms if a != arms[2])
            and all(result[a]['steady_cuda_interval_max_ms'] is None for a in (arms[0],arms[3])),
            'Unmeasured durations stay null and failed maxima cannot be dropped')
    return dict(arms=result, target_ms=target, engineering_screen_passed=False, qualified_gain=False,
                serving_requests_completed=0, checkpoint_tensors_reexecuted=False)


def recompute_optimizer(bundle, self_test=False):
    require(bundle['schema'] == 'nodus.full-model.optimizer-selection/1' and bundle['run_id'] == 44177568742
            and bundle['qualified_gain'] is False and bundle['raw_checkpoints_included'] is False,
            'Optimizer selection scope differs')
    a = bundle['authentication']; raw = a['manifest_utf8'].encode(); selected = a['selection_utf8'].encode()
    require(hashlib.sha256(raw).hexdigest() == a['manifest_sha256'] == '3a913c7aa68862b60a0414799443c94b7c43634331d453e7ec5af8b252a8dd80'
            and hashlib.sha256(selected).hexdigest() == a['selection_sha256'] == '44975bf4f7e2971120feaf1129f11514ee99a6d1f2e82495b4e82f9e3ccbe6f5'
            and a['scientific_artifact_sha256'] == '83a9fa64826f28db66c5425c04d6503e8ec8630640ebf93597c6ff80188194b9'
            and a['whole_original_sha256'] == '26b9044722fe810c7f1506b07a2440652d1d611695620725a911e3b75af3a945'
            and a['original_artifact'] == 14372011924 and a['whole_original_bytes'] == 8558049921
            and a['full_original_authenticated_at_selection'] is False, 'Preserve original selection authentication and scope')
    manifest, selection = json.loads(raw), json.loads(selected)
    expected = {x['path']:x for x in manifest['files']}; names = {x['path'] for x in selection['files'] if x['state']=='selected'}
    require(len(expected)==140 and len(names)==9 and selection['binding']==manifest['binding']
            and selection['manifest_sha256']==a['manifest_sha256'], 'Optimizer manifest/selection census differs')
    rows = {}
    for leaf in bundle['originals']:
        name = leaf['path']; body = leaf['utf8'].encode()
        require(name in names and name not in rows and len(body)==leaf['bytes']==expected[name]['bytes']
                and hashlib.sha256(body).hexdigest()==leaf['sha256']==expected[name]['sha256'], 'Optimizer original byte join failed')
        rows[name] = json.loads(body)
    require(set(rows)==names, 'Missing optimizer original')
    result = optimizer_rows(rows); negatives = 0
    if self_test:
        mutations = [(['comparison.json','engineering_screen','target_ms'],108),
            (['comparison.json','gain_established'],True),
            (['optimizer-exact-foreach-drain/result.json','training','final_hashes'],['changed']),
            (['optimizer-exact-fused-plain/result.json','losses'],rows['optimizer-exact-foreach-plain/result.json']['losses']),
            (['comparison.json','fused_numerical','optimizer-exact-fused-observe','tensors'],{}),
            (['optimizer-exact-fused-plain/result.json','requests'],[{}]),
            (['comparison.json','traces','optimizer-exact-foreach-plain','warm_max_drained_host_ms'],0),
            (['optimizer-controls/result.json','full_model_shapes'],True)]
        for path,value in mutations:
            bad = copy.deepcopy(rows); node = bad
            for key in path[:-1]: node = node[key]
            node[path[-1]] = value
            try: optimizer_rows(bad)
            except (ValueError,KeyError,TypeError): negatives += 1
            else: raise AssertionError('Invalid optimizer interpretation accepted')
    return dict(result, run_id=44177568742, negative_controls=negatives)


def rerank_refusal_controls(rows, identity):
    """Mutate actual interpreted records, after original byte authentication."""
    reference = rows['r0/result.json']['reference_actual']
    first_query = next(iter(reference['scores']))
    mutations = [
        (['r0/result.json','reference_actual','forwards',1], copy.deepcopy(reference['forwards'][0])),
        (['r0/result.json','reference_actual','forwards'], reference['forwards'][:-1]),
        (['r0/result.json','reference_actual','scores',first_query,0], float('nan')),
        (['r0/result.json','reference_actual','forwards',0,'timing','host_monotonic_ns','scores_materialized'], 0),
        (['r0/result.json','reference_actual','forwards',0,'timing','clock_domains_joined'], True),
        (['r0/result.json','reference_actual','input_hashes',first_query,0], '0'*64),
        (['reference-quality.json','scalar_mismatches'], []),
        (['suite.json','owners',1,'status'], 'complete'),
        (['r0/result.json','reference_actual','credited_window_outputs'], 1),
        (['suite.json','performance_claim_eligible'], True),
    ]
    refused = 0
    for path, value in mutations:
        bad = copy.deepcopy(rows); node = bad
        for part in path[:-1]: node = node[part]
        node[path[-1]] = value
        try: rerank_rows(bad, identity)
        except (ValueError, KeyError, TypeError): refused += 1
        else: raise AssertionError('Changed reranking contract accepted')
    return refused


def rerank_rows(rows, identity):
    """Recorded calibration clocks and score comparisons; no GPU execution."""
    from collections import defaultdict
    from statistics import median, mean
    result = rows['r0/result.json']; quality = rows['reference-quality.json']; suite = rows['suite.json']
    require(result['schema'] == 'nodus.online-offline-rerank.condition/1'
            and result['protocol'] == suite['protocol'] == 'online-offline-rerank-v1'
            and result['schedule'] == result['arm'] == 'reference'
            and result['device_name'] == 'NVIDIA A10' and result['status'] == 'complete'
            and result['scientific_acceptance'] is False and quality['qualified'] is False,
            'Preserve actual completed reference and failed numerical qualification')
    require(result['research_source_sha'] == '94038527b98305522fba12c2e3a5d1cb12b0e68b'
            and result['task_sha256'] == suite['task_sha256'] == identity['canonical_task_sha256']
            == 'd537d0a09abab873ffc96c86819c364c222ac26468a0100ff92df461e54716ae', 'Reranking source/task differs')
    arms = ['foreground-only','shared-priority-b32','shared-priority-b8','ordinary-resident-mps',
            'ordinary-opportunistic-query','finite-batch-candidate']
    expected = [('reference','reference')] + [('smooth',a) for a in arms] + [('burst',a) for a in reversed(arms)]
    require([(x['schedule'],x['arm']) for x in suite['owners']] == expected
            and suite['owners'][0]['status'] == 'complete'
            and all(x['status'] == 'unstarted' for x in suite['owners'][1:])
            and suite['status'] == 'incomplete' and suite['performance_claim_eligible'] is False,
            'Incomplete mixed comparison cannot become a measured serving result')
    require(result['clients']['engine']['model_revision'] == identity['model_revision']
            == '953dc6f6f85a1b2dbfca4c34a2796e7dde08d41e', 'Reranking model revision differs')
    actual = result['reference_actual']; queries = {x['query_id']:x for x in identity['queries']}
    require(len(queries) == len(identity['queries']) == 96 and actual['task_sha256'] == result['task_sha256']
            and set(actual['scores']) == set(actual['input_hashes']) == set(queries)
            and actual['credited_window_outputs'] == quality['timed_output_credit'] == 0,
            'Actual input/score ownership or cached output credit differs')
    finite = lambda x: type(x) in (int,float) and math.isfinite(x)
    for qid,q in queries.items():
        require(len(q['pairs']) == len(actual['scores'][qid]) == 32
                and len({x['doc_id'] for x in q['pairs']}) == 32
                and actual['input_hashes'][qid] == [x['input_sha256'] for x in q['pairs']]
                and all(finite(x) for x in actual['scores'][qid]), 'Invalid or mismatched ordered inputs/scores')
    calibration = {q for q in queries if queries[q]['partition'] == 'hardware_calibration'}
    require(len(calibration) == 32 and set(actual['graph_calibration']) == calibration, 'Calibration query census differs')
    boundaries = ('started','inputs_materialized','h2d_submitted','forward_submitted','d2h_submitted','stream_joined','scores_materialized')
    grouped = defaultdict(lambda:defaultdict(list)); seen = set()
    require(len(actual['forwards']) == quality['actual_reference_forwards'] == 320, 'Actual forward census differs')
    for index, forward in enumerate(actual['forwards']):
        qid=forward['query_id']; timing=forward['timing']; engine=forward['engine']; width=timing['batch_size']; position=forward['position']
        require(qid in queries and timing['engine'] == engine and type(width) is int
                and (engine,width) in [('buffered_eager',32),('cuda_graph',32),('cuda_graph',16),('cuda_graph',8)]
                and (engine == 'buffered_eager' or qid in calibration)
                and type(position) is int and position in range(0,32,width)
                and timing['clock_domains_joined'] is False and timing['gpu_exclusive_service_time'] is False,
                'Forward ownership, width or independent clock domain differs')
        key=(engine,width,qid,position);require(key not in seen, 'Duplicate physical forward');seen.add(key)
        stamps=[timing['host_monotonic_ns'][k] for k in boundaries]
        require(all(type(x) is int and x>0 for x in stamps) and sorted(stamps)==stamps and stamps[-1]>stamps[0]
                and all(finite(x) and x>=0 for x in timing['cuda_event_elapsed_ms'].values()), 'Invalid physical clock interval')
        if qid in calibration: grouped[(engine,width)][qid].append((index,position,stamps[0],stamps[-1]))
    expected_forwards={('buffered_eager',32,q,0) for q in queries}
    expected_forwards |= {('cuda_graph',w,q,p) for w in [32,16,8] for q in calibration for p in range(0,32,w)}
    require(seen==expected_forwards, 'Missing physical forward')
    output=[]; mismatch=set();walls={}
    for engine,width in [('buffered_eager',32),('cuda_graph',32),('cuda_graph',16),('cuda_graph',8)]:
        per_query=grouped[(engine,width)];require(set(per_query)==calibration,'Missing calibrated arm')
        durations=[];query_walls=[];sums=[];exact=outside=top10=whole=0;strict_reversals=0
        for qid in sorted(calibration):
            observations=per_query[qid];indices=[r[0] for r in observations]
            require([r[1] for r in observations]==list(range(0,32,width))
                    and indices==list(range(indices[0],indices[0]+len(indices)))
                    and all(observations[i][2]>=observations[i-1][3] for i in range(1,len(observations))), 'Noncontiguous query forward series')
            slices=[(r[3]-r[2])/1e6 for r in observations];durations+=slices;sums.append(sum(slices));query_walls.append((observations[-1][3]-observations[0][2])/1e6)
            target=actual['scores'][qid];values=target if engine=='buffered_eager' else actual['graph_calibration'][qid][str(width)]
            require(len(values)==32 and all(finite(x) for x in values),'Invalid graph score vector')
            ids=[p['doc_id'] for p in queries[qid]['pairs']];order=lambda v: sorted(range(32),key=lambda i:(-v[i],ids[i]))
            top10+=order(values)[:10]==order(target)[:10];whole+=order(values)==order(target)
            for pos,(x,y) in enumerate(zip(values,target)):
                exact+=x==y
                if abs(x-y)>.001+.001*abs(y):
                    outside+=1;mismatch.add((width,qid,pos,x,y))
            strict_reversals+=sum((values[i]-values[j])*(target[i]-target[j])<0 for i in range(32) for j in range(i+1,32))
        if engine=='cuda_graph':walls[width]=query_walls
        output.append({'engine':engine,'documents_per_forward':width,'forward_count':len(durations),'median_forward_host_ms':median(durations),
            'max_forward_host_ms':max(durations),'mean_summed_forward_ms_per_query':mean(sums),'mean_complete_query_host_ms':mean(query_walls),
            'scores_exact_of_1024':exact,'scores_outside_fixed_tolerance':outside,'unchanged_top10_order_of_32_queries':top10,
            'unchanged_full_order_of_32_queries':whole,'strict_order_reversals_of_15872_pairs':strict_reversals})
    declared={(r['shape'],r['query_id'],r['position'],r['actual'],r['reference']) for r in quality['scalar_mismatches']}
    require(len(declared)==len(quality['scalar_mismatches']) and mismatch==declared,'Original scalar failure verdict does not match raw scores')
    for row in output:
        row['mean_complete_query_percent_vs_graph32']=100*(row['mean_complete_query_host_ms']/mean(walls[32])-1)
    return {'run_id':44470392171,'device':'NVIDIA A10','calibration_queries':32,'verified_input_hashes':3072,'actual_forwards':320,
            'mixed_timing_windows_started':0,'qualified_gain':False,'original_reference_qualified':False,'rows':output,
            'scope':'Single allocation and fixed order. Host forward starts before tensor preparation and ends after synchronized CPU-visible scores. Complete-query elapsed includes between-slice time. CUDA and host clocks remain independent. No serving requests or mixed-window utilization were measured.'}


def recompute_rerank(bundle, inputs_zip, self_test=False):
    import zipfile
    require(bundle['schema']=='nodus.full-model.rerank-granularity-selection/1'
            and bundle['run_id']==44470392171 and bundle['scientific_execution'] is True
            and bundle['qualified_gain'] is False and bundle['mixed_timing_windows_started']==0
            and bundle['raw_checkpoints_included'] is False, 'Reranking selection scope differs')
    auth=bundle['authentication'];mr=auth['manifest_utf8'].encode();sr=auth['selection_utf8'].encode()
    require(hashlib.sha256(mr).hexdigest()==auth['manifest_sha256']=='3e80932b7e8016e5638e9008006f61602ff9a82b31c4e2e1cc010e950c00522b'
            and hashlib.sha256(sr).hexdigest()==auth['selection_sha256']=='5b2da1485fcea15bd01d36c329c76d0da3da3852bb0c19161c0bfc08e4c267b6'
            and auth['scientific_artifact']==14505160809 and auth['scientific_artifact_sha256']=='2c13888cae1aa23e9c483162380bb3af1afdce5930a3dccb3aac41d1e6e38212'
            and auth['original_artifact']==14504468340 and auth['whole_original_bytes']==2217987
            and auth['whole_original_sha256']=='eeaddcf0ffe2817061987112872b0c190a6421c3e0fa60921706671a466022a6'
            and auth['full_original_authenticated_at_selection'] is False, 'Preserve actual original and selection-time custody')
    manifest=json.loads(mr);selection=json.loads(sr);binding=manifest['binding']
    require(binding['producer_run_id']=='44470392171' and binding['producer_run_attempt']==1
            and binding['controller_commit']=='c1eafc9c1c8c22e2352c59fabd2091111c8deee0'
            and binding['study_commit']=='94038527b98305522fba12c2e3a5d1cb12b0e68b'
            and binding['workload_profile']=='online-offline-rerank-v1'
            and binding['workload_protocol']=='nodus.warm.rerank-task/1'
            and binding['task_sha256']=='7921844883fcd24413261424390e196db916738ee3ab6978d93d5b607226ac2f'
            and selection['binding']==binding and selection['manifest_sha256']==auth['manifest_sha256']
            and selection['scientific_success'] is False, 'Actual task/manifest identity differs')
    inventory={x['path']:x for x in manifest['files']};selected={x['path'] for x in selection['files'] if x['state']=='selected'}
    require(len(inventory)==len(manifest['files'])==26 and selected=={'suite-start.json','suite-terminal.json','suite.json','reference-quality.json','r0/result.json'},'Selected original census differs')
    rows={}
    for x in bundle['originals']:
        n=x['path'];b=x['utf8'].encode();require(n in selected and n not in rows and len(b)==x['bytes']==inventory[n]['bytes']
            and hashlib.sha256(b).hexdigest()==x['sha256']==inventory[n]['sha256'],'Original reranking bytes differ');rows[n]=json.loads(b)
    require(set(rows)==selected,'Missing original reranking leaf')
    # The public workload kit is byte-pinned and only its inert input identity is read.
    require(Path(inputs_zip).stat().st_size==432258,'Matched input kit size differs')
    raw=Path(inputs_zip).read_bytes();require(len(raw)==432258 and hashlib.sha256(raw).hexdigest()=='d0242f2f4192f97d8d3a9dce59921e74efba3e7fd94f4679bd63185da17e534e','Matched workload kit differs')
    with zipfile.ZipFile(inputs_zip) as z:
        names=z.namelist();require(len(names)==len(set(names))==7,'Workload kit member census differs')
        info=z.getinfo('producer-input-join.json');require(info.file_size==875222,'Input identity size differs');data=z.read(info)
    require(hashlib.sha256(data).hexdigest()=='26ab1c09cf73d3370e6e5b3407bb433b9e54bd60d0b59ea0c74cf38c0bd1826f','Input identity bytes differ')
    identity=json.loads(data);result=rerank_rows(rows,identity)
    result['negative_controls']=rerank_refusal_controls(rows,identity) if self_test else 0
    result['full_original_authenticated_at_selection']=False
    result['public_original_leaves']=5
    return result


def layer32_refusal_controls(rows, identity):
    mutations = [
        lambda r: r['s0a4/foreground.json'].__setitem__(1, copy.deepcopy(r['s0a4/foreground.json'][0])),
        lambda r: r['s0a4/foreground.json'].pop(),
        lambda r: r['s0a4/foreground.json'][0].__setitem__('planned_ns', 0),
        lambda r: r['s0a4/foreground.json'][0].__setitem__('delivered_ns', r['s0a4/foreground.json'][0]['completed_ns']+1),
        lambda r: r['s0a4/foreground.json'][0].__setitem__('completed_ns', float('nan')),
        lambda r: r['s0a4/result.json']['census'].__setitem__('background_complete', 748),
        lambda r: r['suite.json'].__setitem__('performance_claim_eligible', True),
        lambda r: r['s0a4/result.json'].__setitem__('research_source_sha', '0'*40),
        lambda r: r['reference-quality.json'].__setitem__('timed_output_credit', 1),
        lambda r: r['suite.json']['owners'].pop(),
        lambda r: next(iter(r['r0/result.json']['reference_actual']['input_hashes'].values())).__setitem__(0, '0'*64),
        lambda r: r['suite.json']['comparison']['schedules']['smooth']['conditions']['layer-group-b32'].__setitem__('matched_foreground_qualified', True),
        lambda r: next(iter(next(iter(r['r0/result.json']['reference_actual']['layer_calibration'].values())).values()))['background_scores'].__setitem__(0, float('nan')),
    ]
    for mutate in mutations:
        altered=copy.deepcopy(rows);mutate(altered)
        try: layer32_rows(altered, identity)
        except (ValueError,KeyError,TypeError,IndexError): continue
        raise ValueError('Layer-group invalid-evidence control was accepted')
    return len(mutations)


def layer32_rows(rows, identity):
    """Recount recorded host clocks and exact calibration; no model execution."""
    from statistics import mean
    arms=('foreground-only','shared-priority-b32','ordinary-resident-mps-b32',
          'ordinary-opportunistic-query','layer-group-b32')
    protocol='online-offline-rerank-layer32-v1'
    suite=rows['suite.json'];reference=rows['r0/result.json'];quality=rows['reference-quality.json']
    expected=[('reference','reference')]+[('smooth',a) for a in arms]+[('burst',a) for a in reversed(arms)]
    require(suite['status']=='complete' and suite['protocol']==protocol
            and suite['performance_claim_eligible'] is False
            and [(x['schedule'],x['arm']) for x in suite['owners']]==expected
            and all(x['status']=='complete' for x in suite['owners']), 'Layer-group complete owner census differs')
    canonical_task='d537d0a09abab873ffc96c86819c364c222ac26468a0100ff92df461e54716ae'
    require(suite['task_sha256']==reference['task_sha256']==canonical_task
            and reference['status']=='complete' and reference['protocol']==protocol
            and reference['device_name']=='NVIDIA A10' and reference['scientific_acceptance'] is False
            and reference['research_source_sha']=='86cea8e1cf2d8b26e373ef6d51ad0c01be1ff6cd'
            and reference['clients']['engine']['model_revision']=='953dc6f6f85a1b2dbfca4c34a2796e7dde08d41e', 'Layer-group source/model/task differs')
    actual=reference['reference_actual'];cal=actual['layer_calibration'];scores=actual['scores']
    queries={q['query_id']:q for q in identity['queries']}
    require(identity['canonical_task_sha256']==canonical_task and len(queries)==len(identity['queries'])==96
            and set(scores)==set(actual['input_hashes'])==set(queries),'Matched workload identity differs')
    for qid,q in queries.items():
        require(len(q['pairs'])==len(scores[qid])==32 and len({x['doc_id'] for x in q['pairs']})==32
                and actual['input_hashes'][qid]==[x['input_sha256'] for x in q['pairs']]
                and all(type(v) in (int,float) and math.isfinite(v) for v in scores[qid]),'Ordered model inputs/scores differ')
    require(set(cal)=={q for q in queries if queries[q]['partition']=='hardware_calibration'},'Calibration partition differs')
    require(len(cal)==32 and len(scores)==96 and actual['task_sha256']==canonical_task
            and actual['credited_window_outputs']==quality['timed_output_credit']==0
            and quality['qualified'] is True and quality['layer_rankings_qualified'] is True
            and quality['layer_scalar_mismatches']==[] and quality['scalar_mismatches']==[], 'Recorded calibration qualification differs')
    exact=0;trials=0
    for query,cuts in cal.items():
        require(set(cuts)=={'1','2','3','4'} and query in scores,'Four full-width calibration cuts required')
        for cut,row in cuts.items():
            fg=row['foreground_query_id'];require(fg in scores,'Unknown interposed query')
            for name,q in [('background_scores',query),('foreground_scores',fg)]:
                values=row[name];require(len(values)==len(scores[q])==32,'Full-width score census differs')
                for a,b in zip(values,scores[q]):
                    require(type(a) in (int,float) and type(b) in (int,float) and math.isfinite(a) and math.isfinite(b) and a==b,'Exact resumed/interposed score differs');exact+=1
            groups=row['groups'];require(len(groups)==4 and [g['group'] for g in groups]==list(range(4)),'Physical group census differs')
            require(all(type(g[k]) is int for g in groups for k in ('started_ns','drained_ns','returned_ns'))
                    and all(g['started_ns']<=g['drained_ns']<=g['returned_ns'] for g in groups), 'Physical group clock order differs')
            trials+=1
    require(trials==quality['layer_trials']==128 and exact==8192 and quality['layer_groups']==512,'Calibration denominator differs')
    require(suite['comparison']['both_schedules_eligible'] is False and suite['comparison']['production_traffic_claim'] is False,'No eligible mixed gain may be promoted')
    schedules={};total=0
    def distribution(values):
        require(values and all(type(v) in (int,float) and math.isfinite(v) and v>=0 for v in values),'Invalid measured interval')
        ordered=sorted(values)
        return {'mean_ms':mean(values),'p50_ms':ordered[math.ceil(len(values)*.5)-1],
                'p95_ms':ordered[math.ceil(len(values)*.95)-1],'max_ms':ordered[-1]}
    for si,schedule in enumerate(('smooth','burst')):
        recorded=suite['comparison']['schedules'][schedule];require(set(recorded['conditions'])==set(arms),'Schedule condition census differs')
        solo=recorded['conditions']['foreground-only']['foreground_p95_s'];conditions={}
        require(recorded['comparison_eligible'] is False and recorded['strongest_qualified_ordinary'] is None
                and recorded['candidate_to_strongest_completed_query_rate'] is None,'No qualified ordinary baseline exists')
        for ai,arm in enumerate(arms):
            run=rows[f's{si}a{ai}/result.json'];requests=rows[f's{si}a{ai}/foreground.json'];census=run['census'];window=run['window']
            require(run['schema']=='nodus.online-offline-rerank.condition/1' and run['protocol']==protocol
                    and run['arm']==arm and run['schedule']==schedule and run['status']=='complete'
                    and run['task_sha256']==canonical_task and run['research_source_sha']==reference['research_source_sha']
                    and run['task_file_sha256']==reference['task_file_sha256'] and run['score_cache_allowed'] is False
                    and run['scientific_acceptance'] is False and len(requests)==600,'Actual condition identity/census differs')
            origin=window['origin_ns'];require(type(origin) is int and window['background_end_ns']==origin+300_000_000_000
                    and window['foreground_drain_end_ns']==origin+305_000_000_000,'Fixed window and drain differ')
            for i,row in enumerate(requests):
                offset=i*500_000_000 if schedule=='smooth' else (i//6)*3_000_000_000
                require(row['index']==i and all(type(row[k]) is int for k in ('planned_ns','arrival_observed_ns','delivered_ns','completed_ns','deadline_ns'))
                        and row['planned_ns']==origin+offset and row['deadline_ns']==row['planned_ns']+5_000_000_000
                        and row['planned_ns']<=row['arrival_observed_ns']<=row['delivered_ns']<=row['completed_ns']<=row['deadline_ns']
                        and row['completed_ns']==census['completed_ns'][f'online-{i:04d}'],'Exact offered request/host clock join differs')
            require({k for k in census['completed_ns'] if k.startswith('online-')}=={f'online-{i:04d}' for i in range(600)},'Foreground ownership differs')
            require(all(type(v) is int and v>=origin and (k.startswith('online-') or k.startswith('offline-')) for k,v in census['completed_ns'].items()),'Completion ownership/clock differs')
            bg=sum(k.startswith('offline-') and origin<=v<=window['background_end_ns'] for k,v in census['completed_ns'].items())
            require(bg==census['background_complete'] and census['foreground_on_time']==600,'On-time output census differs')
            quality_fg=census['ranking_quality']['foreground'];require(quality_fg['qualified'] is True and quality_fg['complete_queries']==600,'Recorded foreground quality differs')
            if bg:require(census['ranking_quality']['background']['qualified'] is True and census['ranking_quality']['background']['complete_queries']==bg,'Recorded background quality differs')
            measured={name:distribution([(row[end]-row[start])/1e6 for row in requests]) for name,start,end in
                      [('offer_to_delivery','planned_ns','delivered_ns'),('delivery_to_output','delivered_ns','completed_ns'),('offer_to_output','planned_ns','completed_ns')]}
            result=recorded['conditions'][arm];p95=measured['offer_to_output']['p95_ms']/1000
            near(p95,result['foreground_p95_s']);require(result['background_complete']==bg and result['foreground_on_time']==result['foreground_complete']==result['foreground_offered']==600,'Recorded aggregate differs')
            qualified=p95<=1.05*solo;require(result['matched_foreground_qualified'] is qualified and qualified==(arm=='foreground-only'),'Preserve actual relative foreground failure')
            conditions[arm]={'requests':600,'on_time_within_five_seconds':600,'background_complete':bg,
                'background_queries_per_window_second':bg/300,'relative_foreground_qualified':qualified,
                'relative_p95_change_percent':(p95/solo-1)*100,'recorded_numerical_and_relevance_pass':True,
                'posthoc_complete_within_ms':{str(ms):sum(row['completed_ns']-row['planned_ns']<=ms*1_000_000 for row in requests) for ms in (250,300,1500)},**measured}
            total+=600
        candidate=conditions['layer-group-b32'];whole=conditions['ordinary-opportunistic-query']
        schedules[schedule]={'solo_p95_limit_ms':solo*1050,'conditions':conditions,
            'candidate_vs_whole_query_waiting_ratio':whole['offer_to_delivery']['p95_ms']/candidate['offer_to_delivery']['p95_ms'],
            'candidate_vs_whole_query_response_reduction_percent':100*(1-candidate['offer_to_output']['p95_ms']/whole['offer_to_output']['p95_ms']),
            'candidate_vs_whole_query_background_change_percent':100*(candidate['background_complete']/whole['background_complete']-1),
            'strongest_measured_mix_by_response_p95':min(arms[1:],key=lambda a:conditions[a]['offer_to_output']['p95_ms']),
            'qualified_mixed_gain':False}
    require(total==6000,'All-offer denominator differs')
    return {'run_id':44480508310,'calibration_trials':trials,'exact_resumed_and_interposed_scores':exact,
            'verified_input_hashes':3072,'completed_windows':10,'foreground_offered':total,'foreground_on_time':total,'schedules':schedules,
            'qualified_gain':False,'allocation_normalized_or_cost_claim':False,
            'clock_scope':'Host offer to engine delivery and offer to final output; stage percentiles are not additive. Recorded quality verdicts are preserved, not a new model or relevance execution.'}


def recompute_layer32(bundle, inputs_zip, self_test=False):
    import zipfile
    require(bundle['schema']=='nodus.full-model.rerank-layer32-selection/1' and bundle['run_id']==44480508310
            and bundle['scientific_execution'] is True and bundle['qualified_gain'] is False
            and bundle['mixed_timing_windows_completed']==10 and bundle['raw_checkpoints_included'] is False,'Layer-group selection scope differs')
    auth=bundle['authentication'];mr=auth['manifest_utf8'].encode();sr=auth['selection_utf8'].encode()
    require(hashlib.sha256(mr).hexdigest()==auth['manifest_sha256']=='5a3294a8a0e7f41473e1f76d3960237972d24f99c06275a205ddcb5d1edbd3d0'
            and hashlib.sha256(sr).hexdigest()==auth['selection_sha256']=='5b5e6ec129a31331ebe79dfcf042e6677c00715312a66babe376e02e64a62492'
            and auth['scientific_artifact']==14511957138 and auth['scientific_artifact_sha256']=='07068b26f2ddb0aecc043aa1313352ba94f69abb709230d38030737e4696cb44'
            and auth['original_artifact']==14511324078 and auth['whole_original_bytes']==62159268
            and auth['whole_original_sha256']=='87cbca36e2c425e96fdb0d8f9e6c97056c270790051b952fdb90796252c9ddd1'
            and auth['full_original_authenticated_at_selection'] is False,'Actual original/selection-time custody differs')
    manifest=json.loads(mr);selection=json.loads(sr);binding=manifest['binding']
    require(binding['producer_run_id']=='44480508310' and binding['producer_run_attempt']==1
            and binding['controller_commit']=='fb1ef8484c223e0e167022584f85f89a747c01a9'
            and binding['study_commit']=='86cea8e1cf2d8b26e373ef6d51ad0c01be1ff6cd'
            and binding['task_sha256']=='75d909c7715dca15775e970b22e746c830f1590aa87f9de7666e9b6f692d9be9'
            and binding['workload_profile']=='online-offline-rerank-layer32-v1'
            and binding['workload_protocol']=='nodus.warm.rerank-task/1'
            and selection['binding']==binding and selection['manifest_sha256']==auth['manifest_sha256'],'Actual layer-group producer tuple differs')
    selected={x['path'] for x in selection['files'] if x['state']=='selected'}
    expected={'suite-start.json','suite-terminal.json','suite.json','reference-quality.json','r0/result.json'}|{f's{s}a{a}/{n}.json' for s in range(2) for a in range(5) for n in ('result','foreground')}
    inventory={x['path']:x for x in manifest['files']};require(len(inventory)==len(manifest['files'])==250 and selected==expected,'Complete selected science census differs')
    rows={}
    for x in bundle['originals']:
        n=x['path'];b=x['utf8'].encode();require(n in selected and n not in rows and len(b)==x['bytes']==inventory[n]['bytes']
            and hashlib.sha256(b).hexdigest()==x['sha256']==inventory[n]['sha256'],'Original layer-group bytes differ');rows[n]=json.loads(b)
    require(set(rows)==selected,'Missing layer-group scientific report')
    # The public workload kit is byte-pinned and only its inert input identity is read.
    require(Path(inputs_zip).stat().st_size==432258,'Matched input kit size differs')
    raw=Path(inputs_zip).read_bytes();require(len(raw)==432258 and hashlib.sha256(raw).hexdigest()=='d0242f2f4192f97d8d3a9dce59921e74efba3e7fd94f4679bd63185da17e534e','Matched workload kit differs')
    with zipfile.ZipFile(inputs_zip) as z:
        names=z.namelist();require(len(names)==len(set(names))==7,'Workload kit member census differs')
        info=z.getinfo('producer-input-join.json');require(info.file_size==875222,'Input identity size differs');data=z.read(info)
    require(hashlib.sha256(data).hexdigest()=='26ab1c09cf73d3370e6e5b3407bb433b9e54bd60d0b59ea0c74cf38c0bd1826f','Input identity bytes differ')
    identity=json.loads(data);result=layer32_rows(rows,identity);result['negative_controls']=layer32_refusal_controls(rows,identity) if self_test else 0
    result['public_original_leaves']=25;result['full_original_authenticated_at_selection']=False
    return result


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('selected_json', type=Path)
    parser.add_argument('--self-test', action='store_true')
    parser.add_argument('--native-selected-json', type=Path)
    parser.add_argument('--native-controls-gzip', type=Path)
    parser.add_argument('--native-complete-gzip', type=Path)
    parser.add_argument('--permit-gzip', type=Path)
    parser.add_argument('--whole-step-gzip', type=Path)
    parser.add_argument('--whole-step-grants-gzip', type=Path)
    parser.add_argument('--sqrt-partition-gzip', type=Path)
    parser.add_argument('--routing-invalid-gzip', type=Path)
    parser.add_argument('--optimizer-gzip', type=Path)
    parser.add_argument('--routing-preparation-gzip', type=Path)
    parser.add_argument('--rerank-granularity-gzip', type=Path)
    parser.add_argument('--rerank-inputs-zip', type=Path)
    parser.add_argument('--rerank-layer32-gzip', type=Path)
    args = parser.parse_args()
    require(args.selected_json.stat().st_size <= 2*1024*1024, 'Selection exceeds fixed 2 MiB bound')
    bundle = json.loads(args.selected_json.read_bytes())
    result = recompute(bundle)
    if args.self_test: result['negative_controls'] = controls(bundle)
    if args.native_selected_json:
        require(args.native_selected_json.stat().st_size <= 1024*1024, 'Native selection exceeds 1 MiB')
        native = json.loads(args.native_selected_json.read_bytes())
        result['native_component'] = recompute_native(native)
        if args.self_test: result['native_component']['negative_controls'] = native_controls(native)
    if args.native_controls_gzip:
        require(args.native_controls_gzip.stat().st_size <= 1024*1024, 'Control gzip exceeds 1 MiB')
        with gzip.open(args.native_controls_gzip, 'rb') as source:
            raw = source.read(2*1024*1024+1)
        require(len(raw) <= 2*1024*1024, 'Control JSON exceeds 2 MiB')
        result['native_completed_controls'] = recompute_completed_controls(json.loads(raw), args.self_test)
    if args.native_complete_gzip:
        require(args.native_complete_gzip.stat().st_size <= 1024*1024, 'Complete gzip exceeds 1 MiB')
        with gzip.open(args.native_complete_gzip, 'rb') as source:
            raw = source.read(2*1024*1024+1)
        require(len(raw) <= 2*1024*1024, 'Complete JSON exceeds 2 MiB')
        result['native_complete_comparison'] = recompute_native_complete(json.loads(raw), args.self_test)
    if args.permit_gzip:
        require(args.permit_gzip.stat().st_size <= 1024*1024, 'Permit gzip exceeds 1 MiB')
        with gzip.open(args.permit_gzip, 'rb') as source:
            raw = source.read(4*1024*1024+1)
        require(len(raw) <= 4*1024*1024, 'Permit JSON exceeds 4 MiB')
        result['permit_incomplete'] = recompute_permit(json.loads(raw), args.self_test)
    if args.whole_step_gzip:
        require(args.whole_step_gzip.stat().st_size <= 1024*1024, 'Whole-step gzip exceeds 1 MiB')
        with gzip.open(args.whole_step_gzip, 'rb') as source:
            raw = source.read(2*1024*1024+1)
        require(len(raw) <= 2*1024*1024, 'Whole-step JSON exceeds 2 MiB')
        whole_bundle = json.loads(raw)
        result['whole_step_component'] = recompute_whole_step(whole_bundle, args.self_test)
    if args.whole_step_grants_gzip:
        require(args.whole_step_gzip is not None, 'Authenticate whole-step selected manifest before raw companion')
        require(args.whole_step_grants_gzip.stat().st_size <= 4*1024*1024, 'Whole-step raw gzip exceeds 4 MiB')
        with gzip.open(args.whole_step_grants_gzip, 'rb') as source:
            raw = source.read(24*1024*1024+1)
        require(len(raw) <= 24*1024*1024, 'Whole-step raw JSON exceeds 24 MiB')
        result['whole_step_raw'] = recompute_whole_step_grants(raw, whole_bundle, args.self_test)
    if args.sqrt_partition_gzip:
        require(args.sqrt_partition_gzip.stat().st_size <= 1024*1024, 'Partition gzip exceeds 1 MiB')
        with gzip.open(args.sqrt_partition_gzip, 'rb') as source:
            raw = source.read(2*1024*1024+1)
        require(len(raw) <= 2*1024*1024, 'Partition JSON exceeds 2 MiB')
        result['sqrt_partition_component'] = recompute_sqrt_partition(json.loads(raw), args.self_test)
    if args.routing_invalid_gzip:
        require(args.routing_invalid_gzip.stat().st_size <= 1024*1024, 'Routing selection gzip exceeds 1 MiB')
        with gzip.open(args.routing_invalid_gzip, 'rb') as source:
            raw = source.read(4*1024*1024+1)
        require(len(raw) <= 4*1024*1024, 'Routing selection JSON exceeds 4 MiB')
        result['routing_invalid_control'] = recompute_routing_invalid(json.loads(raw), args.self_test)
    if args.optimizer_gzip:
        require(args.optimizer_gzip.stat().st_size <= 1024*1024, 'Optimizer gzip exceeds 1 MiB')
        with gzip.open(args.optimizer_gzip, 'rb') as source:
            raw = source.read(2*1024*1024+1)
        require(len(raw) <= 2*1024*1024, 'Optimizer JSON exceeds 2 MiB')
        result['optimizer_operation'] = recompute_optimizer(json.loads(raw), args.self_test)
    if args.routing_preparation_gzip:
        require(args.routing_preparation_gzip.stat().st_size <= 1024*1024, 'Preparation gzip exceeds 1 MiB')
        with gzip.open(args.routing_preparation_gzip, 'rb') as source:
            raw = source.read(2*1024*1024+1)
        require(len(raw) <= 2*1024*1024, 'Preparation JSON exceeds 2 MiB')
        result['routing_preparation'] = recompute_routing_preparation(json.loads(raw), args.self_test)
    if args.rerank_granularity_gzip:
        require(args.rerank_inputs_zip is not None, 'Matched input kit is required')
        require(args.rerank_granularity_gzip.stat().st_size <= 1024*1024, 'Reranking gzip exceeds 1 MiB')
        with gzip.open(args.rerank_granularity_gzip, 'rb') as source:
            raw = source.read(2*1024*1024+1)
        require(len(raw) <= 2*1024*1024, 'Reranking JSON exceeds 2 MiB')
        result['rerank_granularity'] = recompute_rerank(json.loads(raw), args.rerank_inputs_zip, args.self_test)
    else:
        require(args.rerank_inputs_zip is None or args.rerank_layer32_gzip is not None, 'Input kit requires reranking selection')
    if args.rerank_layer32_gzip:
        require(args.rerank_inputs_zip is not None, 'Matched input kit is required')
        require(args.rerank_layer32_gzip.stat().st_size <= 2*1024*1024, 'Layer-group gzip exceeds 2 MiB')
        with gzip.open(args.rerank_layer32_gzip, 'rb') as source:
            raw = source.read(4*1024*1024+1)
        require(len(raw) <= 4*1024*1024, 'Layer-group JSON exceeds 4 MiB')
        result['rerank_layer32'] = recompute_layer32(json.loads(raw), args.rerank_inputs_zip, args.self_test)
    print(json.dumps(result, indent=2, sort_keys=True))
