Files
rag-technical-docs-assistant/tests/unit/test_live_context_sync.py

425 lines
20 KiB
Python

"""Controlled-clock synchronization races and private branch attribution."""
import asyncio
import logging
from types import SimpleNamespace
import pytest
from tests.unit.test_realtime_phase1 import (
runner, persisted, make, input_turn, response, delta, done, until, commands, terminal,
)
from tests.unit.test_realtime_repairs import Clock, without_ticker
def test_numeric_timeline_is_disabled_by_default(runner, persisted, caplog, monkeypatch, tmp_path):
# Default behavior must not depend on the operator's diagnostic .env.
monkeypatch.chdir(tmp_path)
monkeypatch.delenv("LIVE_DIAGNOSTIC_TRACE_ENABLED", raising=False)
caplog.set_level(logging.INFO, logger="app.modules.voice.diagnostics")
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
await runtime.handle(delta(48000))
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
assert "Voice trace" not in caplog.text
finally:
await runtime.close()
asyncio.run(scenario())
def test_cancellation_timeline_distinguishes_receipt_from_locked_processing(runner, persisted, caplog):
caplog.set_level(logging.INFO, logger="app.modules.voice.diagnostics")
async def scenario():
clock = Clock()
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted, clock=clock)
runtime.settings = runtime.settings.model_copy(update={"diagnostic_trace_enabled": 1})
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: "stage=cancel_sent" in caplog.text)
deadline = runtime.responses["r1"].cancel_deadline
clock.now = deadline - .1
async with runtime.lock:
terminal_task = asyncio.create_task(done(runtime, status="cancelled"))
await until(lambda: "stage=terminal_received" in caplog.text)
assert "stage=terminal_processed" not in caplog.text
clock.advance(.05)
await terminal_task
assert runtime.usable and runtime.responses["r1"].terminal
assert runtime.responses["r1"].cancel_deadline == deadline
stages = [r.message.split("stage=")[1].split()[0] for r in caplog.records if "Voice trace" in r.message]
expected = ["cancel_enqueued", "cancel_dispatched", "cancel_sent", "terminal_received", "terminal_processed"]
assert [s for s in stages if s in expected] == expected
assert "lock_wait_ms=" in caplog.text
assert "turn=live-turn-1" in caplog.text
assert "generated_bytes=48000" in caplog.text and "sent_bytes=48000" in caplog.text
finally:
await runtime.close()
asyncio.run(scenario())
def test_trace_rejects_content_and_untrusted_references(caplog):
from app.modules.voice.diagnostics import trace
caplog.set_level(logging.INFO, logger="app.modules.voice.diagnostics")
trace("SECRET_SESSION", "audio_received", turn_ref="SECRET_TURN", audio_ref="SECRET_AUDIO",
chunk_bytes=9600, text="SECRET_DOCUMENT", generated_bytes=2**63, played_ms=True)
assert "SECRET" not in caplog.text
assert "generated_bytes=2147483647" in caplog.text and "chunk_bytes=9600" in caplog.text
assert "played_ms=" not in caplog.text
@pytest.mark.parametrize("terminal_first", [False, True])
@pytest.mark.parametrize("verified", [False, True])
def test_cancel_error_requires_verified_classification_and_terminal(
runner, persisted, caplog, terminal_first, verified):
async def scenario():
clock = Clock()
runtime, transport, out = await make(SimpleNamespace(engine=None), runner,
persisted, clock=clock,
classifier=(lambda e: e.get("code") == "verified-fixture-race") if verified else None)
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)
await input_turn(runtime, "u2", 10)
await until(lambda: commands(transport, "response.cancel"))
await runtime.playback_progress(audio.ref, 420)
if terminal_first:
await done(runtime)
await runtime.handle(dict(type="error", error=dict(
event_id=runtime.responses["r1"].cancel_event,
code="verified-fixture-race", message="SECRET_PROVIDER_ERROR")))
if not verified:
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
assert "reason=CANCELLATION_PROVIDER_ERROR" in caplog.text
assert "SECRET_PROVIDER_ERROR" not in caplog.text
return
assert runtime.usable
assert len(commands(transport, "response.create")) == 1
if not terminal_first:
await done(runtime)
clock.advance(1)
await runtime.tick()
await until(lambda: commands(transport, "conversation.item.truncate"))
truncation = commands(transport, "conversation.item.truncate")[0]
assert truncation["audio_end_ms"] == 420
assert audio.frozen
ack = dict(type="conversation.item.truncated", item_id="a1",
content_index=0, audio_end_ms=420)
await runtime.handle(ack)
await runtime.handle(dict(ack, event_id="duplicate-ack"))
await runtime.playback_progress(audio.ref, 420)
await until(lambda: len(commands(transport, "response.create")) == 2)
assert runtime.usable and audio.state == "retired"
assert len(commands(transport, "response.cancel")) == 1
assert len(commands(transport, "conversation.item.truncate")) == 1
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("branch,reason", [
("response", "RESPONSE_ACK_DEADLINE"),
("input", "INPUT_COMMIT_DEADLINE"),
("cancel", "CANCELLATION_ACK_DEADLINE"),
("truncate", "TRUNCATION_ACK_DEADLINE"),
])
def test_deadline_diagnostic_identifies_branch(runner, persisted, caplog, branch, reason):
async def scenario():
clock = Clock()
runtime, transport, out = await make(SimpleNamespace(engine=None), runner,
persisted, clock=clock)
await without_ticker(runtime)
try:
if branch == "input":
await input_turn(runtime, commit=False)
deadline = runtime.current.input_deadline
else:
await input_turn(runtime)
await until(lambda: commands(transport, "response.create"))
if branch == "response":
deadline = runtime.intent_deadline
else:
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"))
if branch == "cancel":
deadline = runtime.responses["r1"].cancel_deadline
else:
await done(runtime, status="cancelled")
clock.advance(1)
await runtime.tick()
await until(lambda: commands(transport, "conversation.item.truncate"))
deadline = next(iter(runtime.audio.values())).cleanup_deadline
clock.now = deadline
await runtime.tick()
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
assert runtime.session_id in caplog.text
assert f"reason={reason}" in caplog.text
assert "deadline_remaining_ms=0" in caplog.text
assert "pending_commands=" in caplog.text
if branch == "truncate":
assert "sent_bytes=48000" in caplog.text
assert "played_ms=0" in caplog.text
before = caplog.text
runtime.sync_failed("SECONDARY_FAILURE")
assert caplog.text == before
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("position", [419, 421])
def test_truncation_mismatch_diagnostic_remains_fail_closed(
runner, persisted, caplog, position):
async def scenario():
clock = Clock()
runtime, transport, out = 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 done(runtime)
await input_turn(runtime, "u2", 10)
assert not commands(transport, "response.cancel")
await runtime.playback_progress(audio.ref, 420)
clock.advance(1)
await runtime.tick()
await until(lambda: commands(transport, "conversation.item.truncate"))
await runtime.handle(dict(type="conversation.item.truncated", item_id="a1",
content_index=0, audio_end_ms=position))
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
assert "reason=TRUNCATION_ACK_POSITION_MISMATCH" in caplog.text
assert "played_ms=420" in caplog.text
assert len(commands(transport, "response.create")) == 1
finally:
await runtime.close()
asyncio.run(scenario())
def test_numeric_diagnostics_are_allowlisted_and_bounded(caplog):
from app.modules.voice.diagnostics import diagnostic
diagnostic("fixture-session", "context_sync", "TRUNCATION_PROVIDER_ERROR",
sent_bytes=10**100, played_ms=True, transcript="SECRET_TRANSCRIPT",
tool_result="SECRET_TOOL", pending_audio=3)
assert "sent_bytes=2147483647" in caplog.text
assert "pending_audio=3" in caplog.text
assert "played_ms=" not in caplog.text
assert "SECRET" not in caplog.text
# Sanitized structured fields captured with gpt-realtime-mini/shimmer on
# 2026-10-10; no raw provider events, audio, transcript, or credentials retained.
CAPTURED_NO_ACTIVE = dict(type="invalid_request_error",
code="response_cancel_not_active", param=None)
@pytest.mark.parametrize("terminal_order", ["before_error", "after_error", "missing"])
@pytest.mark.parametrize("model,voice", [("gpt-realtime-mini", "shimmer"), ("gpt-realtime-2.1", "marin"),
("gpt-realtime-2.1-mini", "marin"), ("gpt-realtime-2.1-mini", "shimmer"),
("gpt-realtime-2.1-mini", "cedar")])
def test_captured_protocol_cancellation_race(runner, persisted, terminal_order, model, voice):
async def scenario():
clock = Clock()
runtime, transport, out = await make(SimpleNamespace(engine=None), runner,
persisted, clock=clock)
await without_ticker(runtime)
runtime.adapter.model, runtime.adapter.voice = model, voice
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 input_turn(runtime, "u2", 10)
await until(lambda: commands(transport, "response.cancel"))
await runtime.playback_progress(audio.ref, 420)
error = dict(type="error", error=dict(CAPTURED_NO_ACTIVE,
event_id=runtime.responses["r1"].cancel_event))
if terminal_order == "before_error":
await done(runtime)
await runtime.handle(error)
assert runtime.usable
await runtime.handle(dict(error, event_id="replayed-cancel-error"))
assert runtime.usable
if terminal_order == "missing":
clock.now = runtime.responses["r1"].cancel_deadline
await runtime.tick()
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
assert not commands(transport, "conversation.item.truncate")
return
if terminal_order == "after_error":
await done(runtime)
clock.advance(1)
await runtime.tick()
await until(lambda: commands(transport, "conversation.item.truncate"))
assert commands(transport, "conversation.item.truncate")[0]["audio_end_ms"] == 420
assert len(commands(transport, "response.create")) == 1
await runtime.handle(dict(type="conversation.item.truncated", item_id="a1",
content_index=0, audio_end_ms=420))
await until(lambda: len(commands(transport, "response.create")) == 2)
await response(runtime, transport, response_id="r2")
# Late duplicate cancellation errors cannot cancel the new response.
await runtime.handle(dict(error, event_id="late-cancel-error"))
assert runtime.usable and audio.state == "retired"
assert not runtime.responses["r2"].interrupted
assert len(commands(transport, "response.cancel")) == 1
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("mutation", [
dict(code="other_error"), dict(type="server_error"), dict(param="response_id"),
dict(code="response_cancel_not_active_EXTRA"),
dict(message="response_cancel_not_active", code="invalid_argument"),
])
def test_captured_classifier_rejects_other_errors(mutation):
from app.infrastructure.realtime import RealtimeAdapter
from tests.unit.test_realtime_phase1 import Transport
adapter = RealtimeAdapter(Transport())
assert adapter.is_no_active(CAPTURED_NO_ACTIVE)
assert not adapter.is_no_active(dict(CAPTURED_NO_ACTIVE, **mutation))
@pytest.mark.parametrize("profile", [
dict(model="unverified-model"), dict(voice="unverified-voice"),
])
def test_captured_classifier_does_not_use_model_or_voice(profile):
from app.infrastructure.realtime import RealtimeAdapter
from tests.unit.test_realtime_phase1 import Transport
assert RealtimeAdapter(Transport(), **profile).is_no_active(CAPTURED_NO_ACTIVE)
@pytest.mark.parametrize("failure", ["transport", "protocol"])
def test_receive_failure_during_sync_keeps_category_and_private_reason(
runner, persisted, caplog, failure):
async def scenario():
from app.infrastructure.realtime import ProviderProtocolError
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
await input_turn(runtime, "u2", 10)
await until(lambda: commands(transport, "response.cancel"))
async def broken():
if failure == "transport":
raise ConnectionError("SECRET_TRANSPORT")
raise ProviderProtocolError("SECRET_PROTOCOL")
runtime.adapter.receive = broken
await runtime.receive_loop()
expected = "LIVE_CONTEXT_SYNC_FAILED" if failure == "transport" else "LIVE_PROVIDER_PROTOCOL_ERROR"
assert runtime.failure == expected
assert "SECRET" not in caplog.text
if failure == "transport":
assert "reason=PROVIDER_TRANSPORT_LOST_DURING_SYNC" in caplog.text
assert "exception=ConnectionError" in caplog.text
await asyncio.gather(runtime.close(), runtime.close())
assert runtime.failure == expected and transport.closed
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("status", ["failed", "incomplete"])
def test_terminal_technical_failure_is_not_accepted_as_cancellation_race(
runner, persisted, status):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
await input_turn(runtime, "u2", 10)
await until(lambda: commands(transport, "response.cancel"))
await done(runtime, status=status)
await runtime.handle(dict(type="error", error=dict(CAPTURED_NO_ACTIVE,
event_id=runtime.responses["r1"].cancel_event)))
assert runtime.failure == "LIVE_PROVIDER_UNAVAILABLE"
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("model,voice,accepted", [
("gpt-realtime-mini", "shimmer", True),
("gpt-realtime-2.1", "shimmer", True),
("gpt-realtime-2.1", "marin", True),
("gpt-realtime-mini", "marin", True),
("gpt-realtime-2.1", "cedar", True),
("gpt-realtime-2.1", "alloy", True),
("gpt-realtime-2.1-mini", "shimmer", True),
])
def test_no_active_classifier_is_signature_bounded(model, voice, accepted):
from app.infrastructure.realtime import RealtimeAdapter
adapter = RealtimeAdapter(object(), model=model, voice=voice)
assert adapter.is_no_active(CAPTURED_NO_ACTIVE) is accepted
assert not adapter.is_no_active(dict(CAPTURED_NO_ACTIVE, code="other"))
assert not adapter.is_no_active(dict(CAPTURED_NO_ACTIVE, param="response_id"))
@pytest.mark.parametrize("status,details,reason", [
("failed", {"error": {"code": "server_error"}}, "PROVIDER_RESPONSE_SERVER_ERROR"),
("failed", {"error": {"code": "rate_limit_exceeded"}}, "PROVIDER_RESPONSE_RATE_LIMIT"),
("failed", {"error": {"code": "insufficient_quota"}}, "PROVIDER_RESPONSE_QUOTA"),
("incomplete", {"reason": "content_filter"}, "PROVIDER_RESPONSE_CONTENT_FILTER"),
("incomplete", {"reason": "PRIVATE_PAYLOAD"}, "PROVIDER_RESPONSE_INCOMPLETE"),
("failed", {"error": {"code": ["PRIVATE_PAYLOAD"]}}, "PROVIDER_RESPONSE_FAILED"),
("failed", {"error": {"code": "PRIVATE_PAYLOAD"}}, "PROVIDER_RESPONSE_FAILED"),
("failed", None, "PROVIDER_RESPONSE_FAILED"),
])
def test_terminal_failure_attribution_does_not_log_provider_payload(
runner, persisted, caplog, status, details, reason):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
event = terminal(status=status)
event["response"]["status_details"] = details
event["response"]["private_text"] = "PRIVATE_PAYLOAD"
if isinstance(details, dict):
details["message"] = "PRIVATE_PAYLOAD"
await runtime.handle(event)
assert runtime.failure == "LIVE_PROVIDER_UNAVAILABLE"
assert f"reason={reason} " in caplog.text
assert f"terminal_{status}=1" in caplog.text
assert "PRIVATE_PAYLOAD" not in caplog.text
assert "PRIVATE_PAYLOAD" not in str(out)
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("model", ["gpt-realtime-2.1", "gpt-realtime-2.1-mini"])
def test_known_cancel_signature_with_wrong_intent_does_not_release_turn(runner, persisted, model):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
runtime.adapter.model, runtime.adapter.voice = model, "marin"
try:
await input_turn(runtime)
await response(runtime, transport)
await input_turn(runtime, "u2", 10)
await until(lambda: commands(transport, "response.cancel"))
await runtime.handle(dict(type="error", error=dict(CAPTURED_NO_ACTIVE,
event_id="unrelated-intent")))
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
assert len(commands(transport, "response.create")) == 1
finally:
await runtime.close()
asyncio.run(scenario())