Repository navigation
Refactor: Migrate document metadata config update API - #14286
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughRemoved the legacy POST Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Client
participant REST_API as REST API
participant KB as KnowledgebaseService
participant DOC as DocumentService
Client->>REST_API: PUT /datasets/{dataset_id}/documents/{document_id}/metadata/config\nBody: { metadata: ... }
REST_API->>KB: query(dataset_id, tenant_id) -- verify ownership
KB-->>REST_API: dataset (or empty)
REST_API->>DOC: query(id=document_id, kb_id=dataset_id) -- verify doc exists
DOC-->>REST_API: document (or empty)
REST_API->>DOC: update_parser_config(doc.id, { metadata: ... })
DOC-->>REST_API: success/failure
REST_API->>DOC: get_by_id(doc.id)
DOC-->>REST_API: updated document
REST_API-->>Client: 200 { data: updated_document } / error
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
web/src/pages/dataset/components/metedata/hooks/use-manage-modal.ts (1)
433-454:⚠️ Potential issue | 🟡 MinorMissing
idin useCallback deps.
idfromuseParams()is referenced inside the callback but not listed in the dependency array. ESLint'sreact-hooks/exhaustive-depswill flag this, and it's technically incorrect if the route param ever changes while the hook is mounted.- [tableData, t, otherData], + [tableData, t, otherData, id],Also double-check the payload shape end-to-end: this sends
data: { metadata: data }toupdateDocumentMetaDataConfig, which then callsrequest.put(url, { data: { ...data } }). The backend readsreq["metadata"]directly, so the body ultimately sent over the wire must be{ metadata: ... }and not{ data: { metadata: ... } }. See the related comment ondocument_api.py.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/pages/dataset/components/metedata/hooks/use-manage-modal.ts` around lines 433 - 454, handleSaveSingleFileSettings references id but it’s missing from the dependency array and the payload is double-nested; add id to the useCallback deps and ensure the request body ends up as { metadata: ... } by passing a root-level payload to updateDocumentMetaDataConfig (e.g. payload = { metadata: data }) and adjust updateDocumentMetaDataConfig so it sends that object as the request body (avoid wrapping it again under a data key). Locate handleSaveSingleFileSettings and updateDocumentMetaDataConfig to make these two changes.
🧹 Nitpick comments (1)
web/src/services/knowledge-service.ts (1)
283-294: Consider passingdatadirectly instead of spreading.
{ data: { ...data } }is equivalent to{ data }here, and matches the convention used byupdateKb(line 205-206). A direct pass is clearer and slightly cheaper.- request.put(api.documentUpdateMetaDataConfig(kb_id, doc_id), { - data: { ...data }, - }); + request.put(api.documentUpdateMetaDataConfig(kb_id, doc_id), { data });Also consider typing
datamore precisely thanany(e.g.,{ metadata: IMetaDataReturnJSONSettings }) to catch shape regressions at compile time.🤖 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 283 - 294, The updateDocumentMetaDataConfig function currently spreads data into the request body ({ data: { ...data } }); change this to pass data directly (use { data } as the request body) to match the updateKb convention and avoid unnecessary copying, and replace the loose any type for the parameter with a more precise type (e.g., { metadata: IMetaDataReturnJSONSettings } or an appropriate interface) to enforce shape checks; update the function signature (updateDocumentMetaDataConfig) and its parameter typing, and ensure the request call uses api.documentUpdateMetaDataConfig(kb_id, doc_id) with { data } as the payload.
🤖 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 821-887: Fix three things in update_metadata_config: add logging
calls for permission failure, document-not-found, and successful update (use
logging.error(...) or logging.info(...) consistent with update_document), wrap
the DB calls DocumentService.update_parser_config and DocumentService.get_by_id
in try/except OperationalError and log exception with logging.exception(e) then
return an appropriate get_data_error_result/get_error_data_result, and correct
the decorator comma spacing to "/metadata/config", methods=["PUT"]; reference
update_metadata_config, KnowledgebaseService.query, DocumentService.query,
DocumentService.update_parser_config, DocumentService.get_by_id,
get_request_json, get_error_data_result, get_error_argument_result,
get_data_error_result, and get_result when making these changes.
---
Outside diff comments:
In `@web/src/pages/dataset/components/metedata/hooks/use-manage-modal.ts`:
- Around line 433-454: handleSaveSingleFileSettings references id but it’s
missing from the dependency array and the payload is double-nested; add id to
the useCallback deps and ensure the request body ends up as { metadata: ... } by
passing a root-level payload to updateDocumentMetaDataConfig (e.g. payload = {
metadata: data }) and adjust updateDocumentMetaDataConfig so it sends that
object as the request body (avoid wrapping it again under a data key). Locate
handleSaveSingleFileSettings and updateDocumentMetaDataConfig to make these two
changes.
---
Nitpick comments:
In `@web/src/services/knowledge-service.ts`:
- Around line 283-294: The updateDocumentMetaDataConfig function currently
spreads data into the request body ({ data: { ...data } }); change this to pass
data directly (use { data } as the request body) to match the updateKb
convention and avoid unnecessary copying, and replace the loose any type for the
parameter with a more precise type (e.g., { metadata:
IMetaDataReturnJSONSettings } or an appropriate interface) to enforce shape
checks; update the function signature (updateDocumentMetaDataConfig) and its
parameter typing, and ensure the request call uses
api.documentUpdateMetaDataConfig(kb_id, doc_id) with { data } as the payload.
🪄 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: 18cfa48b-26b5-4c10-ab16-d7337e6c7df1
📒 Files selected for processing (5)
api/apps/document_app.pyapi/apps/restful_apis/document_api.pyweb/src/pages/dataset/components/metedata/hooks/use-manage-modal.tsweb/src/services/knowledge-service.tsweb/src/utils/api.ts
💤 Files with no reviewable changes (1)
- api/apps/document_app.py
| @manager.route("/datasets/<dataset_id>/documents/<document_id>/metadata/config",methods=["PUT"]) # noqa: F821 | ||
| @login_required | ||
| @add_tenant_id_to_kwargs | ||
| async def update_metadata_config(tenant_id, dataset_id, document_id): | ||
| """ | ||
| Update document metadata configuration. | ||
| --- | ||
| tags: | ||
| - Documents | ||
| security: | ||
| - ApiKeyAuth: [] | ||
| parameters: | ||
| - in: path | ||
| name: dataset_id | ||
| type: string | ||
| required: true | ||
| description: ID of the dataset. | ||
| - in: path | ||
| name: document_id | ||
| type: string | ||
| required: true | ||
| description: ID of the document. | ||
| - in: header | ||
| name: Authorization | ||
| type: string | ||
| required: true | ||
| description: Bearer token for authentication. | ||
| - in: body | ||
| name: body | ||
| description: Metadata configuration. | ||
| required: true | ||
| schema: | ||
| type: object | ||
| properties: | ||
| metadata: | ||
| type: object | ||
| description: Metadata configuration JSON. | ||
| responses: | ||
| 200: | ||
| description: Document updated successfully. | ||
| """ | ||
| # Verify ownership and existence of dataset | ||
| if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id): | ||
| return get_error_data_result(message="You don't own the dataset.") | ||
|
|
||
| # Verify document exists in the dataset | ||
| doc = DocumentService.query(id=document_id, kb_id=dataset_id) | ||
| if not doc: | ||
| return get_error_data_result( | ||
| message=f"Document {document_id} not found in dataset {dataset_id}" | ||
| ) | ||
| doc = doc[0] | ||
|
|
||
| # Get request body | ||
| req = await get_request_json() | ||
| if "metadata" not in req: | ||
| return get_error_argument_result(message="metadata is required") | ||
|
|
||
| # Update parser config with metadata | ||
| DocumentService.update_parser_config(doc.id, {"metadata": req["metadata"]}) | ||
|
|
||
| # Get updated document | ||
| e, doc = DocumentService.get_by_id(doc.id) | ||
| if not e: | ||
| return get_data_error_result(message="Document not found!") | ||
|
|
||
| return get_result(data=doc.to_dict()) No newline at end of file |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify get_error_argument_result signature and how `request.put` body is serialized
ast-grep --pattern 'def get_error_argument_result($$$): $$$'
rg -nP -C2 'get_error_argument_result\s*\('
rg -nP -C3 "request\.put\s*\(" web/src/utils/request.ts web/src/utils/request.js 2>/dev/null
fd -t f 'request.(ts|js)' web/src/utilsRepository: infiniflow/ragflow
Length of output: 7545
🏁 Script executed:
# Check request.ts to understand request.put body serialization
cat web/src/utils/request.tsRepository: infiniflow/ragflow
Length of output: 4751
🏁 Script executed:
# Check use-manage-modal.ts and knowledge-service.ts for payload wrapping
fd -type f -name 'use-manage-modal.ts' web/
fd -type f -name 'knowledge-service.ts' web/Repository: infiniflow/ragflow
Length of output: 403
🏁 Script executed:
# Check logging patterns in document_api.py and try/except usage around DocumentService calls
rg -n "logging\.(error|info|exception)" api/apps/restful_apis/document_api.py | head -20
rg -nB2 -A2 "DocumentService\.(get_by_id|update_parser_config|query)" api/apps/restful_apis/document_api.py | head -50Repository: infiniflow/ragflow
Length of output: 2631
🏁 Script executed:
# Check if update_document (mentioned in review) uses try/except for OperationalError
rg -nB5 -A10 "def update_document" api/apps/restful_apis/document_api.pyRepository: infiniflow/ragflow
Length of output: 537
🏁 Script executed:
# The put function in request.ts is empty - check if there's another implementation
rg -n "export const put" web/src/utils/
cat web/src/utils/next-request.ts | grep -A5 "put"Repository: infiniflow/ragflow
Length of output: 211
🏁 Script executed:
# Find the frontend caller for metadata config update
find web -name 'use-manage-modal.ts' 2>/dev/null
find web -name 'knowledge-service.ts' 2>/dev/null
fd 'use-manage-modal' web/
fd 'knowledge-service' web/Repository: infiniflow/ragflow
Length of output: 273
🏁 Script executed:
# Check if there's a way the frontend actually calls PUT - maybe using request directly
rg "request\.put|updateMetadataConfig|metadata.*config" web/src/ --type ts --type tsx -n | head -30Repository: infiniflow/ragflow
Length of output: 89
🏁 Script executed:
# Double-check the update_document handler for try/except pattern to compare
sed -n '45,160p' api/apps/restful_apis/document_api.pyRepository: infiniflow/ragflow
Length of output: 4307
🏁 Script executed:
# Check use-manage-modal.ts for how it calls the metadata config update
cat web/src/pages/dataset/components/metedata/hooks/use-manage-modal.tsRepository: infiniflow/ragflow
Length of output: 14937
🏁 Script executed:
# Check knowledge-service.ts for the service wrapper
cat web/src/services/knowledge-service.ts | head -350Repository: infiniflow/ragflow
Length of output: 7404
🏁 Script executed:
# Check how request.put works in umi-request context (it's a method on request object, not the exported function)
# Let's verify the payload flow one more time by checking a working PUT endpoint
rg -n "request\.put\(" web/src/services/ -A2 | head -30Repository: infiniflow/ragflow
Length of output: 1739
🏁 Script executed:
# Verify the exact line in use-manage-modal.ts where updateDocumentMetaDataConfig is called
sed -n '435,450p' web/src/pages/dataset/components/metedata/hooks/use-manage-modal.tsRepository: infiniflow/ragflow
Length of output: 531
🏁 Script executed:
# Check if there are other endpoints in document_api.py that don't use try/except for DocumentService calls
rg -n "DocumentService\." api/apps/restful_apis/document_api.py | grep -v "try\|except" | head -20Repository: infiniflow/ragflow
Length of output: 855
Add logging and error handling to update_metadata_config.
-
Missing logging for new flow. Per coding guidelines ("Add logging for new flows"), this endpoint needs logging for permission failures, not-found, and successful update. Compare with the
update_documenthandler above which useslogging.error(...)andlogging.exception(e). -
No error handling around DB calls.
update_documentwrapsDocumentService.get_by_idintry/except OperationalError(lines 145–151). This handler should do the same for bothupdate_parser_configandget_by_idat lines 880 and 883. -
Minor spacing issue at line 821: missing space after the comma in
"/metadata/config",methods=["PUT"]— should be"/metadata/config", methods=["PUT"].
🤖 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 821 - 887, Fix three
things in update_metadata_config: add logging calls for permission failure,
document-not-found, and successful update (use logging.error(...) or
logging.info(...) consistent with update_document), wrap the DB calls
DocumentService.update_parser_config and DocumentService.get_by_id in try/except
OperationalError and log exception with logging.exception(e) then return an
appropriate get_data_error_result/get_error_data_result, and correct the
decorator comma spacing to "/metadata/config", methods=["PUT"]; reference
update_metadata_config, KnowledgebaseService.query, DocumentService.query,
DocumentService.update_parser_config, DocumentService.get_by_id,
get_request_json, get_error_data_result, get_error_argument_result,
get_data_error_result, and get_result when making these changes.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14286 +/- ##
=======================================
Coverage 95.97% 95.97%
=======================================
Files 10 10
Lines 695 695
Branches 111 111
=======================================
Hits 667 667
Misses 11 11
Partials 17 17 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
test/testcases/test_web_api/test_document_app/test_document_metadata.py (1)
185-190:⚠️ Potential issue | 🔴 CriticalUpdate the remaining old metadata-setting call.
This test still calls
document_update_metadata_settingwith the removed payload-only signature, so it will raiseTypeErrorbefore asserting the missing-metadata response. The new backend path also returns"metadata is required"for this case.🐛 Proposed fix
`@pytest.mark.p3` def test_update_metadata_setting_missing_metadata(self, WebApiAuth, add_document_func): - _, doc_id = add_document_func - res = document_update_metadata_setting(WebApiAuth, {"doc_id": doc_id}) + dataset_id, doc_id = add_document_func + res = document_update_metadata_setting(WebApiAuth, dataset_id, doc_id, {}) assert res["code"] == 101, res - assert "required argument are missing" in res["message"], res + assert "metadata is required" in res["message"], res assert "metadata" in res["message"], resBased 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_document_metadata.py` around lines 185 - 190, The test calls the old payload-only signature of document_update_metadata_setting and raises TypeError; update the call to use the new signature by passing explicit doc_id and a missing metadata value (e.g. document_update_metadata_setting(WebApiAuth, doc_id=doc_id, metadata=None)) so the backend returns the expected error payload, then assert res["code"] == 101 and that res["message"] contains "metadata is required" (and still reference the test name test_update_metadata_setting_missing_metadata and function document_update_metadata_setting when editing).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@test/testcases/test_web_api/test_document_app/test_document_metadata.py`:
- Around line 185-190: The test calls the old payload-only signature of
document_update_metadata_setting and raises TypeError; update the call to use
the new signature by passing explicit doc_id and a missing metadata value (e.g.
document_update_metadata_setting(WebApiAuth, doc_id=doc_id, metadata=None)) so
the backend returns the expected error payload, then assert res["code"] == 101
and that res["message"] contains "metadata is required" (and still reference the
test name test_update_metadata_setting_missing_metadata and function
document_update_metadata_setting when editing).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 97b19cee-292e-4be5-80aa-749bf2a76972
📒 Files selected for processing (2)
test/testcases/test_web_api/test_common.pytest/testcases/test_web_api/test_document_app/test_document_metadata.py
What problem does this PR solve?
Before migration
Web API: POST /v1/document/update_metadata_setting
After consolidation, Restful API
PUT /api/v1/datasets/<dataset_id>/documents/<document_id>/metadata/config
Type of change