import argparse
import ast
import copy
import json
import os
from pathlib import Path
import shutil
import statistics
import subprocess
import sys
import time
import family_peer
import q2_run_audit
import q3_metrics
import q3_stats
import q5_artifacts
import q5_calibration as q5
import q5_case
import q5_policy
import q5_runtime
import quality_campaign
import quality_launch
HERE = Path(__file__).resolve().parent
POLICY = {'normal_pressure_only': True, 'swap_growth_tolerance_bytes': 0}
def require(ok, reason):
if not ok:
raise ValueError(reason)
def load(path):
return q5_case.loads(Path(path).read_bytes())
def digest(path):
return q5_artifacts.sha256(path)
def reference(path):
path = Path(path).resolve(strict=True)
return {'path': str(path), 'sha256': digest(path)}
def checked(ref):
require(digest(ref['path']) == ref['sha256'], 'bound input changed: ' + ref['path'])
return load(ref['path'])
def save(path, value):
with Path(path).open('x') as stream:
json.dump(value, stream, indent=2, allow_nan=False)
stream.write('\n')
stream.flush()
os.fsync(stream.fileno())
def fresh(path):
path = Path(path).absolute()
require(not path.exists() and not q5.inside_git(path.parent.resolve()), 'fresh namespace outside Git required')
path.mkdir(mode=0o700)
return path
def snapshots(registration):
for artifact in registration['artifacts']:
stat = os.stat(artifact['path'], follow_symlinks=False)
actual = dict(device=stat.st_dev, inode=stat.st_ino, bytes=stat.st_size,
mtime_ns=stat.st_mtime_ns, ctime_ns=stat.st_ctime_ns)
require(actual == artifact['snapshot'], 'retained full-hash/stat witness changed: ' + artifact['path'])
def canonical_sources():
bindings = q5.source_bindings()
bindings.update({str(path): digest(path) for path in HERE.glob('*.py')})
bindings.update({str(path): digest(path) for path in (HERE / 'fixtures').rglob('*') if path.is_file()})
return bindings
def registered_runtime(source_plan, source_selector, family):
if family == 'qwen38':
return Path(load(source_plan.parent / 'recipe.json')['runtime'])
assignments = {node.targets[0].id: node.value for node in ast.parse(source_selector.read_text()).body
if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name)}
base, suffix = assignments['V0'], assignments['V']
require(isinstance(base, ast.Call) and isinstance(base.func, ast.Name) and base.func.id == 'Path' and
len(base.args) == 1 and not base.keywords and isinstance(suffix, ast.BinOp) and
isinstance(suffix.op, ast.Div) and isinstance(suffix.left, ast.Name) and suffix.left.id == 'V0',
'original runtime binding cannot be derived without executing private code')
return Path(ast.literal_eval(base.args[0])) / ast.literal_eval(suffix.right)
def bound_inputs(binding, source_case, case, effective, output):
original = binding['inputs']
require(isinstance(original, dict) and original, 'frozen input hash bindings missing')
replaced = {source_case['variables'][key] for key in ('CARGO', 'SANDBOX_PROOF')}
immutable = {path: expected for path, expected in original.items() if path not in replaced}
for path, expected in immutable.items():
require(digest(path) == expected, 'original immutable input changed: ' + path)
for key in ('CHAT_TEMPLATE', 'CLIENT_APPROVAL_TEMPLATE', 'PEER_BIN'):
path = source_case['variables'][key]
require(path in immutable and case['variables'][key] == path, 'frozen input identity missing: ' + key)
values = case['variables']
proof = checked({'path': values['SANDBOX_PROOF'], 'sha256': values['SANDBOX_PROOF_SHA256']})
cargo = Path(values['CARGO']).resolve(strict=True)
toolchain = Path(proof['toolchain_root']).resolve(strict=True)
require(cargo == toolchain / 'bin/cargo' and toolchain.name == values['TOOLCHAIN'] and
digest(cargo) == proof['cargo_sha256'], 'replacement client toolchain differs from sandbox proof')
current = q5_artifacts.input_hashes(effective, output)
require(all(path not in immutable or immutable[path] == expected for path, expected in current.items()),
'effective input rebases an immutable original hash')
return {**immutable, **current, values['SANDBOX_PROOF']: values['SANDBOX_PROOF_SHA256'],
values['CARGO']: proof['cargo_sha256']}
def prepare(args):
original = load(args.source_plan)
parent = load(args.parent_inputs)
family = args.family
expected_screens = 28 if family == 'qwen38' else 18
incumbent = original.get('incumbent_name', original.get('incumbent'))
require(len(original['screen_order']) == expected_screens and
len(set(original['screen_order'])) == expected_screens and
original['positions'] == ['warmup', 'p1', 'p2', 'p3'] and
set(original['bindings']) == set(original['screen_order']) | {incumbent}, 'registered roster changed')
require(not original['blockers'] and not original['unresolved_mandatory_arms'], 'mandatory input unresolved')
require(original['strict_seconds'] == 360 and original['outer_seconds'] == 450 and
original['outside_lease_spacing_seconds'] == 65, 'registered limits changed')
require(original['comparison_failure_policy'] == {'version': 1, 'reruns_per_position': 2,
'rerun_failure_kinds': ['task'], 'arms': ['peer']}, 'reference retry policy changed')
require(args.previous_runtime.resolve() == registered_runtime(args.source_plan, args.source_selector, family).resolve(),
'previous extension runtime differs from original frozen declaration')
require(not (args.previous_runtime / 'RUN-CLAIM').exists(), 'previous extension already claimed; spend must not reset')
if (args.previous_runtime / 'campaign.json').exists():
require(not load(args.previous_runtime / 'campaign.json').get('attempts'),
'previous extension has attempts; importing its spent positions is required, never restart')
values = parent['family_overrides'][family]
root = fresh(args.output)
(root / 'cases').mkdir()
registration = copy.deepcopy(original)
pins = canonical_sources()
refs = {'source_plan': reference(args.source_plan), 'source_selector': reference(args.source_selector),
'parent_inputs': reference(args.parent_inputs),
'source_prepared': reference(Path(args.source_plan).parent / 'prepared.json')}
prepared = checked(refs['source_prepared'])
require(prepared['plan_sha256'] == refs['source_plan']['sha256'], 'frozen preparation changed')
if family == 'qwen38':
refs['source_recipe'] = reference(args.source_plan.parent / 'recipe.json')
require(checked(refs['source_recipe'])['upstream_executor'] == refs['source_selector'],
'Qwen38 reduction must be the exact registered upstream selector')
else:
require(prepared['executor_sha256'] == refs['source_selector']['sha256'],
'Qwen36 reduction must be the exact prepared selector')
for key in ('old_reference', 'old_population'):
if key in original:
checked(original[key])
pins[original[key]['path']] = original[key]['sha256']
identity = checked(original['peer_identity'])
pins[original['peer_identity']['path']] = original['peer_identity']['sha256']
pins[original['peer_binary']['path']] = original['peer_binary']['sha256']
for key in ('libraries_and_binary_sha256', 'external_dylibs_sha256', 'source_sha256'):
pins.update(identity[key])
bindings = {}
for name, binding in original['bindings'].items():
source_case = checked({'path': binding['case'], 'sha256': binding['sha256']})
require(source_case['family'] == family and '--engine-kind' in source_case['client']['argv'] and
source_case['client']['argv'][source_case['client']['argv'].index('--engine-kind') + 1] == 'peer',
'only the exact registered peer cases are admitted')
case = copy.deepcopy(source_case)
for key in ('MODEL', 'MODEL_SHA256', 'MODEL_ID'):
require(case['variables'][key] == values[key], 'parent original target identity differs: ' + key)
for key in ('CARGO', 'TOOLCHAIN', 'SANDBOX_PROOF', 'SANDBOX_PROOF_SHA256'):
case['variables'][key] = values[key]
approval = load(case['variables']['CLIENT_APPROVAL_TEMPLATE'])
require(approval.get('engine_kind') == 'peer' and approval['agent_template']['engine_kind'] == 'peer',
'hf2q approval cannot authorize peer execution')
require(approval['agent_template']['sandbox_proof_sha256'] ==
source_case['variables']['SANDBOX_PROOF_SHA256'], 'original peer sandbox approval differs')
proof = checked({'path': values['SANDBOX_PROOF'], 'sha256': values['SANDBOX_PROOF_SHA256']})
require('agent_template' not in case['client']['approval']['set'],
'original peer approval already overrides agent_template')
case['client']['approval']['set']['agent_template'] = {
**approval['agent_template'], 'sandbox_proof_sha256': values['SANDBOX_PROOF_SHA256'],
'cargo_sha256': proof['cargo_sha256'], 'toolchain': values['TOOLCHAIN']}
case['policy'] = {**case.get('policy', {}), **POLICY}
q5_case.validate(case)
path = root / 'cases' / (name + '.json')
save(path, case)
effective = q5_case.build_plan(case, q5.builtins(root / 'unexecuted' / name), {})
require(effective['complete'] and all(q5_artifacts.file_checks(effective).values()), 'case input unavailable: ' + name)
require(case['serve'] == source_case['serve'] and case['workload'] == source_case['workload'] and
case['readiness'] == source_case['readiness'] and case['artifact'] == source_case['artifact'],
'frozen runtime settings changed')
inputs = bound_inputs(binding, source_case, case, effective, root / 'unexecuted' / name)
pins.update(inputs)
pins[binding['case']] = binding['sha256']
bindings[name] = {**binding, 'case': str(path), 'sha256': digest(path),
'original_case': {'path': binding['case'], 'sha256': binding['sha256']},
'effective_inputs': inputs}
for key in ('guard', 'guard_sha256', 'prebinding'):
bindings[name].pop(key, None)
pins[str(path)] = digest(path)
registration['bindings'] = bindings
registration['cases'] = bindings
plan = {'schema': 'hf2q.peer-existing-selector-canonical.v1', 'family': family, 'original': refs,
'registration': registration, 'file_sha256': pins,
'supervisor_source_bindings': q5.source_bindings(), 'supervisor_sources': q5.supervisor_sources(),
'native_ownership_sources': q5_runtime.source_bindings(),
'parent_family_values': values, 'strict_policy': POLICY, 'inner_seconds': 360, 'outer_seconds': 450,
'required_volume': str(next(path for path in args.source_plan.resolve().parents if os.path.ismount(path))),
'previous_runtime': str(args.previous_runtime.absolute()),
'cooldown_seconds': 65, 'runtime_qualified': False, 'release_qualified': False}
hostq = args.previous_runtime.parent.parent / 'hostq.sh'
plan['hostq'] = reference(hostq)
pins[str(hostq.resolve())] = digest(hostq)
plan['power_helper'] = reference(HERE.parent / 'qwen36_watchdog_validate.sh')
pins[plan['power_helper']['path']] = plan['power_helper']['sha256']
for ref in refs.values():
pins[ref['path']] = ref['sha256']
save(root / 'plan.json', plan)
print(json.dumps({'prepared': str(root / 'plan.json'), 'models_loaded': 0, 'readiness': False,
'fresh_source_matched_negative_control_required_at_dispatch': True}))
def frozen(path):
plan = load(path)
for name, expected in plan['file_sha256'].items():
require(digest(name) == expected, 'source/input drift: ' + name)
require(plan['supervisor_source_bindings'] == q5.source_bindings(), 'canonical source closure changed')
require(plan['strict_policy'] == POLICY and plan['inner_seconds'] == 360 and
plan['outer_seconds'] == 450 and plan['cooldown_seconds'] == 65, 'registered safety limits changed')
snapshots(plan['registration'])
identity = checked(plan['registration']['peer_identity'])
for alias, binding in identity['dylib_alias_resolution'].items():
require(str(Path(alias).resolve()) == binding['resolved'], 'peer dylib alias resolution changed')
for link, target in binding['symlink_components'].items():
require(os.readlink(link) == target, 'peer dylib alias changed')
previous = Path(plan['previous_runtime'])
require(previous.resolve() == registered_runtime(Path(plan['original']['source_plan']['path']),
Path(plan['original']['source_selector']['path']), plan['family']).resolve(),
'successor runtime differs from original frozen selector identity')
require(not (previous / 'campaign.json').exists() or not load(previous / 'campaign.json').get('attempts'),
'previous extension has historical spend; importing/refunding attempts is forbidden')
if (previous / 'RUN-CLAIM').exists():
claim = load(previous / 'RUN-CLAIM')
require(claim.get('schema') == 'hf2q.peer-selector-claim.v1' and
claim.get('plan') == reference(path) and claim.get('original') == plan['original'] and
claim.get('previous_runtime') == str(previous.resolve()),
'original selector already claimed by another owner; spend must not reset')
require(not any(name.startswith(('HF2Q_Q5_', 'LLAMA_', 'MLX_')) for name in os.environ), 'ambient overrides forbidden')
return plan
def original_reduction(plan, namespace):
ref = plan['original']['source_selector']
require(digest(ref['path']) == ref['sha256'], 'original selector source changed')
tree = ast.parse(Path(ref['path']).read_text())
functions = {node.name: node for node in tree.body if isinstance(node, ast.FunctionDef)}
run = functions['run']
index = next(i for i, node in enumerate(run.body) if isinstance(node, ast.FunctionDef) and node.name == 'configuration')
require(len(run.body[index:]) == 2 and isinstance(run.body[index + 1], ast.Try), 'original selector reduction boundary differs')
select = ast.FunctionDef(name='select', args=ast.arguments(posonlyargs=[], args=[], vararg=None, kwarg=None,
kwonlyargs=[], kw_defaults=[], defaults=[]), body=run.body[index:],
decorator_list=[], returns=None, type_comment=None)
nodes = [functions['rank']]
if 'old_incumbent' in functions:
nodes.append(functions['old_incumbent'])
nodes.append(select)
module = ast.fix_missing_locations(ast.Module(body=nodes, type_ignores=[]))
exec(compile(module, ref['path'], 'exec'), namespace)
return namespace
def storage(root, internal, volume):
volume = Path(volume)
require(os.path.ismount(volume) and root.resolve().is_relative_to(volume.resolve()) and
os.stat(root).st_dev == os.stat(volume).st_dev, 'required external output volume unavailable')
record = {'internal_free_bytes': shutil.disk_usage(internal).free, 'output_free_bytes': shutil.disk_usage(root).free,
'internal_floor_bytes': 25 << 30, 'output_floor_bytes': 12 << 30, 'estimated_output_bytes': 8 << 30}
record['passed'] = record['internal_free_bytes'] >= (25 << 30) and record['output_free_bytes'] >= (20 << 30)
save(root / 'storage.json', record)
require(record['passed'], 'original storage headroom gate refused')
def launch_claim(plan, plan_path, output, previous, control):
runtime = Path(plan['previous_runtime']).resolve(strict=True)
require(not (runtime / 'campaign.json').exists() or not load(runtime / 'campaign.json').get('attempts'),
'original selector already has historical spend')
claim = {'schema': 'hf2q.peer-selector-claim.v1', 'plan': reference(plan_path),
'original': plan['original'], 'previous_runtime': str(runtime), 'output': str(output.resolve()),
'last_completion': previous, 'negative_control': control}
save(runtime / 'RUN-CLAIM', claim) return reference(runtime / 'RUN-CLAIM')
def claimed_launch(plan, record):
claim_path = Path(plan['previous_runtime']).resolve() / 'RUN-CLAIM'
require(record.get('launch_claim') == reference(claim_path), 'attempt has no original selector spend claim')
claim = checked(record['launch_claim'])
require(claim.get('schema') == 'hf2q.peer-selector-claim.v1' and claim['original'] == plan['original'] and
claim['previous_runtime'] == str(Path(plan['previous_runtime']).resolve()) and
checked(claim['plan']) == plan, 'attempt claim owner differs')
unit = f"{record['phase']}-{record['case_name']}-{record['position']}-a{record['repeat']}"
require(record['name'] == unit and Path(record['output']) == Path(claim['output']) / unit / 'q5',
'attempt phase/position/retry differs from its captured unit/output')
ledger = record['attempt_ledger']
require(Path(ledger['path']) == Path(claim['output']) / 'launched' /
f"{record['launch_index']:06d}-{unit}.json", 'attempt ledger is outside claimed sequence')
scheduled = checked(ledger)
require(all(record.get(key) == value for key, value in scheduled.items() if key != 'outcome'),
'attempt differs from durable launched metadata')
packet = load(Path(record['output']).parent / 'execution.json')
require(packet['record'] == {**scheduled, 'attempt_ledger': ledger} and packet['plan'] == claim['plan'] and
packet['negative_control'] == claim['negative_control'],
'attempt packet differs from durable launched metadata')
return scheduled
def replay_samples(receipt, output):
def expanded(row):
host = row.get('host')
if host is None:
return row
vm = {key: host[key] for key in ('free_plus_cached_bytes', 'compressor_bytes', 'wired_bytes',
'anonymous_bytes', 'file_backed_bytes', 'free_bytes', 'speculative_bytes')}
return {**row, 'host': {**host, 'vm': vm, 'swap': {'used_bytes': host['swap_used_bytes']}}}
baseline = [expanded(row) for row in receipt['preflight']['baseline_samples']]
policy = q5_policy.effective_policy(receipt['policy'])
actual, reason = q5_policy.baseline_from(baseline, policy)
require(reason is None and actual == receipt['baseline'], 'strict baseline replay differs')
inputs = receipt['floor_inputs']
monitor = q5_policy.Monitor(actual, policy, inputs['latency_ns'], inputs['latency_source'],
inputs['seed_rate_bytes_per_s'])
declared_ready = (receipt.get('readiness') or {}).get('ready_ns')
allowed_ready = declared_ready if declared_ready is not None else (receipt.get('server') or {}).get('launch_ns')
require(allowed_ready is None or (type(allowed_ready) is int and allowed_ready >= 0),
'captured monitor activation clock invalid')
def feed(row):
require('monitor_ready_ns' in row, 'sample monitor_ready_ns capture missing')
ready = row['monitor_ready_ns']
require(ready is None or (type(ready) is int and ready >= 0 and ready == allowed_ready),
'sample monitor readiness contradicts captured activation')
require(monitor.ready_ns is None or ready == monitor.ready_ns, 'sample monitor readiness reset')
monitor.ready_ns = ready
monitor.feed(expanded(row))
samples_path = Path(receipt['samples']['file'])
with (samples_path if samples_path.is_absolute() else output / samples_path).open() as stream:
for line in stream:
feed(q5_case.loads(line))
feed(receipt['post_cleanup_observation'])
require(declared_ready is None or monitor.ready_ns == declared_ready,
'final monitor readiness contradicts captured activation')
require(monitor.summary() == {key: value for key, value in receipt['samples'].items() if key != 'file'},
'raw strict sampler reduction differs')
return monitor
def settle(plan, record):
claimed_launch(plan, record)
binding = plan['registration']['bindings'][record['case_name']]
case = checked({'path': binding['case'], 'sha256': binding['sha256']})
output = Path(record['output'])
require(record['case'] == binding['case'] and record['case_sha256'] == binding['sha256'],
'attempt case differs from registered configuration')
outer = checked(record['runner_ownership'])
require(outer.get('runner_sha256') == digest(quality_campaign.__file__) and
outer['deadline']['seconds'] == 450 and not outer['deadline']['exceeded'], 'outer source/deadline differs')
quality_launch.validate_runner(record, plan['supervisor_source_bindings'], allow_memory_stop=True)
strict = outer['strict']
control = checked(strict['negative_control'])
require(control.get('supervisor_source_bindings') == plan['supervisor_source_bindings'] and
control.get('supervisor_sources') == plan['supervisor_sources'] and
q5.q5_admission.negative_control_latency(control) == strict['floor_inputs']['latency_ns'],
'strict envelope control source/latency differs')
expected_argv = quality_campaign.q5_argv(binding['case'], output, strict['negative_control']['path']) + [
'--deadline-seconds', '360']
require(record['argv'] == expected_argv, 'actual canonical invocation differs from registered configuration')
require(strict['policy']['normal_pressure_only'] is True and strict['policy']['swap_growth_tolerance_bytes'] == 0 and
strict['deadline']['seconds'] == 360 and outer['deadline']['started_ns'] <= strict['deadline']['started_ns'] <=
outer['launch']['registered_ns'] and
not strict['deadline']['exceeded'] and strict['sampler_alive'] is False and strict['sampler_error'] is None,
'outer strict policy/deadline/observer differs')
power = outer['power']
require(power['helper'] == plan['power_helper'] and not power['errors'] and
power['before']['mode'] == power['after']['mode'] and power['before']['mode'] in ('ac:0', 'ac:2', 'battery:2') and
all(type(power[phase]['thermal']) is int and power[phase]['thermal'] in (0, 1) for phase in ('before', 'after')),
'retained release power/thermal gate differs')
strict_monitor = replay_samples(strict, output)
stop = outer.get('stop')
if stop is not None:
require(strict_monitor.stop is not None and strict_monitor.stop['reason'] == stop['reason'] and
stop['reason'] in q5_policy.MEMORY_STOPS, 'outer stop has no matching strict sample')
return {**record, 'q5': str(output), 'outcome': 'Fail', 'failure_kind': 'memory_stop',
'reason': stop['reason'], 'timing_used_for_selection': False,
'cleanup_empty_ns': outer['cleanup']['empty_ns'], 'launch_ns': outer['launch']['registered_ns']}
require(strict_monitor.stop is None and strict_monitor.max_blind_run == 0 and
strict_monitor.sample_error_count == 0, 'strict outer observations invalid')
receipt = load(output / 'receipt.json')
deadline = receipt.get('deadline') or {}
require(deadline.get('seconds') == 360 and deadline.get('origin') == 'main entry, never reset' and
deadline.get('exceeded') is False and receipt.get('policy', {}).get('normal_pressure_only') is True and
receipt.get('policy', {}).get('swap_growth_tolerance_bytes') == 0, 'inner strict policy/deadline differs')
require(receipt.get('cleanup_proven') is True and receipt['cleanup']['proven'] is True and
receipt.get('sampler_alive') is False and receipt.get('sampler_error') is None and
receipt.get('listener_after_cleanup', {}).get('clear') is True, 'inner cleanup/sampler/listener unproven')
monitor = replay_samples(receipt, output)
if receipt.get('stop') is None:
require(monitor.stop is None, 'unreported strict memory/observation stop')
summary_path = output / 'client/summary.json'
summary = q3_metrics.load_json(summary_path)
outcome, kind, reason = q3_metrics.classify(receipt, summary, q3_metrics.has_oom_marker(output / 'server.stderr'))
if outcome == 'Pass' or (summary is not None and receipt.get('client_native_launch') is not None):
require(summary is not None and receipt.get('client_native_launch') is not None and
(receipt.get('server') or {}).get('native_launch') is not None,
'quality evidence requires actual server/client Native9 launches')
quality_launch.validate(case, {}, record, receipt, summary, summary_path, plan)
q2_run_audit.audit_quality_agents(receipt, summary_path.parent, summary, 'peer')
thermal = record['post_thermal']
require(type(thermal) is int and 0 <= thermal <= 3, 'captured post-run thermal observation required')
require(thermal == power['after']['thermal'], 'post-run thermal differs from owned final observation')
metrics = q3_metrics.run_metrics(output, receipt, summary, 4, thermal)
if outcome == 'Pass':
require(receipt['verdict']['verdict'] == 'CalibrationPass' and metrics['thermal']['valid'] is True and
metrics['tasks_passed'] == 4 and metrics['makespan_s'] > 0 and len(summary['agents']) == 4,
'actual CalibrationPass/thermal/four-task quality required')
for agent in summary['agents'].values():
tests = [tool for tool in agent['tools'] if tool.get('name') == 'run_tests' and tool.get('target') == 'all']
require(tests and tests[-1].get('passed') is True, 'final own-output oracle missing')
actual = family_peer.validate_speculation_proof(output / 'client', load(output / 'client-approval.json'))
require(actual == summary.get('peer_speculation_proof'), 'actual speculation proof differs')
if binding['trained']:
require(all(actual['transports'][transport]['drafted_tokens'] > 0 and
actual['transports'][transport]['accepted_tokens'] > 0 for transport in ('unary', 'sse')),
'trained unary/SSE speculation not exercised')
return {**record, 'q5': str(output), 'outcome': outcome, 'failure_kind': kind, 'reason': reason,
'metrics': metrics, 'cleanup_empty_ns': max(outer['cleanup']['empty_ns'], receipt['cleanup']['empty_ns']),
'launch_ns': outer['launch']['registered_ns']}
def completion_empty(plan, prior):
if prior.get('launch') is not None:
require(prior.get('source_bindings') == plan['supervisor_source_bindings'] and
(prior.get('stop') is None or prior['stop'].get('reason') in q5_policy.MEMORY_STOPS),
'previous outer completion source/stop differs')
launches = [prior['launch']]
else:
require(prior.get('supervisor_source_bindings') == plan['supervisor_source_bindings'] and
prior.get('cleanup_proven') is True, 'previous Q5 cleanup/source closure differs')
launches = [prior['server']['native_launch']]
if prior.get('client_native_launch') is not None:
launches.append(prior['client_native_launch'])
require(prior.get('stop') is None or prior.get('verdict', {}).get('verdict') == 'NegativeControlPass',
'previous Q5 runtime did not complete normally')
quality_launch.validate_cleanup(prior['cleanup'], launches)
return prior['cleanup']['empty_ns']
def execute(args):
packet = load(args.attempt)
checked(packet['plan'])
plan = frozen(Path(packet['plan']['path']))
hostq = Path(plan['hostq']['path'])
require(os.environ.get('HOSTQ_STATE_DIR') is None and
(hostq.parent / 'HOST-LOCK').read_text().strip() == packet['lease_name'],
'actual shared per-attempt hostq measurement lease required')
record = packet['record']
claimed_launch(plan, record)
binding = plan['registration']['bindings'][record['case_name']]
require(record['case'] == binding['case'] and record['case_sha256'] == binding['sha256'],
'queued case binding changed')
control = packet['negative_control']
checked(control)
root = Path(record['output']).parent
expected = quality_campaign.q5_argv(binding['case'], root / 'q5', control['path']) + ['--deadline-seconds', '360']
require(record['argv'] == expected and not Path(record['output']).exists(), 'queued canonical invocation changed')
error = None
with (root / 'stdout').open('xb') as stdout, (root / 'stderr').open('xb') as stderr:
try:
record['q5_exit'] = quality_campaign.subprocess_runner(
expected, dict(os.environ), stdout, stderr, deadline_seconds=450,
strict_policy=POLICY, strict_deadline_seconds=360, negative_control_receipt=control['path'],
power_helper=plan['power_helper']['path'])
except BaseException as exception:
error = exception
record['execution_error'] = repr(exception)
proof_path = root / 'stdout.ownership.json'
if proof_path.exists():
record['runner_ownership'] = reference(proof_path)
outer = load(proof_path) if proof_path.exists() else {}
record['post_thermal'] = ((outer.get('power') or {}).get('after') or {}).get('thermal')
inner = q3_metrics.load_json(root / 'q5/receipt.json') or {}
post_source_error = None
try:
frozen(Path(packet['plan']['path']))
except BaseException as exception:
post_source_error = repr(exception)
record['post_source_error'] = post_source_error
retained = (not (outer.get('cleanup') or {}).get('proven') or
(inner and not inner.get('cleanup_proven')) or
(outer.get('strict') or {}).get('sampler_alive') or inner.get('sampler_alive') or post_source_error)
record['retain_lease'] = bool(retained)
save(root / 'execution-result.json', record)
if retained:
save(root / 'STOP', {'reason': 'Native9 cleanup or sampler shutdown unproven', 'parent_recovery_required': True})
while True:
time.sleep(3600)
return 1 if error is not None else 0
def operate(args, replay=False):
plan = frozen(args.plan)
output = fresh(args.output)
registration = plan['registration']
replay_rows = checked(reference(args.attempts)) if replay else None
if replay:
require(isinstance(replay_rows, list), 'attempts must be the complete ordered JSON array')
claim = load(Path(plan['previous_runtime']) / 'RUN-CLAIM')
require(claim['plan'] == reference(args.plan), 'reduction must use the actual claimed plan')
ledger = sorted((Path(claim['output']) / 'launched').iterdir())
require(all(load(path)['launch_index'] == index for index, path in enumerate(ledger)),
'durable launched ledger has missing/reordered attempts')
if args.configuration is not None:
ledger = [path for path in ledger if
(load(path)['case_name'], load(path)['phase']) == (args.configuration, args.phase)]
require([row.get('attempt_ledger') for row in replay_rows] == [reference(path) for path in ledger],
'replay must include the complete durable launched attempt sequence')
previous_ref = claim['last_completion']
previous_empty = None
else:
require(not (Path(plan['previous_runtime']) / 'RUN-CLAIM').exists(),
'original selector already claimed; no retry/reset')
previous_ref = {'path': str(args.last_completion), 'sha256': args.last_completion_sha256}
previous_empty = completion_empty(plan, checked(previous_ref))
control = checked(reference(args.negative_control_receipt))
require(control.get('supervisor_sources') == plan['supervisor_sources'] and
control.get('supervisor_source_bindings') == plan['supervisor_source_bindings'], 'fresh source-matched NC required')
q5.q5_admission.negative_control_latency(control)
(output / 'launched').mkdir()
claim_ref = launch_claim(plan, args.plan, output, previous_ref, reference(args.negative_control_receipt))
state = {'status': 'Running', 'attempts': [], 'release_qualified': False}
save(output / 'plan.json', plan)
cursor = 0
seen_outputs = set()
def persist():
quality_campaign.save(output / 'campaign.json', state)
persist()
def attempt(name, phase, position, repeat):
nonlocal cursor, previous_empty, previous_ref
frozen(args.plan)
unit = f'{phase}-{name}-{position}-a{repeat}'
if replay:
require(cursor < len(replay_rows), 'unexecuted mandatory position; selection forbidden')
record = replay_rows[cursor]
cursor += 1
require((record['case_name'], record['phase'], record['position'], record['repeat']) ==
(name, phase, position, repeat), 'attempt order/retry/confirmation differs from original selector')
else:
root = output / unit
root.mkdir()
storage(root, Path.home(), plan['required_volume'])
remaining = 65 - (time.monotonic_ns() - previous_empty) / 1e9
if remaining > 0:
time.sleep(remaining)
frozen(args.plan)
binding = registration['bindings'][name]
argv = quality_campaign.q5_argv(binding['case'], root / 'q5', str(args.negative_control_receipt)) + ['--deadline-seconds', '360']
record = {'name': unit, 'case_name': name, 'phase': phase, 'position': position, 'repeat': repeat,
'case': binding['case'], 'case_sha256': binding['sha256'], 'output': str(root / 'q5'),
'argv': argv, 'outcome': 'Launched', 'previous_completion': previous_ref,
'launch_claim': claim_ref, 'launch_index': len(state['attempts'])}
ledger_path = output / 'launched' / f"{record['launch_index']:06d}-{unit}.json"
save(ledger_path, record)
record['attempt_ledger'] = reference(ledger_path)
state['attempts'].append(record)
persist() packet = root / 'execution.json'
lease_name = 'canonical-' + plan['family'] + '-' + unit
save(packet, {'plan': reference(args.plan), 'record': record, 'lease_name': lease_name,
'negative_control': reference(args.negative_control_receipt)})
queue_argv = ['/bin/bash', plan['hostq']['path'], lease_name, 'measure', '--', sys.executable,
'-B', str(Path(__file__).resolve()), 'execute', '--attempt', str(packet)]
with (root / 'hostq.stdout').open('xb') as stdout, (root / 'hostq.stderr').open('xb') as stderr:
code = subprocess.run(queue_argv, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr).returncode
require((root / 'execution-result.json').is_file(), 'queued owner exited without a cleanup result')
record.update(load(root / 'execution-result.json'))
persist()
require(not record.get('retain_lease'), 'queued owner retained the model lease')
if code != 0:
outer = checked(record['runner_ownership'])
require((outer.get('stop') or {}).get('reason') in q5_policy.MEMORY_STOPS,
'queued canonical execution failed: ' + record.get('execution_error', str(code)))
frozen(args.plan)
identity = str(Path(record['output']).resolve())
require(identity not in seen_outputs, 'canonical receipt reused across positions')
seen_outputs.add(identity)
if previous_empty is None:
previous_empty = completion_empty(plan, checked(record['previous_completion']))
row = settle(plan, record)
if previous_empty is not None:
require(row['launch_ns'] - previous_empty >= 65_000_000_000, 'original post-cleanup cooldown violated')
previous_empty = row['cleanup_empty_ns']
previous_ref = record['runner_ownership']
if replay:
state['attempts'].append(row)
else:
record.update(row)
persist()
return row
def result_save(path, value):
if replay and Path(path).name == 'confirmed-reference.json':
require(cursor == len(replay_rows), 'extra attempts forbid a complete selection')
save(path, value)
namespace = dict(require=require, load=load, save=result_save, digest=digest, Path=Path, statistics=statistics,
q3_stats=q3_stats, p=registration, prepared={'bindings': registration['bindings']}, E=output,
state=state, persist=persist, attempt=attempt)
try:
original = original_reduction(plan, namespace)
if replay and args.configuration is not None:
configuration = next(node for node in ast.parse(Path(plan['original']['source_selector']['path']).read_text()).body
if isinstance(node, ast.FunctionDef) and node.name == 'run')
configuration = next(node for node in configuration.body if isinstance(node, ast.FunctionDef) and node.name == 'configuration')
exec(compile(ast.fix_missing_locations(ast.Module(body=[configuration], type_ignores=[])),
plan['original']['source_selector']['path'], 'exec'), original)
require(args.configuration in registration['bindings'], 'unregistered configuration')
score = original['configuration'](args.configuration, args.phase)
require(cursor == len(replay_rows), 'extra attempts cannot be dropped')
save(output / 'configuration-score.json', {'case': args.configuration, 'rank': score,
'complete_selection': False, 'release_qualified': False})
return 0 if score is not None else 3
result = original['select']()
if replay:
require(cursor == len(replay_rows), 'extra attempts cannot be dropped')
return result
except BaseException as error:
state.update(status='Halted', reason=repr(error))
persist()
raise
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
preparation = sub.add_parser('prepare')
preparation.add_argument('--family', choices=('qwen38', 'qwen36'), required=True)
preparation.add_argument('--previous-runtime', type=Path, required=True)
for name in ('source-plan', 'source-selector', 'parent-inputs', 'output'):
preparation.add_argument('--' + name, type=Path, required=True)
for command in ('run', 'reduce'):
child = sub.add_parser(command)
child.add_argument('--plan', type=Path, required=True)
child.add_argument('--output', type=Path, required=True)
if command == 'run':
child.add_argument('--negative-control-receipt', type=Path, required=True)
child.add_argument('--last-completion', type=Path, required=True)
child.add_argument('--last-completion-sha256', required=True)
else:
child.add_argument('--attempts', type=Path, required=True)
child.add_argument('--configuration')
child.add_argument('--phase', choices=('screen', 'confirm'), default='screen')
execution = sub.add_parser('execute')
execution.add_argument('--attempt', type=Path, required=True)
args = parser.parse_args(argv)
if args.command == 'prepare':
return prepare(args)
if args.command == 'execute':
return execute(args)
return operate(args, replay=args.command == 'reduce')
if __name__ == '__main__':
try:
raise SystemExit(main())
except (ValueError, OSError, KeyError, TypeError) as error:
print(json.dumps({'valid': False, 'error': str(error), 'release_qualified': False}), file=sys.stderr)
raise SystemExit(2)