AstrBot icon indicating copy to clipboard operation
AstrBot copied to clipboard

[Bug] 高并发下 SQLAlchemy 提示 QueuePool limit reached

Open muyni233 opened this issue 8 months ago • 2 comments

What happened / 发生了什么

在高并发的情况下,Bot 有时输出类似以下的报错: Error occurred while processing agent request: <Queue at 0x7c31010 maxsize=5 _getters[8] tasks=3502> is bound to a different event loop (同 https://github.com/AstrBotDevs/AstrBot/issues/5464 ) 在更新到 Astrbot v4.19.4 后发现 SQLAlchemy 的连接池问题(见下方 Log)依然会使此报错复现

Reproduce / 如何复现?

  1. 部署 Astrbot
  2. 在 Astrbot 配置多个(4个) OneBot 实例并同时启用
  3. 将这些 Bot 加入到多个群聊(高并发)
  4. 与 Bot 对话时,有时会输出报错

AstrBot version, deployment method (e.g., Windows Docker Desktop deployment), provider used, and messaging platform used. / AstrBot 版本、部署方式(如 Windows Docker Desktop 部署)、使用的提供商、使用的消息平台适配器

Astrbot v4.19.4 OneBot 适配器,通过 NapCat 连接 Python 3.13.10 Windows Server 2025 Standard | 版本号 24H2 | 版本26100.4061 通过源码部署,venv 安装依赖

OS

Windows

Logs / 报错日志

[23:04:41.994] [Core] [ERRO] [asyncio.base_events:1879]: Task exception was never retrieved
future: <Task finished name='Task-178399' coro=<PipelineScheduler.execute() done, defined at E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84
\astrbot\core\pipeline\scheduler.py:78> exception=TimeoutError('QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30.00')>
Traceback (most recent call last):

File "E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\main.py", line 141, in <module>
asyncio.run(main_async(args.webui_dir))
│       │   │          │    └ None
│       │   │          └ Namespace(webui_dir=None)
│       │   └ <function main_async at 0x0000000008338F40>
│       └ <function run at 0x00000000038AED40>
└ <module 'asyncio' from 'C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\asyncio\init.py'>

File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\asyncio\runners.py", line 195, in run
return runner.run(main)
│      │   └ <coroutine object main_async at 0x000000006733AC00>
│      └ <function Runner.run at 0x0000000003964AE0>
└ <asyncio.runners.Runner object at 0x00000000684E86E0>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
│    │     │                  └ <Task pending name='Task-1' coro=<main_async() running at E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba02
3344...
│    │     └ <function BaseEventLoop.run_until_complete at 0x0000000003962660>
│    └ <ProactorEventLoop running=True closed=False debug=False>
└ <asyncio.runners.Runner object at 0x00000000684E86E0>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 712, in run_until_complete
self.run_forever()
│    └ <function BaseEventLoop.run_forever at 0x00000000039625C0>
└ <ProactorEventLoop running=True closed=False debug=False>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 683, in run_forever
self._run_once()
│    └ <function BaseEventLoop._run_once at 0x0000000003964400>
└ <ProactorEventLoop running=True closed=False debug=False>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 2035, in _run_once
handle = self._ready.popleft()
│    │      └ <method 'popleft' of 'collections.deque' objects>
│    └ deque([<Handle _ProactorBaseWritePipeTransport._loop_writing()>, <Handle _ProactorReadPipeTransport._loop_reading()>, <Handle...
└ <ProactorEventLoop running=True closed=False debug=False>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\asyncio\events.py", line 105, in _run
self = None  # Needed to break cycles when an exception occurs.

File "E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\astrbot\core\pipeline\scheduler.py", line 87, in execute
await self._process_stages(event)
│    │               └ <astrbot.core.platform.sources.aiocqhttp.aiocqhttp_message_event.AiocqhttpMessageEvent object at 0x00000001545E6970>
│    └ <function PipelineScheduler._process_stages at 0x0000000067372DE0>
└ <astrbot.core.pipeline.scheduler.PipelineScheduler object at 0x000000007973C690>

File "E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\astrbot\core\pipeline\scheduler.py", line 72, in _process_stages
await coroutine
└ <coroutine object WakingCheckStage.process at 0x000000007D785170>

File "E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\astrbot\core\pipeline\waking_check\stage.py", line 228, in process
activated_handlers = await SessionPluginManager.filter_handlers_by_session(
│                    └ <staticmethod(<function SessionPluginManager.filter_handlers_by_session at 0x000000006D536660>)>
└ <class 'astrbot.core.star.session_plugin_manager.SessionPluginManager'>

File "E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\astrbot\core\star\session_plugin_manager.py", line 68, in filter_handlers_by_session
session_plugin_config = await sp.get_async(
│  └ <function SharedPreferences.get_async at 0x00000000079B84A0>
└ <astrbot.core.utils.shared_preferences.SharedPreferences object at 0x0000000007C2AA50>

File "E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\astrbot\core\utils\shared_preferences.py", line 51, in get_async
result = await self.db_helper.get_preference(scope, scope_id, key)
│    │         │              │      │         └ 'session_plugin_config'
│    │         │              │      └ 'twilight:GroupMessage:878076014'
│    │         │              └ 'umo'
│    │         └ <function SQLiteDatabase.get_preference at 0x000000000798EA20>
│    └ SQLiteDatabase()
└ <astrbot.core.utils.shared_preferences.SharedPreferences object at 0x0000000007C2AA50>

File "E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\astrbot\core\db\sqlite.py", line 1002, in get_preference
result = await session.execute(query)
│       │       └ <sqlmodel.sql._expression_select_cls.SelectOfScalar object at 0x000000007EAD6720>
│       └ <function AsyncSession.execute at 0x0000000007227C40>
└ <sqlalchemy.ext.asyncio.session.AsyncSession object at 0x0000000158F7D730>

File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\ext\asyncio\session.py", line 449, in execute
result = await greenlet_spawn(
└ <function greenlet_spawn at 0x00000000058DA480>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\util_concurrency_py3k.py", line 201, in greenlet_spawn
result = context.throw(*sys.exc_info())
│       │      │   └ <built-in function exc_info>
│       │      └ <module 'sys' (built-in)>
│       └ <method 'throw' of 'greenlet.greenlet' objects>
└ <_AsyncIoGreenlet object at 0x00000000011E6680 (otid=0x00000000057AE490) dead>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\orm\session.py", line 2351, in execute
return self._execute_internal(
│    └ <function Session._execute_internal at 0x0000000007169800>
└ <sqlalchemy.orm.session.Session object at 0x0000000001024230>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\orm\session.py", line 2239, in _execute_internal
conn = self._connection_for_bind(bind)
│    │                    └ Engine(sqlite+aiosqlite:///E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\data\data_v4.db)
│    └ <function Session._connection_for_bind at 0x0000000007169580>
└ <sqlalchemy.orm.session.Session object at 0x0000000001024230>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\orm\session.py", line 2108, in _connection_for_bind
return trans._connection_for_bind(engine, execution_options)
│     │                    │       └ None
│     │                    └ Engine(sqlite+aiosqlite:///E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\data\data_v4.db)
│     └ <function SessionTransaction._connection_for_bind at 0x0000000007168040>
└ <sqlalchemy.orm.session.SessionTransaction object at 0x00000000011E7CD0>
File "<string>", line 2, in _connection_for_bind
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\orm\state_changes.py", line 137, in _go
ret_value = fn(self, *arg, **kw)
│  │      │      └ {}
│  │      └ (Engine(sqlite+aiosqlite:///E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\data\data_v4.db), None)
│  └ <sqlalchemy.orm.session.SessionTransaction object at 0x00000000011E7CD0>
└ <function SessionTransaction._connection_for_bind at 0x0000000007157E20>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\orm\session.py", line 1187, in _connection_for_bind
conn = bind.connect()
│    └ <function Engine.connect at 0x0000000006D9BD80>
└ Engine(sqlite+aiosqlite:///E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\data\data_v4.db)
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\engine\base.py", line 3277, in connect
return self._connection_cls(self)
│    │               └ Engine(sqlite+aiosqlite:///E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\data\data_v4.db)
│    └ <class 'sqlalchemy.engine.base.Connection'>
└ Engine(sqlite+aiosqlite:///E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\data\data_v4.db)
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\engine\base.py", line 143, in init
self._dbapi_connection = engine.raw_connection()
│                        │      └ <function Engine.raw_connection at 0x0000000006D9BE20>
│                        └ Engine(sqlite+aiosqlite:///E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\data\data_v4.db)
└ <sqlalchemy.engine.base.Connection object at 0x00000001545CC890>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\engine\base.py", line 3301, in raw_connection
return self.pool.connect()
│    │    └ <function Pool.connect at 0x000000000693DD00>
│    └ <sqlalchemy.pool.impl.AsyncAdaptedQueuePool object at 0x0000000007C2A510>
└ Engine(sqlite+aiosqlite:///E:\mcsmanager\daemon\data\InstanceData\9e89d7df54b54675ae63ba0233446c84\data\data_v4.db)
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\pool\base.py", line 447, in connect
return _ConnectionFairy._checkout(self)
│                │         └ <sqlalchemy.pool.impl.AsyncAdaptedQueuePool object at 0x0000000007C2A510>
│                └ <classmethod(<function _ConnectionFairy._checkout at 0x000000000693FE20>)>
└ <class 'sqlalchemy.pool.base._ConnectionFairy'>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\pool\base.py", line 1264, in _checkout
fairy = _ConnectionRecord.checkout(pool)
│                 │        └ <sqlalchemy.pool.impl.AsyncAdaptedQueuePool object at 0x0000000007C2A510>
│                 └ <classmethod(<function _ConnectionRecord.checkout at 0x000000000693E980>)>
└ <class 'sqlalchemy.pool.base._ConnectionRecord'>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\pool\base.py", line 711, in checkout
rec = pool._do_get()
│    └ <function QueuePool._do_get at 0x0000000006951C60>
└ <sqlalchemy.pool.impl.AsyncAdaptedQueuePool object at 0x0000000007C2A510>
File "C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy\pool\impl.py", line 166, in _do_get
raise exc.TimeoutError(
│   └ <class 'sqlalchemy.exc.TimeoutError'>
└ <module 'sqlalchemy.exc' from 'C:\Users\Server\AppData\Local\Programs\Python\Python313\Lib\site-packages\sqlalchemy...

sqlalchemy.exc.TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30.00 (Background on this error at: (Background on this error at: https://sqlalche.me/e/20/3o7r)

Are you willing to submit a PR? / 你愿意提交 PR 吗?

  • [ ] Yes!

Code of Conduct

muyni233 avatar Mar 09 '26 15:03 muyni233

我们之后会接入 pg, mysql 这类性能更好的数据库

Soulter @.***

Soulter avatar Mar 09 '26 16:03 Soulter

补充:v4.26.8 单进程环境仍可稳定复现,已定位到 SharedPreferences 跨事件循环共用 AsyncEngine

我在 AstrBot v4.26.8 上遇到了相同问题,并完成了稳定复现和运行验证。

环境

  • AstrBot: v4.26.8
  • Python: 3.12.13
  • SQLAlchemy: 2.0.49
  • aiosqlite: 0.22.1
  • Database: SQLite
  • Deployment: Linux host, uv run python main.py

已经确认:

  • 只运行一个 AstrBot Python 主进程。
  • WebUI 6185 只由该进程监听。
  • 完整停止旧进程并重新启动后仍会出现。
  • 不依赖多个 OneBot/AstrBot 实例。
  • 使用临时 SQLite 数据库即可稳定复现,不需要生产数据库、Provider 或消息适配器。

实际调用链

PreProcessStage.process()
→ ctx.get_using_stt_provider()
→ ProviderManager.get_using_provider()
→ SharedPreferences.get()
→ SharedPreferences.get_async()
→ SQLiteDatabase.get_preference()
→ AsyncSession.execute()
→ AsyncAdaptedQueuePool
→ asyncio.Queue
→ RuntimeError: Queue is bound to a different event loop

根因

  1. AstrBot 在模块初始化阶段创建全局 SQLiteDatabase / AsyncEngine。
  2. main.py 使用 asyncio.run() 创建 AstrBot 主事件循环。
  3. SharedPreferences.__init__() 又创建独立的 _sync_loop 和后台线程。
  4. 同步方法 SharedPreferences.get() 使用 asyncio.run_coroutine_threadsafe(..., self._sync_loop).result() 执行数据库查询。
  5. AstrBot 的其他异步任务同时在主事件循环上使用同一个 AsyncEngine。
  6. 默认 AsyncAdaptedQueuePool 内部使用 asyncio.Queue。发生连接池等待后, Queue 会绑定到首先等待它的事件循环。
  7. 另一个事件循环再次访问同一连接池时便会抛出:
RuntimeError: <Queue ... maxsize=5 ...> is bound to a different event loop

这和多个 AstrBot/OneBot 实例无关,是单进程内两个 event loop 共用同一个 SQLAlchemy AsyncEngine 导致的。

SQLAlchemy 文档也明确说明:使用默认连接池的 AsyncEngine 不应跨 event loop 共享;如果必须跨 loop 使用,应在切换前 dispose,或者使用 NullPool:

https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html#using-multiple-asyncio-event-loops

稳定复现方法

使用临时 SQLite 数据库:

  1. 创建 SQLiteDatabase 和 SharedPreferences。
  2. 在主循环初始化数据库并写入一条 preference。
  3. 在主循环占用默认连接池的 15 个连接: pool_size=5 + max_overflow=10。
  4. 发起第 16 个连接请求,使连接池 Queue 在主循环发生等待。
  5. 从工作线程调用 SharedPreferences.get()。
  6. 该方法会在 _sync_loop 上执行查询,稳定触发跨 loop 异常。

核心复现代码:

held_connections = [
    await db.engine.connect()
    for _ in range(15)
]

waiter = asyncio.create_task(db.engine.connect())
await asyncio.sleep(0.05)

await asyncio.to_thread(
    prefs.get,
    "provider_perf_stt",
    None,
    "umo",
    "loop-repro",
)

复现输出:

main_loop_id=<main-loop>
sync_loop_id=<shared-preferences-loop>
pool_class=AsyncAdaptedQueuePool
pool_queue_bound_to_main=True
secondary_loop_query_error=RuntimeError:
<Queue ... maxsize=5 ...> is bound to a different event loop

已验证的最小兼容修复方向

我在 v4.26.8 上验证了以下方案:

  • 仅对 SQLite AsyncEngine 使用 NullPool,避免异步连接池 Queue 跨 loop 复用。
  • 保留现有 SharedPreferences.get() 同步兼容接口。
  • 使用按 event loop 隔离的 asyncio.Semaphore 限制 SQLite 并发会话数。
  • 因 NullPool 每次建立连接,将连接级 SQLite PRAGMA 放入 SQLAlchemy connect 事件中。
  • 不修改数据库 schema、数据库内容、用户配置、Provider 配置或插件数据。
  • 不新增 asyncio.run()、无限重试或异常吞噬。

验证结果

  • Python syntax check passed.
  • Ruff format/check passed.
  • 60 existing related tests passed.
  • Stable cross-event-loop regression test passed.
  • SQLite concurrency-limit and timeout test passed.
  • AstrBot restarted successfully with one Python process.
  • WebUI port 6185 returned HTTP 200.
  • 857 real incoming message events were processed after restart.
  • is bound to a different event loop: 0 occurrences.
  • Pipeline failures: 0 occurrences.
  • SQLite inode, table count and key row counts remained unchanged.

PR #4968 described essentially the same root cause, but it was closed without commits or merged changes. PR #5774 fixed other event-loop issues but did not change SharedPreferences._sync_loop or the database pool, so the database path is still present in v4.26.8 and current master.

I am willing to submit a backward-compatible PR with the regression test if this fix direction is acceptable.

jmt059 avatar Jul 30 '26 04:07 jmt059