v2.5.0 Change Details¶
Theme: synchronous forced cleanup and Pool reference retention fixes (memory analysis report hazards ⅔). Adds
Engine.terminate()and theEngine.__del__safety net;Result.poolis cleared after close and retyped toOptional[Pool]. Fix plan:arch/asmysql_隐患2_3修复_9cc26c6b.md; analysis report: repo rootasmysql_v2_final_memory_analysis.md.
New Features¶
1. Engine.terminate(): synchronous forced cleanup¶
Engine previously only had the async disconnect(); synchronous shutdown scenarios (atexit, hooks without an event loop) could not clean up the pool. New synchronous method:
- Synchronous and forceful, no waiting for returns: immediately closes all in-use connections (aiomysql
Pool.terminate(), recorded in_terminated) and severs in-flight queries; - Best-effort cleanup of idle connections: relies on the aiomysql private attribute
_free(deque), fetched defensively via getattr with a type check; degrades to terminate-only when missing or changed in shape; when the event loop is already closed, per-connection close exceptions are isolated and never propagate; - Idempotent; a no-op when called before connect; explicit calls emit no warning; does not acquire the internal connect lock (synchronous method, no await);
- After the call,
is_connectedisFalseandexecute()raisesConnectionError; you canconnect()again to reuse the Engine; - A late
Result.close()is safe: it goes through the_terminatedbranch of aiomysql release.
Contrast with disconnect(): terminate = synchronous and forceful, no waiting for returns; disconnect = async graceful wait (see disconnect_timeout). Typical usage:
import atexit
engine = Engine(url="mysql://root:pass@127.0.0.1:3306/")
atexit.register(engine.terminate) # synchronous hook, no event loop required
2. Engine.del safety net¶
If an Engine is garbage-collected without being disconnect()ed, it automatically emits a ResourceWarning and calls terminate() for synchronous cleanup:
- Before: cleanup of abandoned Engines relied on
Connection.__del__(warning noise, delayed cyclic GC, RuntimeError when the loop is already closed); - After: Engine-level fallback with synchronous convergence; GC is silent after
disconnect()/terminate()or when never connected; construction failures and module-global invalidation during interpreter shutdown are all caught; never awaits and never resurrects references (PEP 442, an Engine with a live pool is still collectable).
Production code should still explicitly await engine.disconnect(); the safety net is only a fallback.
Behavior Changes¶
1. Result.pool cleared after close (hazard 3)¶
Result.pool is retyped from Final[Pool] to Optional[Pool]:
close()is wrapped entirely in try/finally, withfinallyclearingself.pool; covers all paths (early return when cursor is None, conn is None, close_failed, CancelledError re-raise); all connection-return bookkeeping happens before the clearing and is unaffected;- The automatic release branch for statements without result sets (DDL/DML) likewise clears
self.poolafter returning the connection; - Before: cached closed/completed Results pinned the event loop via
Result → Pool → Pool._loop; after: caching closed Results no longer pins the Pool and the event loop, and the Pool can be reclaimed immediately.
2. Executing after close now raises explicitly¶
Executing (__call__) an unexecuted Result after close() raises RuntimeError("Result 已关闭,不能再次执行") (previously silently executable). Only this edge usage is affected; re-entering async with on an already executed Result still takes the __executed early-return no-op, behavior unchanged.
Scope Boundaries¶
- Hazard 1 untouched (
Result.__del__does not return connections; handled separately); disconnect_timeoutdefaultNoneunchanged;- AsMysql constructor singleton and v1 untouched.
Documentation¶
connection.md: new "Synchronous Forced Cleanup: terminate()" section (semantics contrast, atexit example,__del__safety net, best-effort boundary when the loop is closed);result.md: "Commit and Connection Release Semantics" extended with pool reference clearing and the execute-after-close error;api.md: Engine methods addterminate()/__del__; Resultpool/close()descriptions updated;faq.md: new Q&A "How to clean up an Engine in synchronous shutdown scenarios".
Testing¶
- Mock:
TestEngineTerminate(terminate semantics/idempotency/no-op,_freecleanup and exception isolation, four__del__states, Engine with live pool collectable);TestResultPoolRetention(pool cleared after close/DDL, execute-after-close error, re-entry no-op, empty fetch returns, weakref assertion that cached Results do not pin the Pool, finally effective on the CancelledError path, double close). - Integration:
test_terminate_with_open_result(terminate while holding an unclosed Result: immediate return, execute raises, late close safe, reconnect reuse; real MySQL). - Real-MySQL program-level probe:
tests/v2/probe_terminate_and_pool_release.py(severing in-flight queries, server-side connection count dropping to zero for_free,__del__fallback, real Pool reclamation, best-effort after loop close); probe report at repo rootasmysql_v2_隐患2_3修复实测报告.md.