Skip to content

Refactor: Migrate document metadata config update API - #14286

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
xugangqiang:doc-metadata-config-update
Apr 22, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
xugangqiang:doc-metadata-config-update

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Refactoring

@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7324c75e-205c-46d9-a716-feecedd9f239

📥 Commits

Reviewing files that changed from the base of the PR and between bfb55c4 and ce8cd3c.

📒 Files selected for processing (1)
  • api/apps/restful_apis/document_api.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/restful_apis/document_api.py

📝 Walkthrough

Walkthrough

Removed the legacy POST /update_metadata_setting endpoint and introduced a dataset-scoped PUT endpoint at /api/v1/datasets/<dataset_id>/documents/<document_id>/metadata/config. Backend, frontend service calls, API constants, and tests were updated to use the new route and request shape.

Changes

Cohort / File(s) Summary
Backend - legacy route removed / new REST endpoint added
api/apps/document_app.py, api/apps/restful_apis/document_api.py
Removed POST /update_metadata_setting handler from document_app.py. Added PUT /datasets/<dataset_id>/documents/<document_id>/metadata/config in document_api.py which validates tenant/dataset, locates the document, calls DocumentService.update_parser_config(doc.id, {"metadata": ...}), and returns the updated document.
Frontend - API constants & service
web/src/utils/api.ts, web/src/services/knowledge-service.ts
Replaced documentUpdateMetaData string with documentUpdateMetaDataConfig(datasetId, documentId) and removed old documentUpdateMetaData method. Added updateDocumentMetaDataConfig service that issues a PUT to the new REST URL with body { data: { ... } }.
Frontend - hook usage
web/src/pages/dataset/components/metedata/hooks/use-manage-modal.ts
Switched from kbService.documentUpdateMetaData to updateDocumentMetaDataConfig, included kb_id route id in call, and changed payload to { data: { metadata: ... } }.
Tests
test/testcases/test_web_api/test_common.py, test/testcases/test_web_api/test_document_app/test_document_metadata.py
Updated test helper to call new PUT URL with dataset_id and doc_id. Replaced a legacy unit test with an integration negative test asserting "Document not found!" after deletion.
Minor non-functional edits
api/apps/restful_apis/document_api.py
Whitespace/comment updates in upload_document() and _parse_doc_id_filter_with_metadata() (no logic 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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

☯️ refactor, 🐖api, 🧪 test, 🧰 typescript, 🌈 python

Suggested reviewers

  • yuzhichang
  • JinHai-CN
  • yingfeng

Poem

🐰 I hop from POST to tidy PUT,
datasets lined up, metadata takes root.
KB checks, parsers wake, documents refreshed,
small hops, big change — a carrot-fueled quest. 🥕

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.15% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description is incomplete. It shows the before/after API endpoints but lacks explanation of the problem being solved, rationale for the migration, and implementation details. Add context about why this migration is necessary (e.g., API consolidation strategy, consistency improvements) and briefly explain the scope of changes across the codebase.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: migrating the document metadata config update API from Web API to a RESTful API endpoint.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@xugangqiang xugangqiang added the ci Continue Integration label Apr 22, 2026
@xugangqiang
xugangqiang marked this pull request as ready for review April 22, 2026 04:51
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 22, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 | 🟡 Minor

Missing id in useCallback deps.

id from useParams() is referenced inside the callback but not listed in the dependency array. ESLint's react-hooks/exhaustive-deps will 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 } to updateDocumentMetaDataConfig, which then calls request.put(url, { data: { ...data } }). The backend reads req["metadata"] directly, so the body ultimately sent over the wire must be { metadata: ... } and not { data: { metadata: ... } }. See the related comment on document_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 passing data directly instead of spreading.

{ data: { ...data } } is equivalent to { data } here, and matches the convention used by updateKb (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 data more precisely than any (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

📥 Commits

Reviewing files that changed from the base of the PR and between 61d756e and f878d2c.

📒 Files selected for processing (5)
  • api/apps/document_app.py
  • api/apps/restful_apis/document_api.py
  • web/src/pages/dataset/components/metedata/hooks/use-manage-modal.ts
  • web/src/services/knowledge-service.ts
  • web/src/utils/api.ts
💤 Files with no reviewable changes (1)
  • api/apps/document_app.py

Comment thread api/apps/restful_apis/document_api.py Outdated
Comment on lines +821 to +887
@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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 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/utils

Repository: infiniflow/ragflow

Length of output: 7545


🏁 Script executed:

# Check request.ts to understand request.put body serialization
cat web/src/utils/request.ts

Repository: 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 -50

Repository: 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.py

Repository: 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 -30

Repository: 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.py

Repository: 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.ts

Repository: infiniflow/ragflow

Length of output: 14937


🏁 Script executed:

# Check knowledge-service.ts for the service wrapper
cat web/src/services/knowledge-service.ts | head -350

Repository: 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 -30

Repository: 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.ts

Repository: 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 -20

Repository: infiniflow/ragflow

Length of output: 855


Add logging and error handling to update_metadata_config.

  1. 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_document handler above which uses logging.error(...) and logging.exception(e).

  2. No error handling around DB calls. update_document wraps DocumentService.get_by_id in try/except OperationalError (lines 145–151). This handler should do the same for both update_parser_config and get_by_id at lines 880 and 883.

  3. 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

codecov Bot commented Apr 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.97%. Comparing base (61d756e) to head (eff72ed).
⚠️ Report is 11 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@xugangqiang xugangqiang changed the title WIP migrate WIP migrate document metadata config update API Apr 22, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 | 🔴 Critical

Update the remaining old metadata-setting call.

This test still calls document_update_metadata_setting with the removed payload-only signature, so it will raise TypeError before 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"], res

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_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

📥 Commits

Reviewing files that changed from the base of the PR and between f878d2c and bfb55c4.

📒 Files selected for processing (2)
  • test/testcases/test_web_api/test_common.py
  • test/testcases/test_web_api/test_document_app/test_document_metadata.py

@xugangqiang xugangqiang changed the title WIP migrate document metadata config update API Refactor: Migrate document metadata config update API Apr 22, 2026
@xugangqiang xugangqiang self-assigned this Apr 22, 2026
@xugangqiang

Copy link
Copy Markdown
Contributor Author

@JinHai-CN
JinHai-CN merged commit c08cd8e into infiniflow:main Apr 22, 2026
1 check passed
@xugangqiang
xugangqiang deleted the doc-metadata-config-update branch May 15, 2026 06:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants