Repository navigation
Go: add context - #17314
Go: add context#17314
Conversation
Signed-off-by: Jin Hai <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis refactor propagates request and execution contexts through handlers, services, ingestion workflows, document operations, file flows, and DAO queries. Document persistence now uses explicit database handles with ChangesContext propagation refactor
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 9
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (15)
internal/ingestion/service/progress_sink.go (1)
53-95: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftPropagate
ctxthrough all progress-service operations.
ctxis accepted by the sink but only reachesUpdateRunProgress.UpdateComponentTotal,RecordComponentProgress, andAggregateTaskProgressremain contextless, so cancellation cannot stop most progress database work. Update those service/DAO contracts and pass the caller context through them as well.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/ingestion/service/progress_sink.go` around lines 53 - 95, Propagate the caller context through the progress update path: update the contracts and implementations for UpdateComponentTotal, RecordComponentProgress, and AggregateTaskProgress, including their DAO calls, to accept and use context.Context. In OnComponentTotal and OnComponentProgress, pass the existing ctx to each corresponding taskSvc operation while preserving current error handling and aggregation behavior.internal/ingestion/service/ingestion_service.go (1)
610-640: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winUse a bounded status-update context that survives task cancellation.
runTaskinvokes these helpers after the per-task context is canceled, and that context derives frome.ctx. During ingestor shutdown,e.ctxis already canceled, so the new document fetch/update calls immediately fail and leave progress stale. Use a short-lived persistence context for both cancellation and timeout markers.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/ingestion/service/ingestion_service.go` around lines 610 - 640, The markCancelProgress and markTimeoutProgress helpers currently use the canceled e.ctx for document persistence. Create a short-lived bounded context independent of task cancellation within each helper, use it for GetDocumentByID and UpdateRunProgress, and ensure it is released after the operation while preserving the existing marker messages and statuses.internal/ingestion/component/document_storage.go (1)
84-100: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftPropagate
ctxthrough every storage lookup.Only
DocumentDAO.GetByIDuses the supplied context.GetByDocumentIDand the file DAO lookup remain contextless, so cancellation and tracing stop before resolving file-backed documents. Update those DAO contracts and calls to use the same context-bound database handle.🤖 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/component/document_storage.go` around lines 84 - 100, Update ResolveDocumentStorage and the relevant DAO contracts so every lookup uses the supplied ctx, including NewFile2DocumentDAO().GetByDocumentID and NewFileDAO().GetByID. Pass the context-bound database handle consistently, matching the existing DocumentDAO.GetByID pattern, while preserving the current document and file resolution behavior.internal/service/document/document_parse.go (3)
317-354: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
docEngine.DeleteChunksstill usescontext.Background()inresetDocumentForReparse.The function now accepts
ctxand uses it fordocumentDAO.UpdateByID(line 332), but thedocEngine.DeleteChunkscall (line 347) still usescontext.Background(). See consolidated comment.🤖 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/document_parse.go` around lines 317 - 354, Update resetDocumentForReparse to pass its ctx parameter to docEngine.DeleteChunks instead of creating a context.Background(), preserving the existing deletion arguments and error handling.
449-471: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
docEngine.UpdateChunksstill usescontext.Background()inupdateDocumentStatusOnly.Same pattern:
ctxis used fordocumentDAO.UpdateByID(line 455) but the subsequentdocEngine.UpdateChunkscall (lines 464-465) hardcodescontext.Background(). See consolidated comment.🤖 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/document_parse.go` around lines 449 - 471, Replace the hardcoded context.Background() passed to docEngine.UpdateChunks in updateDocumentStatusOnly with the method’s existing ctx parameter, preserving cancellation and request-scoped context through the document status update flow.
174-240: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick winRemove commented-out dead code.
Lines 216-235 contain a large block of commented-out task-creation logic (
entity.IngestionTaskconstruction,ingestionTaskDAO.Create) that is dead and unrelated to the currentParseDocumentsimplementation.As per coding guidelines: "Remove dead tests, commented-out code, stale documentation, and “move later” notes." and "Remove commented-out Go code and keep package and documentation comments aligned with the current runtime path rather than migration history."
🗑️ Proposed fix
- // create task for each document - //task := &entity.IngestionTask{ - // ID: utility.GenerateToken(), - // DocumentID: docID, - // UserID: userID, - //} - - // save the task to database - //err = s.ingestionTaskDAO.Create(task) - //if err != nil { - // errorMessage := err.Error() - // responses = append(responses, &service.ParseDocumentResponse{ - // DocumentID: docID, - // Result: &errorMessage, - // }) - // continue - //} - - // Send task to message queue - }🤖 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/document_parse.go` around lines 174 - 240, Remove the commented-out task creation and database persistence block inside ParseDocuments, including the unused entity.IngestionTask and ingestionTaskDAO.Create references, while leaving the surrounding document validation and message-queue flow unchanged.Source: Coding guidelines
internal/service/document/document_ingest.go (1)
34-149: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
docEngine.ChunkStoreExists/DeleteChunksstill usecontext.Background()insideIngest.
Ingestnow acceptsctxand threads it throughdocumentDAO,StartParseDocuments, andCancelDocParsecalls, but the delete-only cleanup path (lines 133, 139) still callsdocEngine.ChunkStoreExists/DeleteChunkswithcontext.Background(). See consolidated comment for the broader pattern across files.🤖 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/document_ingest.go` around lines 34 - 149, Update the delete-only cleanup path in DocumentService.Ingest to pass the method’s ctx to docEngine.ChunkStoreExists and docEngine.DeleteChunks instead of context.Background(). Preserve the existing index, knowledgebase, and deletion behavior while ensuring request cancellation and deadlines propagate through both calls.internal/service/chunk/chunk.go (2)
75-102: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick winDuplicate
ChunkServiceimplementation vs.internal/service/chunk_types.go.This package defines a second
ChunkServicetype with largely overlapping responsibilities (parse/stop-parse/list/switch/update/remove/add chunks) to theservice.ChunkServiceinchunk_types.go. Both were independently updated with ctx propagation in this PR, and have already diverged (e.g.,UpdateChunkhere lacksctxwhilechunk_types.go's has it). See consolidated comment.As per coding guidelines: "Prefer deletion over compatibility shims, deprecated branches, wrapper APIs, and dual-track migration notes; converge coexisting implementations to one path unless an external contract requires compatibility."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/chunk/chunk.go` around lines 75 - 102, Remove the duplicate ChunkService definition and its associated implementation in the chunk package, retaining the canonical service. Update affected callers to use service.ChunkService from chunk_types.go, preserving its context-aware method signatures and behavior; do not add wrappers or compatibility shims.Source: Coding guidelines
1026-1062: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
UpdateChunkstill usescontext.Background()instead of a caller-supplied context.Unlike every other method touched in this refactor (
StopParsing,List,SwitchChunks,RemoveChunks,Parse,AddChunk),UpdateChunkwas not given actx context.Contextparameter — it still buildsctx := context.Background()(line 1035) and threads that fake context into the now ctx-awaredocDAO.GetByID(line 1061),docEngine.GetChunk, anddocEngine.UpdateChunkscalls. This defeats request cancellation/timeout propagation for this entire method, and is inconsistent with the sibling implementation ofUpdateChunkininternal/service/chunk_types.go, which does acceptctx.🔧 Proposed fix
-func (s *ChunkService) UpdateChunk(req *service.UpdateChunkRequest, userID string) error { +func (s *ChunkService) UpdateChunk(ctx context.Context, req *service.UpdateChunkRequest, userID string) error { if s.docEngine == nil { return fmt.Errorf("doc engine not initialized") } if req.ChunkID == "" { return fmt.Errorf("chunk_id is required") } - ctx := context.Background() - // Get user's tenants🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/chunk/chunk.go` around lines 1026 - 1062, Update ChunkService.UpdateChunk to accept a caller-supplied context.Context parameter, remove the locally created context.Background(), and propagate the supplied context to docDAO.GetByID, docEngine.GetChunk, and docEngine.UpdateChunks. Keep the existing update behavior unchanged and align its signature and context handling with the sibling UpdateChunk implementation in chunk_types.go.internal/service/document/document_dataset_update.go (2)
345-373: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
docEngine.UpdateChunksstill usescontext.Background()inupdateDocumentNameOnly.Same pattern as elsewhere in this file: the DAO update (line 346) is ctx-aware, but the subsequent
docEngine.UpdateChunkscall (lines 362-372) is not. See consolidated comment.🤖 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/document_dataset_update.go` around lines 345 - 373, Update updateDocumentNameOnly so docEngine.UpdateChunks receives the method’s ctx instead of context.Background(), preserving the caller’s cancellation and request context while leaving the existing update flow unchanged.
22-109: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
docEngine.UpdateChunksstill usescontext.Background()inside a now-ctx-aware function.
BatchUpdateDocumentStatuswas updated to acceptctxand threads it correctly intodocumentDAO.UpdateByIDcalls (lines 70, 78, 91), but thedocEngine.UpdateChunkscall sandwiched between them (lines 83-84) still hardcodescontext.Background(). See consolidated comment for the broader pattern.🤖 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/document_dataset_update.go` around lines 22 - 109, Replace context.Background() in BatchUpdateDocumentStatus when calling docEngine.UpdateChunks with the function’s incoming ctx. Preserve the existing UpdateChunks arguments and error-handling behavior while ensuring cancellation and deadlines propagate through the document engine operation.internal/service/chunk_types.go (1)
256-327: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
docEngine.ChunkStoreExists/DeleteChunksstill usecontext.Background()despitectxnow being available.
StopParsingwas updated to acceptctxand thread it throughdocumentDAOcalls, but thedocEngine.ChunkStoreExists(line 303) anddocEngine.DeleteChunks(line 308) calls in the same loop still usecontext.Background(), losing cancellation/deadline propagation for what is likely the most expensive operation in this path. See consolidated comment for the broader pattern across files.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/chunk_types.go` around lines 256 - 327, Update the docEngine.ChunkStoreExists and docEngine.DeleteChunks calls inside ChunkService.StopParsing to pass the method’s ctx instead of context.Background(). Preserve the existing operation order, error handling, and index/deletion arguments while ensuring cancellation and deadlines propagate through both chunk-store operations.internal/service/document/file2document.go (1)
150-159: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winDetach the conversion job from the request context.
LinkToDatasetslaunchesconvertFilesin a goroutine, butinternal/handler/file.gopassesc.Request.Context()and returns immediately. After the handler returns, that context is canceled, which can abort later cancellation-sensitive work in the background job, especially afterDeleteByFileIDin replace mode. Use a job-owned context with an explicit lifecycle for this fire-and-forget task.🤖 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/file2document.go` around lines 150 - 159, Update the background conversion launched by LinkToDatasets to use a job-owned context rather than the request-derived ctx, so it remains valid after the handler returns. Create and manage the job context within the goroutine or task lifecycle, pass it to convertFiles, and ensure cancellation/cleanup is explicit without changing the existing error logging.internal/service/document/document_metadata.go (1)
38-51: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winPreserve the caller context when editing document-engine state.
The lookup uses
ctx, but metadata edits/delete cleanup switch tocontext.Background()orctx == nil, so cancelled calls can continue engine work. Forward the caller context through these boundaries:
SetDocumentMetadata: passctxtoUpdateMetadata.DeleteDocumentMetadata: passctxtoDeleteMetadataKeys.DeleteDocumentAllMetadata: passctxtoDeleteMetadata.deleteDocEngineData: acceptctxas a parameter and forward it to chunk deletion and metadata cleanup.🤖 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/document_metadata.go` around lines 38 - 51, Preserve the caller context across document-engine operations: in internal/service/document/document_metadata.go:38-51, pass ctx to DocumentService.SetDocumentMetadata’s UpdateMetadata call; at 59-73 and 82-102, pass ctx to DeleteMetadataKeys and DeleteMetadata. In internal/service/document/document_crud.go:341-351, update deleteDocEngineData to accept ctx and forward it to chunk deletion and metadata cleanup, removing context.Background() or nil-context usage.internal/service/dataset/index.go (1)
265-301: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winAttach
ctxto the direct GORM persistence in the delete path.
DeleteDocument/RemoveDocumentKeepFilepassctxinto resolver/engine work, but the final persistence deletes counters viadeleteDocRecordWithCounters(doc, kbID), which still startsdao.DB.Transaction(...)without context. Passctxthrough this helper and begin the transaction withdao.DB.WithContext(ctx).🤖 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/dataset/index.go` around lines 265 - 301, Update deleteDocRecordWithCounters to accept ctx and start its GORM transaction through dao.DB.WithContext(ctx). Propagate ctx from DeleteDocument and RemoveDocumentKeepFile at internal/service/document/document_crud.go lines 142-167, 191-203, and 235-236; internal/service/dataset/index.go lines 265-301 requires no direct change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/admin/service.go`:
- Line 562: Update the transaction setup surrounding the document deletion flow
to begin with dao.DB.WithContext(ctx).Begin(), and pass the resulting tx to
GetAllDocIDsByKBIDs instead of dao.DB. Ensure the document ID lookup in the
deletion path uses the same transaction before continuing with deletion.
In `@internal/handler/agent.go`:
- Around line 52-59: Remove migration-history references from the documentation:
in internal/handler/agent.go lines 52-59, rewrite the UploadInfos and
UploadFromURL comments to describe their current upload behavior without
“Mirrors python” wording; in internal/dao/document.go lines 477-479, describe
collision-free filename lookup directly without referencing Python’s
duplicate_name.
In `@internal/handler/document.go`:
- Around line 1231-1232: Update DocumentService.SetDocumentMetadata to pass its
received ctx to docEngine.UpdateMetadata instead of context.Background(),
preserving request cancellation and deadlines during the metadata write.
- Around line 66-69: The document-service context contract is inconsistent
across the interface, concrete service, fake, and callers. In
internal/handler/document.go lines 66-69, add context.Context to
GetDocumentByID, DeleteDocumentMetadata, and DeleteDocumentAllMetadata; in
internal/handler/document_test.go line 138 and all related fake metadata
methods, accept the same ctx parameter and update affected handler calls to pass
request context.
In `@internal/ingestion/service/doc_state.go`:
- Around line 33-35: Update the downstream implementations of IncrementChunkNum
and SetDocumentMetadata to honor the caller-provided ctx: pass ctx to the
database transaction instead of using dao.DB.Transaction without context, and
pass ctx to docEngine.UpdateMetadata instead of context.Background(). Preserve
the existing write behavior while ensuring cancellation and tracing propagate
through both operations.
In `@internal/ingestion/task/task_context.go`:
- Around line 60-61: Update LoadFromIngestionTask’s returned TaskContext literal
to assign its Ctx field from the function’s ctx parameter, preserving
cancellation and deadline propagation for downstream ingestion steps.
In `@internal/service/document/document_upload.go`:
- Around line 4-10: Update the no-CGO parser stubs in office_parsers_no_cgo.go
to match the context-first ParseResultProducer.ParseWithResult contract, using
the signature (ctx context.Context, filename string, _ []byte) and preserving
their existing stub behavior; alternatively, delete these dead build-specific
stubs if they are no longer required.
In `@internal/service/file/file_url.go`:
- Line 24: Update UploadFromURL and the utility.FetchRemoteFileSafely call to
propagate ctx through the remote-download path, extending the fetch helper as
needed and applying the context to its HTTP request. Preserve the existing
download and quota-check behavior while ensuring cancellation or expiration
stops the in-flight request.
In `@internal/service/ingestion_task_service.go`:
- Around line 77-85: Propagate the caller’s ctx through the full ingestion task
lifecycle: update CreateAndEnqueue, rollback handling, StartRunning, GetTask,
transition, state checks, and all DAO/publisher calls to use context-aware
variants. Preserve an explicitly detached context only for side effects that
must outlive cancellation, and ensure CreateForDocuments remains consistent with
these lifecycle operations.
---
Outside diff comments:
In `@internal/ingestion/component/document_storage.go`:
- Around line 84-100: Update ResolveDocumentStorage and the relevant DAO
contracts so every lookup uses the supplied ctx, including
NewFile2DocumentDAO().GetByDocumentID and NewFileDAO().GetByID. Pass the
context-bound database handle consistently, matching the existing
DocumentDAO.GetByID pattern, while preserving the current document and file
resolution behavior.
In `@internal/ingestion/service/ingestion_service.go`:
- Around line 610-640: The markCancelProgress and markTimeoutProgress helpers
currently use the canceled e.ctx for document persistence. Create a short-lived
bounded context independent of task cancellation within each helper, use it for
GetDocumentByID and UpdateRunProgress, and ensure it is released after the
operation while preserving the existing marker messages and statuses.
In `@internal/ingestion/service/progress_sink.go`:
- Around line 53-95: Propagate the caller context through the progress update
path: update the contracts and implementations for UpdateComponentTotal,
RecordComponentProgress, and AggregateTaskProgress, including their DAO calls,
to accept and use context.Context. In OnComponentTotal and OnComponentProgress,
pass the existing ctx to each corresponding taskSvc operation while preserving
current error handling and aggregation behavior.
In `@internal/service/chunk_types.go`:
- Around line 256-327: Update the docEngine.ChunkStoreExists and
docEngine.DeleteChunks calls inside ChunkService.StopParsing to pass the
method’s ctx instead of context.Background(). Preserve the existing operation
order, error handling, and index/deletion arguments while ensuring cancellation
and deadlines propagate through both chunk-store operations.
In `@internal/service/chunk/chunk.go`:
- Around line 75-102: Remove the duplicate ChunkService definition and its
associated implementation in the chunk package, retaining the canonical service.
Update affected callers to use service.ChunkService from chunk_types.go,
preserving its context-aware method signatures and behavior; do not add wrappers
or compatibility shims.
- Around line 1026-1062: Update ChunkService.UpdateChunk to accept a
caller-supplied context.Context parameter, remove the locally created
context.Background(), and propagate the supplied context to docDAO.GetByID,
docEngine.GetChunk, and docEngine.UpdateChunks. Keep the existing update
behavior unchanged and align its signature and context handling with the sibling
UpdateChunk implementation in chunk_types.go.
In `@internal/service/dataset/index.go`:
- Around line 265-301: Update deleteDocRecordWithCounters to accept ctx and
start its GORM transaction through dao.DB.WithContext(ctx). Propagate ctx from
DeleteDocument and RemoveDocumentKeepFile at
internal/service/document/document_crud.go lines 142-167, 191-203, and 235-236;
internal/service/dataset/index.go lines 265-301 requires no direct change.
In `@internal/service/document/document_dataset_update.go`:
- Around line 345-373: Update updateDocumentNameOnly so docEngine.UpdateChunks
receives the method’s ctx instead of context.Background(), preserving the
caller’s cancellation and request context while leaving the existing update flow
unchanged.
- Around line 22-109: Replace context.Background() in BatchUpdateDocumentStatus
when calling docEngine.UpdateChunks with the function’s incoming ctx. Preserve
the existing UpdateChunks arguments and error-handling behavior while ensuring
cancellation and deadlines propagate through the document engine operation.
In `@internal/service/document/document_ingest.go`:
- Around line 34-149: Update the delete-only cleanup path in
DocumentService.Ingest to pass the method’s ctx to docEngine.ChunkStoreExists
and docEngine.DeleteChunks instead of context.Background(). Preserve the
existing index, knowledgebase, and deletion behavior while ensuring request
cancellation and deadlines propagate through both calls.
In `@internal/service/document/document_metadata.go`:
- Around line 38-51: Preserve the caller context across document-engine
operations: in internal/service/document/document_metadata.go:38-51, pass ctx to
DocumentService.SetDocumentMetadata’s UpdateMetadata call; at 59-73 and 82-102,
pass ctx to DeleteMetadataKeys and DeleteMetadata. In
internal/service/document/document_crud.go:341-351, update deleteDocEngineData
to accept ctx and forward it to chunk deletion and metadata cleanup, removing
context.Background() or nil-context usage.
In `@internal/service/document/document_parse.go`:
- Around line 317-354: Update resetDocumentForReparse to pass its ctx parameter
to docEngine.DeleteChunks instead of creating a context.Background(), preserving
the existing deletion arguments and error handling.
- Around line 449-471: Replace the hardcoded context.Background() passed to
docEngine.UpdateChunks in updateDocumentStatusOnly with the method’s existing
ctx parameter, preserving cancellation and request-scoped context through the
document status update flow.
- Around line 174-240: Remove the commented-out task creation and database
persistence block inside ParseDocuments, including the unused
entity.IngestionTask and ingestionTaskDAO.Create references, while leaving the
surrounding document validation and message-queue flow unchanged.
In `@internal/service/document/file2document.go`:
- Around line 150-159: Update the background conversion launched by
LinkToDatasets to use a job-owned context rather than the request-derived ctx,
so it remains valid after the handler returns. Create and manage the job context
within the goroutine or task lifecycle, pass it to convertFiles, and ensure
cancellation/cleanup is explicit without changing the existing error logging.
🪄 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 Plus
Run ID: b6ee2316-6ecf-4348-ac8b-b6796491ec87
📒 Files selected for processing (42)
internal/admin/handler.gointernal/admin/service.gointernal/dao/database.gointernal/dao/document.gointernal/handler/agent.gointernal/handler/agent_upload.gointernal/handler/chunk.gointernal/handler/dataset.gointernal/handler/document.gointernal/handler/document_test.gointernal/handler/file.gointernal/ingestion/component/chunker/pdfcrop_cgo.gointernal/ingestion/component/document_storage.gointernal/ingestion/component/file.gointernal/ingestion/component/parser.gointernal/ingestion/pipeline/pipeline.gointernal/ingestion/service/doc_state.gointernal/ingestion/service/ingestion_service.gointernal/ingestion/service/progress_sink.gointernal/ingestion/task/task_context.gointernal/service/chunk/chunk.gointernal/service/chunk_types.gointernal/service/dataset/crud.gointernal/service/dataset/index.gointernal/service/dataset/ingestion.gointernal/service/dataset/metadata.gointernal/service/document/document_artifact.gointernal/service/document/document_crud.gointernal/service/document/document_dataset_update.gointernal/service/document/document_ingest.gointernal/service/document/document_list.gointernal/service/document/document_metadata.gointernal/service/document/document_parse.gointernal/service/document/document_upload.gointernal/service/document/file2document.gointernal/service/file/file.gointernal/service/file/file_content.gointernal/service/file/file_folder.gointernal/service/file/file_upload.gointernal/service/file/file_url.gointernal/service/ingestion_task_service.gointernal/service/nlp/retrieval.go
| if len(kbIDs) > 0 { | ||
| // 2. Get document IDs | ||
| docIDs, err := s.documentDAO.GetAllDocIDsByKBIDs(kbIDs) | ||
| docIDs, err := s.documentDAO.GetAllDocIDsByKBIDs(ctx, dao.DB, kbIDs) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Read document IDs through the deletion transaction.
Using dao.DB here places the task-ID lookup outside tx; a concurrently created task can survive after its document is deleted. Start the transaction with dao.DB.WithContext(ctx).Begin() and pass tx 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/admin/service.go` at line 562, Update the transaction setup
surrounding the document deletion flow to begin with
dao.DB.WithContext(ctx).Begin(), and pass the resulting tx to
GetAllDocIDsByKBIDs instead of dao.DB. Ensure the document ID lookup in the
deletion path uses the same transaction before continuing with deletion.
| // UploadInfos stores raw bytes in the per-user downloads bucket and | ||
| // returns lightweight descriptors. Mirrors python FileService.upload_info | ||
| // (multi-file path) used by the agent upload endpoint. | ||
| UploadInfos(userID string, files []*multipart.FileHeader) ([]map[string]interface{}, error) | ||
| UploadInfos(ctx context.Context, userID string, files []*multipart.FileHeader) ([]map[string]interface{}, error) | ||
| // UploadFromURL downloads a remote file (with SSRF protection) and | ||
| // stores it as an info blob. Mirrors python FileService.upload_info | ||
| // (single-file path with ?url=) used by the agent upload endpoint. | ||
| UploadFromURL(tenantID, rawURL string) (map[string]interface{}, error) | ||
| UploadFromURL(ctx context.Context, tenantID, rawURL string) (map[string]interface{}, error) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Remove Python migration references from Go documentation.
internal/handler/agent.go#L52-L59: describe the current upload behavior without “Mirrors python” wording.internal/dao/document.go#L477-L479: describe collision-free filename lookup without referring to Python’sduplicate_name.
As per coding guidelines, keep documentation aligned with the current runtime path rather than migration history and remove compatibility wording.
📍 Affects 2 files
internal/handler/agent.go#L52-L59(this comment)internal/dao/document.go#L477-L479
🤖 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/agent.go` around lines 52 - 59, Remove migration-history
references from the documentation: in internal/handler/agent.go lines 52-59,
rewrite the UploadInfos and UploadFromURL comments to describe their current
upload behavior without “Mirrors python” wording; in internal/dao/document.go
lines 477-479, describe collision-free filename lookup directly without
referencing Python’s duplicate_name.
Source: Coding guidelines
| ctx := c.Request.Context() | ||
| err = h.documentService.SetDocumentMetadata(ctx, req.DocID, meta) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Propagate ctx into the metadata engine write.
DocumentService.SetDocumentMetadata receives this context but calls docEngine.UpdateMetadata(context.Background(), ...), so cancellation and deadlines are discarded. Pass ctx instead.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/handler/document.go` around lines 1231 - 1232, Update
DocumentService.SetDocumentMetadata to pass its received ctx to
docEngine.UpdateMetadata instead of context.Background(), preserving request
cancellation and deadlines during the metadata write.
| GetDocumentMetadataByID(ctx context.Context, docID string) (map[string]any, error) | ||
| SetDocumentMetadata(ctx context.Context, docID string, meta map[string]any) error | ||
| IncrementChunkNum(ctx context.Context, docID, kbID string, chunkNum, tokenNum int, duration float64) error |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Make downstream implementations honor the new ctx contract.
The updater now forwards ctx, but the supplied implementations still discard it: IncrementChunkNum uses dao.DB.Transaction(...), while SetDocumentMetadata calls docEngine.UpdateMetadata(context.Background(), ...). Cancellation and tracing therefore do not reach chunk or metadata writes. Bind those operations to the caller context.
Also applies to: 54-63, 72-85
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/ingestion/service/doc_state.go` around lines 33 - 35, Update the
downstream implementations of IncrementChunkNum and SetDocumentMetadata to honor
the caller-provided ctx: pass ctx to the database transaction instead of using
dao.DB.Transaction without context, and pass ctx to docEngine.UpdateMetadata
instead of context.Background(). Preserve the existing write behavior while
ensuring cancellation and tracing propagate through both operations.
| func (s *IngestionTaskService) CreateForDocuments(ctx context.Context, datasetID, userID string, docIDs []string) ([]*ParseDocumentResponse, error) { | ||
| uniqueDocIDs := common.Deduplicate(docIDs) | ||
| if len(uniqueDocIDs) == 0 { | ||
| return nil, fmt.Errorf("no documents to parse") | ||
| } | ||
|
|
||
| responses := make([]*ParseDocumentResponse, 0, len(uniqueDocIDs)) | ||
| for _, docID := range uniqueDocIDs { | ||
| doc, err := s.documentDAO.GetByID(docID) | ||
| doc, err := s.documentDAO.GetByID(ctx, dao.DB, docID) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== files =="
git ls-files | sed -n '/^internal\/service\/ingestion_task_service.go$/p;/^internal\/service\//p' | sort | sed -n '1,200p'
echo "== target file size and relevant sections =="
wc -l internal/service/ingestion_task_service.go
sed -n '1,260p', internal/service/ingestion_task_service.go
echo "== related identifiers =="
rg -n "func .*CreateAndEnqueue|func .*GetTask|func .*transition|func .*StartRunning|GetDocument|ParseDocumentResponse|IngestionTask" internal/service internal -g '*.go' | sed -n '1,240p'Repository: infiniflow/ragflow
Length of output: 6618
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== diff stat =="
git diff --stat || true
echo "== target diff (if any) =="
git diff internal/service/ingestion_task_service.go | sed -n '1,240p' || trueRepository: infiniflow/ragflow
Length of output: 199
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== target file relevant sections =="
sed -n '1,260p' internal/service/ingestion_task_service.go
echo "== line-count and relevant identifiers =="
wc -l internal/service/ingestion_task_service.go
rg -n "CreateAndEnqueue|StartRunning|transition|GetTask|CreateForDocuments|publish|publisher|context|ctx" internal/service/ingestion_task_service.go internal/service -g '*.go' | sed -n '1,300p'Repository: infiniflow/ragflow
Length of output: 43600
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== ingestion task service tail =="
sed -n '280,420p' internal/service/ingestion_task_service.go
echo "== task publisher interface and implementation =="
sed -n '1,220p' internal/service/task_publisher.go
echo "== ingestion task DAO context usage =="
rg -n "type IngestionTaskDAO|func .*IngestionTaskDAO|func .*Create|func .*GetBy|func .*Update\\(|func .*Transition|func .*Delete" internal -g '*ingestion*task*.go' -g '*.go' | sed -n '1,260p'
find internal -path '*ingestion*task*' -type f -name '*.go' -print
sed -n '1,260p' internal/dao/ingestion_task_dao.goRepository: infiniflow/ragflow
Length of output: 38677
Propagate ctx through task lifecycle operations.
CreateForDocuments cancels the document lookup but CreateAndEnqueue and the rollback path use contextless DAO/publisher calls. Likewise, StartRunning uses ctx only for the document mirror while GetTask, transition, and state checks run on contextless method paths. Thread ctx through these service/DAO/publisher operations, or use an explicitly scoped detached context if these lifecycle side effects must outlive the caller’s cancellation.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/service/ingestion_task_service.go` around lines 77 - 85, Propagate
the caller’s ctx through the full ingestion task lifecycle: update
CreateAndEnqueue, rollback handling, StartRunning, GetTask, transition, state
checks, and all DAO/publisher calls to use context-aware variants. Preserve an
explicitly detached context only for side effects that must outlive
cancellation, and ensure CreateForDocuments remains consistent with these
lifecycle operations.
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
internal/service/document/document_artifact.go (1)
17-28: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftPropagate
ctxthrough the lower-layer storage and service contracts.The new
ctxparameters are accepted at the document-service boundary, but the artifact, ingestion-task, and metadata paths still call into non-context-aware APIs such asStorage.Get/ObjExist,ListByUser/RequestStopMany/RemoveMany, and metadata search/tenant lookup. Addctxsupport to those operations and fail fast on canceled context when appropriate.🤖 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/document_artifact.go` around lines 17 - 28, Propagate context through the document service’s lower-layer contracts and calls: update Storage.Get and ObjExist in document_artifact.go, ListByUser/RequestStopMany/RemoveMany in document_artifact.go and document_ingest.go, and metadata search and tenant lookup in document_metadata.go to accept and forward ctx. Add cancellation checks where needed so these paths fail fast when ctx is canceled, while preserving existing behavior otherwise.internal/service/document/document_test.go (1)
1789-1829: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winAdd
ctxtoclearDocumentParseResults.
clearDocumentParseResultsstill usescontext.Background()for the chunk-store ops, and it callss.ingestionTaskDAO.GetByDocumentID(doc.ID)/DeleteIfTerminal(doc.ID)via the currentIngestionTaskDAOimplementation does not accept/propagate a context. Thread it through the helper signature, the test call sites, and the internalStartParseDocumentscall so cancellation/timeout reaches the cleanup path.🤖 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/document_test.go` around lines 1789 - 1829, Update clearDocumentParseResults to accept a context.Context and use it for chunk-store operations and ingestion-task DAO calls. Pass ctx from all test call sites and from StartParseDocuments, ensuring GetByDocumentID and DeleteIfTerminal receive and propagate the same context instead of using context.Background().
🧹 Nitpick comments (3)
internal/dao/document_test.go (1)
53-62: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDelete the obsolete global-DB helper.
These migrations leave
pushDocDBwithout a caller in this test file; remove it rather than retaining a deprecated global-database path. As per coding guidelines, “Remove dead tests, commented-out code, stale documentation, and ‘move later’ notes.”🤖 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/document_test.go` around lines 53 - 62, Remove the obsolete pushDocDB global-DB helper from the document DAO test file, along with any associated dead setup or references, since TestDocumentGetByIDs_Success and the remaining tests now use the explicit database handle.Source: Coding guidelines
internal/handler/searchbot_test.go (1)
44-48: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExpose the received context to context-propagation tests.
Both test doubles accept
ctxbut discard it. Make the callback context-aware and/or record it, then assert a request-context value reaches the retriever.Proposed fix
type mockChunkService struct { - retrievalTestFn func(req *service.RetrievalTestRequest, userID string) (*service.RetrievalTestResponse, error) + retrievalTestFn func(context.Context, *service.RetrievalTestRequest, string) (*service.RetrievalTestResponse, error) + lastCtx context.Context } func (m *mockChunkService) RetrievalTest(ctx context.Context, req *service.RetrievalTestRequest, userID string) (*service.RetrievalTestResponse, error) { + m.lastCtx = ctx m.LastReq = req m.LastUserID = userID if m.retrievalTestFn != nil { - return m.retrievalTestFn(req, userID) + return m.retrievalTestFn(ctx, req, userID) }Also applies to: 470-474
🤖 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/searchbot_test.go` around lines 44 - 48, Update mockChunkService.RetrievalTest and the corresponding second test double to preserve the received ctx, either by storing it on the mock or passing it into retrievalTestFn, then extend the context-propagation test to set a request-context value and assert that the retriever receives it.internal/service/file/file_delete.go (1)
87-87: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDescribe the current invariant instead of Python migration history.
Replace “matching Python behavior” with the current reason for deleting the mapping once after all associated documents are processed. As per coding guidelines, Go comments should reflect the current runtime path rather than migration history.
🤖 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/file/file_delete.go` at line 87, Update the comment in the file deletion flow to describe the current invariant: the file2document mapping is deleted once after all associated documents have been processed. Remove the reference to matching Python behavior while preserving the existing placement and deletion logic.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/service/chunk/chunk.go`:
- Line 132: Propagate ctx through ChunkService methods including RetrievalTest
and the related flows at the referenced call sites: update tenant/knowledge-base
lookups, ingestion-task queries, decrementChunkStats, and getDocumentsByIDsFunc
to accept and use ctx, ensuring DAO queries call db.WithContext(ctx). Remove
contextless alternate paths rather than adding compatibility shims, and update
all implementations and callers to the unified context-aware contracts.
In `@internal/service/file/file_delete.go`:
- Around line 81-84: Update the error branch after RemoveDocumentKeepFile in the
file deletion flow to return immediately when the error is context.Canceled or
context.DeadlineExceeded, preserving the cancellation error for the caller. Keep
the existing logging and subsequent cleanup behavior for other errors.
---
Outside diff comments:
In `@internal/service/document/document_artifact.go`:
- Around line 17-28: Propagate context through the document service’s
lower-layer contracts and calls: update Storage.Get and ObjExist in
document_artifact.go, ListByUser/RequestStopMany/RemoveMany in
document_artifact.go and document_ingest.go, and metadata search and tenant
lookup in document_metadata.go to accept and forward ctx. Add cancellation
checks where needed so these paths fail fast when ctx is canceled, while
preserving existing behavior otherwise.
In `@internal/service/document/document_test.go`:
- Around line 1789-1829: Update clearDocumentParseResults to accept a
context.Context and use it for chunk-store operations and ingestion-task DAO
calls. Pass ctx from all test call sites and from StartParseDocuments, ensuring
GetByDocumentID and DeleteIfTerminal receive and propagate the same context
instead of using context.Background().
---
Nitpick comments:
In `@internal/dao/document_test.go`:
- Around line 53-62: Remove the obsolete pushDocDB global-DB helper from the
document DAO test file, along with any associated dead setup or references,
since TestDocumentGetByIDs_Success and the remaining tests now use the explicit
database handle.
In `@internal/handler/searchbot_test.go`:
- Around line 44-48: Update mockChunkService.RetrievalTest and the corresponding
second test double to preserve the received ctx, either by storing it on the
mock or passing it into retrievalTestFn, then extend the context-propagation
test to set a request-context value and assert that the retriever receives it.
In `@internal/service/file/file_delete.go`:
- Line 87: Update the comment in the file deletion flow to describe the current
invariant: the file2document mapping is deleted once after all associated
documents have been processed. Remove the reference to matching Python behavior
while preserving the existing placement and deletion logic.
🪄 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 Plus
Run ID: 2b24fd2e-bd67-49b5-a84d-ff48b38fd374
📒 Files selected for processing (40)
internal/dao/document_test.gointernal/handler/agent.gointernal/handler/agent_attachment.gointernal/handler/agent_download.gointernal/handler/agent_download_test.gointernal/handler/bot_test.gointernal/handler/chat.gointernal/handler/chunk.gointernal/handler/chunk_test.gointernal/handler/dify_retrieval_handler.gointernal/handler/dify_retrieval_handler_test.gointernal/handler/document.gointernal/handler/document_test.gointernal/handler/mindmap.gointernal/handler/searchbot.gointernal/handler/searchbot_test.gointernal/ingestion/pipeline/pipeline_test.gointernal/ingestion/service/doc_state_test.gointernal/ingestion/service/execute_task_test.gointernal/ingestion/service/progress_sink_test.gointernal/ingestion/task/pipeline_e2e_test.gointernal/ingestion/task/pipeline_executor_test.gointernal/ingestion/task/task_context_test.gointernal/service/ask_service.gointernal/service/ask_service_test.gointernal/service/chunk/chunk.gointernal/service/chunk/chunk_test.gointernal/service/dataset/metadata_config_test.gointernal/service/dataset/task_cleanup_test.gointernal/service/document/document_artifact.gointernal/service/document/document_crud.gointernal/service/document/document_ingest.gointernal/service/document/document_list.gointernal/service/document/document_metadata.gointernal/service/document/document_test.gointernal/service/document/document_upload.gointernal/service/file/file_content.gointernal/service/file/file_delete.gointernal/service/file/file_test.gointernal/service/ingestion_task_service_test.go
🚧 Files skipped from review as they are similar to previous changes (6)
- internal/handler/agent.go
- internal/service/file/file_content.go
- internal/service/document/document_upload.go
- internal/service/document/document_list.go
- internal/service/document/document_crud.go
- internal/handler/chunk.go
| // 7. knowledge graph retrieval (not implemented) | ||
| // 8. Apply retrieval by children to group child chunks under parent chunks | ||
| func (s *ChunkService) RetrievalTest(req *service.RetrievalTestRequest, userID string) (*service.RetrievalTestResponse, error) { | ||
| func (s *ChunkService) RetrievalTest(ctx context.Context, req *service.RetrievalTestRequest, userID string) (*service.RetrievalTestResponse, error) { |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Make context propagation end-to-end.
These methods accept ctx, but tenant/knowledge-base lookups, ingestion-task queries, and decrementChunkStats still use contextless paths. A canceled request can therefore continue database and state-changing work after its deadline. The injected getDocumentsByIDsFunc also drops ctx.
Update the owning DAO/service contracts and injection hook to accept and use ctx (including db.WithContext(ctx)), or remove the contextless alternate path. As per coding guidelines, prefer deletion over compatibility shims and converge coexisting implementations to one path.
Also applies to: 505-505, 598-598, 698-703, 705-705, 961-961, 1022-1022, 1161-1161
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/service/chunk/chunk.go` at line 132, Propagate ctx through
ChunkService methods including RetrievalTest and the related flows at the
referenced call sites: update tenant/knowledge-base lookups, ingestion-task
queries, decrementChunkStats, and getDocumentsByIDsFunc to accept and use ctx,
ensuring DAO queries call db.WithContext(ctx). Remove contextless alternate
paths rather than adding compatibility shims, and update all implementations and
callers to the unified context-aware contracts.
Source: Coding guidelines
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (7)
internal/utility/upload.go (1)
41-54: 🩺 Stability & Availability | 🟠 MajorAttach
ctxto the outbound HTTP request.
FetchRemoteFileSafelyaccepts a context, butclient.Get(currentURL)ignores it. Consequently, cancellation and request deadlines do not stop an in-flight remote download. Build the request withhttp.NewRequestWithContextand execute it withclient.Do; add a focused cancellation test.Proposed fix
- resp, err := client.Get(currentURL) // `#nosec` G107 + req, err := http.NewRequestWithContext(ctx, http.MethodGet, currentURL, nil) + if err != nil { + return nil, nil, "", fmt.Errorf("failed to create request: %w", err) + } + resp, err := client.Do(req) // `#nosec` G107🤖 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/utility/upload.go` around lines 41 - 54, Update FetchRemoteFileSafely to create the outbound request with http.NewRequestWithContext using ctx and currentURL, then execute it through client.Do instead of client.Get; preserve the existing safety and redirect handling, and add a focused test verifying cancellation stops the request.internal/service/file/file_delete.go (2)
59-86: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftAvoid deleting storage before cancellable document cleanup.
storageImpl.Removeruns beforeRemoveDocumentKeepFile(ctx). If document removal is canceled, the new early return leaves database rows pointing to a storage object that was already deleted. Perform storage deletion after successful database cleanup, or add a compensating restore/outbox mechanism.🤖 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/file/file_delete.go` around lines 59 - 86, Move the storage deletion block using storageImpl.Remove in deleteSingleFile so it executes only after all RemoveDocumentKeepFile(ctx) calls and associated database cleanup succeed. Preserve the existing storage error logging, and ensure cancellation or other document-cleanup errors return before attempting to delete the storage object.
82-99: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftHonor cancellation across the rest of file deletion.
GetByFileID,DeleteByFileID, andfileDAO.Deleteremain contextless even thoughDeleteFilesacceptsctx. A canceled request with no associated documents, or cancellation between calls, can still perform destructive cleanup. Threadctxthrough these DAO contracts and storage operations.🤖 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/file/file_delete.go` around lines 82 - 99, Propagate the ctx parameter throughout DeleteFiles and its DAO/storage calls: update GetByFileID, DeleteByFileID, and fileDAO.Delete contracts and implementations to accept and honor context cancellation. Ensure cancellation is checked between deletion stages and prevents destructive cleanup, including when no documents are associated or cancellation occurs between calls.internal/service/chunk/chunk.go (2)
780-803: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick winUpdate callers for the new
Listsignature.The supplied
internal/service/chunk/chunk_test.gosnippet (Lines 284-330) still callssvc.List(...)without a context, so the test no longer compiles. Update all callers to pass the appropriate context.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/chunk/chunk.go` around lines 780 - 803, Update every caller of ChunkService.List, including the tests in chunk_test.go, to pass an appropriate context.Context as the first argument before the existing request and userID arguments. Preserve the current request and user behavior while ensuring all call sites match the List signature.
780-827: 🗄️ Data Integrity & Integration | 🟠 MajorFinish propagating
ctxthrough authorization and stats operations.
ListandRemoveChunksstill call tenant/KB DAO methods withoutctx, andRemoveChunkscallsdecrementChunkStatswithout it. Canceled requests can therefore continue database or state-changing work. Update these contracts to usectxanddb.WithContext(ctx)rather than retaining contextless paths.This is the same unresolved issue from the previous review. As per coding guidelines, converge on one context-aware path instead of retaining contextless alternate calls.
Also applies to: 1202-1271
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/chunk/chunk.go` around lines 780 - 827, Propagate ctx through the ChunkService authorization and stats paths: update the tenant/knowledge-base DAO calls in List and RemoveChunks, plus decrementChunkStats, to accept and use ctx, ensuring database operations run through db.WithContext(ctx). Remove contextless alternate calls and keep one context-aware contract throughout.Source: Coding guidelines
internal/service/ingestion_task_service.go (1)
377-435: 🗄️ Data Integrity & Integration | 🟠 MajorDo not drop
ctxinsideCreateAndEnqueue.The new parameter is unused: document lookup, task transitions, enqueue publishing, and both rollback paths remain contextless. Cancellation can therefore leave task state changes or published messages in progress after the caller exits.
Thread
ctxthrough the DAO, transition, rollback, and publisher contracts, or explicitly detach only side effects that must outlive cancellation. This is the same unresolved issue from the previous review. As per coding guidelines, converge on one context-aware path instead of retaining contextless wrappers.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/ingestion_task_service.go` around lines 377 - 435, Make CreateAndEnqueue propagate its ctx through the entire operation: document lookup, task creation, status transition, enqueue publishing, and both rollback paths. Update the involved DAO, transition, rollback, and publisher contracts and their implementations to accept and use context, converging on context-aware methods rather than retaining contextless wrappers; preserve cancellation behavior consistently across all paths.Source: Coding guidelines
internal/parser/parser/office_parsers_nocgo_test.go (1)
6-12: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick winRemove the obsolete
contextimports from both parser tests.Both tests now call
t.Context()directly, so retaining the package import produces an unused-import compilation error.
internal/parser/parser/office_parsers_nocgo_test.go#L6-L12: remove thecontextimport and keepctx := t.Context().internal/parser/parser/pdf_parser_nocgo_test.go#L6-L13: remove thecontextimport and keepctx := t.Context().🤖 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/parser/parser/office_parsers_nocgo_test.go` around lines 6 - 12, Remove the unused context import from the test imports in internal/parser/parser/office_parsers_nocgo_test.go (lines 6-12) and internal/parser/parser/pdf_parser_nocgo_test.go (lines 6-13); keep the existing ctx := t.Context() usage in both tests unchanged.Source: Linters/SAST tools
🧹 Nitpick comments (1)
internal/service/agent.go (1)
1555-1558: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDocument the current Go behavior without migration-history references.
This comment ties the helper to Python implementation history. Keep the comment focused on the current contract: deriving a session name from user input and truncating it to 250 runes.
🤖 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/agent.go` around lines 1555 - 1558, Update the comment for deriveAgentSessionName to describe only the current contract: deriving a session name from user input and truncating it to 250 runes. Remove references to Python implementation history and migration details.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@internal/parser/parser/office_parsers_nocgo_test.go`:
- Around line 6-12: Remove the unused context import from the test imports in
internal/parser/parser/office_parsers_nocgo_test.go (lines 6-12) and
internal/parser/parser/pdf_parser_nocgo_test.go (lines 6-13); keep the existing
ctx := t.Context() usage in both tests unchanged.
In `@internal/service/chunk/chunk.go`:
- Around line 780-803: Update every caller of ChunkService.List, including the
tests in chunk_test.go, to pass an appropriate context.Context as the first
argument before the existing request and userID arguments. Preserve the current
request and user behavior while ensuring all call sites match the List
signature.
- Around line 780-827: Propagate ctx through the ChunkService authorization and
stats paths: update the tenant/knowledge-base DAO calls in List and
RemoveChunks, plus decrementChunkStats, to accept and use ctx, ensuring database
operations run through db.WithContext(ctx). Remove contextless alternate calls
and keep one context-aware contract throughout.
In `@internal/service/file/file_delete.go`:
- Around line 59-86: Move the storage deletion block using storageImpl.Remove in
deleteSingleFile so it executes only after all RemoveDocumentKeepFile(ctx) calls
and associated database cleanup succeed. Preserve the existing storage error
logging, and ensure cancellation or other document-cleanup errors return before
attempting to delete the storage object.
- Around line 82-99: Propagate the ctx parameter throughout DeleteFiles and its
DAO/storage calls: update GetByFileID, DeleteByFileID, and fileDAO.Delete
contracts and implementations to accept and honor context cancellation. Ensure
cancellation is checked between deletion stages and prevents destructive
cleanup, including when no documents are associated or cancellation occurs
between calls.
In `@internal/service/ingestion_task_service.go`:
- Around line 377-435: Make CreateAndEnqueue propagate its ctx through the
entire operation: document lookup, task creation, status transition, enqueue
publishing, and both rollback paths. Update the involved DAO, transition,
rollback, and publisher contracts and their implementations to accept and use
context, converging on context-aware methods rather than retaining contextless
wrappers; preserve cancellation behavior consistently across all paths.
In `@internal/utility/upload.go`:
- Around line 41-54: Update FetchRemoteFileSafely to create the outbound request
with http.NewRequestWithContext using ctx and currentURL, then execute it
through client.Do instead of client.Get; preserve the existing safety and
redirect handling, and add a focused test verifying cancellation stops the
request.
---
Nitpick comments:
In `@internal/service/agent.go`:
- Around line 1555-1558: Update the comment for deriveAgentSessionName to
describe only the current contract: deriving a session name from user input and
truncating it to 250 runes. Remove references to Python implementation history
and migration details.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b7566a6c-8863-4c14-b87f-5aa6bd6f1f0c
📒 Files selected for processing (26)
internal/admin/service.gointernal/handler/agent.gointernal/handler/chunk_test.gointernal/handler/searchbot.gointernal/ingestion/component/parser.gointernal/ingestion/task/task_context.gointernal/parser/parser/office_parsers_nocgo_test.gointernal/parser/parser/pdf_parser_nocgo_test.gointernal/service/agent.gointernal/service/chunk/chunk.gointernal/service/chunk/chunk_test.gointernal/service/dataset/create_test.gointernal/service/dataset/crud.gointernal/service/dataset/index.gointernal/service/dataset/update.gointernal/service/document/document_crud.gointernal/service/document/document_metadata.gointernal/service/document/document_upload.gointernal/service/file/file_commit.gointernal/service/file/file_delete.gointernal/service/file/file_url.gointernal/service/ingestion_task_service.gointernal/service/ingestion_task_service_test.gointernal/service/user.gointernal/utility/upload.gointernal/utility/upload_test.go
🚧 Files skipped from review as they are similar to previous changes (11)
- internal/ingestion/component/parser.go
- internal/admin/service.go
- internal/ingestion/task/task_context.go
- internal/handler/agent.go
- internal/handler/searchbot.go
- internal/handler/chunk_test.go
- internal/service/document/document_upload.go
- internal/service/dataset/index.go
- internal/service/document/document_metadata.go
- internal/service/chunk/chunk_test.go
- internal/service/document/document_crud.go
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]>
Summary
As title.