Files
rag-technical-docs-assistant/tests/unit/test_local_s2s_boundary.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

132 lines
6.9 KiB
Python

"""Provider-free Phase 1 replay: run unchanged before and after the boundary."""
import asyncio
from types import SimpleNamespace
import pytest
from tests.unit.test_realtime_phase1 import (
runner, persisted, make, input_turn, response, delta, done, until, commands,
)
from tests.unit.test_realtime_repairs import Clock, without_ticker
@pytest.mark.parametrize("completed", [False, True], ids=["active", "completed-unplayed"])
@pytest.mark.parametrize("receipt", ["matching", "wrong-item", "wrong-position", "missing", "late", "conflicting"])
def test_interruption_replay(runner, persisted, completed, receipt):
async def scenario():
clock = Clock()
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted, clock=clock)
await without_ticker(runtime)
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 runtime.playback_progress(audio.ref, 100)
if completed:
await done(runtime)
await input_turn(runtime, "u2", 10)
assert len(commands(transport, "response.create")) == 1
if not completed:
await until(lambda: commands(transport, "response.cancel"))
assert not runtime.responses["r1"].terminal
await done(runtime, status="cancelled")
clock.advance(1)
await runtime.tick()
await until(lambda: commands(transport, "conversation.item.truncate"))
request = commands(transport, "conversation.item.truncate")[0]
assert request["item_id"] == "a1" and request["audio_end_ms"] == 100
assert runtime.responses["r1"].terminal
assert len(commands(transport, "response.create")) == 1
ack = dict(type="conversation.item.truncated", event_id="repair-ack",
item_id="a1", content_index=0, audio_end_ms=100)
if receipt == "missing":
clock.now = audio.cleanup_deadline + .01
await runtime.tick()
else:
if receipt == "wrong-item":
ack["item_id"] = "unknown"
if receipt == "wrong-position":
ack["audio_end_ms"] = 101
if receipt == "late":
clock.now = audio.cleanup_deadline + .01
await runtime.handle(ack)
if receipt == "conflicting":
await runtime.handle(dict(ack, audio_end_ms=101))
if receipt == "matching":
await runtime.handle(ack)
await runtime.handle(dict(ack, event_id="duplicate-repair-ack"))
await runtime.tick()
await until(lambda: len(commands(transport, "response.create")) == 2)
assert runtime.usable and audio.state == "retired"
assert len(commands(transport, "response.create")) == 2
print("REPLAY: generation stopped; repair matched at 100ms; duplicate ignored; exactly one next response")
else:
assert not runtime.usable
# A matching ack can release before a later conflict arrives;
# the conflict must close the session, never release further work.
assert len(commands(transport, "response.create")) <= (2 if receipt == "conflicting" else 1)
print(f"REPLAY: {receipt} repair => closed safely ({runtime.failure})")
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("provider", ["openai", "gemini"])
def test_native_repair_contract(provider):
from app.modules.voice.provider import HistoryRepair, ProviderProtocolError
from app.infrastructure.realtime import RealtimeAdapter
from app.infrastructure.gemini_live import GeminiLiveAdapter
from tests.unit.test_realtime_phase1 import Transport
adapter = (RealtimeAdapter if provider == "openai" else GeminiLiveAdapter)(Transport())
repair = HistoryRepair("session", 2, "response", "operation", "item", 0, 100)
assert adapter.cancellation_request("response", "cancel") == dict(
type="response.cancel", response_id="response", event_id="cancel")
assert adapter.history_repair_request(repair) == dict(type="conversation.item.truncate",
event_id="operation", item_id="item", content_index=0, audio_end_ms=100)
event = dict(type="conversation.item.truncated", event_id="native-ack",
item_id="item", content_index=0, audio_end_ms=100)
if provider == "gemini":
with pytest.raises(ProviderProtocolError):
adapter.confirm_history_repair(repair, event)
return
receipt = adapter.confirm_history_repair(repair, event)
assert receipt.repair == repair and receipt.native_event_id == "native-ack"
assert receipt.provenance == "openai.item_truncated"
for changes in ({"item_id": "other"}, {"content_index": False},
{"audio_end_ms": True}, {"audio_end_ms": 101}, {"type": "response.done"}):
with pytest.raises(ProviderProtocolError):
adapter.confirm_history_repair(repair, dict(event, **changes))
def test_adapter_receipt_cannot_rebind_runtime_generation(runner, persisted, monkeypatch):
from dataclasses import replace
from app.infrastructure.realtime import RealtimeAdapter
from app.modules.voice.provider import HistoryRepairReceipt
async def scenario():
clock = Clock()
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted, clock=clock)
await without_ticker(runtime)
try:
await input_turn(runtime)
await response(runtime, transport)
await runtime.handle(delta(48000))
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
await input_turn(runtime, "u2", 10)
await until(lambda: commands(transport, "response.cancel"))
await done(runtime, status="cancelled")
clock.advance(1)
await runtime.tick()
await until(lambda: commands(transport, "conversation.item.truncate"))
monkeypatch.setattr(RealtimeAdapter, "confirm_history_repair", lambda self, repair, event:
HistoryRepairReceipt(replace(repair, generation=repair.generation + 1), "ack", "wrong"))
await runtime.handle(dict(type="conversation.item.truncated", item_id="a1",
content_index=0, audio_end_ms=0))
assert not runtime.usable
assert len(commands(transport, "response.create")) == 1
assert next(iter(runtime.audio.values())).repair_receipt is None
finally:
await runtime.close()
asyncio.run(scenario())