Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
fix: also cleanup on asyncio cancel (#6586)
Sarah Woodersb23722e4a130
diff --git a/letta/server/db.py b/letta/server/db.pyindex 89677ff8c..622f8514d 100644--- a/letta/server/db.py+++ b/letta/server/db.py@@ -1,3 +1,4 @@+import asyncioimport uuidfrom contextlib import asynccontextmanagerfrom typing import AsyncGenerator@@ -63,11 +64,22 @@ class DatabaseRegistry:@asynccontextmanagerasync def async_session(self) -> AsyncGenerator[AsyncSession, None]:- """Get an async database session."""+ """Get an async database session.++ Note: We explicitly handle asyncio.CancelledError separately because it's+ a BaseException (not Exception) in Python 3.8+. Without this, cancelled+ tasks would skip rollback() and return connections to the pool with+ uncommitted transactions, causing "idle in transaction" connection leaks.+ """async with async_session_factory() as session:try:yield sessionawait session.commit()+ except asyncio.CancelledError:+ # Task was cancelled (client disconnect, timeout, explicit cancellation)+ # Must rollback to avoid returning connection with open transaction+ await session.rollback()+ raiseexcept Exception:await session.rollback()raise