#!/usr/bin/env python3 """Pinned MTP acquisition and structural preflight; synthetic CPU worker only.""" import copy import hashlib import http.client import http.server import importlib.util import json import os from pathlib import Path import re import shutil import socket import subprocess import struct import sys import tempfile import threading import time REPO = Path(__file__).resolve().parents[1] def main(): binary = str(Path(sys.argv[1]).resolve()) spec = importlib.util.spec_from_file_location('native_pack_fixture', Path(__file__).with_name('smoke-native-pack.py')) fixture = importlib.util.module_from_spec(spec) spec.loader.exec_module(fixture) with tempfile.TemporaryDirectory(prefix='strata-mtp-bootstrap-') as tmp: root = Path(tmp).resolve() source = root / 'http'; source.mkdir() # Independent engine-consumer names, rather than the validator's own table. consumer = (REPO / 'engine/strata/src/core/mtp.cpp').read_text() names = sorted(set(re.findall(r'\b(q8|bf16|f32)\("([^" ]+)"\)', consumer))) records = json.loads((REPO / 'engine/strata/bench/results/2026-09-30-community-rtx-5090/mtp-manifest.json').read_text()) shapes = {t['name'].removeprefix('mtp.').removeprefix('layers.0.'): t['shape'] for t in records} names += [('q8', 'self_attn.indexer.index_qk_proj.weight'), ('f32', 'self_attn.indexer.k_layernorm.weight'), ('f32', 'self_attn.indexer.q_layernorm.weight')] offset = 0; lines = [] for kind, name in names: kind = 'q8_0' if kind == 'q8' else kind shape = shapes[name] rows, cols = (1, shape[0]) if len(shape) == 1 else shape offset = (offset + 255) // 256 * 256 size = rows * (cols // 32 * 34 if kind == 'q8_0' else cols * (4 if kind == 'f32' else 2)) lines.append(f'{name} {kind} {rows} {cols} {offset} {size}') offset += size with (source / 'dense.bin').open('wb') as f: f.truncate(offset) # sparse synthetic values; geometry from independent pinned source good_index = '\n'.join(lines) + '\n' (source / 'dense.txt').write_text(good_index) # Invalid pinned pack is deliberately tiny: verify no base-model fetch. (source / 'experts.bin').write_bytes(b'invalid') fixture.write_gguf(source / 'model.gguf', fixture.fixtures(), extra_fields=[ ('qwen4exp.' + k, 4, struct.pack(' "$2" printf 'READY 256 stop\\n' while IFS= read -r line; do case "$line" in QUIT) exit 0 ;; esac; done ''') worker.chmod(0o700) with socket.socket() as probe: probe.bind(('127.0.0.1', 0)); port = probe.getsockname()[1] mtp = root / 'mtp-v1' config = {'bind': f'127.0.0.1:{port}', 'mtp_pack': str(mtp), 'assets': [{'manifest': str(mtp_manifest), 'directory': str(mtp)}], 'native_model': {'manifest': str(model_manifest), 'source_dir': str(root / 'base'), 'output': str(root / 'pack'), 'runtime_profile': 'qwen4exp-flash-next'}, 'engine': {'executable': str(worker), 'args': [str(marker)], 'startup_timeout_s': 5, 'max_restarts': 0}} path = root / 'config.json' env = {'PATH': os.defpath} def run(command='provision', ok=True): path.write_text(json.dumps(config)) result = subprocess.run([binary, command, '--config', str(path)], env=env, capture_output=True, timeout=60) assert (result.returncode == 0) == ok, (result.stdout, result.stderr) return result process = None try: assert json.loads(run('check-config').stdout)['mtp_pack'] == 'pinned_structural_check_pending' assert not mtp.exists() and not requests original = copy.deepcopy(config) for args in [[str(marker), '--mtp', '/unused'], [str(marker), '--mtp=/unused']]: config['engine']['args'] = args run('serve', ok=False) assert not requests and not marker.exists() config = copy.deepcopy(original); config['assets'] = [] run('serve', ok=False); assert not requests config = copy.deepcopy(original) run('serve', ok=False) assert requests == ['/dense.txt', '/dense.bin', '/experts.bin'] assert not (root / 'base').exists() and not marker.exists() invalid = (mtp / 'experts.bin').read_bytes() # Valid sparse shape/size fixture: no inference-quality assertion. with (source / 'experts.bin').open('wb') as f: f.truncate(512 * 3 * (2560 * 640 * 18 // 64)) manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin']) mtp = root / 'mtp-v2' config['mtp_pack'] = str(mtp); config['assets'][0]['directory'] = str(mtp) # Correct bytes/ranges, but transpose the rectangular Q projection. bad_index = good_index.replace('self_attn.q_proj.weight q8_0 12288 2560', 'self_attn.q_proj.weight q8_0 2560 12288') assert bad_index != good_index (source / 'dense.txt').write_text(bad_index) manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin']) assert b'geometry' in run(ok=False).stderr assert not (root / 'base').exists() and not marker.exists() assert '/model.gguf' not in requests assert (mtp / 'dense.txt').read_text() == bad_index # Publish the good profile as a new version; preserve both rejected versions. (source / 'dense.txt').write_text(good_index) manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin']) mtp = root / 'mtp-v3' config['mtp_pack'] = str(mtp); config['assets'][0]['directory'] = str(mtp) assert json.loads(run().stdout)['mtp_pack_structurally_validated'] is True assert requests[-4:] == ['/dense.txt', '/dense.bin', '/experts.bin', '/model.gguf'] assert (root / 'mtp-v1/experts.bin').read_bytes() == invalid and not marker.exists() server.shutdown(); server.server_close(); thread.join() count = len(requests) run() # SHA verification and structural checks, offline reuse. assert len(requests) == count with tempfile.TemporaryFile() as log: process = subprocess.Popen([binary, 'serve', '--config', str(path)], env=env, stdout=log, stderr=log) deadline = time.monotonic() + 60 while True: assert process.poll() is None and time.monotonic() < deadline try: c = http.client.HTTPConnection('127.0.0.1', port, timeout=1) c.request('GET', '/ready'); response = c.getresponse(); response.read(); c.close() if response.status == 200: break except OSError: pass time.sleep(.03) assert marker.read_text().splitlines() == [str(mtp), str(root / 'pack'), str(root / 'base/model.gguf')] process.terminate(); assert process.wait(timeout=8) == 0 finally: if process and process.poll() is None: process.kill(); process.wait(timeout=5) if thread.is_alive(): server.shutdown(); server.server_close(); thread.join() print('MTP bootstrap passed: pinned HTTP, invalid pack before base fetch/worker, exact args, offline reuse and previous version preserved; independent pinned geometry and byte-consistent transpose rejection, synthetic values only, no GPU/model quality qualification') if __name__ == '__main__': main()