RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(es): preserve dataset and document scope in single chunk updates (#21842)
ZZZZY5781bcaea752
diff --git a/internal/engine/elasticsearch/chunk.go b/internal/engine/elasticsearch/chunk.goindex e12965f467..d6257f0b17 100644--- a/internal/engine/elasticsearch/chunk.go+++ b/internal/engine/elasticsearch/chunk.go@@ -366,7 +366,7 @@ func (e *Engine) UpdateChunks(ctx context.Context, condition map[string]interfac// Case 1: Single document update (when condition["id"] is a string)if chunkID, ok := condition["id"].(string); ok {- return e.updateSingleChunk(ctx, fullIndexName, chunkID, newValue)+ return e.updateSingleChunk(ctx, fullIndexName, chunkID, condition, newValue)}// Case 2: Multi-document update via UpdateByQuery@@ -520,13 +520,30 @@ func mapMemoryMessageESConditionFields(condition map[string]interface{}) map[str}// updateSingleChunk handles single document update-func (e *Engine) updateSingleChunk(ctx context.Context, indexName, chunkID string, newValue map[string]interface{}) error {+func (e *Engine) updateSingleChunk(ctx context.Context, indexName, chunkID string, condition, newValue map[string]interface{}) error {common.Debug("ElasticsearchConnection.updateSingleChunk called", zap.String("indexName", indexName), zap.String("chunkID", chunkID))- // First find the document by id field to get the actual _id+ // Resolve the actual _id only within all of the caller's update conditions.+ filters := make([]map[string]interface{}, 0, len(condition))+ for field, value := range condition {+ switch field {+ case "and", "or", "must_not", "exists":+ return fmt.Errorf("unsupported single chunk update condition %q", field)+ }+ if items, ok := conditionTermsList(value); ok {+ filters = append(filters, map[string]interface{}{"terms": map[string]interface{}{field: items}})+ continue+ }+ switch value.(type) {+ case string, bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64:+ filters = append(filters, map[string]interface{}{"term": map[string]interface{}{field: value}})+ default:+ return fmt.Errorf("unsupported single chunk update condition %q: %T", field, value)+ }+ }searchReq := map[string]interface{}{"query": map[string]interface{}{- "term": map[string]interface{}{"id": chunkID},+ "bool": map[string]interface{}{"filter": filters},},}diff --git a/internal/engine/elasticsearch/chunk_update_scope_integration_test.go b/internal/engine/elasticsearch/chunk_update_scope_integration_test.gonew file mode 100644index 0000000000..9a168e2494--- /dev/null+++ b/internal/engine/elasticsearch/chunk_update_scope_integration_test.go@@ -0,0 +1,145 @@+//go:build integration++package elasticsearch++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "strings"+ "testing"+ "time"++ "github.com/elastic/go-elasticsearch/v8"+ "github.com/elastic/go-elasticsearch/v8/esapi"++ "ragflow/internal/common"+ "ragflow/internal/engine/types"+)++// TestUpdateSingleChunkScopeRealES verifies dataset and document isolation+// against a real Elasticsearch service, with a matching-scope positive control.+func TestUpdateSingleChunkScopeRealES(t *testing.T) {+ if common.GetEnv(common.EnvESTest) != "1" {+ t.Skip("requires ES_TEST=1 and a real Elasticsearch service")+ }+ cfg := getESTestConfig()+ client, err := elasticsearch.NewClient(elasticsearch.Config{+ Addresses: []string{cfg.Hosts}, Username: cfg.Username, Password: cfg.Password,+ })+ if err != nil {+ t.Fatal(err)+ }+ // Avoid NewEngine: its bootstrap writes shared index templates. This+ // experiment only needs the real client and one disposable tenant index.+ engine := &Engine{client: client}+ ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second)+ defer cancel()+ index := fmt.Sprintf("ragflow_scope_repro_%d", time.Now().UnixNano())+ checkResponse := func(res *esapi.Response, err error) {+ t.Helper()+ if err != nil {+ t.Fatal(err)+ }+ defer res.Body.Close()+ if res.IsError() {+ t.Fatalf("ES request failed: %s", res.String())+ }+ }+ checkResponse(client.Indices.Create(index, client.Indices.Create.WithContext(ctx),+ client.Indices.Create.WithBody(strings.NewReader(`{"settings":{"number_of_shards":1,"number_of_replicas":0},"mappings":{"properties":{"id":{"type":"keyword"},"kb_id":{"type":"keyword"},"doc_id":{"type":"keyword"},"available_int":{"type":"integer"}}}}`))))+ t.Logf("temporary tenant index: %s", index)+ t.Cleanup(func() {+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cleanupCancel()+ res, err := client.Indices.Delete([]string{index}, client.Indices.Delete.WithContext(cleanupCtx))+ if err != nil {+ t.Errorf("cleanup %s: %v", index, err)+ return+ }+ defer res.Body.Close()+ if res.IsError() {+ t.Errorf("cleanup %s: %s", index, res.String())+ return+ }+ t.Logf("deleted temporary index: %s", index)+ })+ chunkID := common.ChunkID("doc-b", "scope reproduction")+ for _, tt := range []struct {+ name, datasetID, documentID string+ wantAvailable float64+ }{+ {"matching_scope", "kb-b", "doc-b", 0},+ {"wrong_dataset", "kb-a", "doc-b", 1},+ {"wrong_document", "kb-b", "doc-a", 1},+ } {+ t.Run(tt.name, func(t *testing.T) {+ chunk := map[string]interface{}{+ "id": chunkID, "doc_id": "doc-b", "available_int": 1,+ "content_with_weight": "original body", "obsolete_kwd": "keep until matched",+ "tag_feas": map[string]int{"old_tag": 2},+ }+ if _, err := engine.InsertChunks(ctx, []map[string]interface{}{chunk}, index, "kb-b", ""); err != nil {+ t.Fatal(err)+ }+ if tt.datasetID == "kb-a" {+ got, err := engine.GetChunk(ctx, index, chunkID, []string{"kb-a"})+ if err != nil || got != nil {+ t.Fatalf("scoped read in A = (%v, %v), want (nil, nil)", got, err)+ }+ t.Log("scoped read in A: not found; fixture belongs to B")+ }+ updateErr := engine.UpdateChunks(ctx,+ map[string]interface{}{"id": chunkID, "doc_id": tt.documentID},+ map[string]interface{}{+ "id": chunkID, "available_int": 0, "content_with_weight": "chunk's body\nsecond line",+ "tag_feas": map[string]int{"new_tag": 3}, "remove": "obsolete_kwd",+ }, index, tt.datasetID)+ res, err := client.Get(index, chunkID, client.Get.WithContext(ctx))+ if err != nil {+ t.Fatal(err)+ }+ defer res.Body.Close()+ if res.IsError() {+ t.Fatalf("read fixture by _id: %s", res.String())+ }+ var stored struct {+ Source map[string]interface{} `json:"_source"`+ }+ if err := json.NewDecoder(res.Body).Decode(&stored); err != nil {+ t.Fatal(err)+ }+ t.Logf("requested kb_id=%s doc_id=%s; update error=%v; before available_int=1; after=%v",+ tt.datasetID, tt.documentID, updateErr, stored.Source)+ if stored.Source["kb_id"] != "kb-b" || stored.Source["doc_id"] != "doc-b" {+ t.Fatalf("fixture identity changed: %v", stored.Source)+ }+ if stored.Source["available_int"] != tt.wantAvailable {+ t.Errorf("scope violation: available_int=%v, want %v", stored.Source["available_int"], tt.wantAvailable)+ }+ if tt.name == "matching_scope" && updateErr != nil {+ t.Fatalf("positive control update failed: %v", updateErr)+ }+ if tt.name != "matching_scope" && !errors.Is(updateErr, types.ErrDocumentNotFound) {+ t.Fatalf("mismatched scope error = %v, want ErrDocumentNotFound", updateErr)+ }+ wantContent, wantTag, wantScore := "original body", "old_tag", float64(2)+ if tt.name == "matching_scope" {+ wantContent, wantTag, wantScore = "chunk's body\nsecond line", "new_tag", 3+ if _, exists := stored.Source["obsolete_kwd"]; exists {+ t.Error("matched update did not remove obsolete_kwd")+ }+ } else if stored.Source["obsolete_kwd"] != "keep until matched" {+ t.Error("mismatched update removed obsolete_kwd")+ }+ if stored.Source["content_with_weight"] != wantContent || stored.Source["id"] != chunkID {+ t.Errorf("content or chunk id changed unexpectedly: %v", stored.Source)+ }+ tags, ok := stored.Source["tag_feas"].(map[string]interface{})+ if !ok || len(tags) != 1 || tags[wantTag] != wantScore {+ t.Errorf("tag_feas = %v, want only %s=%v", stored.Source["tag_feas"], wantTag, wantScore)+ }+ })+ }+}diff --git a/internal/engine/elasticsearch/chunk_update_scope_test.go b/internal/engine/elasticsearch/chunk_update_scope_test.gonew file mode 100644index 0000000000..49c185c6a6--- /dev/null+++ b/internal/engine/elasticsearch/chunk_update_scope_test.go@@ -0,0 +1,149 @@+package elasticsearch++import (+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "ragflow/internal/engine/types"++ "github.com/elastic/go-elasticsearch/v8"+)++// TestUpdateSingleChunkPreservesScope checks the actual outgoing ES query,+// without substituting the engine or relying on a real ES service. Empty hits+// deliberately stop execution before any write; this test proves lost query+// constraints, not a mutation of a real Elasticsearch document.+func TestUpdateSingleChunkPreservesScope(t *testing.T) {+ for _, tt := range []struct {+ name string+ condition map[string]interface{}+ wantTerms map[string]string+ }{+ {+ name: "dataset",+ condition: map[string]interface{}{"id": "chunk-b"},+ wantTerms: map[string]string{"id": "chunk-b", "kb_id": "kb-a"},+ },+ {+ name: "dataset_and_document",+ condition: map[string]interface{}{"id": "chunk-b", "doc_id": "doc-a"},+ wantTerms: map[string]string{"id": "chunk-b", "kb_id": "kb-a", "doc_id": "doc-a"},+ },+ {+ name: "additional_condition",+ condition: map[string]interface{}{"id": "chunk-b", "type_kwd": "wiki_page"},+ wantTerms: map[string]string{"id": "chunk-b", "kb_id": "kb-a", "type_kwd": "wiki_page"},+ },+ } {+ t.Run(tt.name, func(t *testing.T) {+ var queries []map[string]interface{}+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("X-Elastic-Product", "Elasticsearch")+ w.Header().Set("Content-Type", "application/json")+ switch {+ case r.Method == http.MethodHead && r.URL.Path == "/ragflow_scope_test":+ w.WriteHeader(http.StatusOK)+ case r.URL.Path == "/ragflow_scope_test/_search":+ var payload map[string]interface{}+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {+ t.Errorf("decode ES search request: %v", err)+ http.Error(w, "invalid request", http.StatusBadRequest)+ return+ }+ queries = append(queries, payload)+ _, _ = w.Write([]byte(`{"hits":{"total":{"value":0,"relation":"eq"},"hits":[]}}`))+ default:+ t.Errorf("unexpected ES request: %s %s", r.Method, r.URL.Path)+ http.Error(w, "unexpected request", http.StatusNotFound)+ }+ }))+ defer server.Close()++ client, err := elasticsearch.NewClient(elasticsearch.Config{Addresses: []string{server.URL}})+ if err != nil {+ t.Fatal(err)+ }+ engine := &Engine{client: client}+ ctx := t.Context()+ got, err := engine.GetChunk(ctx, "ragflow_scope_test", "chunk-b", []string{"kb-a"})+ if err != nil || got != nil {+ t.Fatalf("GetChunk = (%v, %v), want (nil, nil) for empty hits", got, err)+ }+ err = engine.UpdateChunks(ctx, tt.condition,+ map[string]interface{}{"available_int": 0, "remove": "tag_feas"}, "ragflow_scope_test", "kb-a")+ if !errors.Is(err, types.ErrDocumentNotFound) {+ t.Fatalf("UpdateChunks = %v, want ErrDocumentNotFound for empty hits", err)+ }+ if len(queries) != 2 {+ t.Fatalf("search requests = %d, want read and update lookup", len(queries))+ }+ readJSON, _ := json.Marshal(queries[0])+ updateJSON, _ := json.Marshal(queries[1])+ t.Logf("read lookup: %s", readJSON)+ t.Logf("update lookup: %s", updateJSON)+ for field, want := range tt.wantTerms {+ if !scopeQueryHasTerm(queries[1]["query"], field, want) {+ t.Errorf("update lookup lost required term %s=%q: %s", field, want, updateJSON)+ }+ }+ if !scopeQueryHasTerm(queries[0]["query"], "kb_id", "kb-a") {+ t.Errorf("read lookup lost dataset scope: %s", readJSON)+ }+ })+ }+}++func TestUpdateSingleChunkRejectsUnsupportedCondition(t *testing.T) {+ for _, tt := range []struct {+ name, field string+ value interface{}+ }{+ {"nil", "doc_id", nil},+ {"object", "doc_id", map[string]interface{}{"value": "doc-a"}},+ {"and", "and", []interface{}{}},+ {"or", "or", []interface{}{}},+ {"must_not", "must_not", map[string]interface{}{"doc_id": "doc-a"}},+ {"exists", "exists", "doc_id"},+ } {+ t.Run(tt.name, func(t *testing.T) {+ // A nil client also ensures rejection happens before any ES request.+ engine := &Engine{}+ err := engine.updateSingleChunk(t.Context(), "ragflow_scope_test", "chunk-b",+ map[string]interface{}{"id": "chunk-b", "kb_id": "kb-a", tt.field: tt.value},+ map[string]interface{}{"available_int": 0})+ if err == nil || !strings.Contains(err.Error(), "unsupported single chunk update condition") {+ t.Fatalf("error = %v, want unsupported condition rejection", err)+ }+ })+ }+}++// Only descend through conjunctions: a term in an optional should or a must_not+// clause would not enforce the requested scope.+func scopeQueryHasTerm(value interface{}, field, want string) bool {+ query, ok := value.(map[string]interface{})+ if !ok {+ return false+ }+ if term, ok := query["term"].(map[string]interface{}); ok && term[field] == want {+ return true+ }+ if conjunction, ok := query["bool"].(map[string]interface{}); ok {+ for _, key := range []string{"must", "filter"} {+ if scopeQueryHasTerm(conjunction[key], field, want) {+ return true+ }+ clauses, _ := conjunction[key].([]interface{})+ for _, clause := range clauses {+ if scopeQueryHasTerm(clause, field, want) {+ return true+ }+ }+ }+ }+ return false+}