Repository navigation
Refactor: migrate document run api - #14351
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughDocument execution moved from the legacy app Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant REST_API as REST API\n(/documents/ingest)
participant Auth as Auth/Access
participant DB as Document DB
participant TaskSvc as TaskService
participant DocSvc as DocumentService
participant Index as External Index
Client->>REST_API: POST /documents/ingest {doc_ids, run, delete?, apply_kb?}
REST_API->>Auth: validate tenant & access
REST_API->>DB: fetch documents by doc_ids
alt run == CANCEL
REST_API->>TaskSvc: query tasks for doc
TaskSvc-->>REST_API: tasks state
REST_API->>TaskSvc: cancel tasks (if eligible)
else run == RUNNING
REST_API->>DB: update doc.run/progress (clear counters if rerun/delete)
alt apply_kb
REST_API->>DB: copy parser config from KB to doc
end
REST_API->>DocSvc: DocumentService.run(doc_id, kb_table_map)
end
alt delete requested
REST_API->>TaskSvc: delete task records for doc
REST_API->>Index: delete document from index
end
REST_API-->>Client: {code:0, data:...} / error
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
admin/client/ragflow_client.py (1)
1327-1335:⚠️ Potential issue | 🔴 CriticalClient endpoint migration looks correct, but resolves to the wrong backend route.
The URL and
use_api_base=Truechanges in bothparse_dataset_docs(line 1328) andparse_dataset(line 1354) correctly point at/api/v1/documents/ingest. However, the backend handler inapi/apps/restful_apis/document_api.pyis currently registered at/run, so these calls will 404 until the backend route is fixed (see the blocker on that file). Flagging here so this PR does not ship with a working client but a broken server.Also applies to: 1353-1355
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@admin/client/ragflow_client.py` around lines 1327 - 1335, The client is calling the wrong backend route: in parse_dataset_docs and parse_dataset the POST path uses "/documents/ingest" with use_api_base=True but the server handler is registered at "/documents/run" (under the API base), causing 404s; update the POST path in those functions (parse_dataset_docs and parse_dataset in ragflow_client.py) to "/documents/run" (keeping use_api_base=True and auth_kind="web") so the client targets the registered backend route, or alternatively coordinate with the backend change if you prefer to rename the server handler.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1053-1055: The code reassigns tenant_id from
DocumentService.get_tenant_id(id) which shadows the caller user_id added by
add_tenant_id_to_kwargs and passed into _run_sync(user_id, req); rename the
local variable to doc_tenant_id (used where you currently call
search.index_name(tenant_id) and DocumentService.run(tenant_id,...)) to make
owner vs caller explicit and avoid confusion with
DocumentService.accessible(doc_id, user_id), and stop returning early with
get_data_error_result(message="Tenant not found!") inside the multi-doc
loop—instead collect per-doc failures (e.g., accumulate errors for each id) and
continue processing so previously-processed docs aren’t silently discarded, then
return a combined result summarizing successes and per-doc errors.
- Around line 1040-1088: _req validation and safe multi-doc processing in
_run_sync: validate that req contains a list-like "doc_ids", a present "run"
that can be cast to string, and boolean-ish "delete"/"apply_kb" before any
mutation, returning a 400 on invalid input; normalize and deduplicate doc IDs
into a single list and iterate that once (rename local variable id -> doc_id
everywhere in _run_sync to avoid builtin shadowing); pre-validate all docs
(accessible, tenant exists, DocumentService.get_by_id succeeds) before applying
mutations or alternatively collect per-doc results/errors and apply changes
per-doc while returning a structured success/error map so partial commits are
visible; add structured logging calls around DocumentService.update_by_id,
TaskService.filter_delete, docStore delete, DocumentService.run and on
exceptions to record doc_id and error context.
- Around line 1033-1038: The run handler is incorrectly calling
thread_pool_exec(_run_sync(tenant_id, req)) which invokes _run_sync on the event
loop and then passes its return value to thread_pool_exec; change it to offload
the callable and args to the thread pool like await thread_pool_exec(_run_sync,
tenant_id, req) (or thread_pool_exec with the named function and its args) so
_run_sync runs in the worker thread rather than blocking the event loop, and
preserve the existing try/except returning server_error_response(e). While
fixing, add logging calls in run to log entry (including tenant_id and request
summary), per-document actions inside _run_sync (log each doc id/action), and
the final status before returning so you can trace progress; locate and update
the run function and _run_sync function references accordingly.
- Line 1030: The route decorator on the document ingest handler is registered as
`@manager.route`("/run", methods=["POST"]) which causes the endpoint to be mounted
at /api/v1/run; update the decorator in restful_apis/document_api.py to register
the handler at "/documents/ingest" (i.e. `@manager.route`("/documents/ingest",
methods=["POST"])) so it matches clients and tests that call POST
/api/v1/documents/ingest; keep the same function name and method list so only
the route string changes.
---
Outside diff comments:
In `@admin/client/ragflow_client.py`:
- Around line 1327-1335: The client is calling the wrong backend route: in
parse_dataset_docs and parse_dataset the POST path uses "/documents/ingest" with
use_api_base=True but the server handler is registered at "/documents/run"
(under the API base), causing 404s; update the POST path in those functions
(parse_dataset_docs and parse_dataset in ragflow_client.py) to "/documents/run"
(keeping use_api_base=True and auth_kind="web") so the client targets the
registered backend route, or alternatively coordinate with the backend change if
you prefer to rename the server handler.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 7db105dd-45bb-4abe-9d4f-4e53251a1e02
📒 Files selected for processing (8)
admin/client/ragflow_client.pyapi/apps/document_app.pyapi/apps/restful_apis/document_api.pysdk/python/test/test_frontend_api/common.pytest/testcases/test_web_api/test_common.pyweb/src/hooks/use-document-request.tsweb/src/services/knowledge-service.tsweb/src/utils/api.ts
💤 Files with no reviewable changes (1)
- api/apps/document_app.py
| tenant_id = DocumentService.get_tenant_id(id) | ||
| if not tenant_id: | ||
| return get_data_error_result(message="Tenant not found!") |
There was a problem hiding this comment.
Reassigning tenant_id shadows the document-owner tenant vs. caller user_id and silently exits with only partial work done.
Two issues here:
- The outer parameter bound via
add_tenant_id_to_kwargsis passed asuser_idto_run_sync(user_id, req)(line 1040), and then on line 1053 a new localtenant_idis assigned fromDocumentService.get_tenant_id(id). That local is then used forsearch.index_name(tenant_id)on line 1073 and passed toDocumentService.run(tenant_id, ...)on line 1086. SinceDocumentService.accessible(doc_id, user_id)already ran on line 1042, the owner and the caller can differ (shared-tenant membership). Confirm this is intentional; if yes, rename the local todoc_tenant_idto make the distinction explicit. get_data_error_result(message="Tenant not found!")on line 1055 returns early from the middle of a multi-doc loop. Previously-processed docs are already mutated, but the caller sees only the error message. Consider aggregating per-doc failures instead of aborting.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@api/apps/restful_apis/document_api.py` around lines 1053 - 1055, The code
reassigns tenant_id from DocumentService.get_tenant_id(id) which shadows the
caller user_id added by add_tenant_id_to_kwargs and passed into
_run_sync(user_id, req); rename the local variable to doc_tenant_id (used where
you currently call search.index_name(tenant_id) and
DocumentService.run(tenant_id,...)) to make owner vs caller explicit and avoid
confusion with DocumentService.accessible(doc_id, user_id), and stop returning
early with get_data_error_result(message="Tenant not found!") inside the
multi-doc loop—instead collect per-doc failures (e.g., accumulate errors for
each id) and continue processing so previously-processed docs aren’t silently
discarded, then return a combined result summarizing successes and per-doc
errors.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (2)
api/apps/restful_apis/document_api.py (2)
1034-1064:⚠️ Potential issue | 🟠 MajorMissing request validation and mid-loop partial-commit still unresolved.
Two related correctness gaps persist after the earlier rounds:
req["doc_ids"](lines 1039, 1044) andreq["run"](lines 1045, 1046, 1058, 1065, 1074) are indexed without guards. A payload missing either key, or with a non-listdoc_ids/non-stringablerun, raisesKeyError/TypeErrorthat surfaces as a generic 500 viaserver_error_response. Validate the payload (pydantic model or explicit checks) and return a 400 (RetCode.ARGUMENT_ERROR) with a useful message.- The loop at lines 1044-1084 mutates each document (
update_by_id,filter_delete,docStoreConn.delete,DocumentService.run) in sequence. Early returns at lines 1053 ("Tenant not found"), 1056 ("Document not found"), and 1064 ("Cannot cancel…") fire from the middle of the loop, leaving docs0..N-1already mutated/queued while the caller only sees the single error for doc N. Pre-validate tenant/doc/cancel-eligibility for every ID up-front (alongside the existing accessibility pass at 1039-1041) before applying any mutations, or return a structured per-doc result map.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/restful_apis/document_api.py` around lines 1034 - 1064, The handler blindly indexes req["doc_ids"] and req["run"] and mutates documents mid-loop causing uncaught KeyError/TypeError and partial commits; first add upfront validation (e.g., a small pydantic model or explicit checks) to ensure req contains "doc_ids" as a list and "run" as a string-coercible value and return a 400 with RetCode.ARGUMENT_ERROR and a helpful message if validation fails, and then perform a pre-validation pass over all ids using DocumentService.accessible, DocumentService.get_tenant_id and DocumentService.get_by_id and check cancel eligibility via TaskService.query/has_unfinished_task (and any run-state checks) to collect any per-doc errors; only after every doc passes these checks proceed to call the mutators (update_by_id, filter_delete, docStoreConn.delete, DocumentService.run, cancel_all_task_of), or alternatively return a structured per-doc result map so no partial mutations occur on early error.
1033-1091:⚠️ Potential issue | 🟡 MinorRename loop var
idand add structured logs for the new flow.
- Line 1044 still iterates
for id in req["doc_ids"]:and usesidat lines 1051, 1054, 1059, 1062, 1068, 1070, 1072, 1084, shadowing the builtin. Line 1039 already usesdoc_id— use the same name in the second loop for consistency and readability.- No logs are emitted from
run/_run_sync, which obscures diagnostics for a flow that mutates doc state, deletes index entries, and queues tasks. Please add at minimum: entry log withtenant_idand doc count, per-doc action log (update/cancel/rerun/delete), and a final status log before return.As per coding guidelines: "Add logging for new flows".
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1044-1068: The bug is that the two branches disagree on the
default for req["delete"], causing KB counters to be decremented while the
document keeps old chunk/token counts; update the condition that calls
DocumentService.clear_chunk_num_when_rerun(doc.id) to use the same default as
earlier (req.get("delete", False)) so clearing only happens when the handler
will also zero the per-document counters, or alternatively ensure that when
DocumentService.clear_chunk_num_when_rerun(doc.id) is invoked you also set
info["chunk_num"]=0 and info["token_num"]=0 before calling
DocumentService.update_by_id(id, info); locate this logic around the loop that
references req["doc_ids"], the TaskStatus checks, and the calls to
DocumentService.clear_chunk_num_when_rerun and DocumentService.update_by_id to
apply the fix.
- Around line 1038-1089: The background worker _run_sync (invoked via
thread_pool_exec) must not call Quart response helpers like get_json_result or
get_data_error_result because those require the Quart application/request
context; instead modify _run_sync to return plain Python dicts (e.g.,
{"success": True, "data": ...} or {"success": False, "error": "...", "code":
...}) for every exit path (including authorization, tenant/document not found,
cancel-not-allowed, etc.), and preserve exceptions for unexpected errors; then
update the outer run(...) handler (the coroutine that awaits
thread_pool_exec(_run_sync)) to inspect the returned dict and construct the
appropriate Quart response using get_json_result/get_data_error_result on the
event loop/context. Ensure all references to
get_json_result/get_data_error_result inside _run_sync are removed and replace
early returns there with plain-data returns so only the route builds Quart
responses.
---
Duplicate comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1034-1064: The handler blindly indexes req["doc_ids"] and
req["run"] and mutates documents mid-loop causing uncaught KeyError/TypeError
and partial commits; first add upfront validation (e.g., a small pydantic model
or explicit checks) to ensure req contains "doc_ids" as a list and "run" as a
string-coercible value and return a 400 with RetCode.ARGUMENT_ERROR and a
helpful message if validation fails, and then perform a pre-validation pass over
all ids using DocumentService.accessible, DocumentService.get_tenant_id and
DocumentService.get_by_id and check cancel eligibility via
TaskService.query/has_unfinished_task (and any run-state checks) to collect any
per-doc errors; only after every doc passes these checks proceed to call the
mutators (update_by_id, filter_delete, docStoreConn.delete, DocumentService.run,
cancel_all_task_of), or alternatively return a structured per-doc result map so
no partial mutations occur on early error.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: a1d87ecf-4358-4cf7-95a7-9857c3d5fe08
📒 Files selected for processing (8)
admin/client/ragflow_client.pyapi/apps/document_app.pyapi/apps/restful_apis/document_api.pysdk/python/test/test_frontend_api/common.pytest/testcases/test_web_api/test_common.pyweb/src/hooks/use-document-request.tsweb/src/services/knowledge-service.tsweb/src/utils/api.ts
💤 Files with no reviewable changes (1)
- api/apps/document_app.py
✅ Files skipped from review due to trivial changes (2)
- sdk/python/test/test_frontend_api/common.py
- admin/client/ragflow_client.py
🚧 Files skipped from review as they are similar to previous changes (3)
- web/src/utils/api.ts
- test/testcases/test_web_api/test_common.py
- web/src/services/knowledge-service.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1038-1046: The handler is swallowing (_run_sync) failure tuples
and always returning get_json_result(data=True); change the control flow after
awaiting thread_pool_exec so that if error_code is truthy you return an
appropriate error response instead of falling through—use the returned
error_code and error_message to build/return a Quart response (e.g., call
server_error_response or a mapped error response) rather than logging only;
update the block around thread_pool_exec/_run_sync/get_json_result to
immediately return on error, preserving existing logging and exception handling.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 9a434c84-92a0-47d6-9fe4-4e11aa3c6b4f
📒 Files selected for processing (8)
admin/client/ragflow_client.pyapi/apps/document_app.pyapi/apps/restful_apis/document_api.pysdk/python/test/test_frontend_api/common.pytest/testcases/test_web_api/test_common.pyweb/src/hooks/use-document-request.tsweb/src/services/knowledge-service.tsweb/src/utils/api.ts
💤 Files with no reviewable changes (1)
- api/apps/document_app.py
✅ Files skipped from review due to trivial changes (2)
- test/testcases/test_web_api/test_common.py
- admin/client/ragflow_client.py
🚧 Files skipped from review as they are similar to previous changes (3)
- sdk/python/test/test_frontend_api/common.py
- web/src/services/knowledge-service.ts
- web/src/utils/api.ts
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14351 +/- ##
=======================================
Coverage 95.30% 95.30%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 670 670
Misses 16 16
Partials 17 17 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1049-1098: Validate input at the top of _run_sync: ensure req
contains "doc_ids" as a non-empty list and "run" as a stringable value and
return RetCode.ARGUMENT_ERROR with a clear message on failure; use explicit
isinstance checks or pydantic before any side-effects. Pre-validate all
documents and permissions (use DocumentService.accessible and
DocumentService.get_tenant_id/get_by_id) in a first pass so no partial commits
occur; alternatively build and return a per-doc result map (success/error)
instead of returning immediately on the first failure so callers can reconcile
partial changes. Add per-doc structured logging (include doc_id) at entry and at
each key transition/failure: accessibility check, cancel/rerun decision,
TaskService.filter_delete and settings.docStoreConn.delete calls,
DocumentService.update_by_id/update_parser_config, and when calling
DocumentService.run; include error context when returning RetCode.DATA_ERROR or
raising LookupError.
- Around line 1081-1084: The destructive delete block should only run when the
rerun_with_delete guard is true; update the condition that currently checks
req.get("delete", False) so it also requires rerun_with_delete (e.g., if
rerun_with_delete and req.get("delete", False)): wrap the
TaskService.filter_delete call and the
settings.docStoreConn.index_exist/...delete invocation behind that combined
guard so TaskService.filter_delete, settings.docStoreConn.index_exist and
settings.docStoreConn.delete only execute when rerun_with_delete is set.
In `@test/testcases/test_web_api/test_document_app/test_paser_documents.py`:
- Around line 182-196: The test named test_apply_kb_dataset_not_found is
misleading because it never sets "apply_kb": True nor arranges a missing KB;
either rename the test to reflect the actual behavior (e.g.,
test_parse_without_apply_kb_happy_path) or change the test to exercise the
missing-KB branch in _run_sync by calling parse_documents with "apply_kb": True
and arranging for the dataset to be absent (so that document_api raises
LookupError("Can't find this dataset!")), then assert the error/response matches
the expected failure; update references to add_documents_func, parse_documents,
and validate_document_parse_done accordingly.
- Around line 136-152: The test test_cancel_non_running_task_error incorrectly
asserts success after calling parse_documents to cancel a DONE document; change
the assertion to expect the backend error: assert that res["code"] equals
RetCode.DATA_ERROR (the error returned by document_api._run_sync for non-RUNNING
tasks) and that res["message"] contains "Cannot cancel a task that is not in
RUNNING status" (or otherwise matches the error text returned by
_run_sync/get_json_result); keep references to parse_documents,
validate_document_parse_done, and document_api._run_sync to locate the relevant
logic.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2698ec19-335c-4526-a43d-0a941fb4c51b
📒 Files selected for processing (2)
api/apps/restful_apis/document_api.pytest/testcases/test_web_api/test_document_app/test_paser_documents.py
| def _run_sync(user_id:str, req): | ||
| for doc_id in req["doc_ids"]: | ||
| if not DocumentService.accessible(doc_id, user_id): | ||
| return RetCode.AUTHENTICATION_ERROR, "No authorization." | ||
|
|
||
| kb_table_num_map = {} | ||
| for doc_id in req["doc_ids"]: | ||
| info = {"run": str(req["run"]), "progress": 0} | ||
| rerun_with_delete = str(req["run"]) == TaskStatus.RUNNING.value and req.get("delete", False) | ||
| if rerun_with_delete: | ||
| info["progress_msg"] = "" | ||
| info["chunk_num"] = 0 | ||
| info["token_num"] = 0 | ||
|
|
||
| doc_tenant_id = DocumentService.get_tenant_id(doc_id) | ||
| if not doc_tenant_id: | ||
| return RetCode.DATA_ERROR, "Tenant not found!" | ||
| e, doc = DocumentService.get_by_id(doc_id) | ||
| if not e: | ||
| return RetCode.DATA_ERROR, "Document not found!" | ||
|
|
||
| if str(req["run"]) == TaskStatus.CANCEL.value: | ||
| tasks = list(TaskService.query(doc_id=doc_id)) | ||
| has_unfinished_task = any((task.progress or 0) < 1 for task in tasks) | ||
| if str(doc.run) in [TaskStatus.RUNNING.value, TaskStatus.CANCEL.value] or has_unfinished_task: | ||
| cancel_all_task_of(doc_id) | ||
| else: | ||
| return RetCode.DATA_ERROR, "Cannot cancel a task that is not in RUNNING status" | ||
| if all([rerun_with_delete, str(doc.run) == TaskStatus.DONE.value]): | ||
| DocumentService.clear_chunk_num_when_rerun(doc_id) | ||
|
|
||
| DocumentService.update_by_id(doc_id, info) | ||
| if req.get("delete", False): | ||
| TaskService.filter_delete([Task.doc_id == doc_id]) | ||
| if settings.docStoreConn.index_exist(search.index_name(doc_tenant_id), doc.kb_id): | ||
| settings.docStoreConn.delete({"doc_id": doc_id}, search.index_name(doc_tenant_id), doc.kb_id) | ||
|
|
||
| if str(req["run"]) == TaskStatus.RUNNING.value: | ||
| if req.get("apply_kb"): | ||
| e, kb = KnowledgebaseService.get_by_id(doc.kb_id) | ||
| if not e: | ||
| raise LookupError("Can't find this dataset!") | ||
| doc.parser_config["llm_id"] = kb.parser_config.get("llm_id") | ||
| doc.parser_config["enable_metadata"] = kb.parser_config.get("enable_metadata", False) | ||
| doc.parser_config["metadata"] = kb.parser_config.get("metadata", {}) | ||
| DocumentService.update_parser_config(doc.id, doc.parser_config) | ||
| doc_dict = doc.to_dict() | ||
| DocumentService.run(doc_tenant_id, doc_dict, kb_table_num_map) | ||
|
|
||
| return None, None |
There was a problem hiding this comment.
Still missing: input validation + partial-commit hazard + per-doc logging.
A few items from prior rounds appear unaddressed:
-
No validation on
req["doc_ids"]/req["run"](lines 1050, 1055-1056, 1070, 1086). A missing key, non-listdoc_ids, or non-stringablerunraisesKeyError/TypeErrorinside the thread worker, which surfaces as a generic 500 viaserver_error_response. Validate up front (pydantic or explicitisinstancechecks) and returnRRetCode.ARGUMENT_ERRORwith a helpful message. -
Partial-commit on mid-loop failure. After iteration
N-1completes (update + task delete + index delete + queued run), an error on iterationNhits one of thereturn RetCode.DATA_ERROR, ...paths (lines 1065, 1068, 1076) and the caller gets a single opaque error with no indication that docs0..N-1were already mutated/queued. Either pre-validate all docs before any mutation, or collect per-doc successes/errors and return a structured result so clients can reconcile. -
Per-doc logging. As per coding guidelines ("Add logging for new flows"), please log entry, each per-doc transition (accessibility check, run/cancel/rerun decision, index delete, queued run), and failure paths with
doc_idcontext — the outer handler-level log alone is not enough to trace which doc failed in a multi-doc batch.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@api/apps/restful_apis/document_api.py` around lines 1049 - 1098, Validate
input at the top of _run_sync: ensure req contains "doc_ids" as a non-empty list
and "run" as a stringable value and return RetCode.ARGUMENT_ERROR with a clear
message on failure; use explicit isinstance checks or pydantic before any
side-effects. Pre-validate all documents and permissions (use
DocumentService.accessible and DocumentService.get_tenant_id/get_by_id) in a
first pass so no partial commits occur; alternatively build and return a per-doc
result map (success/error) instead of returning immediately on the first failure
so callers can reconcile partial changes. Add per-doc structured logging
(include doc_id) at entry and at each key transition/failure: accessibility
check, cancel/rerun decision, TaskService.filter_delete and
settings.docStoreConn.delete calls,
DocumentService.update_by_id/update_parser_config, and when calling
DocumentService.run; include error context when returning RetCode.DATA_ERROR or
raising LookupError.
| if req.get("delete", False): | ||
| TaskService.filter_delete([Task.doc_id == doc_id]) | ||
| if settings.docStoreConn.index_exist(search.index_name(doc_tenant_id), doc.kb_id): | ||
| settings.docStoreConn.delete({"doc_id": doc_id}, search.index_name(doc_tenant_id), doc.kb_id) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check all callers that set "delete": true to see which run states they pair with.
rg -nP --type=ts --type=tsx --type=py -C3 '"delete"\s*:\s*true|\bdelete:\s*true'Repository: infiniflow/ragflow
Length of output: 90
🏁 Script executed:
#!/bin/bash
# Search for "delete": true patterns with proper file types
rg -nP --type=ts --type=py --type=js -C3 '"delete"\s*:\s*true|\bdelete:\s*true'Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
#!/bin/bash
# Check the specific file and lines in question
wc -l api/apps/restful_apis/document_api.pyRepository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
# Read the relevant section of the document_api.py file
sed -n '1040,1090p' api/apps/restful_apis/document_api.pyRepository: infiniflow/ragflow
Length of output: 2448
🏁 Script executed:
#!/bin/bash
# Find where _run_sync is called
rg -n '_run_sync' api/apps/restful_apis/document_api.pyRepository: infiniflow/ragflow
Length of output: 189
🏁 Script executed:
#!/bin/bash
# Search for API calls/payloads that set delete flag across the codebase
rg -n 'delete.*true|delete:\s*true' -t py -t ts -t js | head -40Repository: infiniflow/ragflow
Length of output: 50376
🏁 Script executed:
#!/bin/bash
# Check if TaskStatus.RUNNING, CANCEL, DONE values are defined
rg -n 'class TaskStatus|RUNNING|CANCEL|DONE' -t py | grep -E 'TaskStatus|\.RUNNING|\.CANCEL|\.DONE' | head -20Repository: infiniflow/ragflow
Length of output: 3306
🏁 Script executed:
#!/bin/bash
# Find API endpoints and methods that handle the delete parameter
rg -n 'req\[.*delete.*\]|req\.get.*delete|delete.*req' -t py -A2 -B2 | head -50Repository: infiniflow/ragflow
Length of output: 5036
🏁 Script executed:
#!/bin/bash
# Search for the document_api POST/PUT endpoints that call _run_sync
rg -n '@.*route|def.*document|"delete"' api/apps/restful_apis/document_api.py | head -30Repository: infiniflow/ragflow
Length of output: 1201
🏁 Script executed:
#!/bin/bash
# Check the endpoint that calls _run_sync
sed -n '1000,1050p' api/apps/restful_apis/document_api.pyRepository: infiniflow/ragflow
Length of output: 2066
🏁 Script executed:
#!/bin/bash
# Look for frontend/web code that constructs the payload with delete
find web -name "*.ts" -o -name "*.tsx" -o -name "*.js" | xargs rg -l "run.*delete|delete.*run" 2>/dev/null | head -5Repository: infiniflow/ragflow
Length of output: 278
🏁 Script executed:
#!/bin/bash
# Check the bulk operate dataset file for delete + run payload patterns
grep -n "delete\|run" web/src/pages/dataset/dataset/use-bulk-operate-dataset.tsx | head -40Repository: infiniflow/ragflow
Length of output: 840
🏁 Script executed:
#!/bin/bash
# Search for ingest API calls from frontend with delete and run parameters
find web -name "*.ts" -o -name "*.tsx" | xargs grep -l "ingest" 2>/dev/null | head -5Repository: infiniflow/ragflow
Length of output: 172
🏁 Script executed:
#!/bin/bash
# Check if there are any tests that explicitly test delete with different run states
find test -name "*.py" | xargs grep -l "delete.*run\|run.*delete" 2>/dev/null | head -3Repository: infiniflow/ragflow
Length of output: 307
🏁 Script executed:
#!/bin/bash
# Examine test files for the ingest/run endpoint specifically
rg -n "ingest|_run_sync" test/ -t py -A5 | grep -E "delete|run|ingest" | head -30Repository: infiniflow/ragflow
Length of output: 240
🏁 Script executed:
#!/bin/bash
# Find TaskStatus enum definition
rg -n "class TaskStatus|RUNNING|CANCEL|DONE" -t py api/db/models/ | grep -A5 "class TaskStatus"Repository: infiniflow/ragflow
Length of output: 117
🏁 Script executed:
#!/bin/bash
# Check what values these enums have
find api -name "*.py" -exec grep -l "TaskStatus" {} \; | xargs grep -n "RUNNING\|CANCEL\|DONE" -B2 | grep -E "value|RUNNING|CANCEL|DONE" | head -20Repository: infiniflow/ragflow
Length of output: 2449
Align delete operations with rerun_with_delete guard for consistency.
The counter-reset (line 1058) is correctly guarded by rerun_with_delete, but the destructive delete operations (lines 1081-1084) are guarded only by req.get("delete", False). This allows a payload like {"run": "2", "delete": true} (CANCEL + delete) to wipe tasks and index despite the cancel operation. While the frontend prevents this at the UI level, enforce it at the API for clarity and robustness:
🔧 Suggested guard
- if req.get("delete", False):
+ if rerun_with_delete:
TaskService.filter_delete([Task.doc_id == doc_id])
if settings.docStoreConn.index_exist(search.index_name(doc_tenant_id), doc.kb_id):
settings.docStoreConn.delete({"doc_id": doc_id}, search.index_name(doc_tenant_id), doc.kb_id)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@api/apps/restful_apis/document_api.py` around lines 1081 - 1084, The
destructive delete block should only run when the rerun_with_delete guard is
true; update the condition that currently checks req.get("delete", False) so it
also requires rerun_with_delete (e.g., if rerun_with_delete and
req.get("delete", False)): wrap the TaskService.filter_delete call and the
settings.docStoreConn.index_exist/...delete invocation behind that combined
guard so TaskService.filter_delete, settings.docStoreConn.index_exist and
settings.docStoreConn.delete only execute when rerun_with_delete is set.
| @pytest.mark.p2 | ||
| def test_cancel_non_running_task_error(self, WebApiAuth, add_documents_func): | ||
| """Test cancel error when task is not in RUNNING status.""" | ||
| kb_id, document_ids = add_documents_func | ||
| doc_id = document_ids[0] | ||
|
|
||
| # First, run the document parsing | ||
| res = parse_documents(WebApiAuth, {"doc_ids": [doc_id], "run": "1"}) | ||
| assert res["code"] == 0, res | ||
|
|
||
| # Wait for parsing to complete | ||
| condition(WebApiAuth, kb_id, [doc_id]) | ||
| validate_document_parse_done(WebApiAuth, kb_id, [doc_id]) | ||
|
|
||
| # Now try to cancel a completed task - should fail | ||
| res = parse_documents(WebApiAuth, {"doc_ids": [doc_id], "run": "2"}) | ||
| assert res["code"] == 0, res # API returns success but message indicates the status |
There was a problem hiding this comment.
Test assertion contradicts backend behavior and masks a real error path.
_run_sync explicitly returns (RetCode.DATA_ERROR, "Cannot cancel a task that is not in RUNNING status") when the target doc is already DONE and has no unfinished tasks (document_api.py lines 1070-1076). After validate_document_parse_done on line 148 confirms doc.run == "DONE" and progress is 1, the subsequent cancel on line 151 must hit that error branch. Asserting code == 0 here both (a) doesn't match the backend contract, and (b) will start failing as soon as the get_json_result(error_code, error_message) positional-arg bug in the handler is fixed. The trailing inline comment "API returns success but message indicates the status" is also incorrect — the API returns an error code.
Please align the assertion with the intended error semantics:
🧪 Suggested assertion
- # Now try to cancel a completed task - should fail
- res = parse_documents(WebApiAuth, {"doc_ids": [doc_id], "run": "2"})
- assert res["code"] == 0, res # API returns success but message indicates the status
+ # Now try to cancel a completed task - should fail
+ res = parse_documents(WebApiAuth, {"doc_ids": [doc_id], "run": "2"})
+ assert res["code"] != 0, res
+ assert "Cannot cancel" in res["message"], res📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| @pytest.mark.p2 | |
| def test_cancel_non_running_task_error(self, WebApiAuth, add_documents_func): | |
| """Test cancel error when task is not in RUNNING status.""" | |
| kb_id, document_ids = add_documents_func | |
| doc_id = document_ids[0] | |
| # First, run the document parsing | |
| res = parse_documents(WebApiAuth, {"doc_ids": [doc_id], "run": "1"}) | |
| assert res["code"] == 0, res | |
| # Wait for parsing to complete | |
| condition(WebApiAuth, kb_id, [doc_id]) | |
| validate_document_parse_done(WebApiAuth, kb_id, [doc_id]) | |
| # Now try to cancel a completed task - should fail | |
| res = parse_documents(WebApiAuth, {"doc_ids": [doc_id], "run": "2"}) | |
| assert res["code"] == 0, res # API returns success but message indicates the status | |
| `@pytest.mark.p2` | |
| def test_cancel_non_running_task_error(self, WebApiAuth, add_documents_func): | |
| """Test cancel error when task is not in RUNNING status.""" | |
| kb_id, document_ids = add_documents_func | |
| doc_id = document_ids[0] | |
| # First, run the document parsing | |
| res = parse_documents(WebApiAuth, {"doc_ids": [doc_id], "run": "1"}) | |
| assert res["code"] == 0, res | |
| # Wait for parsing to complete | |
| condition(WebApiAuth, kb_id, [doc_id]) | |
| validate_document_parse_done(WebApiAuth, kb_id, [doc_id]) | |
| # Now try to cancel a completed task - should fail | |
| res = parse_documents(WebApiAuth, {"doc_ids": [doc_id], "run": "2"}) | |
| assert res["code"] != 0, res | |
| assert "Cannot cancel" in res["message"], res |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@test/testcases/test_web_api/test_document_app/test_paser_documents.py` around
lines 136 - 152, The test test_cancel_non_running_task_error incorrectly asserts
success after calling parse_documents to cancel a DONE document; change the
assertion to expect the backend error: assert that res["code"] equals
RetCode.DATA_ERROR (the error returned by document_api._run_sync for non-RUNNING
tasks) and that res["message"] contains "Cannot cancel a task that is not in
RUNNING status" (or otherwise matches the error text returned by
_run_sync/get_json_result); keep references to parse_documents,
validate_document_parse_done, and document_api._run_sync to locate the relevant
logic.
| @pytest.mark.p2 | ||
| def test_apply_kb_dataset_not_found(self, WebApiAuth, add_documents_func): | ||
| """Test apply_kb when dataset is not found.""" | ||
| kb_id, document_ids = add_documents_func | ||
| doc_id = document_ids[0] | ||
|
|
||
| # Try to apply_kb with a non-existent dataset - this is tricky to test | ||
| # because we can't easily delete the dataset after getting the doc_id | ||
| # This test verifies the happy path works | ||
| res = parse_documents(WebApiAuth, {"doc_ids": [doc_id], "run": "1"}) | ||
| assert res["code"] == 0, res | ||
|
|
||
| # Wait for parsing to complete | ||
| condition(WebApiAuth, kb_id, [doc_id]) | ||
| validate_document_parse_done(WebApiAuth, kb_id, [doc_id]) |
There was a problem hiding this comment.
Test name doesn't match what is being tested.
The name test_apply_kb_dataset_not_found promises coverage for the apply_kb / missing-KB branch in _run_sync (document_api.py lines 1087-1090, which raises LookupError("Can't find this dataset!")). However, the body never sets "apply_kb": True and doesn't arrange a missing dataset — the comment even acknowledges "This test verifies the happy path works". As written this is a duplicate of test_successful_parse with a misleading name.
Either rename it to something like test_parse_without_apply_kb_happy_path, or actually exercise the branch (e.g., call with "apply_kb": True against a document whose KB was subsequently removed, and assert the resulting error).
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@test/testcases/test_web_api/test_document_app/test_paser_documents.py` around
lines 182 - 196, The test named test_apply_kb_dataset_not_found is misleading
because it never sets "apply_kb": True nor arranges a missing KB; either rename
the test to reflect the actual behavior (e.g.,
test_parse_without_apply_kb_happy_path) or change the test to exercise the
missing-KB branch in _run_sync by calling parse_documents with "apply_kb": True
and arranging for the dataset to be absent (so that document_api raises
LookupError("Can't find this dataset!")), then assert the error/response matches
the expected failure; update references to add_documents_func, parse_documents,
and validate_document_parse_done accordingly.
There was a problem hiding this comment.
♻️ Duplicate comments (2)
test/testcases/test_web_api/test_document_app/test_paser_documents.py (2)
182-196:⚠️ Potential issue | 🟡 MinorTest name still doesn't match what is being tested.
test_apply_kb_dataset_not_foundis intended to cover theapply_kb+ missing-KB branch in_run_sync(which raisesLookupError("Can't find this dataset!")indocument_api.pylines 1087-1090), but the body never sets"apply_kb": Trueand doesn't arrange a missing dataset — the inline comment even concedes "This test verifies the happy path works". As written, this is effectively a duplicate oftest_successful_parsebelow (and of happy-path rows intest_basic_scenarios) under a misleading name.Either rename it (e.g.,
test_parse_without_apply_kb_happy_path) or exercise the intended branch by callingparse_documentswith"apply_kb": Trueagainst a document whose KB was removed and assert the resulting error.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_web_api/test_document_app/test_paser_documents.py` around lines 182 - 196, The test named test_apply_kb_dataset_not_found is misaligned with its intent: either rename it to reflect it tests the happy parse path (e.g., test_parse_without_apply_kb_happy_path) or change the test to exercise the apply_kb missing-dataset branch by calling parse_documents with {"doc_ids": [doc_id], "run": "1", "apply_kb": True}, arrange for the document's KB to be absent (remove or create a non-existent kb_id) so _run_sync in document_api.py hits the LookupError("Can't find this dataset!"), and then assert the response or raised error matches that missing-dataset behavior instead of the current successful-parse assertions; locate this logic around the test function test_apply_kb_dataset_not_found and the parse_documents helper to implement the fix.
150-152:⚠️ Potential issue | 🟠 MajorAssertion still contradicts backend behavior.
Per
_run_syncinapi/apps/restful_apis/document_api.py(lines 1070-1076), attempting to cancel a document whoserun == "DONE"with no unfinished tasks returns(RetCode.DATA_ERROR, "Cannot cancel a task that is not in RUNNING status"). Since line 148 already asserts the document reachedDONE, the cancel at line 151 must hit that error branch, sores["code"] == 0is incorrect, and the inline comment ("API returns success but message indicates the status") is misleading — the API returns an error code, not success.🧪 Suggested assertion
- # Now try to cancel a completed task - should fail - res = parse_documents(WebApiAuth, {"doc_ids": [doc_id], "run": "2"}) - assert res["code"] == 0, res # API returns success but message indicates the status + # Now try to cancel a completed task - should fail + res = parse_documents(WebApiAuth, {"doc_ids": [doc_id], "run": "2"}) + assert res["code"] != 0, res + assert "Cannot cancel" in res["message"], res🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_web_api/test_document_app/test_paser_documents.py` around lines 150 - 152, The test incorrectly expects success when cancelling a document already in DONE; update the assertion in parse_documents call to expect the backend error from _run_sync: check that res["code"] equals RetCode.DATA_ERROR (or != 0) and assert the error message contains "Cannot cancel a task that is not in RUNNING status"; locate this change around the parse_documents(WebApiAuth, {"doc_ids": [doc_id], "run": "2"}) call in test_paser_documents.py and refer to _run_sync and RetCode.DATA_ERROR to align the test with the API behavior.
🧹 Nitpick comments (2)
test/testcases/test_web_api/test_document_app/test_paser_documents.py (2)
198-219: Largely duplicates coverage already provided bytest_basic_scenarios+validate_document_parse_done.
test_successful_parseassertsrun == "DONE",chunk_num > 0,process_begin_at, andprocess_duration > 0after waiting for completion. Thetest_basic_scenarioshappy-path rows (lines 90, 94, 95) already driveparse_documentsand invokevalidate_document_parse_done, which coversrun == "DONE",process_begin_at,process_duration > 0,progress > 0, and"Task done" in progress_msg. The only meaningful delta here ischunk_num > 0.Consider either folding the
chunk_num > 0check intovalidate_document_parse_done(so all happy-path tests benefit) or removing this test to reduce CI runtime. Combined with the fact thattest_apply_kb_dataset_not_foundabove is currently a happy-path test too, the suite has three near-identical successful-parse variants.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_web_api/test_document_app/test_paser_documents.py` around lines 198 - 219, The test_successful_parse function largely duplicates assertions already covered by test_basic_scenarios and validate_document_parse_done; either remove test_successful_parse to avoid redundant CI runtime or consolidate the unique assertion (that document["chunk_num"] > 0) into validate_document_parse_done so all happy-path tests assert chunk count; update or delete test_successful_parse accordingly and ensure validate_document_parse_done (the helper) includes the chunk_num check when chosen.
126-134: Minor: unused fixture unpack; consider droppingkb_idanddocument_ids.Neither
kb_idnordocument_idsis used in this test. You can either inline the fixture call or replace with_, _ = add_documents_functo make the intent clearer. Not a blocker.♻️ Proposed tweak
def test_document_not_found(self, WebApiAuth, add_documents_func): """Test document not found error.""" - kb_id, document_ids = add_documents_func - # Try to parse a non-existent document res = parse_documents(WebApiAuth, {"doc_ids": ["non_existent_doc_id"], "run": "1"}) assert res["code"] == 109, res assert "No authorization" in res["message"], resNote: if the
add_documents_funcfixture has setup side effects required to establish the auth/tenant context, keep the call but drop the unpack:_ = add_documents_func.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_web_api/test_document_app/test_paser_documents.py` around lines 126 - 134, The test_document_not_found function unpacks add_documents_func into kb_id and document_ids but never uses them; remove the unused variables to clarify intent by either calling the fixture without unpacking (e.g., use _ = add_documents_func) or simply reference the fixture inline, keeping the call if its side effects (auth/tenant setup) are required; update the signature/code inside test_document_not_found accordingly so add_documents_func is invoked but unused locals are eliminated.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@test/testcases/test_web_api/test_document_app/test_paser_documents.py`:
- Around line 182-196: The test named test_apply_kb_dataset_not_found is
misaligned with its intent: either rename it to reflect it tests the happy parse
path (e.g., test_parse_without_apply_kb_happy_path) or change the test to
exercise the apply_kb missing-dataset branch by calling parse_documents with
{"doc_ids": [doc_id], "run": "1", "apply_kb": True}, arrange for the document's
KB to be absent (remove or create a non-existent kb_id) so _run_sync in
document_api.py hits the LookupError("Can't find this dataset!"), and then
assert the response or raised error matches that missing-dataset behavior
instead of the current successful-parse assertions; locate this logic around the
test function test_apply_kb_dataset_not_found and the parse_documents helper to
implement the fix.
- Around line 150-152: The test incorrectly expects success when cancelling a
document already in DONE; update the assertion in parse_documents call to expect
the backend error from _run_sync: check that res["code"] equals
RetCode.DATA_ERROR (or != 0) and assert the error message contains "Cannot
cancel a task that is not in RUNNING status"; locate this change around the
parse_documents(WebApiAuth, {"doc_ids": [doc_id], "run": "2"}) call in
test_paser_documents.py and refer to _run_sync and RetCode.DATA_ERROR to align
the test with the API behavior.
---
Nitpick comments:
In `@test/testcases/test_web_api/test_document_app/test_paser_documents.py`:
- Around line 198-219: The test_successful_parse function largely duplicates
assertions already covered by test_basic_scenarios and
validate_document_parse_done; either remove test_successful_parse to avoid
redundant CI runtime or consolidate the unique assertion (that
document["chunk_num"] > 0) into validate_document_parse_done so all happy-path
tests assert chunk count; update or delete test_successful_parse accordingly and
ensure validate_document_parse_done (the helper) includes the chunk_num check
when chosen.
- Around line 126-134: The test_document_not_found function unpacks
add_documents_func into kb_id and document_ids but never uses them; remove the
unused variables to clarify intent by either calling the fixture without
unpacking (e.g., use _ = add_documents_func) or simply reference the fixture
inline, keeping the call if its side effects (auth/tenant setup) are required;
update the signature/code inside test_document_not_found accordingly so
add_documents_func is invoked but unused locals are eliminated.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: fecd4cf0-db61-42b2-9c9b-652cd49af5e9
📒 Files selected for processing (1)
test/testcases/test_web_api/test_document_app/test_paser_documents.py
What problem does this PR solve?
Before migration: POST /v1/document/run
After migration: POST /api/v1/documents/ingest/
Type of change