Files
MeltMind/tools/prepare_r4a.py

69 lines
4.9 KiB
Python

"""Freeze the approved R4(a) metadata contract; never read scientific arrays."""
import argparse
import json
from pathlib import Path
import resource
import time
from gre24_prepare_v2 import sha
from s2_recovery_supervisor import save
def prepare(root):
root.mkdir(parents=True,exist_ok=False)
inventory_path=Path('artifacts/r4a-planning-2026-11-16/input-inventory.json')
inv=json.loads(inventory_path.read_text())
for entry in inv['sources'].values():
if sha(entry['path'])!=entry['sha256']:raise ValueError('Reviewed metadata changed: '+entry['path'])
v5=json.loads(Path(inv['sources']['v5_contract']['path']).read_text())
roster=json.loads(Path(inv['sources']['s2_roster']['path']).read_text())
freeze=json.loads(Path(inv['sources']['v5_preparation_freeze']['path']).read_text())
sources={entry['path']:entry['sha256'] for entry in inv['sources'].values()}
sources[str(inventory_path)]=sha(inventory_path)
sources['docs/r4a-shared-speed-contract-2026-11-16.md']=sha('docs/r4a-shared-speed-contract-2026-11-16.md')
source_code=dict(v5['code_sha256'])
for name,digest in source_code.items():
if sha(name)!=digest:raise ValueError('Frozen v5 source differs: '+name)
names=['r4a_core.py','r4a_part.py','r4a_score.py','run_r4a.py','prepare_r4a.py','test_r4a.py',
's2_custody_common.py','s2_custody_statistics.py','s2_models/features.py','s2_models/objectives.py',
'freeze_g1_components.py','s2_recovery_supervisor.py','s2_recovery_monitoring.py','boundary_distance.py','audit_samples.py']
source_code.update({str(Path('tools')/name):sha(Path('tools')/name) for name in names})
tests=[]
for path in sorted(Path('artifacts/r4a-acceptance-2026-11-16').glob('attempt-*/receipt.json')):
receipt=json.loads(path.read_text());tests.append(dict(path=str(path),sha256=sha(path),**receipt))
sources[str(path)]=sha(path)
if not tests or tests[-1]['status']!='PASS':raise ValueError('Synthetic acceptance missing or failed')
for name,digest in tests[-1]['source_sha256'].items():
if sha(name)!=digest:raise ValueError('Source changed since synthetic acceptance: '+name)
rows=[]
for row in sorted((r for r in roster['parts'] if r['included']),key=lambda r:r['case']):
row=dict(row);row['v5_cache']=freeze['successful'].get(row['case']);rows.append(row)
if len(rows)!=617 or len({r['component_id'] for r in rows})!=209:raise ValueError('Roster changed')
missing=[r['case'] for r in rows if r['v5_cache'] is None]
if missing!=inv['distance_only_missing_parts']:raise ValueError('Cache intersection changed')
setup_cpu=sum(resource.getrusage(resource.RUSAGE_SELF)[:2])
if setup_cpu>60:raise ValueError('Bookkeeping setup reserve insufficient')
contract=dict(version='R4a-shared-cell-speed-v1',authorizing_rulings=['1794819308.674829','1794826344.160199'],
reviewed_git_commit='f9633bd2195cc4a75e888b43a882ba15001fb3d7',created_unix=time.time(),
archive=v5['archive'],archive_stat=v5['archive_stat'],parts=rows,distance_only_missing_parts=missing,
code_sha256=source_code,source_sha256=sources,
label_index=inv['sources']['s2_cached_label_index']['path'],historical_scores=inv['sources']['historical_s2_part_scores']['path'],
worker_cpus=[24,26,28,29],coordinator_cpu=25,compute_worker_cpu_cap=28800,postprocess_worker_cpu_cap=7200,
total_worker_cpu_cap=36000,per_part_cpu_seconds=1800,per_part_wall_seconds=1800,per_part_rss_bytes=4*2**30,
disk_bytes=20*2**30,initial_worker_cpu_seconds=60+sum(t['cpu_seconds'] for t in tests),
initial_charge=dict(synthetic_worker_cpu_seconds=sum(t['cpu_seconds'] for t in tests),
metadata_setup_cpu_observed=setup_cpu,bookkeeping_reserve_seconds=60,
note='60s conservative setup charge within compute cap; actual coordinator/guard CPU separately reported'),
acceptance=tests,zero_retries=True,no_new_labels=True,no_gpu=True,
any_failure_policy='Stop dispatch, terminate active science under live supervisors, retain receipts; no automatic scoring',
bootstrap=dict(seed=2026111408,replicates=2000,interval='percentile95 linear',descriptive=True,no_gate=True),
cache_policy='Validate hash, mesh/IDs/gate/clock and fixed speed construction before reuse; never silent recompute')
save(root/'contract.json',contract)
save(root/'prepared.json',dict(status='READY_NOT_STARTED',contract_sha256=sha(root/'contract.json'),
candidates=611,distance_only_missing=6,total_parts=617,synthetic_checks=tests[-1]['tests'],
scientific_arrays_read=False,scientific_execution=False))
print(json.dumps(dict(root=str(root),contract_sha256=sha(root/'contract.json'),initial_worker_cpu_seconds=contract['initial_worker_cpu_seconds'])))
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);a=p.parse_args();prepare(a.root)