Repository navigation
feat(api): add unified index API and dataset management endpoints - #14222
Conversation
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds 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
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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 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_tagsandrename_tag, add pre/post assertions (e.g., vialist_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 forget_ingestion_log.This class currently validates only failures. Please add one case that obtains a real
log_id(e.g., fromlist_ingestion_logs) and assertsget_ingestion_logreturnscode == 0with 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 onres["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(), andrename_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
📒 Files selected for processing (11)
api/apps/restful_apis/dataset_api.pyapi/apps/services/dataset_api_service.pysdk/python/ragflow_sdk/modules/dataset.pytest/testcases/test_http_api/common.pytest/testcases/test_http_api/test_dataset_management/test_embedding.pytest/testcases/test_http_api/test_dataset_management/test_flattened_metadata.pytest/testcases/test_http_api/test_dataset_management/test_get_dataset.pytest/testcases/test_http_api/test_dataset_management/test_index_api.pytest/testcases/test_http_api/test_dataset_management/test_ingestion_logs.pytest/testcases/test_http_api/test_dataset_management/test_ingestion_summary.pytest/testcases/test_http_api/test_dataset_management/test_tags.py
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
api/apps/restful_apis/dataset_api.py (2)
550-564: Consider validatingindex_typeat the API layer.The
delete_indexendpoint acceptsindex_typeas 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: MisleadingValueErrorerror message.The
aggregate_tagsendpoint catchesValueErrorwith 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, andupdate_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
📒 Files selected for processing (14)
api/apps/kb_app.pyapi/apps/restful_apis/dataset_api.pyapi/apps/services/dataset_api_service.pytest/testcases/test_http_api/common.pytest/testcases/test_http_api/test_dataset_management/test_graphrag_tasks.pytest/testcases/test_http_api/test_dataset_management/test_index_api.pytest/testcases/test_http_api/test_dataset_management/test_raptor_tasks.pytest/testcases/test_web_api/test_common.pytest/testcases/test_web_api/test_dataset_management/test_dataset_sdk_routes_unit.pytest/testcases/test_web_api/test_kb_app/test_kb_pipeline_tasks.pytest/testcases/test_web_api/test_kb_app/test_kb_routes_unit.pyweb/src/pages/dataset/dataset/generate-button/hook.tsweb/src/services/knowledge-service.tsweb/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
Signed-off-by: noob <[email protected]>
There was a problem hiding this comment.
♻️ Duplicate comments (1)
api/apps/restful_apis/dataset_api.py (1)
434-438:⚠️ Potential issue | 🟡 MinorHarden tag mutation body validation for empty values and JSON parse failures.
delete_tagsandrename_tagstill 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_TYPEScouples this route to a private implementation detail. Prefer a public constant/helper in the service API, or rely ondataset_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
📒 Files selected for processing (2)
api/apps/restful_apis/dataset_api.pytest/testcases/test_http_api/common.py
There was a problem hiding this comment.
🧹 Nitpick comments (1)
web/src/utils/api.ts (1)
75-78: Constrain and encodeindexTypein index URL buildersOn Line 75 and Line 77,
indexTypeis typed asstringand 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
📒 Files selected for processing (4)
test/testcases/test_web_api/test_common.pytest/testcases/test_web_api/test_kb_app/test_kb_pipeline_tasks.pyweb/src/services/knowledge-service.tsweb/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
Signed-off-by: noob <[email protected]>
There was a problem hiding this comment.
🧹 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"] != 0can 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
📒 Files selected for processing (2)
test/testcases/test_http_api/test_dataset_management/test_get_dataset.pytest/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
Signed-off-by: noob <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
…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]>
…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` |
What problem does this PR solve?
Summary
Refactor the dataset API layer into a clean service/REST separation pattern, add a unified
/indexAPI for graph/raptor/mindmap operations, and introduce several new dataset management endpoints with full test coverage.Changes
Service Layer (
dataset_api_service.py)trace_index(dataset_id, tenant_id, index_type)— unified trace function for all index typesrun_index,delete_indexservice functionsget_dataset,get_ingestion_summary,list_ingestion_logs,get_ingestion_logrun_embedding,list_tags,aggregate_tags,delete_tags,rename_tagget_flattened_metadata,get_auto_metadata,update_auto_metadataREST API Layer (
dataset_api.py)New unified routes:
/datasets/<id>/index?type=graph|raptor|mindmap/datasets/<id>/index?type=graph|raptor|mindmap/datasets/<id>/<index_type>/datasets/<id>/datasets/<id>/ingestions/summary/datasets/<id>/ingestions/datasets/<id>/ingestions/<log_id>/datasets/<id>/embedding/datasets/<id>/tags/datasets/tags/aggregation/datasets/<id>/tags/datasets/<id>/tags/datasets/metadata/flattened/datasets/<id>/metadata/configRemoved routes (replaced by unified
/index):POST /datasets/<id>/mindmapGET /datasets/<id>/mindmapPreserved legacy routes (backward compatibility):
/run_graphrag,/trace_graphrag,/run_raptor,/trace_raptor/auto_metadataGET/PUTTest Suite
common.pyhelpers: addedtrace_index, removedrun_mindmap/trace_mindmaptest_get_dataset.pytest_ingestion_summary.pytest_ingestion_logs.pytest_index_api.pytest_embedding.pytest_tags.pytest_flattened_metadata.pytest_mindmap_tasks.py(covered by unified index tests)Design Decisions
/index?type=...— single endpoint replaces 3 separate route pairs for graph/raptor/mindmap/run_graphrag,/run_raptor,/auto_metadata) preserved alongside new paths_VALID_INDEX_TYPES = {"graph", "raptor", "mindmap"}— input validation via constant set_INDEX_TYPE_TO_TASK_ID_FIELD— maps index type to KB model task ID field for clean dispatchFiles Changed
api/apps/restful_apis/dataset_api.pyapi/apps/services/dataset_api_service.pysdk/python/ragflow_sdk/modules/dataset.pytest/testcases/test_http_api/common.pytest/testcases/test_http_api/test_dataset_management/(7 new files)Type of change