c528dd268f
Include callable skill and live-GUI prerequisites, epoch sensor reads, packed snapshots, sampled bit-exact kinematics, and verified-tick rendering without changing the physical/control schedule. Record bounded analytic S1 GUI/headless qualification, original failures and CPU evidence (1557 passed, 6 skipped). Preserve accepted_skill=false and sub-real-time limitations. Exclude native authorities, caches, large media and local delivery copies; retain sealed artifact digest.
249 lines
13 KiB
Python
249 lines
13 KiB
Python
"""CPU ONLY: exact GPU decision equivalence, fixed matrix, pairing and lifecycle."""
|
|
import copy
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'scripts'))
|
|
import functional_followup_launch_v3 as f
|
|
import functional_gpu_watch_v3 as watch
|
|
import evaluate_cycle_functional_flow as runner
|
|
|
|
|
|
def test_exact_plan_matrix_and_budget():
|
|
p = f.plan()
|
|
rows = f.api().slots(p)
|
|
commands = f.api().commands(p)
|
|
assert len(rows) == 14 and sum(r['cycles'] * 4500 for r in rows) == 175500
|
|
assert p['limits']['max_physics_calls'] == 175500 + 13 * 250
|
|
assert p['limits']['max_campaign_seconds'] == 300 + 13 * 480
|
|
assert len(commands) == 7
|
|
for delta in list(commands.values())[1:]:
|
|
assert .001 < delta[0] <= .025 and .001 < delta[1] <= .020 and delta[2] == 0
|
|
assert (delta[0]**2 + delta[1]**2)**.5 == pytest.approx(.016 if '16mm' in next(k for k,v in commands.items() if v == delta) else .024)
|
|
assert rows[1]['command_id'] == 'validated_nominal'
|
|
for a,b in zip(rows[2::2], rows[3::2], strict=True):
|
|
assert a['pair_group'] == b['pair_group'] == a['command_id'] == b['command_id']
|
|
assert (a['controller_kind'], b['controller_kind']) == ('analytic_reference','learned_policy')
|
|
|
|
|
|
@pytest.mark.parametrize('field,value', [('execution_authorized',True),('seed',94501),('noise',True),('cycles_per_run',1)])
|
|
def test_no_silent_plan_or_gate_change(field,value):
|
|
p = copy.deepcopy(f.plan());p[field]=value
|
|
with pytest.raises(ValueError):f.api().validate_plan(p)
|
|
|
|
|
|
def test_protocol_three_cycles_commands_and_seams_unchanged_math():
|
|
api=f.api()
|
|
from_module = __import__(api.__package__ + '.functional_flow_v2',fromlist=['load_contract'])
|
|
base=from_module.load_contract(ROOT / f.old.CONFIG)
|
|
reference=from_module.FunctionalFlowProtocol(base,cycles=3,controller_kind='analytic_reference')
|
|
original=api.FollowupProtocol(base,f.plan(),'validated_nominal','learned_policy')
|
|
kwargs=dict(anchor_a_world=(.1,.2,.022),root_origin_world=(0,0,.35),weight_N=52.8597)
|
|
for tick in range(1,13501):
|
|
a=reference.evidence_clock(0,tick);b=original.evidence_clock(0,tick)
|
|
assert a==b
|
|
assert reference.command(0,a,**kwargs)==original.command(0,b,**kwargs)
|
|
for name in list(api.commands(f.plan()))[1:]:
|
|
proto=api.FollowupProtocol(base,f.plan(),name,'analytic_reference')
|
|
assert 'P1_margins' not in proto.document['thresholds']
|
|
for tick in (4500,9000):
|
|
old=proto.command(0,proto.evidence_clock(0,tick),**kwargs)
|
|
new=proto.command(0,proto.next_command_clock(0,tick,seam_admitted=True),**kwargs)
|
|
assert old.target_world_m==new.target_world_m
|
|
assert old.target_velocity_world_m_s==new.target_velocity_world_m_s
|
|
|
|
|
|
@pytest.mark.parametrize('field', ['state','RNG','ik','command','observation'])
|
|
def test_pair_mismatch_fails_without_repair(field):
|
|
initial={field:{'sha':'A'}};other=copy.deepcopy(initial);other[field]['sha']='B'
|
|
assert f.require_pair(initial,copy.deepcopy(initial))
|
|
with pytest.raises(RuntimeError,match='before_rollout'):f.require_pair(other,initial)
|
|
assert other[field]['sha']=='B'
|
|
|
|
|
|
def receipt(slot):
|
|
if slot['cycles']==0:
|
|
return {'success':True,'environment_constructed':False,'physics_counts':{'attempted_steps':0,'completed_steps':0},'preclose_identity_verified':True}
|
|
return {'success':True,'preclose_identity_verified':True,'runtime_continuity_verified':True,
|
|
'controller_kind':slot['controller_kind'],'command_id':slot['command_id'],'cycles_requested':3,
|
|
'physics_counts':{'rollout_steps':13500,'initialization_steps':0,'attempted_steps':13500,'completed_steps':13500},
|
|
'runtime_stop':{'reason':'protocol_complete','causes':[],'clock':{'global_tick':13500}},'hook_violations':[],
|
|
'initial_pair_matched':slot['controller_kind']=='learned_policy','initial_pair_sha256':'same'}
|
|
|
|
|
|
@pytest.mark.parametrize('fault',['success','runtime_continuity_verified','preclose_identity_verified','controller_kind','command_id','cycles_requested','stop','count','hook'])
|
|
def test_physics_alone_never_qualifies_complete_receipt(fault):
|
|
s=f.api().slots(f.plan())[1];r=receipt(s)
|
|
assert f.complete_receipt(r,s)
|
|
if fault=='stop':r['runtime_stop']['reason']='failure'
|
|
elif fault=='count':r['physics_counts']['completed_steps']=13501
|
|
elif fault=='hook':r['hook_violations']=['reset']
|
|
elif fault in ('controller_kind','command_id'):r[fault]='wrong'
|
|
else:r[fault]=False
|
|
assert not f.complete_receipt(r,s)
|
|
|
|
|
|
def test_comparison_needs_both_supervisions_and_exact_pair():
|
|
a,b=f.api().slots(f.plan())[2:4]
|
|
r={'success':True,'worker':receipt(a)};u={'success':True,'worker':receipt(b)}
|
|
assert f.paired_comparison(r,u)['eligible']
|
|
u['success']=False
|
|
assert not f.paired_comparison(r,u)['eligible']
|
|
u['success']=True;u['worker']['initial_pair_sha256']='different'
|
|
assert not f.paired_comparison(r,u)['eligible']
|
|
|
|
|
|
@pytest.fixture
|
|
def gpu(monkeypatch,tmp_path):
|
|
base=watch.base;lib=tmp_path/'nvml.so';lib.write_bytes(b'mock')
|
|
desktop={'pid':7,'starttime':123,'sha256':'hash'}
|
|
identity={'library':str(lib),'sha256':base.b.digest(lib),'uuid':'GPU-test','index':0,'desktop_clients':[desktop]}
|
|
clients={'compute':set(),'graphics':{7}}
|
|
monkeypatch.setattr(base.ctypes,'CDLL',lambda _:object())
|
|
def call(self,name,*args):
|
|
if name=='nvmlDeviceGetUUID':args[1].value=b'GPU-test'
|
|
monkeypatch.setattr(base.GPUOwnership,'call',call)
|
|
monkeypatch.setattr(base.GPUOwnership,'clients',lambda _:clients)
|
|
monkeypatch.setattr(base,'desktop_identity',lambda pid,hash_executable=True:dict(desktop) if hash_executable else {k:v for k,v in desktop.items() if k!='sha256'})
|
|
monkeypatch.setattr(base.owner,'process_table',lambda:{7:(123,1,1,'S'),99:(456,1,1,'S')})
|
|
owned=SimpleNamespace(known={(99,456)},discover=lambda:{99:(456,1,1,'S')})
|
|
events=[];observed=watch.ObservedGPUOwnership(identity,events.append)
|
|
return SimpleNamespace(base=base,identity=identity,clients=clients,owned=owned,events=events,observed=observed)
|
|
|
|
|
|
@pytest.mark.parametrize('compute,graphics,final,passes',[(set(),{7},False,True),({99},{7,99},False,True),
|
|
({8},{7},False,False),(set(),{7,8},False,False),({7},{7},False,False),({99},{7},True,False),(set(),{7},True,True)])
|
|
def test_observer_keeps_exact_existing_gpu_decisions(gpu,compute,graphics,final,passes):
|
|
direct=gpu.base.GPUOwnership(gpu.identity)
|
|
gpu.clients.update(compute=compute,graphics=graphics)
|
|
if passes:
|
|
assert direct.check(gpu.owned,final=final)==gpu.observed.check(gpu.owned,final=final)
|
|
else:
|
|
with pytest.raises(RuntimeError) as old:direct.check(gpu.owned,final=final)
|
|
with pytest.raises(RuntimeError) as new:gpu.observed.check(gpu.owned,final=final)
|
|
assert str(old.value)==str(new.value)
|
|
sample=gpu.events[-1]['recent_checks'][-1]
|
|
assert sample['nvml_clients']=={'compute':sorted(compute),'graphics':sorted(graphics)}
|
|
assert sample['active_owned']=={'99':[456,1,1,'S']}
|
|
assert sample['owned_known']==[[99,456]] and sample['error']
|
|
|
|
|
|
def test_reproduced_query_then_exit_race_stays_failure_not_retrospective_excuse(gpu,monkeypatch):
|
|
gpu.clients['compute']={99}
|
|
gpu.owned.discover=lambda:{}
|
|
monkeypatch.setattr(gpu.base.owner,'process_table',lambda:{7:(123,1,1,'S')})
|
|
with pytest.raises(RuntimeError,match='GPU ownership'):gpu.observed.check(gpu.owned)
|
|
sample=gpu.events[-1]['recent_checks'][-1]
|
|
assert sample['nvml_clients']['compute']==[99] and sample['active_owned']=={}
|
|
assert sample['owned_known']==[[99,456]] and sample['proc_after_failure']['99'] is None
|
|
|
|
|
|
def test_reused_owned_pid_is_still_rejected_and_recorded(gpu,monkeypatch):
|
|
gpu.clients['compute']={99};gpu.owned.discover=lambda:{}
|
|
monkeypatch.setattr(gpu.base.owner,'process_table',lambda:{99:(999,1,1,'S')})
|
|
with pytest.raises(RuntimeError,match='GPU ownership'):gpu.observed.check(gpu.owned)
|
|
sample=gpu.events[-1]['recent_checks'][-1]
|
|
assert sample['owned_known']==[[99,456]] and sample['proc_after_failure']['99'][0]==999
|
|
|
|
|
|
def test_library_drift_fails_before_query(gpu):
|
|
Path(gpu.identity['library']).write_bytes(b'drift')
|
|
with pytest.raises(RuntimeError,match='NVML drift'):gpu.observed.check(gpu.owned)
|
|
assert 'nvml_clients' not in gpu.events[-1]['recent_checks'][-1]
|
|
|
|
|
|
def test_diagnostic_storage_failure_is_not_ignored(gpu):
|
|
def fail(_):raise OSError('cannot publish diagnostics')
|
|
gpu.observed.emit=fail
|
|
with pytest.raises(OSError,match='cannot publish'):gpu.observed.check(gpu.owned,final=True)
|
|
|
|
|
|
def test_after_failure_proc_read_error_never_replaces_original_gpu_failure(gpu,monkeypatch):
|
|
gpu.clients['compute']={8}
|
|
def fail():raise PermissionError('after-check read denied')
|
|
monkeypatch.setattr(gpu.base.owner,'process_table',fail)
|
|
with pytest.raises(RuntimeError,match='GPU ownership'):gpu.observed.check(gpu.owned)
|
|
assert 'proc_after_failure_error' in gpu.events[-1]['recent_checks'][-1]
|
|
|
|
|
|
def test_changed_desktop_or_nvml_error_is_not_waived(gpu,monkeypatch):
|
|
monkeypatch.setattr(gpu.base,'desktop_identity',lambda *a,**k:{'starttime':999})
|
|
with pytest.raises(RuntimeError,match='identity changed'):gpu.observed.check(gpu.owned)
|
|
def fail(_):raise RuntimeError('NVML query failed')
|
|
monkeypatch.setattr(gpu.base.GPUOwnership,'clients',fail)
|
|
with pytest.raises(RuntimeError,match='NVML query failed'):gpu.observed.check(gpu.owned)
|
|
|
|
|
|
def test_no_grant_no_launch_or_directory_creation(tmp_path):
|
|
path=tmp_path/'not-granted.json';path.write_text(json.dumps({'format':f.old.FORMAT}))
|
|
root=tmp_path/'new-root'
|
|
with pytest.raises(PermissionError):f.approval(path,f.old.b.digest(path),root)
|
|
assert not root.exists()
|
|
|
|
|
|
@pytest.mark.parametrize('fault,expected_rows',[(None,14),('nominal_supervision',2),('pair_supervision',4),('missing_result',2)])
|
|
def test_mock_campaign_order_first_failure_and_no_retry(tmp_path,monkeypatch,fault,expected_rows):
|
|
old=f.old;plan=f.plan();slots=f.api().slots(plan);run=tmp_path/'mock-only'
|
|
approval={'limits':plan['limits'],'sources':f.sources(),'gpu_identity':{}}
|
|
monkeypatch.setattr(f,'approval',lambda *a:approval)
|
|
monkeypatch.setattr(runner.ctypes,'CDLL',lambda *a,**k:SimpleNamespace(prctl=lambda *a:0))
|
|
monkeypatch.setattr(old,'native_policy',lambda *a,**k:{})
|
|
monkeypatch.setattr(old,'AsyncMonitor',lambda p:SimpleNamespace(monitor=True,error=None,check=lambda:None,
|
|
stop=SimpleNamespace(set=lambda:None),report=lambda:{'error':None}))
|
|
class Owned:
|
|
known=set()
|
|
def attach(self,child):pass
|
|
def discover(self):return {}
|
|
monkeypatch.setattr(old.owner,'OwnedProcesses',Owned)
|
|
monkeypatch.setattr(old.owner,'cleanup_group',lambda *a,**k:True)
|
|
monkeypatch.setattr(old.owner,'StdoutCapture',lambda *a:SimpleNamespace(check=lambda:None,close=lambda:None,pump=lambda:None))
|
|
monkeypatch.setattr(old,'authenticate',lambda *a:None)
|
|
monkeypatch.setattr(runner,'filesystem_verify',lambda _: {'scope':'CPU mock only'})
|
|
class GPU:
|
|
def __init__(self,*a):pass
|
|
def check(self,*a,**k):return {'clean':True}
|
|
monkeypatch.setattr(watch,'ObservedGPUOwnership',GPU)
|
|
calls=[]
|
|
class Child:
|
|
returncode=0;stdout=None
|
|
def __init__(self,*args,**kwargs):
|
|
i=len(calls);s=slots[i];calls.append(s['slot']);folder=run/s['slot']
|
|
r=receipt(s)
|
|
if i==0:
|
|
(folder/'binding.json').write_text(json.dumps({'format':'skillfactory.functional-followup-binding.v3',
|
|
'contract_sha256':approval['sources'][old.CONFIG],'plan_sha256':approval['sources'][f.PLAN]}))
|
|
(folder/'inventory.json').write_text('{}')
|
|
else:
|
|
for file in ['trace.pt','initial-state.pt','events-and-seams.json','initial-pair.json']:
|
|
if fault=='missing_result' and i==1 and file=='trace.pt':continue
|
|
(folder/file).write_text('CPU MOCK, NOT PHYSICS')
|
|
r['initial_pair_sha256']=old.b.digest(folder/'initial-pair.json')
|
|
(folder/'worker-result.json').write_text(json.dumps(r))
|
|
def poll(self):
|
|
if (fault=='nominal_supervision' and len(calls)==2 or fault=='pair_supervision' and len(calls)==4):
|
|
# Handshake failure is a supervisor failure; worker physics flag stays true.
|
|
return None
|
|
return 0
|
|
def wait(self,**kwargs):return 0
|
|
monkeypatch.setattr(runner.subprocess,'Popen',Child)
|
|
if fault in ('nominal_supervision','pair_supervision'):
|
|
def auth(*a):
|
|
if (fault=='nominal_supervision' and len(calls)==2 or fault=='pair_supervision' and len(calls)==4):
|
|
raise RuntimeError('CPU mocked GPU supervisor failure')
|
|
monkeypatch.setattr(old,'authenticate',auth)
|
|
args=SimpleNamespace(output=run,approval=tmp_path/'unused',trusted_approval_sha256='mock',followup_v3=True)
|
|
code=runner.campaign(args)
|
|
result=json.loads((run/'campaign-result.json').read_bytes())
|
|
assert len(calls)==len(result['rows'])==expected_rows
|
|
assert calls==[s['slot'] for s in slots[:expected_rows]]
|
|
assert result['success']==(fault is None) and code==(0 if fault is None else 2)
|
|
if fault:
|
|
assert result['rows'][-1]['worker']['success'] is True
|
|
assert result['rows'][-1]['success'] is False
|
|
assert len(result['remaining_slots'])==14-expected_rows
|