Skip to content

Refa: migrate chunk APIs to RESTful routes - #14291

Merged
wangq8 merged 8 commits into
infiniflow:mainfrom
buua436:r004
Apr 23, 2026
Merged

wangq8 merged 8 commits into
infiniflow:mainfrom
buua436:r004

Conversation

@buua436

@buua436 buua436 commented Apr 22, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

migrate chunk APIs to RESTful routes

Type of change

  • Refactoring

@coderabbitai

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

This PR removes legacy chunk handlers and SDK chunk surfaces, adds a new RESTful chunk API under api/apps/restful_apis/chunk_api.py, updates docs, adjusts frontend API/service/hooks to the new routes, and migrates tests/fixtures to dataset/document-scoped chunk endpoints and payload shapes.

Changes

Cohort / File(s) Summary
Backend: legacy removal
api/apps/chunk_app.py
Removed legacy chunk REST handlers and imports used only by those handlers.
Backend: new REST API
api/apps/restful_apis/chunk_api.py
Added RESTful chunk endpoints (list/get/add/update/delete/switch), Pydantic Chunk model (positions validator), tenant/document access checks, embedding/image handling, retriever/docstore flows, and response shaping.
Backend SDK surface
api/apps/sdk/doc.py, sdk/python/ragflow_sdk/modules/chunk.py
Removed SDK chunk endpoints and Chunk model from doc.py; changed SDK client update to use PATCH.
API docs
docs/references/http_api_reference.md, docs/references/python_api_reference.md
Added GET chunk-by-id, changed PUT→PATCH for update, added/renamed fields (questions, positions, image_base64), and updated paths to datasets/documents.
Tests: helpers & fixtures
test/testcases/test_http_api/common.py, test/testcases/test_web_api/conftest.py, test/testcases/test_http_api/.../conftest.py
Updated test helpers/fixtures to new signatures (dataset_id, document_id), added get_chunk, batch fixtures, and adapted cleanup/listing to use id.
Tests: unit & route
test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py, test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
Repointed unit tests to restful_apis/chunk_api.py, added module loaders/unwrappers, expanded mocks (DocumentService, KnowledgebaseService, tenant model, image utils), and updated assertions to REST response shapes.
Tests: operation suites
test/testcases/test_web_api/test_chunk_app/*, test/testcases/test_http_api/test_chunk_management_within_dataset/*
Updated create/list/update/delete tests to new endpoints and payloads (content, important_keywords, questions, tag_kwd, available), added get-by-id tests, and changed auth/ownership expectations.
Frontend: API map & service
web/src/utils/api.ts, web/src/services/knowledge-service.ts
Replaced fixed chunk route strings with parameterized REST v1 routes, added chunkDetail, and mapped legacy request/response shapes in kbService to call new REST endpoints.
Frontend: hooks & components
web/src/hooks/use-chunk-request.ts, web/src/hooks/route-hook.ts, web/src/pages/**/chunk-creating-modal/*.tsx, web/src/pages/dataset/.../overview-table.tsx
Added documentId to fetch hook, included knowledgeId/kb_id in payloads, passed doc_id into fetch hooks, and removed obsolete delete hook usage.
Misc tests & utilities
test/unit_test/common/test_delete_query_construction.py, test/testcases/test_web_api/test_common.py, test/testcases/test_web_api/test_kb_app/test_kb_tags_meta.py
Renamed test classes/docstrings to reference REST chunk API; updated test helpers and endpoint templates/signatures.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ChunkAPI as Chunk API
  participant KB as KnowledgebaseService
  participant Doc as DocumentService
  participant Emb as EmbeddingService
  participant Store as ImageStore
  participant Retriever

  Client->>ChunkAPI: HTTP request (list/get/add/update/delete/switch)
  ChunkAPI->>KB: validate tenant/dataset access
  ChunkAPI->>Doc: validate document ownership / fetch document metadata
  alt add/update needs embedding
    ChunkAPI->>Emb: compute embedding vector
  end
  alt image upload/remove
    ChunkAPI->>Store: store or delete image (base64)
  end
  alt list/search via retriever
    ChunkAPI->>Retriever: search with keywords/paging/highlight
    Retriever-->>ChunkAPI: search results
  else direct docstore lookup
    Doc-->>ChunkAPI: chunk record(s)
  end
  ChunkAPI-->>Client: normalized JSON response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • JinHai-CN
  • yuzhichang
  • yingfeng

Poem

🐰 I nibbled through handlers, one by one,

I hopped them into REST where new routes run,
Tokens, images, embeddings in a line,
Now chunks leap tidy — tidy and fine,
🥕 Hooray — a rabbit's patch, small and fun!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.96% 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 'Refa: migrate chunk APIs to RESTful routes' directly and clearly summarizes the main objective of the PR, which is a refactoring effort to migrate chunk-related APIs to RESTful routes.
Description check ✅ Passed The PR description is minimal but addresses the template sections; it identifies the problem (migrate chunk APIs to RESTful routes) and correctly marks the change type as Refactoring. However, it lacks substantial detail about implementation scope, impact, and testing.
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.

@buua436 buua436 added the ci Continue Integration label Apr 22, 2026
@buua436
buua436 marked this pull request as ready for review April 22, 2026 08:04
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 🌈 python Pull requests that update Python code 🐖api The modified files are located under directory 'api/apps/sdk' 🧪 test Pull requests that update test cases. 🧰 typescript Pull requests that update Typescript code labels Apr 22, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 13

🧹 Nitpick comments (3)
web/src/hooks/route-hook.ts (1)

31-40: Pathname-based branching for query-key name is a leaky abstraction.

This hook now hard-codes the knowledge that the dataflow-result page uses the raw key 'knowledgeId' while everywhere else uses KnowledgeSearchParams.KnowledgeId. Every page added later that happens to use the raw key will have to be appended to this branch. Consider either (a) normalizing the key at the navigation helper in navigate-hooks.ts so both flows produce the same query-key, or (b) having this hook fall back across both keys without inspecting the pathname:

♻️ Proposed refactor (option b)
-  const [currentQueryParameters] = useSearchParams();
-  const { pathname } = useLocation();
-  const isDataflowResultPage = pathname === Routes.DataflowResult;
-
-  return {
-    type: currentQueryParameters.get(KnowledgeSearchParams.Type) || '',
-    documentId:
-      currentQueryParameters.get(KnowledgeSearchParams.DocumentId) || '',
-    knowledgeId: isDataflowResultPage
-      ? currentQueryParameters.get('knowledgeId') || ''
-      : currentQueryParameters.get(KnowledgeSearchParams.KnowledgeId) || '',
-  };
+  const [currentQueryParameters] = useSearchParams();
+
+  return {
+    type: currentQueryParameters.get(KnowledgeSearchParams.Type) || '',
+    documentId:
+      currentQueryParameters.get(KnowledgeSearchParams.DocumentId) || '',
+    knowledgeId:
+      currentQueryParameters.get(KnowledgeSearchParams.KnowledgeId) ||
+      currentQueryParameters.get('knowledgeId') ||
+      '',
+  };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/hooks/route-hook.ts` around lines 31 - 40, The hook currently
branches on pathname (isDataflowResultPage) to decide whether to read the raw
'knowledgeId' query key or KnowledgeSearchParams.KnowledgeId, which is a leaky
abstraction; update the return logic in route-hook.ts (the code that reads
currentQueryParameters) to stop inspecting pathname and instead read both keys
with a deterministic preference (e.g., prefer
currentQueryParameters.get(KnowledgeSearchParams.KnowledgeId) and fall back to
currentQueryParameters.get('knowledgeId') if missing) for the knowledgeId field,
and remove the isDataflowResultPage branch so all consumers get the normalized
value.
web/src/pages/chunk/parsed-result/add-knowledge/components/knowledge-chunk/components/chunk-creating-modal/index.tsx (1)

278-280: Remove commented-out delete UI block.

The delete button's JSX and its handler were removed as part of this refactor. Leaving the commented-out block behind is dead code and clutters the render tree; please delete it (or, if the delete action is still intended, restore useDeleteChunkByIds and handleRemove).

♻️ Proposed cleanup
-            {/* <div className="flex items-center gap-1" onClick={handleRemove}>
-              <Trash2 size={16} /> {t('common.delete')}
-            </div> */}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@web/src/pages/chunk/parsed-result/add-knowledge/components/knowledge-chunk/components/chunk-creating-modal/index.tsx`
around lines 278 - 280, Remove the leftover commented-out delete JSX block (the
<div className="flex items-center gap-1" onClick={handleRemove}> containing
Trash2 and {t('common.delete')}) from the component render; if the delete
feature is intended to remain, instead restore the associated hook and handler
by reintroducing useDeleteChunkByIds and the handleRemove function used by that
onClick, otherwise simply delete the commented lines to eliminate dead code and
clutter.
test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py (1)

497-507: Avoid importing the legacy chunk app for REST-only tests.

_load_chunk_api_module() imports api/apps/chunk_app.py through _load_chunk_module() just to set up mocks, so REST route tests can fail because of unrelated legacy-module changes. Split the mock installation from the legacy import, then load only api/apps/restful_apis/chunk_api.py here.

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

In `@test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py` around
lines 497 - 507, The helper _load_chunk_api_module currently calls
_load_chunk_module(monkeypatch) which imports the legacy chunk app; remove that
call and instead install only the mocks needed (e.g., set module.manager =
_DummyManager()) without importing the legacy module, then create and exec the
spec for the REST-only module (the same code that builds module_name, spec,
module, monkeypatch.setitem(sys.modules, module_name, module), and
spec.loader.exec_module(module)) so tests load only the RESTful chunk_api
module; update _load_chunk_api_module to not delegate to _load_chunk_module and
to set up mocks directly before loading chunk_api.
🤖 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/chunk_api.py`:
- Around line 183-197: In get_chunk, treat a missing chunk as a DATA_ERROR/404
instead of throwing a 500: replace the server_error_response(Exception("Chunk
not found")) path with returning get_result(data=False, message="Chunk not
found!", code=RetCode.DATA_ERROR) and ensure you handle both behaviors of
settings.docStoreConn.get (it may return None or raise a NotFoundError string):
catch the specific not-found case from the get exception (matching
"NotFoundError") and return the same get_result(...) for consistency, otherwise
re-raise or return server_error_response(e) for unexpected exceptions; update
the return that currently uses _strip_chunk_runtime_fields(chunk) to remain
unchanged when chunk exists.
- Around line 333-342: In update_chunk, you're fetching the chunk
(settings.docStoreConn.get) before verifying dataset ownership and never
checking the chunk's doc_id against the supplied document_id; move the
KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id) ownership
check to run before fetching the chunk to avoid leaking existence, then after
retrieving the chunk in update_chunk validate that chunk.get("doc_id") ==
document_id and return an error if it does not match; ensure subsequent
operations that update the docstore and recompute embeddings (which use doc.name
from DocumentService.query) only run when the ownership and doc_id match.
- Around line 99-147: The list_chunks handler's req.get("id") branch in
list_chunks bypasses document-level scoping and contains an unreachable `if not
chunk:` check; remove this entire `?id=` branch (the code that calls
settings.docStoreConn.get, _strip_chunk_runtime_fields, builds final_chunk and
instantiates Chunk) and rely on the existing GET /chunks/<chunk_id> endpoint, or
if you prefer to keep it, enforce that the returned chunk's doc_id/document_id
matches the route document_id before returning and delete the redundant `if not
chunk:` after _strip_chunk_runtime_fields; update references to
_strip_chunk_runtime_fields, final_chunk creation, and the Chunk(**final_chunk)
instantiation accordingly so ownership is always validated by document_id.
- Line 21: Replace the deprecated pydantic v1 `validator` import with
`field_validator` in the import line (swap `validator` for `field_validator` in
the from pydantic import ... list) and update the validator on the model to use
`@field_validator` instead of `@validator`; also mark the validation function as
a classmethod by adding `@classmethod` above it (the validator decorator and
function on the model around line 63). Ensure the decorator call signature
remains the same (e.g., same field names/arguments) so the validation logic in
that BaseModel subclass continues to run under pydantic v2.
- Around line 289-327: rm_chunk currently raises a LookupError when
DocumentService.get_by_ids([document_id]) returns empty and doesn't verify the
document belongs to the requested dataset; replace the raise with a normal error
response and add a dataset binding check: after calling
DocumentService.get_by_ids in rm_chunk, if docs is empty return
get_error_data_result with a clear message instead of raising, and if
docs[0].kb_id != dataset_id return get_error_data_result indicating the document
does not belong to the dataset; keep the rest of rm_chunk logic unchanged so
deletions remain scoped to the dataset.

In `@docs/references/http_api_reference.md`:
- Line 572: The docs contain a typo in the allowed "chunk_method" values:
replace the misspelled "manuel" with "manual" wherever it appears in the
"chunk_method" list and in the related "parser_config" descriptions (e.g., the
block listing values including "qa", "manuel", "paper", etc. and the duplicate
at the other occurrence); update both occurrences so the valid chunk_method
value is "manual" and ensure any example or explanatory text referencing
"manuel" is corrected to "manual".
- Around line 2598-2599: Fix the schema text for the "deletes" body parameter:
close the missing quote on the parameter name and correct the typo
`list[ojbect]` to `list[object]` so the line reads `"deletes`: (*Body
parameter*), `list[object]`, *optional* (each object: `{ "key": string, "value":
string }`).
- Around line 2726-2728: Replace the generic "[here]" links with descriptive
link text: for the knowledge graph mention next to the multi-hop option (the
paragraph referencing constructing a knowledge graph) change the link to
something like "construct a knowledge graph" and for the `"toc_enhance"`
paragraph change the link text to "enable table of contents" (or similar
descriptive phrasing) while keeping the existing target URLs; update the
markdown in those sentences so the link text describes the destination rather
than using "[here]".
- Around line 2224-2237: The GET /chunks/{chunk_id} response currently leaks
storage-field names (content_with_weight, doc_id, img_id, important_kwd,
question_kwd, tag_kwd); update the handler and the docs to return the normalized
public chunk shape used by other chunk endpoints — map content_with_weight ->
content (include weight separately if needed), doc_id -> document_id, img_id ->
image_id, important_kwd -> important_keywords, question_kwd ->
question_keywords, tag_kwd -> tags, and keep id/docnm_kwd as id/file_name (or
the canonical names used elsewhere). Ensure the GET /chunks/{chunk_id} handler
(the get-chunk method handling that route) serializes using the same
DTO/serializer as other chunk endpoints and adjust the example JSON in the docs
to match the normalized field names.

In
`@test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py`:
- Around line 312-319: Tests call the decorated REST handlers
(module.list_chunks, module.add_chunk, module.rm_chunk, module.update_chunk) but
currently hit the `@login_required` and `@add_tenant_id_to_kwargs` decorators;
either call the underlying unwrapped functions (restore and use .__wrapped__ on
those symbols when invoking) or update the test setup to satisfy/mock the
decorators (provide a logged-in user/tenant context or stub login_required and
add_tenant_id_to_kwargs in the imported helper) so the core logic is exercised;
also extract the helper loader _load_chunk_api_module from
test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py into a
shared fixture (e.g., conftest) and have _load_restful_chunk_module import that
to avoid fragile cross-module path coupling.

In `@test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py`:
- Around line 608-612: The test and handler currently treat a missing chunk as
an exception (asserting module.RetCode.EXCEPTION_ERROR and the message "Chunk
not found"); change the get_chunk handler to return a not-found/data error code
instead of using server_error_response when DocumentService.query (or the chunk
lookup in get_chunk) yields no matching chunk_id — return
module.RetCode.NOT_FOUND or module.RetCode.DATA_ERROR with an appropriate
message; then update the test to assert that
get_chunk("tenant-1","kb-1","doc-1","chunk-1") returns the NOT_FOUND/DATA_ERROR
code (not EXCEPTION_ERROR). Ensure server_error_response remains for unexpected
exceptions only.

In `@test/testcases/test_web_api/test_chunk_app/test_create_chunk.py`:
- Around line 37-40: The test asserts the wrong field name for the REST
get-chunk response: update the assertion that checks the returned chunk ID
fields in the test using get_chunk (variable fetched) so it expects
"document_id" instead of "doc_id" and still verifies "id" equals chunk["id"]
(i.e. change the assertion referencing fetched["data"]["doc_id"] to
fetched["data"]["document_id"]); keep the existing checks for fetched["code"]
and fetched["data"]["id"] unchanged.

---

Nitpick comments:
In `@test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py`:
- Around line 497-507: The helper _load_chunk_api_module currently calls
_load_chunk_module(monkeypatch) which imports the legacy chunk app; remove that
call and instead install only the mocks needed (e.g., set module.manager =
_DummyManager()) without importing the legacy module, then create and exec the
spec for the REST-only module (the same code that builds module_name, spec,
module, monkeypatch.setitem(sys.modules, module_name, module), and
spec.loader.exec_module(module)) so tests load only the RESTful chunk_api
module; update _load_chunk_api_module to not delegate to _load_chunk_module and
to set up mocks directly before loading chunk_api.

In `@web/src/hooks/route-hook.ts`:
- Around line 31-40: The hook currently branches on pathname
(isDataflowResultPage) to decide whether to read the raw 'knowledgeId' query key
or KnowledgeSearchParams.KnowledgeId, which is a leaky abstraction; update the
return logic in route-hook.ts (the code that reads currentQueryParameters) to
stop inspecting pathname and instead read both keys with a deterministic
preference (e.g., prefer
currentQueryParameters.get(KnowledgeSearchParams.KnowledgeId) and fall back to
currentQueryParameters.get('knowledgeId') if missing) for the knowledgeId field,
and remove the isDataflowResultPage branch so all consumers get the normalized
value.

In
`@web/src/pages/chunk/parsed-result/add-knowledge/components/knowledge-chunk/components/chunk-creating-modal/index.tsx`:
- Around line 278-280: Remove the leftover commented-out delete JSX block (the
<div className="flex items-center gap-1" onClick={handleRemove}> containing
Trash2 and {t('common.delete')}) from the component render; if the delete
feature is intended to remain, instead restore the associated hook and handler
by reintroducing useDeleteChunkByIds and the handleRemove function used by that
onClick, otherwise simply delete the commented lines to eliminate dead code and
clutter.
🪄 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: 778fde24-61b2-482b-bc9a-9dc06601666c

📥 Commits

Reviewing files that changed from the base of the PR and between b8660b9 and 10321e6.

📒 Files selected for processing (26)
  • api/apps/chunk_app.py
  • api/apps/restful_apis/chunk_api.py
  • api/apps/sdk/doc.py
  • docs/references/http_api_reference.md
  • docs/references/python_api_reference.md
  • sdk/python/ragflow_sdk/modules/chunk.py
  • test/testcases/test_http_api/common.py
  • test/testcases/test_http_api/test_chunk_management_within_dataset/test_list_chunks.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
  • test/testcases/test_web_api/conftest.py
  • test/testcases/test_web_api/test_chunk_app/conftest.py
  • test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py
  • test/testcases/test_web_api/test_chunk_app/test_create_chunk.py
  • test/testcases/test_web_api/test_chunk_app/test_list_chunks.py
  • test/testcases/test_web_api/test_chunk_app/test_rm_chunks.py
  • test/testcases/test_web_api/test_chunk_app/test_update_chunk.py
  • test/testcases/test_web_api/test_common.py
  • test/testcases/test_web_api/test_kb_app/test_kb_tags_meta.py
  • test/unit_test/common/test_delete_query_construction.py
  • web/src/hooks/route-hook.ts
  • web/src/hooks/use-chunk-request.ts
  • web/src/pages/chunk/parsed-result/add-knowledge/components/knowledge-chunk/components/chunk-creating-modal/index.tsx
  • web/src/pages/dataflow-result/components/chunk-creating-modal/index.tsx
  • web/src/pages/dataset/dataset-overview/overview-table.tsx
  • web/src/services/knowledge-service.ts
  • web/src/utils/api.ts

import re

import xxhash
from pydantic import BaseModel, Field, validator

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd -H -t f 'pyproject.toml|requirements.*\.txt|uv\.lock|poetry\.lock' --exec rg -nH '(^|[^A-Za-z])pydantic' {} \;

Repository: infiniflow/ragflow

Length of output: 50374


🌐 Web query:

Is pydantic @validator deprecated in pydantic v2 and what is the replacement?

💡 Result:

Yes, the @validator decorator from Pydantic V1 is deprecated in Pydantic V2. It should be replaced with the new @field_validator decorator, which offers improvements and new features such as better support for ValidationInfo and changes to arguments like removal of each_item (use Annotated instead for containers).

Citations:


🏁 Script executed:

# First, let's examine the chunk_api.py file
cat -n api/apps/restful_apis/chunk_api.py | head -40

Repository: infiniflow/ragflow

Length of output: 1686


🏁 Script executed:

# Look for main project dependencies
fd -H -t f 'pyproject.toml|requirements.txt' -x cat -n {} \;

Repository: infiniflow/ragflow

Length of output: 15579


🏁 Script executed:

# Search for `@validator` usage in the codebase
rg -n '@validator' --type py

Repository: infiniflow/ragflow

Length of output: 127


Replace @validator with @field_validator — The project uses pydantic v2 (confirmed in uv.lock showing pydantic-2.12.5), where the @validator decorator is deprecated and emits warnings. Migrate line 21 to import field_validator instead, and update the decorator usage on line 63 to @field_validator with @classmethod.

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

In `@api/apps/restful_apis/chunk_api.py` at line 21, Replace the deprecated
pydantic v1 `validator` import with `field_validator` in the import line (swap
`validator` for `field_validator` in the from pydantic import ... list) and
update the validator on the model to use `@field_validator` instead of
`@validator`; also mark the validation function as a classmethod by adding
`@classmethod` above it (the validator decorator and function on the model
around line 63). Ensure the decorator call signature remains the same (e.g.,
same field names/arguments) so the validation logic in that BaseModel subclass
continues to run under pydantic v2.

Comment thread api/apps/restful_apis/chunk_api.py Resolved
Comment thread api/apps/restful_apis/chunk_api.py Resolved
Comment on lines +218 to +230
chunk_id = xxhash.xxh64((req["content"] + document_id).encode("utf-8")).hexdigest()
d = {
"id": chunk_id,
"content_ltks": rag_tokenizer.tokenize(req["content"]),
"content_with_weight": req["content"],
}
d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
d["important_kwd"] = req.get("important_keywords", [])
d["important_tks"] = rag_tokenizer.tokenize(" ".join(req.get("important_keywords", [])))
d["question_kwd"] = [str(q).strip() for q in req.get("questions", []) if str(q).strip()]
d["question_tks"] = rag_tokenizer.tokenize("\n".join(req.get("questions", [])))
d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
d["create_timestamp_flt"] = datetime.datetime.now().timestamp()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Deterministic chunk_id can silently overwrite existing chunks; replace("T", " ") is a no-op.

  • Line 218: chunk_id = xxhash.xxh64((content + document_id).encode(...)).hexdigest(). Posting the same content to the same document will produce the same id, and settings.docStoreConn.insert([d], ...) on line 262 will overwrite the prior record (including its tags/keywords/images/available flag) without warning. Meanwhile increment_chunk_num(..., 1, 0) on line 267 still bumps the counter, so chunk_num drifts above the actual count. If a unique-per-call id is needed, mix in a nonce/timestamp; if idempotency is wanted, return the existing chunk instead of re-inserting.
  • Line 229: str(datetime.datetime.now()) formats as '2026-04-22 08:03:47.123456' (space separator), so .replace("T", " ") never matches. If ISO is intended, use datetime.now().isoformat(sep=" ", timespec="seconds").

Comment thread api/apps/restful_apis/chunk_api.py Resolved
Comment thread docs/references/http_api_reference.md Resolved
Comment on lines 2726 to 2728
Whether to search chunks related to the generated knowledge graph for multi-hop queries. Defaults to `False`. Before enabling this, ensure you have successfully constructed a knowledge graph for the specified datasets. See [here](../guides/dataset/advanced/construct_knowledge_graph.md) for details.
- `"toc_enhance"`: (*Body parameter*), `boolean`
- `"toc_enhance"`: (*Body parameter*), `boolean`
Whether to search chunks with extracted table of content. Defaults to `False`. Before enabling this, ensure you have enabled `TOC_Enhance` and successfully extracted table of contents for the specified datasets. See [here](https://ragflow.io/docs/dev/enable_table_of_contents) for details.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Use descriptive link text for these guide links.

[here] triggers MD059 and is harder to scan. Name the destination directly.

Suggested link text
-  Whether to search chunks related to the generated knowledge graph for multi-hop queries. Defaults to `False`. Before enabling this, ensure you have successfully constructed a knowledge graph for the specified datasets. See [here](../guides/dataset/advanced/construct_knowledge_graph.md) for details.
+  Whether to search chunks related to the generated knowledge graph for multi-hop queries. Defaults to `False`. Before enabling this, ensure you have successfully constructed a knowledge graph for the specified datasets. See [Construct knowledge graph](../guides/dataset/advanced/construct_knowledge_graph.md) for details.
-  Whether to search chunks with extracted table of content. Defaults to `False`. Before enabling this, ensure you have enabled `TOC_Enhance` and successfully extracted table of contents for the specified datasets. See [here](https://ragflow.io/docs/dev/enable_table_of_contents) for details.
+  Whether to search chunks with extracted table of content. Defaults to `False`. Before enabling this, ensure you have enabled `TOC_Enhance` and successfully extracted table of contents for the specified datasets. See [Enable table of contents](https://ragflow.io/docs/dev/enable_table_of_contents) for details.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Whether to search chunks related to the generated knowledge graph for multi-hop queries. Defaults to `False`. Before enabling this, ensure you have successfully constructed a knowledge graph for the specified datasets. See [here](../guides/dataset/advanced/construct_knowledge_graph.md) for details.
- `"toc_enhance"`: (*Body parameter*), `boolean`
- `"toc_enhance"`: (*Body parameter*), `boolean`
Whether to search chunks with extracted table of content. Defaults to `False`. Before enabling this, ensure you have enabled `TOC_Enhance` and successfully extracted table of contents for the specified datasets. See [here](https://ragflow.io/docs/dev/enable_table_of_contents) for details.
Whether to search chunks related to the generated knowledge graph for multi-hop queries. Defaults to `False`. Before enabling this, ensure you have successfully constructed a knowledge graph for the specified datasets. See [Construct knowledge graph](../guides/dataset/advanced/construct_knowledge_graph.md) for details.
- `"toc_enhance"`: (*Body parameter*), `boolean`
Whether to search chunks with extracted table of content. Defaults to `False`. Before enabling this, ensure you have enabled `TOC_Enhance` and successfully extracted table of contents for the specified datasets. See [Enable table of contents](https://ragflow.io/docs/dev/enable_table_of_contents) for details.
🧰 Tools
🪛 markdownlint-cli2 (0.22.0)

[warning] 2726-2726: Link text should be descriptive

(MD059, descriptive-link-text)


[warning] 2728-2728: Link text should be descriptive

(MD059, descriptive-link-text)

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

In `@docs/references/http_api_reference.md` around lines 2726 - 2728, Replace the
generic "[here]" links with descriptive link text: for the knowledge graph
mention next to the multi-hop option (the paragraph referencing constructing a
knowledge graph) change the link to something like "construct a knowledge graph"
and for the `"toc_enhance"` paragraph change the link text to "enable table of
contents" (or similar descriptive phrasing) while keeping the existing target
URLs; update the markdown in those sentences so the link text describes the
destination rather than using "[here]".

Comment on lines +37 to +40
fetched = get_chunk(auth, dataset_id, document_id, chunk["id"])
assert fetched["code"] == 0, fetched
assert fetched["data"]["id"] == chunk["id"]
assert fetched["data"]["doc_id"] == document_id

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Assert the REST detail field name.

The REST get-chunk response returns document_id, while this assertion still reads doc_id. This will fail even when the created chunk is valid.

🐛 Proposed fix
     fetched = get_chunk(auth, dataset_id, document_id, chunk["id"])
     assert fetched["code"] == 0, fetched
     assert fetched["data"]["id"] == chunk["id"]
-    assert fetched["data"]["doc_id"] == document_id
+    assert fetched["data"]["document_id"] == document_id
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_web_api/test_chunk_app/test_create_chunk.py` around lines
37 - 40, The test asserts the wrong field name for the REST get-chunk response:
update the assertion that checks the returned chunk ID fields in the test using
get_chunk (variable fetched) so it expects "document_id" instead of "doc_id" and
still verifies "id" equals chunk["id"] (i.e. change the assertion referencing
fetched["data"]["doc_id"] to fetched["data"]["document_id"]); keep the existing
checks for fetched["code"] and fetched["data"]["id"] unchanged.

@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 (1)
test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py (1)

496-507: _load_chunk_api_module still forces loading the legacy chunk_app.py.

It unconditionally calls _load_chunk_module(monkeypatch) (which execs api/apps/chunk_app.py) purely to reuse its stubs. Given the PR removes chunk CRUD handlers from chunk_app.py, tightly coupling every REST-API test to also importing the legacy module is fragile — if chunk_app.py is ever removed or further slimmed, all the new REST tests break for unrelated reasons. Consider extracting the stub-installation into a shared helper that both loaders call, rather than chaining _load_chunk_api_module → _load_chunk_module.

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

In `@test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py` around
lines 496 - 507, The test helper _load_chunk_api_module currently calls
_load_chunk_module(monkeypatch) which forces importing legacy
api/apps/chunk_app.py; extract the common stub setup (e.g., installing
_DummyManager and any monkeypatch.setitem entries) into a new shared helper
function (name it something like _install_chunk_stubs) and have both
_load_chunk_api_module and _load_chunk_module call that helper instead of one
calling the other; update _load_chunk_api_module to load only
api/apps/restful_apis/chunk_api.py, set module.manager = _DummyManager via the
shared helper, and remove the cross-import dependency so REST API tests no
longer require importing chunk_app.py.
🤖 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_web_api/test_chunk_app/test_chunk_routes_unit.py`:
- Around line 72-75: The test-local RetCode constants define NOT_FOUND = 102
which duplicates DATA_ERROR; change NOT_FOUND to 404 to match the production
RetCode in common/constants.py so assertions are unambiguous (update the
NOT_FOUND constant near DATA_ERROR, EXCEPTION_ERROR, OPERATING_ERROR in
test_chunk_routes_unit.py).

---

Nitpick comments:
In `@test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py`:
- Around line 496-507: The test helper _load_chunk_api_module currently calls
_load_chunk_module(monkeypatch) which forces importing legacy
api/apps/chunk_app.py; extract the common stub setup (e.g., installing
_DummyManager and any monkeypatch.setitem entries) into a new shared helper
function (name it something like _install_chunk_stubs) and have both
_load_chunk_api_module and _load_chunk_module call that helper instead of one
calling the other; update _load_chunk_api_module to load only
api/apps/restful_apis/chunk_api.py, set module.manager = _DummyManager via the
shared helper, and remove the cross-import dependency so REST API tests no
longer require importing chunk_app.py.
🪄 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: 723e2520-c0dd-4b19-b82e-f20175bb620f

📥 Commits

Reviewing files that changed from the base of the PR and between 10321e6 and b36442b.

📒 Files selected for processing (2)
  • api/apps/sdk/doc.py
  • test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py
✅ Files skipped from review due to trivial changes (1)
  • api/apps/sdk/doc.py

@codecov

codecov Bot commented Apr 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.97%. Comparing base (74b44e1) to head (0ad9741).
⚠️ Report is 32 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14291      +/-   ##
==========================================
- Coverage   97.41%   95.97%   -1.44%     
==========================================
  Files          10       10              
  Lines         695      695              
  Branches      111      111              
==========================================
- Hits          677      667      -10     
- Misses          7       11       +4     
- Partials       11       17       +6     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

@buua436
buua436 marked this pull request as draft April 22, 2026 11:20

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
test/testcases/test_http_api/test_chunk_management_within_dataset/test_add_chunk.py (1)

39-49: ⚠️ Potential issue | 🟡 Minor

Asserting on repr() of a Quart Unauthorized exception is fragile.

The test hardcodes the exact string "<Unauthorized '401: Unauthorized'>" which is the repr() of a quart.exceptions.Unauthorized instance returned by the error handler. Two problems:

  1. Upstream fragility — The _unauthorized_message() function in api/apps/__init__.py falls back to repr(error) when error.description is unavailable, and a hardcoded UNAUTHORIZED_MESSAGE constant returns this exact repr string. Any change in Quart/Werkzeug exception __repr__ will silently break this assertion across all four chunk-management test files (test_add_chunk.py, test_update_chunk.py, test_list_chunks.py, test_delete_chunks.py).

  2. User-facing quality — If the API actually returns this raw repr to clients, it's a server-side bug (the pattern in api/utils/api_utils.py lines 135–150 shows normalized {"code": 401, "message": "Unauthorized"} is the correct approach) rather than something to codify in tests.

Recommend relaxing the assertion to check for a stable substring (e.g., "Unauthorized" in res["message"]) or normalizing the server handler to return a consistent message. Applies to all four test files.

🔧 Suggested relaxation
-            (None, 401, "<Unauthorized '401: Unauthorized'>"),
-            (RAGFlowHttpApiAuth(INVALID_API_TOKEN), 401, "<Unauthorized '401: Unauthorized'>"),
+            (None, 401, "Unauthorized"),
+            (RAGFlowHttpApiAuth(INVALID_API_TOKEN), 401, "Unauthorized"),

And in the test body:

-        assert res["message"] == expected_message
+        assert expected_message in res["message"]
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@test/testcases/test_http_api/test_chunk_management_within_dataset/test_add_chunk.py`
around lines 39 - 49, The test test_invalid_auth currently asserts the fragile
exact repr string for the Quart Unauthorized exception; update the assertion in
test_invalid_auth (and the analogous tests in test_update_chunk.py,
test_list_chunks.py, test_delete_chunks.py) to be stable by checking for a
normalized message or substring—e.g., assert res["code"] == expected_code and
"Unauthorized" in res["message"] — or assert res["message"] == "Unauthorized" if
you prefer enforcing normalized output from the API; locate the call site using
the helper add_chunk and change the equality assertion on res["message"]
accordingly.
♻️ Duplicate comments (3)
docs/references/http_api_reference.md (2)

2224-2237: ⚠️ Potential issue | 🟠 Major

Normalize the Get chunk response example.

This example still exposes storage-field names while the surrounding REST chunk docs use public fields like content, document_id, image_id, important_keywords, and questions.

Suggested response shape
 {
     "code": 0,
     "data": {
-        "available_int": 1,
-        "content_with_weight": "This is a test content.",
-        "doc_id": "b330ec2e91ec11efbc510242ac120004",
+        "available": true,
+        "content": "This is a test content.",
+        "document_id": "b330ec2e91ec11efbc510242ac120004",
         "docnm_kwd": "1.txt",
         "id": "b48c170e90f70af998485c1065490726",
-        "img_id": "",
-        "important_kwd": [],
-        "question_kwd": [],
+        "image_id": "",
+        "important_keywords": [],
+        "questions": [],
         "tag_kwd": []
     }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/references/http_api_reference.md` around lines 2224 - 2237, Update the
JSON example in the "Get chunk" response so it uses the public field names used
elsewhere (e.g., replace content_with_weight → content, doc_id → document_id,
img_id → image_id, important_kwd → important_keywords, question_kwd → questions,
tag_kwd → tags, and normalize docnm_kwd to a public filename field such as
filename or document_name) while preserving values and structure (keep id,
available_int mapped to a public boolean/flag name like available). Ensure the
example JSON keys match the surrounding REST chunk docs' public schema.

2726-2728: ⚠️ Potential issue | 🟡 Minor

Use descriptive link text.

The [here] links still trigger MD059 and are harder to scan.

Markdown fix
-  Whether to search chunks related to the generated knowledge graph for multi-hop queries. Defaults to `False`. Before enabling this, ensure you have successfully constructed a knowledge graph for the specified datasets. See [here](../guides/dataset/advanced/construct_knowledge_graph.md) for details.
+  Whether to search chunks related to the generated knowledge graph for multi-hop queries. Defaults to `False`. Before enabling this, ensure you have successfully constructed a knowledge graph for the specified datasets. See [Construct knowledge graph](../guides/dataset/advanced/construct_knowledge_graph.md) for details.
-  Whether to search chunks with extracted table of content. Defaults to `False`. Before enabling this, ensure you have enabled `TOC_Enhance` and successfully extracted table of contents for the specified datasets. See [here](https://ragflow.io/docs/dev/enable_table_of_contents) for details.
+  Whether to search chunks with extracted table of content. Defaults to `False`. Before enabling this, ensure you have enabled `TOC_Enhance` and successfully extracted table of contents for the specified datasets. See [Enable table of contents](https://ragflow.io/docs/dev/enable_table_of_contents) for details.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/references/http_api_reference.md` around lines 2726 - 2728, Replace
non-descriptive "here" link text with meaningful anchor text to satisfy MD059:
change the first occurrence "See
[here](../guides/dataset/advanced/construct_knowledge_graph.md)" to something
like "See the construct knowledge graph guide" (or "construct knowledge graph
guide") and change the second "See
[here](https://ragflow.io/docs/dev/enable_table_of_contents)" to "See the enable
table of contents guide" (or similar descriptive text); update the link targets
accordingly where the phrases appear near the `"toc_enhance"` parameter and the
multi-hop knowledge graph note so the link text clearly describes the
destination.
api/apps/restful_apis/chunk_api.py (1)

189-197: ⚠️ Potential issue | 🟠 Major

Return a normal not-found response and normalize GET chunk output.

Line 192 turns a missing chunk into a server error, and Line 193 returns raw storage fields (content_with_weight, doc_id, img_id, etc.) instead of the public chunk shape used by list_chunks.

Suggested direction
         chunk = settings.docStoreConn.get(chunk_id, search.index_name(tenant_id), [dataset_id])
         if chunk is None or str(chunk.get("doc_id", chunk.get("document_id"))) != str(document_id):
-            return server_error_response(Exception("Chunk not found"))
-        return get_result(data=_strip_chunk_runtime_fields(chunk))
+            return get_result(message=f"Chunk not found: {dataset_id}/{chunk_id}", code=RetCode.NOT_FOUND)
+        _strip_chunk_runtime_fields(chunk)
+        return get_result(data={
+            "id": chunk.get("id", chunk_id),
+            "content": chunk.get("content_with_weight", ""),
+            "document_id": chunk.get("doc_id", chunk.get("document_id")),
+            "docnm_kwd": chunk.get("docnm_kwd", ""),
+            "important_keywords": chunk.get("important_kwd", []),
+            "questions": chunk.get("question_kwd", []),
+            "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")),
+            "image_id": chunk.get("img_id", ""),
+            "available": bool(chunk.get("available_int", 1)),
+            "positions": chunk.get("position_int", []),
+            "tag_kwd": chunk.get("tag_kwd", []),
+        })
     except Exception as e:
         if str(e).find("NotFoundError") >= 0:
-            return get_result(data=False, message="Chunk not found!", code=RetCode.DATA_ERROR)
+            return get_result(message=f"Chunk not found: {dataset_id}/{chunk_id}", code=RetCode.NOT_FOUND)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/chunk_api.py` around lines 189 - 197, The current GET
chunk handler turns a missing chunk into a server error and returns raw storage
fields; change it so a missing chunk returns the normal not-found response (use
get_result(data=False, message="Chunk not found!", code=RetCode.DATA_ERROR))
instead of server_error_response, and normalize the returned chunk with the same
public shape used by list_chunks by calling the existing
_strip_chunk_runtime_fields (or the same serializer used by list_chunks) before
returning via get_result. Also keep the existing exception branch that maps
storage "NotFoundError" to the same get_result not-found response and only call
server_error_response for other exceptions; reference settings.docStoreConn.get,
_strip_chunk_runtime_fields, get_result, server_error_response, and
RetCode.DATA_ERROR when making the changes.
🧹 Nitpick comments (3)
api/apps/restful_apis/chunk_api.py (1)

203-203: Add structured logging for the new mutation flows.

The new add/delete/update/switch chunk flows currently have no success/failure logging, making REST migration issues hard to trace in production. Include non-sensitive IDs (tenant_id, dataset_id, document_id, chunk_id) and outcome counts.

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

Also applies to: 289-289, 333-333, 416-416

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

In `@api/apps/restful_apis/chunk_api.py` at line 203, The new chunk mutation flows
(e.g., add_chunk, and the corresponding delete/update/switch chunk handlers
referenced at the other locations) currently lack structured success/failure
logs; add structured logging using the module logger (logger.info for success,
logger.error for failures) that records non-sensitive IDs tenant_id, dataset_id,
document_id, chunk_id (when available) and outcome counts (e.g., number of
chunks added/updated/deleted) and error details on exceptions; place an info log
after successful operations with counts and IDs, and an error log in exception
handlers with the same IDs plus the exception message/stack, ensuring no
sensitive payload is logged.
test/testcases/test_http_api/test_chunk_management_within_dataset/test_list_chunks.py (1)

138-145: test_get_chunk doesn't verify any chunk content — consider tightening assertions.

The new test asserts only id and doc_id. Since get_chunk in api/apps/restful_apis/chunk_api.py (lines 180–201) strips runtime fields and returns _strip_chunk_runtime_fields(chunk), it's worth asserting at least content/content_with_weight and maybe dataset_id so a regression that returns an empty or partially populated payload is caught. Also consider a negative case for an unknown chunk_id (the endpoint has a NotFoundError branch that returns code == RetCode.DATA_ERROR with data=False — currently untested here).

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

In
`@test/testcases/test_http_api/test_chunk_management_within_dataset/test_list_chunks.py`
around lines 138 - 145, Update the test_get_chunk test to assert the actual
chunk payload fields returned by get_chunk (which calls
_strip_chunk_runtime_fields) by checking that res["data"] contains non-empty
content or content_with_weight and that res["data"]["dataset_id"] matches
dataset_id; additionally add a negative subtest that calls get_chunk with a
non-existent chunk id and asserts the endpoint returns code ==
RetCode.DATA_ERROR and data == False to cover the NotFoundError branch.
test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py (1)

313-323: Cross-module helper loading is fragile; prefer a shared conftest/fixture.

_load_restful_chunk_module dynamically imports another test file by path to reach _load_chunk_api_module. This creates hard coupling between two test suites: renaming or moving the chunk_app test file will silently break this file.

The good news: Both decorator stacks (@login_required and @add_tenant_id_to_kwargs) properly use @wraps, so inspect.unwrap will correctly traverse through to the core function. That risk is mitigated.

However, the cross-package coupling remains. Consider extracting _load_chunk_api_module into a shared helper (e.g., test/testcases/_helpers/chunk_api_loader.py or a shared conftest.py fixture) and importing it normally from both test modules.

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

In
`@test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py`
around lines 313 - 323, The test dynamically imports another test file via
_load_restful_chunk_module to call _load_chunk_api_module, which creates fragile
cross-module coupling; refactor by extracting _load_chunk_api_module into a
shared helper (e.g., test/testcases/_helpers/chunk_api_loader.py) or a conftest
fixture and update this test to import that helper normally instead of using
importlib (replace calls to _load_restful_chunk_module with a direct import of
the shared loader); keep _route_core as-is since inspect.unwrap works with the
existing decorators.
🤖 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/chunk_api.py`:
- Around line 16-18: The add_chunk and update_chunk flows currently mutate the
docstore or adjust counters before validating base64 image payloads and ensuring
image storage succeeded; change both functions so image validation (check base64
validity and that decoded bytes form a supported image) and the call to the
image storage routine are performed and confirmed successful before any docstore
mutation or metadata/counter updates are applied, and abort/raise on failure so
no chunk references a missing image or leaves counters inconsistent;
specifically, move/insert validation and storage steps ahead of the docstore
write in add_chunk and ahead of preparing/persisting metadata/counter changes in
update_chunk and ensure errors from the storage call are propagated to prevent
the subsequent mutations.
- Around line 363-364: The code currently coerces req["available"] into an int
(d["available_int"] = int(req["available"])) which can raise on bad input and
allow values other than 0/1; update validation so you explicitly accept only "0"
or "1" (or True/False if that’s intended) before converting and set
d["available_int"] accordingly, and return a 4xx error (e.g., 400/422) for any
other values; apply the same strict check where req["available_int"] is parsed
(remove blind int(...) usage) so both branches validate allowed values rather
than coercing arbitrary strings.
- Around line 427-440: The update loop in _switch_sync uses
settings.docStoreConn.update filtering only by {"id": cid} and dataset
(search.index_name(...), doc.kb_id), which allows switching chunks belonging to
other documents in the same dataset; change the update filter in
settings.docStoreConn.update to include the document id (e.g., add {"id": cid,
"document_id": document_id} or the actual doc primary key field from doc) so
each update is scoped to the validated document (refer to _switch_sync,
DocumentService.get_by_id, settings.docStoreConn.update, req["chunk_ids"],
available_int, search.index_name, document_id, doc.kb_id).

In `@docs/references/http_api_reference.md`:
- Line 2669: The docs incorrectly type `rerank_id` as an `integer` in the
parameter section while the body summary (and other model-ID docs) uses
`string`; update the parameter documentation for `rerank_id` to `string` so both
the body summary and parameter list are consistent, and scan the nearby
occurrences (the other instance around the parameters block) to change any
remaining `integer` mentions to `string` for `rerank_id`.
- Around line 1491-1495: Fix the malformed enum entry for the "chunk_method"
Body parameter by closing the missing quote around the manual option; update the
documented values for chunk_method (the list containing "naive", "manual", "qa")
so "manual" is quoted correctly to match the other enum entries and keep the
list well-formed.

---

Outside diff comments:
In
`@test/testcases/test_http_api/test_chunk_management_within_dataset/test_add_chunk.py`:
- Around line 39-49: The test test_invalid_auth currently asserts the fragile
exact repr string for the Quart Unauthorized exception; update the assertion in
test_invalid_auth (and the analogous tests in test_update_chunk.py,
test_list_chunks.py, test_delete_chunks.py) to be stable by checking for a
normalized message or substring—e.g., assert res["code"] == expected_code and
"Unauthorized" in res["message"] — or assert res["message"] == "Unauthorized" if
you prefer enforcing normalized output from the API; locate the call site using
the helper add_chunk and change the equality assertion on res["message"]
accordingly.

---

Duplicate comments:
In `@api/apps/restful_apis/chunk_api.py`:
- Around line 189-197: The current GET chunk handler turns a missing chunk into
a server error and returns raw storage fields; change it so a missing chunk
returns the normal not-found response (use get_result(data=False, message="Chunk
not found!", code=RetCode.DATA_ERROR)) instead of server_error_response, and
normalize the returned chunk with the same public shape used by list_chunks by
calling the existing _strip_chunk_runtime_fields (or the same serializer used by
list_chunks) before returning via get_result. Also keep the existing exception
branch that maps storage "NotFoundError" to the same get_result not-found
response and only call server_error_response for other exceptions; reference
settings.docStoreConn.get, _strip_chunk_runtime_fields, get_result,
server_error_response, and RetCode.DATA_ERROR when making the changes.

In `@docs/references/http_api_reference.md`:
- Around line 2224-2237: Update the JSON example in the "Get chunk" response so
it uses the public field names used elsewhere (e.g., replace content_with_weight
→ content, doc_id → document_id, img_id → image_id, important_kwd →
important_keywords, question_kwd → questions, tag_kwd → tags, and normalize
docnm_kwd to a public filename field such as filename or document_name) while
preserving values and structure (keep id, available_int mapped to a public
boolean/flag name like available). Ensure the example JSON keys match the
surrounding REST chunk docs' public schema.
- Around line 2726-2728: Replace non-descriptive "here" link text with
meaningful anchor text to satisfy MD059: change the first occurrence "See
[here](../guides/dataset/advanced/construct_knowledge_graph.md)" to something
like "See the construct knowledge graph guide" (or "construct knowledge graph
guide") and change the second "See
[here](https://ragflow.io/docs/dev/enable_table_of_contents)" to "See the enable
table of contents guide" (or similar descriptive text); update the link targets
accordingly where the phrases appear near the `"toc_enhance"` parameter and the
multi-hop knowledge graph note so the link text clearly describes the
destination.

---

Nitpick comments:
In `@api/apps/restful_apis/chunk_api.py`:
- Line 203: The new chunk mutation flows (e.g., add_chunk, and the corresponding
delete/update/switch chunk handlers referenced at the other locations) currently
lack structured success/failure logs; add structured logging using the module
logger (logger.info for success, logger.error for failures) that records
non-sensitive IDs tenant_id, dataset_id, document_id, chunk_id (when available)
and outcome counts (e.g., number of chunks added/updated/deleted) and error
details on exceptions; place an info log after successful operations with counts
and IDs, and an error log in exception handlers with the same IDs plus the
exception message/stack, ensuring no sensitive payload is logged.

In
`@test/testcases/test_http_api/test_chunk_management_within_dataset/test_list_chunks.py`:
- Around line 138-145: Update the test_get_chunk test to assert the actual chunk
payload fields returned by get_chunk (which calls _strip_chunk_runtime_fields)
by checking that res["data"] contains non-empty content or content_with_weight
and that res["data"]["dataset_id"] matches dataset_id; additionally add a
negative subtest that calls get_chunk with a non-existent chunk id and asserts
the endpoint returns code == RetCode.DATA_ERROR and data == False to cover the
NotFoundError branch.

In
`@test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py`:
- Around line 313-323: The test dynamically imports another test file via
_load_restful_chunk_module to call _load_chunk_api_module, which creates fragile
cross-module coupling; refactor by extracting _load_chunk_api_module into a
shared helper (e.g., test/testcases/_helpers/chunk_api_loader.py) or a conftest
fixture and update this test to import that helper normally instead of using
importlib (replace calls to _load_restful_chunk_module with a direct import of
the shared loader); keep _route_core as-is since inspect.unwrap works with the
existing decorators.
🪄 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: 90756e20-98db-46f7-9ae0-90e2a4d9b4c3

📥 Commits

Reviewing files that changed from the base of the PR and between b36442b and b607b83.

📒 Files selected for processing (9)
  • api/apps/restful_apis/chunk_api.py
  • docs/references/http_api_reference.md
  • test/testcases/test_http_api/test_chunk_management_within_dataset/conftest.py
  • test/testcases/test_http_api/test_chunk_management_within_dataset/test_add_chunk.py
  • test/testcases/test_http_api/test_chunk_management_within_dataset/test_delete_chunks.py
  • test/testcases/test_http_api/test_chunk_management_within_dataset/test_list_chunks.py
  • test/testcases/test_http_api/test_chunk_management_within_dataset/test_update_chunk.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.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_web_api/test_chunk_app/test_chunk_routes_unit.py

Comment on lines +16 to +18
import base64
import datetime
import re

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Validate and store images before mutating chunk metadata.

Invalid base64 or image-storage failure currently happens after docstore mutation in add_chunk and after update metadata is prepared in update_chunk, leaving chunks that reference missing images or skipped counters.

Safer image handling
 import base64
+import binascii
 import datetime
@@
-    image_base64 = req.get("image_base64")
+    image_base64 = req.get("image_base64")
+    image_bytes = None
     if image_base64:
+        try:
+            image_bytes = base64.b64decode(image_base64, validate=True)
+        except (binascii.Error, ValueError):
+            return get_error_data_result(message="`image_base64` must be valid base64")
         d["img_id"] = f"{dataset_id}-{chunk_id}"
         d["doc_type_kwd"] = "image"
@@
-    settings.docStoreConn.insert([d], search.index_name(tenant_id), dataset_id)
-
-    if image_base64:
-        store_chunk_image(dataset_id, chunk_id, base64.b64decode(image_base64))
+    if image_bytes is not None:
+        store_chunk_image(dataset_id, chunk_id, image_bytes)
+    settings.docStoreConn.insert([d], search.index_name(tenant_id), dataset_id)
@@
-    image_base64 = req.get("image_base64")
+    image_base64 = req.get("image_base64")
+    image_bytes = None
     if image_base64:
+        try:
+            image_bytes = base64.b64decode(image_base64, validate=True)
+        except (binascii.Error, ValueError):
+            return get_error_data_result(message="`image_base64` must be valid base64")
         d["img_id"] = f"{dataset_id}-{chunk_id}"
         d["doc_type_kwd"] = "image"
@@
-    settings.docStoreConn.update({"id": chunk_id}, d, search.index_name(tenant_id), dataset_id)
-    if image_base64:
-        store_chunk_image(dataset_id, chunk_id, base64.b64decode(image_base64))
+    if image_bytes is not None:
+        store_chunk_image(dataset_id, chunk_id, image_bytes)
+    settings.docStoreConn.update({"id": chunk_id}, d, search.index_name(tenant_id), dataset_id)

Also applies to: 247-267, 380-409

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

In `@api/apps/restful_apis/chunk_api.py` around lines 16 - 18, The add_chunk and
update_chunk flows currently mutate the docstore or adjust counters before
validating base64 image payloads and ensuring image storage succeeded; change
both functions so image validation (check base64 validity and that decoded bytes
form a supported image) and the call to the image storage routine are performed
and confirmed successful before any docstore mutation or metadata/counter
updates are applied, and abort/raise on failure so no chunk references a missing
image or leaves counters inconsistent; specifically, move/insert validation and
storage steps ahead of the docstore write in add_chunk and ahead of
preparing/persisting metadata/counter changes in update_chunk and ensure errors
from the storage call are propagated to prevent the subsequent mutations.

Comment on lines +363 to +364
if "available" in req:
d["available_int"] = int(req["available"])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Reject invalid availability values instead of coercing them.

int(req["available"]) and int(req["available_int"]) can raise 500s for strings and can persist values other than 0/1.

Availability validation
     if "available" in req:
-        d["available_int"] = int(req["available"])
+        if not isinstance(req["available"], bool):
+            return get_error_data_result(message="`available` should be a boolean")
+        d["available_int"] = 1 if req["available"] else 0
@@
-    available_int = int(req["available_int"]) if "available_int" in req else (1 if req.get("available") else 0)
+    if "available_int" in req:
+        if req["available_int"] not in (0, 1):
+            return get_error_data_result(message="`available_int` should be 0 or 1.")
+        available_int = req["available_int"]
+    else:
+        if not isinstance(req.get("available"), bool):
+            return get_error_data_result(message="`available` should be a boolean.")
+        available_int = 1 if req["available"] else 0

Also applies to: 422-424

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

In `@api/apps/restful_apis/chunk_api.py` around lines 363 - 364, The code
currently coerces req["available"] into an int (d["available_int"] =
int(req["available"])) which can raise on bad input and allow values other than
0/1; update validation so you explicitly accept only "0" or "1" (or True/False
if that’s intended) before converting and set d["available_int"] accordingly,
and return a 4xx error (e.g., 400/422) for any other values; apply the same
strict check where req["available_int"] is parsed (remove blind int(...) usage)
so both branches validate allowed values rather than coercing arbitrary strings.

Comment on lines +427 to +440
def _switch_sync():
e, doc = DocumentService.get_by_id(document_id)
if not e:
return get_error_data_result(message="Document not found!")
if not doc or str(doc.kb_id) != str(dataset_id):
return get_error_data_result(message="Document not found!")
for cid in req["chunk_ids"]:
if not settings.docStoreConn.update(
{"id": cid},
{"available_int": available_int},
search.index_name(tenant_id),
doc.kb_id,
):
return get_error_data_result(message="Index updating failure")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Scope availability updates to the route document.

switch_chunks validates the document, but each update only filters by id and dataset. A request under one document can switch chunks from another document in the same dataset.

Document-scoped update
                 if not settings.docStoreConn.update(
-                    {"id": cid},
+                    {"id": cid, "doc_id": document_id},
                     {"available_int": available_int},
                     search.index_name(tenant_id),
                     doc.kb_id,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/chunk_api.py` around lines 427 - 440, The update loop
in _switch_sync uses settings.docStoreConn.update filtering only by {"id": cid}
and dataset (search.index_name(...), doc.kb_id), which allows switching chunks
belonging to other documents in the same dataset; change the update filter in
settings.docStoreConn.update to include the document id (e.g., add {"id": cid,
"document_id": document_id} or the actual doc primary key field from doc) so
each update is scoped to the validated document (refer to _switch_sync,
DocumentService.get_by_id, settings.docStoreConn.update, req["chunk_ids"],
available_int, search.index_name, document_id, doc.kb_id).

Comment on lines +1491 to 1495
- `"chunk_method"`: (*Body parameter*), `string`
The parsing method to apply to the document:
- `"naive"`: General
- `"manual`: Manual
- `"qa"`: Q&A

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Close the manual enum quote.

Line 1494 documents "manual without the closing quote, which makes the chunk-method list look malformed.

Documentation fix
-  - `"manual`: Manual
+  - `"manual"`: Manual
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- `"chunk_method"`: (*Body parameter*), `string`
The parsing method to apply to the document:
- `"naive"`: General
- `"manual`: Manual
- `"qa"`: Q&A
- `"chunk_method"`: (*Body parameter*), `string`
The parsing method to apply to the document:
- `"naive"`: General
- `"manual"`: Manual
- `"qa"`: Q&A
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/references/http_api_reference.md` around lines 1491 - 1495, Fix the
malformed enum entry for the "chunk_method" Body parameter by closing the
missing quote around the manual option; update the documented values for
chunk_method (the list containing "naive", "manual", "qa") so "manual" is quoted
correctly to match the other enum entries and keep the list well-formed.

- `"similarity_threshold"`: `float`
- `"vector_similarity_weight"`: `float`
- `"top_k"`: `integer`
- `"rerank_id"`: `string`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Keep rerank_id typed consistently.

The body summary says rerank_id is a string, but the parameter section says integer. Model IDs are documented elsewhere as strings, so this should stay string.

Documentation fix
-- `"rerank_id"`: (*Body parameter*), `integer`
+- `"rerank_id"`: (*Body parameter*), `string`
   The ID of the rerank model.

Also applies to: 2729-2730

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

In `@docs/references/http_api_reference.md` at line 2669, The docs incorrectly
type `rerank_id` as an `integer` in the parameter section while the body summary
(and other model-ID docs) uses `string`; update the parameter documentation for
`rerank_id` to `string` so both the body summary and parameter list are
consistent, and scan the nearby occurrences (the other instance around the
parameters block) to change any remaining `integer` mentions to `string` for
`rerank_id`.

@buua436
buua436 marked this pull request as ready for review April 22, 2026 11:32

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

♻️ Duplicate comments (3)
api/apps/restful_apis/chunk_api.py (3)

363-364: ⚠️ Potential issue | 🟠 Major

Reject invalid availability values instead of coercing them.

int(req["available"]) can raise 500s or persist values outside 0/1; switch_chunks also treats "false" as truthy.

Also applies to: 422-424

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

In `@api/apps/restful_apis/chunk_api.py` around lines 363 - 364, The code
currently coerces req["available"] via int(req["available"]) which can raise and
accepts invalid values; update the parsing in the chunk handling (the block that
sets d["available_int"] and the similar logic used by switch_chunks) to
explicitly validate allowed inputs (e.g., numeric 0/1, string "0"/"1", boolean
True/False, or canonical "true"/"false") and map them to 0 or 1, and return a
client error (422 or 400) for any other value instead of coercing; ensure the
same validated mapping is applied in switch_chunks and the other occurrences
(lines 422-424) so invalid availability values are rejected consistently.

247-267: ⚠️ Potential issue | 🟠 Major

Validate and store images before mutating the docstore.

Invalid base64 or store_chunk_image failure currently happens after insert/update, leaving chunks that reference missing images or inconsistent counters.

Also applies to: 380-409

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

In `@api/apps/restful_apis/chunk_api.py` around lines 247 - 267, The code
currently inserts the chunk into the docstore before validating/storing the
image, risking orphaned records; ensure image validation and storage happen
before mutating the store by decoding and validating image_base64 (use
base64.b64decode inside a try/except) and calling store_chunk_image(dataset_id,
chunk_id, ...) successfully first, and only then call
settings.docStoreConn.insert and DocumentService.increment_chunk_num; if
store_chunk_image fails, log/raise and avoid performing
settings.docStoreConn.insert (or, if insert already occurred, delete/rollback
the inserted chunk and do not call DocumentService.increment_chunk_num) so state
stays consistent.

433-439: ⚠️ Potential issue | 🟠 Major

Scope availability updates to the route document.

switch_chunks validates the document but updates each chunk by id only, so a request under one document can toggle another document’s chunk in the same dataset.

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

In `@api/apps/restful_apis/chunk_api.py` around lines 433 - 439, The loop in
switch_chunks updates chunks by id only, allowing chunk toggles across
documents; change the update call inside the for cid in req["chunk_ids"] loop to
include the route document identifier in the query filter (e.g., use {"id": cid,
"doc_id": doc.id} or similar) so settings.docStoreConn.update filters by both
chunk id and the parent document (reference doc.id/doc.kb_id as appropriate)
when calling update (keeping search.index_name(tenant_id) and the existing
args).
🧹 Nitpick comments (2)
test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py (1)

719-721: Add route-level coverage for invalid positions shapes.

This test only covers a valid 5-item position; add a failing [[1, 2, 3, 4]] case so update_chunk cannot persist invalid shapes. Based on learnings, Applies to tests/**/*.py : Add/adjust tests for behavior changes.

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

In
`@test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py`
around lines 719 - 721, Add a negative test in the same test file that calls
update_chunk via _route_core with get_request_json returning positions
[[1,2,3,4]] and assert the route rejects it (e.g., res["code"] != 0 or the
expected error code/message), so update_chunk cannot persist invalid 4-item
position shapes; reference the existing monkeypatch usage and
_run(_route_core(module.update_chunk)("tenant-1", "ds-1", "doc-1", "chunk-1"))
pattern to add the failing case next to the valid 5-item test.
api/apps/restful_apis/chunk_api.py (1)

99-177: Add logging around the new REST chunk flows.

These new handlers have no logging for access denials, validation failures, docstore mutations, or unexpected error branches, which makes production diagnosis difficult. As per coding guidelines, **/*.py: Add logging for new flows.

Also applies to: 180-197, 200-283, 286-327, 330-410, 413-445

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

In `@api/apps/restful_apis/chunk_api.py` around lines 99 - 177, The new
list_chunks flow (function list_chunks) lacks logging for access denials,
validation failures, docstore fetches/mutations and error branches; add
structured logger calls (e.g., logger.info/debug/warn/error) at key points: log
when KnowledgebaseService.accessible returns false and when
DocumentService.query returns empty, log requests/params (tenant_id, dataset_id,
document_id, page, size, keywords) at function entry, log docstore fetch
attempts and outcomes around settings.docStoreConn.get and
settings.docStoreConn.index_exist, and log retriever.search calls/results and
any exceptions around settings.retriever.search and Chunk(**...) creation; use
consistent context (tenant_id, dataset_id, document_id, chunk id) and ensure
access-denied and not-found branches call logger.warn/error before returning via
get_error_data_result/get_result.
🤖 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/chunk_api.py`:
- Around line 299-310: The handler currently treats a truthy chunk_ids (which
can be a string) as an iterable of IDs; validate that chunk_ids is actually a
list (or sequence of IDs) before proceeding to delete/switch to avoid treating a
string as characters. Update the branch that reads chunk_ids (the variable
chunk_ids) to check type/structure (e.g., isinstance(chunk_ids, list) or ensure
it's a non-string iterable) and return a validation error via get_result() if it
is not valid; then continue to call check_duplicate_ids,
DocumentService.delete_chunk_images, settings.docStoreConn.delete and
DocumentService.decrement_chunk_num only when chunk_ids passes that validation.
Apply the same validation where chunk_ids is handled later in the file (the
chunk delete/switch logic around check_duplicate_ids usage).
- Around line 213-228: The request lists may pass the list-type check but can
contain non-string elements which cause TypeError when joined; in the block that
builds d (around chunk_id, content_ltks, content_with_weight) validate or coerce
elements of req["important_keywords"] and req["questions"] to strings before
using " ".join or "\n".join and before tokenizing (references: keys
"important_keywords", "questions", methods rag_tokenizer.tokenize and
rag_tokenizer.fine_grained_tokenize, and fields "important_tks" and
"question_tks"); either return get_error_data_result if any element is not
coercible to str, or map all elements via str(...).strip() and filter out empty
strings, and make the same change in the other similar block (lines ~353-362) to
ensure safe joins and tokenization.
- Around line 365-368: The code currently only checks that req["positions"] is a
list before assigning to d["position_int"], but Chunk.positions expects each
element to be a 5-integer sublist; update the handler in chunk_api.py to
validate that req["positions"] is a list of lists/tuples where each inner item
has length 5 and each element is an integer (or coercible to int), returning
get_error_data_result("`positions` must be a list of 5-integer sublists") on
failure; when valid, set d["position_int"] to the cleaned/validated list of
5-int lists (use the same variable names req and d["position_int"] to locate the
change).
- Around line 109-121: Validate and sanitize incoming query params before
converting: when reading request.args, explicitly validate page and page_size
(the variables page and size) with checks that the values are present and
numeric, convert inside a try/except/validation block to avoid ValueError
turning into 500s, enforce sensible bounds (e.g., page >=1, 1 <= page_size <=
100) and fall back to defaults or return a 400 error; for the available flag,
only accept exact values "true" or "false" and return a 400 or omit
available_int if the value is invalid rather than silently treating anything
else as false; update the creation of query (the query dict and key
"available_int") accordingly so only validated and coerced values are used.

---

Duplicate comments:
In `@api/apps/restful_apis/chunk_api.py`:
- Around line 363-364: The code currently coerces req["available"] via
int(req["available"]) which can raise and accepts invalid values; update the
parsing in the chunk handling (the block that sets d["available_int"] and the
similar logic used by switch_chunks) to explicitly validate allowed inputs
(e.g., numeric 0/1, string "0"/"1", boolean True/False, or canonical
"true"/"false") and map them to 0 or 1, and return a client error (422 or 400)
for any other value instead of coercing; ensure the same validated mapping is
applied in switch_chunks and the other occurrences (lines 422-424) so invalid
availability values are rejected consistently.
- Around line 247-267: The code currently inserts the chunk into the docstore
before validating/storing the image, risking orphaned records; ensure image
validation and storage happen before mutating the store by decoding and
validating image_base64 (use base64.b64decode inside a try/except) and calling
store_chunk_image(dataset_id, chunk_id, ...) successfully first, and only then
call settings.docStoreConn.insert and DocumentService.increment_chunk_num; if
store_chunk_image fails, log/raise and avoid performing
settings.docStoreConn.insert (or, if insert already occurred, delete/rollback
the inserted chunk and do not call DocumentService.increment_chunk_num) so state
stays consistent.
- Around line 433-439: The loop in switch_chunks updates chunks by id only,
allowing chunk toggles across documents; change the update call inside the for
cid in req["chunk_ids"] loop to include the route document identifier in the
query filter (e.g., use {"id": cid, "doc_id": doc.id} or similar) so
settings.docStoreConn.update filters by both chunk id and the parent document
(reference doc.id/doc.kb_id as appropriate) when calling update (keeping
search.index_name(tenant_id) and the existing args).

---

Nitpick comments:
In `@api/apps/restful_apis/chunk_api.py`:
- Around line 99-177: The new list_chunks flow (function list_chunks) lacks
logging for access denials, validation failures, docstore fetches/mutations and
error branches; add structured logger calls (e.g., logger.info/debug/warn/error)
at key points: log when KnowledgebaseService.accessible returns false and when
DocumentService.query returns empty, log requests/params (tenant_id, dataset_id,
document_id, page, size, keywords) at function entry, log docstore fetch
attempts and outcomes around settings.docStoreConn.get and
settings.docStoreConn.index_exist, and log retriever.search calls/results and
any exceptions around settings.retriever.search and Chunk(**...) creation; use
consistent context (tenant_id, dataset_id, document_id, chunk id) and ensure
access-denied and not-found branches call logger.warn/error before returning via
get_error_data_result/get_result.

In
`@test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py`:
- Around line 719-721: Add a negative test in the same test file that calls
update_chunk via _route_core with get_request_json returning positions
[[1,2,3,4]] and assert the route rejects it (e.g., res["code"] != 0 or the
expected error code/message), so update_chunk cannot persist invalid 4-item
position shapes; reference the existing monkeypatch usage and
_run(_route_core(module.update_chunk)("tenant-1", "ds-1", "doc-1", "chunk-1"))
pattern to add the failing case next to the valid 5-item test.
🪄 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: 7201bf0b-f1be-4e5b-a950-bddb9b8ea5f7

📥 Commits

Reviewing files that changed from the base of the PR and between b607b83 and 632f90b.

📒 Files selected for processing (4)
  • api/apps/restful_apis/chunk_api.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
  • test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py
  • test/testcases/test_web_api/test_chunk_app/test_create_chunk.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/testcases/test_web_api/test_chunk_app/test_create_chunk.py

Comment on lines +109 to +121
req = request.args
page = int(req.get("page", 1))
size = int(req.get("page_size", 30))
question = req.get("keywords", "")
query = {
"doc_ids": [document_id],
"page": page,
"size": size,
"question": question,
"sort": True,
}
if "available" in req:
query["available_int"] = 1 if req["available"] == "true" else 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Validate query parameters before coercion.

int(req.get(...)) can turn malformed page/page_size values into 500s, and any available value other than "true" is silently treated as false.

Proposed validation
-    page = int(req.get("page", 1))
-    size = int(req.get("page_size", 30))
+    try:
+        page = int(req.get("page", 1))
+        size = int(req.get("page_size", 30))
+    except (TypeError, ValueError):
+        return get_error_data_result(message="`page` and `page_size` must be integers.")
+    if page < 1 or size < 1:
+        return get_error_data_result(message="`page` and `page_size` must be positive integers.")
@@
-    if "available" in req:
-        query["available_int"] = 1 if req["available"] == "true" else 0
+    if "available" in req:
+        available = str(req["available"]).lower()
+        if available not in {"true", "false"}:
+            return get_error_data_result(message="`available` should be `true` or `false`.")
+        query["available_int"] = 1 if available == "true" else 0
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/chunk_api.py` around lines 109 - 121, Validate and
sanitize incoming query params before converting: when reading request.args,
explicitly validate page and page_size (the variables page and size) with checks
that the values are present and numeric, convert inside a try/except/validation
block to avoid ValueError turning into 500s, enforce sensible bounds (e.g., page
>=1, 1 <= page_size <= 100) and fall back to defaults or return a 400 error; for
the available flag, only accept exact values "true" or "false" and return a 400
or omit available_int if the value is invalid rather than silently treating
anything else as false; update the creation of query (the query dict and key
"available_int") accordingly so only validated and coerced values are used.

Comment on lines +213 to +228
if "important_keywords" in req and not isinstance(req["important_keywords"], list):
return get_error_data_result("`important_keywords` is required to be a list")
if "questions" in req and not isinstance(req["questions"], list):
return get_error_data_result("`questions` is required to be a list")

chunk_id = xxhash.xxh64((req["content"] + document_id).encode("utf-8")).hexdigest()
d = {
"id": chunk_id,
"content_ltks": rag_tokenizer.tokenize(req["content"]),
"content_with_weight": req["content"],
}
d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
d["important_kwd"] = req.get("important_keywords", [])
d["important_tks"] = rag_tokenizer.tokenize(" ".join(req.get("important_keywords", [])))
d["question_kwd"] = [str(q).strip() for q in req.get("questions", []) if str(q).strip()]
d["question_tks"] = rag_tokenizer.tokenize("\n".join(req.get("questions", [])))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Validate keyword/question element types before joining.

A list like {"questions": [1]} or {"important_keywords": [1]} passes the list check but then raises TypeError in " ".join(...) / "\n".join(...).

Proposed validation
     if "important_keywords" in req and not isinstance(req["important_keywords"], list):
         return get_error_data_result("`important_keywords` is required to be a list")
+    if "important_keywords" in req and not all(isinstance(k, str) for k in req["important_keywords"]):
+        return get_error_data_result("`important_keywords` must be a list of strings")
     if "questions" in req and not isinstance(req["questions"], list):
         return get_error_data_result("`questions` is required to be a list")
+    if "questions" in req and not all(isinstance(q, str) for q in req["questions"]):
+        return get_error_data_result("`questions` must be a list of strings")
@@
     if "important_keywords" in req:
         if not isinstance(req["important_keywords"], list):
             return get_error_data_result("`important_keywords` should be a list")
+        if not all(isinstance(k, str) for k in req["important_keywords"]):
+            return get_error_data_result("`important_keywords` must be a list of strings")
@@
     if "questions" in req:
         if not isinstance(req["questions"], list):
             return get_error_data_result("`questions` should be a list")
+        if not all(isinstance(q, str) for q in req["questions"]):
+            return get_error_data_result("`questions` must be a list of strings")

Also applies to: 353-362

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

In `@api/apps/restful_apis/chunk_api.py` around lines 213 - 228, The request lists
may pass the list-type check but can contain non-string elements which cause
TypeError when joined; in the block that builds d (around chunk_id,
content_ltks, content_with_weight) validate or coerce elements of
req["important_keywords"] and req["questions"] to strings before using " ".join
or "\n".join and before tokenizing (references: keys "important_keywords",
"questions", methods rag_tokenizer.tokenize and
rag_tokenizer.fine_grained_tokenize, and fields "important_tks" and
"question_tks"); either return get_error_data_result if any element is not
coercible to str, or map all elements via str(...).strip() and filter out empty
strings, and make the same change in the other similar block (lines ~353-362) to
ensure safe joins and tokenization.

Comment on lines +299 to +310
chunk_ids = req.get("chunk_ids")
if not chunk_ids:
if req.get("delete_all") is True:
doc = docs[0]
DocumentService.delete_chunk_images(doc, tenant_id)
chunk_number = settings.docStoreConn.delete({"doc_id": document_id}, search.index_name(tenant_id), dataset_id)
if chunk_number != 0:
DocumentService.decrement_chunk_num(document_id, dataset_id, 1, chunk_number, 0)
return get_result(message=f"deleted {chunk_number} chunks")
return get_result()

unique_chunk_ids, duplicate_messages = check_duplicate_ids(chunk_ids, "chunk")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Validate chunk_ids is a list before delete/switch.

A string chunk_ids payload is truthy and iterable, so it can be treated as individual characters instead of chunk ids.

Proposed validation
     chunk_ids = req.get("chunk_ids")
+    if chunk_ids is not None and not isinstance(chunk_ids, list):
+        return get_error_data_result(message="`chunk_ids` should be a list.")
     if not chunk_ids:
@@
     req = await get_request_json()
-    if not req.get("chunk_ids"):
+    if "chunk_ids" in req and not isinstance(req["chunk_ids"], list):
+        return get_error_data_result(message="`chunk_ids` should be a list.")
+    if not req.get("chunk_ids"):
         return get_error_data_result(message="`chunk_ids` is required.")

Also applies to: 419-421

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

In `@api/apps/restful_apis/chunk_api.py` around lines 299 - 310, The handler
currently treats a truthy chunk_ids (which can be a string) as an iterable of
IDs; validate that chunk_ids is actually a list (or sequence of IDs) before
proceeding to delete/switch to avoid treating a string as characters. Update the
branch that reads chunk_ids (the variable chunk_ids) to check type/structure
(e.g., isinstance(chunk_ids, list) or ensure it's a non-string iterable) and
return a validation error via get_result() if it is not valid; then continue to
call check_duplicate_ids, DocumentService.delete_chunk_images,
settings.docStoreConn.delete and DocumentService.decrement_chunk_num only when
chunk_ids passes that validation. Apply the same validation where chunk_ids is
handled later in the file (the chunk delete/switch logic around
check_duplicate_ids usage).

Comment on lines +365 to +368
if "positions" in req:
if not isinstance(req["positions"], list):
return get_error_data_result("`positions` should be a list")
d["position_int"] = req["positions"]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Validate positions shape before persisting it.

The handler only checks that positions is a list, so [[1, 2]] or ["bad"] can be stored even though Chunk.positions requires 5-integer sublists.

Proposed validation
     if "positions" in req:
         if not isinstance(req["positions"], list):
             return get_error_data_result("`positions` should be a list")
+        if not all(
+            isinstance(position, list)
+            and len(position) == 5
+            and all(type(item) is int for item in position)
+            for position in req["positions"]
+        ):
+            return get_error_data_result("Each sublist in `positions` must contain exactly 5 integers")
         d["position_int"] = req["positions"]
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/chunk_api.py` around lines 365 - 368, The code
currently only checks that req["positions"] is a list before assigning to
d["position_int"], but Chunk.positions expects each element to be a 5-integer
sublist; update the handler in chunk_api.py to validate that req["positions"] is
a list of lists/tuples where each inner item has length 5 and each element is an
integer (or coercible to int), returning get_error_data_result("`positions` must
be a list of 5-integer sublists") on failure; when valid, set d["position_int"]
to the cleaned/validated list of 5-int lists (use the same variable names req
and d["position_int"] to locate the change).

"available": bool(chunk.get("available_int", 1)),
"positions": chunk.get("position_int", []),
"tag_kwd": chunk.get("tag_kwd", []),
"tag_feas": chunk.get("tag_feas", {}),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

"id": chunk.get("id", chunk.get("chunk_id")),
"content": chunk["content_with_weight"],
"document_id": chunk.get("doc_id", chunk.get("document_id")),
"docnm_kwd": chunk["docnm_kwd"],
"important_keywords": chunk.get("important_kwd", []),
"questions": chunk.get("question_kwd", []),
"dataset_id": chunk.get("kb_id", chunk.get("dataset_id")),
"image_id": chunk.get("img_id", ""),
"available": bool(chunk.get("available_int", 1)),
"positions": chunk.get("position_int", []),
"tag_kwd": chunk.get("tag_kwd", []),
"tag_feas": chunk.get("tag_feas", {}),
document_keywords        <- docnm_kwd        dup of docnm_kwd         (ne add)
document_type_keywords   <- doc_type_kwd     replace of doc_type_kwd

@wangq8
wangq8 merged commit 7817b0d into infiniflow:main Apr 23, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request May 11, 2026
1 task done
@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 🌈 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. 🧰 typescript Pull requests that update Typescript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants