Repository navigation
Fix: Align part of Go provider APIs with Python APIs - #16823
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughProvider instance creation and alteration now accept model metadata, verify provider connections, persist instance details, and reconcile tenant models. Provider listings expose instance presence, and provider deletion removes dependent tenant records. ChangesProvider instance lifecycle
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant ProviderHandler
participant ModelProviderService
participant ProviderDriver
participant TenantModelInstanceDAO
participant TenantModelDAO
ProviderHandler->>ModelProviderService: CreateProviderInstance(modelInfo)
ModelProviderService->>ProviderDriver: CheckConnection
ProviderDriver-->>ModelProviderService: verification statuses
ModelProviderService->>TenantModelInstanceDAO: create instance
ModelProviderService->>TenantModelDAO: create models
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/service/model_service.go (1)
414-417: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winInconsistent error code for a missing provider.
When
GetByTenantIDAndProviderNamefails (includinggorm.ErrRecordNotFound), this returnsCodeServerError, whereasDeleteModelProvidermaps the same "provider not found" case toCodeNotFound(Line 283). Align the two so a missing provider surfaces as a 404 rather than a 500.Proposed change
provider, err := m.modelProviderDAO.GetByTenantIDAndProviderName(tenantID, providerName) if err != nil { - return common.CodeServerError, err + if errors.Is(err, gorm.ErrRecordNotFound) { + return common.CodeNotFound, fmt.Errorf("provider %s not found", providerName) + } + return common.CodeServerError, err }🤖 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 414 - 417, Update the provider lookup error handling in the relevant model-provider deletion method to detect gorm.ErrRecordNotFound and return common.CodeNotFound, matching DeleteModelProvider’s existing behavior; preserve common.CodeServerError for other errors. Use GetByTenantIDAndProviderName and the surrounding deletion method as the implementation points.
🧹 Nitpick comments (3)
internal/dao/tenant_model_instance.go (1)
114-118: 🗄️ Data Integrity & Integration | 🔵 Trivial | 🏗️ Heavy liftConsider wrapping the multi-step provider deletion in a transaction.
Both new DAO methods (
DeleteByInstanceIDsandDeleteByProviderID) participate inDeleteModelProvider, which performs three sequential unscoped deletes — tenant models, then instances, then the provider record — without a transaction. If any step fails after a prior step succeeds, the data is left in an inconsistent state (e.g., models deleted but instances and provider remain). Wrapping the sequence in a single DB transaction would preserve atomicity and simplify recovery on partial 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/dao/tenant_model_instance.go` around lines 114 - 118, Wrap the sequential deletions in DeleteModelProvider, including DeleteByInstanceIDs, DeleteByProviderID, and provider removal, in a single database transaction. Propagate any error from each step so the transaction rolls back; commit only after all deletes succeed, preserving atomicity across the provider cleanup.internal/service/model_service.go (2)
528-537: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoffRedundant per-model lookups of provider and instance.
CreateProviderInstancealready holdsprovider(Line 414) and the instance it just created (Line 448), yetaddModelToInstancere-queries both by name on every loop iteration. Passing the knownprovider.IDandinstance.IDavoids two DB round-trips per model.🤖 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 528 - 537, Refactor CreateProviderInstance and addModelToInstance to reuse the already loaded provider and newly created instance instead of querying them for each model. Pass provider.ID and instance.ID (or the corresponding objects) into addModelToInstance, remove its GetByTenantIDAndProviderName and GetByProviderIDAndInstanceName calls, and update all callers and downstream logic to use the supplied identifiers.
234-256: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoff
providerHasInstanceadds an N+1 query pattern to the listing.For every provider in the tenant list,
providerHasInstanceissues two extra DB round-trips (GetByTenantIDAndProviderName+GetAllInstancesByProviderID). On tenants with many providers this scales linearly. Consider fetching instance counts grouped by provider ID in a single query and looking up presence from that map.🤖 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 234 - 256, Replace the per-provider database calls in providerHasInstance with a bulk instance-presence lookup performed once during the provider listing flow. Add or use a DAO method that returns instance counts grouped by provider ID for the tenant’s provider IDs, build a map/set from that result, and assign has_instance from it while iterating providers; remove the repeated GetByTenantIDAndProviderName and GetAllInstancesByProviderID calls.
🤖 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/model_service.go`:
- Around line 448-468: The model instance creation and subsequent
addModelToInstance calls are not enclosed in a single transaction, allowing
partial data on failure. Update the surrounding service flow to begin one
transaction before modelInstanceDAO.Create, execute both creation and all model
inserts through the transaction-aware DAO methods, commit only after every
operation succeeds, and roll back on any error; adjust addModelToInstance or
provide a transactional variant so it does not commit independently.
- Around line 287-302: Wrap the provider cleanup sequence in the relevant model
service method, including GetAllInstancesByProviderID, DeleteByInstanceIDs, and
DeleteByProviderID, inside a single dao.DB.Transaction callback. Propagate any
query error from the transaction and return the existing server-error response
only after the transaction fails, ensuring all cleanup operations commit or roll
back together.
---
Outside diff comments:
In `@internal/service/model_service.go`:
- Around line 414-417: Update the provider lookup error handling in the relevant
model-provider deletion method to detect gorm.ErrRecordNotFound and return
common.CodeNotFound, matching DeleteModelProvider’s existing behavior; preserve
common.CodeServerError for other errors. Use GetByTenantIDAndProviderName and
the surrounding deletion method as the implementation points.
---
Nitpick comments:
In `@internal/dao/tenant_model_instance.go`:
- Around line 114-118: Wrap the sequential deletions in DeleteModelProvider,
including DeleteByInstanceIDs, DeleteByProviderID, and provider removal, in a
single database transaction. Propagate any error from each step so the
transaction rolls back; commit only after all deletes succeed, preserving
atomicity across the provider cleanup.
In `@internal/service/model_service.go`:
- Around line 528-537: Refactor CreateProviderInstance and addModelToInstance to
reuse the already loaded provider and newly created instance instead of querying
them for each model. Pass provider.ID and instance.ID (or the corresponding
objects) into addModelToInstance, remove its GetByTenantIDAndProviderName and
GetByProviderIDAndInstanceName calls, and update all callers and downstream
logic to use the supplied identifiers.
- Around line 234-256: Replace the per-provider database calls in
providerHasInstance with a bulk instance-presence lookup performed once during
the provider listing flow. Add or use a DAO method that returns instance counts
grouped by provider ID for the tenant’s provider IDs, build a map/set from that
result, and assign has_instance from it while iterating providers; remove the
repeated GetByTenantIDAndProviderName and GetAllInstancesByProviderID calls.
🪄 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: 88801ebc-05b8-4a4b-961b-b5a6246e78fb
📒 Files selected for processing (5)
internal/dao/tenant_model.gointernal/dao/tenant_model_instance.gointernal/entity/types.gointernal/handler/providers.gointernal/service/model_service.go
| instances, err := m.modelInstanceDAO.GetAllInstancesByProviderID(provider.ID) | ||
| if err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
| if len(instances) > 0 { | ||
| instanceIDs := make([]string, len(instances)) | ||
| for i, inst := range instances { | ||
| instanceIDs[i] = inst.ID | ||
| } | ||
| if _, err := m.modelDAO.DeleteByInstanceIDs(instanceIDs); err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
| if _, err := m.modelInstanceDAO.DeleteByProviderID(provider.ID); err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the relevant service implementation and surrounding helpers.
git ls-files internal/service/model_service.go internal/service | sed -n '1,120p'
wc -l internal/service/model_service.go
sed -n '240,340p' internal/service/model_service.go
# Find transaction usage and delete patterns nearby.
rg -n "DeleteModelProvider|BeginTx|Transaction|WithTx|RunInTx|DeleteByInstanceIDs|DeleteByProviderID|DeleteByModelProvider" internal/service internal -g '!**/*_test.go'
# Inspect DAO interfaces/implementations to see whether these calls share a transaction scope.
rg -n "type .*ModelDAO|type .*ModelInstanceDAO|DeleteByInstanceIDs|DeleteByProviderID|BeginTx|WithTx|Tx" internal -g '!**/*_test.go'Repository: infiniflow/ragflow
Length of output: 26287
🏁 Script executed:
#!/bin/bash
set -euo pipefail
sed -n '1,220p' internal/dao/tenant_model.go
sed -n '1,180p' internal/dao/tenant_model_instance.go
# Look for any transactional variants or shared DB/session usage around these DAOs.
rg -n "DeleteByInstanceIDs|DeleteByProviderID|Transaction|WithTx|tx \\*gorm.DB|DB\\." internal/dao/tenant_model.go internal/dao/tenant_model_instance.go internal/dao/tenant_model*.goRepository: infiniflow/ragflow
Length of output: 19011
Wrap provider cleanup in a transaction. internal/service/model_service.go:287-302 issues the model, instance, and provider deletes as separate DB calls, so a failure mid-sequence can leave orphaned rows. Put the whole cleanup in one dao.DB.Transaction(...) block or equivalent.
🤖 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 287 - 302, Wrap the provider
cleanup sequence in the relevant model service method, including
GetAllInstancesByProviderID, DeleteByInstanceIDs, and DeleteByProviderID, inside
a single dao.DB.Transaction callback. Propagate any query error from the
transaction and return the existing server-error response only after the
transaction fails, ensuring all cleanup operations commit or roll back together.
| err = m.modelInstanceDAO.Create(tenantModelInstance) | ||
| if err != nil { | ||
| return common.CodeServerError, fmt.Errorf("fail to create model instance: %s", err.Error()) | ||
| } | ||
|
|
||
| // Add models with verify result in extra. | ||
| if len(modelInfo) > 0 { | ||
| for _, model := range modelInfo { | ||
| if model.Extra == nil { | ||
| model.Extra = make(map[string]interface{}) | ||
| } | ||
| verifyStatus := modelVerifyResult[model.ModelName] | ||
| if verifyStatus == "" { | ||
| verifyStatus = entity.ModelVerifyUnknown | ||
| } | ||
| model.Extra["verify"] = verifyStatus | ||
| if err := m.addModelToInstance(tenantID, providerName, instanceName, model); err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Look for any transaction wrapper around CreateProviderInstance / DAO tx support.
rg -nP '\b(Transaction|Begin|WithContext|tx)\b' internal/service/model_service.go internal/dao/ -C2
rg -nP 'func .*CreateProviderInstance' internal/ -C3Repository: infiniflow/ragflow
Length of output: 33059
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the service flow around provider instance creation and model insertion.
sed -n '397,590p' internal/service/model_service.go | cat -n
# Inspect the DAO that creates the instance row.
sed -n '1,120p' internal/dao/tenant_model_instance.go | cat -n
# Inspect any transactional helper(s) used by model/tenant model writes.
rg -nP 'func .*CreateTx|func .*Transaction|DB\.Transaction|Begin\(\)' internal/dao/internal internal/dao -C2 || true
# Find the duplicate-model error path mentioned in the review comment.
rg -nP 'duplicate|already exists|model.*exists|instance.*exists' internal/service/model_service.go internal/dao -C2Repository: infiniflow/ragflow
Length of output: 34901
Wrap provider instance creation and model inserts in one transaction. TenantModelInstanceDAO.Create only protects the instance row; addModelToInstance still commits models separately, so a later failure leaves a partial/orphaned instance. No outer transaction covers this 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/model_service.go` around lines 448 - 468, The model instance
creation and subsequent addModelToInstance calls are not enclosed in a single
transaction, allowing partial data on failure. Update the surrounding service
flow to begin one transaction before modelInstanceDAO.Create, execute both
creation and all model inserts through the transaction-aware DAO methods, commit
only after every operation succeeds, and roll back on any error; adjust
addModelToInstance or provide a transactional variant so it does not commit
independently.
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (4)
internal/dao/tenant_model.go (1)
126-127: 📐 Maintainability & Code Quality | 🔵 TrivialRemove "Mirrors Python's" compatibility comments.
Comments "Mirrors Python's TenantModelService.delete_by_ids" and "Mirrors Python's TenantModelService.update_model" are new compatibility wording describing a superseded design. As per coding guidelines, do not add new compatibility wording in comments or documentation, and drop stale comments describing a superseded design.
Also applies to: 136-137
🤖 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 126 - 127, Remove the “Mirrors Python's TenantModelService...” compatibility comments from the DeleteByIDs and update_model declarations, leaving only accurate Go documentation that describes each method’s behavior.Source: Coding guidelines
internal/dao/tenant_model_instance.go (1)
114-115: 📐 Maintainability & Code Quality | 🔵 TrivialRemove "Mirrors Python's" compatibility comment.
The comment "Mirrors Python's TenantModelInstanceService.update_by_id" is new compatibility wording referencing a superseded design. As per coding guidelines, do not add new compatibility wording in comments or documentation, and drop stale comments describing a superseded design.
🤖 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 114 - 115, Remove the “Mirrors Python's TenantModelInstanceService.update_by_id” line from the comment above UpdateByID, leaving only the concise description of the method’s behavior.Source: Coding guidelines
internal/service/model_service.go (1)
419-426: 📐 Maintainability & Code Quality | 🔵 TrivialRemove "Mirrors Python's" compatibility comments.
Comments referencing Python implementations (e.g., "Mirrors Python's _normalize_provider_api_key", "Mirrors Python's create_name_only_provider_instance in provider_api_service.py:536") are new compatibility wording describing a superseded design. As per coding guidelines, do not add new compatibility wording in comments or documentation, and drop stale comments describing a superseded design.
Also applies to: 473-475
🤖 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 419 - 426, Remove the “Mirrors Python’s” compatibility comments near the API-key normalization and provider-instance creation logic, including the references to Python method names and file locations; retain only comments that describe the current Go behavior where necessary.Source: Coding guidelines
internal/handler/providers.go (1)
200-202: 📐 Maintainability & Code Quality | 🔵 TrivialRemove "Mirrors Python's" compatibility comment.
The comment "Mirrors Python's provider_api.py:349 — set(data.keys()) == {"instance_name"}" is new compatibility wording referencing a superseded design. As per coding guidelines, do not add new compatibility wording in comments or documentation.
🤖 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/handler/providers.go` around lines 200 - 202, Remove the “Mirrors Python’s provider_api.py:349…” sentence from the comment above the instance-name-only request handling, while retaining the concise explanation of creating a name-only instance without API key validation or model creation.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.
Inline comments:
In `@internal/handler/providers.go`:
- Around line 200-211: Validate req.InstanceName before the name-only branch in
the provider request handler: when the other fields are empty, reject an empty
instance name with the appropriate client error instead of calling
CreateNameOnlyProviderInstance. Preserve the existing branch behavior for
non-empty names and continue using common.ErrorWithCode for validation failures.
In `@internal/service/model_service.go`:
- Around line 1186-1353: Wrap all writes in AlterProviderInstance in a single
dao.DB.Transaction after the read-only tenant, provider, and instance lookups.
Move instanceUpdates, model deletion, model upsert, and addModelToInstance
operations into the transaction callback, propagate any error to roll back the
transaction, and return the transaction error with the appropriate
common.ErrorCode.
- Around line 1274-1293: Guard the model deletion logic in the model update
method so it runs only when modelInfo is non-nil. Keep building
submittedModelNames, collecting idsToRemove, and calling modelDAO.DeleteByIDs
within this guard, preserving existing behavior for explicitly provided model
lists while leaving models unchanged when model_info is omitted.
- Around line 1225-1227: Prevent Update from clearing an existing API key when
the request omits it: in the method constructing instanceUpdates, add the
"api_key" field only when apiKey is non-empty, while preserving other updates.
Alternatively, change the request field to *string and distinguish omitted from
explicitly empty values before updating.
- Around line 1325-1328: In the existing model extra merge logic, check and
handle the error returned by json.Unmarshal when parsing existingMdl.Extra. If
unmarshaling fails, return or propagate the error instead of continuing with an
empty mergedExtra map and overwriting the stored data.
---
Nitpick comments:
In `@internal/dao/tenant_model_instance.go`:
- Around line 114-115: Remove the “Mirrors Python's
TenantModelInstanceService.update_by_id” line from the comment above UpdateByID,
leaving only the concise description of the method’s behavior.
In `@internal/dao/tenant_model.go`:
- Around line 126-127: Remove the “Mirrors Python's TenantModelService...”
compatibility comments from the DeleteByIDs and update_model declarations,
leaving only accurate Go documentation that describes each method’s behavior.
In `@internal/handler/providers.go`:
- Around line 200-202: Remove the “Mirrors Python’s provider_api.py:349…”
sentence from the comment above the instance-name-only request handling, while
retaining the concise explanation of creating a name-only instance without API
key validation or model creation.
In `@internal/service/model_service.go`:
- Around line 419-426: Remove the “Mirrors Python’s” compatibility comments near
the API-key normalization and provider-instance creation logic, including the
references to Python method names and file locations; retain only comments that
describe the current Go behavior where necessary.
🪄 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: d72a542c-98d1-4470-977e-88b2bb507035
📒 Files selected for processing (4)
internal/dao/tenant_model.gointernal/dao/tenant_model_instance.gointernal/handler/providers.gointernal/service/model_service.go
| // If the request body only contains "instance_name", create a name-only | ||
| // instance without API key validation or model creation. | ||
| // Mirrors Python's provider_api.py:349 — set(data.keys()) == {"instance_name"}. | ||
| if req.APIKey == "" && req.BaseURL == "" && req.Region == "" && len(req.ModelInfo) == 0 { | ||
| code, err := h.modelProviderService.CreateNameOnlyProviderInstance(providerName, req.InstanceName, userID) | ||
| if err != nil { | ||
| common.ErrorWithCode(c, int(code), err.Error()) | ||
| return | ||
| } | ||
| common.SuccessWithMessage(c, "success") | ||
| return | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Validate instance_name before calling CreateNameOnlyProviderInstance.
An empty request body {} satisfies the name-only condition (all fields empty), calling CreateNameOnlyProviderInstance with an empty instance name. The service only rejects "default" but not "". Add an explicit check for req.InstanceName == "" before entering the name-only branch.
🛡️ Proposed fix
if req.APIKey == "" && req.BaseURL == "" && req.Region == "" && len(req.ModelInfo) == 0 {
+ if req.InstanceName == "" {
+ common.ErrorWithCode(c, int(common.CodeBadRequest), "instance_name is required")
+ return
+ }
code, err := h.modelProviderService.CreateNameOnlyProviderInstance(providerName, req.InstanceName, userID)📝 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.
| // If the request body only contains "instance_name", create a name-only | |
| // instance without API key validation or model creation. | |
| // Mirrors Python's provider_api.py:349 — set(data.keys()) == {"instance_name"}. | |
| if req.APIKey == "" && req.BaseURL == "" && req.Region == "" && len(req.ModelInfo) == 0 { | |
| code, err := h.modelProviderService.CreateNameOnlyProviderInstance(providerName, req.InstanceName, userID) | |
| if err != nil { | |
| common.ErrorWithCode(c, int(code), err.Error()) | |
| return | |
| } | |
| common.SuccessWithMessage(c, "success") | |
| return | |
| } | |
| // If the request body only contains "instance_name", create a name-only | |
| // instance without API key validation or model creation. | |
| // Mirrors Python's provider_api.py:349 — set(data.keys()) == {"instance_name"}. | |
| if req.APIKey == "" && req.BaseURL == "" && req.Region == "" && len(req.ModelInfo) == 0 { | |
| if req.InstanceName == "" { | |
| common.ErrorWithCode(c, int(common.CodeBadRequest), "instance_name is required") | |
| return | |
| } | |
| code, err := h.modelProviderService.CreateNameOnlyProviderInstance(providerName, req.InstanceName, userID) | |
| if err != nil { | |
| common.ErrorWithCode(c, int(code), err.Error()) | |
| return | |
| } | |
| common.SuccessWithMessage(c, "success") | |
| return | |
| } |
🤖 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/handler/providers.go` around lines 200 - 211, Validate
req.InstanceName before the name-only branch in the provider request handler:
when the other fields are empty, reject an empty instance name with the
appropriate client error instead of calling CreateNameOnlyProviderInstance.
Preserve the existing branch behavior for non-empty names and continue using
common.ErrorWithCode for validation failures.
| func (m *ModelProviderService) AlterProviderInstance(userID, providerName, instanceIDOrName, newInstanceName, apiKey, baseURL, region string, modelInfo []CreateInstanceModelInfo, verify bool) (common.ErrorCode, error) { | ||
| providerName = strings.TrimSpace(providerName) | ||
| providerName = strings.ToLower(providerName) | ||
|
|
||
| tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner") | ||
| if err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
| if len(tenants) == 0 { | ||
| return common.CodeNotFound, errors.New("user has no tenants") | ||
| } | ||
| tenantID := tenants[0].TenantID | ||
|
|
||
| provider, err := m.modelProviderDAO.GetByTenantIDAndProviderName(tenantID, providerName) | ||
| if err != nil { | ||
| return common.CodeNotFound, fmt.Errorf("provider '%s' does not exist", providerName) | ||
| } | ||
|
|
||
| // Find the instance — try by ID first, then by name. | ||
| instance, err := m.modelInstanceDAO.GetByID(instanceIDOrName) | ||
| if err != nil || instance.ProviderID != provider.ID { | ||
| instance, err = m.modelInstanceDAO.GetByProviderIDAndInstanceName(provider.ID, instanceIDOrName) | ||
| } | ||
| if err != nil { | ||
| return common.CodeNotFound, fmt.Errorf("no instance found for provider '%s' and instance '%s'", providerName, instanceIDOrName) | ||
| } | ||
|
|
||
| // Normalize api_key: VLLM with empty api_key defaults to "x". | ||
| if strings.EqualFold(providerName, "vllm") && apiKey == "" { | ||
| apiKey = "x" | ||
| } | ||
|
|
||
| // Verify API key if requested. | ||
| modelVerifyResult := make(map[string]string) | ||
| if verify { | ||
| modelVerifyResult = m.verifyProviderAPIKey(providerName, apiKey, region, baseURL, modelInfo) | ||
| } | ||
|
|
||
| // Update instance record. | ||
| instanceUpdates := map[string]interface{}{ | ||
| "api_key": apiKey, | ||
| } | ||
| if newInstanceName != "" && newInstanceName != instance.InstanceName { | ||
| instanceUpdates["instance_name"] = newInstanceName | ||
| } | ||
|
|
||
| extraFields := make(map[string]interface{}) | ||
| if baseURL != "" { | ||
| extraFields["base_url"] = baseURL | ||
| } | ||
| if region != "" { | ||
| extraFields["region"] = region | ||
| } | ||
| // Preserve existing extra fields not overwritten. | ||
| existingExtra := make(map[string]interface{}) | ||
| if instance.Extra != "" { | ||
| if err := json.Unmarshal([]byte(instance.Extra), &existingExtra); err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
| } | ||
| for k, v := range extraFields { | ||
| existingExtra[k] = v | ||
| } | ||
| extraBytes, err := json.Marshal(existingExtra) | ||
| if err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
| instanceUpdates["extra"] = string(extraBytes) | ||
| if err := m.modelInstanceDAO.UpdateByID(instance.ID, instanceUpdates); err != nil { | ||
| return common.CodeServerError, fmt.Errorf("fail to update instance: %s", err.Error()) | ||
| } | ||
|
|
||
| // Use the (possibly updated) instance_name for model operations. | ||
| effectiveInstanceName := instance.InstanceName | ||
| if newInstanceName != "" { | ||
| effectiveInstanceName = newInstanceName | ||
| } | ||
|
|
||
| // Upsert models: add new ones, update existing ones, remove ones no longer selected. | ||
| existingModels, err := m.modelDAO.GetModelsByInstanceID(instance.ID) | ||
| if err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
| existingModelMap := make(map[string]*entity.TenantModel) | ||
| for _, mdl := range existingModels { | ||
| existingModelMap[mdl.ModelName] = mdl | ||
| } | ||
|
|
||
| // Delete models that are no longer in the submitted model_info. | ||
| submittedModelNames := make(map[string]bool) | ||
| if modelInfo != nil { | ||
| for _, mdl := range modelInfo { | ||
| if mdl.ModelName != "" { | ||
| submittedModelNames[mdl.ModelName] = true | ||
| } | ||
| } | ||
| } | ||
| var idsToRemove []string | ||
| for name, mdl := range existingModelMap { | ||
| if !submittedModelNames[name] { | ||
| idsToRemove = append(idsToRemove, mdl.ID) | ||
| } | ||
| } | ||
| if len(idsToRemove) > 0 { | ||
| if _, err := m.modelDAO.DeleteByIDs(idsToRemove); err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
| } | ||
|
|
||
| // Add or update models from model_info. | ||
| if modelInfo != nil { | ||
| for _, mdl := range modelInfo { | ||
| if mdl.ModelName == "" { | ||
| continue | ||
| } | ||
| // Attach verify status. | ||
| if verify { | ||
| verifyStatus := modelVerifyResult[mdl.ModelName] | ||
| if verifyStatus == "" { | ||
| verifyStatus = entity.ModelVerifyUnknown | ||
| } | ||
| if mdl.Extra == nil { | ||
| mdl.Extra = make(map[string]interface{}) | ||
| } | ||
| mdl.Extra["verify"] = verifyStatus | ||
| } | ||
|
|
||
| if existingMdl, exists := existingModelMap[mdl.ModelName]; exists { | ||
| // Update existing model. | ||
| updates := make(map[string]interface{}) | ||
| if len(mdl.ModelTypes) > 0 { | ||
| combinedType := entity.ModelType(0) | ||
| for _, t := range mdl.ModelTypes { | ||
| combinedType |= entity.ModelTypeFromString(t) | ||
| } | ||
| if int(combinedType) != existingMdl.ModelType { | ||
| updates["model_type"] = int(combinedType) | ||
| } | ||
| } | ||
| mergedExtra := make(map[string]interface{}) | ||
| if existingMdl.Extra != "" { | ||
| json.Unmarshal([]byte(existingMdl.Extra), &mergedExtra) | ||
| } | ||
| if mdl.Extra != nil { | ||
| for k, v := range mdl.Extra { | ||
| mergedExtra[k] = v | ||
| } | ||
| } | ||
| if mdl.MaxTokens > 0 { | ||
| mergedExtra["max_tokens"] = mdl.MaxTokens | ||
| } | ||
| extraBytes, _ := json.Marshal(mergedExtra) | ||
| updates["extra"] = string(extraBytes) | ||
| if len(updates) > 0 { | ||
| if err := m.modelDAO.UpdateByID(existingMdl.ID, updates); err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
| } | ||
| } else { | ||
| // Add new model. | ||
| if err := m.addModelToInstance(tenantID, providerName, effectiveInstanceName, mdl); err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return common.CodeSuccess, nil |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Wrap AlterProviderInstance in a transaction.
Instance update, model deletions, and model additions/updates are separate DB calls. A failure mid-sequence leaves partial state — e.g., instance renamed but models not reconciled. This is the same pattern previously flagged for DeleteModelProvider (lines 287-302) and CreateProviderInstance (lines 448-468). Wrap the entire method body (after the read-only lookups) in dao.DB.Transaction(...) so all writes commit or roll back together.
🤖 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 1186 - 1353, Wrap all writes
in AlterProviderInstance in a single dao.DB.Transaction after the read-only
tenant, provider, and instance lookups. Move instanceUpdates, model deletion,
model upsert, and addModelToInstance operations into the transaction callback,
propagate any error to roll back the transaction, and return the transaction
error with the appropriate common.ErrorCode.
| instanceUpdates := map[string]interface{}{ | ||
| "api_key": apiKey, | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
API key is unconditionally overwritten, even when not provided.
instanceUpdates["api_key"] is always set. If the client sends a request without api_key (empty string), the existing key is cleared. For non-VLLM providers this renders the instance unusable. Only include api_key in the update when it's non-empty, or use a *string pointer in the request to distinguish "not provided" from "explicitly cleared."
🛡️ Proposed fix: skip api_key update when empty
-instanceUpdates := map[string]interface{}{
- "api_key": apiKey,
-}
+instanceUpdates := map[string]interface{}{}
+if apiKey != "" {
+ instanceUpdates["api_key"] = apiKey
+}📝 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.
| instanceUpdates := map[string]interface{}{ | |
| "api_key": apiKey, | |
| } | |
| instanceUpdates := map[string]interface{}{} | |
| if apiKey != "" { | |
| instanceUpdates["api_key"] = apiKey | |
| } |
🤖 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 1225 - 1227, Prevent Update
from clearing an existing API key when the request omits it: in the method
constructing instanceUpdates, add the "api_key" field only when apiKey is
non-empty, while preserving other updates. Alternatively, change the request
field to *string and distinguish omitted from explicitly empty values before
updating.
| // Delete models that are no longer in the submitted model_info. | ||
| submittedModelNames := make(map[string]bool) | ||
| if modelInfo != nil { | ||
| for _, mdl := range modelInfo { | ||
| if mdl.ModelName != "" { | ||
| submittedModelNames[mdl.ModelName] = true | ||
| } | ||
| } | ||
| } | ||
| var idsToRemove []string | ||
| for name, mdl := range existingModelMap { | ||
| if !submittedModelNames[name] { | ||
| idsToRemove = append(idsToRemove, mdl.ID) | ||
| } | ||
| } | ||
| if len(idsToRemove) > 0 { | ||
| if _, err := m.modelDAO.DeleteByIDs(idsToRemove); err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Nil modelInfo silently deletes all existing models.
When modelInfo is nil (the client omits model_info from the JSON body), submittedModelNames stays empty. The deletion loop then adds every existing model to idsToRemove, wiping all models even though the user only intended to update the API key or instance name.
🛡️ Proposed fix: guard the entire deletion block with `modelInfo != nil`
// Delete models that are no longer in the submitted model_info.
-submittedModelNames := make(map[string]bool)
-if modelInfo != nil {
+if modelInfo != nil {
+ submittedModelNames := make(map[string]bool)
for _, mdl := range modelInfo {
if mdl.ModelName != "" {
submittedModelNames[mdl.ModelName] = true
}
}
-}
-var idsToRemove []string
-for name, mdl := range existingModelMap {
- if !submittedModelNames[name] {
- idsToRemove = append(idsToRemove, mdl.ID)
+ var idsToRemove []string
+ for name, mdl := range existingModelMap {
+ if !submittedModelNames[name] {
+ idsToRemove = append(idsToRemove, mdl.ID)
+ }
}
-}
-if len(idsToRemove) > 0 {
- if _, err := m.modelDAO.DeleteByIDs(idsToRemove); err != nil {
- return common.CodeServerError, err
+ if len(idsToRemove) > 0 {
+ if _, err := m.modelDAO.DeleteByIDs(idsToRemove); err != nil {
+ return common.CodeServerError, err
+ }
}
}📝 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.
| // Delete models that are no longer in the submitted model_info. | |
| submittedModelNames := make(map[string]bool) | |
| if modelInfo != nil { | |
| for _, mdl := range modelInfo { | |
| if mdl.ModelName != "" { | |
| submittedModelNames[mdl.ModelName] = true | |
| } | |
| } | |
| } | |
| var idsToRemove []string | |
| for name, mdl := range existingModelMap { | |
| if !submittedModelNames[name] { | |
| idsToRemove = append(idsToRemove, mdl.ID) | |
| } | |
| } | |
| if len(idsToRemove) > 0 { | |
| if _, err := m.modelDAO.DeleteByIDs(idsToRemove); err != nil { | |
| return common.CodeServerError, err | |
| } | |
| } | |
| // Delete models that are no longer in the submitted model_info. | |
| if modelInfo != nil { | |
| submittedModelNames := make(map[string]bool) | |
| for _, mdl := range modelInfo { | |
| if mdl.ModelName != "" { | |
| submittedModelNames[mdl.ModelName] = true | |
| } | |
| } | |
| var idsToRemove []string | |
| for name, mdl := range existingModelMap { | |
| if !submittedModelNames[name] { | |
| idsToRemove = append(idsToRemove, mdl.ID) | |
| } | |
| } | |
| if len(idsToRemove) > 0 { | |
| if _, err := m.modelDAO.DeleteByIDs(idsToRemove); err != nil { | |
| return common.CodeServerError, err | |
| } | |
| } | |
| } |
🤖 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 1274 - 1293, Guard the model
deletion logic in the model update method so it runs only when modelInfo is
non-nil. Keep building submittedModelNames, collecting idsToRemove, and calling
modelDAO.DeleteByIDs within this guard, preserving existing behavior for
explicitly provided model lists while leaving models unchanged when model_info
is omitted.
| mergedExtra := make(map[string]interface{}) | ||
| if existingMdl.Extra != "" { | ||
| json.Unmarshal([]byte(existingMdl.Extra), &mergedExtra) | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Handle json.Unmarshal error when parsing existing model extra.
The error from unmarshaling existingMdl.Extra is silently discarded. If the stored JSON is malformed, mergedExtra starts empty and the update overwrites the field with incomplete data.
🛡️ Proposed fix
if existingMdl.Extra != "" {
- json.Unmarshal([]byte(existingMdl.Extra), &mergedExtra)
+ if err := json.Unmarshal([]byte(existingMdl.Extra), &mergedExtra); err != nil {
+ return common.CodeServerError, fmt.Errorf("failed to parse existing model extra for %s: %s", existingMdl.ModelName, err.Error())
+ }
}📝 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.
| mergedExtra := make(map[string]interface{}) | |
| if existingMdl.Extra != "" { | |
| json.Unmarshal([]byte(existingMdl.Extra), &mergedExtra) | |
| } | |
| mergedExtra := make(map[string]interface{}) | |
| if existingMdl.Extra != "" { | |
| if err := json.Unmarshal([]byte(existingMdl.Extra), &mergedExtra); err != nil { | |
| return common.CodeServerError, fmt.Errorf("failed to parse existing model extra for %s: %s", existingMdl.ModelName, err.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/service/model_service.go` around lines 1325 - 1328, In the existing
model extra merge logic, check and handle the error returned by json.Unmarshal
when parsing existingMdl.Extra. If unmarshaling fails, return or propagate the
error instead of continuing with an empty mergedExtra map and overwriting the
stored data.
…nto fix/go-model-provider
Summary
As title.