Build Basalt 0.3.3 candidate and integrate media and response controls
This commit is contained in:
1 parent
584a884cc9
commit
34e711721a
44 files changed
+2266
-142
No files matched your search
+12
-2
@@ -11,10 +11,12 @@ from copy import deepcopy
|
||||
CHAT_FIELDS=frozenset({'model','messages','stream','stream_options','temperature','top_p','top_k','max_tokens','max_completion_tokens','stop','seed','tools','tool_choice','parallel_tool_calls','response_format','repeat_penalty','presence_penalty','frequency_penalty','logprobs','top_logprobs','user','n','reasoning_effort','reasoning_budget_tokens','chat_template_kwargs'})
|
||||
LLAMA_FIELDS=frozenset({'min_p','typical_p','repeat_last_n','mirostat','mirostat_tau','mirostat_eta','dynatemp_range','dynatemp_exponent','cache_prompt','ignore_eos','reasoning_format','logit_bias'})
|
||||
ADAPTER_FIELDS=frozenset({'functions','function_call','extra_body','metadata','store','service_tier','safety_identifier','prompt_cache_key'})
|
||||
CHAT_FIELDS=CHAT_FIELDS|LLAMA_FIELDS|ADAPTER_FIELDS
|
||||
CHAT_FIELDS=CHAT_FIELDS|LLAMA_FIELDS|ADAPTER_FIELDS|{'session_id'}
|
||||
|
||||
def capabilities():
|
||||
return dict(version=1,chat_route='/v1/chat/completions',fields=sorted(CHAT_FIELDS),llama_extensions=sorted(LLAMA_FIELDS|{'chat_template_kwargs'}),template_options=['enable_thinking','preserve_thinking'],aliases={'max_completion_tokens':'max_tokens','functions':'tools','function_call':'tool_choice'},unsupported_routes=['/v1/responses','/v1/embeddings','/completion','/slots'],model_dependent=['tools','vision','reasoning','json_schema'],notes=['Only n=1; no stored completions or priority service tier.','Model capabilities and backend-version support are not guaranteed by this field list.'])
|
||||
from chat_control import SESSION_HEADERS
|
||||
from chat_media import LIMITS
|
||||
return dict(version=1,chat_route='/v1/chat/completions',fields=sorted(CHAT_FIELDS),llama_extensions=sorted(LLAMA_FIELDS|{'chat_template_kwargs'}),template_options=['enable_thinking','preserve_thinking'],aliases={'max_completion_tokens':'max_tokens','functions':'tools','function_call':'tool_choice'},unsupported_routes=['/v1/responses','/v1/embeddings','/completion','/slots'],model_dependent=['tools','vision','reasoning','json_schema','logprobs','documents','video','answer_now','session_affinity'],model_properties_route='/props?model=API_ID',media_limits=dict(LIMITS),controls={'answer_now_route':'/v1/answer_now','scope':'same_principal','no_model_load':True,'request_id_header':'X-Request-Id','client_request_id_header':'X-Client-Request-Id','session_headers':list(SESSION_HEADERS)},notes=['Only n=1; no stored completions or priority service tier.','Model capabilities and backend-version support are not guaranteed by this field list.','Attachments are inline-only; no external URLs, file IDs or server paths.'])
|
||||
|
||||
LLAMA_EFFORTS=frozenset({'none','low','medium','high','xhigh'})
|
||||
# The installed llama.cpp server rejects minimal and max. Use nearest supported hints.
|
||||
@@ -35,6 +37,11 @@ def normalize_chat(data):
|
||||
unknown=set(data)-CHAT_FIELDS
|
||||
if unknown:raise CompatibilityError('Nicht unterstützte Chat-Felder: '+', '.join(sorted(unknown)))
|
||||
body=dict(data)
|
||||
if body.get('session_id') is None:body.pop('session_id',None)
|
||||
elif 'session_id' in body:
|
||||
from chat_control import identifier
|
||||
try:identifier(body['session_id'],'Sitzungskennung')
|
||||
except ValueError as exc:raise CompatibilityError(str(exc)) from None
|
||||
ignored=[]
|
||||
for key in ('metadata','safety_identifier','prompt_cache_key'):
|
||||
if key in body:
|
||||
@@ -51,6 +58,9 @@ def normalize_chat(data):
|
||||
ignored.append('service_tier')
|
||||
for key in ('stop','stream_options','logprobs','top_logprobs','tools','tool_choice','response_format','logit_bias'):
|
||||
if body.get(key,'absent') is None:body.pop(key,None)
|
||||
if 'logprobs' in body and type(body['logprobs']) is not bool:raise CompatibilityError('logprobs muss true oder false sein.')
|
||||
if 'top_logprobs' in body and (type(body['top_logprobs']) is not int or not 0<=body['top_logprobs']<=20):raise CompatibilityError('top_logprobs muss eine ganze Zahl von 0 bis 20 sein.')
|
||||
if 'top_logprobs' in body and body.get('logprobs') is not True:raise CompatibilityError('top_logprobs benötigt logprobs=true.')
|
||||
if 'max_completion_tokens' in body:
|
||||
value=body.pop('max_completion_tokens')
|
||||
if value is not None:
|
||||
|
||||
+5
-2
@@ -6,6 +6,7 @@ import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from ltx_original_runtime import LTXOriginalRuntime
|
||||
from basalt_tuning import profile_ready
|
||||
|
||||
RECIPE=json.loads((Path(__file__).parent/'basalt_sources.json').read_text())
|
||||
COMMIT=RECIPE['code']
|
||||
@@ -31,9 +32,11 @@ class BasaltRuntime(LTXOriginalRuntime):
|
||||
python,source=self.paths()
|
||||
try:ready=json.loads((self.root/'ready.json').read_text())
|
||||
except (OSError,ValueError):ready={}
|
||||
installed=ready.get('commit')==COMMIT and ready.get('version')==RECIPE['version'] and python.is_file() and (source/'bin/basalt').is_file()
|
||||
installed=ready.get('commit')==COMMIT and ready.get('version')==RECIPE['version'] and python.is_file() and (source/'bin/basalt').is_file() and profile_ready(self.root,RECIPE)
|
||||
vision=installed and ready.get('vision_architectures')==RECIPE['vision_architectures'] and (source/'bin/basalt-vision').is_file()
|
||||
return dict(installed=installed,revision=COMMIT,version=RECIPE['version'],job=dict(self.job) if self.job else None,required_disk_gib=6,model=dict(RECIPE['model']),gpu_policy='Text: eine SM120-GPU; Vision: separater SM86/SM120-Sidecar',context_per_slot=262144,max_slots=2,vision=vision)
|
||||
video=ready.get('video',{}) if installed else {}
|
||||
features=dict(answer_now=installed,logprobs=installed,session_affinity=installed,documents=bool(installed and ready.get('pdf_version')=='7.0.1'),video=bool(vision and isinstance(video,dict) and video.get('available') is True))
|
||||
return dict(installed=installed,revision=COMMIT,version=RECIPE['version'],job=dict(self.job) if self.job else None,required_disk_gib=6,model=dict(RECIPE['model']),gpu_policy='Text: eine SM120-GPU; Vision: separater SM86/SM120-Sidecar',context_per_slot=262144,max_slots=2,vision=vision,features=features,video=video)
|
||||
def prepared(self,entry):
|
||||
validate_model(entry)
|
||||
path=self.catalog.root/entry['id']/'model.basalt'
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ def install(service_module,handler_module):
|
||||
class Handler(base):
|
||||
def do_GET(self):
|
||||
if self.path.split('?',1)[0].rstrip('/')=='/telemetry':
|
||||
if self._authorized():self._json(200,snapshot(svc))
|
||||
if self._authorized():self._json(200,snapshot(svc.shown() if callable(getattr(svc,'shown',None)) else svc))
|
||||
return
|
||||
return super().do_GET()
|
||||
return Handler
|
||||
|
||||
+14
-5
@@ -1,10 +1,19 @@
|
||||
{
|
||||
"code": "9175e7a3211bda355c02e804c7c107b15b8ea89f",
|
||||
"version": "0.1.0",
|
||||
"code": "2729e2288f59e01836ddd7fcc630810ada98995a",
|
||||
"version": "0.3.3",
|
||||
"url": "https://github.com/jesdga95/basalt.git",
|
||||
"cuda": "13.0",
|
||||
"architectures": [120],
|
||||
"vision_architectures": [86, 120],
|
||||
"tuning": {
|
||||
"conversation_cache_mib": 1024,
|
||||
"expert_profile": {
|
||||
"file": "qwen4exp-48x512-v1pack.prof",
|
||||
"url": "https://raw.githubusercontent.com/xyehya/basalt/17a24e0298a3b998ca245a53000921e1dc60b406/setup/flashnext-ud-lamina/qwen4exp-48x512-v1pack.prof",
|
||||
"size": 196628,
|
||||
"sha256": "cd4f488c45c6936eb2e2f33b164553398f2201da352b4f4c8ffd66c12bcdf2df"
|
||||
}
|
||||
},
|
||||
"vision": {
|
||||
"repo": "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF",
|
||||
"revision": "ed59f92082b1e93c0e96d60a8b11aab089b52f09",
|
||||
@@ -14,9 +23,9 @@
|
||||
},
|
||||
"model": {
|
||||
"repo": "jesdga/Qwen3.8-Flash-Next-Basalt",
|
||||
"revision": "c0e57437ea564aa85263ab0bc0ee83568dd53213",
|
||||
"revision": "21b8357546172bf19a685ccf3353e7da7aeadde0",
|
||||
"file": "Qwen3.8-FN-GSQ-RCO-IQ3_XXS.basalt",
|
||||
"size": 79867643037,
|
||||
"sha256": "d02bb1b188bbc9ed6bc88ce5e89c7c2d64247290c7bae70fbb9d9d17fe65ed71"
|
||||
"size": 79865545428,
|
||||
"sha256": "c20595c2dd1c444b465f916447b835c1f30189ba1286932427115dac7b365165"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Pinned public expert-placement metadata; no model weights or vendor edits."""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import urllib.request
|
||||
|
||||
|
||||
def profile_path(root,recipe):
|
||||
pin=(recipe.get('tuning') or {}).get('expert_profile')
|
||||
return Path(root)/'profiles'/pin['file'] if pin else Path(root)/'source/data/profiles/qwen4exp-48x512.prof'
|
||||
|
||||
|
||||
def profile_ready(root,recipe):
|
||||
pin=(recipe.get('tuning') or {}).get('expert_profile')
|
||||
if not pin:return True
|
||||
p=profile_path(root,recipe)
|
||||
try:return not p.is_symlink() and p.stat().st_size==pin['size'] and hashlib.sha256(p.read_bytes()).hexdigest()==pin['sha256']
|
||||
except OSError:return False
|
||||
|
||||
|
||||
def install_profile(root,recipe):
|
||||
pin=(recipe.get('tuning') or {}).get('expert_profile')
|
||||
if not pin:return profile_path(root,recipe)
|
||||
p=profile_path(root,recipe)
|
||||
if p.name!=pin['file'] or Path(pin['file']).name!=pin['file']:raise ValueError('Ungültiger Expertenprofil-Dateiname.')
|
||||
if profile_ready(root,recipe):return p
|
||||
if p.parent.is_symlink():raise ValueError('Expertenprofil-Verzeichnis darf kein Symlink sein.')
|
||||
if p.exists() or p.is_symlink():raise ValueError('Vorhandenes Expertenprofil weicht vom festen Rezept ab; keine Überschreibung.')
|
||||
if not pin['url'].startswith('https://raw.githubusercontent.com/'):raise ValueError('Feste öffentliche HTTPS-Quelle erforderlich.')
|
||||
with urllib.request.urlopen(pin['url'],timeout=30) as response:data=response.read(pin['size']+1)
|
||||
if len(data)!=pin['size'] or hashlib.sha256(data).hexdigest()!=pin['sha256']:raise ValueError('Expertenprofil: Größe oder SHA-256 stimmt nicht.')
|
||||
p.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
pending=p.with_suffix('.partial')
|
||||
with pending.open('xb') as stream:
|
||||
stream.write(data);stream.flush();os.fsync(stream.fileno())
|
||||
pending.chmod(0o600);pending.replace(p)
|
||||
if not profile_ready(root,recipe):raise ValueError('Expertenprofil nach Installation nicht verifiziert.')
|
||||
return p
|
||||
+43
-6
@@ -1,5 +1,6 @@
|
||||
"""Deck-owned Basalt loopback worker; only selected GPU and own process group."""
|
||||
import json
|
||||
import http.client
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
@@ -7,12 +8,15 @@ import socket
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
from typing import Any
|
||||
import cpu_partition
|
||||
from basalt_runtime import validate_model,validate_projector
|
||||
from basalt_runtime import validate_model,validate_projector,RECIPE
|
||||
from basalt_tuning import profile_path
|
||||
from image_test import probe
|
||||
from inference import InferenceError,MemoryAdmissionError
|
||||
from strata_worker import StrataWorker
|
||||
from chat_control import ControlError
|
||||
|
||||
|
||||
def compute_capabilities():
|
||||
@@ -34,7 +38,37 @@ class BasaltWorker(StrataWorker):
|
||||
def status(self):
|
||||
with self.lock:
|
||||
if self.process and self.process.poll() is not None:self.state='failed';self.error='Basalt-Prozess beendet. Eigenes Worker-Protokoll prüfen; OOM nicht ohne Nachweis behaupten.'
|
||||
return dict(runtime='basalt',state=self.state,profile_id=self.profile['id'] if self.profile else None,profile_name=self.profile['name'] if self.profile else None,port=self.port,error=self.error,gpus=self.devices,memory_plan=self.memory_plan,phase=self.phase,cpu_allowed=self.cpu_layout['strata'] if self.cpu_layout else None)
|
||||
return dict(runtime='basalt',state=self.state,profile_id=self.profile['id'] if self.profile else None,profile_name=self.profile['name'] if self.profile else None,port=self.port,error=self.error,gpus=self.devices,memory_plan=self.memory_plan,phase=self.phase,cpu_allowed=self.cpu_layout['strata'] if self.cpu_layout else None,generation=getattr(self,'generation',None),basalt=getattr(self,'backend_info',None) if self.state=='ready' else None)
|
||||
def capabilities(self,p):
|
||||
installed=self.runtime.status();flags=installed.get('features',{})
|
||||
available=[name for name in ('answer_now','logprobs','documents','video') if flags.get(name) is True and (name!='video' or bool(p['parameters'].get('vision_projector')))]
|
||||
with self.lock:
|
||||
loaded=bool(self.state=='ready' and self.profile and (self.profile['id'],self.profile['revision'])==(p['id'],p.get('revision')))
|
||||
info=getattr(self,'backend_info',{}) or {}
|
||||
actual=info.get('capabilities',[]) if loaded else []
|
||||
if loaded:available=[x for x in available if x in actual]
|
||||
return dict(installed=installed.get('installed') is True,loaded=loaded,version=info.get('version') if loaded else installed.get('version') if installed.get('installed') is True else None,available=available,capabilities=list(actual),session_affinity=flags.get('session_affinity') is True)
|
||||
def answer_now(self,request):
|
||||
# Independent connection; never ensure(), acquire a model lease or stop work.
|
||||
with self.lock:
|
||||
if self.state!='ready' or not self.process or self.process.poll() is not None or not self.profile or (self.profile['id'],self.profile['revision'],getattr(self,'generation',None))!=(request['profile_id'],request['revision'],request['generation']):raise ControlError('Der ursprüngliche Worker ist nicht mehr bereit.',409,'worker_changed')
|
||||
if 'answer_now' not in (getattr(self,'backend_info',{}) or {}).get('capabilities',[]):raise ControlError('Jetzt antworten ist in diesem Worker nicht verfügbar.',501,'answer_now_unavailable')
|
||||
conn=http.client.HTTPConnection('127.0.0.1',self.port,timeout=5);key=self.key
|
||||
try:
|
||||
conn.request('POST','/v1/answer_now',json.dumps({'request_id':request['id']}).encode(),headers={'Content-Type':'application/json','Authorization':'Bearer '+key})
|
||||
response=conn.getresponse();raw=response.read(65537)
|
||||
if len(raw)>65536:raise ValueError()
|
||||
try:value=json.loads(raw)
|
||||
except (ValueError,UnicodeError):raise ValueError() from None
|
||||
if response.status!=200:
|
||||
code={404:'unknown_request',409:'not_thinking',400:'invalid_control'}.get(response.status,'upstream_control_error')
|
||||
raise ControlError('Die Backend-Steuerung wurde abgelehnt.',response.status if response.status in (400,404,409) else 502,code)
|
||||
if not isinstance(value,dict) or value.get('state') not in ('queued','prompt','thinking'):raise ValueError()
|
||||
return {'state':value['state']}
|
||||
except (OSError,ValueError) as exc:
|
||||
if isinstance(exc,ControlError):raise
|
||||
raise ControlError('Backend-Steuerung derzeit nicht erreichbar oder ungültig.',502,'upstream_control_error') from None
|
||||
finally:conn.close()
|
||||
def plan(self,p,cancel=lambda:False):
|
||||
errors=self.blockers(p)
|
||||
if errors:raise InferenceError('; '.join(errors))
|
||||
@@ -55,14 +89,14 @@ class BasaltWorker(StrataWorker):
|
||||
self.memory_plan.update(vision_gpu=vision,vision_index=card)
|
||||
return self.memory_plan
|
||||
@staticmethod
|
||||
def configuration(p,model,port,reserve,vision_index=None):
|
||||
def configuration(p,model,port,reserve,vision_index=None)->dict[str,Any]:
|
||||
params=p['parameters']
|
||||
if params.get('vision_projector') and type(vision_index) is not int:raise InferenceError('Vision-GPU-Index fehlt; kein stiller CPU-/GPU-Fallback.')
|
||||
return dict(server=dict(model=str(model),alias=p['api_id'],host='127.0.0.1',port=port,gpu='0',parallel=params.get('slots',1),**{'slot-full-context':True,'vision':str(vision_index) if params.get('vision_projector') else 'off'}),engine={'max-context':params['context'],'kv':'int8','expert-cache':'auto','prefill':'auto','resident-experts':True,'vram-reserve-mib':reserve})
|
||||
return dict(version=2,server=dict(host='127.0.0.1',port=port,**{'image-remote-only':True}),models=[dict(model=str(model),alias=p['api_id'],gpu='0',parallel=params.get('slots',1),**{'slot-full-context':True,'vision':str(vision_index) if params.get('vision_projector') else 'off'})],engine={'max-context':params['context'],'kv':'int8','expert-cache':'auto','prefill':'auto','resident-experts':True,'vram-reserve-mib':reserve,'conversation-cache-mib':(RECIPE.get('tuning') or {}).get('conversation_cache_mib',0)})
|
||||
@staticmethod
|
||||
def server_command(python,source,config,key):
|
||||
# Upstream accepts API credentials only on CLI, never in a config file.
|
||||
return [str(python),str(Path(__file__).with_name('basalt_serve.py')),'--deck-source',str(source),'--engine-bin',str(source/'bin/basalt'),'--config',str(config),'--api-key',key]
|
||||
return [str(python),str(Path(__file__).with_name('basalt_serve.py')),'--deck-source',str(source),'--engine-bin',str(source/'bin/basalt'),'--config',str(config),'--api-key',key,'--expert-profile',str(profile_path(source.parent,RECIPE))]
|
||||
@staticmethod
|
||||
def verify_properties(props,params):
|
||||
if props.get('is_sleeping') is not False or props.get('total_slots')!=params.get('slots',1) or (props.get('default_generation_settings') or {}).get('n_ctx')!=params['context']:
|
||||
@@ -81,7 +115,7 @@ class BasaltWorker(StrataWorker):
|
||||
for folder in ('home','tmp','cache','cache/cuda'):(self.root/folder).mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
env=dict(os.environ,CUDA_VISIBLE_DEVICES=','.join(self.devices),HOME=str(self.root/'home'),TMPDIR=str(self.root/'tmp'),XDG_CACHE_HOME=str(self.root/'cache'),CUDA_CACHE_PATH=str(self.root/'cache/cuda'),PYTHONUNBUFFERED='1',OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1')
|
||||
libs=self.runtime.root/'cuda';env['LD_LIBRARY_PATH']=str(libs/'lib64')+os.pathsep+str(libs/'lib')+os.pathsep+env.get('LD_LIBRARY_PATH','')
|
||||
self.profile=p
|
||||
self.profile=p;self.generation=uuid.uuid4().hex;self.backend_info={}
|
||||
with (self.root/'server.log').open('w') as output:self.process=subprocess.Popen(cpu_partition.command(self.server_command(python,source,path,self.key),layout['strata'] if layout else None),cwd=source,env=env,stdout=output,stderr=subprocess.STDOUT,start_new_session=True)
|
||||
try:
|
||||
deadline=time.monotonic()+600
|
||||
@@ -93,6 +127,9 @@ class BasaltWorker(StrataWorker):
|
||||
with urllib.request.urlopen(req,timeout=3) as response:props=json.load(response)
|
||||
if props.get('is_sleeping') is False:
|
||||
self.verify_properties(props,params)
|
||||
info=props.get('basalt')
|
||||
if not isinstance(info,dict) or info.get('version')!=RECIPE['version'] or not isinstance(info.get('capabilities'),list) or any(not isinstance(x,str) for x in info['capabilities']):raise InferenceError('Basalt hat Version und Fähigkeiten des gepinnten Rezepts nicht bestätigt.')
|
||||
self.backend_info={'version':info['version'],'capabilities':[x for x in info['capabilities'] if x in ('answer_now','logprobs','documents','video')]}
|
||||
with self.lock:self.state='ready';self.phase='Basalt bereit'
|
||||
return
|
||||
except InferenceError:raise
|
||||
|
||||
+38
-11
@@ -3,27 +3,54 @@ window.ChatTestUI=(()=>{
|
||||
const gib=v=>v==null?'unbekannt':(v/1024).toFixed(2)+' GiB';
|
||||
async function api(path,data){const r=await fetch('/api/v1/'+path,data===undefined?{}:{method:'POST',headers:{'Content-Type':'application/json','X-Athena-Deck':'1'},body:JSON.stringify(data)});const v=await r.json();if(!r.ok)throw Error(v.error||'Anfrage fehlgeschlagen');return v;}
|
||||
function put(el,html){if(el._chatHtml!==html){el.innerHTML=html;el._chatHtml=html;}}
|
||||
function html(){return `<section id="chat-test"><h2>Sprachmodell testen</h2><p>Ein einfacher Textchat mit deinem gespeicherten Profil. Nutzt denselben Worker wie API-Anfragen; eine öffentliche Profilfreigabe ist nicht erforderlich.</p><form id="chat-test-form" class="card"><div class="form-grid"><label>Chatprofil<select id="chat-profile" required></select></label><label>Maximale Antwort-Token<input id="chat-limit" type="number" min="1" max="4096" value="1024" required></label></div><p id="chat-profile-info"></p><div id="chat-transcript" aria-live="polite"></div><label>Nachricht<textarea id="chat-prompt" rows="4" maxlength="8000" required placeholder="Schreibe eine kurze Testnachricht …"></textarea></label><div class="card-actions"><button id="chat-send" disabled>Senden</button><button type="button" class="secondary" id="chat-clear">Neuer Chat</button></div><p class="small">Der Verlauf bleibt nur in dieser Ansicht und wird bei Profilwechsel oder Neuladen verworfen. Prompts und Antworten werden nicht als Chatdatei gespeichert.</p></form><p id="chat-message" role="alert"></p><section class="card"><h3>Laufzeit & Diagnose</h3><div id="chat-state" role="status"></div><div class="card-actions"><button class="secondary" id="chat-cancel" disabled>Test abbrechen</button><button class="secondary" id="chat-unload">Modell entladen</button></div><p>Entladen ist nur ohne laufende Anfragen möglich. Abbrechen beendet nur diesen Test; andere Antworten werden nicht gestoppt.</p></section><section class="card"><h3>Speicherprüfung</h3><div id="chat-memory"></div><p class="small">Prognose mit Reserve, keine Garantie für jede Anfrage. GPU-Layer können automatisch auf die CPU ausgelagert werden. Bei Fehlern helfen häufig kleinerer Kontext oder Microbatch. <a class="link" href="#hardware">Hardware-Messwerte →</a></p></section></section>`;}
|
||||
function html(){return `<section id="chat-test"><h2>Sprachmodell testen</h2><p>Chat mit deinem gespeicherten Profil, bei unterstützter Laufzeit auch mit Bildern, Dokumenten und Videos. Nutzt denselben Worker wie die API; keine öffentliche Profilfreigabe erforderlich.</p>
|
||||
<form id="chat-test-form" class="card"><div class="form-grid"><label>Chatprofil<select id="chat-profile" required></select></label><label>Maximale Antwort-Token<input id="chat-limit" type="number" min="1" max="4096" value="1024" required></label><label>Denkstufe<select id="chat-effort"><option value="">Profilvorgabe</option value="none">Ohne Denken</option><option value="low">Wenig</option><option value="medium">Mittel</option><option value="high">Viel</option><option value="xhigh">Sehr viel</option></select></label></div>
|
||||
<p id="chat-profile-info"></p><p id="chat-features" role="status"></p><div id="chat-transcript" aria-live="polite"></div><label>Nachricht<textarea id="chat-prompt" rows="4" maxlength="8000" required placeholder="Stelle eine Frage, optional zu angehängten Dateien …"></textarea></label>
|
||||
<details><summary>Anhänge & Diagnoseoptionen</summary><div class="form-grid"><label>Dateien anhängen<input id="chat-files" type="file" multiple disabled></label><label>PDF-Seiten für neue Anhänge<input id="chat-pages" placeholder="Alle oder z. B. 1-5,8" maxlength="256"></label><label><input id="chat-logprobs" type="checkbox" disabled>Token-Wahrscheinlichkeiten mitliefern</label></div><div id="chat-attachments" aria-live="polite"></div><p class="small">Nur eingebettete Dateien, keine Serverpfade oder externen URLs. Höchstens 8 Anhänge und 32 MiB im gesamten Verlauf; Dokument je 16 MiB. Video: maximal 2 Bilder/s und 128 Frames, keine Tonspur. Token-Wahrscheinlichkeiten sind kein Fakten- oder Wahrheitsnachweis.</p></details>
|
||||
<div class="card-actions"><button id="chat-send" disabled>Senden</button><button type="button" class="secondary" id="chat-clear">Neuer Chat</button></div><p class="small">Verlauf und Anhänge bleiben nur in dieser Ansicht und werden bei Profilwechsel oder Neuladen verworfen. Keine Chatdatei wird gespeichert.</p></form>
|
||||
<p id="chat-message" role="alert"></p><section class="card"><h3>Laufzeit & Diagnose</h3><div id="chat-state" role="status"></div><div class="card-actions"><button class="secondary" id="chat-answer-now" disabled>Jetzt antworten</button><button class="secondary" id="chat-cancel" disabled>Test abbrechen</button><button class="secondary" id="chat-unload" disabled>Modell entladen</button></div><p>Jetzt antworten beendet nur das Denken dieses Tests und lässt seine Antwort weiterlaufen. Abbrechen beendet nur diesen Test. Entladen ist nur ohne aktive oder wartende Arbeit möglich.</p></section><section class="card"><h3>Speicherprüfung</h3><div id="chat-memory"></div><p class="small">Konfiguration und Prognose sind keine Vollkontext- oder Lastgarantie. <a class="link" href="#hardware">Hardware-Messwerte →</a></p></section></section>`;}
|
||||
function metrics(j){
|
||||
const t=j?.timings||{},u=j?.usage||{},num=(v,d=0)=>typeof v==='number'?v.toLocaleString('de-DE',{maximumFractionDigits:d}):'—',sec=v=>v==null?'—':num(v/1000,3)+' s';
|
||||
return `<h4>Token & Geschwindigkeit · letzter Test</h4><table><thead><tr><th>Phase</th><th>Token</th><th>Dauer</th><th>Token/s</th></tr></thead><tbody><tr><td>Eingabe / Prefill (berechnet)</td><td>${num(t.prompt_n)}</td><td>${sec(t.prompt_ms)}</td><td>${num(t.prompt_per_second,2)}</td></tr><tr><td>Ausgabe / Generierung</td><td>${num(t.predicted_n)}</td><td>${sec(t.predicted_ms)}</td><td>${num(t.predicted_per_second,2)}</td></tr></tbody></table><p>Eingabe gesamt: ${num(u.prompt_tokens)} Token · Ausgabe gesamt: ${num(u.completion_tokens)} Token</p><p class="small">Messwerte von llama.cpp nach Abschluss der Antwort. Prefill zählt neu berechnete Eingabe-Token; wiederverwendeter Kontext kann die Arbeit reduzieren. Ausgabe umfasst auch Reasoning. Modellladen und Wartezeit sind nicht Teil der Token/s. — = noch nicht verfügbar, etwa während der Antwort oder nach Abbruch.</p>`;
|
||||
return `<h4>Token & Geschwindigkeit · letzter Test</h4><table><thead><tr><th>Phase</th><th>Token</th><th>Dauer</th><th>Token/s</th></tr></thead><tbody><tr><td>Eingabe / Prefill (berechnet)</td><td>${num(t.prompt_n)}</td><td>${sec(t.prompt_ms)}</td><td>${num(t.prompt_per_second,2)}</td></tr><tr><td>Ausgabe / Generierung</td><td>${num(t.predicted_n)}</td><td>${sec(t.predicted_ms)}</td><td>${num(t.predicted_per_second,2)}</td></tr></tbody></table><p>Eingabe gesamt: ${num(u.prompt_tokens)} Token · Ausgabe gesamt: ${num(u.completion_tokens)} Token</p><p class="small">Messwerte des Modell-Backends. Prefill zählt neu berechnete Eingabe-Token; wiederverwendeter Kontext kann die Arbeit reduzieren. Ausgabe umfasst auch Reasoning. Modellladen und Wartezeit sind nicht Teil der Token/s. — = noch nicht verfügbar.</p>${j?.logprobs?.length?`<details><summary>Letzte Token-Wahrscheinlichkeiten</summary><p>Modellwahrscheinlichkeiten, kein Wahrheitsnachweis.</p><pre>${e(JSON.stringify(j.logprobs.slice(-20),null,2))}</pre></details>`:''}`;
|
||||
}
|
||||
function bind(){
|
||||
const root=document.querySelector('#chat-test'),el=id=>root.querySelector('#'+id);let profiles=[],messages=[],turns=[],ownJob=null,finished=null,status=null,pending=false;
|
||||
const root=document.querySelector('#chat-test'),el=id=>root.querySelector('#'+id);let profiles=[],messages=[],turns=[],ownJob=null,finished=null,status=null,pending=false,caps={},attachments=[],filePending=false,controlPending=false,epoch=0,historyBytes=0,capabilityStamp=null;
|
||||
const newSession=()=>`test-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;let session=newSession();
|
||||
const notice=t=>{if(root.isConnected)el('chat-message').textContent=t;};
|
||||
function transcript(){put(el('chat-transcript'),turns.map(t=>`<div class="note"><strong>${t.role==='user'?'Du':'Modell'}</strong><p class="chat-text">${e(t.content)}</p>${t.reasoning?`<details><summary>Reasoning-Ausgabe</summary><pre>${e(t.reasoning)}</pre></details>`:''}</div>`).join(''));}
|
||||
function selection(){const p=profiles.find(p=>p.id===el('chat-profile').value),running=status?.job?.state==='running';el('chat-profile-info').textContent=p?`${p.parameters.context.toLocaleString('de-DE')} Token gesamt · ${p.parameters.slots} Slots · Batch ${p.parameters.batch} / Microbatch ${p.parameters.ubatch}${p.blockers.length?' · '+p.blockers.join(' '):''}`:'Zuerst ein Sprachmodellprofil anlegen.';el('chat-send').disabled=pending||running||!p?.runnable;el('chat-profile').disabled=pending||running;el('chat-clear').disabled=pending||running;el('chat-cancel').disabled=!running;el('chat-unload').disabled=!!status?.scheduler.active_requests;}
|
||||
function transcript(){put(el('chat-transcript'),turns.map(t=>`<div class="note"><strong>${t.role==='user'?'Du':'Modell'}</strong><p class="chat-text">${e(t.content)}</p>${t.files?.length?`<p class="small">Anhänge: ${t.files.map(e).join(' · ')}</p>`:''}${t.reasoning?`<details><summary>Reasoning-Ausgabe</summary><pre>${e(t.reasoning)}</pre></details>`:''}</div>`).join(''));}
|
||||
function pendingFiles(){put(el('chat-attachments'),attachments.map((a,n)=>`<p>${e(a.name)} · ${(a.size/1024).toFixed(1)} KiB <button type="button" class="secondary" data-remove="${n}">Entfernen</button></p>`).join(''));el('chat-attachments').querySelectorAll('[data-remove]').forEach(b=>b.onclick=()=>{if(pending||filePending||status?.job?.state==='running')return;attachments.splice(Number(b.dataset.remove),1);pendingFiles();});}
|
||||
function selection(){const p=profiles.find(p=>p.id===el('chat-profile').value),running=status?.job?.state==='running',busy=pending||filePending||running,features=caps.available||[];
|
||||
el('chat-profile-info').textContent=p?`${(p.parameters.context||0).toLocaleString('de-DE')} Token ${['basalt','strata'].includes(p.parameters.chat_runtime)?'pro Slot':'gesamt'} · ${p.parameters.slots} Slot(s)${p.blockers.length?' · '+p.blockers.join(' '):''}`:'Zuerst ein Sprachmodellprofil anlegen.';
|
||||
el('chat-features').textContent=p?`${caps.runtime||p.parameters.chat_runtime||'llama.cpp'}${caps.version?' '+caps.version:''} · ${caps.loaded?'Modell geladen':'nicht geladen / installierte Möglichkeiten'} · ${features.join(', ')||'keine erweiterten Fähigkeiten bestätigt'}`:'';
|
||||
el('chat-send').disabled=busy||!p?.runnable;['chat-profile','chat-clear','chat-effort','chat-pages'].forEach(id=>el(id).disabled=busy);
|
||||
el('chat-cancel').disabled=!running||status?.job?.id!==ownJob;el('chat-answer-now').disabled=controlPending||!running||status?.job?.id!==ownJob||!status?.job?.can_answer_now;
|
||||
const s=status?.scheduler;el('chat-unload').disabled=!s||!Number.isInteger(s.active_requests)||!Number.isInteger(s.waiting_requests)||s.active_requests!==0||s.waiting_requests!==0||s.switching===true||running;
|
||||
el('chat-logprobs').disabled=busy||!features.includes('logprobs');if(!features.includes('logprobs'))el('chat-logprobs').checked=false;
|
||||
let accept=[];if(p?.parameters.vision_projector)accept.push('.png','.jpg','.jpeg','.webp');if(features.includes('documents'))accept.push('.pdf','.docx','.pptx','.xlsx','.txt','.md','.csv','.json','.yaml','.yml','.xml');if(features.includes('video'))accept.push('.mp4','.webm','.mov','.mkv');el('chat-files').accept=accept.join(',');el('chat-files').disabled=busy||!accept.length;
|
||||
}
|
||||
async function capabilities(reset=true){const id=el('chat-profile').value,version=epoch;if(reset)caps={};selection();if(!id)return;try{const value=await api('chat-tests/capabilities?profile_id='+encodeURIComponent(id));if(root.isConnected&&version===epoch&&id===el('chat-profile').value){caps=value;selection();}}catch(error){notice(error.message);}}
|
||||
function memory(plan,w,h){if(!plan)return '<p>Noch keine Speicherprognose vorhanden.</p>';if(['basalt','strata'].includes(plan.runtime))return `<p>${e(plan.runtime)} · ${(plan.context||0).toLocaleString('de-DE')} Token pro Slot · ${plan.slots} Slot(s) · KV ${e(plan.kv)} · Experten ${e(plan.experts)}</p><p>GPU(s): ${(plan.gpus||[]).map(g=>e((h.gpus||[]).find(x=>x.uuid===g)?.name||g)).join(', ')}</p><p>Konfigurierte CPU-Freigabe: ${(w.cpu_allowed||[]).map(e).join(', ')||'nicht gemeldet'}. Keine exklusive Reservierung.</p>`;return `<p><strong>${plan.fits?'Prognose passt einschließlich Reserve':'Prognose passt nicht in den verfügbaren Speicher'}</strong> · ${(plan.context||0).toLocaleString('de-DE')} Token / ${plan.slots} Slots</p>${(plan.gpus||[]).map(g=>`<p>${e(g.name)}: geschätzt ${gib(g.required_mib)} + ${gib(g.reserve_mib)} Reserve / ${gib(g.free_mib)} frei</p>`).join('')}<p>RAM: ${gib(plan.host_required_mib)} benötigt / ${gib(plan.host_available_mib)} verfügbar</p>`;}
|
||||
async function refresh(){try{const [s,h]=await Promise.all([api('chat-tests'),api('hardware').catch(()=>({gpus:[]}))]);if(!root.isConnected)return;status=s;const j=s.job,w=s.worker,plan=w.memory_plan;
|
||||
const stamp=[w.generation,w.state,w.profile_id,el('chat-profile').value].join('/');if(el('chat-profile').value&&stamp!==capabilityStamp){capabilityStamp=stamp;capabilities(false);}
|
||||
put(el('chat-state'),`<p><strong>${e(j?.phase||'Noch kein Chat-Test gestartet.')}</strong></p><p>Worker: ${e(w.phase||w.state)} · ${e(w.profile_name||'kein Modell geladen')}<br>${s.scheduler.active_requests} laufende / ${s.scheduler.waiting_requests} wartende Anfragen</p>${j?.error?`<p role="alert">${e(j.error)}</p>`:''}${w.error?`<p>${e(w.error)}</p>`:''}${metrics(j)}${j?`<p>Dauer: ${Math.max(0,Math.round((j.finished_at||Date.now()/1000)-j.started_at))} s</p>`:''}`);
|
||||
put(el('chat-memory'),(plan?`<p>Letzte Prognose für ${e(plan.profile_name||w.profile_name||'das Modell')}</p><p><strong>${plan.fits?'Prognose passt einschließlich Reserve':'Prognose passt nicht in den verfügbaren Speicher'}</strong> · ${plan.context.toLocaleString('de-DE')} Token / ${plan.slots} Slots · ${plan.gpu_layers===999?'Alle Schichten einschließlich Ausgabe auf GPU':`GPU-Layerlimit ${plan.gpu_layers} · CPU-Auslagerung möglich (kann stark bremsen)`}</p>${plan.gpus.map(g=>`<p>${e(g.name)}: geschätzt ${gib(g.required_mib)} + ${gib(g.reserve_mib)} Reserve / ${gib(g.free_mib)} beim Prüfen frei</p>`).join('')}<p>RAM-Budget: ${gib(plan.host_required_mib)} benötigt / ${gib(plan.host_available_mib)} verfügbar</p>`:'<p>Noch keine Speicherprognose für einen Modellstart vorhanden.</p>')+`<h4>Aktuelle GPU-Belegung</h4>${(h.gpus||[]).map(g=>`<p>${e(g.name)}: ${gib(g.used_mib)} / ${gib(g.total_mib)} belegt · ${g.percent??'—'} % Auslastung</p>`).join('')||'<p>GPU-Messwerte nicht verfügbar.</p>'}`);
|
||||
put(el('chat-memory'),memory(plan,w,h)+`<h4>Aktuelle GPU-Belegung</h4>${(h.gpus||[]).map(g=>`<p>${e(g.name)}: ${gib(g.used_mib)} / ${gib(g.total_mib)} belegt · ${g.percent??'—'} % Auslastung</p>`).join('')||'<p>GPU-Messwerte nicht verfügbar.</p>'}`);
|
||||
if(j&&j.id===ownJob){let response=turns[turns.length-1];if(response?.role!=='assistant'){response={role:'assistant',content:'',reasoning:''};turns.push(response);}response.content=j.answer;response.reasoning=j.reasoning;transcript();
|
||||
if(j.state!=='running'&&finished!==j.id){finished=j.id;if(j.state==='complete'&&j.answer)messages.push({role:'assistant',content:j.answer});else{messages=[];notice('Der nächste Prompt beginnt einen neuen Kontext; der letzte Test wurde nicht vollständig beantwortet.');}if(j.finish_reason==='length')notice('Antwort am Tokenlimit beendet. Bei Bedarf das Antwortlimit erhöhen.');}
|
||||
if(j.state!=='running'&&finished!==j.id){finished=j.id;if(j.state==='complete'&&j.answer)messages.push({role:'assistant',content:j.answer});else{messages=[];historyBytes=0;session=newSession();notice('Der nächste Prompt beginnt einen neuen Kontext; der letzte Test wurde nicht vollständig beantwortet.');}if(j.finish_reason==='length')notice('Antwort am Tokenlimit beendet. Bei Bedarf das Antwortlimit erhöhen.');}
|
||||
}selection();
|
||||
}catch(error){notice(error.message);}finally{if(root.isConnected)setTimeout(refresh,1500);}}
|
||||
api('profiles').then(s=>{if(!root.isConnected)return;profiles=s.profiles.filter(p=>p.kind==='chat');el('chat-profile').innerHTML=profiles.map(p=>`<option value="${e(p.id)}">${e(p.name)}${p.runnable?'':' · nicht ausführbar'}</option>`).join('')||'<option value="">Zuerst ein Chatprofil anlegen</option>';selection();}).catch(err=>notice(err.message));
|
||||
const clear=()=>{messages=[];turns=[];ownJob=null;finished=null;transcript();notice('Neuer Chat.');};el('chat-clear').onclick=clear;el('chat-profile').onchange=()=>{clear();selection();};
|
||||
el('chat-test-form').onsubmit=async event=>{event.preventDefault();pending=true;selection();const text=el('chat-prompt').value.trim();try{const next=[...messages,{role:'user',content:text}];const job=await api('chat-tests/start',{profile_id:el('chat-profile').value,messages:next,max_tokens:Number(el('chat-limit').value)});messages=next;turns.push({role:'user',content:text});ownJob=job.id;finished=null;status={...status,job};el('chat-prompt').value='';transcript();notice('Test gestartet. Speicherprüfung, Modellstart und Antwort erscheinen unter Diagnose.');}catch(error){notice(error.message);}finally{pending=false;selection();}};
|
||||
el('chat-cancel').onclick=async()=>{try{await api('chat-tests/cancel',{});notice('Abbruch angefordert.');}catch(error){notice(error.message);}};
|
||||
api('profiles').then(s=>{if(!root.isConnected)return;profiles=s.profiles.filter(p=>p.kind==='chat');el('chat-profile').innerHTML=profiles.map(p=>`<option value="${e(p.id)}">${e(p.name)}${p.runnable?'':' · nicht ausführbar'}</option>`).join('')||'<option value="">Zuerst ein Chatprofil anlegen</option>';selection();capabilities();}).catch(err=>notice(err.message));
|
||||
const clear=()=>{epoch++;messages=[];turns=[];attachments=[];historyBytes=0;capabilityStamp=null;ownJob=null;finished=null;session=newSession();pendingFiles();transcript();notice('Neuer Chat.');};el('chat-clear').onclick=()=>{clear();capabilities();};el('chat-profile').onchange=()=>{clear();capabilities();};
|
||||
const read=file=>new Promise((resolve,reject)=>{const r=new FileReader();r.onerror=()=>reject(Error('Datei konnte nicht gelesen werden.'));r.onload=()=>resolve(String(r.result).split(',')[1]);r.readAsDataURL(file);});
|
||||
el('chat-files').onchange=async()=>{const version=epoch,selected=[...el('chat-files').files],features=caps.available||[],loaded=[];filePending=true;selection();try{
|
||||
const historyCount=messages.reduce((n,m)=>n+(Array.isArray(m.content)?m.content.filter(p=>p.type!=='text').length:0),0);if(historyCount+attachments.length+selected.length>8)throw Error('Maximal acht Anhänge im gesamten Verlauf.');
|
||||
if(historyBytes+attachments.reduce((n,a)=>n+a.size,0)+selected.reduce((n,f)=>n+f.size,0)>32*1024**2)throw Error('Anhänge überschreiten zusammen 32 MiB. Neuen Chat beginnen oder Dateien verkleinern.');
|
||||
const docs={pdf:'application/pdf',docx:'application/vnd.openxmlformats-officedocument.wordprocessingml.document',pptx:'application/vnd.openxmlformats-officedocument.presentationml.presentation',xlsx:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',txt:'text/plain',md:'text/markdown',csv:'text/csv',json:'application/json',yaml:'application/yaml',yml:'application/yaml',xml:'application/xml'},images={png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',webp:'image/webp'},videos={mp4:'video/mp4',webm:'video/webm',mov:'video/quicktime',mkv:'video/x-matroska'};
|
||||
for(const f of selected){const ext=f.name.split('.').pop().toLowerCase(),p=profiles.find(x=>x.id===el('chat-profile').value);let kind,mime;if(images[ext]&&p?.parameters.vision_projector){kind='image';mime=images[ext];}else if(docs[ext]&&features.includes('documents')){kind='document';mime=docs[ext];}else if(videos[ext]&&features.includes('video')){kind='video';mime=videos[ext];}else throw Error('Dieser Dateityp ist für das gewählte Profil nicht verfügbar.');if(!f.size||f.size>(kind==='document'?16:32)*1024**2)throw Error('Datei leer oder über dem Größenlimit.');const url=`data:${mime};base64,${await read(f)}`;let part=kind==='image'?{type:'image_url',image_url:{url}}:kind==='video'?{type:'video_url',video_url:{url},fps:2,max_frames:128}:{type:'file',file:{filename:f.name,file_data:url}};if(kind==='document'&&ext==='pdf'&&el('chat-pages').value.trim())part.file.pages=el('chat-pages').value.trim();loaded.push({name:f.name,size:f.size,part});}
|
||||
if(version===epoch&&root.isConnected){attachments.push(...loaded);pendingFiles();notice('Dateien angehängt; sie werden erst mit Senden übertragen.');}
|
||||
}catch(error){notice(error.message);}finally{el('chat-files').value='';filePending=false;selection();}};
|
||||
el('chat-test-form').onsubmit=async event=>{event.preventDefault();if(pending||filePending||status?.job?.state==='running')return;pending=true;selection();const text=el('chat-prompt').value.trim();try{const content=attachments.length?[{type:'text',text},...attachments.map(a=>a.part)]:text,next=[...messages,{role:'user',content}],body={profile_id:el('chat-profile').value,messages:next,max_tokens:Number(el('chat-limit').value),session_id:session};if(el('chat-effort').value)body.reasoning_effort=el('chat-effort').value;if(el('chat-logprobs').checked){body.logprobs=true;body.top_logprobs=5;}const job=await api('chat-tests/start',body);messages=next;historyBytes+=attachments.reduce((n,a)=>n+a.size,0);turns.push({role:'user',content:text,files:attachments.map(a=>a.name)});attachments=[];pendingFiles();ownJob=job.id;finished=null;status={...status,job};el('chat-prompt').value='';transcript();notice('Test gestartet. Speicherprüfung, Modellstart und Antwort erscheinen unter Diagnose.');}catch(error){notice(error.message);}finally{pending=false;selection();}};
|
||||
el('chat-answer-now').onclick=async()=>{controlPending=true;selection();try{await api('chat-tests/answer-now',{job_id:ownJob});notice('Denken beenden angefordert; die Antwort läuft im selben Test weiter.');}catch(error){notice(error.message);}finally{controlPending=false;selection();}};
|
||||
el('chat-cancel').onclick=async()=>{try{await api('chat-tests/cancel',{job_id:ownJob});notice('Abbruch dieses Tests angefordert.');}catch(error){notice(error.message);}};
|
||||
el('chat-unload').onclick=async()=>{try{await api('chat-tests/unload',{});notice('Eigener Modellprozess entladen.');}catch(error){notice(error.message);}};
|
||||
refresh();
|
||||
}
|
||||
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
"""Ephemeral, principal-scoped chat controls. Never stores prompts or tokens."""
|
||||
from collections import OrderedDict
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
SESSION_HEADERS=('x-llm-flow-id','x-claude-code-session-id','x-session-id','x-session-affinity')
|
||||
|
||||
|
||||
class ControlError(ValueError):
|
||||
def __init__(self,message,status=400,code='invalid_request_error'):
|
||||
super().__init__(message);self.status=status;self.code=code
|
||||
|
||||
|
||||
def identifier(value,label='Kennung'):
|
||||
if not isinstance(value,str) or not 1<=len(value)<=256 or value!=value.strip() or any(ord(c)<33 or ord(c)>126 for c in value):raise ControlError(label+' muss 1–256 druckbare ASCII-Zeichen ohne Leerzeichen enthalten.')
|
||||
return value
|
||||
|
||||
|
||||
def session_id(headers,body=None):
|
||||
for key in SESSION_HEADERS:
|
||||
value=headers.get(key)
|
||||
if value is not None:return identifier(value,'Sitzungskennung')
|
||||
value=(body or {}).get('session_id')
|
||||
return identifier(value,'Sitzungskennung') if value is not None else None
|
||||
|
||||
|
||||
def thinking(body):
|
||||
return body.get('reasoning_effort')!='none' and (body.get('chat_template_kwargs') or {}).get('enable_thinking') is not False
|
||||
|
||||
|
||||
def immediate_answer(body):
|
||||
"""A Deck-queued request has no native running thought to close yet."""
|
||||
result=dict(body);result['reasoning_effort']='none';result['chat_template_kwargs']={**body.get('chat_template_kwargs',{}),'enable_thinking':False};result.pop('reasoning_budget_tokens',None)
|
||||
return result
|
||||
|
||||
|
||||
class ChatControls:
|
||||
def __init__(self,maximum=1024,ttl=600,clock=time.monotonic):
|
||||
self.lock=threading.RLock();self.records=OrderedDict();self.maximum=maximum;self.ttl=ttl;self.clock=clock;self.secret=secrets.token_bytes(32)
|
||||
def digest(self,owner,value):
|
||||
return hmac.new(self.secret,(owner+'\0'+value).encode(),hashlib.sha256).hexdigest()
|
||||
def scope_session(self,owner,value):
|
||||
return 'deck-session-'+self.digest(owner,identifier(value,'Sitzungskennung')) if value is not None else None
|
||||
def prune(self):
|
||||
now=self.clock()
|
||||
for key,r in list(self.records.items()):
|
||||
if r['state']=='finished' and now-r['updated']>self.ttl:del self.records[key]
|
||||
while len(self.records)>=self.maximum:
|
||||
key=next((k for k,v in self.records.items() if v['state']=='finished'),None)
|
||||
if key is None:break
|
||||
del self.records[key]
|
||||
def begin(self,owner,profile,client_id=None,session=None,can_think=True,supported=False):
|
||||
if client_id is not None:identifier(client_id,'Client-Anfragekennung')
|
||||
scoped=self.scope_session(owner,session)
|
||||
with self.lock:
|
||||
self.prune()
|
||||
if len(self.records)>=self.maximum:raise ControlError('Zu viele laufende Chat-Steuerungen.',429,'control_capacity')
|
||||
alias=self.digest(owner,client_id) if client_id else None
|
||||
if alias and any(r['owner']==owner and alias in r['aliases'] and r['state']!='finished' for r in self.records.values()):raise ControlError('Client-Anfragekennung ist bereits aktiv.',409,'duplicate_request_id')
|
||||
key='deckreq_'+uuid.uuid4().hex
|
||||
self.records[key]={'id':key,'owner':owner,'profile_id':profile['id'],'revision':profile.get('revision'),'session':scoped,'aliases':{self.digest(owner,key)}|({alias} if alias else set()),'state':'queued','updated':self.clock(),'thinking':bool(can_think),'supported':bool(supported),'requested':False,'generation':None,'public_id':key}
|
||||
return key
|
||||
def headers(self,key):
|
||||
with self.lock:
|
||||
r=self.records[key];return {'X-Client-Request-Id':key,**({'x-session-id':r['session']} if r['session'] else {})}
|
||||
def activate(self,key,generation):
|
||||
with self.lock:
|
||||
r=self.records[key];r.update(generation=generation,state='answering' if r['requested'] else 'running',updated=self.clock());return r['requested']
|
||||
def dispatch(self,key,generation):
|
||||
with self.lock:
|
||||
r=self.records[key];r.update(generation=generation,state='dispatching',updated=self.clock());return r['requested']
|
||||
def bind(self,key,value):
|
||||
value=identifier(value,'Backend-Anfragekennung')
|
||||
with self.lock:
|
||||
r=self.records[key];r['aliases'].add(self.digest(r['owner'],value));r['public_id']=value
|
||||
def started(self,key,generation,send):
|
||||
if not self.activate(key,generation):return
|
||||
with self.lock:target={k:self.records[key][k] for k in ('id','profile_id','revision','generation','public_id')}
|
||||
try:send(target)
|
||||
except ControlError as exc:
|
||||
# A queued request sent with thinking off, or already answering, met the goal.
|
||||
if exc.status!=409 or exc.code!='not_thinking':raise
|
||||
def answering(self,key):
|
||||
with self.lock:
|
||||
r=self.records[key]
|
||||
if r['state']!='finished':r.update(state='answering',updated=self.clock())
|
||||
def finish(self,key):
|
||||
with self.lock:
|
||||
if key in self.records:self.records[key].update(state='finished',generation=None,updated=self.clock())
|
||||
def view(self,key):
|
||||
with self.lock:
|
||||
r=self.records[key];return {'request_id':r['public_id'],'state':r['state'],'can_answer_now':bool(r['supported'] and r['thinking'] and not r['requested'] and r['state'] not in ('finished','answering')),'answer_now_requested':r['requested']}
|
||||
def request(self,owner,data,headers,send):
|
||||
if not isinstance(data,dict) or set(data)-{'request_id','session_id'}:raise ControlError('request_id oder session_id erforderlich.')
|
||||
if data.get('request_id') is not None and data.get('session_id') is not None:raise ControlError('Genau eine Anfrage- oder Sitzungskennung angeben.')
|
||||
target=data.get('request_id');session=session_id(headers,data) if target is None else None
|
||||
if target is None and session is None:raise ControlError('Anfrage- oder Sitzungskennung fehlt.',400,'no_target')
|
||||
alias=self.digest(owner,identifier(target,'Anfragekennung')) if target is not None else None
|
||||
scoped=self.scope_session(owner,session)
|
||||
with self.lock:
|
||||
self.prune();matches=[r for r in self.records.values() if r['owner']==owner and (alias in r['aliases'] if alias else r['session']==scoped)]
|
||||
if not matches:raise ControlError('Anfrage oder Sitzung unbekannt.',404,'unknown_request' if alias else 'unknown_session')
|
||||
r=matches[-1]
|
||||
if not r['supported']:raise ControlError('Der Anfrage-Backend unterstützt Jetzt antworten nicht.',501,'answer_now_unavailable')
|
||||
if not r['thinking'] or r['state'] in ('finished','answering') or r['requested']:raise ControlError('Diese Anfrage denkt nicht mehr oder wurde bereits umgeschaltet.',409,'not_thinking')
|
||||
if r['state'] in ('queued','dispatching'):
|
||||
r.update(requested=True,updated=self.clock());return {'object':'answer_now','request_id':r['public_id'],'state':'queued'}
|
||||
selected={k:r[k] for k in ('id','profile_id','revision','generation','public_id')}
|
||||
# No registry lock, lease, ensure/load or prompt data while talking to a worker.
|
||||
result=send(selected)
|
||||
if not isinstance(result,dict) or result.get('state') not in ('thinking','queued','prompt'):raise ControlError('Ungültige Antwort der Backend-Steuerung.',502,'upstream_control_error')
|
||||
with self.lock:
|
||||
r=self.records.get(selected['id'])
|
||||
if r is not None:r.update(requested=True,updated=self.clock())
|
||||
return {'object':'answer_now','request_id':selected['public_id'],'state':result['state']}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
"""Bounded inline chat media; no filesystem paths, remote fetches or model work."""
|
||||
import base64
|
||||
import binascii
|
||||
from copy import deepcopy
|
||||
import io
|
||||
import math
|
||||
from pathlib import PurePosixPath
|
||||
import re
|
||||
import stat
|
||||
import zipfile
|
||||
|
||||
MIB=1024**2
|
||||
LIMITS=dict(request_bytes=64*MIB,attachment_bytes=32*MIB,document_bytes=16*MIB,video_bytes=32*MIB,attachments=8,document_pages=600,video_frames=128,video_fps=2)
|
||||
DOCUMENTS={'.pdf':'application/pdf','.docx':'application/vnd.openxmlformats-officedocument.wordprocessingml.document','.pptx':'application/vnd.openxmlformats-officedocument.presentationml.presentation','.xlsx':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','.txt':'text/plain','.md':'text/markdown','.csv':'text/csv','.json':'application/json','.yaml':'application/yaml','.yml':'application/yaml','.xml':'application/xml'}
|
||||
VIDEO_TYPES={'video/mp4','video/webm','video/quicktime','video/x-matroska'}
|
||||
IMAGE_TYPES={'image/png','image/jpeg','image/webp'}
|
||||
|
||||
|
||||
class MediaError(ValueError):
|
||||
def __init__(self,message,status=400,code='invalid_media'):
|
||||
super().__init__(message);self.status=status;self.code=code
|
||||
|
||||
|
||||
def profile_capabilities(worker,profile):
|
||||
"""Configuration/installed vs loaded are explicit; never ensure/load here."""
|
||||
fn=getattr(type(worker),'capabilities',None)
|
||||
value=fn(worker,profile) if callable(fn) else {}
|
||||
if not isinstance(value,dict):value={}
|
||||
return {**value,'runtime':profile.get('parameters',{}).get('chat_runtime','llama'),'limits':dict(LIMITS),'available':list(value.get('available',[])),'capabilities':list(value.get('capabilities',[]))}
|
||||
|
||||
|
||||
def pages(value):
|
||||
if not isinstance(value,str) or len(value)>256 or not re.fullmatch(r'[0-9,-]+',value):raise MediaError('PDF-Seiten als Bereiche wie 1-5,8 angeben.')
|
||||
selected=set()
|
||||
for token in value.split(','):
|
||||
fields=token.split('-')
|
||||
if not 1<=len(fields)<=2 or any(not x for x in fields):raise MediaError('Ungültiger PDF-Seitenbereich.')
|
||||
first=int(fields[0]);last=int(fields[-1])
|
||||
if not 1<=first<=last<=LIMITS['document_pages']:raise MediaError('PDF-Seiten müssen zwischen 1 und 600 liegen.')
|
||||
selected.update(range(first,last+1))
|
||||
return value
|
||||
|
||||
|
||||
def inline(value,types,maximum):
|
||||
if not isinstance(value,str):raise MediaError('Eingebettete Datei als Base64-Daten-URL erforderlich.')
|
||||
match=re.match(r'^data:([^;,]+);base64,',value)
|
||||
if not match or match[1].lower() not in types:raise MediaError('Nur unterstützte eingebettete Dateien; keine Pfade, Datei-IDs oder externen URLs.')
|
||||
data=value[match.end():]
|
||||
if len(data)>4*((maximum+2)//3):raise MediaError('Eingebettete Datei überschreitet das Größenlimit.',413,'media_too_large')
|
||||
try:raw=base64.b64decode(data,validate=True)
|
||||
except (ValueError,binascii.Error):raise MediaError('Ungültige Base64-Dateikodierung.') from None
|
||||
if not raw or len(raw)>maximum:raise MediaError('Datei leer oder zu groß.',413,'media_too_large')
|
||||
return match[1].lower(),raw
|
||||
|
||||
|
||||
def filename(value):
|
||||
if not isinstance(value,str) or not 1<=len(value)<=160 or value in ('.','..') or any(ord(c)<32 or ord(c)==127 for c in value) or '/' in value or '\\' in value or PurePosixPath(value).name!=value:raise MediaError('Ein einfacher Dateiname ohne Pfad ist erforderlich.')
|
||||
suffix=PurePosixPath(value).suffix.lower()
|
||||
if suffix not in DOCUMENTS:raise MediaError('Unterstützt werden PDF, DOCX, PPTX, XLSX und UTF-8-Textdateien.')
|
||||
return suffix
|
||||
|
||||
|
||||
def office(raw,suffix):
|
||||
"""Inspect bounded ZIP metadata only, never extract a client archive."""
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
|
||||
members=archive.infolist();total=0
|
||||
if len(members)>2048:raise MediaError('Office-Datei enthält zu viele Archiveinträge.')
|
||||
for entry in members:
|
||||
path=PurePosixPath(entry.filename)
|
||||
if path.is_absolute() or '..' in path.parts or '\\' in entry.filename or entry.flag_bits&1 or stat.S_ISLNK(entry.external_attr>>16):raise MediaError('Unsicherer oder verschlüsselter Office-Archiveintrag.')
|
||||
total+=entry.file_size
|
||||
if entry.file_size>16*MIB or total>64*MIB:raise MediaError('Entpacktes Office-Dokument überschreitet das Sicherheitslimit.',413,'media_too_large')
|
||||
required={'.docx':'word/document.xml','.pptx':'ppt/presentation.xml','.xlsx':'xl/workbook.xml'}[suffix]
|
||||
if required not in archive.namelist() or '[Content_Types].xml' not in archive.namelist():raise MediaError('Datei ist kein passendes Office-Open-XML-Dokument.')
|
||||
except zipfile.BadZipFile:raise MediaError('Office-Datei ist kein gültiges ZIP-Dokument.') from None
|
||||
|
||||
|
||||
def validate_messages(messages,profile,features=()):
|
||||
"""Validate in place without changing payload; count all history attachments."""
|
||||
if not isinstance(messages,list) or not messages or any(not isinstance(m,dict) for m in messages):raise MediaError('messages muss eine nichtleere Liste sein.')
|
||||
available=set(features);vision=bool(profile.get('parameters',{}).get('vision_projector'));count=total=0
|
||||
for message in messages:
|
||||
content=message.get('content')
|
||||
if not isinstance(content,list):continue
|
||||
for part in content:
|
||||
if not isinstance(part,dict):raise MediaError('Ungültiger Nachrichteninhalt.')
|
||||
kind=part.get('type')
|
||||
if kind=='text':
|
||||
if set(part)!={'type','text'} or not isinstance(part.get('text'),str):raise MediaError('Textteile benötigen ausschließlich type und text.')
|
||||
continue
|
||||
if message.get('role') in ('system','developer','assistant'):raise MediaError('Anhänge sind nur in Nutzer- oder Werkzeugnachrichten erlaubt.')
|
||||
count+=1
|
||||
if count>LIMITS['attachments']:raise MediaError('Höchstens acht Anhänge im gesamten Chatverlauf.')
|
||||
if kind=='image_url':
|
||||
if not vision:raise MediaError('Für Bilder einen Vision-Projektor im Profil aktivieren.')
|
||||
obj=part.get('image_url')
|
||||
if set(part)!={'type','image_url'} or not isinstance(obj,dict) or set(obj)-{'url','detail'} or obj.get('detail','auto') not in ('auto','low','high'):raise MediaError('Ungültiger Bildteil.')
|
||||
_,raw=inline(obj.get('url'),IMAGE_TYPES,LIMITS['attachment_bytes'])
|
||||
elif kind=='file':
|
||||
if 'documents' not in available:raise MediaError('Dokumente benötigen eine installierte dokumentfähige Basalt-Laufzeit.',501,'documents_unavailable')
|
||||
obj=part.get('file')
|
||||
if set(part)!={'type','file'} or not isinstance(obj,dict) or set(obj)-{'filename','file_data','pages'} or not {'filename','file_data'}<=set(obj):raise MediaError('Dateiteile benötigen filename und file_data; keine Datei-IDs oder URLs.')
|
||||
suffix=filename(obj['filename']);mime,raw=inline(obj['file_data'],{DOCUMENTS[suffix]},LIMITS['document_bytes'])
|
||||
if suffix=='.pdf':
|
||||
if b'%PDF-' not in raw[:1024]:raise MediaError('PDF-Kennung fehlt.')
|
||||
if 'pages' in obj:pages(obj['pages'])
|
||||
else:
|
||||
if 'pages' in obj:raise MediaError('Seitenauswahl wird nur für PDFs unterstützt.')
|
||||
if suffix in ('.docx','.pptx','.xlsx'):office(raw,suffix)
|
||||
else:
|
||||
try:raw.decode('utf-8')
|
||||
except UnicodeError:raise MediaError('Textdateien müssen UTF-8-kodiert sein.') from None
|
||||
elif kind in ('video_url','input_video'):
|
||||
if 'video' not in available or not vision:raise MediaError('Video benötigt Basalt-Videounterstützung, FFmpeg und einen Vision-Projektor.',501,'video_unavailable')
|
||||
obj=part.get(kind)
|
||||
if set(part)-{'type',kind,'fps','max_frames'} or not isinstance(obj,dict) or set(obj)!={'url'}:raise MediaError('Ungültiger Videoteil; nur eingebettetes Video und begrenzte Abtastung.')
|
||||
_,raw=inline(obj.get('url'),VIDEO_TYPES,LIMITS['video_bytes'])
|
||||
fps=part.get('fps',LIMITS['video_fps']);frames=part.get('max_frames',LIMITS['video_frames'])
|
||||
if type(fps) not in (int,float) or not math.isfinite(fps) or not 0<fps<=LIMITS['video_fps'] or type(frames) is not int or not 4<=frames<=LIMITS['video_frames']:raise MediaError('Video-Abtastung: höchstens 2 Bilder/s und 4–128 Frames.')
|
||||
else:raise MediaError('Nicht unterstützter Nachrichteninhalt.')
|
||||
total+=len(raw)
|
||||
if total>LIMITS['attachment_bytes']:raise MediaError('Anhänge des gesamten Verlaufs überschreiten 32 MiB.',413,'media_too_large')
|
||||
return {'attachments':count,'attachment_bytes':total}
|
||||
|
||||
|
||||
def normalize_messages(messages,profile,features=()):
|
||||
"""Preserve the caller while imposing the same bounded defaults upstream."""
|
||||
result=deepcopy(messages);info=validate_messages(result,profile,features)
|
||||
for message in result:
|
||||
if not isinstance(message.get('content'),list):continue
|
||||
for part in message['content']:
|
||||
if part.get('type') in ('video_url','input_video'):
|
||||
part.setdefault('fps',LIMITS['video_fps']);part.setdefault('max_frames',LIMITS['video_frames'])
|
||||
return result,info
|
||||
+62
-16
@@ -5,37 +5,68 @@ import socket
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any
|
||||
from inference import InferenceError
|
||||
from profiles import generation_parameters
|
||||
from api_compat import apply_reasoning_budget
|
||||
from api_compat import normalize_chat,CompatibilityError
|
||||
from chat_media import normalize_messages,profile_capabilities
|
||||
from chat_control import ChatControls,ControlError,thinking,immediate_answer
|
||||
|
||||
class ChatTests:
|
||||
def __init__(self,profiles,worker,scheduler):
|
||||
self.profiles=profiles;self.worker=worker;self.scheduler=scheduler
|
||||
self.lock=threading.RLock();self.job=None;self.cancel=threading.Event();self.socket=None
|
||||
self.lock=threading.RLock();self.job:dict[str,Any]={};self.cancel=threading.Event();self.socket=None
|
||||
self.controls=ChatControls();self.owner='admin-test-'+uuid.uuid4().hex;self.ticket=None
|
||||
def status(self):
|
||||
with self.lock:job=dict(self.job) if self.job else None
|
||||
with self.lock:job=dict(self.job) if self.job else None;ticket=self.ticket
|
||||
if job and ticket:
|
||||
view=self.controls.view(ticket);job.update({k:v for k,v in view.items() if k!='state'});job['request_state']=view['state']
|
||||
return dict(job=job,worker=self.worker.status(),scheduler=self.scheduler.status())
|
||||
def capabilities(self,profile_id):
|
||||
p=next((p for p in self.profiles.status()['profiles'] if p['id']==profile_id and p['kind']=='chat'),None)
|
||||
if not p:raise ValueError('Chatprofil nicht gefunden.')
|
||||
return profile_capabilities(self.worker,p)
|
||||
def answer_now(self,data):
|
||||
if not isinstance(data,dict) or set(data)!={'job_id'}:raise ControlError('Aktuelle Testauftragskennung erforderlich.')
|
||||
with self.lock:
|
||||
if not self.job or self.job['id']!=data['job_id'] or self.job['state']!='running' or not self.ticket:raise ControlError('Dieser Chat-Test läuft nicht mehr.',409,'not_thinking')
|
||||
ticket=self.ticket
|
||||
method=getattr(type(self.worker),'answer_now',None)
|
||||
def send(target):
|
||||
if not callable(method):raise ControlError('Jetzt antworten nicht verfügbar.',501,'answer_now_unavailable')
|
||||
return method(self.worker,target)
|
||||
return self.controls.request(self.owner,{'request_id':ticket},{},send)
|
||||
def start(self,data):
|
||||
if set(data)!={'profile_id','messages','max_tokens'}:raise ValueError('Profil, Nachrichten und Antwortlimit erforderlich.')
|
||||
required={'profile_id','messages','max_tokens'}
|
||||
if not isinstance(data,dict) or not required<=set(data) or set(data)-required-{'session_id','reasoning_effort','logprobs','top_logprobs'}:raise ValueError('Profil, Nachrichten und Antwortlimit erforderlich; unbekannte Testoption.')
|
||||
messages=data['messages'];limit=data['max_tokens']
|
||||
if type(limit)!=int or not 1<=limit<=4096:raise ValueError('Antwortlimit: 1–4096 Token.')
|
||||
if not isinstance(messages,list) or not 1<=len(messages)<=32:raise ValueError('1–32 Textnachrichten erforderlich.')
|
||||
if not isinstance(messages,list) or not 1<=len(messages)<=32:raise ValueError('1–32 Nachrichten erforderlich.')
|
||||
for m in messages:
|
||||
if not isinstance(m,dict) or set(m)!={'role','content'} or m['role'] not in ('user','assistant','system') or not isinstance(m['content'],str) or not m['content'].strip():raise ValueError('Nur Textnachrichten mit Rolle user, assistant oder system unterstützt.')
|
||||
if sum(len(m['content']) for m in messages)>24000:raise ValueError('Testverlauf zu lang (maximal 24.000 Zeichen). Neuen Chat beginnen.')
|
||||
if not isinstance(m,dict) or set(m)!={'role','content'} or m['role'] not in ('user','assistant','system') or not isinstance(m['content'],(str,list)) or not m['content']:raise ValueError('Nachrichten mit Rolle user, assistant oder system und nichtleerem Inhalt erforderlich.')
|
||||
if isinstance(m['content'],str) and not m['content'].strip():raise ValueError('Leere Textnachricht.')
|
||||
length=sum(len(m['content']) if isinstance(m['content'],str) else sum(len(p.get('text','')) for p in m['content'] if isinstance(p,dict) and p.get('type')=='text' and isinstance(p.get('text'),str)) for m in messages)
|
||||
if length>24000:raise ValueError('Testtext zu lang (maximal 24.000 Zeichen, Anhänge separat begrenzt). Neuen Chat beginnen.')
|
||||
profile=next((p for p in self.profiles.status()['profiles'] if p['id']==data['profile_id'] and p['kind']=='chat'),None)
|
||||
if not profile or not profile['runnable']:raise ValueError('Kein ausführbares Chatprofil. Modell und CUDA-Build prüfen.')
|
||||
caps=profile_capabilities(self.worker,profile);messages,_=normalize_messages(messages,profile,caps['available'])
|
||||
body=dict(model=profile.get('api_id',profile['name']),messages=messages,max_tokens=limit,stream=True,stream_options={'include_usage':True},**generation_parameters(profile['parameters']))
|
||||
body.update({k:data[k] for k in ('session_id','reasoning_effort','logprobs','top_logprobs') if k in data})
|
||||
try:body,_=normalize_chat(body);body=apply_reasoning_budget(body,{**profile['parameters'],'reasoning_budget':self.profiles.reasoning_budget()})
|
||||
except CompatibilityError as exc:raise ValueError(str(exc)) from None
|
||||
with self.lock:
|
||||
if self.job and self.job['state']=='running':raise ValueError('Ein Chat-Test läuft bereits.')
|
||||
self.cancel.clear();self.job=dict(id=uuid.uuid4().hex,state='running',phase='Wartet auf freie Modellreservierung',profile_id=profile['id'],profile_name=profile['name'],started_at=time.time(),answer='',reasoning='',error=None,timings={},usage={})
|
||||
threading.Thread(target=self._run,args=(profile,messages,limit),daemon=True).start()
|
||||
ticket=self.controls.begin(self.owner,profile,session=body.pop('session_id',None),can_think=thinking(body),supported='answer_now' in caps['available']);self.ticket=ticket
|
||||
self.cancel.clear();self.job=dict(id=uuid.uuid4().hex,state='running',phase='Wartet auf freie Modellreservierung',profile_id=profile['id'],profile_name=profile['name'],started_at=time.time(),answer='',reasoning='',error=None,timings={},usage={},logprobs=[])
|
||||
threading.Thread(target=self._run,args=(profile,body,ticket,caps),daemon=True).start()
|
||||
return dict(self.job)
|
||||
def phase(self,text):
|
||||
with self.lock:self.job['phase']=text
|
||||
def stop(self):
|
||||
self.cancel.set()
|
||||
with self.lock:sock=self.socket
|
||||
def stop(self,job_id=None):
|
||||
with self.lock:
|
||||
if job_id is not None and (not self.job or self.job['id']!=job_id or self.job['state']!='running'):raise ControlError('Dieser Chat-Test läuft nicht mehr.',409,'job_changed')
|
||||
self.cancel.set();sock=self.socket
|
||||
if sock:
|
||||
try:sock.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:pass
|
||||
@@ -43,7 +74,7 @@ class ChatTests:
|
||||
def unload(self):
|
||||
if not self.scheduler.unload_idle():raise ValueError('Es laufen noch Anfragen. Erst deren Ende abwarten; andere Antworten werden nicht abgebrochen.')
|
||||
return self.status()
|
||||
def _run(self,profile,messages,limit):
|
||||
def _run(self,profile,body,ticket,caps):
|
||||
conn=None;outcome='failed';message='Chat-Test fehlgeschlagen.';error=None
|
||||
try:
|
||||
key=('chat',profile['id'],profile['revision'])
|
||||
@@ -54,16 +85,27 @@ class ChatTests:
|
||||
with self.scheduler.lease(key,profile['parameters']['slots'],prepare,allowed=allowed):
|
||||
if self.cancel.is_set():raise InterruptedError()
|
||||
self.phase('Antwort wird erzeugt')
|
||||
body=dict(model=profile['name'],messages=messages,max_tokens=limit,stream=True,stream_options={"include_usage":True},**generation_parameters(profile['parameters']))
|
||||
body=apply_reasoning_budget(body,{**profile['parameters'],'reasoning_budget':self.profiles.reasoning_budget()})
|
||||
generation=self.worker.status().get('generation')
|
||||
if self.controls.dispatch(ticket,generation):body=immediate_answer(body)
|
||||
body=self.worker.prepare_request(body) if callable(getattr(type(self.worker),'prepare_request',None)) else body
|
||||
headers={'Content-Type':'application/json'}
|
||||
if caps.get('session_affinity'):headers.update(self.controls.headers(ticket))
|
||||
elif profile['parameters'].get('chat_runtime')=='basalt':headers['X-Client-Request-Id']=ticket
|
||||
if headers.get('x-session-id'):body['session_id']=headers['x-session-id']
|
||||
conn,token=self.worker.connect()
|
||||
conn.request('POST','/v1/chat/completions',json.dumps(body).encode(),headers={'Content-Type':'application/json','Authorization':'Bearer '+token})
|
||||
conn.request('POST','/v1/chat/completions',json.dumps(body).encode(),headers={**headers,'Authorization':'Bearer '+token})
|
||||
with self.lock:self.socket=conn.sock
|
||||
if self.cancel.is_set():raise InterruptedError()
|
||||
response=conn.getresponse()
|
||||
if response.status!=200:
|
||||
raise InferenceError('llama.cpp hat den Test abgelehnt. Kontextbudget, Nachrichtenlänge und Profilparameter prüfen.')
|
||||
raise InferenceError('Das Modell-Backend hat den Test abgelehnt. Kontextbudget, Medien und Profilparameter prüfen.')
|
||||
native=getattr(response,'getheader',lambda _:None)('X-Request-Id')
|
||||
if isinstance(native,str) and native:self.controls.bind(ticket,native)
|
||||
method=getattr(type(self.worker),'answer_now',None)
|
||||
def send(target):
|
||||
if not callable(method):raise ControlError('Jetzt antworten nicht verfügbar.',501,'answer_now_unavailable')
|
||||
return method(self.worker,target)
|
||||
self.controls.started(ticket,generation,send)
|
||||
buffer=b'';total=0;done=False;deadline=time.monotonic()+600
|
||||
while time.monotonic()<deadline:
|
||||
if self.cancel.is_set():raise InterruptedError()
|
||||
@@ -85,10 +127,13 @@ class ChatTests:
|
||||
self.job[section]={k:v for k,v in values.items() if k in fields and type(v) in (int,float) and math.isfinite(v) and v>=0}
|
||||
for choice in event.get('choices',[]):
|
||||
delta=choice.get('delta',{})
|
||||
if delta.get('content'):self.controls.answering(ticket)
|
||||
with self.lock:
|
||||
for source,target in [('content','answer'),('reasoning_content','reasoning')]:
|
||||
if isinstance(delta.get(source),str):self.job[target]+=delta[source]
|
||||
if choice.get('finish_reason'):self.job['finish_reason']=choice['finish_reason']
|
||||
logprobs=choice.get('logprobs')
|
||||
if body.get('logprobs') and isinstance(logprobs,dict) and isinstance(logprobs.get('content'),list):self.job['logprobs']=(self.job['logprobs']+logprobs['content'])[-512:]
|
||||
if done:break
|
||||
if not done:raise InferenceError('Antwort unterbrochen oder Zeitlimit erreicht. '+(self.worker.status().get('error') or 'Ein GPU-OOM ist ohne eindeutigen Nachweis nicht bestätigt.'))
|
||||
outcome='complete';message='Antwort fertig · Modell bleibt für weitere Anfragen geladen'
|
||||
@@ -98,4 +143,5 @@ class ChatTests:
|
||||
outcome='cancelled' if cancelled else 'failed';error=None if cancelled else message
|
||||
finally:
|
||||
if conn:conn.close()
|
||||
self.controls.finish(ticket)
|
||||
with self.lock:self.socket=None;self.job.update(state=outcome,error=error,phase=message,finished_at=time.time())
|
||||
+134
-30
@@ -2,11 +2,85 @@
|
||||
|
||||
## Umfang und Abnahmestand
|
||||
|
||||
### Rezept 0.3.3: gebauter Kandidat, keine Produktionsaktivierung
|
||||
|
||||
Das aktuelle Git-Rezept pinnt **Basalt0.3.3**. Modell-/Konfigurationsformat v2,
|
||||
bestehendes GSQ-RCO-IQ3_XXS-Modell, Expertenprofil und 1024-MiB-Konversationscache
|
||||
bleiben erhalten. Kein erneuter Gewichtedownload, keine Neuquantisierung und
|
||||
keine Übernahme einer Vier-Slot-Herstellerbenchmark-Konfiguration.
|
||||
|
||||
Deck reicht begrenzte eingebettete Dokumente/Videos über Chat Completions und
|
||||
die optionale Responses-Kompatibilität durch. `/props?model=API_ID` trennt
|
||||
installierte Möglichkeiten von tatsächlich geladenen Backendfähigkeiten;
|
||||
`/v1/capabilities` beschreibt den Routervertrag. Token-Logprobs werden auf
|
||||
Anforderung weitergereicht, bei Responses einschließlich der Basalt-Erweiterungen
|
||||
für Denken und Werkzeugaufrufe. Sie sind kein Wahrheitsnachweis.
|
||||
|
||||
`POST /v1/answer_now` steuert nur eine zum selben API-Bearer gehörende Anfrage
|
||||
oder Sitzung, ohne Workerstart, FIFO-Lease oder Modellwechsel. Zufällige interne
|
||||
Request-IDs und profil-/generationsgebundene Steuerung verhindern fremde Ziele;
|
||||
Sitzungskennungen werden pro Principal mit einem flüchtigen HMAC geschlüsselt.
|
||||
Vier zusätzliche HTTP-Steuerplätze halten den Pfad bei belegten Datenplätzen
|
||||
erreichbar. Metadaten bleiben begrenzt/flüchtig, ohne Prompts oder Zugangsdaten.
|
||||
Der Testchat bietet Anhänge, PDF-Seitenwahl, Denkstufe, optionale Logprobs und
|
||||
„Jetzt antworten“; Verwaltungsanmeldung und CSRF-Schutz bleiben erforderlich.
|
||||
|
||||
Auf Athena wurde nur ein eigener, CPU-/RAM-begrenzter Kandidat ohne GPU-Zugriff
|
||||
gebaut. Der laufende all-CPU-/Ein-Slot-Basalt0.3.0 wurde nicht ersetzt.
|
||||
Unabhängige Binär-/ABI-Prüfungen, CPU-Mock-, Browser- und Regressionsergebnisse
|
||||
sowie die ausdrücklich offenen Modell-/NVDEC-/Debian-Restore-Gates stehen im
|
||||
[0.3.3-Prüfstand](../docs/maintenance/basalt-033-staged-2026-11-13/README.md).
|
||||
|
||||
### Versionswechsel 0.3.0
|
||||
|
||||
Der frühere Wechsel auf Basalt0.3.0 führte Server-Konfiguration **v2** ein:
|
||||
globale Listener-/Sicherheitsoptionen unter `server`, genau ein von Deck
|
||||
ausgewähltes Modell unter `models`, Engine-Parameter unter `engine`.
|
||||
Deck bleibt für Profile, Warteschlange und Modellwechsel zuständig; Basalts
|
||||
neuer Mehrmodell-Router aktiviert keine weiteren Deck-Modelle selbstständig.
|
||||
Die numerische Telemetrie folgt dem vom Router angezeigten Service.
|
||||
Das Expertenprofil wird ausdrücklich per `--expert-profile` übergeben; auf den
|
||||
eingebetteten Kompilierpfad darf eine verlagerte Installation nicht vertrauen.
|
||||
Ohne Tuning-Pin gilt `source/data/profiles/qwen4exp-48x512.prof`. Das aktuelle
|
||||
Rezept registriert stattdessen öffentliche, revisions- und SHA-256-gepinnte
|
||||
Startprofil-Metadaten unter `basalt-runtime/profiles/`. `basalt_tuning.py` prüft
|
||||
Größe/Hash und verweigert abweichende vorhandene Dateien; der native Installer
|
||||
bezieht das kleine öffentliche Asset ohne Modellstart und ohne Vendor-Änderung.
|
||||
Fehlende/defekte gepinnte Metadaten verhindern die Laufzeitfreigabe.
|
||||
|
||||
Das aktuelle Rezept setzt zusätzlich 1024 MiB RAM-Konversationscache. Das ist
|
||||
keine Vollkontext-Parkgarantie. Ein kurzer Vergleich zeigte Wiederverwendung
|
||||
eines kleinen verdrängten Chats, aber keinen Decode-Gewinn der kombinierten
|
||||
Variante; die 0.3.3-Vorbereitung behauptet keinen neuen Geschwindigkeitsgewinn. CPU-/GPU-Zuteilung,
|
||||
Modellgewichte, Slots und 700-MiB-GPU-Reserve bleiben unverändert. Änderungen am
|
||||
Tuning-Rezept benötigen App-Aktivierung; Worker-Neuladen allein liest eine bereits
|
||||
importierte Rezeptkonstante nicht neu ein. Rückfall: nur den Profil-Pin entfernen
|
||||
für das ausgelieferte Upstream-Profil, Cache separat auf null setzen. Jede
|
||||
produktive Umstellung regulär drainieren und dieselben Audio-Profile herstellen.
|
||||
`image-remote-only=true` verhindert, dass externe Deck-Anfragen durch den
|
||||
Loopback-Proxy als Erlaubnis für lokale Bildpfade behandelt werden.
|
||||
|
||||
Neue Installationen laden das unten fest gepinnte öffentliche **Modellformat
|
||||
v2** direkt. Für vorhandenes v1 ist ausschließlich die mit dem festen
|
||||
Upstream-Commit ausgelieferte `tools/migrations/basalt_v1_to_v2.py` vorgesehen:
|
||||
lokal, ohne Download oder Neuquantisierung, mit vollständiger Ausgabedatei.
|
||||
Vorher freien Platz für Quelle **und** Ausgabe prüfen. Erst nach Vergleich
|
||||
der gesamten Ausgabe mit der unten genannten öffentlichen SHA-256 adoptieren;
|
||||
Katalog-ID aus neuer Quelle/Revision/Datei berechnen und Profilreferenzen
|
||||
konsistent umstellen. Kein eigenes In-place-Umschreiben des Live-Pakets.
|
||||
|
||||
Build, normale Management-Anmeldung, Drain einschließlich wartender Audiojobs,
|
||||
App-/Engine-Aktivierung und anschließende Modell-/Audioabnahme bleiben getrennte
|
||||
Schritte. Ein Neustart kann eine erneute Web-Anmeldung verlangen. Der konkrete
|
||||
Athena-Betriebsstand und seine tatsächlichen Prüfungen sind im
|
||||
[Systemstand](../docs/CURRENT_SYSTEM.md) abgegrenzt; ein frischer nativer Debian-Aufbau
|
||||
und vollständiger verschlüsselter Restore sind damit weiterhin nicht abgenommen.
|
||||
|
||||
### All-CPU-/Ein-Slot-Betrieb auf Athena · 9. November 2026
|
||||
|
||||
Die protokollierte Konfigurationsübernahme auf der bereits lokal aktualisierten
|
||||
Basalt0.3.0-Installation ändert weder Gewichte noch Image. Ihre Dokumentation
|
||||
ist vom noch separat lokalen Runtime-Update-Änderungssatz abgegrenzt; sie ist
|
||||
war vom damals separat lokalen Runtime-Update-Änderungssatz abgegrenzt; sie ist
|
||||
kein Gesamt-Release dieses Images. Nur `flash-next-basalt` verwendet einen Slot;
|
||||
Kontext262144 bleibt. CPU-Rolle `strata`, die auch Basalt nutzt, erhält alle
|
||||
verfügbaren SMT-Paare dieses Hosts (0–11), mit expliziter Schnittmenge zur
|
||||
@@ -57,14 +131,16 @@ Dual-Slot-/Queue-/Cache-/MTP-Abnahme produktiv bestätigt. Für Update/Rückfall
|
||||
App-Stand und Launcher zusammen umstellen, regulär drainieren und Modell neu
|
||||
laden. Keine Profile, Gewichtedateien, GPU-Aufteilung oder privaten Daten ändern.
|
||||
|
||||
Die Deck-Anbindung ist zunächst **text-only**, parallel zur vorhandenen
|
||||
Strata-/llama.cpp-Auswahl im Produkt, nicht gleichzeitig auf derselben GPU.
|
||||
Die Deck-Anbindung unterstützt Text und einen optionalen separaten Vision-
|
||||
Sidecar, parallel zur vorhandenen Strata-/llama.cpp-Auswahl im Produkt, nicht
|
||||
gleichzeitig mit einem anderen Textmodell auf derselben GPU.
|
||||
Sie ändert weder vorhandene Profile/API-Freigaben noch TTS, STT oder Projektoren.
|
||||
Ein Software-Checkout oder bestandener Offline-Test aktiviert kein Modell.
|
||||
Die produktive Aktivierung erfordert ein eigenes Go und einen nachgewiesenen
|
||||
Drain aktiver **und wartender** Aufträge. Fehlende Zähler bedeuten nicht Leerlauf.
|
||||
|
||||
Die Integration nutzt die bereits separat modellgetestete Basalt-Version.
|
||||
Die frühere0.3.0-Integration wurde separat modellgetestet; der aktuelle0.3.3-
|
||||
Kandidat wurde ausdrücklich noch nicht mit einem echten Modell gestartet.
|
||||
Die neue native Installationsroutine und die Deck-Worker-Anbindung wurden noch
|
||||
nicht zusammen auf einem frischen Debian mit echter Inferenz abgenommen.
|
||||
Auch eine vollständige verschlüsselte Fresh-Host-Wiederherstellung ist offen.
|
||||
@@ -75,15 +151,16 @@ Die frühere Kandidatenabnahme ist kein Ersatz dafür.
|
||||
Einzige Rezeptquelle im Code: `basalt_sources.json`.
|
||||
|
||||
- Upstream: <https://github.com/jesdga95/basalt.git>
|
||||
- Commit: `9175e7a3211bda355c02e804c7c107b15b8ea89f`, Version 0.1.0.
|
||||
- Commit: `2729e2288f59e01836ddd7fcc630810ada98995a`, Version 0.3.3.
|
||||
- CUDA Toolkit 13.0 aus `deploy/strata-cuda13.lock.json`, eigene Installation
|
||||
in der Basalt-Wurzel. Keine Abhängigkeit von Stratas Toolkit oder einer
|
||||
anderen Container-Python-Umgebung; kein Treiberupdate.
|
||||
- Native Architektur SM120; die RTX 3060/SM86 wird nicht unterstützt.
|
||||
- Textengine SM120; die RTX 3060/SM86 wird nicht für Text unterstützt.
|
||||
Der unabhängige Vision-Sidecar wird für SM86 und SM120 gebaut.
|
||||
- Öffentliches Modell: `jesdga/Qwen3.8-Flash-Next-Basalt`, feste Revision
|
||||
`c0e57437ea564aa85263ab0bc0ee83568dd53213`,
|
||||
`Qwen3.8-FN-GSQ-RCO-IQ3_XXS.basalt`, 79867643037 Bytes.
|
||||
- SHA-256: `d02bb1b188bbc9ed6bc88ce5e89c7c2d64247290c7bae70fbb9d9d17fe65ed71`.
|
||||
`21b8357546172bf19a685ccf3353e7da7aeadde0`,
|
||||
`Qwen3.8-FN-GSQ-RCO-IQ3_XXS.basalt`, 79865545428 Bytes.
|
||||
- SHA-256: `c20595c2dd1c444b465f916447b835c1f30189ba1286932427115dac7b365165`.
|
||||
Qwen Community License 1.0 vor Bezug/Nutzung prüfen. Nicht durch einen
|
||||
ähnlich benannten GGUF-Download oder ein neueres Hub-HEAD ersetzen.
|
||||
|
||||
@@ -98,6 +175,8 @@ Dienstkonto explizit vorhanden sein:
|
||||
Das Rezept verwendet CMake 3.31.6 und Ninja 1.11.1.4 in einer eigenen venv.
|
||||
Die Python-Serverabhängigkeiten sind im festen Upstream-Commit gepinnt;
|
||||
der tatsächlich aufgelöste Bestand wird als `python-lock.txt` gespeichert.
|
||||
Dazu gehört `pypdf==7.0.1`. Bilder/scannbare PDF-Seiten benötigen weiterhin
|
||||
den registrierten Vision-Projektor; Office-/Textauszug allein braucht ihn nicht.
|
||||
2. Passender NVIDIA-Treiber und `nvidia-smi`, Zugriff auf die ausgewählte
|
||||
SM120-GPU sowie die notwendigen `/dev/nvidia*`-Geräte. Treiberinstallation
|
||||
und eventueller Host-Neustart erfolgen nicht automatisch durch Basalt.
|
||||
@@ -111,6 +190,13 @@ Dienstkonto explizit vorhanden sein:
|
||||
5. Genügend Platz für eigenes Toolkit, Build, venv und das Modellpaket;
|
||||
der Modellkatalog behält zusätzlich 10 GiB freie Reserve. Der tatsächliche
|
||||
Spitzenbedarf des neuen nativen Gesamtbuilds ist noch nicht vermessen.
|
||||
6. Für Video zusammenpassende FFmpeg-Laufzeitbibliotheken: Major-ABIs
|
||||
`(avcodec,avformat,avutil,swscale)` = `(60,60,58,7)` für FFmpeg6,
|
||||
`(61,61,59,8)` für FFmpeg7 oder `(62,62,60,9)` für FFmpeg8.
|
||||
Das native Debian-Paket `ffmpeg` muss eine dieser Gruppen liefern; ein altes
|
||||
FFmpeg5 erfüllt die Videovoraussetzung nicht. Der Installer prüft die ABI
|
||||
ohne Decoder-/GPU-Arbeit und weist fehlende Videounterstützung separat aus.
|
||||
GPU-NVDEC und ein eventueller CPU-Fallback sind erst mit echtem Video zu prüfen.
|
||||
|
||||
Als Dienstkonto aus dem Checkout aufrufen, ohne Docker, sudo oder systemctl:
|
||||
|
||||
@@ -124,8 +210,9 @@ Toolkit-Pfad muss vor einer produktiven Nutzung einschließlich seiner
|
||||
Laufzeitbibliotheken dokumentiert werden; ein erfolgreiches Build allein
|
||||
qualifiziert keinen externen Bibliothekspfad für den Worker.
|
||||
|
||||
Der Build bindet keine GPU ein und startet kein Modell. Er baut nur `basalt`,
|
||||
prüft CLI-Hilfe und pip-Abhängigkeiten und schreibt erst danach `ready.json`.
|
||||
Der Build bindet keine GPU ein und startet kein Modell. Er baut `basalt` und
|
||||
den unabhängigen Vision-Sidecar, prüft CLI-Hilfe, pip-Abhängigkeiten, PDF-Modul
|
||||
und FFmpeg-ABI und schreibt erst danach `ready.json`.
|
||||
`source/`, `build/`, `venv/`, `cuda/`, `home/`, `tmp/` und `cache/` gehören der
|
||||
Basalt-Wurzel. Abbruch beendet nur die eigene Prozessgruppe.
|
||||
|
||||
@@ -136,16 +223,11 @@ Die feste Quelle, Größe und SHA-256 werden vor dem Einreihen geprüft; der
|
||||
Download prüft die gesamte Datei. Das Paket enthält Tokenizer und MTP und
|
||||
benötigt keine separate Strata-Paketvorbereitung oder GGUF-Shard-Zuordnung.
|
||||
|
||||
**Athena-spezifische Aktivierungssperre:** Der vorhandene getestete Kandidat
|
||||
liegt auf der Samsung 980 PRO unter
|
||||
`/opt/athena-deck-dev/basalt-candidate-9175e7a3211b/models/`.
|
||||
`/data` liegt dagegen auf der WD Blue SN580. Der Kandidat wird von dieser
|
||||
Codeänderung weder verschoben noch importiert, gelöscht oder erneut geladen.
|
||||
Vor der Aktivierung den tatsächlichen Modellkatalog-Mount prüfen und einen
|
||||
verwalteten Speicher-/Importweg auf der gewünschten Samsung ausdrücklich
|
||||
festlegen. Nicht stillschweigend einen zweiten Download auf `/data` starten
|
||||
oder den entfernbaren Kandidaten zu einer versteckten Dauerabhängigkeit machen.
|
||||
Die konkrete Übernahme des vorhandenen Pakets ist noch offen.
|
||||
**Athena:** Das vorhandene v2-Modell ist bereits im verwalteten Katalog des
|
||||
laufenden Basalt0.3.0 registriert. Dieses Update ersetzt weder seine Referenz
|
||||
noch Gewichtedateien. Vor einer späteren Aktivierung weiterhin tatsächliche
|
||||
Katalog-/Speichermounts prüfen und dieselbe Datei verwenden; keinen zweiten
|
||||
Download oder neue Abhängigkeit vom alten Experimentverzeichnis einführen.
|
||||
|
||||
## Bedienung, Betrieb und Ressourcen
|
||||
|
||||
@@ -154,7 +236,8 @@ Die konkrete Übernahme des vorhandenen Pakets ist noch offen.
|
||||
- **Chatprofil:** Laufzeit `basalt`, genau eine explizite SM120-GPU-UUID,
|
||||
ein oder zwei Slots, 512 bis 262144 Kontexttokens **pro Slot**.
|
||||
- GPU-Reserve automatisch 700 MiB, manuell mindestens 700 MiB. Kein
|
||||
Mehrkarten-Split, SSD/mmap-Modus oder Vision-Projektor in dieser Anbindung.
|
||||
Mehrkarten-Split oder SSD/mmap-Modus. Optionaler geprüfter BF16-Vision-Projektor
|
||||
auf einer explizit getrennten SM86/SM120-GPU; kein stiller GPU-/CPU-Fallback.
|
||||
llama.cpp-/Strata-Tuningfelder sind keine Basalt-Tuningregler.
|
||||
- Experten RAM-resident; KV int8; automatischer Expert-/Prefill-Cache; MTP
|
||||
gemäß Modellpaket. Keine ungeprüfte Übernahme von Strata-Batch-/MTP-Flags.
|
||||
@@ -168,14 +251,23 @@ Die konkrete Übernahme des vorhandenen Pakets ist noch offen.
|
||||
- Bereit erst nach bestätigtem geladenem Modell, tatsächlicher Slotzahl
|
||||
und Kontext pro Slot. Der Scheduler drainiert vor Laufzeitwechseln;
|
||||
eine Modellumschaltung ist keine Unterbrechung laufender Antworten.
|
||||
- Das Dashboard verwendet nur inhaltsfreie `/slots`-/`/props`-Metadaten.
|
||||
Basalts JSON-`/metrics` enthält Request-Historie und wird nicht eingesammelt.
|
||||
Kontinuierliche zentrale Live-/Summen-Tokenraten sind damit noch nicht
|
||||
angebunden; fehlende Werte werden nicht erfunden. Der bestehende Testchat
|
||||
kann weiter die tatsächlich gelieferten Antworttimings auswerten.
|
||||
- Das Dashboard verwendet inhaltsfreie `/slots`-/`/props`-Metadaten und den
|
||||
numerischen `/telemetry`-Wrapper für Live-/Summenraten. Basalts JSON-`/metrics`
|
||||
enthält Request-Historie und wird nicht eingesammelt. Fehlende Werte werden
|
||||
nicht erfunden; der Testchat nutzt zusätzlich gelieferte Antworttimings.
|
||||
|
||||
## Backup, Restore, Update und Rückfall
|
||||
|
||||
Neue App-Dateien `chat_media.py` und `chat_control.py` gehören zum Git-Checkout
|
||||
und zur Installer-Allowlist. Anhänge und Chatsteuerungen werden nicht als neue
|
||||
dauerhafte Nutzdaten gespeichert. Request-IDs, HMAC-Schlüssel, Warteschlangen,
|
||||
Browserverlauf und RAM-/VRAM-Caches werden bei Neustart/Restore nicht fortgesetzt.
|
||||
Die Limits gelten über den gesamten gesendeten Verlauf: JSON64MiB, Anhänge32MiB,
|
||||
höchstens8, Dokument16MiB, Video32MiB, PDF-Seitenauswahl1–600,
|
||||
Video maximal2Frames/s und128Frames. Externe URLs, Serverpfade und Datei-IDs
|
||||
sind ausgeschlossen. Vorhandene Reverse-Proxys müssen die erlaubte Uploadgröße
|
||||
und Streaming-Steuerverbindungen unterstützen; hier wird kein Proxy umgestellt.
|
||||
|
||||
Das verschlüsselte Konfigurationsbackup enthält Profile, Presets, API-IDs,
|
||||
Freigaben, Modellquelle/Größe/SHA und Basalt-Installationsabsicht mit Code-Pin.
|
||||
Es enthält weder Modellgewichte noch venv/CUDA-/Build-Artefakte. Restore prüft
|
||||
@@ -194,8 +286,20 @@ Updates benötigen ein neues geprüftes Rezept und eigene Build-/Modellabnahme.
|
||||
Die Installationsroutine überschreibt keine abweichenden oder geänderten
|
||||
Quellstände. Das heutige Rezept ist kein automatischer In-place-Updater.
|
||||
|
||||
Rückfall: altes Strata-Profil und dessen Modellpaket beibehalten. Nach neuem
|
||||
Go und nachgewiesenem Drain auf dieses Profil zurückschalten. Deck-Code-
|
||||
Aktivierung/-Rückfall kann einen Deck/API-Neustart benötigen und ist getrennt
|
||||
0.3.3 zuerst in einer neuen versionierten Zustandswurzel bauen, nicht über den
|
||||
laufenden0.3.0-Quellbaum. Beim separaten Aktivierungs-Go App-Code und passendes
|
||||
Runtime-Rezept gemeinsam umstellen, regulär authentifiziert drainieren und
|
||||
ursprüngliches Qwen-/Audio-/Vision-Profil herstellen. Die heutige Stop-Funktion
|
||||
kann auch Audio entladen; dafür ist eine ausdrückliche Freigabe nötig.
|
||||
Der Kandidatenbau mit externem `--nvcc` leiht nur ein read-only-Toolkit. Das ist
|
||||
keine allein wiederherstellbare Laufzeit: nativ das private Toolkit aus dem
|
||||
gepinnten Rezept rekonstruieren und FFmpeg aus dem Ziel-Debian bereitstellen.
|
||||
|
||||
Rückfall für dieses Update: vorheriges Basalt0.3.0-App-/Runtime-Paar sowie
|
||||
unverändertes v2-Modell und Ein-Slot-/CPU-Konfiguration erhalten. Nach neuem
|
||||
Go und nachgewiesenem Drain dieses Paar wieder aktivieren; kein Modellrollback
|
||||
oder Tausch gegen eine andere Quantisierung notwendig. Ein altes Strata-Profil
|
||||
ist eine zusätzliche, getrennt freizugebende Alternative, nicht der Standardrückfall.
|
||||
App-Aktivierung/-Rückfall kann einen Deck/API-Neustart benötigen und ist getrennt
|
||||
freizugeben. Keine Host-, Container-, Gateway- oder Treiberneustarts durch
|
||||
den Basalt-Installer.
|
||||
@@ -26,6 +26,8 @@ FILES += ['cpu_partition.py']
|
||||
FILES += ['deploy/QWEN_ASR_GPU.md','deploy/qwen-asr-3060-profile.json']
|
||||
FILES += ['basalt_runtime.py','basalt_worker.py','basalt_sources.json','deploy/install_basalt.py','deploy/BASALT_NATIVE.md']
|
||||
FILES += ['basalt_serve.py','basalt_telemetry.py']
|
||||
FILES += ['basalt_tuning.py']
|
||||
FILES += ['chat_media.py','chat_control.py']
|
||||
FILES += ['network/reconnect.py']
|
||||
FILES += ['deploy/read_backup_snapshot.py','speech_text.py','tts_text_enhancer.py','strata_runtime.py','strata_worker.py','strata-ui.js','strata_sources.json','deploy/install_strata.py','deploy/strata_toolkit.py','deploy/strata-cuda13.lock.json','deploy/STRATA_NATIVE.md']
|
||||
FILES += sorted(str(p.relative_to(ROOT)) for p in (ROOT/'deploy/xvc-web').rglob('*') if p.is_file() and not {'__pycache__','.pytest_cache'} & set(p.parts))
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unprivileged native Basalt build: no Docker, model load, driver/service changes."""
|
||||
import argparse
|
||||
import ctypes
|
||||
import ctypes.util
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -12,10 +14,29 @@ import sys
|
||||
|
||||
APP=Path(__file__).resolve().parent.parent
|
||||
RECIPE=json.loads((APP/'basalt_sources.json').read_text())
|
||||
sys.path.insert(0,str(APP))
|
||||
from basalt_tuning import install_profile
|
||||
|
||||
def video_libraries():
|
||||
"""Load only the FFmpeg ABI, without a GPU, decoder, model or subprocess."""
|
||||
names={'avcodec':'avcodec_version','avformat':'avformat_version','avutil':'avutil_version','swscale':'swscale_version'}
|
||||
versions={};libraries={}
|
||||
try:
|
||||
for name,symbol in names.items():
|
||||
path=ctypes.util.find_library(name)
|
||||
if not path:raise ValueError('FFmpeg-Bibliothek fehlt: '+name)
|
||||
lib=ctypes.CDLL(path);function=getattr(lib,symbol);function.restype=ctypes.c_uint
|
||||
versions[name]=function()>>16;libraries[name]=path
|
||||
major={(60,60,58,7):6,(61,61,59,8):7,(62,62,60,9):8}.get(tuple(versions[n] for n in names))
|
||||
if major is None:raise ValueError('Video benötigt zusammenpassende FFmpeg-6/7/8-Bibliotheken.')
|
||||
return dict(available=True,ffmpeg_major=major,libraries=libraries,abi_only=True)
|
||||
except (OSError,AttributeError,ValueError) as exc:
|
||||
return dict(available=False,reason=str(exc),abi_only=True)
|
||||
|
||||
def install(destination,nvcc=None):
|
||||
destination=Path(destination).resolve()
|
||||
destination=Path(destination).absolute()
|
||||
if destination==Path('/') or destination.is_symlink():raise ValueError('Eigene Laufzeitwurzel erforderlich.')
|
||||
destination=destination.resolve()
|
||||
for tool in ('git','g++'):
|
||||
if not shutil.which(tool):raise ValueError('Native Build-Abhängigkeit fehlt: '+tool)
|
||||
destination.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
@@ -48,12 +69,16 @@ def install(destination,nvcc=None):
|
||||
run([python.parent/'cmake','-S',source/'tools/vision','-B',vision,'-G','Ninja','-DCMAKE_BUILD_TYPE=Release','-DBUILD_TESTING=OFF','-DCMAKE_CUDA_ARCHITECTURES=86;120','-DCMAKE_CUDA_COMPILER='+str(nvcc),'-DCUDAToolkit_ROOT='+str(toolkit_root),'-DCMAKE_MAKE_PROGRAM='+str(python.parent/'ninja')])
|
||||
run([python.parent/'cmake','--build',vision,'--target','basalt-vision','--parallel','1'])
|
||||
run([python,'-m','pip','check'])
|
||||
pdf_version=run([python,'-c','import pypdf;print(pypdf.__version__)'],capture_output=True,text=True).stdout.strip()
|
||||
if pdf_version!='7.0.1':raise ValueError('Das gepinnte PDF-Modul pypdf 7.0.1 fehlt.')
|
||||
output=subprocess.run([str(source/'bin/basalt'),'--help'],env=env,capture_output=True,text=True,check=True)
|
||||
if 'basalt serve' not in output.stdout+output.stderr:raise ValueError('Gebautes Basalt-Binary hat nicht die erwartete Server-CLI.')
|
||||
lock=run([python,'-m','pip','freeze','--all'],capture_output=True,text=True).stdout
|
||||
(destination/'python-lock.txt').write_text(lock)
|
||||
binary=source/'bin/basalt'
|
||||
marker=dict(commit=RECIPE['code'],version=RECIPE['version'],cuda='13.0',architectures=[120],vision_architectures=RECIPE['vision_architectures'],python=sys.version.split()[0],binary_sha256=hashlib.sha256(binary.read_bytes()).hexdigest(),origin='native-build',inference_performed=False)
|
||||
if not (source/'data/profiles/qwen4exp-48x512.prof').is_file():raise ValueError('Das Basalt-Expertenprofil muss mit dem Engine-Quellbaum ausgeliefert werden.')
|
||||
install_profile(destination,RECIPE)
|
||||
marker=dict(commit=RECIPE['code'],version=RECIPE['version'],cuda='13.0',architectures=[120],vision_architectures=RECIPE['vision_architectures'],python=sys.version.split()[0],binary_sha256=hashlib.sha256(binary.read_bytes()).hexdigest(),vision_binary_sha256=hashlib.sha256((source/'bin/basalt-vision').read_bytes()).hexdigest(),pdf_version=pdf_version,video=video_libraries(),origin='native-build',inference_performed=False)
|
||||
pending=destination/'ready.tmp';pending.write_text(json.dumps(marker,indent=2));pending.replace(destination/'ready.json')
|
||||
return marker
|
||||
|
||||
|
||||
@@ -5,6 +5,29 @@ curated project handoff, not imported chat history. Read applicable `AGENTS.md`,
|
||||
then the current source and relevant linked documentation; verify live state
|
||||
again before changing anything. Historical notes do not override current facts.
|
||||
|
||||
## Basalt 0.3.3 staged: new runtime and Deck media/control integration
|
||||
|
||||
Maintained recipe now pins `2729e2288f59e01836ddd7fcc630810ada98995a` /
|
||||
0.3.3, with the same v2 model/config and existing expert/cache policy. Own bounded
|
||||
Athena candidate built without GPU/model access: textSM120, visionSM86/SM120,
|
||||
pypdf7.0.1 and FFmpeg6 ABI. Actual binary hashes and fatbin architectures checked.
|
||||
Deck adds bounded inline documents/video, installed-versus-loaded capabilities,
|
||||
logprobs (including Responses channel extensions), principal-scoped request/session
|
||||
IDs and authenticated answer-now without ensure/lease/model switching. Testchat
|
||||
attachments, PDF pages, effort/logprobs and job-bound controls are implemented.
|
||||
|
||||
827 synthetic Root tests passed on the exact index, plus 11/11 browser-mock and
|
||||
1102 pinned-upstream CPU-mock tests (6skips, no errors/failures). The hostcontroller
|
||||
timed out after emitting all successful gates and hit an auto/manual-remove race;
|
||||
owned sandbox absence verified, helper fixed with5 local regressions, not rerun.
|
||||
Both the successful checks and failed controller closure are recorded. These are
|
||||
not real0.3.3 inference, NVDEC or a fresh native Debian/full-restore acceptance.
|
||||
No0.3.3 production activation or new-model benchmark has been authorized here.
|
||||
The last verified production remains healthy0.3.0/original model/allCPU/one slot,
|
||||
same image/start/protected settings. Keep that pair for rollback, preserve Qwen
|
||||
and audio; future app/runtime activation needs a separate Go and normal drain.
|
||||
[Build, contracts, checks, execution environments and open gates](maintenance/basalt-033-staged-2026-11-13/README.md).
|
||||
|
||||
## Basalt all-CPU/one-slot configuration active · 9 November, 19:39 CET
|
||||
|
||||
Michael separately approved normal API/audio interruption and short acceptance,
|
||||
|
||||
@@ -1,3 +1,21 @@
|
||||
## Basalt 0.3.3 prepared; production 0.3.0 deliberately unchanged
|
||||
|
||||
The new recipe/runtime candidate and Deck source support bounded documents and
|
||||
video, capabilities/logprobs, principal-scoped request/session IDs and answer-now,
|
||||
including testchat controls. TextSM120 and visionSM86/SM120 built and independently
|
||||
inspected; pypdf7.0.1/FFmpeg6 ABI, 827 Root tests and 11/11 browser-mock gates passed.
|
||||
The exact-index suite passed. Pinned-upstream CPU-mock:1102 tests,6skips,no failures.
|
||||
All8 feature gates passed before the hostcontroller's timeout/auto-remove race;
|
||||
own container absent, helper fixed and5 local unit tests passed. This failed
|
||||
controller closure is retained separately, not hidden by the successful tests.
|
||||
|
||||
No production image/runtime activation, weight download, profile change, service
|
||||
restart or real0.3.3 inference. The running Basalt0.3.0/original Qwen/allCPU/one-slot
|
||||
pair and existing audio remain the protected baseline and rollback. New app-code
|
||||
activation and model/NVDEC/audio acceptance need a separate Go and ordinary
|
||||
authenticated drain. Fresh Debian/systemd/full encrypted restore still unproven.
|
||||
[Prepared artifact, contracts, native recipe and acceptance limits](maintenance/basalt-033-staged-2026-11-13/README.md).
|
||||
|
||||
## 9.11.2026 · Basalt all-CPU/one-slot configuration active
|
||||
|
||||
Existing Basalt0.3.0/original model remains active on5080; normal vision/Anna/ASR
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
# Basalt 0.3.3: Laufzeitkandidat und Deck-Funktionen
|
||||
|
||||
## Ergebnis und klare Betriebsgrenze
|
||||
|
||||
Der Auftrag umfasst **bauen und in Deck implementieren**, nicht das ungefragte
|
||||
Umschalten des laufenden Dienstes. Basalt0.3.3 wurde isoliert gebaut; die neuen
|
||||
Deck-API-/Testchatfunktionen liegen im Quellcode. **Die Produktion bleibt beim
|
||||
bisherigen Basalt0.3.0, demselben Modell und der all-CPU-/Ein-Slot-Konfiguration.**
|
||||
Kein echter Modellstart, GPU-Inferenzlauf, Benchmark, neues TTS-Profil oder
|
||||
Produktions-/Container-/Gatewayneustart gehört zu dieser Vorbereitung.
|
||||
|
||||
- Upstream: [Basalt v0.3.3](https://github.com/jesdga95/basalt/releases/tag/v0.3.3).
|
||||
- Source-Pin: `2729e2288f59e01836ddd7fcc630810ada98995a`.
|
||||
- Modell-/Konfigurationsformat bleiben v2; Gewichte/Quantisierung unverändert.
|
||||
- Athena-Kandidat: `/opt/athena-deck-dev/basalt-033-candidate-2729e2288f59/runtime`.
|
||||
- Native Installation/Restore/Rückfall: [gepflegtes Rezept](../../../deploy/BASALT_NATIVE.md).
|
||||
|
||||
## Implementierte Funktionen
|
||||
|
||||
| Bereich | Deck-Vertrag |
|
||||
|---|---|
|
||||
| Dokumente | Chat: `type=file`, eingebettete `file_data`, `filename`, optional `file.pages`. Responses: `input_file`. PDF, DOCX, PPTX, XLSX und UTF-8-Textformate. Keine Datei-IDs, Serverpfade oder URL-Nachladefunktion. |
|
||||
| Video | Chat: `video_url` bzw. `input_video` mit eingebetteter URL; Responses: `input_video` mit `video_url`. Standard/Maximum2Frames/s und128Frames; keine Audioauswertung. Vision-Projektor und bestätigte Videofähigkeit erforderlich. |
|
||||
| Fähigkeiten | `/props?model=API_ID` trennt `available_capabilities` der Installation von `capabilities` und `loaded` des tatsächlich passenden Workers. Die Erkennung startet kein Modell. `/v1/capabilities` beschreibt den Routervertrag. |
|
||||
| Logprobs | Chat: `logprobs=true`, `top_logprobs` als ganze Zahl0–20. Responses: `include=["message.output_text.logprobs"]`; Text-, Thinking- und Toolkanäle bleiben erhalten. Kein Wahrheits-/Qualitätsscore. |
|
||||
| Request-IDs | `X-Request-Id` auf Chat-/Responses-Antworten; eine optionale `X-Client-Request-Id` ist ein principalgebundener Alias. Interne IDs werden zufällig erzeugt, nicht unkontrolliert vom Client übernommen. |
|
||||
| Sitzung | `session_id` oder in dieser Reihenfolge `x-llm-flow-id`, `x-claude-code-session-id`, `x-session-id`, `x-session-affinity`. Die Weitergabe verwendet einen principalgebundenen flüchtigen HMAC, keinen fremden Klartext-Namespace. |
|
||||
| Jetzt antworten | Authentifiziertes `POST /v1/answer_now` mit `request_id` oder Sitzung. Nur eigener Principal, ursprüngliches Profil/Revision/Workergeneration; keine Lease, kein Ensure/Load/Stop. Auch in Deck wartende Anfragen können die Umschaltung vormerken. |
|
||||
| Testchat | Dateien hinzufügen/entfernen, PDF-Seitenwahl, Denkstufe, optionale Tokenwahrscheinlichkeiten und „Jetzt antworten“. Abbruch/Steuerung bindet die aktuelle Testjob-ID. Anmeldung/CSRF bleiben erforderlich. |
|
||||
|
||||
Die öffentliche Deck-Integration betrifft die vorhandenen Chat-Completions-
|
||||
und optionalen Responses-Routen. Sie veröffentlicht keinen neuen Anthropic-
|
||||
Messages-Endpunkt und aktiviert Responses nicht automatisch.
|
||||
|
||||
### Eingabe- und Kontrollgrenzen
|
||||
|
||||
- Gesamtes JSON einschließlich Verlauf:64MiB.
|
||||
- Höchstens8 Anhänge und zusammen32MiB über den gesamten Verlauf.
|
||||
- Ein Dokument maximal16MiB, ein Video maximal32MiB.
|
||||
- PDF-Seitenauswahl auf Seiten1–600 begrenzt; der native Parser begrenzt auch
|
||||
die Zahl gelesener Seiten. Scans benötigen einen Vision-Projektor.
|
||||
- Office-ZIP-Metadaten: höchstens2048 Einträge,16MiB je entpacktem Eintrag,
|
||||
zusammen64MiB; keine verschlüsselten, Symlink- oder Traversal-Einträge.
|
||||
- Kontroll-JSON maximal4KiB. Die Registry hält höchstens1024 Metadatensätze;
|
||||
abgeschlossene Einträge verfallen nach600s. Prompts und Tokens gehören nicht hinein.
|
||||
- 32 Datenverbindungen plus4 zusätzliche HTTP-Plätze für Steuerung. Das ist keine
|
||||
Zusage gegen beliebige Netzwerküberlastung, hält aber die Kontrollroute bei
|
||||
belegten normalen Datenplätzen frei.
|
||||
|
||||
## Tatsächliche Prüfungen
|
||||
|
||||
- **827 Root-Tests bestanden**, auch im expliziten Git-Indexexport: keine Fehler,
|
||||
Skips oder vom Offline-Audit festgestellten verbotenen I/O, Prozessexit0.
|
||||
Spätere Änderungen betreffen nur Belege, Dokumentation und den separat
|
||||
geprüften Operatorhelfer; die Root-App-/Testquellen sind hashgleich.
|
||||
- **11/11 Browser-Mockprüfungen bestanden**: Dateilesen und Payloadformen,
|
||||
PDF-Seiten, Video-Defaults, Denkstufe/Logprobs, eigener Steuerknopf,
|
||||
Antwortabschluss, Dateinamen-Escaping,32MiB-Clientlimit, alte Laufzeit gesperrt,
|
||||
keine JavaScript-Fehler. Das war die echte neue UI mit synthetischem Backend,
|
||||
nicht die produktiv ausgelieferte Oberfläche und keine echte Videoanalyse.
|
||||
- Managementtests prüfen zusätzlich Anmeldung statt API-Bearer, CSRF,
|
||||
jobgebundene Steuerung und größere Chat-Uploads ohne Aufweitung der32KiB-
|
||||
Grenzen allgemeiner Einstellungen.
|
||||
- Text-/Vision-Binärhashes wurden unabhängig gelesen. NVIDIAs gepinntes
|
||||
`cuobjdump` bestätigte die tatsächlichen ELF-Ziele **Text120, Vision86/120**.
|
||||
- `pypdf7.0.1`, `pip check`, CLI-Hilfe und zusammenpassende FFmpeg6-Bibliotheken
|
||||
bestanden im Kandidatenbau. FFmpeg-ABI-Prüfung ist **kein NVDEC-Funktionstest**.
|
||||
- Der zusätzliche pinned-Upstream-Lauf nutzt echte Server-/Dokument-/Control-
|
||||
Implementierung mit ausdrücklich geskriptetem CPU-Mock: **1102 Tests,
|
||||
0Fehler, 0Fehlschläge, 6Skips**; Skip-Gründe wurden nicht einzeln gespeichert.
|
||||
Alle8 Prüfgates einschließlich Deck→Upstream-Chat/Responses, authentifizierter
|
||||
Kontrolle und numerischer Telemetrie bestanden. Kein Modell-/Geschwindigkeitstest.
|
||||
- **5/5 lokale Operatorhelfer-Tests bestanden**, zuvor3 gezielt rote Fälle:
|
||||
automatisches/manuelles Entfernen, Erhalt des Timeoutfehlers, Zeitbudget,
|
||||
erfolgreicher Abschluss und Verweigerung fremder Containerlabels. Docker wird
|
||||
in diesen Unit-Tests ausdrücklich nur simuliert, nicht wirklich aufgerufen.
|
||||
|
||||
Maschinenlesbare Belege: [Build](build-result.json), [Native-Prüfungen](native-checks.json),
|
||||
[tatsächlich ausgeführte Source-Hashes](native-inputs.json),
|
||||
[Produktion unverändert und Prüfcontainer entfernt](live-preservation.json),
|
||||
[Prüfzusammenfassung](verification.json), [Quellmanifest](source-manifest.json)
|
||||
und [aufgelöste Kandidaten-Pythonabhängigkeiten](python-lock.txt).
|
||||
|
||||
### Festgehaltene anfängliche Fehler
|
||||
|
||||
1. Die erste Root-Gesamtsuite war nicht grün:824 Tests, ein Fehlschlag und zwei
|
||||
Auditfehler. Ein global gepatchtes stdlib-`Popen` fing eine unabhängige
|
||||
Hardwareabfrage ab. Der Testbereich hat jetzt seine eigene subprocess-Fassade
|
||||
mit Rot/Grün-Regression. Zwei Fixtures verwendeten unnötig einen Livepfad-Link
|
||||
bzw. `/tmp`; sie nutzen nun reine aufgelöste Testpfade bzw. das eigene TMPDIR.
|
||||
Der Audit wurde dafür **nicht** abgeschwächt; anschließend827 Tests grün.
|
||||
2. Die erste Native-Zusatzprüfung erwartete fälschlich eine echte Engineversion
|
||||
von einem CPU-Mock. Upstream `/props` bezieht sie aus `engine.info`; eine
|
||||
fehlende Mockversion wird nicht mit erfundenen Metadaten ersetzt.
|
||||
3. Die zweite Zusatzprüfung suchte eine zusammenhängende Antwort in rohen SSE-
|
||||
Bytes, obwohl der Mock einzelne Zeichen pro Event sendet. Der korrigierte
|
||||
Prüfer setzt die Antwort aus den tatsächlichen Events zusammen.
|
||||
4. Befehlsfreigaben liefen zwischenzeitlich ab. Solche Befehle wurden nicht
|
||||
ausgeführt oder über andere Wege wiederholt; erst nach erneuter Freigabe.
|
||||
5. Versuch3 schrieb den vollständigen erfolgreichen Prüfbeleg, sein Hostcontroller
|
||||
endete aber **nicht erfolgreich**: allein die Upstream-Suite dauerte479,532s,
|
||||
das gesamte Containerbudget war480s. Beim Timeout kollidierte zusätzlich
|
||||
`--rm` mit dem manuellen Entfernen; der zweite Fehler verdeckte den ersten.
|
||||
Das ist kein fehlgeschlagener Modelltest. Der eigene Container wurde unabhängig
|
||||
als entfernt nachgewiesen; Produktion/Originaltext-PID/geschützte Hashes gleich.
|
||||
Das gepflegte Skript verwendet jetzt genau einen manuellen Lebenszyklus und
|
||||
höchstens900s einschließlich Setup. Die Korrektur ist lokal Rot/Grün geprüft;
|
||||
**kein vierter Athena-Lauf**, kein nachträglich erfundener Controller-Exit0.
|
||||
|
||||
## Ausführungsorte und Wiederholbarkeit
|
||||
|
||||
- `build_host.py`: **Athena-Host**, expliziter Quelltext-/Vorherzustands-Bundle
|
||||
über die bestehende Athena-SSH-Verbindung. Eigene Wurzel, kein Wiederverwenden
|
||||
einer vorhandenen Wurzel,1CPU/4GiB/nice15, UID65534 des verifizierten heutigen
|
||||
Deck-Kontos, runc ohne GPU-Geräte. Nur CUDA-Werkzeuge read-only geliehen;
|
||||
Produktionsstate ist nicht als Datenmount beteiligt. Das ist ein isolierter
|
||||
Bau auf der bestehenden Ubuntu-Appbasis, kein frischer nativer Debian-Nachweis.
|
||||
- `verify_host.py`: **Athena-Host**, nur eigener fertiger Kandidat. runc ohne GPU
|
||||
und ohne Netz,1CPU/4GiB, Source/Runtime/Toolkit read-only, eigene Temp-/Ausgabe-
|
||||
verzeichnisse. `check_upstream.py` läuft in der tatsächlichen Kandidatenvenv.
|
||||
`cuobjdump-lock.json` pinnt das kleine offizielle Inspektionswerkzeug; es wird
|
||||
nicht hostweit installiert. Jeder Versuch hat eine getrennte, exklusive Wurzel.
|
||||
- `test_verify_host.py`: **NAS**, führt die tatsächlichen Command-/finally-
|
||||
AST-Blöcke mit einer ausdrücklich synthetischen subprocess-Fassade aus.
|
||||
Es liest keine Hostkonfiguration und startet/stoppt keinen echten Container.
|
||||
- `verify_offline.py`: **NAS, eigenes Projekt-Test-Python**, Root-Suite auch gegen
|
||||
einen Export des Git-Index. Sperrt Produktions-/VPN-Zugriffe, andere Profile,
|
||||
Remote-/Containerbefehle und nichtlokale Testverbindungen. Kein Live-Abnahmeclient.
|
||||
- `ui_mock.py`: **NAS**, zeitlich begrenzte Loopback-UI mit explizitem Mock-Banner;
|
||||
keine Verbindung zu Athena, keine Modellinferenz. Keine neue Dauerdienstinstallation.
|
||||
- `acceptance.py`: **NAS, bestehende Hermes-Profilumgebung**. Standardaufruf ohne
|
||||
neues `--go` verweigert vor Zugangsdatenauflösung und API-Zugriff. `--self-test`
|
||||
erzeugt nur synthetisches PNG/PDF/MP4 in RAM; FFmpeg/libx264 arbeitet auf CPU.
|
||||
Der No-Go-Schutz und die Fixture-Erzeugung wurden tatsächlich ausgeführt.
|
||||
|
||||
Der spätere Live-Client ist auf höchstens900s begrenzt, verändert keine
|
||||
Einstellungen und startet kein anderes Modell absichtlich kalt. Vor jeder
|
||||
Inferenz muss `/props` bereits geladenes Basalt0.3.3 mit den erwarteten Fähigkeiten,
|
||||
einem Slot und262144 Kontext bestätigen. Geprüft werden Text/Request-ID/Logprobs,
|
||||
PDF, synthetisches rotes Video und Sitzungs-`answer_now` im selben Stream.
|
||||
Responses wird nur bei bereits eingeschalteter Kompatibilität geprüft; andernfalls
|
||||
erscheint dies ausdrücklich als nicht ausgeübt. Es werden keine Rohantworten,
|
||||
Prompts oder Zugangsdaten in den Ergebnisbeleg geschrieben.
|
||||
|
||||
## Aktivierung, Rückfall und ausdrücklich offene Gates
|
||||
|
||||
**Dieses Ergebnis ist keine Aktivierungserlaubnis.** Eine spätere Übernahme
|
||||
braucht Michaels separates Go, normale Management-Anmeldung, frischen Nachweis
|
||||
für aktive **und wartende** Arbeit sowie ein abgestimmtes Audiofenster. Stop
|
||||
kann auch Audio entladen. App-Code und passendes Runtime-Rezept müssen zusammen
|
||||
umgestellt werden; ein bloßes Worker-Neuladen installiert diese Python-/UI-
|
||||
Änderungen nicht. Noch kein neues produktives App-Image aus diesem Stand aktiviert.
|
||||
|
||||
Altes Basalt0.3.0-App-/Runtime-Paar, dieselben Gewichte und Ein-Slot-/CPU-
|
||||
Konfiguration bleiben der Rückfall. Kein stilles Wechseln auf Strata, Lamina,
|
||||
ein anderes Modell oder eine andere Quantisierung. Das heutige private Toolkit
|
||||
muss nativ aus dem festen Rezept rekonstruierbar sein; die geliehene CUDA-Quelle
|
||||
des Kandidaten ist kein verstecktes dauerhaftes Restore-Erfordernis.
|
||||
|
||||
**Nicht abgenommen:** echte0.3.3-Modell-/NVDEC-Inferenz und Audio-Koexistenz,
|
||||
Geschwindigkeitsgewinn, volle262144 Token oder Last-/Dauertest, produktive UI,
|
||||
Mac-Client sowie frisches Debian/systemd mit vollständigem verschlüsseltem
|
||||
Restore. Der Basisinstaller bleibt der dokumentierte offene Produktumfang;
|
||||
Container- und Dateiprüfungen ersetzen ihn nicht.
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
"""NAS/Hermes-profile client, ONLY after a separate live-model acceptance Go.
|
||||
|
||||
No activation, restart, unload, settings changes or benchmarks. --self-test only
|
||||
creates synthetic media in memory and checks its structure, without credentials.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
import zlib
|
||||
|
||||
HERE=Path(__file__).resolve().parent
|
||||
BASE='http://192.168.1.212:8120'
|
||||
MODEL='flash-next-basalt'
|
||||
CODE='BASALT-033-317'
|
||||
|
||||
|
||||
def fixtures():
|
||||
def chunk(name,data):return struct.pack('!I',len(data))+name+data+struct.pack('!I',zlib.crc32(name+data)&0xffffffff)
|
||||
png=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!2I5B',64,64,8,2,0,0,0))+chunk(b'IDAT',zlib.compress((b'\0'+b'\xff\0\0'*64)*64))+chunk(b'IEND',b'')
|
||||
text=('BT /F1 12 Tf 10 50 Td ('+CODE+') Tj ET').encode()
|
||||
objects=[b'<< /Type /Catalog /Pages 2 0 R >>',b'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',b'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>',b'<< /Length '+str(len(text)).encode()+b' >>\nstream\n'+text+b'\nendstream',b'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>']
|
||||
pdf=bytearray(b'%PDF-1.4\n');offsets=[]
|
||||
for n,obj in enumerate(objects,1):offsets.append(len(pdf));pdf.extend(str(n).encode()+b' 0 obj\n'+obj+b'\nendobj\n')
|
||||
xref=len(pdf);pdf.extend(b'xref\n0 6\n0000000000 65535 f \n'+b''.join(f'{n:010d} 00000 n \n'.encode() for n in offsets)+b'trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n'+str(xref).encode()+b'\n%%EOF\n')
|
||||
# Explicit CPU-only lavfi -> libx264, no input file, decoder or GPU device.
|
||||
command=['ffmpeg','-nostdin','-hide_banner','-loglevel','error','-f','lavfi','-i','color=c=red:s=64x64:r=2:d=2','-frames:v','4','-an','-c:v','libx264','-threads','1','-pix_fmt','yuv420p','-movflags','frag_keyframe+empty_moov','-f','mp4','pipe:1']
|
||||
video=subprocess.run(command,capture_output=True,check=True,timeout=20).stdout
|
||||
assert b'ftyp' in video[:64] and len(video)<1024**2
|
||||
assert pdf[xref:xref+4]==b'xref' and all(pdf[offset:offset+len(str(n))+6].startswith(str(n).encode()+b' 0 obj') for n,offset in enumerate(offsets,1))
|
||||
return dict(png=png,pdf=bytes(pdf),video=video)
|
||||
|
||||
|
||||
def url(mime,data):return 'data:'+mime+';base64,'+base64.b64encode(data).decode()
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
p=argparse.ArgumentParser();p.add_argument('--go',action='store_true');p.add_argument('--self-test',action='store_true');p.add_argument('--output',type=Path);p.add_argument('--seconds',type=int,default=900);a=p.parse_args(argv)
|
||||
if a.self_test:
|
||||
values=fixtures();print(json.dumps({'synthetic_fixtures':{k:len(v) for k,v in values.items()},'credentials_resolved':False,'network_requests':0,'model_inference':False}));return 0
|
||||
if not a.go:p.error('Separate explicit live-model acceptance Go required; --self-test makes no API calls.')
|
||||
if a.output is None or a.output.exists() or not a.output.parent.is_dir() or not 1<=a.seconds<=900:p.error('New output path in an existing directory and a budget of at most 900 seconds required.')
|
||||
spec=importlib.util.spec_from_file_location('athena_managed_transport',HERE.parent/'basalt-candidate-2026-11-01/paired_transport.py')
|
||||
if spec is None or spec.loader is None:raise RuntimeError('Tracked profile-scoped transport is unavailable.')
|
||||
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module);credential=module.key()
|
||||
deadline=time.monotonic()+a.seconds;result={'complete':False,'activation_performed':False,'checks':{},'inference_requests_sent':0,'started_at':time.time()};media=fixtures()
|
||||
def save():a.output.write_text(json.dumps(result,indent=2)+'\n')
|
||||
def request(path,body=None):
|
||||
remaining=deadline-time.monotonic();assert remaining>0
|
||||
req=urllib.request.Request(BASE+path,data=None if body is None else json.dumps(body).encode(),headers={'Content-Type':'application/json','Authorization':'Bearer '+credential})
|
||||
with urllib.request.urlopen(req,timeout=min(30,remaining)) as response:return json.load(response),dict(response.headers)
|
||||
def chat(content,**options):
|
||||
result['inference_requests_sent']+=1
|
||||
return request('/v1/chat/completions',dict(model=MODEL,messages=[dict(role='user',content=content)],temperature=0,max_tokens=32,reasoning_effort='none',**options))
|
||||
def text(value):return value['choices'][0]['message'].get('content') or ''
|
||||
try:
|
||||
props,_=request('/props?model='+MODEL);info=props.get('basalt',{})
|
||||
assert info.get('loaded') is True and info.get('version')=='0.3.3','Resident Basalt0.3.3 required; this client must not cold-load another runtime.'
|
||||
assert {'answer_now','documents','logprobs','video'}<=set(info.get('capabilities',[]))
|
||||
assert props['total_slots']==1 and props['default_generation_settings']['n_ctx']==262144
|
||||
result['checks']['resident_version_and_unchanged_slot_context']=True
|
||||
value,headers=chat('Antworte nur mit BEREIT.',logprobs=True,top_logprobs=2)
|
||||
probs=value['choices'][0].get('logprobs',{}).get('content',[])
|
||||
assert 'BEREIT' in text(value).upper() and headers.get('X-Request-Id') and probs
|
||||
assert all(isinstance(e,dict) and type(e.get('logprob')) in (int,float) and math.isfinite(e['logprob']) and isinstance(e.get('top_logprobs'),list) and len(e['top_logprobs'])<=2 for e in probs)
|
||||
result['checks']['text_request_id_and_logprobs']=True;save()
|
||||
value,_=chat([{'type':'text','text':'Nenne ausschließlich den Code aus der PDF.'},{'type':'file','file':{'filename':'synthetic.pdf','file_data':url('application/pdf',media['pdf']),'pages':'1'}}]);assert CODE in text(value);result['checks']['pdf_selected_page']=True;save()
|
||||
value,_=chat([{'type':'text','text':'Welche Farbe füllt das Video? Antworte mit genau einem deutschen Farbnamen.'},{'type':'video_url','video_url':{'url':url('video/mp4',media['video'])},'fps':2,'max_frames':4}]);assert 'rot' in text(value).lower();result['checks']['synthetic_video_red']=True;save()
|
||||
caps,_=request('/v1/capabilities');enabled=caps.get('responses',{}).get('enabled') is True
|
||||
if enabled:
|
||||
result['inference_requests_sent']+=1
|
||||
value,_=request('/v1/responses',dict(model=MODEL,input=[dict(role='user',content=[dict(type='input_text',text='Gib nur den Dateicode aus.'),dict(type='input_file',filename='synthetic.txt',file_data=url('text/plain',CODE.encode()))])],max_output_tokens=32,reasoning={'effort':'none'},include=['message.output_text.logprobs'],top_logprobs=0))
|
||||
parts=[c for item in value.get('output',[]) if item.get('type')=='message' for c in item.get('content',[])];assert any(CODE in c.get('text','') and c.get('logprobs') for c in parts);result['checks']['responses_file_and_logprobs']=True
|
||||
else:result['responses_not_exercised']='Responses compatibility remains disabled; this client does not change that setting.'
|
||||
ready=threading.Event();finished=threading.Event();session='acceptance-'+uuid.uuid4().hex
|
||||
def stream():
|
||||
result['inference_requests_sent']+=1
|
||||
body=dict(model=MODEL,messages=[dict(role='user',content='Prüfe ausführlich die Vor- und Nachteile von fünf verschiedenen Archivierungsstrategien und gib dann eine kurze Empfehlung.')],stream=True,max_tokens=512,reasoning_effort='high',session_id=session,temperature=0)
|
||||
req=urllib.request.Request(BASE+'/v1/chat/completions',data=json.dumps(body).encode(),headers={'Authorization':'Bearer '+credential,'Content-Type':'application/json'})
|
||||
answer='';done=False
|
||||
try:
|
||||
with urllib.request.urlopen(req,timeout=min(30,deadline-time.monotonic())) as response:
|
||||
assert response.headers.get('X-Request-Id')
|
||||
for line in response:
|
||||
assert time.monotonic()<deadline
|
||||
if not line.startswith(b'data:'):continue
|
||||
raw=line[5:].strip()
|
||||
if raw==b'[DONE]':done=True;break
|
||||
event=json.loads(raw);assert not event.get('error')
|
||||
for choice in event.get('choices',[]):
|
||||
delta=choice.get('delta',{})
|
||||
if delta.get('reasoning_content'):ready.set()
|
||||
answer+=delta.get('content') or ''
|
||||
assert done and answer.strip();return True
|
||||
finally:finished.set()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future=pool.submit(stream)
|
||||
assert ready.wait(min(20,max(.1,deadline-time.monotonic()))) and not finished.is_set(),'No still-running thinking phase observed; answer_now not exercised.'
|
||||
control,_=request('/v1/answer_now',{'session_id':session});assert control.get('state') in ('thinking','prompt','queued')
|
||||
assert future.result(timeout=max(.1,deadline-time.monotonic()))
|
||||
result['checks']['session_answer_now_same_stream']=True;result['complete']=True;save();return 0
|
||||
except Exception as exc:
|
||||
result['failure_type']=type(exc).__name__;save();raise RuntimeError('Bounded acceptance incomplete; inspect nonsecret result flags, not a claimed success.') from None
|
||||
finally:result['finished_at']=time.time();save()
|
||||
|
||||
|
||||
if __name__=='__main__':raise SystemExit(main())
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"owner": "athena-deck",
|
||||
"commit": "2729e2288f59e01836ddd7fcc630810ada98995a",
|
||||
"image": "sha256:0a358dd687a415faf26cea2d73160654fb9b2e56ad68c7013bef52bc166fed33",
|
||||
"root_device": 66306,
|
||||
"root_inode": 8914120,
|
||||
"phase": "built_no_model_test",
|
||||
"started_at": 1794561680.5234628,
|
||||
"cpu_quota": 1,
|
||||
"memory_gib": 4,
|
||||
"nice": 15,
|
||||
"gpu_access": false,
|
||||
"production_state_mount": false,
|
||||
"borrowed_cuda_read_only": "/opt/athena-deck-dev/runtime/state/basalt-runtime/cuda",
|
||||
"source_hashes": {
|
||||
"basalt_sources.json": "e2c0ca28dce89aea30b7ba0be4d05641687938fe9b08e485830c4635bb1ae30f",
|
||||
"basalt_tuning.py": "f2585dab9581ce8c8b3712c4ee9f9a98d5b58d41ce11f9f8ab5b17f429e0dfdf",
|
||||
"deploy/install_basalt.py": "7e81efe44224707c5b3b5417382381113b263bf6532060f8c80b4e1eed4748e5"
|
||||
},
|
||||
"container_id": "33d488507d47157dbfd235710f82f886c6d158d95f4d5d033e59d194acf5cf3b",
|
||||
"client_exit": 0,
|
||||
"container_exit": 0,
|
||||
"oom_killed": false,
|
||||
"ready": {
|
||||
"commit": "2729e2288f59e01836ddd7fcc630810ada98995a",
|
||||
"version": "0.3.3",
|
||||
"cuda": "13.0",
|
||||
"architectures": [
|
||||
120
|
||||
],
|
||||
"vision_architectures": [
|
||||
86,
|
||||
120
|
||||
],
|
||||
"python": "3.12.3",
|
||||
"binary_sha256": "9e89333cd2f12eee69a5e1535433631155ae92dc089774ad6c8f99e9b62c0c46",
|
||||
"vision_binary_sha256": "e75b4f529acf7623c8fede68847052c097a325ca9f808d88cea4c061ed15b798",
|
||||
"pdf_version": "7.0.1",
|
||||
"video": {
|
||||
"available": true,
|
||||
"ffmpeg_major": 6,
|
||||
"libraries": {
|
||||
"avcodec": "libavcodec.so.60",
|
||||
"avformat": "libavformat.so.60",
|
||||
"avutil": "libavutil.so.58",
|
||||
"swscale": "libswscale.so.7"
|
||||
},
|
||||
"abi_only": true
|
||||
},
|
||||
"origin": "native-build",
|
||||
"inference_performed": false
|
||||
},
|
||||
"owned_container_final_state": {
|
||||
"Status": "exited",
|
||||
"Running": false,
|
||||
"Paused": false,
|
||||
"Restarting": false,
|
||||
"OOMKilled": false,
|
||||
"Dead": false,
|
||||
"Pid": 0,
|
||||
"ExitCode": 0,
|
||||
"Error": "",
|
||||
"StartedAt": "2026-11-13T09:21:20.688388049Z",
|
||||
"FinishedAt": "2026-11-13T09:54:01.431731057Z"
|
||||
},
|
||||
"owned_container_removed": true,
|
||||
"finished_at": 1794563641.7705805
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""ATHENA HOST only: bounded no-GPU builder, production state never mounted.
|
||||
|
||||
Input is a reviewed source-only JSON bundle from the NAS. Not an activation tool.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT=Path('/opt/athena-deck-dev/basalt-033-candidate-2729e2288f59')
|
||||
NAME='athena-basalt033-build-20261113'
|
||||
LABEL='basalt033-20261113'
|
||||
COMMIT='2729e2288f59e01836ddd7fcc630810ada98995a'
|
||||
CUDA=Path('/opt/athena-deck-dev/runtime/state/basalt-runtime/cuda')
|
||||
FILES=('basalt_sources.json','basalt_tuning.py','deploy/install_basalt.py')
|
||||
|
||||
|
||||
def run(*args,**kwargs):return subprocess.run(list(map(str,args)),check=True,**kwargs)
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser();p.add_argument('--go',action='store_true');a=p.parse_args();assert a.go
|
||||
bundle=json.load(sys.stdin);assert set(bundle['files'])==set(FILES)
|
||||
recipe=json.loads(bundle['files']['basalt_sources.json']);assert recipe['code']==COMMIT and recipe['version']=='0.3.3'
|
||||
before=bundle['before'];assert before['image'].startswith('sha256:')
|
||||
assert not ROOT.exists() and not ROOT.is_symlink() and CUDA.is_dir()
|
||||
mem=dict(x.split(':',1) for x in Path('/proc/meminfo').read_text().splitlines())
|
||||
assert int(mem['MemAvailable'].split()[0])>=7*1024**2,'Insufficient live headroom; Qwen is not unloaded'
|
||||
assert shutil.disk_usage(ROOT.parent).free>=12*1024**3
|
||||
live=json.loads(subprocess.check_output(['docker','inspect','athena-deck-dev']))[0]
|
||||
assert live['Image']==before['image'] and live['Id']==before['container_id'] and live['State']['StartedAt']==before['started']
|
||||
ROOT.mkdir(mode=0o700);os.chown(ROOT,65534,65534)
|
||||
for folder in ('recipe','recipe/deploy','runtime','tmp'):
|
||||
q=ROOT/folder;q.mkdir();q.chmod(0o700);os.chown(q,65534,65534)
|
||||
for name,text in bundle['files'].items():
|
||||
q=ROOT/'recipe'/name;q.write_text(text);q.chmod(0o600);os.chown(q,65534,65534)
|
||||
marker={'owner':'athena-deck','commit':COMMIT,'image':before['image'],'root_device':ROOT.stat().st_dev,'root_inode':ROOT.stat().st_ino,'phase':'prepared','started_at':time.time(),'cpu_quota':1,'memory_gib':4,'nice':15,'gpu_access':False,'production_state_mount':False,'borrowed_cuda_read_only':str(CUDA),'source_hashes':{n:hashlib.sha256(t.encode()).hexdigest() for n,t in bundle['files'].items()}}
|
||||
status=ROOT/'build-status.json'
|
||||
def save():status.write_text(json.dumps(marker,indent=2)+'\n')
|
||||
save();cid=None
|
||||
try:
|
||||
args=['docker','create','--pull=never','--name',NAME,'--label','athena-deck.build='+LABEL,'--runtime=runc','--network=bridge','--read-only','--user=65534:65534','--cpus=1','--memory=4g','--memory-swap=4g','--pids-limit=1024','--cap-drop=ALL','--security-opt=no-new-privileges',
|
||||
'--mount',f'type=bind,src={ROOT}/recipe,dst=/recipe,readonly','--mount',f'type=bind,src={ROOT}/runtime,dst=/var/lib/deck/basalt-runtime','--mount',f'type=bind,src={ROOT}/tmp,dst=/tmp','--mount',f'type=bind,src={CUDA},dst=/toolchain,readonly',
|
||||
'-e','HOME=/var/lib/deck/basalt-runtime/home','-e','TMPDIR=/tmp','-e','NVIDIA_VISIBLE_DEVICES=void','-e','CUDA_VISIBLE_DEVICES=','-e','OPENBLAS_NUM_THREADS=1','-e','OMP_NUM_THREADS=1','-e','PYTHONDONTWRITEBYTECODE=1','--entrypoint','nice',before['image'],'-n','15','python3','/recipe/deploy/install_basalt.py','--destination','/var/lib/deck/basalt-runtime','--nvcc','/toolchain/bin/nvcc']
|
||||
cid=subprocess.check_output(args,text=True).strip();marker.update(container_id=cid,phase='building');save();print(json.dumps(marker),flush=True)
|
||||
with (ROOT/'build.log').open('w') as log:
|
||||
result=subprocess.run(['docker','start','--attach',cid],stdout=log,stderr=subprocess.STDOUT)
|
||||
info=json.loads(subprocess.check_output(['docker','inspect',cid]))[0]
|
||||
assert info['Config']['Labels'].get('athena-deck.build')==LABEL
|
||||
marker.update(client_exit=result.returncode,container_exit=info['State']['ExitCode'],oom_killed=info['State']['OOMKilled'])
|
||||
assert result.returncode==0 and info['State']['ExitCode']==0,'Owned build failed; inspect build.log and preserved status'
|
||||
ready=json.loads((ROOT/'runtime/ready.json').read_text());assert ready['commit']==COMMIT and ready['inference_performed'] is False
|
||||
assert ready['video']['available'] is True and ready['pdf_version']=='7.0.1'
|
||||
marker.update(phase='built_no_model_test',ready=ready)
|
||||
except BaseException as exc:
|
||||
marker.update(phase='failed',error=type(exc).__name__+': '+str(exc));raise
|
||||
finally:
|
||||
if cid:
|
||||
i=json.loads(subprocess.check_output(['docker','inspect',cid]))[0]
|
||||
assert i['Config']['Labels'].get('athena-deck.build')==LABEL
|
||||
if i['State']['Running']:run('docker','stop','--time','20',cid)
|
||||
marker['owned_container_final_state']=json.loads(subprocess.check_output(['docker','inspect',cid]))[0]['State']
|
||||
run('docker','rm',cid,stdout=subprocess.DEVNULL);marker['owned_container_removed']=True
|
||||
marker['finished_at']=time.time();save();print(json.dumps(marker),flush=True)
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CANDIDATE PYTHON/sandbox only: artifact checks and real upstream CPU mocks.
|
||||
|
||||
This never constructs a real engine or loads weights. SlowThinker and all model
|
||||
answers/probabilities are explicitly scripted upstream test fixtures, not inference.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
from http.client import HTTPConnection
|
||||
import importlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser();p.add_argument('--runtime',type=Path,required=True);p.add_argument('--cuobjdump',type=Path,required=True);p.add_argument('--result',type=Path,required=True);a=p.parse_args()
|
||||
assert os.environ.get('ATHENA_BUILD_SANDBOX')=='basalt033' and os.environ.get('CUDA_VISIBLE_DEVICES')==''
|
||||
runtime=a.runtime;source=runtime/'source';sys.path.insert(0,str(source));checks={}
|
||||
ready=json.loads((runtime/'ready.json').read_text());assert ready['commit']=='2729e2288f59e01836ddd7fcc630810ada98995a' and ready['inference_performed'] is False
|
||||
assert subprocess.check_output(['git','-C',str(source),'rev-parse','HEAD'],text=True).strip()==ready['commit']
|
||||
artifacts={}
|
||||
for name,key,expected in [('basalt','binary_sha256',[120]),('basalt-vision','vision_binary_sha256',[86,120])]:
|
||||
binary=source/'bin'/name;actual=hashlib.sha256(binary.read_bytes()).hexdigest();assert actual==ready[key]
|
||||
result=subprocess.run([a.cuobjdump,'--list-elf',binary],capture_output=True,text=True,check=True)
|
||||
architectures=sorted({int(x) for x in re.findall(r'\.sm_(\d+)',result.stdout)})
|
||||
assert architectures==expected,(name,architectures)
|
||||
artifacts[name]={'sha256':actual,'bytes':binary.stat().st_size,'actual_elf_architectures':architectures}
|
||||
checks['binary_hashes_and_actual_fatbins']=True
|
||||
a.result.write_text(json.dumps({'scope':'isolated_no_gpu_candidate','phase':'artifact_checks_passed_interop_pending','artifacts':artifacts,'real_model_inference':False,'successful':False},indent=2)+'\n')
|
||||
import pypdf
|
||||
assert pypdf.__version__=='7.0.1';checks['pdf_import']=True
|
||||
import deploy.install_basalt as recipe
|
||||
video=recipe.video_libraries();assert video['available'] is True;checks['ffmpeg_abi']=True
|
||||
subprocess.run([sys.executable,'-m','pip','check'],check=True,capture_output=True)
|
||||
service:Any=importlib.import_module('serve.service');handler:Any=importlib.import_module('serve.handler')
|
||||
original_service=service.Service;original_handler=handler.make_handler
|
||||
from basalt_serve import install
|
||||
install(service,handler)
|
||||
SlowThinker=importlib.import_module('serve.tests.test_answer_now').SlowThinker
|
||||
ChatTemplate=importlib.import_module('serve.frontend').ChatTemplate
|
||||
ByteTokenizer=importlib.import_module('serve.util.text').ByteTokenizer
|
||||
from basalt_worker import BasaltWorker
|
||||
from endpoint import Endpoint
|
||||
from inference import Scheduler
|
||||
tok=ByteTokenizer();engine=SlowThinker(tok);svc=service.Service(engine,tok,ChatTemplate.from_file(source/'serve/chat_template.jinja'));svc.api_key='synthetic-native-key'
|
||||
native=handler.serve(svc,host='127.0.0.1',port=0)
|
||||
def http(port,path,body=None,token='synthetic-native-key',headers=None)->tuple[int,dict[str,str],Any]:
|
||||
conn=HTTPConnection('127.0.0.1',port,timeout=15);conn.request('GET' if body is None else 'POST',path,None if body is None else json.dumps(body),{'Content-Type':'application/json','Authorization':'Bearer '+token,**(headers or {})});response=conn.getresponse();raw=response.read();value=raw if (body or {}).get('stream') else json.loads(raw);result=(response.status,dict(response.headers),value);conn.close();return result
|
||||
ep=None
|
||||
try:
|
||||
status,_,props=http(native.server_port,'/props');assert status==200,(status,props)
|
||||
# /props takes version from engine.info; an upstream CPU mock is not the
|
||||
# compiled engine. Do not fabricate a real-engine version for this fixture.
|
||||
engine_version=getattr(engine,'info',{}).get('version');assert props['basalt']['version']==(str(engine_version) if engine_version else None)
|
||||
assert {'documents','logprobs','answer_now'}<=set(props['basalt']['capabilities']);checks['real_upstream_properties']=True
|
||||
assert http(native.server_port,'/v1/answer_now',{'request_id':'fixture'},token='incorrect')[0]==401;assert http(native.server_port,'/telemetry',token='incorrect')[0]==401;checks['native_control_and_telemetry_auth']=True
|
||||
profile={'id':'fixture','revision':1,'name':'Fixture','api_id':'basalt','kind':'chat','runnable':True,'blockers':[],'updated_at':1,'parameters':{'chat_runtime':'basalt','slots':1,'context':65536,'temperature':0,'top_p':1,'top_k':1}}
|
||||
class Worker:
|
||||
def __init__(self):self.profile=profile;self.state='ready';self.generation='fixture-generation';self.lock=threading.RLock();self.port=native.server_port;self.key='synthetic-native-key';self.process=SimpleNamespace(poll=lambda:None);self.backend_info=props['basalt'];self.sent=[]
|
||||
def status(self):return dict(runtime='basalt',state='ready',profile_id='fixture',profile_name='Fixture',generation=self.generation,error=None,gpus=[])
|
||||
def stop(self):pass
|
||||
def ensure(self,p):assert p['id']=='fixture' # never load or switch any engine
|
||||
def capabilities(self,p):return dict(installed=True,loaded=True,version='0.3.3',available=props['basalt']['capabilities'],capabilities=props['basalt']['capabilities'],session_affinity=True)
|
||||
def connect(self):return HTTPConnection('127.0.0.1',self.port,timeout=15),self.key
|
||||
answer_now=BasaltWorker.answer_now
|
||||
worker=Worker();token='synthetic-deck-token-not-for-production';credentials=SimpleNamespace(read=lambda:{'api_token_hash':hashlib.sha256(token.encode()).hexdigest()});profiles=SimpleNamespace(status=lambda:{'profiles':[profile]},reasoning_budget=lambda:None);images=SimpleNamespace(status=lambda:{'job':None},stop=lambda:None)
|
||||
with tempfile.TemporaryDirectory() as state:
|
||||
ep=Endpoint(state,profiles,worker,Scheduler(worker),images,credentials,1)
|
||||
with socket.socket() as sock:sock.bind(('127.0.0.1',0));port=sock.getsockname()[1]
|
||||
ep.configure({'port':port});ep.config['enabled_profiles']=['fixture'];ep.config['responses_compat']=True;ep.start()
|
||||
writer=pypdf.PdfWriter();page=writer.add_blank_page(width=200,height=100)
|
||||
from pypdf.generic import DictionaryObject,NameObject,DecodedStreamObject
|
||||
font=DictionaryObject({NameObject('/Type'):NameObject('/Font'),NameObject('/Subtype'):NameObject('/Type1'),NameObject('/BaseFont'):NameObject('/Helvetica')});page[NameObject('/Resources')]=DictionaryObject({NameObject('/Font'):DictionaryObject({NameObject('/F1'):font})});content=DecodedStreamObject();content.set_data(b'BT /F1 10 Tf 10 30 Td (SYNTHETIC_PDF_TEXT) Tj ET');page[NameObject('/Contents')]=content;pdf=io.BytesIO();writer.write(pdf)
|
||||
for responses in (False,True):
|
||||
engine.thinking.clear();out:dict[str,Any]={};alias='fixture-client-'+str(responses)
|
||||
part={'type':'input_file','filename':'fixture.pdf','file_data':'data:application/pdf;base64,'+base64.b64encode(pdf.getvalue()).decode(),'pages':'1'}
|
||||
body={'model':'basalt','stream':True,**({'input':[{'role':'user','content':[{'type':'input_text','text':'2+2?'},part]}],'max_output_tokens':20000} if responses else {'messages':[{'role':'user','content':[{'type':'text','text':'2+2?'},{'type':'file','file':{k:v for k,v in part.items() if k!='type'}}]}],'max_tokens':20000})}
|
||||
def run():out['reply']=http(port,'/v1/responses' if responses else '/v1/chat/completions',body,token,{'X-Client-Request-Id':alias,'X-Session-Id':'synthetic-session'})
|
||||
thread=threading.Thread(target=run,daemon=True);thread.start();assert engine.thinking.wait(8)
|
||||
status,_,control=http(port,'/v1/answer_now',{'request_id':alias},token);assert status==200 and control['state'] in ('thinking','prompt');thread.join(10);assert not thread.is_alive()
|
||||
code,headers,stream=out['reply'];assert code==200 and headers.get('X-Request-Id')
|
||||
events=[json.loads(line[5:].strip()) for line in stream.splitlines() if line.startswith(b'data:') and line[5:].strip()!=b'[DONE]']
|
||||
# A streaming response may emit one byte/token per JSON event. Compare the
|
||||
# assembled answer, never a purported contiguous string in raw SSE bytes.
|
||||
answer=''.join(e.get('delta','') for e in events if e.get('type')=='response.output_text.delta') if responses else ''.join(c.get('delta',{}).get('content') or '' for e in events for c in e.get('choices',[]))
|
||||
assert answer==SlowThinker.ANSWER,answer
|
||||
assert 'SYNTHETIC_PDF_TEXT' in tok.decode(engine.prompts[-1]);checks['deck_to_real_upstream_'+('responses' if responses else 'chat')]=True
|
||||
assert http(port,'/v1/answer_now',{'request_id':alias},token)[0]==409
|
||||
_,_,telemetry=http(native.server_port,'/telemetry');assert telemetry['metrics']['requests_completed_total']>=2;assert 'SYNTHETIC_PDF_TEXT' not in json.dumps(telemetry);checks['numeric_telemetry_preserved']=True
|
||||
ep.close();ep=None
|
||||
finally:
|
||||
if ep:ep.close()
|
||||
native.shutdown();native.server_close()
|
||||
service.Service=original_service;handler.make_handler=original_handler
|
||||
sys.modules.pop('serve.tests.test_answer_now',None)
|
||||
# Run upstream's own server fixtures: their engines and token probabilities are scripted.
|
||||
started=time.monotonic();suite=unittest.defaultTestLoader.discover(str(source/'serve/tests'),pattern='test_*.py',top_level_dir=str(source));result=unittest.TextTestRunner(verbosity=1).run(suite)
|
||||
value={'scope':'isolated_no_gpu_candidate','commit':ready['commit'],'artifacts':artifacts,'checks':checks,'upstream_mock_engine_version':engine_version,'ffmpeg':video,'upstream_tests':{'tests':result.testsRun,'failures':len(result.failures),'errors':len(result.errors),'skips':len(result.skipped),'seconds':round(time.monotonic()-started,3)},'real_model_inference':False,'nvdec_functional_test':False,'native_debian_restore':False,'successful':result.wasSuccessful() and all(checks.values())}
|
||||
a.result.write_text(json.dumps(value,indent=2)+'\n');print(json.dumps(value),flush=True);return 0 if value['successful'] else 1
|
||||
|
||||
|
||||
if __name__=='__main__':raise SystemExit(main())
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"manifest": "https://developer.download.nvidia.com/compute/cuda/redist/redistrib_13.0.0.json",
|
||||
"url": "https://developer.download.nvidia.com/compute/cuda/redist/cuda_cuobjdump/linux-x86_64/cuda_cuobjdump-linux-x86_64-13.0.39-archive.tar.xz",
|
||||
"version": "13.0.39",
|
||||
"archive_sha256": "2385804b0a628b98b3ed96a19c803143d5c2e2fcc5139f633450862cf7755d65",
|
||||
"archive_bytes": 244840,
|
||||
"member": "cuda_cuobjdump-linux-x86_64-13.0.39-archive/bin/cuobjdump",
|
||||
"purpose": "Independent fatbin inspection only; no driver or host installation."
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"sampled_at": 1794570078.5519354,
|
||||
"container_id": "788723c2fc2f4cae707147d1d339294546bce9ec6011c0fa16dbb2a13ad10976",
|
||||
"image": "sha256:0a358dd687a415faf26cea2d73160654fb9b2e56ad68c7013bef52bc166fed33",
|
||||
"started": "2026-11-09T16:02:55.751847414Z",
|
||||
"health": "healthy",
|
||||
"basalt_version": "0.3.0",
|
||||
"binary_matches_marker": true,
|
||||
"basalt_pids": [
|
||||
3537748
|
||||
],
|
||||
"gpu_pids": [
|
||||
3537711,
|
||||
3538175,
|
||||
3538223,
|
||||
3537748
|
||||
],
|
||||
"protected": {
|
||||
"profiles.json": "2d7602a18d08b0916ebd6ed794ff1246d9766aab02e26047e862602233bb775c",
|
||||
"endpoint.json": "98181e6b1d254f8507aee15e4135ebeaa7c409d6cca2edd030ff25b9f51b1a61",
|
||||
"audio-policy.json": "f48dedea718968c00c0647ca90c1402bdabac9ce600dbeddc495817680527a3f",
|
||||
"cpu-partition.json": "836a97564094f95850c6fa0fd3776e164e7aeff2bf4bb8a61d43ea4182cfaaec",
|
||||
"reasoning-budget.json": "4884a379adf2f888415041b81ef55a01a2c22ef7a41ca1554460f410bec5cf0c"
|
||||
},
|
||||
"same_container_image_start": true,
|
||||
"protected_unchanged": true,
|
||||
"original_text_pid_preserved": true,
|
||||
"sandbox": {
|
||||
"container_absent": true,
|
||||
"running": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"scope": "isolated_no_gpu_candidate",
|
||||
"commit": "2729e2288f59e01836ddd7fcc630810ada98995a",
|
||||
"artifacts": {
|
||||
"basalt": {
|
||||
"sha256": "9e89333cd2f12eee69a5e1535433631155ae92dc089774ad6c8f99e9b62c0c46",
|
||||
"bytes": 154288304,
|
||||
"actual_elf_architectures": [
|
||||
120
|
||||
]
|
||||
},
|
||||
"basalt-vision": {
|
||||
"sha256": "e75b4f529acf7623c8fede68847052c097a325ca9f808d88cea4c061ed15b798",
|
||||
"bytes": 915648,
|
||||
"actual_elf_architectures": [
|
||||
86,
|
||||
120
|
||||
]
|
||||
}
|
||||
},
|
||||
"checks": {
|
||||
"binary_hashes_and_actual_fatbins": true,
|
||||
"pdf_import": true,
|
||||
"ffmpeg_abi": true,
|
||||
"real_upstream_properties": true,
|
||||
"native_control_and_telemetry_auth": true,
|
||||
"deck_to_real_upstream_chat": true,
|
||||
"deck_to_real_upstream_responses": true,
|
||||
"numeric_telemetry_preserved": true
|
||||
},
|
||||
"upstream_mock_engine_version": null,
|
||||
"ffmpeg": {
|
||||
"available": true,
|
||||
"ffmpeg_major": 6,
|
||||
"libraries": {
|
||||
"avcodec": "libavcodec.so.60",
|
||||
"avformat": "libavformat.so.60",
|
||||
"avutil": "libavutil.so.58",
|
||||
"swscale": "libswscale.so.7"
|
||||
},
|
||||
"abi_only": true
|
||||
},
|
||||
"upstream_tests": {
|
||||
"tests": 1102,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skips": 6,
|
||||
"seconds": 479.532
|
||||
},
|
||||
"real_model_inference": false,
|
||||
"nvdec_functional_test": false,
|
||||
"native_debian_restore": false,
|
||||
"successful": true
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"deck_sha256": {
|
||||
"api_compat.py": "729eef3614688fb06ef2f64409c31be7672c0f92fa66c84887e3262c75341cae",
|
||||
"basalt_runtime.py": "e3078aa2a7aa2052a9ffcbcab056a4d134ed156e427ee2cef0679a91e935e701",
|
||||
"basalt_serve.py": "03863add9614e9cc480171a45945a660ac49a21d12d8f33059971bb9e71776cb",
|
||||
"basalt_sources.json": "e2c0ca28dce89aea30b7ba0be4d05641687938fe9b08e485830c4635bb1ae30f",
|
||||
"basalt_telemetry.py": "e6585bf0f9b102dc579704f790985707746b6dab4ffd37233153f0c1064d2054",
|
||||
"basalt_tuning.py": "f2585dab9581ce8c8b3712c4ee9f9a98d5b58d41ce11f9f8ab5b17f429e0dfdf",
|
||||
"basalt_worker.py": "0df07b59c85136bacaf95a87095867796f1d124a8df895d3a92406dc4057e9b7",
|
||||
"chat_control.py": "5efad2c742ba893e22d926fe38cfe31c16eb0e35b1accd2556899ad348bc7923",
|
||||
"chat_media.py": "7d3e6954cd6f4140a97b3991edeb266c5cac19cb781cb9927647c0f21992c06c",
|
||||
"deploy/install_basalt.py": "7e81efe44224707c5b3b5417382381113b263bf6532060f8c80b4e1eed4748e5",
|
||||
"endpoint.py": "22614fce51e306a3e312485fbb103863ca702dfa6361280d84beb4f4fa091684",
|
||||
"responses_compat.py": "08e2fdaeb5b1b670a390dc8f2330ebc0825410d0b17d911e9c9f3f602366640f",
|
||||
"strata_worker.py": "b20b274c97c34641f2c2a0837207a3e6d371098ee5c74f084ce053039b76db3b"
|
||||
},
|
||||
"check_sha256": "a94b840480f007e92cb03230b63ff667f6a431304554b059e03a6db95d403517",
|
||||
"cuobjdump": {
|
||||
"manifest": "https://developer.download.nvidia.com/compute/cuda/redist/redistrib_13.0.0.json",
|
||||
"url": "https://developer.download.nvidia.com/compute/cuda/redist/cuda_cuobjdump/linux-x86_64/cuda_cuobjdump-linux-x86_64-13.0.39-archive.tar.xz",
|
||||
"version": "13.0.39",
|
||||
"archive_sha256": "2385804b0a628b98b3ed96a19c803143d5c2e2fcc5139f633450862cf7755d65",
|
||||
"archive_bytes": 244840,
|
||||
"member": "cuda_cuobjdump-linux-x86_64-13.0.39-archive/bin/cuobjdump",
|
||||
"purpose": "Independent fatbin inspection only; no driver or host installation."
|
||||
},
|
||||
"checker_type_only_update": {
|
||||
"executed_source_sha256": "a94b840480f007e92cb03230b63ff667f6a431304554b059e03a6db95d403517",
|
||||
"current_source_sha256": "1725c41ef6f1c778690a05755a8b264c6a274c42ff2ec08974d1f5f254245872",
|
||||
"type_annotations_only": true,
|
||||
"semantic_bytecode_equal": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
cmake==3.31.6
|
||||
Jinja2==3.1.6
|
||||
MarkupSafe==3.0.3
|
||||
ninja==1.11.1.4
|
||||
numpy==2.5.3
|
||||
pillow==12.3.0
|
||||
pip==24.0
|
||||
psutil==7.2.2
|
||||
pypdf==7.0.1
|
||||
PyYAML==6.0.3
|
||||
regex==2026.9.10
|
||||
tqdm==4.70.1
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"base_commit": "584a884cc909f17be06314751fe24a78a8160077",
|
||||
"root_suite_source_sha256": {
|
||||
"api_compat.py": "729eef3614688fb06ef2f64409c31be7672c0f92fa66c84887e3262c75341cae",
|
||||
"basalt_runtime.py": "e3078aa2a7aa2052a9ffcbcab056a4d134ed156e427ee2cef0679a91e935e701",
|
||||
"basalt_serve.py": "03863add9614e9cc480171a45945a660ac49a21d12d8f33059971bb9e71776cb",
|
||||
"basalt_sources.json": "e2c0ca28dce89aea30b7ba0be4d05641687938fe9b08e485830c4635bb1ae30f",
|
||||
"basalt_tuning.py": "f2585dab9581ce8c8b3712c4ee9f9a98d5b58d41ce11f9f8ab5b17f429e0dfdf",
|
||||
"basalt_worker.py": "0df07b59c85136bacaf95a87095867796f1d124a8df895d3a92406dc4057e9b7",
|
||||
"chat-test-ui.js": "cb299f33c527535ebdbd9f404506f32ca1b47fd4d0a4a1cba815a7c32cd7773b",
|
||||
"chat_control.py": "5efad2c742ba893e22d926fe38cfe31c16eb0e35b1accd2556899ad348bc7923",
|
||||
"chat_media.py": "7d3e6954cd6f4140a97b3991edeb266c5cac19cb781cb9927647c0f21992c06c",
|
||||
"chat_test.py": "02754ae25f8f7e6ad14785f7e2102dbb818f4a5a118abf13b47bfbba779325ab",
|
||||
"deploy/install.py": "e342ddfdf9fa77492c568342e68024e5864e09e68ab3c77b5ca61390b3f99ad5",
|
||||
"deploy/install_basalt.py": "7e81efe44224707c5b3b5417382381113b263bf6532060f8c80b4e1eed4748e5",
|
||||
"endpoint.py": "22614fce51e306a3e312485fbb103863ca702dfa6361280d84beb4f4fa091684",
|
||||
"responses_compat.py": "08e2fdaeb5b1b670a390dc8f2330ebc0825410d0b17d911e9c9f3f602366640f",
|
||||
"server.py": "c73206dbac9ff21cdfb266b67d678a5e4aec79fa92ffbb918f8273df5c01478b",
|
||||
"strata_worker.py": "b20b274c97c34641f2c2a0837207a3e6d371098ee5c74f084ce053039b76db3b",
|
||||
"test_basalt.py": "7fbff965897e488a1a51e605a4a563b8cedb7842b1b802015243fff1e0aaf9bc",
|
||||
"test_basalt033_integration.py": "eac5d60325a41527c42ca4bd80eca2f56fafcf8477517920c79ee91551e36149",
|
||||
"test_basalt_tuning.py": "7bf7c8b1f5f42170a1e93b90bd1b8af1c1ff87f6b837ec94e6108288ee96da4a",
|
||||
"test_chat_control.py": "fa5f45efb07353a49896323094ac6db2e64ff5fd71c8c73241c321d1671c18c6",
|
||||
"test_chat_media.py": "42f9c39a52ad6f138be5d7c64b47cce209fc6e5aa01ef8dbf20b31a758766c37",
|
||||
"test_inference.py": "5918f4b7ac501479711dd0364bf7aa8c530578bec204058afcedde6911dfd173",
|
||||
"test_legacy_cleanup.py": "b3590865f87f0a9bf654663561f84fb5c174cdc74e2ef4108cbc1b40d914f11d",
|
||||
"test_server.py": "973981dc80776937879ca354a3f440d3f999751551bd3755ed924370d1637925",
|
||||
"test_stimmatelier_proxy.py": "9ae213922a121096c0edbea565f17a65fb183744f2943370229bd8babfbade39"
|
||||
},
|
||||
"maintenance_source_sha256": {
|
||||
"docs/maintenance/basalt-033-staged-2026-11-13/acceptance.py": "8b999c7b3d8338898bfbf4c8fdeef11a9f58b4eaa8978e821cd8d46ff8c44ee9",
|
||||
"docs/maintenance/basalt-033-staged-2026-11-13/build_host.py": "a6998be89662f8cd5d1c70bd69725ec2ede9d79cf372f8b8698d2dde0710fa0d",
|
||||
"docs/maintenance/basalt-033-staged-2026-11-13/check_upstream.py": "1725c41ef6f1c778690a05755a8b264c6a274c42ff2ec08974d1f5f254245872",
|
||||
"docs/maintenance/basalt-033-staged-2026-11-13/python-lock.txt": "2dcb15488a68e15eaa3c24c350887a536dc1dfce3919009f5c9c173883bd575c",
|
||||
"docs/maintenance/basalt-033-staged-2026-11-13/test_verify_host.py": "6ccfbc1fe099e62249a705190374abe60b510c8cda2616f3f46990d0a86f6612",
|
||||
"docs/maintenance/basalt-033-staged-2026-11-13/ui_mock.py": "3eb0b859eb17abc4f394dda008f025a4345e1ed32080d151c834e4cf133b9241",
|
||||
"docs/maintenance/basalt-033-staged-2026-11-13/verify_host.py": "4d18e5ce64ab5aca61c451b14397ae9ac83eb64ad08c16d71ffe2a5f3194ed99",
|
||||
"docs/maintenance/basalt-033-staged-2026-11-13/verify_offline.py": "6013b0dcd42ed40dae33cb47f4e7f979a1d22e48b1bba36cc62e0f6be5771313"
|
||||
},
|
||||
"evidence_sha256": {
|
||||
"build-result.json": "03b8442484d07658f10417e1d2629979f961568d0058941e5fa9d441154a58f5",
|
||||
"native-checks.json": "f12b385add37782e2fb3de7a029f5730425907659cad5952df2fa312da5315b4",
|
||||
"native-inputs.json": "4ba9a4294f614807fe702e4847b007a34ecce15d824d6a13e1bb100af44bdde3",
|
||||
"live-preservation.json": "54234e893b913a06fede12398a1e1808419a0b8d1b7b23c61de06b68ad035828"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""NAS-only unit tests for the operator helper; Docker is never executed."""
|
||||
import ast
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
|
||||
|
||||
class HostVerifierTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tree=ast.parse(Path(__file__).with_name('verify_host.py').read_text())
|
||||
self.main=next(n for n in self.tree.body if isinstance(n,ast.FunctionDef) and n.name=='main')
|
||||
self.assignment=next(n for n in self.main.body if isinstance(n,ast.Assign) and any(isinstance(t,ast.Name) and t.id=='command' for t in n.targets))
|
||||
self.block=next(n for n in self.main.body if isinstance(n,ast.Try))
|
||||
|
||||
def command(self,folder):
|
||||
namespace={'ROOT':folder,'folder':folder,'container_name':'synthetic-owned-check','LABEL':'synthetic-verifier','status':{'borrowed_cuda_read_only':str(folder/'cuda'),'image':'synthetic-image-only'}}
|
||||
exec(compile(ast.Module(body=[self.assignment],type_ignores=[]),'<actual-helper-command>','exec'),namespace)
|
||||
return namespace['command']
|
||||
|
||||
def test_explicit_lifecycle_does_not_mix_auto_and_manual_removal(self):
|
||||
self.assertNotIn('--rm',self.command(Path('synthetic-root')))
|
||||
|
||||
def test_bounded_budget_includes_setup_and_completed_suite(self):
|
||||
timeouts=[ast.literal_eval(k.value) for n in ast.walk(self.block) if isinstance(n,ast.Call) for k in n.keywords if k.arg=='timeout']
|
||||
self.assertEqual(len(timeouts),1)
|
||||
observed=json.loads(Path(__file__).with_name('native-checks.json').read_text())['upstream_tests']['seconds']
|
||||
self.assertGreaterEqual(timeouts[0],observed+60)
|
||||
self.assertLessEqual(timeouts[0],900)
|
||||
|
||||
def exercise(self,*,timeout=False,foreign=False):
|
||||
with tempfile.TemporaryDirectory(prefix='verifier-unit-') as name:
|
||||
folder=Path(name);command=self.command(folder);state={'exists':False,'running':False};calls=[]
|
||||
def run(args,**kwargs):
|
||||
calls.append(list(args))
|
||||
if args==command:
|
||||
state.update(exists=True,running=timeout)
|
||||
if timeout:raise subprocess.TimeoutExpired(args,kwargs['timeout'])
|
||||
if '--rm' in args:state['exists']=False
|
||||
return subprocess.CompletedProcess(args,0)
|
||||
if args[:2]==['docker','inspect']:
|
||||
value={'Id':'synthetic-owned-id','Config':{'Labels':{'athena-deck.build':'foreign' if foreign else 'synthetic-verifier'}},'State':{'Running':state['running']}}
|
||||
return subprocess.CompletedProcess(args,0 if state['exists'] else 1,stdout=json.dumps([value]) if state['exists'] else '')
|
||||
if args[:2]==['docker','stop']:
|
||||
state['running']=False
|
||||
if '--rm' in command:state['exists']=False
|
||||
return subprocess.CompletedProcess(args,0)
|
||||
if args[:2]==['docker','rm']:
|
||||
if not state['exists']:raise subprocess.CalledProcessError(1,args)
|
||||
state['exists']=False
|
||||
return subprocess.CompletedProcess(args,0)
|
||||
raise AssertionError('unexpected operator action')
|
||||
namespace={'folder':folder,'command':command,'container_name':'synthetic-owned-check','LABEL':'synthetic-verifier','json':json,'subprocess':SimpleNamespace(run=run,STDOUT=subprocess.STDOUT,DEVNULL=subprocess.DEVNULL)}
|
||||
error=None
|
||||
try:
|
||||
with contextlib.redirect_stdout(io.StringIO()):exec(compile(ast.Module(body=[self.block],type_ignores=[]),'<actual-helper-lifecycle>','exec'),namespace)
|
||||
except BaseException as exc:error=exc
|
||||
return state,calls,error
|
||||
|
||||
def test_timeout_is_not_masked_by_double_removal(self):
|
||||
state,calls,error=self.exercise(timeout=True)
|
||||
self.assertIsInstance(error,subprocess.TimeoutExpired)
|
||||
self.assertFalse(state['exists'])
|
||||
self.assertEqual(sum(c[:2]==['docker','rm'] for c in calls),1)
|
||||
|
||||
def test_success_removes_owned_container(self):
|
||||
state,calls,error=self.exercise()
|
||||
self.assertIsNone(error)
|
||||
self.assertFalse(state['exists'])
|
||||
|
||||
def test_foreign_label_is_never_stopped_or_removed(self):
|
||||
state,calls,error=self.exercise(timeout=True,foreign=True)
|
||||
self.assertIsInstance(error,AssertionError)
|
||||
self.assertTrue(state['exists'])
|
||||
self.assertFalse(any(c[:2] in (['docker','stop'],['docker','rm']) for c in calls))
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
"""NAS development only: bounded loopback UI fixture; never calls a real backend."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
|
||||
from urllib.parse import urlsplit,parse_qs
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[3]
|
||||
sys.path.insert(0,str(ROOT))
|
||||
from chat_media import normalize_messages
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser();p.add_argument('--port',type=int,default=0);p.add_argument('--duration',type=int,default=900);a=p.parse_args()
|
||||
assert 1<=a.duration<=1800
|
||||
profile=dict(id='fixture',api_id='fixture',name='Basalt · synthetisch',kind='chat',runnable=True,blockers=[],parameters=dict(chat_runtime='basalt',context=262144,slots=1,vision_projector='fixture'))
|
||||
legacy=dict(profile,id='legacy',api_id='legacy',name='Alte Laufzeit · synthetisch',parameters=dict(chat_runtime='llama',context=8192,slots=1))
|
||||
state={'job':None,'calls':[],'uploads':[]}
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self,format,*args):pass
|
||||
def send(self,value,status=200,mime='application/json'):
|
||||
raw=value if isinstance(value,bytes) else json.dumps(value,ensure_ascii=False).encode();self.send_response(status);self.send_header('Content-Type',mime);self.send_header('Content-Length',str(len(raw)));self.send_header('Cache-Control','no-store');self.end_headers();self.wfile.write(raw)
|
||||
def do_GET(self):
|
||||
q=urlsplit(self.path);path=q.path
|
||||
if path=='/':return self.send(b'<!doctype html><meta charset="utf-8"><title>Deck 0.3.3 UI mock</title><link rel="stylesheet" href="/style.css"><main><p role="alert"><strong>MOCK ONLY: Keine Verbindung zu Athena, keine Modellinferenz.</strong></p><div id="fixture-root"></div></main><script src="/chat-test-ui.js"></script><script>window.fixtureErrors=[];window.addEventListener("error",e=>fixtureErrors.push(e.message));document.getElementById("fixture-root").innerHTML=ChatTestUI.html();ChatTestUI.bind();</script>',mime='text/html; charset=utf-8')
|
||||
if path in ('/chat-test-ui.js','/style.css'):return self.send((ROOT/path[1:]).read_bytes(),mime='text/javascript' if path.endswith('.js') else 'text/css')
|
||||
if path=='/fixture/state':return self.send(state)
|
||||
if path=='/api/v1/profiles':return self.send({'profiles':[profile,legacy]})
|
||||
if path=='/api/v1/hardware':return self.send({'gpus':[]})
|
||||
if path=='/api/v1/chat-tests/capabilities':
|
||||
old=parse_qs(q.query).get('profile_id',[''])[0]=='legacy';features=[] if old else ['answer_now','documents','video','logprobs']
|
||||
return self.send(dict(runtime='llama' if old else 'basalt',version=None if old else '0.3.3',installed=True,loaded=not old,available=features,capabilities=features,session_affinity=not old))
|
||||
if path=='/api/v1/chat-tests':return self.send(dict(job=state['job'],worker=dict(runtime='basalt',state='ready',phase='Synthetischer Worker',profile_id='fixture',profile_name='UI fixture',generation='fixture',memory_plan=dict(runtime='basalt',context=262144,slots=1,kv='int8',experts='resident',gpus=[])),scheduler=dict(active_requests=int(bool(state['job'] and state['job']['state']=='running')),waiting_requests=0,switching=False)))
|
||||
return self.send({'error':'Keine Fixture-Route.'},404)
|
||||
def do_POST(self):
|
||||
length=int(self.headers.get('Content-Length',0))
|
||||
if not 0<length<=64*1024**2:return self.send({'error':'Fixture-Limit.'},413)
|
||||
data=json.loads(self.rfile.read(length));state['calls'].append({'path':self.path,'csrf_header':self.headers.get('X-Athena-Deck')})
|
||||
if self.path=='/api/v1/chat-tests/start':
|
||||
try:_,info=normalize_messages(data['messages'],profile,('documents','video'))
|
||||
except ValueError as exc:return self.send({'error':str(exc)},400)
|
||||
state['uploads'].append(data);job=dict(id='fixture-job-'+str(len(state['uploads'])),state='running',phase='Synthetisches Denken',profile_id='fixture',started_at=time.time(),answer='',reasoning='Synthetisches Denken',request_id='fixture-request',can_answer_now=True,answer_now_requested=False,timings={},usage={},logprobs=[]);state['job']=job;return self.send(job)
|
||||
if self.path in ('/api/v1/chat-tests/answer-now','/api/v1/chat-tests/cancel'):
|
||||
job=state['job']
|
||||
if not job or job['state']!='running' or data.get('job_id')!=job['id']:return self.send({'error':'Staler Testauftrag.'},409)
|
||||
job.update(state='complete' if self.path.endswith('answer-now') else 'cancelled',phase='Synthetisch beendet',finished_at=time.time(),can_answer_now=False,answer='Synthetische Antwort',logprobs=[{'token':'synthetisch','logprob':-.1,'top_logprobs':[]}]);return self.send({'state':'thinking'})
|
||||
if self.path=='/api/v1/chat-tests/unload':return self.send({'mock_only':True})
|
||||
return self.send({'error':'Keine Fixture-Route.'},404)
|
||||
server=ThreadingHTTPServer(('127.0.0.1',a.port),Handler);server.timeout=.5
|
||||
print(json.dumps({'mock_only':True,'url':'http://127.0.0.1:'+str(server.server_port),'duration':a.duration}),flush=True)
|
||||
deadline=time.monotonic()+a.duration
|
||||
try:
|
||||
while time.monotonic()<deadline:server.handle_request()
|
||||
finally:server.server_close()
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"scope": "built_runtime_and_implemented_not_activated",
|
||||
"root_index_suite": {
|
||||
"scope": "synthetic_root_suite",
|
||||
"tests": 827,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skips": 0,
|
||||
"expected_failures": 0,
|
||||
"unexpected_successes": 0,
|
||||
"blocked_io": [],
|
||||
"seconds": 117.002,
|
||||
"successful": true,
|
||||
"model_inference": false,
|
||||
"process_exit": 0,
|
||||
"process_id": "proc_72ae815b8b18"
|
||||
},
|
||||
"upstream_cpu_mock_suite": {
|
||||
"tests": 1102,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skips": 6,
|
||||
"seconds": 479.532
|
||||
},
|
||||
"upstream_gates": {
|
||||
"binary_hashes_and_actual_fatbins": true,
|
||||
"pdf_import": true,
|
||||
"ffmpeg_abi": true,
|
||||
"real_upstream_properties": true,
|
||||
"native_control_and_telemetry_auth": true,
|
||||
"deck_to_real_upstream_chat": true,
|
||||
"deck_to_real_upstream_responses": true,
|
||||
"numeric_telemetry_preserved": true
|
||||
},
|
||||
"browser_mock": {
|
||||
"passed": 11,
|
||||
"total": 11,
|
||||
"source": "Recorded Browser Use checks in this task session; synthetic backend, real new UI",
|
||||
"real_model": false
|
||||
},
|
||||
"operator_helper_unit": {
|
||||
"tests": 5,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"initial_red_failures": 3,
|
||||
"docker_executed": false
|
||||
},
|
||||
"native_controller_attempt3": {
|
||||
"successful": false,
|
||||
"native_result_successful": true,
|
||||
"failure": "480-second overall timeout followed by auto/manual-remove race",
|
||||
"sandbox_absence_read_back": true,
|
||||
"local_fix": "explicit manual lifecycle and 900-second overall bound",
|
||||
"fixed_controller_rerun_on_athena": false
|
||||
},
|
||||
"acceptance_self_test": {
|
||||
"synthetic_fixtures": {
|
||||
"png": 168,
|
||||
"pdf": 588,
|
||||
"video": 1761
|
||||
},
|
||||
"credentials_resolved": false,
|
||||
"network_requests": 0,
|
||||
"model_inference": false
|
||||
},
|
||||
"acceptance_no_go_exit": 2,
|
||||
"video_fixture_metadata": {
|
||||
"programs": [],
|
||||
"stream_groups": [],
|
||||
"streams": [
|
||||
{
|
||||
"codec_name": "h264",
|
||||
"width": 64,
|
||||
"height": 64
|
||||
}
|
||||
],
|
||||
"format": {
|
||||
"duration": "2.000000"
|
||||
}
|
||||
},
|
||||
"production_preserved": true,
|
||||
"real_model_inference": false,
|
||||
"nvdec_functional_test": false,
|
||||
"native_debian_restore": false,
|
||||
"root_code_hashes_still_match_tested_index": true
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""ATHENA HOST only: verify the owned candidate with no GPU/production mounts."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import urllib.request
|
||||
|
||||
ROOT=Path('/opt/athena-deck-dev/basalt-033-candidate-2729e2288f59')
|
||||
NAME='athena-basalt033-check-20261113'
|
||||
LABEL='basalt033-check-20261113'
|
||||
FILES={'api_compat.py','basalt_runtime.py','basalt_serve.py','basalt_sources.json','basalt_worker.py','basalt_tuning.py','basalt_telemetry.py','chat_media.py','chat_control.py','endpoint.py','responses_compat.py','strata_worker.py','deploy/install_basalt.py'}
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser();parser.add_argument('--attempt',type=int,default=1);args=parser.parse_args();assert 1<=args.attempt<=3
|
||||
container_name=NAME+'-'+str(args.attempt)
|
||||
bundle=json.load(sys.stdin);assert set(bundle['files'])==FILES
|
||||
status=json.loads((ROOT/'build-status.json').read_text());assert status['phase']=='built_no_model_test' and status['owned_container_removed'] is True
|
||||
folder=ROOT/('verification-'+str(args.attempt));assert not folder.exists();folder.mkdir(mode=0o700);os.chown(folder,65534,65534)
|
||||
for name in ('deck','deck/deploy','tools','out','tmp'):
|
||||
p=folder/name;p.mkdir(mode=0o700);os.chown(p,65534,65534)
|
||||
for name,text in {**{'deck/'+k:v for k,v in bundle['files'].items()},'check_upstream.py':bundle['check']}.items():
|
||||
p=folder/name;p.write_text(text);p.chmod(0o600);os.chown(p,65534,65534)
|
||||
lock=bundle['cuobjdump'];assert lock['archive_sha256']=='2385804b0a628b98b3ed96a19c803143d5c2e2fcc5139f633450862cf7755d65' and lock['url'].startswith('https://developer.download.nvidia.com/compute/cuda/redist/')
|
||||
with urllib.request.urlopen(lock['url'],timeout=60) as response:archive=response.read(1024**2)
|
||||
assert len(archive)==lock['archive_bytes'] and hashlib.sha256(archive).hexdigest()==lock['archive_sha256']
|
||||
with tarfile.open(fileobj=io.BytesIO(archive),mode='r:xz') as tar:
|
||||
member=tar.getmember(lock['member']);assert member.isfile() and member.size<16*1024**2
|
||||
stream=tar.extractfile(member);assert stream is not None
|
||||
with stream:binary=stream.read()
|
||||
p=folder/'tools/cuobjdump';p.write_bytes(binary);p.chmod(0o700);os.chown(p,65534,65534)
|
||||
(folder/'inputs.json').write_text(json.dumps({'deck_sha256':{n:hashlib.sha256(t.encode()).hexdigest() for n,t in bundle['files'].items()},'check_sha256':hashlib.sha256(bundle['check'].encode()).hexdigest(),'cuobjdump':lock},indent=2)+'\n')
|
||||
command=['docker','run','--pull=never','--name',container_name,'--label','athena-deck.build='+LABEL,'--runtime=runc','--network=none','--read-only','--user=65534:65534','--cpus=1','--memory=4g','--memory-swap=4g','--pids-limit=1024','--cap-drop=ALL','--security-opt=no-new-privileges',
|
||||
'--mount',f'type=bind,src={ROOT}/runtime,dst=/candidate/runtime,readonly','--mount',f'type=bind,src={folder}/deck,dst=/probe/deck,readonly','--mount',f'type=bind,src={folder}/tools,dst=/probe/tools,readonly','--mount',f'type=bind,src={folder}/check_upstream.py,dst=/probe/check_upstream.py,readonly','--mount',f'type=bind,src={folder}/out,dst=/out','--mount',f'type=bind,src={folder}/tmp,dst=/tmp','--mount',f'type=bind,src={status["borrowed_cuda_read_only"]},dst=/toolchain,readonly',
|
||||
'-e','HOME=/tmp','-e','TMPDIR=/tmp','-e','NVIDIA_VISIBLE_DEVICES=void','-e','CUDA_VISIBLE_DEVICES=','-e','PYTHONDONTWRITEBYTECODE=1','-e','OPENBLAS_NUM_THREADS=1','-e','OMP_NUM_THREADS=1','-e','ATHENA_BUILD_SANDBOX=basalt033','-e','PYTHONPATH=/probe/deck:/app','-e','LD_LIBRARY_PATH=/toolchain/lib64:/toolchain/lib','--entrypoint','/candidate/runtime/venv/bin/python',status['image'],'-B','/probe/check_upstream.py','--runtime','/candidate/runtime','--cuobjdump','/probe/tools/cuobjdump','--result','/out/native-checks.json']
|
||||
try:
|
||||
with (folder/'check.log').open('w') as log:result=subprocess.run(command,stdout=log,stderr=subprocess.STDOUT,timeout=900)
|
||||
finally:
|
||||
leftover=subprocess.run(['docker','inspect',container_name],capture_output=True,text=True)
|
||||
if leftover.returncode==0:
|
||||
c=json.loads(leftover.stdout)[0];assert c['Config']['Labels'].get('athena-deck.build')==LABEL
|
||||
if c['State']['Running']:subprocess.run(['docker','stop','--time','10',container_name],check=True,stdout=subprocess.DEVNULL)
|
||||
subprocess.run(['docker','rm',container_name],check=True,stdout=subprocess.DEVNULL)
|
||||
print(json.dumps({'exit':result.returncode,'log':str(folder/'check.log'),'result':str(folder/'out/native-checks.json')}),flush=True)
|
||||
return result.returncode
|
||||
|
||||
|
||||
if __name__=='__main__':raise SystemExit(main())
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""NAS/project test Python only: synthetic root suite with explicit I/O guards.
|
||||
|
||||
No production, VPN access, remote SSH, external sockets or model acceptance.
|
||||
Can run against a staged-index export using --root.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import unittest
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,default=Path.cwd());p.add_argument('--result',type=Path,required=True);a=p.parse_args()
|
||||
root=a.root.absolute();scratch=Path(os.environ['TMPDIR']).absolute();profile=Path('/opt/data/profiles/athena-deck')
|
||||
blocked=[]
|
||||
def deny(label):
|
||||
blocked.append(label);raise PermissionError('Offline test guard: '+label)
|
||||
def path_check(value):
|
||||
if not isinstance(value,(str,bytes,os.PathLike)):return
|
||||
value=os.fsdecode(value);parts=Path(value).parts
|
||||
if 'vpn.auth' in parts or 'vpn' in parts or any(x in parts for x in ('OpenVPN-KIT','GluetunVPN')):deny('prohibited path')
|
||||
path=os.path.abspath(value)
|
||||
|
||||
if path.startswith(('/etc/wireguard/','/opt/athena-deck-dev/runtime/','/var/lib/deck/','/mnt/nvme-storage/')):deny('production/private path')
|
||||
if path.startswith('/opt/data/profiles/') and not path.startswith(str(profile)+'/'):deny('other profile path')
|
||||
def audit(event,args):
|
||||
if event in ('open','os.listdir','os.scandir','os.remove','os.rmdir','os.mkdir','os.chmod') and args:path_check(args[0])
|
||||
elif event in ('os.rename','os.link','os.symlink'):
|
||||
for value in args[:2]:path_check(value)
|
||||
elif event=='socket.connect':
|
||||
address=args[1]
|
||||
if isinstance(address,tuple):
|
||||
if address[0] not in ('127.0.0.1','::1') or address[1] in (8108,8120):deny('non-fixture socket')
|
||||
elif isinstance(address,str) and not os.path.abspath(address).startswith(str(scratch)+'/'):deny('non-fixture Unix socket')
|
||||
elif event=='socket.getaddrinfo' and args[0] not in (None,'localhost','127.0.0.1','::1'):deny('external name lookup')
|
||||
elif event=='subprocess.Popen':
|
||||
argv=args[1]
|
||||
if isinstance(argv,(tuple,list)):
|
||||
if argv and Path(str(argv[0])).name in ('ssh','athena-ssh','docker','podman'):deny('remote/container command')
|
||||
for value in argv:
|
||||
if isinstance(value,str) and ('/' in value or value=='vpn.auth') and not '\n' in value:path_check(value)
|
||||
sys.addaudithook(audit);sys.path.insert(0,str(root));os.chdir(root)
|
||||
started=time.monotonic();suite=unittest.defaultTestLoader.discover(str(root),pattern='test_*.py',top_level_dir=str(root));result=unittest.TextTestRunner(verbosity=1).run(suite)
|
||||
value={'scope':'synthetic_root_suite','tests':result.testsRun,'failures':len(result.failures),'errors':len(result.errors),'skips':len(result.skipped),'expected_failures':len(result.expectedFailures),'unexpected_successes':len(result.unexpectedSuccesses),'blocked_io':blocked,'seconds':round(time.monotonic()-started,3),'successful':result.wasSuccessful() and not blocked,'model_inference':False}
|
||||
a.result.parent.mkdir(parents=True,exist_ok=True);a.result.write_text(json.dumps(value,indent=2)+'\n');print(json.dumps(value),flush=True)
|
||||
return 0 if value['successful'] else 1
|
||||
|
||||
|
||||
if __name__=='__main__':raise SystemExit(main())
|
||||
+75
-35
@@ -13,12 +13,15 @@ import threading
|
||||
import time
|
||||
from urllib.parse import urlsplit,parse_qs
|
||||
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
|
||||
from typing import Any,cast
|
||||
from api_compat import normalize_chat,CompatibilityError,apply_reasoning_budget
|
||||
from profiles import generation_parameters
|
||||
from inference import InferenceError
|
||||
import logging
|
||||
from stt import read_upload
|
||||
from responses_compat import translate as translate_responses,ResponsesError
|
||||
from chat_media import normalize_messages,profile_capabilities,MediaError
|
||||
from chat_control import ChatControls,ControlError,session_id,thinking,immediate_answer
|
||||
|
||||
MAX_JSON_REQUEST_BYTES = 64 * 1024 * 1024
|
||||
|
||||
@@ -141,6 +144,7 @@ class Endpoint:
|
||||
def __init__(self,root,profiles,worker,scheduler,images,credentials,management_port):
|
||||
self.root=Path(root);self.profiles=profiles;self.worker=worker;self.scheduler=scheduler;self.images=images;self.tts=None;self.voxcpm=None;self.embeddings=None;self.stt=None;self.music=None;self.video=None;self.credentials=credentials
|
||||
self.management_port=management_port;self.lock=threading.RLock();self.http=None;self.thread=None;self.state='stopped';self.error=None;self.inflight=0
|
||||
self.chat_controls=ChatControls()
|
||||
self.allowed_ports=[int(p) for p in os.environ.get('DECK_API_PORTS','').split(',') if p]
|
||||
self.config=dict(port=self.allowed_ports[0] if self.allowed_ports else 8120,enabled_profiles=[],autostart=False,responses_compat=False,tts_text_enhancer=False)
|
||||
path=self.root/'endpoint.json'
|
||||
@@ -153,7 +157,7 @@ class Endpoint:
|
||||
def persist(self):
|
||||
self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
|
||||
path=self.root/'endpoint.tmp';path.write_text(json.dumps(self.config));path.replace(self.root/'endpoint.json')
|
||||
def rows(self):
|
||||
def rows(self)->list[dict[str,Any]]:
|
||||
rows=self.profiles.status()['profiles']
|
||||
with self.lock:enabled=set(self.config['enabled_profiles'])
|
||||
return [dict(p,enabled=p['id'] in enabled) for p in rows if p['kind']!='video']
|
||||
@@ -320,21 +324,28 @@ class Endpoint:
|
||||
# Discovery is configuration-only: never start or probe a model worker.
|
||||
p=self.find_profile(name,'chat')
|
||||
params=p.get('parameters',{})
|
||||
model=p.get('model') or {}
|
||||
model=p.get('model');model=model if isinstance(model,dict) else {}
|
||||
identity=' '.join(str(model.get(k,'')) for k in ('repo','file','filename','name')).lower()
|
||||
known_template=bool(re.search(r'qwen|gemma',identity))
|
||||
return dict(model=p['name'],n_ctx=int(params.get('context',8192)),
|
||||
value:dict[str,Any]=dict(model=p['name'],n_ctx=int(params.get('context',8192)),
|
||||
default_generation_settings=dict(n_ctx=int(params.get('context',8192)),params={}),
|
||||
total_slots=int(params.get('slots',1)),context_scope='per_slot' if params.get('chat_runtime') in ('strata','basalt') else 'shared',
|
||||
modalities=dict(vision=bool(params.get('vision_projector'))),
|
||||
chat_template_caps=dict(supports_tool_calls=known_template,
|
||||
supports_typed_content=True,
|
||||
supports_reasoning_effort='qwen' in identity))
|
||||
caps=profile_capabilities(self.worker,p)
|
||||
if params.get('chat_runtime')=='basalt':
|
||||
value['basalt']=dict(version=caps.get('version'),capabilities=caps['capabilities'],available_capabilities=caps['available'],loaded=caps.get('loaded',False),session_affinity=caps.get('session_affinity',False))
|
||||
value['modalities'].update(documents='documents' in caps['available'],video='video' in caps['available'])
|
||||
value['media_limits']=caps['limits']
|
||||
return value
|
||||
|
||||
class APIHTTPServer(ThreadingHTTPServer):
|
||||
daemon_threads=True
|
||||
endpoint:Endpoint
|
||||
def __init__(self,*args,**kwargs):
|
||||
self.admission=threading.BoundedSemaphore(32);super().__init__(*args,**kwargs)
|
||||
self.admission=threading.BoundedSemaphore(36);self.data_admission=threading.BoundedSemaphore(32);super().__init__(*args,**kwargs)
|
||||
def process_request(self,request,address):
|
||||
if not self.admission.acquire(blocking=False):self.shutdown_request(request);return
|
||||
try:super().process_request(request,address)
|
||||
@@ -349,6 +360,7 @@ class APIHandler(BaseHTTPRequestHandler):
|
||||
def setup(self):super().setup();self.connection.settimeout(15);self.sent=False
|
||||
def log_message(self,*args):pass
|
||||
def compatibility_headers(self):
|
||||
if getattr(self,'request_id',None):self.send_header('X-Request-Id',self.request_id)
|
||||
info=getattr(self,'compatibility',{})
|
||||
if info.get('ignored'):
|
||||
self.send_header('X-Athena-Compatibility-Ignored',','.join(info['ignored']))
|
||||
@@ -373,18 +385,39 @@ class APIHandler(BaseHTTPRequestHandler):
|
||||
def do_DELETE(self):self.route()
|
||||
def do_HEAD(self):self.route()
|
||||
def do_OPTIONS(self):self.route()
|
||||
def answer_now(self,ep):
|
||||
if self.headers.get('Transfer-Encoding') or self.headers.get('Content-Type','').split(';')[0]!='application/json':raise APIError('JSON-Steueranfrage ohne Chunked Upload erforderlich.')
|
||||
try:length=int(self.headers.get('Content-Length','0'))
|
||||
except ValueError:raise APIError('Ungültige Content-Length.') from None
|
||||
if not 0<length<=4096:raise APIError('Steueranfrage maximal 4 KiB.',413,'request_too_large')
|
||||
try:data=json.loads(self.rfile.read(length))
|
||||
except (ValueError,UnicodeError):raise APIError('Ungültige JSON-Steueranfrage.') from None
|
||||
owner=hashlib.sha256(self.headers.get('Authorization','').encode()).hexdigest()
|
||||
method=getattr(type(ep.worker),'answer_now',None)
|
||||
def send(target):
|
||||
if not callable(method):raise ControlError('Backend unterstützt Jetzt antworten nicht.',501,'answer_now_unavailable')
|
||||
return method(ep.worker,target)
|
||||
return self.send(ep.chat_controls.request(owner,data,self.headers,send))
|
||||
def route(self):
|
||||
ep=self.server.endpoint;admitted=False;self._admitted=False
|
||||
api=cast(APIHTTPServer,self.server)
|
||||
ep:Any=api.endpoint # Optional audio/video services are wired dynamically by Server.
|
||||
admitted=False;self._admitted=False;data_slot=False
|
||||
try:
|
||||
browser=bool(ep.video and ep.scheduler.gpu_mode=='video' and getattr(ep,'video_browser_auth',lambda h:False)(self.headers))
|
||||
service_auth=bool(ep.video and callable(getattr(type(ep.video),'service_authenticated',None)) and ep.video.service_authenticated(self.headers.get('Authorization','')))
|
||||
if not browser and not service_auth and not ep.authenticate(self.headers.get('Authorization','')):raise APIError('Gültiger API-Bearer-Token oder Deck-Anmeldung erforderlich.',401,'invalid_api_key')
|
||||
origin=self.headers.get('Origin')
|
||||
if origin and (not browser or origin not in ('http://'+self.headers.get('Host',''),'https://'+self.headers.get('Host',''))):raise APIError('Cross-Origin-API-Zugriff nicht erlaubt.',403)
|
||||
parsed=urlsplit(self.path)
|
||||
control=self.command=='POST' and parsed.path=='/v1/answer_now' and not parsed.query
|
||||
if not control:
|
||||
data_slot=api.data_admission.acquire(blocking=False)
|
||||
if not data_slot:raise APIError('API-Anfragelimit erreicht.',429,'rate_limit_exceeded')
|
||||
with ep.lock:
|
||||
if not ep.allowed():raise APIError('Endpunkt wird gestoppt.',503,'endpoint_stopping')
|
||||
ep.inflight+=1;admitted=True;self._admitted=True
|
||||
parsed=urlsplit(self.path)
|
||||
if control:return self.answer_now(ep)
|
||||
if self.command=='GET' and parsed.path=='/v1/telemetry/speed':
|
||||
provider=getattr(ep,'speed_telemetry',None)
|
||||
if not callable(provider):raise APIError('Geschwindigkeitstelemetrie nicht verfügbar.',503,'telemetry_unavailable')
|
||||
@@ -432,7 +465,7 @@ class APIHandler(BaseHTTPRequestHandler):
|
||||
return
|
||||
if self.command=='GET' and self.path=='/v1/capabilities':
|
||||
from api_compat import capabilities
|
||||
value=capabilities();enabled=bool(ep.config.get('responses_compat',False))
|
||||
value:dict[str,Any]=capabilities();enabled=bool(ep.config.get('responses_compat',False))
|
||||
value['responses']=dict(enabled=enabled,route='/v1/responses',stateless=True,websockets=False,stored_responses=False,tools=['function','custom'],output_formats=['text'])
|
||||
if enabled:value['unsupported_routes']=[r for r in value['unsupported_routes'] if r!='/v1/responses']
|
||||
return self.send(value)
|
||||
@@ -479,7 +512,7 @@ class APIHandler(BaseHTTPRequestHandler):
|
||||
if self.path.endswith('/pcm-stream'):data.setdefault('response_format','pcm')
|
||||
return self.speech(ep,data)
|
||||
return self.image(ep,data)
|
||||
except (APIError,InferenceError) as exc:
|
||||
except (APIError,InferenceError,MediaError,ControlError) as exc:
|
||||
if isinstance(exc,InferenceError):
|
||||
with ep.lock:ep.error=str(exc)
|
||||
self.failure(exc)
|
||||
@@ -489,6 +522,7 @@ class APIHandler(BaseHTTPRequestHandler):
|
||||
self.close_connection=True
|
||||
if admitted:
|
||||
with ep.lock:ep.inflight-=1
|
||||
if data_slot:api.data_admission.release()
|
||||
def transcription(self,ep):
|
||||
if not ep.stt:raise APIError('STT-Laufzeit nicht eingerichtet.',501,'not_implemented')
|
||||
try:
|
||||
@@ -653,44 +687,50 @@ class APIHandler(BaseHTTPRequestHandler):
|
||||
except CompatibilityError as exc:raise APIError(str(exc)) from None
|
||||
if type(data.get('stream',False)) is not bool:raise APIError('stream muss true oder false sein.')
|
||||
if data.get('n',1)!=1:raise APIError('Zunächst wird n=1 unterstützt.')
|
||||
messages=data.get('messages')
|
||||
if not isinstance(messages,list) or not messages or any(not isinstance(m,dict) for m in messages):raise APIError('messages muss eine nichtleere Liste sein.')
|
||||
profile=ep.find_profile(data.get('model'),'chat')
|
||||
for message in messages:
|
||||
content=message.get('content')
|
||||
if isinstance(content,list):
|
||||
for part in content:
|
||||
if not isinstance(part,dict):raise APIError('Ungültiger Nachrichteninhalt.')
|
||||
if part.get('type')=='text':continue
|
||||
if part.get('type')!='image_url' or not profile['parameters'].get('vision_projector'):raise APIError('Für Bildeingaben einen Vision-Projektor im Profil aktivieren.')
|
||||
value=part.get('image_url')
|
||||
url=value.get('url') if isinstance(value,dict) else None
|
||||
if not isinstance(url,str) or not url.startswith(('data:image/png;base64,','data:image/jpeg;base64,','data:image/webp;base64,')):raise APIError('Nur eingebettete PNG/JPEG/WebP-Bilder; keine externen URLs.')
|
||||
import base64,binascii
|
||||
try:raw=base64.b64decode(url.split(',',1)[1],validate=True)
|
||||
except (ValueError,binascii.Error):raise APIError('Ungültige Bildkodierung.') from None
|
||||
if not raw:raise APIError('Leeres Bild.')
|
||||
caps=profile_capabilities(ep.worker,profile)
|
||||
messages,media=normalize_messages(data.get('messages'),profile,caps['available'])
|
||||
body={**data,'messages':messages}
|
||||
for field,value in generation_parameters(profile['parameters']).items():body.setdefault(field,value)
|
||||
try:body=apply_reasoning_budget(body,{**profile['parameters'],'reasoning_budget':ep.profiles.reasoning_budget()})
|
||||
except CompatibilityError as exc:raise APIError(str(exc)) from None
|
||||
owner=hashlib.sha256(self.headers.get('Authorization','').encode()).hexdigest()
|
||||
ticket=ep.chat_controls.begin(owner,profile,client_id=self.headers.get('x-client-request-id'),session=session_id(self.headers,body),can_think=thinking(body),supported='answer_now' in caps['available'])
|
||||
self.request_id=ticket
|
||||
headers={'Content-Type':'application/json'}
|
||||
if caps.get('session_affinity'):
|
||||
headers.update(ep.chat_controls.headers(ticket))
|
||||
elif profile['parameters'].get('chat_runtime')=='basalt':headers['X-Client-Request-Id']=ticket
|
||||
body.pop('session_id',None)
|
||||
if headers.get('x-session-id'):body['session_id']=headers['x-session-id']
|
||||
# Re-resolve after waiting so edits/disable cannot silently launch a stale profile.
|
||||
# Drain preserves requests admitted before stop; route() still rejects
|
||||
# all new requests while stopping.
|
||||
key=('chat',profile['id'],profile['revision'])
|
||||
def allowed():return (ep.allowed() or self._admitted and ep.state=='stopping') and any(p['id']==profile['id'] and p['revision']==profile['revision'] and p['enabled'] for p in ep.rows())
|
||||
with ep.scheduler.lease(key,profile['parameters']['slots'],lambda:ep.worker.ensure(profile),allowed=allowed):
|
||||
body=dict(data)
|
||||
for field,value in generation_parameters(profile['parameters']).items():body.setdefault(field,value)
|
||||
try:body=apply_reasoning_budget(body,{**profile['parameters'],'reasoning_budget':ep.profiles.reasoning_budget()})
|
||||
except CompatibilityError as exc:raise APIError(str(exc)) from None
|
||||
body=ep.worker.prepare_request(body) if callable(getattr(type(ep.worker),'prepare_request',None)) else body
|
||||
conn,key=ep.worker.connect()
|
||||
try:
|
||||
conn.request('POST','/v1/chat/completions',body=json.dumps(body).encode(),headers={'Content-Type':'application/json','Authorization':'Bearer '+key})
|
||||
with ep.scheduler.lease(key,profile['parameters']['slots'],lambda:ep.worker.ensure(profile),allowed=allowed):
|
||||
generation=ep.worker.status().get('generation')
|
||||
if ep.chat_controls.dispatch(ticket,generation):body=immediate_answer(body)
|
||||
body=ep.worker.prepare_request(body) if callable(getattr(type(ep.worker),'prepare_request',None)) else body
|
||||
conn,token=ep.worker.connect()
|
||||
try:
|
||||
conn.request('POST','/v1/chat/completions',body=json.dumps(body).encode(),headers={**headers,'Authorization':'Bearer '+token})
|
||||
response=conn.getresponse()
|
||||
if response.status!=200:
|
||||
raise chat_upstream_error(response.status,response.read(65536),ep.worker.status().get('runtime','llama'))
|
||||
if response.status!=200:raise chat_upstream_error(response.status,response.read(65536),ep.worker.status().get('runtime','llama'))
|
||||
native=response.getheader('X-Request-Id')
|
||||
if native:ep.chat_controls.bind(ticket,native);self.request_id=native
|
||||
if converter:ep.chat_controls.bind(ticket,converter.response['id']);self.request_id=converter.response['id']
|
||||
method=getattr(type(ep.worker),'answer_now',None)
|
||||
def send(target):
|
||||
if not callable(method):raise ControlError('Jetzt antworten nicht verfügbar.',501,'answer_now_unavailable')
|
||||
return method(ep.worker,target)
|
||||
ep.chat_controls.started(ticket,generation,send)
|
||||
if not data.get('stream'):
|
||||
raw=response.read(16*1024*1024+1)
|
||||
if len(raw)>16*1024*1024:raise InferenceError('Modellantwort überschreitet 16 MiB.')
|
||||
value=json.loads(raw)
|
||||
if not converter and isinstance(value.get('id'),str):ep.chat_controls.bind(ticket,value['id']);self.request_id=value['id']
|
||||
if converter:
|
||||
try:value=converter.complete(value)
|
||||
except (ResponsesError,ValueError,KeyError,TypeError):raise APIError('Modellantwort nicht Responses-kompatibel.',502,'upstream_response_error') from None
|
||||
@@ -708,10 +748,10 @@ class APIHandler(BaseHTTPRequestHandler):
|
||||
self.wfile.write(converter.feed(chunk) if converter else chunk);self.wfile.flush()
|
||||
raise InferenceError('Zeitlimit der Streaming-Antwort überschritten.')
|
||||
except (ResponsesError,ValueError,KeyError,TypeError,OSError,InferenceError):
|
||||
if converter:
|
||||
self.wfile.write(converter.failure());self.wfile.flush();return
|
||||
if converter:self.wfile.write(converter.failure());self.wfile.flush();return
|
||||
raise
|
||||
finally:conn.close()
|
||||
finally:ep.chat_controls.finish(ticket)
|
||||
def image(self,ep,data,reference_images=None):
|
||||
if set(data)-{'model','prompt','n','size','response_format','user'}:raise APIError('Nicht unterstützte Bildparameter. Schritte/Guidance/Seed stehen im Profil.')
|
||||
if data.get('n',1)!=1 or data.get('response_format','b64_json')!='b64_json':raise APIError('Unterstützt werden n=1 und response_format=b64_json.')
|
||||
|
||||
+51
-18
@@ -4,19 +4,24 @@ import json
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
class ResponsesError(ValueError):pass
|
||||
|
||||
def ident(prefix):return prefix+'_'+uuid.uuid4().hex
|
||||
|
||||
def translate(body):
|
||||
allowed={'model','input','instructions','tools','tool_choice','parallel_tool_calls','reasoning','text','stream','store','include','max_output_tokens','temperature','top_p','metadata','user','service_tier','prompt_cache_key','prompt_cache_retention','safety_identifier','truncation'}
|
||||
allowed={'model','input','instructions','tools','tool_choice','parallel_tool_calls','reasoning','text','stream','store','include','max_output_tokens','temperature','top_p','metadata','user','service_tier','prompt_cache_key','prompt_cache_retention','safety_identifier','truncation','session_id','top_logprobs'}
|
||||
if not isinstance(body,dict):raise ResponsesError('Responses-Anfrage muss ein JSON-Objekt sein.')
|
||||
if set(body)-allowed:raise ResponsesError('Nicht unterstützte Responses-Felder: '+', '.join(sorted(set(body)-allowed)))
|
||||
if type(body.get('stream',False)) is not bool:raise ResponsesError('stream muss true oder false sein.')
|
||||
if body.get('store',False) is not False:raise ResponsesError('Nur store=false unterstützt; Gesprächskontext vollständig mitsenden.')
|
||||
if body.get('truncation','disabled')!='disabled':raise ResponsesError('Automatische Kontextkürzung wird nicht unterstützt.')
|
||||
if body.get('service_tier','auto') not in ('auto','default'):raise ResponsesError('Keine besonderen Service-Tiers unterstützt.')
|
||||
include=body.get('include',[])
|
||||
if include is None:include=[]
|
||||
if not isinstance(include,list) or len(include)>16 or any(not isinstance(x,str) for x in include):raise ResponsesError('include muss eine Liste von Feldnamen sein.')
|
||||
want_logprobs='message.output_text.logprobs' in include
|
||||
mapping={};tools=[]
|
||||
def add(tool,namespace=None):
|
||||
if not isinstance(tool,dict) or tool.get('type') not in ('function','custom'):raise ResponsesError('Nur Function- und Custom-Werkzeuge unterstützt.')
|
||||
@@ -43,6 +48,21 @@ def translate(body):
|
||||
if body.get('instructions'):
|
||||
if not isinstance(body['instructions'],str):raise ResponsesError('instructions muss Text sein.')
|
||||
systems.append(body['instructions'])
|
||||
def content_parts(content):
|
||||
parts=[]
|
||||
for part in content:
|
||||
if not isinstance(part,dict):raise ResponsesError('Ungültiger Nachrichteninhalt.')
|
||||
kind=part.get('type')
|
||||
if kind in ('input_text','output_text') and isinstance(part.get('text'),str):parts.append(dict(type='text',text=part['text']))
|
||||
elif kind=='input_image':parts.append(dict(type='image_url',image_url={'url':part.get('image_url')}))
|
||||
elif kind=='input_file':
|
||||
if set(part)-{'type','filename','file_data','pages'} or not {'filename','file_data'}<=set(part):raise ResponsesError('input_file benötigt eingebettete file_data und filename; keine Datei-IDs oder URLs.')
|
||||
parts.append({'type':'file','file':{k:v for k,v in part.items() if k!='type'}})
|
||||
elif kind=='input_video':
|
||||
if set(part)-{'type','video_url','fps','max_frames'} or not isinstance(part.get('video_url'),str):raise ResponsesError('input_video benötigt eine eingebettete Video-Daten-URL.')
|
||||
parts.append({'type':'video_url','video_url':{'url':part['video_url']},**{k:part[k] for k in ('fps','max_frames') if k in part}})
|
||||
else:raise ResponsesError('Nicht unterstützter Nachrichteninhalt.')
|
||||
return '\n'.join(p['text'] for p in parts) if all(p['type']=='text' for p in parts) else parts
|
||||
for item in source:
|
||||
if not isinstance(item,dict):raise ResponsesError('Ungültiges input-Element.')
|
||||
kind=item.get('type','message')
|
||||
@@ -59,18 +79,13 @@ def translate(body):
|
||||
elif kind in ('function_call_output','custom_tool_call_output'):
|
||||
if not isinstance(item.get('call_id'),str):raise ResponsesError('call_id fehlt.')
|
||||
output=item.get('output','')
|
||||
messages.append(dict(role='tool',tool_call_id=item['call_id'],content=output if isinstance(output,str) else json.dumps(output)))
|
||||
typed=isinstance(output,list) and bool(output) and all(isinstance(x,dict) and 'type' in x for x in output)
|
||||
messages.append(dict(role='tool',tool_call_id=item['call_id'],content=content_parts(output) if typed else output if isinstance(output,str) else json.dumps(output)))
|
||||
elif kind=='message':
|
||||
role=item.get('role','user');content=item.get('content','')
|
||||
if role not in ('developer','system','user','assistant'):raise ResponsesError('Nicht unterstützte Nachrichtenrolle.')
|
||||
if isinstance(content,list):
|
||||
parts=[]
|
||||
for part in content:
|
||||
if not isinstance(part,dict):raise ResponsesError('Ungültiger Nachrichteninhalt.')
|
||||
if part.get('type') in ('input_text','output_text') and isinstance(part.get('text'),str):parts.append(dict(type='text',text=part['text']))
|
||||
elif part.get('type')=='input_image':parts.append(dict(type='image_url',image_url={'url':part.get('image_url')}))
|
||||
else:raise ResponsesError('Nicht unterstützter Nachrichteninhalt.')
|
||||
content='\n'.join(p['text'] for p in parts) if all(p['type']=='text' for p in parts) else parts
|
||||
content=content_parts(content)
|
||||
if not isinstance(content,(str,list)):raise ResponsesError('Ungültiger Nachrichteninhalt.')
|
||||
if role in ('system','developer'):
|
||||
if not isinstance(content,str):raise ResponsesError('Systemanweisungen müssen Text sein.')
|
||||
@@ -82,9 +97,13 @@ def translate(body):
|
||||
chat=dict(model=body.get('model'),messages=messages,stream=body.get('stream',False))
|
||||
if chat['stream']:chat['stream_options']={'include_usage':True}
|
||||
if tools:chat['tools']=tools
|
||||
for field in ('temperature','top_p','parallel_tool_calls','user'):
|
||||
for field in ('temperature','top_p','parallel_tool_calls','user','session_id'):
|
||||
if field in body:chat[field]=body[field]
|
||||
if 'max_output_tokens' in body:chat['max_tokens']=body['max_output_tokens']
|
||||
if want_logprobs:chat['logprobs']=True
|
||||
if 'top_logprobs' in body:
|
||||
if not want_logprobs:raise ResponsesError('top_logprobs benötigt include=message.output_text.logprobs.')
|
||||
chat['top_logprobs']=body['top_logprobs']
|
||||
reasoning=body.get('reasoning',{})
|
||||
if not isinstance(reasoning,dict) or set(reasoning)-{'effort','summary'}:raise ResponsesError('Nicht unterstützte reasoning-Einstellungen.')
|
||||
if 'effort' in reasoning:chat['reasoning_effort']=reasoning['effort']
|
||||
@@ -99,12 +118,15 @@ def translate(body):
|
||||
name=(choice.get('namespace','')+'__' if choice.get('namespace') else '')+choice['name']
|
||||
chat['tool_choice']=dict(type='function',function={'name':name})
|
||||
else:raise ResponsesError('Nicht unterstütztes tool_choice.')
|
||||
return chat,Converter(body.get('model'),mapping)
|
||||
return chat,Converter(body.get('model'),mapping,want_logprobs)
|
||||
|
||||
class Converter:
|
||||
def __init__(self,model,mapping):
|
||||
self.mapping=mapping;self.seq=0;self.pending='';self.decoder=codecs.getincrementaldecoder('utf8')();self.lines=[];self.done=False;self.reason=None;self.calls={};self.text=None;self.thinking=None;self.usage={}
|
||||
def __init__(self,model,mapping,want_logprobs=False):
|
||||
self.mapping=mapping;self.seq=0;self.pending='';self.decoder=codecs.getincrementaldecoder('utf8')();self.lines=[];self.done=False;self.reason=None;self.calls={};self.usage={}
|
||||
self.text:dict[str,Any]|None=None;self.thinking:dict[str,Any]|None=None
|
||||
self.text_lps=[];self.reasoning_lps=[];self.tool_lps={}
|
||||
self.response=dict(id=ident('resp'),object='response',created_at=int(time.time()),status='in_progress',model=model,output=[],error=None,incomplete_details=None,usage=None)
|
||||
self.want_logprobs=want_logprobs
|
||||
def event(self,type_,**data):
|
||||
value=dict(type=type_,sequence_number=self.seq,**data);self.seq+=1
|
||||
return ('event: '+type_+'\ndata: '+json.dumps(value,ensure_ascii=False)+'\n\n').encode()
|
||||
@@ -112,22 +134,33 @@ class Converter:
|
||||
def add(self,item):
|
||||
index=len(self.response['output']);self.response['output'].append(item)
|
||||
return index,self.event('response.output_item.added',output_index=index,item=item)
|
||||
def delta(self,delta):
|
||||
def delta(self,delta,logprobs=None):
|
||||
out=b'';thinking=delta.get('reasoning_content') or delta.get('reasoning')
|
||||
entries=[]
|
||||
if self.want_logprobs and isinstance(logprobs,dict):
|
||||
entries=logprobs.get('content',[]);reasoning_entries=logprobs.get('reasoning_content',[]);tools=logprobs.get('tool_calls',[])
|
||||
if not isinstance(entries,list) or not isinstance(reasoning_entries,list) or not isinstance(tools,list):raise ResponsesError('Ungültige Tokenwahrscheinlichkeiten im Modellstream.')
|
||||
self.text_lps.extend(entries);self.reasoning_lps.extend(reasoning_entries)
|
||||
for tool in tools:
|
||||
if not isinstance(tool,dict) or type(tool.get('index')) is not int or tool['index']<0 or not isinstance(tool.get('content'),list):raise ResponsesError('Ungültige Werkzeugwahrscheinlichkeiten im Modellstream.')
|
||||
self.tool_lps.setdefault(tool['index'],[]).extend(tool['content'])
|
||||
if thinking:
|
||||
if not self.thinking:
|
||||
self.thinking=dict(id=ident('rs'),type='reasoning',summary=[dict(type='summary_text',text='')]);self.thinking_index,added=self.add(self.thinking);out+=added
|
||||
if self.want_logprobs:self.thinking['logprobs']=self.reasoning_lps
|
||||
out+=self.event('response.reasoning_summary_part.added',item_id=self.thinking['id'],output_index=self.thinking_index,summary_index=0,part=self.thinking['summary'][0])
|
||||
self.thinking['summary'][0]['text']+=thinking
|
||||
out+=self.event('response.reasoning_summary_text.delta',item_id=self.thinking['id'],output_index=self.thinking_index,summary_index=0,delta=thinking)
|
||||
if delta.get('content'):
|
||||
if not self.text:
|
||||
self.text=dict(id=ident('msg'),type='message',role='assistant',status='in_progress',content=[dict(type='output_text',text='',annotations=[])]);self.text_index,added=self.add(self.text);out+=added
|
||||
if self.want_logprobs:self.text['content'][0]['logprobs']=self.text_lps
|
||||
out+=self.event('response.content_part.added',item_id=self.text['id'],output_index=self.text_index,content_index=0,part=self.text['content'][0])
|
||||
self.text['content'][0]['text']+=delta['content']
|
||||
out+=self.event('response.output_text.delta',item_id=self.text['id'],output_index=self.text_index,content_index=0,delta=delta['content'])
|
||||
out+=self.event('response.output_text.delta',item_id=self.text['id'],output_index=self.text_index,content_index=0,delta=delta['content'],**({'logprobs':entries} if self.want_logprobs else {}))
|
||||
for value in delta.get('tool_calls',[]):
|
||||
call=self.calls.setdefault(value['index'],dict(id=ident('fc'),type='function_call',status='in_progress',call_id='',name='',arguments=''))
|
||||
if self.want_logprobs:call['logprobs']=self.tool_lps.setdefault(value['index'],[])
|
||||
if value.get('id'):call['call_id']=value['id']
|
||||
call['name']+=value.get('function',{}).get('name','');call['arguments']+=value.get('function',{}).get('arguments','')
|
||||
return out
|
||||
@@ -143,7 +176,7 @@ class Converter:
|
||||
if value.get('error'):raise ResponsesError('Modellstream meldet einen Fehler.')
|
||||
self.usage=value.get('usage') or self.usage
|
||||
for choice in value.get('choices',[]):
|
||||
out+=self.delta(choice.get('delta',{}));self.reason=choice.get('finish_reason') or self.reason
|
||||
out+=self.delta(choice.get('delta',{}),choice.get('logprobs'));self.reason=choice.get('finish_reason') or self.reason
|
||||
return out
|
||||
def finish(self):
|
||||
if not self.done or not self.reason:raise ResponsesError('Modellstream vorzeitig abgebrochen.')
|
||||
@@ -154,7 +187,7 @@ class Converter:
|
||||
out+=self.event('response.output_item.done',output_index=self.thinking_index,item=self.thinking)
|
||||
if self.text:
|
||||
self.text['status']='completed'
|
||||
out+=self.event('response.output_text.done',item_id=self.text['id'],output_index=self.text_index,content_index=0,text=self.text['content'][0]['text'])
|
||||
out+=self.event('response.output_text.done',item_id=self.text['id'],output_index=self.text_index,content_index=0,text=self.text['content'][0]['text'],**({'logprobs':self.text_lps} if self.want_logprobs else {}))
|
||||
out+=self.event('response.content_part.done',item_id=self.text['id'],output_index=self.text_index,content_index=0,part=self.text['content'][0])
|
||||
out+=self.event('response.output_item.done',output_index=self.text_index,item=self.text)
|
||||
for call in self.calls.values():
|
||||
@@ -184,7 +217,7 @@ class Converter:
|
||||
if not choices:raise ResponsesError('Leere Modellantwort.')
|
||||
message=choices[0].get('message',{});delta=dict(message)
|
||||
delta['tool_calls']=[dict(c,index=i) for i,c in enumerate(message.get('tool_calls',[]))]
|
||||
self.delta(delta);self.reason=choices[0].get('finish_reason') or 'stop';self.usage=value.get('usage') or {};self.done=True;self.finish()
|
||||
self.delta(delta,choices[0].get('logprobs'));self.reason=choices[0].get('finish_reason') or 'stop';self.usage=value.get('usage') or {};self.done=True;self.finish()
|
||||
return self.response
|
||||
def failure(self):
|
||||
self.response.update(status='failed',error=dict(code='upstream_stream_error',message='Responses-Stream konnte nicht vollständig verarbeitet werden.'))
|
||||
|
||||
@@ -30,7 +30,8 @@ from strata_runtime import StrataRuntime
|
||||
from strata_worker import StrataWorker,ChatWorkerRouter
|
||||
from basalt_runtime import BasaltRuntime
|
||||
from basalt_worker import BasaltWorker
|
||||
from endpoint import Endpoint
|
||||
from endpoint import Endpoint,MAX_JSON_REQUEST_BYTES
|
||||
from chat_control import ControlError
|
||||
from chat_test import ChatTests
|
||||
from auto_test import AutoTests
|
||||
from urllib.parse import urlsplit, parse_qs, unquote
|
||||
@@ -413,14 +414,15 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.server.login_attempts.append(now)
|
||||
return True
|
||||
|
||||
def read_json(self):
|
||||
self.connection.settimeout(10)
|
||||
def read_json(self,maximum=32768):
|
||||
self.connection.settimeout(60 if maximum>32768 else 10)
|
||||
if self.headers.get('Transfer-Encoding'):
|
||||
raise ValueError('Chunked Uploads werden nicht unterstützt.')
|
||||
length = int(self.headers.get('Content-Length', '0'))
|
||||
if not 0 < length <= 32768 or self.headers.get('Content-Type') != 'application/json':
|
||||
raise ValueError('JSON-Anfrage erwartet, maximal 32 KiB.')
|
||||
if not 0 < length <= maximum or self.headers.get('Content-Type') != 'application/json':
|
||||
raise ValueError('JSON-Anfrage erwartet, maximal '+('32 KiB.' if maximum==32768 else '64 MiB.'))
|
||||
raw = self.rfile.read(length)
|
||||
if len(raw)!=length:raise ValueError('JSON-Upload unvollständig.')
|
||||
try:
|
||||
value = json.loads(raw)
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
@@ -538,6 +540,9 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if self.path == '/api/v1/auto-tests':return self.respond(self.server.auto_tests.status())
|
||||
if self.path == '/api/v1/backup':return self.respond(self.server.backup.status())
|
||||
if self.path == '/api/v1/chat-tests':return self.respond(self.server.chat_tests.status())
|
||||
if urlsplit(self.path).path == '/api/v1/chat-tests/capabilities':
|
||||
try:return self.respond(self.server.chat_tests.capabilities(parse_qs(urlsplit(self.path).query).get('profile_id',[''])[0]))
|
||||
except ValueError as exc:return self.respond({'error':str(exc)},400)
|
||||
if self.path == '/api/v1/endpoint':return self.respond(self.server.endpoint.status())
|
||||
if self.path == '/api/v1/docker':return self.respond(self.server.docker.status())
|
||||
if self.path == '/api/v1/stt':return self.respond(self.server.stt.status())
|
||||
@@ -811,12 +816,17 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if data:raise ValueError('Keine Parameter erwartet.')
|
||||
return self.respond(self.server.auto_tests.stop())
|
||||
except ValueError as exc:return self.respond({'error':str(exc)},400)
|
||||
if self.path in ('/api/v1/chat-tests/start','/api/v1/chat-tests/cancel','/api/v1/chat-tests/unload'):
|
||||
if self.path in ('/api/v1/chat-tests/start','/api/v1/chat-tests/cancel','/api/v1/chat-tests/unload','/api/v1/chat-tests/answer-now'):
|
||||
try:
|
||||
data=self.read_json()
|
||||
data=self.read_json(MAX_JSON_REQUEST_BYTES if self.path.endswith('/start') else 32768)
|
||||
if self.path.endswith('/start'):return self.respond(self.server.chat_tests.start(data))
|
||||
if self.path.endswith('/answer-now'):return self.respond(self.server.chat_tests.answer_now(data))
|
||||
if self.path.endswith('/cancel') and data:
|
||||
if set(data)!={'job_id'} or not isinstance(data['job_id'],str):raise ValueError('Aktuelle Testauftragskennung erforderlich.')
|
||||
return self.respond(self.server.chat_tests.stop(data['job_id']))
|
||||
if data:raise ValueError('Keine Parameter erwartet.')
|
||||
return self.respond(self.server.chat_tests.stop() if self.path.endswith('/cancel') else self.server.chat_tests.unload())
|
||||
except ControlError as exc:return self.respond({'error':str(exc),'code':exc.code},exc.status)
|
||||
except ValueError as exc:return self.respond({'error':str(exc)},400)
|
||||
if self.path == '/api/v1/separator-profiles/save':
|
||||
try:return self.respond(self.server.separator_tests.configure(self.read_json()))
|
||||
|
||||
@@ -155,6 +155,15 @@ class ChatWorkerRouter:
|
||||
if target is not self.active:self.active.stop();self.active=target
|
||||
return target.ensure(p,cancel)
|
||||
def prepare_request(self,body):return self.active.prepare_request(body) if self.active is self.strata or self.basalt is not None and self.active is self.basalt else body
|
||||
def capabilities(self,p):
|
||||
target=self.target(p);method=getattr(type(target),'capabilities',None)
|
||||
return method(target,p) if callable(method) else {}
|
||||
def answer_now(self,request):
|
||||
with self.lock:target=self.active
|
||||
if target is not self.basalt:
|
||||
from chat_control import ControlError
|
||||
raise ControlError('Der ursprüngliche Basalt-Worker ist nicht mehr aktiv.',409,'worker_changed')
|
||||
return target.answer_now(request)
|
||||
def status(self):return {**self.active.status(),'runtime':'basalt' if self.basalt is not None and self.active is self.basalt else 'strata' if self.active is self.strata else 'llama'}
|
||||
def stop(self):
|
||||
with self.lock:
|
||||
|
||||
+11
-4
@@ -16,6 +16,10 @@ GPU='GPU-aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
|
||||
OTHER='GPU-bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'
|
||||
|
||||
class BasaltTests(unittest.TestCase):
|
||||
def test_expert_profile_is_relative_to_deployed_source_not_build_tree(self):
|
||||
command=BasaltWorker.server_command(Path('/venv/python'),Path('/relocated/source'),Path('/owned/worker.json'),'synthetic-test-key')
|
||||
self.assertIn('--expert-profile',command)
|
||||
self.assertEqual(command[command.index('--expert-profile')+1],'/relocated/profiles/qwen4exp-48x512-v1pack.prof')
|
||||
def params(self,**changes):return chat_parameters({**{k:v[2] for k,v in SCHEMAS['chat'].items()},'chat_runtime':'basalt','gpu_devices':[GPU],**changes})
|
||||
def model(self):return dict(RECIPE['model'],id='a'*64,kind='chat',profile_eligible=True)
|
||||
def test_model_identity_is_not_just_a_filename(self):
|
||||
@@ -60,8 +64,9 @@ class BasaltTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(InferenceError,'SM120'):worker.plan(p)
|
||||
def test_loopback_config_uses_full_per_slot_context_and_no_vision(self):
|
||||
p=dict(parameters=self.params(context=262144,slots=2),api_id='basalt-test');config=BasaltWorker.configuration(p,Path('/owned/model.basalt'),12345,700)
|
||||
self.assertEqual(config['server']['host'],'127.0.0.1');self.assertEqual(config['server']['gpu'],'0');self.assertIs(config['server']['slot-full-context'],True);self.assertEqual(config['server']['parallel'],2);self.assertEqual(config['server']['vision'],'off');self.assertEqual(config['engine']['max-context'],262144)
|
||||
self.assertNotIn('api_key',json.dumps(config));self.assertEqual(BasaltWorker.server_command(Path('/venv/python'),Path('/source'),Path('/owned/worker.json'),'synthetic-test-key'),['/venv/python',str(Path(__file__).with_name('basalt_serve.py')),'--deck-source','/source','--engine-bin','/source/bin/basalt','--config','/owned/worker.json','--api-key','synthetic-test-key'])
|
||||
self.assertEqual(config['version'],2);self.assertEqual(config['server']['host'],'127.0.0.1');self.assertIs(config['server']['image-remote-only'],True);self.assertNotIn('model',config['server']);self.assertEqual(len(config['models']),1);model=config['models'][0];self.assertEqual(model['gpu'],'0');self.assertIs(model['slot-full-context'],True);self.assertEqual(model['parallel'],2);self.assertEqual(model['vision'],'off');self.assertEqual(config['engine']['max-context'],262144)
|
||||
self.assertEqual(config['engine']['conversation-cache-mib'],1024)
|
||||
self.assertNotIn('api_key',json.dumps(config));self.assertEqual(BasaltWorker.server_command(Path('/venv/python'),Path('/source'),Path('/owned/worker.json'),'synthetic-test-key'),['/venv/python',str(Path(__file__).with_name('basalt_serve.py')),'--deck-source','/source','--engine-bin','/source/bin/basalt','--config','/owned/worker.json','--api-key','synthetic-test-key','--expert-profile','/profiles/qwen4exp-48x512-v1pack.prof'])
|
||||
def test_vision_uses_separate_gpu_and_confirms_modality(self):
|
||||
from basalt_runtime import validate_projector
|
||||
validate_projector(RECIPE['vision'])
|
||||
@@ -72,7 +77,7 @@ class BasaltTests(unittest.TestCase):
|
||||
p=dict(api_id='basalt-vision',parameters=params)
|
||||
with self.assertRaises(InferenceError):BasaltWorker.configuration(p,Path('/model.basalt'),12345,700)
|
||||
config=BasaltWorker.configuration(p,Path('/model.basalt'),12345,700,0)
|
||||
self.assertEqual(config['server']['vision'],'0');self.assertEqual(config['server']['gpu'],'0')
|
||||
self.assertEqual(config['models'][0]['vision'],'0');self.assertEqual(config['models'][0]['gpu'],'0')
|
||||
props=dict(is_sleeping=False,total_slots=2,default_generation_settings={'n_ctx':262144})
|
||||
with self.assertRaises(InferenceError):BasaltWorker.verify_properties(props,params)
|
||||
BasaltWorker.verify_properties({**props,'modalities':{'vision':True}},params)
|
||||
@@ -98,7 +103,9 @@ class BasaltTests(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):runtime.prepared(self.model())
|
||||
root=runtime.root;(root/'venv/bin').mkdir(parents=True);(root/'venv/bin/python').touch();(root/'source/bin').mkdir(parents=True);(root/'source/bin/basalt').touch()
|
||||
(root/'ready.json').write_text(json.dumps(dict(commit=COMMIT,version=RECIPE['version'])))
|
||||
self.assertTrue(runtime.status()['installed']);(root/'ready.json').write_text(json.dumps(dict(commit='0'*40,version=RECIPE['version'])))
|
||||
with patch('basalt_runtime.profile_ready',return_value=True):self.assertTrue(runtime.status()['installed'])
|
||||
self.assertFalse(runtime.status()['installed'])
|
||||
(root/'ready.json').write_text(json.dumps(dict(commit='0'*40,version=RECIPE['version'])))
|
||||
self.assertFalse(runtime.status()['installed'])
|
||||
def test_pinned_model_download_checks_metadata_before_queueing(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Synthetic HTTP/GUI-manager contracts. No model, GPU or production connection."""
|
||||
import base64
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
import test_endpoint as endpoint_fixtures
|
||||
import test_chat_test as chat_fixtures
|
||||
from api_compat import normalize_chat,CompatibilityError
|
||||
from basalt_worker import BasaltWorker
|
||||
from chat_control import ControlError
|
||||
from responses_compat import translate,ResponsesError
|
||||
|
||||
|
||||
def data_url(mime,raw):return 'data:'+mime+';base64,'+base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
class FeatureWorker(endpoint_fixtures.FakeWorker):
|
||||
http:Any
|
||||
def capabilities(self,p):
|
||||
return dict(installed=True,loaded=bool(self.name),version='0.3.3',available=['documents','video','logprobs','answer_now'],capabilities=['documents','video','logprobs','answer_now'] if self.name else [],session_affinity=True)
|
||||
def ensure(self,p):
|
||||
super().ensure(p);self.profile=p;self.state='ready';self.generation='synthetic-generation';self.backend_info={'capabilities':['answer_now']};self.process=SimpleNamespace(poll=lambda:None);self.lock=threading.RLock();self.port=self.http.server_port;self.key='internal-test-only'
|
||||
def status(self):return {**super().status(),'runtime':'basalt','generation':getattr(self,'generation',None)}
|
||||
answer_now=BasaltWorker.answer_now
|
||||
|
||||
|
||||
class FeatureUpstream(BaseHTTPRequestHandler):
|
||||
def log_message(self,format,*args):pass
|
||||
def send(self,value,status=200):
|
||||
raw=json.dumps(value).encode();self.send_response(status);self.send_header('Content-Length',str(len(raw)));self.end_headers();self.wfile.write(raw)
|
||||
def do_POST(self):
|
||||
w:Any=getattr(self.server,'worker');body=json.loads(self.rfile.read(int(self.headers['Content-Length'])))
|
||||
if self.path=='/v1/answer_now':
|
||||
w.controls.append(body)
|
||||
if body.get('request_id')!=w.client_id:return self.send({'error':{'code':'unknown_request'}},404)
|
||||
if getattr(w,'control_status',200)!=200:return self.send({'error':{'code':'not_thinking'}},w.control_status)
|
||||
w.block.set();return self.send({'object':'answer_now','request_id':'native-fixture','state':'thinking'})
|
||||
w.requests.append(body);w.forwarded_headers=dict(self.headers);w.client_id=self.headers.get('X-Client-Request-Id')
|
||||
if body.get('stream'):
|
||||
self.send_response(200);self.send_header('Content-Type','text/event-stream');self.send_header('X-Request-Id','native-fixture');self.end_headers()
|
||||
self.wfile.write(b'data: {"choices":[{"delta":{"reasoning_content":"Synthetic reasoning"}}]}\n\n');self.wfile.flush();w.entered.set();w.block.wait(4)
|
||||
self.wfile.write(b'data: {"choices":[{"delta":{"content":"Synthetic answer"},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n');self.wfile.flush()
|
||||
else:
|
||||
self.send({'id':'native-fixture','model':body['model'],'choices':[{'message':{'role':'assistant','content':'Synthetic answer'},'finish_reason':'stop','logprobs':{'content':[{'token':'Synthetic','logprob':-.1,'bytes':[83],'top_logprobs':[]}]}}]})
|
||||
|
||||
|
||||
class HTTPFeatureTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.f:Any=endpoint_fixtures.EndpointTests();self.f.setUp();self.addCleanup(self.f.tearDown)
|
||||
self.w:Any=self.f.worker;self.w.__class__=FeatureWorker;self.w.controls=[];self.w.entered=threading.Event();self.w.http.RequestHandlerClass=FeatureUpstream
|
||||
self.f.rows[0]['parameters'].update(chat_runtime='basalt',vision_projector='synthetic',context=262144)
|
||||
self.f.enable('alpha')
|
||||
def request(self,path,body=None,headers=None)->tuple[int,dict[str,str],Any]:
|
||||
c=http.client.HTTPConnection('127.0.0.1',self.f.port,timeout=5)
|
||||
c.request('GET' if body is None else 'POST',path,json.dumps(body) if body is not None else None,{'Content-Type':'application/json','Authorization':'Bearer '+'A'*32,**(headers or {})})
|
||||
r=c.getresponse();raw=r.read();result=(r.status,dict(r.headers),raw if (body or {}).get('stream') else json.loads(raw));c.close();return result
|
||||
def chat(self,**kw):return dict(model='alpha',messages=[dict(role='user',content='Synthetic question')],**kw)
|
||||
def stream(self,responses=False):
|
||||
self.w.block.clear();out={};body=dict(model='alpha',input='Synthetic question',stream=True) if responses else self.chat(stream=True)
|
||||
if responses:self.f.ep.config['responses_compat']=True
|
||||
thread=threading.Thread(target=lambda:out.setdefault('value',self.request('/v1/responses' if responses else '/v1/chat/completions',body,{'X-Client-Request-Id':'synthetic-client','X-Session-Id':'synthetic-session'})),daemon=True);thread.start();self.assertTrue(self.w.entered.wait(3));return thread,out
|
||||
def test_properties_are_versioned_and_do_not_load(self):
|
||||
code,_,props=self.request('/props?model=alpha');self.assertEqual(code,200);self.assertEqual(props['basalt']['version'],'0.3.3');self.assertFalse(props['basalt']['loaded']);self.assertEqual(props['basalt']['capabilities'],[]);self.assertIn('documents',props['basalt']['available_capabilities']);self.assertEqual(self.w.started,[])
|
||||
_,_,caps=self.request('/v1/capabilities');self.assertEqual(caps['controls']['scope'],'same_principal');self.assertEqual(caps['media_limits']['attachments'],8)
|
||||
def test_document_video_defaults_and_session_scope_reach_worker(self):
|
||||
parts=[dict(type='file',file=dict(filename='note.txt',file_data=data_url('text/plain',b'Synthetic source'))),dict(type='video_url',video_url=dict(url=data_url('video/mp4',b'Synthetic fixture, not a decodable video')))]
|
||||
body=self.chat(session_id='raw-session');body['messages'][0]['content']=parts
|
||||
code,headers,_=self.request('/v1/chat/completions',body);self.assertEqual(code,200);self.assertEqual(headers['X-Request-Id'],'native-fixture')
|
||||
sent=self.w.requests[-1];self.assertEqual(sent['messages'][0]['content'][1]['max_frames'],128);self.assertEqual(sent['messages'][0]['content'][1]['fps'],2);self.assertNotEqual(sent['session_id'],'raw-session');self.assertEqual(sent['session_id'],self.w.forwarded_headers['x-session-id'])
|
||||
self.assertNotIn('max_frames',body['messages'][0]['content'][1])
|
||||
def test_control_uses_separate_connection_and_finishes_same_stream(self):
|
||||
th,out=self.stream();code,_,result=self.request('/v1/answer_now',{'request_id':'synthetic-client'});self.assertEqual((code,result['state']),(200,'thinking'));th.join(4);self.assertFalse(th.is_alive());self.assertIn(b'Synthetic answer',out['value'][2]);self.assertEqual(self.w.controls,[{'request_id':self.w.client_id}]);self.assertEqual(self.w.started,['alpha'])
|
||||
self.assertEqual(self.request('/v1/answer_now',{'request_id':'native-fixture'})[0],409)
|
||||
def test_rotated_principal_cannot_control_old_request(self):
|
||||
th,_=self.stream();self.f.record['api_token_hash']=hashlib.sha256(b'B'*32).hexdigest()
|
||||
self.assertEqual(self.request('/v1/answer_now',{'request_id':'native-fixture'})[0],401)
|
||||
code,_,_=self.request('/v1/answer_now',{'request_id':'native-fixture'},{'Authorization':'Bearer '+'B'*32});self.assertEqual(code,404);self.assertEqual(self.w.controls,[])
|
||||
self.w.block.set();th.join(4)
|
||||
def test_control_remains_admitted_when_data_slots_are_saturated(self):
|
||||
th,_=self.stream();semaphore=self.f.ep.http.data_admission;held=0
|
||||
try:
|
||||
while semaphore.acquire(blocking=False):held+=1
|
||||
self.assertEqual(self.request('/v1/models')[0],429)
|
||||
self.assertEqual(self.request('/v1/answer_now',{'session_id':'synthetic-session'})[0],200)
|
||||
finally:
|
||||
for _ in range(held):semaphore.release()
|
||||
self.w.block.set();th.join(4)
|
||||
def test_queued_control_does_not_load_or_interrupt_current_owner(self):
|
||||
out={}
|
||||
with self.f.ep.scheduler.lease(('other-owner',)):
|
||||
th=threading.Thread(target=lambda:out.setdefault('value',self.request('/v1/chat/completions',self.chat(),{'X-Client-Request-Id':'queued-fixture'})),daemon=True);th.start()
|
||||
deadline=time.monotonic()+3
|
||||
while not self.f.ep.chat_controls.records and time.monotonic()<deadline:time.sleep(.01)
|
||||
self.assertEqual(self.request('/v1/answer_now',{'request_id':'queued-fixture'})[0],200);self.assertEqual(self.w.started,[]);self.assertEqual(self.w.controls,[])
|
||||
self.w.control_status=409
|
||||
th.join(4);self.assertFalse(th.is_alive());self.assertEqual(out['value'][0],200);self.assertEqual(self.w.requests[0]['reasoning_effort'],'none')
|
||||
def test_responses_alias_keeps_control_and_logprobs(self):
|
||||
self.f.ep.config['responses_compat']=True
|
||||
code,headers,value=self.request('/v1/responses',dict(model='alpha',input='Synthetic question',include=['message.output_text.logprobs'],top_logprobs=0))
|
||||
self.assertEqual(code,200);self.assertEqual(headers['X-Request-Id'],value['id']);self.assertEqual(value['output'][0]['content'][0]['logprobs'][0]['token'],'Synthetic');self.assertTrue(self.w.requests[-1]['logprobs'])
|
||||
def test_invalid_inputs_reject_before_model_load(self):
|
||||
bad=self.chat();bad['messages'][0]['content']=[dict(type='file',file=dict(filename='x.pdf',file_data='https://example.invalid/x.pdf'))]
|
||||
for body in (bad,self.chat(logprobs=True,top_logprobs=True),self.chat(top_logprobs=0),self.chat(session_id='bad\r\nheader')):
|
||||
with self.subTest(body=body):self.assertEqual(self.request('/v1/chat/completions',body)[0],400)
|
||||
self.assertEqual(self.w.started,[])
|
||||
def test_worker_generation_change_refuses_control(self):
|
||||
th,_=self.stream();self.w.generation='different-generation';self.assertEqual(self.request('/v1/answer_now',{'request_id':'synthetic-client'})[0],409);self.assertEqual(self.w.controls,[]);self.w.block.set();th.join(4)
|
||||
|
||||
|
||||
class ResponsesFeatureTests(unittest.TestCase):
|
||||
def test_probability_channels_survive_stream_and_complete(self):
|
||||
for stream in (False,True):
|
||||
with self.subTest(stream=stream):
|
||||
body=dict(model='fixture',input='fixture',include=['message.output_text.logprobs'],tools=[dict(type='function',name='read')]);_,converter=translate(body)
|
||||
lp={'token':'x','logprob':-.25,'bytes':[120],'top_logprobs':[]};message={'reasoning_content':'x','content':'x','tool_calls':[dict(id='c1',function=dict(name='read',arguments='{}'))]};probs={'content':[lp],'reasoning_content':[lp],'tool_calls':[{'index':0,'content':[lp]}]}
|
||||
value={'choices':[{'message':message,'finish_reason':'tool_calls','logprobs':probs}]}
|
||||
if stream:
|
||||
delta={**message,'tool_calls':[dict(message['tool_calls'][0],index=0)]};frame={'choices':[{'delta':delta,'finish_reason':'tool_calls','logprobs':probs}]};out=converter.feed(('data: '+json.dumps(frame)+'\n\ndata: [DONE]\n\n').encode())+converter.finish();self.assertIn(b'"logprobs"',out);result=converter.response
|
||||
else:result=converter.complete(value)
|
||||
outputs=result['output'];self.assertEqual(outputs[0]['logprobs'],[lp]);self.assertEqual(outputs[1]['content'][0]['logprobs'],[lp]);self.assertEqual(outputs[2]['logprobs'],[lp])
|
||||
def test_responses_file_video_tool_result_and_legacy_json_output(self):
|
||||
parts=[{'type':'input_file','filename':'note.txt','file_data':data_url('text/plain',b'Synthetic')},{'type':'input_video','video_url':data_url('video/mp4',b'Synthetic'),'max_frames':16}]
|
||||
chat,_=translate(dict(model='q',input=[dict(role='user',content=parts),dict(type='function_call_output',call_id='c1',output=parts)]));self.assertEqual(chat['messages'][0]['content'][0]['type'],'file');self.assertEqual(chat['messages'][1]['content'][1]['type'],'video_url')
|
||||
chat,_=translate(dict(model='q',input=[dict(type='function_call_output',call_id='c1',output=[{'answer':4}])],include=None));self.assertEqual(json.loads(chat['messages'][0]['content']),[{'answer':4}])
|
||||
def test_logprob_bounds_and_source_forms(self):
|
||||
for value in (True,-1,21,'3',.5):
|
||||
with self.subTest(value=value),self.assertRaises(CompatibilityError):normalize_chat({'logprobs':True,'top_logprobs':value})
|
||||
for value in (0,20):self.assertEqual(normalize_chat({'logprobs':True,'top_logprobs':value})[0]['top_logprobs'],value)
|
||||
for field in ('file_url','file_id'):
|
||||
with self.assertRaises(ResponsesError):translate(dict(model='q',input=[dict(role='user',content=[{'type':'input_file',field:'synthetic'}])]))
|
||||
|
||||
|
||||
class ManagerWorker(chat_fixtures.Worker):
|
||||
def capabilities(self,p):return dict(available=['documents','logprobs','answer_now'],session_affinity=True)
|
||||
def status(self):return {**super().status(),'generation':'synthetic-generation'}
|
||||
def answer_now(self,request):return {'state':'thinking'}
|
||||
|
||||
|
||||
class ManagerFeatureTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.f:Any=chat_fixtures.ChatTestsTests();self.f.setUp();self.f.worker.__class__=ManagerWorker;self.f.profile['parameters'].update(chat_runtime='basalt');self.f.profile['api_id']='fixture-api'
|
||||
def test_attachment_options_and_isolated_session_reach_admin_worker(self):
|
||||
request=self.f.request();request.update(session_id='browser-session',logprobs=True,top_logprobs=0);request['messages'][0]['content']=[dict(type='file',file=dict(filename='note.txt',file_data=data_url('text/plain',b'Synthetic note')))]
|
||||
self.f.manager.start(request);job=self.f.finish();self.assertEqual(job['state'],'complete');self.assertEqual(job['request_state'],'finished');body=json.loads(self.f.worker.conn.request.call_args.args[2]);self.assertEqual(body['model'],'fixture-api');self.assertNotEqual(body['session_id'],'browser-session');self.assertEqual(body['top_logprobs'],0);self.assertNotIn('Synthetic note',json.dumps(job))
|
||||
def test_queued_answer_now_and_stale_job_controls(self):
|
||||
with self.f.manager.scheduler.lease(('other-owner',)):
|
||||
job=self.f.manager.start(self.f.request());self.assertTrue(self.f.manager.status()['job']['can_answer_now'])
|
||||
with self.assertRaises(ControlError):self.f.manager.answer_now({'job_id':'other-job'})
|
||||
with self.assertRaises(ControlError):self.f.manager.stop('other-job')
|
||||
self.assertFalse(self.f.manager.cancel.is_set());self.assertEqual(self.f.manager.answer_now({'job_id':job['id']})['state'],'queued')
|
||||
self.assertEqual(self.f.finish()['state'],'complete');body=json.loads(self.f.worker.conn.request.call_args.args[2]);self.assertEqual(body['reasoning_effort'],'none')
|
||||
with self.assertRaises(ControlError):self.f.manager.answer_now({'job_id':job['id']})
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Synthetic pinned-profile installation and rollback-path contracts."""
|
||||
import hashlib
|
||||
import io
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from basalt_tuning import install_profile,profile_path,profile_ready
|
||||
|
||||
class TuningTests(unittest.TestCase):
|
||||
def recipe(self,data=b'synthetic routing metadata'):
|
||||
return dict(tuning=dict(expert_profile=dict(file='fixture.prof',url='https://raw.githubusercontent.com/example/pinned/fixture.prof',size=len(data),sha256=hashlib.sha256(data).hexdigest())))
|
||||
def test_install_verify_and_idempotent(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
data=b'synthetic routing metadata';r=self.recipe(data)
|
||||
with patch('basalt_tuning.urllib.request.urlopen',return_value=io.BytesIO(data)) as fetch:
|
||||
p=install_profile(tmp,r);self.assertTrue(profile_ready(tmp,r));self.assertEqual(p.read_bytes(),data)
|
||||
self.assertEqual(install_profile(tmp,r),p);fetch.assert_called_once()
|
||||
p.write_bytes(b'corrupt');self.assertFalse(profile_ready(tmp,r))
|
||||
with self.assertRaises(ValueError):install_profile(tmp,r)
|
||||
def test_wrong_hash_leaves_no_installed_file(self):
|
||||
with tempfile.TemporaryDirectory() as tmp,patch('basalt_tuning.urllib.request.urlopen',return_value=io.BytesIO(b'bad')):
|
||||
with self.assertRaises(ValueError):install_profile(tmp,self.recipe())
|
||||
self.assertFalse(profile_ready(tmp,self.recipe()))
|
||||
def test_legacy_recipe_retains_upstream_path(self):
|
||||
self.assertEqual(profile_path('/runtime',{}),Path('/runtime/source/data/profiles/qwen4exp-48x512.prof'))
|
||||
self.assertTrue(profile_ready('/runtime',{}))
|
||||
def test_traversal_and_symlink_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
r=self.recipe();r['tuning']['expert_profile']['file']='../outside.prof'
|
||||
with self.assertRaises(ValueError):install_profile(tmp,r)
|
||||
(Path(tmp)/'elsewhere').mkdir();(Path(tmp)/'profiles').symlink_to(Path(tmp)/'elsewhere')
|
||||
with self.assertRaises(ValueError):install_profile(tmp,self.recipe())
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Metadata-only controls, no model, production service or credentials."""
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
from chat_control import ChatControls,ControlError,immediate_answer,session_id
|
||||
|
||||
|
||||
class ControlsTests(unittest.TestCase):
|
||||
def setUp(self):self.clock=[1.0];self.controls=ChatControls(clock=lambda:self.clock[0]);self.profile={'id':'p','revision':3};self.send=Mock(return_value={'state':'thinking'})
|
||||
def start(self,owner='caller-a',**kw):return self.controls.begin(owner,self.profile,supported=True,**kw)
|
||||
def request(self,key,owner='caller-a'):return self.controls.request(owner,{'request_id':key},{},self.send)
|
||||
def test_queued_request_does_not_touch_worker(self):
|
||||
key=self.start();self.assertEqual(self.request(key)['state'],'queued');self.send.assert_not_called();self.assertTrue(self.controls.dispatch(key,'generation'))
|
||||
self.assertFalse(self.controls.view(key)['can_answer_now'])
|
||||
def test_running_control_is_bound_to_generation_and_profile(self):
|
||||
key=self.start();self.controls.dispatch(key,'generation');self.controls.activate(key,'generation');self.controls.bind(key,'chatcmpl-synthetic')
|
||||
self.assertEqual(self.request('chatcmpl-synthetic')['state'],'thinking');selected=self.send.call_args.args[0]
|
||||
self.assertEqual((selected['id'],selected['profile_id'],selected['revision'],selected['generation']),(key,'p',3,'generation'))
|
||||
def test_other_principal_cannot_control_id_or_session(self):
|
||||
key=self.start(session='same');other=self.start(owner='caller-b',session='same')
|
||||
with self.assertRaises(ControlError) as e:self.request(key,'caller-b')
|
||||
self.assertEqual(e.exception.status,404);self.send.assert_not_called()
|
||||
self.assertNotEqual(self.controls.headers(key)['x-session-id'],self.controls.headers(other)['x-session-id'])
|
||||
def test_aliases_priority_and_session_lookup(self):
|
||||
key=self.start(client_id='client-synthetic',session='session-synthetic')
|
||||
self.assertEqual(session_id({'x-session-id':'third','x-llm-flow-id':'first'},{'session_id':'body'}),'first')
|
||||
self.assertEqual(self.request('client-synthetic')['request_id'],key)
|
||||
fresh=self.start(session='session-synthetic');result=self.controls.request('caller-a',{'session_id':'session-synthetic'},{},self.send)
|
||||
self.assertEqual(result['request_id'],fresh)
|
||||
def test_finished_answering_off_and_duplicate_rejected(self):
|
||||
for state in ('finished','answering','off'):
|
||||
key=self.start(can_think=state!='off')
|
||||
if state=='finished':self.controls.finish(key)
|
||||
elif state=='answering':self.controls.answering(key)
|
||||
with self.subTest(state=state),self.assertRaises(ControlError) as e:self.request(key)
|
||||
self.assertEqual(e.exception.status,409)
|
||||
self.start(client_id='unique')
|
||||
with self.assertRaises(ControlError):self.start(client_id='unique')
|
||||
def test_bounded_records_never_evict_running_work(self):
|
||||
self.controls.maximum=2;one=self.start();two=self.start()
|
||||
with self.assertRaises(ControlError):self.start()
|
||||
self.controls.finish(one);three=self.start();self.assertIn(two,self.controls.records);self.assertIn(three,self.controls.records)
|
||||
def test_expiry_and_no_payload_or_raw_session_storage(self):
|
||||
key=self.start(session='private-session-label');self.assertNotIn('private-session-label',str(self.controls.records))
|
||||
self.controls.finish(key);self.clock[0]+=601
|
||||
with self.assertRaises(ControlError):self.request(key)
|
||||
self.assertNotIn(key,self.controls.records)
|
||||
def test_control_inputs_are_not_generic_routes_or_payloads(self):
|
||||
key=self.start()
|
||||
for body in ({},{'request_id':'bad\r\nheader'},{'request_id':True},{'request_id':key,'session_id':'sid'},{'request_id':key,'prompt':'must-not-be-stored'}):
|
||||
with self.subTest(body=body),self.assertRaises(ControlError):self.controls.request('caller-a',body,{},self.send)
|
||||
self.send.assert_not_called()
|
||||
def test_unsupported_backend_no_callback_and_dispatch_race_is_queued(self):
|
||||
key=self.controls.begin('caller-a',self.profile,supported=False)
|
||||
with self.assertRaises(ControlError) as e:self.request(key)
|
||||
self.assertEqual(e.exception.status,501)
|
||||
key=self.start();self.controls.dispatch(key,'g');self.assertEqual(self.request(key)['state'],'queued');self.send.assert_not_called()
|
||||
def test_immediate_answer_only_changes_request_copy(self):
|
||||
body={'reasoning_effort':'high','reasoning_budget_tokens':4096,'chat_template_kwargs':{'preserve_thinking':True}}
|
||||
new=immediate_answer(body);self.assertEqual(body['reasoning_effort'],'high');self.assertNotIn('reasoning_budget_tokens',new);self.assertFalse(new['chat_template_kwargs']['enable_thinking']);self.assertTrue(new['chat_template_kwargs']['preserve_thinking'])
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Inline-only synthetic media fixtures; never reads client files or a GPU."""
|
||||
import base64
|
||||
import copy
|
||||
import io
|
||||
import unittest
|
||||
import zipfile
|
||||
from unittest.mock import patch
|
||||
from chat_media import LIMITS,MediaError,normalize_messages,pages,validate_messages
|
||||
|
||||
|
||||
def data(mime,raw):return 'data:'+mime+';base64,'+base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
class MediaTests(unittest.TestCase):
|
||||
def setUp(self):self.profile={'parameters':{'chat_runtime':'basalt','vision_projector':'synthetic'}};self.features=('documents','video')
|
||||
def file(self,name='sample.pdf',mime='application/pdf',raw=b'%PDF-1.7\nsynthetic'):
|
||||
return {'type':'file','file':{'filename':name,'file_data':data(mime,raw)}}
|
||||
def messages(self,part,role='user'):return [{'role':role,'content':[{'type':'text','text':'Synthetic question.'},part]}]
|
||||
def validate(self,part,**kw):return validate_messages(self.messages(part),self.profile,kw.get('features',self.features))
|
||||
def test_pdf_inline_preserved_and_pages_checked(self):
|
||||
part=self.file();part['file']['pages']='1-5,8';before=copy.deepcopy(part);self.assertEqual(self.validate(part)['attachments'],1);self.assertEqual(part,before)
|
||||
for value in ('0','600-601','5-2','1,,2',True,'1-100000000'):
|
||||
with self.subTest(value=value),self.assertRaises(MediaError):pages(value)
|
||||
def test_utf8_text_documents(self):
|
||||
self.validate(self.file('note.txt','text/plain','Grün und vollständig.'.encode()))
|
||||
with self.assertRaises(MediaError):self.validate(self.file('note.txt','text/plain',b'\xff'))
|
||||
def test_remote_paths_file_ids_and_wrong_mime_are_rejected(self):
|
||||
for value in ('https://example.invalid/a.pdf','file:///etc/passwd','/etc/passwd','data:application/pdf;base64,@@'):
|
||||
part=self.file();part['file']['file_data']=value
|
||||
with self.subTest(value=value),self.assertRaises(MediaError):self.validate(part)
|
||||
for extra in ({'file_id':'id'},{'file_url':'https://example.invalid/a.pdf'}):
|
||||
part=self.file();part['file'].update(extra)
|
||||
with self.assertRaises(MediaError):self.validate(part)
|
||||
with self.assertRaises(MediaError):self.validate(self.file(mime='text/plain'))
|
||||
def test_no_capability_or_vision_is_not_silently_accepted(self):
|
||||
with self.assertRaises(MediaError) as e:self.validate(self.file(),features=())
|
||||
self.assertEqual(e.exception.status,501)
|
||||
part={'type':'video_url','video_url':{'url':data('video/mp4',b'synthetic-video')}}
|
||||
self.profile['parameters'].pop('vision_projector')
|
||||
with self.assertRaises(MediaError):self.validate(part)
|
||||
def test_video_defaults_are_bounded_and_caller_is_unchanged(self):
|
||||
part={'type':'video_url','video_url':{'url':data('video/mp4',b'synthetic-video')}};messages=self.messages(part);before=copy.deepcopy(messages)
|
||||
normalized,_=normalize_messages(messages,self.profile,self.features);self.assertEqual(messages,before)
|
||||
self.assertEqual(normalized[0]['content'][1]['max_frames'],128);self.assertEqual(normalized[0]['content'][1]['fps'],2)
|
||||
for fields in ({'fps':True},{'fps':float('inf')},{'fps':3},{'max_frames':True},{'max_frames':769},{'max_frames':3}):
|
||||
with self.subTest(fields=fields),self.assertRaises(MediaError):self.validate({**part,**fields})
|
||||
def test_filenames_roles_and_unknown_parts(self):
|
||||
for name in ('../x.pdf','/x.pdf','C:\\x.pdf','bad\n.pdf','x.exe',''):
|
||||
with self.subTest(name=name),self.assertRaises(MediaError):self.validate(self.file(name=name))
|
||||
for role in ('system','developer','assistant'):
|
||||
with self.assertRaises(MediaError):validate_messages(self.messages(self.file(),role),self.profile,self.features)
|
||||
with self.assertRaises(MediaError):self.validate({'type':'document','source':{'path':'/etc/passwd'}})
|
||||
def test_request_wide_attachment_limits(self):
|
||||
messages=[{'role':'user','content':[self.file() for _ in range(9)]}]
|
||||
with self.assertRaises(MediaError):validate_messages(messages,self.profile,self.features)
|
||||
with patch.dict(LIMITS,attachment_bytes=30):
|
||||
with self.assertRaises(MediaError):validate_messages([{'role':'user','content':[self.file(),self.file()]}],self.profile,self.features)
|
||||
def test_office_metadata_without_extraction(self):
|
||||
def archive(name='word/document.xml',content=b'<document/>'):
|
||||
out=io.BytesIO()
|
||||
with zipfile.ZipFile(out,'w') as z:z.writestr('[Content_Types].xml','<Types/>');z.writestr(name,content)
|
||||
return out.getvalue()
|
||||
mime='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
|
||||
self.validate(self.file('sample.docx',mime,archive()))
|
||||
for raw in (b'not-a-zip',archive('../outside'),archive('word/document.xml',b'x'*(1024*1024))):
|
||||
with patch('chat_media.MIB',1024):
|
||||
with self.assertRaises(MediaError):self.validate(self.file('sample.docx',mime,raw))
|
||||
def test_legacy_image_rule_and_size(self):
|
||||
self.validate({'type':'image_url','image_url':{'url':data('image/png',b'png-fixture')}})
|
||||
with self.assertRaises(MediaError):self.validate({'type':'image_url','image_url':{'url':'https://example.invalid/a.png'}})
|
||||
with patch.dict(LIMITS,document_bytes=4):
|
||||
with self.assertRaises(MediaError):self.validate(self.file())
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -7,7 +7,16 @@ from inference import LlamaWorker,InferenceError
|
||||
from profiles import SCHEMAS,CHAT_GPU_DEFAULTS
|
||||
|
||||
class WorkerTests(unittest.TestCase):
|
||||
def test_worker_launch_mock_does_not_intercept_unrelated_subprocesses(self):
|
||||
import subprocess
|
||||
with patch('inference.subprocess.Popen') as launch:
|
||||
self.assertIsNot(subprocess.Popen,launch)
|
||||
def setUp(self):
|
||||
# Popen patches must stay local to this worker, not capture sampler threads
|
||||
# that use the shared stdlib subprocess module in other components.
|
||||
import subprocess
|
||||
|
||||
process_api=patch('inference.subprocess',SimpleNamespace(**vars(subprocess)));process_api.start();self.addCleanup(process_api.stop)
|
||||
self.tmp=tempfile.TemporaryDirectory();self.root=Path(self.tmp.name);directory=self.root/'runtime'/'build-id'/'build/bin';directory.mkdir(parents=True);(directory/'llama-server').touch()
|
||||
self.entry=dict(id='model',file='test.gguf',size=1024**3)
|
||||
self.runtime=SimpleNamespace(root=self.root/'runtime',status=lambda:dict(active='build-id',builds=[dict(id='build-id',backend='CUDA',fit_tool=True)]))
|
||||
|
||||
@@ -27,7 +27,9 @@ class LegacyCleanupTests(unittest.TestCase):
|
||||
weight = state / 'runtime' / 'weight.bin'
|
||||
weight.write_bytes(b'weight')
|
||||
link = state / 'models' / 'weight.bin'
|
||||
link.symlink_to('/var/lib/deck/runtime/weight.bin')
|
||||
# Resolution is scripted below; no real link into a live-state path
|
||||
# is necessary to exercise container-to-native path translation.
|
||||
link.touch()
|
||||
# Athena is Linux; macOS resolves /var to /private/var instead.
|
||||
expected = weight.resolve()
|
||||
with patch.object(cleanup, 'STATE', state), patch.object(
|
||||
|
||||
+24
-1
@@ -144,7 +144,7 @@ class Tests(unittest.TestCase):
|
||||
|
||||
def test_chat_test_routes_are_admin_only(self):
|
||||
self.assertIsNone(self.request('chat-tests')['job'])
|
||||
for path,method,body in [('chat-tests','GET',None),('chat-tests/start','POST',b'{}'),('auto-tests','GET',None),('auto-tests/start','POST',b'{}'),('auto-tests/save','POST',b'{}')]:
|
||||
for path,method,body in [('chat-tests','GET',None),('chat-tests/start','POST',b'{}'),('chat-tests/capabilities?profile_id=test','GET',None),('chat-tests/answer-now','POST',b'{}'),('auto-tests','GET',None),('auto-tests/start','POST',b'{}'),('auto-tests/save','POST',b'{}')]:
|
||||
req=urllib.request.Request(self.url+'/api/v1/'+path,method=method,data=body,headers={'Authorization':'Bearer '+self.api_token,'X-Athena-Deck':'1','Content-Type':'application/json'})
|
||||
with self.assertRaises(urllib.error.HTTPError) as exc:urllib.request.urlopen(req)
|
||||
self.assertEqual(exc.exception.code,401);exc.exception.close()
|
||||
@@ -154,6 +154,29 @@ class Tests(unittest.TestCase):
|
||||
with urllib.request.urlopen(req) as r:self.assertEqual(json.load(r)['state'],'running')
|
||||
start.assert_called_once_with(data)
|
||||
|
||||
def test_chat_control_requires_csrf_and_current_job_id(self):
|
||||
with patch.object(self.server.chat_tests,'answer_now',return_value={'state':'thinking'}) as control:
|
||||
for headers,expected in [({'Cookie':self.cookie},403),({'Cookie':self.cookie,'X-Athena-Deck':'1'},200)]:
|
||||
req=urllib.request.Request(self.url+'/api/v1/chat-tests/answer-now',data=b'{"job_id":"fixture"}',headers={'Content-Type':'application/json',**headers})
|
||||
try:
|
||||
with urllib.request.urlopen(req) as result:self.assertEqual(result.status,expected)
|
||||
except urllib.error.HTTPError as error:self.assertEqual(error.code,expected);error.close()
|
||||
control.assert_called_once_with({'job_id':'fixture'})
|
||||
with patch.object(self.server.chat_tests,'stop',return_value={'cancellation_requested':True}) as stop:
|
||||
req=urllib.request.Request(self.url+'/api/v1/chat-tests/cancel',data=b'{"job_id":"fixture"}',headers={'Content-Type':'application/json','Cookie':self.cookie,'X-Athena-Deck':'1'})
|
||||
with urllib.request.urlopen(req) as result:self.assertEqual(result.status,200)
|
||||
stop.assert_called_once_with('fixture')
|
||||
|
||||
def test_chat_media_upload_has_own_limit_not_global_config_limit(self):
|
||||
with patch.object(self.server.chat_tests,'start',return_value={'state':'running'}) as start:
|
||||
data={'profile_id':'test','messages':[{'role':'user','content':'x'*40000}],'max_tokens':8}
|
||||
req=urllib.request.Request(self.url+'/api/v1/chat-tests/start',data=json.dumps(data).encode(),headers={'Cookie':self.cookie,'X-Athena-Deck':'1','Content-Type':'application/json'})
|
||||
with urllib.request.urlopen(req) as result:self.assertEqual(result.status,200)
|
||||
start.assert_called_once_with(data)
|
||||
req=urllib.request.Request(self.url+'/api/v1/endpoint/config',data=json.dumps({'padding':'x'*40000}).encode(),headers={'Cookie':self.cookie,'X-Athena-Deck':'1','Content-Type':'application/json'})
|
||||
with self.assertRaises(urllib.error.HTTPError) as error:urllib.request.urlopen(req)
|
||||
self.assertEqual(error.exception.code,400);error.exception.close()
|
||||
|
||||
def test_control_guard(self):
|
||||
for headers in ({},{'X-Athena-Deck':'1','Origin':'http://evil.invalid'}):
|
||||
with self.assertRaises(urllib.error.HTTPError) as e:self.request('demo/start','POST',headers)
|
||||
|
||||
@@ -4,7 +4,7 @@ from stimmatelier_proxy import asset
|
||||
class StudioProxyTests(unittest.TestCase):
|
||||
def test_unix_proxy_serves_only_fixed_assets_without_network_or_credentials(self):
|
||||
spec=importlib.util.spec_from_file_location('studio_app',Path(__file__).parent/'deploy/stimmatelier/app.py');module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
|
||||
with tempfile.TemporaryDirectory(prefix='studio-',dir='/tmp') as d:
|
||||
with tempfile.TemporaryDirectory(prefix='studio-') as d:
|
||||
root=Path(d);folder=root/'stimmatelier-ui';folder.mkdir()
|
||||
server=module.Server(str(folder/'ui.sock'),module.Handler);thread=threading.Thread(target=server.serve_forever);thread.start()
|
||||
try:
|
||||
|
||||
Reference in new issue
Block a user