diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 18b2389e..a64d53d5 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -180,6 +180,7 @@ jobs: sha256sum -c SHA256SUMS cd "$GITHUB_WORKSPACE" python3 scripts/smoke-embedded-engine.py "$RUNNER_TEMP/combined-fixture/strata-next-linux-x86_64-musl" "$RUNNER_TEMP/embedded-worker" + python3 scripts/smoke-controller-deployment.py "$RUNNER_TEMP/combined-fixture/strata-next-linux-x86_64-musl" python3 scripts/build-runtime-image.py --cpu-fixture --package "$RUNNER_TEMP/combined-fixture" \ --receipt-sha256 "$(sha256sum "$RUNNER_TEMP/combined-fixture/SHA256SUMS" | cut -d ' ' -f 1)" \ > "$RUNNER_TEMP/combined-image.json" diff --git a/docs/experiments/2026-10-04-model-switch.md b/docs/experiments/2026-10-04-model-switch.md index e8971106..754f7ae5 100644 --- a/docs/experiments/2026-10-04-model-switch.md +++ b/docs/experiments/2026-10-04-model-switch.md @@ -75,3 +75,66 @@ keeps its process. `--wait-seconds` accepts 1–7200 seconds; the default is 360 Native uses the retained loopback SSH tunnel, creating one if the port is free. The coordinator only manages the known host recipes; an externally started untracked GPU workload still yields an ownership error. + +## Configured host layout (STRA-68) + +The repository controller also accepts an **opt-in** private deployment file. +The installed controller and the active trial are not changed by this feature. +All paths are absolute and supplied by the operator, for example: + +```json +{ + "schema_version": 1, + "root": "/home/alice/.local/state/strata/switch", + "native": "/home/alice/.local/state/strata/native", + "control": "/home/alice/.local/share/strata/console-helpers", + "agent_helper": "/home/alice/.local/share/strata/agent-profile.py", + "binary": "/home/alice/.local/share/strata/releases/v1/strata-next", + "config": "/home/alice/.config/strata/native-v1.json", + "cwd": "/home/alice/.local/share/strata", + "url": "http://127.0.0.1:18082", + "model": "strata-native-iq3-s", + "key_file": "/home/alice/.config/strata/api-key" +} +``` + +Only `key_file` is optional. The deployment and key files must be private regular +files owned by the invoking user (mode 0600); existing state directories must be +private too (0700). The readiness URL must be literal loopback HTTP with a port, +without credentials or a path. Readiness requires the expected service, model +and `ready=true`; redirects are not followed. Its socket timeout is not a hard +wall deadline against a slow byte stream. + +```sh +chmod 600 /home/alice/.config/strata/deployment.json +printf '%s\n' '{"backend":"native","waitSeconds":3600}' | + python3 scripts/strata-model-switch.py \ + --deployment /home/alice/.config/strata/deployment.json start +``` + +For this explicit mode, the native CLI runs `provision --config` before the +transaction can unload any current model. It resolves pinned assets, embedded +engine and `native_model`/derived tokenizer using the existing native bootstrap; +its bounded subprocess has private/null output and is killed/reaped on timeout. +No old PID file is needed for a first launch. An existing saved live recipe is +retained, including its selected environment. Use separate state directories for +separate native recipes; this remains a single-native-profile controller. Keep +versioned binary/config/model paths immutable while a model is running or being +switched so that rollback can reuse the saved recipe. + +Without `--deployment`, the existing host defaults and preflight behavior remain. +This does **not** install `qwen_remote`, `strata_remote` or the agent helper, nor +make their own backend-specific paths portable: those helpers must already be +configured on the destination host. It also does not replace the native runtime +with Python; Python here is only the console management tool. + +Validation adds private manifest, cold recipe, timeout/reap, authenticated +readiness and legacy-helper regression cases to the controller suite. The hosted +`smoke-controller-deployment.py` runs the actual combined native CLI with a +synthetic CPU engine, provisions a tiny verified GGUF offline, starts the native +profile from an empty state, preserves its PID on failed preflight, then fails a +simulated alternate backend and restores the original native process. The +synthetic Responses output must be exactly `A` before and after rollback (zero +tolerance). GPU ownership and the alternate backend are test adapters. This is +CPU process/transaction coverage; actual CUDA, real-model quality, clean-node +helper installation and GPU failure rollback remain separate acceptance gates. diff --git a/scripts/smoke-controller-deployment.py b/scripts/smoke-controller-deployment.py new file mode 100644 index 00000000..d4815bdf --- /dev/null +++ b/scripts/smoke-controller-deployment.py @@ -0,0 +1,144 @@ +#!/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() diff --git a/scripts/strata-model-switch.py b/scripts/strata-model-switch.py index 76d9a29f..df95ace3 100644 --- a/scripts/strata-model-switch.py +++ b/scripts/strata-model-switch.py @@ -3,7 +3,11 @@ No inference serving code. Existing backend helpers retain download/launch logic. """ +import argparse import fcntl +import http.client +import re +import stat import hashlib import importlib.util import json @@ -14,12 +18,84 @@ import subprocess import sys import time import urllib.request +from urllib.parse import urlsplit ROOT = Path('/home/para/.cache/strata-next/model-switch') NATIVE = Path('/home/para/.cache/strata-next/native-console-20261004') CONTROL = Path('/home/para/inference/codex-qwen') +def private_bytes(path, limit): + fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as source: + info = os.fstat(source.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077: + raise ValueError('deployment and key files must be private regular files owned by this user') + data = source.read(limit + 1) + if len(data) > limit: + raise ValueError('private input exceeds size limit') + return data + + +def load_deployment(path): + try: + value = json.loads(private_bytes(path, 65536)) + required = {'schema_version', 'root', 'native', 'control', 'agent_helper', + 'binary', 'config', 'cwd', 'url', 'model'} + if (not isinstance(value, dict) or set(value) - required - {'key_file'} or + not required <= set(value) or type(value['schema_version']) is not int or value['schema_version'] != 1): + raise ValueError('schema') + for key in ('root', 'native', 'control', 'agent_helper', 'binary', 'config', 'cwd', 'key_file'): + if key not in value: + continue + text = value[key] + if not isinstance(text, str) or not text or any(ord(c) < 32 or ord(c) == 127 for c in text) or not Path(text).is_absolute(): + raise ValueError('absolute paths required') + value[key] = str(Path(text).resolve()) + if value['root'] == value['native']: + raise ValueError('state directories must be distinct') + for key in ('root', 'native'): + directory = Path(value[key]) + if directory.exists(): + info = directory.stat() + if not directory.is_dir() or info.st_uid != os.getuid() or info.st_mode & 0o077: + raise ValueError('state directories must be private and owned by this user') + if not isinstance(value['url'], str) or any(ord(c) <= 32 or ord(c) >= 127 for c in value['url']): + raise ValueError('url') + url = urlsplit(value['url']) + if (url.scheme != 'http' or url.hostname not in {'127.0.0.1','::1'} or + url.username is not None or url.password is not None or url.path or url.query or url.fragment or + url.port is None or not 1 <= url.port <= 65535): + raise ValueError('plain loopback HTTP URL with explicit port required') + if not isinstance(value['model'], str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,180}', value['model']): + raise ValueError('model') + if value.get('key_file'): + key = private_bytes(value['key_file'], 4096).decode().strip() + if not key or any(ord(c) < 33 or ord(c) > 126 for c in key): + raise ValueError('invalid private key file') + return value + except (OSError, ValueError, TypeError, KeyError): + raise RuntimeError('Invalid deployment manifest: check private file, schema, absolute paths and loopback URL') from None + + +def provision_recipe(recipe, budget): + # Native CLI resolves assets, @embedded and generated tokenizer paths itself. + try: + with subprocess.Popen([recipe['binary'], 'provision', '--config', recipe['config']], + cwd=recipe['cwd'], env={**os.environ, **recipe['env']}, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) as process: + try: + if process.wait(timeout=budget): + raise RuntimeError('Native provisioning failed; current model preserved') + except BaseException: + if process.poll() is None: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + raise + except (OSError, subprocess.TimeoutExpired): + raise RuntimeError('Native provisioning failed or timed out; current model preserved') from None + + def save(path, value): path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) temporary = path.with_suffix('.tmp') @@ -99,21 +175,28 @@ def switch(host, target, budget): class Host: - def __init__(self): - sys.path.insert(0, str(CONTROL)) + def __init__(self, deployment=None): + self.deployment = deployment + self.root = Path(deployment['root']) if deployment else ROOT + self.native = Path(deployment['native']) if deployment else NATIVE + self.control = Path(deployment['control']) if deployment else CONTROL + self.binary = Path(deployment['binary']) if deployment else self.native/'strata-next' + self.config = Path(deployment['config']) if deployment else self.native/'config.json' + sys.path.insert(0, str(self.control)) import qwen_remote import strata_remote self.q, self.s = qwen_remote, strata_remote - spec = importlib.util.spec_from_file_location('agent_profile', '/home/para/.cache/strata-next/agent-profile.py') + spec = importlib.util.spec_from_file_location('agent_profile', deployment['agent_helper'] if deployment else '/home/para/.cache/strata-next/agent-profile.py') self.a = importlib.util.module_from_spec(spec) spec.loader.exec_module(self.a) def native_recipe(self): - path = ROOT/'native-recipe.json' - state = json.loads((NATIVE/'state.json').read_text()) - if same_process(state): + path = self.root/'native-recipe.json' + state_path = self.native/'state.json' + state = json.loads(state_path.read_text()) if state_path.exists() else None + if state and same_process(state): pid = state['pid'] - if Path(f'/proc/{pid}/exe').resolve() != NATIVE/'strata-next': + if Path(f'/proc/{pid}/exe').resolve() != self.binary.resolve(): raise RuntimeError('Native PID does not match its recorded executable') env = {} for item in Path(f'/proc/{pid}/environ').read_bytes().split(b'\0'): @@ -122,10 +205,13 @@ class Host: if key.startswith('STRATA_') or key in {'LD_LIBRARY_PATH', 'CUDA_VISIBLE_DEVICES'}: env[key] = value.decode() recipe = {'cwd': str(Path(f'/proc/{pid}/cwd').resolve()), 'env': env, - 'binary': str(NATIVE/'strata-next'), 'config': str(NATIVE/'config.json')} + 'binary': str(self.binary), 'config': str(self.config)} save(path, recipe) elif not path.exists(): - raise RuntimeError('Native launch recipe missing; cannot reconstruct an unrecorded runtime') + if not self.deployment: + raise RuntimeError('Native launch recipe missing; cannot reconstruct an unrecorded runtime') + return {'binary': str(self.binary), 'config': str(self.config), + 'cwd': self.deployment['cwd'], 'env': {}} return json.loads(path.read_text()) def prepare(self, target, budget): @@ -134,6 +220,9 @@ class Host: self.a.prepare(target['profile']) elif backend == 'native': recipe = self.native_recipe() + if self.deployment: + provision_recipe(recipe, budget) + return cfg = json.loads(Path(recipe['config']).read_text()) for p in [recipe['binary'], cfg['engine']['executable']]: if not Path(p).is_file() or not os.access(p, os.X_OK): @@ -171,8 +260,8 @@ class Host: def inventory(self): result = [] - if (NATIVE/'state.json').exists(): - state = json.loads((NATIVE/'state.json').read_text()) + if (self.native/'state.json').exists(): + state = json.loads((self.native/'state.json').read_text()) if same_process(state): recipe = self.native_recipe() result.append({'target': {'backend': 'native'}, 'roots': [state['pid']], 'state': state, 'recipe': recipe}) @@ -268,7 +357,8 @@ class Host: return self.s.start(target) recipe = self.native_recipe() env = {**os.environ, **recipe['env']} - with (NATIVE/'runtime.log').open('ab') as log: + self.native.mkdir(parents=True, exist_ok=True, mode=0o700) + with (self.native/'runtime.log').open('ab') as log: process = subprocess.Popen([recipe['binary'], 'serve', '--config', recipe['config']], cwd=recipe['cwd'], env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) record = identity(process.pid) @@ -277,7 +367,7 @@ class Host: try: with open(recipe['binary'], 'rb') as binary: record['cli_sha256'] = hashlib.file_digest(binary, 'sha256').hexdigest() - save(NATIVE/'state.json', record) + save(self.native/'state.json', record) except BaseException: process.terminate() process.wait(timeout=35) @@ -286,26 +376,51 @@ class Host: def restore(self, owner): if owner['target']['backend'] == 'native': - save(ROOT/'native-recipe.json', owner['recipe']) + save(self.root/'native-recipe.json', owner['recipe']) if owner['target']['backend'] == 'llama': self.q.atomic(self.q.ACTIVE, owner['active']) subprocess.run(['sudo', '-n', 'systemctl', 'start', self.q.SERVICE], check=True, capture_output=True, timeout=30) else: self.launch(owner['target']) + def native_ready(self): + url = urlsplit(self.deployment['url']) + headers = {} + if self.deployment.get('key_file'): + key = private_bytes(self.deployment['key_file'], 4096).decode().strip() + if not key or any(ord(c) < 33 or ord(c) > 126 for c in key): + return False + headers['Authorization'] = 'Bearer ' + key + conn = http.client.HTTPConnection(url.hostname, url.port, timeout=3) + try: + conn.request('GET', '/status', headers=headers) + response = conn.getresponse() + if response.status != 200: + return False + data = response.read(65537) + if len(data) > 65536: + return False + value = json.loads(data) + return (isinstance(value, dict) and value.get('service') == 'strata-control' and + value.get('model') == self.deployment['model'] and value.get('ready') is True) + finally: + conn.close() + def ready(self, target): try: backend = target['backend'] if backend == 'agent': observed = self.a.status() return observed['profile'] == target['profile'] and observed['ready'] + if backend == 'native' and self.deployment: + return self.native_ready() if backend == 'native': with urllib.request.urlopen('http://127.0.0.1:18082/status', timeout=3) as response: value = json.load(response) return value.get('service') == 'strata-control' and value.get('model') == 'strata-native-iq3-s' and value.get('ready') is True models = (self.q if backend == 'llama' else self.s).api('/v1/models')['data'] return len(models) == 1 and (backend != 'llama' or models[0]['id'] == target['id'] + '--' + target['layout'] + 'k') - except (OSError, ValueError, KeyError, RuntimeError): + except (OSError, ValueError, KeyError, RuntimeError, http.client.HTTPException): return False def wait_ready(self, target, budget): @@ -329,26 +444,30 @@ class Host: return {'started': False, 'preparing': False} def journal(self, phase, previous, target): - save(ROOT/'state.json', {'phase': phase, 'previous': previous, 'target': target, 'updated_at': time.time()}) + save(self.root/'state.json', {'phase': phase, 'previous': previous, 'target': target, 'updated_at': time.time()}) def main(): os.umask(0o077) - if len(sys.argv) != 2 or sys.argv[1] != 'start': - raise RuntimeError('Expected start action') + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--deployment', type=Path, help='private schema1 host layout; does not change installed defaults') + parser.add_argument('action', choices=['start']) + args = parser.parse_args() + deployment = load_deployment(args.deployment) if args.deployment else None + root = Path(deployment['root']) if deployment else ROOT target = json.load(sys.stdin) budget = target.pop('waitSeconds', 3600) if type(budget) is not int or not 1 <= budget <= 7200: raise RuntimeError('Switch waitSeconds must be 1..7200') if type(target.get('days', 7)) is not int or not 1 <= target.get('days', 7) <= 31: raise RuntimeError('days must be1..31') - ROOT.mkdir(parents=True, exist_ok=True, mode=0o700) - with (ROOT/'switch.lock').open('a') as lock: + root.mkdir(parents=True, exist_ok=True, mode=0o700) + with (root/'switch.lock').open('a') as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: raise RuntimeError('Another model switch is already running') from None - result = switch(Host(), target, budget) + result = switch(Host(deployment), target, budget) print(json.dumps(result)) diff --git a/scripts/test-model-switch.py b/scripts/test-model-switch.py index 45385451..787cea1a 100644 --- a/scripts/test-model-switch.py +++ b/scripts/test-model-switch.py @@ -1,6 +1,13 @@ #!/usr/bin/env python3 """Transaction tests without touching GPUs, processes, or user services.""" import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import time +from types import SimpleNamespace from pathlib import Path import unittest from unittest.mock import Mock, patch @@ -95,4 +102,118 @@ class PreparationTests(unittest.TestCase): host.free_gpu() self.assertEqual(owners.call_count,2) +class DeploymentTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix='strata-controller-') + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name).resolve() + self.value = dict(schema_version=1, **{key: str(self.root/key) for key in + ('root','native','control','agent_helper','binary','config','cwd')}, + url='http://127.0.0.1:12345', model='fixture') + self.path = self.root/'deployment.json' + + def write(self, value=None): + self.path.write_text(json.dumps(value or self.value)); self.path.chmod(0o600) + return self.path + + def host(self, explicit=True): + host = object.__new__(m.Host) + host.deployment = self.value if explicit else None + for key in ('root','native','control','binary','config'): + setattr(host, key, Path(self.value[key])) + return host + + def test_private_manifest_and_no_mutations(self): + self.assertEqual(m.load_deployment(self.write()), self.value) + self.assertFalse(Path(self.value['root']).exists()) + self.path.chmod(0o644) + with self.assertRaisesRegex(RuntimeError,'Invalid deployment'): m.load_deployment(self.path) + self.path.chmod(0o600) + alias = self.root/'alias'; alias.symlink_to(self.path) + with self.assertRaises(RuntimeError): m.load_deployment(alias) + + def test_schema_paths_loopback_and_private_directories(self): + changes = [{'schema_version':True}, {'unexpected':'secret'}, {'binary':'relative'}, + {'url':'http://server:1234'}, {'url':'http://127.0.0.1:1234/path'}, + {'url':'http://user:secret@127.0.0.1:1234'}, {'url':'http://127.0.0.1'}, + {'model':'bad name'}, {'root':self.value['native']}] + for change in changes: + with self.subTest(change=change), self.assertRaises(RuntimeError) as caught: + m.load_deployment(self.write({**self.value, **change})) + self.assertNotIn('secret', str(caught.exception)) + directory=Path(self.value['root']); directory.mkdir(mode=0o755); directory.chmod(0o755) + with self.assertRaises(RuntimeError): m.load_deployment(self.write()) + directory.chmod(0o700) + self.assertEqual(m.load_deployment(self.write())['root'], str(directory)) + + def test_cold_start_and_cached_recipe(self): + host=self.host() + recipe=host.native_recipe() + self.assertEqual(recipe, {key:self.value[key] for key in ('binary','config','cwd')} | {'env':{}}) + self.assertFalse(host.root.exists()) + cached={**recipe,'env':{'STRATA_FIXTURE':'1'}} + m.save(host.root/'native-recipe.json',cached) + self.assertEqual(host.native_recipe(),cached) + with patch.object(m,'provision_recipe') as provision: + host.prepare(OLD,11) + provision.assert_called_once_with(cached,11) + + def test_key_rejected_before_lifecycle(self): + key=self.root/'key';self.value['key_file']=str(key) + for content,mode in [('fixture-token',0o644),('bad\nkey',0o600),('',0o600)]: + key.write_text(content);key.chmod(mode) + with self.assertRaises(RuntimeError):m.load_deployment(self.write()) + self.assertFalse(Path(self.value['root']).exists()) + key.write_text('fixture-token');key.chmod(0o600) + self.assertEqual(m.load_deployment(self.write())['key_file'],str(key)) + + def test_legacy_missing_recipe_is_not_invented(self): + with self.assertRaisesRegex(RuntimeError,'recipe missing'):self.host(False).native_recipe() + + def test_literal_provision_invocation_and_suppressed_failure(self): + host=self.host(); host.binary=Path(sys.executable) + cwd=Path(self.value['cwd']); cwd.mkdir() + script=cwd/'provision' + script.write_text("import json,os,sys; json.dump([sys.argv[1:], os.environ['STRATA_FIXTURE']],open('seen','w'))") + recipe={'binary':sys.executable,'config':'literal $HOME `x` path','cwd':str(cwd),'env':{'STRATA_FIXTURE':'yes'}} + m.provision_recipe(recipe,5) + self.assertEqual(json.loads((cwd/'seen').read_text()),[['--config',recipe['config']],'yes']) + script.write_text("import sys; print('private secret',file=sys.stderr); sys.exit(7)") + with self.assertRaisesRegex(RuntimeError,'current model preserved') as caught:m.provision_recipe(recipe,5) + self.assertNotIn('secret',str(caught.exception)) + + def test_provision_timeout_reaps_child(self): + cwd=Path(self.value['cwd']);cwd.mkdir() + (cwd/'provision').write_text("import os,time; open('pid','w').write(str(os.getpid())); time.sleep(60)") + recipe={'binary':sys.executable,'config':'unused','cwd':str(cwd),'env':{}} + started=time.monotonic() + with self.assertRaisesRegex(RuntimeError,'timed out'):m.provision_recipe(recipe,.5) + self.assertLess(time.monotonic()-started,3) + with self.assertRaises(ProcessLookupError):os.kill(int((cwd/'pid').read_text()),0) + + def test_readiness_identity_auth_and_no_redirect(self): + host=self.host(); key=self.root/'key';key.write_text('fixture-token');key.chmod(0o600) + self.value['key_file']=str(key) + response=Mock(status=200) + response.read.return_value=json.dumps(dict(service='strata-control',model='fixture',ready=True)).encode() + conn=Mock();conn.getresponse.return_value=response + with patch.object(m.http.client,'HTTPConnection',return_value=conn): + self.assertTrue(host.ready(OLD)) + conn.request.assert_called_with('GET','/status',headers={'Authorization':'Bearer fixture-token'}) + response.status=302;self.assertFalse(host.ready(OLD)) + response.status=200;response.read.return_value=b'{}';self.assertFalse(host.ready(OLD)) + conn.getresponse.side_effect=m.http.client.BadStatusLine('invalid');self.assertFalse(host.ready(OLD)) + self.assertEqual(conn.close.call_count,4) + + def test_ordinary_strata_recipe_unchanged(self): + host=self.host() + cfg=self.root/'strata-iq3_s.json' + cfg.write_text(json.dumps({'args':['--max-context','262144','--kv','int8']})) + (self.root/'strata-artifacts.json').write_text(json.dumps({'files':[]})) + host.s=SimpleNamespace(ROOT=self.root,STATE=self.root,DATA=self.root,prepare=lambda:{'stage':'ready'}) + # Existing service command remains delegated; no configurable path may rewrite helper ROOT. + with patch.object(m.subprocess,'run',return_value=SimpleNamespace(returncode=0)), patch.object(m.subprocess,'Popen'): + try: host.prepare({'backend':'strata'},1) + except (KeyError,AttributeError) as error: self.fail(str(error)) + if __name__ == '__main__': unittest.main()