fix(knowledgebase): delete data sources when knowledge base is removed

Stop cron schedules and cancel in-flight sync logs when a KB is deleted,
and skip datasource sync tasks if the target KB no longer exists.
This commit is contained in:
wizardchen
2026-06-23 15:45:52 +08:00
committed by lyingbug
parent 3cb0e906a7
commit 11d461a4f7
3 changed files with 419 additions and 2 deletions
@@ -1,14 +1,151 @@
package service
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/hibiken/asynq"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestProcessSyncCancelsWhenKnowledgeBaseDeleted(t *testing.T) {
ds := &types.DataSource{
ID: "ds-1",
TenantID: 1,
KnowledgeBaseID: "kb-deleted",
Type: types.ConnectorTypeRSS,
Status: types.DataSourceStatusActive,
}
dsRepo := newKBDeleteDSRepo("kb-deleted", ds)
syncLog := &types.SyncLog{
ID: "log-1",
DataSourceID: ds.ID,
TenantID: ds.TenantID,
Status: types.SyncLogStatusRunning,
StartedAt: time.Now().UTC(),
}
syncLogRepo := &processSyncSyncLogRepo{logs: map[string]*types.SyncLog{syncLog.ID: syncLog}}
svc := &DataSourceService{
dsRepo: dsRepo,
syncLogRepo: syncLogRepo,
kbService: &processSyncKBService{getErr: apprepo.ErrKnowledgeBaseNotFound},
}
payload, err := json.Marshal(types.DataSourceSyncPayload{
DataSourceID: ds.ID,
TenantID: ds.TenantID,
SyncLogID: syncLog.ID,
})
require.NoError(t, err)
err = svc.ProcessSync(context.Background(), asynq.NewTask(types.TypeDataSourceSync, payload))
require.NoError(t, err)
updated := syncLogRepo.logs[syncLog.ID]
require.NotNil(t, updated)
assert.Equal(t, types.SyncLogStatusCanceled, updated.Status)
assert.Equal(t, "knowledge base has been deleted", updated.ErrorMessage)
require.NotNil(t, updated.FinishedAt)
}
type processSyncKBService struct {
getErr error
}
func (s *processSyncKBService) CreateKnowledgeBase(context.Context, *types.KnowledgeBase) (*types.KnowledgeBase, error) {
return nil, nil
}
func (s *processSyncKBService) GetKnowledgeBaseByID(context.Context, string) (*types.KnowledgeBase, error) {
return nil, s.getErr
}
func (s *processSyncKBService) GetKnowledgeBaseByIDOnly(context.Context, string) (*types.KnowledgeBase, error) {
return nil, s.getErr
}
func (s *processSyncKBService) GetKnowledgeBasesByIDsOnly(context.Context, []string) ([]*types.KnowledgeBase, error) {
return nil, nil
}
func (s *processSyncKBService) FillKnowledgeBaseCounts(context.Context, *types.KnowledgeBase) error {
return nil
}
func (s *processSyncKBService) ListKnowledgeBases(context.Context) ([]*types.KnowledgeBase, error) {
return nil, nil
}
func (s *processSyncKBService) ListKnowledgeBasesByTenantID(context.Context, uint64) ([]*types.KnowledgeBase, error) {
return nil, nil
}
func (s *processSyncKBService) UpdateKnowledgeBase(
context.Context, string, string, string, *types.KnowledgeBaseConfig,
) (*types.KnowledgeBase, error) {
return nil, nil
}
func (s *processSyncKBService) DeleteKnowledgeBase(context.Context, string) error { return nil }
func (s *processSyncKBService) TogglePinKnowledgeBase(context.Context, string) (*types.KnowledgeBase, error) {
return nil, nil
}
func (s *processSyncKBService) HybridSearch(context.Context, string, types.SearchParams) ([]*types.SearchResult, error) {
return nil, nil
}
func (s *processSyncKBService) GetQueryEmbedding(context.Context, string, string) ([]float32, error) {
return nil, nil
}
func (s *processSyncKBService) ResolveEmbeddingModelKeys(context.Context, []*types.KnowledgeBase) map[string]string {
return nil
}
func (s *processSyncKBService) CopyKnowledgeBase(context.Context, string, string) (*types.KnowledgeBase, *types.KnowledgeBase, error) {
return nil, nil, nil
}
func (s *processSyncKBService) GetRepository() interfaces.KnowledgeBaseRepository { return nil }
func (s *processSyncKBService) ProcessKBDelete(context.Context, *asynq.Task) error {
return nil
}
var _ interfaces.KnowledgeBaseService = (*processSyncKBService)(nil)
type processSyncSyncLogRepo struct {
logs map[string]*types.SyncLog
}
func (r *processSyncSyncLogRepo) Create(_ context.Context, log *types.SyncLog) error {
r.logs[log.ID] = log
return nil
}
func (r *processSyncSyncLogRepo) FindByID(_ context.Context, id string) (*types.SyncLog, error) {
log, ok := r.logs[id]
if !ok {
return nil, errors.New("sync log not found")
}
return log, nil
}
func (r *processSyncSyncLogRepo) FindByDataSource(context.Context, string, int, int) ([]*types.SyncLog, error) {
return nil, nil
}
func (r *processSyncSyncLogRepo) FindLatest(context.Context, string) (*types.SyncLog, error) {
return nil, nil
}
func (r *processSyncSyncLogRepo) HasRunningSync(context.Context, string) (bool, error) {
return false, nil
}
func (r *processSyncSyncLogRepo) Update(_ context.Context, log *types.SyncLog) error {
r.logs[log.ID] = log
return nil
}
func (r *processSyncSyncLogRepo) UpdateResult(_ context.Context, log *types.SyncLog) error {
return r.Update(context.Background(), log)
}
func (r *processSyncSyncLogRepo) CancelPendingByDataSource(context.Context, string) error {
return nil
}
func (r *processSyncSyncLogRepo) CleanupOldLogs(context.Context, int) error { return nil }
func TestAllFetchedItemsFailedError(t *testing.T) {
err := allFetchedItemsFailedError(&types.SyncResult{
Total: 2,
+51 -2
View File
@@ -10,6 +10,7 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/application/service/retriever"
"github.com/Tencent/WeKnora/internal/datasource"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
@@ -37,6 +38,9 @@ type knowledgeBaseService struct {
fileSvc interfaces.FileService
graphEngine interfaces.RetrieveGraphRepository
asynqClient interfaces.TaskEnqueuer
dsRepo interfaces.DataSourceRepository
syncLogRepo interfaces.SyncLogRepository
dsScheduler *datasource.Scheduler
}
// NewKnowledgeBaseService creates a new knowledge base service
@@ -52,6 +56,9 @@ func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
fileSvc interfaces.FileService,
graphEngine interfaces.RetrieveGraphRepository,
asynqClient interfaces.TaskEnqueuer,
dsRepo interfaces.DataSourceRepository,
syncLogRepo interfaces.SyncLogRepository,
dsScheduler *datasource.Scheduler,
) interfaces.KnowledgeBaseService {
return &knowledgeBaseService{
repo: repo,
@@ -66,6 +73,9 @@ func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
fileSvc: fileSvc,
graphEngine: graphEngine,
asynqClient: asynqClient,
dsRepo: dsRepo,
syncLogRepo: syncLogRepo,
dsScheduler: dsScheduler,
}
}
@@ -641,10 +651,16 @@ func (s *knowledgeBaseService) DeleteKnowledgeBase(ctx context.Context, id strin
}
// Step 1b: Remove all organization shares for this KB so org settings no longer show them
if delErr := s.shareRepo.DeleteByKnowledgeBaseID(ctx, id); delErr != nil {
logger.Warnf(ctx, "Failed to delete KB shares for knowledge base %s: %v", id, delErr)
if s.shareRepo != nil {
if delErr := s.shareRepo.DeleteByKnowledgeBaseID(ctx, id); delErr != nil {
logger.Warnf(ctx, "Failed to delete KB shares for knowledge base %s: %v", id, delErr)
}
}
// Step 1c: Stop and soft-delete all data sources bound to this KB so cron
// schedules and in-flight sync logs do not keep running against a deleted KB.
s.deleteDataSourcesForKnowledgeBase(ctx, id)
// Step 2: Enqueue async task for heavy cleanup operations
payload := types.KBDeletePayload{
TenantID: tenantID,
@@ -824,6 +840,39 @@ func (s *knowledgeBaseService) ProcessKBDelete(ctx context.Context, t *asynq.Tas
return nil
}
// deleteDataSourcesForKnowledgeBase mirrors DataSourceService.DeleteDataSource for
// every data source attached to the KB. Errors on individual sources are logged
// but do not fail KB deletion — the KB record is already soft-deleted.
func (s *knowledgeBaseService) deleteDataSourcesForKnowledgeBase(ctx context.Context, kbID string) {
if s.dsRepo == nil {
return
}
dataSources, err := s.dsRepo.FindByKnowledgeBase(ctx, kbID)
if err != nil {
logger.Warnf(ctx, "Failed to list data sources for deleted KB %s: %v", kbID, err)
return
}
for _, ds := range dataSources {
if ds == nil || ds.ID == "" {
continue
}
if err := s.dsRepo.Delete(ctx, ds.ID); err != nil {
logger.Warnf(ctx, "Failed to delete data source %s for KB %s: %v", ds.ID, kbID, err)
continue
}
if s.dsScheduler != nil {
s.dsScheduler.Remove(ds.ID)
}
if s.syncLogRepo != nil {
if err := s.syncLogRepo.CancelPendingByDataSource(ctx, ds.ID); err != nil {
logger.Warnf(ctx, "Failed to cancel pending sync logs for ds=%s (kb=%s): %v", ds.ID, kbID, err)
}
}
logger.Infof(ctx, "Data source deleted with knowledge base: ds=%s kb=%s", ds.ID, kbID)
}
}
// SetEmbeddingModel sets the embedding model for a knowledge base
func (s *knowledgeBaseService) SetEmbeddingModel(ctx context.Context, id string, modelID string) error {
if id == "" {
@@ -0,0 +1,231 @@
package service
import (
"context"
"errors"
"sync"
"testing"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/hibiken/asynq"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type kbDeleteDSRepo struct {
mu sync.Mutex
byKB map[string][]*types.DataSource
deleted map[string]bool
deleteIDs []string
}
func newKBDeleteDSRepo(kbID string, ds ...*types.DataSource) *kbDeleteDSRepo {
r := &kbDeleteDSRepo{
byKB: map[string][]*types.DataSource{kbID: ds},
deleted: map[string]bool{},
}
return r
}
func (r *kbDeleteDSRepo) Create(_ context.Context, _ *types.DataSource) error { return nil }
func (r *kbDeleteDSRepo) FindByID(_ context.Context, id string) (*types.DataSource, error) {
r.mu.Lock()
defer r.mu.Unlock()
if r.deleted[id] {
return nil, errors.New("data source not found")
}
for _, list := range r.byKB {
for _, ds := range list {
if ds.ID == id {
return ds, nil
}
}
}
return nil, errors.New("data source not found")
}
func (r *kbDeleteDSRepo) FindByKnowledgeBase(_ context.Context, kbID string) ([]*types.DataSource, error) {
r.mu.Lock()
defer r.mu.Unlock()
var active []*types.DataSource
for _, ds := range r.byKB[kbID] {
if !r.deleted[ds.ID] {
active = append(active, ds)
}
}
return active, nil
}
func (r *kbDeleteDSRepo) Update(_ context.Context, _ *types.DataSource) error { return nil }
func (r *kbDeleteDSRepo) UpdateSyncState(_ context.Context, _ *types.DataSource) error {
return nil
}
func (r *kbDeleteDSRepo) Delete(_ context.Context, id string) error {
r.mu.Lock()
defer r.mu.Unlock()
r.deleted[id] = true
r.deleteIDs = append(r.deleteIDs, id)
return nil
}
func (r *kbDeleteDSRepo) FindActive(_ context.Context) ([]*types.DataSource, error) {
return nil, nil
}
var _ interfaces.DataSourceRepository = (*kbDeleteDSRepo)(nil)
type kbDeleteSyncLogRepo struct {
mu sync.Mutex
canceled []string
}
func (r *kbDeleteSyncLogRepo) Create(_ context.Context, _ *types.SyncLog) error { return nil }
func (r *kbDeleteSyncLogRepo) FindByID(_ context.Context, _ string) (*types.SyncLog, error) {
return nil, errors.New("not found")
}
func (r *kbDeleteSyncLogRepo) FindByDataSource(_ context.Context, _ string, _, _ int) ([]*types.SyncLog, error) {
return nil, nil
}
func (r *kbDeleteSyncLogRepo) FindLatest(_ context.Context, _ string) (*types.SyncLog, error) {
return nil, nil
}
func (r *kbDeleteSyncLogRepo) HasRunningSync(_ context.Context, _ string) (bool, error) {
return false, nil
}
func (r *kbDeleteSyncLogRepo) Update(_ context.Context, _ *types.SyncLog) error { return nil }
func (r *kbDeleteSyncLogRepo) UpdateResult(_ context.Context, _ *types.SyncLog) error {
return nil
}
func (r *kbDeleteSyncLogRepo) CancelPendingByDataSource(_ context.Context, dsID string) error {
r.mu.Lock()
defer r.mu.Unlock()
r.canceled = append(r.canceled, dsID)
return nil
}
func (r *kbDeleteSyncLogRepo) CleanupOldLogs(_ context.Context, _ int) error { return nil }
var _ interfaces.SyncLogRepository = (*kbDeleteSyncLogRepo)(nil)
type kbDeleteKBRepo struct {
fakeKBRepo
deletedID string
}
func (r *kbDeleteKBRepo) DeleteKnowledgeBase(_ context.Context, id string) error {
r.deletedID = id
delete(r.rows, id)
return nil
}
type kbDeleteTaskEnqueuer struct{}
func (kbDeleteTaskEnqueuer) Enqueue(_ *asynq.Task, _ ...asynq.Option) (*asynq.TaskInfo, error) {
return &asynq.TaskInfo{ID: "kb-delete-task"}, nil
}
func TestDeleteDataSourcesForKnowledgeBase(t *testing.T) {
const kbID = "kb-1"
dsRepo := newKBDeleteDSRepo(kbID,
&types.DataSource{ID: "ds-1", KnowledgeBaseID: kbID, Status: types.DataSourceStatusActive, SyncSchedule: "0 0 * * * *"},
&types.DataSource{ID: "ds-2", KnowledgeBaseID: kbID, Status: types.DataSourceStatusActive},
)
syncLogRepo := &kbDeleteSyncLogRepo{}
kbRepo := &kbDeleteKBRepo{fakeKBRepo: *newFakeKBRepo()}
kbRepo.rows[kbID] = &types.KnowledgeBase{ID: kbID, TenantID: 1, Name: "test"}
scheduler := datasource.NewScheduler(dsRepo, syncLogRepo, kbDeleteTaskEnqueuer{})
require.NoError(t, scheduler.AddOrUpdate(dsRepo.byKB[kbID][0]))
svc := &knowledgeBaseService{
dsRepo: dsRepo,
syncLogRepo: syncLogRepo,
dsScheduler: scheduler,
}
svc.deleteDataSourcesForKnowledgeBase(ctxWithTenant(1), kbID)
assert.ElementsMatch(t, []string{"ds-1", "ds-2"}, dsRepo.deleteIDs)
assert.ElementsMatch(t, []string{"ds-1", "ds-2"}, syncLogRepo.canceled)
assert.Equal(t, 0, scheduler.EntryCount())
}
func TestDeleteKnowledgeBaseCleansUpDataSources(t *testing.T) {
const kbID = "kb-1"
dsRepo := newKBDeleteDSRepo(kbID,
&types.DataSource{ID: "ds-1", KnowledgeBaseID: kbID, Status: types.DataSourceStatusActive, SyncSchedule: "0 0 * * * *"},
)
syncLogRepo := &kbDeleteSyncLogRepo{}
kbRepo := &kbDeleteKBRepo{fakeKBRepo: *newFakeKBRepo()}
kbRepo.rows[kbID] = &types.KnowledgeBase{ID: kbID, TenantID: 1, Name: "test"}
scheduler := datasource.NewScheduler(dsRepo, syncLogRepo, kbDeleteTaskEnqueuer{})
require.NoError(t, scheduler.AddOrUpdate(dsRepo.byKB[kbID][0]))
svc := &knowledgeBaseService{
repo: kbRepo,
shareRepo: nil,
asynqClient: kbDeleteTaskEnqueuer{},
dsRepo: dsRepo,
syncLogRepo: syncLogRepo,
dsScheduler: scheduler,
}
ctx := ctxWithTenantStorage(1, "local")
err := svc.DeleteKnowledgeBase(ctx, kbID)
require.NoError(t, err)
assert.Equal(t, kbID, kbRepo.deletedID)
assert.Equal(t, []string{"ds-1"}, dsRepo.deleteIDs)
assert.Equal(t, []string{"ds-1"}, syncLogRepo.canceled)
assert.Equal(t, 0, scheduler.EntryCount())
}
func TestDeleteDataSourcesForKnowledgeBaseContinuesOnDeleteError(t *testing.T) {
const kbID = "kb-2"
dsRepo := &deleteErrDSRepo{
kbDeleteDSRepo: *newKBDeleteDSRepo(kbID, &types.DataSource{ID: "ds-bad", KnowledgeBaseID: kbID}),
deleteErr: errors.New("db unavailable"),
}
svc := &knowledgeBaseService{
dsRepo: dsRepo,
syncLogRepo: &kbDeleteSyncLogRepo{},
}
svc.deleteDataSourcesForKnowledgeBase(context.Background(), kbID)
assert.Empty(t, dsRepo.deleteIDs)
}
func TestDeleteKnowledgeBaseContinuesWhenDataSourceCleanupFails(t *testing.T) {
const kbID = "kb-2"
dsRepo := &deleteErrDSRepo{
kbDeleteDSRepo: *newKBDeleteDSRepo(kbID, &types.DataSource{ID: "ds-bad", KnowledgeBaseID: kbID}),
deleteErr: errors.New("db unavailable"),
}
kbRepo := &kbDeleteKBRepo{fakeKBRepo: *newFakeKBRepo()}
kbRepo.rows[kbID] = &types.KnowledgeBase{ID: kbID, TenantID: 1, Name: "test"}
svc := &knowledgeBaseService{
repo: kbRepo,
asynqClient: kbDeleteTaskEnqueuer{},
dsRepo: dsRepo,
syncLogRepo: &kbDeleteSyncLogRepo{},
}
err := svc.DeleteKnowledgeBase(ctxWithTenantStorage(1, "local"), kbID)
require.NoError(t, err)
assert.Equal(t, kbID, kbRepo.deletedID)
}
// deleteErrDSRepo injects a delete failure for testing best-effort cleanup.
type deleteErrDSRepo struct {
kbDeleteDSRepo
deleteErr error
}
func (r *deleteErrDSRepo) Delete(_ context.Context, id string) error {
if r.deleteErr != nil {
return r.deleteErr
}
return r.kbDeleteDSRepo.Delete(context.Background(), id)
}