gpu-head-to-head
aien-dev/gpu-head-to-head
Brought by drakestapleton
gpu-head-to-head / bench / test-shared-window.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Host-only sequencing, recovery and real-child controls; no live shared service access.""" |
| 3 | import contextlib,importlib.util,pathlib,tempfile,unittest,types,os,fcntl,subprocess,threading |
| 4 | from unittest.mock import patch |
| 5 | HERE=pathlib.Path(__file__).resolve().parent |
| 6 | spec=importlib.util.spec_from_file_location('window',HERE/'shared-window.py') |
| 7 | window=importlib.util.module_from_spec(spec);spec.loader.exec_module(window) |
| 8 | class Fake: |
| 9 | def __init__(self,fail=None,code=0): self.fail=fail;self.code=code;self.events=[];self.held=False |
| 10 | def step(self,name): |
| 11 | if not self.held: raise AssertionError('operation without lock') |
| 12 | self.events.append(name) |
| 13 | if self.fail==name: raise RuntimeError('fixture '+name) |
| 14 | @contextlib.contextmanager |
| 15 | def lock(self): |
| 16 | self.held=True;self.events.append('lock') |
| 17 | try: yield |
| 18 | finally:self.held=False;self.events.append('unlock') |
| 19 | def preflight(self):self.step('preflight') |
| 20 | def stop(self):self.step('stop') |
| 21 | def wait_original_exit(self):self.step('wait') |
| 22 | def before_test(self):self.step('before') |
| 23 | def run(self):self.step('run');return self.code |
| 24 | def recovery_gate(self):self.step('recovery') |
| 25 | def restore(self):self.step('restore') |
| 26 | def verify_restored(self):self.step('verify') |
| 27 | class Sequencing(unittest.TestCase): |
| 28 | def test_success_holds_lock_through_verified_restore(self): |
| 29 | f=Fake();r=window.execute(f) |
| 30 | self.assertEqual(r['status'],'PASS') |
| 31 | self.assertEqual(f.events,['lock','preflight','stop','wait','before','run','recovery','restore','verify','unlock']) |
| 32 | def test_busy_preflight_never_stops_or_restores(self): |
| 33 | f=Fake('preflight') |
| 34 | with self.assertRaises(RuntimeError):window.execute(f) |
| 35 | self.assertEqual(f.events,['lock','preflight','unlock']) |
| 36 | def test_failed_test_still_restores_and_fails(self): |
| 37 | f=Fake(code=7);r=window.execute(f) |
| 38 | self.assertEqual(r['test_exit'],7);self.assertTrue(r['restored']);self.assertEqual(r['status'],'INCOMPLETE') |
| 39 | def test_exception_after_stop_always_attempts_gated_recovery(self): |
| 40 | for step in ['stop','wait','before','run']: |
| 41 | with self.subTest(step=step): |
| 42 | f=Fake(step);r=window.execute(f) |
| 43 | self.assertIn('recovery',f.events);self.assertTrue(r['restored']);self.assertEqual(r['status'],'INCOMPLETE') |
| 44 | def test_failed_recovery_gate_never_launches_original(self): |
| 45 | f=Fake('recovery');r=window.execute(f) |
| 46 | self.assertNotIn('restore',f.events);self.assertFalse(r['restored']) |
| 47 | def test_failed_launcher_never_claims_restored(self): |
| 48 | f=Fake('restore');r=window.execute(f) |
| 49 | self.assertNotIn('verify',f.events);self.assertFalse(r['restored']) |
| 50 | def test_failed_identity_never_claims_restored(self): |
| 51 | f=Fake('verify');r=window.execute(f) |
| 52 | self.assertFalse(r['restored']);self.assertIn('recovery_error',r) |
| 53 | class LiveAdapter(unittest.TestCase): |
| 54 | def bare(self,root): |
| 55 | obj=object.__new__(window.Live) |
| 56 | obj.a=types.SimpleNamespace(out=root,repo=root,arm='OURS',round='R1') |
| 57 | obj.child=None;obj.interrupted=False;obj.baseline=5000000 |
| 58 | return obj |
| 59 | def test_real_child_borrows_lock_and_failed_exit_is_preserved(self): |
| 60 | with tempfile.TemporaryDirectory() as temp: |
| 61 | root=pathlib.Path(temp);(root/'bench').mkdir() |
| 62 | (root/'bench/run_arm.sh').write_text('test -e /proc/$$/fd/9 || exit 22\nflock -n 9 || exit 23\necho "$H2H_GPU_LOCK_FD"\nexit 7\n') |
| 63 | obj=self.bare(root) |
| 64 | fd=os.open(root/'lock',os.O_CREAT|os.O_RDWR,0o600) |
| 65 | saved=None |
| 66 | try: |
| 67 | try:saved=os.dup(9) |
| 68 | except OSError:pass |
| 69 | os.dup2(fd,9);fcntl.flock(9,fcntl.LOCK_EX|fcntl.LOCK_NB) |
| 70 | self.assertEqual(obj.run(),7) |
| 71 | probe=subprocess.run(['flock','-n',str(root/'lock'),'true']) |
| 72 | self.assertNotEqual(probe.returncode,0,'child released parent lock') |
| 73 | self.assertEqual((root/'runner.log').read_text().strip(),'9') |
| 74 | finally: |
| 75 | os.close(9) |
| 76 | if saved is not None:os.dup2(saved,9);os.close(saved) |
| 77 | if fd!=9:os.close(fd) |
| 78 | def test_interruption_before_launch_is_refused(self): |
| 79 | with tempfile.TemporaryDirectory() as tmp: |
| 80 | obj=self.bare(pathlib.Path(tmp));obj.interrupted=True |
| 81 | with self.assertRaises(window.guard.Refused):obj.run() |
| 82 | self.assertIsNone(obj.child) |
| 83 | def test_success_without_done_is_refused(self): |
| 84 | with tempfile.TemporaryDirectory() as tmp: |
| 85 | obj=self.bare(pathlib.Path(tmp)) |
| 86 | child=types.SimpleNamespace(poll=lambda:0,returncode=0) |
| 87 | with patch.object(window.subprocess,'Popen',return_value=child): |
| 88 | with self.assertRaisesRegex(window.guard.Refused,'completed-session marker'):obj.run() |
| 89 | def test_interruption_stops_and_reaps_real_fixture_child(self): |
| 90 | with tempfile.TemporaryDirectory() as tmp: |
| 91 | root=pathlib.Path(tmp);(root/'bench').mkdir() |
| 92 | (root/'bench/run_arm.sh').write_text('exec sleep 30\n') |
| 93 | obj=self.bare(root);fd=os.open(root/'lock',os.O_CREAT|os.O_RDWR,0o600);saved=None |
| 94 | timer=threading.Timer(0.1,lambda:setattr(obj,'interrupted',True)) |
| 95 | try: |
| 96 | try:saved=os.dup(9) |
| 97 | except OSError:pass |
| 98 | os.dup2(fd,9);timer.start() |
| 99 | with self.assertRaisesRegex(window.guard.Refused,'interrupted'):obj.run() |
| 100 | self.assertIsNotNone(obj.child.returncode) |
| 101 | with self.assertRaises(ChildProcessError):os.waitpid(obj.child.pid,os.WNOHANG) |
| 102 | finally: |
| 103 | timer.cancel();timer.join() |
| 104 | if obj.child is not None and obj.child.poll() is None:obj.child.kill();obj.child.wait() |
| 105 | os.close(9) |
| 106 | if saved is not None:os.dup2(saved,9);os.close(saved) |
| 107 | if fd!=9:os.close(fd) |
| 108 | def test_active_runner_refuses_restoration_without_gpu_query(self): |
| 109 | obj=self.bare(pathlib.Path('/unused'));obj.child=types.SimpleNamespace(poll=lambda:None) |
| 110 | with patch.object(obj,'gpu_empty') as gpu: |
| 111 | with self.assertRaises(window.guard.Refused):obj.recovery_gate() |
| 112 | gpu.assert_not_called() |
| 113 | def test_original_still_alive_refuses_duplicate(self): |
| 114 | obj=self.bare(pathlib.Path('/unused'));obj.original_fd=42 |
| 115 | with patch.object(window.select,'select',return_value=([],[],[])),patch.object(obj,'gpu_empty') as gpu: |
| 116 | with self.assertRaises(window.guard.Refused):obj.recovery_gate() |
| 117 | gpu.assert_not_called() |
| 118 | def test_memory_deficit_refuses_restore(self): |
| 119 | with tempfile.TemporaryDirectory() as tmp: |
| 120 | obj=self.bare(pathlib.Path(tmp));obj.original_fd=42 |
| 121 | with patch.object(window.select,'select',return_value=([42],[],[])),patch.object(obj,'gpu_empty'),patch.object(obj,'memory',return_value=1): |
| 122 | with self.assertRaises(window.guard.Refused):obj.recovery_gate() |
| 123 | def test_residual_gpu_refuses_restore(self): |
| 124 | obj=self.bare(pathlib.Path('/unused'));obj.original_fd=42 |
| 125 | with patch.object(window.select,'select',return_value=([42],[],[])),patch.object(obj,'gpu_empty',side_effect=window.guard.Refused('foreign GPU')),patch.object(obj,'memory') as memory: |
| 126 | with self.assertRaises(window.guard.Refused):obj.recovery_gate() |
| 127 | memory.assert_not_called() |
| 128 | def test_restore_launcher_does_not_inherit_gpu_lock(self): |
| 129 | with tempfile.TemporaryDirectory() as tmp: |
| 130 | root=pathlib.Path(tmp);obj=self.bare(root) |
| 131 | obj.a.launcher=root/'restore.sh' |
| 132 | obj.a.launcher.write_text('#!/bin/bash\n[ ! -e /proc/$$/fd/9 ] || exit 21\n[ "$Q36_BATCH_BIN" = bin-fixture ] || exit 22\n[ "$Q36_BATCH_SLOTS" = 8 ] || exit 23\n[ "$Q36_MAX_CONTEXT" = 49152 ] || exit 24\necho RESTORED_FIXTURE\n') |
| 133 | obj.a.launcher.chmod(0o700) |
| 134 | obj.snapshot={'cwd':str(root/'bin-fixture'),'env':{'AIEN_Q36_STROKE':'1'}} |
| 135 | fd=os.open(root/'lock',os.O_CREAT|os.O_RDWR,0o600);saved=None |
| 136 | try: |
| 137 | try:saved=os.dup(9) |
| 138 | except OSError:pass |
| 139 | os.dup2(fd,9);fcntl.flock(9,fcntl.LOCK_EX|fcntl.LOCK_NB) |
| 140 | with patch.object(obj,'validate_pins') as pins: |
| 141 | obj.restore();pins.assert_called_once_with(restoration=True) |
| 142 | self.assertEqual((root/'restore.log').read_text().strip(),'RESTORED_FIXTURE') |
| 143 | self.assertNotEqual(subprocess.run(['flock','-n',str(root/'lock'),'true']).returncode,0) |
| 144 | finally: |
| 145 | os.close(9) |
| 146 | if saved is not None:os.dup2(saved,9);os.close(saved) |
| 147 | if fd!=9:os.close(fd) |
| 148 | def test_changed_snapshot_contract_refused_before_stop(self): |
| 149 | obj=self.bare(pathlib.Path('/unused'));obj.snapshot={'argv':['different-model']} |
| 150 | with self.assertRaises(window.guard.Refused):obj.validate_restore_contract() |
| 151 | def test_gpu_query_error_is_not_empty_inventory(self): |
| 152 | obj=self.bare(pathlib.Path('/unused')) |
| 153 | with patch.object(window.subprocess,'check_output',side_effect=subprocess.CalledProcessError(1,'fixture')): |
| 154 | with self.assertRaises(subprocess.CalledProcessError):obj.gpu_empty() |
| 155 | if __name__=='__main__':unittest.main() |