Resolve generic TTS from audio publication and preserve admitted work during drain

This commit is contained in:
Mikei386 committed 2026-10-27 12:16:39 +01:00
1 parent c60de7db2c
commit e83b30badc
4 files changed
+112 -5

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
# Generic TTS alias and safe drain — 27 October 2026
## Reproduced live failure
After shared Hermes configuration was corrected to `tts.openai.model: tts`,
Conduit was reported to play an Edge-like replacement voice. No new Articulino
job appeared. A bounded synthetic request reproduced:
- `POST /v1/audio/speech`, model `tts`: HTTP 409,
`tts_default_ambiguous`, before any synthesis.
- Same request with explicit `articulino-anna-cpu`: HTTP 200, mono PCM16 24 kHz,
176,640 bytes (3.68 seconds audio), first bytes 0.7787 seconds, total 0.8975
seconds. No LLM turn or production text was used.
Athena advertised one dedicated audio profile (Articulino) plus the independent
voice-tool profile OmniVoice Studio. The old alias resolver counted both as
TTS candidates, contradicting the UI's single TTS publication and the desired
stable client endpoint. The exact origin of the perceived Edge replacement
voice has not been established; the verified failure is the rejected upstream
request, not a confirmed native playback defect.
## Correction
Dedicated `kind=audio` publication now controls `model=tts`. Voice-tool profiles
are considered only when no dedicated audio profile is published, preserving
voice-only clients. Multiple audio publications still produce 409; disabled or
unrunnable profiles do not become silently available. Explicit voice-tool model
names and publication are preserved; OmniVoice was not disabled or removed.
No client patch, provider change or extra service is needed.
A separate safety regression test found that the old stop implementation let
active replies finish but rejected already queued chat/image work through its
post-queue state guard. The authenticated route now records admission and lets
only those already accepted requests continue during `stopping`. The initial
route guard still rejects all new requests, and profile revision/enable checks
remain enforced. This makes the requested maintenance drain semantics explicit.
The running old instance had zero queued work in the observations before the
operator drain; no running model response was intentionally cancelled.
## Validation / activation
- Initial alias-only regression run: 83 tests passed.
- Alias + drain implementation: 84 tests passed across endpoint, Articulino,
Pocket and native Qwen.
- Additional boundary check: two tests passed, proving two active synthetic
streams plus a queued request finish, while new requests in `stopping`
receive 503 before any lease/model execution.
- Thin image built from the verified currently active Articulino image, replacing
only `endpoint.py`; no OS/driver/runtime/weight change.
- Automatic approval initially rejected the stop button with two active requests.
No alternate control path was used. Michael then explicitly authorized pausing
new admissions, letting existing work finish and restarting Deck afterward.
Production activation and post-change alias/client acceptance pending.
+13 -5
View File
@@ -369,7 +369,7 @@ class APIHandler(BaseHTTPRequestHandler):
def do_HEAD(self):self.route()
def do_OPTIONS(self):self.route()
def route(self):
ep=self.server.endpoint;admitted=False
ep=self.server.endpoint;admitted=False;self._admitted=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','')))
@@ -378,7 +378,7 @@ class APIHandler(BaseHTTPRequestHandler):
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)
with ep.lock:
if not ep.allowed():raise APIError('Endpunkt wird gestoppt.',503,'endpoint_stopping')
ep.inflight+=1;admitted=True
ep.inflight+=1;admitted=True;self._admitted=True
parsed=urlsplit(self.path)
if self.command=='GET' and parsed.path=='/v1/telemetry/speed':
provider=getattr(ep,'speed_telemetry',None)
@@ -507,7 +507,13 @@ class APIHandler(BaseHTTPRequestHandler):
started=time.monotonic()
if data.get('model')=='tts':
from profiles import voice_recipe
candidates=[p for p in ep.rows() if p['enabled'] and (p['kind']=='audio' or p.get('model') and voice_recipe(p['model']))]
rows=ep.rows()
# The TTS publication controls the generic speech alias. Voice-tool
# profiles may also synthesize text, but must not make a separately
# published TTS profile ambiguous. Preserve voice-only clients when
# no dedicated audio profile is published.
candidates=[p for p in rows if p['enabled'] and p['kind']=='audio']
if not candidates:candidates=[p for p in rows if p['enabled'] and p.get('model') and voice_recipe(p['model'])]
if len(candidates)!=1:raise APIError('Für model=tts genau ein TTS-Profil am Endpunkt freigeben.',409,'tts_default_ambiguous')
data=dict(data,model=candidates[0].get('api_id',candidates[0]['name']))
from humaneness_runtime import supported as humaneness_model
@@ -652,8 +658,10 @@ class APIHandler(BaseHTTPRequestHandler):
except (ValueError,binascii.Error):raise APIError('Ungültige Bildkodierung.') from None
if not raw:raise APIError('Leeres Bild.')
# 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() and any(p['id']==profile['id'] and p['revision']==profile['revision'] and p['enabled'] for p in ep.rows())
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)
@@ -701,7 +709,7 @@ class APIHandler(BaseHTTPRequestHandler):
size=data.get('size')
if size is not None and (not isinstance(size,str) or (size!='auto' and not re.fullmatch(r'[1-9][0-9]{1,4}x[1-9][0-9]{1,4}',size))):raise APIError('size muss auto oder eine Auflösung wie 1024x1024 sein.')
# The selected profile owns resource limits; client size is only a preference.
def allowed():return ep.allowed() and any(p['id']==profile['id'] and p['revision']==profile['revision'] and p['enabled'] for p in ep.rows())
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(('image',),allowed=allowed):
return self.generate_image(ep,profile,data,reference_images or [])
def generate_image(self,ep,profile,data,reference_images=None):
+16
View File
@@ -50,6 +50,22 @@ class ArticulinoTests(unittest.TestCase):
APIHandler.speech(h,ep,dict(model=model,input='Ein synthetischer Satz.',response_format=fmt))
ep.articulino.start.assert_called_once();pocket.start.assert_not_called();ep.tts.start.assert_not_called()
self.assertEqual(ep.articulino.start.call_args.kwargs['streaming'],fmt=='pcm')
def test_generic_tts_prefers_audio_publication_over_omnivoice(self):
h,ep,pocket,row=test_pocket.SpeechRoutingTests().fixture()
row.update(model=MODEL,api_id='articulino-anna-cpu');ep.articulino=Mock()
ep.articulino.start.return_value={'id':'job'};ep.articulino.status.return_value=pocket.status.return_value
ep.articulino.job_status.return_value=pocket.job_status.return_value;ep.articulino.audio.return_value=b'RIFF-articulino'
omni=dict(id='omni',kind='voice',enabled=True,name='OmniVoice Studio',api_id='omnivoice-studio',model=dict(kind='voice',repo='k2-fsa/OmniVoice',file='model.safetensors'))
ep.rows=lambda:[row,omni];ep.voxcpm=Mock()
APIHandler.speech(h,ep,dict(model='tts',input='Synthetischer Text.'))
ep.articulino.start.assert_called_once();ep.voxcpm.start.assert_not_called();pocket.start.assert_not_called()
def test_generic_tts_keeps_voice_only_compatibility(self):
h,ep,pocket,row=test_pocket.SpeechRoutingTests().fixture()
row.update(kind='voice',name='OmniVoice Studio',api_id='omnivoice-studio',model=dict(kind='voice',repo='k2-fsa/OmniVoice',file='model.safetensors'))
ep.voxcpm=Mock();ep.voxcpm.start.return_value={'id':'job'};ep.voxcpm.status.return_value=pocket.status.return_value
ep.voxcpm.job_status.return_value=pocket.job_status.return_value;ep.voxcpm.audio.return_value=b'RIFF-omni';ep.root=Path('/test')
with patch('endpoint.speech_reference',return_value={}):APIHandler.speech(h,ep,dict(model='tts',input='Synthetischer Text.'))
ep.voxcpm.start.assert_called_once();pocket.start.assert_not_called()
def test_worker_pcm_matches_wav_and_cooperative_cancel(self):
import numpy as np
from articulino_worker import generate
+29
View File
@@ -469,6 +469,35 @@ class EndpointTests(unittest.TestCase):
while not self.ep.scheduler.status()['waiting_requests'] and time.monotonic()<deadline:time.sleep(.01)
self.assertEqual(self.worker.name,'alpha');self.assertEqual(self.worker.stopped,[])
self.worker.block.set();self.assertIn(b'[DONE]',r.read());conn.close();thread.join(3);self.assertEqual(result[0][0],200);self.assertEqual(self.worker.name,'beta')
def test_stopping_rejects_new_requests_before_lease(self):
self.enable('alpha');self.ep.state='stopping'
try:
code,data=self.request('/v1/chat/completions',dict(model='alpha',messages=[{}]))
self.assertEqual(code,503);self.assertEqual(data['error']['code'],'endpoint_stopping')
self.assertEqual(self.ep.inflight,0);self.assertEqual(self.worker.requests,[]);self.assertEqual(self.worker.started,[])
finally:self.ep.state='running'
def test_stop_drains_two_streams_and_queued_request_without_abort(self):
self.enable('alpha');self.enable('beta');self.worker.block.clear();streams=[];result=[]
try:
for _ in range(2):
conn=http.client.HTTPConnection('127.0.0.1',self.port,timeout=5)
conn.request('POST','/v1/chat/completions',json.dumps(dict(model='alpha',messages=[{}],stream=True)),headers={'Content-Type':'application/json','Authorization':'Bearer '+'A'*32})
response=conn.getresponse();self.assertEqual(response.status,200);streams.append((conn,response))
queued=threading.Thread(target=lambda:result.append(self.request('/v1/chat/completions',dict(model='beta',messages=[{}]))));queued.start()
deadline=time.monotonic()+2
while not self.ep.scheduler.status()['waiting_requests'] and time.monotonic()<deadline:time.sleep(.01)
self.assertEqual(self.ep.scheduler.status()['active_requests'],2)
self.assertEqual(self.ep.scheduler.status()['waiting_requests'],1)
self.ep.stop();self.assertEqual(self.ep.state,'stopping');self.assertEqual(self.worker.stopped,[])
self.worker.block.set()
for conn,response in streams:self.assertIn(b'[DONE]',response.read());conn.close()
queued.join(3);self.assertFalse(queued.is_alive());self.assertEqual(result[0][0],200)
deadline=time.monotonic()+3
while self.ep.state!='stopped' and time.monotonic()<deadline:time.sleep(.01)
self.assertEqual(self.ep.state,'stopped');self.assertEqual(self.ep.inflight,0)
finally:
self.worker.block.set()
for conn,response in streams:conn.close()
def test_port_conflict_and_graceful_stop(self):
with self.assertRaises(ValueError):self.ep.configure(dict(port=self.port+1))
self.ep.stop();deadline=time.monotonic()+3