Fix Track A recovery projection isolation and bounded prestart deadline

This commit is contained in:
MeltAstra committed 2026-11-18 19:52:43 +08:00
1 parent ef46d35772
commit 0886d459e6
65 files changed
+25625 -46

No files matched your search

+75
View File
@@ -133,6 +133,81 @@ class RecoveryTests(unittest.TestCase):
ns['dispatch']();ns['dispatch']();self.assertFalse(calls);ns['dispatch']()
self.assertEqual(calls,[(4,'THREE_FAILED_DISPATCH_GPU_SAMPLES')]);self.assertIs(active[3],other)
def test_extreme_rejected_projection_cannot_stop_affordable_survivor(self):
from types import SimpleNamespace
from track_a_recovery_common import project_cell
tree=ast.parse((B/'tools/track_a_recovery_queue.py').read_text());node=next(n for n in ast.walk(tree) if isinstance(n,ast.For) and ast.unparse(n.iter)=='list(active)')
with tempfile.TemporaryDirectory() as t:
root=Path(t);save(root/'contract.json',{})
for i in [3,4]:(root/'jobs'/str(i)/'worker/history').mkdir(parents=True)
save(root/'jobs/3/worker/history/001.json',dict(epoch=1,train_epoch_seconds=1000))
save(root/'jobs/4/worker/history/001.json',dict(epoch=1,train_epoch_seconds=50))
own=[];glob=[]
def stop(i,why):own.append((i,why));save(root/'jobs'/str(i)/'stop.json',dict(reason=why))
ns=dict(root=root,c=self.cfg(),active={3:object(),4:object()},terminal={},estimates={},last_epoch={},read=lambda p:json.loads(p.read_text()),save=save,sha=sha,age=lambda:100,live=lambda:{3:160,4:160},project_cell=project_cell,project_total=project_total,time=SimpleNamespace(time=lambda:0),own_stop=stop,global_stop=glob.append)
exec(compile(ast.fix_missing_locations(ast.Module(body=[node],type_ignores=[])),'actual_epoch_block','exec'),ns)
self.assertEqual(own,[(3,'OWN_PROJECTED_CAP')]);self.assertFalse(glob)
failed=json.loads((root/'jobs/3/first-epoch-projection.json').read_text());healthy=json.loads((root/'jobs/4/first-epoch-projection.json').read_text())
self.assertEqual(failed['cell']['projected_gpu_seconds'],249030);self.assertEqual(failed['status'],'STOP_OWN_COST_PROJECTION')
self.assertEqual(failed['total']['cumulative_projected_gpu_seconds'],OLD+30960+30960+7200)
self.assertEqual(healthy['status'],'PASS');self.assertFalse((root/'jobs/4/stop.json').exists())
self.assertEqual(ns['estimates'][3]['projected_gpu_seconds'],249030)
def test_stopping_reserve_keeps_actual_and_terminal_settles_once(self):
p=project_total(self.cfg(),{3:dict(projected_gpu_seconds=249030)}, {},{3:40000},stopping={3})
self.assertEqual(p['rows'][0]['projected_gpu_seconds'],40000)
self.assertEqual(p['rows'][0]['basis'],'locally_stopping_own_cap_or_actual')
p=project_total(self.cfg(),{3:dict(projected_gpu_seconds=249030)},{3:dict(gpu_seconds_charged=190)}, {},stopping={3})
self.assertEqual(p['rows'][0]['projected_gpu_seconds'],190);self.assertEqual(p['rows'][0]['basis'],'terminal_actual')
def test_true_cumulative_overrun_still_stops_after_local_rejection(self):
p=project_total(self.cfg(),{3:dict(projected_gpu_seconds=249030)}, {},{3:130000,4:500},stopping={3})
self.assertEqual(p['status'],'STOP_CUMULATIVE_BUDGET');self.assertGreater(p['cumulative_projected_gpu_seconds'],162000)
def idle_replay(self,clock,query,cap,sleep):
from types import SimpleNamespace
from track_a_recovery_guard import require_prestart_window
tree=ast.parse((B/'tools/track_a_recovery_guard.py').read_text());node=next(n for n in ast.walk(tree) if isinstance(n,ast.While) and ast.unparse(n.test)=='success < 3')
with tempfile.TemporaryDirectory() as t:
root=Path(t);monitor=Monitor(root/'errors.jsonl')
ns=dict(root=root,queue=root,requested=[],monitor=monitor,success=0,samples=[],device_usage=query,job=dict(gpu_uuid='SYNTHETIC',gpu_seconds=cap),elapsed=clock,require_prestart_window=require_prestart_window,time=SimpleNamespace(time=clock,sleep=sleep),save=save)
started=False
try:
exec(compile(ast.fix_missing_locations(ast.Module(body=[node],type_ignores=[])),'actual_idle_loop','exec'),ns)
started=True
except RuntimeError as exc:reason=str(exc)
else:reason=None
return dict(worker_would_start=started,reason=reason,policy=monitor.policy(),errors=list(monitor.records),successes=ns['success'])
def test_already_expired_prestart_makes_zero_queries(self):
calls=[]
d=self.idle_replay(lambda:30961,lambda u:calls.append(u),30960,lambda s:None)
self.assertEqual(calls,[]);self.assertFalse(d['worker_would_start']);self.assertEqual(d['reason'],'PRESTART_OWN_DEADLINE_NO_WORKER_STARTED')
def test_alternating_two_errors_one_idle_expires_without_worker(self):
clock=[60.];calls=[]
def query(u):
calls.append(u);clock[0]+=10
if len(calls)%3:raise TimeoutError('synthetic recoverable')
return 0,0
def sleep(s):clock[0]+=s
d=self.idle_replay(lambda:clock[0],query,160,sleep)
self.assertFalse(d['worker_would_start']);self.assertEqual(d['reason'],'PRESTART_OWN_DEADLINE_NO_WORKER_STARTED')
self.assertFalse(d['policy']['failed']);self.assertEqual(d['policy']['max_streaks']['gpu_usage'],2)
self.assertLess(clock[0],160);self.assertLessEqual(len(calls),7);self.assertGreater(len(d['errors']),3)
def test_prestart_checks_after_query_overrun(self):
clock=[60.];calls=[]
def query(u):calls.append(u);clock[0]=85;return 0,0
d=self.idle_replay(lambda:clock[0],query,100,lambda s:None)
self.assertFalse(d['worker_would_start']);self.assertEqual(len(calls),1);self.assertEqual(d['reason'],'PRESTART_OWN_DEADLINE_NO_WORKER_STARTED')
def test_prestart_checks_before_idle_sleep(self):
clock=[60.];sleeps=[]
def query(u):clock[0]=79.5;return 0,0
d=self.idle_replay(lambda:clock[0],query,100,sleeps.append)
self.assertFalse(d['worker_would_start']);self.assertEqual(sleeps,[]);self.assertEqual(d['successes'],1)
def test_fast_local_guard_not_blocked_on_gpu_query(self):
tree=ast.parse((B/'tools/track_a_recovery_guard.py').read_text());local=next(n for n in ast.walk(tree) if isinstance(n,ast.FunctionDef) and n.name=='local_watch')
self.assertNotIn('device_usage',ast.unparse(local));self.assertIn('WHOLE_TREE_RSS_LIMIT',ast.unparse(local));self.assertIn('OUTPUT_DISK_LIMIT',ast.unparse(local));self.assertIn('RECORDED_VRAM_LIMIT',(B/'tools/track_a_recovery_guard.py').read_text())
+12 -4
View File
@@ -76,13 +76,21 @@ def accepted_guard(rc,g):
and not w['monitor_policy']['failed'] and w['monitor_policy']['errors']==w['monitor_errors'])
def project_total(c,estimates,terminal,live):
if (set(estimates)|set(terminal)|set(live))-set(RECOVERY):raise ValueError('Unknown recovery fold')
def project_total(c,estimates,terminal,live,stopping=None):
stopping=set(stopping or [])
if (set(estimates)|set(terminal)|set(live)|stopping)-set(RECOVERY):raise ValueError('Unknown recovery fold')
rows=[];new=c['postfit_gpu_reserve']
for i in RECOVERY:
value=terminal[i]['gpu_seconds_charged'] if i in terminal else max(live.get(i,0),estimates.get(i,{}).get('projected_gpu_seconds',c['jobs'][i]['gpu_seconds']))
if i in terminal:
value=terminal[i]['gpu_seconds_charged'];basis='terminal_actual'
elif i in stopping:
# No rejected future training remains scheduled. Retain the full
# originally approved own cap for bounded cleanup until actual exit.
value=max(live.get(i,0),c['jobs'][i]['gpu_seconds']);basis='locally_stopping_own_cap_or_actual'
else:
value=max(live.get(i,0),estimates.get(i,{}).get('projected_gpu_seconds',c['jobs'][i]['gpu_seconds']));basis='continuing_projection_or_pending_cap'
if not math.isfinite(value) or value<0:raise ValueError('Invalid new charge')
new+=value;rows.append(dict(id=i,projected_gpu_seconds=value))
new+=value;rows.append(dict(id=i,projected_gpu_seconds=value,basis=basis))
# Per-cell excess is isolated by own stop.json; total exhaustion stays global.
return dict(status='PASS' if OLD+new<=c['gpu_cap'] else 'STOP_CUMULATIVE_BUDGET',rows=rows,new_projected_gpu_seconds=new,old_gpu_seconds_once=OLD,cumulative_projected_gpu_seconds=OLD+new,postfit_reserve=c['postfit_gpu_reserve'])
+17 -2
View File
@@ -1,5 +1,5 @@
"""Isolated recovery fold: 10s GPU samples, three failures; fast local guards stay live."""
import fcntl,json,os,resource,signal,sys,threading,time
import fcntl,json,math,os,resource,signal,sys,threading,time
from pathlib import Path
import psutil
from phase2_h1_worker_v2 import save,sha
@@ -9,6 +9,15 @@ from track_a_recovery_supervisor import supervise,tree_usage,stop_group,disk_usa
from s2_main_memory_guard import PeakRecords
def require_prestart_window(elapsed,cap,next_seconds=0):
"""Reserve bounded query/sleep plus20s cleanup inside the remaining own cap."""
if any(not math.isfinite(v) or v<0 for v in [elapsed,cap,next_seconds]):
raise ValueError('Invalid prestart deadline')
if elapsed+next_seconds+20>=cap:
raise RuntimeError('PRESTART_OWN_DEADLINE_NO_WORKER_STARTED')
def run(queue,fold):
contract,_=config(queue)
if fold not in contract['recovery_folds']:raise PermissionError('Only fresh folds3/4')
@@ -62,16 +71,22 @@ def run(queue,fold):
samples=[];success=0
while success<3:
if requested or (root/'stop.json').exists() or (queue/'global-stop.json').exists():raise RuntimeError('STOP_BEFORE_START')
require_prestart_window(elapsed(),job['gpu_seconds'],10)
value,ok=monitor.sample('gpu_usage',lambda:device_usage(job['gpu_uuid']))
require_prestart_window(elapsed(),job['gpu_seconds'])
if not ok:
success=0
if monitor.failed:raise RuntimeError('THREE_CONSECUTIVE_IDLE_SAMPLE_FAILURES')
require_prestart_window(elapsed(),job['gpu_seconds'],.5)
time.sleep(.5);continue
samples.append(dict(unix=time.time(),memory_bytes=value[0],utilization=value[1]))
save(root/'idle-polls.json',samples)
if value[0]>128*2**20 or value[1]!=0:raise RuntimeError('SELECTED_GPU_BECAME_BUSY_NO_WORKER_STARTED')
success+=1
if success<3:time.sleep(2)
if success<3:
require_prestart_window(elapsed(),job['gpu_seconds'],2)
time.sleep(2)
require_prestart_window(elapsed(),job['gpu_seconds'])
for fn in [local_watch,gpu_watch]:
t=threading.Thread(target=fn,daemon=True);t.start();threads.append(t)
remaining=job['gpu_seconds']-elapsed()-20
+6 -2
View File
@@ -89,11 +89,15 @@ def run(root):
rows=[read(p) for p in sorted((root/'jobs'/str(i)/'worker/history').glob('*.json'))]
if rows and rows[-1]['epoch']>last_epoch.get(i,0):
epoch=rows[-1]['epoch'];cell=project_cell(c['jobs'][i],dict(epoch=epoch,max_epoch_seconds=max(r['train_epoch_seconds'] for r in rows),charged=60+age()))
estimates[i]=cell;total=project_total(c,estimates,terminal,live())
estimates[i]=cell
# Isolate the rejected cell before budgeting future work.
# Its raw estimate is retained in estimates/result unchanged.
if not cell['within_cap']:own_stop(i,'OWN_PROJECTED_CAP')
stopping={j for j in active if (root/'jobs'/str(j)/'stop.json').exists()}
total=project_total(c,estimates,terminal,live(),stopping=stopping)
result=dict(status='PASS' if cell['within_cap'] and total['status']=='PASS' else 'STOP_OWN_COST_PROJECTION',cell=cell,total=total,contract_sha256=sha(root/'contract.json'),unix=time.time())
name='first-epoch-projection.json' if i not in last_epoch else 'latest-cost-projection.json'
save(root/'jobs'/str(i)/name,result);save(root/'latest-cost-projection.json',total);last_epoch[i]=epoch
if not cell['within_cap']:own_stop(i,'OWN_PROJECTED_CAP')
if total['status']!='PASS':global_stop('CUMULATIVE_PROJECTED_CAP')
if not (root/'global-stop.json').exists():dispatch()
else: