Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(qdrant): treat a missing dimension collection as an empty delete target (#3419)
Leon562b131e6c6c
diff --git a/internal/application/repository/retriever/qdrant/repository.go b/internal/application/repository/retriever/qdrant/repository.goindex 77c3ae1bd..473731aef 100644--- a/internal/application/repository/retriever/qdrant/repository.go+++ b/internal/application/repository/retriever/qdrant/repository.go@@ -13,6 +13,8 @@ import ("github.com/Tencent/WeKnora/internal/types/interfaces""github.com/google/uuid""github.com/qdrant/go-client/qdrant"+ "google.golang.org/grpc/codes"+ "google.golang.org/grpc/status")const (@@ -53,22 +55,100 @@ func (q *qdrantRepository) getCollectionName(dimension int) string {return fmt.Sprintf("%s_%d", q.collectionBaseName, dimension)}-// ensureCollection ensures the collection exists for the given dimension-func (q *qdrantRepository) ensureCollection(ctx context.Context, dimension int) error {+// collectionExists reports whether the dimension-specific collection is+// present. Collections are created lazily on the first write for a dimension,+// so callers that only need to know whether there is anything to act on must+// tolerate "does not exist" instead of treating it as a failure.+//+// A dimension already registered as initialized in this process short-circuits+// the RPC, which keeps the common path at one round-trip per delete. The cache+// is only a hint: deletePoints still treats a missing collection on the Delete+// RPC as a no-op and drops the cache, so a Qdrant wipe without restarting this+// process cannot revive "Collection ... doesn't exist!" (#3337).+func (q *qdrantRepository) collectionExists(ctx context.Context, dimension int) (bool, error) {+ if _, ok := q.initializedCollections.Load(dimension); ok {+ return true, nil+ }++ exists, err := q.client.CollectionExists(ctx, q.getCollectionName(dimension))+ if err != nil {+ return false, fmt.Errorf("failed to check collection existence: %w", err)+ }+ return exists, nil+}++// deleteTarget resolves the collection a delete should run against and reports+// whether the delete is worth issuing. A dimension-specific collection that was+// never created holds no points, so deleting from it is a no-op — the same rule+// VectorRetrieve already applies to reads.+//+// This matters because the ingest paths re-index a chunk by deleting first and+// writing second (see knowledgeService.updateChunkVector and+// chunkService.syncChunkIndex). When that delete is the first touch of a+// dimension, failing on the missing collection aborts the write that would have+// created it, so ingestion fails with "Collection ... doesn't exist!" (#3337).+// deletePoints is the second line of defence if this probe (or its cache)+// disagrees with the store.+func (q *qdrantRepository) deleteTarget(ctx context.Context, dimension int) (string, bool, error) {collectionName := q.getCollectionName(dimension)- // Check cache first- if _, ok := q.initializedCollections.Load(dimension); ok {+ exists, err := q.collectionExists(ctx, dimension)+ if err != nil {+ return collectionName, false, err+ }+ if !exists {+ logger.GetLogger(ctx).Infof(+ "[Qdrant] Collection %s does not exist, nothing to delete", collectionName)+ return collectionName, false, nil+ }+ return collectionName, true, nil+}++// isMissingCollectionErr reports whether err is Qdrant saying the dimension+// collection is gone. The go-client wraps the gRPC status, and tests (and some+// server paths) surface the issue's "Collection ... doesn't exist!" wording.+func isMissingCollectionErr(err error) bool {+ if err == nil {+ return false+ }+ if status.Code(err) == codes.NotFound {+ return true+ }+ return strings.Contains(err.Error(), "doesn't exist")+}++// deletePoints issues DeletePoints and treats a missing collection as a no-op.+// When that happens the process-local initialized cache is dropped so the+// following write (ensureCollection) will recreate the collection instead of+// skipping create and failing the upsert.+func (q *qdrantRepository) deletePoints(ctx context.Context, dimension int, collectionName string, points *qdrant.PointsSelector) error {+ _, err := q.client.Delete(ctx, &qdrant.DeletePoints{+ CollectionName: collectionName,+ Points: points,+ })+ if err == nil {return nil}+ if !isMissingCollectionErr(err) {+ return err+ }+ q.initializedCollections.Delete(dimension)+ logger.GetLogger(ctx).Infof(+ "[Qdrant] Collection %s does not exist, nothing to delete", collectionName)+ return nil+}++// ensureCollection ensures the collection exists for the given dimension+func (q *qdrantRepository) ensureCollection(ctx context.Context, dimension int) error {+ collectionName := q.getCollectionName(dimension)log := logger.GetLogger(ctx)- // Check if collection exists- exists, err := q.client.CollectionExists(ctx, collectionName)+ // Cached dimensions and existing collections need no creation work.+ exists, err := q.collectionExists(ctx, dimension)if err != nil {log.Errorf("[Qdrant] Failed to check collection existence: %v", err)- return fmt.Errorf("failed to check collection existence: %w", err)+ return err}if !exists {@@ -281,17 +361,22 @@ func (q *qdrantRepository) DeleteByChunkIDList(ctx context.Context, chunkIDListreturn nil}- collectionName := q.getCollectionName(dimension)+ collectionName, ok, err := q.deleteTarget(ctx, dimension)+ if err != nil {+ log.Errorf("[Qdrant] Failed to check collection existence: %v", err)+ return err+ }+ if !ok {+ return nil+ }+log.Infof("[Qdrant] Deleting indices by chunk IDs from %s, count: %d", collectionName, len(chunkIDList))- _, err := q.client.Delete(ctx, &qdrant.DeletePoints{- CollectionName: collectionName,- Points: qdrant.NewPointsSelectorFilter(&qdrant.Filter{- Must: []*qdrant.Condition{- qdrant.NewMatchKeywords(fieldChunkID, chunkIDList...),- },- }),- })+ err = q.deletePoints(ctx, dimension, collectionName, qdrant.NewPointsSelectorFilter(&qdrant.Filter{+ Must: []*qdrant.Condition{+ qdrant.NewMatchKeywords(fieldChunkID, chunkIDList...),+ },+ }))if err != nil {log.Errorf("[Qdrant] Failed to delete by chunk IDs: %v", err)return fmt.Errorf("failed to delete by chunk IDs: %w", err)@@ -311,17 +396,22 @@ func (q *qdrantRepository) DeleteByKnowledgeIDList(ctx context.Context,return nil}- collectionName := q.getCollectionName(dimension)+ collectionName, ok, err := q.deleteTarget(ctx, dimension)+ if err != nil {+ log.Errorf("[Qdrant] Failed to check collection existence: %v", err)+ return err+ }+ if !ok {+ return nil+ }+log.Infof("[Qdrant] Deleting indices by knowledge IDs from %s, count: %d", collectionName, len(knowledgeIDList))- _, err := q.client.Delete(ctx, &qdrant.DeletePoints{- CollectionName: collectionName,- Points: qdrant.NewPointsSelectorFilter(&qdrant.Filter{- Must: []*qdrant.Condition{- qdrant.NewMatchKeywords(fieldKnowledgeID, knowledgeIDList...),- },- }),- })+ err = q.deletePoints(ctx, dimension, collectionName, qdrant.NewPointsSelectorFilter(&qdrant.Filter{+ Must: []*qdrant.Condition{+ qdrant.NewMatchKeywords(fieldKnowledgeID, knowledgeIDList...),+ },+ }))if err != nil {log.Errorf("[Qdrant] Failed to delete by knowledge IDs: %v", err)return fmt.Errorf("failed to delete by knowledge IDs: %w", err)@@ -341,17 +431,22 @@ func (q *qdrantRepository) DeleteBySourceIDList(ctx context.Context,return nil}- collectionName := q.getCollectionName(dimension)+ collectionName, ok, err := q.deleteTarget(ctx, dimension)+ if err != nil {+ log.Errorf("[Qdrant] Failed to check collection existence: %v", err)+ return err+ }+ if !ok {+ return nil+ }+log.Infof("[Qdrant] Deleting indices by source IDs from %s, count: %d", collectionName, len(sourceIDList))- _, err := q.client.Delete(ctx, &qdrant.DeletePoints{- CollectionName: collectionName,- Points: qdrant.NewPointsSelectorFilter(&qdrant.Filter{- Must: []*qdrant.Condition{- qdrant.NewMatchKeywords(fieldSourceID, sourceIDList...),- },- }),- })+ err = q.deletePoints(ctx, dimension, collectionName, qdrant.NewPointsSelectorFilter(&qdrant.Filter{+ Must: []*qdrant.Condition{+ qdrant.NewMatchKeywords(fieldSourceID, sourceIDList...),+ },+ }))if err != nil {log.Errorf("[Qdrant] Failed to delete by source IDs: %v", err)return fmt.Errorf("failed to delete by source IDs: %w", err)diff --git a/internal/application/repository/retriever/qdrant/repository_test.go b/internal/application/repository/retriever/qdrant/repository_test.goindex c85ef41b5..62b97995e 100644--- a/internal/application/repository/retriever/qdrant/repository_test.go+++ b/internal/application/repository/retriever/qdrant/repository_test.go@@ -9,8 +9,11 @@ import ("time""unicode/utf8"+ "github.com/Tencent/WeKnora/internal/types""github.com/qdrant/go-client/qdrant""google.golang.org/grpc"+ "google.golang.org/grpc/codes"+ "google.golang.org/grpc/status")func TestNewQdrantValueMapSanitizesInvalidUTF8AndNUL(t *testing.T) {@@ -87,35 +90,16 @@ func TestCreatePayloadSanitizesAllStringFields(t *testing.T) {}}-// Intercept the SDK's RPCs so failures and cancellation need no live server.-func newPayloadUpdateTestRepository(t *testing.T, collections []string, listErr error,- setPayload func(context.Context, *qdrant.SetPayloadPoints) error,-) *qdrantRepository {+// newInterceptedQdrantClient builds a client whose unary RPCs are answered by+// the given interceptor, so repository behaviour can be pinned without a live+// Qdrant server.+func newInterceptedQdrantClient(t *testing.T, intercept grpc.UnaryClientInterceptor) *qdrant.Client {t.Helper()client, err := qdrant.NewClient(&qdrant.Config{Host: "localhost",PoolSize: 1,SkipCompatibilityCheck: true,- GrpcOptions: []grpc.DialOption{grpc.WithUnaryInterceptor(func(- ctx context.Context, method string, req, reply any, _ *grpc.ClientConn,- _ grpc.UnaryInvoker, _ ...grpc.CallOption,- ) error {- switch request := req.(type) {- case *qdrant.ListCollectionsRequest:- if listErr != nil {- return listErr- }- response := reply.(*qdrant.ListCollectionsResponse)- for _, name := range collections {- response.Collections = append(response.Collections, &qdrant.CollectionDescription{Name: name})- }- return nil- case *qdrant.SetPayloadPoints:- return setPayload(ctx, request)- default:- return fmt.Errorf("unexpected RPC %s", method)- }- })},+ GrpcOptions: []grpc.DialOption{grpc.WithUnaryInterceptor(intercept)},})if err != nil {t.Fatal(err)@@ -125,6 +109,34 @@ func newPayloadUpdateTestRepository(t *testing.T, collections []string, listErrt.Error(err)}})+ return client+}++// Intercept the SDK's RPCs so failures and cancellation need no live server.+func newPayloadUpdateTestRepository(t *testing.T, collections []string, listErr error,+ setPayload func(context.Context, *qdrant.SetPayloadPoints) error,+) *qdrantRepository {+ t.Helper()+ client := newInterceptedQdrantClient(t, func(+ ctx context.Context, method string, req, reply any, _ *grpc.ClientConn,+ _ grpc.UnaryInvoker, _ ...grpc.CallOption,+ ) error {+ switch request := req.(type) {+ case *qdrant.ListCollectionsRequest:+ if listErr != nil {+ return listErr+ }+ response := reply.(*qdrant.ListCollectionsResponse)+ for _, name := range collections {+ response.Collections = append(response.Collections, &qdrant.CollectionDescription{Name: name})+ }+ return nil+ case *qdrant.SetPayloadPoints:+ return setPayload(ctx, request)+ default:+ return fmt.Errorf("unexpected RPC %s", method)+ }+ })return &qdrantRepository{client: client, collectionBaseName: "vectors"}}@@ -275,3 +287,235 @@ func TestBatchPayloadUpdatesEmptyInput(t *testing.T) {t.Fatal(err)}}++// deleteTestRepository is a stand-in Qdrant that only holds `collections` and+// answers like the real server: a delete against a collection it does not have+// fails with the same "Collection ... doesn't exist!" error the issue reports.+// `probe` optionally overrides the CollectionExists answer, e.g. to inject an+// infrastructure failure; a nil probe answers from the inventory.+const qdrantMissingCollectionErr = "Collection %s doesn't exist!"++type deleteTestRepository struct {+ repo *qdrantRepository+ collections map[string]bool+ probe func(collectionName string) (bool, error)+ probed []string+ deletes []string+}++func newDeleteTestRepository(t *testing.T, collections []string,+ probe func(collectionName string) (bool, error),+) *deleteTestRepository {+ t.Helper()+ harness := &deleteTestRepository{+ collections: make(map[string]bool, len(collections)),+ probe: probe,+ }+ for _, name := range collections {+ harness.collections[name] = true+ }+ client := newInterceptedQdrantClient(t, func(+ _ context.Context, method string, req, reply any, _ *grpc.ClientConn,+ _ grpc.UnaryInvoker, _ ...grpc.CallOption,+ ) error {+ switch request := req.(type) {+ case *qdrant.CollectionExistsRequest:+ name := request.GetCollectionName()+ harness.probed = append(harness.probed, name)+ if harness.probe == nil {+ response := reply.(*qdrant.CollectionExistsResponse)+ response.Result = &qdrant.CollectionExists{Exists: harness.collections[name]}+ return nil+ }+ found, err := harness.probe(name)+ if err != nil {+ return err+ }+ reply.(*qdrant.CollectionExistsResponse).Result = &qdrant.CollectionExists{Exists: found}+ return nil+ case *qdrant.DeletePoints:+ name := request.GetCollectionName()+ harness.deletes = append(harness.deletes, name)+ if !harness.collections[name] {+ // Same gRPC status and wording the real server uses, so the+ // NotFound no-op path is exercised rather than a paraphrase.+ return status.Error(codes.NotFound, fmt.Sprintf(qdrantMissingCollectionErr, name))+ }+ return nil+ default:+ return fmt.Errorf("unexpected RPC %s", method)+ }+ })+ harness.repo = &qdrantRepository{client: client, collectionBaseName: "vectors"}+ return harness+}++// deleteOperations covers every repository method that deletes by a dimension,+// so the missing-collection rule is pinned for all three of them.+func deleteOperations() []struct {+ name string+ run func(context.Context, *qdrantRepository) error+} {+ return []struct {+ name string+ run func(context.Context, *qdrantRepository) error+ }{+ {"chunk ids", func(ctx context.Context, repo *qdrantRepository) error {+ return repo.DeleteByChunkIDList(ctx, []string{"chunk-1"}, 1024, types.KnowledgeBaseTypeDocument)+ }},+ {"knowledge ids", func(ctx context.Context, repo *qdrantRepository) error {+ return repo.DeleteByKnowledgeIDList(ctx, []string{"knowledge-1"}, 1024, types.KnowledgeBaseTypeDocument)+ }},+ {"source ids", func(ctx context.Context, repo *qdrantRepository) error {+ return repo.DeleteBySourceIDList(ctx, []string{"source-1"}, 1024, types.KnowledgeBaseTypeDocument)+ }},+ }+}++// A dimension collection is created lazily on the first write, so deleting from+// one that was never created must be a no-op rather than an error: ingest and+// re-index run "delete then write", and failing here aborts the write that would+// have created the collection (#3337).+func TestDeletesSkipMissingCollection(t *testing.T) {+ for _, operation := range deleteOperations() {+ t.Run(operation.name, func(t *testing.T) {+ // The store holds no dimension collection yet: the delete must not+ // reach Qdrant, otherwise it reports the collection as missing.+ harness := newDeleteTestRepository(t, nil, nil)++ if err := operation.run(context.Background(), harness.repo); err != nil {+ t.Fatalf("delete against a missing collection must be a no-op, got %v", err)+ }+ if len(harness.probed) != 1 || harness.probed[0] != "vectors_1024" {+ t.Fatalf("expected one existence probe for vectors_1024, got %v", harness.probed)+ }+ if len(harness.deletes) != 0 {+ t.Fatalf("expected no delete RPC for a missing collection, got %v", harness.deletes)+ }+ })+ }+}++func TestDeletesIssueWhenCollectionExists(t *testing.T) {+ for _, operation := range deleteOperations() {+ t.Run(operation.name, func(t *testing.T) {+ harness := newDeleteTestRepository(t, []string{"vectors_1024"}, nil)++ if err := operation.run(context.Background(), harness.repo); err != nil {+ t.Fatal(err)+ }+ if len(harness.deletes) != 1 || harness.deletes[0] != "vectors_1024" {+ t.Fatalf("expected one delete against vectors_1024, got %v", harness.deletes)+ }+ })+ }+}++// Infrastructure failures must not be mistaken for an absent collection: a+// store that cannot answer must fail the delete loudly.+func TestDeletePropagatesCollectionCheckFailure(t *testing.T) {+ for _, operation := range deleteOperations() {+ t.Run(operation.name, func(t *testing.T) {+ harness := newDeleteTestRepository(t, []string{"vectors_1024"}, func(string) (bool, error) {+ return false, errors.New("qdrant unavailable")+ })++ err := operation.run(context.Background(), harness.repo)+ if err == nil || !strings.Contains(err.Error(), "failed to check collection existence") {+ t.Fatalf("expected the existence probe failure to surface, got %v", err)+ }+ if len(harness.deletes) != 0 {+ t.Fatalf("expected no delete RPC after a failed probe, got %v", harness.deletes)+ }+ })+ }+}++// A dimension this process already created needs no probe, which keeps the+// steady-state delete at one round-trip.+func TestDeleteSkipsProbeForInitializedDimension(t *testing.T) {+ harness := newDeleteTestRepository(t, []string{"vectors_1024"}, func(string) (bool, error) {+ t.Error("initialized dimensions must not be probed")+ return false, nil+ })+ harness.repo.initializedCollections.Store(1024, true)++ if err := harness.repo.DeleteByKnowledgeIDList(+ context.Background(), []string{"knowledge-1"}, 1024, types.KnowledgeBaseTypeDocument,+ ); err != nil {+ t.Fatal(err)+ }+ if len(harness.deletes) != 1 || harness.deletes[0] != "vectors_1024" {+ t.Fatalf("expected one delete against vectors_1024, got %v", harness.deletes)+ }+}++// An empty ID list short-circuits before any RPC, including the new probe.+func TestDeleteWithEmptyIDListSkipsAllRPCs(t *testing.T) {+ harness := newDeleteTestRepository(t, []string{"vectors_1024"}, func(string) (bool, error) {+ t.Error("empty deletes must not probe the collection")+ return false, nil+ })++ ctx := context.Background()+ if err := harness.repo.DeleteByChunkIDList(ctx, nil, 1024, types.KnowledgeBaseTypeDocument); err != nil {+ t.Fatal(err)+ }+ if err := harness.repo.DeleteByKnowledgeIDList(ctx, nil, 1024, types.KnowledgeBaseTypeDocument); err != nil {+ t.Fatal(err)+ }+ if err := harness.repo.DeleteBySourceIDList(ctx, nil, 1024, types.KnowledgeBaseTypeDocument); err != nil {+ t.Fatal(err)+ }+ if len(harness.deletes) != 0 {+ t.Fatalf("expected no delete RPC for an empty ID list, got %v", harness.deletes)+ }+}++func TestIsMissingCollectionErr(t *testing.T) {+ cases := []struct {+ name string+ err error+ want bool+ }{+ {"nil", nil, false},+ {"generic", errors.New("qdrant unavailable"), false},+ {"issue wording", fmt.Errorf(qdrantMissingCollectionErr, "vectors_1024"), true},+ {"grpc not found", status.Error(codes.NotFound, "Not found: Collection vectors_1024 doesn't exist!"), true},+ {"wrapped not found", fmt.Errorf("Delete() failed: vectors_1024: %w", status.Error(codes.NotFound, "Not found")), true},+ {"other grpc", status.Error(codes.Unavailable, "qdrant down"), false},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := isMissingCollectionErr(tc.err); got != tc.want {+ t.Fatalf("isMissingCollectionErr(%v) = %v, want %v", tc.err, got, tc.want)+ }+ })+ }+}++// A dimension this process already created is not probed, so a Qdrant wipe+// that leaves the cache stale still reaches DeletePoints. That RPC's missing+// collection must be a no-op and must drop the cache so the following write+// can recreate the collection (#3337).+func TestDeleteTreatsStaleCacheMissingCollectionAsNoOp(t *testing.T) {+ for _, operation := range deleteOperations() {+ t.Run(operation.name, func(t *testing.T) {+ harness := newDeleteTestRepository(t, nil, func(string) (bool, error) {+ t.Error("stale cache must skip the existence probe")+ return false, nil+ })+ harness.repo.initializedCollections.Store(1024, true)++ if err := operation.run(context.Background(), harness.repo); err != nil {+ t.Fatalf("stale cache + missing collection must be a no-op, got %v", err)+ }+ if len(harness.deletes) != 1 || harness.deletes[0] != "vectors_1024" {+ t.Fatalf("expected one delete against vectors_1024, got %v", harness.deletes)+ }+ if _, ok := harness.repo.initializedCollections.Load(1024); ok {+ t.Fatal("missing collection must drop the initialized cache so the following write can recreate it")+ }+ })+ }+}