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

220 lines
12 KiB
Python

#!/usr/bin/env python3
"""Transaction tests without touching GPUs, processes, or user services."""
import importlib.util
import json
import os
import subprocess
import sys
import tempfile
import time
from types import SimpleNamespace
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('leleka-api-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)
class DeploymentTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix='leleka-control-planeler-')
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name).resolve()
self.value = dict(schema_version=1, **{key: str(self.root/key) for key in
('root','native','control','agent_helper','binary','config','cwd')},
url='http://127.0.0.1:12345', model='fixture')
self.path = self.root/'deployment.json'
def write(self, value=None):
self.path.write_text(json.dumps(value or self.value)); self.path.chmod(0o600)
return self.path
def host(self, explicit=True):
host = object.__new__(m.Host)
host.deployment = self.value if explicit else None
for key in ('root','native','control','binary','config'):
setattr(host, key, Path(self.value[key]))
return host
def test_private_manifest_and_no_mutations(self):
self.assertEqual(m.load_deployment(self.write()), self.value)
self.assertFalse(Path(self.value['root']).exists())
self.path.chmod(0o644)
with self.assertRaisesRegex(RuntimeError,'Invalid deployment'): m.load_deployment(self.path)
self.path.chmod(0o600)
alias = self.root/'alias'; alias.symlink_to(self.path)
with self.assertRaises(RuntimeError): m.load_deployment(alias)
def test_schema_paths_loopback_and_private_directories(self):
changes = [{'schema_version':True}, {'unexpected':'secret'}, {'binary':'relative'},
{'url':'http://server:1234'}, {'url':'http://127.0.0.1:1234/path'},
{'url':'http://user:secret@127.0.0.1:1234'}, {'url':'http://127.0.0.1'},
{'model':'bad name'}, {'root':self.value['native']}]
for change in changes:
with self.subTest(change=change), self.assertRaises(RuntimeError) as caught:
m.load_deployment(self.write({**self.value, **change}))
self.assertNotIn('secret', str(caught.exception))
directory=Path(self.value['root']); directory.mkdir(mode=0o755); directory.chmod(0o755)
with self.assertRaises(RuntimeError): m.load_deployment(self.write())
directory.chmod(0o700)
self.assertEqual(m.load_deployment(self.write())['root'], str(directory))
def test_cold_start_and_cached_recipe(self):
host=self.host()
recipe=host.native_recipe()
self.assertEqual(recipe, {key:self.value[key] for key in ('binary','config','cwd')} | {'env':{}})
self.assertFalse(host.root.exists())
cached={**recipe,'env':{'STRATA_FIXTURE':'1'}}
m.save(host.root/'native-recipe.json',cached)
self.assertEqual(host.native_recipe(),cached)
with patch.object(m,'provision_recipe') as provision:
host.prepare(OLD,11)
provision.assert_called_once_with(cached,11)
def test_key_rejected_before_lifecycle(self):
key=self.root/'key';self.value['key_file']=str(key)
for content,mode in [('fixture-token',0o644),('bad\nkey',0o600),('',0o600)]:
key.write_text(content);key.chmod(mode)
with self.assertRaises(RuntimeError):m.load_deployment(self.write())
self.assertFalse(Path(self.value['root']).exists())
key.write_text('fixture-token');key.chmod(0o600)
self.assertEqual(m.load_deployment(self.write())['key_file'],str(key))
def test_legacy_missing_recipe_is_not_invented(self):
with self.assertRaisesRegex(RuntimeError,'recipe missing'):self.host(False).native_recipe()
def test_literal_provision_invocation_and_suppressed_failure(self):
host=self.host(); host.binary=Path(sys.executable)
cwd=Path(self.value['cwd']); cwd.mkdir()
script=cwd/'provision'
script.write_text("import json,os,sys; json.dump([sys.argv[1:], os.environ['STRATA_FIXTURE']],open('seen','w'))")
recipe={'binary':sys.executable,'config':'literal $HOME `x` path','cwd':str(cwd),'env':{'STRATA_FIXTURE':'yes'}}
m.provision_recipe(recipe,5)
self.assertEqual(json.loads((cwd/'seen').read_text()),[['--config',recipe['config']],'yes'])
script.write_text("import sys; print('private secret',file=sys.stderr); sys.exit(7)")
with self.assertRaisesRegex(RuntimeError,'current model preserved') as caught:m.provision_recipe(recipe,5)
self.assertNotIn('secret',str(caught.exception))
def test_provision_timeout_reaps_child(self):
cwd=Path(self.value['cwd']);cwd.mkdir()
(cwd/'provision').write_text("import os,time; open('pid','w').write(str(os.getpid())); time.sleep(60)")
recipe={'binary':sys.executable,'config':'unused','cwd':str(cwd),'env':{}}
started=time.monotonic()
with self.assertRaisesRegex(RuntimeError,'timed out'):m.provision_recipe(recipe,.5)
self.assertLess(time.monotonic()-started,3)
with self.assertRaises(ProcessLookupError):os.kill(int((cwd/'pid').read_text()),0)
def test_readiness_identity_auth_and_no_redirect(self):
host=self.host(); key=self.root/'key';key.write_text('fixture-token');key.chmod(0o600)
self.value['key_file']=str(key)
response=Mock(status=200)
response.read.return_value=json.dumps(dict(service='leleka-control-plane',model='fixture',ready=True)).encode()
conn=Mock();conn.getresponse.return_value=response
with patch.object(m.http.client,'HTTPConnection',return_value=conn):
self.assertTrue(host.ready(OLD))
conn.request.assert_called_with('GET','/status',headers={'Authorization':'Bearer fixture-token'})
response.status=302;self.assertFalse(host.ready(OLD))
response.status=200;response.read.return_value=b'{}';self.assertFalse(host.ready(OLD))
conn.getresponse.side_effect=m.http.client.BadStatusLine('invalid');self.assertFalse(host.ready(OLD))
self.assertEqual(conn.close.call_count,4)
def test_ordinary_strata_recipe_unchanged(self):
host=self.host()
cfg=self.root/'strata-iq3_s.json'
cfg.write_text(json.dumps({'args':['--max-context','262144','--kv','int8']}))
(self.root/'strata-artifacts.json').write_text(json.dumps({'files':[]}))
host.s=SimpleNamespace(ROOT=self.root,STATE=self.root,DATA=self.root,prepare=lambda:{'stage':'ready'})
# Existing service command remains delegated; no configurable path may rewrite helper ROOT.
with patch.object(m.subprocess,'run',return_value=SimpleNamespace(returncode=0)), patch.object(m.subprocess,'Popen'):
try: host.prepare({'backend':'strata'},1)
except (KeyError,AttributeError) as error: self.fail(str(error))
if __name__ == '__main__': unittest.main()