Skip to content

Go: use NATS as the message queue - #15327

Merged
JinHai-CN merged 28 commits into
infiniflow:mainfrom
JinHai-CN:fix440
Jun 12, 2026
Merged

JinHai-CN merged 28 commits into
infiniflow:mainfrom
JinHai-CN:fix440

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented May 28, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

RAGFlow(admin)> mq publish 'msg2';
SUCCESS
RAGFlow(admin)> mq publish 'msg3';
SUCCESS
RAGFlow(admin)> mq list;
+---------+---------------+
| message | subject       |
+---------+---------------+
| msg1    | tasks.RAGFLOW |
| msg2    | tasks.RAGFLOW |
| msg3    | tasks.RAGFLOW |
+---------+---------------+
RAGFlow(admin)> mq pull 2;
+---------+---------------+
| message | subject       |
+---------+---------------+
| msg1    | tasks.RAGFLOW |
| msg2    | tasks.RAGFLOW |
+---------+---------------+
RAGFlow(admin)> mq pull noack;
+---------+---------------+
| message | subject       |
+---------+---------------+
| abc     | tasks.RAGFLOW |
+---------+---------------+
RAGFlow(admin)> mq show
+-------------------+----------------+--------+---------------+---------------+-------------------+---------------+
| ack_pending_count | consumer_count | memory | message_count | pending_count | redelivered_count | waiting_count |
+-------------------+----------------+--------+---------------+---------------+-------------------+---------------+
| 2                 | 1              | 0      | 2             | 0             | 1                 | 0             |
+-------------------+----------------+--------+---------------+---------------+-------------------+---------------+

RAGFlow(admin)> list ingestors;
+--------------+-------------------------------------------+--------+
| host         | name                                      | status |
+--------------+-------------------------------------------+--------+
| 192.168.1.38 | ingestor-8f0e4bd5650a4ac58b0151969fbf6935 | alive  |
+--------------+-------------------------------------------+--------+

RAGFlow(admin)> list ingestion tasks;
+----------------------------------+----------------------------------+-----------+------+-------------+----------------------------------+
| document_id                      | id                               | status    | step | user        | user_id                          |
+----------------------------------+----------------------------------+-----------+------+-------------+----------------------------------+
| ffe64fae423411f1a2d938a74640adcc | 90d3d0f6528941c1ac8eb0360effccc4 | COMPLETED | 5    | [email protected] | 2ba4881420fa11f19e9c38a74640adcc |
+----------------------------------+----------------------------------+-----------+------+-------------+----------------------------------+

RAGFlow(admin)> remove ingestion tasks '90d3d0f6528941c1ac8eb0360effccc4';
+---------+----------------------------------+
| delete  | task_id                          |
+---------+----------------------------------+
| success | 90d3d0f6528941c1ac8eb0360effccc4 |
+---------+----------------------------------+

RAGFlow(admin)> stop ingestion tasks 'e89e20d9a25848a1b79bd9345ddbfe1d';
+----------+----------------------------------+
| status   | task_id                          |
+----------+----------------------------------+
| STOPPING | e89e20d9a25848a1b79bd9345ddbfe1d |
+----------+----------------------------------+

# Publish a message
RAGFlow(admin)> mq publish 'cdd';
SUCCESS

# List current tasks in the message queue
RAGFlow(admin)> mq list
+----------------------------------+---------------+
| message                          | subject       |
+----------------------------------+---------------+
| 7ce392a3c1624cd2be4b5276e8825059 | tasks.RAGFLOW |
+----------------------------------+---------------+

# Consume a task from the message queue
RAGFlow(admin)> mq pull
+------+-----+----------------+
| ack  | id  | type           |
+------+-----+----------------+
| true | cdd | ingestion_test |
+------+-----+----------------+

# User mode
# List ingestion tasks, followed by dataset id
RAGFlow(user)> list ingestion tasks from '0abe79f9423311f1ad8d38a74640adcc';
+---------------------------+---------------+----------------------------------+----------------------------------+----------------------------------+--------+-----------+---------------------------+---------------+----------------------------------+
| create_date               | create_time   | dataset_id                       | document_id                      | id                               | schema | status    | update_date               | update_time   | user_id                          |
+---------------------------+---------------+----------------------------------+----------------------------------+----------------------------------+--------+-----------+---------------------------+---------------+----------------------------------+
| 2026-05-30T20:21:06+08:00 | 1780143666289 | 0abe79f9423311f1ad8d38a74640adcc | ffe64fae423411f1a2d938a74640adcc | 8d758cd14a8b4ba8ab505003fb52017d |        | COMPLETED | 2026-05-30T20:21:26+08:00 | 1780143686431 | 2ba4881420fa11f19e9c38a74640adcc |
+---------------------------+---------------+----------------------------------+----------------------------------+----------------------------------+--------+-----------+---------------------------+---------------+----------------------------------+

RAGFlow(user)> list ingestion tasks;
+---------------------------+---------------+----------------------------------+----------------------------------+----------------------------------+--------+-----------+---------------------------+---------------+----------------------------------+
| create_date               | create_time   | dataset_id                       | document_id                      | id                               | schema | status    | update_date               | update_time   | user_id                          |
+---------------------------+---------------+----------------------------------+----------------------------------+----------------------------------+--------+-----------+---------------------------+---------------+----------------------------------+
| 2026-06-02T19:02:31+08:00 | 1780398151417 | 0abe79f9423311f1ad8d38a74640adcc | ffe64fae423411f1a2d938a74640adcc | e89e20d9a25848a1b79bd9345ddbfe1d |        | COMPLETED | 2026-06-02T19:02:52+08:00 | 1780398172208 | 2ba4881420fa11f19e9c38a74640adcc |
+---------------------------+---------------+----------------------------------+----------------------------------+----------------------------------+--------+-----------+---------------------------+---------------+----------------------------------+

# Create an ingestion task
# First argument is document id, second argument is dataset id
RAGFlow(user)> start ingestion 'ffe64fae423411f1a2d938a74640adcc' from '0abe79f9423311f1ad8d38a74640adcc';
+----------------------------------+-------------------------------------------+
| document_id                      | result                                    |
+----------------------------------+-------------------------------------------+
| ffe64fae423411f1a2d938a74640adcc | task_id: 8d758cd14a8b4ba8ab505003fb52017d |
+----------------------------------+-------------------------------------------+

# Pause an ingestion task, first argument is ingestion id
RAGFlow(user)> stop ingestion '8d758cd14a8b4ba8ab505003fb52017d';
+---------------------------+---------------+----------------------------------+----------------------------------+----------------------------------+--------+-----------+---------------------------+---------------+----------------------------------+
| create_date               | create_time   | dataset_id                       | document_id                      | id                               | schema | status    | update_date               | update_time   | user_id                          |
+---------------------------+---------------+----------------------------------+----------------------------------+----------------------------------+--------+-----------+---------------------------+---------------+----------------------------------+
| 2026-05-30T20:21:06+08:00 | 1780143666289 | 0abe79f9423311f1ad8d38a74640adcc | ffe64fae423411f1a2d938a74640adcc | 8d758cd14a8b4ba8ab505003fb52017d |        | COMPLETED | 2026-05-30T20:21:26+08:00 | 1780143686431 | 2ba4881420fa11f19e9c38a74640adcc |
+---------------------------+---------------+----------------------------------+----------------------------------+----------------------------------+--------+-----------+---------------------------+---------------+----------------------------------+

# Delete an ingestion task
RAGFlow(api/default)> remove ingestion tasks 'f366450a27d54677aec1c7090add30f0';
+---------+----------------------------------+
| remove  | task_id                          |
+---------+----------------------------------+
| success | f366450a27d54677aec1c7090add30f0 |
+---------+----------------------------------+

Type of change

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

@coderabbitai

coderabbitai Bot commented May 28, 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: bf76ea72-153c-4250-9ca5-dda987d4dd64

📥 Commits

Reviewing files that changed from the base of the PR and between 148e795 and 3d5656d.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (3)
  • go.mod
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/cli/user_parser.go
  • internal/cli/user_command.go
  • go.mod

📝 Walkthrough

Walkthrough

Migrates ingestion from gRPC to NATS: adds task/message contracts, NATS JetStream engine, transactional DAOs, queue-driven ingestor runtime, updated APIs/CLI, and startup/heartbeat wiring with NATS configuration and Docker compose updates.

Changes

Queue-Driven Ingestion System

Layer / File(s) Summary
Shared contracts & errors
internal/common/task.go, internal/common/constants.go, internal/common/error_code.go, internal/common/status_message.go, internal/common/number.go, internal/storage/types.go
Adds task message types, status constants, and shared errors/helpers used across ingestion and admin flows.
Ingestion models & migration
internal/entity/ingestion_task.go, internal/entity/base.go, internal/dao/database.go
Reshapes ingestion/tasklet/log schemas to store status/schema/checkpoints and adds BaseModel timestamp helpers; includes models in DB auto-migrate.
Message queue abstraction & NATS impl
internal/engine/engine.go, internal/engine/global.go, internal/engine/nats/nats.go
Defines MessageQueue interface, global init/getter, and implements JetStream-backed NatsEngine with publish, list, consumer init, fetch, and message-handle ack/nack.
Task persistence DAOs
internal/dao/ingestion.go
Replaces legacy ingestion DAOs with IngestionTaskDAO and related DAOs featuring transactional CheckAndCreate, state transitions, guarded removals (file aggregation), logs, tasklets, and paginated listing.
Document service orchestration
internal/service/document.go
Refactors ingestion entry to create tasks via DAOs and publish to queue; adds List/Stop/Remove ingestion task service methods.
Document API handlers & routing
internal/handler/document.go, internal/router/router.go
Replaces parse endpoint with ingestion task endpoints (list/start/stop/remove) and updates dataset routes to /ingestion/tasks.
Ingestor runtime (queue consumer)
internal/ingestion/ingestion_service.go
Refactors ingestor to consume tasks.RAGFLOW, mark tasks RUNNING via DAO, execute tasks/tasklets with checkpointed step logs, and simplify shutdown; deactivates gRPC admin lifecycle.
Admin service & API operations
internal/admin/service.go, internal/admin/handler.go, internal/admin/router.go, internal/admin/state.go
Adds admin endpoints for queue show/list/publish/pull and ingestion task list/stop/remove; enriches task listings with latest checkpoint step; computes service liveness from heartbeat timestamp; updates state mutexing and error comparisons to common errors.
CLI grammar, parsers & commands
internal/cli/types.go, internal/cli/lexer.go, internal/cli/parser.go, internal/cli/admin_parser.go, internal/cli/user_parser.go, internal/cli/admin_command.go, internal/cli/user_command.go, internal/cli/cli_http.go
Adds MQ-related tokens/keywords, parser rules, and admin/user command handlers for queue inspection, publish/pull, and ingestion task start/stop/list/remove.
Startup, heartbeat & deployment
cmd/ingestor.go, cmd/admin_server.go, cmd/server_main.go, internal/service/admin_client.go, internal/server/config.go, conf/service_conf.yaml, docker/.env, docker/docker-compose-base.yml, docker/service_conf.yaml.template, go.mod, .gitignore
Initializes message-queue engine on startup (non-fatal), migrates heartbeat sender to AdminClient scheduled reports, removes ingestion-manager gRPC lifecycle, adds NATS config and docker-compose NATS service, and updates module deps.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🐰 From streams to queues I hop with glee,
Tasks now flow where JetStream breathes free,
Checkpoints saved, DAOs keep the score,
Heartbeats hum and Docker opens the door,
A rabbit cheers: ingestion runs with esprit!

Suggested labels: ☯️ refactor, size:L

@JinHai-CN
JinHai-CN marked this pull request as ready for review June 2, 2026 12:59
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jun 2, 2026
@JinHai-CN JinHai-CN added ci Continue Integration and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Jun 2, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft June 2, 2026 12:59
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 2, 2026 12:59
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jun 2, 2026
JinHai-CN added 2 commits June 2, 2026 21:00
Signed-off-by: Jin Hai <[email protected]>
@codecov

codecov Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (a2de880) to head (3d5656d).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15327   +/-   ##
=======================================
  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.

@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: 12

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

Caution

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

⚠️ Outside diff range comments (2)
internal/cli/admin_command.go (2)

1378-1397: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incorrect error messages in AdminRemoveIngestionCommand.

Similar to AdminStopIngestionCommand, the error messages reference "uri" and "ingest file" but this function removes ingestion tasks.

Proposed fix
 	tasks, ok := cmd.Params["tasks"].([]string)
 	if !ok {
-		return nil, fmt.Errorf("uri not provided")
+		return nil, fmt.Errorf("tasks not provided")
 	}
 	payload := map[string]interface{}{
 		"tasks": tasks,
 	}

 	resp, err := c.HTTPClient.Request("DELETE", "/admin/ingestion/tasks", "admin", nil, payload)
 	if err != nil {
-		return nil, fmt.Errorf("failed to ingest file: %w", err)
+		return nil, fmt.Errorf("failed to remove ingestion tasks: %w", err)
 	}

 	if resp.StatusCode != 200 {
-		return nil, fmt.Errorf("failed to ingest file: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
+		return nil, fmt.Errorf("failed to remove ingestion tasks: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
 	}
🤖 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/cli/admin_command.go` around lines 1378 - 1397, The
AdminRemoveIngestionCommand contains incorrect error messages referencing "uri"
and "ingest file"; update the error returns and log text in the block handling
cmd.Params["tasks"], the HTTP request, non-200 response, and JSON unmarshal to
refer to removing ingestion tasks (e.g., change messages like "uri not provided"
→ "tasks not provided", "failed to ingest file" → "failed to remove ingestion
tasks", and "ingest file failed" → "remove ingestion tasks failed") so that
functions/variables such as AdminRemoveIngestionCommand, cmd.Params["tasks"],
payload, c.HTTPClient.Request("DELETE", "/admin/ingestion/tasks", ...),
resp.StatusCode checks, and json.Unmarshal(resp.Body, &result) produce accurate
error strings.

1343-1357: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incorrect error messages in AdminStopIngestionCommand.

The error messages reference "uri" and "ingest file" but this function handles stopping ingestion tasks.

Proposed fix
 	tasks, ok := cmd.Params["tasks"].([]string)
 	if !ok {
-		return nil, fmt.Errorf("uri not provided")
+		return nil, fmt.Errorf("tasks not provided")
 	}
 	payload := map[string]interface{}{
 		"tasks": tasks,
 	}

 	resp, err := c.HTTPClient.Request("PUT", "/admin/ingestion/tasks", "admin", nil, payload)
 	if err != nil {
-		return nil, fmt.Errorf("failed to ingest file: %w", err)
+		return nil, fmt.Errorf("failed to stop ingestion tasks: %w", err)
 	}

 	if resp.StatusCode != 200 {
-		return nil, fmt.Errorf("failed to ingest file: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
+		return nil, fmt.Errorf("failed to stop ingestion tasks: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
 	}
🤖 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/cli/admin_command.go` around lines 1343 - 1357, The error messages
in the AdminStopIngestionCommand flow are incorrect: replace the "uri not
provided" message when cmd.Params["tasks"] fails to cast with a clear "tasks not
provided" (or similar) error referencing the tasks param, and update the
subsequent errors around the HTTP call to mention stopping ingestion tasks
(e.g., "failed to stop ingestion tasks: %w" for the request error and "failed to
stop ingestion tasks: HTTP %d, body: %s" for non-200 responses); locate the
check on cmd.Params["tasks"], the tasks variable, and the
c.HTTPClient.Request("PUT", "/admin/ingestion/tasks", ...) call to apply these
message changes.
🟠 Major comments (13)
internal/handler/document.go-820-842 (1)

820-842: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Missing authorization: any user can stop any task.

The handler retrieves userID (line 830) but doesn't verify task ownership before stopping. A user could stop another user's ingestion tasks by guessing task IDs.

Consider verifying ownership in the service layer or handler before stopping:

 func (h *DocumentHandler) StopIngestionTasks(c *gin.Context) {
 	// ... binding code ...

 	userID := c.GetString("user_id")

-	parseResult, err := h.documentService.StopIngestionTasks(req.Tasks, userID)
+	// Service should verify each task belongs to userID before stopping
+	parseResult, err := h.documentService.StopIngestionTasks(req.Tasks, userID)

The service's StopIngestionTasks should filter tasks by userID or return an error for unauthorized tasks.

🤖 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.go` around lines 820 - 842, The StopIngestionTasks
handler currently calls h.documentService.StopIngestionTasks(req.Tasks, userID)
but does not ensure the tasks belong to the requesting user (userID), allowing
cross-user stops; update the authorization by verifying ownership either in the
handler or (preferably) inside the service method StopIngestionTasks: have it
filter the provided req.Tasks list to only include tasks owned by userID or
return an unauthorized error for any task not owned, and ensure the handler
surfaces that unauthorized/error response instead of blindly stopping tasks;
reference StopIngestionsRequest, userID, h.documentService.StopIngestionTasks
and parseResult when making the change.
internal/service/document.go-314-340 (1)

314-340: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Task creation and queue publish are not atomic—failed publish leaves orphan tasks.

If PublishTask fails (line 337), the task was already persisted to the database (line 314). This creates an orphaned task that exists in the DB but never enters the queue. The same applies if json.Marshal fails after some tasks were successfully published.

Consider either:

  1. Rolling back the DB entry on publish failure, or
  2. Collecting all errors and returning partial success info instead of early-returning
🛠️ Suggested approach: Continue on publish failure and report per-document status
 		// save the task to database
 		task, err = s.ingestionTaskDAO.CheckAndCreate(task)
 		if err != nil {
 			errorMessage := err.Error()
 			responses = append(responses, &ParseDocumentResponse{
 				DocumentID: docID,
 				Result:     errorMessage,
 			})
 			continue
 		}

 		msgQueueEngine := engine.GetMessageQueueEngine()

 		taskMessage := common.TaskMessage{
 			TaskID:   task.ID,
 			TaskType: common.TaskTypeIngestionTask,
 		}

 		// convert task
 		taskMessageStr, err := json.Marshal(taskMessage)
 		if err != nil {
-			return nil, err
+			responses = append(responses, &ParseDocumentResponse{
+				DocumentID: docID,
+				Result:     fmt.Sprintf("failed to marshal task: %s", err.Error()),
+			})
+			continue
 		}

 		err = msgQueueEngine.PublishTask("tasks.RAGFLOW", taskMessageStr)
 		if err != nil {
-			return nil, err
+			responses = append(responses, &ParseDocumentResponse{
+				DocumentID: docID,
+				Result:     fmt.Sprintf("failed to publish task: %s", err.Error()),
+			})
+			continue
 		}
🤖 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/document.go` around lines 314 - 340, The current flow
creates a persistent ingestion task via s.ingestionTaskDAO.CheckAndCreate then
returns immediately on json.Marshal or msgQueueEngine.PublishTask failures,
leaving orphaned DB tasks; update the loop in ParseDocument handling so that on
marshal or PublishTask errors you either rollback the created task (call the DAO
delete/rollback method or use a transaction surrounding CheckAndCreate and
publish) or do not early-return but append a per-document ParseDocumentResponse
containing the error (using DocumentID and Result) and continue processing
remaining documents; specifically modify the code paths around
s.ingestionTaskDAO.CheckAndCreate, json.Marshal(taskMessage), and
msgQueueEngine.PublishTask to perform rollback or report-and-continue semantics
instead of returning nil, err.
internal/admin/service.go-134-143 (1)

134-143: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Unsafe type assertion may cause panic.

If Checkpoint["current_step"] is missing or not a float64, line 141 will panic. Use a type assertion with ok-check.

🐛 Proposed fix
-		if err == nil {
-			showTask = map[string]interface{}{
-				"id":          task.ID,
-				"user_id":     task.UserID,
-				"user":        user.Email,
-				"document_id": task.DocumentID,
-				"status":      task.Status,
-				"step":        int(latestLog.Checkpoint["current_step"].(float64)),
-			}
-		}
+		if err == nil {
+			if step, ok := latestLog.Checkpoint["current_step"].(float64); ok {
+				showTask["step"] = int(step)
+			}
+		}
🤖 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/service.go` around lines 134 - 143, In the block that builds
showTask inside internal/admin/service.go (where
latestLog.Checkpoint["current_step"].(float64) is used), replace the unsafe type
assertion with a safe ok-check: read latestLog.Checkpoint["current_step"],
assert it is a float64 using the comma-ok pattern, handle the case where it is
missing or not a float64 (e.g., default to 0 or nil), then convert the validated
float64 to int for the "step" field; update the code that constructs showTask so
it uses this validated value instead of the direct assertion to avoid panics in
the function/method that generates the task response.
internal/dao/ingestion.go-58-79 (1)

58-79: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle gorm “record not found” separately in CheckAndCreate

internal/dao/ingestion.go IngestionTaskDAO.CheckAndCreate falls into the “create ingestion task” path for any non-nil error from First(...) (no gorm.ErrRecordNotFound guard). A transient DB/connection error can therefore bypass the existing-task check and create/commit a new task.

🐛 Proposed fix
 	var taskRecord *entity.IngestionTask
 	err := tx.Where("document_id = ?", ingestionTask.DocumentID).First(&taskRecord).Error
-	if err == nil {
+	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+		tx.Rollback()
+		return nil, err
+	}
+	if err == nil {
 		// found
 		if taskRecord.Status == common.FAILED || taskRecord.Status == common.STOPPED {
 			// restart the task
 			err = tx.Model(&entity.IngestionTask{}).Where("id = ?", taskRecord.ID).Update("status", common.CREATED).Error
 			if err != nil {
 				tx.Rollback()
 				return nil, err
 			}
+			taskRecord.Status = common.CREATED
 		} else {

This requires importing gorm.io/gorm (or the file’s existing GORM import path); errors is already imported here.

🤖 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 58 - 79, In
IngestionTaskDAO.CheckAndCreate, don't treat any non-nil error from
tx.Where(...).First(&taskRecord).Error as "not found"; import the GORM package
(gorm.io/gorm) and check specifically for gorm.ErrRecordNotFound — only create a
new ingestionTask when that sentinel error is returned; for any other error
return/rollback the transaction and propagate the error instead of falling
through to the create path. Update the tx.First error handling around the
tx.Where(...).First(&taskRecord).Error, the restart/update branch
(tx.Model(...).Update(...)), and the create branch (tx.Create(ingestionTask))
accordingly so transient DB/connection errors do not cause unintentional
creations.
internal/dao/ingestion.go-276-286 (1)

276-286: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Unchecked DB error and incorrect JSON type assertion when collecting files-to-delete

  • err = tx.Where("tasklet_id = ?", tasklet.ID).Find(&taskletLogs).Error is not checked; query failures are silently ignored.
  • taskletLog.Checkpoint["files"].([]string) (and the same pattern for taskLog) is incorrect because Checkpoint is entity.JSONMap map[string]interface{}; JSON arrays deserialize as []interface{} (so the []string assertion will fail and FilesToDelete ends up empty).
🐛 Proposed fix (check err; handle JSON array decoding)
 			var taskletLogs []*entity.IngestionTaskletLog
-			err = tx.Where("tasklet_id = ?", tasklet.ID).Find(&taskletLogs).Error
+			if err = tx.Where("tasklet_id = ?", tasklet.ID).Find(&taskletLogs).Error; err != nil {
+				return nil, err
+			}
 
 			fileMap := make(map[string]bool)
 			for _, taskletLog := range taskletLogs {
-				files, ok := taskletLog.Checkpoint["files"].([]string)
-				if ok {
-					for _, f := range files {
-						if s, ok := f.(string); ok {
-							fileMap[s] = true
-						}
-					}
+				if files, ok := taskletLog.Checkpoint["files"].([]interface{}); ok {
+					for _, f := range files {
+						if s, ok := f.(string); ok {
+							fileMap[s] = true
+						}
+					}
 				}
 			}
🤖 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 276 - 286, Check and handle the DB
error returned by the query that populates taskletLogs (err =
tx.Where("tasklet_id = ?", tasklet.ID).Find(&taskletLogs).Error) instead of
ignoring it, and update the JSON array extraction from taskletLog.Checkpoint to
handle deserialized []interface{} values (convert each element to string before
adding to fileMap). Do the same for the taskLog extraction path if present (look
for variables named taskLog, taskLogs, Checkpoint and FilesToDelete) to ensure
JSON arrays are decoded safely and any DB errors are returned/handled rather
than swallowed.
internal/dao/ingestion.go-456-477 (1)

456-477: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fix incorrect column used by IngestionTaskletLogDAO methods

  • ListLogsByTaskletID and DeleteByTaskletID (internal/dao/ingestion.go lines ~456-477) filter on task_id, but entity.IngestionTaskletLog maps the scoped field as TaskletID -> gorm:"column:tasklet_id".
  • Update both WHERE clauses to tasklet_id = ? and rename the parameter to taskletID for consistency with LatestLogByTaskletID (already uses tasklet_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 456 - 477, ListLogsByTaskletID and
DeleteByTaskletID currently filter on the wrong column (`task_id`) and use an
inconsistent parameter name; update the method signatures and WHERE clauses so
they accept `taskletID string` (not `taskID`) and query `tasklet_id = ?`
(matching the entity's TaskletID gorm column) in both
`IngestionTaskletLogDAO.ListLogsByTaskletID` and
`IngestionTaskletLogDAO.DeleteByTaskletID`, keeping `LatestLogByTaskletID` as
the canonical example for naming and column usage.
internal/dao/ingestion.go-318-329 (1)

318-329: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Ingestion task removal leaves tasklet/log rows orphaned

internal/dao/ingestion.go (RemoveByAPIServerOrAdminServer) deletes only the ingestion_task row in the transaction, while the corresponding ingestion_tasklet, ingestion_tasklet_log, and ingestion_task_log rows are only queried and never deleted. internal/service/document.go and internal/admin/service.go call this DAO directly and don’t perform any further cleanup. With BaseModel containing no gorm.DeletedAt (so Delete is a hard delete) and no cascade/foreign-key behavior for these tables defined in the repo, this leaves hard-orphan rows unless it’s handled elsewhere externally.

Delete the related tasklet/log rows in the same transaction (e.g., using the existing DeleteByTaskID/DeleteByTaskletID helpers) or add/ensure DB-level ON DELETE CASCADE constraints.

🤖 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 318 - 329, The
RemoveByAPIServerOrAdminServer implementation currently only deletes the
ingestion_task row leaving ingestion_tasklet, ingestion_tasklet_log, and
ingestion_task_log orphaned; update RemoveByAPIServerOrAdminServer to delete
related rows inside the same transaction by calling the existing helpers (e.g.,
DeleteByTaskID to remove ingestion_tasklet and ingestion_task_log, and
DeleteByTaskletID for ingestion_tasklet_log as needed) before deleting the
ingestion_task, or alternatively ensure/declare DB-level ON DELETE CASCADE
constraints for those tables so the tasklets/logs are removed atomically with
the task.
internal/entity/base.go-122-127 (1)

122-127: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

UpdateCreateDateAndTime sets the wrong date field.

The method updates CreateTime but then writes UpdateDate instead of CreateDate. As written, CreateDate is never populated while UpdateDate gets clobbered, which contradicts the method name and the paired UpdateUpdateDateAndTime semantics.

🐛 Proposed fix
 func (m *BaseModel) UpdateCreateDateAndTime() error {
 	timestamp, dateTime := autoModelTime()
 	m.CreateTime = &timestamp
-	m.UpdateDate = &dateTime
+	m.CreateDate = &dateTime
 	return 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/entity/base.go` around lines 122 - 127, The UpdateCreateDateAndTime
method is assigning the timestamp to CreateTime but mistakenly writes dateTime
to UpdateDate; change it to set CreateDate (i.e., assign dateTime to the
CreateDate field) so both CreateTime and CreateDate are populated correctly
(matching the paired UpdateUpdateDateAndTime semantics and the method name).
internal/engine/nats/nats.go-163-177 (1)

163-177: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Loop breaks prematurely on gaps in stream sequence.

When a message at seq is not found (e.g., due to message expiration or deletion), the loop breaks immediately, skipping all subsequent messages. This should continue to the next sequence instead.

🐛 Proposed fix to handle sequence gaps
 	for seq <= lastSeq {
 		var msg *jetstream.RawStreamMsg
 		msg, err = n.stream.GetMsg(ctx, seq, jetstream.WithGetMsgSubject(subjectFilter))
 		if err != nil {
 			if errors.Is(err, jetstream.ErrMsgNotFound) {
-				break
+				seq++
+				continue
 			}
 			return nil, fmt.Errorf("failed to get message at seq %d: %w", seq, err)
 		}
🤖 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/engine/nats/nats.go` around lines 163 - 177, The loop currently
breaks on jetstream.ErrMsgNotFound which skips later messages; instead, when
n.stream.GetMsg(ctx, seq, ...) returns jetstream.ErrMsgNotFound, increment seq
(e.g., seq++) and continue to the next iteration so the loop skips the missing
sequence but still processes subsequent messages; keep the existing error
handling for other errors, continue to build messageMap and append to messages
when msg is returned, and use msg.Sequence+1 to advance normally when a message
is found.
internal/engine/nats/nats.go-231-238 (1)

231-238: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Silent failure returns empty TaskMessage on unmarshal error.

If JSON unmarshalling fails, an error is logged but a zero-value TaskMessage is returned. Callers cannot distinguish between a valid empty message and a parse failure, leading to silent data corruption.

🐛 Proposed fix to return error or indicate failure

Option 1: Change signature to return error:

-func (m *NatsMessageHandle) GetMessage() common.TaskMessage {
+func (m *NatsMessageHandle) GetMessage() (common.TaskMessage, error) {
 	var taskMessage common.TaskMessage
 	if err := json.Unmarshal(m.message.Data(), &taskMessage); err != nil {
-		common.Error("failed to unmarshal message", err)
+		return taskMessage, fmt.Errorf("failed to unmarshal message: %w", err)
 	}
-	return taskMessage
+	return taskMessage, nil
 }

Note: This requires updating the TaskHandle interface in internal/common/task.go and all callers.

🤖 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/engine/nats/nats.go` around lines 231 - 238, The GetMessage method
on NatsMessageHandle currently swallows json.Unmarshal errors and returns a
zero-value common.TaskMessage; change NatsMessageHandle.GetMessage to return
(common.TaskMessage, error) instead of just common.TaskMessage, return the
unmarshalled message on success and the uninitialized value plus the error on
failure, and update the TaskHandle interface (in internal/common/task.go) and
all callers to handle the returned error (propagate or handle appropriately) so
callers can distinguish parse failures from valid empty messages.
cmd/ingestor.go-164-170 (1)

164-170: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Ingestor continues running even when Start() fails.

If ingestor.Start() returns an error, the goroutine logs and returns, but the main function continues waiting for OS signals. The ingestor appears to be running but processes no tasks. Consider triggering shutdown on critical failure.

🐛 Proposed fix to trigger shutdown on Start failure
 	go func() {
 		err := ingestor.Start()
 		if err != nil {
 			common.Error("Failed to initialize ingestor", err)
-			return
+			// Trigger shutdown
+			select {
+			case ingestor.ShutdownCh <- struct{}{}:
+			default:
+			}
 		}
 	}()
🤖 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 `@cmd/ingestor.go` around lines 164 - 170, The goroutine launching ingestor
(the block calling ingestor.Start()) currently logs and returns on error but
leaves the main process waiting for OS signals; update that error path to
trigger the app shutdown using the program's existing shutdown mechanism (e.g.,
call the context cancel function, close/send to the shutdown channel, or call
os.Exit(1)) so a Start failure terminates the process; locate the goroutine
where ingestor.Start() is invoked and replace the simple return after
common.Error("Failed to initialize ingestor", err) with a call to the app's
shutdown function (e.g., cancel(), close(stopChan) or equivalent) so the main
loop exits promptly on critical failure.
internal/engine/global.go-85-98 (1)

85-98: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Missing thread-safety for message queue initialization.

InitMessageQueueEngine lacks sync.Once protection unlike Init for the doc engine (line 42). If called concurrently from multiple goroutines, this could lead to race conditions on the messageQueueEngine global variable.

🔒 Proposed fix to add sync.Once protection
 var (
 	globalEngine       DocEngine
 	engineType         EngineType
 	messageQueueEngine MessageQueue
 	once               sync.Once
+	mqOnce             sync.Once
 )
 func InitMessageQueueEngine(messageQueueType string) error {
+	var initErr error
+	mqOnce.Do(func() {
 	config := server.GetConfig()
 	switch messageQueueType {
 	case "nats":
 		messageQueueEngine = nats.NewNatsEngine(config.Nats.Host, config.Nats.Port)
-		err := messageQueueEngine.Init()
+		err := messageQueueEngine.Init()
 		if err != nil {
-			return err
+			initErr = err
+			return
 		}
 	default:
-		return fmt.Errorf("unsupported message queue type: %s", messageQueueType)
+		initErr = fmt.Errorf("unsupported message queue type: %s", messageQueueType)
 	}
-	return nil
+	})
+	return initErr
 }
🤖 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/engine/global.go` around lines 85 - 98, InitMessageQueueEngine is
not protected against concurrent calls and can race when setting the global
messageQueueEngine; add a sync.Once (e.g., messageQueueOnce) to ensure
initialization runs only once, move the NATS creation/Init into the Once.Do
closure, capture any init error into a package-level variable (e.g.,
messageQueueInitErr) so callers get the result, and have InitMessageQueueEngine
return that error when subsequent calls occur; update references to the global
messageQueueEngine and ensure the function remains idempotent and thread-safe.
internal/ingestion/ingestion_service.go-540-543 (1)

540-543: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Manual ID++ increment bypasses GORM auto-increment.

Manually incrementing latestLog.ID before calling Create may conflict with the database's auto-increment behavior, potentially causing primary key collisions or unexpected behavior.

🐛 Proposed fix to let GORM handle ID
 			checkpointMap["current_step"] = i + 1
-			latestLog.Checkpoint = checkpointMap
-			latestLog.ID++
-			err = latestLog.UpdateCreateDateAndTime()
+			newLog := &entity.IngestionTaskLog{
+				TaskID:     task.ID,
+				Checkpoint: checkpointMap,
+			}
+			err = newLog.UpdateCreateDateAndTime()
 			if err != nil {
 				common.Error(fmt.Sprintf("Failed to update date and time of task log for task %s", task.ID), err)
 				return
 			}
-
-			err = e.ingestionTaskLogDAO.Create(latestLog)
+			err = e.ingestionTaskLogDAO.Create(newLog)
🤖 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/ingestion_service.go` around lines 540 - 543, The code is
manually incrementing latestLog.ID which bypasses GORM's auto-increment and can
cause PK collisions; remove the manual increment (delete the `latestLog.ID++`
operation) and ensure the record is created with GORM's auto-increment by
leaving latestLog.ID as the zero value (or explicitly set latestLog.ID = 0)
before calling Create; keep the checkpoint update (checkpointMap/current_step)
and the call to latestLog.UpdateCreateDateAndTime() but do not mutate ID
manually so GORM can assign the primary key.
🟡 Minor comments (10)
internal/admin/service.go-1119-1120 (1)

1119-1120: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Stale comment: says 5 seconds but code uses 30 seconds.

The comment mentions "less than 5 seconds" but the actual threshold is 30*time.Second.

📝 Proposed fix
-		// the difference between now and serverStatus.Timestamp is less than 5 seconds, then the server is alive
+		// the difference between now and serverStatus.Timestamp is less than 30 seconds, then the server is alive
 		if now.Sub(serverStatus.Timestamp) < 30*time.Second {
🤖 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/service.go` around lines 1119 - 1120, The inline comment above
the liveness check is stale (mentions "less than 5 seconds" but the code uses
30*time.Second); update the comment to match the actual threshold used by the
check (30 seconds) where the variables now and serverStatus.Timestamp are
compared in the liveness logic (the if using now.Sub(serverStatus.Timestamp) <
30*time.Second) so the comment accurately documents the behavior.
internal/dao/ingestion.go-61-67 (1)

61-67: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Returned taskRecord.Status is stale on the restart path.

After updating the DB status to CREATED, the in-memory taskRecord.Status still holds FAILED/STOPPED. Callers that rely on the returned struct's status (compare with SetRunningByIngestor, which updates the in-memory field) will see incorrect state. The fix is folded into the diff above (taskRecord.Status = common.CREATED).

🤖 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 61 - 67, After updating the DB row to
CREATED in the restart path (the tx.Model(&entity.IngestionTask{}).Where("id =
?", taskRecord.ID).Update("status", common.CREATED") call), also update the
in-memory struct by setting taskRecord.Status = common.CREATED before returning
so callers (e.g., SetRunningByIngestor comparisons) see the correct status;
ensure this assignment occurs only after a successful DB update and remains
inside the same transaction/flow.
internal/cli/admin_parser.go-1795-1799 (1)

1795-1799: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incomplete error message for REMOVE subcommand.

The error message says "expected SERVICE" but TokenIngestion is also a valid option for the REMOVE command.

Proposed fix
 	case TokenIngestion:
 		return p.parseAdminRemoveIngestionTasks()
 	default:
-		return nil, fmt.Errorf("expected SERVICE")
+		return nil, fmt.Errorf("expected SERVICE or INGESTION after REMOVE")
 	}
🤖 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/cli/admin_parser.go` around lines 1795 - 1799, The default error
message in the switch handling REMOVE currently reads "expected SERVICE" but the
branch supports TokenIngestion via parseAdminRemoveIngestionTasks; update the
error to accurately reflect valid operands (e.g., change the returned error in
the default case to mention both SERVICE and INGESTION or list valid tokens) so
callers get a correct message when neither SERVICE nor TokenIngestion matched;
locate the switch that returns parseAdminRemoveIngestionTasks and adjust the
fmt.Errorf call accordingly.
internal/cli/admin_parser.go-1756-1758 (1)

1756-1758: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Off-by-one in validation error message.

The condition rejects messageCount <= 0, so the minimum valid value is 1, but the error message says "cannot be less than 0" which is misleading.

Proposed fix
 	if messageCount <= 0 || messageCount > 100 {
-		return nil, fmt.Errorf("message count cannot be less than 0 or greater than 100")
+		return nil, fmt.Errorf("message count must be between 1 and 100")
 	}
🤖 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/cli/admin_parser.go` around lines 1756 - 1758, The validation for
messageCount (the if block checking "messageCount <= 0 || messageCount > 100")
uses an incorrect error text; update the error returned by that validation (the
statement that currently returns fmt.Errorf("message count cannot be less than 0
or greater than 100")) to correctly reflect the accepted range (e.g., "message
count must be between 1 and 100" or "cannot be less than 1 or greater than
100"), keeping this change in the same validation block referencing messageCount
in internal/cli/admin_parser.go.
internal/cli/user_command.go-3437-3457 (1)

3437-3457: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incorrect error messages in UserStopIngestionCommand.

The error messages reference "uri" and "ingest file" but this function stops ingestion tasks.

Proposed fix
 	tasks, ok := cmd.Params["tasks"].([]string)
 	if !ok {
-		return nil, fmt.Errorf("uri not provided")
+		return nil, fmt.Errorf("tasks not provided")
 	}
 	payload := map[string]interface{}{
 		"tasks": tasks,
 	}

 	resp, err := c.HTTPClient.Request("PUT", "/datasets/ingestion/tasks", "web", nil, payload)
 	if err != nil {
-		return nil, fmt.Errorf("failed to ingest file: %w", err)
+		return nil, fmt.Errorf("failed to stop ingestion tasks: %w", err)
 	}

 	if resp.StatusCode != 200 {
-		return nil, fmt.Errorf("failed to ingest file: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
+		return nil, fmt.Errorf("failed to stop ingestion tasks: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
 	}

 	var result CommonResponse
 	if err = json.Unmarshal(resp.Body, &result); err != nil {
-		return nil, fmt.Errorf("ingest file failed: invalid JSON (%w)", err)
+		return nil, fmt.Errorf("stop ingestion tasks failed: invalid JSON (%w)", err)
 	}
🤖 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/cli/user_command.go` around lines 3437 - 3457, The error strings in
UserStopIngestionCommand are incorrect: change the initial check on
cmd.Params["tasks"] to return an error like "tasks not provided" (replace the
current "uri not provided"), update the HTTP error messages around
c.HTTPClient.Request and resp.StatusCode to refer to stopping ingestion tasks
(e.g., "failed to stop ingestion tasks: %w" and "failed to stop ingestion tasks:
HTTP %d, body: %s"), and update the JSON unmarshal error to something like "stop
ingestion failed: invalid JSON (%w)"; these changes touch the code that reads
cmd.Params["tasks"], the c.HTTPClient.Request("PUT",
"/datasets/ingestion/tasks", ...) call, the resp.StatusCode error branch, and
the json.Unmarshal into result (CommonResponse).
internal/cli/admin_parser.go-1770-1772 (1)

1770-1772: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Misleading error message for invalid MQ subcommand.

When an unrecognized MQ subcommand is provided, the error says "expected WITH" which doesn't match any of the valid options (SHOW, LIST, PUBLISH, PULL).

Proposed fix
 	default:
-		return nil, fmt.Errorf("expected WITH")
+		return nil, fmt.Errorf("expected SHOW, LIST, PUBLISH, or PULL after MQ")
 	}
🤖 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/cli/admin_parser.go` around lines 1770 - 1772, The error message in
the MQ subcommand parsing branch currently returns fmt.Errorf("expected WITH"),
which is misleading; update the default/error return (the branch that currently
does return nil, fmt.Errorf("expected WITH")) to a clear message like
fmt.Errorf("invalid MQ subcommand: expected one of SHOW, LIST, PUBLISH, PULL")
so callers see valid options; locate the switch/default that returns that error
(the branch with return nil, fmt.Errorf("expected WITH")) and replace the
message accordingly.
internal/cli/user_command.go-3363-3369 (1)

3363-3369: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Typos in error messages.

Line 3364 has a double colon and line 3369 has inconsistent spacing/punctuation.

Proposed fix
 	if resp.StatusCode != 200 {
-		return nil, fmt.Errorf("failed to list ingestion tasks:: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
+		return nil, fmt.Errorf("failed to list ingestion tasks: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
 	}

 	var result CommonResponse
 	if err = json.Unmarshal(resp.Body, &result); err != nil {
-		return nil, fmt.Errorf("list ingestion tasks: failed: invalid JSON (%w)", err)
+		return nil, fmt.Errorf("list ingestion tasks failed: invalid JSON (%w)", err)
 	}
🤖 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/cli/user_command.go` around lines 3363 - 3369, Fix the typo and
punctuation in the two error messages: in the HTTP status check (the block that
inspects resp.StatusCode and uses resp.Body) replace the double-colon "failed to
list ingestion tasks:: HTTP" with a single colon and consistent spacing (e.g.
"failed to list ingestion tasks: HTTP %d, body: %s"), and in the json.Unmarshal
error (the block that unmarshals into result CommonResponse) make the message
consistent and clear (e.g. "list ingestion tasks: failed to parse/unmarshal
JSON: %w") so both errors use a single colon and consistent spacing; update the
fmt.Errorf calls around resp.StatusCode and json.Unmarshal accordingly.
internal/server/config.go-381-387 (1)

381-387: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Set service_type/support for NATS configs so the admin UI can classify them

  • GetAllConfigs() is only consumed by internal/admin/*; with NATS entries missing configDict["service_type"], internal/admin/service.go’s GetServiceDetails falls into the default path and returns "status": "unknown" (no NATS health check).
  • Runtime NATS engine wiring uses config.Nats.Host/Port (not allConfigs), so this inconsistency doesn’t affect message-queue functionality unless you rely on admin service-type handling.
🤖 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/server/config.go` around lines 381 - 387, GetAllConfigs() is
building NATS entries without a service_type so the admin UI classifies them as
unknown; update the NATS branch (where configDict is populated for case "nats")
to set configDict["service_type"] = "message_queue" and also add a subtype like
configDict["service_subtype"] = "nats" (or configDict["service_type"]="nats" if
your admin expects that) so internal/admin/service.go's GetServiceDetails can
detect and run the NATS health check; modify the branch that currently sets
id/name/host/port to include these service_type/subtype keys.
cmd/ingestor.go-139-141 (1)

139-141: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incorrect format verb %w used with fmt.Sprintf.

%w is only valid with fmt.Errorf for error wrapping. Using it with fmt.Sprintf or common.Fatal will print %!w(...) instead of the error.

🐛 Proposed fix
 	if err := engine.InitMessageQueueEngine(config.TaskExecutor.MessageQueueType); err != nil {
-		common.Fatal(fmt.Sprintf("Failed to initialize message queue engine: %w", err))
+		common.Fatal("Failed to initialize message queue engine", zap.Error(err))
 	}
🤖 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 `@cmd/ingestor.go` around lines 139 - 141, The current call uses fmt.Sprintf
with the %w verb which is invalid outside fmt.Errorf; change the error
formatting so the actual error is printed: in the block where
engine.InitMessageQueueEngine(config.TaskExecutor.MessageQueueType) is called,
replace fmt.Sprintf("Failed to initialize message queue engine: %w", err) with
either fmt.Errorf("Failed to initialize message queue engine: %w", err) if you
intend to wrap the error, or use fmt.Sprintf("Failed to initialize message queue
engine: %v", err) / err.Error() before passing to common.Fatal so common.Fatal
receives a properly formatted error string; update the call around
InitMessageQueueEngine and common.Fatal accordingly.
internal/engine/nats/nats.go-195-206 (1)

195-206: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Clarify the immutability field in the fallback condition

  • The conditional checks for "max waiting can not be updated", which refers to JetStream MaxWaiting immutability (not MaxAckPending, which is generally editable). Update the comment/rationale to reference MaxWaiting so the fallback behavior matches the actual error.
🤖 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/engine/nats/nats.go` around lines 195 - 206, Update the explanatory
comment in the error-handling branch that checks for
strings.Contains(err.Error(), "max waiting can not be updated") to correctly
reference JetStream's MaxWaiting immutability (not MaxAckPending); specifically,
edit the comment above that conditional in nats.go where n.consumer and
n.stream.Consumer are used so it states that MaxWaiting is immutable after
consumer creation and thus we fall back to fetching the existing consumer when
that error occurs.
🧹 Nitpick comments (9)
internal/service/document.go (1)

352-363: ⚡ Quick win

Unused userID parameter and early return on partial failure.

  1. The userID parameter is never used—consider removing it or adding authorization checks.
  2. Early return on error (line 358) loses any successfully stopped tasks from the response.
♻️ Suggested fix
-func (s *DocumentService) StopIngestionTasks(tasks []string, userID string) ([]*entity.IngestionTask, error) {
+func (s *DocumentService) StopIngestionTasks(tasks []string) ([]*entity.IngestionTask, error) {

 	var taskResponses []*entity.IngestionTask
 	for _, taskID := range tasks {
 		task, err := s.ingestionTaskDAO.SetStoppingByAPIServer(taskID)
 		if err != nil {
-			return nil, err
+			// Log error and continue, or collect errors
+			common.Warn(fmt.Sprintf("failed to stop task %s: %s", taskID, err.Error()))
+			continue
 		}
 		taskResponses = append(taskResponses, task)
 	}
 	return taskResponses, 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/document.go` around lines 352 - 363, The StopIngestionTasks
method currently declares an unused userID parameter and returns immediately on
the first SetStoppingByAPIServer error, dropping previously stopped tasks;
remove the unused userID parameter from DocumentService.StopIngestionTasks (or,
if authorization is required, explicitly perform checks using userID before
looping) and change the loop to continue on error: for each taskID call
ingestionTaskDAO.SetStoppingByAPIServer, append successful tasks to
taskResponses, collect errors (e.g. aggregate or capture last/error list)
instead of returning immediately, and after the loop return the taskResponses
along with a combined error (or nil if none) so partial successes are preserved.
internal/router/router.go (1)

226-230: 💤 Low value

Route structure is inconsistent—/ingestion/tasks under datasets group creates awkward paths.

These routes are registered under the datasets group (line 200), producing paths like /api/v1/datasets/ingestion/tasks. This is inconsistent with RESTful conventions since:

  1. GET /api/v1/datasets/ingestion/tasks lists tasks across all datasets (not scoped to a dataset)
  2. The parse endpoint at POST /:dataset_id/documents/parse is dataset-scoped

Consider either:

  • Moving task management routes to a top-level /api/v1/ingestion/tasks group, or
  • Scoping them under /:dataset_id/ingestion/tasks if they should be dataset-specific
🤖 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/router/router.go` around lines 226 - 230, The ingestion task routes
are registered under the datasets group which yields awkward paths (e.g.
/api/v1/datasets/ingestion/tasks) and mismatches their scope; update the router
so the handlers r.documentHandler.ListIngestionTasks, StopIngestionTasks and
RemoveIngestionTasks are either moved out into a top-level ingestion group (e.g.
/api/v1/ingestion/tasks) for cross-dataset operations or re-scoped to be
dataset-specific by registering them under a dataset parameter path (e.g.
/:dataset_id/ingestion/tasks) to match StartIngestionTask’s dataset-scoped POST;
pick one consistent approach and update the route registrations accordingly.
internal/dao/ingestion.go (1)

32-41: 💤 Low value

Doc comment uses canceling/canceled, but the implemented statuses are STOPPING/STOPPED.

The lifecycle comment references canceling/canceled states that don't exist in the constant set (CREATED, RUNNING, COMPLETED, FAILED, STOPPED, STOPPING). Align the terminology to avoid confusion.

🤖 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 32 - 41, The doc comment in
ingestion.go refers to non-existent states "canceling"/"canceled"; update the
lifecycle description to use the actual status constants (CREATED, RUNNING,
COMPLETED, FAILED, STOPPING, STOPPED) and describe transitions using
STOPPING/STOPPED instead of canceling/canceled (e.g., "created → stopping",
"running → stopping", "stopping → stopped", "completed → stopping" if
applicable), ensuring the textual transitions match the implemented constants
(CREATED, RUNNING, COMPLETED, FAILED, STOPPING, STOPPED).
internal/cli/user_command.go (1)

3349-3352: ⚡ Quick win

Unusual type assertion pattern for optional parameter.

Using *string type assertion is unconventional. If dataset_id is optional, a simpler pattern would be to check if the key exists and handle the string type directly.

Proposed fix
-	datasetID, ok := cmd.Params["dataset_id"].(*string)
-	if !ok {
-		datasetID = nil
-	}
+	var datasetID *string
+	if id, ok := cmd.Params["dataset_id"].(string); ok && id != "" {
+		datasetID = &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/cli/user_command.go` around lines 3349 - 3352, The current pattern
does a type assertion to *string for cmd.Params["dataset_id"] which is
unconventional for an optional parameter; instead check presence and assert to
string (or to interface then handle nil) and set datasetID to nil or a pointer
accordingly: retrieve v, ok := cmd.Params["dataset_id"]; if !ok || v == nil then
datasetID = nil; else s, ok := v.(string); if ok { datasetID = &s } else handle
unexpected type. Update the code that uses datasetID to expect *string and use
this clearer presence-and-string assertion pattern with the datasetID variable
and cmd.Params map.
internal/cli/admin_command.go (1)

1360-1362: 💤 Low value

Inconsistent error messages for JSON unmarshal failures.

The unmarshal error messages also reference "ingest file" which doesn't match the operation.

Also applies to: 1395-1397

🤖 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/cli/admin_command.go` around lines 1360 - 1362, The json.Unmarshal
error handling in the CommonResponse parsing (unmarshalling resp.Body into
CommonResponse) uses the message "ingest file failed: invalid JSON", which is
incorrect for this operation; update both occurrences (the json.Unmarshal calls
that check err in this file) to return a clear, operation-agnostic message like
"invalid JSON response" or "failed to parse JSON response" and keep wrapping the
original error with %w so the underlying error is preserved (reference symbols:
CommonResponse, json.Unmarshal, resp.Body).
internal/cli/user_parser.go (1)

3944-3944: ⚡ Quick win

Consider parsing multiple quoted task IDs instead of space-splitting a single string.

Using strings.Split(taskStr, " ") to extract task IDs from a single quoted string is fragile if task IDs could contain spaces or need escaping. A more robust approach would be to parse multiple consecutive quoted strings (one per task) instead of relying on space delimitation within a single string.

Current: STOP INGESTION TASKS "task1 task2 task3"
Suggested: STOP INGESTION TASKS "task1" "task2" "task3"

This same pattern appears in parseUserRemoveTask at line 3997.

🤖 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/cli/user_parser.go` at line 3944, The current code uses
strings.Split(taskStr, " ") to split task IDs which breaks when IDs contain
spaces; update the parsing to extract multiple quoted strings instead of
splitting on spaces. In internal/cli/user_parser.go, replace the strings.Split
usage around the tasks := strings.Split(taskStr, " ") with logic that iterates
over taskStr and collects each quoted token (e.g., scanning for successive
quoted substrings and unquoting them), and apply the same change in
parseUserRemoveTask where the same pattern appears; ensure the parser returns a
slice of task IDs (handling escaped quotes) rather than a single space-split
string.
internal/admin/handler.go (1)

1433-1434: ⚡ Quick win

Recommend extracting the ingestor liveness timeout as a constant.

The 30-second threshold at line 1433 is hardcoded. Extracting it to a named constant (e.g., IngestorLivenessTimeout) improves maintainability and makes the threshold easier to tune or document.

♻️ Proposed refactor

At the package level:

+const IngestorLivenessTimeout = 30 * time.Second
+
 // Handler admin handler
 type Handler struct {

Then update the check:

-			if now.Sub(ingestorServer.Timestamp) < 30*time.Second {
+			if now.Sub(ingestorServer.Timestamp) < IngestorLivenessTimeout {
 				ingestorResult["status"] = "alive"
 			} else {
🤖 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 1433 - 1434, Extract the hardcoded
30-second threshold into a package-level constant (e.g.,
IngestorLivenessTimeout) and replace the literal in the liveness check that uses
ingestorServer.Timestamp so the if now.Sub(ingestorServer.Timestamp) <
30*time.Second becomes if now.Sub(ingestorServer.Timestamp) <
IngestorLivenessTimeout; define the constant with type time.Duration near other
package-level constants and update any related comments/tests that rely on this
timeout.
cmd/admin_server.go (1)

97-99: 💤 Low value

Non-fatal message queue initialization may cause runtime failures.

If InitMessageQueueEngine fails, the admin server still starts but queue management endpoints (list/publish/pull/show from internal/admin/handler.go) will fail at runtime when accessing the nil messageQueueEngine. Consider making this fatal or adding nil checks in handlers.

🤖 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 `@cmd/admin_server.go` around lines 97 - 99, The message queue engine init
failure is currently non-fatal which leaves messageQueueEngine nil and will
cause runtime panics in the admin handlers (list/publish/pull/show in
internal/admin/handler.go); change the startup behavior so
InitMessageQueueEngine failures are fatal: when
engine.InitMessageQueueEngine(cfg.TaskExecutor.MessageQueueType) returns an
error, log the error with context and stop startup (e.g., return the error from
the server bootstrap or call os.Exit/ common.Fatal) so the server does not start
with a nil messageQueueEngine, or alternatively add explicit nil checks in each
handler (the methods that reference messageQueueEngine) and return appropriate
HTTP errors—prefer making init fatal and propagate the error from the admin
server start path.
internal/engine/nats/nats.go (1)

74-79: ⚡ Quick win

Use errors.Is with the typed JetStream “stream already exists” error.

In internal/engine/nats/nats.go (lines 74-79), avoid err.Error() string comparison; instead check errors.Is(err, nats.ErrStreamNameAlreadyInUse) (from github.com/nats-io/nats.go) and close/return only when it’s a different error.

🤖 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/engine/nats/nats.go` around lines 74 - 79, Replace the string
comparison on the CreateStream error with an errors.Is check against the typed
JetStream sentinel error; specifically, after calling
n.jetStream.CreateStream(ctx, streamCfg) in the nats.go logic, use
errors.Is(err, nats.ErrStreamNameAlreadyInUse) to detect the “stream already
exists” case and only call n.nc.Close()/return fmt.Errorf(...) for other errors,
ensuring you import the standard errors package and reference
github.com/nats-io/nats.go's nats.ErrStreamNameAlreadyInUse.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 219db590-4a96-44bd-9a67-349238c34eb0

📥 Commits

Reviewing files that changed from the base of the PR and between 9799f33 and fea10f1.

⛔ Files ignored due to path filters (3)
  • go.sum is excluded by !**/*.sum
  • internal/common/ingestion.pb.go is excluded by !**/*.pb.go
  • internal/common/ingestion_grpc.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (42)
  • cmd/admin_server.go
  • cmd/ingestor.go
  • cmd/server_main.go
  • conf/service_conf.yaml
  • docker/.env
  • docker/docker-compose-base.yml
  • docker/service_conf.yaml.template
  • go.mod
  • internal/admin/handler.go
  • internal/admin/ingestion_manager.go
  • internal/admin/router.go
  • internal/admin/service.go
  • internal/admin/state.go
  • internal/cli/admin_command.go
  • internal/cli/admin_parser.go
  • internal/cli/client.go
  • internal/cli/common_command.go
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/common/constants.go
  • internal/common/error_code.go
  • internal/common/number.go
  • internal/common/status_message.go
  • internal/common/task.go
  • internal/dao/database.go
  • internal/dao/ingestion.go
  • internal/engine/engine.go
  • internal/engine/global.go
  • internal/engine/nats/nats.go
  • internal/entity/base.go
  • internal/entity/ingestion_task.go
  • internal/handler/document.go
  • internal/ingestion/ingestion_service.go
  • internal/proto/ingestion.proto
  • internal/router/router.go
  • internal/server/config.go
  • internal/service/admin_client.go
  • internal/service/document.go
  • internal/storage/types.go
💤 Files with no reviewable changes (3)
  • internal/admin/ingestion_manager.go
  • internal/proto/ingestion.proto
  • internal/storage/types.go

Comment thread docker/docker-compose-base.yml Resolved
Comment thread internal/admin/handler.go Resolved
Comment thread internal/admin/handler.go Resolved
Comment thread internal/admin/handler.go
Comment on lines +1317 to +1321
err := msgQueueEngine.InitConsumer("tasks.RAGFLOW")
if err != nil {
errorResponse(c, err.Error(), 400)
}
messages, err := msgQueueEngine.GetMessages(req.MessageCount)

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 | 🔴 Critical | ⚡ Quick win

Critical: Missing return after InitConsumer error and unchecked GetMessages error.

Line 1319 calls errorResponse when InitConsumer fails but does not return, so line 1321 proceeds to call GetMessages. Additionally, line 1321 assigns err from GetMessages but never checks it before using messages. If GetMessages fails, messages may be nil or incomplete, leading to a panic or incorrect behavior.

🐛 Proposed fix to add return and error check
 	msgQueueEngine := engine.GetMessageQueueEngine()
 	err := msgQueueEngine.InitConsumer("tasks.RAGFLOW")
 	if err != nil {
 		errorResponse(c, err.Error(), 400)
+		return
 	}
 	messages, err := msgQueueEngine.GetMessages(req.MessageCount)
+	if err != nil {
+		errorResponse(c, err.Error(), 500)
+		return
+	}
 	var result []map[string]string
📝 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
err := msgQueueEngine.InitConsumer("tasks.RAGFLOW")
if err != nil {
errorResponse(c, err.Error(), 400)
}
messages, err := msgQueueEngine.GetMessages(req.MessageCount)
err := msgQueueEngine.InitConsumer("tasks.RAGFLOW")
if err != nil {
errorResponse(c, err.Error(), 400)
return
}
messages, err := msgQueueEngine.GetMessages(req.MessageCount)
if err != nil {
errorResponse(c, err.Error(), 500)
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 1317 - 1321, The InitConsumer call's
error branch must stop execution: after calling errorResponse(c, err.Error(),
400) when msgQueueEngine.InitConsumer("tasks.RAGFLOW") fails, immediately return
to avoid continuing; also check the error returned from
msgQueueEngine.GetMessages(req.MessageCount) (the err assigned on the same line
as messages) and handle it (call errorResponse and return) before using messages
to prevent nil/invalid values from causing panics—update the block around
msgQueueEngine.InitConsumer, errorResponse, msgQueueEngine.GetMessages, and the
messages variable to perform these two early-returns on error.

Comment thread internal/admin/handler.go
Comment on lines +1338 to +1352
} else {
for _, message := range messages {
taskMessage := message.GetMessage()
resultMessage := map[string]string{
"id": taskMessage.TaskID,
"type": taskMessage.TaskType,
}
if err == nil {
resultMessage["nack"] = "true"
} else {
resultMessage["nack"] = "false"
}
result = append(result, resultMessage)
}
}

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 | 🔴 Critical | ⚡ Quick win

Critical: NACK branch checks wrong error variable.

The NACK branch (lines 1339-1352) checks if err == nil at line 1345, but err was last assigned in the ACK branch at line 1330 (err = message.Ack()). In the NACK flow, no operation sets err, so this condition is checking stale state from a different loop iteration or branch. This logic is incorrect.

🐛 Proposed fix to remove incorrect check

If NACK is a no-op (message is not acknowledged), simply omit the check:

 	} else {
 		for _, message := range messages {
 			taskMessage := message.GetMessage()
 			resultMessage := map[string]string{
 				"id":   taskMessage.TaskID,
 				"type": taskMessage.TaskType,
+				"nack": "true",
 			}
-			if err == nil {
-				resultMessage["nack"] = "true"
-			} else {
-				resultMessage["nack"] = "false"
-			}
 			result = append(result, resultMessage)
 		}
 	}

Alternatively, if NACK requires an explicit operation (e.g., message.Nack() or message.Term()), call it and check its error.

📝 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
} else {
for _, message := range messages {
taskMessage := message.GetMessage()
resultMessage := map[string]string{
"id": taskMessage.TaskID,
"type": taskMessage.TaskType,
}
if err == nil {
resultMessage["nack"] = "true"
} else {
resultMessage["nack"] = "false"
}
result = append(result, resultMessage)
}
}
} else {
for _, message := range messages {
taskMessage := message.GetMessage()
resultMessage := map[string]string{
"id": taskMessage.TaskID,
"type": taskMessage.TaskType,
"nack": "true",
}
result = append(result, resultMessage)
}
}
🤖 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 1338 - 1352, The loop over messages
incorrectly checks the stale variable err (last set by message.Ack()) when
building the NACK result; update the NACK branch in the messages loop to either
call the explicit nack operation (e.g., message.Nack() or message.Term()) and
use that call's returned error to set resultMessage["nack"] = "true"/"false", or
if NACK is a no-op simply remove the err check and set resultMessage["nack"] to
the appropriate constant (e.g., "true" to indicate it was not acked); ensure you
reference the loop variable message, the Task message via taskMessage :=
message.GetMessage(), and the existing message.Ack() usage when determining
which path to implement.

Comment on lines +49 to +54
func (n *NatsEngine) Init() error {
var err error
n.nc, err = nats.Connect(nats.DefaultURL)
if err != nil {
return fmt.Errorf("failed to connect to NATS: %w", err)
}

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 | 🔴 Critical | ⚡ Quick win

Configured host and port are ignored; always connects to nats.DefaultURL.

NewNatsEngine receives host and port parameters but Init() ignores them and connects to nats.DefaultURL (typically nats://127.0.0.1:4222). This breaks configuration from service_conf.yaml.

🐛 Proposed fix to use configured host/port
 func (n *NatsEngine) Init() error {
 	var err error
-	n.nc, err = nats.Connect(nats.DefaultURL)
+	url := fmt.Sprintf("nats://%s:%d", n.host, n.port)
+	n.nc, err = nats.Connect(url)
 	if err != nil {
-		return fmt.Errorf("failed to connect to NATS: %w", err)
+		return fmt.Errorf("failed to connect to NATS at %s: %w", url, err)
 	}
🤖 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/engine/nats/nats.go` around lines 49 - 54, Init() currently always
calls nats.Connect(nats.DefaultURL) ignoring the configured host/port passed
into NewNatsEngine; update Init() to construct the connect URL from the
NatsEngine instance fields (e.g., use n.host and n.port) and call nats.Connect
with that URL, falling back to nats.DefaultURL only if host/port are empty or
invalid; ensure you update the NatsEngine struct usage (and the place where n.nc
is set) so the connection uses the configured values rather than
nats.DefaultURL.

Comment on lines +142 to +158
if task == nil {
common.Info(fmt.Sprintf("task %s is already stopped", taskMessage.TaskID))
}

switch msg.MessageType {
case "TASK_ASSIGNMENT":
e.handleTaskAssignment(msg.TaskAssignment)
switch task.Status {
case common.COMPLETED, common.STOPPED, common.FAILED:
common.Info(fmt.Sprintf("task %s is already %s", taskMessage.TaskID, task.Status))
err = taskHandle.Ack()
if err != nil {
common.Error(fmt.Sprintf("error nack task %s", taskMessage.TaskID), err)
return err
}
continue
case common.STOPPING, common.CREATED:
err = fmt.Errorf("task %s is in unexpected status %s", taskMessage.TaskID, task.Status)
return err
case common.RUNNING:

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 | 🔴 Critical | ⚡ Quick win

Nil pointer dereference on task.Status when task is nil.

Line 142-144 checks if task == nil and logs a message, but execution continues to line 146 which accesses task.Status, causing a panic.

🐛 Proposed fix to skip processing when task is nil
 			if task == nil {
 				common.Info(fmt.Sprintf("task %s is already stopped", taskMessage.TaskID))
+				err = taskHandle.Ack()
+				if err != nil {
+					common.Error(fmt.Sprintf("error ack task %s", taskMessage.TaskID), err)
+					return err
+				}
+				continue
 			}
-
-			switch task.Status {
🤖 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/ingestion_service.go` around lines 142 - 158, The nil
check for task logs "task %s is already stopped" but then falls through to the
switch that reads task.Status causing a panic; fix by returning early or
skipping processing when task == nil — after the log call for task == nil,
invoke taskHandle.Ack() (handle its error like the existing ack error handling)
and continue to the next message so the subsequent switch on task.Status is not
executed; ensure you reference the same symbols: task, taskMessage.TaskID,
taskHandle.Ack(), and the switch on task.Status.

Comment thread internal/ingestion/ingestion_service.go Resolved
Comment on lines +587 to +591
var checkpointMap map[string]interface{}
checkpointMap = latestLog.Checkpoint
currentStep := checkpointMap["current_step"].(int)
totalStep := checkpointMap["total_step"].(int)
for i := currentStep; i < totalStep; i++ {

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 | 🔴 Critical | ⚡ Quick win

Type assertion without ok check will panic on type mismatch.

checkpointMap["current_step"].(int) panics if the value is not an int. Unlike executeTask which uses common.GetInt, this code uses direct type assertion. JSON unmarshalling typically produces float64 for numbers, not int.

🐛 Proposed fix using safe type conversion
 	var checkpointMap map[string]interface{}
 	checkpointMap = latestLog.Checkpoint
-	currentStep := checkpointMap["current_step"].(int)
-	totalStep := checkpointMap["total_step"].(int)
+	currentStep, ok := common.GetInt(checkpointMap["current_step"])
+	if !ok {
+		common.Fatal(fmt.Sprintf("Failed to get current step from tasklet log for tasklet %s", tasklet.ID))
+		return
+	}
+	totalStep, ok := common.GetInt(checkpointMap["total_step"])
+	if !ok {
+		common.Fatal(fmt.Sprintf("Failed to get total step from tasklet log for tasklet %s", tasklet.ID))
+		return
+	}
📝 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
var checkpointMap map[string]interface{}
checkpointMap = latestLog.Checkpoint
currentStep := checkpointMap["current_step"].(int)
totalStep := checkpointMap["total_step"].(int)
for i := currentStep; i < totalStep; i++ {
var checkpointMap map[string]interface{}
checkpointMap = latestLog.Checkpoint
currentStep, ok := common.GetInt(checkpointMap["current_step"])
if !ok {
common.Fatal(fmt.Sprintf("Failed to get current step from tasklet log for tasklet %s", tasklet.ID))
return
}
totalStep, ok := common.GetInt(checkpointMap["total_step"])
if !ok {
common.Fatal(fmt.Sprintf("Failed to get total step from tasklet log for tasklet %s", tasklet.ID))
return
}
for i := currentStep; i < totalStep; i++ {
🤖 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/ingestion_service.go` around lines 587 - 591, The direct
type assertions for checkpointMap["current_step"] and
checkpointMap["total_step"] can panic; replace them with safe conversions (like
calling common.GetInt or performing the two-value type assertion and handling
float64->int) and handle missing/invalid values gracefully. Specifically, in the
block using latestLog.Checkpoint and variables currentStep/totalStep, obtain
ints using common.GetInt(checkpointMap, "current_step") and
common.GetInt(checkpointMap, "total_step") or do an ok-check (v, ok :=
checkpointMap["current_step"].(float64); if ok { currentStep = int(v) } else {
/* handle error/default */ }) and return or log an error if values are invalid,
mirroring the approach used in executeTask.

Comment thread internal/ingestion/ingestion_service.go Resolved

@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

Caution

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

⚠️ Outside diff range comments (5)
internal/cli/admin_parser.go (2)

400-409: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Normalize task IDs with strings.Fields() before sending them downstream.

strings.Split(taskString, " ") preserves empty entries, so extra spaces in STOP/REMOVE ... TASKS "a b" produce ["a", "", "b"]. That malformed payload can leak into the admin/user ingestion-task handlers. Apply the same fix anywhere this new quoted task-list format is parsed.

💡 Proposed fix
-	tasks := strings.Split(taskString, " ")
+	tasks := strings.Fields(taskString)
+	if len(tasks) == 0 {
+		return nil, fmt.Errorf("expected at least one task 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/cli/admin_parser.go` around lines 400 - 409, Replace
strings.Split(taskString, " ") with strings.Fields(taskString) when building the
tasks slice so extra spaces don't produce empty entries; specifically, in the
block after calling p.parseQuotedString() (where tasks := strings.Split(...) and
cmd := NewCommand("admin_stop_ingestion_tasks") and cmd.Params["tasks"] is set)
convert to using strings.Fields and assign that result to cmd.Params["tasks"].
Also search for other places that parse the new quoted task-list format and
apply the same replacement to normalize task IDs consistently.

1864-1883: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reject invalid MQ PULL arguments instead of silently pulling 1 message.

Any non-integer token after MQ PULL currently falls through the parseNumber() error path and becomes message_count = 1. Because this command is wired to the real pull endpoint, a typo can still dequeue/ack messages instead of failing fast.

🐛 Proposed fix
 	case TokenPull:
 		p.nextToken() // consume PULL

-		messageCount, err := p.parseNumber()
-		if err != nil {
-			messageCount = 1
-		} else {
-			p.nextToken() // consume NUMBER
-		}
+		messageCount := 1
+		switch p.curToken.Type {
+		case TokenInteger:
+			var err error
+			messageCount, err = p.parseNumber()
+			if err != nil {
+				return nil, err
+			}
+			p.nextToken() // consume NUMBER
+		case TokenNoACK, TokenSemicolon, TokenEOF:
+			// default to 1 only when the count is actually omitted
+		default:
+			return nil, fmt.Errorf("expected message count or NOACK after PULL")
+		}

 		if messageCount <= 0 || messageCount > 100 {
 			return nil, fmt.Errorf("message count cannot be less than 0 or greater than 100")
 		}
🤖 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/cli/admin_parser.go` around lines 1864 - 1883, The code currently
treats a parseNumber() error as messageCount = 1 which lets typos silently
dequeue messages; update the MQ PULL parsing in the function containing
parseNumber, messageCount and NewCommand("user_pull_message_command") so that if
parseNumber() returns an error you return a parse error (e.g.,
fmt.Errorf("invalid message count: %v", p.curToken.Literal) or include the parse
error) instead of defaulting to 1, and only call p.nextToken() to consume the
NUMBER when parseNumber() succeeds; retain the existing bounds check
(messageCount <= 0 || messageCount > 100) and the ack policy handling using
p.curToken/TokenNoACK and p.nextToken().
internal/cli/user_command.go (3)

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

Fix typo in error message.

The error message contains a double colon (::) which should be a single colon.

📝 Proposed fix
-		return nil, fmt.Errorf("failed to list ingestion tasks:: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
+		return nil, fmt.Errorf("failed to list ingestion tasks: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
🤖 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/cli/user_command.go` at line 3300, The error string in the return
statement that constructs the fmt.Errorf contains a double colon ("::"); update
the message to use a single colon so the call returns fmt.Errorf("failed to list
ingestion tasks: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)). Locate
the return statement that builds the error (the fmt.Errorf call that mentions
"failed to list ingestion tasks:: HTTP") and replace the double colon with a
single colon.

3373-3376: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix misleading error message.

The error message states "uri not provided" but the parameter being checked is "tasks". This mismatch would confuse users troubleshooting failed commands.

🛠️ Proposed fix
 	tasks, ok := cmd.Params["tasks"].([]string)
 	if !ok {
-		return nil, fmt.Errorf("uri not provided")
+		return nil, fmt.Errorf("tasks not provided")
 	}
🤖 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/cli/user_command.go` around lines 3373 - 3376, The error message is
misleading: the code checks cmd.Params["tasks"] but returns "uri not provided";
update the error to reflect the actual missing parameter. In the block that
reads tasks, change the fmt.Errorf call to return an error like
fmt.Errorf("tasks not provided or invalid") (or include the param name
dynamically) so the check around cmd.Params["tasks"]/variable tasks and its
error path accurately report the missing/invalid "tasks" parameter.

3285-3294: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

GET request should use query parameters in URL, not request body.

HTTP GET requests typically do not include request bodies. The dataset_id parameter should be appended as a query parameter in the URL string rather than passed in a payload map. This approach is inconsistent with the codebase pattern (e.g., line 503 uses ?dataset_ids=... in the URL) and may cause the parameter to be ignored.

Additionally, when dataset_id is nil, serializing map[string]interface{}{"dataset_id": nil} may produce unexpected JSON or be rejected by the server.

🔧 Recommended fix
-	datasetID, ok := cmd.Params["dataset_id"].(*string)
-	if !ok {
-		datasetID = nil
-	}
-
-	payload := map[string]interface{}{
-		"dataset_id": datasetID,
-	}
-
-	resp, err := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request("GET", "/datasets/ingestion/tasks", "web", nil, payload)
+	url := "/datasets/ingestion/tasks"
+	if datasetID, ok := cmd.Params["dataset_id"].(*string); ok && datasetID != nil {
+		url = fmt.Sprintf("/datasets/ingestion/tasks?dataset_id=%s", *datasetID)
+	}
+
+	resp, err := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request("GET", url, "web", nil, 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/cli/user_command.go` around lines 3285 - 3294, The GET handler
currently sends datasetID inside the request body (payload) which is wrong;
update the code to build the URL query string instead of the payload: read
datasetID from cmd.Params as you already do, and if datasetID != nil append
"?dataset_id=<value>" (URL-encode value) to the path passed into
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request (the
call currently using "/datasets/ingestion/tasks"), remove dataset_id from the
payload map and pass nil for the body argument to Request so no body is sent
when performing the GET.
🧹 Nitpick comments (1)
internal/cli/user_command.go (1)

3335-3340: ⚡ Quick win

Remove redundant dataset_id from payload.

The dataset_id is already part of the URL path (/datasets/{dataset_id}/documents/parse). Including it again in the request payload is redundant. The server handler extracts the dataset ID from the route parameter, not from the payload body.

♻️ Proposed refactor
 	payload := map[string]interface{}{
 		"documents":  []string{documentID},
-		"dataset_id": datasetID,
 	}
 
 	url := fmt.Sprintf("/datasets/%s/documents/parse", datasetID)
🤖 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/cli/user_command.go` around lines 3335 - 3340, Remove the redundant
"dataset_id" field from the request payload construction in
internal/cli/user_command.go: when building payload (variable payload) for the
parse endpoint, only include "documents": []string{documentID} and omit
"dataset_id" since datasetID is already passed in the URL (url :=
fmt.Sprintf("/datasets/%s/documents/parse", datasetID)); update any related code
that references the removed key accordingly.
🤖 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 `@go.mod`:
- Line 24: go.mod currently pins the dependency "github.com/nats-io/nats.go" at
v1.31.0; update that module string to the latest stable (e.g., v1.52.0) by
running "go get github.com/nats-io/[email protected]" and then "go mod tidy", run
the test suite and build to surface any breaking changes, and review the NATS
changelog/security advisories for any required code adjustments (API changes)
after upgrading.

In `@internal/cli/user_command.go`:
- Around line 3443-3471: ChunkCommand currently parses inputs but performs no
chunking and returns a successful SimpleResponse; update ChunkCommand (in type
CLI) to avoid falsely reporting success by either (A) returning a clear
"chunking not implemented" error when invoked (e.g., fmt.Errorf("chunking not
implemented")) or (B) gating the behavior behind a feature flag/TODO check that
returns an explicit error if the flag is off; make sure to reference and modify
the function ChunkCommand and any call-sites or dispatcher mapping for
user_chunk_command so users do not receive a fake success until the real
chunking/persistence implementation is added.
- Around line 3217-3256: UserParseLocalFile currently only prints a success
message and returns Code=0 without actually parsing/ingesting the file and it
reads the wrong embedding param key; update the function UserParseLocalFile to
(1) use the correct embedding parameter key by reading cmd.Params["embed_model"]
(or normalize both "embed_model" and "embedding_model" into a single variable)
instead of "embedding_model", (2) implement the real parse/ingest logic for the
named file (call your existing parser/ingester helper or add file-open,
validate, and ingest steps) and capture any errors, and (3) set
SimpleResponse.Code and Message based on the actual result and return a non-nil
error on failure so callers can handle it; reference symbols:
UserParseLocalFile, cmd.Params, "embed_model"/"embedding_model", and
SimpleResponse.

---

Outside diff comments:
In `@internal/cli/admin_parser.go`:
- Around line 400-409: Replace strings.Split(taskString, " ") with
strings.Fields(taskString) when building the tasks slice so extra spaces don't
produce empty entries; specifically, in the block after calling
p.parseQuotedString() (where tasks := strings.Split(...) and cmd :=
NewCommand("admin_stop_ingestion_tasks") and cmd.Params["tasks"] is set) convert
to using strings.Fields and assign that result to cmd.Params["tasks"]. Also
search for other places that parse the new quoted task-list format and apply the
same replacement to normalize task IDs consistently.
- Around line 1864-1883: The code currently treats a parseNumber() error as
messageCount = 1 which lets typos silently dequeue messages; update the MQ PULL
parsing in the function containing parseNumber, messageCount and
NewCommand("user_pull_message_command") so that if parseNumber() returns an
error you return a parse error (e.g., fmt.Errorf("invalid message count: %v",
p.curToken.Literal) or include the parse error) instead of defaulting to 1, and
only call p.nextToken() to consume the NUMBER when parseNumber() succeeds;
retain the existing bounds check (messageCount <= 0 || messageCount > 100) and
the ack policy handling using p.curToken/TokenNoACK and p.nextToken().

In `@internal/cli/user_command.go`:
- Line 3300: The error string in the return statement that constructs the
fmt.Errorf contains a double colon ("::"); update the message to use a single
colon so the call returns fmt.Errorf("failed to list ingestion tasks: HTTP %d,
body: %s", resp.StatusCode, string(resp.Body)). Locate the return statement that
builds the error (the fmt.Errorf call that mentions "failed to list ingestion
tasks:: HTTP") and replace the double colon with a single colon.
- Around line 3373-3376: The error message is misleading: the code checks
cmd.Params["tasks"] but returns "uri not provided"; update the error to reflect
the actual missing parameter. In the block that reads tasks, change the
fmt.Errorf call to return an error like fmt.Errorf("tasks not provided or
invalid") (or include the param name dynamically) so the check around
cmd.Params["tasks"]/variable tasks and its error path accurately report the
missing/invalid "tasks" parameter.
- Around line 3285-3294: The GET handler currently sends datasetID inside the
request body (payload) which is wrong; update the code to build the URL query
string instead of the payload: read datasetID from cmd.Params as you already do,
and if datasetID != nil append "?dataset_id=<value>" (URL-encode value) to the
path passed into
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request (the
call currently using "/datasets/ingestion/tasks"), remove dataset_id from the
payload map and pass nil for the body argument to Request so no body is sent
when performing the GET.

---

Nitpick comments:
In `@internal/cli/user_command.go`:
- Around line 3335-3340: Remove the redundant "dataset_id" field from the
request payload construction in internal/cli/user_command.go: when building
payload (variable payload) for the parse endpoint, only include "documents":
[]string{documentID} and omit "dataset_id" since datasetID is already passed in
the URL (url := fmt.Sprintf("/datasets/%s/documents/parse", datasetID)); update
any related code that references the removed key accordingly.
🪄 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: 3477afd1-b843-45a9-9fd3-85b948822d37

📥 Commits

Reviewing files that changed from the base of the PR and between fea10f1 and fab2987.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (22)
  • .gitignore
  • cmd/admin_server.go
  • cmd/ingestor.go
  • cmd/server_main.go
  • conf/service_conf.yaml
  • docker/.env
  • docker/docker-compose-base.yml
  • docker/service_conf.yaml.template
  • go.mod
  • internal/admin/router.go
  • internal/cli/admin_command.go
  • internal/cli/admin_parser.go
  • internal/cli/cli_http.go
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/common/constants.go
  • internal/common/number.go
  • internal/dao/database.go
  • internal/engine/engine.go
💤 Files with no reviewable changes (2)
  • internal/dao/database.go
  • internal/engine/engine.go
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🚧 Files skipped from review as they are similar to previous changes (13)
  • conf/service_conf.yaml
  • docker/docker-compose-base.yml
  • internal/cli/lexer.go
  • internal/cli/types.go
  • internal/common/number.go
  • docker/.env
  • internal/admin/router.go
  • docker/service_conf.yaml.template
  • internal/common/constants.go
  • cmd/server_main.go
  • cmd/admin_server.go
  • cmd/ingestor.go
  • internal/cli/admin_command.go

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

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 3

Caution

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

⚠️ Outside diff range comments (5)
internal/cli/admin_parser.go (2)

400-409: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Normalize task IDs with strings.Fields() before sending them downstream.

strings.Split(taskString, " ") preserves empty entries, so extra spaces in STOP/REMOVE ... TASKS "a b" produce ["a", "", "b"]. That malformed payload can leak into the admin/user ingestion-task handlers. Apply the same fix anywhere this new quoted task-list format is parsed.

💡 Proposed fix
-	tasks := strings.Split(taskString, " ")
+	tasks := strings.Fields(taskString)
+	if len(tasks) == 0 {
+		return nil, fmt.Errorf("expected at least one task 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/cli/admin_parser.go` around lines 400 - 409, Replace
strings.Split(taskString, " ") with strings.Fields(taskString) when building the
tasks slice so extra spaces don't produce empty entries; specifically, in the
block after calling p.parseQuotedString() (where tasks := strings.Split(...) and
cmd := NewCommand("admin_stop_ingestion_tasks") and cmd.Params["tasks"] is set)
convert to using strings.Fields and assign that result to cmd.Params["tasks"].
Also search for other places that parse the new quoted task-list format and
apply the same replacement to normalize task IDs consistently.

1864-1883: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reject invalid MQ PULL arguments instead of silently pulling 1 message.

Any non-integer token after MQ PULL currently falls through the parseNumber() error path and becomes message_count = 1. Because this command is wired to the real pull endpoint, a typo can still dequeue/ack messages instead of failing fast.

🐛 Proposed fix
 	case TokenPull:
 		p.nextToken() // consume PULL

-		messageCount, err := p.parseNumber()
-		if err != nil {
-			messageCount = 1
-		} else {
-			p.nextToken() // consume NUMBER
-		}
+		messageCount := 1
+		switch p.curToken.Type {
+		case TokenInteger:
+			var err error
+			messageCount, err = p.parseNumber()
+			if err != nil {
+				return nil, err
+			}
+			p.nextToken() // consume NUMBER
+		case TokenNoACK, TokenSemicolon, TokenEOF:
+			// default to 1 only when the count is actually omitted
+		default:
+			return nil, fmt.Errorf("expected message count or NOACK after PULL")
+		}

 		if messageCount <= 0 || messageCount > 100 {
 			return nil, fmt.Errorf("message count cannot be less than 0 or greater than 100")
 		}
🤖 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/cli/admin_parser.go` around lines 1864 - 1883, The code currently
treats a parseNumber() error as messageCount = 1 which lets typos silently
dequeue messages; update the MQ PULL parsing in the function containing
parseNumber, messageCount and NewCommand("user_pull_message_command") so that if
parseNumber() returns an error you return a parse error (e.g.,
fmt.Errorf("invalid message count: %v", p.curToken.Literal) or include the parse
error) instead of defaulting to 1, and only call p.nextToken() to consume the
NUMBER when parseNumber() succeeds; retain the existing bounds check
(messageCount <= 0 || messageCount > 100) and the ack policy handling using
p.curToken/TokenNoACK and p.nextToken().
internal/cli/user_command.go (3)

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

Fix typo in error message.

The error message contains a double colon (::) which should be a single colon.

📝 Proposed fix
-		return nil, fmt.Errorf("failed to list ingestion tasks:: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
+		return nil, fmt.Errorf("failed to list ingestion tasks: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
🤖 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/cli/user_command.go` at line 3300, The error string in the return
statement that constructs the fmt.Errorf contains a double colon ("::"); update
the message to use a single colon so the call returns fmt.Errorf("failed to list
ingestion tasks: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)). Locate
the return statement that builds the error (the fmt.Errorf call that mentions
"failed to list ingestion tasks:: HTTP") and replace the double colon with a
single colon.

3373-3376: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix misleading error message.

The error message states "uri not provided" but the parameter being checked is "tasks". This mismatch would confuse users troubleshooting failed commands.

🛠️ Proposed fix
 	tasks, ok := cmd.Params["tasks"].([]string)
 	if !ok {
-		return nil, fmt.Errorf("uri not provided")
+		return nil, fmt.Errorf("tasks not provided")
 	}
🤖 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/cli/user_command.go` around lines 3373 - 3376, The error message is
misleading: the code checks cmd.Params["tasks"] but returns "uri not provided";
update the error to reflect the actual missing parameter. In the block that
reads tasks, change the fmt.Errorf call to return an error like
fmt.Errorf("tasks not provided or invalid") (or include the param name
dynamically) so the check around cmd.Params["tasks"]/variable tasks and its
error path accurately report the missing/invalid "tasks" parameter.

3285-3294: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

GET request should use query parameters in URL, not request body.

HTTP GET requests typically do not include request bodies. The dataset_id parameter should be appended as a query parameter in the URL string rather than passed in a payload map. This approach is inconsistent with the codebase pattern (e.g., line 503 uses ?dataset_ids=... in the URL) and may cause the parameter to be ignored.

Additionally, when dataset_id is nil, serializing map[string]interface{}{"dataset_id": nil} may produce unexpected JSON or be rejected by the server.

🔧 Recommended fix
-	datasetID, ok := cmd.Params["dataset_id"].(*string)
-	if !ok {
-		datasetID = nil
-	}
-
-	payload := map[string]interface{}{
-		"dataset_id": datasetID,
-	}
-
-	resp, err := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request("GET", "/datasets/ingestion/tasks", "web", nil, payload)
+	url := "/datasets/ingestion/tasks"
+	if datasetID, ok := cmd.Params["dataset_id"].(*string); ok && datasetID != nil {
+		url = fmt.Sprintf("/datasets/ingestion/tasks?dataset_id=%s", *datasetID)
+	}
+
+	resp, err := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request("GET", url, "web", nil, 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/cli/user_command.go` around lines 3285 - 3294, The GET handler
currently sends datasetID inside the request body (payload) which is wrong;
update the code to build the URL query string instead of the payload: read
datasetID from cmd.Params as you already do, and if datasetID != nil append
"?dataset_id=<value>" (URL-encode value) to the path passed into
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request (the
call currently using "/datasets/ingestion/tasks"), remove dataset_id from the
payload map and pass nil for the body argument to Request so no body is sent
when performing the GET.
🧹 Nitpick comments (1)
internal/cli/user_command.go (1)

3335-3340: ⚡ Quick win

Remove redundant dataset_id from payload.

The dataset_id is already part of the URL path (/datasets/{dataset_id}/documents/parse). Including it again in the request payload is redundant. The server handler extracts the dataset ID from the route parameter, not from the payload body.

♻️ Proposed refactor
 	payload := map[string]interface{}{
 		"documents":  []string{documentID},
-		"dataset_id": datasetID,
 	}
 
 	url := fmt.Sprintf("/datasets/%s/documents/parse", datasetID)
🤖 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/cli/user_command.go` around lines 3335 - 3340, Remove the redundant
"dataset_id" field from the request payload construction in
internal/cli/user_command.go: when building payload (variable payload) for the
parse endpoint, only include "documents": []string{documentID} and omit
"dataset_id" since datasetID is already passed in the URL (url :=
fmt.Sprintf("/datasets/%s/documents/parse", datasetID)); update any related code
that references the removed key accordingly.
🤖 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 `@go.mod`:
- Line 24: go.mod currently pins the dependency "github.com/nats-io/nats.go" at
v1.31.0; update that module string to the latest stable (e.g., v1.52.0) by
running "go get github.com/nats-io/[email protected]" and then "go mod tidy", run
the test suite and build to surface any breaking changes, and review the NATS
changelog/security advisories for any required code adjustments (API changes)
after upgrading.

In `@internal/cli/user_command.go`:
- Around line 3443-3471: ChunkCommand currently parses inputs but performs no
chunking and returns a successful SimpleResponse; update ChunkCommand (in type
CLI) to avoid falsely reporting success by either (A) returning a clear
"chunking not implemented" error when invoked (e.g., fmt.Errorf("chunking not
implemented")) or (B) gating the behavior behind a feature flag/TODO check that
returns an explicit error if the flag is off; make sure to reference and modify
the function ChunkCommand and any call-sites or dispatcher mapping for
user_chunk_command so users do not receive a fake success until the real
chunking/persistence implementation is added.
- Around line 3217-3256: UserParseLocalFile currently only prints a success
message and returns Code=0 without actually parsing/ingesting the file and it
reads the wrong embedding param key; update the function UserParseLocalFile to
(1) use the correct embedding parameter key by reading cmd.Params["embed_model"]
(or normalize both "embed_model" and "embedding_model" into a single variable)
instead of "embedding_model", (2) implement the real parse/ingest logic for the
named file (call your existing parser/ingester helper or add file-open,
validate, and ingest steps) and capture any errors, and (3) set
SimpleResponse.Code and Message based on the actual result and return a non-nil
error on failure so callers can handle it; reference symbols:
UserParseLocalFile, cmd.Params, "embed_model"/"embedding_model", and
SimpleResponse.

---

Outside diff comments:
In `@internal/cli/admin_parser.go`:
- Around line 400-409: Replace strings.Split(taskString, " ") with
strings.Fields(taskString) when building the tasks slice so extra spaces don't
produce empty entries; specifically, in the block after calling
p.parseQuotedString() (where tasks := strings.Split(...) and cmd :=
NewCommand("admin_stop_ingestion_tasks") and cmd.Params["tasks"] is set) convert
to using strings.Fields and assign that result to cmd.Params["tasks"]. Also
search for other places that parse the new quoted task-list format and apply the
same replacement to normalize task IDs consistently.
- Around line 1864-1883: The code currently treats a parseNumber() error as
messageCount = 1 which lets typos silently dequeue messages; update the MQ PULL
parsing in the function containing parseNumber, messageCount and
NewCommand("user_pull_message_command") so that if parseNumber() returns an
error you return a parse error (e.g., fmt.Errorf("invalid message count: %v",
p.curToken.Literal) or include the parse error) instead of defaulting to 1, and
only call p.nextToken() to consume the NUMBER when parseNumber() succeeds;
retain the existing bounds check (messageCount <= 0 || messageCount > 100) and
the ack policy handling using p.curToken/TokenNoACK and p.nextToken().

In `@internal/cli/user_command.go`:
- Line 3300: The error string in the return statement that constructs the
fmt.Errorf contains a double colon ("::"); update the message to use a single
colon so the call returns fmt.Errorf("failed to list ingestion tasks: HTTP %d,
body: %s", resp.StatusCode, string(resp.Body)). Locate the return statement that
builds the error (the fmt.Errorf call that mentions "failed to list ingestion
tasks:: HTTP") and replace the double colon with a single colon.
- Around line 3373-3376: The error message is misleading: the code checks
cmd.Params["tasks"] but returns "uri not provided"; update the error to reflect
the actual missing parameter. In the block that reads tasks, change the
fmt.Errorf call to return an error like fmt.Errorf("tasks not provided or
invalid") (or include the param name dynamically) so the check around
cmd.Params["tasks"]/variable tasks and its error path accurately report the
missing/invalid "tasks" parameter.
- Around line 3285-3294: The GET handler currently sends datasetID inside the
request body (payload) which is wrong; update the code to build the URL query
string instead of the payload: read datasetID from cmd.Params as you already do,
and if datasetID != nil append "?dataset_id=<value>" (URL-encode value) to the
path passed into
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer].Request (the
call currently using "/datasets/ingestion/tasks"), remove dataset_id from the
payload map and pass nil for the body argument to Request so no body is sent
when performing the GET.

---

Nitpick comments:
In `@internal/cli/user_command.go`:
- Around line 3335-3340: Remove the redundant "dataset_id" field from the
request payload construction in internal/cli/user_command.go: when building
payload (variable payload) for the parse endpoint, only include "documents":
[]string{documentID} and omit "dataset_id" since datasetID is already passed in
the URL (url := fmt.Sprintf("/datasets/%s/documents/parse", datasetID)); update
any related code that references the removed key accordingly.
🪄 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: 3477afd1-b843-45a9-9fd3-85b948822d37

📥 Commits

Reviewing files that changed from the base of the PR and between fea10f1 and fab2987.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (22)
  • .gitignore
  • cmd/admin_server.go
  • cmd/ingestor.go
  • cmd/server_main.go
  • conf/service_conf.yaml
  • docker/.env
  • docker/docker-compose-base.yml
  • docker/service_conf.yaml.template
  • go.mod
  • internal/admin/router.go
  • internal/cli/admin_command.go
  • internal/cli/admin_parser.go
  • internal/cli/cli_http.go
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/common/constants.go
  • internal/common/number.go
  • internal/dao/database.go
  • internal/engine/engine.go
💤 Files with no reviewable changes (2)
  • internal/dao/database.go
  • internal/engine/engine.go
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🚧 Files skipped from review as they are similar to previous changes (13)
  • conf/service_conf.yaml
  • docker/docker-compose-base.yml
  • internal/cli/lexer.go
  • internal/cli/types.go
  • internal/common/number.go
  • docker/.env
  • internal/admin/router.go
  • docker/service_conf.yaml.template
  • internal/common/constants.go
  • cmd/server_main.go
  • cmd/admin_server.go
  • cmd/ingestor.go
  • internal/cli/admin_command.go
🛑 Comments failed to post (3)
go.mod (1)

24-24: ⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Verify NATS library version and security status.

# Check for the latest NATS Go client version
echo "=== Checking latest NATS Go client version ==="
curl -s https://api.github.com/repos/nats-io/nats.go/releases/latest | jq -r '.tag_name'

# Check for security advisories
echo "=== Checking for security advisories ==="
gh api graphql -f query='
{
  securityVulnerabilities(first: 10, ecosystem: GO, package: "github.com/nats-io/nats.go") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'

Repository: infiniflow/ragflow

Length of output: 332


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Latest version from Go module proxy ==="
curl -sSf https://proxy.golang.org/github.com/nats-io/nats.go/@latest

echo
echo "=== Query OSV for package github.com/nats-io/[email protected] ==="
cat <<'JSON' > /tmp/osv-query.json
{
  "package": {
    "name": "github.com/nats-io/nats.go"
  },
  "version": "1.31.0"
}
JSON

curl -sSf https://api.osv.dev/v1/query -H 'Content-Type: application/json' --data `@/tmp/osv-query.json` | jq .

Repository: infiniflow/ragflow

Length of output: 368


🌐 Web query:

github.com/nats-io/nats.go v1.31.0 security advisory CVE

💡 Result:

The GitHub repository github.com/nats-io/nats.go is the Go client library for NATS, which is separate from the nats-server (the messaging server) [1][2]. Security advisories and CVEs for the NATS project are tracked and published on the official NATS Advisories website [3]. There are no CVEs specifically issued against the nats.go library version v1.31.0 itself [3][4]. Most security vulnerabilities associated with "NATS" and tracked by CVEs in 2026 pertain to the nats-server component (the server software), not the client library [3][4][5]. While nats.go is a client library and generally not the subject of these server-side CVEs, like many Go projects, it occasionally updates its dependencies to address security issues found in third-party packages (e.g., vulnerabilities in golang.org/x/crypto) [1]. You should ensure you are using the latest version of nats.go to benefit from dependency updates and security patches, but there is no specific CVE advisory for nats.go v1.31.0 [1][3].

Citations:


Update NATS dependency and sanity-check security

go.mod pins github.com/nats-io/nats.go to v1.31.0, but the current latest release is v1.52.0. No known OSV/GitHub/NATS advisory entries were found for nats.go v1.31.0, but consider upgrading to the latest stable to pick up dependency/security fixes.

🤖 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 `@go.mod` at line 24, go.mod currently pins the dependency
"github.com/nats-io/nats.go" at v1.31.0; update that module string to the latest
stable (e.g., v1.52.0) by running "go get github.com/nats-io/[email protected]"
and then "go mod tidy", run the test suite and build to surface any breaking
changes, and review the NATS changelog/security advisories for any required code
adjustments (API changes) after upgrading.
internal/cli/user_command.go (2)

3217-3256: ⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for other placeholder or stub implementations in the CLI command files
rg -n -C2 'placeholder|stub|TODO.*implement|not implemented' --type=go internal/cli/

Repository: infiniflow/ragflow

Length of output: 1182


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== user_command.go (3210-3265) =="
nl -ba internal/cli/user_command.go | sed -n '3210,3265p'

echo
echo "== Usages of UserParseLocalFile =="
rg -n "UserParseLocalFile" internal/cli/ || true

echo
echo "== Look for local file parsing / doc parse helpers =="
rg -n "ParseLocalFile|parse local file|local file|doc_parse_model|doc parse" internal/cli/user_command.go internal/cli -S || true

Repository: infiniflow/ragflow

Length of output: 157


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== user_command.go (3210-3265) =="
sed -n '3210,3265p' internal/cli/user_command.go | cat -n

echo
echo "== Usages of UserParseLocalFile =="
rg -n "UserParseLocalFile" internal/cli/ || true

echo
echo "== Look for local file parsing / doc parse helpers =="
rg -n "ParseLocalFile|parse local file|local file|doc_parse_model|doc parse" internal/cli/user_command.go internal/cli/ -S || true

Repository: infiniflow/ragflow

Length of output: 3603


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== user_parser.go (3760-3935) =="
sed -n '3760,3935p' internal/cli/user_parser.go | cat -n

echo
echo "== cli_http.go (260-360) =="
sed -n '260,360p' internal/cli/cli_http.go | cat -n

Repository: infiniflow/ragflow

Length of output: 7973


🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n "embed_model|embedding_model" internal/cli/ -S

Repository: infiniflow/ragflow

Length of output: 233


Fix misleading UserParseLocalFile and embed_model/embedding_model mismatch

  • UserParseLocalFile doesn’t parse/ingest the local file; it only returns Code=0, prints a “Success…” message, and returns nil error.
  • The embedding parameter key is inconsistent: user_parser.go sets cmd.Params["embed_model"], but UserParseLocalFile reads cmd.Params["embedding_model"], so the embedding value is always empty in the response.
🤖 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/cli/user_command.go` around lines 3217 - 3256, UserParseLocalFile
currently only prints a success message and returns Code=0 without actually
parsing/ingesting the file and it reads the wrong embedding param key; update
the function UserParseLocalFile to (1) use the correct embedding parameter key
by reading cmd.Params["embed_model"] (or normalize both "embed_model" and
"embedding_model" into a single variable) instead of "embedding_model", (2)
implement the real parse/ingest logic for the named file (call your existing
parser/ingester helper or add file-open, validate, and ingest steps) and capture
any errors, and (3) set SimpleResponse.Code and Message based on the actual
result and return a non-nil error on failure so callers can handle it; reference
symbols: UserParseLocalFile, cmd.Params, "embed_model"/"embedding_model", and
SimpleResponse.

3443-3471: ⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify if ChunkCommand is exposed in the CLI parser/dispatcher
rg -n 'ChunkCommand' internal/cli/

Repository: infiniflow/ragflow

Length of output: 450


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect ChunkCommand implementation (already in prompt, but grab surrounding context)
sed -n '3410,3505p' internal/cli/user_command.go

# Inspect parseChunkCommand wiring
sed -n '4640,4725p' internal/cli/user_parser.go

# Inspect dispatcher usage in parser.go / cli_http.go
sed -n '200,280p' internal/cli/parser.go
sed -n '280,380p' internal/cli/cli_http.go

# Find similar placeholder patterns (optional)
rg -n "not implemented|TODO|stub|placeholder|Success to chunk|ChunkCommand" internal/cli/user_command.go internal/cli/*.go

Repository: infiniflow/ragflow

Length of output: 7677


ChunkCommand is a stub and returns success without chunking

  • ChunkCommand only extracts filename, dsl, and explain, prints to stdout, and returns SimpleResponse{Code: 0, Message: "Success to chunk ..."}—no chunking/persistence logic is invoked.
  • The parser/dispatcher maps user_chunk_command directly to ChunkCommand, so users will see a successful result even though no work is performed.

Add an explicit TODO/feature-gate or return an error like “chunking not implemented” instead of success until the real implementation is added.

🤖 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/cli/user_command.go` around lines 3443 - 3471, ChunkCommand
currently parses inputs but performs no chunking and returns a successful
SimpleResponse; update ChunkCommand (in type CLI) to avoid falsely reporting
success by either (A) returning a clear "chunking not implemented" error when
invoked (e.g., fmt.Errorf("chunking not implemented")) or (B) gating the
behavior behind a feature flag/TODO check that returns an explicit error if the
flag is off; make sure to reference and modify the function ChunkCommand and any
call-sites or dispatcher mapping for user_chunk_command so users do not receive
a fake success until the real chunking/persistence implementation is added.

@JinHai-CN
JinHai-CN merged commit e96bc37 into infiniflow:main Jun 12, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request Jun 12, 2026
1 task done
dripsmvcp added a commit to dripsmvcp/ragflow that referenced this pull request Jun 12, 2026
…nfiniflow#15715)

Resolve conflicts from main's ingestion refactor (infiniflow#15327) and handler-error redaction (infiniflow#15746): union the documentServiceIface upload* and *IngestionTasks methods, adopt main's renamed ingestionTaskDAO/ingestionTaskLogDAO while keeping fileDAO, and dedupe the internal/server import. Build, vet, gofmt and service/handler/dao/router tests (incl. upload-linkage regression tests) pass.
@coderabbitai coderabbitai Bot mentioned this pull request Jun 18, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant