Repository navigation
feat[Go]: implement api /api/v1/datasets/<dataset_id>/chunks POST - #16067
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds a ChangesDocument Re-parse Pipeline
Sequence DiagramsequenceDiagram
participant Client
participant ChunkHandler
participant ChunkService
participant DocumentDAO
participant TaskDAO
participant DocEngine
participant RedisQueue
Client->>ChunkHandler: POST /datasets/:dataset_id/chunks
ChunkHandler->>ChunkService: Parse(userID, datasetID, ParseFileRequest)
ChunkService->>DocumentDAO: validate tenant, fetch documents by ID
ChunkService->>DocEngine: delete existing chunks per document
ChunkService->>TaskDAO: delete prior tasks per document
ChunkService->>TaskDAO: CreateMany(page-range tasks with xxhash digest)
ChunkService->>DocumentDAO: reset run/progress/chunk/token counters
ChunkService->>RedisQueue: enqueue parse-task messages per page range
ChunkService-->>ChunkHandler: result map, ErrorCode, error
ChunkHandler-->>Client: 200 OK with code/data/message
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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: 3
🤖 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 217-223: The validation error response for `user_id` in the chunk
handler is missing a `return` statement after the `c.JSON()` call on line
217-222. This causes execution to continue past the error response and attempt
further processing (including the `datasetId` assignment on line 223), resulting
in a double-write error. Add a `return` statement immediately after the
`c.JSON()` call in the `user_id` validation block to exit the handler early and
prevent downstream processing when validation fails.
In `@internal/service/chunk/chunk.go`:
- Around line 1038-1076: The document state is being updated to running status
before executing fragile operations like chunk deletion, task deletion, document
retrieval, and task queueing. If any of these operations fail, the document
remains stuck in running state with incomplete work. Reorder the code so that
the Updates call that sets the running status and resets progress fields on the
Document model occurs after all subsequent operations (DeleteChunks,
DeleteByDocIDs, GetByID, GetDocumentStorageAddress, and queueParseTasks) have
completed successfully. This way, if any operation fails, the document state
remains unchanged and the error is returned early without leaving the document
in an inconsistent state.
- Around line 1031-1082: The loop mutates and queues documents before validating
that all requested document IDs exist and belong to the correct dataset,
allowing partial side effects before returning an error. Pre-validate all
document IDs by checking existence and dataset ownership (using
s.documentDAO.GetByID and verifying doc.KbID == datasetID) in a separate loop
before the main processing loop that performs updates, chunk deletion, and task
queueing. Collect not-found IDs during this validation phase and return the
CodeDataError early if any IDs fail validation, ensuring no mutations occur
until all requested IDs are confirmed valid.
🪄 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: f84d015f-ec6e-4a12-b498-0a26c9960611
📒 Files selected for processing (6)
internal/dao/task.gointernal/handler/chunk.gointernal/handler/chunk_test.gointernal/router/router.gointernal/service/chunk/chunk.gointernal/service/chunk_types.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16067 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
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 (4)
internal/service/chunk/chunk.go (4)
946-960:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winDo not double-count rows after a CSV parse error.
When
csv.Readerhas already counted some records and then hits malformed input, Lines 956-958 add the full-file newline count on top of the rows already read. Replace the count in the fallback path instead of incrementing it.Proposed fix
- rows += bytes.Count(binary, []byte{'\n'}) + rows = bytes.Count(binary, []byte{'\n'}) if len(binary) > 0 && binary[len(binary)-1] != '\n' { rows++ }🤖 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 946 - 960, The issue is that rows are being double-counted when the CSV reader encounters a parse error after already reading some records. In the fallback path after a non-EOF error (around lines 956-958 in the loop that starts with `for { _, err := reader.Read()`), the code currently uses the += operator to add the newline count to the already-counted rows variable. Replace the += operator with a = assignment operator so the fallback newline count replaces the rows count instead of adding to it, preventing double-counting of records that were already read before the parse error occurred.
1063-1078:⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy liftPreflight storage/task generation before deleting current parse artifacts.
Lines 1063-1070 delete existing chunks and tasks before
GetDocumentStorageAddressandqueueParseTaskscan fail. A missing object or storage outage would returnCodeServerErrorafter removing the document’s current parsed content and task history. Resolve storage and build the replacement task set before destructive cleanup, then swap/queue under a guarded state transition.🤖 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 1063 - 1078, The deletion operations using DeleteChunks and DeleteByDocIDs are being performed before validating that GetDocumentStorageAddress and queueParseTasks will succeed, which means if either of those later operations fail, the document's current parsed content and task history have already been irreversibly removed. Restructure the code to first call GetDocumentStorageAddress to verify storage accessibility and then attempt queueParseTasks to validate the replacement task can be queued, and only after both of these operations succeed should you perform the destructive cleanup by calling DeleteChunks and DeleteByDocIDs.
1051-1080:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftReserve the document atomically before destructive parse work.
The running check uses the preloaded
doc.Run, butbeginParseDocumentis delayed until after delete/task/queue work. Two concurrent requests can both pass Lines 1051-1055, then each delete/recreate/enqueue tasks before either marks the document running at Line 1080. Add a guarded state transition or row lock before side effects, with compensating reset/cleanup if preparation fails.🤖 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 1051 - 1080, The race condition exists because the document is checked for running status at the beginning of the loop iteration, but not marked as running with beginParseDocument until after destructive operations like DeleteChunks, DeleteByDocIDs, and queueParseTasks. Move the beginParseDocument call to execute immediately after the initial running status check and before any delete or queue operations to atomically reserve the document. If any subsequent operation fails (DeleteChunks, DeleteByDocIDs, or queueParseTasks), add compensating cleanup logic to reset the document state back from running to its original state before returning the error.
591-608:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftAvoid hard-deleting task rows after a partial Redis enqueue.
CreateManypersists all tasks before the per-taskQueueProductloop. If one enqueue succeeds and a later enqueue fails, Lines 601-607 delete every task row for the document while earlier Redis messages remain, leaving workers with orphaned task IDs and making retries non-idempotent. Use an outbox/batch enqueue with all-or-nothing semantics, or mark failed tasks as cancelled instead of deleting rows that may already be referenced by queued messages.🤖 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 591 - 608, The issue is that when QueueProduct fails in the loop iterating through tasks, the code deletes all task rows for the document via DeleteByDocIDs, but earlier successful QueueProduct calls have already added messages to Redis, leaving orphaned task IDs. Instead of deleting task rows when a Redis enqueue fails in the loop over tasks, mark the specific failed task(s) as cancelled or in a failed state in the database (e.g., using an UpdateByID method with a status field) so the rows remain but indicate failure and prevent workers from processing orphaned task IDs. Alternatively, refactor to batch enqueue all tasks to Redis before persisting to the database, or use a transactional approach where either all tasks are successfully enqueued or none are persisted.
🤖 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_test.go`:
- Around line 125-127: The in-memory SQLite database opened with
sqlite.Open(":memory:") creates separate database instances for each pooled
connection, causing intermittent failures when queries hit empty tables. Replace
the ":memory:" string with a shared-memory DSN format and add a
SetMaxOpenConns(1) call on the db object immediately after the gorm.Open call to
ensure all queries use a single connection. Refer to the correct implementation
pattern in searchbot_test.go for the exact DSN format and connection
configuration approach.
---
Outside diff comments:
In `@internal/service/chunk/chunk.go`:
- Around line 946-960: The issue is that rows are being double-counted when the
CSV reader encounters a parse error after already reading some records. In the
fallback path after a non-EOF error (around lines 956-958 in the loop that
starts with `for { _, err := reader.Read()`), the code currently uses the +=
operator to add the newline count to the already-counted rows variable. Replace
the += operator with a = assignment operator so the fallback newline count
replaces the rows count instead of adding to it, preventing double-counting of
records that were already read before the parse error occurred.
- Around line 1063-1078: The deletion operations using DeleteChunks and
DeleteByDocIDs are being performed before validating that
GetDocumentStorageAddress and queueParseTasks will succeed, which means if
either of those later operations fail, the document's current parsed content and
task history have already been irreversibly removed. Restructure the code to
first call GetDocumentStorageAddress to verify storage accessibility and then
attempt queueParseTasks to validate the replacement task can be queued, and only
after both of these operations succeed should you perform the destructive
cleanup by calling DeleteChunks and DeleteByDocIDs.
- Around line 1051-1080: The race condition exists because the document is
checked for running status at the beginning of the loop iteration, but not
marked as running with beginParseDocument until after destructive operations
like DeleteChunks, DeleteByDocIDs, and queueParseTasks. Move the
beginParseDocument call to execute immediately after the initial running status
check and before any delete or queue operations to atomically reserve the
document. If any subsequent operation fails (DeleteChunks, DeleteByDocIDs, or
queueParseTasks), add compensating cleanup logic to reset the document state
back from running to its original state before returning the error.
- Around line 591-608: The issue is that when QueueProduct fails in the loop
iterating through tasks, the code deletes all task rows for the document via
DeleteByDocIDs, but earlier successful QueueProduct calls have already added
messages to Redis, leaving orphaned task IDs. Instead of deleting task rows when
a Redis enqueue fails in the loop over tasks, mark the specific failed task(s)
as cancelled or in a failed state in the database (e.g., using an UpdateByID
method with a status field) so the rows remain but indicate failure and prevent
workers from processing orphaned task IDs. Alternatively, refactor to batch
enqueue all tasks to Redis before persisting to the database, or use a
transactional approach where either all tasks are successfully enqueued or none
are persisted.
🪄 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: db9bf3c0-6cb2-487c-ac70-78779703a03d
📒 Files selected for processing (2)
internal/service/chunk/chunk.gointernal/service/chunk/chunk_test.go
| db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{ | ||
| TranslateError: true, | ||
| }) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check whether in-memory SQLite tests use a pooled :memory: DSN without limiting open connections.
rg -n -C3 'sqlite\.Open\(":memory:"\)|SetMaxOpenConns\(|mode=memory|cache=shared' --type goRepository: infiniflow/ragflow
Length of output: 6824
Pin the in-memory SQLite test DB to a single connection.
Using sqlite.Open(":memory:") with connection pooling causes each pooled connection to open a separate database instance, making GORM queries intermittently hit an empty table. Use a shared-memory DSN and set SetMaxOpenConns(1) after opening the DB.
See internal/handler/searchbot_test.go (lines 714–724) for a correct reference implementation.
Proposed fix
- db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
+ db, err := gorm.Open(sqlite.Open("file:chunk-test?mode=memory&cache=shared"), &gorm.Config{
TranslateError: true,
})
if err != nil {
t.Fatalf("failed to open sqlite: %v", err)
}
+ sqlDB, err := db.DB()
+ if err != nil {
+ t.Fatalf("get sqlite handle: %v", err)
+ }
+ sqlDB.SetMaxOpenConns(1)📝 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.
| db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{ | |
| TranslateError: true, | |
| }) | |
| db, err := gorm.Open(sqlite.Open("file:chunk-test?mode=memory&cache=shared"), &gorm.Config{ | |
| TranslateError: true, | |
| }) | |
| if err != nil { | |
| t.Fatalf("failed to open sqlite: %v", err) | |
| } | |
| sqlDB, err := db.DB() | |
| if err != nil { | |
| t.Fatalf("get sqlite handle: %v", err) | |
| } | |
| sqlDB.SetMaxOpenConns(1) |
🤖 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 125 - 127, The in-memory
SQLite database opened with sqlite.Open(":memory:") creates separate database
instances for each pooled connection, causing intermittent failures when queries
hit empty tables. Replace the ":memory:" string with a shared-memory DSN format
and add a SetMaxOpenConns(1) call on the db object immediately after the
gorm.Open call to ensure all queries use a single connection. Refer to the
correct implementation pattern in searchbot_test.go for the exact DSN format and
connection configuration approach.
|
|
||
| // Parse reparse the datasets' files | ||
| func (h *ChunkHandler) Parse(c *gin.Context) { | ||
| user, errorCode, errorMessage := GetUser(c) |
There was a problem hiding this comment.
Can we add test for this new method?
|
LGTM |
What problem does this PR solve?
As title
Type of change