Publish fixed calibration postfit implementation and pre-score review binding

This commit is contained in:
MeltAstra committed 2026-11-17 20:43:20 +08:00
1 parent d67da6382b
commit 1960762d2d
18 files changed
+70002

No files matched your search

+162
View File
@@ -0,0 +1,162 @@
"""Single continuation of fixed calibration: reuse models, predict, freeze, compare."""
import argparse,fcntl,json,os,resource,signal,sys,time
from pathlib import Path
import numpy as np
from phase2_fixed_io import BASE
from phase2_h1_worker_v2 import checked,sha,save
from phase2_home_freeze_io import verify,freeze
from phase2_gate_outcome_review import validate_review
from phase2_gate_outcome_statistics import two_metrics,summarize
from phase2_b1213_features import cached
from s2_custody_common import prediction_inputs
from r4bc_guard import supervise
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');verify(root,'implementation')
if c['total_cpu_seconds']!=72000 or c['postfit_cpu_seconds']!=3600 or c['new_fits']!=0 or c['candidate_label_reads']!=0:raise PermissionError('Fixed scope')
for p,h in {**c['source_sha256'],**c['code_sha256']}.items():checked(p,h)
prep=read(c['preparation_contract']);comparison=read(c['comparison_contract'])
if comparison['rule']!=c['comparison_rule'] or comparison['bands']!=c['bands']:raise ValueError('Fixed7650 statistics changed')
if len(c['parts'])!=552 or len({r['case'] for r in c['parts']})!=552 or {r['case'] for r in c['parts']}!=set(prep['original_cases']):raise ValueError('Original552 roster')
old=read(checked(comparison['original_prediction_manifest'],comparison['original_prediction_manifest_sha256']))['entries'];by={r['case']:r for r in c['parts']}
if len(old)!=552 or set(by)!={e['case'] for e in old}:raise ValueError('Original prediction roster')
for e in old:
row=by[e['case']];test=[a['fold'] for a in row['assignments'] if a['role']=='test']
if test!=[e['fold']] or row['component_id']!=e['component_id']:raise ValueError('Frozen fold/component identity')
return c,prep,comparison,{e['case']:e for e in old}
def terminal_inputs(root,c,prep):
p=Path(c['preparation_root']);verify(p,'features');done=read(p/'complete.json');cost=read(p/'post-freeze-cost.json')
if done['status']!='FEATURES_COMPLETE_PREDICTIONS_AND_COMPARISON_PENDING' or not done['accounting_complete'] or len(done['records'])!=493 or any(r['guard']['status']!='PASS' for r in done['records']):raise PermissionError('All493 original PASS required')
if {r['index'] for r in done['records']}!=set(range(493)):raise ValueError('Distinct493 terminal jobs')
if not cost['within_cap'] or cost['cumulative_cpu_seconds']<done['cumulative_cpu_seconds']:raise ValueError('Complete original CPU ledger required')
import psutil
for process in psutil.process_iter(['pid','cmdline']):
args=process.info['cmdline'] or []
if any(x.endswith('phase2_gate_outcome_queue.py') for x in args):raise PermissionError('Original feature processes still active')
m=read(p/'features-manifest.json');new=m['recomputed'];exact=m['exact_reuse'];invalid=m['invalid_cases']
if len(new)!=493 or exact!=prep['exact_reuse'] or invalid!=prep['invalid_cases']:raise ValueError('Fixed493/52/7 partition')
expected={item['row']['case']:i for i,item in enumerate(prep['parts'])}
if len({e['case'] for e in new})!=493 or set(expected)!={e['case'] for e in new}:raise ValueError('Recomputation roster')
for e in new:
d=Path(e['path']);r=read(checked(d/'result.json',e['result_sha256']))
if e['index']!=expected[e['case']] or r['case']!=e['case'] or r['output_sha256']!=e['output_sha256']:raise ValueError('Feature result identity')
for n,h in e['output_sha256'].items():checked(d/n,h)
for e in exact:
for path,h in e['source_sha256'].items():checked(path,h)
return dict(prior_cpu_seconds=cost['cumulative_cpu_seconds'],original_complete_sha256=sha(p/'complete.json'),original_cost_sha256=sha(p/'post-freeze-cost.json'),features_manifest_sha256=sha(p/'features-manifest.json'),recomputed=new,exact_reuse=exact,invalid_cases=invalid,terminal_pid_absent=True)
def adopted(root,c):
verify(root,'inputs');a=read(root/'adopted-inputs.json');p=Path(c['preparation_root'])
checked(p/'complete.json',a['original_complete_sha256']);checked(p/'post-freeze-cost.json',a['original_cost_sha256']);checked(p/'features-manifest.json',a['features_manifest_sha256'])
if a['prior_cpu_seconds']!=read(p/'post-freeze-cost.json')['cumulative_cpu_seconds']:raise ValueError('Original cost changed')
return a
def query_identity(q,z):
for name in ['raw_ids','counts','coordinates_over_Rg','near_wall']:
if not np.array_equal(q[name],z[name]):raise ValueError('Frozen query identity: '+name)
def predict_arrays(A,G,features,extra,raw,q,t_set):
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 outside full-node array')
if features.shape!=(len(raw),19) or extra.shape!=(len(raw),2) or not np.isfinite(features).all() or np.isinf(extra).any():raise ValueError('Invalid19+2 features')
if not np.isfinite(t_set) or t_set<=0:raise ValueError('Original clock')
x=features[ix].astype(np.float32);g=np.column_stack([features[ix],extra[ix]]).astype(np.float32)
out=dict(A=np.asarray(A.predict(x),np.float64)*t_set,G=np.asarray(G.predict(g),np.float64)*t_set)
if any(v.shape!=(len(ix),) or not np.isfinite(v).all() for v in out.values()):raise ValueError('Nonfinite prediction; no auto exclusion')
return out
def predict(root,fold):
import joblib,xgboost as xgb
from threadpoolctl import threadpool_limits
c,prep,cmp,old=config(root);a=adopted(root,c);by={e['case']:e for e in a['recomputed']};spec=cmp['models'][fold]
if spec['fold']!=fold or xgb.__version__!='2.1.4' or np.__version__!='1.26.4':raise ValueError('Model/library identity')
A=joblib.load(checked(spec['A']['path'],spec['A']['sha256']));G=xgb.XGBRegressor();G.load_model(checked(spec['G']['path'],spec['G']['sha256']));A.set_params(n_jobs=1);G.set_params(n_jobs=1)
if A.get_booster().num_features()!=19 or G.get_booster().num_features()!=21:raise ValueError('Model feature widths')
dest=root/'predict'/str(fold);dest.mkdir(parents=True,exist_ok=False);entries=[]
with threadpool_limits(1):
for row in c['parts']:
case=row['case'];base=old[case]
if base['fold']!=fold or case not in by:continue
e=by[case];path=Path(e['path']);q=prediction_inputs(row);raw=cached(row,'raw_ids')
with np.load(checked(base['path'],base['sha256']),allow_pickle=False) as z:query_identity(q,z)
f=np.load(checked(path/'features.npy',e['output_sha256']['features.npy']),allow_pickle=False);g=np.load(checked(path/'G_extra.npy',e['output_sha256']['G_extra.npy']),allow_pickle=False)
values=predict_arrays(A,G,f,g,raw,q,row['preparation']['t_set']);out=dest/(case+'.npz');np.savez_compressed(out,**values,**{n:q[n] for n in ['raw_ids','counts','coordinates_over_Rg','near_wall']})
entries.append(dict(case=case,component_id=row['component_id'],fold=fold,path=str(out),sha256=sha(out),original=base,exact_reuse=False,negative_predictions={k:int(np.sum(v<0)) for k,v in values.items()}));save(dest/'progress.json',dict(parts=len(entries),labels_read=False))
save(dest/'manifest.json',dict(entries=entries,labels_read=False,new_fits=0))
def freeze_predictions(root,c,cmp,old,a):
entries=[]
for f in range(5):entries.extend(read(root/'predict'/str(f)/'manifest.json')['entries'])
if len(entries)!=493 or {e['case'] for e in entries}!={e['case'] for e in a['recomputed']}:raise ValueError('All493 new predictions required')
for e in a['exact_reuse']:
base=old[e['case']]
if e['prediction']!=base:raise ValueError('Exact52 original prediction identity')
entries.append(dict(case=e['case'],component_id=base['component_id'],fold=base['fold'],path=base['path'],sha256=base['sha256'],original=base,exact_reuse=True))
if len({e['case'] for e in entries})!=545:raise ValueError('Distinct545 predictions')
for e in entries:checked(e['path'],e['sha256'])
save(root/'predictions-manifest.json',dict(entries=entries,invalid_cases=a['invalid_cases'],eligible_denominator=552,new_parts=493,reused_parts=52,labels_read=False))
freeze(root,'predictions',[root/'contract.json',root/'adopted-inputs.json',root/'predictions-manifest.json',*[Path(p) for p in c['code_sha256']]])
def score(root):
c,prep,cmp,old=config(root);adopted(root,c);verify(root,'predictions');validate_review(root) # Before ANY target values or comparison.
dest=root/'score';dest.mkdir(exist_ok=False);manifest=read(root/'predictions-manifest.json');entries={e['case']:e for e in manifest['entries']};invalid=set(manifest['invalid_cases']);prior={r['case']:r for r in read(checked(c['original_score'],c['source_sha256'][c['original_score']]))['rows']}
if len(entries)!=545 or invalid!=set(prep['invalid_cases']) or set(entries)&invalid or set(entries)|invalid!={r['case'] for r in c['parts']}:raise ValueError('Complete eligibility roster')
rows=[];access=[];save(dest/'review-consumed.json',dict(verdict='PASS',review_sha256=sha(root/'review.json'),unix=time.time(),before_target_access=True))
for row in c['parts']:
case=row['case'];base=old[case];prior_row=prior[case]
if prior_row['fold']!=base['fold'] or prior_row['component_id']!=row['component_id']:raise ValueError('Original score roles')
reference=dict(A={k:prior_row['A'][k] for k in ['relative_l2','last_location']},G={k:prior_row['new'][k] for k in ['relative_l2','last_location']})
out=dict(case=case,component_id=row['component_id'],fold=base['fold'],LOG_gate=reference,label_gate=None,eligibility='INVALID_GATE' if case in invalid else 'VALID')
if case not in invalid:
e=entries[case]
if e['original']!=base or e['component_id']!=row['component_id'] or e['fold']!=base['fold']:raise ValueError('Prediction fold/component identity')
if e['exact_reuse']:
checked(e['path'],e['sha256']);out['label_gate']=reference;out['reuse']='Exact seed set, original prediction and metrics by hash'
else:
access.append(dict(case=case,target_sha256=row['v5_cache']['output_sha256']['seconds.npy'],existing_old552_cache=True));save(dest/'target-access.json',access)
truth=cached(row,'seconds');raw=cached(row,'raw_ids')
with np.load(checked(e['path'],e['sha256']),allow_pickle=False) as z,np.load(checked(base['path'],base['sha256']),allow_pickle=False) as zz:
query_identity(z,zz);ix=np.searchsorted(raw,z['raw_ids'])
if np.any(ix>=len(raw)) or not np.array_equal(raw[ix],z['raw_ids']):raise ValueError('Score query IDs')
out['label_gate']={arm:two_metrics(z[arm],truth[ix],z) for arm in ['A','G']}
rows.append(out);save(dest/'progress.json',dict(parts=len(rows)))
result=summarize(rows,{r['component_id'] for r in c['parts']});save(dest/'result.json',dict(status='COMPLETE',**result,rows=rows,eligibility_denominator=552,invalid_gate_parts=sorted(invalid),eligibility_loss=7/552,exact_seed_prediction_reuse=52,new_prediction_parts=493,original_exact_set_FAIL_preserved=True,candidate_label_reads=0,new_decodes=0,new_fits=0,comparison_rule=cmp['rule'],review_sha256=sha(root/'review.json')))
def remaining_cap(prior,post_spent,requested):
remaining=min(3600-post_spent,72000-prior-post_spent)-120
if requested>remaining:raise RuntimeError('Insufficient shared budget for fixed job; no retry/extension')
return requested
def run(root):
start=time.process_time();u0=resource.getrusage(resource.RUSAGE_CHILDREN);c,prep,cmp,old=config(root);validate_review(root);lock=(root/'run.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if (root/'started.json').exists():raise FileExistsError('Single postfit launch; no restart')
os.sched_setaffinity(0,[8]);save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),phase='VERIFY_ORIGINAL_TERMINAL',new_fits=0,candidate_label_reads=0));prior=None;records=[];charged=0.;requested=[]
def post_cost():
u=resource.getrusage(resource.RUSAGE_CHILDREN);return c['setup_cpu_seconds']+time.process_time()-start+max(charged,u.ru_utime+u.ru_stime-u0.ru_utime-u0.ru_stime)
def job(mode,index,cap):
nonlocal charged
if requested or disk_usage(root)>c['disk_bytes']:raise RuntimeError('Signal/disk stop')
cap=remaining_cap(prior,post_cost(),cap);d=root/'guards'/f'{mode}-{index}'
g=supervise([sys.executable,'tools/phase2_gate_outcome_postfit.py',mode,str(root),str(index)],d,dict(cpu_seconds=cap,wall_seconds=cap+180,rss_bytes=4*2**30,disk_bytes=c['disk_bytes']))
charged+=g['cpu_seconds'];records.append(dict(mode=mode,index=index,guard=g));save(root/'live-progress.json',dict(stage=mode,records=records,prior_cpu_once=prior,postfit_cpu_seconds=post_cost(),cumulative_cpu_seconds=prior+post_cost()))
if g['status']!='PASS' or post_cost()>3600 or prior+post_cost()>72000:raise RuntimeError('Postfit guard/budget stop')
old_handlers={s:signal.signal(s,lambda signum,frame:requested.append(signum)) for s in [signal.SIGTERM,signal.SIGINT]}
try:
a=terminal_inputs(root,c,prep);prior=a['prior_cpu_seconds'];save(root/'adopted-inputs.json',a);freeze(root,'inputs',[root/'contract.json',root/'adopted-inputs.json',Path(c['preparation_root'])/'complete.json',Path(c['preparation_root'])/'post-freeze-cost.json',Path(c['preparation_root'])/'features-manifest.json'])
for f in range(5):job('predict',f,300)
freeze_predictions(root,c,cmp,old,a);job('score',0,600)
save(root/'complete.json',dict(status='COMPLETE',decision=read(root/'score/result.json')['decision'],records=records,prior_cpu_once=prior,postfit_cpu_seconds=post_cost(),cumulative_cpu_seconds=prior+post_cost(),accounting_complete=True,new_fits=0,new_decodes=0,retry=False))
freeze(root,'terminal',[root/'contract.json',root/'complete.json',root/'score/result.json',root/'review.json',root/'predictions-manifest.json'])
save(root/'post-terminal-cost.json',dict(cumulative_cpu_seconds=prior+post_cost(),postfit_cpu_seconds=post_cost(),within_cap=prior+post_cost()<=72000 and post_cost()<=3600))
except BaseException as exc:
save(root/'complete.json',dict(status='STOPPED',reason=type(exc).__name__+': '+str(exc),records=records,prior_cpu_once=prior,postfit_cpu_seconds=post_cost(),cumulative_cpu_seconds=prior+post_cost() if prior is not None else None,accounting_complete=prior is not None,retry=False));raise
finally:
for s,h in old_handlers.items():signal.signal(s,h)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('action',choices=['run','predict','score']);p.add_argument('root',type=Path);p.add_argument('index',nargs='?',type=int,default=0);a=p.parse_args()
if a.action=='run':run(a.root)
elif a.action=='predict':predict(a.root,a.index)
else:score(a.root)
+20
View File
@@ -0,0 +1,20 @@
"""Exact semantic PASS and immutable source/contract identity before custody."""
import json
from pathlib import Path
from phase2_h1_worker_v2 import sha,checked
from phase2_home_freeze_io import verify
def read(p):return json.loads(Path(p).read_text())
def validate_review(root):
root=Path(root);c=read(root/'contract.json');proof=verify(root,'implementation');binding=read(root/'expected-review-binding.json');review=read(root/'review.json')
expected=dict(reviewed_commit=proof['commit'],contract_sha256=sha(root/'contract.json'),implementation_proof_sha256=sha(root/'implementation-git-freeze.json'),comparison_contract_sha256=c['comparison_contract_sha256'],code_sha256=c['code_sha256'])
if binding!=expected:raise PermissionError('Review binding differs from implementation')
if review.get('verdict')!='PASS':raise PermissionError('Actual exact PASS required')
for name,value in expected.items():
if review.get(name)!=value:raise PermissionError('Review identity mismatch: '+name)
checked(c['comparison_contract'],expected['comparison_contract_sha256'])
for p,h in expected['code_sha256'].items():checked(p,h)
frozen=verify(root,'implementation-review')
for p in [root/'review.json',root/'expected-review-binding.json',root/'contract.json']:
if frozen['files'].get(str(p.resolve()))!=sha(p):raise PermissionError('Review freeze does not include exact required file')
return review
+34
View File
@@ -0,0 +1,34 @@
"""Fixed7650 paired component equivalence; array/record only, no data I/O."""
from collections import defaultdict
import numpy as np
from r4bc_common import paired_difference
from s2_models.objectives import relative_l2
from s2_custody_statistics import last_location
METRICS={'relative_l2':.001,'last_location':.010}
def two_metrics(pred,truth,query):
p=np.asarray(pred);t=np.asarray(truth)
if p.shape!=t.shape or p.ndim!=1 or not len(p) or not np.isfinite(p).all() or not np.isfinite(t).all():raise ValueError('Invalid metric arrays')
return dict(relative_l2=relative_l2(p,t,query['counts'],np.ones(len(t),bool)),last_location=dict(value=last_location(t,p,query['raw_ids'],query['coordinates_over_Rg']),reason=None))
def summarize(rows,original_components):
if len({r['case'] for r in rows})!=len(rows):raise ValueError('Duplicate part')
result={};all_components=set(original_components)
for arm in ['A','G']:
result[arm]={}
for metric,band in METRICS.items():
paired=defaultdict(list);excluded=[]
for r in rows:
if r['component_id'] not in all_components:raise ValueError('Unknown component')
new=None if r['label_gate'] is None else r['label_gate'][arm][metric]['value']
old=None if r['LOG_gate'] is None else r['LOG_gate'][arm][metric]['value']
if new is None or old is None:excluded.append(r['case']);continue
if not np.isfinite([new,old]).all():raise ValueError('Nonfinite metric must not be silently dropped')
paired[r['component_id']].append((float(new),float(old)))
means={g:np.mean(v,axis=0) for g,v in paired.items()}
new={g:float(v[0]) for g,v in means.items()};old={g:float(v[1]) for g,v in means.items()}
ci=paired_difference(new,old,seed=2026111408,replicates=2000)
passes=ci['low'] is not None and ci['high'] is not None and ci['low']>=-band and ci['high']<=band
result[arm][metric]=dict(label_minus_LOG=ci,label_mean=float(np.mean(list(new.values()))) if new else None,LOG_mean=float(np.mean(list(old.values()))) if old else None,band=[-band,band],passed=passes,paired_parts=sum(map(len,paired.values())),excluded_parts=excluded,component_part_counts={g:len(v) for g,v in paired.items()},excluded_components=sorted(all_components-set(paired)),excluded_component_count=len(all_components-set(paired)))
passed=all(v['passed'] for arm in result.values() for v in arm.values())
return dict(decision='PASS_OUTCOME_EQUIVALENCE' if passed else 'FAIL_OUTCOME_EQUIVALENCE',accepted_for_v2=passed,comparisons=result,interpretation='Acceptance within fixed bands; a failed gate is not proof of non-equivalence or failure of every gate-dependent method')
+29
View File
@@ -0,0 +1,29 @@
"""Local immutable barriers for explicitly approved /home run roots."""
import fcntl,json,shutil,subprocess,hashlib
from pathlib import Path
from phase2_h1_worker_v2 import sha,checked,save
from phase2_local_freeze_io import STORE,LOCK,BRANCH,BASE
HOME_RUNS=Path('/home/frank14f/MeltMind-runs')
def key(path):
p=Path(path).resolve()
if p.is_relative_to(HOME_RUNS):return 'home-runs/'+str(p.relative_to(HOME_RUNS))
return str(p.relative_to(BASE))
def freeze(root,name,files):
with LOCK.open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX)
def git(*a):return subprocess.check_output(['git','-C',str(STORE),'-c','gc.auto=0',*a],text=True).strip()
if git('branch','--show-current')!=BRANCH or git('status','--porcelain'):raise RuntimeError('Local writer not clean')
hashes={};paths={}
for f in files:
f=Path(f).resolve();k=key(f);p=STORE/k;p.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(f,p);hashes[str(f)]=sha(f);paths[str(f)]=k
subprocess.run(['git','-C',str(STORE),'add','--',*paths.values()],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','Immutable home run '+root.name+' '+name],check=True)
commit=git('rev-parse','HEAD')
for p,h in hashes.items():
if hashlib.sha256(subprocess.check_output(['git','-C',str(STORE),'show',commit+':'+paths[p]])).hexdigest()!=h:raise ValueError('Git content mismatch')
save(root/(name+'-git-freeze.json'),dict(commit=commit,files=hashes,git_paths=paths,remote_published=False,local_repository=str(STORE)))
save(root/(name+'-authorization.json'),dict(contract_sha256=sha(root/'contract.json'),proof_sha256=sha(root/(name+'-git-freeze.json'))))
def verify(root,name):
a=json.loads((root/(name+'-authorization.json')).read_text());checked(root/'contract.json',a['contract_sha256']);p=checked(root/(name+'-git-freeze.json'),a['proof_sha256']);d=json.loads(p.read_text())
for f,h in d['files'].items():checked(f,h)
return d
@@ -0,0 +1,30 @@
"""Prepare only; never launches model prediction, score or a waiter."""
import json,time
from pathlib import Path
from phase2_fixed_io import BASE
from phase2_h1_worker_v2 import checked,sha,save
from phase2_home_freeze_io import freeze,verify
from phase2_gate_outcome_postfit import config
def read(p):return json.loads(Path(p).read_text())
def main():
root=Path('/home/frank14f/MeltMind-runs/phase2-gate-outcome-v2-postfit-2026-11-17')
if root.exists():raise FileExistsError('Existing postfit root: inspect, do not duplicate')
prep_root=Path('/home/frank14f/MeltMind-runs/phase2-gate-outcome-calibration-v2-2026-11-17');prep=read(prep_root/'contract.json');verify(prep_root,'launch');verify(prep_root,'comparison-contract');cmp=read(prep_root/'comparison-contract.json');groot=BASE/'artifacts/phase2-b13-e1b-2026-11-17';science=read(groot/'contract.json')
assert sha(prep_root/'contract.json')==cmp['preparation_contract_sha256'];assert prep['total_cpu_seconds']==72000 and cmp['rule']['approval']=='1794917650.044649'
sources={str(p):sha(p) for p in [prep_root/'contract.json',prep_root/'comparison-contract.json',groot/'contract.json',groot/'predictions-manifest.json',groot/'score/result.json']}
for m in cmp['models']:
for arm in ['A','G']:sources[m[arm]['path']]=m[arm]['sha256']
for p,h in sources.items():checked(p,h)
codes={str(BASE/p):h for p,h in prep['code_sha256'].items()}
for p in ['tools/phase2_gate_outcome_statistics.py','tools/phase2_gate_outcome_review.py','tools/phase2_gate_outcome_postfit.py','tools/prepare_phase2_gate_outcome_postfit.py','tools/test_phase2_gate_outcome_postfit.py','docs/phase2-gate-outcome-v2-postfit-2026-11-17.md']:
codes[str(BASE/p)]=sha(BASE/p)
c=dict(version='gate-outcome-v2-postfit-v1',approval='1794916421.489089',comparison_approval='1794917650.044649',total_cpu_seconds=72000,postfit_cpu_seconds=3600,setup_cpu_seconds=120,worker_cpu=8,disk_bytes=3*2**30,new_fits=0,candidate_label_reads=0,preparation_root=str(prep_root),preparation_contract=str(prep_root/'contract.json'),comparison_contract=str(prep_root/'comparison-contract.json'),comparison_contract_sha256=sha(prep_root/'comparison-contract.json'),comparison_rule=cmp['rule'],bands=cmp['bands'],parts=science['parts'],original_score=str(groot/'score/result.json'),source_sha256=sources,code_sha256=codes,new_prediction_parts=493,exact_reuse_parts=52,invalid_gate_parts=7,full_original_terminal_required=True,predictions_freeze_before_score=True,actual_semantic_PASS_required=True,no_retry=True)
root.mkdir();save(root/'contract.json',c)
save(root/'acceptance.json',dict(status='PASS',tests=18,elapsed_seconds=1.606,command='python -m unittest tools.test_phase2_gate_outcome_postfit',scope='8 metric/paired grouping tests,4 prediction/budget/terminal tests,6 actual file/Git semantic review tests; no validator or freeze mock, temporary path constants only',test_source_sha256=sha(BASE/'tools/test_phase2_gate_outcome_postfit.py'),new_actual_predictions=0,new_comparisons=0,setup_cpu_charge=120,unix=time.time()))
save(root/'preparation-audit.json',dict(status='PREPARED_NOT_LAUNCHED',original_feature_pid=666520,original_feature_pins_verified=True,comparison_rule_fixed=True,models_hash_checked=10,no_labels_opened=True,no_prediction_or_comparison=True,no_new_waiter=True,unix=time.time()))
freeze(root,'implementation',[root/'contract.json',root/'acceptance.json',root/'preparation-audit.json',*[Path(p) for p in codes],prep_root/'comparison-contract.json'])
proof=verify(root,'implementation');binding=dict(reviewed_commit=proof['commit'],contract_sha256=sha(root/'contract.json'),implementation_proof_sha256=sha(root/'implementation-git-freeze.json'),comparison_contract_sha256=c['comparison_contract_sha256'],code_sha256=codes)
save(root/'expected-review-binding.json',binding);freeze(root,'review-binding',[root/'contract.json',root/'expected-review-binding.json',root/'implementation-git-freeze.json',root/'implementation-authorization.json']);config(root)
print(json.dumps(dict(root=str(root),implementation_commit=proof['commit'],contract_sha256=sha(root/'contract.json'),implementation_proof_sha256=sha(root/'implementation-git-freeze.json'),binding_sha256=sha(root/'expected-review-binding.json'),actual_PASS_pending=True,no_launch=True)))
if __name__=='__main__':main()
+94
View File
@@ -0,0 +1,94 @@
import copy,json,tempfile,unittest,subprocess
from pathlib import Path
from unittest.mock import patch
import numpy as np
import phase2_home_freeze_io as fio
from phase2_h1_worker_v2 import sha
from phase2_gate_outcome_review import validate_review
from phase2_gate_outcome_statistics import summarize,two_metrics
from phase2_gate_outcome_postfit import predict_arrays,query_identity,remaining_cap,terminal_inputs
from s2_custody_statistics import part_metrics
def metric(v):return dict(relative_l2=dict(value=v),last_location=dict(value=v))
def row(case,component,new,old):
return dict(case=case,component_id=component,label_gate=None if new is None else {a:metric(new) for a in ['A','G']},LOG_gate=None if old is None else {a:metric(old) for a in ['A','G']})
class Statistics(unittest.TestCase):
def test_partial_component_kept_only_empty_component_drops(self):
d=summarize([row('a','x',1,1),row('b','x',None,1),row('c','y',None,1)],['x','y']);v=d['comparisons']['A']['relative_l2']
self.assertEqual(v['component_part_counts'],{'x':1});self.assertEqual(v['excluded_components'],['y']);self.assertEqual(v['paired_parts'],1);self.assertEqual(d['decision'],'PASS_OUTCOME_EQUIVALENCE')
def test_paired_parts_not_independent_arm_averages(self):
d=summarize([row('a','x',1,1),row('b','x',10,None),row('c','x',None,30)],['x']);v=d['comparisons']['A']['relative_l2'];self.assertEqual(v['label_mean'],1);self.assertEqual(v['LOG_mean'],1)
def test_equal_component_not_equal_part_weighting(self):
d=summarize([row('a','x',2,1),row('b','x',2,1),row('c','y',1,1)],['x','y']);self.assertEqual(d['comparisons']['G']['relative_l2']['label_minus_LOG']['value'],.5)
def test_both_models_both_metrics_required(self):
r=row('a','x',0,0);r['label_gate']['G']['last_location']['value']=.011;d=summarize([r],['x']);self.assertFalse(d['accepted_for_v2']);self.assertTrue(d['comparisons']['A']['last_location']['passed'])
def test_closed_band_boundaries_and_zero_support(self):
r=row('a','x',.001,0);d=summarize([r],['x']);self.assertTrue(d['accepted_for_v2']);self.assertFalse(summarize([row('a','x',None,1)],['x'])['accepted_for_v2'])
def test_duplicates_and_nonfinite_rejected(self):
r=row('a','x',0,0)
with self.assertRaises(ValueError):summarize([r,r],['x'])
with self.assertRaises(ValueError):summarize([row('a','x',float('nan'),0)],['x'])
def test_metrics_match_original_with_weighted_counts_and_raw_ties(self):
p=np.array([2.,2.,1.]);t=np.array([1.,3.,3.]);q=dict(counts=np.array([1,3,2]),raw_ids=np.array([5,2,8]),coordinates_over_Rg=np.eye(3),near_wall=np.array([True,False,True]));a=two_metrics(p,t,q);b=part_metrics(p,t,q['counts'],q['near_wall'],q['raw_ids'],q['coordinates_over_Rg'],1)
self.assertEqual(a['relative_l2'],b['relative_l2']);self.assertEqual(a['last_location'],b['last_location'])
def test_zero_truth_denominator_retains_undefined(self):
q=dict(counts=np.ones(2),raw_ids=np.arange(2),coordinates_over_Rg=np.zeros((2,3)));d=two_metrics(np.ones(2),np.zeros(2),q);self.assertIsNone(d['relative_l2']['value'])
class PredictAndBudget(unittest.TestCase):
def test_native_nan_query_order_and_seconds(self):
class Model:
def __init__(self,n):self.n=n
def predict(self,x):
assert x.dtype==np.float32 and x.shape[1]==self.n
if self.n==21:assert np.isnan(x[:,-2:]).all()
return x[:,0]+self.n
f=np.arange(57,dtype=float).reshape(3,19);q={'raw_ids':np.array([2,9])};out=predict_arrays(Model(19),Model(21),f,np.full((3,2),np.nan),np.array([2,5,9]),q,.4)
np.testing.assert_allclose(out['A'],np.array([19,57])*.4);np.testing.assert_allclose(out['G'],np.array([21,59])*.4)
def test_query_mismatch_fails_before_predict(self):
with self.assertRaises(ValueError):predict_arrays(None,None,np.zeros((2,19)),np.zeros((2,2)),np.array([1,2]),{'raw_ids':np.array([3])},1)
a=dict(raw_ids=np.arange(2),counts=np.ones(2),coordinates_over_Rg=np.zeros((2,3)),near_wall=np.zeros(2));b=dict(a,counts=np.array([1,2]))
with self.assertRaises(ValueError):query_identity(a,b)
def test_shared_cost_charged_once_and_both_caps_enforced(self):
self.assertEqual(remaining_cap(68000,120,600),600)
with self.assertRaises(RuntimeError):remaining_cap(71600,120,300)
with self.assertRaises(RuntimeError):remaining_cap(10000,3400,300)
def test_missing_feature_freeze_rejects_adoption(self):
with tempfile.TemporaryDirectory() as p:
with self.assertRaises(FileNotFoundError):terminal_inputs(Path(p),{'preparation_root':p},{})
class SemanticReview(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();p=Path(self.tmp.name);self.base=p/'base';self.home=p/'runs';self.store=p/'store'
for d in [self.base,self.home,self.store]:d.mkdir()
subprocess.run(['git','init','-q','-b','codex/test',str(self.store)],check=True)
self.patches=[patch.object(fio,k,v) for k,v in dict(BASE=self.base,HOME_RUNS=self.home,STORE=self.store,LOCK=p/'lock',BRANCH='codex/test').items()]
for x in self.patches:x.start()
self.root=self.home/'postfit';self.root.mkdir();self.code=self.base/'code.py';self.code.write_text('fixed code');self.comparison=self.base/'comparison.json';self.comparison.write_text('{"band":0.001}')
self.c=dict(comparison_contract=str(self.comparison),comparison_contract_sha256=sha(self.comparison),code_sha256={str(self.code):sha(self.code)})
(self.root/'contract.json').write_text(json.dumps(self.c));fio.freeze(self.root,'implementation',[self.root/'contract.json',self.code,self.comparison]);proof=fio.verify(self.root,'implementation')
self.binding=dict(reviewed_commit=proof['commit'],contract_sha256=sha(self.root/'contract.json'),implementation_proof_sha256=sha(self.root/'implementation-git-freeze.json'),comparison_contract_sha256=sha(self.comparison),code_sha256=self.c['code_sha256'])
(self.root/'expected-review-binding.json').write_text(json.dumps(self.binding));self.good=dict(verdict='PASS',**self.binding)
def tearDown(self):
for x in self.patches:x.stop()
self.tmp.cleanup()
def receipt(self,d,include=True):
(self.root/'review.json').write_text(json.dumps(d));files=[self.root/'contract.json']
if include:files.extend([self.root/'review.json',self.root/'expected-review-binding.json'])
fio.freeze(self.root,'implementation-review',files)
def test_actual_frozen_pass(self):self.receipt(self.good);self.assertEqual(validate_review(self.root)['verdict'],'PASS')
def test_fail_missing_and_unrelated_receipts(self):
for v in [dict(self.good,verdict='FAIL'),self.binding,{'unrelated':'review'}]:
self.receipt(v)
with self.assertRaises(PermissionError):validate_review(self.root)
def test_wrong_exact_identities(self):
for k in ['reviewed_commit','contract_sha256','implementation_proof_sha256','comparison_contract_sha256','code_sha256']:
v=dict(self.good);v[k]={} if k=='code_sha256' else 'wrong';self.receipt(v)
with self.assertRaises(PermissionError):validate_review(self.root)
def test_review_omitted_from_freeze(self):
self.receipt(self.good,False)
with self.assertRaises(PermissionError):validate_review(self.root)
def test_changed_source_rejected(self):
self.receipt(self.good);self.code.write_text('changed')
with self.assertRaises(ValueError):validate_review(self.root)
def test_changed_comparison_rejected(self):
self.receipt(self.good);self.comparison.write_text('changed')
with self.assertRaises(ValueError):validate_review(self.root)
if __name__=='__main__':unittest.main()