Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(retrieval): drop the filter-only fallback (#21240)

qinling0210b99300a41d5e
diff --git a/internal/agent/tool/dataset_navigation.go b/internal/agent/tool/dataset_navigation.go
index c588534748..824ee5121d 100644
--- a/internal/agent/tool/dataset_navigation.go
+++ b/internal/agent/tool/dataset_navigation.go
@@ -237,6 +237,8 @@ func (d *DatasetNavigationByTree) InvokableRun(ctx context.Context, argumentsInJ
TenantID: tenantID,
DocScope: docScope,
RetrievalFrom: "dataset",
+ // Agentic, so no dense-only rescue.
+ AllowDenseFallback: new(false),
})
if err != nil {
common.Warn("dataset navigation: content-recall retrieval failed", zap.Error(err))
diff --git a/internal/agent/tool/dataset_navigation_test.go b/internal/agent/tool/dataset_navigation_test.go
index b8ad8c9970..c8760a7223 100644
--- a/internal/agent/tool/dataset_navigation_test.go
+++ b/internal/agent/tool/dataset_navigation_test.go
@@ -207,6 +207,33 @@ func TestDatasetNavigation_DocScopeFiltersClusterFallback(t *testing.T) {
}
}
+// TestDatasetNavigation_RecallFallbackDisablesDenseFallback pins the agentic
+// half of the split on the content-recall tier: when the nav tree routes
+// nothing the tool recalls by chunk content, and the model reads those chunks
+// as evidence, so no dense-only rescue there either.
+func TestDatasetNavigation_RecallFallbackDisablesDenseFallback(t *testing.T) {
+ fake := &navRoutingFake{}
+ prevNav := nav.GetNavService()
+ nav.SetNavService(fake)
+ defer func() { nav.SetNavService(prevNav) }()
+
+ prevSvc := GetRetrievalService()
+ svc := &capturingRetrievalService{}
+ SetRetrievalService(svc)
+ defer func() { SetRetrievalService(prevSvc) }()
+
+ tool := NewDatasetNavigationByTree()
+ if _, err := tool.InvokableRun(navTestContext(t), `{"topic":"X","dataset_ids":["kb1"]}`); err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if svc.req.Query == "" {
+ t.Fatal("content-recall tier was not exercised: the tool never reached the retrieval service")
+ }
+ if svc.req.AllowDenseFallback == nil || *svc.req.AllowDenseFallback {
+ t.Fatal("dataset navigation is agentic and must disable the dense fallback")
+ }
+}
+
// TestDatasetNavigation_BlankRequestScopeFallsBackToDefaults pins that a blank
// request value cannot DISABLE the configured default scope: [" "] has a
// non-zero length, so it suppressed the default and then compacted to an empty
diff --git a/internal/agent/tool/retrieval.go b/internal/agent/tool/retrieval.go
index a66830d39e..9b5a481ac1 100644
--- a/internal/agent/tool/retrieval.go
+++ b/internal/agent/tool/retrieval.go
@@ -194,6 +194,9 @@ func (r *RetrievalTool) InvokableRun(ctx context.Context, argumentsInJSON string
// ErrRetrievalServiceMissing; once a real impl is installed
// via SetRetrievalService (or SetSimpleRetrievalService for
// dev), the chunks flow through normally.
+ //
+ // Agentic: no dense-only rescue — a row the query's own words never
+ // matched is not evidence the model asked for.
searchReq := RetrievalRequest{
Query: args.Query,
DatasetIDs: args.DatasetIDs,
@@ -204,6 +207,7 @@ func (r *RetrievalTool) InvokableRun(ctx context.Context, argumentsInJSON string
KeywordsSimilarityWeight: args.KeywordsSimilarityWeight,
UseKG: args.UseKG,
SimilarityThreshold: args.SimilarityThreshold,
+ AllowDenseFallback: new(false),
RerankID: args.RerankID,
CrossLanguages: append([]string(nil), args.CrossLanguages...),
TOCEnhance: args.TOCEnhance,
diff --git a/internal/agent/tool/retrieval_test.go b/internal/agent/tool/retrieval_test.go
index 6bc16d0a2b..e86c024b64 100644
--- a/internal/agent/tool/retrieval_test.go
+++ b/internal/agent/tool/retrieval_test.go
@@ -143,6 +143,28 @@ func TestAgenticSearchDisablesDenseFallback(t *testing.T) {
}
}
+// TestRetrievalToolDisablesDenseFallback pins the agentic/human split for the
+// retrieval tool itself. An agent reads these chunks as evidence, so there is
+// no dense-only rescue: it would hand the model rows the query's own words
+// never matched. Only human-facing retrieval keeps that rescue on.
+func TestRetrievalToolDisablesDenseFallback(t *testing.T) {
+ prev := GetRetrievalService()
+ svc := &capturingRetrievalService{}
+ SetRetrievalService(svc)
+ t.Cleanup(func() { SetRetrievalService(prev) })
+
+ state := runtime.NewCanvasState("run-1", "task-1")
+ state.Sys["tenant_id"] = "tenant-1"
+ ctx := runtime.WithState(t.Context(), state)
+
+ if _, err := NewRetrievalTool().InvokableRun(ctx, `{"query":"hello","dataset_ids":["kb-1"]}`); err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if svc.req.AllowDenseFallback == nil || *svc.req.AllowDenseFallback {
+ t.Fatal("the agent retrieval tool must disable the dense fallback")
+ }
+}
+
func TestAgenticSearchExcludesCompiledResults(t *testing.T) {
previous := GetRetrievalService()
service := &capturingRetrievalService{}
diff --git a/internal/agentic_rag/locate_search.go b/internal/agentic_rag/locate_search.go
index bc039df3db..91cf235421 100644
--- a/internal/agentic_rag/locate_search.go
+++ b/internal/agentic_rag/locate_search.go
@@ -148,7 +148,9 @@ func runLocateSearch(ctx context.Context, spec locateSearchSpec) (string, error)
DocScope: docScope,
TenantID: tenantID,
VectorOnly: spec.vectorOnly,
- SelectFields: grepChunksSelectFields,
+ // Agentic, so no dense-only rescue.
+ AllowDenseFallback: new(false),
+ SelectFields: grepChunksSelectFields,
// Same "only ordinary prose" filter as grep_chunks: exclude
// compiled products so the model reads original document text, not
// derived graph content.
diff --git a/internal/agentic_rag/tool_search_semantic_chunks_test.go b/internal/agentic_rag/tool_search_semantic_chunks_test.go
index b1a1acca7a..93326ac74a 100644
--- a/internal/agentic_rag/tool_search_semantic_chunks_test.go
+++ b/internal/agentic_rag/tool_search_semantic_chunks_test.go
@@ -85,6 +85,27 @@ func TestSearchSemanticChunksToolAsksForTheDenseLegAlone(t *testing.T) {
}
}
+// TestLocateSearchDisablesDenseFallback pins the agentic/human split on the
+// shared locate path: search_chunks and search_semantic_chunks both hand
+// chunks to the model as evidence, so neither may ask for a dense-only
+// rescue. Only human-facing retrieval keeps it on.
+func TestLocateSearchDisablesDenseFallback(t *testing.T) {
+ fake := newCaptureService()
+ runtime.SetRetrievalService(fake)
+ defer runtime.SetRetrievalService(nil)
+
+ if _, err := NewSearchSemanticChunksTool("t", []string{"kb1"}).InvokableRun(context.Background(),
+ `{"queries":["an Italian family restaurant"]}`); err != nil {
+ t.Fatalf("invokable run: %v", err)
+ }
+ if len(fake.reqs) != 1 {
+ t.Fatalf("requests = %d, want 1", len(fake.reqs))
+ }
+ if req := fake.reqs[0]; req.AllowDenseFallback == nil || *req.AllowDenseFallback {
+ t.Fatal("locate search is agentic and must disable the dense fallback")
+ }
+}
+
// TestSearchSemanticChunksToolSchemaHasNoWeightKnob keeps the fusion weight out
// of the model's reach: offering it would let the caller rebuild search_chunks
// by hand, which is the one thing this tool must not degrade into.
diff --git a/internal/service/nlp/retrieval.go b/internal/service/nlp/retrieval.go
index ea8911fe82..57aa4d04b5 100644
--- a/internal/service/nlp/retrieval.go
+++ b/internal/service/nlp/retrieval.go
@@ -826,53 +826,35 @@ func (s *RetrievalService) Search(ctx context.Context, req *RetrievalSearchReque
if err != nil {
return nil, fmt.Errorf("search failed: %w", err)
}
- // If result is empty, retry with relaxed conditions
+ // If the result is empty, retry with relaxed conditions. Every leg
+ // keeps at least one MATCH expression: without one Infinity cannot
+ // project a score (error 3013) and every similarity reads back as
+ // 0.0, the "all scores collapsed" signature of infinity#3523.
+ //
+ // No filter-only fallback, deliberately, even for a document scope:
+ // unscored rows carry no relevance and were fed to an LLM as context.
+ // Callers that want a document's chunks use ChunkService.List.
if engineResult.Total == 0 {
- _, hasDocIDFilter := filters["doc_id"]
if req.VectorOnly || matchText == nil {
if *req.AllowDenseFallback {
common.Debug("Retrieval dense-only fallback after empty initial search")
- matchDense = cloneDenseExpr(denseTemplate)
- matchDense.ExtraOptions["similarity"] = 0.17
- searchRequest.MatchExprs = []any{matchDense}
- engineResult, err = s.docEngine.Search(ctx, searchRequest)
+ engineResult, err = s.searchDenseOnly(ctx, searchRequest, denseTemplate)
if err != nil {
return nil, fmt.Errorf("dense-only fallback failed: %w", err)
}
}
- } else if hasDocIDFilter {
- // When a doc_id filter is present (e.g. from metadata filter like era=960)
- // and the hybrid search returns no results, fall back to a filter-only
- // search (no text match, no vector match). This ensures that when a
- // metadata filter restricts the search to a specific set of documents
- // that happen to have no relevant content for the query, we still
- // return those documents' chunks (ordered by the request's sort/order).
- //
- // Example: searching "打虎" with metadata filter era≠960 limits the
- // search to Three Kingdoms documents (era=220). Since "打虎" only
- // appears in Water Margin (era=960), the hybrid search returns 0
- // results. This fallback returns all chunks from Three Kingdoms
- // documents instead of returning an empty result.
- searchRequest.SelectFields = src
- searchRequest.MatchExprs = []interface{}{}
- searchRequest.RankFeature = nil
-
- engineResult, err = s.docEngine.Search(ctx, searchRequest)
- if err != nil {
- return nil, fmt.Errorf("search retry failed: %w", err)
- }
} else {
- // No doc_id filter — retry with lower min_match (0.1 vs default 0.3)
- // and lower vector similarity threshold (0.17 vs default 0.1-0.2).
- // This provides a second chance for queries that were too strict
- // on the first attempt.
- matchText, _ := GetQueryBuilder().Question(req.Question, "qa", minMatch(req.VectorSimilarityWeight, 0.1), req.Language)
+ // Retry with lower min_match (0.1 vs default 0.3) and lower
+ // vector similarity threshold (0.17 vs default 0.1-0.2).
+ // This provides a second chance for queries that were too
+ // strict on the first attempt.
+ relaxedText, _ := GetQueryBuilder().Question(req.Question, "qa", minMatch(req.VectorSimilarityWeight, 0.1), req.Language)
matchDense = cloneDenseExpr(denseTemplate)
matchDense.ExtraOptions["similarity"] = 0.17
- if req.VectorOnly || matchText == nil {
+ if relaxedText == nil {
searchRequest.MatchExprs = []interface{}{matchDense}
} else {
- searchRequest.MatchExprs = []interface{}{matchText, matchDense, fusionExpr}
+ searchRequest.MatchExprs = []interface{}{relaxedText, matchDense, fusionExpr}
}
searchRequest.RankFeature = req.RankFeature
@@ -881,12 +863,9 @@ func (s *RetrievalService) Search(ctx context.Context, req *RetrievalSearchReque
return nil, fmt.Errorf("search retry failed: %w", err)
}
// Zero-only by design: any lexical hit keeps the existing hybrid candidate semantics.
- if engineResult.Total == 0 && matchText != nil && *req.AllowDenseFallback {
+ if engineResult.Total == 0 && relaxedText != nil && *req.AllowDenseFallback {
common.Debug("Retrieval dense-only fallback after empty hybrid retries")
- matchDense = cloneDenseExpr(denseTemplate)
- matchDense.ExtraOptions["similarity"] = 0.17
- searchRequest.MatchExprs = []any{matchDense}
- engineResult, err = s.docEngine.Search(ctx, searchRequest)
+ engineResult, err = s.searchDenseOnly(ctx, searchRequest, denseTemplate)
if err != nil {
return nil, fmt.Errorf("dense-only fallback failed: %w", err)
}
@@ -986,6 +965,16 @@ func (s *RetrievalService) Search(ctx context.Context, req *RetrievalSearchReque
}, nil
}
+// searchDenseOnly re-runs the request with the dense leg alone and the vector
+// floor dropped to 0.17. Unlike a filter-only query, a lone MATCH VECTOR still
+// projects a score.
+func (s *RetrievalService) searchDenseOnly(ctx context.Context, searchRequest *types.SearchRequest, denseTemplate *types.MatchDenseExpr) (*types.SearchResult, error) {
+ matchDense := cloneDenseExpr(denseTemplate)
+ matchDense.ExtraOptions["similarity"] = 0.17
+ searchRequest.MatchExprs = []any{matchDense}
+ return s.docEngine.Search(ctx, searchRequest)
+}
+
func cloneDenseExpr(source *types.MatchDenseExpr) *types.MatchDenseExpr {
clone := *source
clone.EmbeddingData = slices.Clone(source.EmbeddingData)
@@ -1306,6 +1295,7 @@ func (s *RetrievalService) PruneDeletedChunks(ctx context.Context, result *Retri
Keywords: result.Keywords,
Aggregation: result.Aggregation,
Options: result.Options,
+ IndexNames: result.IndexNames,
}, nil
}
diff --git a/internal/service/nlp/retrieval_test.go b/internal/service/nlp/retrieval_test.go
index f0eacd464a..2255c9d93d 100644
--- a/internal/service/nlp/retrieval_test.go
+++ b/internal/service/nlp/retrieval_test.go
@@ -861,3 +861,238 @@ func TestRetrievalSearchesEachTenantIndexOnce(t *testing.T) {
t.Fatalf("index names = %v, want [ragflow_tenant-1]", docEngine.indexNames)
}
}
+
+// TestSearchDocumentScopeRetriesWithRelaxedHybrid pins the first leg of the
+// fix for infiniflow/infinity#3523: a document-scoped query whose first hybrid
+// pass comes back empty retries with relaxed conditions instead of dropping
+// every MATCH expression. A query with none cannot carry a score on Infinity
+// (3013), which is what collapsed every similarity to 0.0.
+func TestSearchDocumentScopeRetriesWithRelaxedHybrid(t *testing.T) {
+ oldQueryBuilder := globalQueryBuilder
+ if GetQueryBuilder() == nil {
+ globalQueryBuilder = NewQueryBuilder()
+ }
+ defer func() { globalQueryBuilder = oldQueryBuilder }()
+
+ docEngine := &retryCaptureEngine{engineType: string(engine.EngineInfinity), totals: []int64{0, 3}}
+ service := NewRetrievalService(docEngine, nil)
+ result, err := service.Search(t.Context(), &RetrievalSearchRequest{
+ Question: "alpha", TenantIDs: []string{"tenant-1"}, KbIDs: []string{"kb-1"}, Page: 1, PageSize: 10,
+ KNNTopK: 7, KNNNumCandidates: 19, DocIDs: []string{"doc-1"},
+ EmbeddingModel: &modelModule.EmbeddingModel{ModelDriver: &captureEmbeddingDriver{}},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(docEngine.requests) != 2 {
+ t.Fatalf("search calls = %d, want the empty hybrid pass plus one scored retry", len(docEngine.requests))
+ }
+ retry := docEngine.requests[1]
+ if len(retry.MatchExprs) != 3 {
+ t.Fatalf("retry expressions = %d, want the relaxed hybrid's 3", len(retry.MatchExprs))
+ }
+ if got := fmt.Sprint(retry.Filter["doc_id"]); got != "[doc-1]" {
+ t.Fatalf("retry document scope = %s, want [doc-1]", got)
+ }
+ if result.Total != 3 {
+ t.Fatalf("total = %d, want the relaxed retry's 3 rows", result.Total)
+ }
+}
+
+// TestSearchDocumentScopeNeverResortsToFilterOnly pins the removal of the
+// document-scope filter-only fallback: it returned the document's chunks with
+// no score at all (infinity#3523), which carries no relevance and is
+// indistinguishable from a real failure. Callers that want a document's chunks
+// ask ChunkService.List.
+func TestSearchDocumentScopeNeverResortsToFilterOnly(t *testing.T) {
+ oldQueryBuilder := globalQueryBuilder
+ if GetQueryBuilder() == nil {
+ globalQueryBuilder = NewQueryBuilder()
+ }
+ defer func() { globalQueryBuilder = oldQueryBuilder }()
+
+ // hybrid, relaxed hybrid, dense-only — and then nothing. The 4th total is
+ // what a filter-only scan would have returned; it must stay unconsumed.
+ docEngine := &retryCaptureEngine{engineType: string(engine.EngineInfinity), totals: []int64{0, 0, 0, 3}}
+ service := NewRetrievalService(docEngine, nil)
+ result, err := service.Search(t.Context(), &RetrievalSearchRequest{
+ Question: "alpha", TenantIDs: []string{"tenant-1"}, KbIDs: []string{"kb-1"}, Page: 1, PageSize: 10,
+ KNNTopK: 7, KNNNumCandidates: 19, DocIDs: []string{"doc-1"},
+ RankFeature: map[string]float64{"pagerank_fea": 10},
+ EmbeddingModel: &modelModule.EmbeddingModel{ModelDriver: &captureEmbeddingDriver{}},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(docEngine.requests) != 3 {
+ t.Fatalf("search calls = %d, want 3: hybrid, relaxed hybrid and dense-only, with no filter-only scan after them", len(docEngine.requests))
+ }
+ for i, want := range []int{3, 3, 1} {
+ if got := len(docEngine.requests[i].MatchExprs); got != want {
+ t.Fatalf("call %d expressions = %d, want %d", i+1, got, want)
+ }
+ }
+ // The invariant behind the removal: no leg may issue a query that cannot
+ // carry a score, whatever else it tries.
+ for i, request := range docEngine.requests {
+ if len(request.MatchExprs) == 0 {
+ t.Fatalf("call %d issued a query with no MATCH expression, which cannot carry a score", i+1)
+ }
+ }
+ if result.Total != 0 {
+ t.Fatalf("total = %d, want 0: nothing in the scope is relevant, so nothing comes back", result.Total)
+ }
+}
+
+// TestSearchDefaultsDenseFallbackOn pins the human half of the agentic/human
+// split: a caller that says nothing keeps the dense-only rescue, because only
+// the agentic tools opt out. Flipping this default would silently change every
+// human-facing retrieval path, so it needs its own guard rather than relying on
+// the agentic tests staying green.
+func TestSearchDefaultsDenseFallbackOn(t *testing.T) {
+ oldQueryBuilder := globalQueryBuilder
+ if GetQueryBuilder() == nil {
+ globalQueryBuilder = NewQueryBuilder()
+ }
+ defer func() { globalQueryBuilder = oldQueryBuilder }()
+
+ // hybrid empty, relaxed hybrid empty, dense-only rescues 3.
+ docEngine := &retryCaptureEngine{engineType: string(engine.EngineInfinity), totals: []int64{0, 0, 3}}
+ service := NewRetrievalService(docEngine, nil)
+ // AllowDenseFallback left nil on purpose: the default is the contract.
+ result, err := service.Search(t.Context(), &RetrievalSearchRequest{
+ Question: "alpha", TenantIDs: []string{"tenant-1"}, KbIDs: []string{"kb-1"}, Page: 1, PageSize: 10,
+ KNNTopK: 7, KNNNumCandidates: 19,
+ EmbeddingModel: &modelModule.EmbeddingModel{ModelDriver: &captureEmbeddingDriver{}},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(docEngine.requests) != 3 {
+ t.Fatalf("search calls = %d, want 3: the dense-only rescue must run when the caller leaves the flag unset", len(docEngine.requests))
+ }
+ if got := len(docEngine.requests[2].MatchExprs); got != 1 {
+ t.Fatalf("rescue expressions = %d, want the dense leg's 1", got)
+ }
+ if result.Total != 3 {
+ t.Fatalf("total = %d, want the dense rescue's 3 rows", result.Total)
+ }
+}
+
+// TestPruneDeletedChunksPreservesIndexNames guards the one rewrite path that
+// rebuilds the result. PruneDeletedChunks returns the caller's struct untouched
+// when there is nothing to prune, so only the rebuild branch can drop a field.
+func TestPruneDeletedChunksPreservesIndexNames(t *testing.T) {
+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ sqlDB, err := db.DB()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer sqlDB.Close()
+ if err := db.AutoMigrate(&entity.Document{}); err != nil {
+ t.Fatal(err)
+ }
+ if err := db.Create(&entity.Document{ID: "doc-1", KbID: "kb-1", ParserConfig: entity.JSONMap{}}).Error; err != nil {
+ t.Fatal(err)
+ }
+ oldDB := dao.DB
+ dao.DB = db
+ defer func() { dao.DB = oldDB }()
+
+ result := &RetrievalSearchResult{
+ Field: map[string]map[string]interface{}{
+ "kept": {"id": "kept", "doc_id": "doc-1"},
+ "gone": {"id": "gone", "doc_id": "deleted-doc"},
+ },
+ IDs: []string{"kept", "gone"},
+ IndexNames: []string{"ragflow_tenant-1"},
+ }
+ pruned, err := NewRetrievalService(nil, &dao.DocumentDAO{}).PruneDeletedChunks(t.Context(), result)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(pruned.IDs, []string{"kept"}) {
+ t.Fatalf("pruned IDs = %v, want [kept] (did the rebuild branch run?)", pruned.IDs)
+ }
+ if !slices.Equal(pruned.IndexNames, []string{"ragflow_tenant-1"}) {
+ t.Fatalf("IndexNames = %v, want [ragflow_tenant-1]", pruned.IndexNames)
+ }
+}
+
+// TestRetrievalReturnsNothingWhenDocumentScopeHasNoRelevantContent pins what
+// replaces the filter-only fallback: chunks that exist but are not relevant
+// yield nothing, rather than a whole document of 0.0 rows (infinity#3523).
+func TestRetrievalReturnsNothingWhenDocumentScopeHasNoRelevantContent(t *testing.T) {
+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ sqlDB, err := db.DB()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer sqlDB.Close()
+ if err := db.AutoMigrate(&entity.Document{}); err != nil {
+ t.Fatal(err)
+ }
+ if err := db.Create(&entity.Document{ID: "doc-1", KbID: "kb-1", ParserConfig: entity.JSONMap{}}).Error; err != nil {
+ t.Fatal(err)
+ }
+ oldDB, oldQueryBuilder := dao.DB, globalQueryBuilder
+ dao.DB, globalQueryBuilder = db, NewQueryBuilder()
+ defer func() { dao.DB, globalQueryBuilder = oldDB, oldQueryBuilder }()
+
+ // Chunks that are inside the scope but match "alpha" on neither leg.
+ irrelevantRows := []map[string]interface{}{
+ {"id": "chunk-1", "doc_id": "doc-1", "kb_id": "kb-1"},
+ {"id": "chunk-2", "doc_id": "doc-1", "kb_id": "kb-1"},
+ }
+ // Every scored pass misses, so Retrieval would once have gone on to scan
+ // the document without a match expression and hand these rows back.
+ docEngine := &unscoredDocScopeEngine{unscoredRows: irrelevantRows}
+ result, err := NewRetrievalService(docEngine, &dao.DocumentDAO{}).Retrieval(t.Context(), &RetrievalRequest{
+ Question: "alpha", TenantIDs: []string{"tenant-1"}, KbIDs: []string{"kb-1"}, DocIDs: []string{"doc-1"},
+ Page: 1, PageSize: 10, VectorSimilarityWeight: new(0.3),
+ EmbeddingModel: &modelModule.EmbeddingModel{ModelDriver: &captureEmbeddingDriver{}},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if docEngine.reachedFilterOnly != 0 {
+ t.Fatalf("filter-only calls = %d, want 0 — no leg may issue a query without a MATCH expression", docEngine.reachedFilterOnly)
+ }
+ if len(result.Chunks) != 0 || result.Total != 0 {
+ t.Fatalf("chunks = %d total = %d, want nothing: the rows are there, they are just not relevant", len(result.Chunks), result.Total)
+ }
+}
+
+// unscoredDocScopeEngine answers every scored pass with nothing and a
+// scoreless pass with unscored rows, so a test can tell "Retrieval declined to
+// return them" apart from "the engine had nothing".
+type unscoredDocScopeEngine struct {
+ retrievalCountEngine
+ unscoredRows []map[string]interface{}
+ scoredCalls int
+ reachedFilterOnly int
+}
+
+func (e *unscoredDocScopeEngine) Search(_ context.Context, req *types.SearchRequest) (*types.SearchResult, error) {
+ // A scored pass: hybrid, relaxed hybrid or dense-only. Report nothing so
+ // the ladder keeps descending.
+ if len(req.MatchExprs) > 0 {
+ e.scoredCalls++
+ return &types.SearchResult{Total: 0}, nil
+ }
+ // No match expressions means the filter-only scan: the last resort, and
+ // the only pass that has rows here.
+ e.reachedFilterOnly++
+ e.searchFilters = append(e.searchFilters, req.Filter)
+ rows := make([]map[string]interface{}, 0, len(e.unscoredRows))
+ for _, row := range e.unscoredRows {
+ rows = append(rows, maps.Clone(row))
+ }
+ return &types.SearchResult{Chunks: rows, Total: int64(len(rows))}, nil
+}