Repository navigation
Description
Environment
- RAGFlow: v0.26.4 and v0.27.2 (both verified; see below)
- peewee 3.19.0 / playhouse.pool, MySQL 8.0.39, single-container deployment (Linux, docker-compose)
- Production deployment: ~10k parsed documents, nightly + around-the-clock parse windows, multi-user retrieval load
Symptom
The API server logs a MySQL disconnect every ~30 seconds, around the clock:
WARNING Database connection issue (attempt 1/5): (0, '')
(0, '') is pymysql's InterfaceError(0, '') — raised when the socket is already gone. On our busiest deployment: 3,788 warnings per 24h (~one every 23s). Under retrieval load bursts, many threads hold connections >30s simultaneously → mass kill + reconnect storm serialized on the pool lock → requests queue behind slow reconnects → health endpoint hangs >10s and user requests time out until the burst passes. It self-heals when traffic drops, which makes it look intermittent.
Verified this is NOT the MySQL server: wait_timeout=28800, mysqld error log shows zero aborted-connection entries (a client-side clean close doesn't count as aborted), and 300/300 disconnect events originate from the API process only — task executors never log it.
Root cause
-
@app.teardown_request _db_close(api/apps/init.py) →close_connection()(api/db/db_models.py) →DB.close_stale(age=30)on every request. -
playhouse.pool.PooledDatabase.close_staleis documented as "Close any connections that are in-use but were checked out quite some time ago" — i.e. a leak guard, keyed onPoolConnection.checked_out, which is stamped at checkout time and never refreshed while the connection is in use (pool.py_connect:self._in_use[key] = PoolConnection(ts, conn, time.time())). Soage=30closes the socket of ANY connection held >30s — even one actively querying right now. It is being used as if it were an idle-reaper, which it is not. -
RAGFlow threads never check connections in (the teardown hook never calls
DB.close()), so every worker thread's connection sits in_in_useforever;BaseDataBase.__init__sets neitherstale_timeoutnormax_connections(pool defaults: cap 20, stale_timeout None) →close_staleis the only reclaim path, and it fires on live connections. Each kill produces exactly theInterfaceError(0,'')above, theRetryingPooledMySQLDatabasewrapper reconnects, and the new lease expires 30s later — hence the ~30s cycle.Typical victim: the retrieval pipeline holds a connection across an embedding call (
LLMBundle.encode_queries, 25s+) plus a vector search before the next DB read — always >30s.
Verified in v0.27.2
v0.27.2 added a proper per-thread check-in for GaussDB (DB.close() in close_connection), but the non-GaussDB branch still runs DB.close_stale(age=30) — the bug is unchanged for MySQL/Postgres/OceanBase.
Our production fix (running since 2026-11-21: 100+/h warnings → ~0)
Since the reclaim contract (lock, _in_use dict rebuild) belongs to upstream close_stale, we kept it and made the lease renewable:
-
Refresh the lease after every successful query — in
RetryingPooledMySQLDatabase.execute_sql, on success:conn = self._state.conn # caller's connection (thread-local) pc = self._in_use.get(self.conn_key(conn)) # conn_key = id if pc is not None: self._in_use[self.conn_key(conn)] = pc._replace(checked_out=time.time())
Active threads renew continuously → never killed; dead threads' connections stop renewing and get reaped by the unchanged upstream
close_stalepath (its dict rebuild is the correct eviction mechanism). Value replacement doesn't change the key set, so there is no structural race with a concurrentclose_staleiteration. -
Raise the pool cap:
max_connections=128inBaseDataBase.__init__pool_config (default is 20, and_in_useonly grows since nothing checks in). Sized as "new-thread checkout rate × window": we measured ≈0.11 new DB-touching threads/s (300s processlist sampling) → ~37 live entries in a 300s window. -
env knobs for the age (default 300s) and cap, plus a kill switch that restores the exact original behavior.
Since deploying: disconnect warnings 0 (from 100+/h), health endpoint back to milliseconds, MySQL connection count stable at single digits.
Suggested upstream fixes
- (a) Per-request check-in for all backends, as the GaussDB branch already does:
DB.close()in the teardown hook returns the caller-thread connection to the pool, then idle reclaim belongs tostale_timeout(set it inBaseDataBase; default poolstale_timeout=Nonemakes it a no-op today) — and dropclose_stale(age=30). Caveat to verify: connection state scoping for async handlers (thread-local vs task-local) so a long request isn't checked in mid-flight by a concurrent teardown. - (b) Or make
close_stalelease-based: refreshchecked_outon every successful query (our approach) so "checked out long ago" actually means "idle". - (c) At minimum, stop using a 30s age for the non-GaussDB branch — it kills every connection held longer than 30s regardless of activity.
We're happy to open a PR — we'd like to align on the preferred direction (a/b/c) first, since (a) is the cleanest but touches request lifecycle semantics.
Footnote
Request failed: <empty> ERROR lines in the same log come from the same teardown hook logging empty-string exceptions (SSE client disconnects) — benign, but easy to mistake for a symptom when triaging this.
Activity
mercant1982 commentedon Nov 21, 2026
I reproduced the cross-thread pool behavior with Peewee 3.19.0 and real SQLite connections under a controlled clock. The fixture executes
close_connection()from RAGFlow v0.27.2, with one thread retaining a connection and another running teardown at age 31 seconds:ProgrammingError: Cannot operate on a closed database.DB.close(): the first thread's next query succeeds.Runnable fixture and output, using
python replay_teardown.py /path/to/ragflow-v0.27.2/api/db/db_models.py.This supports the checked-out-connection diagnosis independently of MySQL, but does not qualify Quart's async request scoping or a complete RAGFlow deployment. Refreshing a lease after successful queries also needs care around a single query or external operation that lasts longer than the lease.
There is a version boundary to settle before a patch: current main at
91c702e86be3dcb3cabc9f6d81e485d02241bef8uses the Go backend, and the two Python files involved here are absent. The project's current guide directs new backend work to Go.Is a fix for the Python release branch wanted here? If so, I can offer the two-thread fixture to check the chosen cleanup behavior, keeping the async connection-ownership check explicit.
wangbo0924 commentedon Nov 21, 2026
Thanks for the independent reproduction — the two-thread fixture is exactly the kind of evidence this needed, and confirming it on SQLite rules out any MySQL-specific explanation. Great catch on the version boundary too; answering your question directly:
Yes — a fix for the Python release branch is wanted. v0.27.2 is the latest Python release, the fix there is an asymmetric patch (the GaussDB branch already returns the caller thread's connection via
DB.close(), while MySQL/Postgres/OceanBase still runDB.close_stale(age=30)), and there are substantial production deployments still on the Python backend — ours parses ~10k documents with around-the-clock parse windows, where this bug produced ~3,800 disconnect warnings/day and periodic API stalls before we patched it.On direction: we recommend (a) — make the teardown hook return the caller thread's connection for all backends, i.e. the
DB.close()form your fixture validated and that the GaussDB branch already uses, plus settingstale_timeoutinBaseDataBase.__init__so idle reclaim has a proper mechanism once connections actually get checked in. That is cleaner than lease-refreshing (the approach we shipped in production, chosen because we couldn't quickly validate the connection-ownership semantics under Quart's async handling — which is precisely the check you flagged as needing to stay explicit, and precisely what your fixture can now cover).Two things worth keeping explicit in the fix:
thread_safe=Truepeewee uses_ConnectionLocal(thread-local state), soDB.close()in the teardown thread returns only that thread's connection — for sync handlers this is the requesting thread's connection, which is correct. The open question is whether any handler runs DB work on a worker thread while the teardown runs on another one (Quartensure_async/to_threadpaths). Your fixture's explicit connection-ownership check is the right tool for that.stale_timeout/checked_out) can still reap a connection mid-flight if a single query outlasts the window. With per-request check-in under (a),stale_timeoutshould be set generously (it only fires on genuinely idle checked-in connections), but the PR should state this edge explicitly.Please do open the PR against the release branch — happy to review it, and we can share production validation from our deployment once it lands (we have the monitoring in place: per-hour disconnect-warning counts and health-endpoint latency histograms that were 100+/h and 10s+ hangs before our patch, ~0 and milliseconds after).
mercant1982 commentedon Nov 21, 2026
Thanks — I found the Python target branch,
0.27.xat27847b3b9424, and checked the ownership question with real Quart 0.20.0 and Peewee 3.19.0, using the branch's dependency pins and the unchangedclose_connection()helper.There is an additional boundary to fix before treating
DB.close()as per-request check-in. Quart sends each synchronous teardown throughensure_asyncindependently; it does not guarantee the handler's worker thread:Five-request fixture, exact dependencies and output. The different-worker case is forced deterministically; this qualifies a permitted scheduling interleaving, not its production frequency. No MySQL/full-application claim.
I agree with removing teardown's global reap. The release fix also needs owner-bound cleanup for synchronous DB work and the async event-loop path; changing only the teardown to
async defleaves the worker case uncovered. Peewee'sstale_timeoutis evaluated at pool checkout/check-in, not by a background query-cancellation timer.Would you agree to keep these ownership cases as acceptance tests for the release-branch fix before opening a PR that claims request-level cleanup?