Skip to content

Commit ff92b55

Browse files
Fix: /file2document/convert blocks event loop on large folders causing 504 timeout (#13784)
Problem The /file2document/convert endpoint ran all file lookups, document deletions, and insertions synchronously inside the request cycle. Linking a large folder (~1.7GB with many files) caused 504 Gateway Timeout because the blocking DB loop held the HTTP connection open for too long. Fix - Extracted the heavy DB work into a plain sync function _convert_files - Inputs are validated and folder file IDs expanded upfront (fast path) - The blocking work is dispatched to a thread pool via get_running_loop().run_in_executor() and the endpoint returns 200 immediately - Frontend only checks data.code === 0 so the response change (file2documents list → True) has no impact Fixes #13781 --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent e705ac6 commit ff92b55

File tree

6 files changed

+99
-103
lines changed

6 files changed

+99
-103
lines changed

api/apps/file2document_app.py

Lines changed: 75 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
# limitations under the License
1515
#
1616

17+
import asyncio
18+
import logging
1719
from pathlib import Path
1820

1921
from api.db.services.file2document_service import File2DocumentService
@@ -28,73 +30,92 @@
2830
from api.db.services.document_service import DocumentService
2931

3032

33+
def _convert_files(file_ids, kb_ids, user_id):
34+
"""Synchronous worker: delete old docs and insert new ones for the given file/kb pairs."""
35+
for id in file_ids:
36+
informs = File2DocumentService.get_by_file_id(id)
37+
for inform in informs:
38+
doc_id = inform.document_id
39+
e, doc = DocumentService.get_by_id(doc_id)
40+
if not e:
41+
continue
42+
tenant_id = DocumentService.get_tenant_id(doc_id)
43+
if not tenant_id:
44+
logging.warning("tenant_id not found for doc_id=%s, skipping remove_document", doc_id)
45+
continue
46+
DocumentService.remove_document(doc, tenant_id)
47+
File2DocumentService.delete_by_file_id(id)
48+
49+
e, file = FileService.get_by_id(id)
50+
if not e:
51+
continue
52+
53+
for kb_id in kb_ids:
54+
e, kb = KnowledgebaseService.get_by_id(kb_id)
55+
if not e:
56+
continue
57+
doc = DocumentService.insert({
58+
"id": get_uuid(),
59+
"kb_id": kb.id,
60+
"parser_id": FileService.get_parser(file.type, file.name, kb.parser_id),
61+
"pipeline_id": kb.pipeline_id,
62+
"parser_config": kb.parser_config,
63+
"created_by": user_id,
64+
"type": file.type,
65+
"name": file.name,
66+
"suffix": Path(file.name).suffix.lstrip("."),
67+
"location": file.location,
68+
"size": file.size
69+
})
70+
File2DocumentService.insert({
71+
"id": get_uuid(),
72+
"file_id": id,
73+
"document_id": doc.id,
74+
})
75+
76+
3177
@manager.route('/convert', methods=['POST']) # noqa: F821
3278
@login_required
3379
@validate_request("file_ids", "kb_ids")
3480
async def convert():
3581
req = await get_request_json()
3682
kb_ids = req["kb_ids"]
3783
file_ids = req["file_ids"]
38-
file2documents = []
3984

4085
try:
4186
files = FileService.get_by_ids(file_ids)
42-
files_set = dict({file.id: file for file in files})
87+
files_set = {file.id: file for file in files}
88+
89+
# Validate all files exist before starting any work
4390
for file_id in file_ids:
44-
file = files_set[file_id]
45-
if not file:
91+
if not files_set.get(file_id):
4692
return get_data_error_result(message="File not found!")
47-
file_ids_list = [file_id]
93+
94+
# Validate all kb_ids exist before scheduling background work
95+
for kb_id in kb_ids:
96+
e, _ = KnowledgebaseService.get_by_id(kb_id)
97+
if not e:
98+
return get_data_error_result(message="Can't find this dataset!")
99+
100+
# Expand folders to their innermost file IDs
101+
all_file_ids = []
102+
for file_id in file_ids:
103+
file = files_set[file_id]
48104
if file.type == FileType.FOLDER.value:
49-
file_ids_list = FileService.get_all_innermost_file_ids(file_id, [])
50-
for id in file_ids_list:
51-
informs = File2DocumentService.get_by_file_id(id)
52-
# delete
53-
for inform in informs:
54-
doc_id = inform.document_id
55-
e, doc = DocumentService.get_by_id(doc_id)
56-
if not e:
57-
return get_data_error_result(message="Document not found!")
58-
tenant_id = DocumentService.get_tenant_id(doc_id)
59-
if not tenant_id:
60-
return get_data_error_result(message="Tenant not found!")
61-
if not DocumentService.remove_document(doc, tenant_id):
62-
return get_data_error_result(
63-
message="Database error (Document removal)!")
64-
File2DocumentService.delete_by_file_id(id)
65-
66-
# insert
67-
for kb_id in kb_ids:
68-
e, kb = KnowledgebaseService.get_by_id(kb_id)
69-
if not e:
70-
return get_data_error_result(
71-
message="Can't find this dataset!")
72-
e, file = FileService.get_by_id(id)
73-
if not e:
74-
return get_data_error_result(
75-
message="Can't find this file!")
76-
77-
doc = DocumentService.insert({
78-
"id": get_uuid(),
79-
"kb_id": kb.id,
80-
"parser_id": FileService.get_parser(file.type, file.name, kb.parser_id),
81-
"pipeline_id": kb.pipeline_id,
82-
"parser_config": kb.parser_config,
83-
"created_by": current_user.id,
84-
"type": file.type,
85-
"name": file.name,
86-
"suffix": Path(file.name).suffix.lstrip("."),
87-
"location": file.location,
88-
"size": file.size
89-
})
90-
file2document = File2DocumentService.insert({
91-
"id": get_uuid(),
92-
"file_id": id,
93-
"document_id": doc.id,
94-
})
95-
96-
file2documents.append(file2document.to_json())
97-
return get_json_result(data=file2documents)
105+
all_file_ids.extend(FileService.get_all_innermost_file_ids(file_id, []))
106+
else:
107+
all_file_ids.append(file_id)
108+
109+
user_id = current_user.id
110+
# Run the blocking DB work in a thread so the event loop is not blocked.
111+
# For large folders this prevents 504 Gateway Timeout by returning as
112+
# soon as the background task is scheduled.
113+
loop = asyncio.get_running_loop()
114+
future = loop.run_in_executor(None, _convert_files, all_file_ids, kb_ids, user_id)
115+
future.add_done_callback(
116+
lambda f: logging.error("_convert_files failed: %s", f.exception()) if f.exception() else None
117+
)
118+
return get_json_result(data=True)
98119
except Exception as e:
99120
return server_error_response(e)
100121

api/utils/tenant_utils.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,23 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515
#
16+
from common.constants import LLMType
1617
from api.db.services.tenant_llm_service import TenantLLMService
1718

19+
_KEY_TO_MODEL_TYPE = {
20+
"llm_id": LLMType.CHAT,
21+
"embd_id": LLMType.EMBEDDING,
22+
"asr_id": LLMType.SPEECH2TEXT,
23+
"img2txt_id": LLMType.IMAGE2TEXT,
24+
"rerank_id": LLMType.RERANK,
25+
"tts_id": LLMType.TTS,
26+
}
27+
1828
def ensure_tenant_model_id_for_params(tenant_id: str, param_dict: dict) -> dict:
1929
for key in ["llm_id", "embd_id", "asr_id", "img2txt_id", "rerank_id", "tts_id"]:
2030
if param_dict.get(key) and not param_dict.get(f"tenant_{key}"):
21-
tenant_model = TenantLLMService.get_api_key(tenant_id, param_dict[key])
31+
model_type = _KEY_TO_MODEL_TYPE.get(key)
32+
tenant_model = TenantLLMService.get_api_key(tenant_id, param_dict[key], model_type)
2233
if tenant_model:
2334
param_dict.update({f"tenant_{key}": tenant_model.id})
2435
else:

test/testcases/test_web_api/test_dialog_app/test_dialog_routes_unit.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ def split_model_name_and_factory(embd_id):
151151
return embd_id.split("@")
152152

153153
@staticmethod
154-
def get_api_key(tenant_id, model_name):
154+
def get_api_key(tenant_id, model_name, model_type=None):
155155
return _MockTableObject(
156156
id=1,
157157
tenant_id=tenant_id,

test/testcases/test_web_api/test_file_app/test_file2document_routes_unit.py

Lines changed: 9 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -244,69 +244,33 @@ def test_convert_branch_matrix_unit(monkeypatch):
244244
req_state = {"kb_ids": ["kb-1"], "file_ids": ["f1"]}
245245
_set_request_json(monkeypatch, module, req_state)
246246

247-
events = {"deleted": []}
248-
247+
# Falsy file → "File not found!" (synchronous validation)
249248
monkeypatch.setattr(module.FileService, "get_by_ids", lambda _ids: [_FalsyFile("f1", module.FileType.DOC.value)])
250249
res = _run(module.convert())
251250
assert res["message"] == "File not found!"
252251

252+
# Valid file but invalid kb → "Can't find this dataset!" (synchronous validation)
253+
# KnowledgebaseService stub returns (False, None) by default
253254
monkeypatch.setattr(module.FileService, "get_by_ids", lambda _ids: [_DummyFile("f1", module.FileType.DOC.value)])
254-
monkeypatch.setattr(module.File2DocumentService, "get_by_file_id", lambda _file_id: [SimpleNamespace(document_id="doc-1")])
255-
monkeypatch.setattr(module.DocumentService, "get_by_id", lambda _doc_id: (False, None))
256-
res = _run(module.convert())
257-
assert res["message"] == "Document not found!"
258-
259-
monkeypatch.setattr(module.DocumentService, "get_by_id", lambda _doc_id: (True, SimpleNamespace(id=_doc_id)))
260-
monkeypatch.setattr(module.DocumentService, "get_tenant_id", lambda _doc_id: None)
261-
res = _run(module.convert())
262-
assert res["message"] == "Tenant not found!"
263-
264-
monkeypatch.setattr(module.DocumentService, "get_tenant_id", lambda _doc_id: "tenant-1")
265-
monkeypatch.setattr(module.DocumentService, "remove_document", lambda *_args, **_kwargs: False)
266-
res = _run(module.convert())
267-
assert "Document removal" in res["message"]
268-
269-
monkeypatch.setattr(module.DocumentService, "remove_document", lambda *_args, **_kwargs: True)
270-
monkeypatch.setattr(module.File2DocumentService, "get_by_file_id", lambda _file_id: [])
271-
monkeypatch.setattr(module.File2DocumentService, "delete_by_file_id", lambda file_id: events["deleted"].append(file_id))
272-
monkeypatch.setattr(module.KnowledgebaseService, "get_by_id", lambda _kb_id: (False, None))
273255
res = _run(module.convert())
274256
assert res["message"] == "Can't find this dataset!"
275-
assert events["deleted"] == ["f1"]
276257

258+
# Valid file and kb → schedules background work, returns data=True immediately
277259
kb = SimpleNamespace(id="kb-1", parser_id="naive", pipeline_id="p1", parser_config={})
278260
monkeypatch.setattr(module.KnowledgebaseService, "get_by_id", lambda _kb_id: (True, kb))
279-
monkeypatch.setattr(module.FileService, "get_by_id", lambda _file_id: (False, None))
280261
res = _run(module.convert())
281-
assert res["message"] == "Can't find this file!"
262+
assert res["code"] == 0
263+
assert res["data"] is True
282264

265+
# Folder expansion → schedules background work, returns data=True immediately
283266
req_state["file_ids"] = ["folder-1"]
284267
monkeypatch.setattr(module.FileService, "get_by_ids", lambda _ids: [_DummyFile("folder-1", module.FileType.FOLDER.value, name="folder")])
285268
monkeypatch.setattr(module.FileService, "get_all_innermost_file_ids", lambda _file_id, _acc: ["inner-1"])
286-
monkeypatch.setattr(
287-
module.FileService,
288-
"get_by_id",
289-
lambda _file_id: (True, _DummyFile("inner-1", module.FileType.DOC.value, name="inner.txt", location="inner.loc", size=2)),
290-
)
291-
inserted = {}
292-
293-
def _insert(payload):
294-
inserted.update(payload)
295-
return SimpleNamespace(id="doc-new")
296-
297-
monkeypatch.setattr(module.DocumentService, "insert", _insert)
298-
monkeypatch.setattr(module.FileService, "get_parser", lambda _ft, _name, _parser_id: "picked-parser")
299-
monkeypatch.setattr(
300-
module.File2DocumentService,
301-
"insert",
302-
lambda _payload: SimpleNamespace(to_json=lambda: {"file_id": "inner-1", "document_id": "doc-new"}),
303-
)
304269
res = _run(module.convert())
305270
assert res["code"] == 0
306-
assert res["data"] == [{"file_id": "inner-1", "document_id": "doc-new"}]
307-
assert inserted["parser_id"] == "picked-parser"
308-
assert inserted["pipeline_id"] == "p1"
271+
assert res["data"] is True
309272

273+
# Exception in file lookup → 500
310274
req_state["file_ids"] = ["f1"]
311275
monkeypatch.setattr(
312276
module.FileService,

test/testcases/test_web_api/test_user_app/test_user_app_unit.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ def insert_many(_payload):
230230
return True
231231

232232
@staticmethod
233-
def get_api_key(tenant_id, model_name):
233+
def get_api_key(tenant_id, model_name, model_type=None):
234234
return _MockTableObject(
235235
id=1,
236236
tenant_id=tenant_id,

web/src/components/shared-badge.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,5 @@ export function SharedBadge({ children }: PropsWithChildren) {
88
return null;
99
}
1010

11-
return <span className="bg-bg-card rounded-sm px-1 text-xs">{children}</span>;
11+
return <span className="bg-bg-card rounded-sm px-1 text-xs inline-block max-w-[120px] truncate align-middle">{children}</span>;
1212
}

0 commit comments

Comments
 (0)