Publish bounded phase2 decisions and immutable evidence mapping without bulk history

This commit is contained in:
MeltAstra committed 2026-11-17 19:39:05 +08:00
1 parent 7b470069f7
commit 1e1d5a6515
180 files changed
+1947655 -3

No files matched your search

+167
View File
@@ -0,0 +1,167 @@
"""Five-fold held-out-test confirmation; immutable G/model reuse and bounded queue."""
import argparse,fcntl,json,os,resource,sys,time,subprocess,signal,traceback
from pathlib import Path
import numpy as np
import xgboost as xgb
from phase2_h1_worker_v2 import checked,sha,save
from phase2_fixed_io import BASE,freeze,verify
from phase2_b1213_features import b13,cached,GeometryFailure
from phase2_b1213_gate import train as fit,coverage
from r4bc_guard import supervise
from s2_recovery_supervisor import tree_usage
from s2_recovery_monitoring import disk_usage
from s2_custody_common import prediction_inputs
from s2_custody_statistics import part_metrics
from r4bc_common import paired_difference
def read(p):return json.loads(Path(p).read_text())
def config(root):
c=read(root/'contract.json')
if c['approval']!='1794905109.925079' or c['evaluation_role']!='test':raise PermissionError('Final test ruling required')
if c['new_geometry_indices'] or c['coverage_gate'] is not False or len(c['reused_geometry'])!=552:raise PermissionError('E1b reuses full552; no geometry or coverage gate')
if xgb.__version__!='2.1.4' or np.__version__!='1.26.4':raise ValueError('Library identity')
for p,h in {**c['source_sha256'],**c['code_sha256']}.items():checked(BASE/p,h)
st=Path(c['archive']).stat();prior=c['archive_stat']
if (st.st_size,st.st_mtime_ns,st.st_ino)!=(prior['bytes'],prior['mtime_ns'],prior['inode']):raise ValueError('Original archive identity changed')
alltest=[]
for f in c['folds']:
for role in ['learning','test']:
for row in f['rows'][role]:
a=next(a for a in row['assignments'] if a['fold']==f['fold'])
if a['role']!=role or (role=='learning' and '100' not in a['learning_pools']):raise ValueError('Frozen fold role mismatch')
if {r['component_id'] for r in f['rows']['learning']}&{r['component_id'] for r in f['rows']['test']}:raise ValueError('Component leakage')
alltest.extend(r['case'] for r in f['rows']['test'])
if len(alltest)!=552 or len(set(alltest))!=552:raise ValueError('Test must partition552')
return c
def field(root,c,index):
row=c['parts'][index];dest=root/'parts'/f'{index:04d}';start=time.process_time()
try:e,r=b13(row,c,dest)
except GeometryFailure as exc:e=np.full((row['nodes'],2),np.nan);r=dict(status='SCIENTIFIC_MISSING',reason=str(exc),labels_read=False)
if e.shape!=(row['nodes'],2) or np.isinf(e).any():raise ValueError('Invalid G readout')
np.save(dest/'extra.npy',e,allow_pickle=False);save(dest/'result.json',dict(case=row['case'],index=index,component_id=row['component_id'],extra_sha256=sha(dest/'extra.npy'),**r,cpu_seconds=time.process_time()-start))
def predict(root,c,fold):
d=root/'folds'/str(fold);verify(d,'model');f=c['folds'][fold];model=xgb.XGBRegressor();model.load_model(d/'phases/train/model.ubj');dest=d/'phases/predict';dest.mkdir(parents=True,exist_ok=False)
by={r['case']:i for i,r in enumerate(c['parts'])};out=[]
for row in f['rows']['test']:
q=prediction_inputs(row);raw=cached(row,'raw_ids');ix=np.searchsorted(raw,q['raw_ids'])
if np.any(ix>=len(raw)) or not np.array_equal(raw[ix],q['raw_ids']):raise ValueError('Query IDs')
p=root/'parts'/f"{by[row['case']]:04d}";r=read(p/'result.json');e=np.load(checked(p/'extra.npy',r['extra_sha256']),allow_pickle=False);features=cached(row,'features');X=np.column_stack([features[ix],e[ix]]).astype(np.float32)
pred=np.asarray(model.predict(X),np.float64)*row['preparation']['t_set'];base=c['A_predictions'][row['case']]
if base['fold']!=fold or base['pool']!=100:raise ValueError('A prediction role mismatch')
with np.load(checked(base['path'],base['sha256']),allow_pickle=False) as z:
if not np.array_equal(z['raw_ids'],raw):raise ValueError('A original raw IDs differ')
A=z['A_seconds'][ix].copy()
if not np.isfinite(pred).all() or not np.isfinite(A).all():raise ValueError('Nonfinite prediction')
p=dest/(row['case']+'.npz');np.savez_compressed(p,pred=pred,A=A,raw_ids=q['raw_ids'],counts=q['counts'],coordinates_over_Rg=q['coordinates_over_Rg'],near_wall=q['near_wall'])
out.append(dict(case=row['case'],component_id=row['component_id'],fold=fold,path=str(p),sha256=sha(p),G_valid=r['status']=='GEOMETRY_COMPLETE',A_source_sha256=base['sha256']))
save(dest/'progress.json',dict(parts=len(out),test_labels_read=False))
save(dest/'manifest.json',dict(entries=out,test_labels_read=False))
def pooled(rows):
groups={}
for r in rows:groups.setdefault(r['component_id'],[]).append(r)
result={}
for metric in ['relative_l2','last_location','kendall_tau_b']:
values={arm:{g:float(np.mean([r[arm][metric]['value'] for r in rs])) for g,rs in groups.items() if all(r[arm][metric]['value'] is not None for r in rs)} for arm in ['new','A']}
result[metric]=dict(means={a:float(np.mean(list(v.values()))) if v else None for a,v in values.items()},components={a:len(v) for a,v in values.items()},new_minus_A=paired_difference(values['new'],values['A']))
return result
def branch_decision(metrics):
primary=metrics['relative_l2'];complete=primary['components']==dict(new=204,A=204);high=primary['new_minus_A']['high']
return 'CONFIRMED_FIXED_GENERIC_CONTEXT_INCREMENT' if complete and high is not None and high<0 else 'NOT_CONFIRMED_FIXED_RECIPE' if complete else 'PARK_UNDEFINED'
def score(root,c):
verify(root,'predictions');dest=root/'score';dest.mkdir(exist_ok=False);by={r['case']:r for r in c['parts']};rows=[]
manifest=read(root/'predictions-manifest.json')['entries']
if len(manifest)!=552 or {e['case'] for e in manifest}!=set(by):raise ValueError('Full test roster incomplete')
for e in manifest:
row=by[e['case']];save(dest/'next-target-access.json',dict(case=e['case'],fold=e['fold'],role='test',target_sha256=row['v5_cache']['output_sha256']['seconds.npy']))
truth=cached(row,'seconds');raw=cached(row,'raw_ids')
with np.load(checked(e['path'],e['sha256']),allow_pickle=False) as z:
ix=np.searchsorted(raw,z['raw_ids'])
if not np.array_equal(raw[ix],z['raw_ids']):raise ValueError('Score raw IDs')
rr=dict(case=e['case'],component_id=e['component_id'],fold=e['fold'],G_valid=e['G_valid'])
for arm in ['new','A']:rr[arm]=part_metrics(z['pred' if arm=='new' else 'A'],truth[ix],z['counts'],z['near_wall'],z['raw_ids'],z['coordinates_over_Rg'],int(e['case'].split('_')[0]))
rows.append(rr);save(dest/'progress.json',dict(parts=len(rows)))
result=pooled(rows);decision=branch_decision(result)
save(dest/'result.json',dict(status='COMPLETE',decision=decision,parts=552,components=204,metrics=result,per_fold={str(f):pooled([r for r in rows if r['fold']==f]) for f in range(5)},G_subsets_descriptive={str(valid):dict(parts=sum(r['G_valid']==valid for r in rows),metrics=pooled([r for r in rows if r['G_valid']==valid])) for valid in [True,False]},per_fold_G_counts={str(f):dict(valid=sum(r['fold']==f and r['G_valid'] for r in rows),invalid=sum(r['fold']==f and not r['G_valid'] for r in rows)) for f in range(5)},rows=rows,invalid_G_parts=[r['case'] for r in rows if not r['G_valid']],gate='pooled field CI high<0 only',validation_used=False,E2_started=False))
def worker(root,mode,index):
c=config(root)
if mode=='field':field(root,c,index)
elif mode=='train':
f=c['folds'][index];d=root/'folds'/str(index);(d/'phases/train').mkdir(parents=True,exist_ok=False);fit(d,dict(c,rows=f['rows'],extra_columns=2))
elif mode=='predict':predict(root,c,index)
else:score(root,c)
def guard(root,mode,index,slot):
c=config(root);os.sched_setaffinity(0,[c['worker_cpus'][slot]]);d=root/'guards'/f'{mode}-{index:04d}';start=time.process_time();cap=c['job_caps'][mode]
result=supervise([sys.executable,'tools/phase2_b13_e1b.py','worker',str(root),mode,str(index)],d,dict(cpu_seconds=cap,wall_seconds=cap+120,rss_bytes=8*2**30,disk_bytes=5*2**30),global_stop=root/'global-stop.json')
save(d/'guard-result.json',dict(mode=mode,index=index,guard=result,guard_cpu_seconds=time.process_time()-start));return 0 if result['status']=='PASS' else 1
def run(root):
c=config(root);os.sched_setaffinity(0,[30,31]);lock=(root/'run.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if (root/'started.json').exists():raise FileExistsError('Single E1 launch')
if not c['projection']['passed']:raise RuntimeError('PARK_PROJECTION_BEFORE_LAUNCH')
start=time.process_time();u0=resource.getrusage(resource.RUSAGE_CHILDREN);settled=0.;records=[];active={};requested=[]
def total():
u=resource.getrusage(resource.RUSAGE_CHILDREN);return c['prior_E1_cpu_seconds']+60+max(settled,u.ru_utime+u.ru_stime-u0.ru_utime-u0.ru_stime)+time.process_time()-start+sum(tree_usage(p.pid)[0] for p,_,_ in active.values())
def batch(mode,ids,phase_cap=None):
nonlocal settled
pending=list(ids);phase0=total()
while pending or active:
if requested or total()>10800-120 or (phase_cap and total()-phase0>phase_cap) or disk_usage(root)>20*2**30 or sum(tree_usage(p.pid)[1] for p,_,_ in active.values())>32*2**30:raise RuntimeError('GLOBAL_RESOURCE_OR_SIGNAL_STOP')
for slot,(p,index,_) in list(active.items()):
if p.poll() is not None:
r=read(root/'guards'/f'{mode}-{index:04d}'/'guard-result.json');settled+=r['guard']['cpu_seconds']+r['guard_cpu_seconds'];records.append(r);del active[slot]
if p.returncode!=0 or r['guard']['status']!='PASS':raise RuntimeError('WORKER_NOT_PASS')
for slot in range(4):
if pending and slot not in active:
reserve=sum(c['job_caps'][mode] for _ in active)+c['job_caps'][mode]+300
if total()+reserve>10800:
if not active:raise RuntimeError('BUDGET_RESERVATION_EXHAUSTED')
break
index=pending.pop(0)
if mode=='field':(root/'parts'/f'{index:04d}').mkdir(parents=True,exist_ok=False)
p=subprocess.Popen([sys.executable,'tools/phase2_b13_e1b.py','guard',str(root),mode,str(index),str(slot)],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True);active[slot]=(p,index,time.time())
save(root/'live-progress.json',dict(stage=mode,pending=len(pending),active=[dict(slot=k,pid=p.pid,index=i) for k,(p,i,_) in active.items()],settled_jobs=len(records),cumulative_cpu_seconds=total(),unix=time.time()));time.sleep(.2)
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json')))
old={s:signal.signal(s,lambda signum,frame:requested.append(signum)) for s in [signal.SIGTERM,signal.SIGINT]}
try:
batch('field',c['new_geometry_indices'],2200)
entries=[];results={}
for i,row in enumerate(c['parts']):
p=root/'parts'/f'{i:04d}'/'result.json';r=read(p);checked(p.parent/'extra.npy',r['extra_sha256']);results[row['case']]=r;entries.append(dict(case=row['case'],index=i,result_sha256=sha(p)))
cov={str(f['fold']):{role:coverage(rows,results) for role,rows in f['rows'].items()} for f in c['folds']};save(root/'coverage.json',cov);save(root/'features-manifest.json',dict(entries=entries,all552_terminal=True,labels_read=False))
# E1b separately approved full-roster deployment test; original E1 gate remains immutable.
for f in c['folds']:
d=root/'folds'/str(f['fold']);d.mkdir(parents=True,exist_ok=False);save(d/'contract.json',c);save(d/'features-manifest.json',read(root/'features-manifest.json'));(d/'parts').symlink_to(root/'parts',target_is_directory=True)
freeze(d,'features',[d/'contract.json',d/'features-manifest.json',root/'coverage.json',*[BASE/p for p in c['code_sha256']]])
d=root/'folds/0/phases/train';d.mkdir(parents=True,exist_ok=False)
import shutil
shutil.copyfile(checked(c['fold0_model']['path'],c['fold0_model']['sha256']),d/'model.ubj');save(d/'result.json',dict(status='FIT_REUSED_BY_HASH',checkpoint_sha256=sha(d/'model.ubj'),original=c['fold0_model']))
batch('train',[1,2,3,4])
for f in range(5):
d=root/'folds'/str(f);freeze(d,'model',[d/'contract.json',d/'phases/train/model.ubj',d/'phases/train/result.json',*[BASE/p for p in c['code_sha256']]])
batch('predict',range(5));entries=[]
for f in range(5):entries.extend(read(root/'folds'/str(f)/'phases/predict/manifest.json')['entries'])
save(root/'predictions-manifest.json',dict(entries=entries,all_predictions_terminal=True));freeze(root,'predictions',[root/'contract.json',root/'predictions-manifest.json',*[BASE/p for p in c['code_sha256']]])
batch('score',[0]);save(root/'complete.json',dict(status='COMPLETE',decision=read(root/'score/result.json')['decision'],cumulative_cpu_seconds=total(),records=records,new_fits=4,reused_fold0=True,E2_started=False))
except BaseException as exc:
save(root/'global-stop.json',dict(reason=type(exc).__name__+': '+str(exc)))
for p,_,_ in active.values():
try:os.kill(p.pid,signal.SIGTERM)
except ProcessLookupError:pass
for p,index,_ in active.values():p.wait()
# Reaped guard/worker child CPU is included once by total().
active.clear();save(root/'complete.json',dict(status='STOPPED',reason=type(exc).__name__+': '+str(exc),cumulative_cpu_seconds=total(),records=records,accounting_complete=True,retry=False));raise
finally:
for s,h in old.items():signal.signal(s,h)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('action',choices=['run','worker','guard']);p.add_argument('root',type=Path);p.add_argument('mode',nargs='?');p.add_argument('index',nargs='?',type=int);p.add_argument('slot',nargs='?',type=int);a=p.parse_args()
if a.action=='run':run(a.root)
elif a.action=='worker':worker(a.root,a.mode,a.index)
else:raise SystemExit(guard(a.root,a.mode,a.index,a.slot))
+101
View File
@@ -0,0 +1,101 @@
"""5002/5314 continuation: reused21, three explicit recoveries,407 new."""
import argparse,fcntl,json,os,resource,sys,time,subprocess,signal
import numpy as np
from pathlib import Path
from phase2_b1213_gate import config,coverage
from phase2_h1_worker_v2 import checked,save,sha
from phase2_fixed_io import BASE,freeze
from r4bc_guard import supervise
from s2_recovery_supervisor import tree_usage
from s2_recovery_monitoring import disk_usage
def read(p):return json.loads(Path(p).read_text())
def validated(root):
c=config(root)
if c['continuation_approval']!='1794905002.631809' or c['explicit_recovery_indices']!=[16,21,22] or set(c['new_indices'])!=(set(range(431))-set(c['reused_indices'])):raise PermissionError('Only approved3 recoveries and407 never attempted')
if len(c['reused_indices'])!=21 or len(c['new_indices'])!=410 or c['part_cpu_seconds']!=300 or c['part_wall_seconds']!=300 or c['total_cpu_cap']!=16000:raise PermissionError('Fixed scope/caps')
if {role:len(rows) for role,rows in c['rows'].items()}!={'learning':320,'validation':111}:raise PermissionError('Original431 roles only')
return c
def guard(root,mode,index,slot,cap):
c=validated(root);os.sched_setaffinity(0,[c['worker_cpus'][slot]]);d=root/'guards'/f'{mode}-{index:04d}';start=time.process_time()
cmd=[sys.executable,c['scientific_entry'],mode,str(root)]+([str(index)] if mode in ['field','prep'] else [])
result=supervise(cmd,d,dict(cpu_seconds=cap,wall_seconds=c['part_wall_seconds'] if mode in ['field','prep'] else cap+60,rss_bytes=c['rss_bytes'],disk_bytes=c['disk_bytes']),global_stop=root/'global-stop.json')
save(d/'guard-result.json',dict(mode=mode,index=index,guard=result,guard_cpu_seconds=time.process_time()-start));return 0 if result['status']=='PASS' else 1
def resource_failure(guard,cap):
return cap==300 and guard['status']=='FAILED' and not guard.get('monitor_errors') and guard.get('stop_reason') in ['cpu_limit','wall_limit','cpu_limit_after_exit','wall_limit_after_exit']
def run(root):
c=validated(root);os.sched_setaffinity(0,[c['coordinator_cpu']]);lock=(root/'run.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if (root/'started.json').exists():raise FileExistsError('Single labelled continuation')
start=time.process_time();u0=resource.getrusage(resource.RUSAGE_CHILDREN);settled=0.;records=[];active={};requested=[]
def total():
u=resource.getrusage(resource.RUSAGE_CHILDREN);return c['prior_cpu_seconds']+60+max(settled,u.ru_utime+u.ru_stime-u0.ru_utime-u0.ru_stime)+time.process_time()-start+sum(tree_usage(p.pid)[0] for p,_,_ in active.values())
def batch(mode,ids,jobcap,geometry=False):
nonlocal settled
pending=list(ids)
while pending or active:
sample=dict(cpu_seconds=total(),disk_bytes=disk_usage(root),rss_bytes=sum(tree_usage(p.pid)[1] for p,_,_ in active.values()),signals=list(requested))
reasons=[]
if requested:reasons.append('COORDINATOR_SIGNAL')
if sample['cpu_seconds']>c['total_cpu_cap']-120:reasons.append('TOTAL_CPU_RESERVE')
if geometry and sample['cpu_seconds']>c['geometry_cpu_cap']-120:reasons.append('GEOMETRY_CPU_RESERVE')
if sample['disk_bytes']>c['disk_bytes']:reasons.append('DIRECTORY_DISK_LIMIT')
if sample['rss_bytes']>32*2**30:reasons.append('TREE_RSS_LIMIT')
if reasons:
save(root/'stop-trigger.json',dict(reasons=reasons,sample=sample,unix=time.time()));raise RuntimeError('GLOBAL_RESOURCE_OR_SIGNAL_STOP')
for slot,(p,index,cap) in list(active.items()):
if p.poll() is not None:
rr=read(root/'guards'/f'{mode}-{index:04d}'/'guard-result.json');settled+=rr['guard']['cpu_seconds']+rr['guard_cpu_seconds'];records.append(rr);del active[slot]
if p.returncode or rr['guard']['status']!='PASS':
if geometry and resource_failure(rr['guard'],cap):
row=c['parts'][index];dest=root/'parts'/f'{index:04d}';np.save(dest/'extra.npy',np.full((row['nodes'],2),np.nan),allow_pickle=False)
save(dest/'result.json',dict(status='RESOURCE_FAIL',reason=rr['guard']['stop_reason'],case=row['case'],component_id=row['component_id'],index=index,extra_sha256=sha(dest/'extra.npy'),partial_families_retained_not_merged=True,geometry_complete=False,labels_read=False,guard_receipt_sha256=sha(root/'guards'/f'{mode}-{index:04d}'/'guard-result.json')))
else:raise RuntimeError('WORKER_NOT_PASS')
slots=range(len(c['worker_cpus'])) if geometry else range(1)
for slot in slots:
if pending and slot not in active:
cap=min(jobcap,c['total_cpu_cap']-total()-sum(z[2] for z in active.values())-300)
if geometry:cap=min(cap,c['geometry_cpu_cap']-total()-sum(z[2] for z in active.values())-120)
if cap<1 or (geometry and cap<jobcap):
if not active:raise RuntimeError('BUDGET_RESERVATION_EXHAUSTED')
break
i=pending.pop(0)
if geometry:(root/'parts'/f'{i:04d}').mkdir(parents=True,exist_ok=False)
p=subprocess.Popen([sys.executable,'tools/phase2_b14_resource_continuation.py','guard',str(root),mode,str(i),str(slot),str(cap)],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True);active[slot]=(p,i,cap)
save(root/'live-progress.json',dict(stage=mode,pending=len(pending),active=[dict(pid=p.pid,index=i,slot=s) for s,(p,i,_) in active.items()],new_terminal=len(records),cumulative_cpu_seconds=total(),unix=time.time()));time.sleep(.2)
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json'),prior_cpu_seconds=c['prior_cpu_seconds'],reused=21,explicit_recoveries=3,never_attempted=407))
old={s:signal.signal(s,lambda signum,frame:requested.append(signum)) for s in [signal.SIGTERM,signal.SIGINT]}
try:
mode='field' if c['kind']=='B14' else 'prep';batch(mode,c['new_indices'],c['part_cpu_seconds'],True)
entries=[];results={}
for i,row in enumerate(c['parts']):
p=root/'parts'/f'{i:04d}'/'result.json';rr=read(p);results[row['case']]=rr;entries.append(dict(case=row['case'],index=i,result_sha256=sha(p)))
save(root/'features-manifest.json',dict(entries=entries,all431_terminal=True,labels_read=False,reused_completed21=True,explicit_recoveries=[16,21,22]))
cov={role:coverage(rows,results) for role,rows in c['rows'].items()};save(root/'coverage.json',cov)
freeze(root,'features',[root/'contract.json',root/'features-manifest.json',root/'coverage.json',*[BASE/p for p in c['code_sha256']]])
if c['kind']=='B14' and any(v['fraction']<.8 for v in cov.values()):
save(root/'complete.json',dict(status='COMPLETE',decision='PARK_CHANNEL_COVERAGE',coverage=cov,cumulative_cpu_seconds=total(),records=records,models_fit=0,old_stop_preserved=True));return
for mode in ['train','predict','score']:
if mode=='predict':freeze(root,'model',[root/'contract.json',root/'phases/train/model.ubj',root/'phases/train/result.json',*[BASE/p for p in c['code_sha256']]])
if mode=='score':freeze(root,'predictions',[root/'contract.json',root/'phases/predict/manifest.json',*[BASE/p for p in c['code_sha256']]])
d=root/'phases'/mode;d.mkdir(parents=True,exist_ok=False)
batch(mode,[0],c['phase_caps'][mode])
save(root/'complete.json',dict(status='COMPLETE',decision=read(root/'phases/score/result.json')['decision'],cumulative_cpu_seconds=total(),records=records,models_fit=1,old_stop_preserved=True,retry=False))
except BaseException as exc:
save(root/'global-stop.json',dict(reason=type(exc).__name__+': '+str(exc)))
for p,_,_ in active.values():
try:os.kill(p.pid,signal.SIGTERM)
except ProcessLookupError:pass
for p,index,_ in active.values():
p.wait();receipt=root/'guards'/f'{mode}-{index:04d}'/'guard-result.json'
if receipt.exists():records.append(read(receipt))
active.clear();save(root/'complete.json',dict(status='STOPPED',reason=type(exc).__name__+': '+str(exc),cumulative_cpu_seconds=total(),records=records,old_stop_preserved=True,accounting_complete=True,retry=False));raise
finally:
for s,h in old.items():signal.signal(s,h)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('action',choices=['run','guard']);p.add_argument('root',type=Path);p.add_argument('mode',nargs='?');p.add_argument('index',nargs='?',type=int);p.add_argument('slot',nargs='?',type=int);p.add_argument('cap',nargs='?',type=float);a=p.parse_args()
if a.action=='run':run(a.root)
else:raise SystemExit(guard(a.root,a.mode,a.index,a.slot,a.cap))
+95
View File
@@ -0,0 +1,95 @@
"""7848 B15 prediction continuation: same per-part science, model/first prediction reused."""
import argparse,fcntl,json,os,resource,signal,subprocess,sys,time
from pathlib import Path
import numpy as np
import xgboost as xgb
import joblib
from phase2_b15_gate import load,entries,positive_speed,flow_mesh,solve_eikonal,strict_volume_cdf,prediction_inputs,cached,score
from phase2_b1213_gate import config as original_config
from phase2_h1_worker_v2 import checked,sha,save
from phase2_fixed_io import BASE,verify
from phase2_local_freeze_io import freeze
from r4bc_guard import supervise
from s2_recovery_supervisor import tree_usage
from s2_recovery_monitoring import disk_usage
def read(p):return json.loads(Path(p).read_text())
def config(root):
c=original_config(root)
if c['continuation_approval']!='1794907848.106509' or c['total_cpu_cap']!=8000:raise PermissionError('One prediction-only extension')
if c['first_prediction']['case']!=c['rows']['validation'][0]['case'] or len(c['rows']['validation'])!=111:raise ValueError('Frozen first/remaining validation identity')
checked(root/'phases/train/model.ubj',c['reused_model_sha256'])
return c
def projection(charged,completed_cpu,completed_nodes,total_nodes):
if completed_nodes<=0 or total_nodes<completed_nodes or min(charged,completed_cpu)<0:raise ValueError('Invalid completed-cost projection')
return charged+1.25*completed_cpu*(total_nodes-completed_nodes)/completed_nodes
def predict(root,c):
verify(root,'model');dest=root/'phases/predict';by=entries(root);model=xgb.XGBRegressor();model.load_model(root/'phases/train/model.ubj');baseline=joblib.load(checked(c['baseline']['model_path'],c['baseline']['model_sha256']));manifest=[dict(c['first_prediction'])]
for row in c['rows']['validation'][1:]:
begin=time.process_time()
with load(root,by[row['case']])[0] as z:
if not np.all(z['geometry_valid']):raise ValueError('Validation contains invalid geometry; no tet deletion')
a=positive_speed(model.predict(z['X']));g=flow_mesh((z['points']-z['center'])/float(z['Rg']),z['tets'])
begin_solver=time.process_time();phi=solve_eikonal(g,z['sources'],a);solver_cpu=time.process_time()-begin_solver;U=strict_volume_cdf(phi,z['mass']);pred_all=c['clock_c']*U
np.savez_compressed(dest/(row['case']+'-field.npz'),raw_ids=z['raw_ids'],raw_cells=z['raw_cells'],speed=a,phi=phi,U=U,pred_normalized=pred_all)
q=prediction_inputs(row);ix=np.searchsorted(z['raw_ids'],q['raw_ids'])
if np.any(ix>=len(z['raw_ids'])) or not np.array_equal(z['raw_ids'][ix],q['raw_ids']):raise ValueError('Query identity')
f=cached(row,'features');A=np.asarray(baseline.predict(f[ix].astype(np.float32)),np.float64);p=dest/(row['case']+'.npz')
np.savez_compressed(p,pred=pred_all[ix],A=A,raw_ids=q['raw_ids'],counts=q['counts'],coordinates_over_Rg=q['coordinates_over_Rg'])
manifest.append(dict(case=row['case'],component_id=row['component_id'],path=str(p),sha256=sha(p),full_field_sha256=sha(dest/(row['case']+'-field.npz')),geometry_valid=True,solver_cpu_seconds=solver_cpu,cpu_seconds=time.process_time()-begin,clock_learning_only=c['clock_c']))
save(dest/'progress.json',dict(parts=len(manifest),last=manifest[-1],completed_prediction_cpu_seconds=sum(e['cpu_seconds'] for e in manifest),validation_targets_read=False))
save(dest/'manifest.json',dict(entries=manifest,validation_labels_read=False,all_validation_complete=True))
def guard(root,mode,cap):
c=config(root);os.sched_setaffinity(0,[4]);start=time.process_time();d=root/'guards'/mode
g=supervise([sys.executable,'tools/phase2_b15_prediction_continue.py','worker',str(root),mode],d,dict(cpu_seconds=cap,wall_seconds=cap+120,rss_bytes=c['rss_bytes'],disk_bytes=c['disk_bytes']-c['referenced_storage_bytes']),global_stop=root/'global-stop.json')
save(d/'guard-result.json',dict(mode=mode,guard=g,guard_cpu_seconds=time.process_time()-start));return 0 if g['status']=='PASS' else 1
def run(root):
c=config(root);os.sched_setaffinity(0,[29]);lock=(root/'run.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if (root/'started.json').exists():raise FileExistsError('Single prediction continuation')
start=time.process_time();u0=resource.getrusage(resource.RUSAGE_CHILDREN);records=[];settled=0.;active=None;requested=[]
def total():
u=resource.getrusage(resource.RUSAGE_CHILDREN);return c['prior_cpu_seconds']+60+max(settled,u.ru_utime+u.ru_stime-u0.ru_utime-u0.ru_stime)+time.process_time()-start+(tree_usage(active.pid)[0] if active else 0)
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json'),prior_cpu_seconds=c['prior_cpu_seconds'],reused_models=1,reused_predictions=1,remaining_predictions=110,refit=False))
old={s:signal.signal(s,lambda signum,frame:requested.append(signum)) for s in [signal.SIGTERM,signal.SIGINT]}
try:
for mode in ['predict','score']:
if mode=='score':
freeze(root,'predictions',[root/'contract.json',root/'phases/predict/manifest.json',*[BASE/p for p in c['code_sha256']]]);(root/'phases/score').mkdir()
cap=8000-total()-120
if cap<=0:raise RuntimeError('TOTAL_RESERVE_EXHAUSTED')
active=subprocess.Popen([sys.executable,'tools/phase2_b15_prediction_continue.py','guard',str(root),mode,str(cap)],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True)
while active.poll() is None:
charged=total();usage=tree_usage(active.pid);sample=dict(cpu_seconds=charged,disk_bytes=c['referenced_storage_bytes']+disk_usage(root),rss_bytes=usage[1],signals=list(requested));reasons=[];estimate=charged
if mode=='predict':
progress=read(root/'phases/predict/progress.json');n=progress['parts'];weights=[r['nodes'] for r in c['rows']['validation']];estimate=projection(charged,progress['completed_prediction_cpu_seconds'],sum(weights[:n]),sum(weights))
if estimate>8000:reasons.append('PROJECTION_EXCEEDS_8000')
if charged>8000-120:reasons.append('TOTAL_CPU_RESERVE')
if sample['disk_bytes']>c['disk_bytes']:reasons.append('CUMULATIVE_DIRECTORY_DISK_LIMIT')
if sample['rss_bytes']>c['rss_bytes']:reasons.append('RSS_LIMIT')
if requested:reasons.append('COORDINATOR_SIGNAL')
if reasons:save(root/'stop-trigger.json',dict(reasons=reasons,sample=sample,phase=mode,projected_total=estimate));raise RuntimeError('RESOURCE_OR_SIGNAL_STOP')
save(root/'live-progress.json',dict(stage=mode,guard_pid=active.pid,cumulative_cpu_seconds=charged,projected_total=estimate,unix=time.time()));time.sleep(.2)
result=read(root/'guards'/mode/'guard-result.json');records.append(result);settled+=result['guard']['cpu_seconds']+result['guard_cpu_seconds'];returncode=active.returncode;active=None
if returncode or result['guard']['status']!='PASS':raise RuntimeError('WORKER_NOT_PASS')
save(root/'complete.json',dict(status='COMPLETE',decision=read(root/'phases/score/result.json')['decision'],cumulative_cpu_seconds=total(),records=records,refit=False,reused_first_prediction=True,accounting_complete=True))
except BaseException as exc:
save(root/'global-stop.json',dict(reason=type(exc).__name__+': '+str(exc)))
if active:
try:os.kill(active.pid,signal.SIGTERM)
except ProcessLookupError:pass
active.wait();p=root/'guards'/mode/'guard-result.json'
if p.exists():records.append(read(p))
active=None
save(root/'complete.json',dict(status='STOPPED',reason=type(exc).__name__+': '+str(exc),cumulative_cpu_seconds=total(),records=records,refit=False,retry=False,accounting_complete=True));raise
finally:
for s,h in old.items():signal.signal(s,h)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('action',choices=['run','guard','worker']);p.add_argument('root',type=Path);p.add_argument('mode',nargs='?');p.add_argument('cap',nargs='?',type=float);a=p.parse_args()
if a.action=='run':run(a.root)
elif a.action=='guard':raise SystemExit(guard(a.root,a.mode,a.cap))
else:
c=config(a.root);(predict if a.mode=='predict' else score)(a.root,c)
+106
View File
@@ -0,0 +1,106 @@
"""5932 single B15 infrastructure recovery; original scientific worker pinned."""
import argparse,fcntl,json,os,resource,sys,time,subprocess,signal,shutil
from pathlib import Path
from phase2_b1213_gate import config
from phase2_h1_worker_v2 import checked,save,sha
from phase2_fixed_io import BASE,freeze
from r4bc_guard import supervise
from s2_recovery_supervisor import tree_usage
from s2_recovery_monitoring import disk_usage
def read(p):return json.loads(Path(p).read_text())
def validated(root):
c=config(root)
if c['continuation_approval']!='1794905932.019429' or c['explicit_recovery_indices']!=[288,290,291]:raise PermissionError('One approved recovery')
if len(c['reused_indices'])!=289 or len(c['new_indices'])!=142 or set(c['new_indices'])!=set(range(431))-set(c['reused_indices']):raise PermissionError('Exact289+3+139 scope')
if c['total_cpu_cap']!=7200 or c['disk_bytes']!=12*2**30:raise PermissionError('Unchanged total; disk12GiB')
return c
def phase_projection(charged,observed_cost,completed_weight,remaining_weight):
if completed_weight<=0 or min(charged,observed_cost,remaining_weight)<0:raise ValueError('Projection inputs')
return charged+1.25*observed_cost*remaining_weight/completed_weight
def guard(root,mode,index,slot,cap):
c=validated(root);os.sched_setaffinity(0,[c['worker_cpus'][slot]]);d=root/'guards'/f'{mode}-{index:04d}';start=time.process_time()
cmd=[sys.executable,c['scientific_entry'],mode,str(root)]+([str(index)] if mode=='prep' else [])
g=supervise(cmd,d,dict(cpu_seconds=cap,wall_seconds=60 if mode=='prep' else cap+120,rss_bytes=c['rss_bytes'],disk_bytes=c['disk_bytes']),global_stop=root/'global-stop.json')
save(d/'guard-result.json',dict(mode=mode,index=index,guard=g,guard_cpu_seconds=time.process_time()-start));return 0 if g['status']=='PASS' else 1
def run(root):
c=validated(root);os.sched_setaffinity(0,[29]);lock=(root/'run.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if (root/'started.json').exists():raise FileExistsError('Single recovery')
free=shutil.disk_usage(root).free
if free<2*c['disk_bytes']:raise RuntimeError('Insufficient free space before launch')
start=time.process_time();u0=resource.getrusage(resource.RUSAGE_CHILDREN);settled=0.;records=[];active={};requested=[];prepared=set(c['reused_indices']);prep_cost=c['projection']['observed_prep_cpu_seconds'];prep_nodes=c['projection']['completed_nodes']
def total():
u=resource.getrusage(resource.RUSAGE_CHILDREN);return c['prior_cpu_seconds']+60+max(settled,u.ru_utime+u.ru_stime-u0.ru_utime-u0.ru_stime)+time.process_time()-start+sum(tree_usage(p.pid)[0] for p,_,_ in active.values())
def projected(mode):
charge=total()
if mode=='prep':return phase_projection(charge,prep_cost,prep_nodes,sum(r['nodes'] for i,r in enumerate(c['parts']) if i not in prepared))
p=root/'phases'/mode/'progress.json'
if mode=='predict' and p.exists():
a=read(p);n=a['parts'];rows=c['rows']['validation'];elapsed=sum(tree_usage(p.pid)[0] for p,_,_ in active.values())
if n:return phase_projection(charge,elapsed,sum(r['nodes'] for r in rows[:n]),sum(r['nodes'] for r in rows[n:]))
if mode=='train' and p.exists() and not (root/'phases/train/result.json').exists():
a=read(p);n=a.get('parts',0);elapsed=sum(tree_usage(p.pid)[0] for p,_,_ in active.values())
if n:return phase_projection(charge,elapsed,n,max(0,320-n))+c['phase_estimates']['train']
return charge
def batch(mode,ids,jobcap=None):
nonlocal settled,prep_cost,prep_nodes
pending=list(ids)
while pending or active:
sample=dict(cpu_seconds=total(),disk_bytes=disk_usage(root),rss_bytes=sum(tree_usage(p.pid)[1] for p,_,_ in active.values()),signals=list(requested));reasons=[]
if requested:reasons.append('COORDINATOR_SIGNAL')
if sample['cpu_seconds']>7200-120:reasons.append('TOTAL_CPU_RESERVE')
if sample['disk_bytes']>c['disk_bytes']:reasons.append('DIRECTORY_DISK_LIMIT')
if sample['rss_bytes']>32*2**30:reasons.append('TREE_RSS_LIMIT')
estimate=projected(mode)
if estimate>7200:reasons.append('PHASE_PROJECTION_EXCEEDS_TOTAL')
if reasons:
save(root/'stop-trigger.json',dict(reasons=reasons,sample=sample,phase=mode,projected_cumulative_cpu=estimate,unix=time.time()));raise RuntimeError('RESOURCE_OR_SIGNAL_STOP')
for slot,(p,index,cap) in list(active.items()):
if p.poll() is not None:
rr=read(root/'guards'/f'{mode}-{index:04d}'/'guard-result.json');cost=rr['guard']['cpu_seconds']+rr['guard_cpu_seconds'];settled+=cost;records.append(rr);del active[slot]
if p.returncode or rr['guard']['status']!='PASS':raise RuntimeError('WORKER_NOT_PASS')
if mode=='prep':prepared.add(index);prep_cost+=cost;prep_nodes+=c['parts'][index]['nodes']
for slot in (range(4) if mode=='prep' else range(1)):
if pending and slot not in active:
remaining=7200-total()-sum(z[2] for z in active.values())-120;cap=min(jobcap,remaining) if jobcap else remaining
if cap<1 or (mode=='prep' and cap<jobcap):
if not active:raise RuntimeError('TOTAL_RESERVATION_EXHAUSTED')
break
i=pending.pop(0)
if mode=='prep':(root/'parts'/f'{i:04d}').mkdir(parents=True,exist_ok=False)
p=subprocess.Popen([sys.executable,'tools/phase2_b15_recovery.py','guard',str(root),mode,str(i),str(slot),str(cap)],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True);active[slot]=(p,i,cap)
save(root/'live-progress.json',dict(stage=mode,pending=len(pending),active=[dict(pid=p.pid,index=i,slot=s) for s,(p,i,_) in active.items()],new_terminal=len(records),cumulative_cpu_seconds=total(),phase_projected_total=estimate,unix=time.time()));time.sleep(.2)
def phase_gate(mode):
projected_total=total()+c['phase_estimates'][mode];save(root/(mode+'-cost-check.json'),dict(projected_cumulative_cpu_seconds=projected_total,phase_planning_estimate=c['phase_estimates'][mode],soft_estimate_not_job_cap=True,passed=projected_total<=7200))
if projected_total>7200:raise RuntimeError('PHASE_PROJECTION_EXCEEDS_TOTAL')
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json'),prior_cpu_seconds=c['prior_cpu_seconds'],reused=289,explicit_recoveries=3,never_attempted=139,free_bytes=free,disk_required_free=2*c['disk_bytes']))
old={s:signal.signal(s,lambda signum,frame:requested.append(signum)) for s in [signal.SIGTERM,signal.SIGINT]}
try:
mode='prep';batch(mode,c['new_indices'],30);entries=[]
for i,row in enumerate(c['parts']):
p=root/'parts'/f'{i:04d}'/'result.json';r=read(p);checked(p.parent/'geometry.npz',r['geometry_sha256']);entries.append(dict(case=row['case'],index=i,result_sha256=sha(p)))
save(root/'features-manifest.json',dict(entries=entries,all431_terminal=True,labels_read=False,reused289=True));freeze(root,'features',[root/'contract.json',root/'features-manifest.json',*[BASE/p for p in c['code_sha256']]])
for mode in ['train','predict','score']:
phase_gate(mode)
if mode=='predict':freeze(root,'model',[root/'contract.json',root/'phases/train/model.ubj',root/'phases/train/result.json',*[BASE/p for p in c['code_sha256']]])
if mode=='score':freeze(root,'predictions',[root/'contract.json',root/'phases/predict/manifest.json',*[BASE/p for p in c['code_sha256']]])
(root/'phases'/mode).mkdir(parents=True,exist_ok=False);batch(mode,[0])
save(root/'complete.json',dict(status='COMPLETE',decision=read(root/'phases/score/result.json')['decision'],cumulative_cpu_seconds=total(),records=records,models_fit=1,old_stop_preserved=True,accounting_complete=True,retry=False))
except BaseException as exc:
save(root/'global-stop.json',dict(reason=type(exc).__name__+': '+str(exc)))
for p,_,_ in active.values():
try:os.kill(p.pid,signal.SIGTERM)
except ProcessLookupError:pass
for p,index,_ in active.values():
p.wait();receipt=root/'guards'/f'{mode}-{index:04d}'/'guard-result.json'
if receipt.exists():records.append(read(receipt))
active.clear();save(root/'complete.json',dict(status='STOPPED',reason=type(exc).__name__+': '+str(exc),cumulative_cpu_seconds=total(),records=records,old_stop_preserved=True,accounting_complete=True,retry=False));raise
finally:
for s,h in old.items():signal.signal(s,h)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('action',choices=['run','guard']);p.add_argument('root',type=Path);p.add_argument('mode',nargs='?');p.add_argument('index',nargs='?',type=int);p.add_argument('slot',nargs='?',type=int);p.add_argument('cap',nargs='?',type=float);a=p.parse_args()
if a.action=='run':run(a.root)
else:raise SystemExit(guard(a.root,a.mode,a.index,a.slot,a.cap))
+101
View File
@@ -0,0 +1,101 @@
"""E2 label-free T/C, original G reused; no cross-arm eligibility filter."""
import argparse,json,time,traceback
from pathlib import Path
import numpy as np
from scipy.spatial import QhullError
from phase2_h1_worker_v2 import checked,sha,save
from phase2_fixed_io import BASE
from phase2_b1213_features import input_geometry,cached,g_metrics
from o1_prepare import source_geometry,difference
from o1_partition import graph,Metis,type_fields,shuffle_type,readout,diameter,interface_difference,GeometryFailure,InputViolation
from o1_v2 import face_weights,reweighted_graph,array_sha
def read(p):return json.loads(Path(p).read_text())
def config(root):
c=read(root/'contract.json')
if c['approval']!='1794907827.062989' or len(c['parts'])!=552:raise PermissionError('E2 fixed552 scope')
for p,h in {**c['code_sha256'],**c['source_sha256']}.items():checked(BASE/p,h)
st=Path(c['archive']).stat();old=c['archive_stat']
if (st.st_size,st.st_mtime_ns,st.st_ino)!=(old['bytes'],old['mtime_ns'],old['inode']):raise InputViolation('Archive identity')
return c
def descriptor(mesh,g,labels,metrics):
ds=[];hulls=[]
for k in range(8):
nodes=np.unique(mesh['tets'][labels==k]);d,h=diameter(mesh['points'][nodes]);ds.append(d);hulls.append(h)
return dict(cut_area=metrics['cut_area'],diameters=sorted(ds),rms_diameter=float(np.sqrt(np.mean(np.asarray(ds)**2))),fractions=metrics['fractions'],hull_vertices=hulls)
def field(root,c,index):
row=c['parts'][index];dest=root/'parts'/f'{index:04d}';start=time.process_time();arms={};fields={};labels_by={};calls=0;G=c['G_sources'][row['case']]
gr=read(checked(G['result'],G['result_sha256']));fields['G']=np.load(checked(G['extra'],G['extra_sha256']),allow_pickle=False);arms['G']=dict(valid=gr['status']=='GEOMETRY_COMPLETE',status=gr['status'],reason=gr.get('reason'),source_result_sha256=G['result_sha256'],source_extra_sha256=G['extra_sha256'],partition_calls=0)
try:
mesh,decoded=source_geometry(c['archive'],row['case']);x,t,raw,old=input_geometry(row)
if not np.array_equal(mesh['points'],x) or not np.array_equal(mesh['raw_nodes'],raw):raise InputViolation('Raw geometry/node identity')
key=lambda a:np.lexsort(tuple(a[:,i] for i in [3,2,1,0]));a=np.sort(t,axis=1);b=mesh['tets']
if not np.array_equal(a[key(a)],b[key(b)]):raise InputViolation('Canonical tetra membership')
features=cached(row,'features');g=graph(mesh);z,values=type_fields(features,mesh['tets']);shuffled,perm=shuffle_type(z,mesh['volume'],mesh['raw_cells'],int(row['case'].split('_')[0]));weights,wd,ranks=face_weights(g,z,shuffled)
if not np.array_equal(reweighted_graph(g,weights['G'])['adjwgt'],g['adjwgt']):raise InputViolation('G integer weights changed')
np.savez_compressed(dest/'geometry-evidence.npz',permutation=perm,raw_nodes=raw,raw_cells=mesh['raw_cells'],volume=mesh['volume'],T_face_integer=weights['T'],C_face_integer=weights['C'])
common={k:array_sha(g[k]) for k in ['xadj','adjncy','vwgt','adjwgt']};save(dest/'input-evidence.json',dict(graph_fingerprints=common,type_sha256=array_sha(z),shuffled_type_sha256=array_sha(shuffled),readout_values_sha256=array_sha(values),weight_diagnostics=wd,decoded_geometry_arrays=decoded,labels_read=False))
if G.get('partition'):
with np.load(checked(G['partition'],G['partition_sha256']),allow_pickle=False) as f:labels_by['G']=f['labels'].copy()
if arms['G']['valid']:
if 'G' not in labels_by:raise InputViolation('Missing frozen valid G partition')
gm=g_metrics(mesh,g,labels_by['G'])
if not gm['passed']:raise InputViolation('Frozen G eligibility changed')
reproduced=readout(mesh['tets'],mesh['volume'],values,labels_by['G'],len(raw))
if not np.array_equal(reproduced,fields['G']):raise InputViolation('Frozen G readout differs')
try:arms['G']['descriptor']=descriptor(mesh,g,labels_by['G'],gm)
except (GeometryFailure,QhullError) as exc:arms['G']['descriptor_error']=type(exc).__name__+': '+str(exc)
engine=Metis();cache=c['O1_cache'].get(row['case']);previous=None
if cache:
previous=read(checked(cache['result'],cache['result_sha256']))
if previous.get('protocol')!='O1-scientific-v2-area-rank-face-weights':raise InputViolation('Only original O1v2 cache')
with np.load(checked(cache['graph'],previous['output_sha256']['graph.npz']),allow_pickle=False) as f:
for k,v in [('raw_nodes',raw),('raw_cells',mesh['raw_cells']),('volume',mesh['volume'])]:
if not np.array_equal(f[k],v):raise InputViolation('Cached canonical graph identity')
dw=cached(row,'Dw')
for arm in ['T','C']:
before=time.process_time();d=dest/arm;d.mkdir();rec=dict(valid=False,partition_calls=0,seed=0,source='new_seed0');ag=reweighted_graph(g,weights[arm]);fp={k:array_sha(ag[k]) for k in common}
try:
if previous and arm in previous.get('arms',{}):
prior=previous['arms'][arm]
if prior['input_sha256']!=fp or prior['seed']!=0:raise InputViolation('Cached T/C fingerprint differs')
rec.update(source='REUSED_O1V2_SEED0',source_result_sha256=cache['result_sha256'])
if 'partition_sha256' not in prior:raise GeometryFailure('REUSED_ORIGINAL_PARTITION_FAILURE: '+prior.get('reason','unknown'))
if prior['options']!=engine.options(0).tolist():raise InputViolation('Cached METIS options')
with np.load(checked(Path(cache['result']).parent/(arm+'-partition.npz'),prior['partition_sha256']),allow_pickle=False) as f:labels=f['labels'].copy()
returned=dict(options=prior['options'],returncode=prior['returncode'],integer_cut=prior['integer_cut'])
else:
calls+=1;rec['partition_calls']=1;labels,returned=engine.partition(ag,mesh['raw_cells'],0)
if fp!={k:array_sha(ag[k]) for k in fp}:raise InputViolation('METIS mutated input')
labels_by[arm]=labels;np.savez_compressed(d/'partition.npz',labels=labels);rec.update(returned,partition_sha256=sha(d/'partition.npz'),input_fingerprints=fp)
metrics=g_metrics(mesh,g,labels);rec['metrics']=metrics
if not metrics['passed']:raise GeometryFailure('SINGLE_ARM_BALANCE_OR_CONNECTIVITY_FAIL')
if not np.isfinite(dw).all() or dw.max()<=0:raise GeometryFailure('DW_NORMALIZATION_UNDEFINED')
fields[arm]=readout(mesh['tets'],mesh['volume'],values,labels,len(raw))
if not np.isfinite(fields[arm]).all():raise InputViolation('Readout nonfinite')
mass=np.bincount(mesh['tets'].ravel(),weights=np.repeat(mesh['volume']/4,4),minlength=len(raw));before_mass=(mass[:,None]*features[:,[0,9]]).sum(0);after_mass=(mass[:,None]*fields[arm]).sum(0)
if not np.allclose(before_mass,after_mass,rtol=1e-11,atol=1e-12):raise InputViolation('Readout mass identity')
rec.update(valid=True,status='GEOMETRY_COMPLETE',reason=None,mass_integral_before=before_mass.tolist(),mass_integral_after=after_mass.tolist())
try:rec['descriptor']=descriptor(mesh,g,labels,metrics)
except (GeometryFailure,QhullError) as exc:rec['descriptor_error']=type(exc).__name__+': '+str(exc)
except GeometryFailure as exc:fields[arm]=np.full((row['nodes'],2),np.nan);rec.update(status='SCIENTIFIC_MISSING',reason=str(exc))
np.save(d/'extra.npy',fields[arm],allow_pickle=False);rec.update(extra_sha256=sha(d/'extra.npy'),cpu_seconds=time.process_time()-before);arms[arm]=rec;save(d/'result.json',dict(case=row['case'],component_id=row['component_id'],**rec));save(dest/'progress.json',dict(arms=list(arms),partition_calls=calls,cpu_seconds=time.process_time()-start))
comparisons={}
for a,b in [('T','G'),('T','C'),('C','G')]:
rec=dict(both_valid=arms[a]['valid'] and arms[b]['valid'])
if a in labels_by and b in labels_by:rec['interface']=interface_difference(labels_by[a],labels_by[b],g)
if rec['both_valid']:
rec['readout_difference']=difference(fields[a],fields[b]);rec['bitwise_equal']=bool(np.array_equal(fields[a],fields[b]));rec['float32_equal']=bool(np.array_equal(fields[a].astype(np.float32),fields[b].astype(np.float32)))
comparisons[a+'-'+b]=rec
save(dest/'result.json',dict(status='PREPARATION_COMPLETE',case=row['case'],index=index,arms=arms,comparisons=comparisons,partition_calls=calls,cpu_seconds=time.process_time()-start,labels_read=False,output_sha256={str(p.relative_to(dest)):sha(p) for p in dest.rglob('*') if p.is_file() and p.name!='progress.json'}))
except GeometryFailure as exc:
for arm in ['T','C']:
d=dest/arm;d.mkdir(exist_ok=True);np.save(d/'extra.npy',np.full((row['nodes'],2),np.nan),allow_pickle=False);arms[arm]=dict(valid=False,status='SCIENTIFIC_MISSING',reason=str(exc),extra_sha256=sha(d/'extra.npy'));save(d/'result.json',dict(case=row['case'],component_id=row['component_id'],**arms[arm]))
save(dest/'result.json',dict(status='PREPARATION_COMPLETE',case=row['case'],index=index,arms=arms,comparisons={},partition_calls=calls,cpu_seconds=time.process_time()-start,labels_read=False,shared_applicability_failure=str(exc)))
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('index',type=int);a=p.parse_args();c=config(a.root)
try:field(a.root,c,a.index)
except BaseException as exc:
save(a.root/'parts'/f'{a.index:04d}'/'failure.json',dict(type=type(exc).__name__,reason=str(exc),traceback=traceback.format_exc(),labels_read=False));raise
+73
View File
@@ -0,0 +1,73 @@
"""E2 first-ten cost gate, then bounded label-free geometry; no fit or scoring."""
import argparse,fcntl,json,os,resource,signal,subprocess,sys,time
from pathlib import Path
from phase2_e2_geometry import config
from phase2_h1_worker_v2 import sha,save
from r4bc_guard import supervise
from s2_recovery_supervisor import tree_usage
from s2_recovery_monitoring import disk_usage
def read(p):return json.loads(Path(p).read_text())
def cost_projection(cpu,done_nodes,total_nodes,postfit,setup=60):
if done_nodes<=0 or total_nodes<done_nodes or cpu<setup:raise ValueError('Invalid cost checkpoint')
return setup+1.25*(cpu-setup)*total_nodes/done_nodes+postfit
def guard(root,index,slot):
c=config(root);os.sched_setaffinity(0,[c['worker_cpus'][slot]]);start=time.process_time();d=root/'guards'/f'{index:04d}'
g=supervise([sys.executable,'tools/phase2_e2_geometry.py',str(root),str(index)],d,dict(cpu_seconds=c['part_cpu_seconds'],wall_seconds=c['part_wall_seconds'],rss_bytes=c['part_rss_bytes'],disk_bytes=c['disk_bytes']),global_stop=root/'global-stop.json')
save(d/'guard-result.json',dict(index=index,guard=g,guard_cpu_seconds=time.process_time()-start));return 0 if g['status']=='PASS' else 1
def run(root):
c=config(root);os.sched_setaffinity(0,[30,31]);lock=(root/'run.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if (root/'started.json').exists():raise FileExistsError('E2 geometry single attempt')
start=time.process_time();u0=resource.getrusage(resource.RUSAGE_CHILDREN);settled=0.;records=[];active={};requested=[]
def total():
u=resource.getrusage(resource.RUSAGE_CHILDREN);return 60+max(settled,u.ru_utime+u.ru_stime-u0.ru_utime-u0.ru_stime)+time.process_time()-start+sum(tree_usage(p.pid)[0] for p,_ in active.values())
def batch(indices):
nonlocal settled
pending=list(indices)
while pending or active:
sample=dict(cpu_seconds=total(),disk_bytes=disk_usage(root),rss_bytes=sum(tree_usage(p.pid)[1] for p,_ in active.values()),signals=list(requested));reasons=[]
if requested:reasons.append('COORDINATOR_SIGNAL')
if sample['cpu_seconds']>14400-120:reasons.append('TOTAL_CPU_RESERVE')
if sample['disk_bytes']>c['disk_bytes']:reasons.append('DISK_LIMIT')
if sample['rss_bytes']>32*2**30:reasons.append('RSS_LIMIT')
if reasons:save(root/'stop-trigger.json',dict(reasons=reasons,sample=sample));raise RuntimeError('RESOURCE_OR_SIGNAL_STOP')
for slot,(p,i) in list(active.items()):
if p.poll() is not None:
rr=read(root/'guards'/f'{i:04d}'/'guard-result.json');settled+=rr['guard']['cpu_seconds']+rr['guard_cpu_seconds'];records.append(rr);del active[slot]
if p.returncode or rr['guard']['status']!='PASS':raise RuntimeError('WORKER_NOT_PASS')
for slot in range(4):
if pending and slot not in active:
if total()+(len(active)+1)*c['part_cpu_seconds']+120>14400:
if not active:raise RuntimeError('TOTAL_ADMISSION_RESERVE')
break
i=pending.pop(0);(root/'parts'/f'{i:04d}').mkdir(parents=True,exist_ok=False)
p=subprocess.Popen([sys.executable,'tools/phase2_e2_geometry_queue.py','guard',str(root),str(i),str(slot)],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True);active[slot]=(p,i)
save(root/'live-progress.json',dict(stage='FIRST_TEN' if max(indices)<10 else 'GEOMETRY',terminal=len(records),pending=len(pending),active=[dict(slot=k,pid=p.pid,index=i) for k,(p,i) in active.items()],cumulative_cpu_seconds=total(),unix=time.time()));time.sleep(.2)
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json'),first_ten=list(range(10)),new_fits=0,new_labels=0))
old={s:signal.signal(s,lambda signum,frame:requested.append(signum)) for s in [signal.SIGTERM,signal.SIGINT]}
try:
batch(list(range(10)));projected=cost_projection(total(),sum(r['nodes'] for r in c['parts'][:10]),sum(r['nodes'] for r in c['parts']),c['postfit_projection']['total'])
save(root/'first-ten-cost-check.json',dict(projected_total_cpu_seconds=projected,total_cap=14400,postfit_projection=c['postfit_projection'],actual_cpu_seconds=total(),passed=projected<=14400,denominator_all_ten_including_missing=True))
if projected>14400:raise RuntimeError('FIRST_TEN_COST_PROJECTION_EXCEEDS_TOTAL')
batch(list(range(10,552)));entries=[]
for i,row in enumerate(c['parts']):
p=root/'parts'/f'{i:04d}'/'result.json';v=read(p);entries.append(dict(case=row['case'],index=i,result_sha256=sha(p),valid={a:v['arms'][a]['valid'] for a in ['G','T','C']}))
save(root/'geometry-manifest.json',dict(entries=entries,all552_terminal=True,labels_read=False,cross_arm_filter=False))
save(root/'complete.json',dict(status='GEOMETRY_COMPLETE_POSTFIT_PENDING',cumulative_cpu_seconds=total(),records=records,new_fits=0,new_predictions=0,scored=False,accounting_complete=True))
except BaseException as exc:
save(root/'global-stop.json',dict(reason=type(exc).__name__+': '+str(exc)))
for p,_ in active.values():
try:os.kill(p.pid,signal.SIGTERM)
except ProcessLookupError:pass
for p,i in active.values():
p.wait();f=root/'guards'/f'{i:04d}'/'guard-result.json'
if f.exists():records.append(read(f))
active.clear();save(root/'complete.json',dict(status='STOPPED',reason=type(exc).__name__+': '+str(exc),cumulative_cpu_seconds=total(),records=records,accounting_complete=True,retry=False));raise
finally:
for s,h in old.items():signal.signal(s,h)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('action',choices=['run','guard']);p.add_argument('root',type=Path);p.add_argument('index',nargs='?',type=int);p.add_argument('slot',nargs='?',type=int);a=p.parse_args()
if a.action=='run':run(a.root)
else:raise SystemExit(guard(a.root,a.index,a.slot))
+185
View File
@@ -0,0 +1,185 @@
"""E2: immutable T/C geometry -> ten fits -> all predictions -> raw/adjusted score."""
import argparse,fcntl,json,os,resource,signal,subprocess,sys,time
from pathlib import Path
from collections import Counter
import numpy as np
import xgboost as xgb
from phase2_h1_worker_v2 import checked,sha,save
from phase2_fixed_io import BASE,verify
from phase2_local_freeze_io import freeze
from phase2_b1213_features import cached
from gre24_models import xgb_model
from s2_custody_common import prediction_inputs
from s2_custody_statistics import part_metrics
from phase2_e2_statistics import analyse
from r4bc_guard import supervise
from s2_recovery_supervisor import tree_usage
from s2_recovery_monitoring import disk_usage
def read(p):return json.loads(Path(p).read_text())
def validate_roles(c):
parts={r['case']:r for r in c['parts']};tests=[];groups={}
if len(parts)!=552 or len(c['folds'])!=5:raise ValueError('Frozen552/five folds required')
for f in c['folds']:
if f['fold'] not in range(5):raise ValueError('Fold identity')
for role in ['learning','test']:
rows=f['rows'][role]
if len({r['case'] for r in rows})!=len(rows):raise ValueError('Duplicate fold role')
for r in rows:
if r!=parts[r['case']]:raise ValueError('Fold/part data changed')
a=next(a for a in r['assignments'] if a['fold']==f['fold'])
if a['role']!=role or (role=='learning' and '100' not in a['learning_pools']):raise ValueError('Learning/test assignment mismatch')
if {r['component_id'] for r in f['rows']['learning']}&{r['component_id'] for r in f['rows']['test']}:raise ValueError('Component leakage')
for r in f['rows']['test']:
tests.append(r['case']);groups.setdefault(r['component_id'],set()).add(f['fold'])
if len(tests)!=552 or set(tests)!=set(parts) or len(groups)!=204 or any(len(v)!=1 for v in groups.values()):raise ValueError('Test roster must partition552/204 once')
def config(root):
c=read(root/'contract.json')
if c['approval']!='1794907827.062989' or c['total_cpu_seconds']!=14400 or c['new_fits']!=10 or c['new_geometry']!=0:raise PermissionError('Original E2 scope required')
if np.__version__!='1.26.4' or xgb.__version__!='2.1.4':raise ValueError('Pinned libraries')
for p,h in {**c['source_sha256'],**c['code_sha256']}.items():checked(BASE/p,h)
st=Path(c['archive']).stat();s=c['archive_stat']
if (st.st_size,st.st_mtime_ns,st.st_ino)!=(s['bytes'],s['mtime_ns'],s['inode']):raise ValueError('Archive identity')
validate_roles(c);return c
def job(index):
if index not in range(10):raise ValueError('Only ten fit/predict cells')
return index//2,('T','C')[index%2]
def jobroot(root,index):return root/'cells'/f'{index:02d}'
def extras(row,arm,entries):
e=entries[row['case']]['arms'][arm];v=np.load(checked(e['path'],e['sha256']),allow_pickle=False)
if v.shape!=(row['nodes'],2) or np.isinf(v).any():raise ValueError('Geometry feature shape/infinity')
if e['valid'] and not np.isfinite(v).all():raise ValueError('Valid arm readout nonfinite')
if not e['valid'] and not np.isnan(v).all():raise ValueError('Missing arm must retain two nativeNaN columns')
return v
def train(root,c,index):
verify(root,'features');fold,arm=job(index);rows=c['folds'][fold]['rows']['learning'];dest=jobroot(root,index)/'train';dest.mkdir(parents=True,exist_ok=False)
entries={e['case']:e for e in read(root/'features-manifest.json')['entries']};n=sum(r['nodes'] for r in rows);X=np.empty((n,21),np.float32);Y=np.empty(n,np.float32);offset=0;access=[]
for row in rows:
f=cached(row,'features');e=extras(row,arm,entries);raw=cached(row,'raw_ids')
if f.shape!=(row['nodes'],19) or not np.isfinite(f).all() or len(raw)!=row['nodes']:raise ValueError('Frozen learning feature identity')
access.append(dict(case=row['case'],fold=fold,arm=arm,role='learning',learning_pool=100,target_sha256=row['v5_cache']['output_sha256']['target.npy'],raw_ids_sha256=row['v5_cache']['output_sha256']['raw_ids.npy'],nodes=row['nodes']));save(dest/'target-access.json',access)
y=cached(row,'target');end=offset+len(y)
if y.shape!=(row['nodes'],) or not np.isfinite(y).all():raise ValueError('Learning target shape/nonfinite')
X[offset:end,:19]=f;X[offset:end,19:]=e;Y[offset:end]=y;offset=end
save(dest/'progress.json',dict(stage='LOAD_LEARNING',parts=len(access),nodes=offset))
if offset!=n:raise ValueError('Learning count')
model=xgb_model(0,1);save(dest/'progress.json',dict(stage='FIT',nodes=n,parts=len(access),columns=21))
model.fit(X,Y,sample_weight=np.ones(n,np.float64));model.save_model(dest/'model.ubj');save(dest/'xgboost-config.json',json.loads(model.get_booster().save_config()))
save(dest/'result.json',dict(status='FIT_COMPLETE',fold=fold,arm=arm,checkpoint_sha256=sha(dest/'model.ubj'),nodes=n,parts=len(rows),columns=21,unit_node_weights=True,test_labels_read=False))
def query_identity(q,z):
for key in ['raw_ids','counts','coordinates_over_Rg','near_wall']:
if not np.array_equal(q[key],z[key]):raise ValueError('Frozen G query mismatch: '+key)
def predict(root,c,index):
verify(root,'models');fold,arm=job(index);d=jobroot(root,index);model=xgb.XGBRegressor();model.load_model(d/'train/model.ubj');dest=d/'predict';dest.mkdir(exist_ok=False)
entries={e['case']:e for e in read(root/'features-manifest.json')['entries']};G={e['case']:e for e in read(c['G_prediction_manifest'])['entries']};out=[]
for row in c['folds'][fold]['rows']['test']:
q=prediction_inputs(row);raw=cached(row,'raw_ids');ix=np.searchsorted(raw,q['raw_ids'])
if np.any(ix>=len(raw)) or not np.array_equal(raw[ix],q['raw_ids']):raise ValueError('Test query IDs')
g=G[row['case']]
if g['fold']!=fold or g['component_id']!=row['component_id']:raise ValueError('G fold/component mismatch')
with np.load(checked(g['path'],g['sha256']),allow_pickle=False) as z:query_identity(q,z)
f=cached(row,'features');e=extras(row,arm,entries);X=np.column_stack([f[ix],e[ix]]).astype(np.float32);pred=np.asarray(model.predict(X),np.float64)*row['preparation']['t_set']
if not np.isfinite(pred).all():raise ValueError('Nonfinite prediction')
p=dest/(row['case']+'.npz');np.savez_compressed(p,pred=pred,**{k:q[k] for k in ['raw_ids','counts','coordinates_over_Rg','near_wall']})
out.append(dict(case=row['case'],component_id=row['component_id'],fold=fold,arm=arm,path=str(p),sha256=sha(p),model_sha256=sha(d/'train/model.ubj'),G_prediction_sha256=g['sha256']))
save(dest/'progress.json',dict(parts=len(out),test_labels_read=False))
save(dest/'manifest.json',dict(entries=out,test_labels_read=False,units='seconds'))
def score(root,c):
verify(root,'predictions');dest=root/'score';dest.mkdir(exist_ok=False);m=read(root/'predictions-manifest.json')['entries'];by={r['case']:r for r in c['parts']};entries={e['case']:e for e in read(root/'features-manifest.json')['entries']}
if len(m)!=1104 or len({(e['case'],e['arm']) for e in m})!=1104 or {(e['case'],e['arm']) for e in m}!={(s,a) for s in by for a in ['T','C']}:raise ValueError('All1104 T/C predictions required')
pred={(e['case'],e['arm']):e for e in m};gm={e['case']:e for e in read(c['G_prediction_manifest'])['entries']};gr={r['case']:r for r in read(c['G_score'])['rows']};rows=[];access=[]
if set(gm)!=set(by) or set(gr)!=set(by):raise ValueError('Frozen G full roster mismatch')
for case,row in by.items():
geometry=read(checked(entries[case]['geometry_result'],entries[case]['geometry_sha256']));g=gm[case];old=gr[case]
if old['fold']!=g['fold'] or old['component_id']!=row['component_id']:raise ValueError('G scoring identity')
access.append(dict(case=case,fold=g['fold'],role='test',target_sha256=row['v5_cache']['output_sha256']['seconds.npy']));save(dest/'target-access.json',access)
truth=cached(row,'seconds');raw=cached(row,'raw_ids');rr=dict(case=case,component_id=row['component_id'],fold=g['fold'],metrics={'G':old['new']},geometry=geometry)
with np.load(checked(g['path'],g['sha256']),allow_pickle=False) as z:
q={k:z[k] for k in ['raw_ids','counts','coordinates_over_Rg','near_wall']};ix=np.searchsorted(raw,q['raw_ids'])
if np.any(ix>=len(raw)) or not np.array_equal(raw[ix],q['raw_ids']):raise ValueError('Score raw IDs')
for arm in ['T','C']:
e=pred[case,arm]
if e['fold']!=g['fold'] or e['G_prediction_sha256']!=g['sha256']:raise ValueError('Prediction role/source mismatch')
with np.load(checked(e['path'],e['sha256']),allow_pickle=False) as v:
query_identity(q,v);rr['metrics'][arm]=part_metrics(v['pred'],truth[ix],q['counts'],q['near_wall'],q['raw_ids'],q['coordinates_over_Rg'],int(case.split('_')[0]))
rows.append(rr);save(dest/'progress.json',dict(stage='PART_METRICS',parts=len(rows)))
save(dest/'part-metrics.json',dict(rows=rows,original_G_metrics_reused=True));save(dest/'progress.json',dict(stage='PAIRED_COMPONENT_BOOTSTRAP_REFIT',parts=552,replicates=2000))
result,arrays=analyse(rows);np.savez_compressed(dest/'bootstrap.npz',**arrays)
result.update(status='COMPLETE',rows=rows,coverage=read(root/'coverage.json'),geometry_cost=c['prior_geometry_cpu_seconds'],new_models=10,reused_G_models=5,new_geometry=0,validation_used=False,new_decodes=0,bootstrap_sha256=sha(dest/'bootstrap.npz'))
save(dest/'result.json',result)
def worker(root,mode,index):
c=config(root)
if mode=='score':score(root,c)
else:{'train':train,'predict':predict}[mode](root,c,index)
def guard(root,mode,index,slot):
c=config(root);os.sched_setaffinity(0,[c['worker_cpus'][slot]]);start=time.process_time();cap=c['job_caps'][mode];d=root/'guards'/f'{mode}-{index:02d}'
g=supervise([sys.executable,'tools/phase2_e2_postfit.py','worker',str(root),mode,str(index)],d,dict(cpu_seconds=cap,wall_seconds=cap+180,rss_bytes=8*2**30,disk_bytes=c['disk_bytes']),global_stop=root/'global-stop.json')
save(d/'guard-result.json',dict(mode=mode,index=index,guard=g,guard_cpu_seconds=time.process_time()-start));return 0 if g['status']=='PASS' else 1
def admission(total,active_count,job_cap,limit=14400):return total+(active_count+1)*job_cap+120<=limit
def run(root):
c=config(root);os.sched_setaffinity(0,[30,31]);lock=(root/'run.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if (root/'started.json').exists():raise FileExistsError('Single attempt E2 postfit')
verify(root,'launch');verify(root,'features');start=time.process_time();u0=resource.getrusage(resource.RUSAGE_CHILDREN);settled=0.;records=[];active={};requested=[]
def total():
u=resource.getrusage(resource.RUSAGE_CHILDREN);return c['prior_geometry_cpu_seconds']+c['setup_seconds']+max(settled,u.ru_utime+u.ru_stime-u0.ru_utime-u0.ru_stime)+time.process_time()-start+sum(tree_usage(p.pid)[0] for p,_,_ in active.values())
def limits():
sample=dict(cpu_seconds=total(),rss_bytes=sum(tree_usage(p.pid)[1] for p,_,_ in active.values()),disk_bytes=disk_usage(root)+disk_usage(Path(c['geometry_root'])),signals=list(requested));reasons=[]
if sample['cpu_seconds']>14400-120:reasons.append('TOTAL_CPU_RESERVE')
if sample['rss_bytes']>32*2**30:reasons.append('RSS_LIMIT')
if sample['disk_bytes']>c['disk_bytes']:reasons.append('COMBINED_GEOMETRY_POSTFIT_DISK_LIMIT')
if requested:reasons.append('COORDINATOR_SIGNAL')
if reasons:save(root/'stop-trigger.json',dict(reasons=reasons,sample=sample));raise RuntimeError('RESOURCE_OR_SIGNAL_STOP')
def batch(mode,indices):
nonlocal settled
pending=list(indices)
while pending or active:
limits()
for slot,(p,i,m) in list(active.items()):
if p.poll() is not None:
r=read(root/'guards'/f'{m}-{i:02d}'/'guard-result.json');settled+=r['guard']['cpu_seconds']+r['guard_cpu_seconds'];records.append(r);del active[slot]
if p.returncode or r['guard']['status']!='PASS':raise RuntimeError('WORKER_NOT_PASS')
for slot in range(4):
if pending and slot not in active:
if not admission(total(),len(active),c['job_caps'][mode]):
if not active:raise RuntimeError('TOTAL_ADMISSION_RESERVE')
break
i=pending.pop(0);p=subprocess.Popen([sys.executable,'tools/phase2_e2_postfit.py','guard',str(root),mode,str(i),str(slot)],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True);active[slot]=(p,i,mode)
save(root/'live-progress.json',dict(stage=mode,pending=len(pending),active=[dict(slot=s,pid=p.pid,index=i,mode=m) for s,(p,i,m) in active.items()],terminal=len(records),cumulative_cpu_seconds=total(),unix=time.time()));time.sleep(.5)
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json'),prior_geometry_cpu_seconds=c['prior_geometry_cpu_seconds'],new_geometry=0))
old={s:signal.signal(s,lambda signum,frame:requested.append(signum)) for s in [signal.SIGTERM,signal.SIGINT]}
try:
batch('train',range(10));freeze(root,'models',[root/'contract.json',*[jobroot(root,i)/'train'/n for i in range(10) for n in ['model.ubj','result.json','target-access.json']],*[BASE/p for p in c['code_sha256']]])
batch('predict',range(10));entries=[]
for i in range(10):entries.extend(read(jobroot(root,i)/'predict/manifest.json')['entries'])
save(root/'predictions-manifest.json',dict(entries=entries,all1104_terminal=True,reused_G_manifest=c['G_prediction_manifest'],reused_G_manifest_sha256=c['source_sha256'][c['G_prediction_manifest']],labels_read=False))
freeze(root,'predictions',[root/'contract.json',root/'predictions-manifest.json',root/'features-manifest.json',Path(c['G_prediction_manifest']),Path(c['G_score']),*[BASE/p for p in c['code_sha256']]])
batch('score',[0]);limits();save(root/'complete.json',dict(status='COMPLETE',decision=read(root/'score/result.json')['decision'],cumulative_cpu_seconds=total(),prior_geometry_cpu_seconds=c['prior_geometry_cpu_seconds'],records=records,new_fits=10,new_predictions=1104,reused_G_predictions=552,accounting_complete=True,retry=False))
freeze(root,'terminal',[root/'contract.json',root/'complete.json',root/'score/result.json',root/'score/bootstrap.npz'])
save(root/'post-terminal-freeze-cost.json',dict(cumulative_cpu_seconds=total(),includes_terminal_freeze=True,within_cap=total()<=14400))
except BaseException as exc:
save(root/'global-stop.json',dict(reason=type(exc).__name__+': '+str(exc)))
for p,_,_ in active.values():
try:os.kill(p.pid,signal.SIGTERM)
except ProcessLookupError:pass
for p,i,m in active.values():
p.wait();f=root/'guards'/f'{m}-{i:02d}'/'guard-result.json'
if f.exists():records.append(read(f))
active.clear();save(root/'complete.json',dict(status='STOPPED',reason=type(exc).__name__+': '+str(exc),cumulative_cpu_seconds=total(),records=records,accounting_complete=True,retry=False));raise
finally:
for s,h in old.items():signal.signal(s,h)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('action',choices=['run','worker','guard']);p.add_argument('root',type=Path);p.add_argument('mode',nargs='?');p.add_argument('index',nargs='?',type=int);p.add_argument('slot',nargs='?',type=int);a=p.parse_args()
if a.action=='run':run(a.root)
elif a.action=='worker':worker(a.root,a.mode,a.index)
else:raise SystemExit(guard(a.root,a.mode,a.index,a.slot))
+73
View File
@@ -0,0 +1,73 @@
"""Frozen E2 raw deployment contrast and weighted descriptive adjustment."""
import numpy as np
from scipy.spatial import ConvexHull,QhullError
SVD_RCOND=1e-12
SUPPORT_RTOL=1e-10
METRICS=('relative_l2','last_location','kendall_tau_b')
PAIRS=(('T','G'),('T','C'),('C','G'))
def weights_for_components(component_ids,multiplicity=None):
ids=sorted(set(component_ids));index={g:i for i,g in enumerate(ids)};group=np.array([index[g] for g in component_ids]);sizes=np.bincount(group,minlength=len(ids))
mult=np.ones(len(ids)) if multiplicity is None else np.asarray(multiplicity,float)
if not len(ids) or mult.shape!=(len(ids),) or not np.isfinite(mult).all() or np.any(mult<0) or not np.isclose(mult.sum(),len(ids)):raise ValueError('Bootstrap must draw original C components')
return mult[group]/(len(ids)*sizes[group]),ids,group
def zero_support(x):
x=np.asarray(x,float)
if x.ndim!=2 or x.shape[1]!=2 or not len(x) or not np.isfinite(x).all():return dict(supported=False,reason='NO_FINITE_DUAL_SUPPORT')
scale=max(1.,float(np.abs(x).max()));tol=SUPPORT_RTOL*scale;mean=x.mean(0);u,s,vt=np.linalg.svd(x-mean,full_matrices=False);rank=int(np.sum(s>SVD_RCOND*max(1.,s[0] if len(s) else 0.)))
if rank==0:return dict(supported=bool(np.linalg.norm(mean)<=tol),affine_rank=0,zero_distance=float(np.linalg.norm(mean)),tolerance=tol)
if rank==1:
direction=vt[0];distance=float(np.linalg.norm(mean-(mean@direction)*direction));v=x@direction;ok=distance<=tol and v.min()<=tol and v.max()>=-tol
return dict(supported=bool(ok),affine_rank=1,zero_distance=distance,projected_range=[float(v.min()),float(v.max())],tolerance=tol)
try:
hull=ConvexHull(x);outside=float(np.max(hull.equations[:,-1]));return dict(supported=bool(outside<=tol),affine_rank=2,max_origin_facet_violation=outside,tolerance=tol)
except QhullError:return dict(supported=False,reason='CONVEX_HULL_NUMERICAL_FAILURE',affine_rank=2,tolerance=tol)
def adjusted_estimate(d,x,valid,w):
d=np.asarray(d,float);x=np.asarray(x,float);valid=np.asarray(valid,bool);w=np.asarray(w,float);active=w>0
if not np.isfinite(d[active]).all():return dict(value=None,reason='UNDEFINED_FULL_ROSTER_DIFFERENCE')
raw=float(np.dot(w[active],d[active]));use=active&valid&np.isfinite(x).all(1);mass=float(w[use].sum())
if not np.any(use):return dict(value=None,raw=raw,reason='NO_DUAL_VALID_SUPPORT',dual_valid_weight=mass)
X=np.column_stack([np.ones(use.sum()),x[use]]);sw=np.sqrt(w[use]);design=X*sw[:,None];target=d[use]*sw;u,s,vt=np.linalg.svd(design,full_matrices=False);rank=int(np.sum(s>SVD_RCOND*s[0]));basis=vt[:rank];intercept=np.array([1.,0.,0.]);residual=float(np.linalg.norm(intercept-basis.T@(basis@intercept)));estimable=residual<=SUPPORT_RTOL
coef=basis.T@((u[:,:rank].T@target)/s[:rank]);support=zero_support(x[use]);model_value=raw-float(np.sum(w[use]*(x[use]@coef[1:])))
reason=None if estimable and support['supported'] else 'ZERO_POINT_NOT_ESTIMABLE' if not estimable else 'ZERO_POINT_OUTSIDE_SUPPORT'
return dict(value=model_value if reason is None else None,raw=raw,model_adjusted_value=model_value,alpha=float(coef[0]) if estimable else None,beta_minimum_norm=coef[1:].tolist(),rank=rank,zero_point_estimable=estimable,estimability_residual=residual,zero_support=support,dual_valid_parts=int(use.sum()),dual_valid_weight=mass,zero_columns=np.flatnonzero(np.all(x[use]==0,axis=0)).tolist(),reason=reason)
def interval(values,point,replicates):
a=np.asarray(values,float);ok=np.isfinite(a);failed=int((~ok).sum());usable=point is not None and failed/replicates<.05
lo=hi=None
if usable:lo,hi=map(float,np.percentile(a[ok],[2.5,97.5],method='linear'))
return dict(value=point,low=lo,high=hi,failed_replicates=failed,failed_fraction=failed/replicates,replicates=replicates,usable=bool(usable),reason=None if usable else 'POINT_UNIDENTIFIED_OR_AT_LEAST_5PCT_FAILED_REPLICATES')
def raw_gate(field,last,total_components=204):
if any(m['defined_components']!=total_components or m['high'] is None for m in [field,last]):return 'PARK_UNDEFINED'
return 'EXPAND_FIXED_TYPE_CONTEXT' if field['high']<0 or (last['high']<0 and field['high']<.001) else 'PRUNE_FIXED_TYPE_CONTEXT_RECIPE'
def analyse(rows,replicates=2000,seed=2026111408,expected_parts=552,expected_components=204):
if len(rows)!=expected_parts or len({r['case'] for r in rows})!=expected_parts or len({r['component_id'] for r in rows})!=expected_components:raise ValueError('Frozen evaluation roster incomplete or duplicated')
component=[r['component_id'] for r in rows];w,ids,group=weights_for_components(component);C=len(ids);sizes=np.bincount(group);rng=np.random.default_rng(seed);draws=rng.integers(0,C,size=(replicates,C));mult=np.array([np.bincount(d,minlength=C) for d in draws]);arrays=dict(component_draws=draws.astype(np.int32));comparisons={}
for a,b in PAIRS:
name=a+'-'+b;valid=np.zeros(len(rows),bool);x=np.full((len(rows),2),np.nan);categories=[]
for i,r in enumerate(rows):
ga=r['geometry']['arms'][a];gb=r['geometry']['arms'][b];da=ga.get('descriptor');db=gb.get('descriptor')
good=ga['valid'] and gb['valid'] and da is not None and db is not None
if good:
va=np.array([da['cut_area'],da['rms_diameter']]);vb=np.array([db['cut_area'],db['rms_diameter']]);good=bool(np.isfinite(va).all() and np.isfinite(vb).all() and np.all(va>0) and np.all(vb>0))
if good:x[i]=np.log(va/vb);valid[i]=True
categories.append('both_adjustable' if good else 'both_descriptor_undefined' if ga['valid'] and gb['valid'] else 'a_only' if ga['valid'] else 'b_only' if gb['valid'] else 'neither')
pair=dict(raw={},adjusted={},covariates=dict(names=['log_cut_area_ratio','log_RMS_diameter_ratio'],centered=False,dual_valid_parts=int(valid.sum()),dual_valid_weight=float(w[valid].sum()),range_min=x[valid].min(0).tolist() if valid.any() else None,range_max=x[valid].max(0).tolist() if valid.any() else None,points=[dict(case=r['case'],component_id=r['component_id'],x=x[i].tolist() if valid[i] else None,category=categories[i],weight=float(w[i])) for i,r in enumerate(rows)]))
for metric in METRICS:
va=np.array([np.nan if r['metrics'][a][metric]['value'] is None else r['metrics'][a][metric]['value'] for r in rows]);vb=np.array([np.nan if r['metrics'][b][metric]['value'] is None else r['metrics'][b][metric]['value'] for r in rows]);d=va-vb;component_d=np.array([d[group==g].mean() for g in range(C)]);boot=component_d[draws].mean(1);defined=int(np.isfinite(component_d).sum());point=float(component_d.mean()) if defined==C else None
raw=interval(boot,point,replicates);raw.update(defined_components=defined,total_components=C,undefined_component_ids=[ids[g] for g in range(C) if not np.isfinite(component_d[g])],arm_means={a:float(np.mean([va[group==g].mean() for g in range(C)])) if np.isfinite(va).all() else None,b:float(np.mean([vb[group==g].mean() for g in range(C)])) if np.isfinite(vb).all() else None});pair['raw'][metric]=raw;arrays[name+'_'+metric+'_raw']=boot
if metric=='kendall_tau_b':continue
adj=adjusted_estimate(d,x,valid,w);values=np.full(replicates,np.nan);failures={};ranks=[]
for k in range(replicates):
wk=mult[k][group]/(C*sizes[group]);v=adjusted_estimate(d,x,valid,wk)
if v['value'] is not None:values[k]=v['value']
else:failures[v['reason']]=failures.get(v['reason'],0)+1
ranks.append(v.get('rank'))
summary=interval(values,adj['value'],replicates);summary.update(point_diagnostics=adj,failed_reasons=failures,bootstrap_regression_refitted=True,rank_counts={str(k):ranks.count(k) for k in set(ranks)},raw_contribution_by_category={category:float(np.sum(w[np.array(categories)==category]*d[np.array(categories)==category])) if np.isfinite(d[np.array(categories)==category]).all() else None for category in sorted(set(categories))});pair['adjusted'][metric]=summary;arrays[name+'_'+metric+'_adjusted']=values
comparisons[name]=pair
decision=raw_gate(comparisons['T-G']['raw']['relative_l2'],comparisons['T-G']['raw']['last_location'],C)
return dict(parts=len(rows),components=C,decision=decision,comparisons=comparisons,seed=seed,replicates=replicates,weights='1/(original component count * original component part count); multiplicity on resample',deployment_gate='raw full-roster T-G only',adjusted_scope='descriptive mechanism; conditional on fixed models/folds and one shuffle; not causal',svd_rcond=SVD_RCOND,support_rtol=SUPPORT_RTOL),arrays
+19
View File
@@ -0,0 +1,19 @@
"""Explicit engineering adapter: replace only coordinator Git storage backend."""
import importlib,json,sys
from pathlib import Path
from phase2_h1_worker_v2 import checked,sha
import phase2_fixed_io
from phase2_local_freeze_io import freeze,ENGINEERING,BASE
def run(module,root):
e=json.loads(ENGINEERING.read_text());job=e['jobs'][root.name]
if job['module']!=module:raise PermissionError('Unapproved coordinator')
for p,h in e['engineering_sha256'].items():checked(BASE/p,h)
checked(root/'contract.json',job['contract_sha256']);phase2_fixed_io.verify(root,'launch')
target=importlib.import_module(module)
if target.freeze is not phase2_fixed_io.freeze:raise RuntimeError('Unexpected existing storage adapter')
# No scientific function, source, config, model, or guard changes.
# Children still execute the original pinned entry; original verify reads the same proof format.
target.freeze=freeze
target.run(root)
if __name__=='__main__':run(sys.argv[1],Path(sys.argv[2]))
+35
View File
@@ -0,0 +1,35 @@
"""6657 engineering-only local Git barriers; unchanged scientific proof verifier."""
import fcntl,hashlib,json,shutil,subprocess
from pathlib import Path
from phase2_h1_worker_v2 import sha,save
BASE=Path('/home/frank14f/optane/MeltMind')
STORE=Path('/tmp/meltmind-phase2-local-fixed-20261117')
LOCK=Path('/tmp/meltmind-phase2-local-fixed-20261117.lock')
BRANCH='codex/phase2-local-fixed-20261117'
ENGINEERING=BASE/'artifacts/phase2-local-launch-2026-11-17/engineering-contract.json'
def freeze(root,name,files):
with LOCK.open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX)
def git(*args):return subprocess.check_output(['git','-C',str(STORE),'-c','gc.auto=0',*args],text=True).strip()
if not (STORE/'.git').exists():
STORE.mkdir(exist_ok=True)
if list(STORE.iterdir()):raise RuntimeError('Unrecognized local evidence store')
subprocess.run(['git','init','-q','-b',BRANCH,str(STORE)],check=True)
if git('branch','--show-current')!=BRANCH or git('status','--porcelain'):raise RuntimeError('Local barrier writer not clean')
hashes={}
extra=[]
if ENGINEERING.exists():
e=json.loads(ENGINEERING.read_text());extra=[ENGINEERING,*[BASE/p for p in e['engineering_sha256']]]
for p,h in e['engineering_sha256'].items():
if sha(BASE/p)!=h:raise RuntimeError('Engineering source changed: '+p)
for p in [*files,*extra]:
p=Path(p);rel=str(p.resolve().relative_to(BASE));dest=STORE/rel;dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(p,dest);hashes[rel]=sha(p)
subprocess.run(['git','-C',str(STORE),'add','--',*hashes],check=True)
if git('diff','--cached','--name-only'):
subprocess.run(['git','-C',str(STORE),'-c','user.name=MeltAstra','-c','user.email=meltrastra@local','commit','-q','-m','Phase2 local immutable '+root.name+' '+name],check=True)
commit=git('rev-parse','HEAD')
for rel,h in hashes.items():
if hashlib.sha256(subprocess.check_output(['git','-C',str(STORE),'show',commit+':'+rel])).hexdigest()!=h:raise ValueError('Local Git byte mismatch')
save(root/(name+'-git-freeze.json'),dict(commit=commit,sha256=hashes,remote_published=False,local_repository=str(STORE),backend='6657_local_immutable_barrier',approval='1794906657.779289'))
save(root/(name+'-authorization.json'),dict(proof_sha256=sha(root/(name+'-git-freeze.json')),contract_sha256=sha(root/'contract.json')))
+61
View File
@@ -0,0 +1,61 @@
"""6657 single replacement launcher and local-to-remote identity monitor."""
import fcntl,json,os,subprocess,sys,time
from pathlib import Path
import psutil,shutil
from phase2_h1_worker_v2 import sha,checked,save
from phase2_local_freeze_io import BASE,ENGINEERING,freeze
from phase2_continuation_launch_chain import processes
def read(p):return json.loads(p.read_text())
def run(root):
os.sched_setaffinity(0,[30,31]);lock=(root/'run.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if (root/'started.json').exists():raise FileExistsError('One labelled replacement')
e=read(ENGINEERING)
for p,h in e['engineering_sha256'].items():checked(BASE/p,h)
old=BASE/'artifacts/phase2-approved-continuation-launch-chain-2026-11-17'
if not (old/'retirement.json').exists() or psutil.pid_exists(604069):raise RuntimeError('Original waiter not retired')
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),approval=e['approval'],engineering_contract_sha256=sha(ENGINEERING),original_waiter_retired=True))
launched=[]
try:
for name in e['order']:
j=e['jobs'][name];r=BASE/'artifacts'/name;c=read(checked(r/'contract.json',j['contract_sha256']))
for p,h in {**c['code_sha256'],**c['source_sha256']}.items():checked(BASE/p,h)
if (r/'started.json').exists() or (r/'service-launch.json').exists():raise RuntimeError('Root already attempted: '+name)
for p in processes():
args=p['cmdline'] or []
if str(r) in args and (j['module'] in args or 'tools/'+j['module']+'.py' in args or 'tools/'+j['worker'] in args):raise RuntimeError('Existing root process')
if name=='phase2-b15-recovery-2026-11-17' and shutil.disk_usage(r).free<24*2**30:raise RuntimeError('B15 free space below24GiB')
freeze(r,'launch',[r/'contract.json',r/'acceptance.json',*[BASE/p for p in c['code_sha256']]])
proof=read(r/'launch-git-freeze.json');checked(r/'contract.json',j['contract_sha256']);commit=proof['commit']
cmd=['systemd-run','--user','--unit='+j['unit'],'--collect','--property=Restart=no','--property=WorkingDirectory='+str(BASE),'--setenv=OMP_NUM_THREADS=1','--setenv=OPENBLAS_NUM_THREADS=1','--setenv=MKL_NUM_THREADS=1',sys.executable,'tools/phase2_local_coordinator.py',j['module'],str(r)]
save(root/(name+'-launch-requested.json'),dict(unix=time.time(),contract_sha256=j['contract_sha256'],local_commit=commit,unit=j['unit']))
result=subprocess.run(cmd,check=True,capture_output=True,text=True);save(r/'service-launch.json',dict(unit=j['unit'],unix=time.time(),local_commit=commit,remote_required=False,engineering_contract_sha256=sha(ENGINEERING),stdout=result.stdout,stderr=result.stderr))
observed=None;end=time.monotonic()+300
while time.monotonic()<end:
actual=[p for p in processes() if str(r) in (p['cmdline'] or []) and 'tools/'+j['worker'] in p['cmdline'] and j['mode'] in p['cmdline']]
if actual:
for p in actual:p['cpu_affinity']=psutil.Process(p['pid']).cpu_affinity()
observed=dict(status='WORKER_OBSERVED',unix=time.time(),started=read(r/'started.json'),workers=actual,contract_sha256=sha(r/'contract.json'),source_pins_pass=True,local_commit=commit,remote_published=False,engineering_contract_sha256=sha(ENGINEERING));save(r/'actual-start-audit.json',observed);break
if (r/'complete.json').exists():raise RuntimeError('Root stopped before actual worker: '+name)
time.sleep(1)
if observed is None:raise RuntimeError('Worker not observed within5min')
launched.append(dict(root=name,pid=observed['started']['pid'],local_commit=commit,contract_sha256=j['contract_sha256'],workers=[p['pid'] for p in observed['workers']]))
save(root/'progress.json',dict(stage='ACTUAL_START_VERIFIED',launched=launched,unix=time.time()))
save(root/'launch-complete.json',dict(status='ALL_THREE_ACTUAL_STARTS_VERIFIED',launched=launched,unix=time.time(),science_results_pending=True))
mapping={};deadline=time.monotonic()+24*3600
while len(mapping)<len(e['order']):
if time.monotonic()>deadline:raise RuntimeError('Remote mapping wait expired; starts not repeated')
for name in e['order']:
j=e['jobs'][name];r=BASE/'artifacts'/name;p=r/'publication.json';mismatch=sha(r/'contract.json')!=j['contract_sha256']
if p.exists():
proof=read(p);rel=str((r/'contract.json').relative_to(BASE));mismatch=mismatch or proof['files'].get(rel)!=j['contract_sha256']
if proof.get('remote_published') and not mismatch:
mapping[name]=dict(local_commit=read(r/'launch-git-freeze.json')['commit'],remote_commit=proof['commit'],contract_sha256=j['contract_sha256'],hash_match=True,unix=time.time());save(r/'local-remote-mapping.json',mapping[name])
if mismatch:
save(root/(name+'-contract-mismatch.json'),dict(status='STOP_ROOT',expected=j['contract_sha256'],actual=sha(r/'contract.json'),unix=time.time()))
subprocess.run(['systemctl','--user','stop',j['unit']],check=False);raise RuntimeError('Contract changed; root stopped: '+name)
save(root/'progress.json',dict(stage='WAIT_REMOTE_IDENTITY_MAPPING',launched=launched,mapped=list(mapping),unix=time.time()));time.sleep(5)
save(root/'complete.json',dict(status='STARTS_AND_REMOTE_MAPPING_COMPLETE',launched=launched,mapping=mapping,unix=time.time()))
except BaseException as exc:
save(root/'complete.json',dict(status='ENGINEERING_STOPPED',reason=type(exc).__name__+': '+str(exc),launched=launched,unix=time.time(),no_retry=True));raise
if __name__=='__main__':run(Path(sys.argv[1]))
+58
View File
@@ -0,0 +1,58 @@
"""Read-only input verification and one-time postfit contract construction; no fits."""
import json,time,unittest,io,resource
from pathlib import Path
from collections import Counter
import numpy as np
from phase2_h1_worker_v2 import checked,sha,save
from phase2_fixed_io import BASE,verify
from phase2_e2_postfit import validate_roles
def read(p):return json.loads(Path(p).read_text())
def prepare():
start=time.process_time();geo=BASE/'artifacts/phase2-b13-e2-geometry-2026-11-17';g=read(geo/'contract.json');done=read(geo/'complete.json');manifest=read(geo/'geometry-manifest.json');root=BASE/'artifacts/phase2-b13-e2-postfit-2026-11-17'
if root.exists():raise FileExistsError('One-time E2 postfit preparation; inspect existing root')
if done['status']!='GEOMETRY_COMPLETE_POSTFIT_PENDING' or len(done['records'])!=552 or any(r['guard']['status']!='PASS' for r in done['records']):raise ValueError('Geometry terminal scope')
for p,h in {**g['code_sha256'],**g['source_sha256']}.items():checked(BASE/p,h)
validate_roles(g)
stream=io.StringIO();tests=unittest.defaultTestLoader.loadTestsFromNames(['test_phase2_e2_statistics','test_phase2_e2_postfit']);result=unittest.TextTestRunner(stream=stream,verbosity=2).run(tests)
if not result.wasSuccessful():raise RuntimeError(stream.getvalue())
root.mkdir();save(root/'synthetic-acceptance.json',dict(status='PASS',tests=result.testsRun,output=stream.getvalue(),cpu_seconds_in_setup=time.process_time()-start))
entries=[];geometry={}
for item in manifest['entries']:
i=item['index'];row=g['parts'][i];p=geo/'parts'/f'{i:04d}'/'result.json';r=read(checked(p,item['result_sha256']))
if row['case']!=item['case'] or r['case']!=row['case'] or r['status']!='PREPARATION_COMPLETE':raise ValueError('Geometry manifest identity')
arms={};geometry[row['case']]=r
for arm in ['T','C','G']:
a=r['arms'][arm];f=geo/'parts'/f'{i:04d}'/arm/'extra.npy' if arm!='G' else Path(g['G_sources'][row['case']]['extra']);h=a['extra_sha256'] if arm!='G' else a['source_extra_sha256'];v=np.load(checked(f,h),mmap_mode='r',allow_pickle=False)
if v.shape!=(row['nodes'],2) or (a['valid'] and not np.isfinite(v).all()) or (not a['valid'] and not np.isnan(v).all()):raise ValueError('Geometry validity/readout mismatch')
arms[arm]=dict(path=str(f),sha256=h,valid=a['valid'],descriptor_defined='descriptor' in a)
entries.append(dict(case=row['case'],index=i,geometry_result=str(p),geometry_sha256=item['result_sha256'],arms=arms))
if len(entries)!=552 or len({e['case'] for e in entries})!=552:raise ValueError('Exactly552 geometry entries')
e1=Path(g['G_prediction_manifest']).parent;verify(e1,'predictions');ep=read(e1/'contract.json');Gscore=e1/'score/result.json';gs=read(Gscore);gp=read(checked(g['G_prediction_manifest'],g['G_prediction_manifest_sha256']))
if gs['decision']!='CONFIRMED_FIXED_GENERIC_CONTEXT_INCREMENT' or gs['parts']!=552 or gs['components']!=204 or ep['folds']!=g['folds'] or ep['parts']!=g['parts']:raise ValueError('E1b roles/confirmation changed')
if len(gp['entries'])!=552 or {e['case'] for e in gp['entries']}!={e['case'] for e in entries}:raise ValueError('G prediction roster')
for e in gp['entries']:checked(e['path'],e['sha256'])
gm=[];source={str(geo/n):sha(geo/n) for n in ['contract.json','complete.json','geometry-manifest.json','first-ten-cost-check.json']}
for f in range(5):
d=Path(g['G_model_root'])/str(f);verify(d,'model');r=read(d/'phases/train/result.json');checked(d/'phases/train/model.ubj',r['checkpoint_sha256'])
access=(BASE/'artifacts/phase2-b13-gate-2026-11-17/phases/train/target-access.json') if f==0 else d/'phases/train/target-access.json';a=read(access);rows=g['folds'][f]['rows']['learning']
if [(x['case'],x['nodes'],x['target_sha256']) for x in a]!=[(x['case'],x['nodes'],x['v5_cache']['output_sha256']['target.npy']) for x in rows]:raise ValueError('G original learning identity')
gm.append(dict(fold=f,model_sha256=r['checkpoint_sha256'],learning_parts=len(rows),target_access_sha256=sha(access),old_role_metadata_hardcoding_preserved=True))
for p in [d/'phases/train/result.json',d/'phases/train/model.ubj',access]:source[str(p)]=sha(p)
for p in [Path(g['G_prediction_manifest']),Gscore,e1/'contract.json',BASE/'references/2026-11-17/phase2-design/mold-b13-e2-spec-182e0312.md']:source[str(p)]=sha(p)
coverage={}
for fold in g['folds']:
coverage[str(fold['fold'])]={}
for role,rows in fold['rows'].items():
groups={}
for row in rows:groups.setdefault(row['component_id'],[]).append(row)
combos=Counter(''.join('1' if geometry[r['case']]['arms'][a]['valid'] else '0' for a in ['G','T','C']) for r in rows)
coverage[str(fold['fold'])][role]=dict(parts=len(rows),components=len(groups),validity_order='GTC',validity_combinations={format(i,'03b'):combos[format(i,'03b')] for i in range(8)},arm={a:dict(valid_parts=sum(geometry[r['case']]['arms'][a]['valid'] for r in rows),complete_components=sum(all(geometry[r['case']]['arms'][a]['valid'] for r in rs) for rs in groups.values())) for a in ['G','T','C']})
names=['phase2_e2_postfit','phase2_e2_statistics','prepare_phase2_e2_postfit','test_phase2_e2_statistics','test_phase2_e2_postfit','phase2_local_freeze_io','phase2_fixed_io','phase2_h1_worker_v2','phase2_b1213_features','gre24_models','s2_custody_common','s2_custody_statistics','r4bc_guard','s2_recovery_supervisor','s2_recovery_monitoring','s2_models/objectives']
code={**g['code_sha256'],**{f'tools/{n}.py':sha(BASE/f'tools/{n}.py') for n in names}};doc=BASE/'docs/phase2-b13-e2-postfit-contract-2026-11-17.md';code[str(doc.relative_to(BASE))]=sha(doc)
c=dict(version='E2-postfit-v1',approval='1794907827.062989',prior_review='1794904249.794959',parts=g['parts'],folds=g['folds'],archive=g['archive'],archive_stat=g['archive_stat'],geometry_root=str(geo),G_prediction_manifest=g['G_prediction_manifest'],G_score=str(Gscore),G_models=gm,code_sha256=code,source_sha256=source,total_cpu_seconds=14400,prior_geometry_cpu_seconds=done['cumulative_cpu_seconds'],setup_seconds=60,worker_cpus=[8,10,12,14],job_caps=dict(train=1800,predict=120,score=2400),disk_bytes=12*2**30,new_fits=10,new_geometry=0,new_label_decodes=0,retry=False,gpu=False,postfit_projection=g['postfit_projection'],projected_total_cpu_seconds=done['cumulative_cpu_seconds']+60+g['postfit_projection']['total'],statistics=dict(replicates=2000,seed=2026111408,svd_rcond=1e-12,support_rtol=1e-10,adjusted_interval_max_failed_fraction_exclusive=.05,deployment_gate='raw full-roster T-G only'))
if c['projected_total_cpu_seconds']>14400:raise RuntimeError('POSTFIT_PROJECTION_EXCEEDS_TOTAL')
save(root/'contract.json',c);save(root/'features-manifest.json',dict(entries=entries,all552_terminal=True,new_geometry=False));save(root/'coverage.json',coverage)
save(root/'preparation-audit.json',dict(status='PASS',geometry_guards=552,feature_arrays_verified=1656,G_predictions_verified=552,G_models_verified=5,roles_verified=True,test_parts=552,test_components=204,geometry_prior_counted_once=done['cumulative_cpu_seconds'],source_sha256=source,setup_cpu_seconds=time.process_time()-start,new_label_access=False,new_computation=False,contract_sha256=sha(root/'contract.json')))
print(json.dumps(dict(root=str(root),contract_sha256=sha(root/'contract.json'),setup_cpu_seconds=time.process_time()-start,projected_total=c['projected_total_cpu_seconds'])))
if __name__=='__main__':prepare()
+11
View File
@@ -0,0 +1,11 @@
import unittest
from phase2_b13_e1b import pooled,branch_decision
class FullRosterTests(unittest.TestCase):
def test_invalid_G_not_filtered_from_gate(self):
metric=lambda x:{k:dict(value=x,reason=None) for k in ['relative_l2','last_location','kendall_tau_b']}
rows=[dict(component_id=str(i),G_valid=i<102,new=metric(.9 if i<102 else 3),A=metric(1)) for i in range(204)]
result=pooled(rows);self.assertEqual(result['relative_l2']['components']['new'],204);self.assertEqual(branch_decision(result),'NOT_CONFIRMED_FIXED_RECIPE');self.assertLess(pooled(rows[:102])['relative_l2']['new_minus_A']['high'],0)
def test_full204_required_and_strict_bound(self):
m=lambda n,h:dict(relative_l2=dict(components=dict(new=n,A=n),new_minus_A=dict(high=h)))
self.assertEqual(branch_decision(m(203,-1)),'PARK_UNDEFINED');self.assertEqual(branch_decision(m(204,0)),'NOT_CONFIRMED_FIXED_RECIPE');self.assertEqual(branch_decision(m(204,-1e-12)),'CONFIRMED_FIXED_GENERIC_CONTEXT_INCREMENT')
if __name__=='__main__':unittest.main()
@@ -0,0 +1,10 @@
import unittest
from phase2_b14_resource_continuation import resource_failure
class ResourceTests(unittest.TestCase):
def test_only_300_cpu_wall_failures_continue(self):
for reason in ['cpu_limit','wall_limit','cpu_limit_after_exit','wall_limit_after_exit']:
g=dict(status='FAILED',stop_reason=reason,monitor_errors=[]);self.assertTrue(resource_failure(g,300));self.assertFalse(resource_failure(g,60))
def test_other_failures_never_masked(self):
for reason in ['MONITOR_ERROR','process_count_limit','rss_limit','GUARD_SIGNAL_15',None]:self.assertFalse(resource_failure(dict(status='FAILED',stop_reason=reason,monitor_errors=[]),300))
def test_monitor_error_overrides_cpu(self):self.assertFalse(resource_failure(dict(status='FAILED',stop_reason='cpu_limit',monitor_errors=[dict(reason='missing')]),300))
if __name__=='__main__':unittest.main()
@@ -0,0 +1,13 @@
import ast,unittest
from pathlib import Path
from phase2_b15_prediction_continue import projection
class PredictionContinuationTests(unittest.TestCase):
def test_original_scientific_loop_unchanged(self):
def statements(path):
f=next(n for n in ast.parse(Path(path).read_text()).body if isinstance(n,ast.FunctionDef) and n.name=='predict');loop=next(n for n in f.body if isinstance(n,ast.For));return [ast.dump(n,include_attributes=False) for n in loop.body[:-1]]
self.assertEqual(statements('tools/phase2_b15_gate.py'),statements('tools/phase2_b15_prediction_continue.py'))
def test_completed_cost_only_and_prior_once(self):
self.assertEqual(projection(3200,32,1,101),7200);self.assertEqual(projection(3210,32,1,101),7210);self.assertEqual(projection(4000,800,101,101),4000)
def test_invalid_support(self):
with self.assertRaises(ValueError):projection(0,0,0,101)
if __name__=='__main__':unittest.main()
+9
View File
@@ -0,0 +1,9 @@
import unittest
from phase2_b15_recovery import phase_projection
class ProjectionTests(unittest.TestCase):
def test_prior_counted_once(self):self.assertEqual(phase_projection(2100,1000,100,50),2725)
def test_no_remaining(self):self.assertEqual(phase_projection(2100,1000,100,0),2100)
def test_inputs(self):
for a in [(1,1,0,1),(1,1,2,-1)]:
with self.assertRaises(ValueError):phase_projection(*a)
if __name__=='__main__':unittest.main()
+23
View File
@@ -0,0 +1,23 @@
import json,tempfile,unittest
from pathlib import Path
from unittest.mock import patch
import numpy as np
import phase2_e2_geometry as e
from phase2_e2_geometry_queue import cost_projection
from test_o1_partition import box
from o1_partition import canonical_mesh,graph,Metis,readout
from phase2_h1_worker_v2 import sha
class E2GeometryTests(unittest.TestCase):
def test_one_invalid_arm_does_not_filter_valid_arms(self):
mesh=canonical_mesh(*box());g=graph(mesh);labels,ret=Metis().partition(g,mesh['raw_cells'],0);n=len(mesh['points']);f=np.zeros((n,19));f[:,0]=mesh['points'][:,0]/8;f[:,9]=.5;values=f[:,[0,9]][mesh['tets']].mean(1);extra=readout(mesh['tets'],mesh['volume'],values,labels,n)
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);dest=root/'parts/0000';dest.mkdir(parents=True);np.save(root/'G.npy',extra);np.savez(root/'G-partition.npz',labels=labels);(root/'G.json').write_text(json.dumps(dict(status='GEOMETRY_COMPLETE')))
row=dict(case='00000001_synthetic',component_id='s',nodes=n);c=dict(parts=[row],archive='not-read',O1_cache={},G_sources={row['case']:dict(result=str(root/'G.json'),result_sha256=sha(root/'G.json'),extra=str(root/'G.npy'),extra_sha256=sha(root/'G.npy'),partition=str(root/'G-partition.npz'),partition_sha256=sha(root/'G-partition.npz'))})
with patch.object(e,'source_geometry',return_value=(mesh,[])),patch.object(e,'input_geometry',return_value=(mesh['points'],mesh['tets'],mesh['raw_nodes'],{})),patch.object(e,'cached',side_effect=lambda row,key:f if key=='features' else np.ones(n)),patch.object(e,'Metis') as m:
m.return_value.partition.side_effect=[(labels,ret),(np.zeros(len(labels),np.int32),ret)];e.field(root,c,0);self.assertEqual(m.return_value.partition.call_count,2)
r=json.loads((dest/'result.json').read_text());self.assertTrue(r['arms']['G']['valid']);self.assertTrue(r['arms']['T']['valid']);self.assertFalse(r['arms']['C']['valid']);self.assertTrue(np.isnan(np.load(dest/'C/extra.npy')).all());np.testing.assert_array_equal(np.load(dest/'T/extra.npy'),extra);self.assertTrue(r['comparisons']['T-G']['bitwise_equal'])
def test_cost_includes_all_ten_and_future_stages(self):self.assertEqual(cost_projection(160,10,100,200),1510)
def test_invalid_cost_inputs_rejected(self):
for a in [(50,10,100,200),(160,0,100,200),(160,101,100,200)]:
with self.assertRaises(ValueError):cost_projection(*a)
if __name__=='__main__':unittest.main()
+40
View File
@@ -0,0 +1,40 @@
import tempfile,unittest,json
from pathlib import Path
from unittest.mock import patch
import numpy as np
import phase2_e2_postfit as p
class Postfit(unittest.TestCase):
def test_budget_includes_live_full_job_reservations(self):
self.assertTrue(p.admission(4000,3,1800));self.assertFalse(p.admission(7100,3,1800));self.assertFalse(p.admission(14300,0,120))
def test_missing_arm_keeps_native_nan(self):
with tempfile.TemporaryDirectory() as tmp:
f=Path(tmp)/'extra.npy';np.save(f,np.full((2,2),np.nan));e={'c':{'arms':{'T':{'path':str(f),'sha256':p.sha(f),'valid':False}}}}
self.assertTrue(np.isnan(p.extras({'case':'c','nodes':2},'T',e)).all())
e['c']['arms']['T']['valid']=True
with self.assertRaises(ValueError):p.extras({'case':'c','nodes':2},'T',e)
def test_query_identity_checks_multiplicity_and_wall(self):
q=dict(raw_ids=np.array([2,4]),counts=np.array([1,3]),coordinates_over_Rg=np.zeros((2,3)),near_wall=np.array([True,False]));p.query_identity(q,q)
for key in ['counts','near_wall','raw_ids']:
z={k:v.copy() for k,v in q.items()};z[key]=z[key][::-1]
with self.assertRaises(ValueError):p.query_identity(q,z)
def test_no_score_target_access_before_freeze(self):
with patch.object(p,'verify',side_effect=ValueError('unfrozen')),patch.object(p,'cached') as cache:
with self.assertRaises(ValueError):p.score(Path('/nonexistent'),{})
cache.assert_not_called()
def test_train_uses_actual_fold_and_full_missing_rows(self):
class Booster:
def save_config(self):return '{}'
class Model:
def fit(self,X,Y,sample_weight):
self.X=X.copy();self.Y=Y.copy();self.w=sample_weight.copy()
def save_model(self,path):Path(path).write_bytes(b'synthetic-model')
def get_booster(self):return Booster()
model=Model();row=dict(case='case',nodes=2,v5_cache=dict(output_sha256={'target.npy':'target','raw_ids.npy':'raw'}));c={'folds':[{}, {}, {'rows':{'learning':[row]}}]}
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);(root/'features-manifest.json').write_text(json.dumps({'entries':[{'case':'case'}]}));data=dict(features=np.ones((2,19)),raw_ids=np.array([1,3]),target=np.array([.2,.4]))
with patch.object(p,'verify'),patch.object(p,'cached',side_effect=lambda row,k:data[k]),patch.object(p,'extras',return_value=np.full((2,2),np.nan)),patch.object(p,'xgb_model',return_value=model) as factory:p.train(root,c,4)
factory.assert_called_once_with(0,1);self.assertEqual(model.X.shape,(2,21));self.assertTrue(np.isnan(model.X[:,19:]).all());np.testing.assert_allclose(model.Y,[.2,.4]);np.testing.assert_array_equal(model.w,[1,1])
a=p.read(root/'cells/04/train/target-access.json')[0];self.assertEqual((a['fold'],a['role'],a['arm']),(2,'learning','T'))
if __name__=='__main__':unittest.main()
+46
View File
@@ -0,0 +1,46 @@
import unittest
import numpy as np
from phase2_e2_statistics import weights_for_components,zero_support,adjusted_estimate,interval,raw_gate,analyse
class Statistics(unittest.TestCase):
def test_component_weights_and_resample(self):
w,ids,g=weights_for_components(['a','a','b']);np.testing.assert_allclose(w,[.25,.25,.5])
w,_,_=weights_for_components(['a','a','b'],[2,0]);np.testing.assert_allclose(w,[.5,.5,0])
def test_no_subset_renormalization(self):
x=np.array([[-1,0],[1,0],[np.nan,np.nan]]);d=np.array([-1.,3.,10.]);w=np.array([.25,.25,.5]);v=adjusted_estimate(d,x,[True,True,False],w)
self.assertAlmostEqual(v['value'],5.5);self.assertAlmostEqual(v['alpha'],1);self.assertEqual(v['dual_valid_weight'],.5)
def test_uncentered_correction(self):
x=np.array([[-1,-1],[1,-1],[-1,1],[1,1],[.5,.5]]);d=2+3*x[:,0]-4*x[:,1]
v=adjusted_estimate(d,x,np.ones(5,bool),np.ones(5)/5);self.assertAlmostEqual(v['value'],2);self.assertAlmostEqual(v['alpha'],2)
def test_zero_column_and_collinear_estimability(self):
for x in [np.zeros((3,2)),np.array([[-1,-2],[0,0],[1,2]])]:
v=adjusted_estimate(np.ones(3),x,[True]*3,np.ones(3)/3);self.assertTrue(v['zero_point_estimable']);self.assertAlmostEqual(v['value'],1)
def test_rank_deficient_offset_and_outside_hull(self):
x=np.array([[-1,1],[0,1],[1,1]]);v=adjusted_estimate(np.ones(3),x,[True]*3,np.ones(3)/3);self.assertIsNone(v['value']);self.assertFalse(v['zero_point_estimable'])
x=np.array([[1,1],[2,1],[1,2]]);v=adjusted_estimate(np.ones(3),x,[True]*3,np.ones(3)/3);self.assertTrue(v['zero_point_estimable']);self.assertIsNone(v['value'])
def test_origin_on_boundary_and_no_support(self):
self.assertTrue(zero_support([[0,0],[1,0],[0,1]])['supported']);self.assertFalse(zero_support([[2,0],[3,0]])['supported']);self.assertFalse(zero_support([])['supported'])
def test_exact_five_percent_boundary(self):
self.assertFalse(interval([np.nan]*5+[1]*95,1,100)['usable']);self.assertTrue(interval([np.nan]*4+[1]*96,1,100)['usable'])
def test_raw_gate_strict_and_complete(self):
f=dict(high=-.001,defined_components=204);l=dict(high=.1,defined_components=204)
self.assertEqual(raw_gate(f,l),'EXPAND_FIXED_TYPE_CONTEXT');self.assertEqual(raw_gate(dict(f,high=0),l),'PRUNE_FIXED_TYPE_CONTEXT_RECIPE');self.assertEqual(raw_gate(dict(f,defined_components=203),l),'PARK_UNDEFINED')
self.assertEqual(raw_gate(dict(f,high=.001),dict(l,high=-.1)),'PRUNE_FIXED_TYPE_CONTEXT_RECIPE')
def test_bootstrap_refits_and_retains_components(self):
rows=[];xs=[-1.,0.,1.,2.,-2.,.5];ds=[-1.,2.,1.,5.,0.,3.]
for i,(x,d) in enumerate(zip(xs,ds)):
geom={a:dict(valid=True,descriptor=dict(cut_area=float(np.exp(x)) if a=='T' else 1.,rms_diameter=1.)) for a in ['T','C','G']}
metrics={a:{m:dict(value=(d if a=='T' else 0.)) for m in ['relative_l2','last_location','kendall_tau_b']} for a in ['T','C','G']}
rows.append(dict(case=str(i),component_id=str(i),metrics=metrics,geometry=dict(arms=geom)))
result,arr=analyse(rows,replicates=40,seed=3,expected_parts=6,expected_components=6)
x=np.column_stack([xs,np.zeros(6)]);w=np.ones(6)/6;point=adjusted_estimate(ds,x,[True]*6,w);different=0
for k,draw in enumerate(arr['component_draws']):
wk=np.bincount(draw,minlength=6)/6;v=adjusted_estimate(ds,x,[True]*6,wk);got=arr['T-G_relative_l2_adjusted'][k]
if v['value'] is None:self.assertTrue(np.isnan(got))
else:
self.assertAlmostEqual(got,v['value']);fixed=np.dot(wk,ds)-np.sum(wk*(x@np.array(point['beta_minimum_norm'])))
different+=abs(got-fixed)>1e-8
self.assertGreater(different,0)
with self.assertRaises(ValueError):analyse(rows,replicates=2)
if __name__=='__main__':unittest.main()
+19
View File
@@ -0,0 +1,19 @@
import json,tempfile,unittest
from pathlib import Path
from unittest.mock import patch
import phase2_local_freeze_io as local
import phase2_fixed_io as original
class LocalBarrierTests(unittest.TestCase):
def test_original_verifier_and_tamper_detection(self):
with tempfile.TemporaryDirectory() as d:
b=Path(d)/'base';r=b/'run';r.mkdir(parents=True);(r/'contract.json').write_text('{}\n');p=b/'code.py';p.write_text('value=1\n')
with patch.multiple(local,BASE=b,STORE=Path(d)/'git',LOCK=Path(d)/'lock',ENGINEERING=b/'missing'),patch.object(original,'BASE',b):
local.freeze(r,'launch',[r/'contract.json',p]);proof=original.verify(r,'launch');self.assertFalse(proof['remote_published']);self.assertEqual(len(proof['commit']),40)
p.write_text('value=2\n')
with self.assertRaises(Exception):original.verify(r,'launch')
def test_sequential_barriers_preserve_prior_commit(self):
with tempfile.TemporaryDirectory() as d:
b=Path(d)/'base';r=b/'run';r.mkdir(parents=True);(r/'contract.json').write_text('{}\n');p=b/'code.py';p.write_text('value=1\n')
with patch.multiple(local,BASE=b,STORE=Path(d)/'git',LOCK=Path(d)/'lock',ENGINEERING=b/'missing'):
local.freeze(r,'one',[r/'contract.json',p]);one=json.loads((r/'one-git-freeze.json').read_text())['commit'];q=b/'model';q.write_text('fixed weights');local.freeze(r,'two',[r/'contract.json',q]);two=json.loads((r/'two-git-freeze.json').read_text())['commit'];self.assertNotEqual(one,two)
if __name__=='__main__':unittest.main()