"""Settings-first durable Live transactions. Remote work runs after commit.""" from datetime import datetime, timezone, timedelta import hashlib import json from uuid import UUID, uuid4 from sqlalchemy import text from app.modules.knowledge.service import SearchInput, authority, transaction, KnowledgeError ACTIVE = ('creating', 'connecting', 'connected') TECHNICAL_ERRORS = frozenset(('SEARCH_TIMEOUT','SEARCH_FAILED','SEARCH_SATURATED', 'PROVIDER_TIMEOUT','PROVIDER_UNAVAILABLE','DEPENDENCY_UNAVAILABLE', 'SERVICE_UNAVAILABLE','DATABASE_UNAVAILABLE','SEARCH_UNAVAILABLE', 'CALIBRATION_REQUIRED','PROFILE_MISMATCH','INVALID_CONFIGURATION','INVALID_VECTOR')) def replayable_error(row): result = row['result_json'] return (row['status'] == 'failed' and isinstance(result, dict) and result.get('status') == 'error' and row['error_code'] in TECHNICAL_ERRORS and (result.get('error') or {}).get('code') == row['error_code']) def canonical_hash(data): return hashlib.sha256(json.dumps(data, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode('utf-8')).hexdigest() def now(): return datetime.now(timezone.utc) class LiveLifecycleService: def __init__(self, engine, session_ttl=timedelta(minutes=10)): self.engine, self.session_ttl = engine, session_ttl def _actor(self, conn, user): try: current, settings = authority(conn, user.id, exclusive=True) except KnowledgeError as exc: raise ValueError("ACCOUNT_DISABLED" if exc.code == "ACTOR_UNAVAILABLE" else "AUTH_REQUIRED") from None if current['organization_id'] != user.organization_id: raise ValueError('AUTH_REQUIRED') auth = conn.execute(text('''SELECT * FROM auth_sessions WHERE id=:auth AND organization_id=:org AND user_id=:owner FOR SHARE'''), dict(auth=user.auth_session_id, org=user.organization_id, owner=user.id)).mappings().first() if auth is None: raise ValueError('AUTH_REQUIRED') if auth['revoked_at'] is not None: raise ValueError('SESSION_REVOKED') if auth['expires_at'] <= now(): raise ValueError('SESSION_EXPIRED') return current, settings def _conversation(self, conn, user, cid, settings): row = conn.execute(text('''SELECT * FROM conversations WHERE id=:id AND organization_id=:org AND owner_user_id=:owner FOR UPDATE'''), dict(id=cid, org=user.organization_id, owner=user.id)).mappings().first() if row is None: raise ValueError('CONVERSATION_NOT_FOUND') if row['mode'] != 'voice': raise ValueError('MODE_MISMATCH') if row['status'] == 'closed': raise ValueError('CONVERSATION_CLOSED') if row['status'] != 'active' or row['access_epoch'] != settings['access_epoch']: raise ValueError('CONVERSATION_STALE') return row def _session(self, conn, user, sid, settings, *, connected=False): initial = conn.execute(text('''SELECT conversation_id FROM live_sessions WHERE id=:id AND organization_id=:org AND owner_user_id=:owner'''), dict(id=sid, org=user.organization_id, owner=user.id)).mappings().first() if initial is None: raise ValueError('SESSION_NOT_FOUND') self._conversation(conn, user, initial['conversation_id'], settings) row = conn.execute(text('SELECT * FROM live_sessions WHERE id=:id FOR UPDATE'), {'id': sid}).mappings().one() if row['expires_at'] <= now(): raise ValueError('LIVE_SESSION_EXPIRED') if (row['auth_session_id'] != user.auth_session_id or row['status'] not in ACTIVE or row['expires_at'] <= now() or row['access_epoch'] != settings['access_epoch'] or (connected and row['status'] != 'connected')): raise ValueError('LIVE_SESSION_UNUSABLE') return row @staticmethod def _calibration_status(row): search = (row["execution_profile"] or {}).get("search", {}) return "calibrated" if search.get("calibration_id") else search.get("calibration_status", "unknown") @staticmethod def _shape(row, *, replayed=False, eligible=True): sid = str(row['id']) return dict(session_id=sid, conversation_id=str(row['conversation_id']), status=row['status'], stream_path=f'/api/v1/voice/sessions/{sid}/stream' if eligible else None, expires_at=row['expires_at'].isoformat(), poll_url=f'/api/v1/voice/sessions/{sid}', replayed=replayed, calibration_status=LiveLifecycleService._calibration_status(row)) @staticmethod def _terminal(conn, sid, reason, *, failed=False): stamp = now() conn.execute(text('''UPDATE live_sessions SET status=:status, closed_at=:now, close_reason=:reason,error_code=:error,updated_at=:now WHERE id=:id AND status IN ('creating','connecting','connected')'''), dict(id=sid, status='failed' if failed else 'closed', now=stamp, reason=reason, error=reason if failed else None)) conn.execute(text('''UPDATE tool_calls SET status='failed',completed_at=:now,error_code=:reason WHERE live_session_id=:id AND status='running' '''), dict(id=sid, now=stamp, reason=reason)) def expire_reservations(self, user): # Cleanup commits independently so a later creation conflict cannot undo it. with transaction(self.engine) as conn: self._actor(conn, user) rows = conn.execute(text('''SELECT id FROM live_sessions WHERE organization_id=:org AND owner_user_id=:owner AND status IN ('creating','connecting','connected') AND expires_at<=:now ORDER BY conversation_id,id'''), dict(org=user.organization_id, owner=user.id, now=now())).scalars().all() for sid in rows: self._terminal(conn, sid, 'LIVE_SESSION_EXPIRED') def create_conversation(self, user, client_request_id, mode='voice', title=None): if mode != 'voice': raise ValueError('MODE_MISMATCH') legacy_title = title title = title.strip() if title is not None else None digest = canonical_hash(dict(mode=mode, title=title)) with transaction(self.engine) as conn: current, settings = self._actor(conn, user) row = conn.execute(text('''SELECT * FROM conversations WHERE owner_user_id=:owner AND organization_id=:org AND client_request_id=:req'''), dict(owner=user.id, org=user.organization_id, req=client_request_id)).mappings().first() replayed = row is not None if row is not None and row['request_hash'] != digest: legacy = canonical_hash(dict(user=str(user.id), request=str(client_request_id), mode=mode, title=legacy_title or '')) if row['request_hash'] != legacy or row['mode'] != mode or row['title'] != legacy_title: raise ValueError('IDEMPOTENCY_CONFLICT') conn.execute(text('UPDATE conversations SET request_hash=:hash WHERE id=:id'), dict(hash=digest, id=row['id'])) if row is None: row = conn.execute(text('''INSERT INTO conversations (id,organization_id,owner_user_id,client_request_id,request_hash,mode,title,access_epoch) VALUES (:id,:org,:owner,:req,:hash,'voice',:title,:epoch) RETURNING *'''), dict(id=uuid4(), org=user.organization_id, owner=user.id, req=client_request_id, hash=digest, title=title, epoch=settings['access_epoch'])).mappings().one() return dict(id=str(row['id']), mode=row['mode'], title=row['title'], status=row['status'], access_epoch=row['access_epoch'], created_at=row['created_at'].isoformat(), replayed=replayed) def create_live_session(self, user, conversation_id, client_request_id, provider='gemini', model='gemini-2.0-flash-exp', execution_profile=None): self.expire_reservations(user) digest = canonical_hash(dict(conversation_id=str(conversation_id))) with transaction(self.engine) as conn: current, settings = self._actor(conn, user) row = conn.execute(text('''SELECT * FROM live_sessions WHERE organization_id=:org AND owner_user_id=:owner AND client_request_id=:req'''), dict(org=user.organization_id, owner=user.id, req=client_request_id)).mappings().first() if row is not None: if row['request_hash'] != digest: # Original Phase 2 included server configuration in V01's hash. # Verify against the original pinned row, never today's config. legacy = canonical_hash(dict(owner=str(user.id), conversation_id=str(conversation_id), client_request_id=str(client_request_id), provider=row['provider'], model=row['model'])) if row['request_hash'] != legacy or row['conversation_id'] != conversation_id: raise ValueError('IDEMPOTENCY_CONFLICT') conn.execute(text('UPDATE live_sessions SET request_hash=:hash WHERE id=:id'), dict(hash=digest, id=row['id'])) self._session(conn, user, row['id'], settings) return self._shape(row, replayed=True) self._conversation(conn, user, conversation_id, settings) if conn.execute(text('''SELECT id FROM live_sessions WHERE conversation_id=:id AND status IN ('creating','connecting','connected')'''), {'id': conversation_id}).first(): raise ValueError('LIVE_SESSION_BUSY') row = conn.execute(text('''INSERT INTO live_sessions (id,organization_id,conversation_id,owner_user_id,auth_session_id,client_request_id,request_hash, provider,model,status,settings_revision,knowledge_revision,access_epoch,execution_profile,expires_at) VALUES (:id,:org,:conv,:owner,:auth,:req,:hash,:provider,:model,'connecting', :revision,:knowledge,:epoch,CAST(:profile AS jsonb),:expires) RETURNING *'''), dict(id=uuid4(), org=user.organization_id, conv=conversation_id, owner=user.id, auth=user.auth_session_id, req=client_request_id, hash=digest, provider=provider, model=model, revision=settings['revision'], knowledge=settings['knowledge_revision'], epoch=settings['access_epoch'], profile=json.dumps(execution_profile or {}), expires=now()+self.session_ttl)).mappings().one() return self._shape(row) def recover_live_session(self, user, client_request_id): self.expire_reservations(user) with transaction(self.engine) as conn: current, settings = self._actor(conn, user) row = conn.execute(text('''SELECT * FROM live_sessions WHERE organization_id=:org AND owner_user_id=:owner AND client_request_id=:req'''), dict(org=user.organization_id, owner=user.id, req=client_request_id)).mappings().first() if row is None: raise ValueError('SESSION_NOT_FOUND') try: self._session(conn, user, row['id'], settings) eligible = row['status'] == 'connecting' except ValueError: eligible = False return self._shape(row, eligible=eligible) def validate_stream(self, user, session_id, execution=None, *, initial=False): with transaction(self.engine) as conn: current, settings = self._actor(conn, user) row = self._session(conn, user, session_id, settings) if initial and row['status'] != 'connecting': raise ValueError('LIVE_SESSION_UNUSABLE') if execution is not None and not execution.capture(current, settings['access_epoch']): raise ValueError('CONTEXT_REVOKED') return dict(row) def mark_connected(self, user, session_id): with transaction(self.engine) as conn: current, settings = self._actor(conn, user) self._session(conn, user, session_id, settings) conn.execute(text('''UPDATE live_sessions SET status='connected',connected_at=COALESCE(connected_at,now()), updated_at=now() WHERE id=:id'''), {'id': session_id}) def finish_session(self, user, session_id, reason='user_requested', *, failed=False): with transaction(self.engine) as conn: conn.execute(text('SELECT organization_id FROM organization_settings WHERE organization_id=:org FOR UPDATE'), {'org': user.organization_id}) row = conn.execute(text('''SELECT * FROM live_sessions WHERE id=:id AND organization_id=:org AND owner_user_id=:owner'''), dict(id=session_id, org=user.organization_id, owner=user.id)).mappings().first() if row is None: raise ValueError('SESSION_NOT_FOUND') self._terminal(conn, session_id, reason, failed=failed) row = conn.execute(text('SELECT * FROM live_sessions WHERE id=:id'), {'id': session_id}).mappings().one() from app.modules.voice.registry import notify notify(session_id=session_id) return dict(session_id=str(session_id), status=row['status'], close_reason=row['close_reason']) def close_live_session(self, user, session_id, reason='user_requested'): return self.finish_session(user, session_id, reason) def _sources(self, conn, org, sources): result = [] for source in sources: copied = dict(source) row = conn.execute(text('''SELECT d.id FROM documents d JOIN document_chunks c ON c.organization_id=d.organization_id AND c.document_id=d.id WHERE d.organization_id=:org AND d.id=:doc AND c.id=:chunk AND d.status='ready' AND d.is_active AND d.deleted_at IS NULL AND d.content_purged_at IS NULL'''), dict(org=org, doc=UUID(source['document_id']), chunk=UUID(source['chunk_id']))).first() copied['available'] = row is not None copied['excerpt'] = copied.pop('text', copied.get('excerpt')) if row else None if row is None: copied.pop('text', None) result.append(copied) return result def get_live_session(self, user, session_id): self.expire_reservations(user) with transaction(self.engine) as conn: self._actor(conn, user) row = conn.execute(text('''SELECT * FROM live_sessions WHERE id=:id AND organization_id=:org AND owner_user_id=:owner'''), dict(id=session_id, org=user.organization_id, owner=user.id)).mappings().first() if row is None: raise ValueError('SESSION_NOT_FOUND') calls = conn.execute(text('''SELECT * FROM tool_calls WHERE live_session_id=:id AND organization_id=:org ORDER BY created_at DESC,id DESC LIMIT 20'''), dict(id=session_id, org=user.organization_id)).mappings().all() results = [dict(tool_call_id=str(c['public_ref']), status=c['status'], created_at=c['created_at'].isoformat(), error_code=c['error_code'], sources=self._sources(conn, user.organization_id, (c['result_json'] or {}).get('sources', []))) for c in reversed(calls)] return dict(session_id=str(row['id']), status=row['status'], close_reason=row['close_reason'], expires_at=row['expires_at'].isoformat(), error_code=row['error_code'], recent_tool_results=results, calibration_status=self._calibration_status(row)) def admit_tool(self, user, session_id, external_call_id, public_ref, arguments, execution): arguments = SearchInput.model_validate(arguments).model_dump() digest = canonical_hash(arguments) with transaction(self.engine) as conn: current, settings = self._actor(conn, user) self._session(conn, user, session_id, settings, connected=True) if not execution.capture(current, settings['access_epoch']): raise ValueError('CONTEXT_REVOKED') row = conn.execute(text('''SELECT * FROM tool_calls WHERE live_session_id=:sid AND external_call_id=:ext FOR UPDATE'''), dict(sid=session_id, ext=external_call_id)).mappings().first() if row: if row['request_hash'] != digest: raise ValueError('IDEMPOTENCY_CONFLICT') if (row['status'] == 'failed' and not replayable_error(row)) or row['access_epoch'] != settings['access_epoch']: raise ValueError('LIVE_SESSION_UNUSABLE') if row['result_json'] and any(not s['available'] for s in self._sources(conn, user.organization_id, row['result_json'].get('sources', []))): raise ValueError('CONTEXT_REVOKED') return dict(row, inserted=False) row = conn.execute(text('''INSERT INTO tool_calls (id,organization_id,live_session_id,external_call_id,public_ref,arguments,request_hash,knowledge_revision,access_epoch) VALUES (:id,:org,:sid,:ext,:ref,CAST(:args AS jsonb),:hash,:knowledge,:epoch) RETURNING *'''), dict(id=uuid4(), org=user.organization_id, sid=session_id, ext=external_call_id, ref=UUID(public_ref), args=json.dumps(arguments), hash=digest, knowledge=settings['knowledge_revision'], epoch=settings['access_epoch'])).mappings().one() return dict(row, inserted=True) def tool_result(self, user, session_id, call_id, execution, *, allow_technical_failure=False): with transaction(self.engine) as conn: current, settings = self._actor(conn, user) self._session(conn, user, session_id, settings, connected=True) if not execution.matches(current, settings['access_epoch']): raise ValueError('CONTEXT_REVOKED') row = conn.execute(text('SELECT * FROM tool_calls WHERE id=:id AND live_session_id=:sid'), dict(id=call_id, sid=session_id)).mappings().one() if row['status'] == 'failed' and not replayable_error(row): raise ValueError('LIVE_SESSION_UNUSABLE') result = row['result_json'] if result and any(not s['available'] for s in self._sources(conn, user.organization_id, result.get('sources', []))): raise ValueError('CONTEXT_REVOKED') return result def complete_tool(self, user, session_id, call_id, result, execution): with transaction(self.engine) as conn: current, settings = self._actor(conn, user) self._session(conn, user, session_id, settings, connected=True) if not execution.matches(current, settings['access_epoch']): raise ValueError('CONTEXT_REVOKED') if any(not s['available'] for s in self._sources(conn, user.organization_id, result.get('sources', []))): raise ValueError('CONTEXT_REVOKED') code = (result.get('error') or {}).get('code') if result.get('status') == 'error' else None return bool(conn.execute(text('''UPDATE tool_calls SET status=:status,result_json=CAST(:result AS jsonb), error_code=:error,completed_at=now() WHERE id=:id AND live_session_id=:sid AND status='running' AND access_epoch=:epoch RETURNING id'''), dict(id=call_id, sid=session_id, epoch=settings['access_epoch'], status='failed' if code else 'succeeded', result=json.dumps(result), error=code)).first()) def cancel_tools(self, user, session_id, refs=None, code='TOOL_CANCELLED'): with transaction(self.engine) as conn: conn.execute(text('SELECT organization_id FROM organization_settings WHERE organization_id=:org FOR UPDATE'), {'org': user.organization_id}) conn.execute(text('''UPDATE tool_calls SET status='failed',completed_at=now(),error_code=:code WHERE live_session_id=:sid AND organization_id=:org AND status='running' AND (:all OR public_ref=ANY(CAST(:refs AS uuid[])))'''), dict(sid=session_id, org=user.organization_id, code=code, all=refs is None, refs=refs or [])) def reconcile_startup(self): from app.infrastructure.database import LIVE_REVISION with transaction(self.engine) as conn: if conn.execute(text('SELECT version_num FROM alembic_version')).scalar_one() != LIVE_REVISION: raise ValueError('SCHEMA_UNAVAILABLE') conn.execute(text('SELECT organization_id FROM organization_settings ORDER BY organization_id FOR UPDATE')) result = conn.execute(text('''UPDATE live_sessions SET status='failed',closed_at=now(), close_reason='API_RESTARTED',error_code='API_RESTARTED',updated_at=now() WHERE status IN ('creating','connecting','connected')''')) conn.execute(text("UPDATE tool_calls SET status='failed',completed_at=now(),error_code='ABANDONED' WHERE status='running'")) return result.rowcount