Skip to content

feat(go-api): add Go support for POST /api/v1/datasets/{dataset_id}/documents/{document_id}/chunks - #16256

Merged
yuzhichang merged 9 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat/dataset-document-chunk/post
Jun 25, 2026
Merged

yuzhichang merged 9 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat/dataset-document-chunk/post

Conversation

@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

Summary

Add the Go implementation of POST /api/v1/datasets/{dataset_id}/documents/{document_id}/chunks.

This wires the full create-chunk path in Go:

  • router and handler registration
  • request/response structs
  • chunk creation service logic
  • embedding generation
  • chunk insert into doc engine
  • chunk/token counter increment
  • tag_feas validation
  • image_base64 decoding and chunk image storage/merge
  • unit tests for handler and service

Testing

Unit tests:

  • /usr/local/go/bin/go test ./internal/handler
  • /usr/local/go/bin/go test ./internal/service/chunk
  • /usr/local/go/bin/go test ./internal/service
  • /usr/local/go/bin/go test ./...

All passed locally.

Manual curl checks:

  • basic text chunk: Go passed
  • chunk with important_keywords / questions / tag_kwd / tag_feas: Go passed
  • blank content validation: Go matched expected code=102
  • invalid image_base64 validation: Go matched expected code=102
  • image upload and repeated image upload / merge path: Go passed twice

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 23, 2026
@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds the chunk creation endpoint, request and response types, service implementation, router wiring, and tests. The service validates input, handles optional images, generates embeddings, inserts chunks, and updates stats. The handler forwards authenticated requests and returns coded responses.

Changes

AddChunk endpoint implementation

Layer / File(s) Summary
API contract and HTTP wiring
internal/service/chunk_types.go, internal/handler/chunk.go, internal/router/router.go
Defines AddChunkRequest, AddChunkResponse, and ErrorCoder; extends the chunk service interface; adds ChunkHandler.AddChunk; registers POST /api/v1/datasets/:dataset_id/documents/:document_id/chunks.
ChunkService AddChunk flow
internal/service/chunk/chunk.go, internal/service/dataset.go
Implements AddChunk with payload validation, ownership checks, chunk lookup, tokenization, tag validation, optional image decoding/storage, embedding merge, chunk insertion, and stat updates. AggregateTags now canonicalizes dataset IDs with normalizeDatasetID.
ChunkService AddChunk tests
internal/service/chunk/chunk_test.go
Adds service coverage for success, validation errors, image/tag validation, existing-chunk stats updates, and image size limits, plus supporting test doubles and embedding/storage stubs.
ChunkHandler AddChunk tests
internal/handler/chunk_test.go
Updates the handler mock for AddChunk and adds tests for success, path ID precedence, and coded error handling.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

  • infiniflow/ragflow#16181: Both PRs touch internal/service/dataset.go’s dataset ID canonicalization used by AggregateTags.

Suggested labels

size:XL

Poem

🐇 A chunk hops in with image bright,
Embeddings mix and stats take flight.
The handler nods, the route is spun,
The tests all cheer: “The work is done!”

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding Go support for the chunks POST endpoint.
Description check ✅ Passed The description is directly aligned with the implemented router, handler, service, and test changes.
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.

@Harry-Hz-Zhang Harry-Hz-Zhang added the ci Continue Integration label Jun 23, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft June 23, 2026 06:02
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review June 23, 2026 06:02

@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

🧹 Nitpick comments (1)
internal/handler/chunk_test.go (1)

312-380: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a regression test for body/path ID conflict.

Current AddChunk tests don’t assert behavior when JSON includes dataset_id/document_id different from path params. Add one case to lock the route contract and prevent regression on resource targeting.

Suggested test addition
+func TestChunkHandlerAddChunkRejectsMismatchedBodyIDs(t *testing.T) {
+	called := false
+	mock := &mockChunkSvc{
+		addChunkFn: func(req *service.AddChunkRequest, userID string) (*service.AddChunkResponse, error) {
+			called = true
+			return &service.AddChunkResponse{Chunk: map[string]interface{}{"id": "chunk-1"}}, nil
+		},
+	}
+
+	gin.SetMode(gin.TestMode)
+	r := gin.New()
+	r.Use(func(c *gin.Context) {
+		c.Set("user", &entity.User{ID: "user1"})
+	})
+	h := &ChunkHandler{chunkService: mock}
+	r.POST("/api/v1/datasets/:dataset_id/documents/:document_id/chunks", h.AddChunk)
+
+	w := httptest.NewRecorder()
+	req, _ := http.NewRequest(
+		"POST",
+		"/api/v1/datasets/kb1/documents/doc1/chunks",
+		strings.NewReader(`{"dataset_id":"kb2","document_id":"doc2","content":"chunk body"}`),
+	)
+	req.Header.Set("Content-Type", "application/json")
+	r.ServeHTTP(w, req)
+
+	var resp map[string]interface{}
+	_ = json.Unmarshal(w.Body.Bytes(), &resp)
+	if resp["code"] != float64(common.CodeArgumentError) {
+		t.Fatalf("expected argument error code, got %v", resp["code"])
+	}
+	if called {
+		t.Fatalf("service should not be called when body/path IDs mismatch")
+	}
+}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handler/chunk_test.go` around lines 312 - 380, Add a regression test
case to verify the AddChunk handler's behavior when the JSON request body
contains dataset_id or document_id values that differ from the path parameters.
Create a new test function (similar in structure to
TestChunkHandlerAddChunkSuccess and TestChunkHandlerAddChunkCodedError) that
sends a POST request with conflicting IDs in the body versus the URL path, and
assert that the handler correctly uses the path parameters when invoking the
service through the mockChunkSvc.addChunkFn, ensuring the route contract
prevents body-based resource targeting exploits.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/handler/chunk.go`:
- Around line 515-517: The AddChunk handler is vulnerable to ID override because
it sets req.DatasetID and req.DocumentID from the path parameters before calling
ShouldBindJSON, which can overwrite these values from the JSON request body.
Reorder the operations in the handler to call ShouldBindJSON first to bind the
request body, then explicitly set req.DatasetID and req.DocumentID from the path
parameters (datasetID, documentID) after the binding, ensuring the path
parameters take precedence and cannot be overridden by values in the request
body.

In `@internal/service/chunk/chunk.go`:
- Around line 1589-1590: The chunk_num counter at line 1676 is being incremented
unconditionally for all chunk writes, including when updating existing chunks
through the merge path (lines 1863-1895). To fix this, gate the chunk_num
increment on whether the chunk is newly created or already exists. Before
incrementing chunk_num at line 1676, check if a chunk with the chunkID (derived
at line 1589 using xxhash.Sum64) already exists in the database. Only increment
chunk_num when creating a new chunk, and skip the increment when the chunk
already exists and is being updated/merged. Ensure this existence check uses the
same chunkID value to maintain consistency with the merge logic.
- Around line 1863-1865: The image merge operation has a race condition where
ObjExist, Get, merge, and Put operations are not atomic. Two concurrent requests
for the same chunkID can read the same old image, merge independently, and both
write results, causing lost updates. Implement per-chunk locking around the
entire ObjExist check through Put operation to ensure the sequence is atomic, or
alternatively use storage-level conditional writes with version checks to
prevent concurrent overwrites. Apply this fix throughout all instances in the
chunk merge logic including the code section from lines 1867-1895.
- Around line 1756-1767: The decodeChunkImageBase64 function and its callers
that perform RGBA canvas merging lack size and dimension validation, allowing
memory-exhaustion attacks through compression-bomb payloads. Add a hard limit
check for the maximum allowed decoded byte size immediately after the base64
decode in decodeChunkImageBase64, and add dimension/pixel validation checks in
the code that merges/allocates the RGBA canvas (around lines 1871-1888) to
ensure decoded images do not exceed reasonable pixel limits before full
allocation and processing.
- Around line 1602-1604: The questionKwd variable on line 1602 filters and trims
the questions to remove blank/whitespace entries, but line 1603 tokenizes the
raw req.Questions instead of the filtered questionKwd. This causes
blank/whitespace-only entries to leak into the question_tks variable, creating
inconsistency between the normalized questions list and the tokenized output.
Fix this by passing questionKwd to the s.tokenize call instead of req.Questions,
ensuring the tokenization is performed on the normalized/filtered question list.

---

Nitpick comments:
In `@internal/handler/chunk_test.go`:
- Around line 312-380: Add a regression test case to verify the AddChunk
handler's behavior when the JSON request body contains dataset_id or document_id
values that differ from the path parameters. Create a new test function (similar
in structure to TestChunkHandlerAddChunkSuccess and
TestChunkHandlerAddChunkCodedError) that sends a POST request with conflicting
IDs in the body versus the URL path, and assert that the handler correctly uses
the path parameters when invoking the service through the
mockChunkSvc.addChunkFn, ensuring the route contract prevents body-based
resource targeting exploits.
🪄 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: 0877377d-fa95-44f8-9232-64c4382a1129

📥 Commits

Reviewing files that changed from the base of the PR and between 9f9433e and 36ac612.

📒 Files selected for processing (6)
  • internal/handler/chunk.go
  • internal/handler/chunk_test.go
  • internal/router/router.go
  • internal/service/chunk/chunk.go
  • internal/service/chunk/chunk_test.go
  • internal/service/chunk_types.go

Comment thread internal/handler/chunk.go Resolved
Comment thread internal/service/chunk/chunk.go Resolved
Comment on lines +1602 to +1604
questionKwd := filterTrimmedStrings(req.Questions)
questionTks, err := s.tokenize(strings.Join(req.Questions, "\n"))
if err != nil {

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Tokenize the normalized question list, not raw input.

Line 1602 trims/filter questions, but Line 1603 tokenizes req.Questions. Blank/whitespace-only entries still leak into question_tks, which makes indexed tokens inconsistent with questions and embedding input.

Suggested fix
 	questionKwd := filterTrimmedStrings(req.Questions)
-	questionTks, err := s.tokenize(strings.Join(req.Questions, "\n"))
+	questionTks, err := s.tokenize(strings.Join(questionKwd, "\n"))
 	if err != nil {
 		return nil, addChunkError{code: common.CodeServerError, message: fmt.Sprintf("tokenize questions: %v", err)}
 	}
📝 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
questionKwd := filterTrimmedStrings(req.Questions)
questionTks, err := s.tokenize(strings.Join(req.Questions, "\n"))
if err != nil {
questionKwd := filterTrimmedStrings(req.Questions)
questionTks, err := s.tokenize(strings.Join(questionKwd, "\n"))
if err != nil {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/service/chunk/chunk.go` around lines 1602 - 1604, The questionKwd
variable on line 1602 filters and trims the questions to remove blank/whitespace
entries, but line 1603 tokenizes the raw req.Questions instead of the filtered
questionKwd. This causes blank/whitespace-only entries to leak into the
question_tks variable, creating inconsistency between the normalized questions
list and the tokenized output. Fix this by passing questionKwd to the s.tokenize
call instead of req.Questions, ensuring the tokenization is performed on the
normalized/filtered question list.

Comment thread internal/service/chunk/chunk.go Resolved
Comment thread internal/service/chunk/chunk.go Resolved
@codecov

codecov Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (5b0b86c) to head (bcb206c).
⚠️ Report is 8 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16256      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

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

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 23, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft June 23, 2026 09:44
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review June 23, 2026 09:44
@xugangqiang

Copy link
Copy Markdown
Collaborator

@Hz-186 Please fix conflict.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jun 24, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft June 24, 2026 08:18
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review June 24, 2026 08:18

@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

Caution

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

⚠️ Outside diff range comments (1)
internal/service/chunk/chunk_test.go (1)

639-649: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Don’t label this as existing-chunk coverage unless the existence path is exercised.

AddChunk no longer consults GetChunk, so getChunkResp is unused and this test only proves unconditional stats increment. Rename it and remove the dead stub, or assert an actual existence check if that behavior is restored.

Suggested cleanup
-func TestAddChunkIncrementsStatsForExistingChunk(t *testing.T) {
+func TestAddChunkAlwaysIncrementsStats(t *testing.T) {
@@
-	engine := &addChunkTestEngine{
-		getChunkResp: map[string]interface{}{"id": "existing"},
-	}
+	engine := &addChunkTestEngine{}

Also applies to: 685-686

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/service/chunk/chunk_test.go` around lines 639 - 649, The test
currently implies an existing-chunk path, but AddChunk no longer calls GetChunk,
so the getChunkResp stub is dead and the assertions only cover unconditional
stats increment. Update TestAddChunkIncrementsStatsForExistingChunk to either
rename it to reflect unconditional AddChunk stats behavior and remove the unused
addChunkTestEngine.getChunkResp setup, or restore/assert a real existence check
only if AddChunk actually exercises that path again.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/service/chunk/chunk.go`:
- Around line 1748-1749: The chunk token accounting in the chunk insertion path
is using the embedding input instead of the actual inserted chunk content, so
stats can reflect questions/doc name rather than the chunk body. Update the
logic around the tokenNum calculation in the chunk insert flow to count tokens
from the persisted chunk content/text fields, while keeping the embedding
surrogate used for embedding generation separate from the values passed to
incrementChunkStats.

---

Outside diff comments:
In `@internal/service/chunk/chunk_test.go`:
- Around line 639-649: The test currently implies an existing-chunk path, but
AddChunk no longer calls GetChunk, so the getChunkResp stub is dead and the
assertions only cover unconditional stats increment. Update
TestAddChunkIncrementsStatsForExistingChunk to either rename it to reflect
unconditional AddChunk stats behavior and remove the unused
addChunkTestEngine.getChunkResp setup, or restore/assert a real existence check
only if AddChunk actually exercises that path again.
🪄 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: 1fe2439e-d1e1-4782-9eba-8546d52137f3

📥 Commits

Reviewing files that changed from the base of the PR and between d4514a5 and 2299ea7.

📒 Files selected for processing (2)
  • internal/service/chunk/chunk.go
  • internal/service/chunk/chunk_test.go

Comment thread internal/service/chunk/chunk.go Resolved
@yuzhichang

Copy link
Copy Markdown
Member

Thanks for the port. Comparing the new Go AddChunk against api/apps/restful_apis/chunk_api.py:511-597 (and the related Python helpers), the core flow matches well — same xxhash chunk id, same 0.1*v[0]+0.9*v[1] merge, same ragflow_{tenant_id} index, same create_time/create_timestamp_flt formats, same increment_chunk_num(doc_id, kb_id, tokens, 1, 0) after insert.

A few items worth addressing before merge:

1. image_base64 size cap is new behavior not present in Python (internal/service/chunk/chunk.go:1840)

if len(imageBinary) > maxChunkImageBytes {  // 10 MB
    return nil, fmt.Errorf("`image_base64` exceeds the maximum allowed size")
}

Python's _decode_chunk_image_base64 has no size cap, and the maxChunkImagePixels bounds in storeChunkImage are also new. A 12 MB image gets a code=102 from Go but 200 from Python. Either document this as intentional hardening, or move the check before base64-decoding to avoid allocating up to 12 MB just to reject.

2. chunkExists is dead code and the corresponding test is misleading (internal/service/chunk/chunk.go:1909, chunk_test.go::TestAddChunkIncrementsStatsForExistingChunk)
AddChunk never calls chunkExists or GetChunk. The test sets getChunkResp: {"id":"existing"} and an addChunkTestEngine.GetChunk override, but the production path doesn't read either. Either remove the helper + rename the test, or actually branch on existing-chunk (Python's behavior on double-insert is engine-dependent and not tested on either side, so removing is fine).

3. JSON-binding errors leak Go internals (internal/handler/chunk.go)
c.ShouldBindJSON produces messages like json: cannot unmarshal object into Go struct field addChunkBody.important_keywords of type []string for type mismatches. Python returns clean messages: \important_keywords` is required to be a list, `tag_kwd` must be a list of strings. To match, either declare these fields as interface{}` and validate in the service with the same wording, or sanitize the binding error.

Minor (nice-to-have):

  • chunkData["important_kwd"] is nil when omitted, Python always sets []. The downstream ListChunks shape diverges (null vs []). Normalize to []string{}.
  • Python's response includes a document field via document_keyword mapping; Go doesn't. Either drop on the Python side or add on Go.
  • chunkImageMergeMu sync.Map grows unboundedly (per bucket/chunkID); for multi-tenant long-running servers this leaks. Add a comment or eviction policy.
  • CodeServerError messages (tokenize content: %v, encode chunk embedding: %v, etc.) are returned verbatim to the user. Python does the same, so this is parity, not regression — but worth a safe_message helper.
  • internal/service/dataset.go:1961 rename normalizeDatasetUUID1 → normalizeDatasetID came from a prior fix PR (a8651e7f8); just noting it's in the diff but out of this PR's scope.

No blockers. Address #1–#3 for parity; the rest is polish.

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 25, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft June 25, 2026 02:33
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review June 25, 2026 02:33
Drop the meaningless WithMaxConcurrency(4) on this linear 100-node
chain. It changed event-production timing and let the final state
event be dropped by the stream buffer, so RunSync returned nil and
the bare type assertion panicked, crashing the whole package test
binary. Also use a checked assertion and remove a duplicated nil
guard.
@yuzhichang
yuzhichang merged commit 54fb5b0 into infiniflow:main Jun 25, 2026
6 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants