Skip to content

Go: add context, part13 - #17445

Merged
JinHai-CN merged 7 commits into
infiniflow:mainfrom
JinHai-CN:fix590
Jul 27, 2026
Merged

JinHai-CN merged 7 commits into
infiniflow:mainfrom
JinHai-CN:fix590

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

No description provided.

Signed-off-by: Jin Hai <[email protected]>
@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: 03005c39-a2d9-4560-90ae-7f66df52ef91

📥 Commits

Reviewing files that changed from the base of the PR and between cdccc53 and 175b645.

📒 Files selected for processing (3)
  • internal/agent/component/browser.go
  • internal/dao/tenant_model_instance.go
  • internal/service/model_service.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/agent/component/browser.go
  • internal/dao/tenant_model_instance.go
  • internal/service/model_service.go

📝 Walkthrough

Walkthrough

The change propagates request contexts and explicit GORM handles through DAO, service, agent, ingestion, and provider model-resolution paths. It also updates related tests, browser error wrapping, OCR availability handling, and selected validation messages.

Changes

Context-aware model resolution

Layer / File(s) Summary
DAO context and database contracts
internal/dao/*
Tenant LLM, tenant model, provider, instance, group, mapping, and time-record DAO operations now accept context.Context and *gorm.DB, using context-bound database operations.
Agent and browser resolution
internal/agent/component/*
Agent, categorization, LLM, browser, and credential resolution paths now pass context and database handles through tenant model lookups; browser errors are wrapped with browser: context.
Provider service flow
internal/handler/providers.go, internal/service/model_service.go
Provider handlers and model-provider operations now propagate request contexts through CRUD, verification, OCR setup, modality endpoints, and model configuration resolution.
Ingestion model dispatch
internal/ingestion/component/*
Tenant model configuration, PDF vision resolution, extractor calls, auto-tags, keywords, and questions now use context- and database-aware resolution.
Supporting service integrations
internal/service/*
Supporting service calls now use updated context-aware model, tenant LLM, display-name, and availability APIs.

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

Possibly related PRs

Suggested labels: ☯️ refactor

Poem

I’m a rabbit with context tucked tight,
Passing DB handles from day into night.
Models resolve, browsers behave,
DAOs now know the paths they pave.
Hop, hop—clean calls arrive!

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is missing the required Summary section and provides no purpose or background. Add the template’s Summary section with a brief purpose statement and relevant background context.
Docstring Coverage ⚠️ Warning Docstring coverage is 45.00% 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 change, but it is too generic and doesn't clearly identify the scope beyond a numbered context update. Use a more specific title that summarizes the main area affected by the context propagation changes.
✅ 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.

@JinHai-CN
JinHai-CN marked this pull request as ready for review July 27, 2026 12:23
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 27, 2026
@JinHai-CN JinHai-CN added ci Continue Integration and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 27, 2026
Signed-off-by: Jin Hai <[email protected]>
@dosubot dosubot Bot added the size:XL This PR changes 500-999 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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/service/llm.go (1)

377-400: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Do not report success after tenant LLM persistence fails.

GetByTenantFactoryAndModelName currently returns an error for missing records, but the service ignores it and falls back to creation. Updates and Create errors are also ignored, so failed persistence still returns Success: true. Use explicit not-found handling and return errors from the lookup, update, and create paths.

🤖 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/llm.go` around lines 377 - 400, Update the tenant LLM
persistence flow around GetByTenantFactoryAndModelName to distinguish a
not-found error from other lookup failures: continue to creation only for an
explicit not-found result, and return other errors immediately. Check and
propagate errors from both the Updates call and tenantLLMDAO.Create so the
service cannot return success when persistence fails.
🧹 Nitpick comments (1)
internal/dao/tenant_model.go (1)

38-51: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Batch-insert via slice instead of a Create-per-row loop.

CreateBatch still issues one INSERT per model inside the transaction. GORM supports passing the whole slice to Create (or CreateInBatches for very large sets) for a single round-trip, which is materially faster and still transactional.

⚡ Proposed batch-insert refactor
 func (dao *TenantModelDAO) CreateBatch(ctx context.Context, db *gorm.DB, models []*entity.TenantModel) error {
 	if len(models) == 0 {
 		return nil
 	}

-	return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
-		for _, model := range models {
-			if err := tx.WithContext(ctx).Create(model).Error; err != nil {
-				return err
-			}
-		}
-		return nil
-	})
+	return db.WithContext(ctx).Create(&models).Error
 }
🤖 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/tenant_model.go` around lines 38 - 51, Update
TenantModelDAO.CreateBatch to pass the entire models slice to GORM’s Create or
CreateInBatches within the existing transaction, removing the per-model Create
loop while preserving the empty-slice early return and transactional error
propagation.
🤖 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/browser.go`:
- Around line 540-551: Update resolveTenantLLM so the factory-empty branch uses
a new factory-agnostic DAO lookup by tenant and model name rather than
GetByTenantAndModelName with an empty factory. Implement the DAO query in
TenantLLMDAO to match tenantID and modelName across factories, return the
credential for a unique match, and return an ambiguity error when multiple
factory records exist. Add coverage for both unique resolution and
duplicate-factory rejection.

In `@internal/service/tenant.go`:
- Around line 712-713: Restrict the early return in checkModelAvailable to the
deepdoc model only by adding the required model-name check alongside modelType,
providerName, and instanceName. Keep other OCR models on the normal availability
and type-validation path, including the flow used by SetTenantDefaultModels.

---

Outside diff comments:
In `@internal/service/llm.go`:
- Around line 377-400: Update the tenant LLM persistence flow around
GetByTenantFactoryAndModelName to distinguish a not-found error from other
lookup failures: continue to creation only for an explicit not-found result, and
return other errors immediately. Check and propagate errors from both the
Updates call and tenantLLMDAO.Create so the service cannot return success when
persistence fails.

---

Nitpick comments:
In `@internal/dao/tenant_model.go`:
- Around line 38-51: Update TenantModelDAO.CreateBatch to pass the entire models
slice to GORM’s Create or CreateInBatches within the existing transaction,
removing the per-model Create loop while preserving the empty-slice early return
and transactional error propagation.
🪄 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: 3878700f-c0d6-4c5e-bbae-d0f05bd147ad

📥 Commits

Reviewing files that changed from the base of the PR and between f9e47ae and 4afc947.

📒 Files selected for processing (25)
  • internal/agent/component/agent.go
  • internal/agent/component/browser.go
  • internal/agent/component/browser_test.go
  • internal/agent/component/categorize.go
  • internal/agent/component/llm.go
  • internal/agent/component/llm_credentials.go
  • internal/dao/tenant_llm.go
  • internal/dao/tenant_model.go
  • internal/dao/tenant_model_test.go
  • internal/handler/providers.go
  • internal/ingestion/component/dispatch_model.go
  • internal/ingestion/component/extractor.go
  • internal/ingestion/component/extractor_tag.go
  • internal/ingestion/component/extractor_test.go
  • internal/ingestion/component/pdf_vision_dispatch.go
  • internal/service/chat_pipeline.go
  • internal/service/chunk/chunk.go
  • internal/service/dataset/crud.go
  • internal/service/generator.go
  • internal/service/llm.go
  • internal/service/memory.go
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • internal/service/tenant.go
  • internal/service/user.go

Comment thread internal/agent/component/browser.go Outdated
Comment on lines +540 to +551
func resolveTenantLLM(ctx context.Context, db *gorm.DB, tenantID, modelName, factory string) (apiKey, baseURL string, err error) {
dao := dao.NewTenantLLMDAO()
var (
row *entity.TenantLLM
)
if factory != "" {
row, err = dao.GetByTenantFactoryAndModelName(tenantID, factory, modelName)
row, err = dao.GetByTenantFactoryAndModelName(ctx, db, tenantID, factory, modelName)
} else {
// No factory suffix on llm_id; fall back to a single-key
// lookup (errors if the model is registered under multiple
// factories — caller must use the explicit form).
row, err = dao.GetByTenantAndModelName(tenantID, "", modelName)
row, err = dao.GetByTenantAndModelName(ctx, db, tenantID, "", modelName)

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

Use a factory-agnostic lookup for bare llm_ids.

GetByTenantAndModelName(ctx, db, tenantID, "", modelName) queries llm_factory = ""; it is not a single-key lookup. Thus a bare ID such as gpt-4o cannot resolve a tenant credential registered under OpenAI. Add a DAO query by tenant/model name that rejects ambiguity, and cover both unique and duplicate-factory cases. As per coding guidelines, inspect the nearest behavior-owning path; internal/dao/tenant_llm.go confirms the exact factory filter.

🤖 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/browser.go` around lines 540 - 551, Update
resolveTenantLLM so the factory-empty branch uses a new factory-agnostic DAO
lookup by tenant and model name rather than GetByTenantAndModelName with an
empty factory. Implement the DAO query in TenantLLMDAO to match tenantID and
modelName across factories, return the credential for a unique match, and return
an ambiguity error when multiple factory records exist. Add coverage for both
unique resolution and duplicate-factory rejection.

Source: Coding guidelines

Comment on lines +712 to 713
if modelType == "ocr" && providerName == "infiniflow" && instanceName == "default" {
return nil

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 bypass OCR validation for every model name.

This condition now treats every ocr model under infiniflow/default as available, despite the comment and GetModelInfo special case being limited to deepdoc. That can allow an incorrectly typed or unavailable model to pass checkModelAvailable; SetTenantDefaultModels then stores the resolved model without rechecking its type.

-	if modelType == "ocr" && providerName == "infiniflow" && instanceName == "default" {
+	if modelType == "ocr" && providerName == "infiniflow" && instanceName == "default" && modelName == "deepdoc" {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if modelType == "ocr" && providerName == "infiniflow" && instanceName == "default" {
return nil
if modelType == "ocr" && providerName == "infiniflow" && instanceName == "default" && modelName == "deepdoc" {
return nil
🤖 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/tenant.go` around lines 712 - 713, Restrict the early return
in checkModelAvailable to the deepdoc model only by adding the required
model-name check alongside modelType, providerName, and instanceName. Keep other
OCR models on the normal availability and type-validation path, including the
flow used by SetTenantDefaultModels.

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

🧹 Nitpick comments (2)
internal/dao/tenant_model_instance.go (1)

82-89: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Use AND instead of && in the WHERE clause.

&& is MySQL-only shorthand for logical AND (a different operator, e.g. array overlap, on Postgres) and is inconsistent with every other predicate in this file, which uses AND.

♻️ Proposed fix
-	err := db.WithContext(ctx).Where("api_key = ? && provider_id = ?", apiKey, providerID).First(&instance).Error
+	err := db.WithContext(ctx).Where("api_key = ? AND provider_id = ?", apiKey, providerID).First(&instance).Error

Please confirm the production database backend (MySQL-only vs. also Postgres) to determine if this is purely a style nit or a portability risk.

🤖 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/tenant_model_instance.go` around lines 82 - 89, Update the WHERE
clause in TenantModelInstanceDAO.GetInstanceByApiKey to use the portable SQL AND
operator instead of && between the api_key and provider_id predicates,
preserving the existing filters and query behavior.
internal/service/model_service.go (1)

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

Remove stale TODO — Builtin is already handled in this function.

The Builtin case is fully resolved later in getModelConfig (the if providerName == "Builtin" block returns a builtin driver directly), so this TODO is stale and misleading.

🧹 Proposed fix
 	}
-	// TODO: if provider name is Builtin, HOW TO?
 
 	var extra map[string]string

As per coding guidelines, "Remove dead tests, commented-out code, stale documentation, and 'move later' notes instead of preserving them."

🤖 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 3906 - 3923, Remove the stale
TODO comment after the provider instance lookup in getModelConfig; Builtin
handling is already implemented by the later providerName == "Builtin" branch,
so leave the existing lookup and return behavior unchanged.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/dao/tenant_model_instance.go`:
- Around line 82-89: Update the WHERE clause in
TenantModelInstanceDAO.GetInstanceByApiKey to use the portable SQL AND operator
instead of && between the api_key and provider_id predicates, preserving the
existing filters and query behavior.

In `@internal/service/model_service.go`:
- Around line 3906-3923: Remove the stale TODO comment after the provider
instance lookup in getModelConfig; Builtin handling is already implemented by
the later providerName == "Builtin" branch, so leave the existing lookup and
return behavior unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3a98aa2a-7d33-4de3-ad40-e9545d050e5d

📥 Commits

Reviewing files that changed from the base of the PR and between 4afc947 and cdccc53.

📒 Files selected for processing (13)
  • internal/agent/component/browser.go
  • internal/agent/component/llm_credentials.go
  • internal/dao/tenant_model_group.go
  • internal/dao/tenant_model_group_mapping.go
  • internal/dao/tenant_model_instance.go
  • internal/dao/tenant_model_provider.go
  • internal/dao/time_record.go
  • internal/handler/providers.go
  • internal/ingestion/component/dispatch_model.go
  • internal/service/memory.go
  • internal/service/model_service.go
  • internal/service/openai_chat.go
  • internal/service/tenant.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • internal/ingestion/component/dispatch_model.go
  • internal/agent/component/llm_credentials.go
  • internal/agent/component/browser.go
  • internal/service/memory.go
  • internal/handler/providers.go
  • internal/service/tenant.go

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