Repository navigation
feat(go-api): add Go support for POST /api/v1/datasets/{dataset_id}/documents/{document_id}/chunks - #16256
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds 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. ChangesAddChunk endpoint implementation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (1)
internal/handler/chunk_test.go (1)
312-380: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a regression test for body/path ID conflict.
Current AddChunk tests don’t assert behavior when JSON includes
dataset_id/document_iddifferent 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
📒 Files selected for processing (6)
internal/handler/chunk.gointernal/handler/chunk_test.gointernal/router/router.gointernal/service/chunk/chunk.gointernal/service/chunk/chunk_test.gointernal/service/chunk_types.go
| questionKwd := filterTrimmedStrings(req.Questions) | ||
| questionTks, err := s.tokenize(strings.Join(req.Questions, "\n")) | ||
| if err != nil { |
There was a problem hiding this comment.
🎯 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.
| 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.
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
@Hz-186 Please fix conflict. |
There was a problem hiding this comment.
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 winDon’t label this as existing-chunk coverage unless the existence path is exercised.
AddChunkno longer consultsGetChunk, sogetChunkRespis 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
📒 Files selected for processing (2)
internal/service/chunk/chunk.gointernal/service/chunk/chunk_test.go
|
Thanks for the port. Comparing the new Go A few items worth addressing before merge: 1. if len(imageBinary) > maxChunkImageBytes { // 10 MB
return nil, fmt.Errorf("`image_base64` exceeds the maximum allowed size")
}Python's 2. 3. JSON-binding errors leak Go internals ( Minor (nice-to-have):
|
…nt-chunk/post # Conflicts: # internal/handler/chunk.go
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.
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:
tag_feasvalidationimage_base64decoding and chunk image storage/mergeTesting
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:
important_keywords/questions/tag_kwd/tag_feas: Go passedcode=102image_base64validation: Go matched expectedcode=102