Skip to content

v2.3.0 Change Details

Theme: write commit reliability fixes. Fixes multiple silent data-loss paths in v2 ("no exception, but data not persisted"), while keeping the result.error silent contract unchanged. Design document: asmysql_v2_commit_reliability_design.md; probe and test reports at repo root: asmysql_v2_commit_reliability_probe_report.md, asmysql_v2_commit_reliability_test_report.md.

Breaking Changes

1. Auto-Commit Mechanism Rework: Server Autocommit + Transaction-State Fallback

  • The pool changes from autocommit=False (hardcoded) to autocommit=True (built-in library behavior, no new configuration parameters); normal statements are auto-committed by the server.
  • The SQL first-keyword whitelist (_WRITE_KEYWORDS / _should_commit()) is removed; SQL text is no longer parsed to distinguish reads from writes. The server transaction state (the IN_TRANS flag) is the single source of truth.
  • Unified rule: successful statements with an open transaction are COMMITted, failed statements are ROLLBACKed (the failure check includes a supplementary check for disabled autocommit).
  • If a backend rejects the SET AUTOCOMMIT handshake, the library internally falls back to the server default (autocommit=None) and emits a RuntimeWarning, transparent to callers.

Behavior change comparison:

Scenario Before After
stream=True + INSERT/UPDATE/DELETE Not committed, rolled back on connection return (silent data loss) Committed, persisted normally
WITH ... UPDATE/DELETE, writes starting with # comments, OPTIMIZE/DO, etc. Missed by the whitelist, not committed Committed according to server transaction state
Regular INSERT (non-stream) Client-side COMMIT Server auto-commit, no duplicate client COMMIT
Connection return after SELECT Transaction residue, connection closed by aiomysql Returned after the transaction ends, connections truly reused
Failed statements Possible transaction residue ROLLBACK, partial writes never committed
Manual BEGIN / START TRANSACTION Unclear behavior Committed immediately after execution (v2 does not support cross-statement transactions)

2. Connection Handling on Commit/Rollback Failure

Connections whose COMMIT/ROLLBACK, cursor close, or init_sql failed are always discarded (closed, then pool bookkeeping only) and never reused from the pool; errors are written to result.error without raising exceptions.

New Features

1. disconnect_timeout Configuration (Default None, Backward Compatible)

Engine adds disconnect_timeout: Optional[float] = None (class attribute default, constructor parameter, and URL query parameter all supported; none in URL means None):

  • None (default): waits forever for all connections to return, fully consistent with legacy behavior;
  • Finite value: after the graceful wait times out, emits a ResourceWarning and forcibly terminates all in-use connections, guaranteed to converge; in-flight queries receive error_no=2013;
  • <= 0: no wait, terminate immediately;
  • If disconnect itself is cancelled, it also terminates and re-raises; the cancellation path always converges.

2. Explicit Warning for execute_many([])

An empty parameter list no longer silently executes nothing: no connection is acquired, no SQL is sent, a UserWarning is emitted, row_count=0, last_rowid=None.

Bug Fixes

  • Silent loss of streaming writes: write statements with stream=True are now committed correctly (immediately without result sets, deferred to cursor close with result sets).
  • Keyword whitelist misses: WITH, comment-prefixed, OPTIMIZE/ANALYZE/DO, etc. are no longer missed.
  • Swallowed COMMIT failures: commit failures are written to result.error and the connection discarded, never returned with an open transaction.
  • GC address reuse in id(conn)-based init_sql tracking: replaced with a WeakSet tracking connections by object identity; new connections always re-execute init_sql.
  • Session loss from silent ping() reconnects: ping() removed from close() and execution paths (transaction end is what actually releases locks; ping cannot do this and rebuilds TCP).
  • Protocol pollution from closing unread streaming cursors: cursor close failure discards the connection; no COMMIT is attempted.
  • Half-initialized connections returned after init_sql failure: discarded on failure; init_sql now runs on an independent buffered cursor, avoiding Commands out of sync on streaming cursors.
  • Connection leaks on CancelledError: on cancellation the connection is discarded synchronously and the slot reclaimed; CancelledError is re-raised (it does not enter result.error); cancellation while queued in acquire is safely retryable, a Result cancelled after acquire is abandoned entirely. __anext__ no longer swallows cancellation into StopAsyncIteration.
  • No retry after non-MySQLError: the unconditional finally setting of __executed is removed; non-MySQLError exceptions during acquire no longer block retrying the same Result.
  • disconnect() infinite wait: optional finite-timeout terminate fallback added (see New Features 1); default behavior unchanged.

Semantic Boundaries (Please Note)

  • Cancellation ≠ rollback: cancellation only interrupts the client-side wait; under autocommit=1, writes already completed by the server are committed and persisted.
  • No cross-statement transactions: each execute() commits independently.
  • Non-transactional backends such as ClickHouse never set the transaction-state flag: zero COMMIT on success paths; failure paths send one harmless ROLLBACK that is accepted (verified on 26.5.1).
  • BOM-prefixed statements are rejected by the MySQL 8 server (1064) — a visible error, not silent loss; leading WITH ... INSERT is invalid syntax in MySQL 8 (CTE INSERT must be trailing).

Documentation

  • transaction.md auto-commit mechanism rewritten (keyword whitelist table removed); failure rollback, streaming commit timing, and no cross-statement transactions added.
  • connection.md: ClickHouse examples switched to the query-level SETTINGS clause (async_insert=1, wait_for_async_insert=1), init_sql demoted to an optional alternative; disconnect_timeout and init_sql constraints documented.
  • result.md adds commit and connection release semantics; faq.md adds Q&A on streaming write commits, cross-statement transactions, cancellation semantics, and disconnect waiting.
  • examples.md, api.md, index.md updated accordingly; README await engine.execute(...) examples changed to async with (Result.__await__ remains unimplemented, deferred to a separate release).

Testing

  • Mock: full M1-M33 matrix of commit state machine / cancellation / terminate (test_mock_result.py, test_mock_engine.py, test_mock_engine_init_sql.py, test_mock_bugfixes.py); legacy whitelist test class removed.
  • Integration: new test_integration_commit.py (24 MySQL commit/cancel/terminate cases) and test_integration_clickhouse.py (16 ClickHouse full-feature cases); full suite 339 passed (Mock 209 + MySQL 114 + ClickHouse 16).
  • Live probes: MySQL 8.0.31 and ClickHouse 26.5.1.882 dual-backend verification of the autocommit handshake, IN_TRANS, COMMIT/ROLLBACK, query-level SETTINGS, and execute_many compatibility.
  • Independent mycli persistence checks: regular writes / streaming writes / CTE writes / ClickHouse async inserts all confirmed persisted.
  • Test infrastructure: .autopytest.env local credential configuration (gitignore-protected, auto-loaded at runtime, never overrides existing environment variables).