Repository navigation
Fix(Go): prevent global state pollution in local model connection check - #14669
Conversation
📝 WalkthroughWalkthroughThis 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. ChangesVolcEngine Embedding & Provider Refactoring
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 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
📒 Files selected for processing (8)
conf/models/volcengine.jsoninternal/cli/user_command.gointernal/entity/models/lmstudio.gointernal/entity/models/ollama.gointernal/entity/models/siliconflow.gointernal/entity/models/vllm.gointernal/entity/models/volcengine.gointernal/service/model_service.go
| for i, text := range texts { | ||
|
|
||
| reqBody := map[string]interface{}{ | ||
| "model": *modelName, |
There was a problem hiding this comment.
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.
| if baseURL, ok := extra["base_url"]; ok && baseURL != "" { | ||
| newURL := map[string]string{ | ||
| region: baseURL, | ||
| } | ||
| providerInfo.ModelDriver = providerInfo.ModelDriver.NewInstance(newURL) | ||
|
|
||
| driver = driver.NewInstance(newURL) | ||
| } |
There was a problem hiding this comment.
Harden per-request driver construction for empty region and nil NewInstance.
Two problems here:
- If
region == "", base URL is stored under""instead of"default"(Line 207 / Line 464), so local providers still fail with “missing base URL”. - If a provider’s
NewInstancereturnsnil, 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
…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)
…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)
What problem does this PR solve?
model_service.go. Previously,ListSupportedModelswould permanently overwrite the global provider singleton with a localized URL instance (driver.NewInstance). This caused cross-request contamination in multi-tenant environments.CheckProviderConnectionfor local models (LM Studio, vLLM, Ollama). It now properly creates a localized driver copy and injects thebase_urlbefore testing the connection, entirely eliminating the false-positivemissing base URLerror without polluting the global state.VolcEngineEmbeddings: - Fully implemented theEncodemethod for thevolcengineprovider, enabling text embedding capabilities for VolcEngine models.SiliconFlow: - Added a strict empty string check (*apiConfig.Region != "") alongside the existingnilcheck 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 andunsupported protocol schemeerrors.Type of change