From 1f7c2bd195ec31937fda047b8b0e2214b58da65e Mon Sep 17 00:00:00 2001 From: amirhosein mazaheri Date: Wed, 14 Oct 2026 12:04:08 +0330 Subject: [PATCH] fix(voice): decouple cancellation race handling from model and voice --- app/infrastructure/realtime.py | 14 ++--- app/modules/voice/diagnostics.py | 2 +- app/modules/voice/runtime.py | 4 +- docker-compose.voice-candidate.yml | 11 ++++ docs/guides/live-context-sync-repair.md | 13 ++++ docs/guides/voice-model-switch-rollback.md | 61 +++++++++++++++++++ docs/specifications/RAG-Phase1-API-Catalog.md | 13 +++- tests/unit/test_live_context_sync.py | 39 +++++++++--- 8 files changed, 134 insertions(+), 23 deletions(-) create mode 100644 docker-compose.voice-candidate.yml create mode 100644 docs/guides/voice-model-switch-rollback.md diff --git a/app/infrastructure/realtime.py b/app/infrastructure/realtime.py index de6ab90..a8dfcda 100644 --- a/app/infrastructure/realtime.py +++ b/app/infrastructure/realtime.py @@ -195,15 +195,11 @@ class RealtimeAdapter: try: if self.no_active_classifier is not None: return self.no_active_classifier(error) is True - # Selected-profile probe: docs/guides/live-context-sync-repair.md. - # The runtime separately requires the cancellation intent event_id, - # terminal response confirmation, and heard-position truncation. - return ((self.model, self.voice) in { - ("gpt-realtime-mini", "shimmer"), - ("gpt-realtime-2.1", "shimmer"), - ("gpt-realtime-2.1", "marin"), - } - and isinstance(error, dict) + # Captured structured OpenAI signature; independent of model/voice. + # Runtime still requires the cancellation intent event_id, terminal + # response confirmation, and heard-position truncation acknowledgements. + # Unknown signatures remain failures; never match provider message text. + return (isinstance(error, dict) and error.get("type") == "invalid_request_error" and error.get("code") == "response_cancel_not_active" and error.get("param") is None) diff --git a/app/modules/voice/diagnostics.py b/app/modules/voice/diagnostics.py index 52de570..3315e75 100644 --- a/app/modules/voice/diagnostics.py +++ b/app/modules/voice/diagnostics.py @@ -120,7 +120,7 @@ NUMERIC_FIELDS = frozenset({ "received_elapsed_ms", "terminal_completed", "terminal_cancelled", "terminal_limited", "terminal_failed", "terminal_incomplete", "terminal_tool_calls", "terminal_output_items", "authority_ms", "emit_ms", "queued_controls", - "cancellation_type_match", "cancellation_code_match", "cancellation_param_match", "cancellation_profile_2_1_shimmer", + "cancellation_type_match", "cancellation_code_match", "cancellation_param_match", "cancellation_correlated", "transport_limit_bytes", "transport_limit_messages", "occupancy_count", "limit_count", "occupancy_bytes", "limit_bytes", "transport_bytes", "transport_messages", "speech_bytes", "elapsed_ms", "deadline_remaining_ms", "sent_bytes", "played_ms", "pending_commands", "pending_responses", "pending_audio", "pending_tasks", "abort_succeeded", "input_bytes", "http_status", diff --git a/app/modules/voice/runtime.py b/app/modules/voice/runtime.py index 1ffc84d..3e19f90 100644 --- a/app/modules/voice/runtime.py +++ b/app/modules/voice/runtime.py @@ -1752,9 +1752,7 @@ class VoiceRuntime: cancellation_type_match=int(error.get("type") == "invalid_request_error"), cancellation_code_match=int(error.get("code") == "response_cancel_not_active"), cancellation_param_match=int(error.get("param") is None), - cancellation_profile_2_1_shimmer=int( - getattr(self.adapter, "model", None) == "gpt-realtime-2.1" - and getattr(self.adapter, "voice", None) == "shimmer")) + cancellation_correlated=1) self.sync_failed("CANCELLATION_PROVIDER_ERROR", turn=matches[0].turn, phase="provider_handle", event_type=kind) elif cleanup: self.sync_failed("TRUNCATION_PROVIDER_ERROR", turn=cleanup.response.turn, phase="provider_handle", event_type=kind, audio=cleanup) diff --git a/docker-compose.voice-candidate.yml b/docker-compose.voice-candidate.yml new file mode 100644 index 0000000..b9b8c31 --- /dev/null +++ b/docker-compose.voice-candidate.yml @@ -0,0 +1,11 @@ +# Start only after stopping rag-api; both APIs share one database. +# Keep rag-api intact for rollback. Never use compose down for switching. +services: + api_candidate: + extends: + file: docker-compose.yml + service: api + image: rag-api-model-switch:20261014 + container_name: rag-api-mini + environment: + OPENAI_REALTIME_MODEL: gpt-realtime-2.1-mini diff --git a/docs/guides/live-context-sync-repair.md b/docs/guides/live-context-sync-repair.md index 3fdc63d..e718a62 100644 --- a/docs/guides/live-context-sync-repair.md +++ b/docs/guides/live-context-sync-repair.md @@ -235,3 +235,16 @@ introduced. Real-provider attribution requires a new occurrence after deployment Validation: 122 focused synchronization, interruption and retained-search tests passed, including eight terminal failure/redaction cases. + + +### Protocol-scoped model switch (2026-10-14) + +The selected-model/voice classifier restriction is superseded by the explicitly +authorized API amendment. The previously captured exact structured signature is +now OpenAI-protocol scoped. The runtime never accepts it as terminal confirmation: +event-ID correlation, response.done, heard-position cleanup and matching truncate +acknowledgement remain independent gates with finite deadlines. Unknown signatures +remain fatal. Diagnostics now record cancellation_correlated instead of a +Shimmer-specific profile flag. Synthetic race coverage includes 2.1-mini with +Marin, Shimmer and Cedar in both terminal orderings and missing-terminal timeout. +Actual Mini speech quality and live interruption acceptance require a fresh session. diff --git a/docs/guides/voice-model-switch-rollback.md b/docs/guides/voice-model-switch-rollback.md new file mode 100644 index 0000000..98c5397 --- /dev/null +++ b/docs/guides/voice-model-switch-rollback.md @@ -0,0 +1,61 @@ +# Isolated OpenAI Mini candidate and rollback + +The original rag-api container is retained, with its image, environment and mounts. +The candidate rag-api-mini uses the separately built rag-api-model-switch:20261014 +image and changes only OPENAI_REALTIME_MODEL to gpt-realtime-2.1-mini via + docker-compose.voice-candidate.yml. Local .env remains the original profile. +The old image is also tagged rag-api-rollback:20261014. + +Both API instances share the database and startup reconciliation, so never run +both simultaneously, even on different ports. Switching ends current voice sessions; +start a fresh session. Worker, frontend, documents and database are not replaced. +Container rollback preserves code/configuration, not a database snapshot or live +session. Do not run compose down, container rm, or image pruning for this workflow. + +Build the candidate without replacing the current container: + +```powershell +docker build -t rag-api-model-switch:20261014 . +``` + +Switch after tests pass (if startup/readiness fails, stop the candidate and start +rag-api immediately): + +```powershell +docker stop rag-api +docker compose -f docker-compose.yml -f docker-compose.voice-candidate.yml up -d --no-deps --no-build api_candidate +Invoke-RestMethod http://localhost:8080/health/ready +``` + +Rollback using the original container, without any rebuild: + +```powershell +docker stop rag-api-mini +docker start rag-api +Invoke-RestMethod http://localhost:8080/health/ready +``` + +Switch back to the existing candidate: + +```powershell +docker stop rag-api +docker start rag-api-mini +``` + +Do not run the ordinary compose api up while the candidate owns port 8080. +Readiness is not provider or Persian quality acceptance. Actual microphone tests +must cover interruption during response and search, repeated questions, source +reports and long-session behavior. Unknown provider failures remain failures. + +## Verification checkpoint + +Before the code fix, expanded regressions reproduced 15 failures (40 passed). +Afterward, 343 focused provider-free cases passed. Adding wrong-cancellation-intent +coverage then passed all 57 context-sync cases, including two additional cases. +The candidate API reports ready; frontend responds HTTP 200. Runtime inspection +confirmed 2.1-mini/Marin, speed 1.30, 2048 output tokens, gpt-transcribe and low +reasoning. No provider generation or real microphone acceptance was performed. +Original container ID remains +65c9fa765c150467bde2d6336b09fb46d5ffe451d1117eb1ab93a7bacff1037d, +with its original image and configuration; it is stopped, not removed. +The unrelated pre-existing .gitignore edit is excluded from this change. diff --git a/docs/specifications/RAG-Phase1-API-Catalog.md b/docs/specifications/RAG-Phase1-API-Catalog.md index 9ba9b89..7c2bcbe 100644 --- a/docs/specifications/RAG-Phase1-API-Catalog.md +++ b/docs/specifications/RAG-Phase1-API-Catalog.md @@ -424,7 +424,7 @@ Require provider-confirmed cancellation/terminal generation within 5 seconds of The backend is the sole cancellation and response-creation owner. Configure private VAD create_response=false AND interrupt_response=false and require provider configuration acknowledgement; VAD still reports speech/commit events. The proof's defaults are not evidence of this configuration. For a known active old response, send at most one response.cancel with that specific private response_id and a unique private event_id mapped to the cancellation intent; never issue a bare cancel that could hit a newer response. Record terminal response.done state by response identity. If completion or provider cancellation was already observed for that response, skip cancellation and proceed to required playback/context cleanup. -A completion/cancellation racing after the backend's active-state check can produce a no-active-response cancellation error. Only an adapter-verified no-active-response classification tied by error event_id to that one cancellation intent/response is benign by itself: it does not fail the session, retry cancellation or satisfy the terminal/cleanup barrier. Independently require a correlated terminal response.done (completed/cancelled; failed/other incomplete handled as technical failure; the validated audio-only output-token limit below is terminal but limited) within the bounded cancellation deadline, then complete all required context cleanup. A terminal event already recorded satisfies this test; missing terminal confirmation times out and fails. A response identity mismatch, generic/unrelated error, bad arguments, authentication failure or truncation error is not this exception and remains fatal under its normal policy. Official docs establish the benign behavior but not a stable named error code; an exact structured classifier must be proved with the selected provider profile before race acceptance, never infer it from a free-text substring or swallow all cancellation errors. +A completion/cancellation racing after the backend's active-state check can produce a no-active-response cancellation error. Only an adapter-verified no-active-response classification tied by error event_id to that one cancellation intent/response is benign by itself: it does not fail the session, retry cancellation or satisfy the terminal/cleanup barrier. Independently require a correlated terminal response.done (completed/cancelled; failed/other incomplete handled as technical failure; the validated audio-only output-token limit below is terminal but limited) within the bounded cancellation deadline, then complete all required context cleanup. A terminal event already recorded satisfies this test; missing terminal confirmation times out and fails. A response identity mismatch, generic/unrelated error, bad arguments, authentication failure or truncation error is not this exception and remains fatal under its normal policy. Official docs establish the benign behavior but not a stable named error code; the exact captured OpenAI structured classifier is provider-protocol scoped, independent of model and voice, and must retain cancellation event-ID correlation plus terminal/cleanup confirmation, never infer it from a free-text substring or swallow all cancellation errors. Keep both VAD flags disabled throughout the session. Unexpected automatic generation/cancellation is an observable configuration/protocol deviation; correlate any actual terminal event for cleanup, suppress unintended output and fail if the controlled state cannot be established. The independent response-release gate in 7.1.6 applies even after all cleanup acknowledgements arrive. This is a future runtime obligation, not proof-script behavior. @@ -870,3 +870,14 @@ It does not admit other model/voice pairs or relax event-ID correlation, terminal confirmation, final playback positions or truncation acknowledgement. Synthetic regressions reproduce the original rejection, cover both terminal orderings, and retain failure when terminal confirmation is absent. + + +### OpenAI model-independent cancellation classification (2026-10-14) + +User-authorized amendment superseding the selected-model/voice restriction: +OpenAI's captured invalid_request_error / response_cancel_not_active / null-param +signature is classified independently of model and voice. Model admission and +session setup acknowledgement remain separate. Cancellation event-ID correlation, +bounded terminal confirmation, final playback and truncation acknowledgement gates +remain mandatory; unknown errors and failed/incomplete technical terminals remain +fatal. This change does not establish live acceptance for every OpenAI model. diff --git a/tests/unit/test_live_context_sync.py b/tests/unit/test_live_context_sync.py index e947f87..58a140a 100644 --- a/tests/unit/test_live_context_sync.py +++ b/tests/unit/test_live_context_sync.py @@ -232,8 +232,10 @@ CAPTURED_NO_ACTIVE = dict(type="invalid_request_error", @pytest.mark.parametrize("terminal_order", ["before_error", "after_error", "missing"]) -@pytest.mark.parametrize("model,voice", [("gpt-realtime-mini", "shimmer"), ("gpt-realtime-2.1", "marin")]) -def test_captured_selected_profile_cancellation_race(runner, persisted, terminal_order, model, voice): +@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, @@ -300,10 +302,10 @@ def test_captured_classifier_rejects_other_errors(mutation): @pytest.mark.parametrize("profile", [ dict(model="unverified-model"), dict(voice="unverified-voice"), ]) -def test_captured_classifier_is_restricted_to_verified_profile(profile): +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 not RealtimeAdapter(Transport(), **profile).is_no_active(CAPTURED_NO_ACTIVE) + 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( @@ -357,12 +359,12 @@ def test_terminal_technical_failure_is_not_accepted_as_cancellation_race( ("gpt-realtime-mini", "shimmer", True), ("gpt-realtime-2.1", "shimmer", True), ("gpt-realtime-2.1", "marin", True), - ("gpt-realtime-mini", "marin", False), - ("gpt-realtime-2.1", "cedar", False), - ("gpt-realtime-2.1", "alloy", False), - ("gpt-realtime-2.1-mini", "shimmer", False), + ("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_profile_and_signature_bounded(model, voice, accepted): +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 @@ -401,3 +403,22 @@ def test_terminal_failure_attribution_does_not_log_provider_payload( 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())