Publish B17 terminal evidence and gate calibration v2 fixed execution scope

This commit is contained in:
MeltAstra committed 2026-11-17 20:23:41 +08:00
1 parent 1e1d5a6515
commit d67da6382b
57 files changed
+612570

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
"""Semantic review gate: every identity is supplied by an immutable binding."""
import json
from pathlib import Path
from phase2_h1_worker_v2 import sha
def validate_review(path,binding):
review=json.loads(Path(path).read_text())
if not isinstance(review,dict) or review.get('verdict')!='PASS':raise PermissionError('Review verdict must be exactly PASS')
for field in ['reviewed_commit','contract_sha256','launch_proof_sha256','fix_commit']:
if not isinstance(review.get(field),str) or review[field]!=binding[field]:raise PermissionError('Review identity mismatch: '+field)
expected=binding['fix_source_sha256']
if not expected or review.get('fix_source_sha256')!=expected:raise PermissionError('Review does not cover all fixed repair sources')
for p,h in expected.items():
if sha(p)!=h:raise PermissionError('Reviewed repair source changed: '+p)
old=Path(binding['original_root'])
if sha(old/'contract.json')!=binding['contract_sha256'] or sha(old/'launch-git-freeze.json')!=binding['launch_proof_sha256']:raise PermissionError('Original frozen root identity changed')
if json.loads((old/'launch-git-freeze.json').read_text())['commit']!=binding['reviewed_commit']:raise PermissionError('Original launch commit changed')
return review
+198
View File
@@ -0,0 +1,198 @@
"""B17: fixed G+channel readouts and tail-weighted direct regression; stage1 only."""
import argparse,fcntl,json,os,resource,signal,subprocess,sys,time
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
from phase2_home_freeze_io import freeze,verify
from phase2_e2_postfit import validate_roles,extras
from phase2_b1213_features import cached
from phase2_b13_e1b import pooled
from phase2_b17_math import tail_weights,validate_review
from phase2_b14_gate import field as original_channel_field
from gre24_models import xgb_model
from s2_custody_common import prediction_inputs
from s2_custody_statistics import part_metrics
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=read(root/'contract.json')
if c['approval']!='1794915553.067999' or c['total_cpu_seconds']!=10800 or c['new_fits']!=5 or c['new_geometry']!=121:raise PermissionError('Fixed B17 scope')
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)
validate_roles(c)
if set(c['new_indices']) & set(c['reused_indices']) or len(c['new_indices'])!=121 or len(c['reused_indices'])!=431 or set(c['new_indices'])|set(c['reused_indices'])!=set(range(552)):raise PermissionError('Exact missing121 and reused431 only')
return c
def job(index):
if index not in range(5):raise ValueError('Only five fits')
return index,'B17'
def jobroot(root,index):return root/'cells'/f'{index:02d}'
def channel_extra(root,row):
e=read(root/'B14-manifest.json')['by_case'][row['case']]
a=np.load(checked(e['path'],e['sha256']),allow_pickle=False)
if a.shape!=(row['nodes'],2) or np.isinf(a).any():raise ValueError('B14 readout identity/shape')
return a
def implementation_review(root):
verify(root,'implementation-review');launch=verify(root,'launch')
binding=dict(reviewed_commit=launch['commit'],contract_sha256=sha(root/'contract.json'),launch_proof_sha256=sha(root/'launch-git-freeze.json'),code_sha256=read(root/'contract.json')['code_sha256'])
return validate_review(root/'review.json',binding,BASE)
def decision(metrics):
m=metrics['last_location'];d=m['new_minus_A']
if m['components']!=dict(new=204,A=204) or d['high'] is None:return 'PARK_UNDEFINED'
return 'SCREEN_PASS_NOT_CONFIRMED' if d['value']<=-.010 and d['high']<0 else 'PRUNE_B17_FIXED_RECIPE'
def train(root,c,index):
verify(root,'features');verify(root,'channels');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,23),np.float32);Y=np.empty(n,np.float32);W=np.empty(n,np.float64);offset=0;access=[]
for row in rows:
f=cached(row,'features');e=extras(row,'G',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:21]=e;X[offset:end,21:]=channel_extra(root,row);Y[offset:end]=y;W[offset:end]=tail_weights(cached(row,'seconds'),cached(row,'mass'));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=23))
model.fit(X,Y,sample_weight=W);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=23,weights_per_part_node_mean_one=True,tail_mass_fraction=.10,tail_weight_ratio=4,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,'G',entries);X=np.column_stack([f[ix],e[ix],channel_extra(root,row)[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');implementation_review(root);dest=root/'score';dest.mkdir(exist_ok=False);m=read(root/'predictions-manifest.json')['entries'];by={r['case']:r for r in c['parts']};G={e['case']:e for e in read(c['G_prediction_manifest'])['entries']};old={r['case']:r for r in read(c['G_score'])['rows']}
if len(m)!=552 or {e['case'] for e in m}!=set(by):raise ValueError('Complete552 prediction roster required')
rows=[];access=[]
for e in m:
case=e['case'];row=by[case];g=G[case];prior=old[case]
if e['fold']!=g['fold'] or prior['fold']!=g['fold'] or prior['component_id']!=row['component_id']:raise ValueError('Paired role identity')
access.append(dict(case=case,role='test',fold=e['fold'],target_sha256=row['v5_cache']['output_sha256']['seconds.npy']));save(dest/'target-access.json',access)
truth=cached(row,'seconds');raw=cached(row,'raw_ids')
with np.load(checked(g['path'],g['sha256']),allow_pickle=False) as z,np.load(checked(e['path'],e['sha256']),allow_pickle=False) as v:
query_identity(z,v);ix=np.searchsorted(raw,v['raw_ids'])
if np.any(ix>=len(raw)) or not np.array_equal(raw[ix],v['raw_ids']):raise ValueError('Score query IDs')
metric=part_metrics(v['pred'],truth[ix],v['counts'],v['near_wall'],v['raw_ids'],v['coordinates_over_Rg'],int(case.split('_')[0]))
rows.append(dict(case=case,component_id=row['component_id'],fold=e['fold'],new=metric,G=prior['new'],A=prior['A'],G_valid=prior['G_valid'],negative_predictions=int(np.sum(v['pred']<0)),true_max_ties=int(np.sum(truth[ix]==truth[ix].max())),candidate_max_ties=int(np.sum(v['pred']==v['pred'].max())),G_max_ties=int(np.sum(z['pred']==z['pred'].max()))))
save(dest/'progress.json',dict(parts=len(rows)))
comparisons={a:pooled([dict(r,A=r[a]) for r in rows]) for a in ['G']};result=decision(comparisons['G'])
differences=[r['new']['last_location']-r['G']['last_location'] for r in rows if r['new']['last_location'] is not None and r['G']['last_location'] is not None]
save(dest/'result.json',dict(status='COMPLETE',decision=result,parts=552,components=204,new_minus=comparisons,primary='new minus frozen E1b G last-location mean<=-.010 and CI high<0; screening only',stage2_authorized=False,part_last_difference_median=float(np.median(differences)) if differences else None,rows=rows,original_G_metrics_reused=True,invalid_G_parts_retained=sum(not r['G_valid'] for r in rows),negative_predictions=sum(r['negative_predictions'] for r in rows),validation_used=False,new_decodes=0))
def worker(root,mode,index):
c=config(root)
if mode=='score':score(root,c)
elif mode=='field':original_channel_field(root,c,index)
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_b17.py','worker',str(root),mode,str(index)],d,dict(cpu_seconds=cap,wall_seconds=cap if mode=='field' else 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=10800):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 B17')
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['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),signals=list(requested));reasons=[]
if sample['cpu_seconds']>10800-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 active and any(m=='field' for _,_,m in active.values()) and sample['cpu_seconds']>c['geometry_cpu_cap']-120:reasons.append('GEOMETRY_RESERVE_FOR_POSTFIT')
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':
if m=='field' and r['guard'].get('stop_reason') in ['cpu_limit','wall_limit','cpu_limit_after_exit','wall_limit_after_exit'] and not r['guard'].get('monitor_errors'):
d=root/'parts'/f'{i:04d}';row=c['parts'][i];np.save(d/'extra.npy',np.full((row['nodes'],2),np.nan));save(d/'result.json',dict(status='RESOURCE_FAIL',case=row['case'],component_id=row['component_id'],index=i,extra_sha256=sha(d/'extra.npy'),reason=r['guard']['stop_reason'],labels_read=False,partial_families_retained_not_merged=True))
else: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],c['geometry_cpu_cap'] if mode=='field' else 10800):
if not active:raise RuntimeError('TOTAL_ADMISSION_RESERVE')
break
i=pending.pop(0)
if mode=='field':(root/'parts'/f'{i:04d}').mkdir(parents=True,exist_ok=False)
p=subprocess.Popen([sys.executable,'tools/phase2_b17.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'),new_geometry=121,reused_geometry=431))
old={s:signal.signal(s,lambda signum,frame:requested.append(signum)) for s in [signal.SIGTERM,signal.SIGINT]}
try:
batch('field',c['new_indices'][:10])
used=sum(r['guard']['cpu_seconds']+r['guard_cpu_seconds'] for r in records if r['mode']=='field')
projected=1.25*used*sum(c['parts'][i]['nodes'] for i in c['new_indices'])/sum(c['parts'][i]['nodes'] for i in c['new_indices'][:10])+c['setup_seconds']
save(root/'first-ten-cost-check.json',dict(projected_geometry_cpu_seconds=projected,geometry_cap=c['geometry_cpu_cap'],postfit_reserve=c['postfit_reserve'],passed=projected<=c['geometry_cpu_cap']))
if projected>c['geometry_cpu_cap']:raise RuntimeError('FIRST_TEN_COST_PROJECTION_STOP')
batch('field',c['new_indices'][10:])
by_case=dict(c['reused_channels'])
for i in c['new_indices']:
d=root/'parts'/f'{i:04d}';r=read(d/'result.json');p=checked(d/'extra.npy',r['extra_sha256']);by_case[c['parts'][i]['case']]=dict(path=str(p),sha256=r['extra_sha256'],result_path=str(d/'result.json'),result_sha256=sha(d/'result.json'),status=r['status'])
if set(by_case)!={r['case'] for r in c['parts']}:raise ValueError('All552 channel manifest')
save(root/'B14-manifest.json',dict(by_case=by_case,new=121,reused=431,labels_read=False))
freeze(root,'channels',[root/'contract.json',root/'B14-manifest.json',*[BASE/p for p in c['code_sha256']]])
batch('train',range(5));freeze(root,'models',[root/'contract.json',*[jobroot(root,i)/'train'/n for i in range(5) for n in ['model.ubj','result.json','target-access.json']],*[BASE/p for p in c['code_sha256']]])
batch('predict',range(5));entries=[]
for i in range(5):entries.extend(read(jobroot(root,i)/'predict/manifest.json')['entries'])
save(root/'predictions-manifest.json',dict(entries=entries,all552_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',root/'B14-manifest.json',Path(c['G_prediction_manifest']),Path(c['G_score']),*[BASE/p for p in c['code_sha256']]])
wait_start=time.monotonic()
while not (root/'implementation-review-authorization.json').exists():
limits();save(root/'live-progress.json',dict(stage='WAIT_IMPLEMENTATION_REVIEW_BEFORE_SCORE',cumulative_cpu_seconds=total(),wait_wall_seconds=time.monotonic()-wait_start,unix=time.time()));time.sleep(2)
implementation_review(root);batch('score',[0]);limits();save(root/'complete.json',dict(status='COMPLETE',decision=read(root/'score/result.json')['decision'],cumulative_cpu_seconds=total(),records=records,new_fits=5,new_predictions=552,reused_G_predictions=552,accounting_complete=True,retry=False))
freeze(root,'terminal',[root/'contract.json',root/'complete.json',root/'score/result.json',root/'score/target-access.json'])
save(root/'post-terminal-freeze-cost.json',dict(cumulative_cpu_seconds=total(),includes_terminal_freeze=True,within_cap=total()<=10800))
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))
+26
View File
@@ -0,0 +1,26 @@
"""Fixed B17 training weights and semantic pre-score review gate."""
import json
from pathlib import Path
import numpy as np
from phase2_h1_worker_v2 import sha
def tail_weights(seconds, mass):
t=np.asarray(seconds,dtype=np.float64);m=np.asarray(mass,dtype=np.float64)
if t.ndim!=1 or m.shape!=t.shape or not len(t) or not np.isfinite(t).all() or not np.isfinite(m).all() or np.any(m<=0):
raise ValueError('Invalid training time/mass')
order=np.argsort(-t,kind='stable');budget=.1*m.sum();cumulative=np.cumsum(m[order]);cut=t[order[np.searchsorted(cumulative,budget,side='left')]]
above=t>cut;ties=t==cut;fraction=(budget-m[above].sum())/m[ties].sum()
if not -1e-12<=fraction<=1+1e-12:raise ValueError('Tail mass fraction outside unit interval')
fraction=min(1.,max(0.,fraction));a=above.astype(np.float64);a[ties]=fraction
if not np.isclose(np.dot(m,a),budget,rtol=1e-12,atol=0):raise ValueError('Tail mass not ten percent')
w=1+3*a;return w/w.mean()
def validate_review(path,binding,base):
d=json.loads(Path(path).read_text())
if d.get('verdict')!='PASS':raise PermissionError('Review must explicitly PASS')
for k in ['reviewed_commit','contract_sha256','launch_proof_sha256','code_sha256']:
if d.get(k)!=binding[k]:raise PermissionError('Review identity mismatch: '+k)
if not binding['code_sha256']:raise PermissionError('Empty reviewed sources')
for name,digest in binding['code_sha256'].items():
if sha(Path(base)/name)!=digest:raise PermissionError('Reviewed source bytes changed')
return d
+84
View File
@@ -0,0 +1,84 @@
"""Independent B17 score-only repair; original fit/predict/coordinator pins untouched."""
import argparse,json,os,resource,sys,time,fcntl
from pathlib import Path
import numpy as np
from phase2_h1_worker_v2 import checked,sha,save
from phase2_home_freeze_io import verify,freeze
from phase2_fixed_io import BASE
from phase2_b17 import config as original_config,query_identity,decision
from phase2_b1213_features import cached
from phase2_b13_e1b import pooled
from s2_custody_statistics import part_metrics
from phase2_b16_review_gate import validate_review
from r4bc_guard import supervise
def read(p):return json.loads(Path(p).read_text())
def config(root):
c=read(root/'contract.json')
if c['total_cpu_seconds']!=10800 or c['new_fits']!=0 or c['new_predictions']!=0:raise PermissionError('Score-only scope')
for p,h in c['source_sha256'].items():checked(p,h)
for p,h in c['fix_source_sha256'].items():checked(p,h)
b=read(checked(root/'review-binding.json',c['binding_sha256']))
if b['fix_source_sha256']!=c['fix_source_sha256']:raise ValueError('Repair code identity')
old=Path(c['original_root']);prior=read(checked(old/'complete.json',c['original_terminal_sha256']))
if prior['cumulative_cpu_seconds']!=c['prior_cpu_seconds'] or len(prior['records'])!=131:raise ValueError('Original131 records required')
fits=[x for x in prior['records'] if x['mode'] in ['train','predict']]
if len(fits)!=10 or any(x['guard']['status']!='PASS' for x in fits):raise ValueError('Original ten fit/predict jobs not terminal PASS')
if {x['index'] for x in fits if x['mode']=='train'}!=set(range(5)) or {x['index'] for x in fits if x['mode']=='predict'}!=set(range(5)):raise ValueError('Five distinct fits/prediction jobs required')
verify(old,'channels');verify(old,'models')
if (old/'score').exists() or (old/'implementation-review-authorization.json').exists():raise PermissionError('Old scorer must remain unopened')
verify(root,'implementation-review');validate_review(root/'review.json',b)
verify(old,'predictions');checked(root/'predictions-manifest.json',c['predictions_manifest_sha256'])
return c,original_config(old)
def part_last_differences(rows):
values=[]
for row in rows:
a=row['new']['last_location']['value'];b=row['G']['last_location']['value']
if a is not None and b is not None:values.append(float(a)-float(b))
return values
def score(root,c):
verify(root,'predictions');verify(root,'implementation-review');validate_review(root/'review.json',read(root/'review-binding.json'));dest=root/'score';dest.mkdir(exist_ok=False);m=read(root/'predictions-manifest.json')['entries'];by={r['case']:r for r in c['parts']};G={e['case']:e for e in read(c['G_prediction_manifest'])['entries']};old={r['case']:r for r in read(c['G_score'])['rows']}
if len(m)!=552 or {e['case'] for e in m}!=set(by):raise ValueError('Complete552 prediction roster required')
rows=[];access=[]
for e in m:
case=e['case'];row=by[case];g=G[case];prior=old[case]
if e['fold']!=g['fold'] or prior['fold']!=g['fold'] or prior['component_id']!=row['component_id']:raise ValueError('Paired role identity')
access.append(dict(case=case,role='test',fold=e['fold'],target_sha256=row['v5_cache']['output_sha256']['seconds.npy']));save(dest/'target-access.json',access)
truth=cached(row,'seconds');raw=cached(row,'raw_ids')
with np.load(checked(g['path'],g['sha256']),allow_pickle=False) as z,np.load(checked(e['path'],e['sha256']),allow_pickle=False) as v:
query_identity(z,v);ix=np.searchsorted(raw,v['raw_ids'])
if np.any(ix>=len(raw)) or not np.array_equal(raw[ix],v['raw_ids']):raise ValueError('Score query IDs')
metric=part_metrics(v['pred'],truth[ix],v['counts'],v['near_wall'],v['raw_ids'],v['coordinates_over_Rg'],int(case.split('_')[0]))
rows.append(dict(case=case,component_id=row['component_id'],fold=e['fold'],new=metric,G=prior['new'],A=prior['A'],G_valid=prior['G_valid'],negative_predictions=int(np.sum(v['pred']<0)),true_max_ties=int(np.sum(truth[ix]==truth[ix].max())),candidate_max_ties=int(np.sum(v['pred']==v['pred'].max())),G_max_ties=int(np.sum(z['pred']==z['pred'].max()))))
save(dest/'progress.json',dict(parts=len(rows)))
comparisons={a:pooled([dict(r,A=r[a]) for r in rows]) for a in ['G']};result=decision(comparisons['G'])
differences=part_last_differences(rows)
save(dest/'result.json',dict(status='COMPLETE',decision=result,parts=552,components=204,new_minus=comparisons,primary='new minus frozen E1b G last-location mean<=-.010 and CI high<0; screening only',stage2_authorized=False,part_last_difference_median=float(np.median(differences)) if differences else None,rows=rows,original_G_metrics_reused=True,invalid_G_parts_retained=sum(not r['G_valid'] for r in rows),negative_predictions=sum(r['negative_predictions'] for r in rows),validation_used=False,new_decodes=0))
def worker(root):
c,science=config(root);score(root,science)
def run(root):
c,science=config(root);lock=(root/'run.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if (root/'started.json').exists():raise FileExistsError('Single repaired scorer attempt')
import psutil
for p in psutil.process_iter(['pid','cmdline']):
if any(x.endswith('phase2_b17.py') for x in (p.info['cmdline'] or [])):raise RuntimeError('Original coordinator must first reach labelled idle retirement')
verify(root,'launch');os.sched_setaffinity(0,[8]);start=time.process_time();u0=resource.getrusage(resource.RUSAGE_CHILDREN);guard_cpu=0.
def total():
u=resource.getrusage(resource.RUSAGE_CHILDREN);return c['prior_cpu_seconds']+c['repair_setup_cpu_seconds']+time.process_time()-start+max(guard_cpu,u.ru_utime+u.ru_stime-u0.ru_utime-u0.ru_stime)
cap=min(600.,10800-total()-120)
if cap<=0:raise RuntimeError('Same total budget exhausted')
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json'),prior_cpu_seconds=c['prior_cpu_seconds'],new_fits=0,new_predictions=0))
try:
g=supervise([sys.executable,'tools/phase2_b17_score_repair.py','worker',str(root)],root/'guard',dict(cpu_seconds=cap,wall_seconds=cap+180,rss_bytes=8*2**30,disk_bytes=3*2**30));guard_cpu=g['cpu_seconds']
if g['status']!='PASS' or total()>10800:raise RuntimeError('REPAIRED_SCORE_NOT_PASS')
save(root/'complete.json',dict(status='COMPLETE',decision=read(root/'score/result.json')['decision'],cumulative_cpu_seconds=total(),prior_cpu_seconds=c['prior_cpu_seconds'],guard=g,new_fits=0,new_predictions=0,accounting_complete=True,retry=False))
freeze(root,'terminal',[root/'contract.json',root/'complete.json',root/'score/result.json',root/'review.json',root/'review-binding.json'])
save(root/'post-terminal-freeze-cost.json',dict(cumulative_cpu_seconds=total(),within_cap=total()<=10800))
except BaseException as exc:
save(root/'complete.json',dict(status='STOPPED',reason=type(exc).__name__+': '+str(exc),cumulative_cpu_seconds=total(),accounting_complete=True,retry=False));raise
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('action',choices=['run','worker']);p.add_argument('root',type=Path);a=p.parse_args();(run if a.action=='run' else worker)(a.root)
+46
View File
@@ -0,0 +1,46 @@
"""Outcome calibration: fixed old algorithm, new sealed seed IDs, no labels."""
import json,time
from pathlib import Path
import numpy as np
from phase2_h1_worker_v2 import checked,save,sha
from phase2_b1213_features import input_geometry,cached
from gre24_features_v2 import mesh,exterior_faces,solve_eikonal,cell_flow_speed,strict_volume_cdf,nodal_gradient,spatial_moment
from o1_prepare import source_geometry
from o1_partition import readout
def recompute(x,t,dw,sources,progress=lambda *a,**kw:None):
g=mesh(x,t);faces=exterior_faces(t);timings={};tick=time.process_time()
def done(name):
nonlocal tick
now=time.process_time();timings[name]=now-tick;tick=now
progress('Di');di=solve_eikonal(g,sources,1.);done('Di')
speed,zero=cell_flow_speed(g,dw,faces);done('cell_speed')
progress('Df');df=solve_eikonal(g,sources,speed);done('Df')
if dw.max()<=0 or di.max()<=0:raise ValueError('Undefined feature normalization')
vf=strict_volume_cdf(df,g['mass']);dis=di/di.max();dws=dw/dw.max()
grads=[nodal_gradient(g,a) for a in (vf,dis,dws)];done('gradients')
progress('moments');moment,meta=spatial_moment(g,di,progress);done('moment')
features=np.column_stack([vf,grads[0],dis,grads[1],dw,dws,grads[2],moment])
if features.shape!=(len(x),19) or not np.isfinite(features).all():raise ValueError('Invalid recomputed features')
return dict(features=features,Di=di,Df=df,Vf=vf),dict(timings_cpu_seconds=timings,moment=meta,all_wall_tetrahedra=len(zero))
def prepare(root,c,index):
item=c['parts'][index];row=item['row'];dest=root/'parts'/f'{index:04d}';start=time.process_time()
x,t,raw,old=input_geometry(row);ids=np.array(item['gate_raw_ids'],dtype=np.int64);sources=np.searchsorted(raw,ids)
if not len(ids) or np.any(sources>=len(raw)) or not np.array_equal(raw[sources],ids):raise ValueError('Sealed source IDs outside tet domain')
dw=cached(row,'Dw')
def progress(stage,**kw):save(dest/'progress.json',dict(stage=stage,case=row['case'],cpu_seconds=time.process_time()-start,**kw))
arrays,meta=recompute(x,t,dw,sources,progress)
gentry=item['G'];extra=np.full((len(raw),2),np.nan)
if gentry['valid']:
cm,decoded=source_geometry(c['archive'],row['case'])
if not np.array_equal(cm['raw_nodes'],raw) or not np.array_equal(cm['points'],x):raise ValueError('Frozen G canonical identity')
with np.load(checked(gentry['partition_path'],gentry['partition_sha256']),allow_pickle=False) as z:labels=z['labels']
values=arrays['features'][:,[0,9]]
if labels.shape!=(len(cm['tets']),):raise ValueError('Frozen partition shape')
extra=readout(cm['tets'],cm['volume'],values[cm['tets']].mean(axis=1),labels,len(raw))
mass=np.bincount(cm['tets'].ravel(),weights=np.repeat(cm['volume']/4,4),minlength=len(raw))
if not np.allclose((mass[:,None]*values).sum(0),(mass[:,None]*extra).sum(0),rtol=1e-11,atol=1e-12):raise ValueError('G readout volume identity')
arrays['G_extra']=extra
for name,a in arrays.items():np.save(dest/(name+'.npy'),a,allow_pickle=False)
save(dest/'result.json',dict(status='FEATURES_COMPLETE_NO_PREDICTIONS',case=row['case'],index=index,output_sha256={name+'.npy':sha(dest/(name+'.npy')) for name in arrays},gate_raw_ids=ids.tolist(),Dw_reused_sha256=row['v5_cache']['output_sha256']['Dw.npy'],G_partition_reused=True,G_valid=gentry['valid'],new_labels_read=False,new_fits=0,cpu_seconds=time.process_time()-start,**meta))
+93
View File
@@ -0,0 +1,93 @@
"""Cal-v2 preparation only:493 recomputations,52 hash reuse,7 ineligible."""
import argparse,fcntl,json,os,resource,signal,subprocess,sys,time
from pathlib import Path
from phase2_fixed_io import BASE
from phase2_h1_worker_v2 import checked,save,sha
from phase2_home_freeze_io import verify,freeze
from phase2_gate_outcome_features import prepare
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_scope(c):
if c['approval']!='1794916421.489089' or c['total_cpu_seconds']!=72000 or len(c['parts'])!=493 or len(c['exact_reuse'])!=52 or len(c['invalid_cases'])!=7:raise PermissionError('Fixed full calibration v2 scope')
names=[p['row']['case'] for p in c['parts']]+[p['case'] for p in c['exact_reuse']]+c['invalid_cases']
if len(set(names))!=552 or set(names)!=set(c['original_cases']):raise ValueError('Disjoint complete552 roster required')
cpus=c['worker_cpus']
if len(cpus)!=12 or len(set(cpus))!=12 or set(cpus)&{8,10,12,14,30,31}:raise PermissionError('B17 and coordinator cores reserved')
if c['geometry_cpu_cap']+c['postfit_reserve']!=72000 or c['postfit_reserve']<3600:raise PermissionError('Shared calibration budget/reserve')
for p in c['parts']:
ids=p['gate_raw_ids']
if not ids or ids!=sorted(set(ids)):raise ValueError('Nonempty unique sorted sealed gate IDs required')
def projection(used,parts,setup,reserve):
return used*sum(p['row']['nodes'] for p in parts)/sum(p['row']['nodes'] for p in parts[:10])+setup+reserve
def config(root):
c=read(root/'contract.json')
validate_scope(c)
for p,h in {**c['source_sha256'],**c['code_sha256']}.items():checked(BASE/p,h)
s=Path(c['archive']).stat();a=c['archive_stat']
if (s.st_size,s.st_ino,s.st_mtime_ns)!=(a['bytes'],a['inode'],a['mtime_ns']):raise ValueError('Archive identity')
return c
def guard(root,index,slot):
c=config(root);os.sched_setaffinity(0,[c['worker_cpus'][slot]]);start=time.process_time();d=root/'parts'/f'{index:04d}'
g=supervise([sys.executable,'tools/phase2_gate_outcome_queue.py','worker',str(root),str(index)],d,dict(cpu_seconds=1800,wall_seconds=1800,rss_bytes=4*2**30,disk_bytes=2*2**30),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);verify(root,'launch');lock=(root/'run.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if (root/'started.json').exists():raise FileExistsError('Single calibration v2 queue')
os.sched_setaffinity(0,[30,31]);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['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 batch(indices,slots):
nonlocal settled
pending=list(indices)
while pending or active:
if requested or total()>c['geometry_cpu_cap']-120 or disk_usage(root)>c['disk_bytes'] or sum(tree_usage(p.pid)[1] for p,_ in active.values())>48*2**30:raise RuntimeError('Resource/signal stop')
for slot,(p,i) in list(active.items()):
if p.poll() is not None:
r=read(root/'parts'/f'{i:04d}'/'guard-result.json');records.append(r);settled+=r['guard']['cpu_seconds']+r['guard_cpu_seconds'];del active[slot]
if p.returncode or r['guard']['status']!='PASS':raise RuntimeError('FEATURE_WORKER_STOP_NO_RETRY')
for slot in range(slots):
if pending and slot not in active:
if total()+(len(active)+1)*1800+120>c['geometry_cpu_cap']:
if not active:raise RuntimeError('Full per-part reservation exceeds remaining budget')
break
i=pending.pop(0);p=subprocess.Popen([sys.executable,'tools/phase2_gate_outcome_queue.py','guard',str(root),str(i),str(slot)],start_new_session=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL);active[slot]=(p,i)
save(root/'live-progress.json',dict(stage='GATE_DEPENDENT_FEATURES_ONLY',pending=len(pending),active=[dict(slot=s,pid=p.pid,index=i) for s,(p,i) 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'),new_feature_parts=493,exact_reused=52,ineligible=7,new_labels_read=False))
old={s:signal.signal(s,lambda signum,frame:requested.append(signum)) for s in [signal.SIGTERM,signal.SIGINT]}
try:
batch(range(10),4)
used=sum(r['guard']['cpu_seconds']+r['guard_cpu_seconds'] for r in records)
projected=projection(used,c['parts'],c['setup_seconds'],c['postfit_reserve'])
save(root/'first-ten-cost-check.json',dict(first10_cpu_seconds=used,projected_total_cpu_seconds=projected,factor=1.,projection_kind='node weighted mean, fixed total cap supplies margin',postfit_reserve=c['postfit_reserve'],cap=72000,passed=projected<=72000))
if projected>72000:raise RuntimeError('FIRST_TEN_COST_STOP_NO_EXTENSION')
batch(range(10,493),12)
entries=[]
for i,item in enumerate(c['parts']):
p=root/'parts'/f'{i:04d}'/'result.json';d=read(p)
for name,h in d['output_sha256'].items():checked(p.parent/name,h)
entries.append(dict(case=item['row']['case'],index=i,path=str(p.parent),result_sha256=sha(p),output_sha256=d['output_sha256']))
save(root/'features-manifest.json',dict(recomputed=entries,exact_reuse=c['exact_reuse'],invalid_cases=c['invalid_cases'],parts_total=552,labels_read=False,new_fits=0,new_predictions=0))
save(root/'complete.json',dict(status='FEATURES_COMPLETE_PREDICTIONS_AND_COMPARISON_PENDING',records=records,cumulative_cpu_seconds=total(),total_cpu_seconds=72000,accounting_complete=True,new_fits=0,new_predictions=0,new_v2_labels_read=0,retry=False))
freeze(root,'features',[root/'contract.json',root/'features-manifest.json',root/'complete.json',*[BASE/p for p in c['code_sha256']]])
save(root/'post-freeze-cost.json',dict(cumulative_cpu_seconds=total(),within_cap=total()<=72000))
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/'parts'/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),records=records,cumulative_cpu_seconds=total(),accounting_complete=True,retry=False,new_v2_labels_read=0));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('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=='guard':raise SystemExit(guard(a.root,a.index,a.slot))
else:prepare(a.root,config(a.root),a.index)
+61
View File
@@ -0,0 +1,61 @@
"""Freeze full authorized calibration preparation without opening target values."""
import json,time,sys
from pathlib import Path
from phase2_fixed_io import BASE
from phase2_h1_worker_v2 import sha,checked,save
from phase2_home_freeze_io import freeze,verify
from phase2_gate_outcome_queue import validate_scope,config
def read(p):return json.loads(Path(p).read_text())
def partition_source(directory,case,expected,sources):
for _ in range(4):
r=read(directory/'result.json');checked(directory/'result.json',expected)
p=directory/'G-partition.npz'
if p.exists():return checked(p,r['partition_sha256'])
if 'source_partition' in r:return checked(r['source_partition'],r['partition_sha256'])
contract=directory.parent.parent/'contract.json';sources[str(contract)]=sha(contract)
match=[x for x in read(contract)['reused_geometry'] if x['case']==case]
if len(match)!=1 or match[0]['result_sha256']!=expected:raise ValueError('Unresolved original partition provenance')
directory=Path(match[0]['source'])
raise ValueError('Partition provenance chain too long')
def main():
root=Path('/home/frank14f/MeltMind-runs/phase2-gate-outcome-calibration-v2-2026-11-17')
if root.exists():raise FileExistsError('Single preparation root already exists')
old=Path('/home/frank14f/MeltMind-runs/phase2-holdout-gate-calibration-2026-11-17');groot=BASE/'artifacts/phase2-b13-e1b-2026-11-17'
verify(old,'terminal');cal=read(old/'calibration-result.json');extract=read(old/'extractor-receipt.json');science=read(groot/'contract.json');rows={r['case']:r for r in science['parts']};gmanifest=read(groot/'features-manifest.json')['entries'];pred={e['case']:e for e in read(groot/'predictions-manifest.json')['entries']}
if cal['accepted_for_v2'] or cal['exact_match_parts']!=52 or len(rows)!=552:raise ValueError('Original exact FAIL must stand')
sources={str(p):sha(p) for p in [old/'contract.json',old/'complete.json',old/'calibration-result.json',old/'extractor-receipt.json',groot/'contract.json',groot/'features-manifest.json',groot/'predictions-manifest.json']}
G={}
for e in gmanifest:
d=groot/'parts'/f"{e['index']:04d}";p=checked(d/'result.json',e['result_sha256']);v=read(p);sources[str(p)]=e['result_sha256'];valid=v['status']=='GEOMETRY_COMPLETE'
g=dict(valid=valid,extra_path=str(d/'extra.npy'),extra_sha256=v['extra_sha256'],result_path=str(p),result_sha256=sha(p))
checked(g['extra_path'],g['extra_sha256'])
if valid:
partition=partition_source(d,e['case'],e['result_sha256'],sources)
g.update(partition_path=str(checked(partition,v['partition_sha256'])),partition_sha256=v['partition_sha256'])
G[e['case']]=g
parts=[];reuse=[];invalid=[]
for entry in cal['rows']:
case=entry['case'];row=rows[case];gatefile=old/'gate-ids'/(case+'.json');ids=read(checked(gatefile,extract['output_sha256'][case+'.json']))['gate_raw_ids']
if ids!=entry['extracted_gate_raw_ids']:raise ValueError('Sealed gate identity')
if not ids:invalid.append(case);continue
if not entry['extracted_all_in_tet_domain']:raise ValueError('Invalid seed coverage')
if entry['exact_node_set_match']:
files={str(Path(row['v5_cache']['output'])/(k+'.npy')):row['v5_cache']['output_sha256'][k+'.npy'] for k in ['features','Di','Df','Dw','Vf','raw_ids']}
files[G[case]['extra_path']]=G[case]['extra_sha256'];files[pred[case]['path']]=pred[case]['sha256']
for p,h in files.items():checked(p,h)
reuse.append(dict(case=case,component_id=row['component_id'],row=row,G=G[case],prediction=pred[case],source_sha256=files,sealed_gate_sha256=sha(gatefile)))
else:parts.append(dict(row=row,gate_raw_ids=ids,sealed_gate_sha256=sha(gatefile),G=G[case]))
if set(invalid)!=set(extract['invalid_gate_input_cases']):raise ValueError('Invalid roster')
codes=dict(science['code_sha256'])
for p in ['tools/phase2_gate_outcome_features.py','tools/phase2_gate_outcome_queue.py','tools/prepare_phase2_gate_outcome.py','tools/test_phase2_gate_outcome_features.py','tools/test_phase2_gate_outcome_queue.py','tools/phase2_home_freeze_io.py','tools/phase2_local_freeze_io.py']:
codes[p]=sha(BASE/p)
for p,h in codes.items():checked(BASE/p,h)
c=dict(version='gate-outcome-v2-preparation-v1',approval='1794916421.489089',total_cpu_seconds=72000,geometry_cpu_cap=68400,postfit_reserve=3600,setup_seconds=600,worker_cpus=list(range(16,28)),disk_bytes=12*2**30,parts=parts,exact_reuse=reuse,invalid_cases=invalid,original_cases=list(rows),source_sha256=sources,code_sha256=codes,archive=science['archive'],archive_stat=science['archive_stat'],first_ten='first ten recomputed cases in frozen original order',first_ten_workers=4,after_cost_workers=12,new_fits=0,new_v2_label_reads=0,predictions_pending=True,comparison_pending=True,comparison_requires_semantic_assist_pass=True,acceptance_bands=dict(field=.001,last_location=.010,both_models=['A','B13-E1b']),exact_set_fail_preserved=True,download_42_paused=True,old_holdout_cost_not_charged_here=True,no_retry=True)
c['comparison_rule']=dict(approval='1794917650.044649',paired_parts='both label-gate and LOG-gate predictions defined',within_component='mean over defined paired parts',component_weight='equal',bootstrap_replicates=2000,bootstrap_seed=2026111408,no_imputation=True,eligibility_denominator=552,invalid_gate_parts=7,eligibility_loss='7/552',exclude_only_components_with_zero_defined_parts=True,report_excluded_component_count=True)
validate_scope(c);root.mkdir();save(root/'contract.json',c)
save(root/'acceptance.json',dict(status='PASS',tests=10,command='python -m unittest tools.test_phase2_gate_outcome_features tools.test_phase2_gate_outcome_queue',reported_elapsed_seconds=1.106,scope='3 original-algorithm bitwise synthetic checks plus7 scope/budget/actual guard checks',new_real_geometry_executions=0,setup_charged_seconds=600,unix=time.time()))
save(root/'preparation-audit.json',dict(status='PASS',recompute=len(parts),exact_reuse=len(reuse),invalid=len(invalid),no_labels_opened=True,exact_reuse_files_hash_checked=True,partitions_hash_checked=True,original_exact_fail=True,archive_metadata_only=True,unix=time.time()))
freeze(root,'launch',[root/'contract.json',root/'acceptance.json',root/'preparation-audit.json',*[BASE/p for p in codes]])
config(root);print(json.dumps(dict(root=str(root),commit=verify(root,'launch')['commit'],contract_sha256=sha(root/'contract.json'),real_queue_started=False)))
if __name__=='__main__':main()
+46
View File
@@ -0,0 +1,46 @@
import unittest,tempfile,json,copy,ast,subprocess
from pathlib import Path
from unittest.mock import patch
from phase2_h1_worker_v2 import sha
from phase2_b16_review_gate import validate_review
import phase2_home_freeze_io as fio
class ReviewGate(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();b=Path(self.tmp.name);self.base=b/'base';self.home=b/'runs';self.store=b/'store'
for p in [self.base,self.home,self.store]:p.mkdir()
subprocess.run(['git','init','-q','-b','codex/test',str(self.store)],check=True)
self.old=self.home/'old';self.old.mkdir();(self.old/'contract.json').write_text('{"scientific":"fixed"}');(self.old/'launch-git-freeze.json').write_text('{"commit":"34fd7b46"}');code=self.base/'scorer.py';code.write_text('fixed repair')
self.root=self.home/'score';self.root.mkdir();(self.root/'contract.json').write_text('{}');self.path=self.root/'review.json';self.binding=dict(original_root=str(self.old),reviewed_commit='34fd7b46',contract_sha256=sha(self.old/'contract.json'),launch_proof_sha256=sha(self.old/'launch-git-freeze.json'),fix_commit='fixcommit',fix_source_sha256={str(code):sha(code)})
self.good=dict(verdict='PASS',**{k:v for k,v in self.binding.items() if k!='original_root'});self.patches=[patch.object(fio,'BASE',self.base),patch.object(fio,'HOME_RUNS',self.home),patch.object(fio,'STORE',self.store),patch.object(fio,'LOCK',b/'lock'),patch.object(fio,'BRANCH','codex/test')]
for p in self.patches:p.start()
def tearDown(self):
for p in self.patches:p.stop()
self.tmp.cleanup()
def frozen_check(self,review):
self.path.write_text(json.dumps(review));fio.freeze(self.root,'implementation-review',[self.root/'contract.json',self.path]);fio.verify(self.root,'implementation-review');return validate_review(self.path,self.binding)
def test_pass_accepts_real_frozen_review(self):self.assertEqual(self.frozen_check(self.good)['verdict'],'PASS')
def test_fail_refused(self):
v=dict(self.good,verdict='FAIL')
with self.assertRaises(PermissionError):self.frozen_check(v)
def test_missing_verdict_refused(self):
v=dict(self.good);del v['verdict']
with self.assertRaises(PermissionError):self.frozen_check(v)
def test_wrong_commit_refused(self):
with self.assertRaises(PermissionError):self.frozen_check(dict(self.good,reviewed_commit='unrelated'))
def test_wrong_contract_refused(self):
with self.assertRaises(PermissionError):self.frozen_check(dict(self.good,contract_sha256='wrong'))
def test_wrong_launch_refused(self):
with self.assertRaises(PermissionError):self.frozen_check(dict(self.good,launch_proof_sha256='wrong'))
def test_unrelated_frozen_file_refused(self):
with self.assertRaises(PermissionError):self.frozen_check({'report':'unrelated'})
def test_fix_not_covered_refused(self):
with self.assertRaises(PermissionError):self.frozen_check(dict(self.good,fix_commit='otherfix'))
with self.assertRaises(PermissionError):self.frozen_check(dict(self.good,fix_source_sha256={}))
def test_science_ast_unchanged(self):
def get(path):return next(n for n in ast.parse(Path(path).read_text()).body if isinstance(n,ast.FunctionDef) and n.name=='score')
old=get('tools/phase2_b16.py');new=get('tools/phase2_b16_score_repair.py')
# Original first two statements are proof checks; new third is semantic validation.
self.assertEqual(ast.dump(ast.Module(body=old.body[2:],type_ignores=[])),ast.dump(ast.Module(body=new.body[3:],type_ignores=[])))
if __name__=='__main__':unittest.main()
+39
View File
@@ -0,0 +1,39 @@
import json,tempfile,unittest
from pathlib import Path
import numpy as np
from phase2_b17_math import tail_weights,validate_review
from phase2_h1_worker_v2 import sha
from phase2_b17 import decision,admission
class Weights(unittest.TestCase):
def test_equal_mass_top_tenth(self):
w=tail_weights(np.arange(10.),np.ones(10));self.assertAlmostEqual(w[-1]/w[0],4);self.assertAlmostEqual(w.sum(),10)
def test_tie_mass_shared(self):
w=tail_weights([0,1,1],[8,1,1]);np.testing.assert_allclose(w/w[0],[1,2.5,2.5]);self.assertAlmostEqual(w.mean(),1)
def test_large_node_mass_fractional(self):
w=tail_weights([0,1],[1,9]);np.testing.assert_allclose(w/w[0],[1,1+3/9]);self.assertAlmostEqual(w.sum(),2)
def test_constant_label_unit_weights(self):np.testing.assert_array_equal(tail_weights([5,5,5],[1,2,7]),np.ones(3))
def test_permutation_and_positive_scale(self):
t=np.array([1.,3.,2.]);m=np.array([3.,6.,1.]);p=np.array([2,0,1]);np.testing.assert_allclose(tail_weights(t*7,m*4),tail_weights(t,m));np.testing.assert_allclose(tail_weights(t[p],m[p]),tail_weights(t,m)[p])
def test_bad_mass(self):
with self.assertRaises(ValueError):tail_weights([1,2],[0,1])
def test_screen_boundaries(self):
def d(v,h):return decision({'last_location':dict(components=dict(new=204,A=204),new_minus_A=dict(value=v,high=h))})
self.assertEqual(d(-.010,-1e-8),'SCREEN_PASS_NOT_CONFIRMED');self.assertEqual(d(-.009999,-.002),'PRUNE_B17_FIXED_RECIPE');self.assertEqual(d(-.02,0),'PRUNE_B17_FIXED_RECIPE');self.assertEqual(d(-.02,None),'PARK_UNDEFINED')
def test_budget_reservation(self):
self.assertTrue(admission(5000,2,1500));self.assertFalse(admission(5000,3,1500));self.assertFalse(admission(6000,0,300,6300))
class Review(unittest.TestCase):
def test_real_receipt_identity_and_mutation(self):
with tempfile.TemporaryDirectory() as d:
b=Path(d);source=b/'source.py';source.write_text('fixed source\n');p=b/'review.json';binding=dict(reviewed_commit='abc',contract_sha256='contract',launch_proof_sha256='proof',code_sha256={'source.py':sha(source)})
good=dict(binding,verdict='PASS');p.write_text(json.dumps(good));validate_review(p,binding,b)
for key,value in [('verdict','FAIL'),('reviewed_commit','wrong'),('contract_sha256','wrong'),('launch_proof_sha256','wrong'),('code_sha256',{})]:
p.write_text(json.dumps(dict(good,**{key:value})))
with self.assertRaises(PermissionError):validate_review(p,binding,b)
bad=dict(good);del bad['verdict'];p.write_text(json.dumps(bad))
with self.assertRaises(PermissionError):validate_review(p,binding,b)
p.write_text(json.dumps(good));source.write_text('changed source\n')
with self.assertRaises(PermissionError):validate_review(p,binding,b)
if __name__=='__main__':unittest.main()
+32
View File
@@ -0,0 +1,32 @@
import ast,copy,json,unittest,tempfile
from pathlib import Path
import numpy as np
from phase2_b17_score_repair import part_last_differences
from s2_custody_statistics import part_metrics
from phase2_h1_worker_v2 import save
class Repair(unittest.TestCase):
def test_real_metric_schema_and_json_assembly(self):
truth=np.array([0.,1.,.8]);xyz=np.array([[0.,0.,0.],[1.,0.,0.],[0.,2.,0.]])
kw=dict(truth=truth,counts=np.ones(3,dtype=int),near_wall=np.ones(3,dtype=bool),raw_ids=np.arange(3),coordinates_over_Rg=xyz,prefix=3)
candidate=part_metrics(prediction=np.array([0.,.9,1.]),**kw)
baseline=part_metrics(prediction=np.array([0.,1.,.7]),**kw)
values=part_last_differences([{'new':candidate,'G':baseline}]);self.assertEqual(values,[np.sqrt(5.)])
out=json.loads(json.dumps(dict(part_last_difference_median=float(np.median(values))),allow_nan=False));self.assertEqual(out['part_last_difference_median'],np.sqrt(5.))
def test_none_filter_and_empty_nullable_median(self):
rows=[{'new':{'last_location':{'value':None}},'G':{'last_location':{'value':1.}}},{'new':{'last_location':{'value':2.}},'G':{'last_location':{'value':None}}}]
d=part_last_differences(rows);self.assertEqual(d,[]);
with tempfile.TemporaryDirectory() as folder:
path=Path(folder)/'result.json';save(path,dict(part_last_difference_median=float(np.median(d)) if d else None,rows=rows));self.assertIsNone(json.loads(path.read_text())['part_last_difference_median'])
def test_score_body_only_gate_and_median_input_changed(self):
def body(path):return copy.deepcopy(next(n for n in ast.parse(Path(path).read_text()).body if isinstance(n,ast.FunctionDef) and n.name=='score').body)
a=body('tools/phase2_b17.py');b=body('tools/phase2_b17_score_repair.py')
# Old first two statements are prediction proof and semantic review;
# new first three are prediction proof, review proof and repair binding.
a=a[2:];b=b[3:]
for nodes in [a,b]:
for node in nodes:
if isinstance(node,ast.Assign) and any(isinstance(t,ast.Name) and t.id=='differences' for t in node.targets):node.value=ast.Constant(value='ONLY_DESCRIPTIVE_MEDIAN_INPUT')
self.assertEqual(ast.dump(ast.Module(body=a,type_ignores=[])),ast.dump(ast.Module(body=b,type_ignores=[])))
if __name__=='__main__':unittest.main()
@@ -0,0 +1,20 @@
import unittest
import numpy as np
from test_gre24_features import box
from gre24_features_v2 import features,gate_nodes
from phase2_gate_outcome_features import recompute
class FixedAlgorithm(unittest.TestCase):
def test_same_gate_reproduces_full_original_feature_builder(self):
x,t=box();raw=np.arange(len(x));gate=x[0];old,meta=features(x,t,raw,gate)
source,_=gate_nodes(x,raw,gate);new,_=recompute(x,t,old['Dw'],source)
for name in ['features','Di','Df','Vf']:np.testing.assert_array_equal(new[name],old[name])
def test_different_sealed_gate_reproduces_original_marked_gate(self):
x,t=box();raw=np.arange(len(x));gate=x[0];sources=np.array([0,1],dtype=np.int64)
old,meta=features(x,t,raw,gate,marked_gate=sources);new,_=recompute(x,t,old['Dw'],sources)
for name in ['features','Di','Df','Vf']:np.testing.assert_array_equal(new[name],old[name])
def test_gate_independent_wall_columns_unchanged(self):
x,t=box();raw=np.arange(len(x));old,meta=features(x,t,raw,x[0]);new,_=recompute(x,t,old['Dw'],np.array([len(x)-1]))
np.testing.assert_array_equal(new['features'][:,8:13],old['features'][:,8:13])
if __name__=='__main__':unittest.main()
+36
View File
@@ -0,0 +1,36 @@
import copy,tempfile,sys,unittest
from pathlib import Path
from phase2_gate_outcome_queue import validate_scope,projection
from r4bc_guard import supervise
def contract():
return dict(approval='1794916421.489089',total_cpu_seconds=72000,parts=[dict(row=dict(case=str(i),nodes=100),gate_raw_ids=[0]) for i in range(493)],exact_reuse=[dict(case=str(i)) for i in range(493,545)],invalid_cases=[str(i) for i in range(545,552)],original_cases=list(map(str,range(552))),worker_cpus=list(range(16,28)),geometry_cpu_cap=68400,postfit_reserve=3600)
class Scope(unittest.TestCase):
def test_complete_disjoint_roster(self):
c=contract();validate_scope(c);c['exact_reuse'][0]['case']='0'
with self.assertRaises(ValueError):validate_scope(c)
def test_invalid_seven_cannot_be_dropped(self):
c=contract();c['invalid_cases'].pop()
with self.assertRaises(PermissionError):validate_scope(c)
def test_b17_cpu_conflict(self):
c=contract();c['worker_cpus'][0]=8
with self.assertRaises(PermissionError):validate_scope(c)
def test_postfit_budget_cannot_be_spent_twice(self):
c=contract();c['geometry_cpu_cap']=72000
with self.assertRaises(PermissionError):validate_scope(c)
def test_empty_or_duplicate_gate_rejected(self):
for ids in [[],[0,0],[1,0]]:
c=contract();c['parts'][0]['gate_raw_ids']=ids
with self.assertRaises(ValueError):validate_scope(c)
def test_projection_includes_postfit_and_stop_boundary(self):
c=contract();a=projection(1300,c['parts'],60,3600);b=projection(1400,c['parts'],60,3600)
self.assertLess(a,72000);self.assertGreater(b,72000)
def test_real_guard_pass_single_attempt_and_failure(self):
with tempfile.TemporaryDirectory() as tmp:
limits=dict(cpu_seconds=5,wall_seconds=5,rss_bytes=128*2**20,disk_bytes=2**20)
d=Path(tmp)/'pass';g=supervise([sys.executable,'-c','print("synthetic only")'],d,limits)
self.assertEqual(g['status'],'PASS')
with self.assertRaises(FileExistsError):supervise([sys.executable,'-c','pass'],d,limits)
g=supervise([sys.executable,'-c','raise ValueError("synthetic preserved failure")'],Path(tmp)/'failure',limits)
self.assertEqual(g['status'],'FAILED');self.assertGreater(g['cpu_seconds'],0)
if __name__=='__main__':unittest.main()