Files
leleka/scripts/test-native-menu.py
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

218 lines
12 KiB
Python

#!/usr/bin/env python3
"""Sanitized picker fixture; no remote calls or user profile access."""
import contextlib
import importlib.util
import io
import json
from pathlib import Path
import tempfile
import os
from types import SimpleNamespace
import unittest
from unittest.mock import Mock, patch
import qwen_native_profile as native_profile
spec = importlib.util.spec_from_file_location('installer', Path(__file__).with_name('install-qwen-native-menu.py'))
installer = importlib.util.module_from_spec(spec)
spec.loader.exec_module(installer)
SOURCE = '''import json
from pathlib import Path
# Strata Next native bearer file integration v1
STRATA_MODEL = dict(id='old', backend='strata')
STRATA_AGENT_MODELS = [dict(id='kar', backend='strata-agent')]
def registry(): return [dict(id='first')]
def start_strata(args):
strata_remote('start', {'days': args.days})
strata_remote('start', {'days': args.days})
def remote(action, payload=None, stream=False, helper='/fixture/remote'):
proc = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', HOST,
'python3', helper, action], input=json.dumps(payload or {}))
return proc
def normal(args, kv_cache):
if not 0 <= args.wait_seconds <= 7200: raise RuntimeError('wait-seconds must be 0..7200')
return dict(days=args.days, kvCache=kv_cache)
def start_strata_agent(args, model):
observed = strata_agent_remote('start', {'profile': model['id']})
return observed
def list_models():
for model in [*registry(), STRATA_MODEL, *STRATA_AGENT_MODELS]:
if model.get('backend') == 'strata': modes = '1x256 · KV int8 · окремий рушій Strata'
print(model['id'])
def select_model(value):
models = [*registry(), STRATA_MODEL, *STRATA_AGENT_MODELS]
return next(m for m in models if m['id'] == value)
def dispatch(args, model):
if args.command == 'start':
if model.get('backend') == 'strata-agent': return start_strata_agent(args, model)
elif args.command == 'fetch':
if model.get('backend') == 'strata-agent':
return
'''
def args(**values):
return SimpleNamespace(**dict(dict(command='start', layout=None, kv_cache=None, kv_mode='with-key', wait_seconds=60, days=7), **values))
class MenuTests(unittest.TestCase):
def setUp(self):
socket_patch = patch('socket.socket')
self.socket = socket_patch.start()
self.socket.return_value.__enter__.return_value.connect_ex.return_value = 0
self.addCleanup(socket_patch.stop)
def module(self):
result = {}
exec(compile(installer.patched(SOURCE), 'fixture', 'exec'), result)
state = dict(backend='strata-native', model='strata-native-iq3-s', context=262144, parallel=1)
result.update(PROFILE=Path('/fixture'), validate_connection=Mock(), discover=Mock(return_value=state),
configure=Mock(), atomic=Mock(), strata_agent_remote=Mock(),
HOST='fixture', REMOTE='/fixture/remote', STRATA_AGENT_HELPER='/fixture/agent',
subprocess=Mock(), remote=Mock())
return result
def test_append_preserves_choices_and_switches_native(self):
m = self.module()
with contextlib.redirect_stdout(io.StringIO()) as out:
m['list_models']()
self.assertEqual(out.getvalue().splitlines(), ['first', 'old', 'kar', 'strata-native'])
with contextlib.redirect_stdout(io.StringIO()):
m['dispatch'](args(), m['select_model']('strata-native'))
target = m['discover'].call_args.args[0]
self.assertEqual(target['backend'], 'strata-native')
self.assertEqual(target['url'], 'http://127.0.0.1:18084')
self.assertFalse(target['managed'])
m['configure'].assert_called_once()
self.assertEqual(json.loads(m['atomic'].call_args.args[1]), target)
m['strata_agent_remote'].assert_not_called()
m['remote'].assert_called_once_with('start', {'backend': 'native', 'waitSeconds': 60}, stream=True, helper=m['STRATA_SWITCH_HELPER'])
def test_failure_and_incompatible_options_do_not_write_profile(self):
for changes in [dict(layout='2x256'), dict(kv_cache='f16'), dict(kv_mode='without-key')]:
m = self.module()
with self.assertRaises(RuntimeError):
m['start_strata_native'](args(**changes))
m['discover'].assert_not_called()
m['atomic'].assert_not_called()
for result in [OSError('offline'), RuntimeError('not ready'), {'model': 'other'}]:
m = self.module()
if isinstance(result, Exception):
m['discover'].side_effect = result
else:
m['discover'].return_value = result
with self.assertRaises(RuntimeError):
m['start_strata_native'](args())
m['configure'].assert_not_called()
m['atomic'].assert_not_called()
def test_all_managed_start_calls_route_through_switcher(self):
m = {}
exec(compile(installer.patched(SOURCE), 'fixture', 'exec'), m)
m.update(HOST='fixture', REMOTE='/fixture/remote', STRATA_AGENT_HELPER='/fixture/agent', subprocess=Mock())
for helper, backend in [('/fixture/remote', 'llama'), ('/fixture/agent', 'agent'), ('/home/para/inference/codex-qwen/strata_remote.py', 'strata')]:
m['remote']('start', {'id': 'test'}, helper=helper)
call = m['subprocess'].run.call_args
self.assertEqual(call.args[0][-2], m['STRATA_SWITCH_HELPER'])
self.assertEqual(json.loads(call.kwargs['input'])['backend'], backend)
m['remote']('status', helper='/fixture/remote')
self.assertEqual(m['subprocess'].run.call_args.args[0][-2], '/fixture/remote')
def test_switch_failure_does_not_write_profile(self):
m = self.module();m['remote'].side_effect=RuntimeError('rollback')
with self.assertRaisesRegex(RuntimeError,'rollback'):m['start_strata_native'](args())
m['atomic'].assert_not_called();m['configure'].assert_not_called()
def test_installer_backup_idempotence_and_anchor_fail_closed(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
path = root/'qwen_local.py'
path.write_text(SOURCE)
connection = root/'connection.json'
connection.write_text('{"unchanged":true}')
self.assertTrue(installer.install(path))
first = path.read_bytes()
self.assertFalse(installer.install(path))
self.assertEqual(path.read_bytes(), first)
self.assertEqual(connection.read_text(), '{"unchanged":true}')
backups = list(root.glob('*.before-native-picker-*'))
self.assertEqual(len(backups), 1)
self.assertEqual(backups[0].read_text(), SOURCE)
self.assertEqual(backups[0].stat().st_mode & 0o777, 0o600)
self.assertEqual((root/'qwen_native_profile.py').stat().st_mode & 0o777, 0o600)
with self.assertRaises(RuntimeError):
installer.patched(SOURCE.replace('def start_strata(args):', 'def changed(args):'))
def test_v1_upgrade_and_unrelated_helper(self):
# Build a genuine v1 fixture by suppressing only the new upgrade stage.
with patch.object(installer, 'profile_patch', side_effect=lambda s: s):
old = installer.patched(SOURCE)
upgraded = installer.patched(old)
self.assertIn(installer.PROFILE_MARKER, upgraded)
self.assertEqual(installer.patched(upgraded), upgraded)
with tempfile.TemporaryDirectory() as directory:
path = Path(directory)/'qwen_local.py'; path.write_text(old)
helper = path.with_name('qwen_native_profile.py'); helper.write_text('unrelated')
with self.assertRaises(RuntimeError): installer.install(path)
self.assertEqual(path.read_text(), old)
self.assertEqual(helper.read_text(), 'unrelated')
def test_explicit_ready_profile_never_uses_remote_or_tunnel(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
manifest = root/'native-picker.json'
manifest.write_text(json.dumps(dict(schema_version=1, mode='attach',
url='http://127.0.0.1:19123', model='fixture-native', key_file='/private/key')))
manifest.chmod(0o600)
m=self.module();m['PROFILE']=root
m['discover'].return_value=dict(backend='strata-native', model='fixture-native', context=262144, parallel=1)
with contextlib.redirect_stdout(io.StringIO()):m['start_strata_native'](args())
m['remote'].assert_not_called();m['subprocess'].run.assert_not_called()
target=json.loads(m['atomic'].call_args.args[1])
self.assertEqual(target['url'],'http://127.0.0.1:19123')
self.assertEqual(target['key_file'],'/private/key')
for changes in [dict(model='wrong'),dict(context=524288),dict(parallel=2),dict(parallel=True),dict(backend='strata')]:
m['atomic'].reset_mock();m['configure'].reset_mock()
m['discover'].return_value=dict(dict(backend='strata-native',model='fixture-native',context=262144,parallel=1),**changes)
with self.assertRaises(RuntimeError):m['start_strata_native'](args())
m['atomic'].assert_not_called();m['configure'].assert_not_called();m['remote'].assert_not_called()
manifest.write_text('{}')
with self.assertRaises(RuntimeError):m['start_strata_native'](args())
m['remote'].assert_not_called()
class ProfileTests(unittest.TestCase):
def test_invalid_files_and_schema_fail_closed(self):
good=dict(schema_version=1,mode='attach',url='http://127.0.0.1:19123',model='fixture',key_file=None)
with tempfile.TemporaryDirectory() as directory:
p=Path(directory)/'native-picker.json'
self.assertIsNone(native_profile.load(p))
for change in [dict(schema_version=True),dict(mode='start'),dict(extra=1),dict(model='a\nb'),
dict(key_file='relative'),dict(url='http://remote:80'),dict(url='http://user@localhost:80'),
dict(url='http://localhost:0'),dict(url='http://localhost:80/'),dict(url='http://localhost:80?q=x'),
dict(url='http://localhost:80\n'),dict(url='http://localhost:99999')]:
p.write_text(json.dumps(dict(good,**change)));p.chmod(0o600)
with self.subTest(change=change),self.assertRaises(RuntimeError):native_profile.load(p)
for raw in ['[]','{'+'"x":0,'*100+'"x":1}',json.dumps(good)+' '*16385]:
p.write_text(raw)
with self.assertRaises(RuntimeError):native_profile.load(p)
p.write_text(json.dumps(good));p.chmod(0o644)
with self.assertRaises(RuntimeError):native_profile.load(p)
p.unlink();p.symlink_to(Path(directory)/'missing')
with self.assertRaises(RuntimeError):native_profile.load(p)
p.unlink();os.mkfifo(p,0o600)
with self.assertRaises(RuntimeError):native_profile.load(p)
def test_offline_and_key_errors_do_not_commit(self):
with tempfile.TemporaryDirectory() as directory:
root=Path(directory);p=root/'native-picker.json'
p.write_text(json.dumps(dict(schema_version=1,mode='attach',url='http://localhost:19123',model='fixture',key_file=None)))
p.chmod(0o600)
for validate,discover in [(Mock(side_effect=RuntimeError('key invalid')),Mock()),
(Mock(),Mock(side_effect=OSError('offline')))]:
configure,atomic=Mock(),Mock()
with self.assertRaises(RuntimeError):native_profile.attach(root,validate=validate,discover=discover,configure=configure,atomic=atomic)
configure.assert_not_called();atomic.assert_not_called()
if __name__ == '__main__':
unittest.main()