Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9519f967a | ||
|
|
4aeec3c541 |
@@ -14,6 +14,7 @@ python3 "${repo_root}/scripts/test-static-cuda-profile.py"
|
||||
python3 "${repo_root}/scripts/test-static-cuda-elf.py"
|
||||
python3 "${repo_root}/scripts/test-linux-package.py"
|
||||
python3 "${repo_root}/scripts/test-runtime-image.py"
|
||||
python3 "${repo_root}/scripts/test-ple-config-parity.py"
|
||||
python3 "${repo_root}/scripts/test-gitea-release.py"
|
||||
python3 "${repo_root}/scripts/test-keyless-routing.py"
|
||||
|
||||
|
||||
Executable
+439
@@ -0,0 +1,439 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline, secret-safe preflight for the Qwen GPU-PLE profile migration.
|
||||
|
||||
This can prove selected settings and the explicitly supplied KAR file digest.
|
||||
It cannot certify deployed parity: credential, model-pack, MTP and incomplete
|
||||
environment identity remain unverified unless separately established. The
|
||||
legacy input must be an operator-supplied redacted projection, not the complete
|
||||
original config; this proves no credential equivalence. Credential-bearing JSON
|
||||
is rejected with a static category after parsing and must not be supplied.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
PINNED_ARCHIVE_SHA256 = '536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5'
|
||||
PINNED_NATIVE_SHARD = 'Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf'
|
||||
PINNED_NATIVE_MANIFEST = 'qwen3.8-flash-next-iq3-s.json'
|
||||
MAX_JSON_BYTES = 1024 * 1024
|
||||
MAX_ARCHIVE_BYTES = 100 * 1024**3
|
||||
MAX_ASSET_BUNDLES = 16
|
||||
U64_MAX = (1 << 64) - 1
|
||||
LEGACY_KEYS = {'exe', 'args', 'cwd', 'log'}
|
||||
FILE_CONFIG_KEYS = {
|
||||
'queue_timeout_s', 'mtp_pack', 'response_history_dir', 'assets',
|
||||
'native_model', 'gpu_requirement', 'cuda_memory', 'engine_probe',
|
||||
'shutdown_grace_s', 'max_in_flight_requests', 'api_key_file', 'bind',
|
||||
'model', 'engine',
|
||||
}
|
||||
ENGINE_KEYS = {
|
||||
'executable', 'args', 'startup_timeout_s', 'generation_timeout_s',
|
||||
'max_restarts', 'tokenizer_dir',
|
||||
}
|
||||
ASSET_KEYS = {'manifest', 'directory'}
|
||||
NATIVE_MODEL_KEYS = {'manifest', 'source_dir', 'output', 'runtime_profile'}
|
||||
CUDA_MEMORY_KEYS = {'required_mib', 'reserve_mib'}
|
||||
NONSECRET_ENV = {
|
||||
'STRATA_BIND', 'STRATA_MODEL_ID', 'STRATA_ENGINE_EXE',
|
||||
'STRATA_ENGINE_ARGS_JSON', 'STRATA_STARTUP_TIMEOUT_S',
|
||||
'STRATA_GENERATION_TIMEOUT_S', 'STRATA_MAX_WORKER_RESTARTS',
|
||||
'STRATA_TOKENIZER_DIR', 'STRATA_MAX_IN_FLIGHT_REQUESTS',
|
||||
'STRATA_QUEUE_TIMEOUT_S', 'STRATA_SHUTDOWN_GRACE_S',
|
||||
'STRATA_RESPONSE_HISTORY_DIR', 'CUDA_VISIBLE_DEVICES',
|
||||
}
|
||||
REQUIRED_SETTINGS = {
|
||||
'--max-context': '262144', '--kv': 'int8', '--kv-resident': '32768',
|
||||
'--spec': '4', '--spec-min-p': '0.5', '--expert-cache': 'auto',
|
||||
'--prefill': 'auto', '--vram-reserve-mib': '700',
|
||||
}
|
||||
PLE_FLAGS = ('--ple-kar', '--ple-kar-level', '--ple-kar-gpu-cache-mib')
|
||||
UNVERIFIED = {
|
||||
'authentication_equivalence', 'legacy_pack_content_equivalence',
|
||||
'mtp_content_equivalence', 'native_runtime_defaults', 'http_capacity_policy',
|
||||
'worker_slot_count', 'request_model_identity', 'source_config_projection',
|
||||
}
|
||||
|
||||
|
||||
class InvalidInput(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _pairs(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise InvalidInput('duplicate_json_key')
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def _constant(_value):
|
||||
raise InvalidInput('nonstandard_json_constant')
|
||||
|
||||
|
||||
def read_json(path):
|
||||
try:
|
||||
with open_regular(path, 'invalid_json') as stream:
|
||||
if os.fstat(stream.fileno()).st_size > MAX_JSON_BYTES:
|
||||
raise InvalidInput('json_size_limit')
|
||||
data = stream.read(MAX_JSON_BYTES + 1)
|
||||
if len(data) > MAX_JSON_BYTES:
|
||||
raise InvalidInput('json_size_limit')
|
||||
return json.loads(data.decode('utf-8'), object_pairs_hook=_pairs,
|
||||
parse_constant=_constant)
|
||||
except InvalidInput:
|
||||
raise
|
||||
except (OSError, UnicodeError, json.JSONDecodeError, RecursionError, OverflowError):
|
||||
raise InvalidInput('invalid_json') from None
|
||||
|
||||
|
||||
def open_regular(path, category):
|
||||
# O_NOFOLLOW and O_NONBLOCK are required together: never fall back to
|
||||
# following a symlink or waiting for a FIFO on unsupported platforms.
|
||||
if not hasattr(os, 'O_NOFOLLOW') or not hasattr(os, 'O_NONBLOCK'):
|
||||
raise InvalidInput('safe_file_open_unavailable')
|
||||
flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK
|
||||
if hasattr(os, 'O_CLOEXEC'):
|
||||
flags |= os.O_CLOEXEC
|
||||
try:
|
||||
fd = os.open(os.fspath(path), flags)
|
||||
except (OSError, TypeError, ValueError):
|
||||
raise InvalidInput(category) from None
|
||||
try:
|
||||
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
||||
raise InvalidInput(category)
|
||||
return os.fdopen(fd, 'rb')
|
||||
except BaseException as error:
|
||||
try:
|
||||
os.close(fd)
|
||||
except OSError:
|
||||
pass
|
||||
if isinstance(error, InvalidInput):
|
||||
raise
|
||||
if isinstance(error, OSError):
|
||||
raise InvalidInput(category) from None
|
||||
raise
|
||||
|
||||
|
||||
def _keys(value, allowed, category):
|
||||
if not isinstance(value, dict) or not set(value).issubset(allowed):
|
||||
raise InvalidInput(category)
|
||||
|
||||
|
||||
def _string(value):
|
||||
return isinstance(value, str) and bool(value)
|
||||
|
||||
|
||||
def _strings(value):
|
||||
return isinstance(value, list) and all(isinstance(item, str) for item in value)
|
||||
|
||||
|
||||
def validate_legacy(value):
|
||||
if isinstance(value, dict) and 'api_key' in value:
|
||||
raise InvalidInput('legacy_credential_present')
|
||||
_keys(value, LEGACY_KEYS, 'legacy_schema')
|
||||
if set(value) != LEGACY_KEYS or not all(_string(value[key]) for key in ('exe', 'cwd', 'log')):
|
||||
raise InvalidInput('legacy_schema')
|
||||
if not _strings(value['args']):
|
||||
raise InvalidInput('legacy_schema')
|
||||
|
||||
|
||||
def validate_candidate(value):
|
||||
_keys(value, FILE_CONFIG_KEYS, 'candidate_schema')
|
||||
if 'engine' not in value or not isinstance(value['engine'], dict):
|
||||
raise InvalidInput('candidate_schema')
|
||||
_keys(value['engine'], ENGINE_KEYS, 'candidate_schema')
|
||||
engine = value['engine']
|
||||
if not _string(engine.get('executable')) or not _strings(engine.get('args', [])):
|
||||
raise InvalidInput('candidate_schema')
|
||||
for key, low, high in (('startup_timeout_s', 1, 3600),
|
||||
('generation_timeout_s', 1, 86400),
|
||||
('max_restarts', 0, 3)):
|
||||
if key in engine and (type(engine[key]) is not int or not low <= engine[key] <= high):
|
||||
raise InvalidInput('candidate_schema')
|
||||
if 'tokenizer_dir' in engine and not _string(engine['tokenizer_dir']):
|
||||
raise InvalidInput('candidate_schema')
|
||||
if 'native_model' not in value or not isinstance(value['native_model'], dict):
|
||||
raise InvalidInput('candidate_schema')
|
||||
_keys(value['native_model'], NATIVE_MODEL_KEYS, 'candidate_schema')
|
||||
if set(value['native_model']) != NATIVE_MODEL_KEYS or value['native_model'].get('runtime_profile') != 'qwen4exp-flash-next':
|
||||
raise InvalidInput('candidate_schema')
|
||||
for key in ('manifest', 'source_dir', 'output'):
|
||||
if not _string(value['native_model'].get(key)):
|
||||
raise InvalidInput('candidate_schema')
|
||||
assets = value.get('assets', [])
|
||||
if (not isinstance(assets, list) or len(assets) > MAX_ASSET_BUNDLES or
|
||||
not all(isinstance(asset, dict) for asset in assets)):
|
||||
raise InvalidInput('candidate_schema')
|
||||
for asset in assets:
|
||||
_keys(asset, ASSET_KEYS, 'candidate_schema')
|
||||
if set(asset) != ASSET_KEYS or not all(_string(asset[key]) for key in ASSET_KEYS):
|
||||
raise InvalidInput('candidate_schema')
|
||||
if 'cuda_memory' in value:
|
||||
_keys(value['cuda_memory'], CUDA_MEMORY_KEYS, 'candidate_schema')
|
||||
if set(value['cuda_memory']) != CUDA_MEMORY_KEYS:
|
||||
raise InvalidInput('candidate_schema')
|
||||
required, reserve = (value['cuda_memory'][key] for key in ('required_mib', 'reserve_mib'))
|
||||
if (type(required) is not int or type(reserve) is not int or required <= 0 or reserve < 0 or
|
||||
required > U64_MAX or reserve > U64_MAX or required + reserve > U64_MAX):
|
||||
raise InvalidInput('candidate_schema')
|
||||
if 'gpu_requirement' in value and value['gpu_requirement'] != 'cuda-13.0-linux':
|
||||
raise InvalidInput('candidate_schema')
|
||||
for key in ('mtp_pack', 'response_history_dir', 'api_key_file', 'bind', 'model'):
|
||||
if key in value and not _string(value[key]):
|
||||
raise InvalidInput('candidate_schema')
|
||||
if 'queue_timeout_s' in value and (type(value['queue_timeout_s']) is not int or
|
||||
not 1 <= value['queue_timeout_s'] <= 86400):
|
||||
raise InvalidInput('candidate_schema')
|
||||
if 'shutdown_grace_s' in value and (type(value['shutdown_grace_s']) is not int or
|
||||
not 0 <= value['shutdown_grace_s'] <= 20):
|
||||
raise InvalidInput('candidate_schema')
|
||||
if 'max_in_flight_requests' in value and (type(value['max_in_flight_requests']) is not int or
|
||||
not 1 <= value['max_in_flight_requests'] <= 256):
|
||||
raise InvalidInput('candidate_schema')
|
||||
if 'engine_probe' in value and type(value['engine_probe']) is not bool:
|
||||
raise InvalidInput('candidate_schema')
|
||||
if 'mtp_pack' not in value or not _string(value['mtp_pack']):
|
||||
raise InvalidInput('candidate_schema')
|
||||
if 'tokenizer_dir' in engine:
|
||||
raise InvalidInput('candidate_schema')
|
||||
|
||||
|
||||
def validate_context(value):
|
||||
_keys(value, {'legacy', 'candidate', 'environment_complete'}, 'service_context_schema')
|
||||
if set(value) != {'legacy', 'candidate', 'environment_complete'} or not isinstance(value['environment_complete'], bool):
|
||||
raise InvalidInput('service_context_schema')
|
||||
for side in ('legacy', 'candidate'):
|
||||
item = value[side]
|
||||
allowed = {'bind', 'cwd', 'log', 'effective_slots', 'environment'}
|
||||
required = allowed - {'effective_slots'}
|
||||
_keys(item, allowed, 'service_context_schema')
|
||||
if not required.issubset(item) or not all(_string(item[k]) for k in ('bind', 'cwd', 'log')):
|
||||
raise InvalidInput('service_context_schema')
|
||||
if ('effective_slots' in item and
|
||||
(type(item['effective_slots']) is not int or item['effective_slots'] < 0)):
|
||||
raise InvalidInput('service_context_schema')
|
||||
env = item['environment']
|
||||
if not isinstance(env, dict) or not set(env).issubset(NONSECRET_ENV):
|
||||
raise InvalidInput('service_context_schema')
|
||||
if not all(isinstance(v, str) for v in env.values()):
|
||||
raise InvalidInput('service_context_schema')
|
||||
|
||||
|
||||
def option_values(arguments, name):
|
||||
found = []
|
||||
index = 0
|
||||
while index < len(arguments):
|
||||
token = arguments[index]
|
||||
if token == name:
|
||||
if index + 1 >= len(arguments) or arguments[index + 1].startswith('--'):
|
||||
raise InvalidInput('engine_arguments')
|
||||
found.append(arguments[index + 1])
|
||||
index += 2
|
||||
elif token.startswith(name + '='):
|
||||
found.append(token[len(name) + 1:])
|
||||
index += 1
|
||||
else:
|
||||
index += 1
|
||||
if len(found) > 1:
|
||||
raise InvalidInput('duplicate_engine_option')
|
||||
return found
|
||||
|
||||
|
||||
def strip_legacy_migrations(arguments):
|
||||
result = []
|
||||
migrated = {'--pack', '--native', '--mtp'}
|
||||
seen = set()
|
||||
index = 0
|
||||
while index < len(arguments):
|
||||
token = arguments[index]
|
||||
name = token.split('=', 1)[0]
|
||||
if name in migrated:
|
||||
if name in seen or token != name or index + 1 >= len(arguments) or arguments[index + 1].startswith('--'):
|
||||
raise InvalidInput('legacy_model_arguments')
|
||||
seen.add(name)
|
||||
index += 2
|
||||
else:
|
||||
result.append(token)
|
||||
index += 1
|
||||
if seen != migrated:
|
||||
raise InvalidInput('legacy_model_arguments')
|
||||
return result
|
||||
|
||||
|
||||
def ple_selection(arguments, archive_path):
|
||||
"""Return argv without its PLE tuple and whether the exact tuple was present."""
|
||||
seen = [token for token in arguments
|
||||
if any(token == flag or token.startswith(flag + '=') for flag in PLE_FLAGS)]
|
||||
if not seen:
|
||||
return list(arguments), False
|
||||
expected = [PLE_FLAGS[0], str(archive_path), PLE_FLAGS[1], '2', PLE_FLAGS[2], '64']
|
||||
if arguments[-len(expected):] != expected:
|
||||
raise InvalidInput('ple_arguments')
|
||||
if len(seen) != len(PLE_FLAGS):
|
||||
raise InvalidInput('ple_arguments')
|
||||
return list(arguments[:-len(expected)]), True
|
||||
|
||||
|
||||
def check_archive(path, expected):
|
||||
if not re.fullmatch(r'[0-9a-f]{64}', expected) or expected != PINNED_ARCHIVE_SHA256:
|
||||
raise InvalidInput('archive_pin')
|
||||
try:
|
||||
stream = open_regular(path, 'archive_file')
|
||||
with stream:
|
||||
if os.fstat(stream.fileno()).st_size > MAX_ARCHIVE_BYTES:
|
||||
raise InvalidInput('archive_size_limit')
|
||||
_verify_archive_stream(stream, expected)
|
||||
except InvalidInput:
|
||||
raise
|
||||
except OSError:
|
||||
raise InvalidInput('archive_file') from None
|
||||
|
||||
|
||||
def _verify_archive_stream(stream, expected):
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
|
||||
size += len(chunk)
|
||||
if size > MAX_ARCHIVE_BYTES:
|
||||
raise InvalidInput('archive_size_limit')
|
||||
digest.update(chunk)
|
||||
if digest.hexdigest() != expected:
|
||||
raise InvalidInput('archive_digest')
|
||||
|
||||
|
||||
def compare(legacy, candidate, context, archive_path, archive_sha, expected_executable,
|
||||
expected_bind, expected_log):
|
||||
validate_legacy(legacy)
|
||||
validate_candidate(candidate)
|
||||
validate_context(context)
|
||||
check_archive(archive_path, archive_sha)
|
||||
mismatches = []
|
||||
unverified = sorted(UNVERIFIED)
|
||||
|
||||
engine = candidate['engine']
|
||||
legacy_args = legacy['args']
|
||||
candidate_args = engine.get('args', [])
|
||||
legacy_env = context['legacy']['environment']
|
||||
candidate_env = context['candidate']['environment']
|
||||
effective_executable = candidate_env.get('STRATA_ENGINE_EXE', engine['executable'])
|
||||
effective_bind = candidate_env.get('STRATA_BIND', candidate.get('bind', '127.0.0.1:8081'))
|
||||
if effective_executable != expected_executable or not _string(expected_executable):
|
||||
mismatches.append('executable_selection')
|
||||
slots = [context[side].get('effective_slots') for side in ('legacy', 'candidate')]
|
||||
if any(value is None for value in slots):
|
||||
unverified.append('worker_slot_count')
|
||||
elif slots != [1, 1]:
|
||||
mismatches.append('slot_count')
|
||||
if context['legacy']['cwd'] != context['candidate']['cwd']:
|
||||
mismatches.append('working_directory')
|
||||
if context['candidate']['bind'] != expected_bind or effective_bind != context['candidate']['bind']:
|
||||
mismatches.append('bind_selection')
|
||||
if context['candidate']['log'] != expected_log:
|
||||
mismatches.append('log_selection')
|
||||
for name in set(legacy_env) | set(candidate_env):
|
||||
if legacy_env.get(name) == candidate_env.get(name):
|
||||
continue
|
||||
if name == 'STRATA_BIND':
|
||||
# The bind delta is explicit and independently checked above.
|
||||
continue
|
||||
if name == 'STRATA_ENGINE_EXE' and candidate_env.get(name) == expected_executable:
|
||||
# The executable delta is explicit and independently checked above.
|
||||
continue
|
||||
mismatches.append('environment_delta')
|
||||
break
|
||||
effective_args = candidate_args
|
||||
if 'STRATA_ENGINE_ARGS_JSON' in candidate_env:
|
||||
try:
|
||||
override = json.loads(candidate_env['STRATA_ENGINE_ARGS_JSON'], object_pairs_hook=_pairs,
|
||||
parse_constant=_constant)
|
||||
except (InvalidInput, json.JSONDecodeError):
|
||||
mismatches.append('engine_arguments')
|
||||
else:
|
||||
if not _strings(override):
|
||||
mismatches.append('engine_arguments')
|
||||
else:
|
||||
effective_args = override
|
||||
if effective_args != candidate_args:
|
||||
mismatches.append('engine_arguments')
|
||||
if 'STRATA_ENGINE_ARGS_JSON' in legacy_env:
|
||||
mismatches.append('environment_delta')
|
||||
if not context['environment_complete']:
|
||||
unverified.append('effective_environment')
|
||||
|
||||
try:
|
||||
legacy_base, _had_legacy_ple = ple_selection(legacy_args, archive_path)
|
||||
legacy_base = strip_legacy_migrations(legacy_base)
|
||||
candidate_base, had_candidate_ple = ple_selection(effective_args, archive_path)
|
||||
expected_base = legacy_base + [
|
||||
PLE_FLAGS[0], str(archive_path), PLE_FLAGS[1], '2', PLE_FLAGS[2], '64']
|
||||
if not had_candidate_ple or candidate_base != legacy_base or effective_args != expected_base:
|
||||
mismatches.append('engine_arguments')
|
||||
for flag, wanted in REQUIRED_SETTINGS.items():
|
||||
if option_values(legacy_args, flag) != [wanted] or option_values(effective_args, flag) != [wanted]:
|
||||
mismatches.append('profile_settings')
|
||||
for flag in ('--pack', '--native', '--gguf', '--mtp'):
|
||||
if option_values(effective_args, flag):
|
||||
mismatches.append('native_asset_mapping')
|
||||
legacy_mtp = option_values(legacy_args, '--mtp')
|
||||
legacy_native = option_values(legacy_args, '--native')
|
||||
if legacy_mtp != [candidate.get('mtp_pack')]:
|
||||
mismatches.append('mtp_asset_mapping')
|
||||
if (len(legacy_native) != 1 or Path(legacy_native[0]).name != PINNED_NATIVE_SHARD or
|
||||
Path(candidate['native_model']['source_dir']) != Path(legacy_native[0]).parent or
|
||||
Path(candidate['native_model']['manifest']).name != PINNED_NATIVE_MANIFEST):
|
||||
mismatches.append('model_selection')
|
||||
except InvalidInput as error:
|
||||
mismatches.append(error.args[0] if error.args and error.args[0] in {
|
||||
'legacy_model_arguments', 'duplicate_engine_option', 'engine_arguments', 'ple_arguments'
|
||||
} else 'engine_arguments')
|
||||
|
||||
if candidate.get('mtp_pack') not in [asset['directory'] for asset in candidate.get('assets', [])]:
|
||||
mismatches.append('mtp_asset_mapping')
|
||||
if context['legacy']['bind'] == '' or context['legacy']['log'] == '':
|
||||
mismatches.append('service_context')
|
||||
if candidate.get('api_key_file') is None:
|
||||
mismatches.append('authentication_configuration')
|
||||
# The candidate's strict schema is checked, but source pack/MTP contents and
|
||||
# credentials are intentionally not opened by this preflight.
|
||||
return {
|
||||
'status': 'mismatch' if mismatches else 'incomplete' if unverified else 'verified',
|
||||
'mismatches': sorted(set(mismatches)),
|
||||
'unverified': sorted(set(unverified)),
|
||||
}
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--legacy-config', required=True,
|
||||
help='operator-supplied redacted projection (exe/args/cwd/log only; never the original file or api_key)')
|
||||
parser.add_argument('--candidate-config', required=True)
|
||||
parser.add_argument('--service-context', required=True)
|
||||
parser.add_argument('--archive', required=True)
|
||||
parser.add_argument('--archive-sha256', required=True)
|
||||
parser.add_argument('--expected-executable', required=True)
|
||||
parser.add_argument('--expected-bind', required=True)
|
||||
parser.add_argument('--expected-log', required=True)
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
result = compare(read_json(args.legacy_config), read_json(args.candidate_config),
|
||||
read_json(args.service_context), args.archive, args.archive_sha256,
|
||||
args.expected_executable, args.expected_bind, args.expected_log)
|
||||
except InvalidInput as error:
|
||||
result = {'status': 'mismatch', 'mismatches': [error.args[0]], 'unverified': sorted(UNVERIFIED)}
|
||||
except Exception:
|
||||
result = {'status': 'mismatch', 'mismatches': ['internal_validation_error'],
|
||||
'unverified': sorted(UNVERIFIED)}
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
return {'verified': 0, 'mismatch': 1, 'incomplete': 2}[result['status']]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,357 @@
|
||||
#!/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/strata-next'
|
||||
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()
|
||||
Reference in New Issue
Block a user