"""Local development adapter, attestation, PCM and bounded component contracts.""" import asyncio from copy import deepcopy from io import BytesIO import json from pathlib import Path from types import SimpleNamespace from uuid import uuid4 import wave import httpx import pytest from app.modules.voice.configuration import VoiceSettings from app.modules.voice.settings import RuntimeSettings from app.modules.voice.local_s2s import effective_identity, require_isolated_candidate from app.infrastructure.local_s2s import LocalS2SAdapter, LocalS2SContextError from app.modules.voice.runtime import VoiceRuntime from app.local_s2s_smoke import stages, stub_response, tone, wav_bytes from tests.unit.test_realtime_phase1 import Transport, runner, until, commands, input_turn, response, delta, done def local_config(**changes): values = dict(provider='local_s2s', local_s2s_enabled=True, voice_transport_testing=True, local_s2s_stt_model='test/stt', local_s2s_llm_model='test/llm', local_s2s_tts_model='test/tts', local_s2s_tts_voice='fixture') values.update(changes) return VoiceSettings(_env_file=None, **values) def confirmed(adapter): session = adapter.setup()['session'] session['s2s_effective'] = effective_identity(adapter.config.components(), deepcopy(session)) return session @pytest.mark.parametrize('changed', [dict(local_s2s_enabled=False), dict(voice_transport_testing=False), dict(local_s2s_stt_model=''), dict(local_s2s_tts_model=''), dict(local_s2s_tts_voice='')]) def test_opt_in_and_complete_fixed_profile_required(changed): with pytest.raises(ValueError): local_config(**changed).require_voice() def test_profile_has_no_credentials_and_changes_with_effective_components(): a = local_config(local_s2s_token='private-fixture') a.require_voice() profile = a.profile() assert 'private-fixture' not in json.dumps(profile) assert profile == local_config(local_s2s_token='rotated-fixture').profile() assert profile != local_config(local_s2s_stt_model='other/stt').profile() assert profile['development_only'] and profile['interruption_policy'] == 'close_until_phase3' assert profile['input_sample_rate'] == profile['output_sample_rate'] == 24000 @pytest.mark.parametrize('path', ['engine_revision', 'patch_revision', 'contract_revision', 'components', 'effective_config_sha256']) def test_setup_echo_or_mismatched_engine_identity_never_ready(path): adapter = LocalS2SAdapter(Transport(), config=local_config(), settings=RuntimeSettings(_env_file=None)) assert not adapter.acknowledged(adapter.setup()['session']) session = confirmed(adapter) assert adapter.acknowledged(session) session['s2s_effective'][path] = 'wrong' assert not adapter.acknowledged(session) assert not adapter.acknowledged(dict(confirmed(adapter), model='other/llm')) @pytest.mark.parametrize('kind', ['response.cancel', 'conversation.item.truncate']) def test_no_fake_history_or_terminal_on_interruption(kind): async def scenario(): wire = Transport() adapter = LocalS2SAdapter(wire, config=local_config(), settings=RuntimeSettings(_env_file=None)) with pytest.raises(LocalS2SContextError): await adapter.send({'type': kind}) assert not wire.sent with pytest.raises(LocalS2SContextError): adapter.confirm_history_repair(None, {}) asyncio.run(scenario()) def test_actual_runtime_normal_local_audio_and_close(runner): async def scenario(): wire, output = Transport(), [] adapter = LocalS2SAdapter(wire, config=local_config(), settings=RuntimeSettings(_env_file=None)) async def emit(event): output.append(event) async def authority(execution): return execution.capture(dict(id=execution.user_id, organization_id='fixture', role='user'), 1) runtime = VoiceRuntime(adapter, SimpleNamespace(engine=None), runner, uuid4(), emit, authority_check=authority) try: await runtime.start() await until(lambda: commands(wire, 'session.update')) assert not runtime.ready await runtime.handle(dict(type='session.updated', session=confirmed(adapter))) await until(lambda: runtime.ready) await input_turn(runtime) await response(runtime, wire) await runtime.handle(dict(type='conversation.item.input_audio_transcription.completed', item_id='u1', content_index=0, transcript='hello fixture')) await runtime.handle(delta(960)) await runtime.handle(dict(type='response.output_audio_transcript.done', response_id='r1', item_id='a1', output_index=0, content_index=0, transcript='answer fixture')) await runtime.handle(dict(type='response.output_audio.done', response_id='r1', item_id='a1', output_index=0, content_index=0)) await done(runtime) await until(lambda: any(isinstance(e, bytes) for e in output)) audio = next(iter(runtime.audio.values())) await until(lambda: audio.sent == 960) await runtime.playback_progress(audio.ref, 20) assert runtime.usable and b''.join(e for e in output if isinstance(e, bytes)) == bytes(960) await until(lambda: len([e for e in output if isinstance(e, dict) and e.get('type') == 'transcript']) >= 2) assert {e['role'] for e in output if isinstance(e, dict) and e.get('type') == 'transcript'} == {'user', 'assistant'} assert not commands(wire, 'conversation.item.truncate') finally: await runtime.close() assert wire.closed asyncio.run(scenario()) def test_factory_selects_local_only(monkeypatch): import app.infrastructure.local_s2s as local from app.infrastructure.voice_provider import create_adapter wire = Transport() async def connect(config, limits): return wire monkeypatch.setattr(local, 'connect_local', connect) async def scenario(): adapter = await create_adapter(local_config(), RuntimeSettings(_env_file=None)) assert isinstance(adapter, LocalS2SAdapter) await adapter.close() asyncio.run(scenario()) def test_isolation_precedes_startup_reconciliation(settings): config = local_config() with pytest.raises(ValueError, match='isolated'): require_isolated_candidate(config, settings) candidate = settings.model_copy(update={'database_url': __import__('pydantic').SecretStr('postgresql+psycopg://unused/app_local_s2s_test')}) with pytest.raises(ValueError, match='storage'): require_isolated_candidate(config, candidate) candidate = candidate.model_copy(update={'original_directory': Path('data/local-s2s-test/originals'), 'extraction_directory': Path('data/local-s2s-test/extractions')}) require_isolated_candidate(config, candidate) # An edited environment cannot relabel the API's already-open operational DB. with pytest.raises(ValueError, match='isolated'): require_isolated_candidate(config, candidate, database_url='postgresql+psycopg://unused/operational') @pytest.mark.parametrize('mode', ['multipart', 'json']) def test_stub_stages_forward_credentials_and_use_persian_pcm_contract(mode): seen = [] def remote(request): seen.append(request) assert request.headers['authorization'] == 'Bearer fixture-secret' return stub_response(request) async def scenario(): async with httpx.AsyncClient(transport=httpx.MockTransport(remote)) as client: pcm = await stages(local_config(), tone(), client, 'fixture-secret', stt_format=mode) assert pcm == tone() and len(seen) == 3 with wave.open(BytesIO(wav_bytes(pcm)), 'rb') as audio: assert (audio.getframerate(), audio.getnchannels(), audio.getsampwidth()) == (24000, 1, 2) if mode == 'json': assert json.loads(seen[0].content)['language'] == 'fa' else: assert b'name="file"' in seen[0].content and b'test/stt' in seen[0].content assert json.loads(seen[1].content)['max_tokens'] == 128 assert json.loads(seen[2].content)['response_format'] == 'pcm' asyncio.run(scenario()) @pytest.mark.parametrize('failure', ['http', 'odd-audio', 'oversize', 'unfinished-llm', 'json-error-audio']) def test_stage_failures_are_bounded_and_never_become_success(failure): def remote(request): if failure == 'http': return httpx.Response(401, text='PRIVATE_KEY_PROVIDER_TEXT') if request.url.path.endswith('/chat/completions') and failure == 'unfinished-llm': return httpx.Response(200, json={'choices': [{'finish_reason': 'length'}]}) if request.url.path.endswith('/audio/speech'): if failure == 'odd-audio': return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=b'x') if failure == 'oversize': return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=bytes(480002)) if failure == 'json-error-audio': return httpx.Response(200, json={'error': 'private'}) return stub_response(request) async def scenario(): async with httpx.AsyncClient(transport=httpx.MockTransport(remote)) as client: with pytest.raises(ValueError, match='LOCAL_STAGE_'): await stages(local_config(), tone(), client, 'fixture-secret') asyncio.run(scenario())