Skip to content

fix: bind transaction connection per-task via ContextVar and improve commit error handling - #1

Open
aoright wants to merge 1 commit into
masterfrom
fix/transaction-connection-binding-and-commit-safety
Open

aoright wants to merge 1 commit into
masterfrom
fix/transaction-connection-binding-and-commit-safety

Conversation

@aoright

@aoright aoright commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Summary

This pull request resolves two issues regarding asyncio task handling and error recovery in databases.core.Transaction:

  1. Fixes IndexError on force_rollback of Transaction in tests. encode/databases#570 - Cross-task transaction connection binding via ContextVar:
    Transaction._connection previously called self._connection_callable() on every access. In Database, connection_callable() resolves to different Connection instances across distinct asyncio tasks because Database._connection_map is keyed by asyncio.current_task(). When a transaction is entered in one task and completed/rolled back in another (such as background tasks or asyncio.gather), accessing self._connection in the secondary task resulted in an IndexError or AssertionError because that task's connection had an empty _transaction_stack.

    To resolve this, transactions now bind their connection at start() time using a ContextVar-backed dictionary (_BOUND_CONNECTIONS). Each task context preserves access to the bound connection while maintaining task-local safety.

  2. Fixes Handle errors in transaction.commit() (for sqlite) encode/databases#594 - Safe error handling and rollback on commit failure:
    Previously, Transaction.commit() popped self from self._connection._transaction_stack before executing await 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_stack is popped and the connection exited only after successful commit. If commit() raises an exception, an automatic rollback() attempt is made, followed by guaranteed cleanup of _transaction_stack, the active transaction reference, and the connection lock before re-raising the exception.

  3. Test suite and driver improvements:

    • Added test_transaction_across_tasks to verify cross-task rollback safety.
    • Added test_transaction_commit_error_handling to verify connection lock release and cleanup after commit failures.
    • Fixed SQLite parameter placeholder syntax (? instead of %s or $1) in test_queries_with_expose_backend_connection.
    • Fixed pytest.mark.parametrize deprecation warning when passing combinations of test URLs.
    • Added engine.dispose() to create_test_database test fixture to ensure SQLite file locks are released cleanly.

Test Plan

  • Executed native test suite using SQLite backend:
    TEST_DATABASE_URLS="sqlite:///test.db" .venv/bin/pytest tests/test_databases.py -k "sqlite"
    Result: 55 passed, 3 skipped.
  • Verified dedicated regression tests:
    TEST_DATABASE_URLS="sqlite:///test.db" .venv/bin/pytest tests/test_databases.py -k "test_transaction_across_tasks or test_transaction_commit_error_handling" -v
    Result: 2 passed.

…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Handle errors in transaction.commit() (for sqlite) IndexError on force_rollback of Transaction in tests.

1 participant