"""Prepare/freeze the one H2-S1 postfit entry; never starts prediction or scoring.""" import json,time,shutil from pathlib import Path import psutil from phase2_fixed_io import BASE from phase2_h1_worker_v2 import sha,checked,save from phase2_home_freeze_io import freeze,verify from phase2_h2_s1_postfit import config,h2_execution_command def read(p):return json.loads(Path(p).read_text()) def main(): root=Path('/home/frank14f/MeltMind-runs/phase2-h2-s1-postfit-2026-11-17') if root.exists():raise FileExistsError('Existing H2 postfit; inspect instead of duplicate') trainroot=BASE/'artifacts/phase2-h2-s1-2026-11-17';pilotroot=BASE/'artifacts/phase2-h2-pilot-2026-11-17';checkpointroot=Path('/home/frank14f/MeltMind-runs/phase2-h2-s1-checkpoint-2026-11-17');aroot=BASE/'artifacts/phase2-b13-e1b-2026-11-17';hroot=BASE/'artifacts/phase2-h1-execution-2026-11-17' cp=verify(checkpointroot,'checkpoint');train=read(trainroot/'contract.json');pilot=read(pilotroot/'contract.json');done=read(trainroot/'complete.json');result=read(checked(trainroot/'worker/result.json',done['worker_result_sha256']));a=read(aroot/'contract.json');h=read(hroot/'contract.json');f=pilot['folds'][0];af=a['folds'][0];hj=h['jobs'][0] if done['status']!='PASS' or done['reasons'] or done['monitor_errors'] or done['worker']['returncode']!=0 or result['test_targets_read'] is not False:raise ValueError('Training PASS required') if train['prediction_gpu_reserve']!=600 or train['postfit_cpu_cap']!=3600 or train['total_h2_gpu_seconds']!=144000:raise ValueError('Original budget mismatch') if hj['baseline_model']!=af['A_baseline'] or set(hj['learning'])!=set(f['learning']) or set(hj['test'])!=set(f['test']):raise ValueError('H1/A baseline model/roles differ') if {r['case'] for r in af['rows']['learning']}!=set(f['learning']) or {r['case'] for r in af['rows']['test']}!=set(f['test']):raise ValueError('H2/A learning/test mismatch') by={r['case']:r for r in af['rows']['test']};rows=[by[k] for k in f['test']] if len(rows)!=121 or len({r['component_id'] for r in rows})!=37 or sum(r['nodes'] for r in rows)!=3125278:raise ValueError('Fixed test roster') entries=[e for e in read(aroot/'predictions-manifest.json')['entries'] if e['fold']==0] if len(entries)!=121 or {e['case'] for e in entries}!=set(f['test']):raise ValueError('A prediction manifest coverage') A={e['case']:e for e in entries} for row in rows: case=row['case'];pr=pilot['parts'][case];entry=A[case] if pr['output_sha256']!=row['v5_cache']['output_sha256'] or pr['t_set']!=row['preparation']['t_set'] or pr['clock_group']!=row['component_id'] or entry['component_id']!=row['component_id'] or entry['A_source_sha256']!=a['A_predictions'][case]['sha256']:raise ValueError('A/H2 cache/clock/component/prediction identity') active=[] for proc in psutil.process_iter(['pid','cmdline']): if h2_execution_command(proc.info['cmdline'] or []):active.append(proc.info['pid']) if active:raise RuntimeError('H2 active processes: '+str(active)) sources={str(BASE/p):digest for p,digest in train['source_sha256'].items()} source_paths=[trainroot/'contract.json',trainroot/'complete.json',trainroot/'worker/result.json',trainroot/'worker/standardization.json',pilotroot/'contract.json',aroot/'contract.json',aroot/'predictions-manifest.json',aroot/'score/result.json',checkpointroot/'contract.json',checkpointroot/'checkpoint-git-freeze.json',checkpointroot/'checkpoint-authorization.json',Path(result['checkpoint'])] sources.update({str(p):sha(p) for p in source_paths});sources[hj['baseline_model']['path']]=hj['baseline_model']['sha256'] sources.update({e['path']:e['sha256'] for e in entries}) for p,digest in sources.items():checked(p,digest) # Opaque hashes only; old score/target values not parsed. codes={} for old in [train,a]: for p,digest in old['code_sha256'].items(): p=str(BASE/p) if p in codes and codes[p]!=digest:raise ValueError('Conflicting source pin: '+p) checked(p,digest);codes[p]=digest extra=['phase2_h2_s1_test_data.py','phase2_h2_s1_postfit.py','phase2_h2_s1_prediction_guard.py','prepare_phase2_h2_s1_postfit.py','test_phase2_h2_s1_postfit.py','phase2_home_freeze_io.py','phase2_local_freeze_io.py','phase2_gate_outcome_review.py','test_phase2_gate_outcome_postfit.py','phase2_gate_outcome_statistics.py','phase2_gate_outcome_postfit.py'] for name in extra:codes[str(BASE/'tools'/name)]=sha(BASE/'tools'/name) doc=BASE/'docs/phase2-h2-s1-postfit-2026-11-17.md';codes[str(doc)]=sha(doc) root.mkdir() comparison=dict(approval='1794921374.599419',fold=0,seed=0,checkpoint_epoch=200,learning_parts=320,validation_parts=111,test_parts=121,test_components=37,full_nodes=3125278,roles_unchanged=True,A_model=hj['baseline_model'],normalization_sha256=train['standardization_sha256'],clock=dict(c=f['c'],path=f['clock_path'],sha256=f['clock_sha256']),metrics=['relative_l2','last_location','kendall_tau_b'],query='Original eligible S2 query; multiplicities once; raw-ID minimum tie rule; last distance/Rg',pooling='Original E1b pooled(): per-arm components require all constituent part metrics defined, component means equally weighted, paired intersection',bootstrap=dict(replicates=2000,seed=2026111408),S2_gate='field H2-A CI upper < +0.005 OR last-location/Rg H2-A CI upper < 0; strict, finite bounds',S2_automatic_launch=False,next_stage='Data sufficiency only after S1 scored; no additional stage launch in this entry',new_fits=0,new_decodes=0,negative_clipping=False,actual_semantic_PASS_before_any_target=True) save(root/'comparison-contract.json',comparison) c=dict(version='H2-S1-final200-postfit-v1',approval='1794921374.599419',checkpoint_root=str(checkpointroot),checkpoint_commit=cp['commit'],checkpoint=result['checkpoint'],checkpoint_sha256=result['checkpoint_sha256'],training_contract=str(trainroot/'contract.json'),training_complete=str(trainroot/'complete.json'),training_result=str(trainroot/'worker/result.json'),pilot_contract=str(pilotroot/'contract.json'),standardization=str(trainroot/'worker/standardization.json'),prior_gpu_seconds=done['cumulative_h2_gpu_seconds'],prior_training_cpu_seconds=done['cpu_seconds_charged'],prediction_gpu_seconds=600,postfit_cpu_seconds=3600,total_h2_gpu_seconds=144000,setup_cpu_seconds=120,gpu_uuid=train['gpu_uuid'],worker_cpus=[0,1],coordinator_cpus=[2],vram_bytes=15*2**30,rss_bytes=16*2**30,disk_bytes=20*2**30,rows=rows,A_predictions=A,A_score=str(aroot/'score/result.json'),A_model=hj['baseline_model'],source_sha256=sources,code_sha256=codes,comparison_contract=str(root/'comparison-contract.json'),comparison_contract_sha256=sha(root/'comparison-contract.json'),new_fits=0,new_decodes=0,no_retry=True,actual_semantic_PASS_required=True,predictions_freeze_before_score=True,validation_used_for_selection=False) save(root/'contract.json',c) shutil.copyfile('/tmp/h2-postfit-synthetic-attempt1.log',root/'synthetic-attempt1.log') shutil.copyfile('/tmp/h2-postfit-synthetic-attempt2.log',root/'synthetic-attempt2.log') save(root/'preparation-attempt1-failure.json',dict(status='STOPPED_BEFORE_ROOT_CREATION',reason='Process suffix match falsely identified preparer PID686575 as H2 execution',fix='Exact Path(arg).name match; regression test added',real_predictions=0,target_values_read=False)) log=(root/'synthetic-attempt2.log').read_text() if 'Ran 21 tests' not in log or not log.rstrip().endswith('OK'):raise ValueError('Actual synthetic acceptance missing') save(root/'acceptance.json',dict(status='PASS',tests=21,elapsed_seconds=1.056,command='python -m unittest tools.test_phase2_h2_s1_postfit -v',log_sha256=sha(root/'synthetic-attempt2.log'),scope='15 input/identity/science/failure synthetic checks plus 6 actual file/Git semantic review checks; CPU only, no real target/prediction/GPU',test_source_sha256=sha(BASE/'tools/test_phase2_h2_s1_postfit.py'),setup_cpu_charge=120,unix=time.time())) save(root/'preparation-audit.json',dict(status='PREPARED_NOT_LAUNCHED',unix=time.time(),h2_active_pids=active,checkpoint_commit=cp['commit'],test_parts=121,test_components=37,test_nodes=3125278,original_H2_A_roles_equal=True,baseline_model_hash_equal=True,A_predictions_hash_checked=121,training_sources_verified=True,test_target_values_read=False,old_score_values_read=False,new_predictions=0,new_scores=0,gate_queue_untouched=True)) freeze(root,'model',[root/'contract.json',Path(c['checkpoint']),Path(c['standardization']),trainroot/'worker/result.json',checkpointroot/'checkpoint-git-freeze.json']) freeze(root,'implementation',[root/'contract.json',root/'comparison-contract.json',root/'acceptance.json',root/'synthetic-attempt1.log',root/'synthetic-attempt2.log',root/'preparation-attempt1-failure.json',root/'preparation-audit.json',*[Path(p) for p in codes]]) proof=verify(root,'implementation');save(root/'expected-review-binding.json',dict(reviewed_commit=proof['commit'],contract_sha256=sha(root/'contract.json'),implementation_proof_sha256=sha(root/'implementation-git-freeze.json'),comparison_contract_sha256=c['comparison_contract_sha256'],code_sha256=codes)) freeze(root,'review-binding',[root/'contract.json',root/'expected-review-binding.json',root/'implementation-git-freeze.json',root/'implementation-authorization.json']);config(root) print(json.dumps(dict(root=str(root),implementation=proof['commit'],contract_sha256=sha(root/'contract.json'),binding_sha256=sha(root/'expected-review-binding.json'),code_files=len(codes),review_pending=True,launched=False))) if __name__=='__main__':main()