Repository navigation
Conversation
…commit error handling Fix two bugs in the Transaction class: 1. Connection binding across asyncio tasks (fixes encode#570): Transaction._connection property calls connection_callable() each time, which resolves to different Connection objects in different asyncio tasks (via Database._connection_map keyed by asyncio.Task). This causes an IndexError when a transaction started in one task is committed/rolled back in another, because the transaction_stack on the new connection is empty. Solution: Bind the connection at start() time using a ContextVar-backed property (_BOUND_CONNECTIONS), so each task context gets its own bound connection even when sharing the same Transaction object (as happens with the @database.transaction() decorator pattern with asyncio.gather). 2. Commit error handling (fixes encode#594): Transaction.commit() previously popped from _transaction_stack BEFORE calling the backend commit(). If commit() raised an exception, the transaction was lost from the stack but the database connection remained locked in a broken transaction state. Solution: Only pop from _transaction_stack AFTER successful commit. On failure, attempt rollback first, then clean up the stack and connection. Additional test fixes: - Fix SQLite placeholder syntax in test_queries_with_expose_backend_connection - Fix pytest.mark.parametrize deprecation warning (generator -> list) - Add engine.dispose() in create_test_database fixture to prevent SQLite file lock issues - Add test_transaction_across_tasks to verify cross-task transaction safety - Add test_transaction_commit_error_handling to verify commit failure recovery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This pull request resolves two issues regarding asyncio task handling and error recovery in
databases.core.Transaction:Fixes
IndexErroron force_rollback of Transaction in tests. encode/databases#570 - Cross-task transaction connection binding via ContextVar:Transaction._connectionpreviously calledself._connection_callable()on every access. InDatabase,connection_callable()resolves to differentConnectioninstances across distinct asyncio tasks becauseDatabase._connection_mapis keyed byasyncio.current_task(). When a transaction is entered in one task and completed/rolled back in another (such as background tasks orasyncio.gather), accessingself._connectionin the secondary task resulted in anIndexErrororAssertionErrorbecause that task's connection had an empty_transaction_stack.To resolve this, transactions now bind their connection at
start()time using aContextVar-backed dictionary (_BOUND_CONNECTIONS). Each task context preserves access to the bound connection while maintaining task-local safety.Fixes Handle errors in transaction.commit() (for sqlite) encode/databases#594 - Safe error handling and rollback on commit failure:
Previously,
Transaction.commit()poppedselffromself._connection._transaction_stackbefore executingawait self._transaction.commit(). If the backend commit failed (such as on serialization error, connection drop, or deferred constraint violation), the transaction was prematurely removed from the stack, but the connection remained locked in an active transaction state without rollback.The commit process is now wrapped in error-handling logic:
_transaction_stackis popped and the connection exited only after successful commit. Ifcommit()raises an exception, an automaticrollback()attempt is made, followed by guaranteed cleanup of_transaction_stack, the active transaction reference, and the connection lock before re-raising the exception.Test suite and driver improvements:
test_transaction_across_tasksto verify cross-task rollback safety.test_transaction_commit_error_handlingto verify connection lock release and cleanup after commit failures.?instead of%sor$1) intest_queries_with_expose_backend_connection.pytest.mark.parametrizedeprecation warning when passing combinations of test URLs.engine.dispose()tocreate_test_databasetest fixture to ensure SQLite file locks are released cleanly.Test Plan
TEST_DATABASE_URLS="sqlite:///test.db" .venv/bin/pytest tests/test_databases.py -k "sqlite"Result: 55 passed, 3 skipped.
TEST_DATABASE_URLS="sqlite:///test.db" .venv/bin/pytest tests/test_databases.py -k "test_transaction_across_tasks or test_transaction_commit_error_handling" -vResult: 2 passed.