Skip to content

Go: add drop instance models - #14485

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
JinHai-CN:fix408
Apr 29, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
JinHai-CN:fix408

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

What problem does this PR solve?

  1. drop instance model
  2. Fix issue of drop instance but not drop models.

Type of change

  • New Feature (non-breaking change which adds functionality)

@coderabbitai

coderabbitai Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR introduces a new drop_instance_model CLI command and HTTP endpoint to remove custom models from provider instances, updates the custom model creation flow to support multiple model types, and enhances model instance cleanup with new DAO deletion methods supporting composite key lookups.

Changes

Cohort / File(s) Summary
CLI Parsing & Routing
internal/cli/admin_parser.go, internal/cli/client.go, internal/cli/user_parser.go
Removes TokenModel DROP recognition from admin parser; adds drop_instance_model command dispatch in client; implements parseDropInstanceModel to handle new syntax expecting FROM <provider_name> <instance_name> and parseAddModel to collect multiple model types in a slice with relaxed validation.
CLI User Commands
internal/cli/user_command.go
Adds new DropInstanceModel method that validates server type, extracts instance/provider/model parameters, and sends DELETE request; updates AddCustomModel signature to accept model_types array instead of single model_type string.
HTTP Handler & Routing
internal/handler/providers.go, internal/router/router.go
Introduces DropInstanceModels handler that extracts path params, validates request body with models array, and routes DELETE requests to service; adds new route /api/v1/providers/:provider_name/instances/:instance_name/models; updates AddCustomModel validation to check ModelTypes array instead of single string.
Service Layer
internal/service/model_service.go
Adds DropInstanceModels method to delete specified models from provider instance with validation and error handling; updates DropProviderInstances to cascade-delete associated tenant models; modifies AddCustomModel to persist model_types array to instance Extra and use first element as stored ModelType; updates ChatToModel to extract and output model_types from instance metadata.
Data Access Layer
internal/dao/tenant_model.go
Adds two hard-delete methods: DeleteByProviderIDAndInstanceID for bulk deletion by provider/instance; DeleteByProviderIDAndInstanceIDAndModelName for targeted deletion by provider/instance/model name; both return row count and error.
Entity Types
internal/entity/models/types.go
Adds optional Vision *bool field to ChatConfig struct to enable vision capability control in chat requests.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

💞 feature, size:XL

Poem

🐰 With models dropping clean and neat,
And types now dancing to a multi-beat,
The instance gardens trimmed with care,
Vision and wisdom float through air,
A rabbit hops through endpoints bright! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description addresses the problem being solved and includes the required 'Type of change' section with appropriate selection, but lacks sufficient detail and context. Expand 'What problem does this PR solve?' with more context about why dropping instance models is important and how it was previously broken; provide more specific details about the implementation approach.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: add drop instance models' directly and specifically describes the main feature addition in the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.


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
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

@JinHai-CN JinHai-CN added the ci Continue Integration label Apr 29, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review April 29, 2026 10:38
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 29, 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: 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 | 🔴 Critical

Reject empty model_types before indexing it.

request.ModelTypes[0] will panic when the request contains "model_types": []. The current handler only rejects nil, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1b84892 and 37a0687.

📒 Files selected for processing (9)
  • internal/cli/admin_parser.go
  • internal/cli/client.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/dao/tenant_model.go
  • internal/entity/models/types.go
  • internal/handler/providers.go
  • internal/router/router.go
  • internal/service/model_service.go
💤 Files with no reviewable changes (1)
  • internal/cli/admin_parser.go

Comment on lines +743 to +748
_, err := h.modelProviderService.DropInstanceModels(providerName, instanceName, userID, req.Models)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": common.CodeServerError,
"message": err.Error(),
})

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

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.

Suggested change
_, 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.

Comment on lines 480 to +496
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)

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

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.

Comment on lines +535 to +545
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)
}

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

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

codecov Bot commented Apr 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.30%. Comparing base (1b84892) to head (37a0687).
⚠️ Report is 6 commits behind head on main.

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.
📢 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 261be81 into infiniflow:main Apr 29, 2026
1 check passed
TIMBLOCKER pushed a commit to TIMBLOCKER/kira that referenced this pull request Apr 29, 2026
### 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]>
TIMBLOCKER pushed a commit to TIMBLOCKER/kira that referenced this pull request May 7, 2026
### 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]>
@coderabbitai coderabbitai Bot mentioned this pull request May 26, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant