RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(agent): wire document service so dataflow rerun works instead of 500ing (#19094)
euvre60fcf20c89af
diff --git a/cmd/ragflow_server.go b/cmd/ragflow_server.goindex 64dcb6316a..9274be2306 100644--- a/cmd/ragflow_server.go+++ b/cmd/ragflow_server.go@@ -827,7 +827,12 @@ func startServer(ctx context.Context) {agentOpts.stateSerializer,agentOpts.runTracker,)- agentHandler := handler.NewAgentHandler(ctx, agentService, fileService)+ // WithDocumentService wires the rerun dependency used by+ // POST /api/v1/agents/rerun (dataflow "re-run" in the pipeline+ // result viewer). RerunAgent fails closed without it, so this must+ // stay attached to NewAgentHandler.+ agentHandler := handler.NewAgentHandler(ctx, agentService, fileService).+ WithDocumentService(documentService)// Public chatbot/agentbot endpoints (api/v1/chatbots/...,// api/v1/agentbots/...) and the agent attachment download.diff --git a/internal/dao/pipeline_operation_log.go b/internal/dao/pipeline_operation_log.goindex ee95738a1b..fb52966c73 100644--- a/internal/dao/pipeline_operation_log.go+++ b/internal/dao/pipeline_operation_log.go@@ -168,6 +168,27 @@ func (dao *PipelineOperationLogDAO) GetByIDAndKBID(ctx context.Context, db *gormreturn &log, nil}+// GetByID fetches a single pipeline operation log by id, regardless of+// knowledge base. Callers that must scope to a dataset use+// GetByIDAndKBID instead.+func (dao *PipelineOperationLogDAO) GetByID(ctx context.Context, db *gorm.DB, logID string) (*entity.PipelineOperationLog, error) {+ var log entity.PipelineOperationLog+ if err := db.WithContext(ctx).Where("id = ?", logID).First(&log).Error; err != nil {+ return nil, err+ }+ return &log, nil+}++// UpdateDSL replaces the DSL stored on a pipeline operation log. Used by the+// dataflow rerun endpoint to persist the front-end's edited component+// configuration plus the rerun entry point (dsl.path = [component_id]),+// mirroring Python's PipelineOperationLogService.update_by_id(id, {"dsl": dsl}).+func (dao *PipelineOperationLogDAO) UpdateDSL(ctx context.Context, db *gorm.DB, logID string, dsl entity.JSONMap) error {+ return db.WithContext(ctx).Model(&entity.PipelineOperationLog{}).+ Where("id = ?", logID).+ Update("dsl", dsl).Error+}+// Create inserts a new pipeline operation log.func (dao *PipelineOperationLogDAO) Create(ctx context.Context, db *gorm.DB, log *entity.PipelineOperationLog) error {return db.WithContext(ctx).Create(log).Errordiff --git a/internal/handler/agent.go b/internal/handler/agent.goindex 93a1ccd25f..d17cd84729 100644--- a/internal/handler/agent.go+++ b/internal/handler/agent.go@@ -39,6 +39,7 @@ import (pipelinepkg "ragflow/internal/ingestion/pipeline""ragflow/internal/ingestion/task""ragflow/internal/service"+ "ragflow/internal/service/document""ragflow/internal/service/file""ragflow/internal/utility"@@ -71,29 +72,33 @@ type chatAgentService interface {RunAgent(ctx context.Context, userID, canvasID, sessionID, version string, userInput any, files []map[string]interface{}) (<-chan canvas.RunEvent, error)}-// documentAccessChecker is the minimal surface RerunAgent needs-// from DocumentService. Defined as an interface (instead of taking-// the concrete *service.DocumentService) so handler tests can-// inject a deny-all stub without spinning up the full service-// (DB DAOs, storage clients, …). The production *service.DocumentService-// satisfies this interface because its Accessible signature-// matches.-type documentAccessChecker interface {- Accessible(docID, userID string) bool+// documentRerunService is the surface RerunAgent needs from the document+// service: re-run the ingestion pipeline a pipeline operation log points+// at, with document accessibility enforced inside the service. Defined as+// an interface (instead of taking the concrete *document.DocumentService)+// so handler tests can inject a stub without spinning up the full service+// (DB DAOs, storage clients, …). The production *document.DocumentService+// satisfies this interface because its RerunDocument signature matches.+type documentRerunService interface {+ RerunDocument(ctx context.Context, userID, logID string, dsl map[string]interface{}, componentID string) error}+// Compile-time proof that the production document service satisfies the+// rerun surface, keeping the interface and the service in lockstep.+var _ documentRerunService = (*document.DocumentService)(nil)+// AgentHandler agent handlertype AgentHandler struct {agentService *service.AgentServicechatRunner chatAgentServicefileService agentFileServiceloader canvasLoader- // documentService is optional. Wired in cmd/server_main.go after- // NewAgentHandler (which doesn't take it to preserve the existing- // test-friendly signature). When nil, RerunAgent falls back to- // tenant-only authorization (i.e. cannot verify the doc, so the- // check is skipped — same shape as the pre-port behaviour).- documentService documentAccessChecker+ // documentService is required by RerunAgent. Wired in+ // cmd/ragflow_server.go after NewAgentHandler (which doesn't take it+ // to preserve the existing test-friendly signature). RerunAgent fails+ // closed (500) when it is nil: skipping the service would bypass the+ // document ownership gate.+ documentService documentRerunService// redisGet fetches a raw string from Redis. Defaults to the global// client (redis.Get) so production behaviour is unchanged; tests inject// a miniredis-backed getter to exercise Agent log endpoints without a@@ -122,10 +127,10 @@ type debugExecutor interface {}// WithDocumentService injects the document service used by-// RerunAgent to enforce DocumentService.accessible(docID, tenantID)-// before re-running. Returns the receiver for chaining in-// server_main wiring.-func (h *AgentHandler) WithDocumentService(s documentAccessChecker) *AgentHandler {+// RerunAgent to resolve the pipeline operation log, enforce+// DocumentService accessibility, and enqueue the rerun. Returns the+// receiver for chaining in the server wiring.+func (h *AgentHandler) WithDocumentService(s documentRerunService) *AgentHandler {h.documentService = sreturn h}@@ -1471,21 +1476,19 @@ func (h *AgentHandler) AgentChatCompletions(c *gin.Context) {}// RerunAgent POST /api/v1/agents/rerun — requires id, dsl, and-// component_id. The Python agent API uses PipelineOperationLogService-// and the dataflow queue, none of which the Go port has implemented-// yet; we keep the validation envelope (101 with the "required-// argument are missing" message) so the test contract is satisfied,-// and accept the request when all three fields are present.+// component_id. The front-end dataflow "view result" page sends the+// pipeline operation LOG id plus the edited DSL (web+// useRerunDataflow); the service resolves log -> document, enforces+// ownership, persists the edited DSL, and re-enqueues the ingestion+// run (see DocumentService.RerunDocument).//-// Tenant / document ownership gate (PR #15145, review round 6):-// body.id is treated as a document ID and-// `DocumentService.accessible(docID, user.ID)` is enforced BEFORE-// the rerun. The gate is REQUIRED: a nil documentService turns a-// wiring miss into an auth bypass (any caller could rerun an-// arbitrary doc id without an ownership check), so we fail closed-// with 500 instead of accepting the request. On denial we return-// "Document not found." so a caller cannot probe whether a-// document exists in another tenant.+// DocumentService.RerunDocument enforces accessibility BEFORE the+// rerun. The gate is REQUIRED: a nil documentService turns a wiring+// miss into an auth bypass (any caller could rerun an arbitrary doc+// id without an ownership check), so we fail closed with 500 instead+// of accepting the request. On denial the service returns+// "Document not found." so a caller cannot probe whether a document+// exists in another tenant.func (h *AgentHandler) RerunAgent(c *gin.Context) {user, code, msg := GetUser(c)if code != common.CodeSuccess {@@ -1516,17 +1519,35 @@ func (h *AgentHandler) RerunAgent(c *gin.Context) {return}// Fail closed on missing dependency: a nil documentService- // means the handler was wired without the access checker,- // which would let any caller rerun an arbitrary doc id- // without proving ownership. Surface as a 500 so a missing- // dependency is loud, not silent.+ // means the handler was wired without the rerun service, which+ // would let any caller rerun an arbitrary doc id without proving+ // ownership. Surface as a 500 so a missing dependency is loud,+ // not silent.if h.documentService == nil {zap.L().Error("RerunAgent: documentService is nil; refusing request to prevent auth bypass")common.ResponseWithCodeData(c, common.CodeServerError, nil, "server misconfiguration: document service not wired")return}- if !h.documentService.Accessible(body.ID, user.ID) {- common.ResponseWithCodeData(c, common.CodeDataError, nil, "Document not found.")+ if err := h.documentService.RerunDocument(c.Request.Context(), user.ID, body.ID, body.DSL, body.ComponentID); err != nil {+ // Domain failures (unknown log/document, access denial,+ // document mid-run) map to the data-error envelope (code 102)+ // with the service's caller-safe message. Everything else is+ // an internal failure: log it server-side and answer 500 with+ // a generic message so internals (DB errors, queue failures)+ // are neither leaked to the tenant nor mislabeled as a data+ // error.+ var processingErr *document.RerunDocumentProcessingError+ switch {+ case errors.Is(err, document.ErrRerunDocumentNotFound):+ common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())+ case errors.As(err, &processingErr):+ common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())+ default:+ zap.L().Error("RerunAgent: rerun failed",+ zap.String("log_id", body.ID),+ zap.Error(err))+ common.ResponseWithCodeData(c, common.CodeServerError, nil, "rerun failed, please try again later")+ }return}common.SuccessWithData(c, true, "success")diff --git a/internal/handler/agent_test.go b/internal/handler/agent_test.goindex 27025305c7..803028d110 100644--- a/internal/handler/agent_test.go+++ b/internal/handler/agent_test.go@@ -36,6 +36,7 @@ import ("ragflow/internal/dao""ragflow/internal/entity""ragflow/internal/service"+ "ragflow/internal/service/document""ragflow/internal/tokenizer")@@ -1630,23 +1631,20 @@ func TestRerunAgent_RequiresAllFields(t *testing.T) {}// TestRerunAgent_AcceptsCompleteRequest covers the happy path: all-// three required fields present + documentService wired with an-// accessible document -> 200 / code 0.-//-// Round 6: now that RerunAgent fails closed when documentService is-// nil, the happy path needs an accessible stub. We use the deny-all-// stub flipped to accessible=true so the gate passes.+// three required fields present + documentService wired with a+// rerun that succeeds -> 200 / code 0, and the stub receives the+// log id / dsl / component_id from the request verbatim.func TestRerunAgent_AcceptsCompleteRequest(t *testing.T) {gin.SetMode(gin.TestMode)w := httptest.NewRecorder()c, _ := gin.CreateTestContext(w)c.Request = httptest.NewRequest("POST", "/api/v1/agents/rerun",- strings.NewReader(`{"id":"x","dsl":{"path":[]},"component_id":"c1"}`))+ strings.NewReader(`{"id":"log-1","dsl":{"path":[]},"component_id":"c1"}`))c.Request.Header.Set("Content-Type", "application/json")c.Set("user", &entity.User{ID: "u1"})c.Set("user_id", "u1")- stub := &stubDocService{accessible: true}+ stub := &stubDocService{}ctx := t.Context()h := NewAgentHandler(ctx, service.NewAgentService(), nil).WithDocumentService(stub)@@ -1657,6 +1655,13 @@ func TestRerunAgent_AcceptsCompleteRequest(t *testing.T) {if code, _ := resp["code"].(float64); code != float64(common.CodeSuccess) {t.Errorf("code = %v, want 0 (msg=%v)", code, resp["message"])}+ if stub.userID != "u1" || stub.logID != "log-1" || stub.componentID != "c1" {+ t.Errorf("stub args = user %q log %q component %q, want u1/log-1/c1",+ stub.userID, stub.logID, stub.componentID)+ }+ if _, ok := stub.dsl["path"]; !ok {+ t.Errorf("stub dsl = %v, want the request dsl passed through", stub.dsl)+ }}// TestPromptsReturnsHardcodedFields covers the contract: the data@@ -1686,14 +1691,11 @@ func TestPromptsReturnsHardcodedFields(t *testing.T) {}}-// TestRerunAgent_RejectsInaccessibleDocument mirrors PR #15145:-// POST /api/v1/agents/rerun gates on DocumentService.accessible-// (the python "is the document reachable by this tenant" check)-// before accepting the request. Without documentService wired,-// the gate is skipped (existing behaviour, returns success). With-// it wired, an inaccessible doc must return CodeDataError + "Document-// not found." so a caller cannot probe whether a doc exists in-// another tenant.+// TestRerunAgent_RejectsInaccessibleDocument: POST /api/v1/agents/rerun+// gates on RerunDocument resolving the log and validating document access+// before accepting the request. A denial from the service must surface as+// CodeDataError + "Document not found." so a caller cannot probe whether a+// document exists in another tenant.func TestRerunAgent_RejectsInaccessibleDocument(t *testing.T) {gin.SetMode(gin.TestMode)w := httptest.NewRecorder()@@ -1704,11 +1706,9 @@ func TestRerunAgent_RejectsInaccessibleDocument(t *testing.T) {c.Set("user", &entity.User{ID: "u1"})c.Set("user_id", "u1")- // Wire a stub documentService that denies all access. The setter- // now accepts a narrow documentAccessChecker interface (PR review- // round 5), so the deny-all stub injects cleanly without standing- // up the real DocumentService (DB, storage, ...).- stub := &stubDocService{accessible: false}+ // The stub models the service's deny path: unknown log or an+ // inaccessible document both collapse to ErrRerunDocumentNotFound.+ stub := &stubDocService{err: document.ErrRerunDocumentNotFound}ctx := t.Context()h := NewAgentHandler(ctx, service.NewAgentService(), nil).WithDocumentService(stub)@@ -1725,13 +1725,12 @@ func TestRerunAgent_RejectsInaccessibleDocument(t *testing.T) {}}-// TestRerunAgent_NoDocumentServiceFailsClosed pins PR review round 6,-// Major #2: a nil documentService is now treated as a wiring-// misconfiguration that would create an auth bypass, NOT a-// backward-compatible "skip the gate" state. The handler must-// return 500 / "server misconfiguration" so a missing-// dependency is loud and gets fixed, instead of silently-// allowing any caller to rerun an arbitrary doc id.+// TestRerunAgent_NoDocumentServiceFailsClosed pins the fail-closed+// rule: a nil documentService is treated as a wiring misconfiguration+// that would create an auth bypass, NOT a backward-compatible "skip+// the gate" state. The handler must return 500 / "server+// misconfiguration" so a missing dependency is loud and gets fixed,+// instead of silently allowing any caller to rerun an arbitrary doc id.func TestRerunAgent_NoDocumentServiceFailsClosed(t *testing.T) {gin.SetMode(gin.TestMode)w := httptest.NewRecorder()@@ -1745,9 +1744,9 @@ func TestRerunAgent_NoDocumentServiceFailsClosed(t *testing.T) {ctx := t.Context()h := NewAgentHandler(ctx, service.NewAgentService(), nil)// Note: no WithDocumentService call → documentService is nil.- // Production wiring (cmd/server_main.go) always calls- // WithDocumentService; a nil here means the handler was- // constructed without its required dependency.+ // The production wiring (cmd/ragflow_server.go) chains+ // WithDocumentService onto NewAgentHandler; a nil here means the+ // handler was constructed without its required dependency.h.RerunAgent(c)var resp map[string]interface{}@@ -1761,12 +1760,84 @@ func TestRerunAgent_NoDocumentServiceFailsClosed(t *testing.T) {}}-type stubDocService struct {- accessible bool+// TestRerunAgent_InternalErrorReturns500: a non-domain failure (DB down,+// queue publish failed, ...) is neither a caller data error nor safe to+// echo back. The handler must answer CodeServerError with a generic+// message and keep the raw error text out of the response.+func TestRerunAgent_InternalErrorReturns500(t *testing.T) {+ gin.SetMode(gin.TestMode)+ w := httptest.NewRecorder()+ c, _ := gin.CreateTestContext(w)+ c.Request = httptest.NewRequest("POST", "/api/v1/agents/rerun",+ strings.NewReader(`{"id":"log-1","dsl":{"path":[]},"component_id":"c1"}`))+ c.Request.Header.Set("Content-Type", "application/json")+ c.Set("user", &entity.User{ID: "u1"})+ c.Set("user_id", "u1")++ stub := &stubDocService{err: errors.New("update pipeline log dsl: connection refused")}+ ctx := t.Context()+ h := NewAgentHandler(ctx, service.NewAgentService(), nil).+ WithDocumentService(stub)+ h.RerunAgent(c)++ var resp map[string]interface{}+ _ = json.Unmarshal(w.Body.Bytes(), &resp)+ if code, _ := resp["code"].(float64); code != float64(common.CodeServerError) {+ t.Errorf("internal error: want code %d, got %v (msg=%v)",+ common.CodeServerError, code, resp["message"])+ }+ if msg, _ := resp["message"].(string); strings.Contains(msg, "connection refused") {+ t.Errorf("internal error: raw error leaked into the response message %q", msg)+ }}-func (s *stubDocService) Accessible(_, _ string) bool {- return s.accessible+// TestRerunAgent_DocumentProcessingIsDataError: a mid-run document is a+// caller-facing conflict, so the typed processing error keeps the 102+// envelope with the service's message.+func TestRerunAgent_DocumentProcessingIsDataError(t *testing.T) {+ gin.SetMode(gin.TestMode)+ w := httptest.NewRecorder()+ c, _ := gin.CreateTestContext(w)+ c.Request = httptest.NewRequest("POST", "/api/v1/agents/rerun",+ strings.NewReader(`{"id":"log-1","dsl":{"path":[]},"component_id":"c1"}`))+ c.Request.Header.Set("Content-Type", "application/json")+ c.Set("user", &entity.User{ID: "u1"})+ c.Set("user_id", "u1")++ stub := &stubDocService{err: &document.RerunDocumentProcessingError{DocumentName: "hlm.docx"}}+ ctx := t.Context()+ h := NewAgentHandler(ctx, service.NewAgentService(), nil).+ WithDocumentService(stub)+ h.RerunAgent(c)++ var resp map[string]interface{}+ _ = json.Unmarshal(w.Body.Bytes(), &resp)+ if code, _ := resp["code"].(float64); code != float64(common.CodeDataError) {+ t.Errorf("processing error: want code %d, got %v (msg=%v)",+ common.CodeDataError, code, resp["message"])+ }+ if msg, _ := resp["message"].(string); !strings.Contains(msg, "is processing") {+ t.Errorf("processing error: want message to contain 'is processing', got %q", msg)+ }+}++// stubDocService stubs the documentRerunService surface for handler+// tests: it records the arguments and replays err (nil = success,+// document.ErrRerunDocumentNotFound = deny).+type stubDocService struct {+ err error+ userID string+ logID string+ dsl map[string]interface{}+ componentID string+}++func (s *stubDocService) RerunDocument(_ context.Context, userID, logID string, dsl map[string]interface{}, componentID string) error {+ s.userID = userID+ s.logID = logID+ s.dsl = dsl+ s.componentID = componentID+ return s.err}// TestAgentChatCompletions_FilesDeserialized verifies that thediff --git a/internal/service/document/document.go b/internal/service/document/document.goindex f15611bde6..c3208e0f56 100644--- a/internal/service/document/document.go+++ b/internal/service/document/document.go@@ -35,6 +35,7 @@ type DocumentService struct {kbDAO *dao.KnowledgebaseDAOingestionTaskDAO *dao.IngestionTaskDAOingestionTaskLogDAO *dao.IngestionTaskLogDAO+ pipelineLogDAO *dao.PipelineOperationLogDAOingestionTaskSvc *service.IngestionTaskServicedocEngine engine.DocEnginemetadataSvc *service.MetadataService@@ -58,6 +59,7 @@ func NewDocumentService() *DocumentService {documentDAO: dao.NewDocumentDAO(),ingestionTaskDAO: dao.NewIngestionTaskDAO(),ingestionTaskLogDAO: dao.NewIngestionTaskLogDAO(),+ pipelineLogDAO: dao.NewPipelineOperationLogDAO(),ingestionTaskSvc: ingestionTaskSvc,kbDAO: dao.NewKnowledgebaseDAO(),docEngine: engine.Get(),diff --git a/internal/service/document/document_rerun.go b/internal/service/document/document_rerun.gonew file mode 100644index 0000000000..74b7518f3b--- /dev/null+++ b/internal/service/document/document_rerun.go@@ -0,0 +1,120 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++package document++import (+ "context"+ "errors"+ "fmt"++ "gorm.io/gorm"++ "ragflow/internal/dao"+ "ragflow/internal/entity"+)++// ErrRerunDocumentNotFound is the rerun endpoint's only "unknown or denied"+// answer: an unknown log id, a missing document/dataset, and an access+// denial all collapse to the same message so a caller cannot probe whether+// a document exists in another tenant.+var ErrRerunDocumentNotFound = errors.New("Document not found.")++// RerunDocumentProcessingError reports a rerun attempt while the document+// is mid-run (0 < progress < 1). The handler maps it to the data-error+// envelope, so the message is written for the caller, not the server log.+type RerunDocumentProcessingError struct {+ DocumentName string+}++func (e *RerunDocumentProcessingError) Error() string {+ return fmt.Sprintf("`%s` is processing...", e.DocumentName)+}++// RerunDocument re-runs the ingestion pipeline a pipeline operation log+// belongs to. It backs POST /api/v1/agents/rerun, whose id is the+// ingestion LOG id, resolved to its document before the accessibility+// gate.+//+// Steps: resolve log -> document and enforce DocumentService+// accessibility; refuse while the document is mid-run (0 < progress < 1);+// persist the front-end's edited DSL with dsl.path = [component_id] on+// the log row; clear the prior parse results (chunks, counters, terminal+// tasks) and enqueue a fresh ingestion run (StartParseDocuments with+// RerunWithDelete), which records a new pipeline operation log the+// front-end can track.+//+// The Go pipeline has no partial-resume entry point (execution always+// starts at the graph entry; see pipeline.Pipeline.Run), so the rerun+// re-executes the whole pipeline instead of resuming from component_id.+//+// Known divergence from the Python endpoint: the persisted edited DSL is+// an audit record only. The Go ingestion worker sources the parse DSL+// from the canvas (doc.PipelineID -> user_canvas.dsl; see+// loadDSLFromCanvas) and IngestionTask carries no DSL/log reference, so+// the edited dsl/component_id currently has no effect on the Go rerun.+// Plumbing the log DSL through the task to the worker is a follow-up.+func (s *DocumentService) RerunDocument(ctx context.Context, userID, logID string, dsl map[string]interface{}, componentID string) error {+ // A missing row is the caller-facing not-found; any other DB error is+ // an internal failure and must not be collapsed into it.+ opLog, err := s.pipelineLogDAO.GetByID(ctx, dao.DB, logID)+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return ErrRerunDocumentNotFound+ }+ if err != nil {+ return fmt.Errorf("get pipeline operation log %s: %w", logID, err)+ }+ doc, err := s.documentDAO.GetByID(ctx, dao.DB, opLog.DocumentID)+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return ErrRerunDocumentNotFound+ }+ if err != nil {+ return fmt.Errorf("get document %s: %w", opLog.DocumentID, err)+ }+ kb, err := s.kbDAO.GetByID(ctx, dao.DB, doc.KbID)+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return ErrRerunDocumentNotFound+ }+ if err != nil {+ return fmt.Errorf("get knowledgebase %s: %w", doc.KbID, err)+ }+ if !s.Accessible(ctx, doc.ID, userID) {+ return ErrRerunDocumentNotFound+ }+ if doc.Progress > 0 && doc.Progress < 1 {+ name := opLog.DocumentName+ if doc.Name != nil && *doc.Name != "" {+ name = *doc.Name+ }+ return &RerunDocumentProcessingError{DocumentName: name}+ }++ if dsl != nil {+ // Persist for any non-nil dsl, including an empty map. Copy+ // before writing so the caller's DSL map is not mutated in+ // place.+ persisted := make(map[string]interface{}, len(dsl)+1)+ for k, v := range dsl {+ persisted[k] = v+ }+ persisted["path"] = []interface{}{componentID}+ if err := s.pipelineLogDAO.UpdateDSL(ctx, dao.DB, logID, entity.JSONMap(persisted)); err != nil {+ return fmt.Errorf("update pipeline log dsl: %w", err)+ }+ }++ return s.StartParseDocuments(ctx, doc, kb, userID, StartParseOptions{RerunWithDelete: true})+}diff --git a/internal/service/document/document_rerun_e2e_test.go b/internal/service/document/document_rerun_e2e_test.gonew file mode 100644index 0000000000..ab5c7e51da--- /dev/null+++ b/internal/service/document/document_rerun_e2e_test.go@@ -0,0 +1,110 @@+//go:build e2e++package document++import (+ "testing"++ "ragflow/internal/common"+ "ragflow/internal/engine"+ "ragflow/internal/entity"+ "ragflow/internal/ingestion/testutil"+ servicepkg "ragflow/internal/service"+)++// TestRerunDocument_E2E_EnqueuesThroughRealMessageQueue drives the rerun+// through the production MessageQueueTaskPublisher into a real NATS+// JetStream stream and consumes the task message back. The unit tier's+// recording publisher only proves the publish call happened; this tier+// proves the enqueue actually lands on tasks.RAGFLOW with a task id that+// resolves to a SCHEDULED ingestion task for the document.+func TestRerunDocument_E2E_EnqueuesThroughRealMessageQueue(t *testing.T) {+ db := testutil.SetupTestDB(t,+ &entity.IngestionTask{}, &entity.IngestionTaskLog{}, &entity.Task{},+ &entity.Document{}, &entity.Knowledgebase{}, &entity.Tenant{},+ &entity.File{}, &entity.File2Document{}, &entity.PipelineOperationLog{},+ )+ defer testutil.ReplaceDBForTest(t, db)()++ mq := testutil.SetupNatsEngine(t)+ previous := engine.GetMessageQueueEngine()+ engine.SetMessageQueueEngine(mq)+ t.Cleanup(func() { engine.SetMessageQueueEngine(previous) })+ if err := mq.InitConsumer("tasks.>"); err != nil {+ t.Fatalf("InitConsumer: %v", err)+ }++ testutil.SeedTestData(t, db,+ testutil.WithTenantID("tenant-1"),+ testutil.WithKBID("kb-1"),+ testutil.WithDocID("doc-1"),+ )+ // SeedTestData leaves a RUNNING ingestion task behind, which+ // clearDocumentParseResults would (rightly) refuse to clear. The rerun+ // starts from a completed parse, so drop the seeded in-flight rows.+ if err := db.Where("id = ?", "task-1").Delete(&entity.IngestionTask{}).Error; err != nil {+ t.Fatalf("drop seeded ingestion task: %v", err)+ }+ if err := db.Where("id = ?", "task-1").Delete(&entity.Task{}).Error; err != nil {+ t.Fatalf("drop seeded task: %v", err)+ }+ // Prior parse results the rerun must clear, and a finished progress.+ if err := db.Model(&entity.Document{}).Where("id = ?", "doc-1").+ Updates(map[string]interface{}{"token_num": 9, "chunk_num": 4, "progress": 1}).Error; err != nil {+ t.Fatalf("set doc counters: %v", err)+ }+ insertTestPipelineLog(t, "log-1", "doc-1", "kb-1", "tenant-1",+ entity.JSONMap{"components": map[string]interface{}{}})++ svc := testDocumentService(t)+ svc.ingestionTaskSvc.SetTaskPublisher(servicepkg.NewMessageQueueTaskPublisher())++ dsl := map[string]interface{}{+ "components": map[string]interface{}{"c1": map[string]interface{}{"obj": map[string]interface{}{}}},+ }+ if err := svc.RerunDocument(t.Context(), "tenant-1", "log-1", dsl, "c1"); err != nil {+ t.Fatalf("RerunDocument: %v", err)+ }++ // Counters cleared for the rerun.+ doc, err := svc.documentDAO.GetByID(t.Context(), db, "doc-1")+ if err != nil {+ t.Fatalf("reload doc: %v", err)+ }+ if doc.TokenNum != 0 || doc.ChunkNum != 0 {+ t.Fatalf("doc counters after rerun = token %d chunk %d, want zeros", doc.TokenNum, doc.ChunkNum)+ }++ // The edited DSL is persisted on the log row with the rerun entry point.+ updated, err := svc.pipelineLogDAO.GetByID(t.Context(), db, "log-1")+ if err != nil {+ t.Fatalf("reload log: %v", err)+ }+ path, _ := updated.DSL["path"].([]interface{})+ if len(path) != 1 || path[0] != "c1" {+ t.Fatalf("log dsl path = %v, want [c1]", updated.DSL["path"])+ }++ // The enqueue actually landed on tasks.RAGFLOW.+ handles, err := mq.GetMessages(1)+ if err != nil {+ t.Fatalf("GetMessages: %v", err)+ }+ if len(handles) != 1 {+ t.Fatalf("expected 1 message on tasks.RAGFLOW, got %d", len(handles))+ }+ defer func() { _ = handles[0].Ack() }()+ taskMsg := handles[0].GetMessage()+ if taskMsg.TaskType != common.TaskTypeIngestionTask {+ t.Fatalf("message task type = %s, want %s", taskMsg.TaskType, common.TaskTypeIngestionTask)+ }++ // ...and the referenced task row exists, already SCHEDULED.+ task, err := svc.ingestionTaskDAO.GetByID(t.Context(), db, taskMsg.TaskID)+ if err != nil {+ t.Fatalf("load enqueued ingestion task %s: %v", taskMsg.TaskID, err)+ }+ if task.DocumentID != "doc-1" || task.DatasetID != "kb-1" || task.Status != common.SCHEDULED {+ t.Fatalf("ingestion task = %+v", task)+ }+}diff --git a/internal/service/document/document_rerun_test.go b/internal/service/document/document_rerun_test.gonew file mode 100644index 0000000000..853ab11dc9--- /dev/null+++ b/internal/service/document/document_rerun_test.go@@ -0,0 +1,188 @@+package document++import (+ "errors"+ "strings"+ "testing"++ "ragflow/internal/common"+ "ragflow/internal/dao"+ "ragflow/internal/entity"+)++func insertTestPipelineLog(t *testing.T, id, docID, kbID, tenantID string, dsl entity.JSONMap) {+ t.Helper()+ opLog := &entity.PipelineOperationLog{+ ID: id,+ DocumentID: docID,+ TenantID: tenantID,+ KbID: kbID,+ ParserID: "pipeline",+ DocumentName: "hlm.docx",+ DocumentSuffix: ".docx",+ DocumentType: "docx",+ SourceFrom: "local",+ TaskType: "parse",+ OperationStatus: "done",+ DSL: dsl,+ }+ if err := dao.DB.Create(opLog).Error; err != nil {+ t.Fatalf("insert test pipeline log: %v", err)+ }+}++func rerunTestService(t *testing.T) (*DocumentService, *recordingTaskPublisher) {+ t.Helper()+ svc := testDocumentService(t)+ publisher := &recordingTaskPublisher{}+ svc.ingestionTaskSvc.SetTaskPublisher(publisher)+ return svc, publisher+}++func TestRerunDocument_UnknownLogID(t *testing.T) {+ db := setupServiceTestDB(t)+ pushServiceDB(t, db)++ svc, _ := rerunTestService(t)+ err := svc.RerunDocument(t.Context(), "tenant-1", "missing-log", entity.JSONMap{"components": struct{}{}}, "c1")+ if err != ErrRerunDocumentNotFound {+ t.Fatalf("err = %v, want ErrRerunDocumentNotFound", err)+ }+}++func TestRerunDocument_InaccessibleDocument(t *testing.T) {+ db := setupServiceTestDB(t)+ pushServiceDB(t, db)++ insertTestKB(t, "kb-1", "tenant-1", 0, 0, 0)+ insertTestDoc(t, "doc-1", "kb-1", 9, 4)+ insertTestPipelineLog(t, "log-1", "doc-1", "kb-1", "tenant-1", nil)++ // No user_tenant row joins "stranger" to tenant-1 and the kb is owned+ // by tenant-1, so Accessible must deny.+ svc, _ := rerunTestService(t)+ err := svc.RerunDocument(t.Context(), "stranger", "log-1", entity.JSONMap{"components": struct{}{}}, "c1")+ if err != ErrRerunDocumentNotFound {+ t.Fatalf("err = %v, want ErrRerunDocumentNotFound", err)+ }+}++func TestRerunDocument_DocumentProcessing(t *testing.T) {+ db := setupServiceTestDB(t)+ pushServiceDB(t, db)++ insertTestKB(t, "kb-1", "tenant-1", 0, 0, 0)+ insertTestDoc(t, "doc-1", "kb-1", 9, 4)+ if err := dao.DB.Model(&entity.Document{}).Where("id = ?", "doc-1").Update("progress", 0.5).Error; err != nil {+ t.Fatalf("set progress: %v", err)+ }+ insertTestPipelineLog(t, "log-1", "doc-1", "kb-1", "tenant-1", nil)++ svc, _ := rerunTestService(t)+ err := svc.RerunDocument(t.Context(), "tenant-1", "log-1", entity.JSONMap{"components": struct{}{}}, "c1")+ if err == nil || !strings.Contains(err.Error(), "is processing") {+ t.Fatalf("err = %v, want 'is processing' message", err)+ }+ // The handler classifies via errors.As, so pin the typed contract.+ var processingErr *RerunDocumentProcessingError+ if !errors.As(err, &processingErr) {+ t.Fatalf("err = %T, want RerunDocumentProcessingError", err)+ }+}++func TestRerunDocument_RerunsAndPersistsDSL(t *testing.T) {+ db := setupServiceTestDB(t)+ pushServiceDB(t, db)++ insertTestKB(t, "kb-1", "tenant-1", 1, 9, 4)+ insertTestDoc(t, "doc-1", "kb-1", 9, 4)+ // GetDocumentStorageAddress requires a non-empty document location.+ if err := dao.DB.Model(&entity.Document{}).Where("id = ?", "doc-1").Update("location", "loc-1").Error; err != nil {+ t.Fatalf("set location: %v", err)+ }+ insertTestPipelineLog(t, "log-1", "doc-1", "kb-1", "tenant-1", entity.JSONMap{"components": map[string]interface{}{}})++ svc, publisher := rerunTestService(t)+ dsl := map[string]interface{}{+ "components": map[string]interface{}{"c1": map[string]interface{}{"obj": map[string]interface{}{}}},+ }+ if err := svc.RerunDocument(t.Context(), "tenant-1", "log-1", dsl, "c1"); err != nil {+ t.Fatalf("RerunDocument: %v", err)+ }++ // The caller's DSL map is not mutated in place.+ if _, ok := dsl["path"]; ok {+ t.Fatalf("caller dsl was mutated in place: %v", dsl)+ }++ // The edited DSL is persisted on the log with the rerun entry point.+ updated, err := svc.pipelineLogDAO.GetByID(t.Context(), db, "log-1")+ if err != nil {+ t.Fatalf("reload log: %v", err)+ }+ path, _ := updated.DSL["path"].([]interface{})+ if len(path) != 1 || path[0] != "c1" {+ t.Fatalf("log dsl path = %v, want [c1]", updated.DSL["path"])+ }+ if _, ok := updated.DSL["components"]; !ok {+ t.Fatalf("log dsl lost its components: %v", updated.DSL)+ }++ // A fresh ingestion task is enqueued for the document.+ if len(publisher.messages) != 1 {+ t.Fatalf("expected 1 published message, got %d", len(publisher.messages))+ }+ task, err := svc.ingestionTaskDAO.GetByID(t.Context(), db, publisher.messages[0].TaskID)+ if err != nil {+ t.Fatalf("load ingestion task: %v", err)+ }+ // CreateAndEnqueue marks the task SCHEDULED once its queue message has+ // been published (the publisher here records instead of failing), so the+ // persisted row is already past CREATED by the time we reload it.+ if task.DocumentID != "doc-1" || task.DatasetID != "kb-1" || task.Status != common.SCHEDULED {+ t.Fatalf("ingestion task = %+v", task)+ }++ // Prior counters are cleared for the rerun.+ doc, err := svc.documentDAO.GetByID(t.Context(), db, "doc-1")+ if err != nil {+ t.Fatalf("reload doc: %v", err)+ }+ if doc.TokenNum != 0 || doc.ChunkNum != 0 {+ t.Fatalf("doc counters after rerun = token %d chunk %d, want zeros", doc.TokenNum, doc.ChunkNum)+ }+}++func TestRerunDocument_EmptyDSLPersistsEntryPath(t *testing.T) {+ db := setupServiceTestDB(t)+ pushServiceDB(t, db)++ insertTestKB(t, "kb-1", "tenant-1", 1, 9, 4)+ insertTestDoc(t, "doc-1", "kb-1", 9, 4)+ // GetDocumentStorageAddress requires a non-empty document location.+ if err := dao.DB.Model(&entity.Document{}).Where("id = ?", "doc-1").Update("location", "loc-1").Error; err != nil {+ t.Fatalf("set location: %v", err)+ }+ insertTestPipelineLog(t, "log-1", "doc-1", "kb-1", "tenant-1", entity.JSONMap{"components": map[string]interface{}{}})++ svc, publisher := rerunTestService(t)+ if err := svc.RerunDocument(t.Context(), "tenant-1", "log-1", entity.JSONMap{}, "c1"); err != nil {+ t.Fatalf("RerunDocument: %v", err)+ }++ // An empty but non-nil dsl is still persisted, with the rerun entry+ // point recorded on the log row.+ updated, err := svc.pipelineLogDAO.GetByID(t.Context(), db, "log-1")+ if err != nil {+ t.Fatalf("reload log: %v", err)+ }+ path, _ := updated.DSL["path"].([]interface{})+ if len(path) != 1 || path[0] != "c1" {+ t.Fatalf("log dsl path = %v, want [c1]", updated.DSL["path"])+ }++ // The rerun itself is still enqueued.+ if len(publisher.messages) != 1 {+ t.Fatalf("expected 1 published message, got %d", len(publisher.messages))+ }+}diff --git a/internal/service/document/document_test.go b/internal/service/document/document_test.goindex 127d3921e8..ca7c5785b9 100644--- a/internal/service/document/document_test.go+++ b/internal/service/document/document_test.go@@ -458,6 +458,7 @@ func setupServiceTestDBWithDSN(t *testing.T, dsn string) *gorm.DB {if err = db.AutoMigrate(&entity.Document{},&entity.Knowledgebase{},+ &entity.PipelineOperationLog{},&entity.Task{},&entity.IngestionTask{},&entity.IngestionTaskLog{},@@ -494,6 +495,7 @@ func testDocumentService(t *testing.T) *DocumentService {file2DocumentDAO: dao.NewFile2DocumentDAO(),fileDAO: dao.NewFileDAO(),ingestionTaskDAO: dao.NewIngestionTaskDAO(),+ pipelineLogDAO: dao.NewPipelineOperationLogDAO(),ingestionTaskSvc: service.NewIngestionTaskService(),docEngine: nil,metadataSvc: nil, // nil engine → metadata ops skipped