"""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()= 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'