Files
leleka/scripts/test-ple-config-parity.py

358 lines
18 KiB
Python

#!/usr/bin/env python3
"""Synthetic, offline tests for the secret-safe PLE parity preflight."""
import importlib.util
import hashlib
import io
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from contextlib import redirect_stdout
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('parity', Path(__file__).with_name('check-ple-config-parity.py'))
parity = importlib.util.module_from_spec(spec)
spec.loader.exec_module(parity)
class ParityTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.archive = self.root / 'synthetic.kar'
self.archive.write_bytes(b'synthetic archive bytes')
self.archive_sha = hashlib.sha256(self.archive.read_bytes()).hexdigest()
self.legacy_args = [
'--pack', '/models/current-pack', '--native',
'/models/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf',
'--max-context', '262144', '--kv', 'int8', '--kv-resident', '32768',
'--spec', '4', '--spec-min-p', '0.5', '--expert-cache', 'auto',
'--prefill', 'auto', '--vram-reserve-mib', '700', '--mtp', '/models/mtp-v1',
]
self.candidate_executable = '/runtime/leleka-api'
self.ple = ['--ple-kar', str(self.archive), '--ple-kar-level', '2',
'--ple-kar-gpu-cache-mib', '64']
self.legacy = {'exe': '/legacy/strata', 'args': list(self.legacy_args),
'cwd': '/srv/qwen', 'log': '/var/log/old-engine.log'}
self.candidate = {
'bind': '127.0.0.1:18081',
'api_key_file': str(self.root / 'unread-api-key'),
'max_in_flight_requests': 1,
'engine': {'executable': self.candidate_executable,
'args': self.legacy_args_after_migration() + self.ple,
'startup_timeout_s': 600, 'max_restarts': 0},
'native_model': {'manifest': '/fixtures/qwen3.8-flash-next-iq3-s.json',
'source_dir': '/models', 'output': '/models/new-pack',
'runtime_profile': 'qwen4exp-flash-next'},
'assets': [{'manifest': '/fixtures/mtp-manifest.json',
'directory': '/models/mtp-v1'}],
'mtp_pack': '/models/mtp-v1',
}
self.context = {
'legacy': {'bind': '192.168.1.196:18081', 'cwd': '/srv/qwen',
'log': '/var/log/old-engine.log', 'effective_slots': 1,
'environment': {}},
'candidate': {'bind': '127.0.0.1:18081', 'cwd': '/srv/qwen',
'log': 'systemd-journal', 'effective_slots': 1,
'environment': {}},
'environment_complete': True,
}
self.expected_sha = parity.PINNED_ARCHIVE_SHA256
def legacy_args_after_migration(self):
result = []
skip = False
for token in self.legacy_args:
if skip:
skip = False
elif token in {'--pack', '--native', '--mtp'}:
skip = True
else:
result.append(token)
return result
def run_compare(self, *, legacy=None, candidate=None, context=None):
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha):
return parity.compare(legacy or self.legacy, candidate or self.candidate,
context or self.context, self.archive, self.archive_sha,
self.candidate_executable, '127.0.0.1:18081', 'systemd-journal')
def test_baseline_to_gpu_ple_is_incomplete_not_full_pass(self):
result = self.run_compare()
self.assertEqual(result['status'], 'incomplete')
self.assertEqual(result['mismatches'], [])
self.assertEqual(set(result['unverified']), parity.UNVERIFIED)
self.assertIn('request_model_identity', result['unverified'])
def test_already_ple_selected_in_original_is_preserved_exactly(self):
legacy = json.loads(json.dumps(self.legacy))
legacy['args'] += self.ple
candidate = json.loads(json.dumps(self.candidate))
candidate['engine']['args'] = self.legacy_args_after_migration() + self.ple
self.assertEqual(self.run_compare(legacy=legacy, candidate=candidate)['mismatches'], [])
def test_partial_duplicate_changed_or_reordered_ple_fails(self):
cases = [
self.ple[:-2],
self.ple + self.ple,
['--ple-kar', str(self.archive), '--ple-kar-level', '3', '--ple-kar-gpu-cache-mib', '64'],
['--ple-kar-level', '2', '--ple-kar', str(self.archive), '--ple-kar-gpu-cache-mib', '64'],
]
for flags in cases:
with self.subTest(flags=flags):
legacy = json.loads(json.dumps(self.legacy))
legacy['args'] += flags
result = self.run_compare(legacy=legacy)
self.assertIn('ple_arguments', result['mismatches'])
def test_malformed_candidate_ple_tuple_is_rejected(self):
cases = [
self.ple[:-2],
self.ple + self.ple,
['--ple-kar', str(self.archive), '--ple-kar-level', '1',
'--ple-kar-gpu-cache-mib', '64'],
['--ple-kar-level', '2', '--ple-kar', str(self.archive),
'--ple-kar-gpu-cache-mib', '64'],
]
for flags in cases:
with self.subTest(flags=flags):
candidate = json.loads(json.dumps(self.candidate))
candidate['engine']['args'] = self.legacy_args_after_migration() + flags
result = self.run_compare(candidate=candidate)
self.assertIn('ple_arguments', result['mismatches'])
def test_changes_to_non_ple_model_mtp_and_profile_settings_fail(self):
cases = []
altered = json.loads(json.dumps(self.candidate))
altered['engine']['args'][1] = '262143'
cases.append((altered, 'profile_settings'))
altered = json.loads(json.dumps(self.legacy))
altered['args'][3] = '/models/Other-IQ3_S.gguf'
cases.append((altered, 'model_selection'))
altered = json.loads(json.dumps(self.candidate))
altered['mtp_pack'] = '/models/mtp-other'
altered['assets'][0]['directory'] = '/models/mtp-other'
cases.append((altered, 'mtp_asset_mapping'))
altered = json.loads(json.dumps(self.candidate))
altered['engine']['args'].insert(0, '--force')
altered['engine']['args'].insert(1, 'other')
cases.append((altered, 'engine_arguments'))
for value, expected in cases:
with self.subTest(expected=expected):
if expected in ('model_selection',):
result = self.run_compare(legacy=value)
else:
result = self.run_compare(candidate=value)
self.assertIn(expected, result['mismatches'])
def test_every_retained_profile_setting_must_match_on_both_sides(self):
for flag, wanted in parity.REQUIRED_SETTINGS.items():
with self.subTest(flag=flag, side='legacy'):
legacy = json.loads(json.dumps(self.legacy))
index = legacy['args'].index(flag)
legacy['args'][index + 1] = f'{wanted}-changed'
self.assertIn('profile_settings',
self.run_compare(legacy=legacy)['mismatches'])
with self.subTest(flag=flag, side='candidate'):
candidate = json.loads(json.dumps(self.candidate))
index = candidate['engine']['args'].index(flag)
candidate['engine']['args'][index + 1] = f'{wanted}-changed'
self.assertIn('profile_settings',
self.run_compare(candidate=candidate)['mismatches'])
def test_service_context_requires_bind_workdir_log_and_one_slot(self):
for key, value in [('cwd', '/srv/other'), ('bind', '0.0.0.0:18081'),
('log', '/tmp/other.log'), ('effective_slots', 2)]:
context = json.loads(json.dumps(self.context))
context['candidate'][key] = value
result = self.run_compare(context=context)
expected = {'cwd': 'working_directory', 'bind': 'bind_selection',
'log': 'log_selection', 'effective_slots': 'slot_count'}[key]
self.assertIn(expected, result['mismatches'])
context = json.loads(json.dumps(self.context))
context['environment_complete'] = False
self.assertIn('effective_environment', self.run_compare(context=context)['unverified'])
for side in ('legacy', 'candidate'):
context = json.loads(json.dumps(self.context))
context[side].pop('effective_slots')
result = self.run_compare(context=context)
self.assertNotIn('slot_count', result['mismatches'])
self.assertIn('worker_slot_count', result['unverified'])
def test_only_declared_bind_and_executable_environment_deltas_are_allowed(self):
context = json.loads(json.dumps(self.context))
context['candidate']['environment'] = {
'STRATA_BIND': '127.0.0.1:18081',
'STRATA_ENGINE_EXE': self.candidate_executable,
}
self.assertEqual(self.run_compare(context=context)['mismatches'], [])
context['candidate']['environment']['CUDA_VISIBLE_DEVICES'] = '1'
self.assertIn('environment_delta', self.run_compare(context=context)['mismatches'])
def test_http_request_capacity_is_not_confused_with_worker_slot_count(self):
candidate = json.loads(json.dumps(self.candidate))
candidate.pop('max_in_flight_requests')
result = self.run_compare(candidate=candidate)
self.assertNotIn('slot_count', result['mismatches'])
self.assertIn('http_capacity_policy', result['unverified'])
def test_archive_bytes_are_stream_checked_against_pin(self):
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha):
parity.check_archive(self.archive, self.archive_sha)
self.archive.write_bytes(b'corrupted fixture')
with self.assertRaisesRegex(parity.InvalidInput, 'archive_digest'):
parity.check_archive(self.archive, self.archive_sha)
with self.assertRaisesRegex(parity.InvalidInput, 'archive_pin'):
parity.check_archive(self.archive, '0' * 64)
def test_strict_json_rejects_duplicates_constants_invalid_utf8_and_nonobject(self):
path = self.root / 'config.json'
for raw in (b'{"x":1,"x":2}', b'{"x":NaN}', b'\xff', b'[]'):
with self.subTest(raw=raw):
path.write_bytes(raw)
with self.assertRaises(parity.InvalidInput):
value = parity.read_json(path)
parity.validate_legacy(value)
def test_json_parser_recursion_and_overflow_errors_are_bounded(self):
path = self.root / 'nested.json'
path.write_text('{}')
for error in (RecursionError, OverflowError):
with self.subTest(error=error.__name__):
with patch.object(parity.json, 'loads', side_effect=error):
with self.assertRaisesRegex(parity.InvalidInput, 'invalid_json'):
parity.read_json(path)
def test_safe_file_open_accepts_regular_files_and_rejects_symlinks(self):
config = self.root / 'regular.json'
config.write_text('{}')
self.assertEqual(parity.read_json(config), {})
config_link = self.root / 'config-link.json'
config_link.symlink_to(config)
with self.assertRaisesRegex(parity.InvalidInput, 'invalid_json'):
parity.read_json(config_link)
archive_link = self.root / 'archive-link.kar'
archive_link.symlink_to(self.archive)
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha):
with self.assertRaisesRegex(parity.InvalidInput, 'archive_file'):
parity.check_archive(archive_link, self.archive_sha)
@unittest.skipUnless(hasattr(os, 'mkfifo'), 'named FIFO unavailable')
def test_named_fifo_is_rejected_quickly_for_json_and_archive(self):
fifo = self.root / 'input.fifo'
os.mkfifo(fifo)
module_path = Path(__file__).with_name('check-ple-config-parity.py')
code = (
"import importlib.util,sys; "
"s=importlib.util.spec_from_file_location('p',sys.argv[1]); "
"m=importlib.util.module_from_spec(s); s.loader.exec_module(m); "
"\ntry:\n"
" if sys.argv[3]=='json': m.read_json(sys.argv[2])\n"
" else: m.check_archive(sys.argv[2],m.PINNED_ARCHIVE_SHA256)\n"
"except m.InvalidInput: pass\nelse: raise SystemExit(9)"
)
for kind in ('json', 'archive'):
with self.subTest(kind=kind):
result = subprocess.run(
[sys.executable, '-c', code, str(module_path), str(fifo), kind],
capture_output=True, text=True, timeout=2)
self.assertEqual(result.returncode, 0, result.stderr)
def test_nonregular_open_failure_closes_the_descriptor(self):
opened = []
real_open = os.open
def capture(path, flags):
fd = real_open(path, flags)
opened.append(fd)
return fd
with patch.object(parity.os, 'open', capture):
with self.assertRaisesRegex(parity.InvalidInput, 'invalid_json'):
parity.open_regular(self.root, 'invalid_json')
self.assertEqual(len(opened), 1)
with self.assertRaises(OSError):
os.fstat(opened[0])
def test_candidate_resource_limits_match_runtime_bounds(self):
cases = []
candidate = json.loads(json.dumps(self.candidate))
candidate['max_in_flight_requests'] = 257
cases.append(candidate)
candidate = json.loads(json.dumps(self.candidate))
candidate['assets'] = [{'manifest': f'/m/{i}', 'directory': f'/a/{i}'}
for i in range(parity.MAX_ASSET_BUNDLES + 1)]
cases.append(candidate)
for memory in ({'required_mib': parity.U64_MAX + 1, 'reserve_mib': 0},
{'required_mib': parity.U64_MAX, 'reserve_mib': 1},
{'required_mib': 1, 'reserve_mib': -1}):
candidate = json.loads(json.dumps(self.candidate))
candidate['cuda_memory'] = memory
cases.append(candidate)
for candidate in cases:
with self.subTest(candidate=candidate):
with self.assertRaisesRegex(parity.InvalidInput, 'candidate_schema'):
parity.validate_candidate(candidate)
def test_unknown_legacy_and_native_keys_are_rejected(self):
legacy = dict(self.legacy, future_secret_setting='opaque')
with self.assertRaisesRegex(parity.InvalidInput, 'legacy_schema'):
parity.validate_legacy(legacy)
with self.assertRaisesRegex(parity.InvalidInput, 'legacy_credential_present'):
parity.validate_legacy(dict(self.legacy, api_key='must-not-be-read'))
candidate = json.loads(json.dumps(self.candidate))
candidate['future_runtime_setting'] = True
with self.assertRaisesRegex(parity.InvalidInput, 'candidate_schema'):
parity.validate_candidate(candidate)
candidate = json.loads(json.dumps(self.candidate))
candidate['engine']['future_runtime_setting'] = True
with self.assertRaisesRegex(parity.InvalidInput, 'candidate_schema'):
parity.validate_candidate(candidate)
def test_candidate_secret_file_is_not_opened_and_output_never_contains_secret(self):
secret_path = Path(self.candidate['api_key_file'])
secret_path.write_text('synthetic-secret-do-not-print')
original_open = Path.open
def guarded_open(path, *args, **kwargs):
if path == secret_path:
raise AssertionError('secret file must not be opened')
return original_open(path, *args, **kwargs)
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha), \
patch.object(Path, 'open', guarded_open):
output = parity.compare(self.legacy, self.candidate, self.context, self.archive,
self.archive_sha, self.candidate_executable,
'127.0.0.1:18081', 'systemd-journal')
encoded = json.dumps(output)
self.assertNotIn('synthetic-secret', encoded)
self.assertEqual(output['status'], 'incomplete')
def test_cli_prints_safe_json_and_returns_two_for_positive_incomplete_fixture(self):
legacy_path = self.root / 'legacy.json'
candidate_path = self.root / 'candidate.json'
context_path = self.root / 'context.json'
for path, value in ((legacy_path, self.legacy), (candidate_path, self.candidate),
(context_path, self.context)):
path.write_text(json.dumps(value))
stdout = io.StringIO()
argv = ['--legacy-config', str(legacy_path), '--candidate-config', str(candidate_path),
'--service-context', str(context_path), '--archive', str(self.archive),
'--archive-sha256', self.archive_sha, '--expected-executable', self.candidate_executable,
'--expected-bind', '127.0.0.1:18081', '--expected-log', 'systemd-journal']
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha), redirect_stdout(stdout):
result = parity.main(argv)
self.assertEqual(result, 2)
self.assertNotIn('synthetic-secret', stdout.getvalue())
self.assertNotIn(str(self.root), stdout.getvalue())
self.assertEqual(json.loads(stdout.getvalue())['status'], 'incomplete')
if __name__ == '__main__':
unittest.main()