feat(console): switch managed model runtimes with preflight and rollback

This commit is contained in:
Pavlo Ratushnyi
2026-10-04 10:56:52 +02:00
parent cf5f08f6c4
commit 1bfa49f67e
7 changed files with 820 additions and 18 deletions
@@ -0,0 +1,77 @@
# Managed console model switching — 2026-10-04
## Scope
STRA-35 fixes the failed `codex-qwen-ctl start` selection of
`strata-next-kar-ple-gpu` while the qualified native runtime owned the GPU.
Previously the independent experiment controller rejected any occupied GPU;
it did not know how to stop and restore the native supervisor.
The installed console now routes ordinary llama.cpp, ordinary Strata,
experimental Strata and native starts through one remote coordinator.
Existing menu numbers are preserved; `strata-native` is appended.
## Transaction
1. Resolve and preflight the requested model through its existing controller.
Ordinary downloads/verification happen before unloading the old model.
2. Inventory managed process roots and reject unrelated CUDA processes.
Serialize console switches with a private host lock.
3. Save the previous launch recipe privately, stop the known current owner,
and wait for its GPU memory to release.
4. Launch the selected backend and wait for its API/model readiness.
5. Only then discover the endpoint and update the harness profile.
6. If the target fails, clean up its known processes and restore the previous
recipe. Report failed restoration explicitly and retain the private journal.
The qualified legacy native runtime has no admin drain endpoint. An explicit
model switch sends its supervisor normal SIGTERM; an in-flight native request
can be interrupted. Existing ordinary/experiment controllers retain their
busy-request guards. Unrelated GPU work is never killed.
## Verification
- 11 transaction/preparation tests: sequencing, preflight preservation,
unrelated and ambiguous owners, PID reuse/ancestry, idempotence,
rollback, rollback failure, failed-target cleanup and GPU-release waiting.
- 5 menu tests: stable numbering, native dispatch, all backend routing,
profile preservation on failure, installer backup and idempotence.
- All 16 passed on macOS and Linux; 13 existing native-service and 12 native-API
tests also passed on macOS. New suites are included in `check-local.sh`.
- Live RTX 5090 switch passed through the installed command:
`codex-qwen-ctl start strata-next-kar-ple-gpu --layout 1x256 --kv-cache q8_0 --wait-seconds 900`.
Previous native PID 4031422 exited; experiment supervisor 4133313 and engine
4133347 became ready on port 18081. The private switch journal is `ready`.
Engine log confirmed the experimental level-2 PLE KAR CUDA cache arm.
- Re-selecting the same model through `qwen-codex-ctl start` preserved those
process IDs and completed successfully. The ordinary harness connection now
selects `strata-next-kar-ple-gpu`.
- A short non-streaming generation returned HTTP 200, one choice, 56 input and
16 output tokens. Its deliberately capped output ended with `length`; this
checks generation transport, not answer quality or a complete agent task.
- Model startup took several minutes reading NTFS-backed weights. Observed
disk reads were around 150 MB/s during loading; no whole-archive SHA pass was
added. Switching the controller does not remove model I/O startup cost.
- The retained native restart recipe passed preflight. Reverse switching and
the ordinary llama.cpp/Strata service transitions were covered by dispatch
and transaction tests, but were not separately run on the GPU in this trial.
This is a lifecycle change; engine arguments, model weights and numerical
kernels are unchanged. No inference speed or quality improvement is claimed.
KAR PLE and V-only retain their experimental quality status. CPU fault tests
exercise rollback; they are not a live GPU failure-injection trial.
## Commands
```sh
codex-qwen-ctl start strata-next-kar-ple-gpu
codex-qwen-ctl start strata-native
codex-qwen-ctl start
```
`qwen-codex-ctl` uses the same controller. Start the agent with `qwen-codex`
after the controller reports readiness. Re-selecting the already-ready profile
keeps its process. `--wait-seconds` accepts 1–7200 seconds; the default is 3600.
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.
+2
View File
@@ -7,6 +7,8 @@ python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_
python3 "${repo_root}/scripts/test-benchmark-harness.py"
python3 "${repo_root}/scripts/test-native-service.py"
python3 "${repo_root}/scripts/test-native-api.py"
python3 "${repo_root}/scripts/test-native-menu.py"
python3 "${repo_root}/scripts/test-model-switch.py"
python3 "${repo_root}/scripts/test-static-cuda-elf.py"
python3 "${repo_root}/scripts/test-keyless-routing.py"
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Install automatic managed model switching and the native console picker."""
import argparse
import ast
import hashlib
import os
from pathlib import Path
import tempfile
MARKER = '# Strata Next native picker integration v1'
NATIVE = '''STRATA_SWITCH_HELPER = '/home/para/.cache/strata-next/model-switch.py'
STRATA_NATIVE_MODEL = dict(id='strata-native',
label='Flash-Next IQ3_S · Native Responses · автоматичне перемикання',
backend='strata-native', maxContext=262144, bytes=84525205664)
def start_strata_native(args):
if args.layout not in (None, '1x256') or args.kv_cache not in (None, 'q8_0') or args.kv_mode != 'with-key':
raise RuntimeError('strata-native: чинний профіль 1x256 · INT8 K+V; для іншого режиму вибери відповідний профіль')
target = dict(backend='strata-native', url='http://127.0.0.1:18084', key_file=None, managed=False)
validate_connection(target)
import socket
with socket.socket() as probe:
probe.settimeout(1)
listening = probe.connect_ex(('127.0.0.1', 18084)) == 0
if not listening:
subprocess.run(['ssh', '-fN', '-o', 'BatchMode=yes', '-o', 'ExitOnForwardFailure=yes',
'-o', 'ConnectTimeout=8', '-L', '127.0.0.1:18084:127.0.0.1:18082', HOST],
check=True, timeout=15)
remote('start', {'backend': 'native', 'waitSeconds': args.wait_seconds},
stream=True, helper=STRATA_SWITCH_HELPER)
try:
state = discover(target)
except (OSError, ValueError, KeyError, RuntimeError):
raise RuntimeError('Native runtime недоступний або не готовий на 127.0.0.1:18084. Перевір endpoint і SSH tunnel; профіль harness не змінено.') from None
if state.get('model') != 'strata-native-iq3-s':
raise RuntimeError('Native endpoint має іншу модель; скористайся connect strata-native з явним URL')
configure(state)
atomic(PROFILE / 'connection.json', json.dumps(target, indent=2) + '\\n')
print('Готово: strata-native · 1 × 256К · INT8 K+V · Responses API. Запускай codex-qwen.')
'''
def patched(original):
if MARKER in original:
return original
if '# Strata Next native bearer file integration v1' not in original:
raise RuntimeError('Install native Responses integration first')
text = original
def replace(old, new, count=1):
nonlocal text
if text.count(old) != count:
raise RuntimeError('Launcher changed: native picker anchor mismatch')
text = text.replace(old, new)
replace('def start_strata(args):\n', NATIVE + 'def start_strata(args):\n')
replace('[*registry(), STRATA_MODEL, *STRATA_AGENT_MODELS]',
'[*registry(), STRATA_MODEL, *STRATA_AGENT_MODELS, STRATA_NATIVE_MODEL]', count=2)
replace(" if model.get('backend') == 'strata': modes = '1x256 · KV int8 · окремий рушій Strata'",
" if model.get('backend') == 'strata-native': modes = '1x256 · INT8 K+V · native endpoint 127.0.0.1:18084; автоматичне перемикання'\n"
" if model.get('backend') == 'strata': modes = '1x256 · KV int8 · окремий рушій Strata'")
replace(" if model.get('backend') == 'strata-agent': return start_strata_agent(args, model)",
" if model.get('backend') == 'strata-native': return start_strata_native(args)\n"
" if model.get('backend') == 'strata-agent': return start_strata_agent(args, model)")
replace(" if model.get('backend') == 'strata-agent':\n",
" if model.get('backend') == 'strata-native':\n"
" print('Native використовує підготовлений IQ3_S pack; start strata-native автоматично перемикає runtime.')\n"
" return\n"
" if model.get('backend') == 'strata-agent':\n")
replace(" proc = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', HOST,",
" switches = {REMOTE: 'llama', '/home/para/inference/codex-qwen/strata_remote.py': 'strata', STRATA_AGENT_HELPER: 'agent'}\n"
" if action == 'start' and helper in switches:\n"
" return remote('start', dict(payload or {}, backend=switches[helper]), stream=True, helper=STRATA_SWITCH_HELPER)\n"
" proc = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', HOST,")
replace("strata_remote('start', {'days': args.days})", "strata_remote('start', {'days': args.days, 'waitSeconds': args.wait_seconds})", count=2)
replace("strata_agent_remote('start', {'profile': model['id']})", "strata_agent_remote('start', {'profile': model['id'], 'waitSeconds': args.wait_seconds})")
replace("days=args.days, kvCache=kv_cache)", "days=args.days, kvCache=kv_cache, waitSeconds=args.wait_seconds)")
replace("if not 0 <= args.wait_seconds <= 7200: raise RuntimeError('wait-seconds must be 0..7200')",
"if not 1 <= args.wait_seconds <= 7200: raise RuntimeError('wait-seconds must be 1..7200 for managed switching')")
text += '\n' + MARKER + '\n'
ast.parse(text)
return text
def install(path):
original = path.read_text()
text = patched(original)
if text == original:
return False
backup = path.with_name(path.name + '.before-native-picker-' + hashlib.sha256(original.encode()).hexdigest()[:12])
if not backup.exists():
fd = os.open(backup, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
with os.fdopen(fd, 'w') as out:
out.write(original)
fd, name = tempfile.mkstemp(prefix='native-picker-', dir=path.parent)
try:
with os.fdopen(fd, 'w') as out:
out.write(text)
os.chmod(name, path.stat().st_mode & 0o777)
if path.read_text() != original:
raise RuntimeError('Launcher changed during installation')
os.replace(name, path)
finally:
if os.path.exists(name):
os.unlink(name)
return True
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--path', type=Path, default=Path.home()/'.local/share/codex-qwen/qwen_local.py')
changed = install(parser.parse_args().path)
print('Native menu installed; selected connection unchanged' if changed else 'Native menu already installed')
+26 -18
View File
@@ -111,7 +111,7 @@ def ensure_idle():
raise RuntimeError('experimental server is processing a request')
def start(profile):
def prepare(profile):
if profile not in EXES:
raise ValueError('unknown experiment profile')
routing_identity = None
@@ -120,22 +120,6 @@ def start(profile):
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']
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')
for path in (SOURCE, SERVER, PYTHON, EXES[profile]):
if not path.is_file():
raise FileNotFoundError(path)
@@ -164,6 +148,27 @@ def start(profile):
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')
@@ -175,7 +180,7 @@ def start(profile):
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=raw['cwd'], stdout=output, stderr=subprocess.STDOUT,
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)
@@ -190,6 +195,9 @@ def main():
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':
+360
View File
@@ -0,0 +1,360 @@
#!/usr/bin/env python3
"""Private Linux console controller: prepare, switch known model owner, rollback.
No inference serving code. Existing backend helpers retain download/launch logic.
"""
import fcntl
import hashlib
import importlib.util
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/model-switch')
NATIVE = Path('/home/para/.cache/strata-next/native-console-20261004')
CONTROL = Path('/home/para/inference/codex-qwen')
def save(path, value):
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
temporary = path.with_suffix('.tmp')
with temporary.open('w') as out:
os.chmod(temporary, 0o600)
json.dump(value, out)
os.replace(temporary, path)
def identity(pid):
try:
fields = Path(f'/proc/{int(pid)}/stat').read_text().rsplit(')', 1)[1].split()
if fields[0] == 'Z':
return None
return {'pid': int(pid), 'start_ticks': fields[19], 'ppid': int(fields[1])}
except (OSError, ValueError, IndexError):
return None
def owned(pid, roots):
seen = set()
while pid > 1 and pid not in seen:
if pid in roots:
return True
seen.add(pid)
current = identity(pid)
if current is None:
return False
pid = current['ppid']
return False
def same_process(record):
current = identity(record['pid'])
return current is not None and current['start_ticks'] == record['start_ticks']
def switch(host, target, budget):
"""All prerequisites/ownership checks precede unloading; tested with fake hosts."""
host.prepare(target, budget)
previous = host.inventory()
host.check_owners(previous)
if len(previous) > 1:
raise RuntimeError('Multiple managed model owners are active; refusing an ambiguous switch')
if previous and host.matches(previous[0], target) and host.ready(target):
return host.existing_result(target)
host.journal('prepared', previous, target)
try:
for owner in previous:
host.stop(owner)
host.free_gpu()
host.journal('loading', previous, target)
result = host.launch(target)
host.wait_ready(target, budget)
host.journal('ready', previous, target)
return result
except BaseException:
host.journal('restoring', previous, target)
try:
current = host.inventory()
host.check_owners(current)
for owner in current:
if host.matches(owner, target):
host.stop(owner, failed=True)
elif not any(host.matches(owner, old['target']) for old in previous):
raise RuntimeError('Managed owner changed during switch')
for old in previous:
if not host.ready(old['target']):
host.free_gpu()
host.restore(old)
host.wait_ready(old['target'], budget)
host.journal('restored' if previous else 'failed', previous, target)
except BaseException:
host.journal('restore_failed', previous, target)
raise RuntimeError('Model switch failed and previous model could not be restored; private switch state/logs retained') from None
raise RuntimeError('Selected model failed to start; previous model restored' if previous else 'Selected model failed to start; no previous model was running') from None
class Host:
def __init__(self):
sys.path.insert(0, str(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')
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):
pid = state['pid']
if Path(f'/proc/{pid}/exe').resolve() != NATIVE/'strata-next':
raise RuntimeError('Native PID does not match its recorded executable')
env = {}
for item in Path(f'/proc/{pid}/environ').read_bytes().split(b'\0'):
key, _, value = item.partition(b'=')
key = key.decode()
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')}
save(path, recipe)
elif not path.exists():
raise RuntimeError('Native launch recipe missing; cannot reconstruct an unrecorded runtime')
return json.loads(path.read_text())
def prepare(self, target, budget):
backend = target['backend']
if backend == 'agent':
self.a.prepare(target['profile'])
elif backend == 'native':
recipe = self.native_recipe()
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):
raise RuntimeError('Native executable missing or inaccessible')
if not Path(cfg['engine']['tokenizer_dir']).is_dir() or not Path(recipe['cwd']).is_dir():
raise RuntimeError('Native tokenizer or working directory is missing')
elif backend == 'llama':
model = self.q.model_by_id(target['id'])
self.q.validate(model, target['layout'])
self.q.validate_cache(target.get('kvCache', 'f16'))
self.q.fetch(model)
elif backend == 'strata':
deadline = time.monotonic() + budget
observed = self.s.prepare()
while observed['stage'] != 'ready':
if str(observed['stage']).startswith('failed') or time.monotonic() >= deadline:
raise RuntimeError('Ordinary Strata preparation failed or timed out; current model preserved')
time.sleep(2)
observed = self.s.status()
cfg = json.loads((self.s.ROOT/'strata-iq3_s.json').read_text())
args = cfg['args']
if args[args.index('--max-context')+1] != '262144' or args[args.index('--kv')+1] != 'int8' or '--control-vector-scaled' in args:
raise RuntimeError('Unexpected ordinary Strata configuration')
for item in json.loads((self.s.STATE/'strata-artifacts.json').read_text())['files']:
p = self.s.DATA/'models'/item['path']
receipt = json.loads(p.with_suffix('.verified.json').read_text())
if p.stat().st_size != item['bytes'] or receipt['sha256'] != item['sha256'] or receipt['mtime_ns'] != p.stat().st_mtime_ns:
raise RuntimeError('Ordinary Strata receipt mismatch; current model preserved')
else:
raise RuntimeError('Unknown model backend')
def unit(self, name):
p = subprocess.run(['systemctl', 'show', name, '-p', 'ActiveState', '-p', 'MainPID'], capture_output=True, text=True, check=True)
return dict(line.split('=', 1) for line in p.stdout.splitlines() if '=' in line)
def inventory(self):
result = []
if (NATIVE/'state.json').exists():
state = json.loads((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})
state = self.a.state()
if state and identity(state['pid']):
cmd = Path(f"/proc/{state['pid']}/cmdline").read_bytes().split(b'\0')
if str(self.a.SERVER).encode() not in cmd or str(self.a.CONFIG).encode() not in cmd or os.getpgid(state['pid']) != state['pid']:
raise RuntimeError('Experiment PID identity mismatch')
result.append({'target': {'backend': 'agent', 'profile': state['profile']}, 'roots': [state['pid']],
'state': {**state, **identity(state['pid'])}})
for backend, name in [('strata', self.s.UNIT), ('llama', self.q.SERVICE)]:
unit = self.unit(name)
if unit.get('ActiveState') not in {'inactive', 'failed'}:
roots = [int(unit.get('MainPID', 0))]
target = {'backend': backend, 'days': 7}
owner = {'target': target, 'roots': roots, 'unit': name}
if backend == 'llama':
active = self.q.read(self.q.ACTIVE)
target.update(id=active['id'], layout=active['layout'], kvCache=active.get('kvCache', 'f16'))
owner['active'] = active
container = subprocess.run(['docker', 'inspect', '--format', '{{.State.Pid}}', self.q.CONTAINER], capture_output=True, text=True)
if container.returncode == 0:
roots.append(int(container.stdout.strip()))
result.append(owner)
return result
def check_owners(self, owners):
roots = {pid for owner in owners for pid in owner['roots'] if pid > 1}
p = subprocess.run(['nvidia-smi', '--query-compute-apps=pid', '--format=csv,noheader,nounits'], capture_output=True, text=True, check=True)
for line in p.stdout.splitlines():
if line.strip() and not owned(int(line.strip()), roots):
raise RuntimeError('GPU belongs to an unrelated workload; it was not stopped')
def matches(self, owner, target):
previous = owner['target']
fields = {'native': [], 'strata': [], 'agent': ['profile'], 'llama': ['id', 'layout', 'kvCache']}
if previous['backend'] != target['backend']:
return False
return all(previous.get(k, 'f16' if k == 'kvCache' else None) == target.get(k, 'f16' if k == 'kvCache' else None) for k in fields[target['backend']])
def stop(self, owner, failed=False):
print('Вивантаження поточної моделі: ' + owner['target']['backend'], file=sys.stderr, flush=True)
backend = owner['target']['backend']
if backend in {'native', 'agent'}:
record = owner['state']
if not same_process(record):
raise RuntimeError('Managed process identity changed before stop')
if backend == 'agent':
if not failed:
self.a.ensure_idle()
self.a.unload(record)
else:
# This legacy qualified runtime has no admin drain endpoint.
# An explicit model switch authorizes its normal SIGTERM stop.
os.kill(record['pid'], signal.SIGTERM)
deadline = time.monotonic() + 35
while same_process(record):
if time.monotonic() >= deadline:
raise RuntimeError('Native runtime did not terminate; not killing an unknown process')
time.sleep(.1)
else:
if not failed:
if backend == 'strata':
self.s.ensure_idle()
else:
self.q.ensure_idle(self.q.observation())
subprocess.run(['sudo', '-n', 'systemctl', 'stop', owner['unit']], check=True, capture_output=True, timeout=60)
def free_gpu(self):
deadline = time.monotonic() + 15
while True:
try:
self.check_owners([])
except RuntimeError:
if time.monotonic() >= deadline:
raise
time.sleep(.25)
continue
used = subprocess.check_output(['nvidia-smi', '--query-gpu=memory.used', '--format=csv,noheader,nounits'], text=True)
if int(used.splitlines()[0]) <= 1024:
return
if time.monotonic() >= deadline:
raise RuntimeError('GPU memory did not release after managed shutdown')
time.sleep(.25)
def launch(self, target):
print('Завантаження вибраної моделі: ' + target['backend'], file=sys.stderr, flush=True)
if target['backend'] == 'agent':
return self.a.start(target['profile'])
if target['backend'] == 'llama':
return self.q.start(target)
if target['backend'] == 'strata':
return self.s.start(target)
recipe = self.native_recipe()
env = {**os.environ, **recipe['env']}
with (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)
if not record:
raise RuntimeError('Native supervisor exited immediately')
try:
with open(recipe['binary'], 'rb') as binary:
record['cli_sha256'] = hashlib.file_digest(binary, 'sha256').hexdigest()
save(NATIVE/'state.json', record)
except BaseException:
process.terminate()
process.wait(timeout=35)
raise
return {'started': True}
def restore(self, owner):
if owner['target']['backend'] == 'native':
save(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 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':
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):
return False
def wait_ready(self, target, budget):
started = time.monotonic()
deadline = started + budget
next_update = started + 20
while not self.ready(target):
if not any(self.matches(owner, target) for owner in self.inventory()) or time.monotonic() >= deadline:
raise RuntimeError('Target model failed or readiness deadline expired')
if time.monotonic() >= next_update:
print(f'Очікування готовності моделі: {int(time.monotonic() - started)} с', file=sys.stderr, flush=True)
next_update = time.monotonic() + 20
time.sleep(1)
print('Модель готова.', file=sys.stderr, flush=True)
def existing_result(self, target):
if target['backend'] == 'agent':
return {'started': False, **self.a.status()}
if target['backend'] == 'llama':
return {'started': False, 'key': self.q.KEY.read_text().strip(), 'state': self.q.observation()}
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()})
def main():
os.umask(0o077)
if len(sys.argv) != 2 or sys.argv[1] != 'start':
raise RuntimeError('Expected start action')
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:
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)
print(json.dumps(result))
if __name__ == '__main__':
try:
main()
except Exception as exc:
print(str(exc) if isinstance(exc, RuntimeError) else type(exc).__name__ + ': switch failed; current state saved privately', file=sys.stderr)
sys.exit(1)
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""Transaction tests without touching GPUs, processes, or user services."""
import importlib.util
from pathlib import Path
import unittest
from unittest.mock import Mock, patch
spec = importlib.util.spec_from_file_location('switcher', Path(__file__).with_name('strata-model-switch.py'))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
OLD = {'backend': 'native'}
NEW = {'backend': 'agent', 'profile': 'kar'}
class Fake:
def __init__(self, old=True):
self.current = [{'target': OLD}] if old else []
self.events = []
self.fail = None
self.unrelated = False
def prepare(self, target, budget):
self.events.append('prepare')
if self.fail == 'prepare': raise RuntimeError('missing file')
def inventory(self): return list(self.current)
def check_owners(self, owners):
self.events.append('owners')
if self.unrelated: raise RuntimeError('unrelated')
def matches(self, owner, target): return owner['target'] == target
def ready(self, target): return any(self.matches(o, target) for o in self.current)
def existing_result(self, target): return {'started': False}
def journal(self, phase, previous, target): self.events.append(phase)
def stop(self, owner, failed=False):
self.events.append('cleanup' if failed else 'stop')
self.current.remove(owner)
def free_gpu(self): self.events.append('free')
def launch(self, target):
self.events.append('launch')
self.current = [{'target': target}]
return {'started': True}
def wait_ready(self, target, budget):
self.events.append('wait')
if target == NEW and self.fail in {'ready', 'restore'}: raise RuntimeError('load failed')
def restore(self, owner):
self.events.append('restore')
if self.fail == 'restore': raise RuntimeError('restore failed')
self.current = [owner]
class Tests(unittest.TestCase):
def test_success_order(self):
h = Fake(); self.assertEqual(m.switch(h, NEW, 10), {'started': True})
self.assertEqual(h.events, ['prepare','owners','prepared','stop','free','loading','launch','wait','ready'])
def test_preflight_failure_keeps_old(self):
h=Fake(); h.fail='prepare'
with self.assertRaisesRegex(RuntimeError, 'missing'): m.switch(h, NEW, 10)
self.assertTrue(h.ready(OLD)); self.assertEqual(h.events,['prepare'])
def test_unrelated_owner_untouched(self):
h=Fake(); h.unrelated=True
with self.assertRaisesRegex(RuntimeError, 'unrelated'): m.switch(h, NEW, 10)
self.assertTrue(h.ready(OLD)); self.assertNotIn('stop',h.events)
def test_ambiguous_owners_untouched(self):
h=Fake();h.current.append({'target': NEW})
with self.assertRaisesRegex(RuntimeError,'Multiple'):m.switch(h,NEW,10)
self.assertNotIn('stop',h.events)
def test_idempotent(self):
h=Fake();self.assertFalse(m.switch(h,OLD,10)['started']);self.assertNotIn('stop',h.events)
def test_failed_start_rolls_back(self):
h=Fake();h.fail='ready'
with self.assertRaisesRegex(RuntimeError,'previous model restored'):m.switch(h,NEW,10)
self.assertTrue(h.ready(OLD));self.assertIn('cleanup',h.events);self.assertEqual(h.events[-1],'restored')
def test_failed_restore_reported(self):
h=Fake();h.fail='restore'
with self.assertRaisesRegex(RuntimeError,'could not be restored'):m.switch(h,NEW,10)
self.assertEqual(h.events[-1],'restore_failed')
def test_failure_without_previous_cleans_target(self):
h=Fake(False);h.fail='ready'
with self.assertRaisesRegex(RuntimeError,'no previous'):m.switch(h,NEW,10)
self.assertEqual(h.current,[])
def test_pid_reuse_and_ancestry(self):
processes={20:dict(pid=20,start_ticks='2',ppid=10),10:dict(pid=10,start_ticks='1',ppid=1)}
with patch.object(m,'identity',side_effect=processes.get):
self.assertTrue(m.owned(20,{10}));self.assertFalse(m.owned(20,{30}))
self.assertFalse(m.same_process(dict(pid=20,start_ticks='1')))
self.assertTrue(m.same_process(dict(pid=20,start_ticks='2')))
class PreparationTests(unittest.TestCase):
def test_agent_preflight_failure_never_unloads(self):
spec=importlib.util.spec_from_file_location('agent',Path(__file__).with_name('strata-agent-profile.py'))
agent=importlib.util.module_from_spec(spec);spec.loader.exec_module(agent)
with patch.object(agent,'prepare',side_effect=FileNotFoundError('missing')), patch.object(agent,'state') as state, patch.object(agent,'unload') as unload:
with self.assertRaises(FileNotFoundError):agent.start('strata-next-kar-ple-gpu')
state.assert_not_called();unload.assert_not_called()
def test_gpu_release_waits_without_killing(self):
host=object.__new__(m.Host)
with patch.object(host,'check_owners',side_effect=[RuntimeError('still exiting'),None]) as owners, patch.object(m.time,'sleep'), patch.object(m.subprocess,'check_output',return_value='500\n'):
host.free_gpu()
self.assertEqual(owners.call_count,2)
if __name__ == '__main__': unittest.main()
+143
View File
@@ -0,0 +1,143 @@
#!/usr/bin/env python3
"""Sanitized picker fixture; no remote calls or user profile access."""
import contextlib
import importlib.util
import io
import json
from pathlib import Path
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import Mock, patch
spec = importlib.util.spec_from_file_location('installer', Path(__file__).with_name('install-qwen-native-menu.py'))
installer = importlib.util.module_from_spec(spec)
spec.loader.exec_module(installer)
SOURCE = '''import json
from pathlib import Path
# Strata Next native bearer file integration v1
STRATA_MODEL = dict(id='old', backend='strata')
STRATA_AGENT_MODELS = [dict(id='kar', backend='strata-agent')]
def registry(): return [dict(id='first')]
def start_strata(args):
strata_remote('start', {'days': args.days})
strata_remote('start', {'days': args.days})
def remote(action, payload=None, stream=False, helper='/fixture/remote'):
proc = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', HOST,
'python3', helper, action], input=json.dumps(payload or {}))
return proc
def normal(args, kv_cache):
if not 0 <= args.wait_seconds <= 7200: raise RuntimeError('wait-seconds must be 0..7200')
return dict(days=args.days, kvCache=kv_cache)
def start_strata_agent(args, model):
observed = strata_agent_remote('start', {'profile': model['id']})
return observed
def list_models():
for model in [*registry(), STRATA_MODEL, *STRATA_AGENT_MODELS]:
if model.get('backend') == 'strata': modes = '1x256 · KV int8 · окремий рушій Strata'
print(model['id'])
def select_model(value):
models = [*registry(), STRATA_MODEL, *STRATA_AGENT_MODELS]
return next(m for m in models if m['id'] == value)
def dispatch(args, model):
if args.command == 'start':
if model.get('backend') == 'strata-agent': return start_strata_agent(args, model)
elif args.command == 'fetch':
if model.get('backend') == 'strata-agent':
return
'''
def args(**values):
return SimpleNamespace(**dict(dict(command='start', layout=None, kv_cache=None, kv_mode='with-key', wait_seconds=60, days=7), **values))
class MenuTests(unittest.TestCase):
def setUp(self):
socket_patch = patch('socket.socket')
self.socket = socket_patch.start()
self.socket.return_value.__enter__.return_value.connect_ex.return_value = 0
self.addCleanup(socket_patch.stop)
def module(self):
result = {}
exec(compile(installer.patched(SOURCE), 'fixture', 'exec'), result)
state = dict(backend='strata-native', model='strata-native-iq3-s', context=262144, parallel=1)
result.update(PROFILE=Path('/fixture'), validate_connection=Mock(), discover=Mock(return_value=state),
configure=Mock(), atomic=Mock(), strata_agent_remote=Mock(),
HOST='fixture', REMOTE='/fixture/remote', STRATA_AGENT_HELPER='/fixture/agent',
subprocess=Mock(), remote=Mock())
return result
def test_append_preserves_choices_and_switches_native(self):
m = self.module()
with contextlib.redirect_stdout(io.StringIO()) as out:
m['list_models']()
self.assertEqual(out.getvalue().splitlines(), ['first', 'old', 'kar', 'strata-native'])
with contextlib.redirect_stdout(io.StringIO()):
m['dispatch'](args(), m['select_model']('strata-native'))
target = m['discover'].call_args.args[0]
self.assertEqual(target['backend'], 'strata-native')
self.assertEqual(target['url'], 'http://127.0.0.1:18084')
self.assertFalse(target['managed'])
m['configure'].assert_called_once()
self.assertEqual(json.loads(m['atomic'].call_args.args[1]), target)
m['strata_agent_remote'].assert_not_called()
m['remote'].assert_called_once_with('start', {'backend': 'native', 'waitSeconds': 60}, stream=True, helper=m['STRATA_SWITCH_HELPER'])
def test_failure_and_incompatible_options_do_not_write_profile(self):
for changes in [dict(layout='2x256'), dict(kv_cache='f16'), dict(kv_mode='without-key')]:
m = self.module()
with self.assertRaises(RuntimeError):
m['start_strata_native'](args(**changes))
m['discover'].assert_not_called()
m['atomic'].assert_not_called()
for result in [OSError('offline'), RuntimeError('not ready'), {'model': 'other'}]:
m = self.module()
if isinstance(result, Exception):
m['discover'].side_effect = result
else:
m['discover'].return_value = result
with self.assertRaises(RuntimeError):
m['start_strata_native'](args())
m['configure'].assert_not_called()
m['atomic'].assert_not_called()
def test_all_managed_start_calls_route_through_switcher(self):
m = {}
exec(compile(installer.patched(SOURCE), 'fixture', 'exec'), m)
m.update(HOST='fixture', REMOTE='/fixture/remote', STRATA_AGENT_HELPER='/fixture/agent', subprocess=Mock())
for helper, backend in [('/fixture/remote', 'llama'), ('/fixture/agent', 'agent'), ('/home/para/inference/codex-qwen/strata_remote.py', 'strata')]:
m['remote']('start', {'id': 'test'}, helper=helper)
call = m['subprocess'].run.call_args
self.assertEqual(call.args[0][-2], m['STRATA_SWITCH_HELPER'])
self.assertEqual(json.loads(call.kwargs['input'])['backend'], backend)
m['remote']('status', helper='/fixture/remote')
self.assertEqual(m['subprocess'].run.call_args.args[0][-2], '/fixture/remote')
def test_switch_failure_does_not_write_profile(self):
m = self.module();m['remote'].side_effect=RuntimeError('rollback')
with self.assertRaisesRegex(RuntimeError,'rollback'):m['start_strata_native'](args())
m['atomic'].assert_not_called();m['configure'].assert_not_called()
def test_installer_backup_idempotence_and_anchor_fail_closed(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
path = root/'qwen_local.py'
path.write_text(SOURCE)
connection = root/'connection.json'
connection.write_text('{"unchanged":true}')
self.assertTrue(installer.install(path))
first = path.read_bytes()
self.assertFalse(installer.install(path))
self.assertEqual(path.read_bytes(), first)
self.assertEqual(connection.read_text(), '{"unchanged":true}')
backups = list(root.glob('*.before-native-picker-*'))
self.assertEqual(len(backups), 1)
self.assertEqual(backups[0].read_text(), SOURCE)
self.assertEqual(backups[0].stat().st_mode & 0o777, 0o600)
with self.assertRaises(RuntimeError):
installer.patched(SOURCE.replace('def start_strata(args):', 'def changed(args):'))
if __name__ == '__main__':
unittest.main()