Files
rag-technical-docs-assistant/tests/unit/test_voice_search_interruption.py
amirhosein mazaheri 18e595ac93 fix(voice): preserve interrupted searches and report used sources
Retain and revalidate interrupted searches, resolve abandoned provider calls, recover invalid source reports privately, and expose only declared sources. Improve Persian delivery and provider event replay capacity. Include regression coverage and contract updates.
2026-10-13 14:09:20 +03:30

222 lines
10 KiB
Python

"""Old-turn durable cancellation must not terminate a healthy voice session."""
import asyncio
import json
from threading import Event
from types import SimpleNamespace
from uuid import uuid4
import pytest
from sqlalchemy.exc import SQLAlchemyError
from app.modules.voice.durable_tools import DurableTools
from tests.unit.test_realtime_phase1 import (
runner, persisted, make, input_turn, response, call, done, until, commands,
)
@pytest.mark.parametrize("terminal_first", [False, True])
@pytest.mark.parametrize("completion", ["cancelled", "late_result"])
def test_old_search_interruption_keeps_session_usable(
runner, persisted, monkeypatch, terminal_first, completion):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
entered, finish = asyncio.Event(), asyncio.Event()
completing, publish = Event(), Event()
state = {}
result = dict(status="ok", sources=[dict(source_ref="S1",
document_id=str(uuid4()), chunk_id=str(uuid4()), title="Old source",
excerpt="Old evidence", location=None)])
async def invoke(args):
entered.set()
await finish.wait()
return result
monkeypatch.setattr("app.modules.voice.runtime.create_search_tool",
lambda *args: SimpleNamespace(ainvoke=invoke))
def admit(*args):
state["status"] = "running"
return dict(id=uuid4(), public_ref=uuid4(), inserted=True)
def cancel(*args):
state.update(status="failed", error_code="TOOL_CANCELLED")
def complete(*args):
completing.set()
assert publish.wait(3)
state["status"] = "succeeded"
return True
runtime.tool_store = DurableTools(SimpleNamespace(
admit_tool=admit, cancel_tools=cancel, complete_tool=complete), None, runtime.session_id)
try:
old = await input_turn(runtime)
await response(runtime, transport)
await runtime.handle(call())
# Start trusted retrieval while generation is active; terminal
# confirmation then races with genuine speech and search completion.
event = call()
async with runtime.lock:
await runtime.dispatch(runtime.responses["r1"], event["call_id"],
event["name"], event["arguments"], event["item_id"])
await asyncio.wait_for(entered.wait(), 3)
task = next(iter(runtime.tasks))
if completion == "late_result":
finish.set()
await until(completing.is_set)
if terminal_first:
await done(runtime)
await input_turn(runtime, "u2", 210)
if not terminal_first:
assert len(commands(transport, "response.create")) == 1
await done(runtime, status="cancelled")
assert old.superseded and old.cancelled.is_set()
finish.set()
publish.set()
await asyncio.wait_for(asyncio.shield(task), 3)
assert runtime.usable and runtime.failure is None
assert runtime.calls["c1"][1]["result"] is None
await until(lambda: len(commands(transport, "response.create")) == 2)
outputs = commands(transport, "conversation.item.create")
assert len(outputs) == 1 and outputs[0]["item"]["call_id"] == "c1"
payload = json.loads(outputs[0]["item"]["output"])
assert payload["status"] == "cancelled" and payload["sources"] == []
assert "Old evidence" not in outputs[0]["item"]["output"]
assert not any(isinstance(e, dict) and e.get("type") == "sources" for e in out)
assert state == dict(status="succeeded")
assert runtime.calls["c1"][1]["retained_result"] == result
await response(runtime, transport, response_id="r2")
await done(runtime, "r2")
assert runtime.usable and len(commands(transport, "response.create")) == 2
assert not runtime.responses["r1"].continued
finally:
finish.set()
publish.set()
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("supersede", [False, True])
@pytest.mark.parametrize("exc,code", [
(ValueError("CANCELLED"), "SEARCH_CANCELLED"),
(ValueError("SESSION_REVOKED"), "CONTEXT_REVOKED"),
(SQLAlchemyError("private persistence failure"), "DEPENDENCY_UNAVAILABLE"),
(TimeoutError(), "SEARCH_TIMEOUT"),
(ConnectionError("private provider failure"), "LIVE_PROVIDER_UNAVAILABLE"),
])
def test_search_failure_policy(runner, persisted, supersede, exc, code):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
entered, finish = asyncio.Event(), asyncio.Event()
async def execute(*args):
entered.set()
await finish.wait()
raise exc
runtime.tool_store = SimpleNamespace(execute=execute)
try:
await input_turn(runtime)
await response(runtime, transport)
await runtime.handle(call())
await done(runtime)
await asyncio.wait_for(entered.wait(), 3)
task = next(iter(runtime.tasks))
if supersede:
await input_turn(runtime, "u2", 210)
if code == "SEARCH_CANCELLED":
# Explicit topic discard cancels retrieval; speech alone does not.
runtime.calls["c1"][1]["retrieval_cancelled"].set()
finish.set()
await asyncio.wait_for(asyncio.shield(task), 3)
if supersede and code == "SEARCH_CANCELLED":
assert runtime.usable and runtime.failure is None
else:
assert not runtime.usable and runtime.failure == code
outputs = commands(transport, "conversation.item.create")
if not supersede:
assert outputs == []
for output in outputs:
payload = json.loads(output["item"]["output"])
assert output["item"]["call_id"] == "c1"
assert payload["status"] == "cancelled" and payload["sources"] == []
assert runtime.calls["c1"][1]["result"] is None
finally:
finish.set()
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("known", [False, True])
@pytest.mark.parametrize("voice", ["shimmer", "coral"])
def test_profile_cancellation_diagnostics(runner, persisted, caplog, known, voice):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
runtime.adapter.model = "gpt-realtime-2.1"
runtime.adapter.voice = voice
try:
await input_turn(runtime)
await response(runtime, transport)
await input_turn(runtime, "u2", 210)
await until(lambda: commands(transport, "response.cancel"))
await runtime.handle(dict(type="error", error=dict(
event_id=runtime.responses["r1"].cancel_event,
type="invalid_request_error" if known else "PRIVATE_TYPE",
code="response_cancel_not_active" if known else "PRIVATE_CODE",
param=None if known else "PRIVATE_PARAM", message="PRIVATE_MESSAGE")))
if known and voice == "shimmer":
assert runtime.usable and runtime.failure is None
assert not runtime.responses["r1"].terminal
assert len(commands(transport, "response.create")) == 1
return
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
assert f"cancellation_profile_2_1_shimmer={int(voice == 'shimmer')}" in caplog.text
for field in ("type", "code", "param"):
assert f"cancellation_{field}_match={int(known)}" in caplog.text
assert "PRIVATE" not in caplog.text
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("state", ["lock_race", "current_flag", "old_without_flag"])
def test_cancellation_decision_uses_locked_turn_state(runner, persisted, state):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
entered, finish, raising = asyncio.Event(), asyncio.Event(), asyncio.Event()
async def execute(*args):
entered.set()
await finish.wait()
raising.set()
raise ValueError("CANCELLED")
runtime.tool_store = SimpleNamespace(execute=execute)
try:
old = await input_turn(runtime)
await response(runtime, transport)
await runtime.handle(call())
await done(runtime)
await asyncio.wait_for(entered.wait(), 3)
task = next(iter(runtime.tasks))
async with runtime.lock:
finish.set()
await asyncio.wait_for(raising.wait(), 3)
# The exception path is now waiting for this same runtime lock.
if state == "current_flag":
old.cancelled.set()
else:
await runtime.new_turn("u2")
if state == "lock_race":
runtime.calls["c1"][1]["retrieval_cancelled"].set()
if state == "old_without_flag":
runtime.calls["c1"][1]["retrieval_cancelled"].clear()
await asyncio.wait_for(asyncio.shield(task), 3)
if state == "lock_race":
assert runtime.usable and runtime.failure is None
else:
assert runtime.failure == "SEARCH_CANCELLED" and not runtime.usable
assert runtime.calls["c1"][1]["result"] is None
assert not commands(transport, "conversation.item.create")
finally:
finish.set()
await runtime.close()
asyncio.run(scenario())