"""Recompute public scalar/inventory consistency; no original-artifact claim.

Download this script and coalescing-feasibility-attempts.json together, then run:
python3 coalescing-feasibility-recompute.py coalescing-feasibility-attempts.json
With no argument, the script uses that JSON filename beside itself.
"""
import hashlib
import json
from pathlib import Path
import sys

p = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).with_name('coalescing-feasibility-attempts.json')
v = json.loads(p.read_bytes())
assert v['schema'] == 'nodus.coalescing-campaign-attempts/0.3'
assert v['performance_claim_eligible'] is False and len(v['observations']) == 4
first, second, third, no_launch, *transport_attempts = v['attempts']
assert [a['run_id'] for a in transport_attempts] == [43143219462,43151268293]
for attempt, timeout, custody_hash in zip(transport_attempts,[299.999968543,299.9999893940002],['113d54176e45f964a87e94b62f1173dd929f7cd09ea5cb2c23630ec55f952eed', '620c366d4f1b750a00dded9f4ca1ed1defefaa7cfedd6d00465e394b3fa6d742']):
    assert attempt['controller_revision'] == 'ee2753834702b7ab1a1b12aaeac4caed2328fbdf'
    assert attempt['study_revision'] == '9e7fb29208a90c99a4b31d36d40ddca2285385a2'
    assert attempt['classification'] == 'input_scp_timeout_before_host_workload' and attempt['workflow_conclusion'] == 'failure'
    assert attempt['provider_execution_started'] is attempt['gpu_device_probe_observed'] is True
    assert attempt['host_workload_started'] is attempt['performance_claim_eligible'] is False
    assert attempt['numerical_cells_observed'] == attempt['runtime_phase_events_observed'] == attempt['park_memory_samples_observed'] == 0
    assert attempt['observations'] == []
    assert attempt['hardware_observed'] == {'name':'NVIDIA A10','driver':'570.148.08','memory_mib':23028,'physical_gpu_count':1}
    failure = attempt['failure']
    assert failure['stage'] == 'recursive_input_scp' and failure['error_type'] == 'TimeoutExpired'
    assert failure['timeout_s'] == timeout and failure['raw_log_public'] is False
    assert failure['actual_transferred_bytes'] is failure['actual_transfer_rate'] is failure['underlying_cause'] is None
    assert (failure['controller_failure_line'],failure['subsequent_host_execution_line'],failure['raw_log_exception_line']) == (407,412,641)
    retention = attempt['retention']
    assert hashlib.sha256(json.dumps({'retention':retention,'raw_log':failure['raw_log']},sort_keys=True,separators=(',',':')).encode()).hexdigest() == custody_hash
    assert retention['result_tar_regular_files'] == 0
    inventory = {r['path']:r for r in retention['outer_inventory']}
    assert len(inventory) == len(retention['outer_inventory']) == 12
    assert set(inventory) == {'cleanup.json','coalescing-collection.command.json','coalescing-collection.stderr','coalescing-deadlines.json','coalescing-stage.json','collection-error.json','gpu-device-probe.log','gpu-results.tar','launch.json','mixed-allocation.json','reservation.json','termination.json'}
    assert all(r['payload_public'] is False and type(r['bytes']) is int and r['bytes'] >= 0 and len(r['sha256']) == 64 for r in inventory.values())
    assert inventory['gpu-results.tar']['bytes'] == 10240 and inventory['gpu-results.tar']['sha256'] == '84ff92691f909a05b224e1c56abb4864f01b4f8e3c854e4bb4c7baf1d3f6d652'
    assert retention['controller_source'] == {'path':'.github/scripts/utilization_gpu_trial.py','bytes':42038,'sha256':'0d2740a8ade577f8c7275c484fbb920e9ef404a3367c413249c2848a6bfbf266'}
    cleanup, accounting = attempt['cleanup'], attempt['accounting']
    assert cleanup['provider_direct_get_terminated'] is cleanup['task_key_deleted'] is True
    assert cleanup['guard_conclusion'] == 'cancelled' and cleanup['provider_final_invoice_known'] is False
    assert all(accounting[k] is False for k in ['controller_interval_is_billing_interval','provider_billing_start_known','provider_final_invoice_known'])
    assert accounting['physical_gpu_allocation_interval'] is accounting['invoice_usd'] is None
    from datetime import datetime
    assert accounting['controller_reservation_to_cleanup_s'] == (datetime.fromisoformat(cleanup['provider_cleanup_observed_at'])-datetime.fromisoformat(accounting['reservation_started_at'])).total_seconds()
    assert accounting['quoted_price_cents_per_hour'] == 129
assert first['run_id'] == 43050913017 and second['run_id'] == 43052734432
assert first['provider_execution_started'] is False
assert first['failed_step']['conclusion'] == 'failure'
assert first['provider_step']['conclusion'] == 'skipped'
assert first['numerical_cells_observed'] == second['numerical_cells_observed'] == 0
assert any(x['initial_source_sha256'] != x['expected_sha256'] for x in first['input_source_hashes'])
assert all(x['corrected_source_sha256'] == x['expected_sha256'] for x in first['input_source_hashes'])
commands = {r['operation']: r for r in second['commands']}
assert len(commands) == len(second['commands'])
assert commands['runtime-start']['returncode'] == 0
assert commands['namespace-create']['returncode'] == 1
delta = commands['namespace-create']['started_unix_s'] - commands['runtime-start']['ended_unix_s']
assert delta == second['failure']['seconds_after_systemctl_start_return']
error = (second['failure']['message'] + '\n').encode()
assert len(error) == commands['namespace-create']['stderr_bytes']
assert hashlib.sha256(error).hexdigest() == commands['namespace-create']['stderr_sha256']
assert second['failure']['cause_established'] is False
assert second['runtime_qualified'] is second['image_import_observed'] is second['cuda_workload_observed'] is False
assert second['park_memory_samples_observed'] == 0
rows = second['retained_files']
assert len(rows) == len({x['path'] for x in rows}) == second['retention']['member_count'] == 75
assert not any(x['path'].startswith('cells/') or x['path'] == 'feasibility-result.json' for x in rows)
for row in rows:
    assert type(row['bytes']) is int and row['bytes'] >= 0
    assert len(row['sha256']) == 64 and all(c in '0123456789abcdef' for c in row['sha256'])
inventory = {row['path']: row for row in rows}
for command in commands.values():
    stem = 'host/' + command['operation']
    assert inventory[stem + '.command.json']['sha256'] == command['raw_command_sha256']
    for channel in ('stdout', 'stderr'):
        # Presence is required: an omitted stream is not an observed empty stream.
        stream = inventory[stem + '.' + channel]
        assert (stream['bytes'], stream['sha256']) == (command[channel + '_bytes'], command[channel + '_sha256'])
cleanup = second['cleanup']
assert cleanup['owned_final_unit_state'] == 'failed' and cleanup['owned_final_main_pid'] == 0
assert cleanup['final_context_query_returncode'] == 0 and cleanup['final_context_count'] == 0
assert cleanup['provider_direct_get_terminated'] is cleanup['task_key_deleted'] is True
assert cleanup['guard_conclusion'] == 'cancelled' and cleanup['provider_final_invoice_known'] is False
assert third['run_id'] == 43064953799
assert third['study_revision'] == '50bf946c730839e0dd47a1894437da11def5d5f7'
assert third['controller_revision'] == 'f7df509efa282a0b58006852a10b8f0ab6cf4766'
assert third['numerical_cells_observed'] == third['park_memory_samples_observed'] == 0
assert third['cuda_workload_observed'] is third['runtime_qualified'] is third['suite_returned'] is False
assert third['runtime_readiness']['ready'] is True
assert third['failure']['cause_established'] is False and third['failure']['parsed_image_rows'] == 0
assert third['imported_identity_verified'] is False
commands3 = {r['operation']: r for r in third['commands']}
assert len(commands3) == len(third['commands']) == 32
rows3 = third['retained_files']
inventory3 = {r['path']: r for r in rows3}
assert len(rows3) == len(inventory3) == third['retention']['member_count'] == 100
assert not any(r['path'].startswith('cells/') or r['path'] == 'feasibility-result.json' for r in rows3)
for row in rows3:
    assert type(row['bytes']) is int and row['bytes'] >= 0
    assert len(row['sha256']) == 64 and all(c in '0123456789abcdef' for c in row['sha256'])
sources = {r['path']: r for r in third['source_files']}
assert sources['host.py']['sha256'] == '8c53d00bf16af445b8a909bd3ba0f938662b710927d7fef8856b7a6c4264bf39'
# One frozen source-bound sink, not a generic exception for missing streams.
omitted, = third['omitted_command_streams']
omitted_path = 'host/image-decompress.stdout'
expected_image = (17087502848, '0c0fdcde652236d863fd0c9dc49cebd10ed750db893d980398b7b656f09ccbb7')
assert omitted['path'] == omitted_path and omitted_path not in inventory3
assert omitted['retained'] is False and omitted['independently_byte_verified'] is False
assert (omitted['recorded_bytes'], omitted['recorded_sha256']) == expected_image
streams_checked = 0
for command in commands3.values():
    stem = 'host/' + command['operation']
    assert inventory3[stem + '.command.json']['sha256'] == command['raw_command_sha256']
    for channel in ('stdout', 'stderr'):
        path = stem + '.' + channel
        expected = (command[channel + '_bytes'], command[channel + '_sha256'])
        if path == omitted_path:
            assert expected == expected_image
            continue
        stream = inventory3[path]
        assert (stream['bytes'], stream['sha256']) == expected
        streams_checked += 1
assert streams_checked == 63
for operation in ('runtime-start','runtime-api-version','namespace-create','image-import','image-list'):
    assert commands3[operation]['returncode'] == 0
header = third['failure']['image_list_stdout'].encode()
assert header == b'REF TYPE DIGEST SIZE PLATFORMS LABELS \n'
assert (len(header), hashlib.sha256(header).hexdigest()) == (
    commands3['image-list']['stdout_bytes'], commands3['image-list']['stdout_sha256'])
cleanup3 = third['cleanup']
assert cleanup3['owned_unit_stopped'] is True and cleanup3['owned_final_main_pid'] == 0
assert cleanup3['final_context_query_returncode'] == cleanup3['final_context_count'] == 0
assert cleanup3['provider_direct_get_terminated'] is cleanup3['task_key_deleted'] is True
assert cleanup3['guard_conclusion'] == 'cancelled' and cleanup3['provider_final_invoice_known'] is False
# Separate hosted diagnostic: no fourth GPU attempt or numerical observation.
diagnostic, = v['diagnostics']
assert diagnostic['run_id'] == 43073145308 and diagnostic['historical_attempt_run_id'] == 43064953799
assert diagnostic['source_revision'] == 'c7927fb5865e3651fd5d76056b467466ed667a65'
assert diagnostic['workflow_conclusion'] == 'success'
diagnostic_sources = {r['path']:r for r in diagnostic['source_files']}
assert diagnostic_sources['utilization_lab/bench/coalescing/import_diagnostic.py']['sha256'] == 'b2b0730ff3905c20c71cc9cb08fa77f1ea582c7515c7054c5e5643a0bbd24f62'
for key in ('gpu_execution','image_process_executed','provider_action','runtime_or_quality_qualified'):
    assert diagnostic[key] is False
for key in ('numerical_cells_observed','park_memory_samples_observed','policy_cells_observed'):
    assert diagnostic[key] == 0
commands4 = {r['operation']:r for r in diagnostic['commands']}
inventory4 = {r['path']:r for r in diagnostic['retained_files']}
assert len(commands4) == len(diagnostic['commands']) == 28
assert len(inventory4) == len(diagnostic['retained_files']) == 100
omitted4, = diagnostic['omitted_command_streams']
assert omitted4['path'] == 'runtime/image-decompress.stdout' and omitted4['path'] not in inventory4
assert omitted4['retained'] is False and omitted4['independently_byte_verified'] is False
assert (omitted4['recorded_bytes'],omitted4['recorded_sha256']) == expected_image
streams4 = 0
for row in inventory4.values():
    assert type(row['bytes']) is int and row['bytes'] >= 0
    assert len(row['sha256']) == 64 and all(c in '0123456789abcdef' for c in row['sha256'])
for command in commands4.values():
    assert command['returncode'] == 0 and command['error_type'] is None
    stem = 'runtime/' + command['operation']
    assert inventory4[stem+'.command.json']['sha256'] == command['raw_command_sha256']
    for channel in ('stdout','stderr'):
        path = stem + '.' + channel
        expected = (command[channel+'_bytes'],command[channel+'_sha256'])
        if path == omitted4['path']:
            assert expected == expected_image
        else:
            stream = inventory4[path]
            assert (stream['bytes'],stream['sha256']) == expected
            streams4 += 1
assert streams4 == 55
original = diagnostic['original_control']
assert original['flags'] == ['images','import','--local','--platform','linux/amd64']
assert original['returncode'] == original['parsed_image_rows'] == 0
assert original['header_only_reproduced'] is True
original_stdout = original['image_list_stdout'].encode()
assert original_stdout == b'REF TYPE DIGEST SIZE PLATFORMS LABELS \n'
assert (len(original_stdout),hashlib.sha256(original_stdout).hexdigest()) == (commands4['original-list']['stdout_bytes'],commands4['original-list']['stdout_sha256'])
archive = diagnostic['archive_metadata']
assert archive['repo_tags'] is None
manifest, = archive['index']['manifests']
assert not manifest.get('annotations')
assert (archive['decoded_bytes'],archive['decoded_sha256']) == expected_image
assert archive['decoded_bytes_retained_in_this_public_download'] is False
assert archive['decoded_bytes_independently_rehashed_from_retained_artifact'] is False
registration = diagnostic['explicit_registration']
assert registration['flags'] == ['images','import','--local','--digests','--no-unpack','--platform','linux/amd64']
assert registration['returncode'] == 0 and registration['identity_verified'] is True
assert registration['registry_manifest_equality_claimed'] is False
assert registration['target_digest'] == manifest['digest'] == 'sha256:'+registration['imported_manifest_sha256']
assert registration['config_digest'] == archive['config_digest'] == 'sha256:'+registration['imported_config_sha256']
assert registration['config_digest'] == 'sha256:33bdae5111bb00c87d72f41dd4f0cde140ae8df75cf958649b21d1379b568bf1'
for filename, key in [('runtime/imported-manifest.stdout','imported_manifest_sha256'),('runtime/imported-config.stdout','imported_config_sha256')]:
    assert inventory4[filename]['sha256'] == registration[key]
registered = registration['image_list_stdout'].encode()
assert (len(registered),hashlib.sha256(registered).hexdigest()) == (commands4['digest-list']['stdout_bytes'],commands4['digest-list']['stdout_sha256'])
assert len(registered.splitlines()) == 2
assert registration['target_digest'].encode() in registered.splitlines()[1]
diffids = registration['ordered_diff_ids'];layers = registration['ordered_layer_descriptors']
assert len(diffids) == len(layers) == archive['docker_layer_count'] == 23
assert diffids == [row['digest'] for row in layers]
assert all(row['mediaType'] == 'application/vnd.oci.image.layer.v1.tar' for row in layers)
chain = diffids[0]
for layer in diffids[1:]:
    chain = 'sha256:'+hashlib.sha256((chain+' '+layer).encode()).hexdigest()
unpack = diagnostic['unpack']
assert unpack['same_combined_host_import_command'] is False
assert unpack['separate_read_only_mount_command'] is unpack['unpack_verified'] is True
assert unpack['expected_chain_id'] == unpack['observed_mount_chain_id'] == chain
assert unpack['uncompressed_layer_bytes'] == sum(row['size'] for row in layers)
reference = ('local/nodus-coalescing@'+registration['target_digest'])
assert unpack['complete_unpacked_reference'] == reference
reference_bytes = (reference+'\n').encode()
assert (len(reference_bytes),hashlib.sha256(reference_bytes).hexdigest()) == (commands4['unpacked-record']['stdout_bytes'],commands4['unpacked-record']['stdout_sha256'])
cleanup4 = diagnostic['cleanup']
assert cleanup4['unmount_command_returncode'] == cleanup4['owned_final_main_pid'] == 0
assert cleanup4['owned_final_unit_state'] == 'inactive'
assert cleanup4['host_reported_mount_absent'] is cleanup4['owned_unit_stopped'] is cleanup4['cleanup_confirmed'] is True
assert cleanup4['provider_release_not_applicable'] is True

# Appended to the unchanged historical public checks; no workload imports.
import math
import struct

assert len(v['observations']) == 4
observation = v['observations'][0]
assert observation['run_id'] == 43079070680
assert observation['controller_revision'] == 'fcccd9937a09dd91812cef1800cf7a827d6f3960'
assert observation['study_revision'] == '10b688e64309b8a992dbab94e20c9f756588a87d'
assert observation['qualified'] is observation['performance_claim_eligible'] is observation['cause_established'] is False
assert observation['failure']['classification'] == 'runtime_failure_not_numerical_rejection'
assert observation['failure']['underlying_error_message_retained'] is False
files5 = observation['retained_files']
inventory5 = {r['path']: r for r in files5}
assert len(inventory5) == len(files5) == 407
commands5 = observation['host_commands']
assert len({r['operation'] for r in commands5}) == len(commands5) == 39
omission5, = observation['omitted_command_streams']
assert omission5['path'] == 'results/coalescing/host/image-decompress.stdout'
assert (omission5['recorded_bytes'], omission5['recorded_sha256']) == expected_image
assert omission5['retained'] is omission5['independently_byte_verified'] is False
assert omission5['path'] not in inventory5
streams5 = 0
for command in commands5:
    stem = 'results/coalescing/host/' + command['operation']
    assert command['raw_command_path'] == stem + '.command.json'
    assert inventory5[command['raw_command_path']]['sha256'] == command['raw_command_sha256']
    for channel in ('stdout', 'stderr'):
        path = stem + '.' + channel
        pair = command[channel + '_bytes'], command[channel + '_sha256']
        if path == omission5['path']:
            assert pair == expected_image
        else:
            assert pair == (inventory5[path]['bytes'], inventory5[path]['sha256'])
            streams5 += 1
assert streams5 == 77
staged = {r['name']: r for r in observation['staged_files']}
assert len(observation['source_files']) == 9
for source in observation['source_files']:
    row = staged[source['path'].rsplit('/', 1)[1]]
    assert source['revision'] == observation['study_revision']
    assert (source['bytes'], source['sha256']) == (row['bytes'], row['sha256'])
cells = observation['cells']
assert len(cells) == 12
assert sorted(c['status'] for c in cells.values()) == ['complete'] * 5 + ['failed'] + ['not_started'] * 6
update_count = state_count = 0
for name, cell in cells.items():
    if cell['status'] == 'not_started':
        assert cell == {'status': 'not_started'}
        continue
    identity = cell['identity']
    assert identity['torch'] == '2.7.1+cu128' and identity['cuda'] == '12.8'
    assert identity['contract_sha256'] == staged['workload.json']['sha256']
    assert identity['model_sha256'] == staged['model_317ed.py']['sha256']
    assert identity['train_sha256'] == staged['train.bin']['sha256']
    assert cell['result']['performance_claim_eligible'] is False
    updates = cell['updates']
    expected_n = 8 if cell['status'] == 'failed' else 16
    assert len(updates) == expected_n
    assert [r['update'] for r in updates] == list(range(1, expected_n + 1))
    previous_end = -1
    for row in updates:
        assert row['cursor'] == row['update'] * 4096 and row['global_token_positions'] == 4096
        assert math.isfinite(row['loss']) and struct.pack('<d', row['loss']).hex() == row['loss_binary64']
        assert previous_end <= row['started_monotonic_ns'] < row['completed_monotonic_ns']
        previous_end = row['completed_monotonic_ns']
    update_count += len(updates)
    for filename, receipt in cell['state_receipts'].items():
        state = receipt['state']
        assert receipt['full_tensor_payloads_retained'] is False
        assert state['cursor'] == state['completed'] * 4096
        assert state['losses_binary64'] == [r['loss_binary64'] for r in updates[:state['completed']]]
        assert len(state['losses_binary64']) == state['completed']
        canonical = json.dumps(state, sort_keys=True, allow_nan=False, separators=(',', ':')).encode()
        assert hashlib.sha256(canonical).hexdigest() == receipt['state_sha256']
        assert len({e['name'] for e in state['entries']}) == len(state['entries'])
        assert all(e['bytes'] > 0 and len(e['sha256']) == 64 for e in state['entries'])
        state_count += 1
    for filename, command in cell['worker_commands'].items():
        sequence = int(filename.removesuffix('.json'))
        ack = cell['worker_control_receipts'][f'ack-{sequence:06d}.json']
        assert ack['command_sequence'] == sequence
        assert ack['operation'] == command['operation']
    if 'park_memory' in cell:
        for when in ('before', 'after'):
            sample = cell['park_memory'][when]
            if sample is None:
                continue
            assert sample['valid'] is True and sample['sampling_atomic'] is False
            assert sample['capacity_workload_qualified'] is sample['performance_claim_eligible'] is False
            assert sample['started_monotonic_ns'] < sample['ended_monotonic_ns']
            queries = {r['kind']: r for r in sample['observations']}
            assert set(queries) == {'device-memory', 'compute-contexts'}
            assert all(r['returncode'] == 0 for r in queries.values())
            assert queries['device-memory']['parsed_measurement'] == {'used_mib': sample['memory_used_mib'], 'free_mib': sample['memory_free_mib'], 'total_mib': sample['memory_total_mib']}
            assert queries['compute-contexts']['parsed_measurement'] == {'context_count': sample['context_count']}
assert (update_count, state_count) == (88, 74)
reference = cells['reference-resident_fit-foreground']
native = cells['native_cuda_checkpoint-resident_fit-foreground']
nodus = cells['nodus_containerd_criu-resident_fit-foreground']
for actual in (native, nodus):
    assert actual['state_receipts']['initial.json']['state'] == reference['state_receipts']['initial.json']['state']
    for a, b in zip(actual['updates'], reference['updates']):
        assert all(a[k] == b[k] for k in ('update', 'cursor', 'global_token_positions', 'input_positions_sha256', 'loss_binary64', 'grad_norm'))
    assert actual['state_receipts']['hash-000009.json']['state'] == reference['state_receipts']['prefix-0008.json']['state']
assert native['state_receipts']['hash-000010.json']['state'] == native['state_receipts']['hash-000009.json']['state']
assert native['state_receipts']['hash-000019.json']['state'] == reference['state_receipts']['prefix-0016.json']['state']
assert native['reported_quality'] == {'qualified': True, 'ordered_complete_prefix': True,
    'initial_state_equal': True, 'final_state_equal': True, 'state_losses_match_rows': True,
    'input_mismatch_updates': [], 'loss_mismatch_updates': [], 'unique_completed_updates': 16,
    'tensor_payloads_independently_recomputed': False, 'performance_claim_eligible': False}
assert native['result']['restored_prefix_equal'] is True
assert native['reported_quality']['tensor_payloads_independently_recomputed'] is False
assert native['park_memory']['before']['memory_used_mib'] == 4547
assert native['park_memory']['after']['memory_used_mib'] == native['park_memory']['after']['context_count'] == 0
assert nodus['park_memory']['after'] is None and nodus['park_memory']['observations_complete'] is False
park, = [e for e in nodus['backend_events'] if e.get('operation') == 'park']
assert park['failed'] is True and not any(e.get('operation') == 'restore' for e in nodus['backend_events'])
assert observation['host_runtime']['suite_qualified'] is observation['host_runtime']['runtime_qualified'] is False
assert observation['cleanup']['direct_provider_termination_observed'] is observation['cleanup']['task_key_deleted'] is True
assert observation['accounting']['provider_billing_start_known'] is observation['accounting']['provider_final_invoice_known'] is False
# A separate operational attempt: historical UI record plus later private REST log.
assert set(no_launch) == {
    'accounting',
    'artifact_custody',
    'classification',
    'controller_revision',
    'controller_step',
    'cuda_execution',
    'execution_evidence',
    'later_terminal_evidence',
    'guard',
    'note',
    'numerical_cells_observed',
    'numerical_or_backend_result',
    'provider_execution_started',
    'provider_launch_attempted',
    'retained_evidence_files',
    'run_id',
    'source_control_flow',
    'ssh_key_creation_attempted',
    'study_revision',
    'study_revision_scope',
    'terminal_artifact',
    'workflow_conclusion',
    'workflow_conclusion_scope'
}
assert no_launch['run_id'] == 43093709048
assert no_launch['controller_revision'] == '01600a2945d24375202140c68e66ad8d37f89638'
assert no_launch['study_revision'] == '087b45ffff8318e7d0ac3a0eaf6a169c211ab8a8'
assert no_launch['classification'] == 'guard_not_running_controller_failed_closed_before_provider_mutation'
assert no_launch['workflow_conclusion'] == 'failure' and no_launch['terminal_artifact'] is None
assert no_launch['provider_execution_started'] is no_launch['provider_launch_attempted'] is False
assert no_launch['ssh_key_creation_attempted'] is no_launch['cuda_execution'] is False
assert no_launch['numerical_cells_observed'] == 0 and no_launch['numerical_or_backend_result'] is None
step = no_launch['controller_step']
assert step == {'number': 23, 'observed_exit_code': 1,
                'exception': 'RuntimeError: independent deadline guard not running; no launch',
                'evidence_kind': 'authenticated_ui_observation_record'}
assert no_launch['guard'] == {'run_id': 43095235638, 'source_revision': no_launch['controller_revision'],
                              'status': 'completed', 'conclusion': 'startup_failure', 'jobs': 0}
flow = no_launch['source_control_flow']
assert (flow['failure_line'], flow['ssh_keygen_line'], flow['provider_key_post_line'], flow['provider_launch_post_line']) == (322, 325, 337, 345)
assert flow['path'] == '.github/scripts/utilization_gpu_trial.py' and flow['revision'] == no_launch['controller_revision']
assert flow['source_statement'] == "if guard_id is None: raise RuntimeError('independent deadline guard not running; no launch')"
evidence_files = {r['path']: r for r in no_launch['retained_evidence_files']}
expected_evidence = {'controller-failure-ui.json': {'bytes': 1802,
                                'kind': 'authenticated_ui_observation_record',
                                'path': 'controller-failure-ui.json',
                                'sha256': 'c406c2d317dec82b7807b52fe92aa2ee5c78799dee1a021f39fea1c236192341'},
 'executed-controller.py': {'bytes': 42038,
                            'kind': 'exact_git_controller_source',
                            'path': 'executed-controller.py',
                            'sha256': '0d2740a8ade577f8c7275c484fbb920e9ef404a3367c413249c2848a6bfbf266'},
 'guard-terminal-jobs.json': {'bytes': 27,
                              'kind': 'authenticated_github_jobs_metadata',
                              'path': 'guard-terminal-jobs.json',
                              'sha256': 'b3dab5870ff3a8209160335de7c1077b89e461d875d9041ac9d8b8ed7c1666f6'},
 'guard-terminal.json': {'bytes': 13784,
                         'kind': 'authenticated_github_run_metadata',
                         'path': 'guard-terminal.json',
                         'sha256': '32b3a8d018bd5e51d27a40d618a2c8fc5b01789a529a93528ea499a9cf3e7749'}}
expected_evidence.update({'main-terminal-artifacts.json': {'bytes': 32,
                                  'kind': 'authenticated_github_artifact_inventory',
                                  'path': 'main-terminal-artifacts.json',
                                  'sha256': '244563f989470892c537c9a4622920af0d228ee4528f7d00c64a06d6cd95856c'},
 'main-terminal-job-captured.log': {'bytes': 64233,
                                    'kind': 'authenticated_github_job_log_private',
                                    'path': 'main-terminal-job-captured.log',
                                    'sha256': 'e389880c1b8f385cb9389577cc74fd13e2fe1c16adff4830c7b9f763ebcbd6e0'},
 'main-terminal-job-log.stderr': {'bytes': 99,
                                  'kind': 'first_acquisition_cli_refusal',
                                  'path': 'main-terminal-job-log.stderr',
                                  'sha256': '8b6407b2fdbca54bf3d53fb93e79a3560dbe59567fa5044cfee4bed1b5b6e467'},
 'main-terminal-job.log': {'bytes': 0,
                           'kind': 'first_acquisition_empty_output',
                           'path': 'main-terminal-job.log',
                           'sha256': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'},
 'main-terminal-jobs.json': {'bytes': 8042,
                             'kind': 'authenticated_github_jobs_metadata',
                             'path': 'main-terminal-jobs.json',
                             'sha256': '62658f44bf8a14367242b8d996e6387756043310900ad4b447434569139bb668'},
 'main-terminal-log-acquisition.json': {'bytes': 204,
                                        'kind': 'first_log_acquisition_record',
                                        'path': 'main-terminal-log-acquisition.json',
                                        'sha256': 'ddb8e2de28fb7fe7a01eae558d1ee667969eeac81b7cb3eedf41979fd39a047d'},
 'main-terminal-log-corrected-acquisition.json': {'bytes': 604,
                                                  'kind': 'corrected_file_only_log_acquisition_record',
                                                  'path': 'main-terminal-log-corrected-acquisition.json',
                                                  'sha256': 'b146e768ec40092b74fd08ac501819c54f8728613a3ed9fbaa27e3268421088c'},
 'main-terminal.json': {'bytes': 13411,
                        'kind': 'authenticated_github_run_metadata',
                        'path': 'main-terminal.json',
                        'sha256': 'fe3c6fc3c06d4a74c170fc2952a76b405e8362985194c19d7ebbf6b34dca09f0'}})
assert len(evidence_files) == len(no_launch['retained_evidence_files']) == 12
assert evidence_files == expected_evidence
assert flow['sha256'] == evidence_files['executed-controller.py']['sha256']
evidence = no_launch['execution_evidence']
assert evidence['kind'] == 'authenticated_ui_observation_record'
assert evidence['observation_record_sha256'] == evidence_files['controller-failure-ui.json']['sha256']
assert 'capture_sha256' not in evidence
assert 'job_url' not in evidence
assert set(evidence) == {'complete_rest_log_retained', 'job_id', 'kind', 'observation_record_bytes_public', 'observation_record_sha256', 'observed_at', 'projection_scope', 'raw_ui_capture_retained', 'run_id', 'structured_observation_record_retained'}
assert evidence['run_id'] == no_launch['run_id'] and evidence['job_id'] == 130777049692
assert evidence['complete_rest_log_retained'] is evidence['raw_ui_capture_retained'] is evidence['observation_record_bytes_public'] is False
assert evidence['structured_observation_record_retained'] is True
# Historical UI custody fields remain as observed; its public locator is sanitized.
terminal = no_launch['later_terminal_evidence']
assert terminal == {'acquisition_history': {'corrected_acquisition_path': 'main-terminal-log-corrected-acquisition.json',
                         'corrected_outcome': 'file_only_capture_succeeded',
                         'initial_acquisition_path': 'main-terminal-log-acquisition.json',
                         'initial_empty_output_path': 'main-terminal-job.log',
                         'initial_outcome': 'CLI_terminal_escape_safeguard_refused_output',
                         'initial_output_bytes': 0,
                         'initial_stderr_path': 'main-terminal-job-log.stderr',
                         'scope': 'The initial local CLI refusal did not establish server-side log '
                                  'absence. Earlier acquisition files are retained unchanged.'},
 'artifact_inventory': {'inventory_path': 'main-terminal-artifacts.json', 'total_count': 0},
 'initial_ui_observation_record_unchanged': True,
 'initial_ui_observation_scope': 'execution_evidence describes only the earlier UI observation; '
                                 'complete_rest_log_retained=false there is historical, not the '
                                 'current custody state. The retained authored record is '
                                 'unchanged; its private repository URL is projected only as '
                                 'numeric run/job identifiers.',
 'job': {'completed_at': '2026-11-11T20:33:09Z',
         'conclusion': 'failure',
         'id': 130777049692,
         'inventory_path': 'main-terminal-jobs.json',
         'status': 'completed'},
 'job_log': {'bytes': 64233,
             'complete_rest_log_retained': True,
             'inventory_path': 'main-terminal-job-captured.log',
             'raw_bytes_public': False,
             'sanitized_exception': {'exception_log_line': 631,
                                     'source_basename': 'utilization_gpu_trial.py',
                                     'source_line': 322,
                                     'stack_frame_log_line': 628,
                                     'text': 'RuntimeError: independent deadline guard not '
                                             'running; no launch',
                                     'timestamp': '2026-11-11T20:22:38.2332261Z'},
             'sha256': 'e389880c1b8f385cb9389577cc74fd13e2fe1c16adff4830c7b9f763ebcbd6e0',
             'timestamped_lines': 687,
             'total_lines': 709},
 'kind': 'authenticated_rest_terminal_metadata_and_job_log',
 'observed_at': '2026-11-11T21:11:52.756492+00:00',
 'scope': 'Sanitized projection bound to private retained REST metadata and actual job-log bytes. '
          'A retained job log is not an uploaded Actions artifact, controller result receipt or '
          'effective host packet; those remain unavailable.',
 'workflow': {'conclusion': 'failure',
              'inventory_path': 'main-terminal.json',
              'source_revision': '01600a2945d24375202140c68e66ad8d37f89638',
              'status': 'completed',
              'updated_at': '2026-11-11T21:01:26Z'}}
log = terminal['job_log']
assert (log['bytes'], log['sha256']) == (evidence_files[log['inventory_path']]['bytes'], evidence_files[log['inventory_path']]['sha256'])
assert terminal['workflow']['source_revision'] == flow['revision']
assert log['sanitized_exception']['text'] == step['exception']
assert log['sanitized_exception']['source_line'] == flow['failure_line']
assert evidence_files[terminal['acquisition_history']['initial_empty_output_path']]['bytes'] == 0
for key in ('workflow', 'job', 'artifact_inventory'):
    assert terminal[key]['inventory_path'] in evidence_files
assert no_launch['artifact_custody'] == {'actions_upload_retained': False, 'declared_small_files': 3, 'upload_step': 25,
    'error_category': 'CreateArtifact_failed_after_five_HTML_instead_of_JSON_responses',
    'raw_controller_receipts_available': False, 'effective_host_packet_retained': False}
assert no_launch['accounting'] == {'this_attempt_provider_launch_attempted': False,
    'account_wide_inventory_available': False, 'observed_supplier_charge_usd': None,
    'final_invoice_known': False, 'provider_gpu_hours_measured': False}

# The new run retains independent receipts; only duplicate canonical state bodies refer backward.
def resolve_state(observations, observation_index, receipt):
    if type(observations) is not list or type(observation_index) is not int:
        raise ValueError('invalid observation boundary')
    if not 0 <= observation_index < len(observations) or type(receipt) is not dict:
        raise ValueError('invalid receipt boundary')
    digest = receipt.get('state_sha256')
    if type(digest) is not str or len(digest) != 64 or any(c not in '0123456789abcdef' for c in digest):
        raise ValueError('invalid canonical digest')
    if ('state' in receipt) == ('state_ref' in receipt):
        raise ValueError('exactly one inline state or reference required')
    if 'state' in receipt:
        state = receipt['state']
    else:
        ref = receipt['state_ref']
        if type(ref) is not dict or set(ref) != {'observation_run_id', 'cell', 'receipt', 'canonical_sha256'}:
            raise ValueError('invalid state reference schema')
        if type(ref['observation_run_id']) is not int or ref['canonical_sha256'] != digest:
            raise ValueError('invalid state reference identity')
        if any(type(ref[k]) is not str or not ref[k] or len(ref[k]) > 128 for k in ('cell', 'receipt')):
            raise ValueError('invalid state reference key')
        matches = [o for o in observations[:observation_index]
                   if o.get('run_id') == ref['observation_run_id']]
        if len(matches) != 1:
            raise ValueError('reference must identify one earlier observation')
        try:
            target = matches[0]['cells'][ref['cell']]['state_receipts'][ref['receipt']]
        except (KeyError, TypeError):
            raise ValueError('dangling state reference') from None
        if type(target) is not dict or 'state' not in target or 'state_ref' in target:
            raise ValueError('reference target must be inline; chains and cycles prohibited')
        if target.get('state_sha256') != digest:
            raise ValueError('referenced receipt digest differs')
        state = target['state']
    if type(state) is not dict:
        raise ValueError('canonical state must be an object')
    canonical = json.dumps(state, sort_keys=True, allow_nan=False, separators=(',', ':')).encode()
    if hashlib.sha256(canonical).hexdigest() != digest:
        raise ValueError('resolved canonical digest differs')
    return state

import copy
original_observation = observation
old_totals = update_count, state_count, len(inventory5), streams5
observation = copy.deepcopy(v['observations'][1])
assert observation['state_representation']['kind'] == 'exact_prior_state_reference'
assert observation['state_representation']['source_observation_run_id'] == 43079070680
resolved_count = 0
for cell in observation['cells'].values():
    for receipt in cell.get('state_receipts', {}).values():
        assert set(receipt) == {'elapsed_s', 'full_tensor_payloads_retained', 'state_sha256', 'state_ref'}
        assert type(receipt['elapsed_s']) in (int, float) and math.isfinite(receipt['elapsed_s']) and receipt['elapsed_s'] >= 0
        state = resolve_state(v['observations'], 1, receipt)
        receipt.pop('state_ref')
        receipt['state'] = state
        resolved_count += 1
assert resolved_count == observation['state_representation']['resolved_state_count'] == 74
assert observation['run_id'] == 43105728078
assert observation['controller_revision'] == '01600a2945d24375202140c68e66ad8d37f89638'
assert observation['study_revision'] == '087b45ffff8318e7d0ac3a0eaf6a169c211ab8a8'
assert observation['qualified'] is observation['performance_claim_eligible'] is observation['cause_established'] is False
assert observation['failure']['classification'] == 'runtime_failure_not_numerical_rejection'
assert observation['failure']['underlying_error_message_retained'] is False
files5 = observation['retained_files']
inventory5 = {r['path']: r for r in files5}
assert len(inventory5) == len(files5) == 408
commands5 = observation['host_commands']
assert len({r['operation'] for r in commands5}) == len(commands5) == 39
omission5, = observation['omitted_command_streams']
assert omission5['path'] == 'results/coalescing/host/image-decompress.stdout'
assert (omission5['recorded_bytes'], omission5['recorded_sha256']) == expected_image
assert omission5['retained'] is omission5['independently_byte_verified'] is False
assert omission5['path'] not in inventory5
streams5 = 0
for command in commands5:
    stem = 'results/coalescing/host/' + command['operation']
    assert command['raw_command_path'] == stem + '.command.json'
    assert inventory5[command['raw_command_path']]['sha256'] == command['raw_command_sha256']
    for channel in ('stdout', 'stderr'):
        path = stem + '.' + channel
        pair = command[channel + '_bytes'], command[channel + '_sha256']
        if path == omission5['path']:
            assert pair == expected_image
        else:
            assert pair == (inventory5[path]['bytes'], inventory5[path]['sha256'])
            streams5 += 1
assert streams5 == 77
staged = {r['name']: r for r in observation['staged_files']}
assert len(observation['source_files']) == 9
for source in observation['source_files']:
    row = staged[source['path'].rsplit('/', 1)[1]]
    assert source['revision'] == observation['study_revision']
    assert (source['bytes'], source['sha256']) == (row['bytes'], row['sha256'])
cells = observation['cells']
assert len(cells) == 12
assert sorted(c['status'] for c in cells.values()) == ['complete'] * 5 + ['failed'] + ['not_started'] * 6
update_count = state_count = 0
for name, cell in cells.items():
    if cell['status'] == 'not_started':
        assert cell == {'status': 'not_started'}
        continue
    identity = cell['identity']
    assert identity['torch'] == '2.7.1+cu128' and identity['cuda'] == '12.8'
    assert identity['contract_sha256'] == staged['workload.json']['sha256']
    assert identity['model_sha256'] == staged['model_317ed.py']['sha256']
    assert identity['train_sha256'] == staged['train.bin']['sha256']
    assert cell['result']['performance_claim_eligible'] is False
    updates = cell['updates']
    expected_n = 8 if cell['status'] == 'failed' else 16
    assert len(updates) == expected_n
    assert [r['update'] for r in updates] == list(range(1, expected_n + 1))
    previous_end = -1
    for row in updates:
        assert row['cursor'] == row['update'] * 4096 and row['global_token_positions'] == 4096
        assert math.isfinite(row['loss']) and struct.pack('<d', row['loss']).hex() == row['loss_binary64']
        assert previous_end <= row['started_monotonic_ns'] < row['completed_monotonic_ns']
        previous_end = row['completed_monotonic_ns']
    update_count += len(updates)
    for filename, receipt in cell['state_receipts'].items():
        state = receipt['state']
        assert receipt['full_tensor_payloads_retained'] is False
        assert state['cursor'] == state['completed'] * 4096
        assert state['losses_binary64'] == [r['loss_binary64'] for r in updates[:state['completed']]]
        assert len(state['losses_binary64']) == state['completed']
        canonical = json.dumps(state, sort_keys=True, allow_nan=False, separators=(',', ':')).encode()
        assert hashlib.sha256(canonical).hexdigest() == receipt['state_sha256']
        assert len({e['name'] for e in state['entries']}) == len(state['entries'])
        assert all(e['bytes'] > 0 and len(e['sha256']) == 64 for e in state['entries'])
        state_count += 1
    for filename, command in cell['worker_commands'].items():
        sequence = int(filename.removesuffix('.json'))
        ack = cell['worker_control_receipts'][f'ack-{sequence:06d}.json']
        assert ack['command_sequence'] == sequence
        assert ack['operation'] == command['operation']
    if 'park_memory' in cell:
        for when in ('before', 'after'):
            sample = cell['park_memory'][when]
            if sample is None:
                continue
            assert sample['valid'] is True and sample['sampling_atomic'] is False
            assert sample['capacity_workload_qualified'] is sample['performance_claim_eligible'] is False
            assert sample['started_monotonic_ns'] < sample['ended_monotonic_ns']
            queries = {r['kind']: r for r in sample['observations']}
            assert set(queries) == {'device-memory', 'compute-contexts'}
            assert all(r['returncode'] == 0 for r in queries.values())
            assert queries['device-memory']['parsed_measurement'] == {'used_mib': sample['memory_used_mib'], 'free_mib': sample['memory_free_mib'], 'total_mib': sample['memory_total_mib']}
            assert queries['compute-contexts']['parsed_measurement'] == {'context_count': sample['context_count']}
assert (update_count, state_count) == (88, 74)
reference = cells['reference-resident_fit-foreground']
native = cells['native_cuda_checkpoint-resident_fit-foreground']
nodus = cells['nodus_containerd_criu-resident_fit-foreground']
for actual in (native, nodus):
    assert actual['state_receipts']['initial.json']['state'] == reference['state_receipts']['initial.json']['state']
    for a, b in zip(actual['updates'], reference['updates']):
        assert all(a[k] == b[k] for k in ('update', 'cursor', 'global_token_positions', 'input_positions_sha256', 'loss_binary64', 'grad_norm'))
    assert actual['state_receipts']['hash-000009.json']['state'] == reference['state_receipts']['prefix-0008.json']['state']
assert native['state_receipts']['hash-000010.json']['state'] == native['state_receipts']['hash-000009.json']['state']
assert native['state_receipts']['hash-000019.json']['state'] == reference['state_receipts']['prefix-0016.json']['state']
assert native['reported_quality'] == {'qualified': True, 'ordered_complete_prefix': True,
    'initial_state_equal': True, 'final_state_equal': True, 'state_losses_match_rows': True,
    'input_mismatch_updates': [], 'loss_mismatch_updates': [], 'unique_completed_updates': 16,
    'tensor_payloads_independently_recomputed': False, 'performance_claim_eligible': False}
assert native['result']['restored_prefix_equal'] is True
assert native['reported_quality']['tensor_payloads_independently_recomputed'] is False
assert native['park_memory']['before']['memory_used_mib'] == 4547
assert native['park_memory']['after']['memory_used_mib'] == native['park_memory']['after']['context_count'] == 0
assert nodus['park_memory']['after']['memory_used_mib'] == nodus['park_memory']['after']['context_count'] == 0
assert nodus['park_memory']['before']['memory_used_mib'] == 4547
assert nodus['park_memory']['observations_complete'] is True
park, = [e for e in nodus['backend_events'] if e.get('operation') == 'park']
restore, = [e for e in nodus['backend_events'] if e.get('operation') == 'restore']
checkpoint, = [e for e in nodus['backend_events'] if e.get('event') == 'checkpoint_retained']
inner_cleanup, = [e for e in nodus['backend_events'] if e.get('event') == 'owned_runtime_cleanup']
assert park['failed'] is False and park['elapsed_s'] == 5.196756238 and park['state'] == 'parked'
assert restore['failed'] is True and restore['failure_stage'] == 'backend_restore' and restore['epoch'] == 2
assert restore['elapsed_s'] == 0.04076179 and restore['state'] == 'parked'
assert restore['failure_evidence']['checkpoint_failure_code'] == 'node incompatible with the checkpoint'
assert restore['failure_evidence']['path_not_found'] is True and restore['failure_evidence']['raw_error_retained'] is False
assert observation['failure']['typed_failure_evidence'] == restore['failure_evidence']
assert checkpoint['bytes'] == 5925568575
assert inner_cleanup['kill_error'] is inner_cleanup['kill_returned'] is inner_cleanup['remove_returned'] is True
assert inner_cleanup['remove_error'] is False
assert nodus['result']['runtime_cleanup_complete'] is nodus['backend_terminal']['owned_runtime_cleanup_complete'] is False
assert observation['host_runtime']['owned_unit_stopped'] is observation['host_runtime']['compute_contexts_absent'] is True
assert observation['host_runtime']['suite_qualified'] is observation['host_runtime']['runtime_qualified'] is False
assert observation['cleanup']['direct_provider_termination_observed'] is observation['cleanup']['task_key_deleted'] is True
assert observation['accounting']['provider_billing_start_known'] is observation['accounting']['provider_final_invoice_known'] is False

update_count += old_totals[0]
state_count += old_totals[1]
all_gpu_files = len(inventory5) + old_totals[2]
streams5 += old_totals[3]

# Two separate completed compatibility screens; every earlier failure remains checked.
for observation_index, expected_run, expected_controller, expected_study, expected_files, expected_classification, expected_pressure in [
    (2, 43120056044, '74dc188b82c8decbf34cdf22f7d319f2425fb2c5', '693f79dfeb6ab0125778e95fe81e52ab13cd25f9', 880,
     'fixed16_complete_gpu_compatibility_screen', (18.008112871, 20.520512449)),
    (3, 43155798511, '56470e9b0ca29879b370a9c3736a47946d0bc775', '9e7fb29208a90c99a4b31d36d40ddca2285385a2', 888,
     'fixed16_complete_gpu_compatibility_screen_with_restore_phase_observations', (17.192246698, 18.486995636)),
]:
    complete = v['observations'][observation_index]
    assert complete['run_id'] == expected_run
    assert complete['controller_revision'] == expected_controller
    assert complete['study_revision'] == expected_study
    assert complete['classification'] == expected_classification
    assert complete['status'] == 'complete' and complete['qualified'] is True
    assert complete['performance_claim_eligible'] is False
    assert complete['state_representation']['kind'] == 'exact_prior_state_reference'
    assert complete['state_representation']['source_observation_run_id'] == 43079070680
    inventory6 = {r['path']: r for r in complete['retained_files']}
    assert len(inventory6) == len(complete['retained_files']) == expected_files
    commands6 = complete['host_commands']
    assert len({r['operation'] for r in commands6}) == len(commands6) == 39
    omission6, = complete['omitted_command_streams']
    assert omission6['path'] == 'results/coalescing/host/image-decompress.stdout'
    assert (omission6['recorded_bytes'], omission6['recorded_sha256']) == expected_image
    assert omission6['retained'] is omission6['independently_byte_verified'] is False
    assert omission6['path'] not in inventory6
    streams6 = 0
    for command in commands6:
        stem = 'results/coalescing/host/' + command['operation']
        assert command['raw_command_path'] == stem + '.command.json'
        assert inventory6[command['raw_command_path']]['sha256'] == command['raw_command_sha256']
        for channel in ('stdout', 'stderr'):
            path = stem + '.' + channel
            pair = command[channel + '_bytes'], command[channel + '_sha256']
            if path == omission6['path']:
                assert pair == expected_image
            else:
                assert pair == (inventory6[path]['bytes'], inventory6[path]['sha256'])
                streams6 += 1
    assert streams6 == 77
    staged6 = {r['name']: r for r in complete['staged_files']}
    assert len(complete['source_files']) == 9
    for source in complete['source_files']:
        row = staged6[source['path'].rsplit('/', 1)[1]]
        assert source['revision'] == complete['study_revision']
        assert (source['bytes'], source['sha256']) == (row['bytes'], row['sha256'])
    cells6 = complete['cells']
    assert set(cells6) == {f'{backend}-{mode}-{role}'
        for backend in ('reference', 'native_cuda_checkpoint', 'nodus_containerd_criu')
        for mode in ('resident_fit', 'memory_pressure') for role in ('foreground', 'background')}
    new_updates = new_states = memory_samples = 0
    resolved6 = {}
    for name, cell in cells6.items():
        assert cell['status'] == 'complete'
        assert cell['identity']['torch'] == '2.7.1+cu128' and cell['identity']['cuda'] == '12.8'
        for field, staged_name in [('contract_sha256', 'workload.json'), ('model_sha256', 'model_317ed.py'), ('train_sha256', 'train.bin')]:
            assert cell['identity'][field] == staged6[staged_name]['sha256']
        assert cell['result']['runtime_cleanup_complete'] is cell['result']['compute_contexts_absent'] is True
        assert cell['result']['performance_claim_eligible'] is cell['result']['supplier_release_proved'] is False
        assert cell['backend_terminal']['owned_runtime_cleanup_complete'] is True
        assert cell['backend_terminal']['exit_code'] == 0 and cell['backend_terminal']['stream_error'] is None
        assert cell['backend_terminal']['truncated_stdout'] is False
        updates = cell['updates']
        assert len(updates) == 16 and [r['update'] for r in updates] == list(range(1, 17))
        previous_end = -1
        for row in updates:
            assert row['cursor'] == row['update'] * 4096 and row['global_token_positions'] == 4096
            assert math.isfinite(row['loss']) and struct.pack('<d', row['loss']).hex() == row['loss_binary64']
            assert previous_end <= row['started_monotonic_ns'] < row['completed_monotonic_ns']
            previous_end = row['completed_monotonic_ns']
        new_updates += len(updates)
        resolved6[name] = {}
        for filename, receipt in cell['state_receipts'].items():
            assert set(receipt) == {'elapsed_s', 'full_tensor_payloads_retained', 'state_sha256', 'state_ref'}
            assert type(receipt['elapsed_s']) in (int, float) and math.isfinite(receipt['elapsed_s']) and receipt['elapsed_s'] >= 0
            assert receipt['full_tensor_payloads_retained'] is False
            state = resolve_state(v['observations'], observation_index, receipt)
            assert state['cursor'] == state['completed'] * 4096
            assert state['losses_binary64'] == [r['loss_binary64'] for r in updates[:state['completed']]]
            assert len(state['losses_binary64']) == state['completed']
            if filename == 'initial.json':
                assert state['completed'] == 0
            elif name.startswith('reference-'):
                assert state['completed'] == int(filename.removeprefix('prefix-').removesuffix('.json'))
            assert len({e['name'] for e in state['entries']}) == len(state['entries'])
            assert all(e['bytes'] > 0 and len(e['sha256']) == 64 for e in state['entries'])
            resolved6[name][filename] = state
            new_states += 1
        for filename, command in cell['worker_commands'].items():
            sequence = int(filename.removesuffix('.json'))
            ack = cell['worker_control_receipts'][f'ack-{sequence:06d}.json']
            assert ack['command_sequence'] == sequence and ack['operation'] == command['operation']
            assert ack['completed'] == (sequence if sequence <= 8 else 8 if sequence <= 10 else min(sequence - 2, 16))
            assert ack['mode'] == ('stopped' if sequence == 20 else 'paused')
        if name.startswith('reference-'):
            assert set(resolved6[name]) == {'initial.json'} | {f'prefix-{n:04d}.json' for n in range(1, 17)}
        else:
            assert set(cell['worker_commands']) == {f'{n:06d}.json' for n in range(1, 21)}
            assert set(resolved6[name]) == {'initial.json', 'hash-000009.json', 'hash-000010.json', 'hash-000019.json'}
            events = [e for e in cell['backend_events'] if e['event'] == 'command_complete']
            assert [e['operation'] for e in events] == ['create', 'park', 'restore', 'remove']
            assert [e['sequence'] for e in events] == [1, 2, 3, 4]
            assert all(e['failed'] is False and math.isfinite(e['elapsed_s']) and e['elapsed_s'] >= 0 for e in events)
            assert cell['result']['restored_prefix_equal'] is True
            inner, = [e for e in cell['backend_events'] if e['event'] == 'owned_runtime_cleanup']
            assert inner['kill_returned'] is inner['remove_returned'] is True
            assert inner['kill_error'] is inner['remove_error'] is False
            for when in ('before', 'after'):
                sample = cell['park_memory'][when]
                assert sample['valid'] is True and sample['sampling_atomic'] is False
                assert sample['capacity_workload_qualified'] is sample['performance_claim_eligible'] is sample['supplier_release_proved'] is False
                assert sample['started_monotonic_ns'] < sample['ended_monotonic_ns']
                queries = {r['kind']: r for r in sample['observations']}
                assert set(queries) == {'device-memory', 'compute-contexts'}
                assert all(r['returncode'] == 0 for r in queries.values())
                assert queries['device-memory']['parsed_measurement'] == {'used_mib': sample['memory_used_mib'], 'free_mib': sample['memory_free_mib'], 'total_mib': sample['memory_total_mib']}
                assert queries['compute-contexts']['parsed_measurement'] == {'context_count': sample['context_count']}
                assert sample['memory_used_mib'] == (0 if when == 'after' else 12047 if '-memory_pressure-' in name else 4547)
                assert sample['context_count'] == (0 if when == 'after' else 1)
                memory_samples += 1
    assert new_updates == 192 and new_states == complete['state_representation']['resolved_state_count'] == 100
    assert memory_samples == 16
    for mode in ('resident_fit', 'memory_pressure'):
        for role in ('foreground', 'background'):
            reference_name = f'reference-{mode}-{role}'
            for backend in ('native_cuda_checkpoint', 'nodus_containerd_criu'):
                name = f'{backend}-{mode}-{role}'
                cell = cells6[name]
                for actual, expected in zip(cell['updates'], cells6[reference_name]['updates']):
                    assert all(actual[k] == expected[k] for k in ('update', 'cursor', 'global_token_positions', 'input_positions_sha256', 'loss_binary64', 'grad_norm'))
                for actual, expected in [('initial.json', 'initial.json'), ('hash-000009.json', 'prefix-0008.json'), ('hash-000010.json', 'prefix-0008.json'), ('hash-000019.json', 'prefix-0016.json')]:
                    assert resolved6[name][actual] == resolved6[reference_name][expected]
                assert cell['reported_quality'] == {'qualified': True, 'ordered_complete_prefix': True,
                    'initial_state_equal': True, 'final_state_equal': True, 'state_losses_match_rows': True,
                    'input_mismatch_updates': [], 'loss_mismatch_updates': [], 'unique_completed_updates': 16,
                    'tensor_payloads_independently_recomputed': False, 'performance_claim_eligible': False}
    for role, duration in zip(('foreground', 'background'), expected_pressure):
        restore, = [e for e in cells6[f'nodus_containerd_criu-memory_pressure-{role}']['backend_events'] if e.get('operation') == 'restore']
        assert restore['elapsed_s'] == duration > 15
    assert all(complete['host_runtime'][k] is True for k in ('suite_returned', 'suite_qualified', 'runtime_qualified', 'owned_unit_stopped', 'compute_contexts_absent'))
    assert complete['host_runtime']['suite_returncode'] == 0
    assert complete['cleanup']['direct_provider_termination_observed'] is complete['cleanup']['task_key_deleted'] is True
    assert complete['accounting']['provider_billing_start_known'] is complete['accounting']['provider_final_invoice_known'] is False
    update_count += new_updates
    state_count += new_states
    resolved_count += new_states
    all_gpu_files += len(inventory6)
    streams5 += streams6

# Recompute the new phase document from sanitized, ordered event receipts.
PHASES = set('checkpoint checkpoint_cuda_release checkpoint_freeze checkpoint_dump checkpoint_layer '
             'restore_criu restore_cuda restore_primary ensure container_create rootfs_diff_apply '
             'task_receipt runtime_options io_create task_create restore_remove restore_ensure '
             'native_state native_lock native_checkpoint native_restore native_unlock'.split())

def require(ok, reason):
    assert ok, reason

def integer(value):
    return type(value) is int and value >= 0

def phase_pairs(events):
    opened, complete, invalid = {}, [], []
    for index, event in enumerate(events):
        if event.get('event') != 'runtime_phase':
            continue
        phase, epoch = event.get('phase'), event.get('epoch')
        require(phase in PHASES and integer(epoch) and type(event.get('failed')) is bool,
                'unknown_phase_schema')
        key = (phase, epoch)
        transition = event.get('transition')
        require(transition in ('begin', 'end'), 'unknown_phase_transition')
        if transition == 'begin':
            if key in opened:
                invalid.append({'phase': phase, 'epoch': epoch, 'reason': 'overlapping_same_phase'})
                opened[key] = None
            else:
                opened[key] = (index, event)
        elif key not in opened or opened[key] is None:
            opened.pop(key, None)
            invalid.append({'phase': phase, 'epoch': epoch, 'reason': 'missing_or_ambiguous_begin'})
        else:
            start_index, begin = opened.pop(key)
            start, end = begin['monotonic_elapsed_ns'], event['monotonic_elapsed_ns']
            item = {'phase': phase, 'epoch': epoch, 'begin_event': start_index, 'end_event': index,
                    'start_ns': start, 'end_ns': end}
            if begin['failed'] or event['failed'] or end <= start:
                invalid.append(dict(item, reason='failed_or_empty_pair'))
            else:
                complete.append(item)
    invalid.extend({'phase': key[0], 'epoch': key[1], 'reason': 'missing_end'} for key in opened)
    crossing = set()
    for i, left in enumerate(complete):
        for j, right in enumerate(complete[i + 1:], i + 1):
            a, b = sorted((left, right), key=lambda p: p['begin_event'])
            if a['begin_event'] < b['begin_event'] < a['end_event'] < b['end_event']:
                crossing.update((i, j))
    invalid.extend(dict(complete[i], reason='crossing_overlap') for i in sorted(crossing))
    complete = [p for i, p in enumerate(complete) if i not in crossing]
    for i, item in enumerate(complete):
        item['pair_id'] = i
        parents = [p for p in complete if p['begin_event'] < item['begin_event'] and
                   item['end_event'] < p['end_event']]
        parent = min(parents, key=lambda p: p['end_ns'] - p['start_ns']) if parents else None
        item['parent_pair_id'] = complete.index(parent) if parent else None
        item['duration_s'] = (item['end_ns'] - item['start_ns']) / 1e9
    for item in complete:
        children = [p for p in complete if p['parent_pair_id'] == item['pair_id']]
        item['exclusive_s'] = (item['end_ns'] - item['start_ns'] -
                               sum(p['end_ns'] - p['start_ns'] for p in children)) / 1e9
    return complete, invalid


phase_observation = v['observations'][3]
analysis = phase_observation['phase_analysis']
assert analysis['schema'] == 'nodus.coalescing-phase-reduction/0.1'
assert analysis['reducer_sha256'] == '0616eeabaaf479bc2fdb3cd54d5ed9fc9edfb8d6f11aea0c838d58e1d0b7236d'
assert analysis['quality_source_sha256'] == '0955dce5e7d15b4482ffa9e8a90a893bd0f7d4c1b33e37093139fdea41ad728a'
assert analysis['clock_domains'] == {'phases': 'one Go adapter process per cell', 'resume': 'Python host per cell'}
assert analysis['cross_process_clock_subtraction'] is analysis['speedup_claim'] is analysis['product_request_latency'] is False
assert analysis['nested_durations_are_not_additive'] is True
phase_bytes = (json.dumps(analysis, indent=2, allow_nan=False) + '\n').encode()
custody = phase_observation['phase_analysis_custody']
assert (len(phase_bytes), hashlib.sha256(phase_bytes).hexdigest()) == (custody['bytes'], custody['sha256'])
assert custody['kind'] == 'derived_offline_reduction_of_retained_receipts'
for relative, pin in analysis['sources'].items():
    retained = inventory6['results/coalescing/' + relative]
    assert (pin['bytes'], pin['sha256']) == (retained['bytes'], retained['sha256'])
assert set(analysis['cells']) == {name for name in cells6 if not name.startswith('reference-')}
phase_pair_count = 0
for name, reduced in analysis['cells'].items():
    cell = cells6[name]
    events = cell['backend_events']
    clocks = [e['monotonic_elapsed_ns'] for e in events]
    assert all(integer(t) for t in clocks) and clocks == sorted(clocks)
    ready, = [e for e in events if e['event'] == 'adapter_ready']
    assert ready['runtime_observation_overlay_sha256'] == '98cb335984a191ef0b1c0c427037e60ebe255bb9f9d0de6a81a78c39cd9b1d2b'
    assert ready['adapter_sha256'] == cell['manifest']['adapter_sha256']
    commands = [(i,e) for i,e in enumerate(events) if e['event'] == 'command_complete']
    pairs, invalid = phase_pairs(events)
    for pair in pairs:
        pair['operation'] = next(e['operation'] for index,e in commands if pair['end_event'] < index)
        assert pair['exclusive_s'] >= 0
    assert pairs == reduced['completed_phases'] and invalid == reduced['excluded_phases'] == []
    assert reduced['status'] == 'quality_qualified' and reduced['restore_decomposition_complete'] is True
    assert (reduced['backend'],reduced['workload'],reduced['role']) == tuple(cell['manifest'][k] for k in ('backend','workload','role'))
    restore = [p for p in pairs if commands[1][0] < p['begin_event'] < p['end_event'] < commands[2][0]]
    outer = [p for p in restore if not any(q['begin_event'] < p['begin_event'] and p['end_event'] < q['end_event'] for q in restore)]
    assigned = sum(p['end_ns']-p['start_ns'] for p in outer)/1e9
    total = commands[2][1]['elapsed_s']
    assert reduced['restore_command_s'] == total and reduced['assigned_restore_s'] == assigned <= total
    assert reduced['restore_outer_pair_ids'] == [p['pair_id'] for p in outer]
    assert reduced['unassigned_restore_s'] == total-assigned
    assert reduced['unassigned_scope'] == 'outside outer phases; within-parent remainder is exclusive_s'
    timing = cell['resume_timing']
    prefix = 'results/coalescing/cells/' + name + '/'
    assert timing['quality_sha256'] == inventory6[prefix+'quality.json']['sha256']
    assert timing['first_update_receipt_sha256'] == inventory6[prefix+'outputs/worker/update-0009.json']['sha256']
    assert timing['quality_qualified'] is True and timing['first_update'] == 9
    times = [timing[k] for k in ('restore_requested_monotonic_ns','restore_ack_monotonic_ns','prefix_verified_monotonic_ns','first_update_ack_monotonic_ns')]
    assert all(integer(t) for t in times) and times == sorted(times)
    duration = (times[3]-times[0])/1e9
    assert timing['restore_to_first_update_observed_s'] == duration
    assert reduced['first_correct_resumed_update'] == {
        'update':9, 'restore_request_to_update_ack_s':duration,
        'restore_request_to_ack_s':(times[1]-times[0])/1e9,
        'ack_to_prefix_verification_s':(times[2]-times[1])/1e9,
        'prefix_verification_to_update_ack_s':(times[3]-times[2])/1e9,
        'includes_original_hash_and_control_overhead':True}
    phase_pair_count += len(pairs)

print(json.dumps({'status': 'public_scalar_consistency_passed', 'attempts': 6, 'hosted_diagnostics': 1,
                  'operational_transport_failures': 2,
                  'actual_gpu_runs': 4, 'operational_no_launch_attempts': 1,
                  'ui_observation_record_inventory_joined': True, 'raw_ui_capture_retained': False,
                  'later_terminal_log_inventory_joined': True, 'uploaded_actions_artifacts': 0,
                  'complete_gpu_cells': 34, 'runtime_failed_cells': 2,
                  'not_started_cells': 12, 'update_rows': update_count, 'canonical_state_receipts': state_count, 'exact_prior_states_resolved': resolved_count,
                  'native_recorded_prefix_gate': True, 'nodus_pre_failure_prefix_matches': True,
                  'qualified_performance_comparisons': 0, 'tensor_payloads_independently_recomputed': False,
                  'namespace_start_after_service_return_s': delta,
                  'retained_regular_files': len(rows) + len(rows3) + len(inventory4) + all_gpu_files,
                  'third_attempt_streams_verified': streams_checked, 'hosted_diagnostic_streams_verified': streams4,
                  'actual_gpu_host_streams_verified': streams5, 'explicit_unretained_image_streams': 6,
                  'complete_run_updates': new_updates, 'complete_run_state_receipts': new_states,
                  'complete_run_candidates': 8, 'completed_compatibility_runs': 2, 'phase_cells': 8, 'phase_pairs': phase_pair_count, 'complete_run_memory_samples': memory_samples,
                  'pressure_restore_exceeds_prospective_15s': True,
                  'original_private_bytes_independently_verified_by_this_script': False}))
