"""Pinned extension checks use initialized fake handlers; no models/providers.""" import asyncio from copy import deepcopy from queue import Empty from threading import Event, Thread from types import SimpleNamespace import httpx import pytest from pydantic import BaseModel, ConfigDict from services.local_s2s.components import ComponentServer from services.local_s2s.extension import FailClosedQueue, active_components, install_session_proof, EngineTokenGuard from app.modules.voice.local_s2s import setup_session from app.infrastructure.local_s2s import LocalS2SAdapter from app.modules.voice.settings import RuntimeSettings from tests.unit.test_local_s2s_phase2 import local_config from tests.unit.test_realtime_phase1 import Transport def test_saturated_pipeline_stops_without_blocking_teardown(): stop = Event() queue = FailClosedQueue(stop, maxsize=1) queue.put(b'one') with pytest.raises(RuntimeError, match='QUEUE_CAPACITY'): queue.put(b'two', block=True) assert stop.is_set() and queue.get_nowait() == b'one' with pytest.raises(Empty): queue.get_nowait() def handlers(config): stt_type = type('STT', (), {'__module__': 'speech_to_speech.STT.openai_compatible_handler'}) tts_type = type('TTS', (), {'__module__': 'speech_to_speech.TTS.openai_compatible_handler'}) stt, tts = stt_type(), tts_type() stt.model, stt.language, stt.response_format = config.local_s2s_stt_model, 'fa', 'json' stt.base_url, stt.api_key, stt.timeout = 'http://127.0.0.1:8766/v1', 'local-components', 30 tts.model, tts.voice, tts.response_format, tts.sample_rate = config.local_s2s_tts_model, config.local_s2s_tts_voice, 'pcm', 24000 tts.base_url, tts.api_key, tts.timeout = stt.base_url, stt.api_key, stt.timeout class Client: token_limit, max_retries = 256, 0 base_url, api_key = stt.base_url, stt.api_key def with_options(self, **kwargs): assert kwargs == {'max_retries': 0} return self llm = SimpleNamespace(model_name=config.local_s2s_llm_model, gen_kwargs={'max_tokens': 256}, request_timeout_s=30, client=Client()) return SimpleNamespace(handlers=[SimpleNamespace(enable_realtime_transcription=False), stt, llm, tts]) @pytest.mark.parametrize('change', ['none', 'model', 'voice', 'rate', 'credential', 'progressive']) def test_authoritative_components_come_from_initialized_handlers(change): config = local_config() unit = handlers(config) if change == 'model': unit.handlers[1].model = 'wrong' if change == 'voice': unit.handlers[-1].voice = 'wrong' if change == 'rate': unit.handlers[-1].sample_rate = 16000 if change == 'credential': unit.handlers[1].api_key = '' if change == 'progressive': unit.handlers[0].enable_realtime_transcription = True if change != 'none': with pytest.raises(ValueError): active_components(unit, config.components()) else: assert active_components(unit, config.components()) == config.components() def test_native_session_proof_uses_applied_state_instead_of_request_echo(): config = local_config() class Session(BaseModel): model_config = ConfigDict(extra='allow') class Result(BaseModel): session: Session actual = Session(**setup_session(config)) service = object() class Handler: _service = service def _state(self, conn): return SimpleNamespace(runtime_config=SimpleNamespace(session=actual)) def build_session_updated(self, conn): return Result(session=actual.model_copy()) install_session_proof(Handler, {id(service): config.components()}, setup_session(config)) adapter = LocalS2SAdapter(Transport(), config=config, settings=RuntimeSettings(_env_file=None)) event = Handler().build_session_updated('native-session') assert adapter.acknowledged(event.session.model_dump()) actual.model = 'other/model' assert not adapter.acknowledged(Handler().build_session_updated('native-session').session.model_dump()) @pytest.mark.parametrize('kind', ['http', 'websocket']) def test_engine_token_mismatch_refuses_before_native_handler(kind): async def scenario(): sent, entered = [], [] async def app(scope, receive, send): entered.append(True) async def send(e): sent.append(e) async def receive(): return {} guard = EngineTokenGuard(app, 'private-test-token') await guard({'type': kind, 'headers': []}, receive, send) assert not entered assert sent[0].get('status', sent[0].get('code')) in (401, 1008) await guard({'type': kind, 'headers': [(b'authorization', b'Bearer private-test-token')]}, receive, send) assert entered == [True] asyncio.run(scenario()) @pytest.mark.parametrize('failure', [False, True]) def test_loopback_gateway_credentials_pcm_and_detectable_stream_abort(failure): observed = [] def upstream(request): observed.append(request) assert request.url == 'https://openrouter.ai/api/v1/audio/speech' assert request.headers['authorization'] == 'Bearer fake-router-key' size = 1440002 if failure else 9600 return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=bytes(size)) server = ComponentServer('fake-router-key', port=0, transport=httpx.MockTransport(upstream)) thread = Thread(target=server.serve_forever, daemon=True) thread.start() try: url = f'http://127.0.0.1:{server.server_port}/v1/audio/speech' with httpx.Client(timeout=3, trust_env=False) as client: assert client.post(url, content=b'{}').status_code == 403 if failure: with pytest.raises(httpx.RemoteProtocolError): client.post(url, content=b'{}', headers={'Authorization': 'Bearer local-components'}) else: result = client.post(url, content=b'{}', headers={'Authorization': 'Bearer local-components'}) assert result.status_code == 200 and result.content == bytes(9600) assert len(observed) == 1 and server.counts['/v1/audio/speech'] == 1 finally: server.shutdown() server.server_close() thread.join(timeout=3)