Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/gpu-head-to-head/blob/main/bench/test-shared-model-guard.py # gpu-head-to-head aien-dev/gpu-head-to-head Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `gpu-head-to-head / bench / test-shared-model-guard.py` 127 lines ยท 7515 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """External guard controls. No shared port, GPU query or shared model is touched.""" 3 import hashlib 4 import importlib.util 5 import json 6 import os 7 from pathlib import Path 8 import signal 9 import subprocess 10 import sys 11 import tempfile 12 import unittest 13 from unittest.mock import patch 14 sys.dont_write_bytecode=True 15 HERE=Path(__file__).resolve().parent 16 spec=importlib.util.spec_from_file_location('shared_guard',HERE/'shared-model-guard.py') 17 guard=importlib.util.module_from_spec(spec);spec.loader.exec_module(guard) 18 HEALTH=dict(status='ok',model='qwen3.6-35b-a3b-fp8',engine='omega-qwen36-batch', 19 concurrency=8,busy=False,in_flight=0) 20 21 class ObservationTests(unittest.TestCase): 22 def test_expected_idle_observation_passes(self): 23 guard.check_observation(42,HEALTH,'',[42],'reviewed','reviewed') 24 def test_active_or_changed_health_refused(self): 25 for key,value in [('busy',True),('in_flight',1),('in_flight',False),('concurrency',1), 26 ('model','other'),('engine','other'),('status','loading')]: 27 health=dict(HEALTH);health[key]=value 28 with self.subTest(key=key,value=value),self.assertRaises(guard.Refused): 29 guard.check_observation(42,health,'',[42],'reviewed','reviewed') 30 def test_established_client_refused(self): 31 with self.assertRaises(guard.Refused):guard.check_observation(42,HEALTH,'fixture client',[42],'reviewed','reviewed') 32 def test_foreign_missing_or_duplicate_gpu_pid_refused(self): 33 for pids in [[],[41],[42,43],[42,42],['42'],[True]]: 34 with self.subTest(pids=pids),self.assertRaises(guard.Refused): 35 guard.check_observation(42,HEALTH,'',pids,'reviewed','reviewed') 36 def test_board_change_refused(self): 37 with self.assertRaises(guard.Refused):guard.check_observation(42,HEALTH,'',[42],'new','reviewed') 38 39 class IdentityTests(unittest.TestCase): 40 def fixture(self,root): 41 binary=root/'fixture-executable';binary.write_bytes(b'harmless identity fixture') 42 proc=root/'proc/42';proc.mkdir(parents=True) 43 (proc/'exe').symlink_to(binary);(proc/'cwd').symlink_to(root) 44 argv=['./fixture','--engine','omega'];(proc/'cmdline').write_bytes(b'\0'.join(x.encode() for x in argv)+b'\0') 45 (proc/'environ').write_bytes(b'AIEN_Q36_STROKE=1\0UNRELATED=not-recorded\0') 46 fields=['S','1']+['0']*17+['12345']+['0']*5 47 (proc/'stat').write_text('42 (fixture name) '+ ' '.join(fields)) 48 snapshot=dict(exe=str(binary),cwd=str(root),argv=argv,env={'AIEN_Q36_STROKE':'1'}) 49 return snapshot,hashlib.sha256(binary.read_bytes()).hexdigest(),proc 50 def test_saved_identity_matches_without_recording_unrelated_environment(self): 51 with tempfile.TemporaryDirectory() as tmp: 52 root=Path(tmp);snapshot,digest,proc=self.fixture(root) 53 actual=guard.process_identity(42,snapshot,digest,root/'proc') 54 self.assertEqual(actual['starttime_ticks'],'12345') 55 self.assertNotIn('not-recorded',json.dumps(actual)) 56 def test_configuration_drift_refused(self): 57 for key,value in [('argv',['changed']),('cwd','/different'),('exe','/different')]: 58 with self.subTest(key=key),tempfile.TemporaryDirectory() as tmp: 59 root=Path(tmp);snapshot,digest,proc=self.fixture(root);snapshot[key]=value 60 with self.assertRaises(guard.Refused):guard.process_identity(42,snapshot,digest,root/'proc') 61 def test_binary_and_required_environment_changes_refused(self): 62 for kind in ['binary','environment']: 63 with self.subTest(kind=kind),tempfile.TemporaryDirectory() as tmp: 64 root=Path(tmp);snapshot,digest,proc=self.fixture(root) 65 if kind=='binary':Path(snapshot['exe']).write_bytes(b'changed') 66 else:(proc/'environ').write_bytes(b'AIEN_Q36_STROKE=0\0') 67 with self.assertRaises(guard.Refused):guard.process_identity(42,snapshot,digest,root/'proc') 68 69 class SequencingTests(unittest.TestCase): 70 def run_fake(self,stop=False,busy=False,changed=False,exited=False): 71 identity=dict(pid=42,starttime_ticks='1',exe_sha256='fixture') 72 observations=[dict(HEALTH)]*4 73 with patch.object(guard.os,'pidfd_open',return_value=999),patch.object(guard.os,'close') as close,\ 74 patch.object(guard,'process_identity',side_effect=[identity,dict(identity,starttime_ticks='2') if changed else identity]),\ 75 patch.object(guard,'observe',side_effect=guard.Refused('busy') if busy else observations) as observe,\ 76 patch.object(guard.time,'sleep'),patch.object(guard.select,'select',return_value=([999] if exited else [],[],[])),\ 77 patch.object(guard,'send_term') as send: 78 try: 79 result=guard.guard(42,{},'fixture',Path('/unused'),'reviewed',stop) 80 return result,send.call_count,observe.call_count 81 finally: 82 self.assertEqual(close.call_args_list,[( (999,), {} )]) 83 if busy or changed or exited:self.assertEqual(send.call_count,0) 84 def test_check_only_never_signals(self): 85 result,sent,observed=self.run_fake() 86 self.assertFalse(result['stop_sent']);self.assertEqual(sent,0);self.assertEqual(observed,4) 87 def test_stop_requires_all_samples_and_final_identity_check(self): 88 result,sent,observed=self.run_fake(stop=True) 89 self.assertTrue(result['stop_sent']);self.assertEqual(sent,1);self.assertEqual(observed,4) 90 def test_busy_identity_drift_or_exited_handle_never_signals(self): 91 for options in [dict(busy=True),dict(changed=True),dict(exited=True)]: 92 with self.subTest(options=options),self.assertRaises(guard.Refused):self.run_fake(stop=True,**options) 93 94 class ReceiptTests(unittest.TestCase): 95 def test_cli_refuses_existing_receipt_before_any_process_access(self): 96 with tempfile.TemporaryDirectory() as tmp: 97 output=Path(tmp)/'existing.json';output.write_text('preserve evidence') 98 result=subprocess.run([sys.executable,str(HERE/'shared-model-guard.py'), 99 '--pid','0','--snapshot',str(Path(tmp)/'absent.json'), 100 '--binary-sha256','invalid','--reviewed-board-sha256','invalid', 101 '--stop','--out',str(output)],capture_output=True,text=True,timeout=5) 102 self.assertNotEqual(result.returncode,0) 103 self.assertEqual(output.read_text(),'preserve evidence') 104 self.assertIn('FileExistsError',result.stderr) 105 106 class PidfdTests(unittest.TestCase): 107 def test_bound_signal_stops_only_fixture_child(self): 108 child=subprocess.Popen(['sleep','60']);decoy=subprocess.Popen(['sleep','60']) 109 fd=os.pidfd_open(child.pid) 110 try: 111 guard.send_term(fd);self.assertEqual(child.wait(timeout=2),-signal.SIGTERM) 112 self.assertIsNone(decoy.poll()) 113 finally: 114 os.close(fd) 115 for process in [child,decoy]: 116 if process.poll() is None:process.terminate() 117 process.wait(timeout=2) 118 def test_exited_bound_handle_refused(self): 119 child=subprocess.Popen(['sleep','60']);fd=os.pidfd_open(child.pid) 120 try: 121 child.terminate();child.wait(timeout=2) 122 with self.assertRaises(guard.Refused):guard.send_term(fd) 123 finally: 124 os.close(fd) 125 if child.poll() is None:child.terminate();child.wait(timeout=2) 126 127 if __name__=='__main__':unittest.main()