Skip to content

Fix(Go): prevent global state pollution in local model connection check - #14669

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main
May 8, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

  1. Fix Global State Pollution in Local Providers (Critical Bug): - Resolved a severe concurrency and architecture issue in model_service.go. Previously, ListSupportedModels would permanently overwrite the global provider singleton with a localized URL instance (driver.NewInstance). This caused cross-request contamination in multi-tenant environments.
    • Fixed CheckProviderConnection for local models (LM Studio, vLLM, Ollama). It now properly creates a localized driver copy and injects the base_url before testing the connection, entirely eliminating the false-positive missing base URL error without polluting the global state.
  2. Implement VolcEngine Embeddings: - Fully implemented the Encode method for the volcengine provider, enabling text embedding capabilities for VolcEngine models.
  3. Enhance Region Validation in SiliconFlow: - Added a strict empty string check (*apiConfig.Region != "") alongside the existing nil check when parsing regions. This ensures that if an empty string is passed, the system safely falls back to the "default" region, preventing malformed URL requests and unsupported protocol scheme errors.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 8, 2026
@Haruko386 Haruko386 added ci Continue Integration and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 8, 2026
@Haruko386
Haruko386 marked this pull request as draft May 8, 2026 06:55
@Haruko386
Haruko386 marked this pull request as ready for review May 8, 2026 06:55
@dosubot dosubot Bot added 🐞 bug Something isn't working, pull request that fix bug. size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels May 8, 2026
@coderabbitai

coderabbitai Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR extends VolcEngine with embedding support, consolidates provider connection checking logic, introduces error standardization, and enables dynamic base_url configuration for local-deployed model providers.

Changes

VolcEngine Embedding & Provider Refactoring

Layer / File(s) Summary
Configuration & Model Definition
conf/models/volcengine.json
Added embedding: "embeddings/multimodal" to url_suffix and registered new model doubao-embedding-vision-250615 with max_tokens: 131072 and model_types: ["embedding"].
Error Handling Utility
internal/cli/user_command.go
New formatRequestError(action, err) helper standardizes EOF, timeout, and generic error formatting; ChatToModel non-stream path now uses this helper instead of inline classification.
Provider Connection Check Consolidation
internal/entity/models/lmstudio.go, ollama.go, vllm.go
CheckConnection methods simplified across three providers to directly call ListModels(apiConfig) and return its error, removing prior region selection, base URL validation, and custom error wrapping.
Defensive Region Selection
internal/entity/models/siliconflow.go
ListModels now checks that apiConfig.Region is both non-nil and non-empty before updating region, preserving default fallback when Region is present but blank.
VolcEngine Embedding Implementation
internal/entity/models/volcengine.go
Encode method fully implemented: validates empty input, resolves region and embedding endpoint, loops over texts, marshals requests, performs HTTP calls with Content-Type and Authorization headers, unmarshals responses, validates non-empty embeddings, and returns aligned results or descriptive errors.
Model Service Instance Switching
internal/service/model_service.go
ListSupportedModels and CheckProviderConnection now detect base_url in instance Extra and dynamically create NewInstance with region-keyed base_url map before calling driver methods, enabling proper routing for local-deployed providers.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

  • infiniflow/ragflow#14614: Introduces the same CheckConnection simplifications across lmstudio, ollama, and vllm providers.
  • infiniflow/ragflow#14546: Related model_service.py changes to instance handling and driver usage patterns for local deployments.
  • infiniflow/ragflow#14409: Adds foundational VolcEngine provider support; this PR extends it with embedding functionality.

Suggested labels

☯️ refactor, size:XL

Poem

🐰 A rabbit hops through embedding trails,
VolcEngine's vectors never fail,
Providers check their connection state,
Error helpers standardize with grace,
Instance switching sets the pace! 🚀

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main critical bug fix: preventing global state pollution in local model connection checks, which aligns with the primary purpose described in the PR objectives.
Description check ✅ Passed The PR description provides comprehensive details on three distinct changes, identifies the problem types (critical bug fix and new feature), and includes the Type of change section with appropriate boxes checked, matching the repository template.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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 and usage tips.

@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

🤖 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/entity/models/volcengine.go`:
- Line 427: In Encode (internal/entity/models/volcengine.go) guard all pointer
dereferences — check that modelName != nil before using *modelName and that
apiConfig != nil and apiConfig.ApiKey != nil before using those values; if any
are nil return a clear error (or skip adding those fields) instead of
dereferencing, and mirror the same nil-checks for the second occurrence around
line 451 so Encode never panics when modelName, apiConfig, or apiConfig.ApiKey
are nil.

In `@internal/service/model_service.go`:
- Around line 205-211: The per-request driver creation stores base URL under
possibly empty region and doesn't guard against NewInstance returning nil;
update the logic that builds newURL so it uses "default" when region == ""
(i.e., key := region; if key=="" { key = "default" }) and after calling
driver.NewInstance(newURL) check for a nil return and handle it the same way
CheckProviderConnection does (return an error / nil result instead of assigning
a nil driver and allowing later panics). Apply the same fix to the other
occurrence mentioned (around driver.NewInstance at lines ~461-467) so both spots
use the "default" key and validate NewInstance != nil.
🪄 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

Run ID: 45593319-0093-42a8-909f-c2aa2b0db991

📥 Commits

Reviewing files that changed from the base of the PR and between d843035 and bbf9e3f.

📒 Files selected for processing (8)
  • conf/models/volcengine.json
  • internal/cli/user_command.go
  • internal/entity/models/lmstudio.go
  • internal/entity/models/ollama.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/vllm.go
  • internal/entity/models/volcengine.go
  • internal/service/model_service.go

for i, text := range texts {

reqBody := map[string]interface{}{
"model": *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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Guard pointer dereferences in Encode to avoid panics.

Line 427 and Line 451 dereference pointers without validation. A nil modelName, apiConfig, or apiConfig.ApiKey will panic at runtime.

Suggested fix
 func (z *VolcEngine) Encode(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([][]float64, error) {
 	if len(texts) == 0 {
 		return [][]float64{}, nil
 	}
+	if modelName == nil || *modelName == "" {
+		return nil, fmt.Errorf("model name is required")
+	}
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("api key is required")
+	}
@@
 		reqBody := map[string]interface{}{
-			"model":           *modelName,
+			"model":           *modelName,
 			"encoding_format": "float",
@@
-		req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
+		req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))

Also applies to: 451-451

🤖 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/entity/models/volcengine.go` at line 427, In Encode
(internal/entity/models/volcengine.go) guard all pointer dereferences — check
that modelName != nil before using *modelName and that apiConfig != nil and
apiConfig.ApiKey != nil before using those values; if any are nil return a clear
error (or skip adding those fields) instead of dereferencing, and mirror the
same nil-checks for the second occurrence around line 451 so Encode never panics
when modelName, apiConfig, or apiConfig.ApiKey are nil.

Comment on lines 205 to 211
if baseURL, ok := extra["base_url"]; ok && baseURL != "" {
newURL := map[string]string{
region: baseURL,
}
providerInfo.ModelDriver = providerInfo.ModelDriver.NewInstance(newURL)

driver = driver.NewInstance(newURL)
}

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Harden per-request driver construction for empty region and nil NewInstance.

Two problems here:

  1. If region == "", base URL is stored under "" instead of "default" (Line 207 / Line 464), so local providers still fail with “missing base URL”.
  2. If a provider’s NewInstance returns nil, later calls can panic.
Suggested fix pattern
-	if baseURL, ok := extra["base_url"]; ok && baseURL != "" {
-		newURL := map[string]string{
-			region: baseURL,
-		}
-		driver = driver.NewInstance(newURL)
-	}
+	if baseURL, ok := extra["base_url"]; ok && baseURL != "" {
+		regionKey := "default"
+		if region != "" {
+			regionKey = region
+		}
+		newURL := map[string]string{
+			regionKey: baseURL,
+		}
+		newDriver := driver.NewInstance(newURL)
+		if newDriver == nil {
+			return nil, fmt.Errorf("provider %s does not support localized instance", providerName)
+		}
+		driver = newDriver
+	}

Use the same guard in CheckProviderConnection (adapt return type accordingly).

Also applies to: 461-467

🤖 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 205 - 211, The per-request
driver creation stores base URL under possibly empty region and doesn't guard
against NewInstance returning nil; update the logic that builds newURL so it
uses "default" when region == "" (i.e., key := region; if key=="" { key =
"default" }) and after calling driver.NewInstance(newURL) check for a nil return
and handle it the same way CheckProviderConnection does (return an error / nil
result instead of assigning a nil driver and allowing later panics). Apply the
same fix to the other occurrence mentioned (around driver.NewInstance at lines
~461-467) so both spots use the "default" key and validate NewInstance != nil.

@codecov

codecov Bot commented May 8, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14669   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ View full report in Codecov by Sentry.
📢 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.

@JinHai-CN
JinHai-CN merged commit 94f82ac into infiniflow:main May 8, 2026
1 check passed
pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
…ck (infiniflow#14669)

### What problem does this PR solve?

1. **Fix Global State Pollution in Local Providers (Critical Bug):** -
Resolved a severe concurrency and architecture issue in
`model_service.go`. Previously, `ListSupportedModels` would permanently
overwrite the global provider singleton with a localized URL instance
(`driver.NewInstance`). This caused cross-request contamination in
multi-tenant environments.
- Fixed `CheckProviderConnection` for local models (LM Studio, vLLM,
Ollama). It now properly creates a localized driver copy and injects the
`base_url` before testing the connection, entirely eliminating the
false-positive `missing base URL` error without polluting the global
state.
2. **Implement `VolcEngine` Embeddings:** - Fully implemented the
`Encode` method for the `volcengine` provider, enabling text embedding
capabilities for VolcEngine models.
3. **Enhance Region Validation in `SiliconFlow`:** - Added a strict
empty string check (`*apiConfig.Region != ""`) alongside the existing
`nil` check when parsing regions. This ensures that if an empty string
is passed, the system safely falls back to the `"default"` region,
preventing malformed URL requests and `unsupported protocol scheme`
errors.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] New Feature (non-breaking change which adds functionality)
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…ck (infiniflow#14669)

### What problem does this PR solve?

1. **Fix Global State Pollution in Local Providers (Critical Bug):** -
Resolved a severe concurrency and architecture issue in
`model_service.go`. Previously, `ListSupportedModels` would permanently
overwrite the global provider singleton with a localized URL instance
(`driver.NewInstance`). This caused cross-request contamination in
multi-tenant environments.
- Fixed `CheckProviderConnection` for local models (LM Studio, vLLM,
Ollama). It now properly creates a localized driver copy and injects the
`base_url` before testing the connection, entirely eliminating the
false-positive `missing base URL` error without polluting the global
state.
2. **Implement `VolcEngine` Embeddings:** - Fully implemented the
`Encode` method for the `volcengine` provider, enabling text embedding
capabilities for VolcEngine models.
3. **Enhance Region Validation in `SiliconFlow`:** - Added a strict
empty string check (`*apiConfig.Region != ""`) alongside the existing
`nil` check when parsing regions. This ensures that if an empty string
is passed, the system safely falls back to the `"default"` region,
preventing malformed URL requests and `unsupported protocol scheme`
errors.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] New Feature (non-breaking change which adds functionality)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants