Skip to content

v2.5.0 Change Details

Theme: synchronous forced cleanup and Pool reference retention fixes (memory analysis report hazards ⅔). Adds Engine.terminate() and the Engine.__del__ safety net; Result.pool is cleared after close and retyped to Optional[Pool]. Fix plan: arch/asmysql_隐患2_3修复_9cc26c6b.md; analysis report: repo root asmysql_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:

def terminate(self) -> None
  • 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_connected is False and execute() raises ConnectionError; you can connect() again to reuse the Engine;
  • A late Result.close() is safe: it goes through the _terminated branch 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, with finally clearing self.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.pool after 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_timeout default None unchanged;
  • 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 add terminate()/__del__; Result pool/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, _free cleanup 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 root asmysql_v2_隐患2_3修复实测报告.md.