Files
leleka/scripts/smoke-mtp-pack.py
T
Pavlo Ratushnyi faed0f8165 Validate pinned MTP packs before base model acquisition (#17)
* feat: validate pinned MTP packs before base model acquisition

* test: cover additive MTP provision status in bootstrap contracts
2026-10-05 01:45:04 +02:00

152 lines
7.5 KiB
Python

#!/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 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)))
dense = bytearray(); lines = []
for kind, name in names:
kind = 'q8_0' if kind == 'q8' else kind
dense.extend(bytes(-len(dense) % 256))
size = {'q8_0': 34, 'bf16': 64, 'f32': 128}[kind]
lines.append(f'{name} {kind} 1 32 {len(dense)} {size}')
dense.extend(bytes(size))
(source / 'dense.bin').write_bytes(dense)
(source / 'dense.txt').write_text('\n'.join(lines) + '\n')
# 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())
requests = []
class Source(http.server.BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_GET(self):
requests.append(self.path)
path = source / self.path.lstrip('/')
self.send_response(200)
self.send_header('Content-Length', str(path.stat().st_size))
self.end_headers()
with path.open('rb') as data:
shutil.copyfileobj(data, self.wfile, 1024 * 1024)
server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Source)
thread = threading.Thread(target=server.serve_forever, daemon=True); thread.start()
def manifest(path, files):
records = []
for name in files:
with (source / name).open('rb') as f:
digest = hashlib.file_digest(f, 'sha256').hexdigest()
records.append({'name': name, 'size': (source / name).stat().st_size,
'sha256': digest, 'url': f'http://127.0.0.1:{server.server_port}/{name}'})
path.write_text(json.dumps({'schema_version': 1, 'files': records}))
model_manifest = root / 'model.json'; manifest(model_manifest, ['model.gguf'])
mtp_manifest = root / 'mtp.json'; manifest(mtp_manifest, ['dense.txt', 'dense.bin', 'experts.bin'])
marker = root / 'worker-started'
worker = root / 'worker.sh'
worker.write_text('''#!/bin/sh
set -eu
[ "$1" = --serve ]
[ "$3" = --mtp ]; [ -f "$4/experts.bin" ]
[ "$5" = --pack ]; [ -f "$6/receipt.json" ]
[ "$7" = --native ]; [ -f "$8" ]
printf '%s\\n%s\\n%s\\n' "$4" "$6" "$8" > "$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')},
'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)
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; synthetic layout only, no GPU/model qualification')
if __name__ == '__main__':
main()