Archived
Preserve R4 terminal evidence and prepare approved single1470 recovery with paired scoring
This commit is contained in:
1 parent
3914fc193f
commit
3b14c562f1
4331 files changed
+214418
No files matched your search
@@ -0,0 +1,104 @@
|
||||
"""Approved post-stop scoring: all arms share complete canonical components."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
import numpy as np
|
||||
from gre24_prepare_v2 import sha
|
||||
from r4a_part import contract, exact
|
||||
from s2_custody_common import checked, prediction_inputs
|
||||
from s2_custody_statistics import part_metrics, contrast
|
||||
from s2_recovery_supervisor import save
|
||||
|
||||
ARMS=('EIK','GRAPH','B0_S2')
|
||||
METRICS=('relative_l2','kendall_tau_b','last_location','near_wall')
|
||||
|
||||
|
||||
def summaries(rows, roster, pass_ids):
|
||||
by={r['case']:r for r in rows};groups={}
|
||||
for r in roster:groups.setdefault(r['component_id'],[]).append(r)
|
||||
failed_components={k:dict(parts=[{'case':r['case'],'nodes':r['nodes'],'prediction_pass':r['case'] in pass_ids} for r in members],
|
||||
nodes=sum(r['nodes'] for r in members))
|
||||
for k,members in groups.items() if any(r['case'] not in pass_ids for r in members)}
|
||||
report={}
|
||||
for metric in METRICS:
|
||||
values={a:{} for a in ARMS};undefined={}
|
||||
for group,members in sorted(groups.items()):
|
||||
if group in failed_components:continue
|
||||
absent=[]
|
||||
for member in members:
|
||||
for arm in ARMS:
|
||||
v=by.get(member['case'],{}).get('metrics',{}).get(arm,{}).get(metric,{}).get('value')
|
||||
if v is None or not np.isfinite(v):absent.append(dict(case=member['case'],arm=arm,metric=metric))
|
||||
if absent:undefined[group]=absent;continue
|
||||
for arm in ARMS:
|
||||
values[arm][group]=float(np.mean([by[r['case']]['metrics'][arm][metric]['value'] for r in members]))
|
||||
component_ids=sorted(values['EIK'])
|
||||
item=dict(component_ids=component_ids,components=len(component_ids),
|
||||
parts=sum(len(groups[g]) for g in component_ids),nodes=sum(sum(r['nodes'] for r in groups[g]) for g in component_ids),
|
||||
means={a:float(np.mean(list(v.values()))) if v else None for a,v in values.items()},
|
||||
component_values=values,undefined_components_excluded_from_all_arms=undefined)
|
||||
if metric=='relative_l2':
|
||||
item['contrasts']={}
|
||||
for candidate in ['GRAPH','B0_S2']:
|
||||
delta=contrast(values['EIK'],values[candidate],replicates=2000,seed=2026111408)
|
||||
delta.pop('region',None)
|
||||
delta.update(formula='1 - E_'+candidate+'/E_EIK',reference='EIK',candidate=candidate,
|
||||
interpretation='Positive means candidate has lower error than EIK; descriptive percentile interval, no gate')
|
||||
item['contrasts'][candidate]=delta
|
||||
report[metric]=item
|
||||
return report,failed_components
|
||||
|
||||
|
||||
def score(root):
|
||||
c=contract(root);eng=json.loads((root/'continuation-contract.json').read_text())
|
||||
for p,h in eng['code_sha256'].items():checked(p,h)
|
||||
frozen=root/'pass-predictions-freeze.json';freeze=json.loads(frozen.read_text())
|
||||
if freeze['contract_sha256']!=sha(root/'contract.json') or freeze['continuation_contract_sha256']!=sha(root/'continuation-contract.json'):
|
||||
raise ValueError('Freeze/contract mismatch')
|
||||
requested={r['case'] for r in c['parts']};passed=set(freeze['parts']);failed={r['case'] for r in freeze['canonical_failures']}
|
||||
if passed&failed or passed|failed!=requested:raise ValueError('Canonical coverage mismatch')
|
||||
for entry in freeze['parts'].values():
|
||||
checked(entry['result'],entry['result_sha256']);checked(entry['predictions'],entry['predictions_sha256'])
|
||||
# Labels are opened only after every PASS prediction hash has been verified.
|
||||
labels={r['case']:r for r in json.loads(Path(c['label_index']).read_text())}
|
||||
historical={r['case']:r for r in json.loads(Path(c['historical_scores']).read_text()) if r['arm']=='B0'}
|
||||
out=root/'postfit';out.mkdir(exist_ok=True);start=time.process_time();rows=[]
|
||||
for row in c['parts']:
|
||||
case=row['case']
|
||||
if case not in passed:continue
|
||||
q=prediction_inputs(row);label=labels[case]
|
||||
fold=next(a['fold'] for a in row['assignments'] if a['role']=='test')
|
||||
if label['fold']!=fold:raise ValueError('Cached fold mismatch')
|
||||
with np.load(checked(label['path'],label['sha256']),allow_pickle=False) as z:
|
||||
exact(z['raw_ids'],q['raw_ids'],'target/query IDs');exact(z['counts'],q['counts'],'target/query counts');truth=z['seconds'].copy()
|
||||
if not np.isfinite(truth).all() or np.any(truth<0):raise ValueError('Invalid cached truth')
|
||||
entry=freeze['parts'][case]
|
||||
with np.load(checked(entry['predictions'],entry['predictions_sha256']),allow_pickle=False) as z:
|
||||
exact(z['raw_ids'],q['raw_ids'],'prediction IDs');exact(z['counts'],q['counts'],'prediction multiplicity')
|
||||
metrics={arm:part_metrics(z[array],truth,q['counts'],q['near_wall'],q['raw_ids'],q['coordinates_over_Rg'],int(case.split('_')[0]))
|
||||
for arm,array in [('EIK','F'),('GRAPH','G')]}
|
||||
b0=historical.get(case)
|
||||
if b0 is None:raise ValueError('Missing historical B0 row')
|
||||
metrics['B0_S2']={metric:b0[metric] for metric in METRICS}
|
||||
rows.append(dict(case=case,component_id=row['component_id'],fold=fold,metrics=metrics,
|
||||
cached_label_sha256=label['sha256'],prediction_sha256=entry['predictions_sha256']))
|
||||
save(out/'progress.json',dict(stage='CACHE_ONLY_SCORING',parts=len(rows),worker_cpu_seconds=time.process_time()-start))
|
||||
report,excluded=summaries(rows,c['parts'],passed)
|
||||
save(out/'part-scores.json',dict(rows=rows,predictions_freeze_sha256=sha(frozen)))
|
||||
save(out/'score-summary.json',dict(status='SCORED_DESCRIPTIVE_COMPLETE_COMPONENTS',authorizing_ruling='1794830693.515879',
|
||||
requested_parts=len(requested),requested_components=len({r['component_id'] for r in c['parts']}),
|
||||
pass_prediction_parts=len(passed),canonical_failures=freeze['canonical_failures'],excluded_components=excluded,
|
||||
summary=report,delta_direction='EIK reference; 1 - GRAPH/EIK and 1 - B0_S2/EIK',
|
||||
superseded_draft_direction='1 - EIK/GRAPH was not scored; changed by Claude1794830693',
|
||||
historical_B0_interpretation='whole distance construction; not pure propagation attribution',
|
||||
new_decodes=0,new_fits=0,worker_cpu_seconds=time.process_time()-start,
|
||||
predictions_freeze_sha256=sha(frozen),part_scores_sha256=sha(out/'part-scores.json'),
|
||||
limitations=['Fixed v5 geometry and S2 query domain, not fresh blind testing',
|
||||
'Failed components excluded identically from every arm; no trimmed membership',
|
||||
'Component-only descriptive bootstrap; no CI or 10% gate',
|
||||
'Historical B0 differs in full distance construction, not just propagation']))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('root',type=Path);a=p.parse_args();score(a.root)
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Single labelled1470 recovery, then immutable PASS freeze and approved scoring."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from gre24_prepare_v2 import sha
|
||||
from r4a_part import contract
|
||||
from run_r4a import kill_guard_worker
|
||||
from s2_custody_common import checked
|
||||
from s2_recovery_supervisor import save,supervise
|
||||
from s2_recovery_monitoring import disk_usage
|
||||
|
||||
CASE='00001470_a45f6c99e2154f3b94955175_step_054'
|
||||
|
||||
|
||||
def verify_scope(c,e,prior):
|
||||
if e['recovery_indices']!=[568] or c['parts'][568]['case']!=CASE:raise ValueError('Only one1470 recovery permitted')
|
||||
if prior['never_attempted'] or prior['missing_receipt_indices'] or not prior['accounting_complete']:raise ValueError('Original terminal differs')
|
||||
records={r['index']:r for r in prior['records']};r=records[568]
|
||||
if r['worker']['returncode']!=-9 or r['worker']['stop_reason'] is not None:raise ValueError('1470 original evidence differs')
|
||||
if e['prior_charged_worker_cpu_seconds']!=prior['charged_worker_cpu_seconds']:raise ValueError('Prior ledger mismatch')
|
||||
if e['prior_charged_worker_cpu_seconds']+e['new_initial_cpu_seconds']+1802>28800:raise ValueError('Insufficient shared compute budget')
|
||||
|
||||
|
||||
def run(root):
|
||||
root=Path(root)
|
||||
with (root/'recovery.lock').open('a') as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
return locked(root)
|
||||
|
||||
|
||||
def locked(root):
|
||||
c=contract(root);e=json.loads((root/'continuation-contract.json').read_text());original=Path(e['original_root'])
|
||||
for p,h in {**e['code_sha256'],**e['source_sha256']}.items():checked(p,h)
|
||||
if sha(root/'contract.json')!=sha(original/'contract.json'):raise ValueError('Scientific contract must be byte identical')
|
||||
prior=json.loads((original/'preparation-complete.json').read_text());verify_scope(c,e,prior)
|
||||
if (root/'recovery-started.json').exists():raise FileExistsError('Never restart labelled recovery')
|
||||
os.sched_setaffinity(0,[25]);started=time.monotonic();stop=[None]
|
||||
def interrupted(*_):stop[0]=stop[0] or 'COORDINATOR_INTERRUPTED'
|
||||
signal.signal(signal.SIGTERM,interrupted);signal.signal(signal.SIGINT,interrupted)
|
||||
save(root/'recovery-started.json',dict(pid=os.getpid(),unix=time.time(),recovery_indices=[568],
|
||||
contract_sha256=sha(root/'contract.json'),continuation_contract_sha256=sha(root/'continuation-contract.json')))
|
||||
dest=root/'parts'/CASE;dest.mkdir(parents=True,exist_ok=False)
|
||||
env=dict(os.environ,OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1',MKL_NUM_THREADS='1',NUMEXPR_NUM_THREADS='1',CUDA_VISIBLE_DEVICES='')
|
||||
with (dest/'guard.log').open('x') as log:
|
||||
proc=subprocess.Popen([sys.executable,'tools/run_r4a.py',str(root),'--guard','568','--slot','0'],stdout=log,stderr=subprocess.STDOUT,env=env,start_new_session=True)
|
||||
while proc.poll() is None:
|
||||
if disk_usage(original)+disk_usage(root)>=20*2**30:stop[0]=stop[0] or 'GLOBAL_DISK_LIMIT'
|
||||
if stop[0]:kill_guard_worker(proc.pid)
|
||||
save(root/'progress.json',dict(stage='LABELLED_1470_DISTANCE_ONLY_RECOVERY',guard_pid=proc.pid,
|
||||
prior_charged_worker_cpu_seconds=e['prior_charged_worker_cpu_seconds'],new_initial_cpu_seconds=e['new_initial_cpu_seconds'],
|
||||
stop_reason=stop[0],wall_seconds=time.monotonic()-started))
|
||||
time.sleep(.5)
|
||||
guard_path=dest/'guard-result.json'
|
||||
if not guard_path.exists():raise RuntimeError('Missing recovery guard receipt; no scoring')
|
||||
recovery=json.loads(guard_path.read_text())
|
||||
spent=e['prior_charged_worker_cpu_seconds']+e['new_initial_cpu_seconds']+recovery['worker']['cpu_seconds']
|
||||
if recovery['worker']['monitor_errors']:stop[0]=stop[0] or 'MONITOR_ERROR'
|
||||
if spent>28800:stop[0]=stop[0] or 'COMPUTE_CPU_LIMIT'
|
||||
contract(root) # A global source mismatch never becomes a local failure.
|
||||
for p,h in e['code_sha256'].items():checked(p,h)
|
||||
parts={};failures=[]
|
||||
for record in prior['records']:
|
||||
chosen=recovery if record['index']==568 else record
|
||||
if chosen['worker']['status']!='PASS':
|
||||
failures.append(dict(case=chosen['case'],source='labelled_recovery' if chosen is recovery else 'original',worker=chosen['worker']));continue
|
||||
result=checked(chosen['result_path'],chosen['result_sha256']);data=json.loads(result.read_text())
|
||||
pred=result.parent/'query-predictions.npz';digest=data['output_sha256'][pred.name];checked(pred,digest)
|
||||
parts[chosen['case']]=dict(result=str(result),result_sha256=sha(result),predictions=str(pred),predictions_sha256=digest,
|
||||
source='labelled_recovery' if chosen is recovery else 'original')
|
||||
post=None
|
||||
if stop[0] is None:
|
||||
save(root/'pass-predictions-freeze.json',dict(contract_sha256=sha(root/'contract.json'),
|
||||
continuation_contract_sha256=sha(root/'continuation-contract.json'),parts=parts,canonical_failures=failures,
|
||||
original_preparation_complete_sha256=sha(original/'preparation-complete.json'),recovery_guard_sha256=sha(guard_path),
|
||||
original_1470_receipt_preserved=True,classification_ruling='1794830693.515879',new_labels_read=False))
|
||||
remaining=20*2**30-disk_usage(original)-disk_usage(root)
|
||||
if remaining<=0:stop[0]='GLOBAL_DISK_LIMIT'
|
||||
else:
|
||||
os.sched_setaffinity(0,[24])
|
||||
post=supervise([sys.executable,'tools/r4a_poststop_score.py',str(root)],root/'postfit','worker',
|
||||
dict(total_cpu_seconds=7200,job_cpu_seconds=7200,job_wall_seconds=7200,
|
||||
tree_rss_bytes=4*2**30,disk_bytes=remaining,max_processes=1),poll=.2)
|
||||
os.sched_setaffinity(0,[25]);spent+=post['cpu_seconds']
|
||||
if post['status']!='PASS' or post['monitor_errors']:stop[0]='POSTPROCESS_FAILED'
|
||||
save(root/'continuation-complete.json',dict(status='COMPLETE' if post and post['status']=='PASS' and stop[0] is None else 'STOPPED',
|
||||
stop_reason=stop[0],recovery=recovery,canonical_pass=len(parts),canonical_failures=failures,postfit=post,
|
||||
charged_worker_cpu_seconds=spent,total_worker_cpu_cap=36000,postprocess_cpu_cap=7200,
|
||||
prior_charged_worker_cpu_seconds=e['prior_charged_worker_cpu_seconds'],new_initial_cpu_seconds=e['new_initial_cpu_seconds'],
|
||||
coordinator_cpu_seconds=sum(resource.getrusage(resource.RUSAGE_SELF)[:2]),wall_seconds=time.monotonic()-started,
|
||||
labelled_recoveries=1,other_retries=0,original_receipts_unchanged=True))
|
||||
return 0 if post and post['status']=='PASS' and stop[0] is None else 1
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('root',type=Path);a=p.parse_args();raise SystemExit(run(a.root))
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Synthetic scope, common-component, ledger and cache-scoring checks."""
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import numpy as np
|
||||
from gre24_prepare_v2 import sha
|
||||
from s2_recovery_supervisor import save
|
||||
from run_r4a_recovery import verify_scope,CASE
|
||||
import r4a_poststop_score as scorer
|
||||
|
||||
|
||||
class Checks(unittest.TestCase):
|
||||
def fixture(self):
|
||||
c={'parts':[{} for _ in range(569)]};c['parts'][568]={'case':CASE}
|
||||
e=dict(recovery_indices=[568],prior_charged_worker_cpu_seconds=7517.870153,new_initial_cpu_seconds=3.)
|
||||
p=dict(never_attempted=[],missing_receipt_indices=[],accounting_complete=True,charged_worker_cpu_seconds=7517.870153,
|
||||
records=[dict(index=568,worker=dict(returncode=-9,stop_reason=None))])
|
||||
return c,e,p
|
||||
|
||||
def test_only_1470_once_scope(self):
|
||||
c,e,p=self.fixture();verify_scope(c,e,p)
|
||||
for indices in [[243],[568,568],[243,568],[]]:
|
||||
bad=dict(e,recovery_indices=indices)
|
||||
with self.assertRaises(ValueError):verify_scope(c,bad,p)
|
||||
|
||||
def test_ledger_and_never_attempted_not_reclassified(self):
|
||||
c,e,p=self.fixture()
|
||||
with self.assertRaises(ValueError):verify_scope(c,dict(e,prior_charged_worker_cpu_seconds=0),p)
|
||||
with self.assertRaises(ValueError):verify_scope(c,e,dict(p,never_attempted=[568]))
|
||||
with self.assertRaises(ValueError):verify_scope(c,e,dict(p,missing_receipt_indices=[568]))
|
||||
with self.assertRaises(ValueError):verify_scope(c,dict(e,new_initial_cpu_seconds=25000),p)
|
||||
|
||||
def test_original_signal_evidence_not_changed(self):
|
||||
c,e,p=self.fixture();before=copy.deepcopy(p);verify_scope(c,e,p);self.assertEqual(p,before)
|
||||
p['records'][0]['worker']['stop_reason']='wall_limit'
|
||||
with self.assertRaises(ValueError):verify_scope(c,e,p)
|
||||
|
||||
def test_three_arms_same_complete_components_and_new_delta_direction(self):
|
||||
roster=[dict(case='a',component_id='A',nodes=4),dict(case='b',component_id='A',nodes=5),dict(case='c',component_id='C',nodes=6)]
|
||||
def row(case):return dict(case=case,metrics={a:{m:{'value':v} for m in scorer.METRICS} for a,v in [('EIK',1.),('GRAPH',2.),('B0_S2',.5)]})
|
||||
summary,excluded=scorer.summaries([row('a'),row('c')],roster,{'a','c'})
|
||||
self.assertEqual(excluded['A']['nodes'],9)
|
||||
self.assertEqual(summary['relative_l2']['component_ids'],['C'])
|
||||
delta=summary['relative_l2']['contrasts'];self.assertEqual(delta['GRAPH']['value'],-1)
|
||||
self.assertEqual(delta['GRAPH']['low'],-1);self.assertEqual(delta['B0_S2']['high'],.5)
|
||||
self.assertNotIn('region',delta['GRAPH'])
|
||||
|
||||
def test_undefined_one_arm_excludes_component_for_every_arm(self):
|
||||
roster=[dict(case='a',component_id='A',nodes=4)]
|
||||
rows=[dict(case='a',metrics={a:{m:{'value':1.} for m in scorer.METRICS} for a in scorer.ARMS})]
|
||||
rows[0]['metrics']['B0_S2']['relative_l2']['value']=None
|
||||
summary,_=scorer.summaries(rows,roster,{'a'})
|
||||
self.assertEqual(summary['relative_l2']['components'],0)
|
||||
self.assertEqual(summary['relative_l2']['means'],{a:None for a in scorer.ARMS})
|
||||
|
||||
def test_frozen_cached_score_integration_and_tamper_before_labels(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root=Path(temp);(root/'contract.json').write_text('{}');save(root/'continuation-contract.json',{'code_sha256':{}})
|
||||
case='00000001_synthetic';failed='00000002_synthetic'
|
||||
truth=np.array([1.,2.]);raw=np.array([10,20]);counts=np.array([1,3]);labels=root/'labels.npz';np.savez(labels,seconds=truth,raw_ids=raw,counts=counts)
|
||||
index=root/'labels.json';save(index,[dict(case=case,fold=0,path=str(labels),sha256=sha(labels))])
|
||||
hist=root/'historical.json';save(hist,[dict(case=case,arm='B0',**{m:dict(value=.1,reason=None) for m in scorer.METRICS})])
|
||||
pred=root/'pred.npz';np.savez(pred,raw_ids=raw,counts=counts,F=.8*truth,G=.6*truth)
|
||||
result=root/'result.json';save(result,{'status':'PASS'})
|
||||
rows=[dict(case=k,component_id=k,nodes=2,assignments=[dict(fold=0,role='test')]) for k in [case,failed]]
|
||||
c=dict(parts=rows,label_index=str(index),historical_scores=str(hist))
|
||||
freeze=dict(contract_sha256=sha(root/'contract.json'),continuation_contract_sha256=sha(root/'continuation-contract.json'),
|
||||
canonical_failures=[dict(case=failed)],parts={case:dict(result=str(result),result_sha256=sha(result),predictions=str(pred),predictions_sha256=sha(pred))})
|
||||
save(root/'pass-predictions-freeze.json',freeze)
|
||||
q=dict(raw_ids=raw,counts=counts,near_wall=np.array([True,True]),coordinates_over_Rg=np.array([[0.,0,0],[1,0,0]]))
|
||||
with patch.object(scorer,'contract',return_value=c),patch.object(scorer,'prediction_inputs',return_value=q):scorer.score(root)
|
||||
summary=json.loads((root/'postfit/score-summary.json').read_text())
|
||||
self.assertEqual(summary['pass_prediction_parts'],1);self.assertEqual(summary['new_decodes'],0)
|
||||
self.assertAlmostEqual(summary['summary']['relative_l2']['contrasts']['GRAPH']['value'],-1)
|
||||
pred.write_bytes(b'tampered');labels.unlink()
|
||||
with patch.object(scorer,'contract',return_value=c):
|
||||
with self.assertRaisesRegex(ValueError,'SHA mismatch'):scorer.score(root)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
out=Path(sys.argv[1]);out.mkdir(parents=True,exist_ok=False)
|
||||
with (out/'tests.log').open('x') as log:
|
||||
r=unittest.TextTestRunner(stream=log,verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(Checks))
|
||||
save(out/'receipt.json',dict(status='PASS' if r.wasSuccessful() else 'FAIL',tests=r.testsRun,failures=len(r.failures),errors=len(r.errors),
|
||||
cpu_seconds=sum(resource.getrusage(resource.RUSAGE_SELF)[:2]),scope='synthetic only; no real labels or geometry',
|
||||
code_sha256={n:sha(n) for n in ['tools/r4a_poststop_score.py','tools/run_r4a_recovery.py','tools/test_r4a_recovery.py']}))
|
||||
print((out/'receipt.json').read_text());raise SystemExit(0 if r.wasSuccessful() else 1)
|
||||
Reference in new issue
Block a user