"""Offline token-limit lifecycle coverage; no hosted provider or browser claims.""" import asyncio from copy import deepcopy from types import SimpleNamespace import time import pytest from pydantic import ValidationError from app.infrastructure.realtime import RealtimeAdapter from app.modules.voice.configuration import VoiceSettings, OpenAIInputSettings from tests.unit.test_realtime_phase1 import ( Transport, runner, persisted, make, input_turn, response, commands, until, terminal, message, delta, call, done, ) def limited(output=None, **changes): event = terminal(status='incomplete', output=output) event['response'].update(status_details=dict(type='incomplete', reason='max_output_tokens'), max_output_tokens=256) event['response'].update(changes) return event async def audio_done(runtime): await runtime.handle(dict(type='response.output_audio.done', response_id='r1', item_id='a1', output_index=0, content_index=0)) @pytest.mark.parametrize('value', [1, 256, 512, 4096]) def test_limit_is_pinned_and_acknowledged(value): config = VoiceSettings(_env_file=None, provider='openai', openai_realtime_max_output_tokens=value) adapter = RealtimeAdapter(Transport(), input_settings=config) setup = adapter.setup()['session'] assert setup['max_output_tokens'] == config.profile()['max_output_tokens'] == value assert adapter.acknowledged(deepcopy(setup)) for bad in (None, 'inf', True, value + 1): ack = deepcopy(setup); ack['max_output_tokens'] = bad assert not adapter.acknowledged(ack) ack = deepcopy(setup); del ack['max_output_tokens'] assert not adapter.acknowledged(ack) gemini = VoiceSettings(_env_file=None, provider='gemini') assert gemini.model_copy(update={'openai_realtime_max_output_tokens':value}).profile() == gemini.profile() @pytest.mark.parametrize('value', [0, 4097, True, False, 256.0, 1.5, 'inf', '-1', '1.5']) def test_invalid_generation_limits(value): with pytest.raises(ValidationError): OpenAIInputSettings(openai_realtime_max_output_tokens=value) def test_limit_environment(monkeypatch): monkeypatch.setenv('OPENAI_REALTIME_MAX_OUTPUT_TOKENS', '128') assert VoiceSettings(_env_file=None, provider='openai').profile()['max_output_tokens'] == 128 @pytest.mark.parametrize('transcript_first', [False, True]) def test_limited_audio_drains_and_next_turn_releases_once(runner, persisted, transcript_first): async def scenario(): runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted) try: first = await input_turn(runtime) await response(runtime, transport) transcript = dict(type='response.output_audio_transcript.done', response_id='r1', item_id='a1', output_index=0, content_index=0, transcript='Exact generated words') for _ in range(10): await runtime.handle(delta(48000)) await audio_done(runtime) if transcript_first: await runtime.handle(transcript) assert not any(isinstance(e, dict) and e.get('status') == 'completed' for e in out) ending = limited() await runtime.handle(ending) await runtime.handle(dict(ending, event_id='duplicate-terminal')) if not transcript_first: await runtime.handle(transcript) audio = next(iter(runtime.audio.values())) await until(lambda: audio.sent > 0) while audio.sent < audio.generated or audio.played < audio.sent // 48: sent = audio.sent old = audio.played credit = audio.credit await runtime.playback_progress(audio.ref, sent // 48) # Delivery cannot mutate counters until this coroutine yields. assert credit - audio.credit == 48 * (sent // 48 - old) credit = audio.credit await runtime.playback_progress(audio.ref, sent // 48) assert audio.credit == credit if audio.sent < audio.generated: await until(lambda: audio.sent > sent) await until(lambda: audio.state == 'retired') await until(lambda: any(isinstance(e, dict) and e.get('type') == 'transcript' for e in out)) assert runtime.usable and runtime.responses['r1'].status == 'incomplete' assert runtime.responses['r1'].limited assert audio.generated == audio.sent == 48 * audio.played == 480000 assert audio.credit == audio.reserved == 0 assert len([e for e in out if isinstance(e, dict) and e.get('type') == 'answer_limited']) == 1 assert [e['status'] for e in out if isinstance(e, dict) and e.get('role') == 'assistant'] == ['limited'] assert runtime.normal(first) await input_turn(runtime, 'u2', 210) await until(lambda: len(commands(transport, 'response.create')) == 2) await runtime.handle(dict(type='input_audio_buffer.committed', item_id='u2')) await runtime.handle(dict(ending, event_id='third-terminal')) await asyncio.sleep(.01) assert len(commands(transport, 'response.create')) == 2 assert not any(isinstance(e, dict) and e.get('type') == 'turn_interrupted' for e in out) assert not commands(transport, 'response.cancel') finally: await runtime.close() asyncio.run(scenario()) @pytest.mark.parametrize('status,details', [ ('failed', dict(type='failed', error={'code':'server_error'})), ('incomplete', dict(type='incomplete', reason='content_filter')), ('incomplete', dict(type='incomplete', reason='other')), ('incomplete', None), ('incomplete', dict(type='failed', reason='max_output_tokens')), ('incomplete', dict(type='incomplete', reason='max_output_tokens', error={})), ]) def test_other_terminal_outcomes_fail(runner, persisted, status, details): async def scenario(): runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted) try: await input_turn(runtime); await response(runtime, transport) await runtime.handle(limited(status=status, status_details=details)) assert runtime.failure == 'LIVE_PROVIDER_UNAVAILABLE' assert not any(isinstance(e, dict) and e.get('type') == 'answer_limited' for e in out) assert len(commands(transport, 'response.create')) == 1 finally: await runtime.close() asyncio.run(scenario()) @pytest.mark.parametrize('raw', ['{"query":', '{"query":"q"}']) @pytest.mark.parametrize('argument_done', [False, True]) def test_limited_tools_never_execute_or_continue(runner, persisted, raw, argument_done, caplog): async def scenario(): service = SimpleNamespace(engine=None, search=lambda *_: pytest.fail('Cut-off tool executed')) runtime, transport, out = await make(service, runner, persisted) try: await input_turn(runtime); await response(runtime, transport) event = call(raw=raw) if argument_done: await runtime.handle(event) item = dict(type='function_call', id=event['item_id'], call_id='c1', name='search_knowledge', arguments=raw, status='incomplete') await runtime.handle(limited(output=[item])) assert 'reason=TOKEN_LIMIT_WITH_UNFINISHED_TOOLS ' in caplog.text assert 'terminal_limited=1' in caplog.text assert runtime.failure == 'LIVE_PROVIDER_UNAVAILABLE' assert runner._active == runner._admitted == 0 assert not commands(transport, 'conversation.item.create') assert len(commands(transport, 'response.create')) == 1 finally: await runtime.close() asyncio.run(scenario()) @pytest.mark.parametrize('terminal_first', [False, True]) def test_limited_interruption_waits_for_truncation_and_current_commit(runner, persisted, terminal_first): async def scenario(): now = [time.monotonic()] runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted, clock=lambda:now[0]) try: await input_turn(runtime); await response(runtime, transport) await runtime.handle(delta(48000)) await until(lambda: next(iter(runtime.audio.values())).sent == 48000) audio = next(iter(runtime.audio.values())) await audio_done(runtime) if terminal_first: await runtime.handle(limited()) await runtime.handle(dict(type='input_audio_buffer.speech_started', item_id='u2', audio_start_ms=10)) await runtime.playback_progress(audio.ref, 420) if not terminal_first: await until(lambda: bool(commands(transport, 'response.cancel'))) await runtime.handle(limited()) else: assert not commands(transport, 'response.cancel') now[0] += 1.01 await runtime.tick() await until(lambda: audio.cleanup_dispatched) assert audio.played == 420 and audio.credit == 48000 - 420 * 48 await runtime.handle(dict(type='conversation.item.truncated', item_id='a1', content_index=0, audio_end_ms=420)) assert audio.state == 'retired' and audio.credit == 0 assert audio.sent == audio.generated == 48000 and audio.played == 420 assert len(commands(transport, 'response.create')) == 1 await runtime.handle(dict(type='input_audio_buffer.speech_stopped', item_id='u2', audio_end_ms=100)) assert len(commands(transport, 'response.create')) == 1 await runtime.handle(dict(type='input_audio_buffer.committed', item_id='u2')) await until(lambda: len(commands(transport, 'response.create')) == 2) await runtime.handle(dict(type='conversation.item.truncated', item_id='a1', content_index=0, audio_end_ms=420)) await asyncio.sleep(.01) assert runtime.usable and len(commands(transport, 'response.create')) == 2 assert len([e for e in out if isinstance(e, dict) and e.get('type') == 'turn_interrupted']) == 1 finally: await runtime.close() asyncio.run(scenario()) @pytest.mark.parametrize('mode', ['stall', 'overflow', 'missing_audio_done', 'changed_terminal']) def test_limits_and_protocol_failures_still_enforced(runner, persisted, mode): async def scenario(): now = [time.monotonic()] runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted, clock=lambda:now[0]) try: await input_turn(runtime); await response(runtime, transport) await runtime.handle(delta(48000)) await until(lambda: next(iter(runtime.audio.values())).sent == 48000) if mode == 'missing_audio_done': await runtime.handle(limited()) assert runtime.failure == 'LIVE_PROVIDER_PROTOCOL_ERROR' elif mode == 'overflow': for _ in range(30): await runtime.handle(delta(48000)) assert runtime.failure == 'LIVE_BUFFER_OVERFLOW' else: await audio_done(runtime); await runtime.handle(limited()) if mode == 'stall': now[0] += 5.01; await runtime.tick() assert runtime.failure == 'LIVE_BUFFER_OVERFLOW' else: await runtime.handle(limited(status_details=dict(type='incomplete', reason='content_filter'))) assert runtime.failure == 'LIVE_PROVIDER_PROTOCOL_ERROR' finally: await runtime.close() asyncio.run(scenario()) @pytest.mark.parametrize('size', [0, 50]) def test_limited_empty_or_rounded_tail_does_not_fake_interruption(runner, persisted, size): async def scenario(): runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted) try: first = await input_turn(runtime); await response(runtime, transport) if size: await runtime.handle(delta(size)) await until(lambda: next(iter(runtime.audio.values())).sent == size) await runtime.playback_progress(next(iter(runtime.audio.values())).ref, 1) await audio_done(runtime); await runtime.handle(limited()) audio = next(iter(runtime.audio.values())) if size: await until(lambda: audio.cleanup_dispatched) else: await until(lambda: audio.state == 'retired') await input_turn(runtime, 'u2', 210) assert not first.superseded and not runtime.responses['r1'].interrupted if size: assert len(commands(transport, 'response.create')) == 1 assert audio.credit == 2 await runtime.handle(dict(type='conversation.item.truncated', item_id='a1', content_index=0, audio_end_ms=1)) await until(lambda: len(commands(transport, 'response.create')) == 2) assert audio.generated == audio.sent == size assert audio.played == size // 48 and audio.credit == 0 assert not [e for e in out if isinstance(e, dict) and e.get('type') == 'turn_interrupted'] finally: await runtime.close() asyncio.run(scenario()) def test_successful_response_cannot_execute_incomplete_tool_item(runner, persisted): async def scenario(): runtime, transport, out = await make(SimpleNamespace(engine=None, search=lambda *_: pytest.fail('Incomplete item executed')), runner, persisted) try: await input_turn(runtime); await response(runtime, transport) event = call(); await runtime.handle(event) output = [dict(type='function_call', id=event['item_id'], call_id='c1', name='search_knowledge', arguments=event['arguments'], status='incomplete')] await runtime.handle(terminal(output=output)) assert runtime.failure == 'LIVE_PROVIDER_PROTOCOL_ERROR' assert runner._active == runner._admitted == 0 assert not commands(transport, 'conversation.item.create') finally: await runtime.close() asyncio.run(scenario()) @pytest.mark.parametrize('finish', ['limited', 'interrupted', 'failed', 'closed']) def test_deferred_transcript_uses_and_releases_existing_control_budget(runner, persisted, finish): async def scenario(): runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted) try: await input_turn(runtime); r = await response(runtime, transport) await until(lambda: runtime.control_count == 0) event = dict(type='response.output_audio_transcript.done', response_id='r1', item_id='a1', output_index=0, content_index=0, transcript='Generated final text') await runtime.handle(event) held = r.pending_transcript assert held is not None and held.accounted assert runtime.control_count == 1 and runtime.control_bytes == held.size await runtime.handle(dict(event, event_id='duplicate-transcript')) assert runtime.control_count == 1 assert not [e for e in out if isinstance(e, dict) and e.get('type') == 'transcript'] if finish == 'limited': await runtime.handle(limited()) elif finish == 'interrupted': await runtime.handle(dict(type='input_audio_buffer.speech_started', item_id='u2', audio_start_ms=10)) elif finish == 'failed': await runtime.handle(limited(status='failed')) else: await runtime.close() assert not held.accounted and r.pending_transcript is None finally: await runtime.close() asyncio.run(scenario())