Files
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

88 lines
4.1 KiB
Python

"""Durable admission wraps actual StructuredTool work, never browser event inference."""
import asyncio
import time
from app.infrastructure.blocking import blocking
from sqlalchemy.exc import SQLAlchemyError
class DurableFailure(ValueError):
def __init__(self, code):
self.live_code = code
super().__init__(code)
class DurableTools:
def __init__(self, lifecycle, user, session_id):
self.lifecycle, self.user, self.session_id = lifecycle, user, session_id
async def execute(self, external_id, call, ctx, args, invoke):
row = await blocking(self.lifecycle.admit_tool, self.user, self.session_id,
external_id, call['ref'], args, ctx.execution)
call['ref'], call['durable_id'], call['inserted'] = str(row['public_ref']), row['id'], row['inserted']
if row['inserted']:
result = await invoke()
if ctx.cancelled.is_set():
await blocking(self.lifecycle.cancel_tools, self.user, self.session_id, [call['ref']])
raise ValueError('CANCELLED')
if not await blocking(self.lifecycle.complete_tool, self.user, self.session_id,
row['id'], result, ctx.execution):
raise ValueError('LIVE_SESSION_UNUSABLE')
return result
# Independent callers coalesce through the durable row; no second retrieval.
while True:
if time.monotonic() >= ctx.deadline:
raise TimeoutError("Tool duplicate wait expired")
if ctx.cancelled.is_set():
raise ValueError('CANCELLED')
result = await blocking(self.lifecycle.tool_result, self.user, self.session_id, row['id'], ctx.execution)
if result is not None:
return result
await asyncio.sleep(.025)
async def delivery(self, call, execution):
if call.get('name') == 'report_used_sources':
for original in call.get('source_origins', []):
await self.delivery(original, execution)
return
if 'durable_id' not in call:
return
try:
result = await blocking(self.lifecycle.tool_result, self.user, self.session_id, call['durable_id'], execution,
allow_technical_failure=True, require_current_knowledge='reused_result' in call)
if result != call.get('reused_result', call['result']):
raise ValueError('LIVE_CONTEXT_SYNC_FAILED')
except Exception as exc:
raise DurableFailure(failure_code(exc)) from None
async def reuse(self, original, execution):
# No admission/INSERT: this is the original real retrieval, revalidated.
await blocking(self.lifecycle.validate_stream, self.user, self.session_id, execution)
return await blocking(self.lifecycle.tool_result, self.user, self.session_id,
original['durable_id'], execution, require_current_knowledge=True)
def failure_code(exc):
"""A persistence failure is terminal: no unverified result may continue.
Diagnostics distinguish technical failure from verified authority loss.
"""
if isinstance(exc, DurableFailure):
return exc.live_code
if isinstance(exc, SQLAlchemyError):
return 'DEPENDENCY_UNAVAILABLE'
if isinstance(exc, TimeoutError):
return 'SEARCH_TIMEOUT'
code = str(exc) if isinstance(exc, ValueError) else getattr(exc, 'code', '')
if code in ('AUTH_REQUIRED','ACCOUNT_DISABLED','SESSION_REVOKED','SESSION_EXPIRED',
'CONTEXT_REVOKED','CONVERSATION_STALE','CONVERSATION_CLOSED',
'LIVE_SESSION_EXPIRED','LIVE_SESSION_UNUSABLE'):
return 'CONTEXT_REVOKED'
if code == 'LIVE_CONTEXT_SYNC_FAILED':
return code
if code in ('CANCELLED','TOOL_CANCELLED','SEARCH_CANCELLED'):
return 'SEARCH_CANCELLED'
if code == 'IDEMPOTENCY_CONFLICT':
return 'LIVE_PROVIDER_PROTOCOL_ERROR'
if code in ('SERVICE_BUSY','SEARCH_SATURATED'):
return 'SEARCH_SATURATED'
# Database/connectivity/provider availability never masquerades as revocation.
return 'LIVE_PROVIDER_UNAVAILABLE'