Repository navigation
Go: add drop instance models - #14485
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughThis PR introduces a new Changes
Sequence DiagramsequenceDiagram
actor User
participant CLI as CLI Parser
participant Handler as HTTP Handler
participant Service as Model Service
participant DAO as Tenant Model DAO
participant DB as Database
User->>CLI: drop_instance_model command
CLI->>Handler: DELETE /api/v1/providers/{provider}/instances/{instance}/models
Handler->>Handler: Parse path params & JSON body
Handler->>Service: DropInstanceModels(provider, instance, userID, models[])
Service->>Service: Resolve tenant & validate provider
Service->>Service: Validate instance exists
loop For each model name
Service->>DAO: DeleteByProviderIDAndInstanceIDAndModelName()
DAO->>DB: DELETE WHERE provider_id=? AND instance_id=? AND model_name=?
DB-->>DAO: Return rows affected
DAO-->>Service: rows affected or error
Service->>Service: Verify deletion (error if 0 rows)
end
Service-->>Handler: Success/Error response
Handler-->>User: {code: 0, message: "success"} or error JSON
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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. Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
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)
1001-1013:⚠️ Potential issue | 🔴 CriticalReject empty
model_typesbefore indexing it.
request.ModelTypes[0]will panic when the request contains"model_types": []. The current handler only rejectsnil, so an empty array still reaches this code path.Suggested fix
func (m *ModelProviderService) AddCustomModel(request *AddCustomModelRequest, userID string) (common.ErrorCode, error) { // Get tenant ID from user 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") } + + if len(request.ModelTypes) == 0 { + return common.CodeBadRequest, errors.New("at least one model type is required") + } tenantID := tenants[0].TenantID @@ model := &entity.TenantModel{ ID: modelID, ModelName: request.ModelName, ModelType: request.ModelTypes[0],🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/service/model_service.go` around lines 1001 - 1013, The code currently indexes request.ModelTypes[0] when building entity.TenantModel, which panics for an empty slice; add a guard that rejects an empty slice (len(request.ModelTypes) == 0) earlier in the handler (before assigning extra["model_types"] and before constructing model) and return the appropriate error/code (same style as the nil check) so TenantModel.ModelType is only set from a non-empty request.ModelTypes; update any error message to indicate "model_types cannot be empty" and keep using request.ModelTypes elsewhere unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/handler/providers.go`:
- Around line 743-748: The response currently hardcodes common.CodeServerError
when h.modelProviderService.DropInstanceModels(providerName, instanceName,
userID, req.Models) returns an error; change the handler to extract and
propagate the service error code from the returned error (e.g. use the error's
Code field or Code() method) into the JSON "code" value and only fall back to
common.CodeServerError if the error does not expose a specific code, while
keeping the existing "message": err.Error() field.
In `@internal/service/model_service.go`:
- Around line 535-545: The current loop in the function that iterates over
models uses m.modelDAO.DeleteByProviderIDAndInstanceIDAndModelName and can
partially delete if a later modelName is missing; wrap the whole operation in an
all-or-nothing transaction or pre-validate the entire models slice before
calling DeleteByProviderIDAndInstanceIDAndModelName: either (a) start a DB
transaction, perform existence checks for every modelName and then delete all
within the same transaction and commit/rollback on error, or (b) first query for
count/existence of all model names for provider.ID and modelInstance.ID and
return CodeNotFound if any are missing, then proceed to delete each model
without a transaction; update error handling accordingly so partial deletes
cannot occur.
- Around line 480-496: The per-instance cleanup currently deletes tenant-model
rows before deleting the instance, which can leave a partial state if the
instance delete fails; wrap the whole per-instance sequence (retrieving
tenantModelInstance via modelInstanceDAO.GetByProviderIDAndInstanceName,
deleting models via modelDAO.DeleteByProviderIDAndInstanceID, and deleting the
instance via modelInstanceDAO.DeleteByProviderIDAndInstanceName) in a single DB
transaction: begin a transaction at the start of processing each instance,
perform the three DAO operations using tx-aware DAO methods (or pass the tx into
DAO calls / use DAO.WithTx variants), rollback and return on any error, and
commit only after the instance delete succeeds so both model deletes and
instance delete are atomic.
---
Outside diff comments:
In `@internal/service/model_service.go`:
- Around line 1001-1013: The code currently indexes request.ModelTypes[0] when
building entity.TenantModel, which panics for an empty slice; add a guard that
rejects an empty slice (len(request.ModelTypes) == 0) earlier in the handler
(before assigning extra["model_types"] and before constructing model) and return
the appropriate error/code (same style as the nil check) so
TenantModel.ModelType is only set from a non-empty request.ModelTypes; update
any error message to indicate "model_types cannot be empty" and keep using
request.ModelTypes elsewhere unchanged.
🪄 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: 8bd889b9-a132-47c5-b1dd-6f5c550cd030
📒 Files selected for processing (9)
internal/cli/admin_parser.gointernal/cli/client.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/dao/tenant_model.gointernal/entity/models/types.gointernal/handler/providers.gointernal/router/router.gointernal/service/model_service.go
💤 Files with no reviewable changes (1)
- internal/cli/admin_parser.go
| _, err := h.modelProviderService.DropInstanceModels(providerName, instanceName, userID, req.Models) | ||
| if err != nil { | ||
| c.JSON(http.StatusOK, gin.H{ | ||
| "code": common.CodeServerError, | ||
| "message": err.Error(), | ||
| }) |
There was a problem hiding this comment.
Propagate the service error code instead of hardcoding CodeServerError.
DropInstanceModels returns a specific common.ErrorCode, but this path discards it and always responds with CodeServerError. A missing model will be reported as a server failure instead of CodeNotFound, which breaks client-side handling.
Suggested fix
- _, err := h.modelProviderService.DropInstanceModels(providerName, instanceName, userID, req.Models)
+ errorCode, err := h.modelProviderService.DropInstanceModels(providerName, instanceName, userID, req.Models)
if err != nil {
c.JSON(http.StatusOK, gin.H{
- "code": common.CodeServerError,
+ "code": errorCode,
"message": err.Error(),
})
return
}📝 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.
| _, err := h.modelProviderService.DropInstanceModels(providerName, instanceName, userID, req.Models) | |
| if err != nil { | |
| c.JSON(http.StatusOK, gin.H{ | |
| "code": common.CodeServerError, | |
| "message": err.Error(), | |
| }) | |
| errorCode, err := h.modelProviderService.DropInstanceModels(providerName, instanceName, userID, req.Models) | |
| if err != nil { | |
| c.JSON(http.StatusOK, gin.H{ | |
| "code": errorCode, | |
| "message": err.Error(), | |
| }) | |
| return | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/handler/providers.go` around lines 743 - 748, The response currently
hardcodes common.CodeServerError when
h.modelProviderService.DropInstanceModels(providerName, instanceName, userID,
req.Models) returns an error; change the handler to extract and propagate the
service error code from the returned error (e.g. use the error's Code field or
Code() method) into the JSON "code" value and only fall back to
common.CodeServerError if the error does not expose a specific code, while
keeping the existing "message": err.Error() field.
| for _, instanceName := range instances { | ||
| count, err := m.modelInstanceDAO.DeleteByProviderIDAndInstanceName(provider.ID, instanceName) | ||
| // Get model instance | ||
| var tenantModelInstance *entity.TenantModelInstance | ||
| tenantModelInstance, err = m.modelInstanceDAO.GetByProviderIDAndInstanceName(provider.ID, instanceName) | ||
| if err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
|
|
||
| // Delete all models of this instance | ||
| var count int64 = 0 | ||
| count, err = m.modelDAO.DeleteByProviderIDAndInstanceID(provider.ID, tenantModelInstance.ID) | ||
| if err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
|
|
||
| // Delete model instance | ||
| count, err = m.modelInstanceDAO.DeleteByProviderIDAndInstanceName(provider.ID, instanceName) |
There was a problem hiding this comment.
Make provider-instance cleanup atomic.
This now deletes all tenant-model rows before deleting the instance row. If the instance delete fails, the instance survives but its models are already gone. That leaves the system in a broken partial state.
Wrap the per-instance cleanup in one DB transaction so the model deletes and instance delete succeed or fail together.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/service/model_service.go` around lines 480 - 496, The per-instance
cleanup currently deletes tenant-model rows before deleting the instance, which
can leave a partial state if the instance delete fails; wrap the whole
per-instance sequence (retrieving tenantModelInstance via
modelInstanceDAO.GetByProviderIDAndInstanceName, deleting models via
modelDAO.DeleteByProviderIDAndInstanceID, and deleting the instance via
modelInstanceDAO.DeleteByProviderIDAndInstanceName) in a single DB transaction:
begin a transaction at the start of processing each instance, perform the three
DAO operations using tx-aware DAO methods (or pass the tx into DAO calls / use
DAO.WithTx variants), rollback and return on any error, and commit only after
the instance delete succeeds so both model deletes and instance delete are
atomic.
| for _, modelName := range models { | ||
| // Delete all models of this instance | ||
| var count int64 = 0 | ||
| count, err = m.modelDAO.DeleteByProviderIDAndInstanceIDAndModelName(provider.ID, modelInstance.ID, modelName) | ||
| if err != nil { | ||
| return common.CodeServerError, err | ||
| } | ||
|
|
||
| if count == 0 { | ||
| return common.CodeNotFound, fmt.Errorf("model: %s not found", modelName) | ||
| } |
There was a problem hiding this comment.
This bulk delete can return an error after partially deleting models.
The loop mutates state as it goes. If an earlier model is deleted and a later modelName is missing, the method returns CodeNotFound after already applying part of the request. For a bulk drop API, callers will reasonably expect all-or-nothing behavior.
Prevalidate the full models slice before deleting, or execute the whole loop in a transaction.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/service/model_service.go` around lines 535 - 545, The current loop
in the function that iterates over models uses
m.modelDAO.DeleteByProviderIDAndInstanceIDAndModelName and can partially delete
if a later modelName is missing; wrap the whole operation in an all-or-nothing
transaction or pre-validate the entire models slice before calling
DeleteByProviderIDAndInstanceIDAndModelName: either (a) start a DB transaction,
perform existence checks for every modelName and then delete all within the same
transaction and commit/rollback on error, or (b) first query for count/existence
of all model names for provider.ID and modelInstance.ID and return CodeNotFound
if any are missing, then proceed to delete each model without a transaction;
update error handling accordingly so partial deletes cannot occur.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14485 +/- ##
=======================================
Coverage 95.30% 95.30%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 670 670
Misses 16 16
Partials 17 17 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
### What problem does this PR solve? 1. drop instance model 2. Fix issue of drop instance but not drop models. ### Type of change - [x] New Feature (non-breaking change which adds functionality) Signed-off-by: Jin Hai <[email protected]>
### What problem does this PR solve? 1. drop instance model 2. Fix issue of drop instance but not drop models. ### Type of change - [x] New Feature (non-breaking change which adds functionality) Signed-off-by: Jin Hai <[email protected]>
What problem does this PR solve?
Type of change