361 lines
17 KiB
Python
361 lines
17 KiB
Python
#!/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)
|