#!/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())