#!/usr/bin/env python3 """Actual isolated Linux systemd native-profile switch and failed-target rollback. Synthetic CPU workers only. Never inspect or modify any existing unit. """ import fcntl import hashlib import importlib.util import json import os from pathlib import Path import socket import subprocess import sys import tempfile import urllib.request def run(*args, check=True): result = subprocess.run(args, text=True, capture_output=True, timeout=45) if check: assert result.returncode == 0, (args[1:3], result.stderr) return result def main(): binary = Path(sys.argv[1]).resolve() with tempfile.TemporaryDirectory(prefix='strata-native-switch-') as directory: root = Path(directory) fixture_spec = importlib.util.spec_from_file_location('fixture', Path(__file__).with_name('smoke-worker-cancel.py')) fixture = importlib.util.module_from_spec(fixture_spec); fixture_spec.loader.exec_module(fixture) fixture.tokenizer(root) good = root/'good.sh' good.write_text("#!/bin/sh\nprintf 'READY 262144 stop\\n'\nwhile IFS= read -r line; do\n case \"$line\" in\n 'GEN '*) printf 'T 65\\nDONE 1 7 1.0 2.0 stop\\n' ;;\n QUIT) exit 0 ;;\n esac\ndone\n") good.chmod(0o700) bad = root/'bad.sh'; bad.write_text('#!/bin/sh\nexit 17\n'); bad.chmod(0o700) key = root/'key'; key.write_text('native-switch-synthetic-key-00000001'); key.chmod(0o600) with socket.socket() as probe: probe.bind(('127.0.0.1',0)); port=probe.getsockname()[1] origin=f'http://127.0.0.1:{port}' profiles={} unit_dir=Path(os.environ.get('XDG_CONFIG_HOME',Path.home()/'.config'))/'systemd/user' owned=[] def control(name, action, check=True): p=profiles[name] args=[str(binary),'service-control',action,'--config',p['config'],'--working-dir',str(root),'--unit',p['unit']] if action=='start-ready': args+=['--ready-url',origin,'--ready-model',name,'--ready-key-file',str(key),'--ready-timeout-s','5'] return run(*args,check=check) def status(name):return json.loads(control(name,'status').stdout)['manager'] def inference(name): request=urllib.request.Request(origin+'/v1/responses',data=json.dumps({'model':name,'input':'fixture','max_output_tokens':8,'reasoning':{'effort':'none'}}).encode(),headers={'Content-Type':'application/json','Authorization':'Bearer '+key.read_text()}) with urllib.request.urlopen(request,timeout=5) as response: result=json.load(response) assert result['status']=='completed' and result['output'][0]['content'][0]['text']=='A',result catalog=root/'catalog.json'; state=root/'state' def switch(previous,target,check=True): return run(str(binary),'service-switch','--catalog',str(catalog),'--from',previous,'--to',target,'--state-dir',str(state),check=check) def select(target,check=True): return run(str(binary),'service-switch','--catalog',str(catalog),'--to',target,'--state-dir',str(state),check=check) try: for name in ['old','next','bad','preflight']: unit=f'strata-next-switch-{root.name}-{name}.service' unit_path=unit_dir/unit assert not unit_path.exists() and not unit_path.is_symlink() config=root/f'{name}.json' config.write_text(json.dumps({'bind':f'127.0.0.1:{port}','model':name,'api_key_file':str(key),'engine':{'executable':str(bad if name=='bad' else good),'tokenizer_dir':str(root),'startup_timeout_s':1,'max_restarts':0}})) profiles[name]={'unit':unit,'config':str(config),'working_dir':str(root),'url':origin,'model':name,'key_file':str(key),'timeout_s':3} generated=run(str(binary),'service-unit','--config',str(config),'--working-dir',str(root)).stdout owned.append((unit,unit_path,generated)) run(str(binary),'service-install','--config',str(config),'--working-dir',str(root),'--unit',unit) catalog.write_text(json.dumps({'schema_version':1,'profiles':profiles,'provision_timeout_s':10}));catalog.chmod(0o600) # Cold failure is cleaned up; a subsequent cold start needs no --from. result=select('bad',check=False) assert result.returncode!=0 and 'cold_failed' in result.stderr,result.stderr assert status('bad')['main_pid']==0 assert json.loads((state/'transaction.json').read_text())['phase']=='cold_failed' assert json.loads(select('old').stdout)['cold_started'] original=status('old')['main_pid']; inference('old') assert json.loads(select('old').stdout)['reused'] assert status('old')['main_pid']==original; inference('old') # Another managed runtime may be alive on a different actual listener. # Auto discovery refuses ambiguity before contacting either endpoint. preflight=Path(profiles['preflight']['config']) config=json.loads(preflight.read_text()); config['bind']='127.0.0.1:0' preflight.write_text(json.dumps(config)); control('preflight','start') other=status('preflight')['main_pid']; assert other>0 result=select('next',check=False) assert result.returncode!=0 and 'multiple catalog' in result.stderr,result.stderr assert status('old')['main_pid']==original and status('preflight')['main_pid']==other control('preflight','stop'); inference('old') # Parse/preparation failure cannot unload the current model. Path(profiles['preflight']['config']).write_text('{invalid json') result=switch('old','preflight',check=False) assert result.returncode!=0 and 'before previous service drain' in result.stderr,result.stderr assert status('old')['main_pid']==original assert json.loads((state/'transaction.json').read_text())['phase']=='preflight_failed' inference('old') # Cooperative OS locking refuses another transaction before mutation. with (state/'switch.lock').open('r+') as lock: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) assert switch('old','next',check=False).returncode!=0 assert status('old')['main_pid']==original result=json.loads(select('next').stdout) assert result['profile']=='next' and result['switched'] next_pid=status('next')['main_pid']; assert next_pid>0 and status('old')['main_pid']==0 assert not Path(f'/proc/{original}').exists(); inference('next') # Failing target is removed before previous profile is restored. result=select('bad',check=False) assert result.returncode!=0 and 'rolled_back' in result.stderr,result.stderr restored=status('next')['main_pid']; assert restored>0 and restored!=next_pid assert status('bad')['main_pid']==0 and status('old')['main_pid']==0 assert json.loads((state/'transaction.json').read_text())['phase']=='rolled_back' inference('next') # An unfinished durable record is never implicitly replayed. journal=json.loads((state/'transaction.json').read_text());journal['phase']='starting_target' (state/'transaction.json').write_text(json.dumps(journal)) result=switch('next','old',check=False) assert result.returncode!=0 and 'reconciliation' in result.stderr assert status('next')['main_pid']==restored and status('old')['main_pid']==0 inference('next') # Explicit SHA acknowledgment reconciles stable state without lifecycle replay. record=state/'transaction.json'; before=record.read_bytes() digest=hashlib.sha256(before).hexdigest() def reconcile(sha,check=True): return run(str(binary),'service-switch','reconcile','--catalog',str(catalog), '--state-dir',str(state),'--expected-journal-sha',sha,check=check) assert reconcile('0'*64,check=False).returncode!=0 assert record.read_bytes()==before and status('next')['main_pid']==restored original_catalog=catalog.read_bytes();catalog.write_bytes(original_catalog+b' ') assert reconcile(digest,check=False).returncode!=0 catalog.write_bytes(original_catalog);assert record.read_bytes()==before changed=Path(profiles['next']['config']); original_config=changed.read_bytes() changed.write_bytes(original_config+b' ') assert reconcile(digest,check=False).returncode!=0 changed.write_bytes(original_config);assert record.read_bytes()==before extra=Path(profiles['preflight']['config']); extra_before=extra.read_bytes() extra_config=json.loads(original_config);extra_config['bind']='127.0.0.1:0' extra.write_text(json.dumps(extra_config));control('preflight','start') extra_pid=status('preflight')['main_pid'];assert extra_pid>0 result=reconcile(digest,check=False) assert result.returncode!=0 and 'multiple catalog' in result.stderr,result.stderr assert record.read_bytes()==before and status('next')['main_pid']==restored control('preflight','stop');extra.write_bytes(extra_before) reconciled=json.loads(reconcile(digest).stdout) assert reconciled['reconciled'] and not reconciled['lifecycle_action_requested'] assert reconciled['pid']==restored and reconciled['profile']=='next' assert status('next')['main_pid']==restored;inference('next') terminal=record.read_bytes(); assert json.loads(terminal)['prior_journal_sha256']==digest assert reconcile(digest,check=False).returncode!=0 and record.read_bytes()==terminal assert json.loads(select('old').stdout)['profile']=='old';inference('old') # All-inactive reconciliation also allows a later explicit cold start. control('old','stop') prior=json.loads(record.read_bytes());prior['phase']='starting_target' record.write_text(json.dumps(prior));digest=hashlib.sha256(record.read_bytes()).hexdigest() reconciled=json.loads(reconcile(digest).stdout) assert reconciled['pid'] is None and reconciled['profile'] is None assert json.loads(select('next').stdout)['cold_started'];inference('next') print('Native reconciliation passed: wrong SHA/catalog/config preserve record, stable PID/A retained, no lifecycle replay, subsequent switch and all-inactive cold selection') print('Native switch passed: cold failure cleanup/retry, cold start, same-target PID/A reuse, multiple-active refusal, preparation preserves PID/A, OS lock, automatic old-to-next and failed-target rollback/A, durable interrupted refusal; CPU only') finally: for unit,path,generated in reversed(owned): run('systemctl','--user','stop',unit,check=False) if path.is_file() and not path.is_symlink() and path.read_text()==generated:path.unlink() run('systemctl','--user','reset-failed',unit,check=False) run('systemctl','--user','daemon-reload',check=False) if __name__=='__main__':main()