Freeze incident ledger and isolated 134-part recovery with three-source pilot handoff

This commit is contained in:
Frank14f committed 2026-11-15 05:14:57 +08:00
1 parent f9eeb1262f
commit a5c6c0444e
352 files changed
+32433

No files matched your search

+116
View File
@@ -0,0 +1,116 @@
"""Freeze the original incident, quarantine partial outputs, and plan 134 parts."""
import json
from pathlib import Path
import shutil
from freeze_g1_components import sha
from s2_e1_supervisor import save
from s2_recovery_monitoring import disk_usage
ORIGINAL=Path('artifacts/s2-pilot-inputs-2026-11-15')
INCIDENT=Path('artifacts/s2-preparation-incident-2026-11-15')
RECOVERY=Path('artifacts/s2-pilot-recovery-inputs-2026-11-15')
INFRA=[318,322,349,354,355,356,365,366,370,371,372,373,375,378,379,380]
WALL=[181,201,211]
UNATTEMPTED=list(range(381,499))
INDICES=sorted(INFRA+UNATTEMPTED)
def inventory(path):
if not path.exists():return []
result=[]
for p in sorted(path.rglob('*')):
assert not p.is_symlink()
if p.is_file():result.append(dict(path=str(p.relative_to(path)),bytes=p.stat().st_size,sha256=sha(p)))
return result
def main():
assert not INCIDENT.exists() and not RECOVERY.exists(),'Never overwrite an incident/recovery plan'
assert not (ORIGINAL/'batch-complete.json').exists(),'Original incident has no normal batch terminal'
c=json.loads((ORIGINAL/'contract.json').read_text());roles=json.loads((ORIGINAL/'role-manifest.json').read_text())
assert sha(ORIGINAL/'role-manifest.json')==c['role_manifest_sha256']
for p,h in c['code_sha256'].items():assert sha(p)==h,p
progress=json.loads((ORIGINAL/'progress.json').read_text())
assert progress['completed']==365 and progress['next_index']==381 and progress['active']==INFRA
started={int(p.parent.name.split('-')[1]) for p in (ORIGINAL/'jobs').glob('*/worker.started.json')}
completed={int(p.parent.name.split('-')[1]) for p in (ORIGINAL/'jobs').glob('*/guard-result.json')}
assert started==completed==set(range(381))
rows=[]
for i in range(381):
folder=ORIGINAL/'jobs'/f'job-{i:04d}';r=json.loads((folder/'guard-result.json').read_text());w=r['worker'];spec=c['cases'][i]
if i in INFRA:
assert w['returncode']==-9 and w['stop_reason'] is None and w['status']!='PASS'
classification='INFRA_ABORTED';assert not (ORIGINAL/'ready'/spec['case']/'receipt.json').exists()
assert not spec.get('reuse_preparation'),'Infrastructure aborts must start from fresh output directories'
elif i in WALL:
assert w['returncode']==-9 and w['stop_reason']=='wall_limit';classification='WALL_LIMIT_FAIL'
else:
assert w['status']=='PASS' and w['returncode']==0;classification='PASS'
assert (ORIGINAL/'ready'/spec['case']/'receipt.json').exists()
rows.append(dict(index=i,case=spec['case'],nodes=spec['tet_nodes'],role='learning' if spec['case'] in roles['learning_parts'] else 'validation',
classification=classification,worker=r['worker'],supervisor_cpu_seconds=r['supervisor_cpu_seconds'],
guard_receipt_path=str(folder/'guard-result.json'),guard_receipt_sha256=sha(folder/'guard-result.json'),
worker_started_sha256=sha(folder/'worker.started.json'),worker_receipt_sha256=sha(folder/'worker.receipt.json')))
INCIDENT.mkdir();(INCIDENT/'quarantine').mkdir()
snapshot=dict(status='INFRA_ABORTED',original_root=str(ORIGINAL),original_contract_sha256=sha(ORIGINAL/'contract.json'),
batch_started_sha256=sha(ORIGINAL/'batch-started.json'),last_progress_sha256=sha(ORIGINAL/'progress.json'),jobs=rows,
ordinary_pass=362,wall_limit_fail_indices=WALL,infra_aborted_indices=INFRA,never_attempted_indices=UNATTEMPTED,
cause='Coordinator FileNotFoundError during disk_usage stat of progress.json.tmp; finally terminated 16 active workers',
original_session=16682,original_exit_code=1,original_batch_complete_created=False)
save(INCIDENT/'original-batch-infra-aborted.json',snapshot)
moves=[]
for i in INFRA:
case=c['cases'][i]['case']
for kind in ['parts','ready']:
source=ORIGINAL/kind/case;dest=INCIDENT/'quarantine'/kind/case
assert source.exists() and not dest.exists()
moves.append(dict(original_index=i,kind=kind,from_path=str(source),to_path=str(dest),files=inventory(source)))
save(INCIDENT/'quarantine-plan.json',dict(moves=moves))
moved=[]
for item in moves:
source=Path(item['from_path']);dest=Path(item['to_path']);dest.parent.mkdir(parents=True,exist_ok=True)
source.rename(dest);assert inventory(dest)==item['files']
moved.append(item['to_path']);save(INCIDENT/'quarantine-progress.json',dict(moved=moved,total=len(moves)))
save(INCIDENT/'quarantine-receipt.json',dict(status='ALL_16_PARTIALS_MOVED_AND_HASH_VERIFIED',moves=moves,reused_by_recovery=False))
prior=sum(r['worker']['cpu_seconds'] for r in rows);aborted=sum(r['worker']['cpu_seconds'] for r in rows if r['classification']=='INFRA_ABORTED')
ledger=dict(status='FROZEN_INCIDENT_LEDGER',ruling='1794689807.792819',original_root=str(ORIGINAL),
original_snapshot=str(INCIDENT/'original-batch-infra-aborted.json'),original_snapshot_sha256=sha(INCIDENT/'original-batch-infra-aborted.json'),
quarantine_receipt=str(INCIDENT/'quarantine-receipt.json'),quarantine_receipt_sha256=sha(INCIDENT/'quarantine-receipt.json'),
pass_count=362,wall_limit_indices=WALL,infra_aborted_indices=INFRA,unattempted_indices=UNATTEMPTED,recovery_indices=INDICES,
prior_worker_cpu_seconds=prior,prior_aborted_worker_cpu_seconds_included=aborted,
prior_guard_cpu_seconds=sum(r['supervisor_cpu_seconds'] for r in rows),coordinator_cpu_seconds='UNKNOWN_NO_EXIT_ACCOUNTING_RECEIPT',
accounting_rule='All 381 original worker receipts counted once, including the 16 aborted; add only new recovery worker CPU',
labelled_recovery_allowance_per_infra_part=1,original_batch_complete_created=False)
save(INCIDENT/'incident-ledger.json',ledger)
RECOVERY.mkdir();(RECOVERY/'public').mkdir();shutil.copy2(ORIGINAL/'role-manifest.json',RECOVERY/'role-manifest.json')
selected=[c['cases'][i] for i in INDICES]
terminal=[r for r in rows if r['classification']!='INFRA_ABORTED']
rates={}
for cached in [False,True]:
group=[r for r in terminal if bool(c['cases'][r['index']].get('reuse_preparation'))==cached]
rates[cached]=sum(r['worker']['cpu_seconds'] for r in group)/sum(r['nodes'] for r in group) if group else c['initial_cpu_seconds_per_node']
projected=prior+1.25*sum(rates[bool(s.get('reuse_preparation'))]*s['tet_nodes'] for s in selected)
roots=[str(ORIGINAL),str(INCIDENT),str(RECOVERY)];existing=sum(disk_usage(p) for p in roots)
projected_disk=existing+c['initial_projection_gib']*2**30*sum(s['tet_nodes'] for s in selected)/sum(s['tet_nodes'] for s in c['cases'])
added=['tools/s2_recovery_monitoring.py','tools/s2_recovery_supervisor.py','tools/run_s2_recovery_preparation.py','tools/prepare_s2_incident_recovery.py']
contract=dict(c,version='S2-labelled-infrastructure-recovery-v1',cases=selected,original_indices=INDICES,infra_aborted_indices=INFRA,
original_root=str(ORIGINAL),original_contract_sha256=sha(ORIGINAL/'contract.json'),
original_snapshot=ledger['original_snapshot'],original_snapshot_sha256=ledger['original_snapshot_sha256'],
incident_ledger=str(INCIDENT/'incident-ledger.json'),incident_ledger_sha256=sha(INCIDENT/'incident-ledger.json'),
code_sha256={p:sha(p) for p in list(c['code_sha256'])+added},prior_worker_cpu_seconds=prior,budget_roots=roots,
projected_cumulative_worker_cpu_hours=projected/3600,projected_cumulative_gib=projected_disk/2**30,
projection_method='Exclude partial infrastructure aborts from rate estimation, retain their CPU in prior total; successful/true-timeout observed category rates times 134 nodes plus 25%; original maximum-byte/node margin for extra outputs',
limits=dict(worker_cpu_hours=60,workers=16,disk_bytes=100*2**30,per_part_wall_seconds=1800,per_part_tree_rss_bytes=1342177280,retries=0,replacements=0),
checkpoint='No new first50 barrier; original accepted checkpoint retained',authorizing_rulings=['1794689807.792819'],
partial_outputs_policy='Original 16 quarantined by rename and hash verified, never read/reused; recovery uses a new root; original part specs identical')
save(RECOVERY/'contract.json',contract)
report=dict(status='READY_WITHIN_CAPS' if projected<=60*3600 and projected_disk<=100*2**30 else 'PROJECTION_OVER_CAP_REPORT_BEFORE_LAUNCH',
original_pass=362,original_wall_fail=3,labelled_recovery=16,never_attempted=118,recovery_parts=134,
prior_worker_cpu_hours=prior/3600,prior_aborted_cpu_hours_already_included=aborted/3600,
projected_cumulative_worker_cpu_hours=projected/3600,projected_cumulative_gib=projected_disk/2**30,
contract_sha256=sha(RECOVERY/'contract.json'),incident_ledger_sha256=sha(INCIDENT/'incident-ledger.json'),
worker_numerical_code_unchanged=True,workers_started=False,GPU_started=False)
save(RECOVERY/'public/prelaunch-projection.json',report);print(json.dumps(report))
if __name__=='__main__':main()
@@ -0,0 +1,67 @@
"""Finalize all 499 terminal preparation attempts and freeze one pilot plan."""
import argparse
import json
from pathlib import Path
import numpy as np
from freeze_g1_components import sha
from s2_e1_supervisor import save
from s2_pilot_data import permitted_role
from s2_incident_recovery_manifest import load_manifest
def quantile_probe(records,roles):
learning=sorted((r for r in records if permitted_role(roles,r['case'])=='learning'),key=lambda r:(r['nodes'],r['case']))
if len(learning)<20:raise ValueError('Need 20 distinct successful learning parts')
return [learning[int(i)]['case'] for i in np.linspace(0,len(learning)-1,20,dtype=int)]
def finalize(source,root,gpu_uuid,terminal_path):
c=json.loads((source/'contract.json').read_text());batch=load_manifest(terminal_path)
assert batch['status']=='ATTEMPTS_COMPLETE' and batch['stop_reason'] is None
assert len(batch['jobs'])==len(c['cases'])==499 and not batch['not_run_indices']
assert sorted(r['index'] for r in batch['jobs'])==list(range(499))
assert not root.exists(),'No overwrite or retry of an existing pilot'
roles=json.loads((source/'role-manifest.json').read_text());assert sha(source/'role-manifest.json')==c['role_manifest_sha256']
ready=[];failed=[]
for job in sorted(batch['jobs'],key=lambda r:r['index']):
spec=c['cases'][job['index']];case=spec['case'];role=permitted_role(roles,case)
assert job['case']==case
dest=Path(job.get('ready_source_root',source))/'ready'/case
if job['worker']['status']!='PASS':
failed.append(dict(case=case,role=role,nodes=spec['tet_nodes'],component_id=spec['component_id'],guard=job['worker'],
failure=json.loads((dest/'failure.json').read_text()) if (dest/'failure.json').exists() else None))
continue
r=json.loads((dest/'receipt.json').read_text());assert r['status']=='READY' and r['role']==role and r['case']==case
prep=Path(r['preparation_root']);assert sha(prep/'result.json')==r['preparation_result_sha256']
pr=json.loads((prep/'result.json').read_text());assert pr['status']=='COMPLETE'
hashes={name:sha(prep/name) for name in ['base.npy','queries.npz']}
assert all(hashes[name]==pr['output_sha256'][name] for name in hashes)
label=dest/'labels.npz';hashes['labels.npz']=sha(label);assert hashes['labels.npz']==r['label_sha256']
assert r['nodes']==spec['tet_nodes'] and r['component_id']==spec['component_id'] and r['t_set']==spec['t_set']
ready.append(dict(case=case,role=role,component_id=r['component_id'],nodes=r['nodes'],t_set=r['t_set'],
preparation_root=str(prep),label_path=str(label),input_sha256=hashes,ready_receipt_sha256=sha(dest/'receipt.json')))
planned={role:sum(s['tet_nodes'] for s in c['cases'] if permitted_role(roles,s['case'])==role) for role in ['learning','validation']}
successful={role:dict(parts=sum(r['role']==role for r in ready),nodes=sum(r['nodes'] for r in ready if r['role']==role)) for role in planned}
assert planned==dict(learning=11863762,validation=3330152)
if not all(successful[k]['parts'] for k in successful):raise ValueError('Empty successful role')
probe=quantile_probe(ready,roles)
paths=['tools/prepare_s2_recovered_pilot_training.py','tools/run_s2_recovered_pilot.py','tools/run_s2_pilot_probe.py',
'tools/run_s2_pilot_training.py','tools/s2_pilot_train.py','tools/s2_recovered_pilot_gpu_guard.py','tools/s2_recovery_gpu_supervisor.py',
'tools/s2_e1_supervisor.py','tools/s2_pilot_data.py','tools/s2_incident_recovery_manifest.py','tools/freeze_g1_components.py']
paths+=['tools/s2_recovery_monitoring.py','tools/prepare_s2_incident_recovery.py','tools/run_s2_recovery_chain.py']
paths+=sorted(str(p) for p in Path('tools/s2_models').glob('*.py'))
code={p:sha(p) for p in paths}
root.mkdir();save(root/'success-manifest.json',dict(ready_parts=ready,failed_parts=failed,successful=successful,
preparation_batch_sha256=sha(terminal_path),preparation_terminal_manifest=str(terminal_path),
preparation_sources=batch.get('source_provenance',[]),preparation_contract_sha256=sha(source/'contract.json')))
plan=dict(fold=0,pool=100,seed=0,gpu_uuid=gpu_uuid,code_sha256=code,role_manifest=str(source/'role-manifest.json'),
role_manifest_sha256=sha(source/'role-manifest.json'),success_manifest=str(root/'success-manifest.json'),
success_manifest_sha256=sha(root/'success-manifest.json'),probe_cases=probe,
probe_selection='20 equally spaced ranks in successful learning node-count order; includes min/max; tie by case',
learning_nodes=planned['learning'],validation_nodes=planned['validation'],successful=successful,
extrapolation='Train rate * all 387 planned learning nodes + FP32 inference rate * all 112 planned validation nodes; conservative if failed parts dropped',
runs=[dict(name=f'{arm}{width}-seed0',arm=arm,width=width,seed=0) for width in [128,256] for arm in ['N','E']],
limits=dict(total_gpu_wall_seconds=7200,probe_wall_seconds=300,run_wall_seconds=1800,host_rss_bytes=16*2**30,vram_bytes=15*2**30,disk_bytes=5*2**30),
coverage_boundary=dict(planned_max_learning_nodes=max(s['tet_nodes'] for s in c['cases'] if permitted_role(roles,s['case'])=='learning'),max_successful_learning_nodes=max(r['nodes'] for r in ready if r['role']=='learning'),failed_parts=failed,statement='VRAM probe covers only the maximum successful learning part included; not failed/larger unprobed parts'),
authorizing_rulings=['1794680129.303719','1794681576.845789','1794681807.376669','1794689807.792819'],test_labels_read=False)
save(root/'pilot-plan.json',plan);return plan
+54
View File
@@ -0,0 +1,54 @@
"""One irreversible attempt: bounded timing probe, frozen E_max, then four runs."""
import argparse
import fcntl
import json
from pathlib import Path
import sys
import time
import traceback
from freeze_g1_components import sha
from s2_e1_supervisor import save
from s2_recovered_pilot_gpu_guard import guarded_worker,run as train_runs
from s2_pilot_train import common_epoch_limit
def freeze_training_contract(root,plan,probe):
assert probe['status']=='COMPLETE' and probe['labels_read'] is False and probe['metrics_evaluated'] is False
assert [r['case'] for r in probe['rows']]==plan['probe_cases']
nodes=sum(r['nodes'] for r in probe['rows']);assert nodes==probe['probe_nodes']
timing=common_epoch_limit(sum(r['training_seconds'] for r in probe['rows'])/nodes,
sum(r['inference_seconds'] for r in probe['rows'])/nodes,plan['learning_nodes'],plan['validation_nodes'])
assert all(probe[k]==v for k,v in timing.items())
c=dict(plan,**timing,timing_probe_receipt=str(root/'timing-probe/result.json'),timing_probe_sha256=sha(root/'timing-probe/result.json'),
timing_probe_guard_sha256=sha(root/'timing-probe-guard-receipt.json'),
probe_guard_wall_seconds=json.loads((root/'timing-probe-guard-receipt.json').read_text())['total_run_wall_seconds'],
standardizer_fingerprint=probe['standardizer_fingerprint'])
with (root/'training-contract.json').open('x') as f:json.dump(c,f,indent=2);f.write('\n')
return c
def run(root):
with (root/'orchestrator.lock').open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
assert not (root/'orchestrator-started.json').exists(),'No automatic probe/pilot retry'
plan=json.loads((root/'pilot-plan.json').read_text())
for p,h in plan['code_sha256'].items():assert sha(p)==h,p
start=time.monotonic();save(root/'orchestrator-started.json',dict(started_unix=time.time(),plan_sha256=sha(root/'pilot-plan.json')))
try:
receipt,probe=guarded_worker(root,dict(name='timing-probe'),-1,plan['gpu_uuid'],300,
[sys.executable,'tools/run_s2_pilot_probe.py',str(root)])
if receipt['status']!='PASS' or not probe or probe['status']!='COMPLETE':raise RuntimeError('Timing probe failed; no training, no retry')
coverage=dict(**plan['coverage_boundary'],actual_probe_max_nodes=max(r['nodes'] for r in probe['rows']),probe_receipt_sha256=sha(root/'timing-probe/result.json'),probe_guard_sha256=sha(root/'timing-probe-guard-receipt.json'))
assert coverage['actual_probe_max_nodes']==coverage['max_successful_learning_nodes']
save(root/'timing-probe/coverage-addendum.json',coverage)
freeze_training_contract(root,plan,probe)
train_runs(root,prior_wall_seconds=time.monotonic()-start)
result=json.loads((root/'pilot-complete.json').read_text())
save(root/'orchestrator-complete.json',dict(status=result['status'],total_wall_seconds=time.monotonic()-start,
selected_global_width=result['selected_global_width'],test_labels_read=False,probe_included_in_7200_seconds=True))
except Exception as exc:
save(root/'orchestrator-failure.json',dict(status='FAILED_NO_RETRY',error=str(exc),traceback=traceback.format_exc(),total_wall_seconds=time.monotonic()-start));raise
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);a=p.parse_args();run(a.root)
+50
View File
@@ -0,0 +1,50 @@
"""Wait only for the authorized recovery, validate three sources, then pilot."""
import argparse
import fcntl
import json
from pathlib import Path
import time
import traceback
from freeze_g1_components import sha
from s2_e1_supervisor import save
from s2_incident_recovery_manifest import create_manifest
from prepare_s2_recovered_pilot_training import finalize
from run_s2_recovered_pilot import run as pilot
def run(original,incident,recovery,root,watch,gpu_uuid):
watch.mkdir(exist_ok=True)
with (watch/'execution.lock').open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
assert not (watch/'started.json').exists() and not root.exists(),'No repeated recovery-chain attempt'
assert (recovery/'batch-started.json').exists()
paths=[str(p) for p in Path('tools').glob('*s2*recover*.py')]+[str(p) for p in Path('tools').glob('*s2*pilot*.py')]+[str(p) for p in Path('tools/s2_models').glob('*.py')]
paths+=['tools/s2_e1_supervisor.py','tools/freeze_g1_components.py']
frozen={p:sha(p) for p in sorted(set(paths))};expected=sha(recovery/'contract.json');start=time.monotonic()
save(watch/'started.json',dict(started_unix=time.time(),pid=__import__('os').getpid(),recovery_root=str(recovery),
recovery_contract_sha256=expected,incident_ledger_sha256=sha(incident/'incident-ledger.json'),code_sha256=frozen,
pilot_root=str(root),gpu_uuid=gpu_uuid,ruling='1794689807.792819',waiting_uses_GPU=False))
try:
while not (recovery/'batch-complete.json').exists():
p=json.loads((recovery/'progress.json').read_text())
save(watch/'progress.json',dict(stage='WAITING_FOR_AUTHORIZED_RECOVERY',completed=p['completed'],
recovery_stop_reason=p['stop_reason'],waiting_seconds=time.monotonic()-start,GPU_started=False))
time.sleep(10)
assert sha(recovery/'contract.json')==expected
for p,h in frozen.items():assert sha(p)==h,p
terminal=create_manifest(incident,recovery)
plan=finalize(original,root,gpu_uuid,terminal)
save(watch/'preparation-accepted.json',dict(status='THREE_SOURCES_499_TERMINALS_VERIFIED',merged_terminal=str(terminal),
merged_terminal_sha256=sha(terminal),successful=plan['successful'],pilot_plan_sha256=sha(root/'pilot-plan.json'),
failed_parts_dropped=499-sum(v['parts'] for v in plan['successful'].values()),waiting_seconds=time.monotonic()-start))
save(watch/'progress.json',dict(stage='BOUNDED_PROBE_AND_PILOT',pilot_root=str(root),GPU_wall_limit_seconds=7200))
pilot(root);result=json.loads((root/'orchestrator-complete.json').read_text())
save(watch/'complete.json',dict(**result,wall_seconds_including_CPU_wait=time.monotonic()-start))
except Exception as exc:
save(watch/'failure.json',dict(status='STOPPED_NO_RETRY',error=str(exc),traceback=traceback.format_exc(),wall_seconds=time.monotonic()-start));raise
if __name__=='__main__':
p=argparse.ArgumentParser()
for name in ['original','incident','recovery','root','watch']:p.add_argument(name,type=Path)
p.add_argument('gpu_uuid');a=p.parse_args();run(a.original,a.incident,a.recovery,a.root,a.watch,a.gpu_uuid)
+102
View File
@@ -0,0 +1,102 @@
"""Three-source merge for this explicitly authorized infrastructure incident."""
import json
import math
import os
from pathlib import Path
from freeze_g1_components import sha
from s2_recovery_monitoring import disk_usage
from prepare_s2_incident_recovery import INFRA,WALL,UNATTEMPTED,INDICES
def read_bound(entry):
p=Path(entry['path']);assert sha(p)==entry['sha256'];return json.loads(p.read_text())
def verify(proof):
assert set(proof)=={'original_batch','recovery_batch','incident_ledger'}
original=read_bound(proof['original_batch']);recovered=read_bound(proof['recovery_batch']);ledger=read_bound(proof['incident_ledger'])
root=Path(original['original_root']);recovery=Path(proof['recovery_batch']['root'])
assert original['status']=='INFRA_ABORTED' and not (root/'batch-complete.json').exists()
assert sha(root/'contract.json')==original['original_contract_sha256']
assert sha(root/'batch-started.json')==original['batch_started_sha256']
assert sha(root/'progress.json')==original['last_progress_sha256']
old=json.loads((root/'contract.json').read_text());c=json.loads((recovery/'contract.json').read_text())
assert sha(recovery/'contract.json')==proof['recovery_batch']['contract_sha256']
assert c['original_root']==str(root) and c['original_contract_sha256']==original['original_contract_sha256']
assert c['incident_ledger_sha256']==proof['incident_ledger']['sha256']
assert c['incident_ledger']==proof['incident_ledger']['path']
assert c['original_snapshot']==ledger['original_snapshot']==proof['original_batch']['path']
assert c['original_snapshot_sha256']==proof['original_batch']['sha256']==ledger['original_snapshot_sha256']
assert ledger['recovery_indices']==c['original_indices']==INDICES
assert ledger['infra_aborted_indices']==c['infra_aborted_indices']==INFRA
assert ledger['wall_limit_indices']==WALL and ledger['unattempted_indices']==UNATTEMPTED
assert c['role_manifest_sha256']==old['role_manifest_sha256']==sha(root/'role-manifest.json')==sha(recovery/'role-manifest.json')
assert len(old['cases'])==499 and len(c['cases'])==134
assert c['cases']==[old['cases'][i] for i in INDICES]
assert c['limits']==dict(worker_cpu_hours=60,workers=16,disk_bytes=100*2**30,per_part_wall_seconds=1800,per_part_tree_rss_bytes=1342177280,retries=0,replacements=0)
for p,h in old['code_sha256'].items():assert c['code_sha256'][p]==h and sha(p)==h
for p,h in c['code_sha256'].items():assert sha(p)==h
assert sha(ledger['quarantine_receipt'])==ledger['quarantine_receipt_sha256']
quarantine=json.loads(Path(ledger['quarantine_receipt']).read_text())
assert quarantine['status']=='ALL_16_PARTIALS_MOVED_AND_HASH_VERIFIED' and quarantine['reused_by_recovery'] is False
assert {(m['original_index'],m['kind']) for m in quarantine['moves']}=={(i,k) for i in INFRA for k in ['parts','ready']}
for move in quarantine['moves']:
assert not Path(move['from_path']).exists()
for f in move['files']:assert sha(Path(move['to_path'])/f['path'])==f['sha256']
old_jobs=original['jobs'];assert [r['index'] for r in old_jobs]==list(range(381))
for r in old_jobs:
i=r['index'];assert r['case']==old['cases'][i]['case'] and r['nodes']==old['cases'][i]['tet_nodes']
path=Path(r['guard_receipt_path']);assert sha(path)==r['guard_receipt_sha256']
raw=json.loads(path.read_text());assert r['worker']==raw['worker'] and r['supervisor_cpu_seconds']==raw['supervisor_cpu_seconds']
assert sha(path.parent/'worker.started.json')==r['worker_started_sha256'] and sha(path.parent/'worker.receipt.json')==r['worker_receipt_sha256']
expected='INFRA_ABORTED' if i in INFRA else 'WALL_LIMIT_FAIL' if i in WALL else 'PASS'
assert r['classification']==expected
if i in INFRA:assert r['worker']['returncode']==-9 and r['worker']['stop_reason'] is None
elif i in WALL:assert r['worker']['stop_reason']=='wall_limit'
else:assert r['worker']['status']=='PASS' and r['worker']['returncode']==0
prior=sum(r['worker']['cpu_seconds'] for r in old_jobs)
assert math.isclose(prior,ledger['prior_worker_cpu_seconds'],rel_tol=1e-12)
assert math.isclose(prior,c['prior_worker_cpu_seconds'],rel_tol=1e-12)
assert math.isclose(sum(r['worker']['cpu_seconds'] for r in old_jobs if r['index'] in INFRA),ledger['prior_aborted_worker_cpu_seconds_included'],rel_tol=1e-12)
assert recovered['status']=='ATTEMPTS_COMPLETE' and recovered['stop_reason'] is None and not recovered['not_run_indices']
assert sorted(r['index'] for r in recovered['jobs'])==list(range(134))
jobs=[dict(r,ready_source_root=str(root)) for r in old_jobs if r['index'] not in INFRA]
for r in recovered['jobs']:
local=r['index'];i=INDICES[local];spec=old['cases'][i]
assert r['case']==spec['case'] and r['original_index']==i
assert r['labelled_infrastructure_recovery']==(i in INFRA)
path=recovery/'jobs'/f'job-{local:04d}'/'guard-result.json';raw=json.loads(path.read_text())
assert r['worker']==raw['worker'] and r['supervisor_cpu_seconds']==raw['supervisor_cpu_seconds']
assert raw['original_index']==i and raw['labelled_infrastructure_recovery']==(i in INFRA)
w=r['worker'];assert math.isfinite(w['cpu_seconds']) and w['cpu_seconds']>=0 and not w['gpu_visible']
assert not (w['returncode']<0 and w['stop_reason'] is None),'Unexplained recovery signal is not a scientific failure'
jobs.append(dict(r,index=i,source_index=local,ready_source_root=str(recovery),guard_receipt_sha256=sha(path),
original_infra_abort=old_jobs[i] if i in INFRA else None))
assert sorted(r['index'] for r in jobs)==list(range(499))
extra=sum(r['worker']['cpu_seconds'] for r in recovered['jobs']);cpu=prior+extra
assert math.isclose(extra,recovered['worker_cpu_seconds'],rel_tol=1e-12)
assert math.isclose(cpu,recovered['cumulative_worker_cpu_seconds'],rel_tol=1e-12)
assert len(c['budget_roots'])==len(set(c['budget_roots']))==3
assert set(c['budget_roots'])=={str(root),str(recovery),str(Path(proof['incident_ledger']['path']).parent)}
used=sum(disk_usage(p) for p in c['budget_roots'])
assert cpu<=60*3600 and used<=100*2**30
return dict(status='ATTEMPTS_COMPLETE',stop_reason=None,jobs=sorted(jobs,key=lambda r:r['index']),not_run_indices=[],
source_provenance=proof,prior_worker_cpu_seconds=prior,recovery_worker_cpu_seconds=extra,worker_cpu_seconds=cpu,
original_infra_abort_CPU_already_included=ledger['prior_aborted_worker_cpu_seconds_included'],disk_bytes=used,
failed=sum(r['worker']['status']!='PASS' for r in jobs),labelled_infrastructure_recoveries=16,
scientific_retries=0,test_labels_read=False,ruling='1794689807.792819')
def load_manifest(path):
saved=json.loads(Path(path).read_text());batch=verify(saved['source_provenance'])
assert batch['jobs']==saved['jobs'] and math.isclose(batch['worker_cpu_seconds'],saved['worker_cpu_seconds'],rel_tol=1e-12)
return batch
def create_manifest(incident,recovery):
proof=dict(original_batch=dict(path=str(incident/'original-batch-infra-aborted.json'),sha256=sha(incident/'original-batch-infra-aborted.json')),
incident_ledger=dict(path=str(incident/'incident-ledger.json'),sha256=sha(incident/'incident-ledger.json')),
recovery_batch=dict(path=str(recovery/'batch-complete.json'),sha256=sha(recovery/'batch-complete.json'),root=str(recovery),contract_sha256=sha(recovery/'contract.json')))
batch=verify(proof);dest=incident/'merged-recovery-terminal.json';pending=dest.with_suffix('.json.pending')
with pending.open('x') as f:json.dump(batch,f,indent=2);f.write('\n');f.flush();os.fsync(f.fileno())
os.link(pending,dest);pending.unlink();return dest
+114
View File
@@ -0,0 +1,114 @@
"""Sequential four-run pilot guard: process-tree RSS/wall plus device VRAM."""
import argparse
import fcntl
import json
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
import psutil
from freeze_g1_components import sha
from s2_recovery_gpu_supervisor import supervise,save,stop_group,disk_usage,tree_usage
from s2_pilot_train import select_capacity
def parse_device_usage(text):
lines=text.strip().splitlines()
if len(lines)!=1:raise ValueError('Expected exactly one GPU')
fields=lines[0].split(',')
if len(fields)!=2:raise ValueError('Malformed GPU usage row')
memory,util=map(lambda s:int(s.strip()),fields)
if memory<0 or not 0<=util<=100:raise ValueError('Invalid GPU counters')
return memory*2**20,util
def device_usage(uuid):
r=subprocess.run(['nvidia-smi','--id='+uuid,'--query-gpu=memory.used,utilization.gpu','--format=csv,noheader,nounits'],check=True,capture_output=True,text=True,timeout=2)
return parse_device_usage(r.stdout)
def active_training_pids(parent,root,index):
ids=[]
try:children=psutil.Process(parent).children(recursive=True)
except psutil.NoSuchProcess:return ids
for p in children:
try:
cmd=p.cmdline()
if str(root) in cmd and (('tools/run_s2_pilot_training.py' in cmd and str(index)==cmd[-1]) or (index==-1 and 'tools/run_s2_pilot_probe.py' in cmd)):ids.append(p.pid)
except psutil.NoSuchProcess:pass
return ids
def guarded_worker(root,spec,i,uuid,wall_limit,command):
run_start=time.monotonic();initial,util=device_usage(uuid)
if initial>128*2**20 or util>0:raise RuntimeError('SELECTED_GPU_BUSY_BEFORE_RUN')
done=threading.Event();monitor=dict(peak_device_memory_bytes=initial,peak_whole_run_tree_rss_bytes=0,max_poll_gap_seconds=0.,reason=None,samples=0)
def watch():
previous=time.monotonic()
while not done.is_set():
now=time.monotonic();monitor['max_poll_gap_seconds']=max(monitor['max_poll_gap_seconds'],now-previous);previous=now
try:
used,_=device_usage(uuid);monitor['samples']+=1;monitor['peak_device_memory_bytes']=max(monitor['peak_device_memory_bytes'],used)
if used>15*2**30:monitor['reason']='DEVICE_VRAM_LIMIT'
_,rss,_=tree_usage(os.getpid());monitor['peak_whole_run_tree_rss_bytes']=max(monitor['peak_whole_run_tree_rss_bytes'],rss)
if rss>16*2**30:monitor['reason']='WHOLE_RUN_HOST_RSS_LIMIT'
if disk_usage(root)>=5*2**30:monitor['reason']='PILOT_DISK_LIMIT'
except Exception as exc:monitor['reason']='GPU_MONITOR_FAILED';monitor['error']=str(exc)
if monitor['reason']:
for pid in active_training_pids(os.getpid(),root,i):stop_group(pid)
done.wait(.5)
thread=threading.Thread(target=watch,daemon=True);thread.start()
try:
wall=wall_limit-(time.monotonic()-run_start)-2.5
if wall<=0:raise RuntimeError('No budget left before spawn')
r=supervise(command,root/'guards',spec['name'],dict(total_cpu_seconds=7200,job_cpu_seconds=wall_limit,job_wall_seconds=wall,
tree_rss_bytes=16*2**30,disk_bytes=5*2**30,max_processes=2),poll=.1,gpu_uuid=uuid)
finally:
done.set();thread.join(timeout=3)
total_wall=time.monotonic()-run_start
result_path=root/spec['name']/'result.json'
result=json.loads(result_path.read_text()) if result_path.exists() else None
if monitor['reason']:r.update(status='STOPPED_OR_FAILED',stop_reason=monitor['reason'])
if total_wall>wall_limit:r.update(status='STOPPED_OR_FAILED',stop_reason='TOTAL_RUN_WALL_LIMIT')
if result and max(result['peak_allocated_bytes'],result['peak_reserved_bytes'])>15*2**30:r.update(status='STOPPED_OR_FAILED',stop_reason='RECORDED_VRAM_LIMIT')
r.update(gpu_visible=True,gpu_uuid=uuid,device_monitor=monitor,total_run_wall_seconds=total_wall,
result_sha256=sha(result_path) if result else None)
save(root/(spec['name']+'-guard-receipt.json'),r)
return r,result
def run(root,prior_wall_seconds=0.):
with (root/'pilot.lock').open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
return run_locked(root,prior_wall_seconds)
def run_locked(root,prior_wall_seconds=0.):
c=json.loads((root/'training-contract.json').read_text());uuid=c['gpu_uuid']
prior_wall_seconds=max(prior_wall_seconds,c.get('probe_guard_wall_seconds',0.))
assert [(r['arm'],r['width'],r['seed']) for r in c['runs']]==[('N',128,0),('E',128,0),('N',256,0),('E',256,0)]
for p,h in c['code_sha256'].items():assert sha(p)==h,p
assert not (root/'pilot-started.json').exists(),'No automatic pilot retry'
start=time.monotonic();save(root/'pilot-started.json',dict(started_unix=time.time(),contract_sha256=sha(root/'training-contract.json')))
rows=[];scores={};reason=None
for i,spec in enumerate(c['runs']):
remaining=7200-prior_wall_seconds-(time.monotonic()-start)
if remaining<=3:reason='TOTAL_PILOT_WALL_LIMIT';break
command=[sys.executable,'tools/run_s2_pilot_training.py',str(root),str(i)]
try:r,result=guarded_worker(root,spec,i,uuid,min(1800,remaining),command)
except Exception as exc:reason=str(exc);break
rows.append(dict(run=spec,**r))
if r['status']!='PASS' or not result or result['status']!='COMPLETE':reason='PILOT_RUN_FAILED_NO_RETRY';break
scores[(spec['arm'],spec['width'])]=result['best_validation_score']
if prior_wall_seconds+time.monotonic()-start>7200:reason='TOTAL_PILOT_WALL_LIMIT_AFTER_EXIT'
selected=select_capacity(scores) if len(scores)==4 and reason is None else None
summary=dict(status='FOUR_RUNS_COMPLETE' if selected else 'PILOT_INCOMPLETE',reason=reason,runs=rows,selected_global_width=selected,
selection_rule='mean of N/E validation error at each width, ties smaller; all four runs required',
pilot_wall_seconds=prior_wall_seconds+time.monotonic()-start,probe_and_setup_wall_seconds=prior_wall_seconds,test_labels_read=False,test_predictions=False,retries=0)
save(root/'pilot-complete.json',summary);print(json.dumps(summary),flush=True)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);a=p.parse_args();run(a.root)
+77
View File
@@ -0,0 +1,77 @@
import json
from pathlib import Path
import tempfile
import unittest
from freeze_g1_components import sha
from s2_incident_recovery_manifest import create_manifest,load_manifest,verify
from prepare_s2_incident_recovery import INFRA,WALL,UNATTEMPTED,INDICES
def put(path,value):path.parent.mkdir(parents=True,exist_ok=True);path.write_text(json.dumps(value))
class RecoveryMergeTests(unittest.TestCase):
def fixture(self,base):
original=base/'original';incident=base/'incident';recovery=base/'recovery'
for p in [original,incident,recovery]:p.mkdir()
cases=[dict(case=f'case-{i}',tet_nodes=i+1) for i in range(499)]
for root in [original,recovery]:put(root/'role-manifest.json',dict(learning_parts=[s['case'] for s in cases[:387]],validation_parts=[s['case'] for s in cases[387:]],sealed_test_parts=['sealed']))
old=dict(cases=cases,code_sha256={},role_manifest_sha256=sha(original/'role-manifest.json'))
put(original/'contract.json',old);put(original/'batch-started.json',{});put(original/'progress.json',dict(completed=365,active=INFRA,next_index=381))
rows=[]
for i in range(381):
status='INFRA_ABORTED' if i in INFRA else 'WALL_LIMIT_FAIL' if i in WALL else 'PASS'
w=dict(status='PASS' if status=='PASS' else 'STOPPED_OR_FAILED',returncode=0 if status=='PASS' else -9,
stop_reason='wall_limit' if i in WALL else None,cpu_seconds=1.,gpu_visible=False)
folder=original/'jobs'/f'job-{i:04d}';put(folder/'guard-result.json',dict(worker=w,supervisor_cpu_seconds=.01))
put(folder/'worker.started.json',{});put(folder/'worker.receipt.json',w)
rows.append(dict(index=i,case=cases[i]['case'],nodes=i+1,classification=status,worker=w,supervisor_cpu_seconds=.01,
guard_receipt_path=str(folder/'guard-result.json'),guard_receipt_sha256=sha(folder/'guard-result.json'),
worker_started_sha256=sha(folder/'worker.started.json'),worker_receipt_sha256=sha(folder/'worker.receipt.json')))
snapshot=incident/'original-batch-infra-aborted.json'
put(snapshot,dict(status='INFRA_ABORTED',original_root=str(original),original_contract_sha256=sha(original/'contract.json'),batch_started_sha256=sha(original/'batch-started.json'),last_progress_sha256=sha(original/'progress.json'),jobs=rows))
quarantine=incident/'quarantine-receipt.json'
put(quarantine,dict(status='ALL_16_PARTIALS_MOVED_AND_HASH_VERIFIED',reused_by_recovery=False,moves=[dict(original_index=i,kind=k,from_path=str(original/k/cases[i]['case']),to_path=str(incident/'quarantine'/k/cases[i]['case']),files=[]) for i in INFRA for k in ['parts','ready']]))
ledger=incident/'incident-ledger.json'
put(ledger,dict(original_snapshot=str(snapshot),original_snapshot_sha256=sha(snapshot),quarantine_receipt=str(quarantine),quarantine_receipt_sha256=sha(quarantine),recovery_indices=INDICES,infra_aborted_indices=INFRA,wall_limit_indices=WALL,unattempted_indices=UNATTEMPTED,prior_worker_cpu_seconds=381.,prior_aborted_worker_cpu_seconds_included=16.))
c=dict(cases=[cases[i] for i in INDICES],original_indices=INDICES,infra_aborted_indices=INFRA,original_root=str(original),original_contract_sha256=sha(original/'contract.json'),incident_ledger=str(ledger),incident_ledger_sha256=sha(ledger),original_snapshot=str(snapshot),original_snapshot_sha256=sha(snapshot),role_manifest_sha256=old['role_manifest_sha256'],code_sha256={},prior_worker_cpu_seconds=381.,budget_roots=[str(original),str(incident),str(recovery)],limits=dict(worker_cpu_hours=60,workers=16,disk_bytes=100*2**30,per_part_wall_seconds=1800,per_part_tree_rss_bytes=1342177280,retries=0,replacements=0))
put(recovery/'contract.json',c);jobs=[]
for local,i in enumerate(INDICES):
w=dict(status='PASS',returncode=0,stop_reason=None,cpu_seconds=1.,gpu_visible=False)
r=dict(worker=w,supervisor_cpu_seconds=.01,original_index=i,labelled_infrastructure_recovery=i in INFRA)
put(recovery/'jobs'/f'job-{local:04d}'/'guard-result.json',r);jobs.append(dict(index=local,case=cases[i]['case'],**r))
put(recovery/'batch-complete.json',dict(status='ATTEMPTS_COMPLETE',stop_reason=None,not_run_indices=[],jobs=jobs,worker_cpu_seconds=134.,cumulative_worker_cpu_seconds=515.))
return original,incident,recovery
def test_three_sources_499_outcomes_keep_abort_cpu_once_and_no_fake_original_terminal(self):
with tempfile.TemporaryDirectory() as tmp:
original,incident,recovery=self.fixture(Path(tmp));path=create_manifest(incident,recovery);r=load_manifest(path)
self.assertEqual(len(r['jobs']),499);self.assertEqual(r['failed'],3);self.assertEqual(r['worker_cpu_seconds'],515.)
self.assertEqual(sum(j['worker']['cpu_seconds'] for j in r['jobs']),499.)
self.assertEqual(r['original_infra_abort_CPU_already_included'],16.)
self.assertIsNotNone(r['jobs'][INFRA[0]]['original_infra_abort']);self.assertFalse((original/'batch-complete.json').exists())
with self.assertRaises(FileExistsError):create_manifest(incident,recovery)
def test_reject_wrong_index_set_changed_specs_or_duplicate_budget(self):
for kind in ['index','spec','double_count','missing_terminal','fake_original','global_stop']:
with self.subTest(kind=kind),tempfile.TemporaryDirectory() as tmp:
original,incident,recovery=self.fixture(Path(tmp))
if kind=='fake_original':put(original/'batch-complete.json',{})
elif kind in ['index','spec']:
path=recovery/'contract.json';c=json.loads(path.read_text())
if kind=='index':c['original_indices'][0]=0
else:c['cases'][0]['tet_nodes']+=1
put(path,c)
else:
path=recovery/'batch-complete.json';b=json.loads(path.read_text())
if kind=='double_count':b['cumulative_worker_cpu_seconds']+=16.
elif kind=='global_stop':b.update(status='STOPPED',stop_reason='GLOBAL_CPU_LIMIT')
else:b['jobs'].pop()
put(path,b)
with self.assertRaises(AssertionError):create_manifest(incident,recovery)
def test_hash_bound_source_mutation_rejected(self):
with tempfile.TemporaryDirectory() as tmp:
original,incident,recovery=self.fixture(Path(tmp));path=create_manifest(incident,recovery)
put(original/'jobs/job-0000/guard-result.json',{})
with self.assertRaises(AssertionError):load_manifest(path)
if __name__=='__main__':unittest.main(verbosity=2)
+14
View File
@@ -0,0 +1,14 @@
"""Run the existing synthetic guard scenarios against the recovered guard copy."""
import unittest
import test_s2_pilot_gpu_guard as scenarios
import s2_recovered_pilot_gpu_guard as recovered
from s2_recovery_gpu_supervisor import supervise
scenarios.guard=recovered
scenarios.supervise=supervise
scenarios.parse_device_usage=recovered.parse_device_usage
if __name__=='__main__':
print('Targets: s2_recovered_pilot_gpu_guard and s2_recovery_gpu_supervisor; synthetic only, no GPU')
result=unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(scenarios.GPUUsageTests))
raise SystemExit(not result.wasSuccessful())