#!/usr/bin/env python3 """Start one private Strata A/B agent profile on the Linux GPU host. This is an offline experiment controller. It keeps its config in tmpfs, never prints credentials, and does not modify the ordinary Strata service on port 8080. """ import json import os from pathlib import Path import signal import subprocess import sys import time import urllib.request ROOT = Path('/home/para/.cache/strata-next/agent-profiles') STATE = ROOT / 'state.json' CONFIG = Path('/dev/shm/strata-next-agent-profile.json') SOURCE = Path('/home/para/inference/strata/strata-iq3_s.json') SERVER = Path('/home/para/inference/strata/serve/server.py') PYTHON = Path('/home/para/inference/strata/.venv/bin/python') ARCHIVE = Path('/mnt/microcrm-flash-preflight/microcrm-flash-next-experiment/strata-next/qwen-iq3-s-l2-v4.kar') KEYLESS_ROUTING = Path('/home/para/.cache/strata-next/keyless-feasibility/query-routing-distilled-wide.bin') EXES = { 'strata-next-v-only': Path('/home/para/.cache/strata-next/keyless-runtime-20261003/build/strata'), 'strata-next-baseline': Path('/home/para/.cache/strata-next/engine-fork-f80a3e0/build/strata'), 'strata-next-kar-ple': Path('/home/para/.cache/strata-next/engine-kar-ple-build/strata'), 'strata-next-kar-ple-gpu': Path('/home/para/.cache/strata-next/engine-ple-gpu-36e512a/build/strata'), } HOST = '192.168.1.196' PORT = 18081 URL = f'http://{HOST}:{PORT}' def pid_alive(pid): try: os.kill(pid, 0) return True except (ProcessLookupError, PermissionError): return False def state(): if not STATE.exists(): return None value = json.loads(STATE.read_text()) if not pid_alive(value['pid']): return None return value def health(): try: with urllib.request.urlopen(URL + '/health', timeout=3) as response: value = json.load(response) return {'ready': bool(value.get('loaded') and value.get('max_context') == 262144), 'context': value.get('max_context')} except (OSError, ValueError): return {'ready': False} def status(): current = state() observed = health() if current else {'ready': False} return {'profile': current['profile'] if current else None, 'pid': current['pid'] if current else None, 'kv_mode': 'without-key' if current and current['profile'] == 'strata-next-v-only' else 'with-key', 'quality_gate': (json.loads(Path(str(KEYLESS_ROUTING) + '.json').read_text()).get('quality_gate', 'not_run') if current and current['profile'] == 'strata-next-v-only' else None), **observed} def unload(current): if health()['ready']: key = json.loads(CONFIG.read_text())['api_key'] request = urllib.request.Request(URL + '/unload', data=b'{}', method='POST', headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'}) with urllib.request.urlopen(request, timeout=180) as response: if response.status != 200: raise RuntimeError('model unload failed') try: os.killpg(current['pid'], signal.SIGTERM) except ProcessLookupError: pass for _ in range(30): if not pid_alive(current['pid']): break time.sleep(1) if pid_alive(current['pid']): os.killpg(current['pid'], signal.SIGKILL) STATE.unlink(missing_ok=True) CONFIG.unlink(missing_ok=True) def ensure_idle(): current = state() if not current: return config = json.loads(CONFIG.read_text()) key = config['api_key'] request = urllib.request.Request(URL + '/slots', headers={'Authorization': 'Bearer ' + key}) try: with urllib.request.urlopen(request, timeout=5) as response: slots = json.load(response) except (OSError, ValueError): raise RuntimeError('experimental server is loading or its state is unknown') if not slots or any(slot.get('is_processing', True) for slot in slots): raise RuntimeError('experimental server is processing a request') def prepare(profile): if profile not in EXES: raise ValueError('unknown experiment profile') routing_identity = None if profile == 'strata-next-v-only': routing_report = Path(str(KEYLESS_ROUTING) + '.json') if not KEYLESS_ROUTING.is_file() or not routing_report.is_file(): raise FileNotFoundError(KEYLESS_ROUTING) routing_identity = json.loads(routing_report.read_text())['routing_sha256'] for path in (SOURCE, SERVER, PYTHON, EXES[profile]): if not path.is_file(): raise FileNotFoundError(path) if profile in {'strata-next-kar-ple', 'strata-next-kar-ple-gpu'} and not ARCHIVE.is_file(): raise FileNotFoundError(ARCHIVE) environment = dict(os.environ) environment.pop('STRATA_KEYLESS_ROUTING', None) environment.pop('STRATA_KEYLESS_TRACE', None) if profile == 'strata-next-v-only': if not KEYLESS_ROUTING.is_file(): raise FileNotFoundError(KEYLESS_ROUTING) environment['STRATA_KEYLESS_ROUTING'] = str(KEYLESS_ROUTING) raw = json.loads(SOURCE.read_text()) args = raw['args'] if (args[args.index('--max-context') + 1] != '262144' or args[args.index('--kv') + 1] != 'int8' or args[args.index('--kv-resident') + 1] != '32768'): raise RuntimeError('expected 1x256K with INT8 K+V and 32768 resident cells') if ('--ple-kar' in args or '--ple-kar-gpu-cache-mib' in args or '--control-vector-scaled' in args): raise RuntimeError('source config contains another experiment') cfg = dict(raw) cfg['exe'] = str(EXES[profile]) cfg['args'] = list(args) if profile in {'strata-next-kar-ple', 'strata-next-kar-ple-gpu'}: cfg['args'] += ['--ple-kar', str(ARCHIVE), '--ple-kar-level', '2'] if profile == 'strata-next-kar-ple-gpu': cfg['args'] += ['--ple-kar-gpu-cache-mib', '64'] return cfg, environment, routing_identity def start(profile): cfg, environment, routing_identity = prepare(profile) current = state() if current and current['profile'] == profile and current.get('routing_identity') == routing_identity: return {'started': False, **status()} if current: ensure_idle() unload(current) elif STATE.exists(): STATE.unlink() CONFIG.unlink(missing_ok=True) if health()['ready']: raise RuntimeError('port is already occupied by an untracked server') used = subprocess.check_output( ['nvidia-smi', '--query-gpu=memory.used', '--format=csv,noheader,nounits'], text=True).strip() if int(used.splitlines()[0]) > 1024: raise RuntimeError('GPU is already occupied by another workload') ROOT.mkdir(mode=0o700, parents=True, exist_ok=True) os.chmod(ROOT, 0o700) cfg['log'] = str(ROOT / f'{profile}-engine.log') fd = os.open(CONFIG, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) try: with os.fdopen(fd, 'w') as file: json.dump(cfg, file) log = ROOT / f'{profile}-server.log' with log.open('ab') as output: proc = subprocess.Popen([str(PYTHON), '-u', str(SERVER), '--engine', 'strata', '--config', str(CONFIG), '--host', HOST, '--port', str(PORT)], cwd=cfg['cwd'], stdout=output, stderr=subprocess.STDOUT, start_new_session=True, close_fds=True, env=environment) STATE.write_text(json.dumps({'pid': proc.pid, 'profile': profile, 'routing_identity': routing_identity}) + '\n') os.chmod(STATE, 0o600) except BaseException: CONFIG.unlink(missing_ok=True) raise return {'started': True, **status()} def main(): action = sys.argv[1] payload = json.load(sys.stdin) if action == 'status': result = status() elif action == 'prepare': prepare(payload['profile']) result = {'prepared': True} elif action == 'start': result = start(payload['profile']) elif action == 'stop': current = state() if current: ensure_idle() unload(current) result = {'stopped': bool(current)} else: raise ValueError('unknown action') print(json.dumps(result)) if __name__ == '__main__': try: main() except Exception as exc: print(type(exc).__name__ + ': ' + str(exc), file=sys.stderr) sys.exit(1)