Skip to content

Merge document metadata summary APIs into one Restful API - #14001

Merged
yuzhichang merged 9 commits into
infiniflow:mainfrom
xugangqiang:merge-metadata-summary
Apr 10, 2026
Merged

yuzhichang merged 9 commits into
infiniflow:mainfrom
xugangqiang:merge-metadata-summary

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Consolidation WEB API & HTTP API for document metadata summary

Before consolidation
Web API: POST /api/v1/document/metadata/summary
Http API - GET /v1/datasets/<dataset_id>/metadata/summary

After consolidation, Restful API -- GET /v1/datasets/<dataset_id>/metadata/summary

Type of change

  • Refactoring

@coderabbitai

coderabbitai Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Migrates the metadata-summary flow from a legacy POST /metadata/summary to a RESTful GET /datasets/<dataset_id>/metadata/summary; removes old handlers in document_app/SDK, adds new handler in restful_apis, updates frontend to call dataset-scoped GET with query doc_ids, and adapts tests accordingly.

Changes

Cohort / File(s) Summary
Backend: route removal
api/apps/document_app.py
Removed legacy POST endpoints /metadata/summary and /set_meta (handlers deleted).
Backend: new RESTful handler
api/apps/restful_apis/document_api.py
Added GET /datasets/<dataset_id>/metadata/summary with @login_required, tenant injection, KnowledgebaseService.accessible() check, optional doc_ids parsed from comma-separated query param, calls DocMetadataService.get_metadata_summary, and unified server_error_response error handling.
Backend: SDK route removed
api/apps/sdk/doc.py
Deleted SDK metadata_summary route handler (GET /datasets/<dataset_id>/metadata/summary).
Frontend: API surface & client calls
web/src/utils/api.ts, web/src/services/knowledge-service.ts
getMetaData changed from a static URL to getMetaData(datasetId) returning /datasets/{datasetId}/metadata/summary; client switches from POST body to GET with optional doc_ids comma-separated query param.
Tests: enable and expand metadata-summary tests
test/testcases/test_http_api/test_file_management_within_dataset/test_metadata_summary.py
Activated and expanded tests: cover missing dataset id (404), unauthorized dataset id (code 102), successful summary (code 0), and precise metadata counts; updated fixtures/usage accordingly.
Tests: unit adjustments
test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
Removed unit assertions/mocks for metadata_summary, renamed test to test_metadata_batch_update, retained batch-update-related tests.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Client (Browser / Frontend)
  participant FrontendSvc as KnowledgeService
  participant API as REST API (/datasets/:id/metadata/summary)
  participant KB as KnowledgebaseService
  participant DocMeta as DocMetadataService

  Client->>FrontendSvc: getMetaData(kb_id, doc_ids?)
  FrontendSvc->>API: GET /datasets/{kb_id}/metadata/summary?doc_ids=...
  API->>KB: accessible(kb_id, tenant_id)
  KB-->>API: allowed / denied
  alt allowed
    API->>DocMeta: get_metadata_summary(kb_id, doc_ids?)
    DocMeta-->>API: summary
    API-->>FrontendSvc: { code:0, data:{summary} }
    FrontendSvc-->>Client: display summary
  else denied
    API-->>FrontendSvc: { code:102, message: "You don't own the dataset ..." }
    FrontendSvc-->>Client: show error
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Suggested labels

☯️ refactor

Suggested reviewers

  • asiroliu
  • JinHai-CN
  • yongtenglei

Poem

🐰 Hopping endpoints, quick and merry,

From body to query the pathways we carry,
GET now sings where POST once lay,
Datasets tidy, counts at play,
A rabbit cheers the code today.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: consolidating separate document metadata summary APIs into a single RESTful API, which aligns with the refactoring objective.
Docstring Coverage ✅ Passed Docstring coverage is 85.71% which is sufficient. The required threshold is 80.00%.
Description check ✅ Passed The pull request description adequately addresses the consolidation objective and includes required template sections.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@xugangqiang xugangqiang added the ci Continue Integration label Apr 9, 2026
@xugangqiang
xugangqiang marked this pull request as ready for review April 9, 2026 06:45
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐖api The modified files are located under directory 'api/apps/sdk' 🧪 test Pull requests that update test cases. labels Apr 9, 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: 3

🧹 Nitpick comments (1)
test/testcases/test_http_api/test_file_management_within_dataset/test_metadata_summary.py (1)

60-81: Add a doc_ids-filtered assertion to cover the new API contract.

The endpoint migration changed how filtering is passed (doc_ids query param), but current tests only call unfiltered metadata summary.

💡 Suggested addition
         res = metadata_summary(HttpApiAuth, dataset_id)
         assert res["code"] == 0, res

         summary = res["data"]["summary"]
         counts = _summary_to_counts(summary)
@@
         assert counts["author"]["bob"] == 1, counts
         assert "None" not in counts["author"], counts
+
+        # verify query-param filtering path
+        filtered_res = metadata_summary(
+            HttpApiAuth,
+            dataset_id,
+            params={"doc_ids": ",".join(document_ids[:2])},
+        )
+        assert filtered_res["code"] == 0, filtered_res
+        filtered_counts = _summary_to_counts(filtered_res["data"]["summary"])
+        assert "baz" not in filtered_counts.get("tags", {}), filtered_counts
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_http_api/test_file_management_within_dataset/test_metadata_summary.py`
around lines 60 - 81, The test test_metadata_summary_counts currently only
asserts unfiltered metadata_summary behavior; update it to also call
metadata_summary with the new doc_ids filtering contract and assert counts
reflect only the provided doc_ids. After creating docs via add_documents_func
and updating with update_document, invoke metadata_summary(HttpApiAuth,
dataset_id, doc_ids=[...]) (use a subset of document_ids, e.g., first two) then
convert with _summary_to_counts and assert tag/author counts match the filtered
subset (e.g., "foo"==2,"bar"==1, etc.). Ensure the new assertion checks that
"None" is not present for author in filtered results as well.
🤖 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 177-178: Normalize parsing of doc_ids by splitting doc_ids_param
on commas, stripping whitespace from each token and filtering out empty strings
so blank entries like "" or tokens with leading/trailing spaces are removed;
replace the current doc_ids assignment (using doc_ids_param.split(",") if
doc_ids_param else None) with code that maps strip() over tokens and keeps only
non-empty tokens, and set doc_ids to None if the resulting list is empty (use
the variables doc_ids_param and doc_ids to locate and update the logic).
- Around line 148-183: Add flow-level logging to metadata_summary: log an entry
at start (include dataset_id, tenant_id and parsed doc_ids), log an
access-denied message when KnowledgebaseService.accessible(...) returns False,
log a success message after DocMetadataService.get_metadata_summary(...) before
returning get_result, and log the exception (with stack/exception details) in
the except block before calling server_error_response; refer to function
metadata_summary and the calls to KnowledgebaseService.accessible,
DocMetadataService.get_metadata_summary, get_result, and server_error_response
to locate insertion points.

In
`@test/testcases/test_http_api/test_file_management_within_dataset/test_metadata_summary.py`:
- Around line 40-47: The test test_metadata_summary_unauthorized currently uses
the same HttpApiAuth that created the dataset and asserts success; change it to
call metadata_summary with an auth context that does NOT have access (e.g., a
different/unauthenticated HttpApiAuth or a second fixture representing another
user) using the kb_id from add_document_func, then assert the response indicates
unauthorized access (expect non-zero/error code or the specific unauthorized
code your API returns) instead of asserting code == 0; update any fixture usage
to obtain the alternate auth and keep test name metadata_summary_unauthorized
and call site metadata_summary(HttpApiAuth, kb_id).

---

Nitpick comments:
In
`@test/testcases/test_http_api/test_file_management_within_dataset/test_metadata_summary.py`:
- Around line 60-81: The test test_metadata_summary_counts currently only
asserts unfiltered metadata_summary behavior; update it to also call
metadata_summary with the new doc_ids filtering contract and assert counts
reflect only the provided doc_ids. After creating docs via add_documents_func
and updating with update_document, invoke metadata_summary(HttpApiAuth,
dataset_id, doc_ids=[...]) (use a subset of document_ids, e.g., first two) then
convert with _summary_to_counts and assert tag/author counts match the filtered
subset (e.g., "foo"==2,"bar"==1, etc.). Ensure the new assertion checks that
"None" is not present for author in filtered results as well.
🪄 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: be04a408-d2e4-487c-9593-38f72d63533d

📥 Commits

Reviewing files that changed from the base of the PR and between 577c96b and 4e518a0.

📒 Files selected for processing (6)
  • api/apps/document_app.py
  • api/apps/restful_apis/document_api.py
  • api/apps/sdk/doc.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_metadata_summary.py
  • web/src/services/knowledge-service.ts
  • web/src/utils/api.ts
💤 Files with no reviewable changes (2)
  • api/apps/sdk/doc.py
  • api/apps/document_app.py

Comment on lines +148 to +183
@manager.route("/datasets/<dataset_id>/metadata/summary", methods=["GET"]) # noqa: F821
@login_required
@add_tenant_id_to_kwargs
async def metadata_summary(dataset_id, tenant_id):
"""
Get metadata summary for a dataset.
---
tags:
- Documents
security:
- ApiKeyAuth: []
parameters:
- in: path
name: dataset_id
type: string
required: true
description: ID of the dataset.
- in: query
name: doc_ids
type: string
required: false
description: Comma-separated document IDs to filter metadata.
responses:
200:
description: Metadata summary retrieved successfully.
"""
if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
return get_error_data_result(message=f"You don't own the dataset {dataset_id}. ")
# Get doc_ids from query parameters (comma-separated string)
doc_ids_param = request.args.get("doc_ids", "")
doc_ids = doc_ids_param.split(",") if doc_ids_param else None
try:
summary = DocMetadataService.get_metadata_summary(dataset_id, doc_ids)
return get_result(data={"summary": summary})
except Exception as e:
return server_error_response(e)

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

Add flow-level logging in the new metadata summary endpoint.

This new request path has no explicit entry/deny/failure logs, which makes operational debugging harder.

💡 Suggested update
 `@manager.route`("/datasets/<dataset_id>/metadata/summary", methods=["GET"])  # noqa: F821
 `@login_required`
 `@add_tenant_id_to_kwargs`
 async def metadata_summary(dataset_id, tenant_id):
+    logging.info(f"[METADATA SUMMARY API] dataset_id={dataset_id}")
     """
@@
     if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
+        logging.warning(f"[METADATA SUMMARY API] access denied dataset_id={dataset_id}")
         return get_error_data_result(message=f"You don't own the dataset {dataset_id}. ")
@@
     try:
         summary = DocMetadataService.get_metadata_summary(dataset_id, doc_ids)
         return get_result(data={"summary": summary})
     except Exception as e:
+        logging.exception(f"[METADATA SUMMARY API] failed dataset_id={dataset_id}")
         return server_error_response(e)
As per coding guidelines `**/*.py`: Add logging for new flows.
🤖 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 148 - 183, Add flow-level
logging to metadata_summary: log an entry at start (include dataset_id,
tenant_id and parsed doc_ids), log an access-denied message when
KnowledgebaseService.accessible(...) returns False, log a success message after
DocMetadataService.get_metadata_summary(...) before returning get_result, and
log the exception (with stack/exception details) in the except block before
calling server_error_response; refer to function metadata_summary and the calls
to KnowledgebaseService.accessible, DocMetadataService.get_metadata_summary,
get_result, and server_error_response to locate insertion points.

Comment on lines +177 to +178
doc_ids_param = request.args.get("doc_ids", "")
doc_ids = doc_ids_param.split(",") if doc_ids_param else None

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

Normalize doc_ids parsing to drop blanks and whitespace.

A query like doc_ids=a,, b currently yields invalid tokens ("", " b"), which can pollute filtering.

💡 Suggested update
-    doc_ids_param = request.args.get("doc_ids", "")
-    doc_ids = doc_ids_param.split(",") if doc_ids_param else None
+    doc_ids_param = request.args.get("doc_ids", "")
+    doc_ids = (
+        [doc_id.strip() for doc_id in doc_ids_param.split(",") if doc_id.strip()]
+        if doc_ids_param
+        else None
+    )
📝 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.

Suggested change
doc_ids_param = request.args.get("doc_ids", "")
doc_ids = doc_ids_param.split(",") if doc_ids_param else None
doc_ids_param = request.args.get("doc_ids", "")
doc_ids = (
[doc_id.strip() for doc_id in doc_ids_param.split(",") if doc_id.strip()]
if doc_ids_param
else None
)
🤖 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 177 - 178, Normalize
parsing of doc_ids by splitting doc_ids_param on commas, stripping whitespace
from each token and filtering out empty strings so blank entries like "" or
tokens with leading/trailing spaces are removed; replace the current doc_ids
assignment (using doc_ids_param.split(",") if doc_ids_param else None) with code
that maps strip() over tokens and keeps only non-empty tokens, and set doc_ids
to None if the resulting list is empty (use the variables doc_ids_param and
doc_ids to locate and update the logic).

@xugangqiang xugangqiang changed the title Merge metadata summary Merge document metadata summary APIs into one Restful API Apr 9, 2026
@xugangqiang
xugangqiang force-pushed the merge-metadata-summary branch from 4e518a0 to 13cebde Compare April 9, 2026 07:06

@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

♻️ Duplicate comments (2)
api/apps/restful_apis/document_api.py (2)

150-185: ⚠️ Potential issue | 🟡 Minor

Add flow-level logs to the new metadata summary endpoint.

This new request flow has no explicit entry/deny/success/failure logs, which makes production debugging harder.

💡 Suggested update
 async def metadata_summary(dataset_id, tenant_id):
@@
+    logging.info(
+        "[METADATA SUMMARY API] request dataset_id=%s tenant_id=%s",
+        dataset_id,
+        tenant_id,
+    )
     if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
+        logging.warning(
+            "[METADATA SUMMARY API] access denied dataset_id=%s tenant_id=%s",
+            dataset_id,
+            tenant_id,
+        )
         return get_error_data_result(message=f"You don't own the dataset {dataset_id}. ")
@@
     try:
         summary = DocMetadataService.get_metadata_summary(dataset_id, doc_ids)
+        logging.info(
+            "[METADATA SUMMARY API] success dataset_id=%s fields=%s",
+            dataset_id,
+            len(summary),
+        )
         return get_result(data={"summary": summary})
     except Exception as e:
+        logging.exception(
+            "[METADATA SUMMARY API] failed dataset_id=%s tenant_id=%s",
+            dataset_id,
+            tenant_id,
+        )
         return server_error_response(e)

As per coding guidelines **/*.py: Add logging for new flows.

🤖 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 150 - 185, Add flow-level
logging to the metadata_summary endpoint: log an entry at the start of
metadata_summary with dataset_id, tenant_id and doc_ids_param; when
KnowledgebaseService.accessible(...) returns False log a deny message including
dataset_id and tenant_id before calling get_error_data_result; after
successfully obtaining summary from DocMetadataService.get_metadata_summary(...)
log a success message including dataset_id, tenant_id and number of summary
items (or presence of summary) before returning get_result; in the except block
log the exception details (exception message and stack) together with dataset_id
and tenant_id before calling server_error_response. Use the module logger used
elsewhere in this file to keep logs consistent.

179-180: ⚠️ Potential issue | 🟡 Minor

Normalize doc_ids parsing to drop blanks and whitespace.

At Line 180, raw split keeps empty tokens and padded IDs (e.g. "a,, b"), which can pollute filtering.

💡 Suggested update
     doc_ids_param = request.args.get("doc_ids", "")
-    doc_ids = doc_ids_param.split(",") if doc_ids_param else None
+    doc_ids = (
+        [doc_id.strip() for doc_id in doc_ids_param.split(",") if doc_id.strip()]
+        if doc_ids_param
+        else None
+    ) or None
🤖 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 179 - 180, The current
parsing of doc_ids (variables doc_ids_param and doc_ids) uses a raw split which
preserves empty tokens and surrounding whitespace; update the logic to split on
commas, strip whitespace from each token, filter out empty strings, and set
doc_ids to None if the resulting list is empty so downstream filtering isn't
polluted (refer to doc_ids_param and doc_ids in document_api.py and replace the
simple split with a split+strip+filter approach).
🧹 Nitpick comments (2)
test/testcases/test_http_api/test_file_management_within_dataset/test_metadata_summary.py (2)

60-81: Add coverage for doc_ids filtering behavior on the new endpoint.

Current tests validate full-dataset aggregation but not the doc_ids query filter that was introduced in this API change.

Based on learnings 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_http_api/test_file_management_within_dataset/test_metadata_summary.py`
around lines 60 - 81, Extend the test_metadata_summary_counts test to exercise
the new doc_ids filtering by calling metadata_summary(HttpApiAuth, dataset_id,
{"doc_ids": [...]}) (or the appropriate query param shape expected by
metadata_summary) with a subset of document_ids (e.g., [document_ids[0],
document_ids[1]]), then assert the returned summary/counts only reflect those
documents (e.g., tags "foo" count becomes 2, "bar" count adjusts, author counts
match the selected docs) and ensure "None" is still not present for authors;
update expectations using the same _summary_to_counts helper and reuse
document_ids and payloads for clarity.

49-55: Rename this test or add actual exception-path assertions.

The method/docstring says “success and exception,” but it currently validates only the success path.

💡 Suggested update
-    def test_metadata_summary_success_and_exception(self, HttpApiAuth, add_document_func):
-        """Test metadata summary success case and exception handling."""
+    def test_metadata_summary_success(self, HttpApiAuth, add_document_func):
+        """Test metadata summary success case."""
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@test/testcases/test_http_api/test_file_management_within_dataset/test_metadata_summary.py`
around lines 49 - 55, The test named test_metadata_summary_success_and_exception
currently only exercises the success path; either rename it to reflect that
(e.g., test_metadata_summary_success) or add assertions that exercise and
validate the exception path: call metadata_summary(HttpApiAuth, kb_id) under a
failure condition (for example by mocking or removing permissions for
HttpApiAuth or passing an invalid kb_id), assert the error code and error
message structure returned (e.g., res["code"] != 0 and relevant keys in
res["data"] or res["error"]). Ensure the added assertions reference the existing
test helper names (metadata_summary, HttpApiAuth, add_document_func, kb_id) so
the failure scenario is clearly covered.
🤖 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_http_api/test_file_management_within_dataset/test_metadata_summary.py`:
- Around line 44-45: The inline comment is contradictory to the assertion on res
(assert res["code"] == 102, res); update the comment to reflect the actual
expectation (e.g., change "Should succeed with valid access" to something like
"Should fail / return error code 102 for invalid access") so the comment matches
the assertion using the same symbols (res and the assert line).

---

Duplicate comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 150-185: Add flow-level logging to the metadata_summary endpoint:
log an entry at the start of metadata_summary with dataset_id, tenant_id and
doc_ids_param; when KnowledgebaseService.accessible(...) returns False log a
deny message including dataset_id and tenant_id before calling
get_error_data_result; after successfully obtaining summary from
DocMetadataService.get_metadata_summary(...) log a success message including
dataset_id, tenant_id and number of summary items (or presence of summary)
before returning get_result; in the except block log the exception details
(exception message and stack) together with dataset_id and tenant_id before
calling server_error_response. Use the module logger used elsewhere in this file
to keep logs consistent.
- Around line 179-180: The current parsing of doc_ids (variables doc_ids_param
and doc_ids) uses a raw split which preserves empty tokens and surrounding
whitespace; update the logic to split on commas, strip whitespace from each
token, filter out empty strings, and set doc_ids to None if the resulting list
is empty so downstream filtering isn't polluted (refer to doc_ids_param and
doc_ids in document_api.py and replace the simple split with a
split+strip+filter approach).

---

Nitpick comments:
In
`@test/testcases/test_http_api/test_file_management_within_dataset/test_metadata_summary.py`:
- Around line 60-81: Extend the test_metadata_summary_counts test to exercise
the new doc_ids filtering by calling metadata_summary(HttpApiAuth, dataset_id,
{"doc_ids": [...]}) (or the appropriate query param shape expected by
metadata_summary) with a subset of document_ids (e.g., [document_ids[0],
document_ids[1]]), then assert the returned summary/counts only reflect those
documents (e.g., tags "foo" count becomes 2, "bar" count adjusts, author counts
match the selected docs) and ensure "None" is still not present for authors;
update expectations using the same _summary_to_counts helper and reuse
document_ids and payloads for clarity.
- Around line 49-55: The test named test_metadata_summary_success_and_exception
currently only exercises the success path; either rename it to reflect that
(e.g., test_metadata_summary_success) or add assertions that exercise and
validate the exception path: call metadata_summary(HttpApiAuth, kb_id) under a
failure condition (for example by mocking or removing permissions for
HttpApiAuth or passing an invalid kb_id), assert the error code and error
message structure returned (e.g., res["code"] != 0 and relevant keys in
res["data"] or res["error"]). Ensure the added assertions reference the existing
test helper names (metadata_summary, HttpApiAuth, add_document_func, kb_id) so
the failure scenario is clearly covered.
🪄 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: fc136311-44c6-41c2-8ae3-e03ca7b9b784

📥 Commits

Reviewing files that changed from the base of the PR and between 4e518a0 and 13cebde.

📒 Files selected for processing (6)
  • api/apps/document_app.py
  • api/apps/restful_apis/document_api.py
  • api/apps/sdk/doc.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_metadata_summary.py
  • web/src/services/knowledge-service.ts
  • web/src/utils/api.ts
💤 Files with no reviewable changes (2)
  • api/apps/document_app.py
  • api/apps/sdk/doc.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • web/src/services/knowledge-service.ts
  • web/src/utils/api.ts

@xugangqiang
xugangqiang force-pushed the merge-metadata-summary branch from 13cebde to 4a3a125 Compare April 9, 2026 07:22

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

♻️ Duplicate comments (2)
api/apps/restful_apis/document_api.py (2)

179-180: ⚠️ Potential issue | 🟡 Minor

Normalize doc_ids query parsing before passing to service.

At Line 180, comma-splitting without trimming/filtering can produce invalid IDs (e.g., blanks/whitespace), which pollutes filtering input.

💡 Suggested update
     doc_ids_param = request.args.get("doc_ids", "")
-    doc_ids = doc_ids_param.split(",") if doc_ids_param else None
+    doc_ids = (
+        [doc_id.strip() for doc_id in doc_ids_param.split(",") if doc_id.strip()]
+        if doc_ids_param
+        else None
+    )
+    if not doc_ids:
+        doc_ids = None
🤖 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 179 - 180, The doc_ids
query parsing currently splits doc_ids_param by commas and can yield blank or
whitespace-only entries; update the code that builds doc_ids (from
doc_ids_param) to split on ",", strip whitespace from each piece, filter out
empty strings, and set doc_ids to None if the resulting list is empty so
downstream service receives either a clean list of IDs or None; refer to
doc_ids_param and doc_ids when making this change.

153-185: ⚠️ Potential issue | 🟡 Minor

Add flow-level logs for the new metadata summary path.

The new handler has no entry/deny/success/exception logs, which makes production debugging and audit trails harder for this flow.

💡 Suggested update
 async def metadata_summary(dataset_id, tenant_id):
@@
+    logging.info(
+        "[METADATA SUMMARY API] request dataset_id=%s tenant_id=%s raw_doc_ids=%s",
+        dataset_id,
+        tenant_id,
+        request.args.get("doc_ids", ""),
+    )
     if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
+        logging.warning(
+            "[METADATA SUMMARY API] access denied dataset_id=%s tenant_id=%s",
+            dataset_id,
+            tenant_id,
+        )
         return get_error_data_result(message=f"You don't own the dataset {dataset_id}. ")
@@
     try:
         summary = DocMetadataService.get_metadata_summary(dataset_id, doc_ids)
+        logging.info(
+            "[METADATA SUMMARY API] success dataset_id=%s tenant_id=%s",
+            dataset_id,
+            tenant_id,
+        )
         return get_result(data={"summary": summary})
     except Exception as e:
+        logging.exception(
+            "[METADATA SUMMARY API] failed dataset_id=%s tenant_id=%s",
+            dataset_id,
+            tenant_id,
+        )
         return server_error_response(e)

As per coding guidelines **/*.py: Add logging for new flows.

🤖 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 153 - 185, Add flow-level
logging to the metadata_summary handler: log an entry message at start
(including dataset_id and tenant_id / doc_ids), log a deny/warn when
KnowledgebaseService.accessible(...) returns False, log a success/info with the
resulting summary before returning get_result(...), and log an exception/error
in the except block including the exception details before calling
server_error_response(e); use the module logger (e.g., logger or
current_app.logger) and reference the functions/variables metadata_summary,
KnowledgebaseService.accessible, DocMetadataService.get_metadata_summary,
get_result, get_error_data_result, server_error_response and request.args so the
logs clearly show the flow, inputs, and outcomes.
🤖 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 179-180: The doc_ids query parsing currently splits doc_ids_param
by commas and can yield blank or whitespace-only entries; update the code that
builds doc_ids (from doc_ids_param) to split on ",", strip whitespace from each
piece, filter out empty strings, and set doc_ids to None if the resulting list
is empty so downstream service receives either a clean list of IDs or None;
refer to doc_ids_param and doc_ids when making this change.
- Around line 153-185: Add flow-level logging to the metadata_summary handler:
log an entry message at start (including dataset_id and tenant_id / doc_ids),
log a deny/warn when KnowledgebaseService.accessible(...) returns False, log a
success/info with the resulting summary before returning get_result(...), and
log an exception/error in the except block including the exception details
before calling server_error_response(e); use the module logger (e.g., logger or
current_app.logger) and reference the functions/variables metadata_summary,
KnowledgebaseService.accessible, DocMetadataService.get_metadata_summary,
get_result, get_error_data_result, server_error_response and request.args so the
logs clearly show the flow, inputs, and outcomes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f8f14e64-b723-44c8-879e-b1e4280f7c10

📥 Commits

Reviewing files that changed from the base of the PR and between 13cebde and 4a3a125.

📒 Files selected for processing (6)
  • api/apps/document_app.py
  • api/apps/restful_apis/document_api.py
  • api/apps/sdk/doc.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_metadata_summary.py
  • web/src/services/knowledge-service.ts
  • web/src/utils/api.ts
💤 Files with no reviewable changes (2)
  • api/apps/document_app.py
  • api/apps/sdk/doc.py
✅ Files skipped from review due to trivial changes (1)
  • web/src/services/knowledge-service.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • web/src/utils/api.ts
  • test/testcases/test_http_api/test_file_management_within_dataset/test_metadata_summary.py

@codecov

codecov Bot commented Apr 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.66%. Comparing base (3b77238) to head (68807ca).
⚠️ Report is 25 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14001      +/-   ##
==========================================
- Coverage   98.11%   96.66%   -1.45%     
==========================================
  Files          10       10              
  Lines         690      690              
  Branches      108      108              
==========================================
- Hits          677      667      -10     
- Misses          4        8       +4     
- Partials        9       15       +6     

☔ 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 force-pushed the merge-metadata-summary branch from 2ace97e to 8b1708c Compare April 9, 2026 12:22
@xugangqiang xugangqiang self-assigned this Apr 10, 2026
@yuzhichang

Copy link
Copy Markdown
Member

LGTM

@yuzhichang
yuzhichang merged commit 582c792 into infiniflow:main Apr 10, 2026
1 check passed
yuzhichang added a commit that referenced this pull request Apr 10, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Apr 10, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐖api The modified files are located under directory 'api/apps/sdk' ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants