Files
leleka/scripts/test-model-switch.py
T

99 lines
5.1 KiB
Python

#!/usr/bin/env python3
"""Transaction tests without touching GPUs, processes, or user services."""
import importlib.util
from pathlib import Path
import unittest
from unittest.mock import Mock, patch
spec = importlib.util.spec_from_file_location('switcher', Path(__file__).with_name('strata-model-switch.py'))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
OLD = {'backend': 'native'}
NEW = {'backend': 'agent', 'profile': 'kar'}
class Fake:
def __init__(self, old=True):
self.current = [{'target': OLD}] if old else []
self.events = []
self.fail = None
self.unrelated = False
def prepare(self, target, budget):
self.events.append('prepare')
if self.fail == 'prepare': raise RuntimeError('missing file')
def inventory(self): return list(self.current)
def check_owners(self, owners):
self.events.append('owners')
if self.unrelated: raise RuntimeError('unrelated')
def matches(self, owner, target): return owner['target'] == target
def ready(self, target): return any(self.matches(o, target) for o in self.current)
def existing_result(self, target): return {'started': False}
def journal(self, phase, previous, target): self.events.append(phase)
def stop(self, owner, failed=False):
self.events.append('cleanup' if failed else 'stop')
self.current.remove(owner)
def free_gpu(self): self.events.append('free')
def launch(self, target):
self.events.append('launch')
self.current = [{'target': target}]
return {'started': True}
def wait_ready(self, target, budget):
self.events.append('wait')
if target == NEW and self.fail in {'ready', 'restore'}: raise RuntimeError('load failed')
def restore(self, owner):
self.events.append('restore')
if self.fail == 'restore': raise RuntimeError('restore failed')
self.current = [owner]
class Tests(unittest.TestCase):
def test_success_order(self):
h = Fake(); self.assertEqual(m.switch(h, NEW, 10), {'started': True})
self.assertEqual(h.events, ['prepare','owners','prepared','stop','free','loading','launch','wait','ready'])
def test_preflight_failure_keeps_old(self):
h=Fake(); h.fail='prepare'
with self.assertRaisesRegex(RuntimeError, 'missing'): m.switch(h, NEW, 10)
self.assertTrue(h.ready(OLD)); self.assertEqual(h.events,['prepare'])
def test_unrelated_owner_untouched(self):
h=Fake(); h.unrelated=True
with self.assertRaisesRegex(RuntimeError, 'unrelated'): m.switch(h, NEW, 10)
self.assertTrue(h.ready(OLD)); self.assertNotIn('stop',h.events)
def test_ambiguous_owners_untouched(self):
h=Fake();h.current.append({'target': NEW})
with self.assertRaisesRegex(RuntimeError,'Multiple'):m.switch(h,NEW,10)
self.assertNotIn('stop',h.events)
def test_idempotent(self):
h=Fake();self.assertFalse(m.switch(h,OLD,10)['started']);self.assertNotIn('stop',h.events)
def test_failed_start_rolls_back(self):
h=Fake();h.fail='ready'
with self.assertRaisesRegex(RuntimeError,'previous model restored'):m.switch(h,NEW,10)
self.assertTrue(h.ready(OLD));self.assertIn('cleanup',h.events);self.assertEqual(h.events[-1],'restored')
def test_failed_restore_reported(self):
h=Fake();h.fail='restore'
with self.assertRaisesRegex(RuntimeError,'could not be restored'):m.switch(h,NEW,10)
self.assertEqual(h.events[-1],'restore_failed')
def test_failure_without_previous_cleans_target(self):
h=Fake(False);h.fail='ready'
with self.assertRaisesRegex(RuntimeError,'no previous'):m.switch(h,NEW,10)
self.assertEqual(h.current,[])
def test_pid_reuse_and_ancestry(self):
processes={20:dict(pid=20,start_ticks='2',ppid=10),10:dict(pid=10,start_ticks='1',ppid=1)}
with patch.object(m,'identity',side_effect=processes.get):
self.assertTrue(m.owned(20,{10}));self.assertFalse(m.owned(20,{30}))
self.assertFalse(m.same_process(dict(pid=20,start_ticks='1')))
self.assertTrue(m.same_process(dict(pid=20,start_ticks='2')))
class PreparationTests(unittest.TestCase):
def test_agent_preflight_failure_never_unloads(self):
spec=importlib.util.spec_from_file_location('agent',Path(__file__).with_name('strata-agent-profile.py'))
agent=importlib.util.module_from_spec(spec);spec.loader.exec_module(agent)
with patch.object(agent,'prepare',side_effect=FileNotFoundError('missing')), patch.object(agent,'state') as state, patch.object(agent,'unload') as unload:
with self.assertRaises(FileNotFoundError):agent.start('strata-next-kar-ple-gpu')
state.assert_not_called();unload.assert_not_called()
def test_gpu_release_waits_without_killing(self):
host=object.__new__(m.Host)
with patch.object(host,'check_owners',side_effect=[RuntimeError('still exiting'),None]) as owners, patch.object(m.time,'sleep'), patch.object(m.subprocess,'check_output',return_value='500\n'):
host.free_gpu()
self.assertEqual(owners.call_count,2)
if __name__ == '__main__': unittest.main()