Skip to content

Go: add context, part5 - #17392

Merged
JinHai-CN merged 6 commits into
infiniflow:mainfrom
JinHai-CN:fix582
Jul 27, 2026
Merged

JinHai-CN merged 6 commits into
infiniflow:mainfrom
JinHai-CN:fix582

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

No description provided.

Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: eaeebd5a-8cb0-4e0a-8791-8a5f1957b712

📥 Commits

Reviewing files that changed from the base of the PR and between 65bef32 and 2765812.

📒 Files selected for processing (1)
  • internal/service/tag.go

📝 Walkthrough

Walkthrough

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

Changes

Context and database propagation

Layer / File(s) Summary
DAO and engine contracts
internal/dao/kb.go, internal/engine/...
DAO operations and metadata pushdown interfaces now accept context and database handles.
Component runtime contracts
internal/agent/..., internal/ingestion/...
Invoke and Stream contracts now include *gorm.DB, with implementations and test doubles updated.
Service and handler wiring
internal/service/..., internal/handler/...
Request contexts are passed through dataset, document, metadata, chat, search, tenant, chunk, and MCP operations.
Tool and cleanup fixes
agent/tools/..., internal/agent/tool/..., internal/admin/...
The retrieval alias is corrected, retrieval and cascade-delete calls receive database handles, and SQL error assignment avoids shadowing.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

Suggested labels: ☯️ refactor

Suggested reviewers: qinling0210

Poem

A rabbit hops through context streams,
Database paws fulfill its dreams.
Tool names align, contracts flow,
Handles travel where they go.
Hop, hop—the code is ready to grow!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is missing the required Summary section and provides no background or purpose. Add a Summary section that briefly describes the change and includes background context for reviewers, as required by the template.
Docstring Coverage ⚠️ Warning Docstring coverage is 59.79% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and matches the main change: adding context plumbing across Go code.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@JinHai-CN JinHai-CN added the ci Continue Integration label Jul 26, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 26, 2026 12:15
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 26, 2026
@JinHai-CN JinHai-CN added ci Continue Integration and removed ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 26, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 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 win

Preserve the caller context for document-engine work.

The new ctx reaches 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: pass ctx to d.docEngine.Search instead of context.Background().
  • internal/service/dataset/tags.go#L99-L115: derive the 30-second timeout with context.WithTimeout(ctx, 30*time.Second).
  • internal/service/dataset/tags.go#L192-L208: pass ctx to d.docEngine.UpdateChunks instead of context.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 win

Remove 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 win

Propagate the new context through dataset creation.

CreateDataset accepts ctx, 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 win

Propagate ctx to tenant membership lookup.

ListDatasets uses the context-aware KB queries, but GetJoinedTenantsByUserID remains 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 win

Assert the forwarded context in the test.

The callbacks accept ctx, but TestEmbedderResolver_UsesKBEmbdID never 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

📥 Commits

Reviewing files that changed from the base of the PR and between 53e83dc and 32fd27e.

📒 Files selected for processing (179)
  • agent/tools/retrieval.py
  • cmd/ragflow_server.go
  • internal/admin/service.go
  • internal/agent/canvas/node_body.go
  • internal/agent/canvas/node_body_override_params_test.go
  • internal/agent/canvas/node_body_per_class_timeout_integration_test.go
  • internal/agent/canvas/node_body_timeout_test.go
  • internal/agent/component/agent.go
  • internal/agent/component/agent_test.go
  • internal/agent/component/base.go
  • internal/agent/component/begin.go
  • internal/agent/component/begin_test.go
  • internal/agent/component/browser.go
  • internal/agent/component/browser_test.go
  • internal/agent/component/canvas_var_resolution_test.go
  • internal/agent/component/categorize.go
  • internal/agent/component/categorize_test.go
  • internal/agent/component/chat_template_kwargs_test.go
  • internal/agent/component/citation_test.go
  • internal/agent/component/data_operations.go
  • internal/agent/component/data_operations_test.go
  • internal/agent/component/docs_generator.go
  • internal/agent/component/docs_generator_test.go
  • internal/agent/component/downstream_message_test.go
  • internal/agent/component/excel_processor.go
  • internal/agent/component/excel_processor_test.go
  • internal/agent/component/fillup.go
  • internal/agent/component/fillup_test.go
  • internal/agent/component/fixture_stubs.go
  • internal/agent/component/grounding_test.go
  • internal/agent/component/history_window_test.go
  • internal/agent/component/invoke.go
  • internal/agent/component/invoke_test.go
  • internal/agent/component/list_operations.go
  • internal/agent/component/list_operations_test.go
  • internal/agent/component/llm.go
  • internal/agent/component/llm_retry.go
  • internal/agent/component/llm_retry_test.go
  • internal/agent/component/llm_test.go
  • internal/agent/component/loop.go
  • internal/agent/component/loop_test.go
  • internal/agent/component/message.go
  • internal/agent/component/message_phase8b_test.go
  • internal/agent/component/message_test.go
  • internal/agent/component/parallel.go
  • internal/agent/component/parallel_test.go
  • internal/agent/component/production_chain_fixes_test.go
  • internal/agent/component/retrieval_swap_test.go
  • internal/agent/component/sampler_params_test.go
  • internal/agent/component/stagehand_runtime_integration_test.go
  • internal/agent/component/streaming_test.go
  • internal/agent/component/string_transform.go
  • internal/agent/component/string_transform_test.go
  • internal/agent/component/structured_output_test.go
  • internal/agent/component/switch.go
  • internal/agent/component/switch_test.go
  • internal/agent/component/tool_call_memory_test.go
  • internal/agent/component/tool_component.go
  • internal/agent/component/tool_component_test.go
  • internal/agent/component/tool_dispatch_test.go
  • internal/agent/component/universe_a_wrappers.go
  • internal/agent/component/userfillup.go
  • internal/agent/component/userfillup_test.go
  • internal/agent/component/variable_aggregator.go
  • internal/agent/component/variable_aggregator_test.go
  • internal/agent/component/variable_assigner.go
  • internal/agent/component/variable_assigner_test.go
  • internal/agent/component/vision_test.go
  • internal/agent/runtime/component.go
  • internal/agent/runtime/registry_test.go
  • internal/agent/tool/code_exec.go
  • internal/agent/tool/exesql.go
  • internal/agent/tool/mcp.go
  • internal/agent/tool/registry_test.go
  • internal/agent/tool/retrieval.go
  • internal/agent/tool/retrieval_nlp.go
  • internal/agent/tool/retrieval_nlp_test.go
  • internal/agent/tool/retrieval_service.go
  • internal/agent/tool/retrieval_service_test.go
  • internal/agent/tool/retrieval_test.go
  • internal/agent/tool/retrieval_wiring_test.go
  • internal/dao/kb.go
  • internal/dao/kb_test.go
  • internal/engine/elasticsearch/metadata.go
  • internal/engine/engine.go
  • internal/engine/infinity/metadata.go
  • internal/handler/agent_component.go
  • internal/handler/agent_component_test.go
  • internal/handler/dataset.go
  • internal/handler/dataset_search_test.go
  • internal/handler/dify_retrieval_handler.go
  • internal/handler/dify_retrieval_handler_test.go
  • internal/handler/document.go
  • internal/handler/file_commit.go
  • internal/handler/mcp_server.go
  • internal/handler/search.go
  • internal/handler/tenant.go
  • internal/ingestion/component/chunker/group.go
  • internal/ingestion/component/chunker/group_test.go
  • internal/ingestion/component/chunker/hierarchy.go
  • internal/ingestion/component/chunker/hierarchy_test.go
  • internal/ingestion/component/chunker/image_upload_test.go
  • internal/ingestion/component/chunker/one.go
  • internal/ingestion/component/chunker/one_test.go
  • internal/ingestion/component/chunker/presentation.go
  • internal/ingestion/component/chunker/presentation_test.go
  • internal/ingestion/component/chunker/python_parity_test.go
  • internal/ingestion/component/chunker/qa.go
  • internal/ingestion/component/chunker/qa_batch2_test.go
  • internal/ingestion/component/chunker/qa_test.go
  • internal/ingestion/component/chunker/register.go
  • internal/ingestion/component/chunker/table.go
  • internal/ingestion/component/chunker/table_test.go
  • internal/ingestion/component/chunker/tag.go
  • internal/ingestion/component/chunker/tag_test.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/chunker/title_test.go
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/chunker/token_test.go
  • internal/ingestion/component/extractor.go
  • internal/ingestion/component/extractor_tag_test.go
  • internal/ingestion/component/extractor_test.go
  • internal/ingestion/component/file.go
  • internal/ingestion/component/file_test.go
  • internal/ingestion/component/parser.go
  • internal/ingestion/component/parser_dispatch_pdf_vision_cgo_test.go
  • internal/ingestion/component/parser_dispatch_test.go
  • internal/ingestion/component/parser_test.go
  • internal/ingestion/component/slice3_integration_test.go
  • internal/ingestion/component/tokenizer.go
  • internal/ingestion/component/tokenizer_test.go
  • internal/ingestion/component/tokenizer_unit_test.go
  • internal/ingestion/pipeline/pipeline_test.go
  • internal/ingestion/pipeline/template_integration_test.go
  • internal/ingestion/task/embedder.go
  • internal/ingestion/task/embedder_test.go
  • internal/ingestion/task/pipeline_executor_test.go
  • internal/ingestion/task/task_context.go
  • internal/mcp/connector.go
  • internal/mcp/server.go
  • internal/service/agent_run_e2e_test.go
  • internal/service/chat.go
  • internal/service/chat_pipeline.go
  • internal/service/chunk/chunk.go
  • internal/service/chunk/chunk_test.go
  • internal/service/chunk_types.go
  • internal/service/dataset/create_test.go
  • internal/service/dataset/crud.go
  • internal/service/dataset/fake_doc_engine_test.go
  • internal/service/dataset/index.go
  • internal/service/dataset/index_delete_test.go
  • internal/service/dataset/ingestion.go
  • internal/service/dataset/metadata.go
  • internal/service/dataset/permission.go
  • internal/service/dataset/search.go
  • internal/service/dataset/tags.go
  • internal/service/dataset/tags_aggregate_test.go
  • internal/service/dataset/tags_list_test.go
  • internal/service/dataset/tags_rename_test.go
  • internal/service/dataset/update.go
  • internal/service/dataset/update_test.go
  • internal/service/document/document_crud.go
  • internal/service/document/document_dataset_update.go
  • internal/service/document/document_ingest.go
  • internal/service/document/document_metadata.go
  • internal/service/document/document_test.go
  • internal/service/document/file2document.go
  • internal/service/file_permission.go
  • internal/service/memory_message_test.go
  • internal/service/metadata.go
  • internal/service/metadata_filter.go
  • internal/service/model_service.go
  • internal/service/openai_chat.go
  • internal/service/search.go
  • internal/service/skill_indexer.go
  • internal/service/skill_search.go
  • internal/service/tag.go
  • internal/service/tenant.go
  • internal/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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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 with dao.DB.
  • internal/agent/tool/retrieval.go#L165-L165: obtain that propagated DB in InvokableRun; retain dao.DB only 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.

Comment thread internal/agent/tool/registry_test.go Outdated
// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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"})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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 || true

Repository: 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 240

Repository: 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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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: propagate ctx through tenant, canvas, and model lookups during creation.
  • internal/service/dataset/crud.go#L196-L196: pass ctx into deleteDataset and apply it to all queries, transactions, and supported engine cleanup.
  • internal/service/dataset/crud.go#L316-L316: pass ctx into tenant membership retrieval.
📍 Affects 1 file
  • internal/service/dataset/crud.go#L19-L19 (this comment)
  • internal/service/dataset/crud.go#L196-L196
  • internal/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.

Comment on lines +229 to 232
kb, err := d.kbDAO.GetByIDAndTenantID(ctx, dao.DB, id, tenantID)
if err != nil || kb == nil {
unauthorizedIDs = append(unauthorizedIDs, id)
continue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread internal/service/metadata.go Resolved
Comment on lines +3192 to 3193
func (m *ModelProviderService) GetEmbeddingModel(ctx context.Context, tenantID, compositeModelName string) (*modelModule.EmbeddingModel, error) {
driver, modelName, apiConfig, maxTokens, err := m.ResolveModelConfig(tenantID, entity.ModelTypeEmbedding, compositeModelName)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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

codecov Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (d2a769c) to head (2765812).
⚠️ Report is 1 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Signed-off-by: Jin Hai <[email protected]>
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 26, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 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 win

Guard the resolved storage reference before dereferencing it.

ResolveDocumentStorageOverride can return (nil, nil), but Line 647 dereferences ref.Bucket unconditionally. This panics; the PDF crop caller already handles ref == nil in internal/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

📥 Commits

Reviewing files that changed from the base of the PR and between 32fd27e and 65bef32.

📒 Files selected for processing (14)
  • internal/agent/tool/registry_test.go
  • internal/handler/dify_retrieval_handler.go
  • internal/handler/dify_retrieval_handler_test.go
  • internal/ingestion/component/chunker/pdfcrop_cgo.go
  • internal/ingestion/component/chunker/pdfcrop_nocgo.go
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/document_storage.go
  • internal/ingestion/component/parser.go
  • internal/service/dataset/index.go
  • internal/service/metadata.go
  • internal/service/model_chat.go
  • internal/service/model_service.go
  • internal/service/tag.go
  • internal/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

Comment thread internal/service/tag.go Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant