fix(model): block deletion when model is referenced by KB or agent

Reject model delete with HTTP 400 when the current tenant still has
knowledge bases or custom agents bound to the model ID.
This commit is contained in:
wizardchen
2026-06-23 20:33:01 +08:00
committed by lyingbug
parent 775cc9ef11
commit 7855f36799
11 changed files with 437 additions and 2 deletions
@@ -60,3 +60,16 @@ func (r *customAgentRepository) UpdateAgent(ctx context.Context, agent *types.Cu
func (r *customAgentRepository) DeleteAgent(ctx context.Context, id string, tenantID uint64) error {
return r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).Delete(&types.CustomAgent{}).Error
}
// CountByModelID counts active agents whose config references modelID.
func (r *customAgentRepository) CountByModelID(
ctx context.Context, tenantID uint64, modelID string,
) (int64, error) {
var count int64
query := r.db.WithContext(ctx).
Model(&types.CustomAgent{}).
Where("tenant_id = ?", tenantID)
query = scopeCustomAgentsByModelID(query, modelID)
err := query.Count(&count).Error
return count, err
}
@@ -203,3 +203,17 @@ func (r *knowledgeBaseRepository) CountByVectorStoreID(
Count(&count).Error
return count, err
}
// CountByModelID counts active knowledge bases that reference modelID in any
// model-binding column (scalar fields or JSON config blobs).
func (r *knowledgeBaseRepository) CountByModelID(
ctx context.Context, tenantID uint64, modelID string,
) (int64, error) {
var count int64
query := r.db.WithContext(ctx).
Model(&types.KnowledgeBase{}).
Where("tenant_id = ?", tenantID)
query = scopeKnowledgeBasesByModelID(query, modelID)
err := query.Count(&count).Error
return count, err
}
@@ -0,0 +1,49 @@
package repository
import (
"gorm.io/gorm"
)
// scopeKnowledgeBasesByModelID filters knowledge_bases rows that reference
// modelID in any model-binding field.
func scopeKnowledgeBasesByModelID(db *gorm.DB, modelID string) *gorm.DB {
if db.Dialector.Name() == "postgres" {
return db.Where(
"embedding_model_id = ? OR summary_model_id = ? OR "+
"image_processing_config->>'model_id' = ? OR "+
"vlm_config->>'model_id' = ? OR "+
"asr_config->>'model_id' = ? OR "+
"wiki_config->>'synthesis_model_id' = ?",
modelID, modelID, modelID, modelID, modelID, modelID,
)
}
return db.Where(
"embedding_model_id = ? OR summary_model_id = ? OR "+
"json_extract(image_processing_config, '$.model_id') = ? OR "+
"json_extract(vlm_config, '$.model_id') = ? OR "+
"json_extract(asr_config, '$.model_id') = ? OR "+
"json_extract(wiki_config, '$.synthesis_model_id') = ?",
modelID, modelID, modelID, modelID, modelID, modelID,
)
}
// scopeCustomAgentsByModelID filters custom_agents rows whose config JSON
// references modelID in any model-binding field.
func scopeCustomAgentsByModelID(db *gorm.DB, modelID string) *gorm.DB {
if db.Dialector.Name() == "postgres" {
return db.Where(
"config->>'model_id' = ? OR config->>'rerank_model_id' = ? OR "+
"config->>'vlm_model_id' = ? OR config->>'asr_model_id' = ? OR "+
"config->>'query_understand_model_id' = ?",
modelID, modelID, modelID, modelID, modelID,
)
}
return db.Where(
"json_extract(config, '$.model_id') = ? OR "+
"json_extract(config, '$.rerank_model_id') = ? OR "+
"json_extract(config, '$.vlm_model_id') = ? OR "+
"json_extract(config, '$.asr_model_id') = ? OR "+
"json_extract(config, '$.query_understand_model_id') = ?",
modelID, modelID, modelID, modelID, modelID,
)
}
@@ -0,0 +1,113 @@
package repository
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
const customAgentsTestDDL = `
CREATE TABLE IF NOT EXISTS custom_agents (
id VARCHAR(36) NOT NULL,
name VARCHAR(255) NOT NULL,
description TEXT,
avatar VARCHAR(64),
is_builtin BOOLEAN NOT NULL DEFAULT 0,
tenant_id INTEGER NOT NULL,
created_by VARCHAR(36),
config TEXT NOT NULL DEFAULT '{}',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
deleted_at DATETIME,
PRIMARY KEY (id, tenant_id)
);
`
func setupModelUsageTestDB(t *testing.T) *gorm.DB {
t.Helper()
db := setupKBTestDB(t)
require.NoError(t, db.Exec(customAgentsTestDDL).Error)
return db
}
func TestCountByModelID_KnowledgeBase(t *testing.T) {
ctx := context.Background()
db := setupModelUsageTestDB(t)
repo := NewKnowledgeBaseRepository(db)
modelID := "embed-model-1"
kb := makeKB(nil)
kb.EmbeddingModelID = modelID
require.NoError(t, db.Create(kb).Error)
count, err := repo.CountByModelID(ctx, 1, modelID)
require.NoError(t, err)
assert.Equal(t, int64(1), count)
count, err = repo.CountByModelID(ctx, 1, "other-model")
require.NoError(t, err)
assert.Equal(t, int64(0), count)
kb2 := makeKB(nil)
kb2.ID = uuid.New().String()
kb2.VLMConfig = types.VLMConfig{Enabled: true, ModelID: modelID}
require.NoError(t, db.Create(kb2).Error)
count, err = repo.CountByModelID(ctx, 1, modelID)
require.NoError(t, err)
assert.Equal(t, int64(2), count)
require.NoError(t, db.Delete(kb2).Error)
count, err = repo.CountByModelID(ctx, 1, modelID)
require.NoError(t, err)
assert.Equal(t, int64(1), count)
}
func TestCountByModelID_CustomAgent(t *testing.T) {
ctx := context.Background()
db := setupModelUsageTestDB(t)
repo := NewCustomAgentRepository(db)
modelID := "chat-model-1"
agent := &types.CustomAgent{
ID: uuid.New().String(),
Name: "test-agent",
TenantID: 1,
Config: types.CustomAgentConfig{
ModelID: modelID,
},
}
require.NoError(t, repo.CreateAgent(ctx, agent))
count, err := repo.CountByModelID(ctx, 1, modelID)
require.NoError(t, err)
assert.Equal(t, int64(1), count)
agent2 := &types.CustomAgent{
ID: uuid.New().String(),
Name: "rerank-agent",
TenantID: 1,
Config: types.CustomAgentConfig{
RerankModelID: modelID,
},
}
require.NoError(t, repo.CreateAgent(ctx, agent2))
count, err = repo.CountByModelID(ctx, 1, modelID)
require.NoError(t, err)
assert.Equal(t, int64(2), count)
count, err = repo.CountByModelID(ctx, 2, modelID)
require.NoError(t, err)
assert.Equal(t, int64(0), count)
require.NoError(t, repo.DeleteAgent(ctx, agent2.ID, 1))
count, err = repo.CountByModelID(ctx, 1, modelID)
require.NoError(t, err)
assert.Equal(t, int64(1), count)
}