Files
Athena-Deck/docs/maintenance/shared-qwen/activate.py
T
Mikei386 c0bc5d3a1b Integrate Basalt telemetry and shared GPU speech runtimes
Publish the reviewed accumulated runtime, scheduler, profile, UI, native recipes and historical maintenance evidence. Includes Qwen GPU ASR correction and shared Anna/atelier ownership. Validated with 784 local tests, Python/JSON parsing and eight JavaScript syntax checks. Live GPU acceptance and full fresh-host restore limits remain documented.
2026-11-03 21:16:41 +01:00

109 lines
11 KiB
Python

#!/usr/bin/env python3
"""Athena host: authorized shared-Qwen Deck + existing static atelier update."""
import argparse,difflib,hashlib,importlib.util,json,shutil,subprocess,time
from pathlib import Path
ROOT=Path('/opt/athena-deck-dev/shared-qwen-activation-v2');BASE=Path('/opt/athena-deck-dev/runtime');STATE=BASE/'state';SOURCE=Path('/opt/athena-deck-dev/source');HELPER=Path('/opt/athena-deck-docker-helper/stimmatelier/app.js')
IMAGE='athena-deck-standalone:shared-qwen';UI_STAGE='athena-stimmatelier:shared-qwen-candidate';UI_NAME='athena-stimmatelier'
FILES=('audio_policy.py','inference.py','tts_test.py','tts_worker.py','voxcpm_test.py','server.py','voice-ui.js','deploy/stimmatelier/app.js','deploy/stimmatelier/index.html')
SETTINGS=('profiles.json','endpoint.json','audio-policy.json','cpu-partition.json','reasoning-budget.json')
HOST_KEYS=('NetworkMode','ReadonlyRootfs','CapDrop','CapAdd','SecurityOpt','PidsLimit','Memory','MemorySwap','NanoCpus','RestartPolicy','PortBindings','Mounts','LogConfig','Tmpfs')
def info(name='athena-deck-dev'):return json.loads(subprocess.check_output(['docker','inspect',name],text=True))[0]
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def save(a):
p=ROOT/'activation.json';p.write_text(json.dumps(a,indent=2));p.chmod(0o600);assert json.loads(p.read_text())==a
def image_hashes(name,files):
code='from pathlib import Path;import hashlib,json;print(json.dumps({n:hashlib.sha256((Path("/app")/n).read_bytes()).hexdigest() for n in '+repr(tuple(files))+'}))'
return json.loads(subprocess.check_output(['docker','exec',name,'python3','-B','-c',code],text=True))
def build(context,tag):
with (context/'build.log').open('w') as f:subprocess.run(['docker','build','--network','none','--pull=false','-t',tag,context],check=True,stdout=f,stderr=subprocess.STDOUT,timeout=180)
def prepare():
assert not (ROOT/'activation.json').exists()
d=info();ui=info(UI_NAME)
for x in (d,ui):assert subprocess.check_output(['docker','image','inspect','--format','{{.Id}}',x['Config']['Image']],text=True).strip()==x['Image']
h=ui['HostConfig'];assert h['NetworkMode']=='none' and h['ReadonlyRootfs'] and h['CapDrop']==['ALL'] and not h.get('CapAdd') and not h.get('DeviceRequests') and not h.get('Devices') and not h.get('Privileged')
assert h.get('Mounts')==[dict(Type='bind',Source=str(STATE/'stimmatelier-ui'),Target='/data')]
assert ui['Config']['User']=='65534:65534' and ui['Config']['Entrypoint']==['python3','/app/app.py'] and not ui['Config']['Cmd']
before={n:sha(SOURCE/n) for n in FILES};after={n:sha(ROOT/'app'/n) for n in FILES}
assert image_hashes('athena-deck-dev',FILES)==before
ui_hashes=image_hashes(UI_NAME,['app.js','index.html'])
assert sha(HELPER)==ui_hashes['app.js'] and sha(HELPER.parent/'index.html')==ui_hashes['index.html']
assert after['deploy/stimmatelier/index.html']==ui_hashes['index.html'],'Preserve the actual live atelier markup'
diff=[]
for n in FILES:
p=ROOT/'before'/n;p.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(SOURCE/n,p)
(ROOT/'app'/n).chmod(0o644)
diff.extend(difflib.unified_diff((SOURCE/n).read_text().splitlines(True),(ROOT/'app'/n).read_text().splitlines(True),fromfile=n+' (live)',tofile=n+' (candidate)'))
(ROOT/'candidate.diff').write_text(''.join(diff));shutil.copy2(HELPER,ROOT/'helper-app.before.js')
(ROOT/'Dockerfile').write_text('FROM '+d['Config']['Image']+'\nUSER root\nCOPY app/ /app/\nUSER 65534:65534\n')
(ROOT/'.dockerignore').write_text('*\n!Dockerfile\n!app/\n!app/**\n')
build(ROOT,IMAGE)
probe="from pathlib import Path;import tempfile;from server import Server;from stt import qwen_asr_request;t=tempfile.TemporaryDirectory();s=Server(0,state_dir=Path(t.name));assert s.voxcpm_tests.shared_tts is s.tts_tests;assert s.tts_tests.acquire==s.scheduler.tts_reservation;assert '<asr_text>' in qwen_asr_request(b'fixture','de')['messages'][-1]['content'];s.endpoint.close();s.video.close();s.dashboard.close();s.server_close();t.cleanup();print('Shared Qwen image: full isolated constructor and preserved ASR passed')"
subprocess.run(['docker','run','--rm','--network','none','--read-only','--user','65534:65534','--memory','512m','--pids-limit','256','--cap-drop','ALL','-e','NVIDIA_VISIBLE_DEVICES=void','-e','DECK_REQUIRE_SETUP=0','-e','DECK_NETWORK_MODE=disabled','-e','TMPDIR=/test-tmp','--mount','type=bind,src='+str(STATE/'basalt-runtime/tmp')+',dst=/test-tmp','--entrypoint','python3',IMAGE,'-B','-c',probe],check=True,timeout=45)
u=ROOT/'ui';u.mkdir();shutil.copy2(ROOT/'app/deploy/stimmatelier/app.js',u/'app.js')
(u/'Dockerfile').write_text('FROM '+ui['Config']['Image']+'\nUSER root\nCOPY app.js /app/app.js\nUSER 65534:65534\n');build(u,UI_STAGE)
subprocess.run(['docker','run','--rm','--network','none','--read-only','--entrypoint','python3',UI_STAGE,'-B','-c',"import ast;from pathlib import Path;ast.parse(Path('/app/app.py').read_text());assert 'voice/select' in Path('/app/app.js').read_text();print('Static atelier candidate checked')"],check=True,timeout=20)
assert info()['State']['StartedAt']==d['State']['StartedAt'] and info(UI_NAME)['Id']==ui['Id']
image_id=subprocess.check_output(['docker','image','inspect','--format','{{.Id}}',IMAGE],text=True).strip();ui_image_id=subprocess.check_output(['docker','image','inspect','--format','{{.Id}}',UI_STAGE],text=True).strip()
save(dict(phase='prepared',image_before=d['Config']['Image'],image_id_before=d['Image'],image_id_after=image_id,ui_image_id_after=ui_image_id,started_before=d['State']['StartedAt'],source_before=before,source_after=after,config=json.loads((BASE/'installation.json').read_text()),settings={n:(STATE/n).read_text() for n in SETTINGS},ui_before=ui,ui_before_hashes=ui_hashes))
print('Both images prepared; protected live processes unchanged',flush=True)
def launch_ui(a):
old=a['ui_before'];h=old['HostConfig'];c=old['Config']
args=['docker','run','-d','--name',UI_NAME,'--network','none','--read-only','--cap-drop','ALL','--security-opt','no-new-privileges:true','--restart',h['RestartPolicy']['Name'],'--pids-limit',str(h['PidsLimit']),'--memory',str(h['Memory']),'--memory-swap',str(h['MemorySwap']),'--cpus',str(h['NanoCpus']/1e9),'--user',c['User'],'--workdir',c['WorkingDir'],'--hostname',c['Hostname'],'--mount','type=bind,src='+str(STATE/'stimmatelier-ui')+',dst=/data']
if h.get('LogConfig',{}).get('Type'):
args+=['--log-driver',h['LogConfig']['Type']]
for k,v in h['LogConfig'].get('Config',{}).items():args+=['--log-opt',k+'='+v]
for k,v in c.get('Labels',{}).items():args+=['--label',k+'='+v]
for v in c.get('Env',[]):args+=['-e',v]
args += [c['Image']] # The overlay inherits the complete original entrypoint/Cmd.
subprocess.run(args,check=True,stdout=subprocess.DEVNULL)
def apply():
a=json.loads((ROOT/'activation.json').read_text());assert a['phase']=='prepared'
d=json.loads((ROOT/'drained.json').read_text());assert 0<=time.time()-d['checked_at']<60 and d['state']=='stopped' and type(d['active_requests']) is int and d['active_requests']==0
assert all(type(d['scheduler'][k]) is int and d['scheduler'][k]==0 for k in ('active_requests','waiting_requests','tts_waiting_requests','stt_waiting_requests')) and d['scheduler']['switching'] is False
assert info()['Image']==a['image_id_before'] and info(UI_NAME)['Id']==a['ui_before']['Id']
assert subprocess.check_output(['docker','image','inspect','--format','{{.Id}}',IMAGE],text=True).strip()==a['image_id_after']
assert subprocess.check_output(['docker','image','inspect','--format','{{.Id}}',UI_STAGE],text=True).strip()==a['ui_image_id_after']
assert all(sha(SOURCE/n)==a['source_before'][n] for n in FILES) and sha(HELPER)==a['ui_before_hashes']['app.js']
assert all((STATE/n).read_text()==a['settings'][n] for n in SETTINGS if n!='endpoint.json')
subprocess.run(['docker','stop','--timeout','45','athena-deck-dev'],check=True)
assert not subprocess.check_output(['nvidia-smi','--query-compute-apps=pid','--format=csv,noheader,nounits'],text=True).strip()
for n in FILES:shutil.copy2(ROOT/'app'/n,SOURCE/n)
(STATE/'endpoint.json').write_text(a['settings']['endpoint.json'])
subprocess.run(['docker','rm','athena-deck-dev'],check=True)
spec=importlib.util.spec_from_file_location('deck_install',SOURCE/'deploy/install.py');assert spec and spec.loader;module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
config=dict(a['config'],image=IMAGE,previous_image=a['image_before']);module.launch(config);module.ready(config)
deadline=time.monotonic()+90
while info()['State'].get('Health',{}).get('Status')=='starting' and time.monotonic()<deadline:time.sleep(1)
assert info()['State']['Health']['Status']=='healthy';module.write_manifest(BASE,config)
# Keep the registered canonical UI tag so existing backup validation remains valid.
subprocess.run(['docker','tag',a['ui_before']['Image'],'athena-stimmatelier:before-shared-qwen'],check=True)
subprocess.run(['docker','tag',UI_STAGE,a['ui_before']['Config']['Image']],check=True)
subprocess.run(['docker','stop','--timeout','15',UI_NAME],check=True);subprocess.run(['docker','rm',UI_NAME],check=True);launch_ui(a)
shutil.copy2(ROOT/'app/deploy/stimmatelier/app.js',HELPER)
deadline=time.monotonic()+90
while info(UI_NAME)['State'].get('Health',{}).get('Status')=='starting' and time.monotonic()<deadline:time.sleep(1)
verify()
def verify():
a=json.loads((ROOT/'activation.json').read_text())
assert info()['Image']==a['image_id_after'] and info()['State']['Health']['Status']=='healthy'
actual=info(UI_NAME);assert actual['State']['Health']['Status']=='healthy'
assert actual['Image']==a['ui_image_id_after']
for k in HOST_KEYS:assert actual['HostConfig'].get(k)==a['ui_before']['HostConfig'].get(k),k
old_env=a['ui_before']['Config']['Env'];new_env=actual['Config']['Env']
pairs=lambda rows:dict(v.split('=',1) for v in rows)
assert len(pairs(old_env))==len(old_env) and len(pairs(new_env))==len(new_env) and pairs(old_env)==pairs(new_env),'Environment values changed'
for k in ('Labels','User','WorkingDir','Entrypoint','Cmd','Hostname'):assert actual['Config'].get(k)==a['ui_before']['Config'].get(k),k
assert image_hashes('athena-deck-dev',FILES)==a['source_after'] and image_hashes(UI_NAME,['app.js'])['app.js']==a['source_after']['deploy/stimmatelier/app.js']
assert sha(HELPER)==a['source_after']['deploy/stimmatelier/app.js'] and all((STATE/n).read_text()==a['settings'][n] for n in SETTINGS)
a.update(phase='activated; shared GPU acceptance pending',activated_at=time.time());save(a)
print('Deck and atelier activated healthy; source/image/helper hashes, UI sandbox and all protected settings verified',flush=True)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('operation',choices=('prepare','apply','verify'));p.add_argument('--go',action='store_true');args=p.parse_args();assert args.go,'Retained explicit Michael activation Go required'
{'prepare':prepare,'apply':apply,'verify':verify}[args.operation]()