fix: prevent InFailedSQLTransactionError in session creation

Root cause: embedding generation could break the DB transaction via a failed
SQL statement. The except block caught the Python error but left the transaction
in a failed state. Subsequent queries (_record_usage → subscription lookup)
then failed with InFailedSQLTransactionError.

Fixes:
- session_embedding_service: use begin_nested() savepoint so failures don't
  poison the parent transaction
- ai_sessions.py: add db.rollback() before _record_usage in all 3 error
  handlers (create, respond, pickup) to recover from broken transactions

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-20 04:36:12 +00:00
parent 2ed8a2af15
commit eed771cb27
2 changed files with 74 additions and 61 deletions

View File

@@ -54,44 +54,44 @@ async def generate_session_embedding(session_id: UUID, db: AsyncSession) -> None
embedding_str = "[" + ",".join(str(v) for v in embedding_vector) + "]"
# Check for existing embedding
existing = await db.execute(
select(AISessionEmbedding).where(
AISessionEmbedding.session_id == session_id
# Use a savepoint so failures don't poison the parent transaction
async with db.begin_nested():
# Check for existing embedding
existing = await db.execute(
select(AISessionEmbedding).where(
AISessionEmbedding.session_id == session_id
)
)
)
embed_record = existing.scalar_one_or_none()
embed_record = existing.scalar_one_or_none()
if embed_record:
# Update existing
embed_record.chunk_text = chunk_text
await db.execute(
text(
"UPDATE ai_session_embeddings "
"SET embedding = :emb::vector, updated_at = now() "
"WHERE session_id = :sid"
),
{"emb": embedding_str, "sid": str(session_id)},
)
else:
# Insert new via raw SQL to include vector column
await db.execute(
text("""
INSERT INTO ai_session_embeddings
(id, session_id, account_id, chunk_text, embedding_model, embedding, created_at, updated_at)
VALUES
(gen_random_uuid(), :session_id, :account_id, :chunk_text, :model, :embedding::vector, now(), now())
"""),
{
"session_id": str(session_id),
"account_id": str(session.account_id),
"chunk_text": chunk_text,
"model": "voyage-3.5",
"embedding": embedding_str,
},
)
await db.flush()
if embed_record:
# Update existing
embed_record.chunk_text = chunk_text
await db.execute(
text(
"UPDATE ai_session_embeddings "
"SET embedding = :emb::vector, updated_at = now() "
"WHERE session_id = :sid"
),
{"emb": embedding_str, "sid": str(session_id)},
)
else:
# Insert new via raw SQL to include vector column
await db.execute(
text("""
INSERT INTO ai_session_embeddings
(id, session_id, account_id, chunk_text, embedding_model, embedding, created_at, updated_at)
VALUES
(gen_random_uuid(), :session_id, :account_id, :chunk_text, :model, :embedding::vector, now(), now())
"""),
{
"session_id": str(session_id),
"account_id": str(session.account_id),
"chunk_text": chunk_text,
"model": "voyage-3.5",
"embedding": embedding_str,
},
)
except Exception:
logger.warning(
"Failed to generate embedding for session %s", session_id, exc_info=True