#!/usr/bin/env python3 """CPU subprocess bootstrap contract: real download/pack, synthetic worker only.""" import copy import fcntl import hashlib import http.client import http.server import importlib.util import json import os from pathlib import Path import socket import subprocess import sys import tempfile import threading import time def main(): binary = str(Path(sys.argv[1]).resolve()) spec = importlib.util.spec_from_file_location('pack_fixture', Path(__file__).with_name('smoke-native-pack.py')) fixture = importlib.util.module_from_spec(spec) spec.loader.exec_module(fixture) requests = [] data = b'' class Source(http.server.BaseHTTPRequestHandler): def log_message(self, *_): pass def do_GET(self): requests.append(self.path) self.send_response(200) self.send_header('Content-Length', str(len(data))) self.end_headers() self.wfile.write(data) with tempfile.TemporaryDirectory(prefix='strata-native-bootstrap-') as tmp: root = Path(tmp).resolve() gguf = root / 'fixture.gguf' fixture.write_gguf(gguf, fixture.fixtures()) data = gguf.read_bytes() server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Source) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() manifest = root / 'manifest.json' manifest.write_text(json.dumps({'schema_version': 1, 'files': [{ 'name': 'model.gguf', 'url': f'http://127.0.0.1:{server.server_port}/model.gguf', 'size': len(data), 'sha256': hashlib.sha256(data).hexdigest()}]})) marker = root / 'started' worker = root / 'worker.sh' # Assert the actual pinned engine's --native PATH / --pack DIR grammar. worker.write_text('''#!/bin/sh set -eu [ "$1" = --serve ] marker="$2" [ "$3" = --pack ]; pack="$4" [ "$5" = --native ]; source="$6" [ -s "$source" ] && [ -s "$pack/receipt.json" ] [ -s "$pack/dense.bin" ] && [ -s "$pack/tokenizer/vocab.json" ] printf '%s\\n%s\\n' "$pack" "$source" > "$marker" 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] source, output = root / 'sources-v1', root / 'pack-v1' config = {'bind': f'127.0.0.1:{port}', 'native_model': { 'manifest': str(manifest), 'source_dir': str(source), 'output': str(output)}, 'engine': {'executable': str(worker), 'args': [str(marker)], 'startup_timeout_s': 5, 'max_restarts': 0}} config_path = root / 'config.json' env = {'PATH': os.defpath} count = 0 processes = [] def save(): config_path.write_text(json.dumps(config)) def run(command='provision', ok=True): nonlocal count save() r = subprocess.run([binary, command, '--config', str(config_path)], env=env, capture_output=True, text=True, timeout=15) assert (r.returncode == 0) == ok, (r.stdout, r.stderr) count += 1 return r def gated_failure(): marker.unlink(missing_ok=True) run('serve', ok=False) assert not marker.exists() with socket.socket() as check: check.bind(('127.0.0.1', port)) def start(): nonlocal count save() log = open(root / f'serve-{len(processes)}.log', 'w+') p = subprocess.Popen([binary, 'serve', '--config', str(config_path)], env=env, stdout=log, stderr=log) processes.append((p, log)) deadline = time.monotonic() + 12 while time.monotonic() < deadline: assert p.poll() is None, 'server exited during bootstrap' 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, http.client.HTTPException): pass time.sleep(.03) else: raise AssertionError('bootstrap never ready') assert marker.read_text().splitlines() == [config['native_model']['output'], str(source / 'model.gguf')] p.terminate(); p.wait(timeout=8) count += 1 try: report = json.loads(run('check-config').stdout) assert report['native_model_configured'] and not report['native_model_verified'] and not report['tokenizer_validated'] assert not requests and not source.exists() and not output.exists() # Malformed other asset manifest must fail before any source acquisition. bad = root / 'bad.json'; bad.write_text('{}') config['assets'] = [{'manifest': str(bad), 'directory': str(root / 'aux')}] gated_failure() assert not requests del config['assets'] start() # Empty node -> download -> exact conversion -> synthetic worker -> ready. assert requests == ['/model.gguf'] before = {str(p.relative_to(output)): p.read_bytes() for p in output.rglob('*') if p.is_file()} server.shutdown(); server.server_close(); thread.join() report = json.loads(run().stdout) assert report['native_model_prepared'] and not report['worker_started'] start() # Offline startup, no regeneration. assert requests == ['/model.gguf'] assert before == {str(p.relative_to(output)): p.read_bytes() for p in output.rglob('*') if p.is_file()} # Each invalid cache must fail before listener/worker and preserve the damaged version. dense = output / 'dense.bin'; original = dense.read_bytes() dense.write_bytes(bytes([original[0] ^ 1]) + original[1:]) gated_failure(); assert dense.read_bytes() != original dense.write_bytes(original) extra = output / 'extra'; extra.write_text('unexpected'); gated_failure(); extra.unlink() receipt = output / 'receipt.json'; raw = receipt.read_bytes() r = json.loads(raw); r['sources']['model.gguf']['sha256'] = '0' * 64 receipt.write_text(json.dumps(r)); gated_failure(); receipt.write_bytes(raw) dense.unlink(); dense.symlink_to(gguf); gated_failure(); dense.unlink(); dense.write_bytes(original) raw_source = (source / 'model.gguf').read_bytes() (source / 'model.gguf').write_bytes(b'bad'); gated_failure(); (source / 'model.gguf').write_bytes(raw_source) lock = open(root / '.pack-v1.native-model-lock', 'a+') fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) gated_failure(); lock.close() # New version failure must never mutate previous validated output. wrong = root / 'wrong.gguf'; fixture.write_gguf(wrong, fixture.fixtures(), architecture='unsupported') source2 = root / 'sources-v2'; source2.mkdir(); (source2 / 'model.gguf').write_bytes(wrong.read_bytes()) manifest2 = root / 'manifest-v2.json'; m = json.loads(manifest.read_text()) m['files'][0].update(size=wrong.stat().st_size, sha256=hashlib.sha256(wrong.read_bytes()).hexdigest()) manifest2.write_text(json.dumps(m)) initial = copy.deepcopy(config) config['native_model'].update(manifest=str(manifest2), source_dir=str(source2), output=str(root / 'pack-v2')) gated_failure(); assert not (root / 'pack-v2').exists() assert before == {str(p.relative_to(output)): p.read_bytes() for p in output.rglob('*') if p.is_file()} config = copy.deepcopy(initial) config['native_model']['output'] = str(source / 'inside'); gated_failure() config = copy.deepcopy(initial) alias = root / 'pack-alias'; alias.symlink_to(output, target_is_directory=True) config['native_model']['source_dir'] = str(alias / 'new-sources') gated_failure() assert not (output / 'new-sources').exists() alias.unlink() config = copy.deepcopy(initial) config['engine']['args'].append('--native'); gated_failure() config = copy.deepcopy(initial) config['engine']['tokenizer_dir'] = str(output / 'tokenizer'); gated_failure() config = copy.deepcopy(initial) del config['engine']; run(ok=False) print(json.dumps({'status': 'passed', 'scenarios': count, 'real_model': False, 'worker': 'synthetic', 'gpu_used': False})) finally: for p, log in processes: if p.poll() is None: p.kill(); p.wait(timeout=5) log.close() if thread.is_alive(): server.shutdown(); server.server_close(); thread.join() if __name__ == '__main__': main()