Files
leleka/scripts/strata-model-switch.py
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

480 lines
23 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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 argparse
import fcntl
import http.client
import re
import stat
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import signal
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')
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, 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', 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 = 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() != 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'):
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(self.binary), 'config': str(self.config)}
save(path, recipe)
elif not path.exists():
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):
backend = target['backend']
if backend == 'agent':
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):
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 (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})
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']}
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)
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(self.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(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, http.client.HTTPException):
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(self.root/'state.json', {'phase': phase, 'previous': previous, 'target': target, 'updated_at': time.time()})
def main():
os.umask(0o077)
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:
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(deployment), 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)