8000 MySQL connections killed every ~30s: teardown hook's close_stale(age=30) closes in-use connections (PoolConnection.checked_out never refreshed) · Issue #22618 · infiniflow/ragflow · GitHub
[go: up one dir, main page]

Skip to content

MySQL connections killed every ~30s: teardown hook's close_stale(age=30) closes in-use connections (PoolConnection.checked_out never refreshed) #22618

Open

Description

@wangbo0924

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

  1. @app.teardown_request _db_close (api/apps/init.py) → close_connection() (api/db/db_models.py) → DB.close_stale(age=30) on every request.

  2. playhouse.pool.PooledDatabase.close_stale is documented as "Close any connections that are in-use but were checked out quite some time ago" — i.e. a leak guard, keyed on PoolConnection.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())). So age=30 closes 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.

  3. RAGFlow threads never check connections in (the teardown hook never calls DB.close()), so every worker thread's connection sits in _in_use forever; BaseDataBase.__init__ sets neither stale_timeout nor max_connections (pool defaults: cap 20, stale_timeout None) → close_stale is the only reclaim path, and it fires on live connections. Each kill produces exactly the InterfaceError(0,'') above, the RetryingPooledMySQLDatabase wrapper 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:

  1. 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_stale path (its dict rebuild is the correct eviction mechanism). Value replacement doesn't change the key set, so there is no structural race with a concurrent close_stale iteration.

  2. Raise the pool cap: max_connections=128 in BaseDataBase.__init__ pool_config (default is 20, and _in_use only 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.

  3. 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 to stale_timeout (set it in BaseDataBase; default pool stale_timeout=None makes it a no-op today) — and drop close_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_stale lease-based: refresh checked_out on 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

  1. mercant1982 commented on Nov 21, 2026

    @mercant1982

    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:

    • Current non-GaussDB teardown: the first thread's next query fails with ProgrammingError: Cannot operate on a closed database.
    • Returning only the teardown thread's connection with 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 91c702e86be3dcb3cabc9f6d81e485d02241bef8 uses 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.

  2. wangbo0924 commented on Nov 21, 2026

    @wangbo0924
    Author

    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 run DB.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 setting stale_timeout in BaseDataBase.__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:

    1. Ownership scoping: with thread_safe=True peewee uses _ConnectionLocal (thread-local state), so DB.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 (Quart ensure_async/to_thread paths). Your fixture's explicit connection-ownership check is the right tool for that.
    2. Long single queries: any fix where reclaim is keyed on a timestamp (lease refresh or 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_timeout should 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).

  3. mercant1982 commented on Nov 21, 2026

    @mercant1982

    Thanks — I found the Python target branch, 0.27.x at 27847b3b9424, and checked the ownership question with real Quart 0.20.0 and Peewee 3.19.0, using the branch's dependency pins and the unchanged close_connection() helper.

    There is an additional boundary to fix before treating DB.close() as per-request check-in. Quart sends each synchronous teardown through ensure_async independently; it does not guarantee the handler's worker thread:

    Case Result
    Current global reap, another worker's connection aged 31 s Owner's next query fails: closed database
    Per-thread close, sync handler and teardown on different workers Query survives, but the original connection remains checked out
    Per-thread close, async handler and sync teardown Event-loop connection remains checked out
    Cleanup explicitly on each owning execution boundary Both sync and async controls return their connections

    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 def leaves the worker case uncovered. Peewee's stale_timeout is 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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0