Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(retriever/es): _bulk 的 per-item 失败不再被吞,全部被拒时 BatchSave 返回错误 (#3842)

linus-liu-webf9eeb8dc8535
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 000000000..ad0414a5b
--- /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 973f9fb14..b801127e0 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 {
+// bulkErrorSummaryLimit caps how many per-item failures are described in the
+// returned error; the reported count always covers every failed item.
+const bulkErrorSummaryLimit = 5
+
+// 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)
- log.Warn("[ElasticsearchV7] Bulk operation completed with some errors")
-
- 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"])
- }
- }
+
+ 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 000000000..d23019537
--- /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 9b10671d1..bae1bbe93 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 {