#!/usr/bin/env python3 """Verify an embedded synthetic CPU ELF through the Linux serving supervisor.""" import fcntl import errno import hashlib import http.client import importlib.util import json import os from pathlib import Path import signal import socket import subprocess import sys import tempfile import time def main(): binary = Path(sys.argv[1]).resolve() fixture = Path(sys.argv[2]).resolve() info = json.loads(subprocess.check_output([binary, 'engine-info'])) assert info['embedded'] is True and info['shared_libraries_bundled'] is False assert info['sha256'] == hashlib.sha256(fixture.read_bytes()).hexdigest() assert info['bytes'] == fixture.stat().st_size assert subprocess.check_output([binary, 'engine-help'], text=True).strip() == 'embedded fixture help (GPU hidden)' spec = importlib.util.spec_from_file_location('cancel_smoke', Path(__file__).with_name('smoke-worker-cancel.py')) helper = importlib.util.module_from_spec(spec) spec.loader.exec_module(helper) with tempfile.TemporaryDirectory(prefix='strata-embedded-smoke-') as directory: root = Path(directory) helper.tokenizer(root) pid_file = root / 'worker.pid' with socket.socket() as probe: probe.bind(('127.0.0.1', 0)) port = probe.getsockname()[1] config = root / 'config.json' config.write_text(json.dumps({'bind': f'127.0.0.1:{port}', 'model': 'embedded-fixture', 'engine_probe': True, 'engine': {'executable': '@embedded', 'args': [str(pid_file)], 'tokenizer_dir': str(root), 'startup_timeout_s': 5, 'max_restarts': 1}})) checked = json.loads(subprocess.check_output( [binary, 'check-config', '--config', config], env={'PATH': os.defpath}, text=True)) assert checked['engine'] == 'embedded' and checked['inference_configured'] assert checked['readiness_checked'] is False and not pid_file.exists() assert checked['engine_probe_configured'] and not checked['engine_probe_checked'] provisioned = json.loads(subprocess.check_output([binary, 'provision', '--config', str(config)], text=True)) assert not provisioned['worker_started'] and not pid_file.exists() def request(path, body=None): connection = http.client.HTTPConnection('127.0.0.1', port, timeout=10) try: connection.request('POST' if body else 'GET', path, body, {'Content-Type': 'application/json'}) response = connection.getresponse() return response.status, json.loads(response.read()) finally: connection.close() with tempfile.TemporaryFile() as log: process = subprocess.Popen([binary, 'serve', '--config', config], env={'PATH': os.defpath}, stdout=log, stderr=log) worker_pids = [] try: def ready(previous=None): deadline = time.monotonic() + 10 while time.monotonic() < deadline: assert process.poll() is None try: pid = int(pid_file.read_text()) if pid != previous and request('/status')[1]['ready']: worker_pids.append(pid) return pid except (OSError, ValueError): pass time.sleep(.02) raise AssertionError('embedded worker did not become ready') first = ready() memfds = [] for path in Path(f'/proc/{process.pid}/fd').iterdir(): try: if 'memfd:strata-engine' in os.readlink(path): memfds.append(path) except FileNotFoundError: pass # HTTP socket fds can close between enumeration and readlink. assert len(memfds) == 1 fd_path = memfds[0] assert hashlib.sha256(fd_path.read_bytes()).hexdigest() == info['sha256'] with fd_path.open('rb', buffering=0) as handle: assert fcntl.fcntl(handle, fcntl.F_GET_SEALS) & 15 == 15 try: with fd_path.open('r+b', buffering=0) as handle: handle.write(b'x') raise AssertionError('sealed engine allowed a write') except OSError as error: assert error.errno in (errno.EPERM, errno.ETXTBSY), error def generate(): code, result = request('/v1/responses', json.dumps({ 'model': 'embedded-fixture', 'input': 'Reply A', 'max_output_tokens': 1, 'reasoning': {'effort': 'none'}})) assert code == 200 and result['status'] == 'completed', result assert result['output'][0]['content'][0]['text'] == 'A', result return result['output'][0]['content'] expected = generate() os.kill(first, signal.SIGKILL) second = ready(first) assert second != first and generate() == expected process.terminate() assert process.wait(timeout=10) == 0 assert not fd_path.exists() assert all(not Path(f'/proc/{pid}').exists() for pid in worker_pids) # The identical fixture as an external executable is the baseline. external = json.loads(config.read_text()) external['engine']['executable'] = str(fixture) config.write_text(json.dumps(external)) process = subprocess.Popen([binary, 'serve', '--config', config], env={'PATH': os.defpath}, stdout=log, stderr=log) ready(second) assert generate() == expected process.terminate() assert process.wait(timeout=10) == 0 assert all(not Path(f'/proc/{pid}').exists() for pid in worker_pids) finally: if process.poll() is None: process.terminate() try: process.wait(timeout=10) except subprocess.TimeoutExpired: process.kill(); process.wait() print('Embedded CPU ELF passed: exact payload digest, seals, inference A, crash restart, external baseline equality, worker/fd cleanup') if __name__ == '__main__': main()