#!/usr/bin/env python3 """Check native unit syntax; optionally exercise an isolated CPU-only user service. Requires Linux/systemd. --lifecycle needs a running user manager. It never touches an existing inference service. Activation tests use only the temporary owned unit. """ import argparse import concurrent.futures import http.server import importlib.util import threading import json import os from pathlib import Path import shutil import socket import subprocess import tempfile import time import urllib.error import urllib.request def run(*args, check=True, env=None): return subprocess.run(args, check=check, text=True, capture_output=True, timeout=60, env=env) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('binary', type=Path) parser.add_argument('--lifecycle', action='store_true') args = parser.parse_args() with tempfile.TemporaryDirectory(prefix='strata-next-install-') as directory: root = Path(directory) # Exercise literal $, systemd % specifiers, quoting and C escaping. odd = root / 'space %n ${HOME} "quote" back\\slash' odd.mkdir() binary = root / 'strata-next %n ${HOME}' shutil.copy2(args.binary.resolve(), binary) config = odd / 'config.json' env_file = root / 'runtime %n ${HOME} "quote".env' with socket.socket() as probe: probe.bind(('127.0.0.1', 0)) port = probe.getsockname()[1] config.write_text(json.dumps({'bind': f'127.0.0.1:{port}', 'model': 'service-smoke'})) env_file.write_text('STRATA_CONFIG=/definitely-missing-service-smoke.json\n' 'STRATA_MODEL_ID=service-smoke-env\n') unit_name = root.name + '.service' unit = root / unit_name generated = run(str(binary), 'service-unit', '--config', str(config), '--working-dir', str(odd), '--env-file', str(env_file)).stdout unit.write_text(generated) # Offline verification still initializes a user manager context. CI's # runner container has no login session or /run/user directory; provide # only this invocation with a private runtime directory, not a live bus. verify_runtime = root / 'verify-runtime' verify_runtime.mkdir(mode=0o700) verify_env = dict(os.environ, XDG_RUNTIME_DIR=str(verify_runtime)) verify = run('systemd-analyze', '--user', 'verify', str(unit), check=False, env=verify_env) assert verify.returncode == 0, verify.stderr # The renderer must fail closed, before printing any installable unit. bad = run(str(binary), 'service-unit', '--config', 'relative.json', '--working-dir', str(odd), check=False) assert bad.returncode != 0 and not bad.stdout pattern_env = root / 'runtime[1].env' pattern_env.write_text('') bad = run(str(binary), 'service-unit', '--config', str(config), '--working-dir', str(odd), '--env-file', str(pattern_env), check=False) assert bad.returncode != 0 and not bad.stdout # Offline fault: the unit survives a failed manager command for retry. fake_bin = root / 'fake-bin' fake_bin.mkdir() fake_ctl = fake_bin / 'systemctl' fake_ctl.write_text('#!/bin/sh\nexit 42\n') fake_ctl.chmod(0o700) fault_home = root / 'fault-config' fault_env = dict(os.environ, XDG_CONFIG_HOME=str(fault_home), PATH=str(fake_bin) + os.pathsep + os.environ['PATH']) fault_args = (str(binary), 'service-install', '--config', str(config), '--working-dir', str(odd), '--unit', unit_name) failed = run(*fault_args, check=False, env=fault_env) assert failed.returncode != 0 and 'daemon-reload' in failed.stderr and 'unit retained' in failed.stderr fault_unit = fault_home / 'systemd/user' / unit_name retained = fault_unit.read_bytes() fault_inode = fault_unit.stat().st_ino fake_ctl.write_text('#!/bin/sh\nexit 0\n') reused = json.loads(run(*fault_args, env=fault_env).stdout) assert reused['reused'] and fault_unit.stat().st_ino == fault_inode fault_unit.unlink() fault_unit.symlink_to(root / 'absent-unit') assert run(*fault_args, env=fault_env, check=False).returncode != 0 assert fault_unit.is_symlink() and not (root / 'absent-unit').exists() fault_unit.unlink() fault_unit.write_bytes(retained) fault_unit.chmod(0o600) fake_ctl.write_text(f"""#!/bin/sh if [ "$3" = show ]; then echo "FragmentPath=$XDG_CONFIG_HOME/systemd/user/{unit_name}" echo "DropInPaths=" echo "NeedDaemonReload=no" fi [ "$3" = start ] && exit 42 exit 0 """) failed = run(*fault_args, '--start', env=fault_env, check=False) assert failed.returncode != 0 and 'systemctl --user start' in failed.stderr assert fault_unit.read_bytes() == retained fake_ctl.write_text('#!/bin/sh\necho FragmentPath=/different.service\necho DropInPaths=\n') failed = run(*fault_args, '--start', env=fault_env, check=False) assert failed.returncode != 0 and 'start was not requested' in failed.stderr assert fault_unit.read_bytes() == retained # Native control reads the exact existing unit and never installs/reloads. commands = root / 'control-commands' def manager(fragment=None, drop_ins='', reload='no', status='ActiveState=active\nSubState=running\nMainPID=123\nUnitFileState=disabled\n', fail_action=False): fragment = fragment or str(fault_unit) fake_ctl.write_text(f"""#!/bin/sh printf '%s|%s|%s|%s|%s\\n' "$1" "$2" "$3" "$4" "$5" >> '{commands}' if [ "$3" = show ]; then if [ "$4" = --property=FragmentPath ]; then printf '%s\\n' 'FragmentPath={fragment}' 'DropInPaths={drop_ins}' 'NeedDaemonReload={reload}' else printf '%s' '{status}' fi exit 0 fi exit {42 if fail_action else 0} """) def control(action, check=True): return run(str(binary), 'service-control', action, *fault_args[2:], env=fault_env, check=check) manager() for action in ['status', 'start', 'stop', 'restart', 'enable', 'disable']: commands.write_text('') result = json.loads(control(action).stdout) assert result['manager'] == {'active_state': 'active', 'sub_state': 'running', 'main_pid': 123, 'unit_file_state': 'disabled'} assert result['action_requested'] == (action != 'status') and result['model_readiness'] == 'not_checked' lines = commands.read_text().splitlines() expected = ['show', 'show'] if action == 'status' else ['show', action, 'show'] if action in ('enable', 'disable'): expected.insert(2, 'show') assert [line.split('|')[2] for line in lines] == expected if action != 'status': assert lines[1] == f'--user|--no-pager|{action}|--|{unit_name}' assert fault_unit.read_bytes() == retained # Readiness inputs and private credentials are checked before any manager call. for ready_args in [[], ['--ready-url', 'http://192.0.2.1', '--ready-model', 'fixture'], ['--ready-url', 'http://127.0.0.1:1', '--ready-model', 'fixture', '--ready-key-file', str(root/'absent-key')]]: commands.write_text('') bad = run(str(binary), 'service-control', 'restart-ready', *fault_args[2:], *ready_args, env=fault_env, check=False) assert bad.returncode != 0 and not commands.read_text(), bad.stderr # Change identity only after the HTTP response. Success requires a fresh # manager/file check and cannot replay start to hide the mismatch. for changed in ('pid', 'fragment', 'unit'): manager(); commands.write_text('') class ChangingEndpoint(http.server.BaseHTTPRequestHandler): def do_GET(self): if changed == 'pid': manager(status='ActiveState=active\nSubState=running\nMainPID=124\nUnitFileState=disabled\n') elif changed == 'fragment': manager(fragment='/changed.service') else: fault_unit.write_text('changed during wait') data = json.dumps({'service':'strata-control', 'model':'fixture', 'server_pid':123, 'ready':True, 'worker':'ready'}).encode() self.send_response(200); self.send_header('Content-Length', str(len(data))) self.end_headers(); self.wfile.write(data) def log_message(self, *_): pass changed_http = http.server.ThreadingHTTPServer(('127.0.0.1', 0), ChangingEndpoint) changed_thread = threading.Thread(target=changed_http.serve_forever, daemon=True); changed_thread.start() try: bad = run(str(binary), 'service-control', 'start-ready', *fault_args[2:], '--ready-url', f'http://127.0.0.1:{changed_http.server_port}', '--ready-model', 'fixture', '--ready-timeout-s', '2', env=fault_env, check=False) assert bad.returncode != 0, bad.stdout actions = [line.split('|')[2] for line in commands.read_text().splitlines()] assert actions.count('start') == 1 and all(a in ('start','show') for a in actions), actions finally: changed_http.shutdown(); changed_http.server_close(); changed_thread.join(timeout=5) fault_unit.write_bytes(retained) for fragment, drop_ins in [('/different.service', ''), (None, '/unexpected.conf')]: manager(fragment, drop_ins); commands.write_text('') assert control('restart', check=False).returncode != 0 assert [x.split('|')[2] for x in commands.read_text().splitlines()] == ['show'] manager(reload='yes'); commands.write_text('') assert control('restart', check=False).returncode != 0 assert [x.split('|')[2] for x in commands.read_text().splitlines()] == ['show'] manager(fail_action=True); commands.write_text('') failed = control('restart', check=False) assert failed.returncode != 0 and 'may be pending' in failed.stderr assert [x.split('|')[2] for x in commands.read_text().splitlines()] == ['show', 'restart'] manager(status='ActiveState=active\nSubState=running\nMainPID=invalid\n') assert control('status', check=False).returncode != 0 manager(); commands.write_text('') fault_unit.chmod(0o644) assert control('stop', check=False).returncode != 0 and not commands.read_text() fault_unit.chmod(0o600) fault_unit.write_text('different') assert control('stop', check=False).returncode != 0 and not commands.read_text() fault_unit.unlink(); fault_unit.symlink_to(root/'absent-control') assert control('stop', check=False).returncode != 0 and not commands.read_text() fault_unit.unlink() assert control('status', check=False).returncode != 0 and not fault_unit.exists() fault_unit.write_bytes(retained); fault_unit.chmod(0o600) if not args.lifecycle: print('Native systemd unit syntax and rejected-path checks passed') return def ctl(*commands, check=True): return run('systemctl', '--user', *commands, check=check) link = Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config')) / 'systemd/user' / unit_name assert not link.exists() and not link.is_symlink(), 'refusing to replace a user unit' try: install_args = (str(binary), 'service-install', '--config', str(config), '--working-dir', str(odd), '--env-file', str(env_file), '--unit', unit_name) installed = json.loads(run(*install_args, '--start').stdout) assert installed['created'] and not installed['reused'], installed assert installed['model_readiness'] == 'not_checked' and not installed['enable_requested'], installed assert link.read_text() == generated and link.stat().st_mode & 0o777 == 0o600 inode = link.stat().st_ino original_pid = ctl('show', '--property=MainPID', '--value', unit_name).stdout.strip() repeated = json.loads(run(*install_args, '--start').stdout) assert ctl('show', '--property=MainPID', '--value', unit_name).stdout.strip() == original_pid assert repeated['reused'] and not repeated['created'], repeated assert link.stat().st_ino == inode # A different config path must not replace the active service unit. other = odd / 'other-config.json' other.write_text(config.read_text()) bad = run(str(binary), 'service-install', '--config', str(other), '--working-dir', str(odd), '--unit', unit_name, '--start', check=False) assert bad.returncode != 0 and not bad.stdout assert link.read_text() == generated and link.stat().st_ino == inode deadline = time.monotonic() + 15 while True: try: with urllib.request.urlopen(f'http://127.0.0.1:{port}/status', timeout=1) as response: state = json.load(response) break except (OSError, urllib.error.URLError): assert time.monotonic() < deadline, 'isolated service failed to listen' time.sleep(0.05) assert state['model'] == 'service-smoke-env', state assert state['worker'] == 'unconfigured' and not state['ready'], state with urllib.request.urlopen(f'http://127.0.0.1:{port}/health', timeout=1) as response: assert response.status == 200 try: urllib.request.urlopen(f'http://127.0.0.1:{port}/ready', timeout=1) raise AssertionError('no-worker service must not claim inference readiness') except urllib.error.HTTPError as error: assert error.code == 503 error.close() # Installer readiness is bounded and never treats no-worker health as ready. before=ctl('show','--property=MainPID','--value',unit_name).stdout.strip() bad=run(*install_args,'--start-ready','--ready-url',f'http://127.0.0.1:{port}', '--ready-model','service-smoke-env','--ready-timeout-s','1',check=False) assert bad.returncode!=0 and 'retained' in bad.stderr,bad.stderr assert link.read_text()==generated assert ctl('show','--property=MainPID','--value',unit_name).stdout.strip()==before def native_ctl(action): result = run(str(binary), 'service-control', action, *install_args[2:], check=False) assert result.returncode == 0, (action, result.stderr, ctl('show', '--property=NeedDaemonReload', '--property=UnitFileState', unit_name).stdout) return json.loads(result.stdout) status = native_ctl('status') assert status['manager']['active_state'] == 'active' and status['model_readiness'] == 'not_checked' pid = status['manager']['main_pid'] assert pid == int(original_pid) and state['server_pid'] == pid assert native_ctl('start')['manager']['main_pid'] == pid assert status['manager']['unit_file_state'] == 'disabled' activation = link.parent / 'default.target.wants' / unit_name assert not activation.exists() and not activation.is_symlink() # Opt-in installation reuses the unit and enables without starting/restarting. enabled = json.loads(run(*install_args, '--enable').stdout) assert enabled['reused'] and enabled['enable_requested'] and not enabled['start_requested'] assert activation.is_symlink() and activation.resolve() == link.resolve() for _ in range(2): state = native_ctl('enable')['manager'] assert state['main_pid'] == pid and state['unit_file_state'] == 'enabled', state for _ in range(2): state = native_ctl('disable')['manager'] assert state['main_pid'] == pid and state['unit_file_state'] == 'disabled', state assert not activation.exists() and not activation.is_symlink() # Both activation directions must preserve a conflicting link. activation.parent.mkdir(exist_ok=True) activation.symlink_to(root / 'foreign-missing-unit') activation_inode = activation.lstat().st_ino for action in ('enable', 'disable'): bad = run(str(binary), 'service-control', action, *install_args[2:], check=False) assert bad.returncode != 0 and activation.lstat().st_ino == activation_inode assert int(ctl('show', '--property=MainPID', '--value', unit_name).stdout) == pid activation.unlink() # An intentionally altered activation link can mark the manager # stale. Reconcile the owned fixture after restoring it. ctl('daemon-reload') for action in ('enable', 'disable'): bad = run(str(binary), 'service-control', action, '--config', str(other), '--working-dir', str(odd), '--unit', unit_name, check=False) assert bad.returncode != 0 and not activation.exists() assert native_ctl('status')['manager']['main_pid'] == pid assert Path(f'/proc/{pid}/cwd').resolve() == odd.resolve() assert Path(f'/proc/{pid}/exe').resolve() == binary.resolve() # Wrong rendered config must fail before touching the running service. bad = run(str(binary), 'service-control', 'stop', '--config', str(other), '--working-dir', str(odd), '--unit', unit_name, check=False) assert bad.returncode != 0 and native_ctl('status')['manager']['main_pid'] == pid restarted = native_ctl('restart') next_pid = restarted['manager']['main_pid'] assert next_pid > 0 and next_pid != pid and not Path(f'/proc/{pid}').exists() for _ in range(2): stopped = native_ctl('stop') assert stopped['manager']['active_state'] == 'inactive' and stopped['manager']['main_pid'] == 0 assert not Path(f'/proc/{next_pid}').exists() assert native_ctl('status')['manager']['active_state'] == 'inactive' assert native_ctl('start')['manager']['main_pid'] > 0 native_ctl('stop') # Configure only this stopped, owned fixture for synthetic inference. spec = importlib.util.spec_from_file_location('worker_fixture', Path(__file__).with_name('smoke-worker-cancel.py')) fixture = importlib.util.module_from_spec(spec) spec.loader.exec_module(fixture) tokens = root / 'tokens'; tokens.mkdir(); fixture.tokenizer(tokens) engine = root / 'ready-worker.sh' engine.write_text("#!/bin/sh\nprintf 'READY 262144 stop\\n'\nwhile IFS= read -r line; do\n case \"$line\" in\n 'GEN '*) : > \"$2/begun\"; while [ -e \"$2/hold\" ]; do sleep 0.01; done; printf 'T 65\\nDONE 1 7 1.0 2.0 stop\\n' ;;\n QUIT) exit 0 ;;\n esac\ndone\n") engine.chmod(0o700) key_file = root / 'api.key'; key_file.write_text('service-fixture-private-key-0123456789'); key_file.chmod(0o600) config.write_text(json.dumps({'bind': f'127.0.0.1:{port}', 'model': 'service-smoke', 'api_key_file': str(key_file), 'engine': {'executable': str(engine), 'args':[str(root)], 'tokenizer_dir': str(tokens)}})) ready_args = ['--ready-url', f'http://127.0.0.1:{port}', '--ready-model', 'service-smoke-env', '--ready-key-file', str(key_file), '--ready-timeout-s', '10'] def ready_control(action, options=ready_args, check=True): value = run(str(binary), 'service-control', action, *install_args[2:], *options, check=False) if check: assert value.returncode == 0, value.stderr return value def inference(): request = urllib.request.Request(f'http://127.0.0.1:{port}/v1/responses', data=json.dumps({'model':'service-smoke-env', 'input':'fixture', 'max_output_tokens':8, 'reasoning':{'effort':'none'}}).encode(), headers={'Content-Type':'application/json', 'Authorization':'Bearer service-fixture-private-key-0123456789'}) with urllib.request.urlopen(request, timeout=15) as response: value = json.load(response) assert value['status'] == 'completed', value assert value['output'][0]['content'][0]['text'] == 'A', value # Recreate only the stopped owned fixture to prove fresh install+ready. assert native_ctl('status')['manager']['main_pid']==0 assert link.read_text()==generated link.unlink();ctl('daemon-reload') bad=run(*install_args,'--start-ready',*ready_args[:4], '--ready-key-file',str(root/'missing-key'),check=False) assert bad.returncode!=0 and not link.exists() first=json.loads(run(*install_args,'--start-ready',*ready_args).stdout) assert first['created'] and first['start_requested'] pid = first['manager']['main_pid'] assert first['model_readiness'] == 'ready' and first['readiness']['server_pid'] == pid inference() repeated=json.loads(run(*install_args,'--start-ready',*ready_args).stdout) assert repeated['reused'] and repeated['manager']['main_pid']==pid assert repeated['readiness']['server_pid']==pid assert json.loads(ready_control('start-ready').stdout)['manager']['main_pid'] == pid for bad_options in [ready_args + ['--ready-timeout-s', '0'], ready_args[:4] + ['--ready-key-file', str(root/'missing-key')]]: assert ready_control('restart-ready', bad_options, check=False).returncode != 0 assert native_ctl('status')['manager']['main_pid'] == pid response_body = {'service':'strata-control', 'model':'service-smoke-env', 'ready':True, 'worker':'ready', 'server_pid':1} class OtherEndpoint(http.server.BaseHTTPRequestHandler): def do_GET(self): data = json.dumps(response_body).encode() self.send_response(200); self.send_header('Content-Length', str(len(data))) self.end_headers(); self.wfile.write(data) def log_message(self, *_): pass other_http = http.server.ThreadingHTTPServer(('127.0.0.1', 0), OtherEndpoint) thread = threading.Thread(target=other_http.serve_forever, daemon=True); thread.start() try: wrong = ready_args.copy(); wrong[1] = f'http://127.0.0.1:{other_http.server_port}' bad = ready_control('start-ready', wrong, check=False) assert bad.returncode != 0 and 'managed server PID' in bad.stderr, bad.stderr response_body.update(server_pid=pid, ready=False, worker='starting') wrong[-1] = '1' began = time.monotonic() bad = ready_control('start-ready', wrong, check=False) assert bad.returncode != 0 and 'deadline expired' in bad.stderr and time.monotonic()-began < 5, bad.stderr assert native_ctl('status')['manager']['main_pid'] == pid inference() finally: other_http.shutdown(); other_http.server_close(); thread.join(timeout=5) restarted = json.loads(ready_control('restart-ready').stdout) new_pid = restarted['manager']['main_pid'] assert new_pid != pid and restarted['readiness']['server_pid'] == new_pid and not Path(f'/proc/{pid}').exists() inference() def admin(path='/admin/lifecycle', payload=None): req = urllib.request.Request(f'http://127.0.0.1:{port}'+path, data=json.dumps(payload).encode() if payload is not None else None, headers={'Authorization':'Bearer '+key_file.read_text(), 'Content-Type':'application/json'}) with urllib.request.urlopen(req, timeout=3) as response: return json.load(response) def until(predicate): deadline = time.monotonic()+5 while not predicate(): assert time.monotonic()