#!/usr/bin/env python3 """Real Linux native CPU processes; simulated GPU ownership and failed backend. Exercises the existing switch transaction and native lifecycle, never CUDA or installed helpers. Synthetic A must survive a failed preflight and match after failed-target rollback. This is not real-model/GPU rollback qualification. """ 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 from types import SimpleNamespace def module(name, file): spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(file)) value = importlib.util.module_from_spec(spec); spec.loader.exec_module(value) return value m = module('switcher', 'strata-model-switch.py') fixture = module('pack_fixture', 'smoke-native-pack.py') helper = module('cancel_fixture', 'smoke-worker-cancel.py') NATIVE = {'backend':'native'} BAD = {'backend':'agent','profile':'failed-cpu-fixture'} def main(): binary = str(Path(sys.argv[1]).resolve()) os.umask(0o077) with tempfile.TemporaryDirectory(prefix='strata-controller-smoke-') as tmp: root = Path(tmp).resolve() with socket.socket() as probe: probe.bind(('127.0.0.1',0)); port=probe.getsockname()[1] cfg = root/'config.json' deployment = dict(schema_version=1,root=str(root/'switch'),native=str(root/'native'), control=str(root/'helpers'),agent_helper=str(root/'agent.py'),binary=binary, config=str(cfg),cwd=str(root),url=f'http://127.0.0.1:{port}',model='controller-fixture') manifest_path=root/'deployment.json';m.save(manifest_path,deployment) deployment=m.load_deployment(manifest_path) class Host(m.Host): def __init__(self): # CPU test substitutes only external backend/ownership adapters. # Native recipe, prepare/launch/stop/restore/readiness/journal are production code. self.deployment=deployment for key in ('root','native','control','binary','config'): setattr(self,key,Path(deployment[key])) self.failed=None self.a=SimpleNamespace(prepare=lambda _:None,start=self.fail_start, status=lambda:{'profile':BAD['profile'],'ready':False},unload=self.fail_stop) def fail_start(self, _): self.failed=subprocess.Popen(['/bin/sleep','60']) return {'started':True} def fail_stop(self, _): self.failed.terminate();self.failed.wait(timeout=5) def inventory(self): result=[] state_path=self.native/'state.json' if state_path.exists(): state=json.loads(state_path.read_text()) if m.same_process(state): result.append({'target':NATIVE,'state':state,'roots':[state['pid']], 'recipe':self.native_recipe()}) if self.failed and self.failed.poll() is None: record=m.identity(self.failed.pid) result.append({'target':BAD,'state':record,'roots':[record['pid']]}) return result def check_owners(self, owners): assert all(m.same_process(o['state']) for o in owners) def free_gpu(self): assert not self.inventory(), 'CPU fixture owner was not released' host=Host() source=root/'sources';source.mkdir() gguf=source/'model.gguf';fixture.write_gguf(gguf,fixture.fixtures()) source_manifest=root/'source.json' m.save(source_manifest,dict(schema_version=1,files=[dict(name='model.gguf', url='http://127.0.0.1:1/not-used',size=gguf.stat().st_size, sha256=hashlib.sha256(gguf.read_bytes()).hexdigest())])) config=dict(bind=f'127.0.0.1:{port}',model=deployment['model'],engine_probe=True, native_model=dict(manifest=str(source_manifest),source_dir=str(source),output=str(root/'pack')), engine=dict(executable='@embedded',startup_timeout_s=5,max_restarts=0)) m.save(cfg,config) host.prepare(NATIVE,15) assert (root/'pack/receipt.json').is_file() assert (root/'pack/tokenizer/vocab.json').is_file() assert not (host.native/'state.json').exists() # Serve the CPU oracle with its own full tokenizer, not the GGUF's tiny vocabulary. tok=root/'tokenizer';tok.mkdir();helper.tokenizer(tok) config.pop('native_model') config['engine'].update(tokenizer_dir=str(tok),args=[str(root/'worker.pid')]) m.save(cfg,config) records=[] def generate(): conn=http.client.HTTPConnection('127.0.0.1',port,timeout=5) try: conn.request('POST','/v1/responses',json.dumps(dict(model=deployment['model'],input='Reply A', max_output_tokens=1,reasoning={'effort':'none'})),{'Content-Type':'application/json'}) response=conn.getresponse();value=json.loads(response.read()) assert response.status==200 and value['status']=='completed' content=value['output'][0]['content'];assert content[0]['text']=='A' return content finally:conn.close() def remember(): state=json.loads((host.native/'state.json').read_text());records.append(state);return state try: # Cold start has no legacy PID/recipe prerequisite. assert m.switch(host,NATIVE,10)['started'] first=remember();expected=generate() config['engine']['executable']='/missing-controller-fixture-engine';m.save(cfg,config) try:m.switch(host,NATIVE,5) except RuntimeError as error:assert 'provisioning failed' in str(error) else:raise AssertionError('bad preflight accepted') assert m.same_process(first) and generate()==expected config['engine']['executable']='@embedded';m.save(cfg,config) assert not m.switch(host,NATIVE,5)['started'] try:m.switch(host,BAD,2) except RuntimeError as error:assert 'previous model restored' in str(error),error else:raise AssertionError('failed target accepted') second=remember() assert second['pid']!=first['pid'] and not m.same_process(first) assert host.failed.poll() is not None and generate()==expected assert json.loads((host.root/'state.json').read_text())['phase']=='restored' host.stop(host.inventory()[0]);assert not host.inventory() print('PASS controller: embedded/native_model provisioning, cold start, failed preflight preservation, reuse, actual CPU failed-target rollback; A exact before/after (zero tolerance); no GPU qualification') finally: for owner in host.inventory():host.stop(owner,failed=True) for state in records: try:os.waitpid(state['pid'],0) except ChildProcessError:pass if host.failed and host.failed.poll() is None: host.failed.terminate();host.failed.wait(timeout=5) if __name__=='__main__':main()