Skip to content

feat(api): add unified index API and dataset management endpoints - #14222

Merged
wangq8 merged 44 commits into
infiniflow:mainfrom
euvre:add-api
Apr 27, 2026
Merged

wangq8 merged 44 commits into
infiniflow:mainfrom
euvre:add-api

Conversation

@euvre

@euvre euvre commented Apr 20, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Summary

Refactor the dataset API layer into a clean service/REST separation pattern, add a unified /index API for graph/raptor/mindmap operations, and introduce several new dataset management endpoints with full test coverage.

Changes

Service Layer (dataset_api_service.py)

  • Added trace_index(dataset_id, tenant_id, index_type) — unified trace function for all index types
  • Added run_index, delete_index service functions
  • Added get_dataset, get_ingestion_summary, list_ingestion_logs, get_ingestion_log
  • Added run_embedding, list_tags, aggregate_tags, delete_tags, rename_tag
  • Added get_flattened_metadata, get_auto_metadata, update_auto_metadata

REST API Layer (dataset_api.py)

New unified routes:

Method Route Description
POST /datasets/<id>/index?type=graph|raptor|mindmap Run index task
GET /datasets/<id>/index?type=graph|raptor|mindmap Trace index task
DELETE /datasets/<id>/<index_type> Delete index
GET /datasets/<id> Get dataset details
GET /datasets/<id>/ingestions/summary Ingestion summary
GET /datasets/<id>/ingestions List ingestion logs
GET /datasets/<id>/ingestions/<log_id> Get single ingestion log
POST /datasets/<id>/embedding Run embedding
GET /datasets/<id>/tags List tags
GET /datasets/tags/aggregation Aggregate tags across datasets
DELETE /datasets/<id>/tags Delete tags
PUT /datasets/<id>/tags Rename tag
GET /datasets/metadata/flattened Get flattened metadata
GET/PUT /datasets/<id>/metadata/config New metadata config path

Removed routes (replaced by unified /index):

  • POST /datasets/<id>/mindmap
  • GET /datasets/<id>/mindmap

Preserved legacy routes (backward compatibility):

  • /run_graphrag, /trace_graphrag, /run_raptor, /trace_raptor
  • /auto_metadata GET/PUT

Test Suite

  • Updated common.py helpers: added trace_index, removed run_mindmap/trace_mindmap
  • Added 7 new test files with 39 test cases total:
Test File Cases
test_get_dataset.py 4
test_ingestion_summary.py 2
test_ingestion_logs.py 5
test_index_api.py 14
test_embedding.py 2
test_tags.py 8
test_flattened_metadata.py 4
  • Deleted test_mindmap_tasks.py (covered by unified index tests)

Design Decisions

  1. Unified /index?type=... — single endpoint replaces 3 separate route pairs for graph/raptor/mindmap
  2. Backward compatibility — old routes (/run_graphrag, /run_raptor, /auto_metadata) preserved alongside new paths
  3. _VALID_INDEX_TYPES = {"graph", "raptor", "mindmap"} — input validation via constant set
  4. _INDEX_TYPE_TO_TASK_ID_FIELD — maps index type to KB model task ID field for clean dispatch

Files Changed

  • api/apps/restful_apis/dataset_api.py
  • api/apps/services/dataset_api_service.py
  • sdk/python/ragflow_sdk/modules/dataset.py
  • test/testcases/test_http_api/common.py
  • test/testcases/test_http_api/test_dataset_management/ (7 new files)

Type of change

  • New Feature (non-breaking change which adds functionality)
  • Refactoring

euvre added 2 commits April 20, 2026 14:34
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Apr 20, 2026
@coderabbitai

coderabbitai Bot commented Apr 20, 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

Adds unified dataset indexing/embedding APIs, new dataset/tag/metadata/ingestion endpoints and service implementations, updates SDK and frontend callers to index-based APIs, expands HTTP tests for these flows, and removes legacy Graphrag/Raptor/Mindmap routes and related tests.

Changes

Cohort / File(s) Summary
API Endpoints
api/apps/restful_apis/dataset_api.py
Added handlers for dataset retrieval, ingestion summary/logs, tags (list/aggregate/delete/rename), flattened metadata, legacy + new auto-metadata config routes, index run/trace/delete, and embedding. Standardized validation and error mapping (ValueError→argument error, generic exceptions→internal error).
Service Layer
api/apps/services/dataset_api_service.py
Introduced index-type constants/mappings and implemented run_index/trace_index/delete_index, embedding scheduling, dataset read/ingestion summaries, tag ops (list/aggregate/delete/rename), flattened metadata, and ingestion log APIs; includes authorization, task lifecycle, and persistence logic.
SDK
sdk/python/ragflow_sdk/modules/dataset.py
Updated auto-metadata SDK endpoints to use /datasets/{id}/metadata/config for GET/PUT (caller paths changed only).
HTTP Test Helpers
test/testcases/test_http_api/common.py
Made helper headers parameterizable; removed Graphrag/Raptor helpers; added helpers for dataset GET, ingestion summary/logs, index run/trace/delete, embedding, tag ops, and flattened metadata.
HTTP Tests — New suites
test/testcases/test_http_api/test_dataset_management/*.py
Added integration tests for get_dataset, embedding, flattened metadata, index lifecycle, ingestion logs/summary, and tags (success/error/pagination scenarios).
Tests — Removed suites/helpers
test/testcases/test_http_api/test_dataset_management/test_graphrag_tasks.py, test/testcases/test_http_api/test_dataset_management/test_raptor_tasks.py, test/testcases/test_web_api/test_common.py, test/testcases/test_web_api/test_kb_app/test_kb_pipeline_tasks.py
Deleted Graphrag/Raptor/Mindmap run/trace tests and related helpers.
Unit Tests — web API harness
test/testcases/test_web_api/test_dataset_sdk_routes_unit.py, test/testcases/test_web_api/test_kb_app/test_kb_routes_unit.py
Reworked unit tests to target index-based flows; added UserTenantService stub and normalized expectations to unified task_id fields.
Frontend — API & usage
web/src/utils/api.ts, web/src/services/knowledge-service.ts, web/src/pages/.../hook.ts
Replaced GraphRag/Raptor run/trace helpers with runIndex/traceIndex(indexType) and updated callers to pass indexType parameter.
KB App
api/apps/kb_app.py
Removed Mindmap endpoints (run_mindmap, trace_mindmap).

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API as DatasetAPI
    participant Service as DatasetAPIService
    participant Auth as Authorization
    participant DB as Storage
    participant Queue as TaskQueue

    Client->>API: POST /datasets/{id}/index?type={idx}
    activate API
    API->>API: validate index_type, parse tenant
    API->>Service: run_index(dataset_id, tenant_id, index_type)
    activate Service
    Service->>Auth: authorize dataset access
    Auth-->>Service: authorized
    Service->>DB: verify dataset & docs, check existing task
    DB-->>Service: dataset/docs info
    Service->>Queue: enqueue indexing task
    Queue-->>Service: returns task_id
    Service->>DB: persist task_id and timestamps
    Service-->>API: {task_id}
    deactivate Service
    API-->>Client: 200 {code:0, data:{task_id}}
    deactivate API
Loading
sequenceDiagram
    participant Client
    participant API as DatasetAPI
    participant Service as DatasetAPIService
    participant Auth as Authorization
    participant DB as Storage

    Client->>API: GET /datasets/tags/aggregation?dataset_ids=[...]
    activate API
    API->>API: parse & validate dataset_ids
    API->>Service: aggregate_tags(dataset_ids, tenant_id)
    activate Service
    Service->>Auth: authorize datasets
    Auth-->>Service: authorized
    Service->>DB: fetch tags across datasets
    DB-->>Service: aggregated tags
    Service-->>API: return aggregated tags
    deactivate Service
    API-->>Client: 200 {code:0, data:...}
    deactivate API
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested labels

size:XXL

Suggested reviewers

  • yuzhichang
  • JinHai-CN
  • yingfeng

Poem

🐰 I hopped through routes both old and new,
I stitched index seeds and metadata too,
Tags danced, logs chimed, embeddings took flight,
Tests and SDKs cheered in the moonlight,
A carrot-coded hop — the release feels true!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: a unified index API and new dataset management endpoints. It is specific, concise, and directly reflects the primary purpose of the refactoring.
Description check ✅ Passed The description covers the main objectives, lists specific service/REST layer additions, details new routes, explains design decisions, and includes test coverage information. However, the required template sections are not explicitly followed (missing checklist items for type of change and incomplete problem statement format).
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.

@dosubot dosubot Bot added ☯️ refactor Pull request that refactor/refine code 🐖api The modified files are located under directory 'api/apps/sdk' 💞 feature Feature request, pull request that fullfill a new feature. 🧪 test Pull requests that update test cases. labels Apr 20, 2026
@euvre
euvre marked this pull request as draft April 20, 2026 06:37

@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: 8

🧹 Nitpick comments (6)
sdk/python/ragflow_sdk/modules/dataset.py (1)

155-173: Add request/response failure logging for the new metadata-config flow.

Line 159 and Line 169 introduce new endpoint usage but keep silent failure paths (raise Exception(res["message"])). Please add structured logging before raising so SDK failures are diagnosable in production.

📌 Proposed patch
+import logging
 from typing import Any
 from .base import Base
 from .document import Document
+
+logger = logging.getLogger(__name__)
@@
     def get_auto_metadata(self) -> dict[str, Any]:
@@
         res = self.get(f"/datasets/{self.id}/metadata/config")
         res = res.json()
         if res.get("code") == 0:
             return res["data"]
+        logger.error(
+            "get_auto_metadata failed: dataset_id=%s code=%s message=%s",
+            self.id,
+            res.get("code"),
+            res.get("message"),
+        )
         raise Exception(res["message"])
@@
     def update_auto_metadata(self, **config: Any) -> dict[str, Any]:
@@
         res = self.put(f"/datasets/{self.id}/metadata/config", config)
         res = res.json()
         if res.get("code") == 0:
             return res["data"]
+        logger.error(
+            "update_auto_metadata failed: dataset_id=%s code=%s message=%s",
+            self.id,
+            res.get("code"),
+            res.get("message"),
+        )
         raise Exception(res["message"])

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 `@sdk/python/ragflow_sdk/modules/dataset.py` around lines 155 - 173, Both
get_auto_metadata and update_auto_metadata swallow response details when the SDK
call fails; before raising the Exception include structured logging of request
and response to aid diagnosis. Update the functions get_auto_metadata and
update_auto_metadata to log the HTTP method and endpoint (e.g.,
f"/datasets/{self.id}/metadata/config"), the request payload for
update_auto_metadata (the config dict), and the full response body/status/code
using the module or instance logger (e.g., a logger on this class or module)
immediately before raising the Exception so failures are recorded in production.
test/testcases/test_http_api/test_dataset_management/test_tags.py (1)

64-86: Mutation tests should verify post-state, not only return code.

For delete_tags and rename_tag, add pre/post assertions (e.g., via list_tags/aggregate_tags) to confirm tags were actually removed/renamed, not just accepted.

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_dataset_management/test_tags.py` around
lines 64 - 86, The tests only assert response codes for delete_tags and
rename_tag; update test_delete_tags_missing_body, test_delete_tags_invalid_id,
test_rename_tag_missing_body, and test_rename_tag_invalid_id to perform pre- and
post-state checks using the tag listing helpers (e.g., list_tags or
aggregate_tags) and the dataset fixture add_dataset_func/HttpApiAuth: for
delete_tags add an initial assertion that the expected tags exist on the
dataset, call delete_tags, then assert those tags are gone (and unchanged on
invalid_id); for rename_tag assert the old tag exists before the call, call
rename_tag, then assert the old tag is replaced by the new tag (and that
invalid_id calls do not alter server state). Use the existing helper names
delete_tags, rename_tag, list_tags/aggregate_tags, add_dataset_func, and
HttpApiAuth to locate code to change.
test/testcases/test_http_api/test_dataset_management/test_ingestion_logs.py (1)

44-53: Add a success-path test for get_ingestion_log.

This class currently validates only failures. Please add one case that obtains a real log_id (e.g., from list_ingestion_logs) and asserts get_ingestion_log returns code == 0 with expected log fields.

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_dataset_management/test_ingestion_logs.py`
around lines 44 - 53, Add a positive test that verifies get_ingestion_log
succeeds: create or reuse a dataset via the add_dataset_func fixture, call
list_ingestion_logs(HttpApiAuth, dataset_id) to obtain a real log_id, then call
get_ingestion_log(HttpApiAuth, dataset_id, log_id) and assert res["code"] == 0
and required fields exist (e.g., "log_id", "status", "message" or whichever
standard log fields your API returns). Add this as a new test function (e.g.,
test_get_ingestion_log_success) alongside the existing tests and use the
HttpApiAuth and add_dataset_func fixtures to locate the dataset and logs.
test/testcases/test_http_api/test_dataset_management/test_embedding.py (1)

22-32: Add one happy-path embedding test to complete endpoint coverage.

Current tests validate only error paths. Please add a case that uploads at least one document and asserts run_embedding(...) returns success (code == 0) to protect the primary flow.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_http_api/test_dataset_management/test_embedding.py`
around lines 22 - 32, Add a happy-path test that uses the existing fixtures to
create a dataset and upload at least one document, then call run_embedding and
assert success: call add_dataset_func to obtain dataset_id, upload a document
into that dataset using the project’s document-upload helper (use the same
helper used elsewhere in tests), then call run_embedding(HttpApiAuth,
dataset_id) and assert res["code"] == 0 (and optionally that the message
indicates embedding completed). Ensure the new test function name follows the
pattern (e.g., test_run_embedding_success) and reuses the HttpApiAuth and
add_dataset_func fixtures so it integrates with existing test setup.
test/testcases/test_http_api/test_dataset_management/test_flattened_metadata.py (1)

23-33: Strengthen success assertions for flattened metadata payload.

Line 26 and Line 32 only check code == 0. Add assertions on res["data"] shape/content (e.g., non-empty structure or expected keys per dataset) so schema regressions are caught.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@test/testcases/test_http_api/test_dataset_management/test_flattened_metadata.py`
around lines 23 - 33, The tests test_get_flattened_metadata_success and
test_get_flattened_metadata_multiple_datasets only assert res["code"] == 0;
strengthen them by asserting the payload shape and content from
get_flattened_metadata: verify res["data"] exists and is non-empty, that it
contains an entry for each requested dataset_id(s) (use dataset_id and
dataset_ids), and that each entry includes the expected keys (e.g., metadata
fields like "id", "name", or other known keys your API returns). Add these
assertions after the existing code==0 check so schema regressions or missing
dataset entries fail the test.
api/apps/services/dataset_api_service.py (1)

470-526: Add success-path logs for the new mutation flows.

run_index(), delete_index(), run_embedding(), delete_tags(), and rename_tag() only log warnings/exceptions today. Adding structured success-path logs here would make these new dataset-management actions much easier to audit and debug.

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

Also applies to: 956-1000, 1003-1064

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/services/dataset_api_service.py` around lines 470 - 526, The
run_index function currently only logs warnings/errors; add structured
success-path logs: after queuing the task (queue_raptor_o_graphrag_tasks) log an
info with dataset_id, tenant_id, task_id, task_type (task_type / display_name),
and document_count; also log info when KnowledgebaseService.update_by_id
succeeds (include kb.id and the saved task_id_field); keep using the module
logger (logging.info) to match existing warnings and ensure messages are concise
and machine-parseable for auditing/debugging.
🤖 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/dataset_api.py`:
- Around line 421-446: The delete_tags and rename_tag handlers currently only
check for key presence but not types/shape; update delete_tags to ensure
req["tags"] is a non-empty list and that every element is a string (reject
otherwise with get_error_data_result), and update rename_tag to ensure
req["from_tag"] and req["to_tag"] are non-empty strings (reject otherwise);
perform these validations immediately after request.get_json() (before calling
dataset_api_service.delete_tags or dataset_api_service.rename_tag) and mirror
the same schema-based validation rules used by the other endpoints so malformed
payloads like {"tags":"foo"} or non-string tag values are rejected.
- Around line 559-566: The request parameter parsing in list_ingestion_logs
currently converts page and page_size with int(...) before your API error
handling, so invalid values raise ValueError outside your try/except; move the
parsing and conversion of request.args.get("page", ...),
request.args.get("page_size", ...), and any other user-supplied params (e.g.,
desc, orderby, operation_status, create_date_from/to) into the existing try
block or validate them with a small helper that raises a controlled API
exception, catching ValueError and returning the standard error response; update
references to page and page_size inside the function to use the safely-parsed
variables.

In `@api/apps/services/dataset_api_service.py`:
- Around line 192-194: The access check erroneously uses
KnowledgebaseService.get_or_none(id=dataset_id, tenant_id=tenant_id) which
enforces owner-only access; replace those checks with
KnowledgebaseService.accessible(tenant_id=tenant_id, dataset_id=dataset_id) (or
the existing accessible(...) signature used elsewhere in this file) so
membership/shared datasets are allowed; update both occurrences (the block
around kb = KnowledgebaseService.get_or_none(...) and the similar check later)
to call accessible(...) and branch on its boolean result, keeping the same error
message behavior when access is denied.
- Around line 1003-1039: The run_embedding function currently falls off without
returning a tuple after scheduling documents; update the function (around
run_embedding and the loop invoking DocumentService.run) to always return a
(success, result) tuple: keep the existing error returns, and after the for-loop
return something like (True, {"message": "Embedding tasks scheduled",
"scheduled_count": len(documents), "kb_table_num_map": kb_table_num_map}) so
callers (e.g., api/apps/restful_apis/dataset_api.py) can unpack the response
reliably.
- Around line 1039-1064: The rename_tag function currently falls through without
returning a value; update it to return an explicit success tuple after the
doc-store update (e.g., return True and a meaningful result like the new tag or
update response). Locate rename_tag and after the call to
settings.docStoreConn.update(..., search.index_name(kb.tenant_id), dataset_id)
add a return such as (True, {"from": from_tag, "to": to_tag}) or include the
update operation's response; also handle and return failure cases if update
raises/returns an error so callers (REST handler expecting (success, result))
get a proper tuple.
- Around line 758-762: aggregate_tags() currently calls
settings.retriever.all_tags(tenant["tenant_id"], dataset_ids) with the full
dataset_ids list for every tenant, which allows all_tags() to short-circuit on
kb_ids[0] and drop tags for datasets belonging to later tenants; fix it by first
partitioning dataset_ids by tenant (use UserTenantService.get_tenants_by_user_id
and map datasets to their tenant_id), then call
settings.retriever.all_tags(tenant_id, tenant_dataset_ids) for each tenant with
only that tenant's dataset IDs, and finally merge/normalize the returned tag
lists (deduplicate by tag name) so same-name tags from different tenants are
combined rather than overwritten.

In `@test/testcases/test_http_api/common.py`:
- Around line 484-487: The helper run_embedding currently ignores its headers
parameter and always sends the module-level HEADERS; update the requests.post
call inside run_embedding to pass the local headers variable (not HEADERS) so
callers can override headers, keeping the function signature and other arguments
(auth, json=payload) unchanged and referencing the run_embedding function name
to locate the change.

In `@test/testcases/test_http_api/test_dataset_management/test_index_api.py`:
- Around line 29-38: The helper _parse_done incorrectly treats missing/empty
responses as "DONE" because it assumes list_documents returned a successful
payload and uses all([])==True; update _parse_done to validate the
list_documents response (e.g., ensure res is truthy and res["data"]["docs"]
exists and is a list), return False immediately if the response is missing or
indicates failure, and when document_ids is provided ensure all required ids are
present in target_docs before checking their run status; reference the
_parse_done function and the list_documents call and change the logic so
empty/malformed responses do not count as completion.

---

Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 470-526: The run_index function currently only logs
warnings/errors; add structured success-path logs: after queuing the task
(queue_raptor_o_graphrag_tasks) log an info with dataset_id, tenant_id, task_id,
task_type (task_type / display_name), and document_count; also log info when
KnowledgebaseService.update_by_id succeeds (include kb.id and the saved
task_id_field); keep using the module logger (logging.info) to match existing
warnings and ensure messages are concise and machine-parseable for
auditing/debugging.

In `@sdk/python/ragflow_sdk/modules/dataset.py`:
- Around line 155-173: Both get_auto_metadata and update_auto_metadata swallow
response details when the SDK call fails; before raising the Exception include
structured logging of request and response to aid diagnosis. Update the
functions get_auto_metadata and update_auto_metadata to log the HTTP method and
endpoint (e.g., f"/datasets/{self.id}/metadata/config"), the request payload for
update_auto_metadata (the config dict), and the full response body/status/code
using the module or instance logger (e.g., a logger on this class or module)
immediately before raising the Exception so failures are recorded in production.

In `@test/testcases/test_http_api/test_dataset_management/test_embedding.py`:
- Around line 22-32: Add a happy-path test that uses the existing fixtures to
create a dataset and upload at least one document, then call run_embedding and
assert success: call add_dataset_func to obtain dataset_id, upload a document
into that dataset using the project’s document-upload helper (use the same
helper used elsewhere in tests), then call run_embedding(HttpApiAuth,
dataset_id) and assert res["code"] == 0 (and optionally that the message
indicates embedding completed). Ensure the new test function name follows the
pattern (e.g., test_run_embedding_success) and reuses the HttpApiAuth and
add_dataset_func fixtures so it integrates with existing test setup.

In
`@test/testcases/test_http_api/test_dataset_management/test_flattened_metadata.py`:
- Around line 23-33: The tests test_get_flattened_metadata_success and
test_get_flattened_metadata_multiple_datasets only assert res["code"] == 0;
strengthen them by asserting the payload shape and content from
get_flattened_metadata: verify res["data"] exists and is non-empty, that it
contains an entry for each requested dataset_id(s) (use dataset_id and
dataset_ids), and that each entry includes the expected keys (e.g., metadata
fields like "id", "name", or other known keys your API returns). Add these
assertions after the existing code==0 check so schema regressions or missing
dataset entries fail the test.

In `@test/testcases/test_http_api/test_dataset_management/test_ingestion_logs.py`:
- Around line 44-53: Add a positive test that verifies get_ingestion_log
succeeds: create or reuse a dataset via the add_dataset_func fixture, call
list_ingestion_logs(HttpApiAuth, dataset_id) to obtain a real log_id, then call
get_ingestion_log(HttpApiAuth, dataset_id, log_id) and assert res["code"] == 0
and required fields exist (e.g., "log_id", "status", "message" or whichever
standard log fields your API returns). Add this as a new test function (e.g.,
test_get_ingestion_log_success) alongside the existing tests and use the
HttpApiAuth and add_dataset_func fixtures to locate the dataset and logs.

In `@test/testcases/test_http_api/test_dataset_management/test_tags.py`:
- Around line 64-86: The tests only assert response codes for delete_tags and
rename_tag; update test_delete_tags_missing_body, test_delete_tags_invalid_id,
test_rename_tag_missing_body, and test_rename_tag_invalid_id to perform pre- and
post-state checks using the tag listing helpers (e.g., list_tags or
aggregate_tags) and the dataset fixture add_dataset_func/HttpApiAuth: for
delete_tags add an initial assertion that the expected tags exist on the
dataset, call delete_tags, then assert those tags are gone (and unchanged on
invalid_id); for rename_tag assert the old tag exists before the call, call
rename_tag, then assert the old tag is replaced by the new tag (and that
invalid_id calls do not alter server state). Use the existing helper names
delete_tags, rename_tag, list_tags/aggregate_tags, add_dataset_func, and
HttpApiAuth to locate code to change.
🪄 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: d57efaab-534f-4868-b5e2-e9609f2895a5

📥 Commits

Reviewing files that changed from the base of the PR and between d053317 and 7deca6f.

📒 Files selected for processing (11)
  • api/apps/restful_apis/dataset_api.py
  • api/apps/services/dataset_api_service.py
  • sdk/python/ragflow_sdk/modules/dataset.py
  • test/testcases/test_http_api/common.py
  • test/testcases/test_http_api/test_dataset_management/test_embedding.py
  • test/testcases/test_http_api/test_dataset_management/test_flattened_metadata.py
  • test/testcases/test_http_api/test_dataset_management/test_get_dataset.py
  • test/testcases/test_http_api/test_dataset_management/test_index_api.py
  • test/testcases/test_http_api/test_dataset_management/test_ingestion_logs.py
  • test/testcases/test_http_api/test_dataset_management/test_ingestion_summary.py
  • test/testcases/test_http_api/test_dataset_management/test_tags.py

Comment thread api/apps/restful_apis/dataset_api.py Resolved
Comment thread api/apps/restful_apis/dataset_api.py Resolved
Comment thread test/testcases/test_http_api/common.py Resolved
euvre added 3 commits April 20, 2026 21:18
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
@euvre
euvre marked this pull request as ready for review April 21, 2026 02:24
@dosubot dosubot Bot added the python Pull requests that update python code label Apr 21, 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

🧹 Nitpick comments (2)
api/apps/restful_apis/dataset_api.py (2)

550-564: Consider validating index_type at the API layer.

The delete_index endpoint accepts index_type as a path parameter but doesn't validate it before calling the service. While the service validates it, rejecting invalid types early at the API layer provides clearer error responses and aligns with the pattern used in other endpoints.

🔧 Optional validation
+VALID_INDEX_TYPES = {"graph", "raptor", "mindmap"}
+
 `@manager.route`("/datasets/<dataset_id>/<index_type>", methods=["DELETE"])
 `@login_required`
 `@add_tenant_id_to_kwargs`
 def delete_index(tenant_id, dataset_id, index_type):
+    if index_type not in VALID_INDEX_TYPES:
+        return get_error_argument_result(f"Invalid index type '{index_type}'")
     try:
         success, result = dataset_api_service.delete_index(dataset_id, tenant_id, index_type)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/dataset_api.py` around lines 550 - 564, The
delete_index API should validate the path param index_type before calling
dataset_api_service.delete_index: in the delete_index function check index_type
against the canonical allowed set (use an existing constant like
dataset_api_service.VALID_INDEX_TYPES or define a small local list of valid
types) and if not valid return get_error_argument_result with a clear message
(e.g., "Invalid index_type: must be one of [...]"); only call
dataset_api_service.delete_index when validation passes and keep existing
exception handling unchanged.

34-54: Misleading ValueError error message.

The aggregate_tags endpoint catches ValueError with message "page and page_size must be integers", but this endpoint doesn't use pagination parameters. Consider removing this catch block or using a generic message.

🔧 Suggested fix
     try:
         success, result = dataset_api_service.aggregate_tags(dataset_ids, tenant_id)
         if success:
             return get_result(data=result)
         else:
             return get_error_data_result(message=result)
-    except ValueError:
-        return get_error_argument_result("page and page_size must be integers")
     except Exception as e:
         logging.exception(e)
         return get_error_data_result(message="Internal server error")

This same issue appears in multiple other endpoints: get_flattened_metadata, create, get_dataset, get_ingestion_summary, list_tags, delete_tags, rename_tag, run_index, trace_index, delete_index, get_ingestion_log, get_auto_metadata_legacy, update_auto_metadata_legacy, get_auto_metadata, and update_auto_metadata.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/dataset_api.py` around lines 34 - 54, The handler
aggregate_tags (and the other listed endpoints like get_flattened_metadata,
create, get_dataset, get_ingestion_summary, list_tags, delete_tags, rename_tag,
run_index, trace_index, delete_index, get_ingestion_log,
get_auto_metadata_legacy, update_auto_metadata_legacy, get_auto_metadata,
update_auto_metadata) is catching ValueError and returning a misleading "page
and page_size must be integers" message; remove that hardcoded ValueError branch
or replace it with a generic/accurate response. Locate the except ValueError
block in aggregate_tags (and the same pattern in the other functions) and either
delete it so the generic Exception handler handles errors, or change it to
return get_error_argument_result(str(e)) or a neutral message like "Invalid
argument" so the error reflects the actual validation issue instead of the
pagination text.
🤖 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/common.py`:
- Around line 139-142: Multiple functions reference an undefined variable
headers; update each affected function signature (parse_documents, add_chunk,
retrieval_chunks, create_chat_assistant, create_session_with_chat_assistant,
metadata_batch_update, related_questions, create_agent, agent_completions,
chat_completions, chat_completions_openai) to accept a headers parameter (e.g.,
headers) and use that parameter in the requests.* calls (headers=headers)
instead of the undefined global; ensure any internal calls to these functions
are updated to pass the appropriate headers value (or default to None if callers
should remain unchanged).

---

Nitpick comments:
In `@api/apps/restful_apis/dataset_api.py`:
- Around line 550-564: The delete_index API should validate the path param
index_type before calling dataset_api_service.delete_index: in the delete_index
function check index_type against the canonical allowed set (use an existing
constant like dataset_api_service.VALID_INDEX_TYPES or define a small local list
of valid types) and if not valid return get_error_argument_result with a clear
message (e.g., "Invalid index_type: must be one of [...]"); only call
dataset_api_service.delete_index when validation passes and keep existing
exception handling unchanged.
- Around line 34-54: The handler aggregate_tags (and the other listed endpoints
like get_flattened_metadata, create, get_dataset, get_ingestion_summary,
list_tags, delete_tags, rename_tag, run_index, trace_index, delete_index,
get_ingestion_log, get_auto_metadata_legacy, update_auto_metadata_legacy,
get_auto_metadata, update_auto_metadata) is catching ValueError and returning a
misleading "page and page_size must be integers" message; remove that hardcoded
ValueError branch or replace it with a generic/accurate response. Locate the
except ValueError block in aggregate_tags (and the same pattern in the other
functions) and either delete it so the generic Exception handler handles errors,
or change it to return get_error_argument_result(str(e)) or a neutral message
like "Invalid argument" so the error reflects the actual validation issue
instead of the pagination text.
🪄 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: 2bbbf953-f945-47d7-ac98-afe2c71e4705

📥 Commits

Reviewing files that changed from the base of the PR and between 7deca6f and c136155.

📒 Files selected for processing (14)
  • api/apps/kb_app.py
  • api/apps/restful_apis/dataset_api.py
  • api/apps/services/dataset_api_service.py
  • test/testcases/test_http_api/common.py
  • test/testcases/test_http_api/test_dataset_management/test_graphrag_tasks.py
  • test/testcases/test_http_api/test_dataset_management/test_index_api.py
  • test/testcases/test_http_api/test_dataset_management/test_raptor_tasks.py
  • test/testcases/test_web_api/test_common.py
  • test/testcases/test_web_api/test_dataset_management/test_dataset_sdk_routes_unit.py
  • test/testcases/test_web_api/test_kb_app/test_kb_pipeline_tasks.py
  • test/testcases/test_web_api/test_kb_app/test_kb_routes_unit.py
  • web/src/pages/dataset/dataset/generate-button/hook.ts
  • web/src/services/knowledge-service.ts
  • web/src/utils/api.ts
💤 Files with no reviewable changes (5)
  • test/testcases/test_web_api/test_kb_app/test_kb_pipeline_tasks.py
  • test/testcases/test_web_api/test_common.py
  • test/testcases/test_http_api/test_dataset_management/test_graphrag_tasks.py
  • test/testcases/test_http_api/test_dataset_management/test_raptor_tasks.py
  • api/apps/kb_app.py

Comment thread test/testcases/test_http_api/common.py Resolved
Signed-off-by: noob <[email protected]>

@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 (1)
api/apps/restful_apis/dataset_api.py (1)

434-438: ⚠️ Potential issue | 🟡 Minor

Harden tag mutation body validation for empty values and JSON parse failures.

delete_tags and rename_tag still accept empty values (e.g., tags=[], from_tag="") and parse JSON outside the guarded block, so malformed JSON can bypass this handler’s normal error path.

Suggested fix
 async def delete_tags(tenant_id, dataset_id):
-    req = await request.get_json()
+    try:
+        req = await request.get_json()
+    except Exception:
+        return get_error_argument_result("Invalid JSON body")
     if not req or "tags" not in req:
         return get_error_data_result(message="Lack of tags in request body")
-    if not isinstance(req["tags"], list) or not all(isinstance(t, str) for t in req["tags"]):
-        return get_error_argument_result("tags must be a list of strings")
+    if (
+        not isinstance(req["tags"], list)
+        or len(req["tags"]) == 0
+        or not all(isinstance(t, str) and t.strip() for t in req["tags"])
+    ):
+        return get_error_argument_result("tags must be a non-empty list of non-empty strings")

 async def rename_tag(tenant_id, dataset_id):
-    req = await request.get_json()
+    try:
+        req = await request.get_json()
+    except Exception:
+        return get_error_argument_result("Invalid JSON body")
     if not req or "from_tag" not in req or "to_tag" not in req:
         return get_error_data_result(message="Lack of from_tag or to_tag in request body")
-    if not isinstance(req["from_tag"], str) or not isinstance(req["to_tag"], str):
-        return get_error_argument_result("from_tag and to_tag must be strings")
+    if (
+        not isinstance(req["from_tag"], str) or not req["from_tag"].strip()
+        or not isinstance(req["to_tag"], str) or not req["to_tag"].strip()
+    ):
+        return get_error_argument_result("from_tag and to_tag must be non-empty strings")

Also applies to: 457-461

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/dataset_api.py` around lines 434 - 438, The request
JSON parsing and tag validation in the delete_tags and rename_tag handlers must
be hardened: move the await request.get_json() inside a try/except to catch JSON
parse errors and return a proper error result, then validate that "tags" exists,
is a non-empty list and contains only non-empty strings (reject tags==[] and any
"" entries), and for rename_tag validate both "from_tag" and "to_tag" are
present and non-empty strings; update the checks in the functions referenced
(delete_tags, rename_tag) and mirror the same stricter validation logic used in
the other handler around lines 457-461 so malformed JSON and empty values are
rejected consistently.
🧹 Nitpick comments (2)
api/apps/restful_apis/dataset_api.py (2)

554-555: Avoid cross-module use of private service constants.

Using dataset_api_service._VALID_INDEX_TYPES couples this route to a private implementation detail. Prefer a public constant/helper in the service API, or rely on dataset_api_service.delete_index(...) validation only.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/dataset_api.py` around lines 554 - 555, The route is
referencing the private constant dataset_api_service._VALID_INDEX_TYPES; remove
this cross-module access and either use a public constant or helper exposed by
the service (e.g., dataset_api_service.VALID_INDEX_TYPES or
dataset_api_service.is_valid_index_type(index_type)) or simply delegate
validation to the service call (dataset_api_service.delete_index(...)) and
return/propagate the service's validation error; update the check to call the
public symbol or rely on delete_index's validation so the route no longer
imports a private member.

34-76: Add flow-level logging for newly introduced endpoints.

The new handlers only log exceptions. Please add minimal structured logs (route intent + key identifiers such as dataset_id, index_type, and operation result) for observability.

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

Also applies to: 379-411, 430-474, 514-756

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/dataset_api.py` around lines 34 - 76, The new endpoints
aggregate_tags and get_flattened_metadata lack flow-level logs; add minimal
structured logging at key points: log an entry message when each route is
invoked (include route name or path, dataset_ids list and tenant_id), log a
success message when returning get_result (include result summary or count), and
log a failure message when returning get_error_data_result (include error/result
message); keep the existing logging.exception for unexpected exceptions. Use the
existing logger (logging.info/debug/error) and reference the functions
aggregate_tags and get_flattened_metadata so the logs appear at the start, on
success, and on handled failures.
🤖 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/dataset_api.py`:
- Around line 434-438: The request JSON parsing and tag validation in the
delete_tags and rename_tag handlers must be hardened: move the await
request.get_json() inside a try/except to catch JSON parse errors and return a
proper error result, then validate that "tags" exists, is a non-empty list and
contains only non-empty strings (reject tags==[] and any "" entries), and for
rename_tag validate both "from_tag" and "to_tag" are present and non-empty
strings; update the checks in the functions referenced (delete_tags, rename_tag)
and mirror the same stricter validation logic used in the other handler around
lines 457-461 so malformed JSON and empty values are rejected consistently.

---

Nitpick comments:
In `@api/apps/restful_apis/dataset_api.py`:
- Around line 554-555: The route is referencing the private constant
dataset_api_service._VALID_INDEX_TYPES; remove this cross-module access and
either use a public constant or helper exposed by the service (e.g.,
dataset_api_service.VALID_INDEX_TYPES or
dataset_api_service.is_valid_index_type(index_type)) or simply delegate
validation to the service call (dataset_api_service.delete_index(...)) and
return/propagate the service's validation error; update the check to call the
public symbol or rely on delete_index's validation so the route no longer
imports a private member.
- Around line 34-76: The new endpoints aggregate_tags and get_flattened_metadata
lack flow-level logs; add minimal structured logging at key points: log an entry
message when each route is invoked (include route name or path, dataset_ids list
and tenant_id), log a success message when returning get_result (include result
summary or count), and log a failure message when returning
get_error_data_result (include error/result message); keep the existing
logging.exception for unexpected exceptions. Use the existing logger
(logging.info/debug/error) and reference the functions aggregate_tags and
get_flattened_metadata so the logs appear at the start, on success, and on
handled failures.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0b6029fc-f07f-42be-901f-0987f70ea9c4

📥 Commits

Reviewing files that changed from the base of the PR and between c136155 and bae53ab.

📒 Files selected for processing (2)
  • api/apps/restful_apis/dataset_api.py
  • test/testcases/test_http_api/common.py

@euvre euvre added the ci Continue Integration label Apr 21, 2026
@euvre
euvre marked this pull request as draft April 21, 2026 02:55
@euvre
euvre marked this pull request as ready for review April 21, 2026 02:55

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

🧹 Nitpick comments (1)
web/src/utils/api.ts (1)

75-78: Constrain and encode indexType in index URL builders

On Line 75 and Line 77, indexType is typed as string and interpolated raw into the query string. This permits invalid values and can break query parsing if special characters appear. Consider narrowing to the backend-supported union and encoding the param.

Proposed refactor
+type IndexType = 'graph' | 'raptor' | 'mindmap';
+
-  runIndex: (datasetId: string, indexType: string) =>
-    `${restAPIv1}/datasets/${datasetId}/index?type=${indexType}`,
-  traceIndex: (datasetId: string, indexType: string) =>
-    `${restAPIv1}/datasets/${datasetId}/index?type=${indexType}`,
+  runIndex: (datasetId: string, indexType: IndexType) =>
+    `${restAPIv1}/datasets/${datasetId}/index?type=${encodeURIComponent(indexType)}`,
+  traceIndex: (datasetId: string, indexType: IndexType) =>
+    `${restAPIv1}/datasets/${datasetId}/index?type=${encodeURIComponent(indexType)}`,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/utils/api.ts` around lines 75 - 78, runIndex and traceIndex accept a
generic string for indexType and interpolate it raw into the query, which can
allow invalid values or break the URL; change both functions (runIndex,
traceIndex) to narrow indexType to the backend-supported union (e.g., type
IndexType = 'inverted' | 'vector' | ...) and ensure the value is encoded with
encodeURIComponent when building the query string; additionally add a simple
runtime validation or a typed wrapper to reject/convert unsupported values
before interpolation so only allowed, encoded index types are sent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@web/src/utils/api.ts`:
- Around line 75-78: runIndex and traceIndex accept a generic string for
indexType and interpolate it raw into the query, which can allow invalid values
or break the URL; change both functions (runIndex, traceIndex) to narrow
indexType to the backend-supported union (e.g., type IndexType = 'inverted' |
'vector' | ...) and ensure the value is encoded with encodeURIComponent when
building the query string; additionally add a simple runtime validation or a
typed wrapper to reject/convert unsupported values before interpolation so only
allowed, encoded index types are sent.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7e942002-0ac8-4880-9558-e773010c8dc8

📥 Commits

Reviewing files that changed from the base of the PR and between bae53ab and 100981b.

📒 Files selected for processing (4)
  • test/testcases/test_web_api/test_common.py
  • test/testcases/test_web_api/test_kb_app/test_kb_pipeline_tasks.py
  • web/src/services/knowledge-service.ts
  • web/src/utils/api.ts
💤 Files with no reviewable changes (2)
  • test/testcases/test_web_api/test_kb_app/test_kb_pipeline_tasks.py
  • test/testcases/test_web_api/test_common.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/src/services/knowledge-service.ts

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

🧹 Nitpick comments (1)
test/testcases/test_http_api/test_dataset_management/test_get_dataset.py (1)

31-45: Tighten negative-case assertions to lock the API contract.

res["code"] != 0 can pass for unrelated failures, including a 500-style service error. Consider asserting the expected error code/message for invalid ID, unauthorized token, and nonexistent dataset so regressions are caught precisely.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_http_api/test_dataset_management/test_get_dataset.py`
around lines 31 - 45, Update the three negative tests
(test_get_dataset_invalid_id, test_get_dataset_unauthorized,
test_get_dataset_nonexistent) to assert exact API contract values instead of
using res["code"] != 0: call get_dataset as before and then assert the specific
expected error code and/or error message fields (e.g. exact numeric code and
res["msg"] or res["error"] text) for each scenario — invalid ID (use the invalid
id input), unauthorized (use RAGFlowHttpApiAuth(INVALID_API_TOKEN) and assert an
auth error code/message), and nonexistent (use "0"*32 and assert a not-found
code/message); keep get_dataset, HttpApiAuth, add_dataset_func and
RAGFlowHttpApiAuth references to locate the tests.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@test/testcases/test_http_api/test_dataset_management/test_get_dataset.py`:
- Around line 31-45: Update the three negative tests
(test_get_dataset_invalid_id, test_get_dataset_unauthorized,
test_get_dataset_nonexistent) to assert exact API contract values instead of
using res["code"] != 0: call get_dataset as before and then assert the specific
expected error code and/or error message fields (e.g. exact numeric code and
res["msg"] or res["error"] text) for each scenario — invalid ID (use the invalid
id input), unauthorized (use RAGFlowHttpApiAuth(INVALID_API_TOKEN) and assert an
auth error code/message), and nonexistent (use "0"*32 and assert a not-found
code/message); keep get_dataset, HttpApiAuth, add_dataset_func and
RAGFlowHttpApiAuth references to locate the tests.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2ff7b46b-b7db-4ca1-927b-57f303999de5

📥 Commits

Reviewing files that changed from the base of the PR and between 100981b and cb4a73f.

📒 Files selected for processing (2)
  • test/testcases/test_http_api/test_dataset_management/test_get_dataset.py
  • test/testcases/test_http_api/test_dataset_management/test_tags.py
✅ Files skipped from review due to trivial changes (1)
  • test/testcases/test_http_api/test_dataset_management/test_tags.py

@codecov

codecov Bot commented Apr 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.30%. Comparing base (beb2406) to head (1ff5489).
⚠️ Report is 13 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14222   +/-   ##
=======================================
  Coverage   95.30%   95.30%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          670      670           
  Misses         16       16           
  Partials       17       17           

☔ View full report in Codecov by Sentry.
📢 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.

@wangq8
wangq8 merged commit 4dcc42e into infiniflow:main Apr 27, 2026
1 check passed
wangq8 pushed a commit that referenced this pull request Apr 27, 2026
…moved in #14222 (#14390)

### What problem does this PR solve?

### Summary

PR #14222 consolidated KB (web) API endpoints into RESTful Dataset
(HTTP) API endpoints and deleted the web API test suite under
`test_web_api/test_kb_app/` and `test_web_api/test_document_app/`. While
most test coverage was migrated to the HTTP API test suite, some tests
were not ported over. This PR adds back the missing coverage.

### Route migration reference

| Old Web API | New HTTP API | Missing tests |
|---|---|---|
| `POST /v1/kb/update_metadata_setting` | `PUT
/api/v1/datasets/<id>/metadata/config` | auth & error paths |
| `GET /api/v1/datasets/<id>/auto_metadata` | `GET
/api/v1/datasets/<id>/metadata/config` | auth & CRUD |
| `PUT /api/v1/datasets/<id>/auto_metadata` | `PUT
/api/v1/datasets/<id>/metadata/config` | auth & CRUD |
| `GET /v1/kb/<kb_id>/basic_info` | `GET
/api/v1/datasets/<id>/ingestions/summary` | covered |
| `POST /v1/kb/list_pipeline_logs` | `GET
/api/v1/datasets/<id>/ingestions` | edge cases missing |

### Changes

#### `test_file_management_within_dataset/test_metadata_config.py` (new,
10 tests)

Covers `GET/PUT /datasets/<id>/metadata/config` (migrated from
`test_kb_tags_meta.py`'s `test_update_metadata_setting` and
`test_document_metadata.py`'s negative tests):
- Authorization for dataset metadata config GET/PUT
- Authorization for document metadata config PUT
- Success, invalid dataset, missing payload, not found scenarios

#### `test_dataset_management/test_ingestion_logs.py` (extended, +2
tests)

Covers `GET /datasets/<id>/ingestions` edge cases (migrated from
`test_kb_pipeline_tasks.py`):
- Missing dataset ID
- Abnormal date filter

### Type of change

- [x] Other: Test coverage improvement

---------

Signed-off-by: noob <[email protected]>
wangq8 pushed a commit that referenced this pull request Apr 28, 2026
…I endpoints (#14402)

### What problem does this PR solve?

## Summary

Migrate two web API endpoints to REST-style HTTP API endpoints,
following the pattern established in #14222:

| Old Endpoint | New Endpoint |
|---|---|
| `POST /v1/chunk/retrieval_test` | `POST
/api/v1/datasets/<dataset_id>/search` |
| `GET /v1/chunk/knowledge_graph` | `GET
/api/v1/datasets/<dataset_id>/graph` |
@coderabbitai coderabbitai Bot mentioned this pull request May 13, 2026
2 tasks 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 💞 feature Feature request, pull request that fullfill a new feature. python Pull requests that update python code ☯️ refactor Pull request that refactor/refine code size:XXL This PR changes 1000+ 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