Repository navigation
Consolidateion of document upload API - #14106
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:
📝 WalkthroughWalkthroughUpload flow moved from a generic Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Client
participant Frontend
participant API_Server as API(Server)
participant KB as KnowledgebaseService
participant FileSvc as FileService
participant Storage
Client->>Frontend: select files + datasetId
Frontend->>Frontend: build FormData (files only)
Frontend->>API_Server: POST /datasets/{datasetId}/documents (Auth, formData)
API_Server->>KB: get_by_id(datasetId)
KB-->>API_Server: dataset object / not found
API_Server->>API_Server: check_kb_team_permission(tenant, kb)
API_Server->>FileSvc: thread_pool_exec(upload_document, kb, files, tenant, parent_path)
FileSvc->>Storage: persist files / extract metadata
Storage-->>FileSvc: file metadata list
FileSvc-->>API_Server: uploaded files payload
API_Server->>API_Server: map_doc_keys_with_run_status(...) or return_raw_files
API_Server-->>Frontend: 200/4xx/5xx + payload
Frontend-->>Client: show result (success/partial/failure)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (5)
web/src/services/knowledge-service.ts (1)
96-99: Dead code:documentUploadin methods object is no longer usable.Since
api.documentUploadis now a function (not a string), thedocumentUploadentry in themethodsobject will fail if invoked viakbService.documentUpload(). Consider removing it to avoid confusion.🧹 Proposed cleanup
- documentUpload: { - url: documentUpload, - method: 'post', - },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/services/knowledge-service.ts` around lines 96 - 99, The methods object contains a dead entry "documentUpload" that assumes api.documentUpload is a URL string, but api.documentUpload is now a function, so kbService.documentUpload() will be invalid; remove the "documentUpload" property from the methods object (and any references to kbService.documentUpload()) and ensure callers use the api.documentUpload function directly or add a proper wrapper function that calls api.documentUpload instead.test/testcases/test_web_api/test_common.py (1)
353-357: Missing validation for requiredkb_idparameter.When
payloadisNoneor missing thekb_idkey, the URL becomes/api/{VERSION}/datasets/None/documents, which will fail with a confusing error. Consider validatingkb_idearly:♻️ Proposed validation
def upload_documents(auth, payload=None, files_path=None, *, filename_override=None): # New endpoint: /api/v1/datasets/{kb_id}/documents kb_id = payload.get("kb_id") if payload else None + if not kb_id: + raise ValueError("kb_id is required in payload for upload_documents") url = f"{HOST_ADDRESS}/api/{VERSION}/datasets/{kb_id}/documents"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_web_api/test_common.py` around lines 353 - 357, The upload_documents helper constructs the URL using kb_id but doesn't validate it, causing URLs like /datasets/None/documents; update the upload_documents function to explicitly validate the kb_id extracted from payload (the kb_id variable) before building url (the url variable) — if payload is None or kb_id is missing/falsey, raise a clear error or return early with a descriptive exception/message indicating the missing required kb_id parameter so callers get a helpful failure instead of a malformed URL.web/src/pages/dataset/dataset/use-upload-document.ts (1)
32-38: Type casting loses type safety.Using
(x: any)bypasses TypeScript's type checking. Ifret.datais typed asIDocumentInfo[](from the mutation's generic parameter), theidproperty should be directly accessible.♻️ Suggested improvement
if (isSuccess && parseOnCreation) { runDocumentByIds({ - documentIds: ret.data.map((x: any) => x.id), + documentIds: ret.data?.map((x) => x.id) ?? [], run: 1, shouldDelete: false, }); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/pages/dataset/dataset/use-upload-document.ts` around lines 32 - 38, The map currently casts items as any which loses type safety; change the mapping over ret.data to use the inferred type (e.g., IDocumentInfo) instead of (x: any) so you can access x.id directly—update the call to runDocumentByIds to pass documentIds: ret.data.map(x => x.id) (ensuring ret is typed as the mutation result containing IDocumentInfo[]) and remove the explicit any cast in use-upload-document.ts where runDocumentByIds is invoked.api/apps/restful_apis/document_api.py (1)
281-284: Return a client-facing data error for missing datasets instead ofserver_error_response.A missing dataset is an expected client/domain error, but this path wraps it as an exception response (
LookupError(...)text leak). Consider returningget_error_data_result(...)with a stable message/code to keep error semantics consistent.✅ Suggested fix
- if not e: - return server_error_response(LookupError(f"Can't find the dataset with ID {dataset_id}!")) + if not e: + return get_error_data_result( + message=f"Can't find the dataset with ID {dataset_id}!", + code=RetCode.DATA_ERROR, + )🤖 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 281 - 284, The code currently treats a missing dataset as an internal error by returning server_error_response(LookupError(...)) after calling KnowledgebaseService.get_by_id(dataset_id); replace that with a client-facing data error using get_error_data_result with a stable error message and code (e.g., "dataset_not_found" or similar) so callers get a consistent domain error response instead of an exception leak; update the branch that checks the e falsy return from KnowledgebaseService.get_by_id to call get_error_data_result(...) with the dataset_id included in logs/metadata but not in the top-level message.test/testcases/test_web_api/test_document_app/test_upload_documents.py (1)
289-294: Don’t skip the no-permission path for this endpoint change.This PR changes upload routing and permission checks; keeping the authorization-negative case skipped leaves a core behavior unverified. Please wire a fixture/user setup to assert the
No authorization.response instead of skipping.Based on learnings
Applies to tests/**/*.py : Add/adjust tests for behavior changes.🤖 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_upload_documents.py` around lines 289 - 294, Remove the pytest.skip in test_no_permission and implement the negative authorization case: using the existing WebApiAuth fixture create (or reuse) a dataset owned by a different user (or ensure the current fixture has no access), prepare a temporary upload file via tmp_path, perform the upload request against the upload endpoint (the same call used by other upload tests inside test_no_permission), and assert the response is an authorization failure (status code and body contains "No authorization."). Reference the test function name test_no_permission and the WebApiAuth fixture to locate where to wire the unauthorized user/dataset and perform the POST to the dataset documents upload route.
🤖 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 188-313: Add structured logging to the upload_document flow: log
request start with dataset_id, tenant_id and incoming filenames at the top of
upload_document; log KB lookup failure (KnowledgebaseService.get_by_id) with
dataset_id and error; log validation rejections (missing file, empty filename,
filename length) including offending filename(s); log permission rejection from
check_kb_team_permission with tenant_id and kb id; log
FileService.upload_document outcome including any err details and number of
files returned; finally log successful return with count and mapped document
ids/names from map_doc_keys. Use the module's logger consistently and include
error/exception details when available to aid troubleshooting.
- Around line 272-277: The code currently calls
file_obj.filename.encode("utf-8") without guarding against None which will
raise; update the validation in the upload handler to first check for falsy
filename (e.g., if not file_obj.filename) before any encoding/length check and
return get_error_data_result(message="No file selected!",
code=RetCode.ARGUMENT_ERROR) when missing; then only perform the byte-length
check against FILE_NAME_LEN_LIMIT on a confirmed string filename to avoid a 500
on None.
In `@api/apps/services/document_api_service.py`:
- Around line 206-215: The current logic overwrites textual run statuses in
renamed_doc (e.g., "DONE"/"RUNNING") because run_mapping only contains numeric
keys; update the run-handling so that if run_value is provided it is used,
otherwise if renamed_doc contains "run" and its value is already a string leave
renamed_doc["run"] unchanged, and only apply run_mapping.get(...) for non-string
(numeric) run values; adjust the block referring to run_value,
renamed_doc["run"], and run_mapping accordingly.
In `@test/playwright/e2e/test_dataset_upload_parse.py`:
- Around line 632-634: The lambda used to filter the POST request is using the
string containment check with the literal pattern "/v1/datasets/.*/documents",
which will not perform regex matching; update the predicate to use a regex
search (e.g., re.search) against resp.url instead of "in", and add/import the re
module; keep the existing method check (resp.request.method == "POST") and
replace the containment check with a regex match for the dataset path pattern
like r"/v1/datasets/.*/documents".
In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`:
- Around line 199-202: The imports "import asyncio", "import sys" and "from
types import ModuleType, SimpleNamespace" are placed mid-file and trigger ruff
E402; move these four import statements into the top-level import section of
test_upload_documents.py (grouped with other standard-library imports) so they
appear before any executable code or other statements, preserving
alphabetical/grouping conventions used in the file.
In `@web/src/hooks/use-document-request.ts`:
- Around line 73-75: The code calls uploadDocument(id!, formData) using a
non-null assertion on the route param id from useParams(), which can be
undefined; change the logic in the useDocumentRequest hook (the place where id
is read and uploadDocument is called) to validate id before calling
uploadDocument: return early or throw a clear error when id is missing, or guard
the mutation so it only runs when id !== undefined (e.g., disable/skip the
mutation or check and set an error state). Ensure any callers of the mutation
respect the new guard so uploadDocument never receives undefined and the URL is
not built with "undefined".
---
Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 281-284: The code currently treats a missing dataset as an
internal error by returning server_error_response(LookupError(...)) after
calling KnowledgebaseService.get_by_id(dataset_id); replace that with a
client-facing data error using get_error_data_result with a stable error message
and code (e.g., "dataset_not_found" or similar) so callers get a consistent
domain error response instead of an exception leak; update the branch that
checks the e falsy return from KnowledgebaseService.get_by_id to call
get_error_data_result(...) with the dataset_id included in logs/metadata but not
in the top-level message.
In `@test/testcases/test_web_api/test_common.py`:
- Around line 353-357: The upload_documents helper constructs the URL using
kb_id but doesn't validate it, causing URLs like /datasets/None/documents;
update the upload_documents function to explicitly validate the kb_id extracted
from payload (the kb_id variable) before building url (the url variable) — if
payload is None or kb_id is missing/falsey, raise a clear error or return early
with a descriptive exception/message indicating the missing required kb_id
parameter so callers get a helpful failure instead of a malformed URL.
In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`:
- Around line 289-294: Remove the pytest.skip in test_no_permission and
implement the negative authorization case: using the existing WebApiAuth fixture
create (or reuse) a dataset owned by a different user (or ensure the current
fixture has no access), prepare a temporary upload file via tmp_path, perform
the upload request against the upload endpoint (the same call used by other
upload tests inside test_no_permission), and assert the response is an
authorization failure (status code and body contains "No authorization.").
Reference the test function name test_no_permission and the WebApiAuth fixture
to locate where to wire the unauthorized user/dataset and perform the POST to
the dataset documents upload route.
In `@web/src/pages/dataset/dataset/use-upload-document.ts`:
- Around line 32-38: The map currently casts items as any which loses type
safety; change the mapping over ret.data to use the inferred type (e.g.,
IDocumentInfo) instead of (x: any) so you can access x.id directly—update the
call to runDocumentByIds to pass documentIds: ret.data.map(x => x.id) (ensuring
ret is typed as the mutation result containing IDocumentInfo[]) and remove the
explicit any cast in use-upload-document.ts where runDocumentByIds is invoked.
In `@web/src/services/knowledge-service.ts`:
- Around line 96-99: The methods object contains a dead entry "documentUpload"
that assumes api.documentUpload is a URL string, but api.documentUpload is now a
function, so kbService.documentUpload() will be invalid; remove the
"documentUpload" property from the methods object (and any references to
kbService.documentUpload()) and ensure callers use the api.documentUpload
function directly or add a proper wrapper function that calls api.documentUpload
instead.
🪄 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: 69a1a650-ff1a-455f-8f7d-bdb96d1baf82
📒 Files selected for processing (14)
admin/client/ragflow_client.pyapi/apps/document_app.pyapi/apps/restful_apis/document_api.pyapi/apps/sdk/doc.pyapi/apps/services/document_api_service.pytest/playwright/e2e/test_dataset_upload_parse.pytest/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.pytest/testcases/test_http_api/test_file_management_within_dataset/test_upload_documents.pytest/testcases/test_web_api/test_common.pytest/testcases/test_web_api/test_document_app/test_upload_documents.pyweb/src/hooks/use-document-request.tsweb/src/pages/dataset/dataset/use-upload-document.tsweb/src/services/knowledge-service.tsweb/src/utils/api.ts
💤 Files with no reviewable changes (3)
- test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
- api/apps/document_app.py
- api/apps/sdk/doc.py
| # Handle run field | ||
| if run_value is not None: | ||
| # Explicit run value provided (e.g., "UNSTART" for uploads) | ||
| renamed_doc["run"] = run_value | ||
| elif "run" in renamed_doc: | ||
| # Map existing run value using run_mapping | ||
| renamed_doc["run"] = run_mapping.get(str(renamed_doc["run"]), "UNSTART") | ||
| else: | ||
| # No run field present - default to UNSTART (for new uploads) | ||
| renamed_doc["run"] = "UNSTART" |
There was a problem hiding this comment.
Preserve already-normalized run values when input is a dict.
If doc["run"] is already textual (e.g., "DONE"/"RUNNING"), the current branch remaps it to "UNSTART" because only numeric keys exist in run_mapping. That returns an incorrect status for valid dict inputs.
✅ Suggested fix
- elif "run" in renamed_doc:
- # Map existing run value using run_mapping
- renamed_doc["run"] = run_mapping.get(str(renamed_doc["run"]), "UNSTART")
+ elif "run" in renamed_doc:
+ # Map existing run value using run_mapping, but preserve already-normalized values
+ run_raw = renamed_doc["run"]
+ run_text = str(run_raw).upper()
+ if run_text in run_mapping.values():
+ renamed_doc["run"] = run_text
+ else:
+ renamed_doc["run"] = run_mapping.get(str(run_raw), "UNSTART")📝 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.
| # Handle run field | |
| if run_value is not None: | |
| # Explicit run value provided (e.g., "UNSTART" for uploads) | |
| renamed_doc["run"] = run_value | |
| elif "run" in renamed_doc: | |
| # Map existing run value using run_mapping | |
| renamed_doc["run"] = run_mapping.get(str(renamed_doc["run"]), "UNSTART") | |
| else: | |
| # No run field present - default to UNSTART (for new uploads) | |
| renamed_doc["run"] = "UNSTART" | |
| # Handle run field | |
| if run_value is not None: | |
| # Explicit run value provided (e.g., "UNSTART" for uploads) | |
| renamed_doc["run"] = run_value | |
| elif "run" in renamed_doc: | |
| # Map existing run value using run_mapping, but preserve already-normalized values | |
| run_raw = renamed_doc["run"] | |
| run_text = str(run_raw).upper() | |
| if run_text in run_mapping.values(): | |
| renamed_doc["run"] = run_text | |
| else: | |
| renamed_doc["run"] = run_mapping.get(str(run_raw), "UNSTART") | |
| else: | |
| # No run field present - default to UNSTART (for new uploads) | |
| renamed_doc["run"] = "UNSTART" |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@api/apps/services/document_api_service.py` around lines 206 - 215, The
current logic overwrites textual run statuses in renamed_doc (e.g.,
"DONE"/"RUNNING") because run_mapping only contains numeric keys; update the
run-handling so that if run_value is provided it is used, otherwise if
renamed_doc contains "run" and its value is already a string leave
renamed_doc["run"] unchanged, and only apply run_mapping.get(...) for non-string
(numeric) run values; adjust the block referring to run_value,
renamed_doc["run"], and run_mapping accordingly.
| lambda resp: resp.request.method == "POST" | ||
| and "/v1/document/upload" in resp.url, | ||
| and "/v1/datasets/.*/documents" in resp.url, | ||
| ) |
There was a problem hiding this comment.
String containment check won't match regex pattern.
The in operator performs literal string containment, not regex matching. The pattern "/v1/datasets/.*/documents" will never match a URL like /v1/datasets/abc123/documents because .* is treated literally.
Use re.search for regex matching:
🐛 Proposed fix
capture_response(
page,
trigger,
lambda resp: resp.request.method == "POST"
- and "/v1/datasets/.*/documents" in resp.url,
+ and re.search(r"/v1/datasets/.*/documents", resp.url),
)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@test/playwright/e2e/test_dataset_upload_parse.py` around lines 632 - 634, The
lambda used to filter the POST request is using the string containment check
with the literal pattern "/v1/datasets/.*/documents", which will not perform
regex matching; update the predicate to use a regex search (e.g., re.search)
against resp.url instead of "in", and add/import the re module; keep the
existing method check (resp.request.method == "POST") and replace the
containment check with a regex match for the dataset path pattern like
r"/v1/datasets/.*/documents".
| import asyncio | ||
| import sys | ||
| from types import ModuleType, SimpleNamespace | ||
|
|
There was a problem hiding this comment.
Move these imports to the top-level import section.
Module imports in the middle of the file are likely to fail lint checks (ruff E402) and can break CI.
✅ Suggested fix
import string
+import asyncio
+import sys
+from types import ModuleType, SimpleNamespace
import pytest
from test_common import list_datasets, upload_documents
from configs import DOCUMENT_NAME_LIMIT, INVALID_API_TOKEN
from libs.auth import RAGFlowWebApiAuth
from utils.file_utils import create_txt_file
from api.constants import FILE_NAME_LEN_LIMIT
from concurrent.futures import ThreadPoolExecutor, as_completed
@@
-import asyncio
-import sys
-from types import ModuleType, SimpleNamespaceAs per coding guidelines **/*.py: Use ruff for Python linting and formatting.
📝 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.
| import asyncio | |
| import sys | |
| from types import ModuleType, SimpleNamespace |
🤖 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_upload_documents.py`
around lines 199 - 202, The imports "import asyncio", "import sys" and "from
types import ModuleType, SimpleNamespace" are placed mid-file and trigger ruff
E402; move these four import statements into the top-level import section of
test_upload_documents.py (grouped with other standard-library imports) so they
appear before any executable code or other statements, preserving
alphabetical/grouping conventions used in the file.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
test/testcases/test_web_api/test_document_app/test_upload_documents.py (1)
127-131: Avoid asserting the full exception/router repr verbatim.These strings are implementation details, so harmless formatting changes will fail the tests. Prefer checking the code plus a stable substring like the dataset id or
"Method Not Allowed".Also applies to: 255-261
🤖 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_upload_documents.py` around lines 127 - 131, Update the fragile assertions in test_invalid_kb_id to avoid matching the full exception/router repr; keep the numeric check for res["code"] == 100 and replace the exact message equality with a substring assertion that the dataset id ("invalid_kb_id") or a stable phrase like "Can't find the dataset" is present in res["message"]; locate the test_invalid_kb_id test and the upload_documents call to adjust the assertion style (also apply the same change to the other similar checks around lines 255-261).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`:
- Around line 288-293: The skipped test test_no_permission should be turned into
a real auth failure test: use the existing WebApiAuth and tmp_path fixtures but
monkeypatch/mock the authorization check used by the consolidated upload
endpoint (the function check_kb_team_permission in
api/apps/restful_apis/document_api.py) to return False for the target dataset,
then attempt the upload and assert the HTTP response is a 403 (or appropriate
error) and that check_kb_team_permission was invoked; ensure the test still
creates a temp file to upload and cleans up, and keep the test focused on
permission denial rather than full dataset setup.
- Around line 295-304: The test_thread_pool_errors currently exercises
unsupported file-type logic instead of the thread-pool error path; update the
test to simulate a failure from the thread pool by monkeypatching the call used
in document_api (e.g., thread_pool_exec or FileService.upload_document) to
return an error list (or raise/return the same shape the API expects), then call
upload_documents(WebApiAuth, {"kb_id": kb_id}, [fp]) and assert the response
code is 500 and the message contains "supported" or "type" (or otherwise
reflects the thread-pool error); target the monkeypatch to the symbol used in
api/apps/restful_apis/document_api.py (thread_pool_exec or
FileService.upload_document) so the API hits the error branch.
- Around line 306-316: The test test_empty_upload_result currently only asserts
"code" in res which is too weak; change the call to upload_documents(WebApiAuth,
{"kb_id": kb_id}, []) to force the empty-files branch (instead of passing a
single empty file path) and then assert the response represents an error (e.g.,
res.get("code") != 0 and "message" in res and that the message indicates no
files/empty upload). Update assertions around the upload_documents call to
explicitly check for an error code and an error message to validate the
empty-result path.
---
Nitpick comments:
In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`:
- Around line 127-131: Update the fragile assertions in test_invalid_kb_id to
avoid matching the full exception/router repr; keep the numeric check for
res["code"] == 100 and replace the exact message equality with a substring
assertion that the dataset id ("invalid_kb_id") or a stable phrase like "Can't
find the dataset" is present in res["message"]; locate the test_invalid_kb_id
test and the upload_documents call to adjust the assertion style (also apply the
same change to the other similar checks around lines 255-261).
🪄 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: 07d0e10e-05bb-4331-878b-8cccaa9b2a58
📒 Files selected for processing (3)
api/apps/restful_apis/document_api.pyapi/apps/sdk/doc.pytest/testcases/test_web_api/test_document_app/test_upload_documents.py
💤 Files with no reviewable changes (1)
- api/apps/sdk/doc.py
🚧 Files skipped from review as they are similar to previous changes (1)
- api/apps/restful_apis/document_api.py
| def test_no_permission(self, WebApiAuth, tmp_path): | ||
| """Test that no permission returns error""" | ||
| # Create a file and try to upload to a dataset we don't have access to | ||
| # This test would require setting up a dataset without permission | ||
| # For now, we skip this test as it requires specific setup | ||
| pytest.skip("Requires dataset without permission setup") |
There was a problem hiding this comment.
Please keep a real authorization test here.
Skipping this case drops coverage for the consolidated upload endpoint's check_kb_team_permission branch in api/apps/restful_apis/document_api.py. That branch is part of the refactor surface, so it should stay exercised with a focused fixture/monkeypatch setup instead of pytest.skip(...).
Based on learnings Applies to tests/**/*.py : Add/adjust tests for behavior changes.
🤖 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_upload_documents.py`
around lines 288 - 293, The skipped test test_no_permission should be turned
into a real auth failure test: use the existing WebApiAuth and tmp_path fixtures
but monkeypatch/mock the authorization check used by the consolidated upload
endpoint (the function check_kb_team_permission in
api/apps/restful_apis/document_api.py) to return False for the target dataset,
then attempt the upload and assert the HTTP response is a 403 (or appropriate
error) and that check_kb_team_permission was invoked; ensure the test still
creates a temp file to upload and cleans up, and keep the test focused on
permission denial rather than full dataset setup.
| def test_thread_pool_errors(self, WebApiAuth, add_dataset_func, tmp_path): | ||
| """Test that thread pool errors are handled""" | ||
| kb_id = add_dataset_func | ||
| # Upload a file with unsupported type | ||
| fp = tmp_path / "test.exe" | ||
| fp.write_text("test") | ||
| res = upload_documents(WebApiAuth, {"kb_id": kb_id}, [fp]) | ||
| # Should return error for unsupported file type | ||
| assert res["code"] == 500 | ||
| assert "unsupported type" in res["message"] | ||
| assert res["data"] == ["file1"] | ||
|
|
||
| def test_empty_upload_result(self, document_app_module, monkeypatch): | ||
| module = document_app_module | ||
| kb = SimpleNamespace(id="kb1", tenant_id="tenant1", name="kb", parser_id="parser", parser_config={}) | ||
| monkeypatch.setattr(module.KnowledgebaseService, "get_by_id", lambda _kb_id: (True, kb)) | ||
| monkeypatch.setattr(module, "check_kb_team_permission", lambda *_args, **_kwargs: True) | ||
|
|
||
| async def fake_thread_pool_exec(*_args, **_kwargs): | ||
| return (None, []) | ||
| assert "supported" in res["message"].lower() or "type" in res["message"].lower() |
There was a problem hiding this comment.
test_thread_pool_errors no longer exercises the thread-pool error path.
The current body just repeats unsupported file-type coverage already provided by test_unsupported_file_type, but it never hits the thread_pool_exec error branch in api/apps/restful_apis/document_api.py. Please restore a targeted failure by monkeypatching that call, or FileService.upload_document, to return an error list and assert the server-error response.
Based on learnings Applies to tests/**/*.py : Add/adjust tests for behavior changes.
🤖 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_upload_documents.py`
around lines 295 - 304, The test_thread_pool_errors currently exercises
unsupported file-type logic instead of the thread-pool error path; update the
test to simulate a failure from the thread pool by monkeypatching the call used
in document_api (e.g., thread_pool_exec or FileService.upload_document) to
return an error list (or raise/return the same shape the API expects), then call
upload_documents(WebApiAuth, {"kb_id": kb_id}, [fp]) and assert the response
code is 500 and the message contains "supported" or "type" (or otherwise
reflects the thread-pool error); target the monkeypatch to the symbol used in
api/apps/restful_apis/document_api.py (thread_pool_exec or
FileService.upload_document) so the API hits the error branch.
| def test_empty_upload_result(self, WebApiAuth, add_dataset_func, tmp_path): | ||
| """Test that empty upload result returns error""" | ||
| kb_id = add_dataset_func | ||
| # Create an empty file | ||
| fp = tmp_path / "empty.txt" | ||
| fp.write_text("") | ||
| res = upload_documents(WebApiAuth, {"kb_id": kb_id}, [fp]) | ||
| # Empty file might cause issues | ||
| # The exact behavior depends on the implementation | ||
| # Just verify we get a response | ||
| assert "code" in res |
There was a problem hiding this comment.
This assertion is too weak to catch regressions.
assert "code" in res will pass for almost any response, including the current success path, so the test no longer validates the if not files branch at all. Please force the empty-result path and assert the expected error code/message.
Based on learnings Applies to tests/**/*.py : Add/adjust tests for behavior changes.
🤖 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_upload_documents.py`
around lines 306 - 316, The test test_empty_upload_result currently only asserts
"code" in res which is too weak; change the call to upload_documents(WebApiAuth,
{"kb_id": kb_id}, []) to force the empty-files branch (instead of passing a
single empty file path) and then assert the response represents an error (e.g.,
res.get("code") != 0 and "message" in res and that the message indicates no
files/empty upload). Update assertions around the upload_documents call to
explicitly check for an error code and an error message to validate the
empty-result path.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14106 +/- ##
=======================================
Coverage 96.66% 96.66%
=======================================
Files 10 10
Lines 690 690
Branches 108 108
=======================================
Hits 667 667
Misses 8 8
Partials 15 15 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
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 283-287: The code treats a missing dataset (result of
KnowledgebaseService.get_by_id(dataset_id) where e is falsy) as a 5xx server
error by calling server_error_response; change this to a client/4xx response
(e.g., not_found_response or bad_request_response) so the API returns an
appropriate client error for an invalid/nonexistent dataset id. Update the
branch that currently logs and returns server_error_response to instead return
the chosen 4xx helper (keeping the logging/message but replacing
server_error_response with not_found_response/bad_request_response) and ensure
it references dataset_id, e, and kb as in the existing block.
🪄 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: 1be3146f-7fc0-43e5-979e-001b242ec413
📒 Files selected for processing (3)
api/apps/restful_apis/document_api.pyapi/apps/services/document_api_service.pyweb/src/hooks/use-document-request.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- web/src/hooks/use-document-request.ts
- api/apps/services/document_api_service.py
4333966 to
cfe7cf8
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
api/apps/restful_apis/document_api.py (1)
282-285:⚠️ Potential issue | 🟠 MajorReturn a client/domain error for an unknown dataset.
This branch is driven by request input, not an internal failure. Routing it through
server_error_response()makes an invaliddataset_idlook like a retriable server problem.💡 Suggested fix
e, kb = KnowledgebaseService.get_by_id(dataset_id) if not e: - logging.error(f"Can't find the dataset with ID {dataset_id}!") - return server_error_response(LookupError(f"Can't find the dataset with ID {dataset_id}!")) + logging.error("Can't find the dataset with ID %s!", dataset_id) + return get_error_data_result( + message=f"Can't find the dataset with ID {dataset_id}!", + code=RetCode.DATA_ERROR, + )🤖 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 282 - 285, The code currently treats a missing dataset (result of KnowledgebaseService.get_by_id(dataset_id)) as a server error by calling server_error_response; instead return a client/domain error (e.g., not_found_response or bad_request_response) so the client knows the dataset_id is invalid. Replace the server_error_response(...) call in the branch where KnowledgebaseService.get_by_id(dataset_id) returns no entity with the appropriate client error response function (preserving the same message that references dataset_id) so the handler for KnowledgebaseService.get_by_id and variable dataset_id remain the points of change.api/apps/services/document_api_service.py (1)
260-263:⚠️ Potential issue | 🟠 MajorNormalize
run_statusbefore the lookup.This branch only accepts string keys
"0"-"4", so values like3,TaskStatus.DONE.value, or already-normalized"DONE"all fall back to"0"and get returned asUNSTART. That can misreport persisted document state inmap_doc_keys().💡 Suggested fix
def _process_run_mapping(doc, run_status): """ Map document keys to match API response format. @@ run_mapping = { "0": "UNSTART", "1": "RUNNING", "2": "CANCEL", "3": "DONE", "4": "FAIL", } - # Handle run field - if run_status is None or run_status not in run_mapping.keys(): - run_status = "0" - - doc["run"] = run_mapping[run_status] + raw_status = getattr(run_status, "value", run_status) + status_text = None if raw_status is None else str(raw_status).upper() + + if status_text in run_mapping.values(): + doc["run"] = status_text + else: + doc["run"] = run_mapping.get(str(raw_status), "UNSTART") return doc🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/services/document_api_service.py` around lines 260 - 263, The code currently assumes run_status is a string key ("0"–"4"); normalize run_status before lookup in map_doc_keys(): if run_status is an int (e.g., 3) or an enum with a numeric .value, convert it to its numeric string (run_status = str(int(run_status)) ); if run_status is a string but is a named status (e.g., "DONE" or "Unstart"), do a reverse lookup on run_mapping (find the key whose value equals run_status.upper() or run_status) and set run_status to that key; finally use run_mapping[run_status] as before. Ensure you reference and modify the run_status variable and run_mapping lookup in map_doc_keys() (or the surrounding function) so persisted numeric and named statuses are handled correctly.
🤖 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 293-300: The current handler calling FileService.upload_document
via thread_pool_exec drops successful uploads when err is non-empty; update the
handler in document_api.py (the call using thread_pool_exec and variables err,
files) to return a partial-success response instead of a full error: if files
contains persisted documents, include them in the response payload along with
the err list (use get_error_data_result or create a new partial-success wrapper)
so clients can see which files committed and avoid duplicate retries;
alternatively, if you want strict atomicity, change FileService.upload_document
(the implementation at api/db/services/file_service.py) to perform a
transactional rollback on any failure and then keep the existing full-error
return — pick one approach and implement it consistently.
---
Duplicate comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 282-285: The code currently treats a missing dataset (result of
KnowledgebaseService.get_by_id(dataset_id)) as a server error by calling
server_error_response; instead return a client/domain error (e.g.,
not_found_response or bad_request_response) so the client knows the dataset_id
is invalid. Replace the server_error_response(...) call in the branch where
KnowledgebaseService.get_by_id(dataset_id) returns no entity with the
appropriate client error response function (preserving the same message that
references dataset_id) so the handler for KnowledgebaseService.get_by_id and
variable dataset_id remain the points of change.
In `@api/apps/services/document_api_service.py`:
- Around line 260-263: The code currently assumes run_status is a string key
("0"–"4"); normalize run_status before lookup in map_doc_keys(): if run_status
is an int (e.g., 3) or an enum with a numeric .value, convert it to its numeric
string (run_status = str(int(run_status)) ); if run_status is a string but is a
named status (e.g., "DONE" or "Unstart"), do a reverse lookup on run_mapping
(find the key whose value equals run_status.upper() or run_status) and set
run_status to that key; finally use run_mapping[run_status] as before. Ensure
you reference and modify the run_status variable and run_mapping lookup in
map_doc_keys() (or the surrounding function) so persisted numeric and named
statuses are handled correctly.
🪄 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: 7982e6c0-2be9-4336-8332-b18ef6443cff
📒 Files selected for processing (3)
api/apps/restful_apis/document_api.pyapi/apps/services/document_api_service.pyweb/src/hooks/use-document-request.ts
✅ Files skipped from review due to trivial changes (1)
- web/src/hooks/use-document-request.ts
| err, files = await thread_pool_exec( | ||
| FileService.upload_document, kb, file_objs, tenant_id, | ||
| parent_path=form.get("parent_path") | ||
| ) | ||
| if err: | ||
| msg = "\n".join(err) | ||
| logging.error(msg) | ||
| return get_error_data_result(message=msg, code=RetCode.SERVER_ERROR) |
There was a problem hiding this comment.
Don’t hide partial upload success behind a full-error response.
FileService.upload_document() can return both err and persisted documents in files (api/db/services/file_service.py:432-518). This branch drops the successful uploads and returns a full error anyway, so a client retry can duplicate documents that already committed. Either make the batch atomic or return an explicit partial-success payload.
🤖 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 293 - 300, The current
handler calling FileService.upload_document via thread_pool_exec drops
successful uploads when err is non-empty; update the handler in document_api.py
(the call using thread_pool_exec and variables err, files) to return a
partial-success response instead of a full error: if files contains persisted
documents, include them in the response payload along with the err list (use
get_error_data_result or create a new partial-success wrapper) so clients can
see which files committed and avoid duplicate retries; alternatively, if you
want strict atomicity, change FileService.upload_document (the implementation at
api/db/services/file_service.py) to perform a transactional rollback on any
failure and then keep the existing full-error return — pick one approach and
implement it consistently.
cfe7cf8 to
7d70bce
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (2)
api/apps/restful_apis/document_api.py (1)
297-300:⚠️ Potential issue | 🟠 MajorPartial upload success is discarded when any file fails.
Per
FileService.upload_document(context snippet 3), botherrandfilescan contain data when some uploads succeed and others fail. The current logic returns an error response whenerris non-empty, discarding any successfully uploaded documents infiles. This can cause:
- Client retries that duplicate already-committed documents
- Loss of visibility into which files succeeded
Consider returning a partial-success response that includes both the error messages and the successfully uploaded files.
💡 Suggested approach
if err: + # Return partial success if some files were uploaded + if files: + files = [f[0] for f in files] + return_raw_files = request.args.get("return_raw_files", "false").lower() == "true" + if return_raw_files: + return get_error_data_result( + message="\n".join(err), + code=RetCode.SERVER_ERROR, + data=files + ) + renamed_doc_list = [map_doc_keys_with_run_status(doc, run_status="0") for doc in files] + return get_error_data_result( + message="\n".join(err), + code=RetCode.SERVER_ERROR, + data=renamed_doc_list + ) msg = "\n".join(err) logging.error(msg) return get_error_data_result(message=msg, code=RetCode.SERVER_ERROR)🤖 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 297 - 300, The current branch in document_api.py returns an error and discards successful uploads when FileService.upload_document returns both err and files; change the logic to detect partial success (err and files both non-empty), log errors, and return a partial-success response that includes the error messages and the list of successfully uploaded files instead of calling get_error_data_result alone; update the branch around the err/files check (reference variables err, files and function FileService.upload_document) to build and return a combined payload (e.g., include an "errors" array plus the "files" array or use the existing success response wrapper with an added errors field) so the client can see which files succeeded and which failed.api/apps/services/document_api_service.py (1)
238-264:⚠️ Potential issue | 🟠 MajorAlready-normalized
runvalues are overwritten to "UNSTART".When
map_doc_keys(doc)is called on a document that already has a textualrunvalue (e.g.,"DONE","RUNNING"), the value is passed to_process_run_mappingat line 183. Since"DONE"is not a key inrun_mapping(which only has numeric string keys"0"through"4"), line 260-261 defaults it to"0", incorrectly resetting the status to"UNSTART".This affects the
PATCHendpoint at line 146 indocument_api.py.🐛 Suggested fix
def _process_run_mapping(doc, run_status): run_mapping = { "0": "UNSTART", "1": "RUNNING", "2": "CANCEL", "3": "DONE", "4": "FAIL", } + # If run_status is already a normalized value, preserve it + if run_status in run_mapping.values(): + doc["run"] = run_status + return doc # Handle run field if run_status is None or run_status not in run_mapping.keys(): run_status = "0" doc["run"] = run_mapping[run_status] return doc🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/apps/services/document_api_service.py` around lines 238 - 264, The _process_run_mapping function currently only recognizes numeric-string keys ("0"-"4") and overwrites already-normalized textual run values (e.g., "DONE", "RUNNING") to "UNSTART"; update _process_run_mapping to accept both numeric keys and already-normalized textual values: if run_status is one of the mapping values leave it unchanged, else if it matches a mapping key convert it via run_mapping, otherwise default to "UNSTART". Refer to _process_run_mapping and any callers like map_doc_keys to implement this check and then set doc["run"] appropriately.
🧹 Nitpick comments (1)
web/src/hooks/use-document-request.ts (1)
68-70: Return value missingdatafield for TypeScript type safety.The early return
{ code: 500, message: 'Dataset ID is required' }doesn't include thedatafield, which may cause TypeScript to complain or lead to undefined access when consumers expectResponseType<IDocumentInfo[]>.🛡️ Suggested fix
if (!id) { - return { code: 500, message: 'Dataset ID is required' }; + return { code: 500, message: 'Dataset ID is required', data: [] }; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/hooks/use-document-request.ts` around lines 68 - 70, The early return in use-document-request (the block that currently returns { code: 500, message: 'Dataset ID is required' }) is missing the required data field for ResponseType<IDocumentInfo[]>; update that return to include a properly typed empty data value (e.g., data: [] or the appropriate empty payload) so the function's return shape matches ResponseType<IDocumentInfo[]> and avoids TypeScript errors — locate the early-return inside the function in web/src/hooks/use-document-request.ts and add the data property to the returned object.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 297-300: The current branch in document_api.py returns an error
and discards successful uploads when FileService.upload_document returns both
err and files; change the logic to detect partial success (err and files both
non-empty), log errors, and return a partial-success response that includes the
error messages and the list of successfully uploaded files instead of calling
get_error_data_result alone; update the branch around the err/files check
(reference variables err, files and function FileService.upload_document) to
build and return a combined payload (e.g., include an "errors" array plus the
"files" array or use the existing success response wrapper with an added errors
field) so the client can see which files succeeded and which failed.
In `@api/apps/services/document_api_service.py`:
- Around line 238-264: The _process_run_mapping function currently only
recognizes numeric-string keys ("0"-"4") and overwrites already-normalized
textual run values (e.g., "DONE", "RUNNING") to "UNSTART"; update
_process_run_mapping to accept both numeric keys and already-normalized textual
values: if run_status is one of the mapping values leave it unchanged, else if
it matches a mapping key convert it via run_mapping, otherwise default to
"UNSTART". Refer to _process_run_mapping and any callers like map_doc_keys to
implement this check and then set doc["run"] appropriately.
---
Nitpick comments:
In `@web/src/hooks/use-document-request.ts`:
- Around line 68-70: The early return in use-document-request (the block that
currently returns { code: 500, message: 'Dataset ID is required' }) is missing
the required data field for ResponseType<IDocumentInfo[]>; update that return to
include a properly typed empty data value (e.g., data: [] or the appropriate
empty payload) so the function's return shape matches
ResponseType<IDocumentInfo[]> and avoids TypeScript errors — locate the
early-return inside the function in web/src/hooks/use-document-request.ts and
add the data property to the returned object.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 7c71d130-7901-4f97-92bf-4c27ce3d59ee
📒 Files selected for processing (4)
admin/client/ragflow_client.pyapi/apps/restful_apis/document_api.pyapi/apps/services/document_api_service.pyweb/src/hooks/use-document-request.ts
76df14d to
e018f85
Compare
e018f85 to
04339b7
Compare
### What problem does this PR solve? Consolidation WEB API & HTTP API for document upload Before consolidation Web API: POST /v1/document/upload Http API - POST /api/v1/datasets/<dataset_id>/documents After consolidation, Restful API -- POST /api/v1/datasets/<dataset_id>/documents ### Type of change - [x] Refactoring
What problem does this PR solve?
Consolidation WEB API & HTTP API for document upload
Before consolidation
Web API: POST /v1/document/upload
Http API - POST /api/v1/datasets/<dataset_id>/documents
After consolidation, Restful API -- POST /api/v1/datasets/<dataset_id>/documents
Type of change