Async engine cancellation and timeout controls across the SQLAlchemy 1.4 to 2.0 transition
0 reputation · 10 Sept 2023, 03:30 UTC
0 reputation · 10 Sept 2023, 03:30 UTC
Migrating an async application from SQLAlchemy 1.4 to 2.0 introduces uncertainty around how in-flight database operations respond to cancellation and statement timeouts. The async engine surfaces cancellation through asyncio task cancellation, but SQLAlchemy does not guarantee driver-level query abortion; actual stop behavior remains dialect and DBAPI dependent. Statement timeout controls are available via execution_options and dialect-specific parameters, while engine-level settings such as pool_timeout govern connection acquisition rather than query execution duration.
A further complication arises when cancellation interrupts an active transaction. The database transaction may remain in an indeterminate state, and SQLAlchemy relies on the application to catch cancellation exceptions and explicitly rollback. Whether the underlying connection can be safely returned to the pool or must be discarded depends on driver-specific behavior. Pool settings like pool_pre_ping and pool_recycle affect whether a connection invalidated by client-side cancellation is detected on subsequent checkout.
Which execution_options keys for statement timeouts remain stable across dialects when moving from SQLAlchemy 1.4 to 2.0? What is the required cleanup sequence after an asyncio cancellation to avoid protocol errors on connection reuse? How do pool recovery settings interact with connections left in an unknown state by cancelled async operations?
A thoughtful contribution can make all the difference. Be the first to share one.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.