From 04da26024c2412b34b3b30e7b283c98197ef95f1 Mon Sep 17 00:00:00 2001 From: linus-liu-web <395141741@qq.com> Date: Fri, 9 Oct 2026 10:47:30 +0800 Subject: [PATCH] =?UTF-8?q?fix(weaviate):=20CopyIndices=20=E8=A1=A5?= =?UTF-8?q?=E6=B8=B8=E6=A0=87=E9=98=B2=E6=8A=A4=EF=BC=8C=E5=B9=B6=E4=BF=AE?= =?UTF-8?q?=E6=8E=89=20GraphQL=20=E6=8A=A5=E9=94=99=E6=97=B6=E7=9A=84=20pa?= =?UTF-8?q?nic=20(#3881)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(weaviate): 复制索引时游标不前进立即报错,并给分页加跳数上限 CopyIndices 的游标由每页最后一个对象的 id 反推(repository.go:763),循环的 退出条件只有"查询出错"和"这一页为空"。源端只要重复返回同一页,游标就永远 停在同一个 id 上:循环把这一页反复读出、再反复 upsert 进目标库,直到复制任务 撞上 2 小时超时;源端在该页之后的数据永远读不到,而目标库里同一批 chunk 已经 被写成成千上万份候选向量。同包的 move.go 早就记录了 after+where 在 Weaviate 上不可靠,并为此用 seen 集合拦住"游标不前进",CopyIndices 用的正是这个组合, 却没有那层保护。 本次修改: - 记录每个用过的游标,重复即返回 "copy indices made no progress at cursor", 不再把"游标不动"当成"读完了"。检测点放在整页解析之后、批量写入之前,所以 重复的那一页不会再多写一份。 - 分页跳数上限 maxCopyPaginationHops(10000 页,按每页 64 条合 64 万行,与 confluence 的 maxPaginationHops 同量级);触顶时打印 Warn 并返回错误,而不是 把这轮复制当成成功——静默截断会留下一个看起来正常的残缺索引。 - additional["id"] 从无检查断言改为带检查断言,缺 id 或 id 为空时返回错误; 原先这里会 panic。同包 move.go 的 move index ID 已是这种写法。 回归用例用假 Weaviate 服务端复现两种源端形态:恒定返回同一页的源端在第二次 查询后被拦下(GraphQL 查询 2 次、目标库只写 64 条,而修复前 5s 内同一页被重放 4484 次、写入 286912 条);一直推进但永不结束的源端在第 10000 页被拦下。 * fix(weaviate): 复制索引时 GraphQL 层报错不再被当成"源已读完",也不再 panic Weaviate 对于"执行不了的查询"返回的是 HTTP 200 + errors 数组 + 没有 data。SDK 的 runGraphQLQuery 只在 HTTP 状态异常时返回 error(weaviate-go-client 的 graphql/gql.go:136-150),所以这种响应到 CopyIndices 手里时 err == nil,而 result.Data 是 nil。 原代码只检查 err,随后一行完成两件事: objects, ok := result.Data["Get"].(map[string]interface{})[collectionName].([]interface{}) 这里逗号-ok 只作用于最后一个断言,第一个 `.(map[string]interface{})` 是单值断言; result.Data 为 nil 时该表达式的值是 nil 接口,单值断言直接 panic。实测 (假服务端返回 {"errors":[{"message":"class Weknora_embeddings_64 does not exist"}]}): panic: interface conversion: models.JSONObject is nil, not map[string]interface {} .../weaviate.(*weaviateRepository).CopyIndices(...) repository.go:753 也就是说复制任务在这种响应下不是"静默少拷",而是直接 panic;即便不 panic,把 "没有 data"当成"这一页为空"也会让一次失败的查询以 Index copy completed 收尾。 本次修改: - 在 err 检查之后补 `len(result.Errors) > 0` → 记录日志并返回 "weaviate: copy indices query failed: ",与同文件 VectorRetrieve (:608-611)、KeywordsRetrieve (:677-680) 以及同包 move.go:32-34 的既有写法一致。 - 把那一行的两级断言拆成两次逗号-ok 断言,响应缺 Get 或 class 键时返回 "weaviate: copy indices invalid response",不再 panic。 回归用例 TestCopyIndicesReportsAQueryError:假服务端对所有 Get 返回上述 errors 响应,断言 CopyIndices 返回带原始 message 的错误(修复前是 panic),且只发一次 查询、没有把任何东西当成复制成功。 * test(weaviate): 补一个"响应读不出 data 时不得 panic"的复制用例 上一个提交把 `result.Data["Get"].(map[string]interface{})` 这一处单值断言拆成了两次 逗号-ok 断言,但只验证了"带 errors 的响应"那条路径:那条路径在 Errors 检查处就返回 了,走不到断言。这里补 TestCopyIndicesRejectsAResponseWithoutData,让假服务端返回 HTTP 200 + `{"data":{}}`(没有 errors,也没有 Get 键),断言 CopyIndices 返回 invalid response 而不是 panic;去掉断言拆分、只保留 Errors 检查时该用例必红。 两个用例都用 recover 把 panic 转成明确的用例失败,避免一个 panic 直接终结整个测试 二进制、连带吞掉同包其它用例的结果。 * fix(retriever/weaviate): CopyIndices 按映射分块读源行,去掉会被服务端拒绝的游标 CopyIndices 用 where + after 遍历源知识库,而 Weaviate 的游标 API 不允许过滤条件 与 after 同时出现:ValidateCursor 直接返回 "where cannot be set with after and limit parameters",且 client 第一页就会把 WithAfter("") 发成 after: "",所以这个 查询在真实服务端上一页都跑不通。该报错以 HTTP 200 + errors 返回,不检查 errors 的 代码会把它当成"源已读完",返回成功但一条都没复制(本 PR 已补的 errors 检查会把它 变成错误,但那是在暴露一个本就不合法的查询)。即使去掉 where,游标仍然是"跨请求 保持不变的结果顺序"上的位置,服务端不承诺维持该顺序,一旦漂移就会漏行且仍报成功。 改成按映射里的源 chunk ID 分块读:谓词 = knowledge_base_id 相等 AND chunk_id ContainsAny(本批 64 个),不带 after。读到的行集合由谓词唯一确定,没有游标可漂。 同一个 chunk 会有正文向量 + 多个生成问题向量,64 个 ID 不等于最多 64 行,所以每批 查询显式带 limit(QUERY_MAXIMUM_RESULTS,v1.37.3 默认 10000)。该配置没有客户端 接口(/v1/meta 只有 version/hostname/modules),先按默认值查,被服务端以 "query maximum results exceeded ... QUERY_MAXIMUM_RESULTS 'N'" 拒绝时按 N 降级 重试。一批返回行数达到 limit 说明可能被截断,对该批对半拆分重查直到单个 chunk; 单个 chunk 仍然填满 limit 时明确报错(含 chunk ID 与服务端上限),绝不返回复制成功。 不带 limit 的 GraphQL Get 会落到 QUERY_DEFAULTS_LIMIT_GRAPHQL(100) 静默截断。 页数上限(maxCopyPaginationHops)与重复游标防护随游标一起去掉:读取范围由映射 限定,不存在走不完的分页。GraphQL errors 检查与 data["Get"]、_additional["id"] 的逗号-ok 解包保留。 测试:copy_test.go 的假服务改成按 chunk_id 过滤的真实形状,并像 v1.37.3 一样拒绝 where+after 组合(假服务会断言这种组合从未出现);补同一 chunk 多向量、批次触顶 拆分、单 chunk 超限报错、QUERY_MAXIMUM_RESULTS 降级四类用例。 --------- Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com> Co-authored-by: linus-liu-web --- .../retriever/weaviate/copy_test.go | 503 ++++++++++++++++++ .../retriever/weaviate/repository.go | 218 +++++++- .../repository/retriever/weaviate/structs.go | 4 + 3 files changed, 700 insertions(+), 25 deletions(-) create mode 100644 internal/application/repository/retriever/weaviate/copy_test.go diff --git a/internal/application/repository/retriever/weaviate/copy_test.go b/internal/application/repository/retriever/weaviate/copy_test.go new file mode 100644 index 00000000..33e2655d --- /dev/null +++ b/internal/application/repository/retriever/weaviate/copy_test.go @@ -0,0 +1,503 @@ +package weaviate + +import ( + "context" + "encoding/json" + "fmt" + "maps" + "net/http" + "net/http/httptest" + "regexp" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + sdk "github.com/weaviate/weaviate-go-client/v5/weaviate" +) + +const copyTestCollection = "Copy_64" + +// cursorConflictMessage is what weaviate v1.37.3 answers when a Get combines a +// filter with the cursor API (entities/filters/cursor_validator.go). +const cursorConflictMessage = "where cannot be set with after and limit parameters" + +var ( + afterArgPattern = regexp.MustCompile(`after:\s*"([^"]*)"`) + limitArgPattern = regexp.MustCompile(`limit:\s*(\d+)`) + chunkArgPattern = regexp.MustCompile(`path: \["chunk_id"\] valueText: \[([^\]]*)\]`) + quotedPattern = regexp.MustCompile(`"([^"]*)"`) +) + +// copySourceRow is one source vector, in the shape a GraphQL Get answers with. +func copySourceRow(id, chunkID, sourceID string) map[string]any { + return map[string]any{ + fieldContent: "content of " + sourceID, + fieldSourceID: sourceID, + fieldSourceType: 1, + fieldChunkID: chunkID, + fieldKnowledgeID: "know-1", + fieldKnowledgeBaseID: "kb-src", + fieldTagID: "", + "_additional": map[string]any{"id": id, "vector": []any{0.5, 0.25}}, + } +} + +// copyWrittenObject is one object the copy sent to the batch endpoint. +type copyWrittenObject struct { + sourceID string + targetChunkID string +} + +// copyPageServer stands in for a Weaviate data node holding the source +// vectors. It answers Get the way the real one does - with the rows whose +// chunk_id is in the ContainsAny list the query asked for, cut off at the +// query's limit - and it validates the cursor API the way the real one does, +// so a query that combines `where` with `after` fails here exactly as it fails +// in production. +type copyPageServer struct { + mu sync.Mutex + // rows holds each chunk's vectors: one for the chunk content plus one per + // generated question, all sharing the chunk_id. + rows map[string][]map[string]any + order []string + + // queryLimit is the server's QUERY_MAXIMUM_RESULTS; 0 means no refusal. + queryLimit int + // ignoreChunkFilter answers every query with the same page, the way a + // source whose pages repeat themselves behaves. + ignoreChunkFilter bool + // queryError, when set, is the GraphQL error every Get is answered with. + queryError string + // omitData answers every Get with a data object that carries no Get key. + omitData bool + // omitCollection answers with a Get object that carries no key for the + // queried collection. + omitCollection bool + + queries int + limits []int + requested [][]string + rejected []string + batches int + written []copyWrittenObject + unexpected []string +} + +// copyTestStore builds a source whose chunks hold the given vectors. Each +// entry maps a chunk ID to its source IDs: the chunk's own content vector +// first, then one per generated question. +func copyTestStore(vectors map[string][]string) *copyPageServer { + s := ©PageServer{rows: make(map[string][]map[string]any)} + next := 0 + for _, chunkID := range slices.Sorted(maps.Keys(vectors)) { + for _, sourceID := range vectors[chunkID] { + s.rows[chunkID] = append(s.rows[chunkID], copySourceRow(copyTestUUID(next), chunkID, sourceID)) + next++ + } + s.order = append(s.order, chunkID) + } + return s +} + +func copyTestUUID(i int) string { + return fmt.Sprintf("00000000-0000-0000-0000-%012d", i) +} + +// copyTestChunkMap maps size chunks onto target chunks. +func copyTestChunkMap(size int) map[string]string { + m := make(map[string]string, size) + for i := range size { + m[fmt.Sprintf("chunk-%d", i)] = fmt.Sprintf("target-chunk-%d", i) + } + return m +} + +// copyTestSingleVectorChunks builds a source with one vector per named chunk. +func copyTestSingleVectorChunks(chunkIDs ...string) *copyPageServer { + vectors := make(map[string][]string, len(chunkIDs)) + for _, chunkID := range chunkIDs { + vectors[chunkID] = []string{chunkID} + } + return copyTestStore(vectors) +} + +// serve starts an httptest server for s and returns a repository pointed at +// it. The copy's own query limit is left at its default; tests that need the +// truncation path lower it on the returned repository. +func (s *copyPageServer) serve(t *testing.T) *weaviateRepository { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(s.handle)) + t.Cleanup(server.Close) + client, err := sdk.NewClient(sdk.Config{Scheme: "http", Host: strings.TrimPrefix(server.URL, "http://")}) + require.NoError(t, err) + return &weaviateRepository{client: client, collectionBaseName: "Copy"} +} + +func (s *copyPageServer) handle(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodPost && r.URL.Path == "/v1/graphql": + var body struct { + Query string `json:"query"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + _ = json.NewEncoder(w).Encode(s.resolve(body.Query)) + case r.Method == http.MethodPost && r.URL.Path == "/v1/batch/objects": + var body struct { + Objects []struct { + Properties map[string]any `json:"properties"` + } `json:"objects"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + s.mu.Lock() + s.batches++ + for _, obj := range body.Objects { + s.written = append(s.written, copyWrittenObject{ + sourceID: fmt.Sprint(obj.Properties[fieldSourceID]), + targetChunkID: fmt.Sprint(obj.Properties[fieldChunkID]), + }) + } + s.mu.Unlock() + _, _ = w.Write([]byte(`[]`)) + case r.Method == http.MethodGet && r.URL.Path == "/v1/meta": + _, _ = w.Write([]byte(`{"version":"1.37.3"}`)) + default: + s.mu.Lock() + s.unexpected = append(s.unexpected, r.Method+" "+r.URL.Path) + s.mu.Unlock() + w.WriteHeader(http.StatusNotFound) + } +} + +// resolve answers one GraphQL Get the way Weaviate does. A query it refused +// comes back as a successful call carrying an errors array, which is what the +// copy has to read as a failure. +func (s *copyPageServer) resolve(query string) map[string]any { + s.mu.Lock() + defer s.mu.Unlock() + s.queries++ + + limit := 0 + if match := limitArgPattern.FindStringSubmatch(query); match != nil { + limit, _ = strconv.Atoi(match[1]) + } + s.limits = append(s.limits, limit) + + // The cursor API refuses a filtered query: a Get that asks for rows after a + // cursor cannot also carry where and limit. + if strings.Contains(query, "where:") { + if afterArgPattern.MatchString(query) { + s.rejected = append(s.rejected, query) + return graphQLError("cursor api: invalid 'after' parameter: " + cursorConflictMessage) + } + } + + switch { + case s.queryError != "": + return graphQLError(s.queryError) + case s.omitData: + return map[string]any{"data": map[string]any{}} + case s.omitCollection: + return map[string]any{"data": map[string]any{"Get": map[string]any{}}} + } + + if s.queryLimit > 0 && limit > s.queryLimit { + return graphQLError(fmt.Sprintf( + "query maximum results exceeded: the total limit calculated from the provided offset '0' "+ + "and limit '%d' exceeds the configured value for QUERY_MAXIMUM_RESULTS '%d'. "+ + "If you've supplied a negative offset or limit, this may be an underflow error", + limit, s.queryLimit)) + } + + chunkIDs := copyRequestedChunkIDs(query) + s.requested = append(s.requested, chunkIDs) + + order := chunkIDs + if s.ignoreChunkFilter { + order = s.order + } + rows := make([]any, 0, len(s.rows)) + for _, chunkID := range order { + for _, row := range s.rows[chunkID] { + rows = append(rows, row) + } + } + if limit > 0 && len(rows) > limit { + rows = rows[:limit] + } + return map[string]any{"data": map[string]any{"Get": map[string]any{copyTestCollection: rows}}} +} + +func graphQLError(message string) map[string]any { + return map[string]any{"errors": []any{map[string]any{"message": message}}} +} + +// copyRequestedChunkIDs pulls the chunk_id ContainsAny values out of a query. +func copyRequestedChunkIDs(query string) []string { + match := chunkArgPattern.FindStringSubmatch(query) + if match == nil { + return nil + } + var ids []string + for _, quoted := range quotedPattern.FindAllStringSubmatch(match[1], -1) { + ids = append(ids, quoted[1]) + } + return ids +} + +func (s *copyPageServer) queryCount() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.queries +} + +func (s *copyPageServer) queryLimits() []int { + s.mu.Lock() + defer s.mu.Unlock() + return slices.Clone(s.limits) +} + +func (s *copyPageServer) requestedBatches() [][]string { + s.mu.Lock() + defer s.mu.Unlock() + batches := make([][]string, 0, len(s.requested)) + for _, batch := range s.requested { + batches = append(batches, slices.Clone(batch)) + } + return batches +} + +func (s *copyPageServer) writtenObjects() []copyWrittenObject { + s.mu.Lock() + defer s.mu.Unlock() + return slices.Clone(s.written) +} + +func (s *copyPageServer) summary() string { + s.mu.Lock() + defer s.mu.Unlock() + return fmt.Sprintf("queries=%d limits=%v batches-requested=%v objects-written=%d refused-cursor-combos=%d", + s.queries, s.limits, s.requested, len(s.written), len(s.rejected)) +} + +// check states the invariants every copy test depends on: no Get ever combined +// where with after, and every Get named the chunk IDs it wanted. +func (s *copyPageServer) check(t *testing.T) { + t.Helper() + s.mu.Lock() + defer s.mu.Unlock() + assert.Empty(t, s.rejected, "a source query combined where with after; weaviate refuses that") + assert.Empty(t, s.unexpected, "the copy called an endpoint it should not have") + for i, batch := range s.requested { + assert.NotEmpty(t, batch, "query %d did not name the chunks it wanted", i) + } +} + +// copyTestRun copies mapping from the fake source and logs what the source saw. +func copyTestRun(t *testing.T, source *copyPageServer, repo *weaviateRepository, mapping map[string]string) error { + t.Helper() + defer func() { t.Log("copy walk: " + source.summary()) }() + defer source.check(t) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return repo.CopyIndices(ctx, "kb-src", map[string]string{"know-1": "know-2"}, mapping, "kb-dst", 64, "doc") +} + +// CopyIndices has to read the source by the chunk IDs the mapping names. A +// filtered Get that carries `after` is refused by Weaviate ("where cannot be +// set with after and limit parameters"), which the cursor walk this replaces +// provoked on its very first page, and the fake server refuses it the same way. +func TestCopyIndicesQueriesByChunkIDWithoutACursor(t *testing.T) { + const chunks = 130 // 64 + 64 + 2: more than one batch, one short batch + source := copyTestSingleVectorChunks(keysOf(copyTestChunkMap(chunks))...) + repo := source.serve(t) + + require.NoError(t, copyTestRun(t, source, repo, copyTestChunkMap(chunks))) + + assert.Equal(t, 3, source.queryCount(), "130 mapped chunks are read as three batches") + assert.Equal(t, 130, len(source.writtenObjects()), "every mapped chunk must be copied") + assert.ElementsMatch(t, []int{64, 64, 2}, batchSizes(source.requestedBatches()), + "each read asks for one batch of the mapping") + + var read []string + for _, batch := range source.requestedBatches() { + assert.True(t, slices.IsSorted(batch), "a batch is read in mapping order") + read = append(read, batch...) + } + assert.ElementsMatch(t, keysOf(copyTestChunkMap(chunks)), read, + "the reads cover the mapping exactly, each chunk once") +} + +// A source that answers every request with the same page must not have that +// page replayed into the target. Reads are bounded by the mapping, so the copy +// asks for each batch once and cannot walk in circles. +func TestCopyIndicesDoesNotReplayARepeatedPage(t *testing.T) { + const pageSize = 64 + source := copyTestSingleVectorChunks(keysOf(copyTestChunkMap(pageSize))...) + source.ignoreChunkFilter = true + repo := source.serve(t) + + require.NoError(t, copyTestRun(t, source, repo, copyTestChunkMap(pageSize))) + + assert.Equal(t, 1, source.queryCount(), "the mapping is read once, not walked page by page") + assert.Equal(t, pageSize, len(source.writtenObjects()), "the page must not be written twice") +} + +// A chunk holds one vector for its content plus one per generated question, +// all sharing the chunk_id. Every one of them has to reach the target: a query +// that names one chunk ID must not be mistaken for a query that returns one +// row. +func TestCopyIndicesCopiesEveryVectorOfAChunk(t *testing.T) { + source := copyTestStore(map[string][]string{ + "chunk-0": {"chunk-0", "chunk-0-q1", "chunk-0-q2", "chunk-0-q3"}, + }) + repo := source.serve(t) + + require.NoError(t, copyTestRun(t, source, repo, map[string]string{"chunk-0": "target-chunk-0"})) + + written := source.writtenObjects() + assert.Equal(t, 4, len(written), "the chunk's content vector and all three question vectors") + assert.ElementsMatch(t, + []string{"target-chunk-0", "target-chunk-0-q1", "target-chunk-0-q2", "target-chunk-0-q3"}, + sourceIDsOf(written)) + for _, obj := range written { + assert.Equal(t, "target-chunk-0", obj.targetChunkID) + } +} + +// A batch that comes back with exactly as many rows as it asked for may have +// been cut off, so it has to be split and re-read. Here four chunk IDs produce +// five vectors: the first read is full, the two halves are not, and all five +// vectors still have to be copied. +func TestCopyIndicesSplitsABatchThatFillsTheLimit(t *testing.T) { + source := copyTestStore(map[string][]string{ + "chunk-0": {"chunk-0", "chunk-0-q1"}, + "chunk-1": {"chunk-1"}, + "chunk-2": {"chunk-2"}, + "chunk-3": {"chunk-3"}, + }) + repo := source.serve(t) + repo.copyQueryLimit = 4 + + mapping := map[string]string{ + "chunk-0": "target-chunk-0", + "chunk-1": "target-chunk-1", + "chunk-2": "target-chunk-2", + "chunk-3": "target-chunk-3", + } + require.NoError(t, copyTestRun(t, source, repo, mapping)) + + assert.Equal(t, 5, len(source.writtenObjects()), "every vector of the batch must be copied") + assert.Equal(t, 3, source.queryCount(), "a full read is followed by two half reads") + assert.ElementsMatch(t, []int{4, 2, 2}, batchSizes(source.requestedBatches())) +} + +// When one chunk on its own fills the query limit it cannot be read +// completely, and the copy has to say so rather than report success on an +// index that is missing vectors. +func TestCopyIndicesStopsOnAChunkThatFillsTheLimit(t *testing.T) { + source := copyTestStore(map[string][]string{ + "chunk-0": {"chunk-0", "chunk-0-q1", "chunk-0-q2", "chunk-0-q3", "chunk-0-q4"}, + }) + repo := source.serve(t) + repo.copyQueryLimit = 3 + + err := copyTestRun(t, source, repo, map[string]string{"chunk-0": "target-chunk-0"}) + + require.ErrorContains(t, err, "chunk-0", "the error must name the chunk that cannot be read") + require.ErrorContains(t, err, "QUERY_MAXIMUM_RESULTS", + "the error must say the chunk's vector count reaches the server's query limit") + assert.Zero(t, len(source.writtenObjects()), "an unreadable chunk must not be reported as copied") +} + +// The server's QUERY_MAXIMUM_RESULTS is not exposed over the client API, so the +// copy asks for the documented default first and, refused for it, retries at +// the limit the server names. +func TestCopyIndicesLowersTheQueryLimitWhenTheServerRefuses(t *testing.T) { + source := copyTestSingleVectorChunks("chunk-0", "chunk-1", "chunk-2") + source.queryLimit = 4 + repo := source.serve(t) + + require.NoError(t, copyTestRun(t, source, repo, copyTestChunkMap(3))) + + assert.Equal(t, []int{10000, 4}, source.queryLimits(), + "the refused default is retried at the server's own limit") + assert.Equal(t, 3, len(source.writtenObjects())) + assert.Equal(t, 2, source.queryCount(), "only the first read pays for the refusal") +} + +// A query Weaviate could not run comes back as HTTP 200 with an errors array and +// no data, so the SDK reports no Go error. Reading that as "the source has no +// more objects" turns a failed query into a successful, silently truncated copy +// - and the response type check used to panic before it could even get there. +func TestCopyIndicesReportsAQueryError(t *testing.T) { + const failure = "class Weknora_embeddings_64 does not exist" + source := copyTestSingleVectorChunks("chunk-0") + source.queryError = failure + repo := source.serve(t) + defer func() { + if r := recover(); r != nil { + t.Fatalf("CopyIndices panicked on a query that could not run: %v", r) + } + }() + + require.ErrorContains(t, copyTestRun(t, source, repo, copyTestChunkMap(1)), failure) + assert.Equal(t, 1, source.queryCount(), "the walk must stop on the failed query") + assert.Zero(t, len(source.writtenObjects()), "a failed query must not be reported as a finished copy") +} + +// A response the walk cannot read must be reported, not turned into a panic by +// an unchecked assertion on the response shape. +func TestCopyIndicesRejectsAResponseWithoutData(t *testing.T) { + brokenResponses := map[string]func(*copyPageServer){ + "no data object": func(s *copyPageServer) { s.omitData = true }, + "no collection in Get": func(s *copyPageServer) { s.omitCollection = true }, + } + for name, breakResponse := range brokenResponses { + t.Run(name, func(t *testing.T) { + source := copyTestSingleVectorChunks("chunk-0") + breakResponse(source) + repo := source.serve(t) + defer func() { + if r := recover(); r != nil { + t.Fatalf("CopyIndices panicked on a response without data: %v", r) + } + }() + + require.ErrorContains(t, copyTestRun(t, source, repo, copyTestChunkMap(1)), "invalid response") + assert.Equal(t, 1, source.queryCount(), "the walk must stop on the unreadable response") + assert.Zero(t, len(source.writtenObjects()), "nothing may be reported as copied") + }) + } +} + +func keysOf[V any](m map[string]V) []string { + return slices.Sorted(maps.Keys(m)) +} + +func batchSizes(batches [][]string) []int { + sizes := make([]int, 0, len(batches)) + for _, batch := range batches { + sizes = append(sizes, len(batch)) + } + return sizes +} + +func sourceIDsOf(objects []copyWrittenObject) []string { + ids := make([]string, 0, len(objects)) + for _, obj := range objects { + ids = append(ids, obj.sourceID) + } + return ids +} diff --git a/internal/application/repository/retriever/weaviate/repository.go b/internal/application/repository/retriever/weaviate/repository.go index de4bcafc..c1305839 100644 --- a/internal/application/repository/retriever/weaviate/repository.go +++ b/internal/application/repository/retriever/weaviate/repository.go @@ -6,7 +6,9 @@ import ( "fmt" "maps" "net/http" + "regexp" "slices" + "strconv" "strings" "github.com/Tencent/WeKnora/internal/logger" @@ -34,6 +36,17 @@ const ( fieldEmbedding = "embedding" fieldIsEnabled = "is_enabled" fieldID = "id" + + // defaultCopyQueryLimit is the row limit CopyIndices reads source vectors + // with. Weaviate caps a single query at QUERY_MAXIMUM_RESULTS, 10000 by + // default in v1.37.3 (weaviate/usecases/config.DefaultQueryMaximumResults), + // and refuses anything above it with "query maximum results exceeded". + // Without an explicit limit a GraphQL Get would instead fall back to + // QUERY_DEFAULTS_LIMIT_GRAPHQL (100) and truncate silently. The setting is not + // exposed to clients - /v1/meta reports only version, hostname and modules + // - so ask for the default and, if the server refuses, take the value it + // names in the refusal. + defaultCopyQueryLimit = 10000 ) // NewWeaviateRetrieveEngineRepository creates and initializes a new Weaviate repository. @@ -719,36 +732,32 @@ func (w *weaviateRepository) CopyIndices(ctx context.Context, } collectionName := w.getCollectionName(dimension) - batchSize := 64 - var lastID string + reader := newCopySourceReader(w, collectionName, getVectorFields()) totalCopied := 0 - fields := getVectorFields() - for { - result, err := w.client.GraphQL().Get(). - WithClassName(collectionName). - WithWhere(filters.Where(). - WithPath([]string{fieldKnowledgeBaseID}). - WithOperator(filters.Equal). - WithValueString(sourceKnowledgeBaseID)). - WithLimit(batchSize). - WithFields(fields...). - WithAfter(lastID). - Do(ctx) + // Read the rows the mapping names, in batches of source chunk IDs. The + // mapping is the set of chunks this copy has to move, so a predicate over + // it makes every read self-contained. + // + // The cursor walk this replaces could not be made correct: Weaviate refuses + // `after` together with `where` and `limit` ("where cannot be set with + // after and limit parameters"), and anywhere a cursor is accepted it is a + // position in a result order the data node never promised to keep between + // requests. Every request still succeeds, which is how such a walk reports + // an incomplete target as a finished copy. A mapping predicate has no + // cursor that can drift. + sourceChunkIDs := slices.Sorted(maps.Keys(sourceToTargetChunkIDMap)) + const chunkBatchSize = 64 + for chunkBatch := range slices.Chunk(sourceChunkIDs, chunkBatchSize) { + objects, err := reader.readBatch(ctx, sourceKnowledgeBaseID, chunkBatch) if err != nil { - log.Errorf("[Weaviate] Failed to query source points: %v", err) return err } - - objects, ok := result.Data["Get"].(map[string]interface{})[collectionName].([]interface{}) - if !ok || len(objects) == 0 { - break + if len(objects) == 0 { + continue } log.Infof("[Weaviate] Found %d source points in batch", len(objects)) - batcher := w.client.Batch().ObjectsBatcher() - currentBatchCount := 0 - targetObjects := make([]*models.Object, 0, len(objects)) for _, obj := range objects { data, ok := obj.(map[string]interface{}) @@ -760,7 +769,12 @@ func (w *weaviateRepository) CopyIndices(ctx context.Context, continue } - lastID = additional["id"].(string) + // The id is no longer a cursor, but a row whose id cannot be read + // is still a response this copy does not understand; it must not be + // counted towards a copy reported as complete. + if id, ok := additional["id"].(string); !ok || id == "" { + return fmt.Errorf("weaviate: copy indices source object has no id") + } sourceChunkID, ok := data[fieldChunkID].(string) if !ok { @@ -823,10 +837,10 @@ func (w *weaviateRepository) CopyIndices(ctx context.Context, Vector: vector, } targetObjects = append(targetObjects, newObj) - currentBatchCount++ } + if len(targetObjects) > 0 { - resp, err := batcher.WithObjects(targetObjects...).Do(ctx) + resp, err := w.client.Batch().ObjectsBatcher().WithObjects(targetObjects...).Do(ctx) if err != nil { return fmt.Errorf("batch upsert failed: %w", err) } @@ -843,6 +857,160 @@ func (w *weaviateRepository) CopyIndices(ctx context.Context, return nil } +// copySourceReader reads the source vectors a copy needs, one batch of source +// chunk IDs at a time. +// +// A chunk is not one vector: it is stored as a row for its own content plus one +// row per generated question, all sharing the same chunk_id. A batch of n chunk +// IDs therefore says nothing about how many rows come back, and the only reads +// that can be trusted as complete are the ones that returned fewer rows than +// the limit they asked for. A batch that comes back full is split and re-read; +// a single chunk that still fills the limit cannot be read completely, and the +// copy reports that instead of returning success on a partial index. +type copySourceReader struct { + repo *weaviateRepository + collectionName string + fields []graphql.Field + // limit is the row limit every query asks for. It starts at the server's + // documented default and is lowered to the value the server names if it + // refuses a query for exceeding QUERY_MAXIMUM_RESULTS. + limit int +} + +func newCopySourceReader(repo *weaviateRepository, collectionName string, fields []graphql.Field) *copySourceReader { + limit := repo.copyQueryLimit + if limit <= 0 { + limit = defaultCopyQueryLimit + } + return ©SourceReader{ + repo: repo, + collectionName: collectionName, + fields: fields, + limit: limit, + } +} + +// readBatch returns every source vector whose chunk_id is in chunkIDs. +func (r *copySourceReader) readBatch(ctx context.Context, + sourceKnowledgeBaseID string, chunkIDs []string, +) ([]interface{}, error) { + if len(chunkIDs) == 0 { + return nil, nil + } + + objects, err := r.query(ctx, sourceKnowledgeBaseID, chunkIDs) + if err != nil { + return nil, err + } + if len(objects) < r.limit { + return objects, nil + } + + // The batch filled the limit, so it may have been cut off. A batch of one + // chunk that does so cannot be split any further. + if len(chunkIDs) == 1 { + return nil, fmt.Errorf( + "weaviate: source chunk %q returned a full query page of %d vectors, "+ + "which reaches the server's query limit (QUERY_MAXIMUM_RESULTS); "+ + "the chunk cannot be read completely and the copy was stopped", + chunkIDs[0], r.limit) + } + + middle := len(chunkIDs) / 2 + front, err := r.readBatch(ctx, sourceKnowledgeBaseID, chunkIDs[:middle]) + if err != nil { + return nil, err + } + back, err := r.readBatch(ctx, sourceKnowledgeBaseID, chunkIDs[middle:]) + if err != nil { + return nil, err + } + return append(front, back...), nil +} + +// query runs one chunk_id-bounded Get. Weaviate answers a query it could not +// run with HTTP 200, an errors array and no data, so a failed query has to be +// read as a failure here - reading it as "the source has no more rows" is how +// a failed copy gets reported as a finished one. +func (r *copySourceReader) query(ctx context.Context, + sourceKnowledgeBaseID string, chunkIDs []string, +) ([]interface{}, error) { + log := logger.GetLogger(ctx) + result, err := r.repo.client.GraphQL().Get(). + WithClassName(r.collectionName). + WithWhere(filters.Where(). + WithOperator(filters.And). + WithOperands([]*filters.WhereBuilder{ + filters.Where(). + WithPath([]string{fieldKnowledgeBaseID}). + WithOperator(filters.Equal). + WithValueString(sourceKnowledgeBaseID), + filters.Where(). + WithPath([]string{fieldChunkID}). + WithOperator(filters.ContainsAny). + WithValueText(chunkIDs...), + })). + WithLimit(r.limit). + WithFields(r.fields...). + Do(ctx) + + var queryError string + switch { + case err != nil: + queryError = err.Error() + case len(result.Errors) > 0: + queryError = result.Errors[0].Message + } + if queryError != "" { + if serverLimit, ok := queryMaximumResults(queryError); ok && serverLimit < r.limit { + // QUERY_MAXIMUM_RESULTS is a server setting with no client-facing + // API, so the refusal is the only place it can be read. Retry the + // same read under the limit the server actually enforces; the + // completeness check above uses the lowered limit from here on. + log.Warnf("[Weaviate] Source query limit %d exceeds the server's "+ + "QUERY_MAXIMUM_RESULTS %d; retrying with %d", + r.limit, serverLimit, serverLimit) + r.limit = serverLimit + return r.query(ctx, sourceKnowledgeBaseID, chunkIDs) + } + log.Errorf("[Weaviate] Failed to query source points: %s", queryError) + if err != nil { + return nil, err + } + return nil, fmt.Errorf("weaviate: copy indices query failed: %s", queryError) + } + + get, ok := result.Data["Get"].(map[string]interface{}) + if !ok { + return nil, fmt.Errorf("weaviate: copy indices invalid response") + } + objects, ok := get[r.collectionName].([]interface{}) + if !ok { + return nil, fmt.Errorf("weaviate: copy indices invalid response for collection %s", r.collectionName) + } + return objects, nil +} + +// queryMaximumResultsPattern matches the refusal Weaviate returns for a query +// that asks for more rows than QUERY_MAXIMUM_RESULTS allows, e.g. "query +// maximum results exceeded: ... exceeds the configured value for +// QUERY_MAXIMUM_RESULTS '10000'" (weaviate/adapters/repos/db/search.go). +var queryMaximumResultsPattern = regexp.MustCompile(`QUERY_MAXIMUM_RESULTS '(\d+)'`) + +// queryMaximumResults returns the row cap the server names in a refusal, if +// message is one. +func queryMaximumResults(message string) (int, bool) { + match := queryMaximumResultsPattern.FindStringSubmatch(message) + if match == nil { + return 0, false + } + limit, err := strconv.Atoi(match[1]) + if err != nil || limit <= 0 { + return 0, false + } + return limit, true +} + func (w *weaviateRepository) ListCollections(ctx context.Context) ([]string, error) { schema, err := w.client.Schema().Getter().Do(ctx) if err != nil { diff --git a/internal/application/repository/retriever/weaviate/structs.go b/internal/application/repository/retriever/weaviate/structs.go index 32bf981c..35c652db 100644 --- a/internal/application/repository/retriever/weaviate/structs.go +++ b/internal/application/repository/retriever/weaviate/structs.go @@ -11,6 +11,10 @@ type weaviateRepository struct { collectionBaseName string replicationFactor int // 0 = use Weaviate server default desiredShardCount int // 0 = use Weaviate server default + // copyQueryLimit caps the rows one CopyIndices source query may return. + // 0 = defaultCopyQueryLimit. Tests lower it to drive the truncation and + // batch-splitting paths with small fixtures. + copyQueryLimit int // Cache for initialized collections (dimension -> true) initializedCollections sync.Map }