Repository navigation
Go: add context, part5 - #17392
Go: add context, part5#17392
Conversation
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThe PR propagates request contexts and explicit GORM database handles through component execution, retrieval, MCP, service, handler, DAO, and ingestion paths. It updates implementations and tests for the new contracts, corrects the retrieval tool identifier, and fixes SQL error-variable shadowing. ChangesContext and database propagation
Estimated code review effort: 5 (Critical) | ~120 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 (1)
internal/service/dataset/tags.go (1)
16-37: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winPreserve the caller context for document-engine work.
The new
ctxreaches DAO calls but is discarded before document-engine calls. Client cancellation and request deadlines therefore do not stop tag searches or updates.
internal/service/dataset/tags.go#L16-L37: passctxtod.docEngine.Searchinstead ofcontext.Background().internal/service/dataset/tags.go#L99-L115: derive the 30-second timeout withcontext.WithTimeout(ctx, 30*time.Second).internal/service/dataset/tags.go#L192-L208: passctxtod.docEngine.UpdateChunksinstead ofcontext.Background().🤖 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/tags.go` around lines 16 - 37, Preserve the caller context for document-engine operations in DatasetService.AggregateTags and the related tag-update flow: at internal/service/dataset/tags.go lines 16-37, pass ctx to d.docEngine.Search instead of context.Background(); at lines 99-115, derive the 30-second timeout from ctx with context.WithTimeout(ctx, 30*time.Second); and at lines 192-208, pass ctx to d.docEngine.UpdateChunks instead of context.Background().
🧹 Nitpick comments (4)
internal/dao/kb.go (1)
376-423: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove migration-history doc comments.
“These matches the Python …” comments describe migration provenance rather than current behavior; keep the operation-focused summary only.
As per coding guidelines, “Keep package comments and doc comments aligned with the current runtime path, not 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/dao/kb.go` around lines 376 - 423, Remove the migration-history comments beginning with “This matches the Python” from DecreaseDocumentNum, GetKBIDsByTenantID, GetAllIDs, and UpdateParserConfig, while retaining each operation-focused summary comment. Do not alter the implementations or the existing DeleteFieldMap comment.Source: Coding guidelines
internal/service/dataset/crud.go (2)
19-19: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winPropagate the new context through dataset creation.
CreateDatasetacceptsctx, but the tenant lookup and later canvas/model lookups remain context-free. Request cancellation therefore does not stop the full create 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/dataset/crud.go` at line 19, Update DatasetService.CreateDataset to propagate its ctx through the entire dataset creation flow, including the tenant lookup and subsequent canvas/model lookups. Replace context-free calls with their context-aware variants, preserving existing behavior while ensuring request cancellation reaches every lookup.
316-316: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winPropagate
ctxto tenant membership lookup.
ListDatasetsuses the context-aware KB queries, butGetJoinedTenantsByUserIDremains context-free. A canceled request can still block on tenant membership retrieval.🤖 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/crud.go` at line 316, Update ListDatasets to use the context-aware variant of the tenant membership lookup, passing its ctx argument into GetJoinedTenantsByUserID or the corresponding context-aware method. Preserve the existing tenant filtering behavior while ensuring cancellation propagates through membership retrieval.internal/ingestion/task/embedder_test.go (1)
34-43: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAssert the forwarded context in the test.
The callbacks accept
ctx, butTestEmbedderResolver_UsesKBEmbdIDnever records or compares it. A regression that drops or replaces the context would still pass; capture the callback context and assert it equals the resolver input.🤖 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/task/embedder_test.go` around lines 34 - 43, Update TestEmbedderResolver_UsesKBEmbdID to capture the ctx received by the embedding-model callback, then assert it equals the context passed to resolver. Preserve the existing tenant and embedding ID assertions while adding this forwarded-context check.
🤖 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/agent/component/agent.go`:
- Line 634: The Agent component’s sub-agent invocation must preserve the
caller-owned execution DB instead of replacing it with dao.DB. In
internal/agent/component/agent.go lines 634-634, pass the parent execution DB
into the NewAgentComponent(...).Invoke path; in internal/agent/tool/retrieval.go
lines 165-165, have InvokableRun retrieve and use that propagated DB, retaining
dao.DB only as the fallback for standalone tool execution.
In `@internal/agent/tool/registry_test.go`:
- Line 121: Update the alias comments near the registry test setup to list the
exact alias set exercised by names and canonicalByAlias, including both
search_my_dataset and search_my_dateset exactly once. Remove stale or superseded
alias comments rather than retaining duplicates.
In `@internal/handler/dify_retrieval_handler_test.go`:
- Around line 71-73: Update mockModelService.GetEmbeddingModel and the
getEmbeddingFn callback signature to accept context.Context, then forward ctx
when invoking the callback. Adjust all callback implementations and test
fixtures to match, preserving context propagation for cancellation and
request-scoped values.
In `@internal/ingestion/component/parser_test.go`:
- Line 266: Update ParserComponent.Invoke and readParserBinary to pass the
injected *gorm.DB into ResolveDocumentStorage, then use that handle for all
Document, File2Document, and File DAO lookups instead of global dao.DB. Update
direct component tests and thread the same DB through File and Parser node
invocation in full pipelines.
In `@internal/service/dataset/crud.go`:
- Line 19: Complete context propagation in internal/service/dataset/crud.go:
update CreateDataset to pass ctx to tenant, canvas, and model lookups; update
deleteDataset and its callers to accept ctx and apply it to all queries,
transactions, and supported-engine cleanup; update tenant membership retrieval
to receive ctx. Affected sites are internal/service/dataset/crud.go lines 19-19,
196-196, and 316-316.
- Around line 229-232: Update the dataset lookup flow around GetByIDAndTenantID
so only not-found or tenant-mismatch results append to unauthorizedIDs; detect
and propagate cancellation, timeout, and other database or operational errors
separately, while preserving the existing authorization handling for genuinely
inaccessible datasets.
In `@internal/service/metadata.go`:
- Around line 110-115: Propagate the request context through all listed
operations instead of replacing it with context.Background(): in
internal/service/metadata.go, pass ctx from SearchMetadataByKBs to
SearchMetadata; in internal/service/tag.go, thread ctx through TagQuery to
docEngine.Search; in internal/service/tenant.go, pass ctx to CreateChunkStore
and DropChunkStore; and in internal/service/dataset/index.go, use
dao.DB.WithContext(ctx) for the transaction and task deletion, and pass ctx to
sampling, chunk retrieval, and DeleteChunks.
In `@internal/service/model_service.go`:
- Around line 3192-3193: Update ResolveModelConfig and its database-read
operations to accept and use context.Context for cancellation and deadlines,
then pass the ctx parameter from GetEmbeddingModel into ResolveModelConfig.
Preserve the existing model-resolution behavior while ensuring all lookup
operations remain within the request context.
In `@internal/service/search.go`:
- Line 353: Update PrepareCompletion and the underlying completion lookup
contracts so every authorization and detail query receives and uses ctx. Replace
the ctx-less AccessibleForCompletion and GetDetail calls, including the
additional call near the later completion branch, with context-aware variants
and propagate ctx through their service/DAO implementations.
---
Outside diff comments:
In `@internal/service/dataset/tags.go`:
- Around line 16-37: Preserve the caller context for document-engine operations
in DatasetService.AggregateTags and the related tag-update flow: at
internal/service/dataset/tags.go lines 16-37, pass ctx to d.docEngine.Search
instead of context.Background(); at lines 99-115, derive the 30-second timeout
from ctx with context.WithTimeout(ctx, 30*time.Second); and at lines 192-208,
pass ctx to d.docEngine.UpdateChunks instead of context.Background().
---
Nitpick comments:
In `@internal/dao/kb.go`:
- Around line 376-423: Remove the migration-history comments beginning with
“This matches the Python” from DecreaseDocumentNum, GetKBIDsByTenantID,
GetAllIDs, and UpdateParserConfig, while retaining each operation-focused
summary comment. Do not alter the implementations or the existing DeleteFieldMap
comment.
In `@internal/ingestion/task/embedder_test.go`:
- Around line 34-43: Update TestEmbedderResolver_UsesKBEmbdID to capture the ctx
received by the embedding-model callback, then assert it equals the context
passed to resolver. Preserve the existing tenant and embedding ID assertions
while adding this forwarded-context check.
In `@internal/service/dataset/crud.go`:
- Line 19: Update DatasetService.CreateDataset to propagate its ctx through the
entire dataset creation flow, including the tenant lookup and subsequent
canvas/model lookups. Replace context-free calls with their context-aware
variants, preserving existing behavior while ensuring request cancellation
reaches every lookup.
- Line 316: Update ListDatasets to use the context-aware variant of the tenant
membership lookup, passing its ctx argument into GetJoinedTenantsByUserID or the
corresponding context-aware method. Preserve the existing tenant filtering
behavior while ensuring cancellation propagates through membership retrieval.
🪄 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: d9d9122c-11fc-4348-8a25-b200051c4807
📒 Files selected for processing (179)
agent/tools/retrieval.pycmd/ragflow_server.gointernal/admin/service.gointernal/agent/canvas/node_body.gointernal/agent/canvas/node_body_override_params_test.gointernal/agent/canvas/node_body_per_class_timeout_integration_test.gointernal/agent/canvas/node_body_timeout_test.gointernal/agent/component/agent.gointernal/agent/component/agent_test.gointernal/agent/component/base.gointernal/agent/component/begin.gointernal/agent/component/begin_test.gointernal/agent/component/browser.gointernal/agent/component/browser_test.gointernal/agent/component/canvas_var_resolution_test.gointernal/agent/component/categorize.gointernal/agent/component/categorize_test.gointernal/agent/component/chat_template_kwargs_test.gointernal/agent/component/citation_test.gointernal/agent/component/data_operations.gointernal/agent/component/data_operations_test.gointernal/agent/component/docs_generator.gointernal/agent/component/docs_generator_test.gointernal/agent/component/downstream_message_test.gointernal/agent/component/excel_processor.gointernal/agent/component/excel_processor_test.gointernal/agent/component/fillup.gointernal/agent/component/fillup_test.gointernal/agent/component/fixture_stubs.gointernal/agent/component/grounding_test.gointernal/agent/component/history_window_test.gointernal/agent/component/invoke.gointernal/agent/component/invoke_test.gointernal/agent/component/list_operations.gointernal/agent/component/list_operations_test.gointernal/agent/component/llm.gointernal/agent/component/llm_retry.gointernal/agent/component/llm_retry_test.gointernal/agent/component/llm_test.gointernal/agent/component/loop.gointernal/agent/component/loop_test.gointernal/agent/component/message.gointernal/agent/component/message_phase8b_test.gointernal/agent/component/message_test.gointernal/agent/component/parallel.gointernal/agent/component/parallel_test.gointernal/agent/component/production_chain_fixes_test.gointernal/agent/component/retrieval_swap_test.gointernal/agent/component/sampler_params_test.gointernal/agent/component/stagehand_runtime_integration_test.gointernal/agent/component/streaming_test.gointernal/agent/component/string_transform.gointernal/agent/component/string_transform_test.gointernal/agent/component/structured_output_test.gointernal/agent/component/switch.gointernal/agent/component/switch_test.gointernal/agent/component/tool_call_memory_test.gointernal/agent/component/tool_component.gointernal/agent/component/tool_component_test.gointernal/agent/component/tool_dispatch_test.gointernal/agent/component/universe_a_wrappers.gointernal/agent/component/userfillup.gointernal/agent/component/userfillup_test.gointernal/agent/component/variable_aggregator.gointernal/agent/component/variable_aggregator_test.gointernal/agent/component/variable_assigner.gointernal/agent/component/variable_assigner_test.gointernal/agent/component/vision_test.gointernal/agent/runtime/component.gointernal/agent/runtime/registry_test.gointernal/agent/tool/code_exec.gointernal/agent/tool/exesql.gointernal/agent/tool/mcp.gointernal/agent/tool/registry_test.gointernal/agent/tool/retrieval.gointernal/agent/tool/retrieval_nlp.gointernal/agent/tool/retrieval_nlp_test.gointernal/agent/tool/retrieval_service.gointernal/agent/tool/retrieval_service_test.gointernal/agent/tool/retrieval_test.gointernal/agent/tool/retrieval_wiring_test.gointernal/dao/kb.gointernal/dao/kb_test.gointernal/engine/elasticsearch/metadata.gointernal/engine/engine.gointernal/engine/infinity/metadata.gointernal/handler/agent_component.gointernal/handler/agent_component_test.gointernal/handler/dataset.gointernal/handler/dataset_search_test.gointernal/handler/dify_retrieval_handler.gointernal/handler/dify_retrieval_handler_test.gointernal/handler/document.gointernal/handler/file_commit.gointernal/handler/mcp_server.gointernal/handler/search.gointernal/handler/tenant.gointernal/ingestion/component/chunker/group.gointernal/ingestion/component/chunker/group_test.gointernal/ingestion/component/chunker/hierarchy.gointernal/ingestion/component/chunker/hierarchy_test.gointernal/ingestion/component/chunker/image_upload_test.gointernal/ingestion/component/chunker/one.gointernal/ingestion/component/chunker/one_test.gointernal/ingestion/component/chunker/presentation.gointernal/ingestion/component/chunker/presentation_test.gointernal/ingestion/component/chunker/python_parity_test.gointernal/ingestion/component/chunker/qa.gointernal/ingestion/component/chunker/qa_batch2_test.gointernal/ingestion/component/chunker/qa_test.gointernal/ingestion/component/chunker/register.gointernal/ingestion/component/chunker/table.gointernal/ingestion/component/chunker/table_test.gointernal/ingestion/component/chunker/tag.gointernal/ingestion/component/chunker/tag_test.gointernal/ingestion/component/chunker/title.gointernal/ingestion/component/chunker/title_test.gointernal/ingestion/component/chunker/token.gointernal/ingestion/component/chunker/token_test.gointernal/ingestion/component/extractor.gointernal/ingestion/component/extractor_tag_test.gointernal/ingestion/component/extractor_test.gointernal/ingestion/component/file.gointernal/ingestion/component/file_test.gointernal/ingestion/component/parser.gointernal/ingestion/component/parser_dispatch_pdf_vision_cgo_test.gointernal/ingestion/component/parser_dispatch_test.gointernal/ingestion/component/parser_test.gointernal/ingestion/component/slice3_integration_test.gointernal/ingestion/component/tokenizer.gointernal/ingestion/component/tokenizer_test.gointernal/ingestion/component/tokenizer_unit_test.gointernal/ingestion/pipeline/pipeline_test.gointernal/ingestion/pipeline/template_integration_test.gointernal/ingestion/task/embedder.gointernal/ingestion/task/embedder_test.gointernal/ingestion/task/pipeline_executor_test.gointernal/ingestion/task/task_context.gointernal/mcp/connector.gointernal/mcp/server.gointernal/service/agent_run_e2e_test.gointernal/service/chat.gointernal/service/chat_pipeline.gointernal/service/chunk/chunk.gointernal/service/chunk/chunk_test.gointernal/service/chunk_types.gointernal/service/dataset/create_test.gointernal/service/dataset/crud.gointernal/service/dataset/fake_doc_engine_test.gointernal/service/dataset/index.gointernal/service/dataset/index_delete_test.gointernal/service/dataset/ingestion.gointernal/service/dataset/metadata.gointernal/service/dataset/permission.gointernal/service/dataset/search.gointernal/service/dataset/tags.gointernal/service/dataset/tags_aggregate_test.gointernal/service/dataset/tags_list_test.gointernal/service/dataset/tags_rename_test.gointernal/service/dataset/update.gointernal/service/dataset/update_test.gointernal/service/document/document_crud.gointernal/service/document/document_dataset_update.gointernal/service/document/document_ingest.gointernal/service/document/document_metadata.gointernal/service/document/document_test.gointernal/service/document/file2document.gointernal/service/file_permission.gointernal/service/memory_message_test.gointernal/service/metadata.gointernal/service/metadata_filter.gointernal/service/model_service.gointernal/service/openai_chat.gointernal/service/search.gointernal/service/skill_indexer.gointernal/service/skill_search.gointernal/service/tag.gointernal/service/tenant.gointernal/service/test_helpers_test.go
| } | ||
|
|
||
| out, err := NewAgentComponent(t.spec.Param).Invoke(ctx, inputs) | ||
| out, err := NewAgentComponent(t.spec.Param).Invoke(ctx, dao.DB, inputs) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Keep the execution DB attached across Agent tool callbacks. The new explicit DB contract is lost once execution enters Eino tools: both paths substitute global dao.DB, bypassing caller-owned transactions or scoped handles.
internal/agent/component/agent.go#L634-L634: pass the parent execution DB into the sub-agent tool path instead of invoking the child withdao.DB.internal/agent/tool/retrieval.go#L165-L165: obtain that propagated DB inInvokableRun; retaindao.DBonly as an intentional fallback for standalone tool execution.
📍 Affects 2 files
internal/agent/component/agent.go#L634-L634(this comment)internal/agent/tool/retrieval.go#L165-L165
🤖 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/agent/component/agent.go` at line 634, The Agent component’s
sub-agent invocation must preserve the caller-owned execution DB instead of
replacing it with dao.DB. In internal/agent/component/agent.go lines 634-634,
pass the parent execution DB into the NewAgentComponent(...).Invoke path; in
internal/agent/tool/retrieval.go lines 165-165, have InvokableRun retrieve and
use that propagated DB, retaining dao.DB only as the fallback for standalone
tool execution.
| // TestToolRegistry_SchemasAreComplete sweeps every name the public | ||
| // registry advertises (including the execute_sql/exesql and | ||
| // retrieval/search_my_dateset alias pairs), builds the tool, and | ||
| // retrieval/search_my_dataset alias pairs), builds the tool, and |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Keep the alias comments synchronized with the test contract.
The changed comments omit or duplicate search_my_dateset, while names and canonicalByAlias still exercise both spellings. List the exact alias set once so the test intent is not misleading.
As per coding guidelines, remove stale superseded comments rather than preserving them.
Also applies to: 191-191
🤖 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/agent/tool/registry_test.go` at line 121, Update the alias comments
near the registry test setup to list the exact alias set exercised by names and
canonicalByAlias, including both search_my_dataset and search_my_dateset exactly
once. Remove stale or superseded alias comments rather than retaining
duplicates.
Source: Coding guidelines
|
|
||
| c := &ParserComponent{Param: schema.ParserParam{}.Defaults()} | ||
| out, err := c.Invoke(context.Background(), map[string]any{"doc_id": "doc-parser"}) | ||
| out, err := c.Invoke(context.Background(), db, map[string]any{"doc_id": "doc-parser"}) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Files:"
git ls-files | rg -n 'internal/ingestion/component/(parser|document_storage).*\.(go|test)$' || true
echo
echo "Relevant symbols:"
rg -n "ResolveDocumentStorage|func \(.*Invoke|documentStorage|dao\.DB|type.*Database|Open(?!s)|DB" internal/ingestion/internal ingestion internal 2>/dev/null | head -n 200 || trueRepository: infiniflow/ragflow
Length of output: 568
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Candidate files:"
git ls-files | rg '(^|/)internal/ingestion/(component/parser_test.go|component/parser.go|component/document_storage.go|.*document.*storage.*\.go)$|(^|/)internal/.*parser.*storage.*\.go$' || true
echo
echo "Relevant code slices:"
for f in $(git ls-files | rg '(^|/)internal/ingestion/(component/parser_test.go|component/parser.go|component/document_storage.go)$'); do
if [ -n "$f" ]; then
echo "===== $f ====="
wc -l "$f"
rg -n "Invoke|ResolveDocumentStorage|document_storage|doc_id|dao\.DB|DB\)|func .*Storage" "$f" -C 8 || true
fi
done
echo
echo "Repository-wide relevant symbols (bounded):"
rg -n "ResolveDocumentStorage\(|var \s*DB\(|dao\.DB|func .*Storage|doc_id|DocumentStorage|type .*Storage" internal/ingestion -C 4 | head -n 240Repository: infiniflow/ragflow
Length of output: 42221
Propagate db through doc-ID binary resolution.
ParserComponent.Invoke now accepts a *gorm.DB, but readParserBinary resolves doc_id via ResolveDocumentStorage(ctx, docID), and ResolveDocumentStorage(...) still looks up Document, File2Document, and File through global dao.DB. Pass db into the storage resolver and have it use the injected DB for those DAO calls, including tests using this component directly; for full pipelines, thread the same value through File and Parser node invocation so every run uses the run DB 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/parser_test.go` at line 266, Update
ParserComponent.Invoke and readParserBinary to pass the injected *gorm.DB into
ResolveDocumentStorage, then use that handle for all Document, File2Document,
and File DAO lookups instead of global dao.DB. Update direct component tests and
thread the same DB through File and Parser node invocation in full pipelines.
| ) | ||
|
|
||
| func (d *DatasetService) CreateDataset(req *service.CreateDatasetRequest, tenantID string) (map[string]interface{}, common.ErrorCode, error) { | ||
| func (d *DatasetService) CreateDataset(ctx context.Context, req *service.CreateDatasetRequest, tenantID string) (map[string]interface{}, common.ErrorCode, error) { |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Complete context propagation across dataset service flows.
The new ctx parameters are only partially effective because downstream tenant, canvas/model, membership, and destructive deletion operations still use context-free APIs.
internal/service/dataset/crud.go#L19-L19: propagatectxthrough tenant, canvas, and model lookups during creation.internal/service/dataset/crud.go#L196-L196: passctxintodeleteDatasetand apply it to all queries, transactions, and supported engine cleanup.internal/service/dataset/crud.go#L316-L316: passctxinto tenant membership retrieval.
📍 Affects 1 file
internal/service/dataset/crud.go#L19-L19(this comment)internal/service/dataset/crud.go#L196-L196internal/service/dataset/crud.go#L316-L316
🤖 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/crud.go` at line 19, Complete context propagation in
internal/service/dataset/crud.go: update CreateDataset to pass ctx to tenant,
canvas, and model lookups; update deleteDataset and its callers to accept ctx
and apply it to all queries, transactions, and supported-engine cleanup; update
tenant membership retrieval to receive ctx. Affected sites are
internal/service/dataset/crud.go lines 19-19, 196-196, and 316-316.
| kb, err := d.kbDAO.GetByIDAndTenantID(ctx, dao.DB, id, tenantID) | ||
| if err != nil || kb == nil { | ||
| unauthorizedIDs = append(unauthorizedIDs, id) | ||
| continue |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Do not classify operational failures as authorization failures.
This branch treats every GetByIDAndTenantID error—including cancellation, timeout, and database failure—as an unauthorized dataset. Only not-found or tenant-mismatch results should follow the authorization path; operational errors should be propagated separately.
🤖 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/crud.go` around lines 229 - 232, Update the dataset
lookup flow around GetByIDAndTenantID so only not-found or tenant-mismatch
results append to unauthorizedIDs; detect and propagate cancellation, timeout,
and other database or operational errors separately, while preserving the
existing authorization handling for genuinely inaccessible datasets.
| func (m *ModelProviderService) GetEmbeddingModel(ctx context.Context, tenantID, compositeModelName string) (*modelModule.EmbeddingModel, error) { | ||
| driver, modelName, apiConfig, maxTokens, err := m.ResolveModelConfig(tenantID, entity.ModelTypeEmbedding, compositeModelName) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Forward ctx into model resolution.
GetEmbeddingModel accepts the request context, but immediately calls ResolveModelConfig without it. Callers therefore still perform model lookup outside the request cancellation/deadline path. Update ResolveModelConfig and its database reads to accept/use ctx, then pass it through 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/service/model_service.go` around lines 3192 - 3193, Update
ResolveModelConfig and its database-read operations to accept and use
context.Context for cancellation and deadlines, then pass the ctx parameter from
GetEmbeddingModel into ResolveModelConfig. Preserve the existing
model-resolution behavior while ensuring all lookup operations remain within the
request context.
| } | ||
|
|
||
| func (s *SearchService) PrepareCompletion(userID, searchID string, req *SearchCompletionsRequest) (*SearchCompletionPlan, common.ErrorCode, error) { | ||
| func (s *SearchService) PrepareCompletion(ctx context.Context, userID, searchID string, req *SearchCompletionsRequest) (*SearchCompletionPlan, common.ErrorCode, error) { |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Propagate ctx through all completion lookups.
The new context reaches dataset permission checks, but AccessibleForCompletion and GetDetail are still called through ctx-less methods at Lines 370 and 378. Canceled or timed-out requests can therefore continue search authorization/detail queries. Update those service/DAO contracts and call sites to forward ctx consistently.
Also applies to: 393-393
🤖 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/search.go` at line 353, Update PrepareCompletion and the
underlying completion lookup contracts so every authorization and detail query
receives and uses ctx. Replace the ctx-less AccessibleForCompletion and
GetDetail calls, including the additional call near the later completion branch,
with context-aware variants and propagate ctx through their service/DAO
implementations.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17392 +/- ##
==========================================
- Coverage 94.56% 90.65% -3.91%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 650 -28
- Misses 25 39 +14
- Partials 14 28 +14 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/ingestion/component/parser.go (1)
642-647: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winGuard the resolved storage reference before dereferencing it.
ResolveDocumentStorageOverridecan return(nil, nil), but Line 647 dereferencesref.Bucketunconditionally. This panics; the PDF crop caller already handlesref == nilininternal/ingestion/component/chunker/pdfcrop_cgo.go, Lines 39-42. Reject the nil reference here or define it as an explicit no-input result.Proposed fix
ref, err := ResolveDocumentStorage(ctx, db, docID) if err != nil { return nil, fmt.Errorf("Parser: resolve doc_id %q: %w", docID, err) } + if ref == nil { + return nil, fmt.Errorf("Parser: resolve doc_id %q returned no storage reference", docID) + } return FetchBinary(ctx, ref.Bucket, ref.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/ingestion/component/parser.go` around lines 642 - 647, Guard the result of ResolveDocumentStorage in the doc_id path before accessing ref.Bucket or ref.Path. When the resolver returns nil without an error, handle it explicitly as an invalid or absent storage reference using the surrounding parser’s established error/no-input behavior, while preserving FetchBinary for valid references.
🤖 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/tag.go`:
- Line 167: Update MetadataService.TagQuery and the corresponding secondary call
site to pass the received ctx into the document-engine search instead of
creating context.Background(), preserving request cancellation and deadline
propagation throughout tag queries.
---
Outside diff comments:
In `@internal/ingestion/component/parser.go`:
- Around line 642-647: Guard the result of ResolveDocumentStorage in the doc_id
path before accessing ref.Bucket or ref.Path. When the resolver returns nil
without an error, handle it explicitly as an invalid or absent storage reference
using the surrounding parser’s established error/no-input behavior, while
preserving FetchBinary for valid references.
🪄 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: 82f0ab9f-b390-4518-b2f0-f1f81af93fa3
📒 Files selected for processing (14)
internal/agent/tool/registry_test.gointernal/handler/dify_retrieval_handler.gointernal/handler/dify_retrieval_handler_test.gointernal/ingestion/component/chunker/pdfcrop_cgo.gointernal/ingestion/component/chunker/pdfcrop_nocgo.gointernal/ingestion/component/chunker/token.gointernal/ingestion/component/document_storage.gointernal/ingestion/component/parser.gointernal/service/dataset/index.gointernal/service/metadata.gointernal/service/model_chat.gointernal/service/model_service.gointernal/service/tag.gointernal/service/tenant.go
🚧 Files skipped from review as they are similar to previous changes (7)
- internal/service/model_service.go
- internal/agent/tool/registry_test.go
- internal/ingestion/component/chunker/token.go
- internal/service/metadata.go
- internal/handler/dify_retrieval_handler_test.go
- internal/service/dataset/index.go
- internal/handler/dify_retrieval_handler.go
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
No description provided.