Repository navigation
Go: use NATS as the message queue - #15327
Conversation
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughMigrates 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. ChangesQueue-Driven Ingestion System
Estimated code review effort 🎯 4 (Complex) | ⏱️ ~60 minutes
Suggested labels: |
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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 winIncorrect 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 winIncorrect 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 winMissing 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
StopIngestionTasksshould filter tasks byuserIDor 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 liftTask creation and queue publish are not atomic—failed publish leaves orphan tasks.
If
PublishTaskfails (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 ifjson.Marshalfails after some tasks were successfully published.Consider either:
- Rolling back the DB entry on publish failure, or
- 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 winUnsafe type assertion may cause panic.
If
Checkpoint["current_step"]is missing or not afloat64, 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 winHandle gorm “record not found” separately in CheckAndCreate
internal/dao/ingestion.goIngestionTaskDAO.CheckAndCreatefalls into the “create ingestion task” path for any non-nil error fromFirst(...)(nogorm.ErrRecordNotFoundguard). 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);errorsis 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 winUnchecked DB error and incorrect JSON type assertion when collecting files-to-delete
err = tx.Where("tasklet_id = ?", tasklet.ID).Find(&taskletLogs).Erroris not checked; query failures are silently ignored.taskletLog.Checkpoint["files"].([]string)(and the same pattern fortaskLog) is incorrect becauseCheckpointisentity.JSONMap map[string]interface{}; JSON arrays deserialize as[]interface{}(so the[]stringassertion will fail andFilesToDeleteends 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 winFix incorrect column used by
IngestionTaskletLogDAOmethods
ListLogsByTaskletIDandDeleteByTaskletID(internal/dao/ingestion.golines ~456-477) filter ontask_id, butentity.IngestionTaskletLogmaps the scoped field asTaskletID->gorm:"column:tasklet_id".- Update both WHERE clauses to
tasklet_id = ?and rename the parameter totaskletIDfor consistency withLatestLogByTaskletID(already usestasklet_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 winIngestion task removal leaves tasklet/log rows orphaned
internal/dao/ingestion.go(RemoveByAPIServerOrAdminServer) deletes only theingestion_taskrow in the transaction, while the correspondingingestion_tasklet,ingestion_tasklet_log, andingestion_task_logrows are only queried and never deleted.internal/service/document.goandinternal/admin/service.gocall this DAO directly and don’t perform any further cleanup. WithBaseModelcontaining nogorm.DeletedAt(soDeleteis 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/DeleteByTaskletIDhelpers) or add/ensure DB-levelON DELETE CASCADEconstraints.🤖 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
UpdateCreateDateAndTimesets the wrong date field.The method updates
CreateTimebut then writesUpdateDateinstead ofCreateDate. As written,CreateDateis never populated whileUpdateDategets clobbered, which contradicts the method name and the pairedUpdateUpdateDateAndTimesemantics.🐛 Proposed fix
func (m *BaseModel) UpdateCreateDateAndTime() error { timestamp, dateTime := autoModelTime() m.CreateTime = ×tamp - 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 winLoop breaks prematurely on gaps in stream sequence.
When a message at
seqis 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 winSilent failure returns empty
TaskMessageon unmarshal error.If JSON unmarshalling fails, an error is logged but a zero-value
TaskMessageis 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
TaskHandleinterface ininternal/common/task.goand 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 winIngestor 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 winMissing thread-safety for message queue initialization.
InitMessageQueueEnginelackssync.Onceprotection unlikeInitfor the doc engine (line 42). If called concurrently from multiple goroutines, this could lead to race conditions on themessageQueueEngineglobal 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 winManual
ID++increment bypasses GORM auto-increment.Manually incrementing
latestLog.IDbefore callingCreatemay 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 winStale 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 winReturned
taskRecord.Statusis stale on the restart path.After updating the DB status to
CREATED, the in-memorytaskRecord.Statusstill holdsFAILED/STOPPED. Callers that rely on the returned struct's status (compare withSetRunningByIngestor, 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 winIncomplete error message for REMOVE subcommand.
The error message says "expected SERVICE" but
TokenIngestionis 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 winOff-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 winIncorrect 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 winMisleading 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 winTypos 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 winSet
service_type/support for NATS configs so the admin UI can classify them
GetAllConfigs()is only consumed byinternal/admin/*; with NATS entries missingconfigDict["service_type"],internal/admin/service.go’sGetServiceDetailsfalls into the default path and returns"status": "unknown"(no NATS health check).- Runtime NATS engine wiring uses
config.Nats.Host/Port(notallConfigs), 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 winIncorrect format verb
%wused withfmt.Sprintf.
%wis only valid withfmt.Errorffor error wrapping. Using it withfmt.Sprintforcommon.Fatalwill 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 winClarify the immutability field in the fallback condition
- The conditional checks for
"max waiting can not be updated", which refers to JetStreamMaxWaitingimmutability (notMaxAckPending, which is generally editable). Update the comment/rationale to referenceMaxWaitingso 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 winUnused
userIDparameter and early return on partial failure.
- The
userIDparameter is never used—consider removing it or adding authorization checks.- 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 valueRoute structure is inconsistent—
/ingestion/tasksunder datasets group creates awkward paths.These routes are registered under the
datasetsgroup (line 200), producing paths like/api/v1/datasets/ingestion/tasks. This is inconsistent with RESTful conventions since:
GET /api/v1/datasets/ingestion/taskslists tasks across all datasets (not scoped to a dataset)- The parse endpoint at
POST /:dataset_id/documents/parseis dataset-scopedConsider either:
- Moving task management routes to a top-level
/api/v1/ingestion/tasksgroup, or- Scoping them under
/:dataset_id/ingestion/tasksif 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 valueDoc comment uses
canceling/canceled, but the implemented statuses areSTOPPING/STOPPED.The lifecycle comment references
canceling/canceledstates 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 winUnusual type assertion pattern for optional parameter.
Using
*stringtype assertion is unconventional. Ifdataset_idis 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 valueInconsistent 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 winConsider 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
parseUserRemoveTaskat 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 winRecommend 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 valueNon-fatal message queue initialization may cause runtime failures.
If
InitMessageQueueEnginefails, the admin server still starts but queue management endpoints (list/publish/pull/show frominternal/admin/handler.go) will fail at runtime when accessing the nilmessageQueueEngine. 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 winUse
errors.Iswith the typed JetStream “stream already exists” error.In
internal/engine/nats/nats.go(lines 74-79), avoiderr.Error()string comparison; instead checkerrors.Is(err, nats.ErrStreamNameAlreadyInUse)(fromgithub.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
⛔ Files ignored due to path filters (3)
go.sumis excluded by!**/*.suminternal/common/ingestion.pb.gois excluded by!**/*.pb.gointernal/common/ingestion_grpc.pb.gois excluded by!**/*.pb.go
📒 Files selected for processing (42)
cmd/admin_server.gocmd/ingestor.gocmd/server_main.goconf/service_conf.yamldocker/.envdocker/docker-compose-base.ymldocker/service_conf.yaml.templatego.modinternal/admin/handler.gointernal/admin/ingestion_manager.gointernal/admin/router.gointernal/admin/service.gointernal/admin/state.gointernal/cli/admin_command.gointernal/cli/admin_parser.gointernal/cli/client.gointernal/cli/common_command.gointernal/cli/lexer.gointernal/cli/parser.gointernal/cli/types.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/common/constants.gointernal/common/error_code.gointernal/common/number.gointernal/common/status_message.gointernal/common/task.gointernal/dao/database.gointernal/dao/ingestion.gointernal/engine/engine.gointernal/engine/global.gointernal/engine/nats/nats.gointernal/entity/base.gointernal/entity/ingestion_task.gointernal/handler/document.gointernal/ingestion/ingestion_service.gointernal/proto/ingestion.protointernal/router/router.gointernal/server/config.gointernal/service/admin_client.gointernal/service/document.gointernal/storage/types.go
💤 Files with no reviewable changes (3)
- internal/admin/ingestion_manager.go
- internal/proto/ingestion.proto
- internal/storage/types.go
| err := msgQueueEngine.InitConsumer("tasks.RAGFLOW") | ||
| if err != nil { | ||
| errorResponse(c, err.Error(), 400) | ||
| } | ||
| messages, err := msgQueueEngine.GetMessages(req.MessageCount) |
There was a problem hiding this comment.
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.
| 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.
| } 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) | ||
| } | ||
| } |
There was a problem hiding this comment.
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.
| } 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.
| 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) | ||
| } |
There was a problem hiding this comment.
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.
| 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: |
There was a problem hiding this comment.
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.
| var checkpointMap map[string]interface{} | ||
| checkpointMap = latestLog.Checkpoint | ||
| currentStep := checkpointMap["current_step"].(int) | ||
| totalStep := checkpointMap["total_step"].(int) | ||
| for i := currentStep; i < totalStep; i++ { |
There was a problem hiding this comment.
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.
| 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.
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
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 winNormalize task IDs with
strings.Fields()before sending them downstream.
strings.Split(taskString, " ")preserves empty entries, so extra spaces inSTOP/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 winReject invalid
MQ PULLarguments instead of silently pulling 1 message.Any non-integer token after
MQ PULLcurrently falls through theparseNumber()error path and becomesmessage_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 winFix 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 winFix 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 winGET request should use query parameters in URL, not request body.
HTTP GET requests typically do not include request bodies. The
dataset_idparameter 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_idisnil, serializingmap[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 winRemove redundant
dataset_idfrom payload.The
dataset_idis 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
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (22)
.gitignorecmd/admin_server.gocmd/ingestor.gocmd/server_main.goconf/service_conf.yamldocker/.envdocker/docker-compose-base.ymldocker/service_conf.yaml.templatego.modinternal/admin/router.gointernal/cli/admin_command.gointernal/cli/admin_parser.gointernal/cli/cli_http.gointernal/cli/lexer.gointernal/cli/parser.gointernal/cli/types.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/common/constants.gointernal/common/number.gointernal/dao/database.gointernal/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
There was a problem hiding this comment.
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 winNormalize task IDs with
strings.Fields()before sending them downstream.
strings.Split(taskString, " ")preserves empty entries, so extra spaces inSTOP/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 winReject invalid
MQ PULLarguments instead of silently pulling 1 message.Any non-integer token after
MQ PULLcurrently falls through theparseNumber()error path and becomesmessage_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 winFix 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 winFix 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 winGET request should use query parameters in URL, not request body.
HTTP GET requests typically do not include request bodies. The
dataset_idparameter 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_idisnil, serializingmap[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 winRemove redundant
dataset_idfrom payload.The
dataset_idis 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
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (22)
.gitignorecmd/admin_server.gocmd/ingestor.gocmd/server_main.goconf/service_conf.yamldocker/.envdocker/docker-compose-base.ymldocker/service_conf.yaml.templatego.modinternal/admin/router.gointernal/cli/admin_command.gointernal/cli/admin_parser.gointernal/cli/cli_http.gointernal/cli/lexer.gointernal/cli/parser.gointernal/cli/types.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/common/constants.gointernal/common/number.gointernal/dao/database.gointernal/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:
- 1: nats-io/nats.go@ca54e50
- 2: https://nvd.nist.gov/vuln/detail/cve-2026-33218
- 3: https://advisories.nats.io/
- 4: https://app.opencve.io/cve/?product=nats_server&vendor=nats
- 5: https://repology.org/project/nats-server/cves
Update NATS dependency and sanity-check security
go.modpinsgithub.com/nats-io/nats.gotov1.31.0, but the current latest release isv1.52.0. No known OSV/GitHub/NATS advisory entries were found fornats.gov1.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 || trueRepository: 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 || trueRepository: 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 -nRepository: infiniflow/ragflow
Length of output: 7973
🏁 Script executed:
#!/bin/bash set -euo pipefail rg -n "embed_model|embedding_model" internal/cli/ -SRepository: infiniflow/ragflow
Length of output: 233
Fix misleading
UserParseLocalFileandembed_model/embedding_modelmismatch
UserParseLocalFiledoesn’t parse/ingest the local file; it only returnsCode=0, prints a “Success…” message, and returnsnilerror.- The embedding parameter key is inconsistent:
user_parser.gosetscmd.Params["embed_model"], butUserParseLocalFilereadscmd.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/*.goRepository: infiniflow/ragflow
Length of output: 7677
ChunkCommand is a stub and returns success without chunking
ChunkCommandonly extractsfilename,dsl, andexplain, prints to stdout, and returnsSimpleResponse{Code: 0, Message: "Success to chunk ..."}—no chunking/persistence logic is invoked.- The parser/dispatcher maps
user_chunk_commanddirectly toChunkCommand, 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.
Signed-off-by: Jin Hai <[email protected]>
…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.
What problem does this PR solve?
Type of change