postgres-mcp-server: 启动自检时,将连接的 aiorwlock 绑定到一个临时事件循环,导致第一个真正的查询崩溃(问题 #2505 项 #4)
作者: modosc创建于 2026年7月30日更新于 2026年9月29日
标签stale
summary main()'s startup self-test runs run_query('SELECT 1') inside asyncio.run(), then mcp.run() serves real requests on a separate loop. aiorwlock.RWLock binds lazily to whichever loop first acquires it, so the self-test's connection stays bound to that throwaway loop. every first real run_query/get_table_schema call after a successful startup crashes with: <aiorwlock._RWLockCore object at ...> is bound to a different event loop this is item 4 of #2505, bundled with four unrelated issues. filing separately since it has its own root cause and fix, and #2504's proposed fix has a correctness problem worth its own thread. ## where this lives (current main, f984f58f) server.py:1206-1233 (DummyCtx at line 88): Python if db_connection: ctx = DummyCtx() response = asyncio.run( run_query('SELECT 1', ctx, ConnectionMethod[args.connection_method], cluster_identifier, args.db_endpoint, args.database) ) ... logger.info('Postgres MCP server started') mcp.run() asyncio.run() runs the self-test to completion and tears the loop down. mcp.run() then serves on a different loop. the connection survives in db_connection_map, but its aiorwlock.RWLock doesn't. every cluster, every time, on 1.1.7 and current main. ## why #2504 leaks a connection #2504's fix (discard the self-test's connection, auto-reconnect lazily in run_query's cache-miss path) is the obvious first attempt, and what i tried too. - close() acquires the same dead-loop-bound rwlock, raises the same RuntimeError, swallowed by a broad except. does nothing. - that leaves clear() (drop the reference, don't close). but psycopg_pool.AsyncConnectionPool's idle-reaper task (ShrinkPool) is scheduled on the self-test's loop and dies with it. nothing ever closes the underlying connection. verified against a live Aurora cluster: with this fix, every server start leaves one orphaned idle backend (query = COMMIT, state_change matching startup time), one found idle 17.5 hours later. against a role with a small CONNECTION LIMIT (typical for IAM-auth users), repeated restarts exhaust it from orphans alone, independent of actual query load. ## proposed fix: run the self-test in the same loop mcp.run() serves on mcp.run() is just anyio.run(self.run_stdio_async) for stdio. run_stdio_async is already a public coroutine, so nothing requires the self-test and the serving loop to be separate asyncio.run() calls: Python async def _run_server(): if args.db_type: cluster_identifier = args.db_cluster_arn.split(':')[-1] db_connection, llm_response = internal_create_connection( region=args.region, database_type=DatabaseType[args.db_type], connection_method=ConnectionMethod[args.connection_method], cluster_identifier=cluster_identifier, db_endpoint=args.db_endpoint, port=args.port, database=args.database, ) if
内容来源: awslabs/mcp