dify icon indicating copy to clipboard operation
dify copied to clipboard

[Refactor/Chore] Pooled DB connections are held across model, vector-store and thread waits in many request paths: name the holders and stop new ones

Open Theysua opened this issue 3 weeks ago • 4 comments

Self Checks

  • [x] I have read the Contributing Guide and Language Policy.
  • [x] This is only for refactors or chores; if you would like to ask a question, please head to Discussions.
  • [x] I have searched for existing issues search for existing issues, including closed ones.
  • [x] I confirm that I am using English to submit this report, otherwise it will be closed.
  • [x] 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :)
  • [x] Please do not modify this template :) and fill in all the required fields.

Description

Several request paths keep a pooled database connection checked out while they wait on something that is not the database: a model, a vector store, another thread, a whole workflow run. Each one works at low concurrency. Once the number of such requests reaches the pool capacity (40 with the defaults), every request in the process waits for SQLALCHEMY_POOL_TIMEOUT and then fails, and the error names the request that could not get a connection, not the ones holding them.

Four instances were found one at a time by load-testing one path after another: #46241, #46253, #46278, #46354. That does not scale, and nothing stops the next one from being added. Two things make the pattern easy to write and hard to see:

  • db.session outside request handlers. It keeps its connection until something ends the transaction, and in worker threads, generators and Celery tasks nothing does. models/engine.py already carries a notice asking new code not to use db outside controllers, but nothing enforces it. On main at 29f044b57 there are 236 uses outside controllers, commands, migrations and tests (core 103, tasks 50, services 48, schedule 15, events 11, extensions 6, others 3).
  • No signal until the pool is empty. A held connection produces no log line, no metric and no failing test. The first symptom is the pool timeout under load.

This issue proposes two small pieces that make the class visible and stop it from growing, and tracks the holders that are still open.

Motivation

1. A monitor that names the holders (opt-in, pull request to follow). It listens to the pool's checkout and check-in events, records the application frame that checked each connection out, and logs two things: a connection that was held longer than a limit, and the holders of every connection at the moment the pool is fully checked out.

Mounted into stock 1.19.0 with a 0.3 s limit and run over thirteen scenarios at 10 concurrent requests (30 requests each, model stand-in answering in 2 s, embedding stand-in in 200 ms), it reported these checkout sites:

Scenario Process Connections held, median Checked out at Known as
Workflow, blocking (three variants) API 30 of 30, 2.3–2.6 s WorkflowService.get_published_workflow ← AppGenerateService._get_workflow #46253
Chat app, streaming and blocking API 30 of 30, 2.1 s Message.app ← TokenBufferMemory.get_history_prompt_messages #46278
Chatflow, streaming worker 30 of 30, 2.1 s same site #46278
Chat app, blocking API 30 of 30, 2.3 s AppService.get_app_by_id ← service_api/wraps.py decorated_view #46241
Chat app with two knowledge bases API 56, 0.4 s DatasetRetrieval._retriever ← _run_retriever_thread #46354
Workflow with two knowledge bases worker 60, 0.8 s same site #46354
POST /v1/datasets/{id}/retrieve API 29 of 30, 0.4 s DatasetService.get_dataset ← hit_testing_base.get_and_validate_dataset; get_active_key_scope ← service_api/wraps.py decorated new, see below
Indexing one document worker 10, 1.2 s CacheEmbedding.embed_documents 1.19.0 only; already fixed on main
Workflow, streaming, 20 nodes worker 7 reports in 30 runs, 1.1–1.2 s node and run persistence writes not waits: the worker was CPU-bound
Workflow with an HTTP or LLM node, streaming — none — —

So one run of a few minutes re-found the four known instances and one that was not known. The retrieval API one is confirmed: with every open fix mounted, 100 concurrent POST /v1/datasets/{id}/retrieve complete 28 of 200 in 62 s, and the monitor's own report at that moment reads:

Database connection pool is fully checked out (40 of 40), 0 earlier reports left out. Holders: 15 x services/knowledge/dataset_service.py:468 in get_dataset, called from controllers/console/datasets/hit_testing_base.py:94 in get_and_validate_dataset (oldest 61.5 s); 13 x repositories/knowledge/dataset_api_key_bindings.py:103 in get_active_key_scope, called from controllers/service_api/wraps.py:407 in decorated (oldest 0.1 s); ...

The request session loads the dataset and stays in its transaction while HitTestingService.retrieve runs, and the retrieval threads need connections of their own. I will open a separate issue and fix for that path.

2. A guard against net-new db.session outside controllers (pull request to follow). Same mechanism as no-new-controller-sqlalchemy: an ast-grep rule over changed lines, existing uses untouched, # guard-ignore: no-new-global-db-session -- <reason> for the cases that need it. It enforces what the notice in models/engine.py asks for and lets the 236 existing uses go down without new ones being added.

Not in these two pull requests, listed so the scope is clear:

  • Removing the existing holders. Open pull requests cover four (#46244, #46254, #46279, #46355). Still open: the retrieval API path above, DatasetRetrieval.single_retrieve, and whatever the monitor reports for paths I have no scenario for (agent apps, external knowledge, plugins and tools).
  • Turning the monitor on by default, and shortening the pool timeout so a missed holder fails one request quickly instead of stalling the process for 30 s. Both are worth doing once the known holders are gone; before that they would only add noise and errors.

Additional Context

  • The monitor costs about 2.4 µs per checkout and check-in pair in a micro-benchmark on a real QueuePool with a shallow stack; it walks the stack to find the application frame, so the cost grows with stack depth. It installs nothing when the setting is 0.
  • A larger pool or a connection pooler in front of PostgreSQL does not remove the problem: a connection that is idle in a transaction is pinned either way. With the pool at 250 per process, 150 concurrent requests exhausted a 200-connection PostgreSQL in an earlier test.
  • Scripts and raw numbers are available if useful.

Theysua avatar Nov 14 '26 07:11 Theysua

The retrieval API path reported by the monitor is filed as #46373, with a fix in #46374 (100 concurrent POST /v1/datasets/{id}/retrieve: 11–29 of 200 completed in 62 s before, 200 of 200 in 4–7 s after).

Theysua avatar Nov 14 '26 07:11 Theysua

Following up on "whatever the monitor reports for paths I have no scenario for": I went through the whole api/ tree by reading (main at 29f044b57) for the same shape — a session that has executed a statement and is still in its transaction when the code waits on a model, a vector store, the plugin daemon, HTTP, object storage or other threads. The pass produced about a hundred sites that reduce to roughly forty distinct holders. Posting the list here so it is not lost; most of it has not been load-tested, so treat severity as unranked unless a row says otherwise.

Legend: measured = the connection-hold monitor (#46371) reported it on a run of stock 1.19.0; read = I re-read the code myself and the session is in a transaction across the wait; pass = reported by the code-reading pass as confirmed, not individually re-read by me; unsure = the pass itself was not sure.

Request paths used by end users

Where the transaction begins What it waits on while held Reached by Status
core/provider_manager.py get_default_model: db.session.scalar, never released whatever the caller does next with the default model (about 20 call sites: titles, audio, suggested questions, QA indexing…) any use of a workspace default model measured: 2.0 s per chat with title generation
core/app/task_pipeline/message_cycle_manager.py _generate_conversation_name_worker: with create_session() around the whole function LLMGenerator.generate_conversation_name (LLM call); commit only after it first message of every conversation with auto-generated names measured: 20 of 20 requests, 2.0 s each
core/app/task_pipeline/easy_ui_based_generate_task_pipeline.py _save_message message_was_created.send(...) inside the save transaction; the handler (events/event_handlers/update_provider_when_message_created.py) opens a second connection and, on cloud, calls billing every chat / agent-chat message. The stopped-agent branch already sends after commit, with a comment saying why read
core/app/features/annotation_reply/annotation_reply.py Vector(..., session=session).search_by_vector (embedding model + vector store) every message of an app with annotation reply enabled read
core/rag/retrieval/dataset_retrieval.py get_metadata_filter_condition on the caller's session the whole retrieval that follows (plus an LLM call in automatic mode) Knowledge Retrieval node, chat/completion apps with a knowledge base, when metadata filtering is not disabled read
dataset_retrieval.py single_retrieve router LLM, then RetrievalService.retrieve N-to-1 retrieval pass
core/tools/utils/dataset_retriever/dataset_retriever_tool.py _run metadata filter, external knowledge HTTP, RetrievalService.retrieve; the agent runner commits only after the tool returns agent-chat apps, every knowledge tool call read
core/tools/tool_manager.py get_api_provider_controller: db.session.scalar, never released the tool invocation that follows custom API tools in workflow Tool nodes, Agent nodes, agent apps read (start); duration unsure
core/moderation/api/api.py _get_config_by_requestor: db.session the extension HTTP call; the output-moderation thread then keeps it for the whole stream apps with API-extension moderation read
core/external_data_tool/api/api.py query: db.session the extension HTTP call (60 s read timeout) apps with API-based external data variables read
services/knowledge/external/service.py fetch_external_knowledge_retrieval(session=...) the customer's external knowledge endpoint four callers: _retriever external branch, single_retrieve, console hit testing for external datasets, the agent dataset tool. prepare_…/execute_… already exist as a split read
core/rag/datasource/retrieval_service.py embedding_search: with Session(db.engine) around Vector(...) and the search embedding model + vector store only when the Vector constructor runs a statement: Qdrant with a collection binding, or an image query pass (conditional)
services/audio_service.py transcript_asr / transcript_agent_asr / transcript_tts the speech model /v1/audio-to-text, /v1/text-to-audio, web and console audio read for ASR; TTS unsure
services/agent_tool_inner_service.py invoke the whole tool call (ToolEngine.generic_invoke and draining its messages) inner API for every agent tool call read
services/knowledge_retrieval_inner_service.py retrieve DatasetRetrieval.knowledge_retrieval(session=session, ...) inner API for every agent knowledge lookup read
controllers/inner_api/plugin/wraps.py get_user_tenant: db.session.get(Tenant, ...) the model call or app run the plugin asked for the eleven non-streaming plugin reverse-invocation endpoints read (start); duration unsure
controllers/mcp/mcp.py + core/mcp/server/streamable_http.py AppGenerateService.generate(streaming=False) tools/call on a workflow app published as an MCP server pass
services/installed_app_generation_adapters.py, services/trial_app_generation_adapters.py the whole blocking run Explore / trial apps in blocking mode pass
services/knowledge/dataset_service.py save_document_with_dataset_id billing, default model lookup, then redis_client.lock(..., timeout=600) with no blocking timeout POST /v1/datasets/{id}/document/create-by-text and by file; requests queued on the same knowledge base each keep a connection measured: 17 of 20 concurrent requests reported, up to 1.7 s

Agent app, pipelines, console

  • Agent app (core/app/apps/agent_app/): the generator has the same shape as #46278 for the new app type; input guards run inside begin(); the runner's scoped session is re-opened right after a commit and then waits on the agent backend stream; workspace binding is allocated over HTTP inside a session (session_store.py). pass, one item unsure.
  • Agent v2 node (core/workflow/nodes/agent_v2/): tool layers are built on db.session, then the agent run starts; same workspace-binding shape. pass.
  • Files inside the handler-session window: file_factory.build_from_mappings (remote HEAD to a user URL) in the chat, completion, agent-chat and advanced-chat generators; BaseAgentRunner.organize_agent_history loads files with the worker session open. pass / unsure.
  • RAG pipeline: PipelineGenerator._generate_worker runs the whole pipeline inside with Session(...); the Celery run tasks and retry_document_indexing_task hold another session across _generate in blocking mode; RagPipelineService datasource runs are generators that reuse a session after its owner closed it; get_rag_pipeline leaves db.session in a transaction. pass.
  • Console: get_app_model leaves a transaction open, so single-node run, trigger-node debug, console audio and instruction-generate wait with it held. pass.
  • OpenAPI: with the default context="orm" the handler runs inside the router session (draft node run, plugin install, enterprise checks); libs/oauth_bearer.py reads through db.session and nothing ends it. pass / unsure.
  • Skills: the assistant stream reuses a session with_session already closed, and nothing closes it again if the plan has no file operation; archive pulls read storage inside a session. pass / unsure.
  • Enterprise RBAC: services/knowledge_fs/capability_broker.py holds a FOR UPDATE row lock across the RBAC HTTP call; four plain holds of the same call. pass.
  • Admin paths: workflow publish (billing and plugin checks inside begin()), MCP tool refresh, credential validation for built-in tools, datasources and load balancing, file-scan test, API tool test. pass / unsure.

Background tasks

  • Add to index (enable_segment_to_index_task, enable_segments_to_index_task, create_segment_to_index_task, add_document_to_index_task): index_processor.load(..., session=session) with the task session already in a transaction, so embedding and the vector write run inside it. measured: enable task 10 of 10, 1.1 s each.
  • Index clean (seven tasks, the three processors' clean, summary vector deletion): vector deletes inside the transaction; for economy knowledge bases the wait includes the 600 s keyword lock. measured for the disable task (up to 1.3 s); the rest pass.
  • Dataset-wide re-index (deal_dataset_vector_index_task, deal_dataset_index_update_task), annotation tasks (batch_import, enable, disable), retry_document_indexing_task. pass.
  • Indexing internals: PDF and Excel image extraction write to storage inside the caller's session; _get_content_files downloads images; Vector.create_multimodal; index() on Qdrant; multimodal rerank; summary preview with vision models. pass, conditional on images or backend.
  • schedule/check_upgradable_plugin_task.py: db.session read, then a marketplace fetch and time.sleep batches for about fifteen minutes, every fifteen minutes. pass.
  • Object storage inside transactions, some with row locks: workflow pause repository, delete_conversation_task, clean_dataset_task, clean_document_task, draft variable cleanup, human-input timeouts, staged upload cleanup, run archiving. pass.
  • Billing or mail inside a session: start of the indexing tasks (cloud), mail_human_input_delivery_task, mail_clean_document_notify_task, clean_unused_datasets_task, delete_account_task, telemetry. pass.

What the pass found clean

Workflow and advanced-chat workers (they close before the run), chat and completion runners (commit and close before the model call), agent runners around each model and tool call, CacheEmbedding, full-text search, summary generation, the web passport decorator, suggested questions / more-like-this / conversation rename, trigger and webhook entry, file endpoints, the main document indexing task.

Limits of the pass

graphon is not in this repository and was not read. Controllers: entry decorators fully read, end-user slow paths about 90%, console about 40%. Services: all files machine-scanned, about half read at function level. Vector backends: only Qdrant, Weaviate and TiDB-on-Qdrant were opened.

Given the size of the list I do not think fixing these one pull request at a time is the way; the guard in #46372 and a shorter path to "one way to get a session" matter more. If it helps, I can start with the ones that sit on every request: get_default_model, the title worker, the message_was_created send, and annotation reply.

Theysua avatar Nov 14 '26 08:11 Theysua

Four of the per-request holders from the inventory above now have pull requests. Each was confirmed with the monitor (#46371) on 1.19.0 before the change and re-run after it:

Holder Pull request 100 concurrent, 200 requests: before → after
ProviderManager.get_default_model reads through db.session and the caller then invokes the model #46380 measured together with #46381
Conversation title worker keeps its session across the title model call #46381 41–60 of 200 in 77–134 s, about 300 pool timeouts per round → 200 of 200 in 16–19 s, none
message_was_created sent inside the save transaction #46382 not measurable on a self-hosted deployment; same shape
Annotation reply searches the index on the caller's session #46383 105–159 of 200 in 44–101 s, 85–224 pool timeouts per round → 200 of 200 in 14–15 s, none

One thing the monitor caught that reading the code did not: the first version of #46383 opened the vector index inside its short session, and at 100 concurrent that step alone still held the connection for 0.5 s, because opening the index connects to the vector store. The version in the pull request resolves only the vector type inside the session.

Theysua avatar Nov 14 '26 09:11 Theysua

Update on the four per-request holders listed above: the default-model lookup is fixed on main by #45806, so #46380 is closed. #46381, #46382 and #46383 are still open.

Theysua avatar Nov 15 '26 03:11 Theysua