Skip to content

Refactor: migrate chunk retrieval_test and knowledge_graph to REST API endpoints - #14402

Merged
wangq8 merged 19 commits into
infiniflow:mainfrom
euvre:add-more-api
Apr 28, 2026
Merged

wangq8 merged 19 commits into
infiniflow:mainfrom
euvre:add-more-api

Conversation

@euvre

@euvre euvre commented Apr 27, 2026

Copy link
Copy Markdown
Contributor

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

Changes

Backend

  • api/apps/services/dataset_api_service.py: Add search() service function that extracts retrieval test logic from the old chunk_app.py, adapted for a single dataset_id instead of kb_ids list.
  • api/apps/restful_apis/dataset_api.py:
    • Add POST /datasets/<dataset_id>/search route.
    • Replace old GET /datasets/<dataset_id>/graph/search with GET /datasets/<dataset_id>/graph (aligns with REST conventions).
  • api/apps/chunk_app.py: Remove retrieval_test and knowledge_graph endpoints.

Frontend

  • web/src/utils/api.ts: Update retrievalTest to a dynamic URL function with datasetId; update getKnowledgeGraph URL from /graph/search to /graph.
  • web/src/services/knowledge-service.ts: Move retrievalTest out of registerServer into a custom method that injects datasetId into the URL.

Tests

  • Added: test/testcases/test_http_api/test_dataset_management/test_search.py — covers auth, missing params, basic search, search with doc_ids, and parameter variations.
  • Updated: test/testcases/test_http_api/common.py — add search_dataset() helper; update knowledge_graph() URL to /graph.
  • Removed: test/testcases/test_web_api/test_chunk_app/test_retrieval_chunks.py (308 lines)
  • Removed: test_retrieval_test_branch_matrix_unit and test_knowledge_graph_repeat_deal_matrix_unit from test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py
  • Removed: retrieval_chunks(), knowledge_graph(), delete_knowledge_graph() from test/testcases/test_web_api/test_common.py

Type of change

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

euvre added 2 commits April 27, 2026 19:27
Signed-off-by: noob <[email protected]>
Signed-off-by: noob <[email protected]>
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 27, 2026
@coderabbitai

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

Removes the standalone chunk_app and its endpoints; introduces a dataset-scoped POST /datasets/:id/search service with metadata-filtering, optional LLM rewrite/keyword extraction, model selection, optional KG augmentation, retrieval and result normalization; adds GET /datasets/:id/graph; updates frontend API mappings and tests accordingly.

Changes

Cohort / File(s) Summary
Removed chunk app
api/apps/chunk_app.py
Deleted module and its two endpoints (POST /retrieval_test, GET /knowledge_graph) and related imports/handlers.
Dataset API & service
api/apps/restful_apis/dataset_api.py, api/apps/services/dataset_api_service.py
Adds POST /datasets/<id>/search handler and new async search(...) service: access checks, metadata-filter construction (including search-config/auto flow using an LLMBundle), cross-language rewrite/keyword extraction, embedding/rerank model selection, retriever call with thresholds/weights, optional KG augmentation, child-expansion, vector stripping, labeling, and structured responses. Also adds GET /datasets/<id>/graph handler.
Validation schema
api/utils/validation_utils.py
Adds SearchDatasetReq Pydantic model describing request fields and defaults for dataset search.
Backend tests — helpers & removals
test/testcases/test_http_api/common.py, test/testcases/test_web_api/test_common.py
Updates knowledge_graph helper route, adds search_dataset helper, and removes wrappers targeting deleted chunk endpoints.
Deleted test suites
test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py, test/testcases/test_web_api/test_chunk_app/test_retrieval_chunks.py
Removes unit/integration tests covering the removed chunk endpoints and many related scenarios (validation, ownership, KG parsing, pagination, concurrency).
New dataset search tests
test/testcases/test_http_api/test_dataset_management/test_search.py
Adds HTTP tests for dataset-scoped search/graph: auth failure, missing question, successful search responses, doc_id filtering, and parameterized tuning (page, size, similarity_threshold, vector_similarity_weight, top_k).
Frontend API & service mappings
web/src/utils/api.ts, web/src/services/knowledge-service.ts
Updates API mappings: getKnowledgeGraph -> /api/v1/datasets/:id/graph; retrievalTest changed to function (datasetId) => /api/v1/datasets/:datasetId/search; removes old chunk knowledgeGraph mapping and adapts client call sites.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Client
  participant API as Dataset API
  participant Service as Dataset Service
  participant LLM as LLM / Rewriter
  participant Retriever as Vector DB / Retriever
  participant KG as Knowledge Graph Service

  Client->>API: POST /datasets/:id/search (payload)
  API->>Service: forward request + auth/dataset check
  alt metadata-filter requires auto/semi_auto
    Service->>LLM: build/apply metadata filter (LLMBundle)
    LLM-->>Service: constrained local_doc_ids / filter
  end
  alt cross-language or keyword extraction enabled
    Service->>LLM: rewrite query / extract keywords
    LLM-->>Service: rewritten query / keywords
  end
  Service->>Retriever: vector search (model, rerank, thresholds, filters)
  Retriever-->>Service: retrieved chunks
  alt use_kg enabled
    Service->>KG: query KG for related nodes/documents
    KG-->>Service: KG results
    Service->>Retriever: fetch KG-linked chunks
    Retriever-->>Service: additional chunks
  end
  Service->>Service: post-process (expand children, strip vectors, label, compute total)
  Service-->>API: structured search response
  API-->>Client: 200 JSON (ranked chunks / graph)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

🐖api, python, 🧰 typescript

Suggested reviewers

  • yuzhichang
  • JinHai-CN
  • yingfeng

Poem

🐰 I hopped through routes both old and new,
nudged chunks to datasets, split graphs from view,
tests pruned like carrots, APIs realigned,
rewrites and KG fluff neatly combined,
a happy rabbit cheered: "Search now redesigned!"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.53% 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 pull request title accurately describes the primary change: migrating chunk retrieval_test and knowledge_graph endpoints to REST API endpoints, which is the main objective of this PR.
Description check ✅ Passed The pull request description covers all required template sections with comprehensive detail: problem statement with endpoint mapping table, type of change (New Feature) is selected, and detailed backend/frontend/test changes are documented.
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 💞 feature Feature request, pull request that fullfill a new feature. 🧪 test Pull requests that update test cases. labels Apr 27, 2026
Signed-off-by: noob <[email protected]>
@euvre euvre added the ci Continue Integration label Apr 27, 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 (3)
web/src/services/knowledge-service.ts (1)

144-149: Guard against missing datasetId.

getDatasetId(params) returns undefined when none of dataset_id/kb_id/knowledge_id is set, in which case the URL becomes …/datasets/undefined/search and the request silently fails with a confusing 404/500 instead of a clear client-side error. Other dataset-scoped exports in this file (e.g. listDocument at line 274) explicitly throw when the id is missing — match that pattern here:

♻️ Proposed defensive guard
   retrievalTest: async (params: Record<string, any>) => {
     const datasetId = getDatasetId(params);
+    if (!datasetId) {
+      throw new Error('dataset_id (or kb_id/knowledge_id) is required for retrievalTest');
+    }
     return request.post(api.retrievalTest(datasetId), {
       data: params,
     });
   },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/services/knowledge-service.ts` around lines 144 - 149, The
retrievalTest function should validate that getDatasetId(params) returns a value
before building the URL; currently it can be undefined and cause a confusing
404/500. Update retrievalTest to mirror the pattern used by listDocument: call
getDatasetId(params), and if the result is falsy, throw a clear Error like
"datasetId is required" (or similar) before calling
request.post(api.retrievalTest(datasetId), ...); otherwise proceed with the
existing request.post call. Ensure you reference the retrievalTest function and
getDatasetId helper when making this guard.
api/apps/services/dataset_api_service.py (1)

904-1031: Add logging for the new search flow.

Per coding guidelines, new Python flows should add logging. The new search() is a non-trivial async retrieval pipeline (access checks, model bundle selection, optional KG augmentation, reranking) but emits no logs at all — making post-deploy issues (e.g., model-config lookup failures, missing search configs, empty retrieval results, KG retrieval errors) hard to diagnose. At minimum, log a debug entry for the request shape and a warning/exception around the KG block and retriever calls similar to other handlers in this module.

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

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

In `@api/apps/services/dataset_api_service.py` around lines 904 - 1031, The
search() flow currently has no logs; add a module logger
(logging.getLogger(__name__)) and instrument search() to log key checkpoints and
failures: log a debug entry at start with dataset_id, tenant_id and a redacted
request shape; log warnings when access checks fail (when
KnowledgebaseService.accessible or get_by_id fail) and when meta_data_filter
changes local_doc_ids; after selecting models log info/debug about embd_mdl,
rerank_mdl and chat_mdl choices (reference variables embd_mdl, rerank_mdl,
chat_mdl and functions get_model_config_by_id/get_tenant_default_model_by_type);
wrap the main retrieval calls (settings.retriever.retrieval and
settings.kg_retriever.retrieval) in try/except and log exceptions with context
(including dataset_id, tenant_ids, top) and log a warning if ranks["chunks"] or
ck["content_with_weight"] are empty; ensure sensitive data from req is redacted
in logs.
api/apps/restful_apis/dataset_api.py (1)

479-515: Add OpenAPI documentation to match surrounding handlers.

The search and get_knowledge_graph routes lack docstring and OpenAPI/swagger specifications, unlike surrounding handlers (create, update, delete, etc.) in this file. Add docstrings describing the request parameters (such as question, doc_ids, top_k, etc.) and response structure for consistency and API discoverability.

The exception handling for "not_found" is consistent with established patterns elsewhere in the codebase (api/apps/sdk/doc.py:529, api/apps/sdk/session.py:422), so no changes needed there.

🤖 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 479 - 515, Add
OpenAPI-style docstrings to the search and get_knowledge_graph route handlers to
match surrounding handlers: document the HTTP method, path parameters
(dataset_id), tenant injection, expected request JSON for search (required
"question", optional "doc_ids", "top_k", "filters", etc.), response schema
(success flag, data payload, error messages and RetCode usage), and possible
error responses; add a brief one-line summary and parameter descriptions at the
top of the search and get_knowledge_graph functions (names: search,
get_knowledge_graph) following the same docstring format used by
create/update/delete handlers so automatic swagger/OpenAPI generators pick them
up. Ensure the docstrings describe the GET/POST semantics and include examples
or types for request/response fields for consistency.
🤖 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 522-540: There are duplicate helper functions for the /graph
route: keep a single canonical pair and remove the duplicates so imports don't
get shadowed; specifically, remove the later get_knowledge_graph(...) and the
second delete_knowledge_graph(...) definitions and retain the original
knowledge_graph(auth, dataset_id, params=None) and delete_knowledge_graph(auth,
dataset_id, payload=None) (or replace the originals with the new
implementations, but not both), ensure the retained helpers use the updated
"/graph" URL and have the signature that callers/tests expect (match callers
that do from common import delete_knowledge_graph, knowledge_graph), and keep
header/auth handling consistent across the retained helper functions.

---

Nitpick comments:
In `@api/apps/restful_apis/dataset_api.py`:
- Around line 479-515: Add OpenAPI-style docstrings to the search and
get_knowledge_graph route handlers to match surrounding handlers: document the
HTTP method, path parameters (dataset_id), tenant injection, expected request
JSON for search (required "question", optional "doc_ids", "top_k", "filters",
etc.), response schema (success flag, data payload, error messages and RetCode
usage), and possible error responses; add a brief one-line summary and parameter
descriptions at the top of the search and get_knowledge_graph functions (names:
search, get_knowledge_graph) following the same docstring format used by
create/update/delete handlers so automatic swagger/OpenAPI generators pick them
up. Ensure the docstrings describe the GET/POST semantics and include examples
or types for request/response fields for consistency.

In `@api/apps/services/dataset_api_service.py`:
- Around line 904-1031: The search() flow currently has no logs; add a module
logger (logging.getLogger(__name__)) and instrument search() to log key
checkpoints and failures: log a debug entry at start with dataset_id, tenant_id
and a redacted request shape; log warnings when access checks fail (when
KnowledgebaseService.accessible or get_by_id fail) and when meta_data_filter
changes local_doc_ids; after selecting models log info/debug about embd_mdl,
rerank_mdl and chat_mdl choices (reference variables embd_mdl, rerank_mdl,
chat_mdl and functions get_model_config_by_id/get_tenant_default_model_by_type);
wrap the main retrieval calls (settings.retriever.retrieval and
settings.kg_retriever.retrieval) in try/except and log exceptions with context
(including dataset_id, tenant_ids, top) and log a warning if ranks["chunks"] or
ck["content_with_weight"] are empty; ensure sensitive data from req is redacted
in logs.

In `@web/src/services/knowledge-service.ts`:
- Around line 144-149: The retrievalTest function should validate that
getDatasetId(params) returns a value before building the URL; currently it can
be undefined and cause a confusing 404/500. Update retrievalTest to mirror the
pattern used by listDocument: call getDatasetId(params), and if the result is
falsy, throw a clear Error like "datasetId is required" (or similar) before
calling request.post(api.retrievalTest(datasetId), ...); otherwise proceed with
the existing request.post call. Ensure you reference the retrievalTest function
and getDatasetId helper when making this guard.
🪄 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: 2196775e-dae1-4082-b97e-84fb1c00e3e1

📥 Commits

Reviewing files that changed from the base of the PR and between 488c3ef and 8cb611c.

📒 Files selected for processing (9)
  • api/apps/chunk_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_web_api/test_chunk_app/test_chunk_routes_unit.py
  • test/testcases/test_web_api/test_chunk_app/test_retrieval_chunks.py
  • test/testcases/test_web_api/test_common.py
  • web/src/services/knowledge-service.ts
  • web/src/utils/api.ts
💤 Files with no reviewable changes (4)
  • test/testcases/test_web_api/test_chunk_app/test_retrieval_chunks.py
  • test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py
  • test/testcases/test_web_api/test_common.py
  • api/apps/chunk_app.py

Comment thread test/testcases/test_http_api/common.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

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

37-72: Add a smoke test for the new graph endpoint.

This module covers /datasets/<id>/search, but the PR also moves knowledge-graph to /datasets/<id>/graph and removes the legacy path. One auth check plus one happy-path check here would protect that migration too.

🤖 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_search.py` around
lines 37 - 72, Add two tests for the new dataset graph endpoint: one auth check
and one happy-path. Create a helper analogous to search_dataset (name it
graph_dataset) that calls GET/POST /datasets/<id>/graph; add a test (e.g.,
test_graph_requires_auth) that calls graph_dataset without HttpApiAuth and
asserts an auth error code, and add a happy-path test (e.g., test_graph_basic)
that uses HttpApiAuth with add_chunks/add_dataset_func to call graph_dataset and
asserts success (code 0) and presence of expected keys like "nodes" or "edges"
in res["data"]; place them alongside TestDatasetSearch or in a new
TestDatasetGraph class. Ensure you reference graph_dataset,
TestDatasetSearch/TestDatasetGraph, HttpApiAuth, add_chunks/add_dataset_func
when adding the tests.
🤖 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 492-505: The handler currently reads raw JSON via
get_request_json() and only checks `question`, allowing invalid
pagination/similarity fields (page/size/top_k/similarity) to reach
dataset_api_service.search() and cause 500s; switch to the shared validation
flow by using validate_and_parse_json_request(...) to parse and validate the
incoming payload (same schema used by other dataset endpoints), reject bad
values with a client error before calling dataset_api_service.search(dataset_id,
tenant_id, req), and keep the existing success/error handling and exception
mapping for not_found; update references in this function to use the validated
request output instead of get_request_json().

In `@api/apps/services/dataset_api_service.py`:
- Around line 1031-1032: The code overwrites the retriever-provided hit count by
setting ranks["total"] = len(ranks["chunks"]) after calling
settings.retriever.retrieval_by_children; instead preserve the original
retriever total (e.g., save orig_total = ranks.get("total") before calling
retrieval_by_children) and after post-processing only set ranks["total"] to
orig_total if it exists, otherwise fall back to len(ranks["chunks"]); update the
logic around ranks["chunks"], ranks["total"], and the call to
settings.retriever.retrieval_by_children(...) so pagination metadata returned by
the retriever is not lost.
- Line 927: The debug log currently prints raw user-supplied search text in the
logging.debug call (the "search(...)" message using dataset_id, tenant_id,
req.get("question", "")[:50]) — replace the user content with a non-sensitive
indicator such as the question length or a redacted token; e.g., compute
question = req.get("question", "") and log dataset_id, tenant_id and
len(question) (or "redacted") instead of question[:50] to avoid writing
PII/secrets to logs while keeping the logging.debug invocation and variables
(dataset_id, tenant_id, req) intact.

---

Nitpick comments:
In `@test/testcases/test_http_api/test_dataset_management/test_search.py`:
- Around line 37-72: Add two tests for the new dataset graph endpoint: one auth
check and one happy-path. Create a helper analogous to search_dataset (name it
graph_dataset) that calls GET/POST /datasets/<id>/graph; add a test (e.g.,
test_graph_requires_auth) that calls graph_dataset without HttpApiAuth and
asserts an auth error code, and add a happy-path test (e.g., test_graph_basic)
that uses HttpApiAuth with add_chunks/add_dataset_func to call graph_dataset and
asserts success (code 0) and presence of expected keys like "nodes" or "edges"
in res["data"]; place them alongside TestDatasetSearch or in a new
TestDatasetGraph class. Ensure you reference graph_dataset,
TestDatasetSearch/TestDatasetGraph, HttpApiAuth, add_chunks/add_dataset_func
when adding the tests.
🪄 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: 51f38452-5d00-4ba3-bb25-5ba0acd8d81c

📥 Commits

Reviewing files that changed from the base of the PR and between 77c5547 and e2c5182.

📒 Files selected for processing (8)
  • 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_search.py
  • test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py
  • test/testcases/test_web_api/test_common.py
  • web/src/services/knowledge-service.ts
  • web/src/utils/api.ts
💤 Files with no reviewable changes (2)
  • test/testcases/test_web_api/test_common.py
  • test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/testcases/test_http_api/common.py

Comment thread api/apps/restful_apis/dataset_api.py Resolved
@codecov

codecov Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14402   +/-   ##
=======================================
  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.

euvre and others added 4 commits April 28, 2026 11:29

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 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/services/dataset_api_service.py`:
- Around line 955-957: The code dereferences
SearchService.get_detail(...).get(...) without checking that get_detail returned
a non-None/dict result; update the block to first pull req.get("search_id","")
into a variable (e.g., search_id), call SearchService.get_detail(search_id) and
verify the result is truthy and a mapping before calling .get on it, and if it
is None/invalid return/raise a client validation error or set search_config to
{} so meta_data_filter = search_config.get("meta_data_filter", {}) is safe;
reference SearchService.get_detail, search_config, meta_data_filter and req when
making this change.
- Around line 937-951: The code currently does local_doc_ids = list(doc_ids)
which silently converts non-list values (e.g., a string) into a list of
characters; validate the incoming req["doc_ids"] before coercion by checking if
doc_ids is None or an instance of list (and optionally that each element is the
correct type), and if it's not a list return a clear error (e.g., False,
"doc_ids must be a list"); then set local_doc_ids = list(doc_ids) only after
that validation. Reference variables: doc_ids and local_doc_ids (and the
surrounding access checks using KnowledgebaseService.accessible/get_by_id to
maintain flow).

In `@test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py`:
- Around line 494-501: The helper _load_chunk_module currently only assigns
module when module_path.exists() is true, but always returns module, causing
UnboundLocalError when chunk_app.py is missing; fix by initializing module =
None before the if or explicitly return None when module_path.exists() is false
so callers get a clear None result; update references to module_name, spec,
module.manager/_DummyManager, monkeypatch and spec.loader.exec_module
accordingly to only run inside the if block and ensure sys.modules is only
modified when module is created.
🪄 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: aab6a0c9-2d3b-4dd3-80a2-56a2d1ddcae3

📥 Commits

Reviewing files that changed from the base of the PR and between e2c5182 and 01e631d.

📒 Files selected for processing (3)
  • api/apps/services/dataset_api_service.py
  • test/testcases/test_http_api/test_dataset_management/test_search.py
  • test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/testcases/test_http_api/test_dataset_management/test_search.py

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.

Actionable comments posted: 2

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

512-532: Add a breadcrumb log for the new /graph flow.

This migrated endpoint only logs on unhandled exceptions, so successful or soft-failure calls leave no trace with tenant_id/dataset_id. A small debug/info log before the service call would make rollout issues much easier to diagnose.

Suggested fix
 async def get_knowledge_graph(tenant_id, dataset_id):
     """Get the knowledge graph of a dataset.
@@
     Errors: AUTHENTICATION_ERROR for access denied; DATA_ERROR for internal errors.
     """
+    logging.debug("get_knowledge_graph(dataset=%s, tenant=%s)", dataset_id, tenant_id)
     try:
         success, result = await dataset_api_service.get_knowledge_graph(dataset_id, tenant_id)

As per coding guidelines, "Add logging for new flows".

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

In `@api/apps/restful_apis/dataset_api.py` around lines 512 - 532, The
get_knowledge_graph endpoint lacks request-level logging; add a breadcrumb log
containing tenant_id and dataset_id just before calling
dataset_api_service.get_knowledge_graph so successful or soft-failure requests
are traceable. Use the existing logging module (e.g., logging.info or
logging.debug) in the get_knowledge_graph function to emit a short message like
"get_knowledge_graph called" with tenant_id and dataset_id included, ensuring
the log occurs immediately before the await
dataset_api_service.get_knowledge_graph(dataset_id, tenant_id) call.
🤖 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/utils/validation_utils.py`:
- Line 825: The field declaration question: Annotated[str, Field(...,
min_length=1)] accepts whitespace-only strings; change validation to strip
whitespace before measuring length. Either replace the annotation with
Annotated[str, constr(strip_whitespace=True, min_length=1)] or add a Pydantic
validator for the "question" field that does value = value.strip() and raises
ValueError if not value, ensuring whitespace-only input is rejected; keep the
same field name ("question") so callers remain unchanged.
- Around line 822-835: The SearchDatasetReq model currently drops inputs due to
model_config = ConfigDict(extra="ignore"), causing
validate_and_parse_json_request() to omit meta_data_filter, search_id,
rerank_id, and tenant_rerank_id which are still consumed by
dataset_api_service.py; update SearchDatasetReq to declare those missing fields
(e.g., meta_data_filter: Annotated[dict | None, Field(default=None)] or
appropriate types, and search_id, rerank_id, tenant_rerank_id as Annotated[str |
None, Field(default=None)] or lists if needed) so they are forwarded, or
alternatively change model_config to allow extras and ensure
validate_and_parse_json_request() preserves them—refer to the SearchDatasetReq
class and validate_and_parse_json_request/read sites in dataset_api_service.py
when making the change.

---

Nitpick comments:
In `@api/apps/restful_apis/dataset_api.py`:
- Around line 512-532: The get_knowledge_graph endpoint lacks request-level
logging; add a breadcrumb log containing tenant_id and dataset_id just before
calling dataset_api_service.get_knowledge_graph so successful or soft-failure
requests are traceable. Use the existing logging module (e.g., logging.info or
logging.debug) in the get_knowledge_graph function to emit a short message like
"get_knowledge_graph called" with tenant_id and dataset_id included, ensuring
the log occurs immediately before the await
dataset_api_service.get_knowledge_graph(dataset_id, tenant_id) call.
🪄 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: c4f03dcc-4501-48a5-9456-905b44db3b47

📥 Commits

Reviewing files that changed from the base of the PR and between 01e631d and f980aaf.

📒 Files selected for processing (3)
  • api/apps/restful_apis/dataset_api.py
  • api/utils/validation_utils.py
  • test/testcases/test_http_api/test_dataset_management/test_search.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/testcases/test_http_api/test_dataset_management/test_search.py

Comment thread api/utils/validation_utils.py Resolved
Comment thread api/utils/validation_utils.py Resolved
Signed-off-by: noob <[email protected]>
@wangq8
wangq8 requested a review from xugangqiang April 28, 2026 05:16
Signed-off-by: noob <[email protected]>
@wangq8
wangq8 merged commit 35f6d81 into infiniflow:main Apr 28, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request May 8, 2026
2 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:L This PR changes 100-499 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants