Files
rag-technical-docs-assistant/services/local_s2s/lifecycle.py
T
amirhosein mazaheri 628aec8def feat(voice): implement local S2S responsiveness candidate and direct TTS routing
Add local S2S responsiveness candidate pinning ASR options and sentence-at-a-time generation. Route speech synthesis directly to OpenAI API for fluent Persian phonetics with gpt-4o-mini-tts-2025-12-15. Add responsiveness, budget carry, and browser watch unit tests along with acceptance benchmarks and evaluation evidence.
2026-10-17 13:02:41 +03:30

109 lines
4.2 KiB
Python

"""Independent bounded cleanup and owned process signal lifecycle."""
from contextlib import contextmanager
import json
import signal
from threading import Event, Lock, Thread
import time
from services.local_s2s.components import start_components
@contextmanager
def termination_signals(stop):
previous = {sig: signal.getsignal(sig) for sig in (signal.SIGINT, signal.SIGTERM)}
try:
for sig in previous:
signal.signal(sig, lambda *_: stop.set())
yield
finally:
for sig, handler in previous.items():
signal.signal(sig, handler)
def bounded_call(action, timeout):
finished, result = Event(), []
def run():
try:
action()
result.append(0)
except BaseException:
result.append(1)
finally:
finished.set()
Thread(target=run, daemon=True).start()
return result[0] if finished.wait(timeout) else 2
def cleanup(runtime, guard, thread, stop, *, timeout=2, emit=print):
stop.set()
counters = {}
# Cancel owned provider I/O before joining workers which may be awaiting it.
# Every operation is independent; one failure cannot skip later cleanup.
for name, action in (
('gateway_shutdown', guard.shutdown),
('gateway_close', guard.server_close),
('runtime_stop', runtime.stop if runtime is not None else lambda: None),
('gateway_join', lambda: thread.join(timeout)),
):
counters[name] = bounded_call(action, timeout)
counters['gateway_alive'] = int(thread.is_alive())
emit(json.dumps(dict(stage='close', cleanup=counters, request_counts=dict(guard.counts))), flush=True)
return any(counters.values())
def run_owned(build, key, request_timeout, *, startup_timeout=90, cleanup_timeout=2, emit=print, component_options=None):
stop, constructed, finished, abandoned, lock = Event(), Event(), Event(), Event(), Lock()
runtime = None
result = {}
with termination_signals(stop):
guard, thread = start_components(key, request_timeout, **(component_options or {}))
def drive():
nonlocal runtime
if stop.is_set():
return 1
def construct():
try:
value = build(stop)
with lock:
if not abandoned.is_set():
result['runtime'] = value
else:
bounded_call(value.stop, cleanup_timeout)
except BaseException:
result['failed'] = True
finally:
constructed.set()
Thread(target=construct, daemon=True).start()
deadline = time.monotonic() + startup_timeout
while not constructed.wait(.01):
if stop.is_set() or time.monotonic() >= deadline:
with lock:
abandoned.set()
emit(json.dumps(dict(status='failed', category='LOCAL_ENGINE_STARTUP_DEADLINE')), flush=True)
return 1
runtime = result.get('runtime')
if runtime is None or stop.is_set():
emit(json.dumps(dict(status='failed', category='LOCAL_ENGINE_STARTUP_OR_RUNTIME_FAILURE')), flush=True)
return 1
emit(json.dumps(dict(stage='startup', request_counts=dict(guard.counts))), flush=True)
def serve():
try:
runtime.start()
runtime.wait()
except BaseException:
result['failed'] = True
finally:
finished.set()
Thread(target=serve, daemon=True).start()
while not finished.wait(.02) and not stop.is_set():
pass
return int(bool(result.get('failed')))
try:
outcome = drive()
finally:
# Fetch a construction result which raced the deadline before abandoning it.
with lock:
abandoned.set()
runtime = runtime or result.get('runtime')
cleanup_failed = cleanup(runtime, guard, thread, stop, timeout=cleanup_timeout, emit=emit)
return int(outcome or cleanup_failed)