chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,231 @@
|
||||
package qdrant
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/qdrant/go-client/qdrant"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// copyTestRecordLimit bounds how many target chunk ids the fake keeps, so a run
|
||||
// that writes the same page over and over cannot grow without limit.
|
||||
const copyTestRecordLimit = 4096
|
||||
|
||||
// copyTestServer answers the RPCs CopyIndices makes and emulates the scroll
|
||||
// cursor of a real Qdrant server: `offset` is inclusive (the returned page
|
||||
// starts at that id), so the id the next request has to start at is the first
|
||||
// point that was *not* returned - and the server hands that id back in
|
||||
// next_page_offset.
|
||||
type copyTestServer struct {
|
||||
mu sync.Mutex
|
||||
source []*qdrant.RetrievedPoint
|
||||
target []string
|
||||
scrolls int
|
||||
upserts int
|
||||
written int
|
||||
// stuck answers every scroll with the same page and the same cursor, which
|
||||
// is what a server that never moves the cursor on looks like.
|
||||
stuck bool
|
||||
}
|
||||
|
||||
func copyTestUUID(i int) string {
|
||||
return fmt.Sprintf("00000000-0000-0000-0000-%012d", i)
|
||||
}
|
||||
|
||||
// copyTestVectors builds the dense vector a stored point carries.
|
||||
func copyTestVectors() *qdrant.VectorsOutput {
|
||||
return &qdrant.VectorsOutput{
|
||||
VectorsOptions: &qdrant.VectorsOutput_Vector{
|
||||
Vector: &qdrant.VectorOutput{
|
||||
Vector: &qdrant.VectorOutput_Dense{
|
||||
Dense: &qdrant.DenseVector{Data: []float32{0.1, 0.2, 0.3, 0.4}},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func copyTestSourcePoint(i int) *qdrant.RetrievedPoint {
|
||||
chunk := fmt.Sprintf("chunk-%d", i)
|
||||
return &qdrant.RetrievedPoint{
|
||||
Id: qdrant.NewID(copyTestUUID(i)),
|
||||
Payload: newQdrantValueMap(map[string]any{
|
||||
fieldContent: "content of " + chunk,
|
||||
fieldSourceID: chunk,
|
||||
fieldSourceType: int64(1),
|
||||
fieldChunkID: chunk,
|
||||
fieldKnowledgeID: "know-1",
|
||||
fieldKnowledgeBaseID: "kb-src",
|
||||
fieldTagID: "",
|
||||
fieldIsEnabled: true,
|
||||
}),
|
||||
Vectors: copyTestVectors(),
|
||||
}
|
||||
}
|
||||
|
||||
// page answers one scroll the way the emulated server would.
|
||||
func (s *copyTestServer) page(req *qdrant.ScrollPoints) ([]*qdrant.RetrievedPoint, *qdrant.PointId) {
|
||||
limit := int(req.GetLimit())
|
||||
if s.stuck {
|
||||
if limit > len(s.source) {
|
||||
limit = len(s.source)
|
||||
}
|
||||
return s.source[:limit], s.source[0].Id
|
||||
}
|
||||
|
||||
start := 0
|
||||
if offset := req.GetOffset(); offset != nil {
|
||||
for start < len(s.source) && s.source[start].Id.GetUuid() < offset.GetUuid() {
|
||||
start++
|
||||
}
|
||||
}
|
||||
end := min(start+limit, len(s.source))
|
||||
if end >= len(s.source) {
|
||||
return s.source[start:end], nil
|
||||
}
|
||||
return s.source[start:end], s.source[end].Id
|
||||
}
|
||||
|
||||
// repository returns a repository whose client is answered by this fake, plus
|
||||
// the chunk mapping CopyIndices is called with for `count` source chunks.
|
||||
func (s *copyTestServer) repository(t *testing.T, count int) (*qdrantRepository, map[string]string) {
|
||||
t.Helper()
|
||||
for i := range count {
|
||||
s.source = append(s.source, copyTestSourcePoint(i))
|
||||
}
|
||||
chunkMap := make(map[string]string, count)
|
||||
for i := range count {
|
||||
chunkMap[fmt.Sprintf("chunk-%d", i)] = fmt.Sprintf("target-chunk-%d", i)
|
||||
}
|
||||
|
||||
client := newInterceptedQdrantClient(t, func(
|
||||
ctx context.Context, method string, req, reply any, _ *grpc.ClientConn,
|
||||
_ grpc.UnaryInvoker, _ ...grpc.CallOption,
|
||||
) error {
|
||||
// A live server stops answering once the caller's deadline passes.
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
switch request := req.(type) {
|
||||
case *qdrant.CollectionExistsRequest:
|
||||
reply.(*qdrant.CollectionExistsResponse).Result = &qdrant.CollectionExists{Exists: true}
|
||||
return nil
|
||||
case *qdrant.ScrollPoints:
|
||||
s.scrolls++
|
||||
response := reply.(*qdrant.ScrollResponse)
|
||||
response.Result, response.NextPageOffset = s.page(request)
|
||||
return nil
|
||||
case *qdrant.UpsertPoints:
|
||||
s.upserts++
|
||||
s.written += len(request.Points)
|
||||
for _, point := range request.Points {
|
||||
if len(s.target) >= copyTestRecordLimit {
|
||||
break
|
||||
}
|
||||
s.target = append(s.target, point.Payload[fieldChunkID].GetStringValue())
|
||||
}
|
||||
reply.(*qdrant.PointsOperationResponse).Result = &qdrant.UpdateResult{
|
||||
Status: qdrant.UpdateStatus_Completed,
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unexpected RPC %s", method)
|
||||
}
|
||||
})
|
||||
return &qdrantRepository{client: client, collectionBaseName: "Copy"}, chunkMap
|
||||
}
|
||||
|
||||
func (s *copyTestServer) counts() (scrolls, upserts, written int) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.scrolls, s.upserts, s.written
|
||||
}
|
||||
|
||||
// repeatedTargetChunks returns the recorded target chunk ids that were written
|
||||
// more than once, and how many extra copies they account for.
|
||||
func (s *copyTestServer) repeatedTargetChunks() (chunks []string, extra int) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
counts := make(map[string]int, len(s.target))
|
||||
for _, chunk := range s.target {
|
||||
counts[chunk]++
|
||||
}
|
||||
for chunk, n := range counts {
|
||||
if n > 1 {
|
||||
chunks = append(chunks, chunk)
|
||||
extra += n - 1
|
||||
}
|
||||
}
|
||||
return chunks, extra
|
||||
}
|
||||
|
||||
func (s *copyTestServer) summary() string {
|
||||
scrolls, upserts, written := s.counts()
|
||||
repeated, extra := s.repeatedTargetChunks()
|
||||
return fmt.Sprintf(
|
||||
"scrolls=%d upserts=%d points written=%d recorded=%d chunks written twice=%v duplicate copies=%d",
|
||||
scrolls, upserts, written, len(s.target), repeated, extra)
|
||||
}
|
||||
|
||||
func runCopyTest(repo *qdrantRepository, chunkMap map[string]string, timeout time.Duration) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
return repo.CopyIndices(ctx, "kb-src", map[string]string{"know-1": "know-2"},
|
||||
chunkMap, "kb-dst", 64, "doc")
|
||||
}
|
||||
|
||||
// Qdrant's scroll offset is inclusive, so the last id of a page is not the
|
||||
// cursor for the next page; the server returns that cursor in
|
||||
// next_page_offset. Deriving the cursor from the page instead makes every page
|
||||
// after the first re-read its last point and copy it into the target again.
|
||||
func TestCopyIndicesCopiesEachSourceChunkOnce(t *testing.T) {
|
||||
const sourceCount = 150
|
||||
server := ©TestServer{}
|
||||
repo, chunkMap := server.repository(t, sourceCount)
|
||||
defer func() { t.Log("copy run: " + server.summary()) }()
|
||||
|
||||
if err := runCopyTest(repo, chunkMap, 30*time.Second); err != nil {
|
||||
t.Fatalf("CopyIndices: %v", err)
|
||||
}
|
||||
|
||||
scrolls, upserts, written := server.counts()
|
||||
if repeated, extra := server.repeatedTargetChunks(); len(repeated) > 0 {
|
||||
t.Errorf("target chunks %v were copied again (%d extra copies)", repeated, extra)
|
||||
}
|
||||
// 150 chunks at 64 per page: 64 + 64 + 22, so three pages and three writes.
|
||||
if scrolls != 3 || upserts != 3 {
|
||||
t.Errorf("scrolls = %d, upserts = %d, want 3 and 3", scrolls, upserts)
|
||||
}
|
||||
if written != sourceCount {
|
||||
t.Errorf("target points = %d, want %d", written, sourceCount)
|
||||
}
|
||||
}
|
||||
|
||||
// A source that never moves its cursor on must fail loudly instead of writing
|
||||
// the same page into the target until the task deadline.
|
||||
func TestCopyIndicesRejectsANonAdvancingCursor(t *testing.T) {
|
||||
const sourceCount = 64
|
||||
server := ©TestServer{stuck: true}
|
||||
repo, chunkMap := server.repository(t, sourceCount)
|
||||
defer func() { t.Log("copy run: " + server.summary()) }()
|
||||
|
||||
err := runCopyTest(repo, chunkMap, 5*time.Second)
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), "made no progress") {
|
||||
t.Fatalf("CopyIndices error = %v, want one about a cursor that made no progress", err)
|
||||
}
|
||||
scrolls, upserts, written := server.counts()
|
||||
if scrolls != 2 {
|
||||
t.Errorf("scrolls = %d, want 2 (stop on the first repeated cursor)", scrolls)
|
||||
}
|
||||
if upserts != 1 || written != sourceCount {
|
||||
t.Errorf("upserts = %d writing %d points, want 1 writing %d", upserts, written, sourceCount)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Package qdrant implements vector retrieval and metadata updates in Qdrant.
|
||||
package qdrant
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/qdrant/go-client/qdrant"
|
||||
)
|
||||
|
||||
func (q *qdrantRepository) MoveKnowledgeIndices(
|
||||
ctx context.Context,
|
||||
sourceKB, targetKB, knowledgeID string,
|
||||
_ []string,
|
||||
dimension int,
|
||||
_ string,
|
||||
) error {
|
||||
wait := true
|
||||
_, err := q.client.SetPayload(ctx, &qdrant.SetPayloadPoints{
|
||||
CollectionName: q.getCollectionName(dimension), Wait: &wait,
|
||||
Payload: newQdrantValueMap(map[string]any{fieldKnowledgeBaseID: targetKB, fieldTagID: ""}),
|
||||
PointsSelector: qdrant.NewPointsSelectorFilter(&qdrant.Filter{Must: []*qdrant.Condition{
|
||||
qdrant.NewMatch(fieldKnowledgeBaseID, sourceKB), qdrant.NewMatch(fieldKnowledgeID, knowledgeID),
|
||||
}}),
|
||||
})
|
||||
return err
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,942 @@
|
||||
package qdrant
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/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) {
|
||||
malformed := "prefix" + string([]byte{0xff}) + "\x00suffix"
|
||||
payload := newQdrantValueMap(map[string]any{
|
||||
fieldContent: malformed,
|
||||
fieldSourceType: int64(1),
|
||||
fieldIsEnabled: true,
|
||||
})
|
||||
|
||||
got := payload[fieldContent].GetStringValue()
|
||||
if got != "prefixsuffix" {
|
||||
t.Fatalf("unexpected sanitized content: %q", got)
|
||||
}
|
||||
if !utf8.ValidString(got) {
|
||||
t.Fatalf("sanitized content is not valid UTF-8: % x", []byte(got))
|
||||
}
|
||||
if gotSourceType := payload[fieldSourceType].GetIntegerValue(); gotSourceType != 1 {
|
||||
t.Fatalf("source type changed: got %d, want 1", gotSourceType)
|
||||
}
|
||||
if gotEnabled := payload[fieldIsEnabled].GetBoolValue(); !gotEnabled {
|
||||
t.Fatal("is_enabled changed during payload sanitization")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewQdrantValueMapPreservesValidUTF8(t *testing.T) {
|
||||
valid := "valid UTF-8 中文内容"
|
||||
payload := newQdrantValueMap(map[string]any{
|
||||
fieldContent: valid,
|
||||
})
|
||||
|
||||
got := payload[fieldContent].GetStringValue()
|
||||
if got != valid {
|
||||
t.Fatalf("valid content changed: got %q, want %q", got, valid)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatePayloadSanitizesAllStringFields(t *testing.T) {
|
||||
malformed := "a" + string([]byte{0xff}) + "\x00b"
|
||||
embedding := &QdrantVectorEmbedding{
|
||||
Content: malformed,
|
||||
SourceID: malformed,
|
||||
SourceType: 2,
|
||||
ChunkID: malformed,
|
||||
KnowledgeID: malformed,
|
||||
KnowledgeBaseID: malformed,
|
||||
TagID: malformed,
|
||||
IsEnabled: true,
|
||||
}
|
||||
|
||||
payload := createPayload(embedding)
|
||||
stringFields := []string{
|
||||
fieldContent,
|
||||
fieldSourceID,
|
||||
fieldChunkID,
|
||||
fieldKnowledgeID,
|
||||
fieldKnowledgeBaseID,
|
||||
fieldTagID,
|
||||
}
|
||||
for _, field := range stringFields {
|
||||
got := payload[field].GetStringValue()
|
||||
if got != "ab" {
|
||||
t.Errorf("%s was not sanitized correctly: got %q", field, got)
|
||||
}
|
||||
if !utf8.ValidString(got) {
|
||||
t.Errorf("%s remains invalid UTF-8: % x", field, []byte(got))
|
||||
}
|
||||
}
|
||||
if got := payload[fieldSourceType].GetIntegerValue(); got != 2 {
|
||||
t.Errorf("source type changed: got %d, want 2", got)
|
||||
}
|
||||
if got := payload[fieldIsEnabled].GetBoolValue(); !got {
|
||||
t.Error("is_enabled changed during payload creation")
|
||||
}
|
||||
}
|
||||
|
||||
// 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(intercept)},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := client.Close(); err != nil {
|
||||
t.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"}
|
||||
}
|
||||
|
||||
func TestBatchPayloadUpdates(t *testing.T) {
|
||||
operations := []struct {
|
||||
name string
|
||||
groups int
|
||||
run func(context.Context, *qdrantRepository) error
|
||||
}{
|
||||
{"enable", 1, func(ctx context.Context, repo *qdrantRepository) error {
|
||||
return repo.BatchUpdateChunkEnabledStatus(ctx, map[string]bool{"chunk": true})
|
||||
}},
|
||||
{"disable", 1, func(ctx context.Context, repo *qdrantRepository) error {
|
||||
return repo.BatchUpdateChunkEnabledStatus(ctx, map[string]bool{"chunk": false})
|
||||
}},
|
||||
{"mixed status", 2, func(ctx context.Context, repo *qdrantRepository) error {
|
||||
return repo.BatchUpdateChunkEnabledStatus(ctx, map[string]bool{"on": true, "off": false})
|
||||
}},
|
||||
{"tags", 2, func(ctx context.Context, repo *qdrantRepository) error {
|
||||
return repo.BatchUpdateChunkTagID(ctx, map[string]string{"one": "tag-a", "two": "tag-b"})
|
||||
}},
|
||||
}
|
||||
for _, operation := range operations {
|
||||
t.Run(operation.name, func(t *testing.T) {
|
||||
modes := []string{"success", "partial failure", "all failures", "list failure", "no collections"}
|
||||
for _, mode := range modes {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
collections := []string{"vectors_768", "unrelated_768", "vectors_1536"}
|
||||
if mode == "no collections" {
|
||||
collections = []string{"unrelated_768"}
|
||||
}
|
||||
var listErr error
|
||||
if mode == "list failure" {
|
||||
listErr = errors.New("list unavailable")
|
||||
}
|
||||
calls := 0
|
||||
var failures []error
|
||||
var descriptions []string
|
||||
repo := newPayloadUpdateTestRepository(t, collections, listErr,
|
||||
func(_ context.Context, request *qdrant.SetPayloadPoints) error {
|
||||
calls++
|
||||
if request.CollectionName == "unrelated_768" {
|
||||
t.Error("updated an unrelated collection")
|
||||
}
|
||||
fail := mode == "all failures" ||
|
||||
(mode == "partial failure" && request.CollectionName == "vectors_768")
|
||||
if !fail {
|
||||
return nil
|
||||
}
|
||||
failure := fmt.Errorf("failure %d", calls)
|
||||
failures = append(failures, failure)
|
||||
description := fmt.Sprintf("set chunk tag_id %q",
|
||||
request.Payload[fieldTagID].GetStringValue())
|
||||
if enabled, ok := request.Payload[fieldIsEnabled]; ok {
|
||||
description = "disable chunks"
|
||||
if enabled.GetBoolValue() {
|
||||
description = "enable chunks"
|
||||
}
|
||||
}
|
||||
descriptions = append(descriptions, description+" in collection "+request.CollectionName)
|
||||
return failure
|
||||
})
|
||||
err := operation.run(context.Background(), repo)
|
||||
wantCalls := 2 * operation.groups
|
||||
if mode == "list failure" || mode == "no collections" {
|
||||
wantCalls = 0
|
||||
}
|
||||
if calls != wantCalls {
|
||||
t.Fatalf("got %d updates, want %d", calls, wantCalls)
|
||||
}
|
||||
if listErr != nil && !errors.Is(err, listErr) {
|
||||
t.Fatalf("lost list failure: %v", err)
|
||||
}
|
||||
if listErr == nil && len(failures) == 0 && err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
for i, failure := range failures {
|
||||
if !errors.Is(err, failure) {
|
||||
t.Errorf("lost failure %v in %v", failure, err)
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), descriptions[i]) {
|
||||
t.Errorf("missing operation/collection %q in %v", descriptions[i], err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("cancellation retains earlier failures", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
failure := errors.New("first update failed")
|
||||
calls := 0
|
||||
repo := newPayloadUpdateTestRepository(t, []string{"vectors_768", "vectors_1536", "vectors_384"}, nil,
|
||||
func(context.Context, *qdrant.SetPayloadPoints) error {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return failure
|
||||
}
|
||||
cancel()
|
||||
return ctx.Err()
|
||||
})
|
||||
err := operation.run(ctx, repo)
|
||||
if calls != 2 || !errors.Is(err, failure) || !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("calls=%d, err=%v; want 2 calls and both errors", calls, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("canceled before starting", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if err := operation.run(ctx, &qdrantRepository{}); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("expected cancellation before any RPC, got %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("canceled during final update", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
calls := 0
|
||||
repo := newPayloadUpdateTestRepository(t, []string{"vectors_768"}, nil,
|
||||
func(context.Context, *qdrant.SetPayloadPoints) error {
|
||||
calls++
|
||||
if calls == operation.groups {
|
||||
cancel()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err := operation.run(ctx, repo); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("expected cancellation instead of success, got %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("expired deadline", func(t *testing.T) {
|
||||
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
|
||||
defer cancel()
|
||||
if err := operation.run(ctx, &qdrantRepository{}); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("expected deadline error before any RPC, got %v", err)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchPayloadUpdatesEmptyInput(t *testing.T) {
|
||||
repo := &qdrantRepository{}
|
||||
if err := repo.BatchUpdateChunkEnabledStatus(context.Background(), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.BatchUpdateChunkTagID(context.Background(), nil); err != nil {
|
||||
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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// errKeywordScroll makes every Scroll RPC fail the way an unreachable or
|
||||
// overloaded Qdrant does.
|
||||
var errKeywordScroll = errors.New("qdrant scroll unavailable")
|
||||
|
||||
type keywordsTestHarness struct {
|
||||
repo *qdrantRepository
|
||||
scrolls []string
|
||||
}
|
||||
|
||||
// newKeywordsTestHarness wires KeywordsRetrieve to a fake Qdrant server. The
|
||||
// collection list and the per-collection Scroll outcome are the only inputs the
|
||||
// search loop has, so both are controlled here instead of stubbing the
|
||||
// repository.
|
||||
func newKeywordsTestHarness(t *testing.T, collections []string,
|
||||
scroll func(collectionName string) ([]*qdrant.RetrievedPoint, error),
|
||||
) *keywordsTestHarness {
|
||||
t.Helper()
|
||||
harness := &keywordsTestHarness{}
|
||||
client := newInterceptedQdrantClient(t, func(
|
||||
_ context.Context, method string, req, reply any, _ *grpc.ClientConn,
|
||||
_ grpc.UnaryInvoker, _ ...grpc.CallOption,
|
||||
) error {
|
||||
switch request := req.(type) {
|
||||
case *qdrant.ListCollectionsRequest:
|
||||
response := reply.(*qdrant.ListCollectionsResponse)
|
||||
for _, name := range collections {
|
||||
response.Collections = append(response.Collections, &qdrant.CollectionDescription{Name: name})
|
||||
}
|
||||
return nil
|
||||
case *qdrant.ScrollPoints:
|
||||
name := request.GetCollectionName()
|
||||
harness.scrolls = append(harness.scrolls, name)
|
||||
points, err := scroll(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reply.(*qdrant.ScrollResponse).Result = points
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unexpected RPC %s", method)
|
||||
}
|
||||
})
|
||||
harness.repo = &qdrantRepository{client: client, collectionBaseName: "vectors"}
|
||||
return harness
|
||||
}
|
||||
|
||||
func keywordsRetrieveParams() types.RetrieveParams {
|
||||
return types.RetrieveParams{
|
||||
Query: "invoice total",
|
||||
TopK: 10,
|
||||
KnowledgeBaseIDs: []string{"kb-1"},
|
||||
}
|
||||
}
|
||||
|
||||
func keywordHitPoint(id, content string) *qdrant.RetrievedPoint {
|
||||
return &qdrant.RetrievedPoint{
|
||||
Id: &qdrant.PointId{PointIdOptions: &qdrant.PointId_Uuid{Uuid: id}},
|
||||
Payload: map[string]*qdrant.Value{
|
||||
fieldContent: qdrant.NewValueString(content),
|
||||
fieldChunkID: qdrant.NewValueString(id),
|
||||
fieldSourceID: qdrant.NewValueString("source-1"),
|
||||
fieldSourceType: qdrant.NewValueInt(2),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// captureLogs redirects the package logger for one test. The conclusion
|
||||
// "No keyword matches found" is only legitimate when nothing failed, so the
|
||||
// tests assert on the rendered log rather than on the counters alone.
|
||||
func captureLogs(t *testing.T) *bytes.Buffer {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
logger.SetOutput(&buf)
|
||||
t.Cleanup(func() { logger.SetOutput(os.Stdout) })
|
||||
return &buf
|
||||
}
|
||||
|
||||
// A batch in which every matching collection fails must reach the caller as an
|
||||
// error. Returning an empty result set with a nil error is indistinguishable
|
||||
// from a genuine zero-hit search, and the QA pipeline answers "no relevant
|
||||
// content" on top of it (#3835).
|
||||
func TestKeywordsRetrieveFailsWhenEveryMatchedCollectionFails(t *testing.T) {
|
||||
logs := captureLogs(t)
|
||||
harness := newKeywordsTestHarness(t,
|
||||
[]string{"vectors_1024", "vectors_1536", "other_2048"},
|
||||
func(string) ([]*qdrant.RetrievedPoint, error) {
|
||||
return nil, errKeywordScroll
|
||||
},
|
||||
)
|
||||
|
||||
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())
|
||||
|
||||
if !errors.Is(err, errKeywordScroll) {
|
||||
t.Fatalf("all-collections failure must surface as an error, got %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "all 2 matched collections") {
|
||||
t.Fatalf("error must state how many collections failed, got %q", err)
|
||||
}
|
||||
if results != nil {
|
||||
t.Fatalf("no result set may accompany the error, got %d sets", len(results))
|
||||
}
|
||||
if want := []string{"vectors_1024", "vectors_1536"}; !slices.Equal(harness.scrolls, want) {
|
||||
t.Fatalf("scroll attempts = %v, want %v: only base-name collections are searched", harness.scrolls, want)
|
||||
}
|
||||
if strings.Contains(logs.String(), "No keyword matches found") {
|
||||
t.Fatal("a failed batch must not be logged as a search that found no matches")
|
||||
}
|
||||
}
|
||||
|
||||
// One failing collection must not fail the batch as long as another one
|
||||
// answered: partial results are still results. The failure must travel with
|
||||
// them though (RetrieveResult.Error) — otherwise callers treat the incomplete
|
||||
// answer as a complete one (#3835).
|
||||
func TestKeywordsRetrieveKeepsResultsWhenOnlySomeCollectionsFail(t *testing.T) {
|
||||
logs := captureLogs(t)
|
||||
harness := newKeywordsTestHarness(t, []string{"vectors_1024", "vectors_1536"},
|
||||
func(name string) ([]*qdrant.RetrievedPoint, error) {
|
||||
if name == "vectors_1024" {
|
||||
return nil, errKeywordScroll
|
||||
}
|
||||
return []*qdrant.RetrievedPoint{keywordHitPoint("chunk-1", "invoice total 42")}, nil
|
||||
},
|
||||
)
|
||||
|
||||
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())
|
||||
if err != nil {
|
||||
t.Fatalf("a partially failed batch must not fail the caller, got %v", err)
|
||||
}
|
||||
if len(results) != 1 {
|
||||
t.Fatalf("expected one result set, got %d", len(results))
|
||||
}
|
||||
if results[0].Error == nil {
|
||||
t.Fatal("a partially failed batch must mark its result set with the failure")
|
||||
}
|
||||
if !errors.Is(results[0].Error, errKeywordScroll) {
|
||||
t.Fatalf("partial error must keep the underlying cause, got %v", results[0].Error)
|
||||
}
|
||||
if !strings.Contains(results[0].Error.Error(), "1 of 2 matched collections") {
|
||||
t.Fatalf("partial error must state what failed, got %q", results[0].Error)
|
||||
}
|
||||
if len(results[0].Results) != 1 {
|
||||
t.Fatalf("expected the surviving collection's hit, got %d results", len(results[0].Results))
|
||||
}
|
||||
if got := results[0].Results[0].ChunkID; got != "chunk-1" {
|
||||
t.Fatalf("unexpected chunk id %q", got)
|
||||
}
|
||||
if results[0].RetrieverType != types.KeywordsRetrieverType {
|
||||
t.Fatalf("expected keywords retriever type, got %v", results[0].RetrieverType)
|
||||
}
|
||||
if strings.Contains(logs.String(), "No keyword matches found") {
|
||||
t.Fatal("a partially failed batch must not be logged as a search that found no matches")
|
||||
}
|
||||
}
|
||||
|
||||
// The genuine zero-hit outcome keeps its old shape: every collection answered,
|
||||
// no token matched, so an empty result with a nil error is correct and the
|
||||
// conclusion log still fires.
|
||||
func TestKeywordsRetrieveReportsNoMatchesWhenNothingFailed(t *testing.T) {
|
||||
logs := captureLogs(t)
|
||||
harness := newKeywordsTestHarness(t, []string{"vectors_1024"},
|
||||
func(string) ([]*qdrant.RetrievedPoint, error) {
|
||||
return nil, nil
|
||||
},
|
||||
)
|
||||
|
||||
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())
|
||||
if err != nil {
|
||||
t.Fatalf("a successful search without matches must not error, got %v", err)
|
||||
}
|
||||
if len(results) != 1 || len(results[0].Results) != 0 {
|
||||
t.Fatalf("expected one empty result set, got %#v", results)
|
||||
}
|
||||
if results[0].Error != nil {
|
||||
t.Fatalf("a complete zero-hit search must not mark an error, got %v", results[0].Error)
|
||||
}
|
||||
if !strings.Contains(logs.String(), "No keyword matches found") {
|
||||
t.Fatal("a successful zero-hit search must still be logged as such")
|
||||
}
|
||||
}
|
||||
|
||||
// A partial failure with zero hits is still a partial failure: the result set
|
||||
// stays empty but must carry the error, and the conclusion log must stay off.
|
||||
func TestKeywordsRetrieveMarksPartialFailureWhenNothingHit(t *testing.T) {
|
||||
logs := captureLogs(t)
|
||||
harness := newKeywordsTestHarness(t, []string{"vectors_1024", "vectors_1536"},
|
||||
func(name string) ([]*qdrant.RetrievedPoint, error) {
|
||||
if name == "vectors_1024" {
|
||||
return nil, errKeywordScroll
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
)
|
||||
|
||||
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())
|
||||
if err != nil {
|
||||
t.Fatalf("a partially failed batch must not fail the caller, got %v", err)
|
||||
}
|
||||
if len(results) != 1 || len(results[0].Results) != 0 {
|
||||
t.Fatalf("expected one empty result set, got %#v", results)
|
||||
}
|
||||
if !errors.Is(results[0].Error, errKeywordScroll) {
|
||||
t.Fatalf("partial failure with zero hits must still be marked, got %v", results[0].Error)
|
||||
}
|
||||
if strings.Contains(logs.String(), "No keyword matches found") {
|
||||
t.Fatal("a partially failed batch must not be logged as a search that found no matches")
|
||||
}
|
||||
}
|
||||
|
||||
// No collection carries the repository's base name: nothing was searched at
|
||||
// all, which must be distinguishable from a search that ran and hit nothing.
|
||||
func TestKeywordsRetrieveWarnsWhenNoCollectionMatchesBaseName(t *testing.T) {
|
||||
logs := captureLogs(t)
|
||||
harness := newKeywordsTestHarness(t, []string{"other_1024"},
|
||||
func(string) ([]*qdrant.RetrievedPoint, error) {
|
||||
return nil, nil
|
||||
},
|
||||
)
|
||||
|
||||
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())
|
||||
if err != nil {
|
||||
t.Fatalf("an empty collection list must not error, got %v", err)
|
||||
}
|
||||
if len(results) != 1 || len(results[0].Results) != 0 {
|
||||
t.Fatalf("expected one empty result set, got %#v", results)
|
||||
}
|
||||
if results[0].Error != nil {
|
||||
t.Fatalf("no matching collection is not a partial failure, got %v", results[0].Error)
|
||||
}
|
||||
if len(harness.scrolls) != 0 {
|
||||
t.Fatalf("no Scroll may be issued without a matching collection, got %v", harness.scrolls)
|
||||
}
|
||||
if !strings.Contains(logs.String(), "No collection matched base name") {
|
||||
t.Fatal("a search that never ran must be logged as such")
|
||||
}
|
||||
if strings.Contains(logs.String(), "No keyword matches found") {
|
||||
t.Fatal("a search that never ran must not be logged as a search that found no matches")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPointWritesWaitForApplication(t *testing.T) {
|
||||
indices := make([]*types.IndexInfo, 101)
|
||||
embeddings := make(map[string][]float32, len(indices))
|
||||
for i := range indices {
|
||||
id := fmt.Sprintf("chunk-%d", i)
|
||||
indices[i] = &types.IndexInfo{SourceID: id, ChunkID: id, IsEnabled: true}
|
||||
embeddings[id] = []float32{0.1, 0.2, 0.3, 0.4}
|
||||
}
|
||||
params := map[string]any{fieldEmbedding: embeddings}
|
||||
chunkMap := make(map[string]string, 65)
|
||||
for i := range 65 {
|
||||
chunkMap[fmt.Sprintf("chunk-%d", i)] = fmt.Sprintf("target-%d", i)
|
||||
}
|
||||
operations := []struct {
|
||||
name string
|
||||
writes int
|
||||
run func(context.Context, *qdrantRepository) error
|
||||
}{
|
||||
{"save", 1, func(ctx context.Context, repo *qdrantRepository) error {
|
||||
return repo.Save(ctx, indices[0], params)
|
||||
}},
|
||||
{"batch save", 2, func(ctx context.Context, repo *qdrantRepository) error {
|
||||
return repo.BatchSave(ctx, indices, params)
|
||||
}},
|
||||
{"copy", 2, func(ctx context.Context, repo *qdrantRepository) error {
|
||||
return repo.CopyIndices(ctx, "kb-src", map[string]string{"know-1": "know-2"},
|
||||
chunkMap, "kb-dst", 4, types.KnowledgeBaseTypeDocument)
|
||||
}},
|
||||
{"enable and disable", 2, func(ctx context.Context, repo *qdrantRepository) error {
|
||||
return repo.BatchUpdateChunkEnabledStatus(ctx, map[string]bool{"on": true, "off": false})
|
||||
}},
|
||||
{"tags", 2, func(ctx context.Context, repo *qdrantRepository) error {
|
||||
return repo.BatchUpdateChunkTagID(ctx, map[string]string{"one": "tag-a", "two": "tag-b"})
|
||||
}},
|
||||
{"move", 1, func(ctx context.Context, repo *qdrantRepository) error {
|
||||
return repo.MoveKnowledgeIndices(ctx, "kb-src", "kb-dst", "know-1", nil, 4, "doc")
|
||||
}},
|
||||
}
|
||||
for _, operation := range deleteOperations() {
|
||||
operations = append(operations, struct {
|
||||
name string
|
||||
writes int
|
||||
run func(context.Context, *qdrantRepository) error
|
||||
}{operation.name, 1, operation.run})
|
||||
}
|
||||
for _, operation := range operations {
|
||||
t.Run(operation.name, func(t *testing.T) {
|
||||
for _, outcome := range []struct {
|
||||
name string
|
||||
err error
|
||||
}{
|
||||
{"completed", nil},
|
||||
{"application failure", status.Error(codes.Internal, "failed to apply write")},
|
||||
{"timeout", context.DeadlineExceeded},
|
||||
} {
|
||||
t.Run(outcome.name, func(t *testing.T) {
|
||||
server := ©TestServer{}
|
||||
for i := range 65 {
|
||||
server.source = append(server.source, copyTestSourcePoint(i))
|
||||
}
|
||||
applied, acknowledged := 0, 0
|
||||
client := newInterceptedQdrantClient(t, func(
|
||||
_ context.Context, method string, req, reply any, _ *grpc.ClientConn,
|
||||
_ grpc.UnaryInvoker, _ ...grpc.CallOption,
|
||||
) error {
|
||||
var wait bool
|
||||
switch request := req.(type) {
|
||||
case *qdrant.ListCollectionsRequest:
|
||||
reply.(*qdrant.ListCollectionsResponse).Collections = []*qdrant.CollectionDescription{
|
||||
{Name: "vectors_4"},
|
||||
}
|
||||
return nil
|
||||
case *qdrant.ScrollPoints:
|
||||
response := reply.(*qdrant.ScrollResponse)
|
||||
response.Result, response.NextPageOffset = server.page(request)
|
||||
return nil
|
||||
case *qdrant.UpsertPoints:
|
||||
wait = request.GetWait()
|
||||
case *qdrant.DeletePoints:
|
||||
wait = request.GetWait()
|
||||
case *qdrant.SetPayloadPoints:
|
||||
wait = request.GetWait()
|
||||
default:
|
||||
return fmt.Errorf("unexpected RPC %s", method)
|
||||
}
|
||||
// An asynchronous write can be acknowledged before it is applied,
|
||||
// even if application will fail. Only waiting exposes that failure.
|
||||
response := reply.(*qdrant.PointsOperationResponse)
|
||||
if !wait {
|
||||
acknowledged++
|
||||
response.Result = &qdrant.UpdateResult{Status: qdrant.UpdateStatus_Acknowledged}
|
||||
return nil
|
||||
}
|
||||
if outcome.err != nil {
|
||||
return outcome.err
|
||||
}
|
||||
applied++
|
||||
response.Result = &qdrant.UpdateResult{Status: qdrant.UpdateStatus_Completed}
|
||||
return nil
|
||||
})
|
||||
repo := &qdrantRepository{client: client, collectionBaseName: "vectors"}
|
||||
repo.initializedCollections.Store(4, true)
|
||||
repo.initializedCollections.Store(1024, true)
|
||||
err := operation.run(context.Background(), repo)
|
||||
if !errors.Is(err, outcome.err) {
|
||||
t.Fatalf("got error %v, want %v", err, outcome.err)
|
||||
}
|
||||
if acknowledged != 0 {
|
||||
t.Fatalf("returned with %d writes acknowledged but not applied", acknowledged)
|
||||
}
|
||||
if outcome.err == nil && applied != operation.writes {
|
||||
t.Fatalf("applied %d writes before return, want %d", applied, operation.writes)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// newEnsureCollectionTestRepository answers the existence probe with "missing"
|
||||
// and CreateCollection with createErr, recording the payload indexes created.
|
||||
func newEnsureCollectionTestRepository(t *testing.T, createErr error) (*qdrantRepository, *[]string) {
|
||||
t.Helper()
|
||||
var indexed []string
|
||||
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:
|
||||
reply.(*qdrant.CollectionExistsResponse).Result = &qdrant.CollectionExists{Exists: false}
|
||||
return nil
|
||||
case *qdrant.CreateCollection:
|
||||
return createErr
|
||||
case *qdrant.CreateFieldIndexCollection:
|
||||
indexed = append(indexed, request.GetFieldName())
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unexpected RPC %s", method)
|
||||
}
|
||||
})
|
||||
return &qdrantRepository{client: client, collectionBaseName: "vectors"}, &indexed
|
||||
}
|
||||
|
||||
// Several workers write the first batches of a new dimension at once, so the
|
||||
// create can lose to another worker. That must not fail the write: the
|
||||
// collection exists, and its payload indexes are still ensured.
|
||||
func TestEnsureCollectionAcceptsConcurrentCreate(t *testing.T) {
|
||||
repo, indexed := newEnsureCollectionTestRepository(t,
|
||||
status.Error(codes.AlreadyExists, "Wrong input: Collection `vectors_1024` already exists!"))
|
||||
|
||||
if err := repo.ensureCollection(context.Background(), 1024); err != nil {
|
||||
t.Fatalf("ensureCollection after losing the create race: %v", err)
|
||||
}
|
||||
if _, ok := repo.initializedCollections.Load(1024); !ok {
|
||||
t.Fatal("dimension must be cached once the collection is known to exist")
|
||||
}
|
||||
want := []string{fieldChunkID, fieldKnowledgeID, fieldKnowledgeBaseID, fieldSourceID, fieldIsEnabled, fieldContent}
|
||||
if !slices.Equal(*indexed, want) {
|
||||
t.Fatalf("payload indexes = %v, want %v", *indexed, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureCollectionReturnsOtherCreateErrors(t *testing.T) {
|
||||
repo, indexed := newEnsureCollectionTestRepository(t, status.Error(codes.Unavailable, "qdrant down"))
|
||||
|
||||
err := repo.ensureCollection(context.Background(), 1024)
|
||||
if status.Code(err) != codes.Unavailable {
|
||||
t.Fatalf("ensureCollection error = %v, want the Unavailable create error", err)
|
||||
}
|
||||
if _, ok := repo.initializedCollections.Load(1024); ok {
|
||||
t.Fatal("a failed create must not cache the dimension")
|
||||
}
|
||||
if len(*indexed) != 0 {
|
||||
t.Fatalf("no payload index should be created after a failed create, got %v", *indexed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package qdrant
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/qdrant/go-client/qdrant"
|
||||
)
|
||||
|
||||
type qdrantRepository struct {
|
||||
client *qdrant.Client
|
||||
collectionBaseName string
|
||||
shardNumber int // 0 = use Qdrant server default
|
||||
replicationFactor int // 0 = use Qdrant server default
|
||||
// Cache for initialized collections (dimension -> true)
|
||||
initializedCollections sync.Map
|
||||
}
|
||||
|
||||
type QdrantVectorEmbedding struct {
|
||||
Content string `json:"content"`
|
||||
SourceID string `json:"source_id"`
|
||||
SourceType int `json:"source_type"`
|
||||
ChunkID string `json:"chunk_id"`
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
TagID string `json:"tag_id"`
|
||||
Embedding []float32 `json:"embedding"`
|
||||
IsEnabled bool `json:"is_enabled"`
|
||||
}
|
||||
|
||||
type QdrantVectorEmbeddingWithScore struct {
|
||||
QdrantVectorEmbedding
|
||||
Score float64
|
||||
}
|
||||
Reference in new issue
Block a user