From f9eeb8dc8535d678e206b00c6e24540db542b868 Mon Sep 17 00:00:00 2001 From: linus-liu-web <395141741@qq.com> Date: Wed, 7 Oct 2026 23:59:32 +0800 Subject: [PATCH] =?UTF-8?q?fix(retriever/es):=20=5Fbulk=20=E7=9A=84=20per-?= =?UTF-8?q?item=20=E5=A4=B1=E8=B4=A5=E4=B8=8D=E5=86=8D=E8=A2=AB=E5=90=9E?= =?UTF-8?q?=EF=BC=8C=E5=85=A8=E9=83=A8=E8=A2=AB=E6=8B=92=E6=97=B6=20BatchS?= =?UTF-8?q?ave=20=E8=BF=94=E5=9B=9E=E9=94=99=E8=AF=AF=20(#3842)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Elasticsearch 受理 _bulk 请求即返回 HTTP 200,单个文档的写入失败只体现在响应体的 errors 与 items[]..error。v8 把响应对象整个丢弃,只看传输层错误;v7 读了响应, 却只把结论降级成一行告警,响应体解析失败同样返回 nil。两个驱动的 BatchSave 因此在 文档被逐条拒绝时仍返回成功:调用方不标记 failed、不清理 chunks,阶段数据照写全部 条数,文档从此搜不到也不会重试。触发条件都是常规运维事件——mapping 不符、磁盘水位 只读、index 缺失、写压力下的 item 级拒绝。 修复: - v8 接收 typed bulk 响应对象,resp.Errors 为真时遍历 resp.Items 聚合失败项。 - v7 把 countBulkErrors 的结论从"仅告警"升级为返回错误;响应体解析失败同样返回 错误,不再把结果未知当成成功。 - 错误信息只带文档 _id 与有界的 error.type,最多摘要 5 条,失败条数覆盖全部失败 项;error.reason 可能含文档正文,只写 debug 日志。写法对齐 OpenSearch 驱动既有 的 inspectBulkResponse。 回归测试(v7/v8 各一份,httptest 假 ES + 真实构造函数):全部被拒返回错误、部分 失败返回错误且能看出失败条数、全部成功返回 nil;v7 另覆盖响应体损坏。断言同时确认 返回的错误不含 error.reason 中的文档内容。 反向验证:把两个驱动改回原实现后,新增用例 v7 失败 3 条、v8 失败 2 条;恢复修复后 全部通过。 Fixes #3832 Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com> --- .../retriever/elasticsearch/v7/bulk_test.go | 150 ++++++++++++++++++ .../retriever/elasticsearch/v7/repository.go | 87 ++++++---- .../retriever/elasticsearch/v8/bulk_test.go | 146 +++++++++++++++++ .../retriever/elasticsearch/v8/repository.go | 54 ++++++- 4 files changed, 402 insertions(+), 35 deletions(-) create mode 100644 internal/application/repository/retriever/elasticsearch/v7/bulk_test.go create mode 100644 internal/application/repository/retriever/elasticsearch/v8/bulk_test.go diff --git a/internal/application/repository/retriever/elasticsearch/v7/bulk_test.go b/internal/application/repository/retriever/elasticsearch/v7/bulk_test.go new file mode 100644 index 00000000..ad0414a5 --- /dev/null +++ b/internal/application/repository/retriever/elasticsearch/v7/bulk_test.go @@ -0,0 +1,150 @@ +package v7 + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + typesLocal "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/elastic/go-elasticsearch/v7" +) + +// bulkReasonSentinel stands for document content that a per-item error.reason +// can carry; the error returned to the caller must never include it. +const bulkReasonSentinel = "LEAK-SENTINEL-DOC-BODY" + +// fakeBulkServer answers every request the v7 repository makes while BatchSave +// runs, and returns body for the _bulk call. +type fakeBulkServer struct { + body string + calls int +} + +func (f *fakeBulkServer) handler() http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case strings.HasSuffix(r.URL.Path, "/_bulk"): + f.calls++ + _, _ = io.WriteString(w, f.body) + case strings.HasSuffix(r.URL.Path, "/_mapping"): + _, _ = io.WriteString(w, + `{"xwrag_default":{"mappings":{"properties":{"chunk_id":{"type":"keyword"}}}}}`) + case r.Method == http.MethodHead: + w.WriteHeader(http.StatusNotFound) + default: + _, _ = io.WriteString(w, + `{"acknowledged":true,"shards_acknowledged":true,"index":"xwrag_default"}`) + } + } +} + +// newBulkTestRepository builds the repository through its public constructor +// against a fake Elasticsearch that answers _bulk with body. +func newBulkTestRepository(t *testing.T, body string) (interfaces.RetrieveEngineRepository, *fakeBulkServer) { + t.Helper() + + fake := &fakeBulkServer{body: body} + server := httptest.NewServer(fake.handler()) + t.Cleanup(server.Close) + + client, err := elasticsearch.NewClient( + elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true}, + ) + require.NoError(t, err) + + return NewElasticsearchEngineRepository(client, nil, nil), fake +} + +func bulkTestIndexInfos() []*typesLocal.IndexInfo { + return []*typesLocal.IndexInfo{ + { + Content: "alpha", SourceID: "src-1", SourceType: typesLocal.ChunkSourceType, + ChunkID: "chunk-1", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true, + }, + { + Content: "beta", SourceID: "src-2", SourceType: typesLocal.ChunkSourceType, + ChunkID: "chunk-2", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true, + }, + } +} + +func bulkTestParams() map[string]any { + return map[string]any{ + "embedding": map[string][]float32{"src-1": {0.1, 0.2}, "src-2": {0.3, 0.4}}, + } +} + +// TestBatchSaveReportsPerItemBulkErrors is a regression test for #3832: +// Elasticsearch answers an accepted _bulk request with HTTP 200, so a document +// rejected for a mapping mismatch, a read-only index or an item-level +// rejection is visible only in the response body. BatchSave must surface those +// per-item failures instead of logging a warning and reporting success. +func TestBatchSaveReportsPerItemBulkErrors(t *testing.T) { + cases := []struct { + name string + body string + wantContains []string + }{ + { + name: "all documents rejected", + body: `{"took":1,"errors":true,"items":[` + + `{"index":{"_id":"chunk-1","status":400,` + + `"error":{"type":"mapper_parsing_exception","reason":"` + bulkReasonSentinel + `"}}},` + + `{"index":{"_id":"chunk-2","status":429,` + + `"error":{"type":"es_rejected_execution_exception","reason":"` + bulkReasonSentinel + `"}}}]}`, + wantContains: []string{ + "2/2 documents failed", + "chunk-1", "mapper_parsing_exception", + "chunk-2", "es_rejected_execution_exception", + }, + }, + { + name: "partial failure", + body: `{"took":1,"errors":true,"items":[` + + `{"index":{"_id":"chunk-1","status":201,"result":"created"}},` + + `{"index":{"_id":"chunk-2","status":400,` + + `"error":{"type":"cluster_block_exception","reason":"` + bulkReasonSentinel + `"}}}]}`, + wantContains: []string{"1/2 documents failed", "chunk-2", "cluster_block_exception"}, + }, + { + name: "malformed response body", + body: `{"took":1`, + wantContains: []string{"failed to parse bulk response"}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo, fake := newBulkTestRepository(t, tc.body) + + err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams()) + + require.Positive(t, fake.calls, "the _bulk endpoint was never called") + require.Error(t, err) + for _, want := range tc.wantContains { + assert.Contains(t, err.Error(), want) + } + assert.NotContains(t, err.Error(), bulkReasonSentinel, + "the returned error must not carry error.reason") + }) + } + + t.Run("all documents accepted", func(t *testing.T) { + repo, fake := newBulkTestRepository(t, `{"took":1,"errors":false,"items":[`+ + `{"index":{"_id":"chunk-1","status":201,"result":"created"}},`+ + `{"index":{"_id":"chunk-2","status":201,"result":"created"}}]}`) + + err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams()) + + require.Positive(t, fake.calls, "the _bulk endpoint was never called") + require.NoError(t, err) + }) +} diff --git a/internal/application/repository/retriever/elasticsearch/v7/repository.go b/internal/application/repository/retriever/elasticsearch/v7/repository.go index 973f9fb1..b801127e 100644 --- a/internal/application/repository/retriever/elasticsearch/v7/repository.go +++ b/internal/application/repository/retriever/elasticsearch/v7/repository.go @@ -322,8 +322,7 @@ func (e *elasticsearchRepository) BatchSave(ctx context.Context, defer resp.Body.Close() // Process bulk response - err = e.processBulkResponse(ctx, resp, len(embeddingList)) - if err != nil { + if err := e.processBulkResponse(ctx, resp); err != nil { return err } @@ -368,9 +367,21 @@ func (e *elasticsearchRepository) prepareBulkRequestBody(ctx context.Context, return body, processedCount, nil } -// processBulkResponse processes the response from a bulk indexing operation +// bulkResponseItem is one entry of an Elasticsearch _bulk response. Only the +// fields needed to report a failure are decoded. +type bulkResponseItem struct { + ID string `json:"_id"` + Error *struct { + Type string `json:"type"` + Reason string `json:"reason"` + } `json:"error"` +} + +// processBulkResponse turns a bulk response into an error when Elasticsearch +// rejected individual documents. A bulk request that the server accepted +// always answers HTTP 200, so the per-item errors are the only failure signal. func (e *elasticsearchRepository) processBulkResponse(ctx context.Context, - resp *esapi.Response, totalDocuments int, + resp *esapi.Response, ) error { log := logger.GetLogger(ctx) @@ -380,46 +391,56 @@ func (e *elasticsearchRepository) processBulkResponse(ctx context.Context, return fmt.Errorf("failed to index documents: %s", resp.String()) } - // Parse bulk response to check for individual document errors - var bulkResponse map[string]interface{} + // Parse bulk response to check for individual document errors. A body that + // cannot be decoded leaves the outcome unknown, so it is an error too. + var bulkResponse struct { + Errors bool `json:"errors"` + Items []map[string]bulkResponseItem `json:"items"` + } if err := json.NewDecoder(resp.Body).Decode(&bulkResponse); err != nil { - log.Warnf("[ElasticsearchV7] Could not parse bulk response: %v", err) - return nil + log.Errorf("[ElasticsearchV7] Could not parse bulk response: %v", err) + return fmt.Errorf("failed to parse bulk response: %w", err) } // Check for errors in individual operations - if hasErrors, ok := bulkResponse["errors"].(bool); ok && hasErrors { - errorCount := e.countBulkErrors(ctx, bulkResponse, totalDocuments) - if errorCount > 0 { - log.Warnf("[ElasticsearchV7] %d/%d documents failed to index", errorCount, totalDocuments) - } + if !bulkResponse.Errors { + return nil } - - return nil + return e.bulkItemsError(ctx, bulkResponse.Items) } -// countBulkErrors counts the number of errors in a bulk response -func (e *elasticsearchRepository) countBulkErrors(ctx context.Context, - bulkResponse map[string]interface{}, totalDocuments int, -) int { - log := logger.GetLogger(ctx) - log.Warn("[ElasticsearchV7] Bulk operation completed with some errors") +// bulkErrorSummaryLimit caps how many per-item failures are described in the +// returned error; the reported count always covers every failed item. +const bulkErrorSummaryLimit = 5 - errorCount := 0 - if items, ok := bulkResponse["items"].([]interface{}); ok { - for _, item := range items { - if itemMap, ok := item.(map[string]interface{}); ok { - if indexResp, ok := itemMap["index"].(map[string]interface{}); ok { - if indexResp["error"] != nil { - errorCount++ - log.Errorf("[ElasticsearchV7] Item error: %v", indexResp["error"]) - } - } +// bulkItemsError aggregates per-item bulk failures into a single error. Each +// described item carries its document _id and the bounded error.type; +// error.reason is deliberately excluded because it can embed document content. +func (e *elasticsearchRepository) bulkItemsError(ctx context.Context, + items []map[string]bulkResponseItem, +) error { + log := logger.GetLogger(ctx) + + msgs := make([]string, 0, bulkErrorSummaryLimit) + failed := 0 + for _, item := range items { + for op, detail := range item { + if detail.Error == nil { + continue + } + failed++ + log.Debugf("[ElasticsearchV7] Bulk item failed: op=%s id=%s type=%s", + op, detail.ID, detail.Error.Type) + if len(msgs) < bulkErrorSummaryLimit { + msgs = append(msgs, fmt.Sprintf("[%s %s] %s", op, detail.ID, detail.Error.Type)) } } } - - return errorCount + if failed == 0 { + return fmt.Errorf("elasticsearch v7: bulk reported errors without per-item failure detail") + } + return fmt.Errorf("elasticsearch v7: bulk partial failure (%d/%d documents failed, first %d: %s)", + failed, len(items), len(msgs), strings.Join(msgs, "; ")) } // DeleteByChunkIDList Delete indices by chunk ID list diff --git a/internal/application/repository/retriever/elasticsearch/v8/bulk_test.go b/internal/application/repository/retriever/elasticsearch/v8/bulk_test.go new file mode 100644 index 00000000..d2301953 --- /dev/null +++ b/internal/application/repository/retriever/elasticsearch/v8/bulk_test.go @@ -0,0 +1,146 @@ +package v8 + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + typesLocal "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/elastic/go-elasticsearch/v8" +) + +// bulkReasonSentinel stands for document content that a per-item error.reason +// can carry; the error returned to the caller must never include it. +const bulkReasonSentinel = "LEAK-SENTINEL-DOC-BODY" + +// fakeBulkServer answers every request the v8 repository makes while BatchSave +// runs, and returns body for the _bulk call. +type fakeBulkServer struct { + body string + calls int +} + +func (f *fakeBulkServer) handler() http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("X-Elastic-Product", "Elasticsearch") + switch { + case strings.HasSuffix(r.URL.Path, "/_bulk"): + f.calls++ + _, _ = io.WriteString(w, f.body) + case strings.HasSuffix(r.URL.Path, "/_mapping"): + _, _ = io.WriteString(w, + `{"xwrag_default":{"mappings":{"properties":{"chunk_id":{"type":"keyword"}}}}}`) + case r.Method == http.MethodHead: + w.WriteHeader(http.StatusNotFound) + default: + _, _ = io.WriteString(w, + `{"acknowledged":true,"shards_acknowledged":true,"index":"xwrag_default"}`) + } + } +} + +// newBulkTestRepository builds the repository through its public constructor +// against a fake Elasticsearch that answers _bulk with body. +func newBulkTestRepository(t *testing.T, body string) (interfaces.RetrieveEngineRepository, *fakeBulkServer) { + t.Helper() + + fake := &fakeBulkServer{body: body} + server := httptest.NewServer(fake.handler()) + t.Cleanup(server.Close) + + client, err := elasticsearch.NewTypedClient( + elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true}, + ) + require.NoError(t, err) + + return NewElasticsearchEngineRepository(client, nil, nil), fake +} + +func bulkTestIndexInfos() []*typesLocal.IndexInfo { + return []*typesLocal.IndexInfo{ + { + Content: "alpha", SourceID: "src-1", SourceType: typesLocal.ChunkSourceType, + ChunkID: "chunk-1", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true, + }, + { + Content: "beta", SourceID: "src-2", SourceType: typesLocal.ChunkSourceType, + ChunkID: "chunk-2", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true, + }, + } +} + +func bulkTestParams() map[string]any { + return map[string]any{ + "embedding": map[string][]float32{"src-1": {0.1, 0.2}, "src-2": {0.3, 0.4}}, + } +} + +// TestBatchSaveReportsPerItemBulkErrors is a regression test for #3832: +// Elasticsearch answers an accepted _bulk request with HTTP 200, so a document +// rejected for a mapping mismatch, a read-only index or an item-level +// rejection is visible only in the response body. BatchSave must surface those +// per-item failures to the caller. +func TestBatchSaveReportsPerItemBulkErrors(t *testing.T) { + cases := []struct { + name string + body string + wantContains []string + }{ + { + name: "all documents rejected", + body: `{"took":1,"errors":true,"items":[` + + `{"create":{"_id":"chunk-1","status":400,` + + `"error":{"type":"mapper_parsing_exception","reason":"` + bulkReasonSentinel + `"}}},` + + `{"create":{"_id":"chunk-2","status":429,` + + `"error":{"type":"es_rejected_execution_exception","reason":"` + bulkReasonSentinel + `"}}}]}`, + wantContains: []string{ + "2/2 documents failed", + "chunk-1", "mapper_parsing_exception", + "chunk-2", "es_rejected_execution_exception", + }, + }, + { + name: "partial failure", + body: `{"took":1,"errors":true,"items":[` + + `{"create":{"_id":"chunk-1","status":201,"result":"created"}},` + + `{"create":{"_id":"chunk-2","status":400,` + + `"error":{"type":"cluster_block_exception","reason":"` + bulkReasonSentinel + `"}}}]}`, + wantContains: []string{"1/2 documents failed", "chunk-2", "cluster_block_exception"}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo, fake := newBulkTestRepository(t, tc.body) + + err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams()) + + require.Positive(t, fake.calls, "the _bulk endpoint was never called") + require.Error(t, err) + for _, want := range tc.wantContains { + assert.Contains(t, err.Error(), want) + } + assert.NotContains(t, err.Error(), bulkReasonSentinel, + "the returned error must not carry error.reason") + }) + } + + t.Run("all documents accepted", func(t *testing.T) { + repo, fake := newBulkTestRepository(t, `{"took":1,"errors":false,"items":[`+ + `{"create":{"_id":"chunk-1","status":201,"result":"created"}},`+ + `{"create":{"_id":"chunk-2","status":201,"result":"created"}}]}`) + + err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams()) + + require.Positive(t, fake.calls, "the _bulk endpoint was never called") + require.NoError(t, err) + }) +} diff --git a/internal/application/repository/retriever/elasticsearch/v8/repository.go b/internal/application/repository/retriever/elasticsearch/v8/repository.go index 9b10671d..bae1bbe9 100644 --- a/internal/application/repository/retriever/elasticsearch/v8/repository.go +++ b/internal/application/repository/retriever/elasticsearch/v8/repository.go @@ -12,6 +12,7 @@ import ( typesLocal "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/elastic/go-elasticsearch/v8" + "github.com/elastic/go-elasticsearch/v8/typedapi/core/bulk" "github.com/elastic/go-elasticsearch/v8/typedapi/core/search" "github.com/elastic/go-elasticsearch/v8/typedapi/types" "github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/scriptlanguage" @@ -205,17 +206,66 @@ func (e *elasticsearchRepository) BatchSave(ctx context.Context, log.Debugf("[Elasticsearch] Added chunk ID %s to bulk request", embedding.ChunkID) } - // Execute the bulk request - _, err := indexRequest.Do(ctx) + // Execute the bulk request. Elasticsearch answers an accepted _bulk call + // with HTTP 200 even when it rejects individual documents, so the + // per-item errors in the response body are the only failure signal. + resp, err := indexRequest.Do(ctx) if err != nil { log.Errorf("[Elasticsearch] Failed to execute bulk operation: %v", err) return fmt.Errorf("failed to do bulk: %w", err) } + if err := inspectBulkResponse(ctx, resp); err != nil { + return err + } log.Infof("[Elasticsearch] Successfully batch saved %d indices", len(embeddingList)) return nil } +// bulkErrorSummaryLimit caps how many per-item failures are described in the +// returned error; the reported count always covers every failed item. +const bulkErrorSummaryLimit = 5 + +// inspectBulkResponse converts per-item _bulk failures into an error. A bulk +// request that the server accepted answers HTTP 200, so a document rejected +// for a mapping mismatch, a read-only index or an item-level rejection is +// visible only in the response body. +// +// The error names the document _id and the bounded error.type of up to +// bulkErrorSummaryLimit failed items. error.reason is deliberately excluded +// because it can embed document content. +func inspectBulkResponse(ctx context.Context, resp *bulk.Response) error { + if resp == nil || !resp.Errors { + return nil + } + + log := logger.GetLogger(ctx) + msgs := make([]string, 0, bulkErrorSummaryLimit) + failed := 0 + for _, item := range resp.Items { + for op, detail := range item { + if detail.Error == nil { + continue + } + failed++ + id := "" + if detail.Id_ != nil { + id = *detail.Id_ + } + log.Debugf("[Elasticsearch] Bulk item failed: op=%s id=%s type=%s", + op, id, detail.Error.Type) + if len(msgs) < bulkErrorSummaryLimit { + msgs = append(msgs, fmt.Sprintf("[%s %s] %s", op, id, detail.Error.Type)) + } + } + } + if failed == 0 { + return fmt.Errorf("elasticsearch: bulk reported errors without per-item failure detail") + } + return fmt.Errorf("elasticsearch: bulk partial failure (%d/%d documents failed, first %d: %s)", + failed, len(resp.Items), len(msgs), strings.Join(msgs, "; ")) +} + // DeleteByChunkIDList removes documents from the index based on chunk IDs // Returns an error if the delete operation fails func (e *elasticsearchRepository) DeleteByChunkIDList(ctx context.Context, chunkIDList []string, dimension int, knowledgeType string) error {