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.errorsilent 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) toautocommit=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 (theIN_TRANSflag) 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 AUTOCOMMIThandshake, the library internally falls back to the server default (autocommit=None) and emits aRuntimeWarning, 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
ResourceWarningand forciblyterminates all in-use connections, guaranteed to converge; in-flight queries receiveerror_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=Trueare 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.errorand the connection discarded, never returned with an open transaction. - GC address reuse in
id(conn)-basedinit_sqltracking: replaced with aWeakSettracking connections by object identity; new connections always re-executeinit_sql. - Session loss from silent
ping()reconnects:ping()removed fromclose()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_sqlfailure: discarded on failure;init_sqlnow 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;CancelledErroris re-raised (it does not enterresult.error); cancellation while queued in acquire is safely retryable, a Result cancelled after acquire is abandoned entirely.__anext__no longer swallows cancellation intoStopAsyncIteration. - No retry after non-MySQLError: the unconditional
finallysetting of__executedis 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 ... INSERTis invalid syntax in MySQL 8 (CTE INSERT must be trailing).
Documentation¶
transaction.mdauto-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_sqldemoted to an optional alternative;disconnect_timeoutandinit_sqlconstraints documented.result.mdadds commit and connection release semantics;faq.mdadds Q&A on streaming write commits, cross-statement transactions, cancellation semantics, and disconnect waiting.examples.md,api.md,index.mdupdated accordingly; READMEawait engine.execute(...)examples changed toasync 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) andtest_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.envlocal credential configuration (gitignore-protected, auto-loaded at runtime, never overrides existing environment variables).