Repository navigation
Refactor: Refine ingestion task state transitions - #16814
Conversation
📝 WalkthroughWalkthroughIngestion task persistence and lifecycle transitions are centralized in ChangesIngestion task lifecycle
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant DocumentService
participant IngestionTaskService
participant DAO
participant TaskPublisher
Client->>DocumentService: Create ingestion task
DocumentService->>IngestionTaskService: CreateAndEnqueue(task)
IngestionTaskService->>DAO: Create or update task
IngestionTaskService->>TaskPublisher: PublishTaskMessage(tasks.RAGFLOW, message)
TaskPublisher-->>IngestionTaskService: Publish result
IngestionTaskService-->>DocumentService: Task result
DocumentService-->>Client: Ingestion response
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
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 |
85e88d7 to
8335d56
Compare
8335d56 to
95308fd
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/admin/handler.go (1)
1085-1104: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winInconsistent error-code mapping between the two
StopIngestionTasksbranches.The primary branch now derives the code via
httputil.IngestionTaskErrorCode(err)(Line 1088), but the...ByConditionbranch at Line 1103 still hardcodescommon.CodeBadRequest. IfStopIngestionTasksByConditioncan also surface transition/conflict/not-found errors, they'll be misclassified as 400 here, unlike theRemoveIngestionTaskshandler where both branches were updated consistently.🔧 Align the ByCondition branch
tasks, err := h.service.StopIngestionTasksByCondition(req.Tasks, req.Email, req.Status) if err != nil { - common.ErrorWithCode(c, common.CodeBadRequest, err.Error()) + common.ErrorWithCode(c, httputil.IngestionTaskErrorCode(err), err.Error()) return }🤖 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/admin/handler.go` around lines 1085 - 1104, Align error handling in the conditional branch of the handler by replacing the hardcoded common.CodeBadRequest mapping after StopIngestionTasksByCondition with httputil.IngestionTaskErrorCode(err), matching the StopIngestionTasks branch and the corresponding RemoveIngestionTasks behavior.
🧹 Nitpick comments (4)
internal/handler/document_test.go (1)
1254-1325: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a handler test for
TaskStatusConflictError→CodeConflictmapping.The new tests cover
InvalidTaskTransitionErrorandErrTaskNotFoundmappings, butTaskStatusConflictError(returned when a concurrent status change causes the conditional update to affect 0 rows) is also mapped toCodeConflictbyIngestionTaskErrorCode. This is a real production scenario worth verifying at the handler level.✅ Suggested test addition
func TestStopIngestionTasksHandler_StatusConflictReturnsConflict(t *testing.T) { gin.SetMode(gin.TestMode) fake := &fakeDocumentService{ stopIngestionTaskErr: &service.TaskStatusConflictError{ TaskID: "task-1", ExpectedFrom: common.CREATED, AttemptedTo: common.RUNNING, ActualCurrent: common.STOPPING, }, } h := &DocumentHandler{documentService: fake} c, w := setupGinContextWithUser("PUT", "/api/v1/datasets/ds-1/ingestion/tasks", `{"tasks":["task-1"]}`) h.StopIngestionTasks(c) if w.Code != http.StatusOK { t.Fatalf("expected 200, got %d", w.Code) } var resp map[string]interface{} if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { t.Fatal(err) } if resp["code"] != float64(common.CodeConflict) { t.Fatalf("expected code %d, got %v", common.CodeConflict, resp["code"]) } }🤖 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/document_test.go` around lines 1254 - 1325, Add a handler-level test alongside TestStopIngestionTasksHandler_InvalidTransitionReturnsConflict that configures fakeDocumentService.stopIngestionTaskErr with a service.TaskStatusConflictError and invokes StopIngestionTasks; assert the response remains HTTP 200 and its JSON code is common.CodeConflict.internal/dao/ingestion.go (1)
35-59: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the duplicated "already exists" error to a helper.
The
fmt.Errorf("document id %s already exists, status: %s, task id: %s", ...)call is identical at lines 41 and 53. Extracting a small helper eliminates the duplication and ensures the message format stays consistent if it ever changes.♻️ Proposed refactor
func (dao *IngestionTaskDAO) Create(ingestionTask *entity.IngestionTask) (*entity.IngestionTask, error) { existing, err := dao.GetByDocumentID(ingestionTask.DocumentID) if err != nil { return nil, err } if existing != nil { - return nil, fmt.Errorf("document id %s already exists, status: %s, task id: %s", ingestionTask.DocumentID, existing.Status, existing.ID) + return nil, dao.duplicateTaskError(ingestionTask.DocumentID, existing) } if ingestionTask.ID == "" { ingestionTask.ID = utility.GenerateUUID() } if err := DB.Create(ingestionTask).Error; err != nil { if errors.Is(err, gorm.ErrDuplicatedKey) { existing, getErr := dao.GetByDocumentID(ingestionTask.DocumentID) if getErr != nil { return nil, getErr } if existing != nil { - return nil, fmt.Errorf("document id %s already exists, status: %s, task id: %s", ingestionTask.DocumentID, existing.Status, existing.ID) + return nil, dao.duplicateTaskError(ingestionTask.DocumentID, existing) } } return nil, err } return ingestionTask, nil } + +func (dao *IngestionTaskDAO) duplicateTaskError(documentID string, existing *entity.IngestionTask) error { + return fmt.Errorf("document id %s already exists, status: %s, task id: %s", documentID, existing.Status, existing.ID) +}🤖 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/dao/ingestion.go` around lines 35 - 59, Extract the duplicated existing-document error formatting from IngestionTaskDAO.Create into a small helper, such as a method or function accepting the document ID and existing task. Replace both identical fmt.Errorf calls in Create with that helper while preserving the current message and behavior.internal/service/ingestion_task_service.go (1)
150-181: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winN+1 query pattern and inconsistent error handling in ListAllForAdmin.
Two concerns:
N+1 queries: For each task,
GetByTenantID(line 158) andLatestLogByTaskID(line 171) are called individually. With many tasks, this generates2N+1DB round-trips. Consider batch-fetching users and logs.Inconsistent error resilience:
GetByTenantIDfailure aborts the entire listing (line 159), whileLatestLogByTaskIDfailure is silently ignored (line 172). A single missing user would prevent admins from viewing any tasks. Consider degrading gracefully (e.g.,"user": "unknown").♻️ Proposed fix: graceful degradation for missing users
user, err := s.userDAO.GetByTenantID(task.UserID) if err != nil { - return nil, err + // Degrade gracefully so admins can still see tasks + // even if a user has been deleted. + user = &entity.User{Email: "unknown"} }🤖 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/ingestion_task_service.go` around lines 150 - 181, Refactor ListAllForAdmin to avoid per-task GetByTenantID and LatestLogByTaskID calls by adding or using batch DAO methods and mapping the returned users/logs by tenant or task ID. Preserve task listing when related records are missing or lookups fail: use a fallback such as "unknown" for the user and omit the step when no latest log is available, while handling batch errors consistently without aborting the entire response.internal/ingestion/service/ingestion_service.go (1)
63-63: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the unused
ingestionTaskDAOfield.
Start()andexecuteTask()no longer reference it, so the struct field and its initializer inNewIngestor()can be dropped.🤖 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/ingestion/service/ingestion_service.go` at line 63, Remove the unused ingestionTaskDAO field from the relevant struct and delete its initializer in NewIngestor(); verify Start() and executeTask() remain unchanged since they no longer reference it.Source: Coding guidelines
🤖 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/dao/ingestion.go`:
- Around line 35-59: Add a database-level unique constraint for document_id in
the IngestionTask model’s GORM tags, replacing the plain index, and create a
migration to apply the unique index/constraint for existing ingestion task
tables. Ensure the migration safely handles the existing schema and aligns with
Create’s gorm.ErrDuplicatedKey handling.
In `@internal/service/ingestion_task_service.go`:
- Around line 298-326: Handle enqueueTask failures in CreateAndEnqueue by
rolling back the task state: delete a newly created task after Create fails to
enqueue, and transition an existing FAILED or STOPPED task back to its prior
terminal status if enqueue fails after transitioning it to CREATED. Return the
original enqueue error, while handling rollback errors consistently with
existing service conventions.
---
Outside diff comments:
In `@internal/admin/handler.go`:
- Around line 1085-1104: Align error handling in the conditional branch of the
handler by replacing the hardcoded common.CodeBadRequest mapping after
StopIngestionTasksByCondition with httputil.IngestionTaskErrorCode(err),
matching the StopIngestionTasks branch and the corresponding
RemoveIngestionTasks behavior.
---
Nitpick comments:
In `@internal/dao/ingestion.go`:
- Around line 35-59: Extract the duplicated existing-document error formatting
from IngestionTaskDAO.Create into a small helper, such as a method or function
accepting the document ID and existing task. Replace both identical fmt.Errorf
calls in Create with that helper while preserving the current message and
behavior.
In `@internal/handler/document_test.go`:
- Around line 1254-1325: Add a handler-level test alongside
TestStopIngestionTasksHandler_InvalidTransitionReturnsConflict that configures
fakeDocumentService.stopIngestionTaskErr with a service.TaskStatusConflictError
and invokes StopIngestionTasks; assert the response remains HTTP 200 and its
JSON code is common.CodeConflict.
In `@internal/ingestion/service/ingestion_service.go`:
- Line 63: Remove the unused ingestionTaskDAO field from the relevant struct and
delete its initializer in NewIngestor(); verify Start() and executeTask() remain
unchanged since they no longer reference it.
In `@internal/service/ingestion_task_service.go`:
- Around line 150-181: Refactor ListAllForAdmin to avoid per-task GetByTenantID
and LatestLogByTaskID calls by adding or using batch DAO methods and mapping the
returned users/logs by tenant or task ID. Preserve task listing when related
records are missing or lookups fail: use a fallback such as "unknown" for the
user and omit the step when no latest log is available, while handling batch
errors consistently without aborting the entire response.
🪄 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: f02bf2e2-f44c-4513-967b-1abe5789f314
📒 Files selected for processing (23)
internal/admin/handler.gointernal/admin/service.gointernal/dao/ingestion.gointernal/dao/ingestion_task_test.gointernal/deepdoc/parser/pdf/parser_pipeline_integration_test.gointernal/engine/infinity/chunk.gointernal/handler/document.gointernal/handler/document_test.gointernal/httputil/ingestion_task_error.gointernal/httputil/ingestion_task_error_test.gointernal/ingestion/pipeline/real_storage_integration_test.gointernal/ingestion/service/ingestion_service.gointernal/ingestion/task/dataflow_e2e_test.gointernal/ingestion/task/dataflow_service.gointernal/ingestion/task/embedding_test.gointernal/ingestion/task/has_vectors_test.gointernal/ingestion/task/real_consumer_test.gointernal/service/document.gointernal/service/document_test.gointernal/service/ingestion_task_service.gointernal/service/ingestion_task_service_test.gointernal/service/ingestion_task_transition_test.gointernal/service/task_publisher.go
💤 Files with no reviewable changes (3)
- internal/ingestion/task/has_vectors_test.go
- internal/ingestion/task/embedding_test.go
- internal/ingestion/task/dataflow_service.go
95308fd to
ae4cd6f
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/entity/ingestion_task.go`:
- Line 22: The `DocumentID` field in `IngestionTask` currently causes
`AutoMigrate` to create a unique index before `RunMigrations` can handle legacy
duplicates. Remove the `uniqueIndex:idx_ingestion_task_document_id` constraint
from its GORM tag, then add or preserve creation of that unique index
exclusively in the manual `RunMigrations` migration logic after duplicate
handling.
🪄 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: 4464e0f6-0661-4e8c-9593-394dec78d61c
📒 Files selected for processing (27)
internal/admin/handler.gointernal/admin/service.gointernal/dao/ingestion.gointernal/dao/ingestion_task_test.gointernal/dao/migration.gointernal/dao/task_test.gointernal/deepdoc/parser/pdf/parser_pipeline_integration_test.gointernal/engine/infinity/chunk.gointernal/entity/ingestion_task.gointernal/handler/document.gointernal/handler/document_test.gointernal/httputil/ingestion_task_error.gointernal/httputil/ingestion_task_error_test.gointernal/ingestion/pipeline/real_storage_integration_test.gointernal/ingestion/service/ingestion_service.gointernal/ingestion/task/dataflow_chunk_assets.gointernal/ingestion/task/dataflow_e2e_test.gointernal/ingestion/task/dataflow_service.gointernal/ingestion/task/embedding_test.gointernal/ingestion/task/has_vectors_test.gointernal/ingestion/task/real_consumer_test.gointernal/service/document.gointernal/service/document_test.gointernal/service/ingestion_task_service.gointernal/service/ingestion_task_service_test.gointernal/service/ingestion_task_transition_test.gointernal/service/task_publisher.go
💤 Files with no reviewable changes (4)
- internal/ingestion/task/dataflow_chunk_assets.go
- internal/ingestion/task/has_vectors_test.go
- internal/ingestion/task/dataflow_service.go
- internal/ingestion/task/embedding_test.go
✅ Files skipped from review due to trivial changes (3)
- internal/httputil/ingestion_task_error_test.go
- internal/ingestion/pipeline/real_storage_integration_test.go
- internal/deepdoc/parser/pdf/parser_pipeline_integration_test.go
🚧 Files skipped from review as they are similar to previous changes (17)
- internal/httputil/ingestion_task_error.go
- internal/ingestion/task/real_consumer_test.go
- internal/dao/ingestion_task_test.go
- internal/service/ingestion_task_transition_test.go
- internal/service/document_test.go
- internal/service/task_publisher.go
- internal/engine/infinity/chunk.go
- internal/admin/handler.go
- internal/handler/document_test.go
- internal/dao/ingestion.go
- internal/handler/document.go
- internal/admin/service.go
- internal/ingestion/task/dataflow_e2e_test.go
- internal/ingestion/service/ingestion_service.go
- internal/service/ingestion_task_service_test.go
- internal/service/document.go
- internal/service/ingestion_task_service.go
| ID string `gorm:"column:id;primaryKey;size:32" json:"id"` | ||
| UserID string `gorm:"column:user_id;size:32;not null" json:"user_id"` | ||
| DocumentID string `gorm:"column:document_id;size:32;not null;index" json:"document_id"` | ||
| DocumentID string `gorm:"column:document_id;size:32;not null;uniqueIndex:idx_ingestion_task_document_id" json:"document_id"` |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Find AutoMigrate calls and whether IngestionTask is included, plus ordering vs RunMigrations.
rg -nP 'AutoMigrate' --type=go -C3
rg -nP 'IngestionTask\b' --type=go -g '!**/*_test.go' -C2 | rg -n 'AutoMigrate|Migrator|RunMigrations' -C2Repository: infiniflow/ragflow
Length of output: 265
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate the owning files and relevant symbols.
git ls-files | rg 'internal/entity/ingestion_task\.go|migrate|migration|gorm|main\.go|db\.go|repository|store'
echo '--- ingestion_task.go ---'
cat -n internal/entity/ingestion_task.go | sed -n '1,120p'
echo '--- AutoMigrate / RunMigrations / IngestionTask references ---'
rg -n 'AutoMigrate|RunMigrations|IngestionTask\b|migrateIngestionTaskDocumentIDUnique' internal -g '!**/*_test.go' -C 2
echo '--- broader repo references ---'
rg -n 'AutoMigrate|RunMigrations|IngestionTask\b|migrateIngestionTaskDocumentIDUnique' -g '!**/*_test.go' -C 2Repository: infiniflow/ragflow
Length of output: 29744
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- internal/dao/database.go (migration bootstrap) ---'
cat -n internal/dao/database.go | sed -n '140,260p'
echo '--- internal/dao/migration.go (ingestion task migration) ---'
cat -n internal/dao/migration.go | sed -n '200,270p'
echo '--- duplicate-index handling helpers ---'
rg -n 'duplicate index|autoMigrateSafely|AutoMigrate\(' internal/dao/database.go internal/dao/migration.go -n -C 2Repository: infiniflow/ragflow
Length of output: 9925
Keep this unique index out of AutoMigrate
internal/dao/database.go migrates entity.IngestionTask before RunMigrations, so this tag can still make startup try to add the unique index on legacy rows with duplicate document_id values and fail before the manual skip logic runs. Move the uniqueness enforcement to the manual migration path instead.
🤖 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/entity/ingestion_task.go` at line 22, The `DocumentID` field in
`IngestionTask` currently causes `AutoMigrate` to create a unique index before
`RunMigrations` can handle legacy duplicates. Remove the
`uniqueIndex:idx_ingestion_task_document_id` constraint from its GORM tag, then
add or preserve creation of that unique index exclusively in the manual
`RunMigrations` migration logic after duplicate handling.
Source: Linters/SAST tools
Summary
Refine ingestion task state transitions