Files
rag-technical-docs-assistant/tests/unit/test_local_s2s_repairs.py
T
amirhosein mazaheri 8d348f0ba1 feat(voice): add isolated Local S2S v3 candidate and acceptance evidence
Extract the provider boundary while retaining OpenAI/Gemini contracts. Add
an opt-in isolated Local S2S adapter, pinned engine extension, bounded
component gateway and frozen effective configuration profiles.

Enforce request token limits, zero retries, local asset validation,
connection deadlines, disconnect ownership, bounded cleanup and signals.
Include regression coverage, pinned source fixtures, operator guidance,
asset fingerprints and guarded disposable PostgreSQL acceptance tooling.
Preserve immutable fixture bytes across Git line-ending conversion.

Validation recorded in the reports:
- 74 repair, 107 combined and 242 preservation checks passed.
- Fresh PostgreSQL local checks: 2 passed.
- Expanded PostgreSQL: 57 passed, 6 documented baseline failures.
- Compose configurations, staged whitespace and fixture hashes passed.

Phase 1 live listening and Phase 2 complete engine/SDK/POSIX, real component
audio and Persian browser acceptance remain pending. No operational switch,
paid call, model download or Phase 3 implementation is included.
2026-10-15 12:28:17 +03:30

591 lines
30 KiB
Python

"""Regression evidence for five repairs: real pinned methods and owned loopback I/O."""
import asyncio
from contextlib import contextmanager
import hashlib
import json
import logging
from pathlib import Path
import signal
import socket
import socketserver
from threading import Event, Lock, Thread, Timer, current_thread, BoundedSemaphore
import time
from types import SimpleNamespace
import httpx
import pytest
from services.local_s2s.request_policy import LimitedChatClient, install_client_policy
from services.local_s2s.components import ComponentServer, CLEANUP_WINDOW_SECONDS
from services.local_s2s.assets import REQUIRED_NLTK, REQUIRED_VAD, AssetError, validate_assets, configure_nltk, patch_pipeline_source
from services.local_s2s.lifecycle import cleanup, run_owned
from tests.support.local_s2s_pinned import functions, tree, constant, ROOT
from tests.unit.test_local_s2s_phase2 import local_config
class RecordingSDK:
"""SDK boundary stand-in; pinned request/setup/process/warmup methods run unchanged."""
def __init__(self, calls, *, max_retries=0, failure=None, **kwargs):
self.calls, self.max_retries, self.failure = calls, max_retries, failure
self.chat = SimpleNamespace(completions=SimpleNamespace(create=self.create))
def with_options(self, **kwargs):
return RecordingSDK(self.calls, max_retries=kwargs.get('max_retries', self.max_retries), failure=self.failure)
def create(self, **kwargs):
payload = {key: value for key, value in kwargs.items() if key != 'timeout'}
def send(request):
self.calls.append(json.loads(request.content))
if self.failure:
raise self.failure
return httpx.Response(200, json={})
for attempt in range(self.max_retries + 1):
try:
with httpx.Client(transport=httpx.MockTransport(send), trust_env=False) as transport:
transport.post('https://fixture.invalid/v1/chat/completions', json=payload)
return payload
except httpx.HTTPError:
if attempt == self.max_retries:
raise
def upstream_handler(client):
ns = dict(time=time, logger=logging.getLogger('pinned-fixture'), WARMUP_MAX_RETRIES=constant('base.py.source', 'WARMUP_MAX_RETRIES'),
_build_chat_optional_kwargs=lambda *_: {})
functions('chat.py.source', [(None, '_request_chat_completions'),
('ChatCompletionsApiModelHandler', '_request'), ('ChatCompletionsApiModelHandler', 'warmup'),
('ChatCompletionsApiModelHandler', '_build_optional_kwargs')], ns)
functions('base.py.source', [('BaseOpenAICompatibleHandler', 'process'), ('BaseOpenAICompatibleHandler', 'setup')], ns)
ns.update(os=__import__('os'), httpx=httpx, BoundedSemaphore=BoundedSemaphore,
Lock=Lock, PREFETCH_PROVIDER_WORKER_LIMIT=2)
ns.update(is_out_of_band=lambda _: False, resolve_auto_language=lambda x: (x, None),
language_name_for_prompt=lambda *a, **k: None, response_wants_audio=lambda _: True,
_Turn=lambda **kw: SimpleNamespace(**kw))
Handler = type('PinnedHandler', (), {name: ns[name] for name in ('_request', 'warmup', '_build_optional_kwargs', 'process', 'setup')})
handler = Handler()
handler.client, handler.model_name, handler.stream = client, 'test/llm', False
handler._extra_body, handler.request_timeout, handler.cancel_scope = {}, 1, None
handler.enable_lang_prompt = False
handler._turn_is_latest = lambda *_: True
handler._apply_config = lambda *a, **kw: None
# Only serialization/history output is isolated; process calls the pinned _request.
handler._generate = lambda chat, original, turn, kw: iter([handler._request(chat.messages, kw)])
return handler
@pytest.mark.parametrize('limit', [17, 83])
def test_pinned_normal_stt_turn_and_warmup_emit_actual_nondefault_token_limit(limit):
calls = []
client = LimitedChatClient(RecordingSDK(calls), limit)
handler = upstream_handler(client)
chat = SimpleNamespace(messages=[{'role': 'user', 'content': 'transcribed fixture'}], buffer=[],
copy=lambda **kw: chat, history_anchor_id=lambda: None, has_pending_tool_calls=lambda: False)
request = SimpleNamespace(audio=None, response=None, turn_id='turn', turn_revision=1,
speech_stopped_at_s=0, runtime_config=SimpleNamespace(chat=chat,
session=SimpleNamespace(instructions='fixture', tools=None, tool_choice=None)),
language_code='fa', selected_language='fa', response_key='r', prefetch_transaction=None)
list(handler.process(request))
handler.warmup()
assert len(calls) == 2
assert [c['max_tokens'] for c in calls] == [limit, limit]
assert calls[0]['messages'][0]['content'] == 'transcribed fixture'
assert calls[1]['messages'][-1]['content'] == 'Hello'
@pytest.mark.parametrize('failure', [httpx.ConnectError('fixture connection failure'),
httpx.HTTPStatusError('fixture retryable 503', request=httpx.Request('POST', 'https://fixture.invalid'), response=httpx.Response(503))])
def test_pinned_warmup_cannot_restore_retries(failure):
calls = []
handler = upstream_handler(LimitedChatClient(RecordingSDK(calls, failure=failure), 29))
with pytest.raises(type(failure)):
handler.warmup()
assert len(calls) == 1 and calls[0]['max_tokens'] == 29
def asset_bundle(tmp_path):
roots = {'nltk': tmp_path / 'nltk', 'vad': tmp_path / 'vad'}
files = {}
for kind, paths in [('nltk', REQUIRED_NLTK), ('vad', REQUIRED_VAD)]:
for name in paths:
path = roots[kind] / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'controlled asset fixture')
files[kind + '/' + name] = hashlib.sha256(path.read_bytes()).hexdigest()
manifest = tmp_path / 'assets.json'
manifest.write_text(json.dumps(dict(schema=1, files=files)))
return roots, manifest
@pytest.mark.parametrize('fault', ['missing', 'changed', 'extra', 'valid'])
def test_required_assets_are_complete_and_fingerprinted_before_any_probe(tmp_path, fault):
roots, manifest = asset_bundle(tmp_path)
path = roots['nltk'] / REQUIRED_NLTK[0]
if fault == 'missing': path.unlink()
if fault == 'changed': path.write_bytes(b'changed')
if fault == 'extra': (roots['vad'] / 'untracked').write_bytes(b'x')
if fault == 'valid':
assert validate_assets(roots['nltk'], roots['vad'], manifest) == hashlib.sha256(manifest.read_bytes()).hexdigest()
else:
with pytest.raises(AssetError): validate_assets(roots['nltk'], roots['vad'], manifest)
def test_pinned_import_has_no_runtime_nltk_download_and_keeps_tokenization(tmp_path):
calls = []
nltk = SimpleNamespace(data=SimpleNamespace(path=[], find=lambda p: p),
sent_tokenize=lambda text: calls.append('sent') or [text],
pos_tag=lambda words, **kw: calls.append('pos') or [(words[0], 'NN')],
download=lambda *a: pytest.fail('download invoked'))
configure_nltk(nltk, tmp_path)
source = (ROOT / 'pipeline.py.source').read_text()
patched = patch_pipeline_source(source)
assert 'nltk.download(' not in patched
# Execute the exact import-time patched preflight, not a replacement tokenizer.
start, end = patched.index('from services.local_s2s.assets'), patched.index('# caching allows')
exec(patched[start:end], {'nltk': nltk})
assert calls == ['sent', 'pos', 'sent', 'pos']
with pytest.raises(AssetError): nltk.download('anything')
def test_missing_assets_main_fails_safely_before_provider_imports(monkeypatch, tmp_path, capsys):
from services.local_s2s import engine
import sys
monkeypatch.setattr(sys, 'argv', ['engine', '--allow-paid-startup'])
monkeypatch.setenv('LOCAL_S2S_ALLOW_PAID_STARTUP', 'true')
monkeypatch.setenv('LOCAL_S2S_NLTK_DATA', str(tmp_path / 'missing'))
monkeypatch.setattr('app.modules.voice.configuration.VoiceSettings', lambda **kw: local_config())
monkeypatch.setattr(engine, 'build_runtime', lambda *a: pytest.fail('provider construction reached'))
assert engine.main() == 1
assert 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED' in capsys.readouterr().out
@contextmanager
def gateway(handler=None, *, timeout=.2, inactivity=.1, transport=None):
server = ComponentServer('fixture-key', port=0, transport=transport or httpx.MockTransport(handler or (lambda r: httpx.Response(503))),
timeout=timeout, inactivity=inactivity)
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
assert server.ready.wait(2)
try: yield server
finally:
server.shutdown(); server.server_close(); thread.join(2)
assert not thread.is_alive()
def wait_released(server, count=1):
deadline = time.monotonic() + 2
while server.counts['released'] < count and time.monotonic() < deadline: time.sleep(.005)
assert server.counts['released'] >= count and not server.requests
@pytest.mark.parametrize('partial', [b'', b'POST /v1/audio/speech HTTP/1.1\r\nContent-',
b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 100\r\n\r\nx'])
def test_silent_partial_headers_and_stalled_body_release_slots(partial):
with gateway() as server:
with socket.create_connection(('127.0.0.1', server.server_port), timeout=2) as client:
if partial: client.sendall(partial)
assert client.recv(4096) == b''
wait_released(server)
assert server.counts['expired'] == 1 and sum(server.counts[p] for p in ('/v1/audio/speech','/v1/chat/completions')) == 0
def test_slow_upstream_headers_cancel_transport_and_release_slot():
cancelled = Event()
async def remote(request):
try: await asyncio.sleep(10)
finally: cancelled.set()
with gateway(remote) as server:
with httpx.Client(timeout=2, trust_env=False) as client:
with pytest.raises(httpx.RemoteProtocolError):
client.post(f'http://127.0.0.1:{server.server_port}/v1/audio/speech', content=b'{}', headers={'Authorization':'Bearer local-components'})
wait_released(server)
assert cancelled.is_set() and server.counts['/v1/audio/speech'] == 1
@pytest.mark.parametrize('path,media', [('/v1/audio/speech','audio/pcm'),('/v1/chat/completions','text/event-stream')])
def test_sub8192_trickle_is_forwarded_but_total_deadline_leaves_incomplete_stream(path, media):
closed = Event()
class Stream(httpx.AsyncByteStream):
async def __aiter__(self):
while True:
yield b'x'
await asyncio.sleep(.02)
async def aclose(self): closed.set()
def remote(request): return httpx.Response(200, headers={'content-type':media}, stream=Stream())
with gateway(remote, timeout=.2, inactivity=.1) as server:
began = time.monotonic()
with httpx.Client(timeout=2, trust_env=False) as client:
with client.stream('POST',f'http://127.0.0.1:{server.server_port}'+path,content=b'{}',headers={'Authorization':'Bearer local-components'}) as result:
iterator=result.iter_raw()
assert next(iterator) == b'x'
assert time.monotonic()-began < .18
with pytest.raises(httpx.RemoteProtocolError): list(iterator)
wait_released(server)
assert closed.is_set() and server.counts['expired'] == 1
def test_blocked_downstream_drain_is_bounded_and_transports_close():
async def scenario():
with gateway(lambda r:httpx.Response(200,headers={'content-type':'audio/pcm'},content=b'xx')) as server:
reader = asyncio.StreamReader()
reader.feed_data(b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 2\r\nAuthorization: Bearer local-components\r\n\r\n{}')
class Writer:
closed=False
def write(self,data): pass
drains=0
async def drain(self):
self.drains+=1
if self.drains>1: await asyncio.Event().wait()
def close(self): self.closed=True
async def wait_closed(self): pass
writer=Writer()
start=time.monotonic()
await server._serve(reader,writer,asyncio.get_running_loop().time()+.1)
assert writer.closed and time.monotonic()-start<.5 and writer.drains==2
asyncio.run(scenario())
def test_pinned_stop_exception_does_not_skip_gateway_cleanup():
ns=dict(monotonic=time.monotonic,current_thread=current_thread,_JOIN_TIMEOUT_S=.01,logger=logging.getLogger('pinned'),ConfiguredRuntimeError=RuntimeError,_cleanup=lambda _:None)
functions('lifecycle.py.source',[('ConfiguredRuntime','stop')],ns)
class Survivor:
def join(self,timeout): pass
def is_alive(self): return True
runtime=SimpleNamespace(_lock=Lock(),state='running',_signal_stop=lambda:None,_threads=[Survivor()],_monitor=None)
runtime.stop=lambda:ns['stop'](runtime)
logs=[]
with gateway() as guard:
thread=SimpleNamespace(join=lambda timeout:None,is_alive=lambda:False)
assert cleanup(runtime,guard,thread,Event(),timeout=.2,emit=lambda value,**kw:logs.append(json.loads(value)))
assert logs[-1]['cleanup']['runtime_stop']==1
assert logs[-1]['cleanup']['gateway_shutdown']==0
assert guard.done.is_set()
@pytest.mark.parametrize('sig',[signal.SIGINT,signal.SIGTERM])
def test_termination_during_inflight_restores_handlers_and_emits_final_counters(monkeypatch,sig):
import services.local_s2s.lifecycle as lifecycle
captured,logs=[],[]
previous={s:signal.getsignal(s) for s in (signal.SIGINT,signal.SIGTERM)}
entered=Event()
async def remote(request):
entered.set()
await asyncio.sleep(10)
def start(key,timeout):
guard=ComponentServer(key,port=0,transport=httpx.MockTransport(remote),timeout=1)
thread=Thread(target=guard.serve_forever,daemon=True);thread.start();assert guard.ready.wait(2)
captured.extend([guard,thread]);return guard,thread
monkeypatch.setattr(lifecycle,'start_components',start)
def build(stop):
class Runtime:
def start(self):
def request():
try:
with httpx.Client(timeout=2,trust_env=False) as client:
client.post(f'http://127.0.0.1:{captured[0].server_port}/v1/audio/speech',content=b'{}',headers={'Authorization':'Bearer local-components'})
except httpx.HTTPError: pass
Thread(target=request,daemon=True).start()
def wait(self): stop.wait()
def stop(self): raise RuntimeError('controlled stop failure')
def terminate():
assert entered.wait(2)
signal.getsignal(sig)(sig,None) # installed handler dispatch; portable on Windows
Thread(target=terminate,daemon=True).start()
return Runtime()
assert lifecycle.run_owned(build,'fixture-key',1,emit=lambda value,**kw:logs.append(json.loads(value)))==1
assert not captured[1].is_alive() and not captured[0].requests
assert logs[-1]['stage']=='close' and logs[-1]['request_counts']['released']==1
assert all(signal.getsignal(s)==handler for s,handler in previous.items())
@pytest.mark.parametrize('limit', [19, 71])
def test_real_pinned_setup_warmup_is_already_capped_before_constructor_returns(limit):
calls=[]
handler=upstream_handler(None)
ns=handler.setup.__func__.__globals__
module=SimpleNamespace(OpenAI=lambda **kw: RecordingSDK(calls, **kw),
BaseOpenAICompatibleHandler=type('Base', (), {'setup': handler.setup.__func__}))
install_client_policy(module, local_config(local_s2s_max_output_tokens=limit,local_s2s_request_timeout_seconds=9))
handler.setup=module.BaseOpenAICompatibleHandler.setup.__get__(handler)
ns['OpenAI']=module.OpenAI
handler._build_extra_body=lambda *a: {}
handler.setup(model_name='test/llm', api_key='fixture', base_url='http://127.0.0.1/v1', compact_history=False)
assert len(calls)==1 and calls[0]['max_tokens']==limit
assert handler.client.token_limit==limit and handler.gen_kwargs=={}
assert handler.request_timeout_s==9 and handler.request_timeout.read==9
def test_hung_construction_and_hung_stop_are_bounded_and_gateway_always_closes(monkeypatch):
import services.local_s2s.lifecycle as lifecycle
captured,logs=[],[]
def start(key,timeout):
server=ComponentServer(key,port=0,timeout=.2)
thread=Thread(target=server.serve_forever,daemon=True);thread.start();assert server.ready.wait(1)
captured.extend([server,thread]);return server,thread
monkeypatch.setattr(lifecycle,'start_components',start)
latch=Event()
began=time.monotonic()
assert lifecycle.run_owned(lambda stop:latch.wait(10),'fixture',.2,startup_timeout=.05,cleanup_timeout=.2,
emit=lambda value,**kw:logs.append(json.loads(value)))==1
assert time.monotonic()-began<1 and not captured[1].is_alive()
assert logs[-1]['stage']=='close'
latch.set()
with gateway() as server:
runtime=SimpleNamespace(stop=lambda:Event().wait(10))
logs=[]
assert cleanup(runtime,server,SimpleNamespace(join=lambda timeout:None,is_alive=lambda:False),Event(),timeout=.05,
emit=lambda value,**kw:logs.append(json.loads(value)))
assert logs[-1]['cleanup']['runtime_stop']==2 and server.done.is_set()
def test_downstream_disconnect_closes_upstream_and_releases_slot():
closed=Event()
class Stream(httpx.AsyncByteStream):
async def __aiter__(self):
while True:
yield b'a'*256
await asyncio.sleep(.01)
async def aclose(self): closed.set()
with gateway(lambda r:httpx.Response(200,headers={'content-type':'audio/pcm'},stream=Stream()),timeout=.4,inactivity=.2) as server:
with httpx.Client(timeout=1,trust_env=False) as client:
with client.stream('POST',f'http://127.0.0.1:{server.server_port}/v1/audio/speech',content=b'{}',headers={'Authorization':'Bearer local-components'}) as result:
assert next(result.iter_raw())
wait_released(server)
assert closed.is_set()
def test_concurrency_slots_include_silent_connections_and_recover_after_expiry():
with gateway(timeout=.3,inactivity=.15) as server:
peers=[socket.create_connection(('127.0.0.1',server.server_port),timeout=1) for _ in range(4)]
try:
deadline=time.monotonic()+1
while server.counts['rejected']<1 and time.monotonic()<deadline: time.sleep(.005)
assert server.counts['rejected']==1 and server.counts['accepted']==3
wait_released(server,3)
finally:
for peer in peers: peer.close()
def test_asset_provisioning_is_local_only_and_emits_reviewable_fingerprint(tmp_path,monkeypatch,capsys):
import services.local_s2s.assets as assets
import sys
roots,_=asset_bundle(tmp_path)
output=tmp_path/'new-assets.json'
monkeypatch.setattr(sys,'argv',['assets','--nltk-root',str(roots['nltk']),'--vad-root',str(roots['vad']),'--output',str(output)])
assert assets.main()==0
record=json.loads(capsys.readouterr().out)
assert record['manifest_sha256']==validate_assets(roots['nltk'],roots['vad'],output)
assert record['files']==len(REQUIRED_NLTK)+len(REQUIRED_VAD)
def test_trickled_request_body_still_expires_on_total_deadline():
with gateway(timeout=.2,inactivity=.1) as server:
with socket.create_connection(('127.0.0.1',server.server_port),timeout=1) as client:
client.sendall(b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 100\r\n\r\n')
began=time.monotonic()
for _ in range(20):
try: client.sendall(b'x')
except OSError: break
time.sleep(.02)
try:
closed=client.recv(1024)==b''
except (ConnectionResetError, ConnectionAbortedError):
closed=True # Windows resets a timed-out socket with unread body bytes.
assert closed
assert time.monotonic()-began<.7
wait_released(server)
assert server.counts['expired']==1 and server.counts['/v1/audio/speech']==0
@pytest.mark.parametrize('invalid', [[], {'schema': 1, 'files': []}, {'schema': 1, 'files': None}])
def test_malformed_asset_manifest_has_safe_category(tmp_path, invalid):
roots, manifest = asset_bundle(tmp_path)
manifest.write_text(json.dumps(invalid))
with pytest.raises(AssetError, match='^LOCAL_ENGINE_ASSET_VALIDATION_FAILED$'):
validate_assets(roots['nltk'], roots['vad'], manifest)
def test_unusable_tokenizer_with_downloads_blocked_fails_before_provider_calls(tmp_path, monkeypatch, capsys):
from services.local_s2s import engine
import sys
roots, manifest = asset_bundle(tmp_path)
nltk = SimpleNamespace(data=SimpleNamespace(path=[], find=lambda p: p),
download=lambda *a: pytest.fail('runtime download reached'),
pos_tag=lambda *a, **kw: [])
# A tokenizer trying to obtain a missing asset must hit the installed blocker.
nltk.sent_tokenize = lambda text: nltk.download('punkt_tab')
monkeypatch.setitem(sys.modules, 'nltk', nltk)
monkeypatch.setattr(sys, 'argv', ['engine', '--allow-paid-startup'])
for name, value in {'LOCAL_S2S_ALLOW_PAID_STARTUP': 'true',
'LOCAL_S2S_NLTK_DATA': str(roots['nltk']), 'LOCAL_S2S_SILERO_SOURCE': str(roots['vad']),
'LOCAL_S2S_ASSET_MANIFEST': str(manifest),
'LOCAL_S2S_ASSET_MANIFEST_SHA256': hashlib.sha256(manifest.read_bytes()).hexdigest()}.items():
monkeypatch.setenv(name, value)
monkeypatch.setattr('app.modules.voice.configuration.VoiceSettings', lambda **kw: local_config())
calls = []
monkeypatch.setattr(engine, 'build_runtime', lambda *a: calls.append('provider'))
assert engine.main() == 1 and calls == []
assert 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED' in capsys.readouterr().out
@contextmanager
def loopback_upstream(*, headers=False, hang_close=False):
"""Real local TCP upstream: cancellation must close its actual HTTP socket."""
entered, closed, transport_closed = Event(), Event(), Event()
class Handler(socketserver.BaseRequestHandler):
def handle(self):
self.request.settimeout(6)
try:
data = b''
while b'\r\n\r\n' not in data:
data += self.request.recv(4096)
head, body = data.split(b'\r\n\r\n', 1)
size = int(next(line.split(b':', 1)[1] for line in head.split(b'\r\n') if line.lower().startswith(b'content-length:')))
while len(body) < size:
body += self.request.recv(size - len(body))
if headers:
self.request.sendall(b'HTTP/1.1 200 OK\r\nContent-Type: audio/pcm\r\nTransfer-Encoding: chunked\r\n\r\n')
entered.set()
# No data is produced. Only owned cancellation closes this socket.
assert self.request.recv(1) == b''
except ConnectionResetError:
pass
finally:
closed.set()
class Server(socketserver.ThreadingTCPServer):
daemon_threads = True
remote = Server(('127.0.0.1', 0), Handler)
thread = Thread(target=remote.serve_forever, kwargs={'poll_interval': .01}, daemon=True)
thread.start()
class Transport(httpx.AsyncHTTPTransport):
async def handle_async_request(self, request):
request.url = httpx.URL(f'http://127.0.0.1:{remote.server_address[1]}' + request.url.path)
return await super().handle_async_request(request)
async def aclose(self):
await super().aclose()
transport_closed.set()
if hang_close:
await asyncio.Event().wait()
try:
yield Transport(retries=0), entered, closed, transport_closed
finally:
remote.shutdown(); remote.server_close(); thread.join(1)
def speech_request(extra=b''):
return (b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 2\r\n'
b'Authorization: Bearer local-components\r\n' + extra + b'\r\n{}')
@pytest.mark.parametrize('headers', [False, True], ids=['before-upstream-headers', 'stalled-after-headers'])
def test_disconnect_cancels_silent_real_upstream_and_releases_slot(headers):
with loopback_upstream(headers=headers) as (transport, entered, closed, transport_closed):
with gateway(transport=transport, timeout=5, inactivity=4) as server:
peer = socket.create_connection(('127.0.0.1', server.server_port), timeout=2)
try:
peer.sendall(speech_request())
assert entered.wait(1)
if headers:
received = b''
while b'\r\n\r\n' not in received:
received += peer.recv(4096)
assert received.startswith(b'HTTP/1.1 200')
assert not received.endswith(b'0\r\n\r\n')
began = time.monotonic()
finally:
peer.close()
assert closed.wait(CLEANUP_WINDOW_SECONDS + .4)
assert transport_closed.wait(.4)
wait_released(server)
assert time.monotonic() - began < CLEANUP_WINDOW_SECONDS + .6 < server.timeout
assert server.counts['disconnected'] == 1 and server.counts['expired'] == 0
assert server.counts['accepted'] == server.counts['released'] == 1
@pytest.mark.parametrize('half_close', [False, True], ids=['normal', 'declared-receive-only-half-close'])
def test_success_and_declared_half_close_receive_complete_response(half_close):
entered = Event()
async def remote(request):
entered.set()
await asyncio.sleep(.08) # receive-side EOF precedes upstream headers
return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=b'xx')
with gateway(remote, timeout=2, inactivity=1) as server:
with socket.create_connection(('127.0.0.1', server.server_port), timeout=1) as peer:
peer.sendall(speech_request(b'X-Local-S2S-Half-Close: receive-response\r\n' if half_close else b''))
if half_close:
peer.shutdown(socket.SHUT_WR)
received = b''
while part := peer.recv(4096):
received += part
assert entered.is_set()
assert received.startswith(b'HTTP/1.1 200')
assert received.endswith(b'2\r\nxx\r\n0\r\n\r\n')
wait_released(server)
assert server.counts['disconnected'] == server.counts['expired'] == 0
def test_undeclared_half_close_is_explicit_cancellation_even_if_peer_can_receive():
with loopback_upstream() as (transport, entered, closed, transport_closed):
with gateway(transport=transport, timeout=5, inactivity=4) as server:
with socket.create_connection(('127.0.0.1', server.server_port), timeout=2) as peer:
peer.sendall(speech_request())
assert entered.wait(1)
peer.shutdown(socket.SHUT_WR)
assert peer.recv(4096) == b'' # policy cancellation, not inferred inability to receive
assert closed.wait(1) and transport_closed.wait(1)
wait_released(server)
assert server.counts['disconnected'] == 1 and server.counts['expired'] == 0
def test_disconnect_cleanup_has_shared_bound_even_if_transport_close_stalls():
with loopback_upstream(hang_close=True) as (transport, entered, closed, transport_closed):
with gateway(transport=transport, timeout=5, inactivity=4) as server:
peer = socket.create_connection(('127.0.0.1', server.server_port), timeout=2)
peer.sendall(speech_request())
assert entered.wait(1)
began = time.monotonic()
peer.close()
assert closed.wait(1) and transport_closed.wait(1)
wait_released(server)
assert time.monotonic() - began < CLEANUP_WINDOW_SECONDS + .6 < server.timeout
assert server.counts['close_errors'] >= 1
LOCAL_IDENTIFIERS = ('local_s2s_stt_model', 'local_s2s_llm_model', 'local_s2s_tts_model', 'local_s2s_tts_voice')
@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
@pytest.mark.parametrize('value', ['bad id', 'bad\tvalue', 'bad\nvalue', 'bad\x00value', 'bad\x7fvalue', 'bad\u00e9value'])
def test_voice_settings_inherits_local_identifier_validation(field, value):
from pydantic import ValidationError
with pytest.raises(ValidationError, match='Invalid local component identifier'):
local_config(**{field: value}) # constructs the real VoiceSettings, not the base class
@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
def test_voice_settings_preserves_valid_local_identifiers(field):
value = 'vendor/Valid-Model_1.2'
assert getattr(local_config(**{field: value}), field) == value
@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
def test_invalid_local_identifiers_fail_before_assets_gateway_or_provider(monkeypatch, field, capsys):
from services.local_s2s import engine, assets, lifecycle
import sys
monkeypatch.setattr(sys, 'argv', ['engine', '--allow-paid-startup'])
monkeypatch.setenv('LOCAL_S2S_ALLOW_PAID_STARTUP', 'true')
monkeypatch.setenv(field.upper(), 'bad id')
calls = []
monkeypatch.setattr(assets, 'validate_assets', lambda *a: calls.append('assets'))
monkeypatch.setattr(lifecycle, 'run_owned', lambda *a: calls.append('provider'))
assert engine.main() == 1 and calls == []
assert 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED' in capsys.readouterr().out
def test_warmup_retry_constant_is_read_from_hash_checked_upstream_source():
assert constant('base.py.source', 'WARMUP_MAX_RETRIES') == 6
@pytest.mark.parametrize('field', ['gemini_model', 'gemini_voice', 'openai_realtime_model', 'openai_realtime_voice'])
def test_existing_provider_identifier_validators_remain_active(field):
from pydantic import ValidationError
with pytest.raises(ValidationError, match='Invalid voice profile identifier'):
local_config(**{field: 'bad id'})
assert getattr(local_config(**{field: 'Valid-1.2'}), field) == 'Valid-1.2'