Skip to content

Go: add context, part9 - #17412

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

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

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

No description provided.

Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 27, 2026 05:51
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 27, 2026
@JinHai-CN JinHai-CN added ci Continue Integration and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 27, 2026
@coderabbitai

coderabbitai Bot commented Jul 27, 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: 816f67c9-6f95-4bb7-ba80-cf30343b4cd8

📥 Commits

Reviewing files that changed from the base of the PR and between 372cd05 and 28716f9.

📒 Files selected for processing (1)
  • internal/service/dataset/index.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/service/dataset/index.go

📝 Walkthrough

Walkthrough

This refactor propagates context.Context through DAO, service, handler, model-resolution, and pipeline execution paths. DAOs now accept explicit *gorm.DB handles and use WithContext, while callers and tests pass request- or test-scoped contexts.

Changes

Context propagation refactor

Layer / File(s) Summary
Context-aware DAO contracts
internal/dao/*.go
Pipeline logs, searches, skill-search configs, and skill spaces now use explicit database handles and context-aware GORM operations.
Search and skill integration
internal/service/search.go, internal/service/skill_*.go, internal/handler/search*.go, internal/handler/skill_search.go
Search, skill configuration, indexing, and space operations pass request contexts through service and DAO calls.
Model resolution paths
internal/service/model_service.go, internal/service/chat*.go, internal/service/dataset/*.go, internal/service/memory*.go
Model configuration, tenant lookups, dataset operations, chat flows, and memory operations use context-aware provider APIs.
Pipeline execution and validation
internal/ingestion/task/*
Pipeline log callbacks accept context and database handles; executor and integration tests use test contexts.
Supporting callers and behavior updates
internal/service/related_question.go, internal/service/user.go, internal/service/chunk/chunk.go, internal/handler/chat*.go, internal/service/*_test.go
Remaining call sites and tests are aligned with updated APIs, with selected error messages and not-found handling updated.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

Suggested labels: ☯️ refactor

Poem

I’m a rabbit with context in tow,
Through every DAO query I go.
With GORM close at hand,
Requests cross the land—
And pipeline logs neatly flow.

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning No PR description was provided, so the required Summary section and background context are missing. Add a Summary section that briefly explains the goal of the PR and any needed background context.
Docstring Coverage ⚠️ Warning Docstring coverage is 23.53% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is related to the PR, but "part9" is generic and doesn't describe the main change clearly. Use a concise title that names the main change, such as context threading across DAOs/services, instead of "part9".
✅ Passed checks (2 passed)
Check name Status Explanation
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.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 27, 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: 7

🧹 Nitpick comments (1)
internal/ingestion/task/pipeline_executor_test.go (1)

411-411: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the context and DB passed to the log hook.

This test accepts ctx and db but ignores both, so a regression that drops either argument at recordPipelineLog would still pass. Assert the hook receives taskCtx.Ctx (including the test value) and dao.DB, and verify that the hook was invoked.

🤖 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/pipeline_executor_test.go` at line 411, Update the
WithLogCreateFunc callback in the relevant pipeline executor test to assert it
receives taskCtx.Ctx, including its test value, and dao.DB. Also track the
callback invocation and assert it was called, while preserving the existing
successful hook behavior.
🤖 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/ingestion/task/pipeline_real_integration_test.go`:
- Around line 315-316: Update the processOutput invocation in the pipeline
integration test to pass the existing ctx from t.Context() instead of
context.Background(), preserving the same context through both pipe.Run and
svc.processOutput.

In `@internal/service/dataset/ingestion.go`:
- Around line 103-108: Update the error handling around
pipelineLogDAO.GetByIDAndKBID in the ingestion flow to check
dao.IsNotFoundErr(err) first and return the existing “log not found” message
with common.CodeDataError; retain the generic wrapped error and
common.CodeServerError response for other errors, while preserving the existing
nil-log guard.

In `@internal/service/dataset/search.go`:
- Around line 114-119: In the search detail lookup flow, check ctx.Err()
immediately after d.searchService.GetDetail returns and before the existing
invalid-result normalization. Return the context error unchanged for
cancellation or deadline expiration; keep the current invalid search_id response
for other lookup errors, nil results, or empty details.

In `@internal/service/search.go`:
- Around line 255-257: Update SearchService.GetSearchDetail to pass its existing
ctx argument into UserTenantDAO.GetByUserID, and ensure the DAO method accepts
and propagates that context through the tenant lookup. Preserve the current
userID-based lookup behavior.
- Around line 266-268: Update the error handling in the tenant loop around
SearchDAO.QueryByTenantIDAndID so context.Canceled and context.DeadlineExceeded
are returned immediately instead of discarded; retain the existing
continue-to-next-tenant behavior for other query errors.
- Around line 219-222: Update the duplicate-name validation in the create and
update flows around common.DuplicateName so errors from
searchDAO.GetByNameAndTenant are not discarded. Make the callback/API
error-aware and propagate lookup failures, ensuring database or timeout errors
fail closed instead of being treated as no duplicate.

In `@internal/service/skill_space.go`:
- Around line 422-433: Update asyncDeleteSpace to create a detached background
context with a bounded timeout at the start of the asynchronous cleanup, and use
that context for every DAO operation in the normal and panic-recovery paths,
including CASStatus. Preserve the existing cleanup behavior while ensuring final
status updates are not affected by the canceled HTTP request context.

---

Nitpick comments:
In `@internal/ingestion/task/pipeline_executor_test.go`:
- Line 411: Update the WithLogCreateFunc callback in the relevant pipeline
executor test to assert it receives taskCtx.Ctx, including its test value, and
dao.DB. Also track the callback invocation and assert it was called, while
preserving the existing successful hook behavior.
🪄 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: 848bc262-f95c-48ed-b0b5-a64790ba6df6

📥 Commits

Reviewing files that changed from the base of the PR and between f5aa5f7 and caf2e8f.

📒 Files selected for processing (22)
  • internal/dao/pipeline_operation_log.go
  • internal/dao/search.go
  • internal/dao/search_detail_test.go
  • internal/dao/skill_search_config.go
  • internal/dao/skill_space.go
  • internal/handler/chat.go
  • internal/handler/search.go
  • internal/handler/searchbot.go
  • internal/handler/skill_search.go
  • internal/ingestion/task/pipeline_executor.go
  • internal/ingestion/task/pipeline_executor_test.go
  • internal/ingestion/task/pipeline_real_integration_test.go
  • internal/service/chunk/chunk.go
  • internal/service/dataset/ingestion.go
  • internal/service/dataset/search.go
  • internal/service/related_question.go
  • internal/service/search.go
  • internal/service/search_share_detail_test.go
  • internal/service/search_test.go
  • internal/service/skill_indexer.go
  • internal/service/skill_search.go
  • internal/service/skill_space.go

Comment thread internal/service/dataset/ingestion.go Outdated
Comment on lines +103 to +108
log, err := d.pipelineLogDAO.GetByIDAndKBID(ctx, dao.DB, logID, datasetID)
if err != nil {
return nil, common.CodeServerError, fmt.Errorf("get ingestion log: %w", err)
}
if log == nil {
return nil, common.CodeDataError, errors.New("Log not found")
return nil, common.CodeDataError, errors.New("log not found")

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

Map missing logs to the data-error path.

GetByIDAndKBID returns (nil, gorm.ErrRecordNotFound) for a missing row, so Line [107] is unreachable in that case. The current branch returns CodeServerError instead of "log not found" with CodeDataError. Check dao.IsNotFoundErr(err) before the generic error 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/ingestion.go` around lines 103 - 108, Update the
error handling around pipelineLogDAO.GetByIDAndKBID in the ingestion flow to
check dao.IsNotFoundErr(err) first and return the existing “log not found”
message with common.CodeDataError; retain the generic wrapped error and
common.CodeServerError response for other errors, while preserving the existing
nil-log guard.

Comment thread internal/service/dataset/search.go Resolved
Comment on lines 219 to 222
uniqueName, err := common.DuplicateName(func(name string, tid string) bool {
existing, _ := s.searchDAO.GetByNameAndTenant(name, tid)
existing, _ := s.searchDAO.GetByNameAndTenant(ctx, dao.DB, name, tid)
return len(existing) > 0
}, name, userID)

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

Fail closed when duplicate-name lookups fail.

GetByNameAndTenant errors are discarded in both create and update flows. A timeout or database failure is treated as “no duplicate,” allowing writes to proceed with incomplete validation. Propagate the lookup error, or make DuplicateName error-aware.

Also applies to: 578-583

🤖 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` around lines 219 - 222, Update the duplicate-name
validation in the create and update flows around common.DuplicateName so errors
from searchDAO.GetByNameAndTenant are not discarded. Make the callback/API
error-aware and propagate lookup failures, ensuring database or timeout errors
fail closed instead of being treated as no duplicate.

Comment on lines +255 to 257
func (s *SearchService) GetSearchDetail(ctx context.Context, userID string, searchID string) (*entity.Search, error) {
// Step 1: Get user tenants (same as Python UserTenantService.query(user_id=current_user.id))
tenants, err := s.userTenantDAO.GetByUserID(userID)

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 the request context through the tenant lookup.

GetSearchDetail accepts ctx, but Line [257] still calls UserTenantDAO.GetByUserID without it. Canceled or timed-out requests can remain blocked in this permission query.

🤖 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` around lines 255 - 257, Update
SearchService.GetSearchDetail to pass its existing ctx argument into
UserTenantDAO.GetByUserID, and ensure the DAO method accepts and propagates that
context through the tenant lookup. Preserve the current userID-based lookup
behavior.

Comment thread internal/service/search.go Resolved
Comment thread internal/service/skill_space.go Resolved
Signed-off-by: Jin Hai <[email protected]>
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 27, 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 (3)
internal/service/model_service.go (3)

3251-3276: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Complete context propagation through model resolution.

The public APIs now accept request contexts, but several underlying tenant, provider, instance, and model lookups still use contextless DAO/helper paths.

  • internal/service/model_service.go#L3251-L3276: use a context-aware tenant lookup in GetTenantDefaultModelByType.
  • internal/service/model_service.go#L3279-L3311: pass context through every DAO call in GetModelConfigByID, not only the tenant-relation lookup.
  • internal/service/model_service.go#L3391-L3401: add context to GetModelConfigFromProviderInstance and its downstream lookups.
  • internal/service/model_service.go#L3403-L3461: add context to the composite-model provider, instance, and model lookups.
🤖 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 3251 - 3276, Propagate the
request context through all model-resolution lookups: update
GetTenantDefaultModelByType to use the context-aware tenant DAO method; update
every DAO call in GetModelConfigByID to pass ctx; extend
GetModelConfigFromProviderInstance and its downstream lookups with ctx; and pass
ctx through the composite-model provider, instance, and model lookups. Apply
these changes at internal/service/model_service.go ranges 3251-3276, 3279-3311,
3391-3401, and 3403-3461, preserving existing fallback and error behavior.

1002-1025: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Preserve failures from ListModels.

When the remote model listing fails—including cancellation, deadline, authentication, or network errors—listErr is discarded and the method reports only no models found for provider. Return or wrap listErr so callers receive the actual failure.

🤖 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 1002 - 1025, Update the
remote model fallback in the model verification method around driver.ListModels
so any non-nil listErr is returned or wrapped immediately, preserving
cancellation, deadline, authentication, and network failures; only return “no
models found for provider” when listing succeeds but yields no usable models.

1002-1020: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Verify each remote model independently.

The new fallback can return multiple models of the same type, but passedTypes is global and keyed only by model type. After the first chat model passes, later chat models are skipped and then marked ModelVerifyFail because anyPassed remains false.

Use a per-model-and-type key, or remove cross-model deduplication.

Proposed fix
-			if passedTypes[mtLower] {
+			verifyKey := modelName + "\x00" + mtLower
+			if passedTypes[verifyKey] {
 				continue
 			}
...
-				passedTypes[mtLower] = true
+				passedTypes[verifyKey] = true
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/service/model_service.go` around lines 1002 - 1020, Update the
verification logic following the remote-model population in the fallback so
deduplication is scoped to both model identity and model type, rather than the
global type-only passedTypes key. Ensure every remote model is independently
verified, while preserving deduplication for repeated checks of the same
model/type pair and correct anyPassed/ModelVerifyFail handling.
🤖 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/dataset/index.go`:
- Around line 442-443: Update the verifyEmbeddingAvailability call in the
dataset flow to pass kb.TenantID instead of userID, matching the tenant used by
the later embedding resolution and preserving consistent shared-dataset
validation.

---

Outside diff comments:
In `@internal/service/model_service.go`:
- Around line 3251-3276: Propagate the request context through all
model-resolution lookups: update GetTenantDefaultModelByType to use the
context-aware tenant DAO method; update every DAO call in GetModelConfigByID to
pass ctx; extend GetModelConfigFromProviderInstance and its downstream lookups
with ctx; and pass ctx through the composite-model provider, instance, and model
lookups. Apply these changes at internal/service/model_service.go ranges
3251-3276, 3279-3311, 3391-3401, and 3403-3461, preserving existing fallback and
error behavior.
- Around line 1002-1025: Update the remote model fallback in the model
verification method around driver.ListModels so any non-nil listErr is returned
or wrapped immediately, preserving cancellation, deadline, authentication, and
network failures; only return “no models found for provider” when listing
succeeds but yields no usable models.
- Around line 1002-1020: Update the verification logic following the
remote-model population in the fallback so deduplication is scoped to both model
identity and model type, rather than the global type-only passedTypes key.
Ensure every remote model is independently verified, while preserving
deduplication for repeated checks of the same model/type pair and correct
anyPassed/ModelVerifyFail handling.
🪄 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: f86d5ff9-ee0b-42c5-a4e2-a217ad524182

📥 Commits

Reviewing files that changed from the base of the PR and between caf2e8f and 372cd05.

📒 Files selected for processing (21)
  • internal/handler/chat_audio.go
  • internal/ingestion/task/pipeline_real_integration_test.go
  • internal/service/chat.go
  • internal/service/chat_pipeline.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/chunk/chunk.go
  • internal/service/dataset/crud.go
  • internal/service/dataset/index.go
  • internal/service/dataset/ingestion.go
  • internal/service/dataset/search.go
  • internal/service/dataset/update.go
  • internal/service/generator.go
  • internal/service/memory.go
  • internal/service/memory_message_service.go
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • internal/service/openai_chat.go
  • internal/service/search.go
  • internal/service/skill_space.go
  • internal/service/user.go
💤 Files with no reviewable changes (1)
  • internal/service/user.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/ingestion/task/pipeline_real_integration_test.go
  • internal/service/dataset/ingestion.go
  • internal/service/dataset/search.go
  • internal/service/skill_space.go
  • internal/service/search.go

Comment thread internal/service/dataset/index.go Resolved
@JinHai-CN
JinHai-CN merged commit 3065a29 into infiniflow:main Jul 27, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant