Skip to content

feat[Go]: implement api /api/v1/datasets/<dataset_id>/chunks POST - #16067

Merged
JinHai-CN merged 9 commits into
infiniflow:mainfrom
Haruko386:monday
Jun 22, 2026
Merged

JinHai-CN merged 9 commits into
infiniflow:mainfrom
Haruko386:monday

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

As title

Type of change

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

@Haruko386 Haruko386 added the ci Continue Integration label Jun 16, 2026
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jun 16, 2026
@Haruko386
Haruko386 marked this pull request as draft June 16, 2026 03:53
@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9aae5e2c-8c27-4e8b-b515-7e16980841c2

📥 Commits

Reviewing files that changed from the base of the PR and between e8999df and af0438e.

📒 Files selected for processing (2)
  • internal/service/chunk/chunk.go
  • internal/service/chunk/chunk_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/service/chunk/chunk.go

📝 Walkthrough

Walkthrough

Adds a POST /api/v1/datasets/:dataset_id/chunks endpoint for document re-parsing. The change introduces ParseFileRequest, a TaskDAO.CreateMany batch method, and a large ChunkService.Parse orchestration method that resets document state, deletes existing chunks and tasks, splits documents into page-range tasks, hashes them for deduplication, and enqueues them into Redis. The handler, router, interface, and comprehensive test coverage are updated accordingly.

Changes

Document Re-parse Pipeline

Layer / File(s) Summary
Request type and DAO foundations
internal/service/chunk_types.go, internal/dao/task.go
Adds ParseFileRequest with document_ids field, formats RetrievalTestRequest.Datasets, introduces TaskDAO.CreateMany for batch task inserts, and adds ascending from_page/create_time ordering on GetByDocID.
ChunkService.Parse orchestration and helpers
internal/service/chunk/chunk.go
Adds imports for archive/ZIP, CSV/JSON/XML parsing, PDF/table estimation, xxhash, and Redis/queue components. Injects seven unexported function fields for testing. Implements duplicate-ID detection, page-range splitting by document type/parser (PDF, table, default), PDF page-count and table row-count estimation, deterministic xxhash digest per task, DB progress reset, CreateMany call, and Redis queue enqueueing. Removes Get, List, UpdateChunk, and RemoveChunks from this file.
HTTP handler, interface, and route wiring
internal/handler/chunk.go, internal/router/router.go, internal/handler/chunk_test.go
Reorders imports, extends chunkService interface with Parse(userID, datasetID string, req *service.ParseFileRequest) (map[string]interface{}, common.ErrorCode, error), adds ChunkHandler.Parse with user/dataset validation and conditional JSON responses, registers the POST /:dataset_id/chunks route, reflows commit routing blocks, and updates the mock to satisfy the interface.
Tests and database-backed validation
internal/service/chunk/chunk_test.go
Adds test database helpers (setupChunkTestDB, pushChunkTestDB), a newParseTestService factory, and a parseTestDocEngine stub. Includes 13 test cases covering authorization, input validation, missing data, delete/queue/state failures, cleanup behavior, partial success on duplicates, and successful task queuing with state transitions.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐇 Hop hop, the parser wakes anew,
Pages split and tasks enqueue,
xxhash stamps each job with care,
Redis fills the parse-task air,
Old chunks swept, fresh ones to brew —
The rabbit reparsed it all for you! 🥕

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.85% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description is incomplete and minimal. While it follows the template structure, it lacks substantive detail about the problem being solved and defers entirely to the title. Expand the description to explain what problem the new endpoint solves, why it's needed, and provide context for reviewers beyond just the title.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: implementing a new POST API endpoint for datasets chunks.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@dosubot dosubot Bot added the 💞 feature Feature request, pull request that fullfill a new feature. label Jun 16, 2026
@Haruko386
Haruko386 marked this pull request as ready for review June 16, 2026 03:53

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against 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

📥 Commits

Reviewing files that changed from the base of the PR and between a6f71e0 and 5406246.

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

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

codecov Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

Codecov Report

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

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.
📢 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.

@Haruko386
Haruko386 marked this pull request as draft June 16, 2026 05:00
@Haruko386
Haruko386 marked this pull request as ready for review June 16, 2026 05:06
@Haruko386
Haruko386 marked this pull request as draft June 17, 2026 07:29
@Haruko386
Haruko386 marked this pull request as ready for review June 17, 2026 07:37

@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 (4)
internal/service/chunk/chunk.go (4)

946-960: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Do not double-count rows after a CSV parse error.

When csv.Reader has 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 lift

Preflight storage/task generation before deleting current parse artifacts.

Lines 1063-1070 delete existing chunks and tasks before GetDocumentStorageAddress and queueParseTasks can fail. A missing object or storage outage would return CodeServerError after 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 lift

Reserve the document atomically before destructive parse work.

The running check uses the preloaded doc.Run, but beginParseDocument is 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 lift

Avoid hard-deleting task rows after a partial Redis enqueue.

CreateMany persists all tasks before the per-task QueueProduct loop. 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

📥 Commits

Reviewing files that changed from the base of the PR and between fb8e28f and e8999df.

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

Comment on lines +125 to +127
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
TranslateError: true,
})

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
# 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 go

Repository: 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.

Suggested change
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.

Comment thread internal/handler/chunk.go

// Parse reparse the datasets' files
func (h *ChunkHandler) Parse(c *gin.Context) {
user, errorCode, errorMessage := GetUser(c)

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.

Can we add test for this new method?

@xugangqiang

Copy link
Copy Markdown
Contributor

LGTM

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