Skip to content

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

feat(agentic_rag): port the harness table/metadata paths to Go, with field-driven metadata_search (#19941)

Caobaining1071da6c3338a
diff --git a/cmd/ragflow_server.go b/cmd/ragflow_server.go
index a2c8679ce2..105571e70c 100644
--- a/cmd/ragflow_server.go
+++ b/cmd/ragflow_server.go
@@ -1250,10 +1250,25 @@ func startServer(ctx context.Context, args *serverArgs) error {
// is what hybrid_search applies to its vector leg (search.py:143), so
// getting it wrong silently degrades search_chunks to keyword-only.
hasEmbedder := hasEmbedderFor(kbs)
+ // Retrieval tuning mirrors the dialog's own settings, so the agentic
+ // searches run with the same budget as the standard path. Without it the
+ // harness falls back to its package defaults (top_n=12) and the dialog's
+ // configured top_n is silently ignored.
+ //
+ // The runtime carries the KEYWORD leg's weight and derives the vector leg
+ // as its complement (runtime.resolveKeywordsSimilarityWeight, and the
+ // RetrieveRequest contract: 0.7 hybrid / 0.0 vector-only / 1.0
+ // keyword-only). The dialog configures the VECTOR weight, so it is inverted
+ // here; the dialog's default 0.3 therefore yields the runtime's own 0.7.
+ keywordsWeight := 1 - req.Retrieval.VectorSimilarityWeight
deps := agentic_rag.RAGTools{
- Model: model,
- ModelName: resolvedModelName,
- Outer: outerModel,
+ Model: model,
+ ModelName: resolvedModelName,
+ Outer: outerModel,
+ TopN: req.Retrieval.TopN,
+ SimilarityThreshold: req.Retrieval.SimilarityThreshold,
+ KeywordsSimilarityWeight: &keywordsWeight,
+ RerankCandidatesCount: req.Retrieval.RerankCandidatesCount,
// OriginalQuestion mirrors Python RAGTools(original_user_question=...):
// the user's own, unrewritten question as received from the chat
// layer. The outer model's `rag(question=...)` argument is
@@ -1266,6 +1281,15 @@ func startServer(ctx context.Context, args *serverArgs) error {
// retrieval to the user-selected documents instead of the whole kb.
DocScope: req.DocIDs,
DocIDVerifier: agentic_rag.NewDocIDLookup(),
+ // MetadataResolver backs the metadata_search tool and the pre-search
+ // metadata channel (Python DocMetadataService push-down + meta_filter
+ // fallback). metadataService already carries the doc engine and the DAO
+ // the metadata index reads need.
+ MetadataResolver: metadataService,
+ // DeclaredMetadata lets the metadata_search catalog describe each field
+ // (meaning + allowed values) from the dataset's own parser_config, not just
+ // name it. Same service: it also carries the KB DAO that read needs.
+ DeclaredMetadata: metadataService,
// DocChunks pages one document's chunks in reading order off the
// chunk index (Python retriever.chunk_list), backing the
// document-level tools (summarize_document / fetch_full_document).
diff --git a/internal/common/metadata_utils.go b/internal/common/metadata_utils.go
index 85e9e79da2..3cfd7c80d2 100644
--- a/internal/common/metadata_utils.go
+++ b/internal/common/metadata_utils.go
@@ -18,6 +18,7 @@ package common
import (
"regexp"
+ "sort"
"strconv"
"strings"
)
@@ -415,6 +416,151 @@ func Turn2JSONSchema(fields []MetadataFieldDef) map[string]any {
}
}
+// ParserConfigBool coerces a parser_config boolean-like value (bool / number) to bool,
+// mirroring the frontend's metadata enable flag.
+func ParserConfigBool(v any) bool {
+ switch typed := v.(type) {
+ case bool:
+ return typed
+ case float64:
+ return typed > 0
+ case int:
+ return typed > 0
+ }
+ return false
+}
+
+// ExtractorMetadataConfig returns the modular metadata config
+// ({"enabled", "metadata", "built_in_metadata"}) of the FIRST Extractor component node, in
+// sorted key order so two extractor nodes resolve deterministically.
+//
+// This is the component-scoped config the ingestion pipeline reads; flat legacy fields
+// (enable_metadata / metadata_config / built_in_metadata at the top level or on the node)
+// are deliberately not supported.
+func ExtractorMetadataConfig(parserConfig map[string]any) (map[string]any, bool) {
+ if parserConfig == nil {
+ return nil, false
+ }
+ var extractorKeys []string
+ for k := range parserConfig {
+ lower := strings.ToLower(k)
+ if strings.HasPrefix(lower, "extractor:") || strings.HasPrefix(lower, "extractor_") {
+ extractorKeys = append(extractorKeys, k)
+ }
+ }
+ sort.Strings(extractorKeys)
+ for _, k := range extractorKeys {
+ node, ok := parserConfig[k].(map[string]any)
+ if !ok {
+ continue
+ }
+ if metaObj, ok := node["metadata"].(map[string]any); ok {
+ return metaObj, true
+ }
+ }
+ return nil, false
+}
+
+// DatasetMetadataConfig returns the top-level modular metadata config of a dataset
+// (parser_config["metadata"]), which is where the dataset metadata API writes the fields a
+// user declared for extraction.
+func DatasetMetadataConfig(parserConfig map[string]any) (map[string]any, bool) {
+ if parserConfig == nil {
+ return nil, false
+ }
+ metaObj, ok := parserConfig["metadata"].(map[string]any)
+ return metaObj, ok
+}
+
+// MetadataRawFieldList normalizes a metadata field list that may arrive as []any (the DB
+// round-trip) or []map[string]any (in-memory construction) into a []any.
+func MetadataRawFieldList(value any) []any {
+ switch list := value.(type) {
+ case []any:
+ return list
+ case []map[string]any:
+ out := make([]any, 0, len(list))
+ for _, item := range list {
+ out = append(out, item)
+ }
+ return out
+ }
+ return nil
+}
+
+// MetadataFieldDefsFromRaw parses a raw {key, type, description, enum} field list into
+// typed defs. Entries without a key are dropped, so a malformed entry cannot become a
+// field nobody can filter on.
+func MetadataFieldDefsFromRaw(value any) []MetadataFieldDef {
+ if value == nil {
+ return nil
+ }
+ if defs, ok := value.([]MetadataFieldDef); ok {
+ return defs
+ }
+ arr := MetadataRawFieldList(value)
+ if arr == nil {
+ return nil
+ }
+ fields := make([]MetadataFieldDef, 0, len(arr))
+ for _, f := range arr {
+ m, ok := f.(map[string]any)
+ if !ok {
+ continue
+ }
+ key, _ := m["key"].(string)
+ if key = strings.TrimSpace(key); key == "" {
+ continue
+ }
+ def := MetadataFieldDef{Key: key}
+ if t, ok := m["type"].(string); ok {
+ def.Type = t
+ }
+ if d, ok := m["description"].(string); ok {
+ def.Description = d
+ }
+ if e, ok := m["enum"].([]any); ok {
+ for _, ev := range e {
+ if s, ok := ev.(string); ok {
+ def.Enum = append(def.Enum, s)
+ }
+ }
+ }
+ fields = append(fields, def)
+ }
+ return fields
+}
+
+// DeclaredMetadataFieldsFromParserConfig returns the metadata fields a dataset DECLARES for
+// extraction, reading both the dataset-level config (parser_config["metadata"]) and, when
+// that is absent, the first Extractor component node's.
+//
+// This is the DECLARATIVE source of a dataset's metadata: unlike the doc-metadata index it
+// exists BEFORE anything is indexed, and it carries each field's meaning (description) and
+// allowed values (enum) — what a model needs to fill a filter correctly rather than guess.
+// Fields declared in both lists are de-duplicated, first occurrence winning.
+func DeclaredMetadataFieldsFromParserConfig(parserConfig map[string]any) []MetadataFieldDef {
+ metaObj, ok := DatasetMetadataConfig(parserConfig)
+ if !ok {
+ metaObj, ok = ExtractorMetadataConfig(parserConfig)
+ }
+ if !ok {
+ return nil
+ }
+ var out []MetadataFieldDef
+ seen := map[string]bool{}
+ for _, raw := range []any{metaObj["metadata"], metaObj["built_in_metadata"]} {
+ for _, def := range MetadataFieldDefsFromRaw(raw) {
+ if seen[def.Key] {
+ continue
+ }
+ seen[def.Key] = true
+ out = append(out, def)
+ }
+ }
+ return out
+}
+
// combinedValueDelim splits a single combined metadata value into its parts.
// Mirrors Python doc_metadata_service.py _split_combined_values regex
// r"[、,,;;|]+" (Chinese comma 、, ASCII comma ,, full-width comma ,,
diff --git a/internal/common/metadata_utils_test.go b/internal/common/metadata_utils_test.go
index 4a5b01101d..35c268c8ff 100644
--- a/internal/common/metadata_utils_test.go
+++ b/internal/common/metadata_utils_test.go
@@ -17,6 +17,7 @@
package common
import (
+ "reflect"
"testing"
)
@@ -613,3 +614,68 @@ func TestMetaFilter_NotEquals(t *testing.T) {
t.Errorf("expected [doc2] for ≠, got %v", result)
}
}
+
+// --- DeclaredMetadataFieldsFromParserConfig ---
+
+// TestDeclaredMetadataFieldsFromDatasetConfig pins the declarative read: the dataset-level
+// config's fields, with their meaning and allowed values, and a field declared in both lists
+// resolved once (first definition wins, so the richer entry is the one kept).
+func TestDeclaredMetadataFieldsFromDatasetConfig(t *testing.T) {
+ pc := map[string]any{
+ "metadata": map[string]any{
+ "enabled": true,
+ "metadata": []any{
+ map[string]any{"key": "author", "type": "string", "description": "who wrote it"},
+ map[string]any{"key": "doc_type", "type": "string", "enum": []any{"report", "paper"}},
+ map[string]any{"key": "", "type": "string"}, // blank key dropped
+ },
+ "built_in_metadata": []any{
+ map[string]any{"key": "author", "type": "string"}, // duplicate: dropped
+ map[string]any{"key": "file_name", "type": "string"},
+ },
+ },
+ }
+ got := DeclaredMetadataFieldsFromParserConfig(pc)
+ want := []MetadataFieldDef{
+ {Key: "author", Type: "string", Description: "who wrote it"},
+ {Key: "doc_type", Type: "string", Enum: []string{"report", "paper"}},
+ {Key: "file_name", Type: "string"},
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("fields = %#v, want %#v", got, want)
+ }
+}
+
+// TestDeclaredMetadataFieldsFallsBackToExtractorNode pins the second location: a config that
+// lives on the Extractor component node is read when the dataset level declares nothing.
+func TestDeclaredMetadataFieldsFallsBackToExtractorNode(t *testing.T) {
+ pc := map[string]any{
+ "Extractor:AutoExtractDefault": map[string]any{
+ "metadata": map[string]any{
+ "enabled": true,
+ "metadata": []any{
+ map[string]any{"key": "topic", "description": "subject area"},
+ },
+ },
+ },
+ }
+ got := DeclaredMetadataFieldsFromParserConfig(pc)
+ if len(got) != 1 || got[0].Key != "topic" || got[0].Description != "subject area" {
+ t.Errorf("fields = %#v, want the extractor node's topic field", got)
+ }
+}
+
+// TestDeclaredMetadataFieldsEmptyWhenNothingDeclared pins the degradation: absent or
+// malformed config declares nothing and must not panic.
+func TestDeclaredMetadataFieldsEmptyWhenNothingDeclared(t *testing.T) {
+ for name, pc := range map[string]map[string]any{
+ "nil": nil,
+ "empty": {},
+ "malformed": {"metadata": "nonsense"},
+ "enabled-no-list": {"metadata": map[string]any{"enabled": true}},
+ } {
+ if got := DeclaredMetadataFieldsFromParserConfig(pc); len(got) != 0 {
+ t.Errorf("%s: fields = %#v, want none", name, got)
+ }
+ }
+}
diff --git a/internal/ingestion/component/extractor.go b/internal/ingestion/component/extractor.go
index 29fffb6d8a..10c82fd8af 100644
--- a/internal/ingestion/component/extractor.go
+++ b/internal/ingestion/component/extractor.go
@@ -1654,53 +1654,10 @@ func tryParseJSONObject(s string) (map[string]any, bool) {
}
// parseMetadataFieldDefs converts an any value (typically []any of maps)
-// to a typed []common.MetadataFieldDef slice.
+// to a typed []common.MetadataFieldDef slice. The parsing lives in common so the
+// ingestion extractor and the agentic metadata catalog share one field contract.
func parseMetadataFieldDefs(v any) []common.MetadataFieldDef {
- if v == nil {
- return nil
- }
- if defs, ok := v.([]common.MetadataFieldDef); ok {
- return defs
- }
- var arr []any
- switch typed := v.(type) {
- case []any:
- arr = typed
- case []map[string]any:
- arr = make([]any, 0, len(typed))
- for _, item := range typed {
- arr = append(arr, item)
- }
- default:
- return nil
- }
- fields := make([]common.MetadataFieldDef, 0, len(arr))
- for _, f := range arr {
- m, ok := f.(map[string]any)
- if !ok {
- continue
- }
- key, _ := m["key"].(string)
- if key = strings.TrimSpace(key); key == "" {
- continue
- }
- def := common.MetadataFieldDef{Key: key}
- if t, ok := m["type"].(string); ok {
- def.Type = t
- }
- if d, ok := m["description"].(string); ok {
- def.Description = d
- }
- if e, ok := m["enum"].([]any); ok {
- for _, ev := range e {
- if s, ok := ev.(string); ok {
- def.Enum = append(def.Enum, s)
- }
- }
- }
- fields = append(fields, def)
- }
- return fields
+ return common.MetadataFieldDefsFromRaw(v)
}
// mapInt converts a JSON-compatible value to int.
diff --git a/internal/ingestion/task/pipeline_executor.go b/internal/ingestion/task/pipeline_executor.go
index 16c3af4e03..d7ff66805b 100644
--- a/internal/ingestion/task/pipeline_executor.go
+++ b/internal/ingestion/task/pipeline_executor.go
@@ -385,57 +385,21 @@ func (s *PipelineExecutor) terminalDuration(start time.Time) float64 {
// component-scoped Extractor node's modular metadata config. Legacy flat
// fields (enable_metadata / metadata_config / built_in_metadata at either the
// top level or on the node) are intentionally not supported.
+// builtInMetadataFromParserConfig extracts the built-in metadata config
+// (update_time / file_name) and whether auto-metadata is enabled from the
+// component-scoped Extractor node's modular metadata config. Legacy flat
+// fields (enable_metadata / metadata_config / built_in_metadata at either the
+// top level or on the node) are intentionally not supported.
+//
+// The config lookup and the field-list normalisation live in common (see
+// ExtractorMetadataConfig / MetadataRawFieldList) so the ingestion pipeline and the agentic
+// metadata catalog read the very same shape.
func builtInMetadataFromParserConfig(parserConfig entity.JSONMap) ([]any, bool) {
- var extractorKeys []string
- for k := range parserConfig {
- lower := strings.ToLower(k)
- if strings.HasPrefix(lower, "extractor:") || strings.HasPrefix(lower, "extractor_") {
- extractorKeys = append(extractorKeys, k)
- }
- }
- sort.Strings(extractorKeys)
-
- for _, k := range extractorKeys {
- nodeRaw := parserConfig[k]
- if node, ok := nodeRaw.(map[string]any); ok {
- if metaObj, ok := node["metadata"].(map[string]any); ok {
- arr := metadataFieldSlice(metaObj["built_in_metadata"])
- return arr, parserConfigBool(metaObj["enabled"])
- }
- }
+ metaObj, ok := common.ExtractorMetadataConfig(parserConfig)
+ if !ok {
+ return nil, false
}
- return nil, false
-}
-
-// metadataFieldSlice normalizes a built_in_metadata / metadata value that may
-// arrive as []interface{} (DB round-trip) or []map[string]interface{} (in-memory
-// construction) into a []any.
-func metadataFieldSlice(value any) []any {
- if list, ok := value.([]any); ok {
- return list
- }
- if list, ok := value.([]map[string]any); ok {
- out := make([]any, 0, len(list))
- for _, item := range list {
- out = append(out, item)
- }
- return out
- }
- return nil
-}
-
-// parserConfigBool coerces a parser_config boolean-like value (bool / number)
-// to bool, mirroring the frontend's enable_metadata handling.
-func parserConfigBool(v any) bool {
- switch typed := v.(type) {
- case bool:
- return typed
- case float64:
- return typed > 0
- case int:
- return typed > 0
- }
- return false
+ return common.MetadataRawFieldList(metaObj["built_in_metadata"]), common.ParserConfigBool(metaObj["enabled"])
}
func docNameValue(name *string) string {
diff --git a/internal/rag/agentic-rag/agentic_rag.go b/internal/rag/agentic-rag/agentic_rag.go
index 4bfe9116d8..6ff1554906 100644
--- a/internal/rag/agentic-rag/agentic_rag.go
+++ b/internal/rag/agentic-rag/agentic_rag.go
@@ -185,6 +185,15 @@ type RAGTools struct {
// (summarize_document / fetch_full_document)
// Nil disables it: the document-level tools report that reading is unavailable.
DocChunks runtime.DocChunkLister
+ // MetadataResolver resolves document sets from document metadata. It backs the
+ // metadata_search tool and the pre-search metadata channel
+ // (implemented by internal/service.MetadataService). Nil leaves both unavailable.
+ MetadataResolver runtime.MetadataResolver
+ // DeclaredMetadata reads the metadata fields the datasets DECLARE in their
+ // parser_config, which is what lets the metadata_search catalog describe a field
+ // (its meaning and allowed values) instead of only naming it. Same implementation as
+ // MetadataResolver; nil leaves the catalog with the metadata index alone.
+ DeclaredMetadata runtime.DeclaredMetadataResolver
// Outer is the outer-layer chat model that drives the rag_agent react loop
// (dialog_service.rag_agent): it binds tools=[rag, summarize_document] with
// terminal_tools={"rag"}. When non-nil, Rag runs that outer loop: the model may call
@@ -968,6 +977,8 @@ func searchDepsFor(ctx context.Context, deps RAGTools, req runtime.RunRequest, d
DocIDVerifier: deps.DocIDVerifier,
DocChunks: deps.DocChunks,
DocTenantResolver: dbDocTenantResolver{},
+ MetadataResolver: deps.MetadataResolver,
+ DeclaredMetadata: deps.DeclaredMetadata,
Model: deps.Model, // the calculate tool writes its expression via the model
DocScope: deps.DocScope,
// Python retrieve:614-646 — configuration is the middle precedence
@@ -1551,8 +1562,14 @@ func prepareOuterReact(ctx context.Context, deps RAGTools, req runtime.RunReques
{
"type": "function",
"function": map[string]any{
- "name": "rag",
- "description": "Run the full agentic research graph over the configured datasets and return a cited answer.",
+ "name": "rag",
+ "description": "Run the full agentic research graph over the configured datasets and return a cited answer. " +
+ "WHEN TO CALL: every question whose answer must come from the knowledge base — a fact, an enumeration, " +
+ "a count, \"which documents ...\", a date or updated-time range, a comparison, a multi-hop relation, " +
+ "or anything that needs citations. " +
+ "DO NOT CALL: only for pure chit-chat or a rewriting task that cannot need the datasets. " +
+ "You MUST call this before answering a knowledge-base question: the dataset names and your own prior " +
+ "knowledge are not evidence, and answering without it is a wrong answer even when it reads well.",
"parameters": map[string]any{
"type": "object",
"properties": map[string]any{
@@ -1568,14 +1585,18 @@ func prepareOuterReact(ctx context.Context, deps RAGTools, req runtime.RunReques
{
"type": "function",
"function": map[string]any{
- "name": "summarize_document",
- "description": "Read an entire document by id into the evidence set and return a short summary the model can answer from.",
+ "name": "summarize_document",
+ "description": "Read an entire document by id into the evidence set and return a short summary the model can answer from. " +
+ "WHEN TO CALL: only when you ALREADY hold a doc_id — returned by an earlier `rag` call, or given by the user. " +
+ "DO NOT CALL: when you have no doc_id, or the question asks WHICH documents exist, or it needs several " +
+ "documents compared or aggregated — that is the `rag` tool's job. This tool cannot find a document: " +
+ "called without a real doc_id it only returns an error and wastes a round.",
"parameters": map[string]any{
"type": "object",
"properties": map[string]any{
"doc_id": map[string]any{
"type": "string",
- "description": "The document id to read.",
+ "description": "The document id to read — one you already hold from a prior `rag` result or from the user.",
},
},
"required": []string{"doc_id"},
@@ -2401,9 +2422,11 @@ func runSingleSession(ctx context.Context, deps RAGTools, req runtime.RunRequest
ThinkingMode: resp.Mode.Label,
// Provider gate: without a wired provider the tool is hidden rather than
// advertised dead.
- HasWebSearch: resp.Mode.HasTool("web_search") && deps.WebSearch != nil,
- DisabledTools: map[string]bool{},
- Exec: runtime.NewSearchExecutor(sd, req),
+ HasWebSearch: resp.Mode.HasTool("web_search") && deps.WebSearch != nil,
+ // The dataset's real metadata fields (see NewAgenticLoop).
+ MetadataFields: runtime.MetadataCatalogPtr(ctx, sd),
+ DisabledTools: map[string]bool{},
+ Exec: runtime.NewSearchExecutor(sd, req),
},
Model: deps.Model,
Prompts: deps.Prompts,
diff --git a/internal/rag/agentic-rag/agentic_rag_graph.go b/internal/rag/agentic-rag/agentic_rag_graph.go
index bfb8416f8e..40c099c1dd 100644
--- a/internal/rag/agentic-rag/agentic_rag_graph.go
+++ b/internal/rag/agentic-rag/agentic_rag_graph.go
@@ -418,7 +418,10 @@ func prefetchNode(ctx context.Context, deps RAGTools, st *AgenticState, logger *
step(ctx, logger, "Prefetch", "%s", prefetchSummary(len(st.Plan), len(queries)))
// The legs report one level deeper: they are what this prefetch runs, not
// sibling steps of it.
- added := FanoutSearch(runtime.Nested(callCtx), deps, st, queries, FanoutTopN, capacity)
+ // The FIRST prefetch round is the one that runs the metadata channel: the rewrites
+ // that follow are already targeted at a gap, while these sub-questions are the
+ // planner's raw wording and more likely to NAME a document.
+ added := FanoutSearch(runtime.Nested(callCtx), deps, st, queries, FanoutTopN, capacity, true)
for _, q := range queries {
st.Attempted = append(st.Attempted, map[string]any{"q": q, "r": 0, "new": added})
}
@@ -695,7 +698,7 @@ func queryRewriteNode(ctx context.Context, deps RAGTools, st *AgenticState, logg
// round got room <= 0 and admitted nothing, so the round reported "retrieval
// saturated" and discarded itself while the pool still had room to take the
// evidence it had just asked for.
- added := FanoutSearch(callCtx, deps, st, queries, FanoutTopNRewrite, runtime.EvidencePoolCap())
+ added := FanoutSearch(callCtx, deps, st, queries, FanoutTopNRewrite, runtime.EvidencePoolCap(), false)
// Retrieval saturation early-exit: a rewrite round that produced ZERO new
// snippets means further full research passes just burn latency.
if added == 0 && st.SearchRounds >= 1 {
@@ -1718,9 +1721,13 @@ func NewAgenticLoop() AgenticLoop {
// web_search is visible only when the mode exposes it AND a provider is actually
// wired. Advertising it without a provider leaves the model calling a tool that can
// only return an infra error.
- HasWebSearch: resp.Mode.HasTool("web_search") && deps.WebSearch != nil,
- DisabledTools: map[string]bool{},
- Exec: runtime.NewSearchExecutor(sd, req),
+ HasWebSearch: resp.Mode.HasTool("web_search") && deps.WebSearch != nil,
+ // The dataset's real metadata fields, read once here and rendered into the
+ // metadata_search schema and the session seed. Nil (no metadata / unreadable
+ // index / no resolver) keeps the shipped title-only schema.
+ MetadataFields: runtime.MetadataCatalogPtr(ctx, sd),
+ DisabledTools: map[string]bool{},
+ Exec: runtime.NewSearchExecutor(sd, req),
}
st, runErr := BuildAgenticGraph(ctx, RAGTools{
diff --git a/internal/rag/agentic-rag/agentic_rag_graph_test.go b/internal/rag/agentic-rag/agentic_rag_graph_test.go
index 657dea2453..a1cefda348 100644
--- a/internal/rag/agentic-rag/agentic_rag_graph_test.go
+++ b/internal/rag/agentic-rag/agentic_rag_graph_test.go
@@ -15,6 +15,7 @@ import (
"testing"
"time"
+ "ragflow/internal/common"
"ragflow/internal/engine"
"ragflow/internal/engine/types"
"ragflow/internal/entity"
@@ -783,7 +784,7 @@ func TestFanoutSearchIsDualChannel(t *testing.T) {
r := &channelRetriever{}
deps := RAGTools{Search: runtime.SearchDeps{Backend: r, KbIDs: []string{"kb1"}, HasEmbedder: true}}
st := &AgenticState{KB: &runtime.Kbinfos{}}
- FanoutSearch(ctx, deps, st, []string{"when was it built", "where located"}, 8, 60)
+ FanoutSearch(ctx, deps, st, []string{"when was it built", "where located"}, 8, 60, false)
// Two fan-outs x two channels.
if len(r.keywordsWeights) != 4 {
@@ -820,7 +821,7 @@ func TestFanoutSearchPrefersExactOverSemantic(t *testing.T) {
r := &fanoutHitRetriever{}
deps := RAGTools{Search: runtime.SearchDeps{Backend: r, KbIDs: []string{"kb1"}, HasEmbedder: true}}
st := &AgenticState{KB: &runtime.Kbinfos{}}
- added := FanoutSearch(ctx, deps, st, []string{"alpha", "beta"}, 8, 2)
+ added := FanoutSearch(ctx, deps, st, []string{"alpha", "beta"}, 8, 2, false)
if added != 2 {
t.Fatalf("added = %d, want 2 (the pool's remaining room)", added)
@@ -908,7 +909,7 @@ func TestFanoutSearchEvidenceTopUp(t *testing.T) {
KbIDs: []string{"kb-1"},
}}
st := &AgenticState{KB: &runtime.Kbinfos{}}
- added := FanoutSearch(context.Background(), deps, st, []string{"tower height topup"}, 8, 60)
+ added := FanoutSearch(context.Background(), deps, st, []string{"tower height topup"}, 8, 60, false)
if added != 2 {
t.Fatalf("added = %d, want 2 (the claim row + its source chunk)", added)
}
@@ -4520,3 +4521,407 @@ func TestRunSlotResearchPassEnumeratesOnce(t *testing.T) {
t.Errorf("second round ran the enumeration again (%d), want the stored set reused", got)
}
}
+
+// metadataScopedRetriever serves a hit ONLY to a doc-scoped request, so a test can tell
+// which fan-out channel admitted what: channels A/B search the whole corpus (no scope),
+// channel C searches inside the documents the metadata filter selected.
+type metadataScopedRetriever struct {
+ scopes [][]string
+}
+
+func (r *metadataScopedRetriever) Retrieve(_ context.Context, req runtime.RetrieveRequest) ([]map[string]any, error) {
+ if len(req.DocScope) == 0 {
+ return nil, nil
+ }
+ r.scopes = append(r.scopes, req.DocScope)
+ return []map[string]any{{"id": "meta-1", "doc_id": "d1", "content": "Culdcept tower height is 42 m."}}, nil
+}
+
+// fanoutMetadataResolver is a scripted MetadataResolver: the push-down always answers with
+// the configured documents, the flattened view answers with metas, and the filters/logic it
+// was handed are recorded.
+type fanoutMetadataResolver struct {
+ ids []string
+ metas common.MetaData
+ calls int
+ filters []map[string]any
+ logic string
+ // docMeta backs the metadata_search context block (doc_id → fields).
+ docMeta map[string]map[string]any
+}
+
+func (m *fanoutMetadataResolver) FilterDocIDsByMetaPushdown(_ context.Context, _ []string, filters []map[string]any, logic string) ([]string, bool) {
+ m.calls++
+ m.filters = filters
+ m.logic = logic
+ return m.ids, true
+}
+
+func (m *fanoutMetadataResolver) GetFlattedMetaByKBs(context.Context, []string) (common.MetaData, error) {
+ return m.metas, nil
+}
+
+// MetadataForDocIDs answers the metadata_search context block. These tests observe the
+// selection, not the context block, so it stays empty unless a case sets docMeta.
+func (m *fanoutMetadataResolver) MetadataForDocIDs(context.Context, []string, []string) (map[string]map[string]any, error) {
+ return m.docMeta, nil
+}
+
+// TestFanoutSearchMetadataChannelUsesCatalogFields pins channel C end to end with the
+// catalog-driven vocabulary: the model reads a sub-question and names a field the SESSION
+// offers — here `author`, not the historical hard-coded `title` — and the retrieval runs inside
+// the documents that field matches, even though the corpus-wide channels returned nothing.
+func TestFanoutSearchMetadataChannelUsesCatalogFields(t *testing.T) {
+ ctx := context.Background()
+ r := &metadataScopedRetriever{}
+ resolver := &fanoutMetadataResolver{ids: []string{"d1"}}
+ mdl := &scriptedModel{}
+ mdl.push(`{"filters": [[{"key":"author","op":"contains","value":"OmiyaSoft"}]]}`)
+ deps := RAGTools{
+ Search: runtime.SearchDeps{
+ Backend: r,
+ KbIDs: []string{"kb1"},
+ HasEmbedder: true,
+ MetadataResolver: resolver,
+ },
+ Model: mdl,
+ Tools: &runtime.Toolset{ThinkingMode: "high", MetadataFields: &runtime.MetadataCatalog{
+ Keys: []string{"author", "title"},
+ }},
+ }
+ st := &AgenticState{KB: &runtime.Kbinfos{}}
+
+ added := FanoutSearch(ctx, deps, st, []string{"what is the Culdcept tower height"}, 8, 60, true)
+
+ if added != 1 || len(st.KB.Chunks) != 1 {
+ t.Fatalf("added = %d, pool = %d; want the metadata channel's one hit", added, len(st.KB.Chunks))
+ }
+ if got := runtime.ChunkIDOf(st.KB.Chunks[0]); got != "meta-1" {
+ t.Errorf("pooled chunk = %q, want the channel-C hit", got)
+ }
+ if len(mdl.seen) != 1 {
+ t.Errorf("model calls = %d, want exactly ONE extraction call for the batch", len(mdl.seen))
+ }
+ if resolver.calls != 1 || resolver.logic != "or" {
+ t.Errorf("resolver calls = %d logic = %q, want one OR-combined lookup", resolver.calls, resolver.logic)
+ }
+ if len(resolver.filters) != 1 || resolver.filters[0]["key"] != "author" ||
+ resolver.filters[0]["op"] != "contains" || resolver.filters[0]["value"] != "OmiyaSoft" {
+ t.Errorf("filters = %v, want the author-contains condition the catalog offered", resolver.filters)
+ }
+ if len(r.scopes) != 1 || len(r.scopes[0]) != 1 || r.scopes[0][0] != "d1" {
+ t.Errorf("scoped requests = %v, want the search restricted to the matched document", r.scopes)
+ }
+}
+
+// TestFanoutSearchSkipsMetadataChannelUnlessAsked pins the gate: the rewrite round (and
+// every other caller that does not ask for the metadata channel) must not pay the
+// entity-extraction model call, and must not resolve documents.
+func TestFanoutSearchSkipsMetadataChannelUnlessAsked(t *testing.T) {
+ ctx := context.Background()
+ r := &metadataScopedRetriever{}
+ resolver := &fanoutMetadataResolver{ids: []string{"d1"}}
+ mdl := &scriptedModel{}
+ mdl.push(`{"entities": [["Culdcept"]]}`)
+ deps := RAGTools{
+ Search: runtime.SearchDeps{
+ Backend: r,
+ KbIDs: []string{"kb1"},
+ HasEmbedder: true,
+ MetadataResolver: resolver,
+ },
+ Model: mdl,
+ }
+ st := &AgenticState{KB: &runtime.Kbinfos{}}
+
+ if added := FanoutSearch(ctx, deps, st, []string{"what is the Culdcept tower height"}, 8, 60, false); added != 0 {
+ t.Errorf("added = %d, want 0 without the metadata channel", added)
+ }
+ if len(mdl.seen) != 0 {
+ t.Errorf("model calls = %d, want none: entity extraction must not run", len(mdl.seen))
+ }
+ if resolver.calls != 0 || len(r.scopes) != 0 {
+ t.Errorf("resolver calls = %d scoped searches = %d, want none", resolver.calls, len(r.scopes))
+ }
+}
+
+// TestFanoutSearchGatesMetadataChannelOnFilterableFields pins the gate that keeps Channel C
+// from being pure cost: a session whose catalog offers NO filterable field pays neither the
+// extraction call nor one guaranteed-empty scoped retrieval per sub-question.
+//
+// The gate is the field VOCABULARY, not one particular field: a catalog that offers `author`
+// and no `title` is perfectly usable, because the model may name whichever field the
+// sub-question fits. Nothing is baked in as a fallback — a caller that wired no toolset, or a
+// session whose catalog is empty because the dataset carries no metadata, is skipped too.
+func TestFanoutSearchGatesMetadataChannelOnFilterableFields(t *testing.T) {
+ ctx := context.Background()
+ cases := []struct {
+ name string
+ cat *runtime.MetadataCatalog
+ noToolset bool
+ want int
+ }{
+ {
+ name: "wired session, no metadata",
+ cat: nil,
+ want: 0,
+ },
+ {
+ name: "wired session, empty catalog",
+ cat: &runtime.MetadataCatalog{},
+ want: 0,
+ },
+ {
+ name: "caller wired no tool surface",
+ noToolset: true,
+ want: 0,
+ },
+ {
+ name: "catalog offers a non-title field",
+ cat: &runtime.MetadataCatalog{
+ Keys: []string{"author"},
+ Samples: map[string][]runtime.MetadataSample{"author": {{Value: "OmiyaSoft", Docs: 1}}},
+ },
+ want: 1,
+ },
+ }
+ for _, c := range cases {
+ r := &metadataScopedRetriever{}
+ resolver := &fanoutMetadataResolver{ids: []string{"d1"}}
+ mdl := &scriptedModel{}
+ mdl.push(`{"filters": [[{"key":"author","op":"contains","value":"OmiyaSoft"}]]}`)
+ deps := RAGTools{
+ Search: runtime.SearchDeps{
+ Backend: r,
+ KbIDs: []string{"kb1"},
+ HasEmbedder: true,
+ MetadataResolver: resolver,
+ },
+ Model: mdl,
+ }
+ if !c.noToolset {
+ deps.Tools = &runtime.Toolset{ThinkingMode: "high", MetadataFields: c.cat}
+ }
+ st := &AgenticState{KB: &runtime.Kbinfos{}}
+
+ added := FanoutSearch(ctx, deps, st, []string{"what is the Culdcept tower height"}, 8, 60, true)
+ if added != c.want {
+ t.Errorf("%s: added = %d, want %d", c.name, added, c.want)
+ }
+ if c.want == 0 {
+ if len(mdl.seen) != 0 {
+ t.Errorf("%s: model calls = %d, want none — the extraction must not run when no field is filterable", c.name, len(mdl.seen))
+ }
+ if resolver.calls != 0 || len(r.scopes) != 0 {
+ t.Errorf("%s: resolver calls = %d scoped searches = %d, want none", c.name, resolver.calls, len(r.scopes))
+ }
+ }
+ }
+}
+
+// TestParseFanoutFiltersShapesAndGuards pins the reply shapes and the guards. The guard set is
+// what keeps the channel from filtering on something the session never offered: a field outside
+// the catalog (which is also how the blacklist holds here), a WIDENING operator, a copied
+// sub-question, an answer sentence, an over-long value, a duplicate and an empty value are all
+// dropped, and at most three conditions survive per sub-question.
+func TestParseFanoutFiltersShapesAndGuards(t *testing.T) {
+ fanouts := []string{"q one", "q two"}
+ allowed := map[string]bool{"title": true, "author": true}
+
+ // Positional arrays: one condition-group per sub-question, in order.
+ got := parseFanoutFilters(`{"filters": [[`+
+ `{"key":"title","op":"contains","value":"Alpha Corp"},`+
+ `{"key":"author","op":"=","value":"Beta"}],`+
+ `[{"key":"title","op":"contains","value":"Gamma"}]]}`, fanouts, allowed)
+ if len(got) != 2 || len(got[0]) != 2 || got[0][0]["value"] != "Alpha Corp" ||
+ got[0][1]["key"] != "author" || got[1][0]["value"] != "Gamma" {
+ t.Errorf("positional = %v", got)
+ }
+
+ // Dict form matched by sub-question text: the unmatched one stays empty.
+ got = parseFanoutFilters(`{"filters": [{"sub_question":"q two","filters":[{"key":"title","op":"contains","value":"Delta"}]}]}`, fanouts, allowed)
+ if len(got[0]) != 0 || len(got[1]) != 1 || got[1][0]["value"] != "Delta" {
+ t.Errorf("by-text = %v", got)
+ }
+
+ // A flat list of conditions is read POSITIONALLY: one condition per sub-question, so a
+ // single-condition list only fills the first one.
+ got = parseFanoutFilters(`{"filters": [{"key":"author","op":"=","value":"Alice"}]}`, fanouts, allowed)
+ if len(got[0]) != 1 || got[0][0]["value"] != "Alice" || len(got[1]) != 0 {
+ t.Errorf("flat = %v", got)
+ }
+
+ // Guards: an unoffered field, a widening operator, an over-long value, an 11-word value, a
+ // prose/citation value, a duplicate and an empty value are dropped; the cap is three.
+ long := strings.Repeat("x", metadataValueMaxChars+1)
+ reply := `{"filters": [[` +
+ `{"key":"question_id","op":"contains","value":"444"},` +
+ `{"key":"title","op":"not contains","value":"Alpha"},` +
+ `{"key":"title","op":"contains","value":"` + long + `"},` +
+ `{"key":"title","op":"contains","value":"one two three four five six seven eight nine ten eleven"},` +
+ `{"key":"title","op":"contains","value":"see https://example.com"},` +
+ `{"key":"title","op":"contains","value":"Dup"},` +
+ `{"key":"title","op":"contains","value":"Dup"},` +
+ `{"key":"title","op":"contains","value":""},` +
+ `{"key":"title","op":"contains","value":"e1"},` +
+ `{"key":"title","op":"contains","value":"e2"},` +
+ `{"key":"title","op":"contains","value":"e3"},` +
+ `{"key":"title","op":"contains","value":"e4"}]]}`
+ got = parseFanoutFilters(reply, fanouts, allowed)
+ want := []string{"Dup", "e1", "e2"}
+ if len(got[0]) != len(want) {
+ t.Fatalf("guarded = %v, want %v", got[0], want)
+ }
+ for i, w := range want {
+ if got[0][i]["value"] != w {
+ t.Errorf("guarded[%d] = %v, want %q", i, got[0][i], w)
+ }
+ }
+
+ // 'in' keeps its list (the value SET) and needs at least one entry.
+ got = parseFanoutFilters(`{"filters": [[{"key":"title","op":"in","value":["A","B"]}]]}`, fanouts, allowed)
+ if len(got[0]) != 1 {
+ t.Fatalf("in = %v, want one condition", got)
+ }
+ if list, ok := got[0][0]["value"].([]any); !ok || len(list) != 2 {
+ t.Errorf("in value = %v, want the list kept", got[0][0]["value"])
+ }
+ if got := parseFanoutFilters(`{"filters": [[{"key":"title","op":"in","value":[]}]]}`, fanouts, allowed); len(got[0]) != 0 {
+ t.Errorf("empty 'in' = %v, want it dropped", got[0])
+ }
+
+ // No JSON at all: nothing parsed, and the fan-outs are still order-aligned.
+ got = parseFanoutFilters("no json here", fanouts, allowed)
+ if len(got) != 2 || len(got[0]) != 0 || len(got[1]) != 0 {
+ t.Errorf("non-JSON = %v", got)
+ }
+}
+
+// TestExtractFanoutFiltersDegradesToNothing pins the best-effort contract: no chat model, no
+// sub-questions, or a reply with nothing usable all mean NO conditions (nil, the channel
+// simply skipped), never a failure.
+func TestExtractFanoutFiltersDegradesToNothing(t *testing.T) {
+ if got := ExtractFanoutFilters(context.Background(), RAGTools{}, []string{"q"}); got != nil {
+ t.Errorf("filters = %v, want nil without a model", got)
+ }
+ if got := ExtractFanoutFilters(context.Background(), RAGTools{Model: &scriptedModel{}}, nil); got != nil {
+ t.Errorf("filters = %v, want nil without sub-questions", got)
+ }
+ if got := ExtractFanoutFilters(context.Background(), RAGTools{Model: &scriptedModel{}}, []string{"q"}); got != nil {
+ t.Errorf("filters = %v, want nil when the caller wired no tool surface", got)
+ }
+}
+
+// slotResearchWithMetadataTool builds one action session whose tool executor is the REAL
+// metadata_search executor, so a tool call made by the model is observed end to end: the
+// resolver records the filter and answers with the documents the selector returns.
+func slotResearchWithMetadataTool(resolver *fanoutMetadataResolver, retriever *corpusRetriever, cat *runtime.MetadataCatalog, replies []*runtime.ModelReply) (*AgenticState, *runtime.Kbinfos, *fakeModel) {
+ kb := &runtime.Kbinfos{}
+ sd := runtime.SearchDeps{
+ Backend: retriever,
+ KbIDs: []string{"kb1"},
+ HasEmbedder: true,
+ KB: kb,
+ MetadataResolver: resolver,
+ }
+ mdl := &fakeModel{replies: replies}
+ st := &AgenticState{
+ Question: "who wrote it?",
+ KB: kb,
+ SlotTable: runtime.NewState([]runtime.Variable{
+ {ID: 0, Type: "aspect", QuestionClues: []string{"who wrote it?"}},
+ }, 0, nil),
+ }
+ deps := runtime.SessionDeps{
+ Model: mdl,
+ Tools: &runtime.Toolset{
+ ThinkingMode: "high",
+ MetadataFields: cat,
+ Exec: runtime.NewSearchExecutor(sd, runtime.RunRequest{ThinkingMode: "high"}),
+ },
+ KB: kb,
+ }
+ RunSlotResearchPass(context.Background(), context.Background(), deps, "who wrote it?", st, 60)
+ return st, kb, mdl
+}
+
+// TestSlotResearchSessionUsesCatalogFieldForMetadataSearch pins the whole chain in one run:
+// the catalog advertises `author`, the model spends its one metadata_search on that field,
+// and the real executor resolves documents by it. The resolver seeing the author condition
+// is the observation that the advertised field is the one that reaches the index — the
+// schema, the tool call and the executor all agreeing.
+func TestSlotResearchSessionUsesCatalogFieldForMetadataSearch(t *testing.T) {
+ resolver := &fanoutMetadataResolver{
+ ids: []string{"doc-culdcept"},
+ metas: common.MetaData{"author": {"Alice": {"doc-culdcept"}}, "title": {"Culdcept History": {"doc-culdcept"}}},
+ }
+ cat := &runtime.MetadataCatalog{
+ Keys: []string{"author", "title"},
+ Samples: map[string][]runtime.MetadataSample{"author": {{Value: "Alice", Docs: 1}}},
+ }
+ _, _, mdl := slotResearchWithMetadataTool(resolver, &corpusRetriever{}, cat, []*runtime.ModelReply{
+ {
+ Content: "Narrowing by author.",
+ ToolCalls: []runtime.ToolCall{{
+ ID: "call_0",
+ Name: "metadata_search",
+ Args: map[string]any{
+ "filters": []any{map[string]any{"key": "author", "op": "contains", "value": "Alice"}},
+ },
+ }},
+ },
+ {Content: `<state>{"new_states": []}</state>`},
+ })
+
+ if resolver.calls == 0 {
+ t.Fatal("the session never resolved documents by metadata; the advertised field did not reach the executor")
+ }
+ if len(resolver.filters) != 1 || resolver.filters[0]["key"] != "author" {
+ t.Errorf("resolver filters = %v, want the author condition the catalog advertised", resolver.filters)
+ }
+ if mdl.calls < 2 {
+ t.Errorf("model calls = %d, want the session to have continued after the tool result", mdl.calls)
+ }
+}
+
+// TestSlotResearchSessionSurvivesMetadataSearchWithoutMetadata pins the requirement that a
+// metadata-free dataset must not derail the run: the index carries NO field, the model still
+// spends its one metadata_search on `title`, and the session must read that as a query-level
+// miss and carry on with the next tool — never abort, never disable the run.
+func TestSlotResearchSessionSurvivesMetadataSearchWithoutMetadata(t *testing.T) {
+ resolver := &fanoutMetadataResolver{} // no ids, no metas: a dataset with no metadata
+ retriever := &corpusRetriever{}
+ // No catalog: the shipped title-only schema is what the model sees.
+ _, _, mdl := slotResearchWithMetadataTool(resolver, retriever, nil, []*runtime.ModelReply{
+ {
+ Content: "Trying a title filter.",
+ ToolCalls: []runtime.ToolCall{{
+ ID: "call_0",
+ Name: "metadata_search",
+ Args: map[string]any{
+ "filters": []any{map[string]any{"key": "title", "op": "contains", "value": "Culdcept"}},
+ },
+ }},
+ },
+ {
+ Content: "Falling back to retrieval.",
+ ToolCalls: []runtime.ToolCall{{
+ ID: "call_1",
+ Name: "retrieve",
+ Args: map[string]any{"query": []any{"who wrote it?"}},
+ }},
+ },
+ {Content: `<state>{"new_states": []}</state>`},
+ })
+
+ // The metadata miss must not have stopped the loop: the session went on to retrieval.
+ if len(retriever.calls) == 0 {
+ t.Fatalf("retriever calls = 0; a metadata-free dataset aborted the session instead of degrading to retrieval")
+ }
+ if mdl.calls < 3 {
+ t.Errorf("model calls = %d, want the session to have kept running to its own empty patch", mdl.calls)
+ }
+ if resolver.calls != 0 {
+ t.Errorf("push-down calls = %d, want none: an unknown key is rejected before the index is touched", resolver.calls)
+ }
+}
diff --git a/internal/rag/agentic-rag/graph_fanout.go b/internal/rag/agentic-rag/graph_fanout.go
index abac734274..23be1972bb 100644
--- a/internal/rag/agentic-rag/graph_fanout.go
+++ b/internal/rag/agentic-rag/graph_fanout.go
@@ -157,12 +157,289 @@ func ExpandFanouts(ctx context.Context, deps RAGTools, question string) []string
return fanouts
}
+// Metadata pre-filter channel: the metadata conditions a sub-question's wording supports.
+//
+// Channel C exists because a sub-question that NAMES a document is better served by
+// pre-filtering the document set by metadata and searching inside it than by another
+// whole-corpus round: the whole-corpus round has to rank the named document against every
+// other one, and on a large corpus it loses. The conditions come from ONE chat call for the
+// whole fan-out batch, and every value must look like a SHORT NAME — a copied sub-question or
+// an answer would make the condition match nothing.
+
+// fanoutFilterPrompt is the ONE chat call the pre-search metadata channel makes per batch: it
+// turns each named thing a sub-question carries into a metadata condition over the dataset's
+// OWN fields. The vocabulary is injected under AVAILABLE METADATA (see MetadataCatalog.Render),
+// so the channel is not pinned to any single field: a dataset whose content fields are called
+// `title` / `file_name` / `topic` is filtered on whichever of them the sub-question names.
+const fanoutFilterPrompt = `For each numbered search sub-question below, decide whether it NAMES something a ` +
+ `document's metadata would carry — a document title or file name, an author, an organisation, a place, ` +
+ `an event — and turn each named thing into ONE metadata condition {key, op, value} over the fields ` +
+ `listed under AVAILABLE METADATA. ` +
+ `Use the field whose meaning fits the named thing; prefer "contains" unless the whole value is named. ` +
+ `The value MUST be copied EXACTLY as it appears — keep underscores, punctuation and file extensions ` +
+ `as written, never re-normalise them (a stored file name keeps its underscores; a stored title keeps ` +
+ `its spaces) — and when the sub-question's wording matches one of the listed values, use that listed ` +
+ `value verbatim. Keep each value under 10 words: never copy the whole sub-question, never answer it. ` +
+ `Emit ONLY conditions you are confident about: a sub-question that names no such thing gets an EMPTY ` +
+ `list — do not invent a condition just to fill one. ` +
+ `Respond with JSON only: {"filters": [[{"key":"...","op":"...","value":"..."}], ...]} — one ` +
+ `condition-array per sub-question, in the SAME ORDER as the sub-questions, JSON only, no prose.`
+
+const (
+ // metadataValueMaxWords / metadataValueMaxChars are the guard on a filter value taken from a
+ // sub-question: a long string is a copied sub-question or an answer.
+ metadataValueMaxWords = 10
+ metadataValueMaxChars = 80
+ // metadataMaxConditions caps the conditions taken from one sub-question.
+ metadataMaxConditions = 3
+ // fanoutMetadataQuota is the metadata channel's per-query quota. Modest like the
+ // semantic quota: the channel's hits are only as good as the extraction.
+ fanoutMetadataQuota = 4
+)
+
+// fanoutMetadataOps are the operators the pre-search channel may use: the POSITIVE
+// value-matching subset of the tool's operators. The channel's contract is "the sub-question
+// NAMED something, so look inside the documents whose metadata matches it"; `not contains` /
+// `empty` / `not empty` are deliberately absent because they WIDEN a document set — the
+// opposite of what a pre-filter is for, and a model reaching for one would scope the channel's
+// search to everything it was meant to narrow.
+var fanoutMetadataOps = map[string]bool{
+ "=": true,
+ "contains": true,
+ "start with": true,
+ "end with": true,
+ "in": true,
+}
+
+// fanoutMetadataVocabulary returns the field vocabulary the pre-search channel may use, and
+// whether the channel can run at all.
+//
+// The vocabulary IS the session's metadata catalog — the same "declared ∪ observed − blacklist"
+// set the metadata_search tool advertises. There is no field name baked in anywhere: a caller
+// that wired no toolset, or a session whose catalog is empty because the dataset carries no
+// metadata, has no vocabulary to offer and the channel is skipped. (It would otherwise pay the
+// extraction call and then run one guaranteed-empty scoped retrieval per sub-question.)
+//
+// The vocabulary is the catalog's FULL rendering, value samples included. That is deliberate:
+// this channel has no feedback loop — a condition that matches nothing is a silent miss, not a
+// retry — so the model must be able to pick the exact form the index stores. A guessed value
+// that differs from the stored one by case, punctuation or an underscore normalisation is the
+// observed failure (measured 2026-09-20: `file_name contains "02 Endpoint Isolation ..."` found
+// nothing while the stored value kept its underscores).
+func fanoutMetadataVocabulary(deps RAGTools) (string, map[string]bool, bool) {
+ if deps.Tools == nil {
+ return "", nil, false
+ }
+ cat := deps.Tools.MetadataFields
+ if cat == nil || cat.Empty() {
+ return "", nil, false
+ }
+ allowed := make(map[string]bool, len(cat.Keys))
+ for _, k := range cat.Keys {
+ allowed[k] = true
+ }
+ return cat.Render(), allowed, true
+}
+
+// fanoutValueLooksUsable reports whether a filter value is a short name rather than a copied
+// sub-question or an answer.
+func fanoutValueLooksUsable(value string) bool {
+ s := strings.TrimSpace(value)
+ if s == "" {
+ return false
+ }
+ low := strings.ToLower(s)
+ for _, mark := range fanoutAnswerMarks {
+ if strings.Contains(low, mark) {
+ return false
+ }
+ }
+ // The character cap counts code points: a byte-based cap would reject a legitimate CJK
+ // value well below the 80-character limit.
+ return utf8.RuneCountInString(s) <= metadataValueMaxChars && len(strings.Fields(s)) <= metadataValueMaxWords
+}
+
+// fanoutCondition validates one model-written condition against the dataset's offered fields
+// and the pre-search operators, returning nil when it must be dropped.
+//
+// The value is coerced by runtime.NormalizeMetadataValue — the same function the
+// metadata_search tool uses — so a condition means the same thing on either path.
+func fanoutCondition(raw any, allowed map[string]bool) map[string]any {
+ m, ok := raw.(map[string]any)
+ if !ok {
+ return nil
+ }
+ key := strings.TrimSpace(fmt.Sprint(m["key"]))
+ op := strings.TrimSpace(fmt.Sprint(m["op"]))
+ if !allowed[key] || !fanoutMetadataOps[op] {
+ return nil
+ }
+ value := runtime.NormalizeMetadataValue(m["value"], op)
+ if op == "in" {
+ list, ok := value.([]any)
+ if !ok || len(list) == 0 {
+ return nil
+ }
+ for _, item := range list {
+ if !fanoutValueLooksUsable(fmt.Sprint(item)) {
+ return nil
+ }
+ }
+ return map[string]any{"key": key, "op": op, "value": value}
+ }
+ text := strings.TrimSpace(fmt.Sprint(value))
+ if value == nil || text == "" || text == "<nil>" || !fanoutValueLooksUsable(text) {
+ return nil
+ }
+ return map[string]any{"key": key, "op": op, "value": text}
+}
+
+// parseFanoutFilters extracts up to metadataMaxConditions conditions per sub-question from a
+// model reply, order-aligned with fanouts.
+//
+// Accepts {"filters": [[{...}, ...], ...]} (preferred), a flat {"filters": [{...}, ...]} (read
+// positionally: one condition per sub-question), or
+// {"filters": [{"sub_question": ..., "filters": [...]}]} matched by text. Conditions are
+// validated by fanoutCondition: an unknown field, a non-pre-search operator, an over-long value
+// or a duplicate is dropped. Sub-questions left with no condition simply skip the channel.
+func parseFanoutFilters(text string, fanouts []string, allowed map[string]bool) [][]map[string]any {
+ out := make([][]map[string]any, len(fanouts))
+ data, ok := extractJSONObject(text).(map[string]any)
+ if !ok {
+ return out
+ }
+ items := asSliceOfAny(data["filters"])
+ if len(items) == 0 {
+ return out
+ }
+ byText := map[string][]map[string]any{}
+ var positional [][]map[string]any
+ for _, it := range items {
+ switch v := it.(type) {
+ case map[string]any:
+ // A sub-question key means the object groups its own conditions; otherwise the
+ // object IS one condition.
+ if _, grouped := v["sub_question"]; grouped || v["fanout"] != nil || v["filters"] != nil {
+ conds := fanoutConditions(asSliceOfAny(v["filters"]), allowed)
+ sq := ""
+ if sv := v["sub_question"]; sv != nil {
+ sq = strings.TrimSpace(fmt.Sprint(sv))
+ }
+ if sq == "" && v["fanout"] != nil {
+ sq = strings.TrimSpace(fmt.Sprint(v["fanout"]))
+ }
+ if sq != "" {
+ byText[sq] = conds
+ }
+ positional = append(positional, conds)
+ continue
+ }
+ positional = append(positional, fanoutConditions([]any{v}, allowed))
+ case []any:
+ positional = append(positional, fanoutConditions(v, allowed))
+ }
+ }
+ for i, fq := range fanouts {
+ var raw []map[string]any
+ if len(byText) > 0 {
+ raw = byText[fq]
+ } else if i < len(positional) {
+ raw = positional[i]
+ }
+ seen := make(map[string]bool, len(raw))
+ cleaned := make([]map[string]any, 0, metadataMaxConditions)
+ for _, c := range raw {
+ fingerprint := fmt.Sprint(c["key"], c["op"], c["value"])
+ if seen[fingerprint] {
+ continue
+ }
+ seen[fingerprint] = true
+ cleaned = append(cleaned, c)
+ if len(cleaned) >= metadataMaxConditions {
+ break
+ }
+ }
+ out[i] = cleaned
+ }
+ return out
+}
+
+// fanoutConditions validates a raw condition list, dropping everything fanoutCondition rejects.
+func fanoutConditions(raw []any, allowed map[string]bool) []map[string]any {
+ out := make([]map[string]any, 0, len(raw))
+ for _, item := range raw {
+ if c := fanoutCondition(item, allowed); c != nil {
+ out = append(out, c)
+ }
+ }
+ return out
+}
+
+// ExtractFanoutFilters maps each sub-question to the metadata conditions its wording supports:
+// ONE chat call for the whole batch.
+//
+// The conditions name fields from the session's catalog, so the channel filters on the dataset's
+// real fields instead of a hard-coded one. Only sub-questions with at least one valid condition
+// are returned, and any failure — no model, no filterable field, a model error, an unparseable
+// reply — yields nil so the metadata channel is simply skipped for this round; pre-search is
+// never blocked by it.
+func ExtractFanoutFilters(ctx context.Context, deps RAGTools, fanouts []string) map[string][]map[string]any {
+ queries := make([]string, 0, len(fanouts))
+ for _, f := range fanouts {
+ if q := strings.TrimSpace(f); q != "" {
+ queries = append(queries, q)
+ }
+ }
+ if len(queries) == 0 || deps.Model == nil {
+ return nil
+ }
+ fields, allowed, ok := fanoutMetadataVocabulary(deps)
+ if !ok {
+ return nil
+ }
+ listed := make([]string, 0, len(queries))
+ for i, q := range queries {
+ listed = append(listed, fmt.Sprintf("%d. %s", i+1, q))
+ }
+ reply, err := deps.Model.Complete(ctx, []schema.Message{
+ *schema.SystemMessage(fanoutFilterPrompt + "\n\nAVAILABLE FIELDS:\n" + fields),
+ *schema.UserMessage("Sub-questions:\n" + strings.Join(listed, "\n")),
+ }, nil)
+ if err != nil {
+ _LOG.Printf("[Prefetch] metadata filter extraction failed; skipping the metadata channel: %v", err)
+ return nil
+ }
+ filterSets := parseFanoutFilters(reply.Content, queries, allowed)
+ out := make(map[string][]map[string]any, len(queries))
+ for i, q := range queries {
+ if len(filterSets[i]) > 0 {
+ out[q] = filterSets[i]
+ }
+ }
+ if len(out) == 0 {
+ // Nothing survived the guards: report "no conditions" as nil, the same shape every
+ // other failure of this best-effort call returns, so the caller needs no special case.
+ //
+ // The reply is logged here because this is the channel's SILENT outcome — a condition
+ // rejected by the guards contributes nothing and produces no other trace, so without the
+ // raw reply a miss is indistinguishable from "the model named nothing". (Empty
+ // condition-lists are the COMMON, correct answer to a question that names no metadata
+ // value; a non-empty reply here means the guards rejected something.) Newlines are
+ // flattened so the reply stays one log line.
+ flat := strings.ReplaceAll(truncateRunes(reply.Content, 300), "\n", " ")
+ _LOG.Printf("[Prefetch] metadata channel produced no usable condition; reply was: %s", flat)
+ return nil
+ }
+ _LOG.Printf("[Prefetch] metadata filters: %v", out)
+ return out
+}
+
// Phase 2: programmatic fan-out search.
// FanoutSearch: the
// programmatic multi-query prefetch that seeds the snippet pool.
//
-// It is a DUAL-CHANNEL search, and the two channels are deliberately different:
+// It is a three-channel search, and the channels are deliberately different:
//
// - channel A (exact): a keyword BM25 round over a wide pool (top_n=60) whose
// hits are then narrowed by the query's own terms — the precision path. A
@@ -172,16 +449,23 @@ func ExpandFanouts(ctx context.Context, deps RAGTools, question string) []string
// pool. These are quarantined to a small per-fan-out quota
// (fanoutSemanticQuota) because bypassing narrowing is what makes them
// low-precision.
+// - channel C (metadata pre-filter): the sub-question's wording is turned into
+// metadata conditions over the SESSION's catalog fields, those documents are
+// pre-selected, and the retrieval runs INSIDE that subset (see
+// ExtractFanoutFilters). Best effort: no usable condition — or no metadata
+// resolver — simply skips the channel. Only runs when the caller asks for it
+// (useMetadata): the FIRST prefetch round, where the sub-questions are the
+// planner's raw wording; a rewrite round's queries are already targeted at a gap.
//
// Collapsing them into one call loses the split, and with it the ability to
// admit a paraphrase-only match without letting it displace an exact one.
//
// Admission order is the point: every fan-out's channel A is admitted before any
-// fan-out's channel B, so an exact hit from a later fan-out outranks a semantic
-// hit from an earlier one.
+// fan-out's channel B, and C takes whatever room is left — its hits are the ones
+// A/B did not reach at all.
//
// Returns the number of NEW snippets admitted to the pool.
-func FanoutSearch(ctx context.Context, deps RAGTools, st *AgenticState, queries []string, topN, capacity int) int {
+func FanoutSearch(ctx context.Context, deps RAGTools, st *AgenticState, queries []string, topN, capacity int, useMetadata bool) int {
if len(queries) == 0 || st.KB == nil {
return 0
}
@@ -227,6 +511,20 @@ func FanoutSearch(ctx context.Context, deps RAGTools, st *AgenticState, queries
type fanoutPair struct {
exact []map[string]any
semantic []map[string]any
+ metadata []map[string]any
+ }
+ // Channel C's conditions: ONE chat call for the whole batch, and only when the metadata
+ // channel was asked for AND the dataset offers at least one filterable field. Without that
+ // second gate a metadata-free dataset pays the extraction call and then runs one
+ // guaranteed-empty scoped retrieval per sub-question, every round. A failure yields nil and
+ // the channel is skipped.
+ var filtersByQuery map[string][]map[string]any
+ if useMetadata {
+ if _, _, ok := fanoutMetadataVocabulary(deps); ok {
+ filtersByQuery = ExtractFanoutFilters(ctx, deps, qs)
+ } else {
+ _LOG.Printf("[Prefetch] metadata channel skipped — the dataset offers no filterable metadata field")
+ }
}
pairs := make([]fanoutPair, 0, len(qs))
for _, q := range qs {
@@ -235,8 +533,8 @@ func FanoutSearch(ctx context.Context, deps RAGTools, st *AgenticState, queries
return 0
default:
}
- exact, semantic := fanoutSearchQuery(ctx, sd, q, capPerQuery)
- pairs = append(pairs, fanoutPair{exact: exact, semantic: semantic})
+ exact, semantic, metadata := fanoutSearchQuery(ctx, sd, q, capPerQuery, filtersByQuery[q])
+ pairs = append(pairs, fanoutPair{exact: exact, semantic: semantic, metadata: metadata})
}
added := 0
@@ -342,7 +640,7 @@ func FanoutSearch(ctx context.Context, deps RAGTools, st *AgenticState, queries
}
}
}
- // Channel A across every fan-out first, then channel B.
+ // Channel A across every fan-out first, then channel B, then channel C.
for _, p := range pairs {
if admit(p.exact) {
return added
@@ -353,12 +651,18 @@ func FanoutSearch(ctx context.Context, deps RAGTools, st *AgenticState, queries
return added
}
}
+ for _, p := range pairs {
+ if admit(p.metadata) {
+ return added
+ }
+ }
return added
}
-// fanoutSearchQuery runs one fan-out's two channels. It only retrieves; the
-// caller admits the results.
-func fanoutSearchQuery(ctx context.Context, sd runtime.SearchDeps, fq string, capPerQuery int) (exact, semantic []map[string]any) {
+// fanoutSearchQuery runs one fan-out's three channels. It only retrieves; the caller admits the
+// results. filters are the sub-question's metadata conditions (key/op/value over the session's
+// catalog); an empty list skips channel C.
+func fanoutSearchQuery(ctx context.Context, sd runtime.SearchDeps, fq string, capPerQuery int, filters []map[string]any) (exact, semantic, metadata []map[string]any) {
terms := runtime.QueryToTerms(fq)
keyed := runtime.FanoutKeyedTerms(terms)
termList := keyed
@@ -403,5 +707,34 @@ func fanoutSearchQuery(ctx context.Context, sd runtime.SearchDeps, fq string, ca
break
}
}
- return exact, semantic
+
+ // Channel C — metadata pre-filter: documents are pre-selected by the metadata conditions the
+ // sub-question's wording supports (OR across them), and the retrieval runs INSIDE that
+ // subset. The conditions name the session catalog's fields, and they are the SAME shape the
+ // metadata_search tool takes, so a condition means the same thing on either path.
+ // runtime.MetadataSearch is inert without a resolver, and the caller only spends the
+ // extraction call when the dataset offers a filterable field (see fanoutMetadataVocabulary).
+ if len(filters) > 0 {
+ seenAB := make(map[string]bool, len(exact)+len(semantic))
+ for _, c := range exact {
+ seenAB[runtime.ChunkIDOf(c)] = true
+ }
+ for _, c := range semantic {
+ seenAB[runtime.ChunkIDOf(c)] = true
+ }
+ hits, _ := runtime.MetadataSearch(ctx, sd, runtime.SearchParams{
+ Question: fq,
+ TopN: capPerQuery,
+ }, filters, "or")
+ for _, c := range hits {
+ if seenAB[runtime.ChunkIDOf(c)] {
+ continue
+ }
+ metadata = append(metadata, c)
+ if len(metadata) >= fanoutMetadataQuota {
+ break
+ }
+ }
+ }
+ return exact, semantic, metadata
}
diff --git a/internal/rag/agentic-rag/runtime/action_session.go b/internal/rag/agentic-rag/runtime/action_session.go
index 39efa70dac..fee5baf7bb 100644
--- a/internal/rag/agentic-rag/runtime/action_session.go
+++ b/internal/rag/agentic-rag/runtime/action_session.go
@@ -968,14 +968,34 @@ var (
Function: ToolFunction{
Name: "retrieve",
Description: `WHEN TO CALL: you know or suspect exact surface terms in the corpus (names, titles, codes, phrases) — the first recall pass; cover different facets.` +
- `HOW IT WORKS: keyword recall FIRST, then the pattern is applied to what came back — ` + "`A.*B`" + ` (A then B, anything between) matches only inside the passages its operands recalled, and the RAREST operand bounds it: put the rare word first. A FULL recall page was truncated.` +
- `ONE STRING, MANY TERMS: ` + "`A|B|C`" + ` recalls each term in ONE call — synonyms belong in one string, not one call each.` +
- `ENUMERATING A SET: probe the NAMES themselves, alternated with |, 4-6 per query. Hits are members; guess the next batch yourself rather than stopping at what you hold.` +
+ `HOW IT WORKS: keyword recall FIRST, then the pattern applies to what came back — ` + "`A.*B`" + ` (A then B, anything between) matches only inside the passages its operands recalled, and the RAREST operand bounds it: put the rare word first. A FULL recall page was truncated.` +
+ `ONE STRING, MANY TERMS: ` + "`A|B|C`" + ` recalls each in ONE call — synonyms go in one string.` +
+ `ENUMERATING A SET: probe the NAMES themselves, alternated with |, 4-6 per query; hits are members — guess the next batch yourself.` +
`DO NOT CALL: for a whole document (list_chunks); when no surface word matches (search_chunks).` +
- `ARGUMENTS: query — array of 1-3 strings; only a query's first ~10 snippets survive; doc_scope is NOT declared.` +
+ `ARGUMENTS: query — array of 1-3 strings (only the first ~10 snippets survive); doc_scope — optional doc_ids from an earlier tool result, to search INSIDE them only.` +
`OUTPUT: Exact-term snippets with doc_id and chunk id. ok = new evidence; redundant = seen.` +
- `IF IT FAILS: a miss on an exact-term probe means the corpus lacks that term — in an enumeration that is a RESULT (record it as not a member, probe the next). redundant = stop and emit a state patch.`,
- Parameters: arrayParam("", 1, 3),
+ `IF IT FAILS: a miss on an exact-term probe means the corpus lacks that term — in an enumeration that is a RESULT (probe the next). redundant = stop and emit a state patch.`,
+ Parameters: map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "query": map[string]any{
+ "type": "array",
+ "items": map[string]any{"type": "string"},
+ "minItems": 1,
+ "maxItems": 3,
+ },
+ // Decoding lives in toolDocScope, which retrieve and graph_explore
+ // share: the scope is ceiling-ed by the session's DocScope and
+ // verified against the bound datasets (resolveDocScope), so a
+ // stale or out-of-dataset doc_id cannot widen the search.
+ "doc_scope": map[string]any{
+ "type": "array",
+ "items": map[string]any{"type": "string"},
+ "description": "optional doc_ids from a prior tool result (metadata_search / navigate_tree / list_chunks), to search inside those documents only",
+ },
+ },
+ "required": []string{"query"},
+ },
},
}
@@ -1016,6 +1036,50 @@ var (
},
}
+ metadataSearchToolSpec = ToolSpec{
+ Type: "function",
+ Function: ToolFunction{
+ Name: "metadata_search",
+ Description: `WHEN TO CALL: SELECT the document set by METADATA before searching — call it when the question names explicit entities (a person, a time, a place) or any concrete name a metadata field would carry (a title, a file name, an author, a date), or needs a named subset. Use ONLY the AVAILABLE METADATA fields; prefer 'contains' with a distinctive substring. ` +
+ `CALL AT MOST ONCE PER DIRECTION, then spend the returned doc_ids: list_chunks(doc_id), navigate_structure(doc_id, query), or retrieve(query, doc_scope=[ids]). ` +
+ `DO NOT CALL: nothing names a document/subset; you already hold a doc_id; counting or enumerating. ` +
+ `ARGUMENTS: filters — [{key, value, op}] over the AVAILABLE METADATA fields; op — see enum; logic 'and'|'or'. String ops take ONE keyword, one call per keyword; 'in' takes a list; 'empty' none. Example (one day): [{key: 'update_time', op: 'start with', value: '2026-09-20'}]. ` +
+ `OUTPUT: doc_ids — the handle other tools take — plus each matched document's metadata as CONTEXT ONLY, never an argument to pass on. No passages. ok = selected; miss = nothing matched. ` +
+ `IF IT FAILS: 'no documents match' — shorten the substring or use search_chunks; do not retry.`,
+ Parameters: map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ "filters": map[string]any{
+ "type": "array",
+ "minItems": 1,
+ "items": map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ // The field enum is rendered PER SESSION from the dataset's
+ // catalog (see metadataSearchSpecForCatalog); the shipped
+ // parameter deliberately carries no enum, so no field is
+ // advertised as available before the dataset says it is.
+ "key": paramString("a metadata field of this dataset — one of those listed under AVAILABLE METADATA"),
+ "value": map[string]any{
+ "type": []any{"string", "array", "null"},
+ "description": "the keyword/value to match: ONE string keyword for contains / = / start with / " +
+ "end with / not contains (call once per keyword); a list for in / not in; nothing for empty / not empty. " +
+ "Copy a value exactly as the dataset stores it — never re-normalise it. " +
+ "A 'time' field stores 'YYYY-MM-DD HH:MM:SS', so filter ONE day with op 'start with' and the bare " +
+ "'YYYY-MM-DD' — '=' never matches a stored time.",
+ },
+ "op": paramEnum("the comparison", "=", "contains", "not contains", "start with", "end with", "in", "empty", "not empty"),
+ },
+ "required": []string{"key", "op"},
+ },
+ },
+ "logic": paramEnum("how several filters combine, default and", "and", "or"),
+ },
+ "required": []string{"filters"},
+ },
+ },
+ }
+
webSearchToolSpec = ToolSpec{
Type: "function",
Function: ToolFunction{
@@ -1140,11 +1204,74 @@ func paramEnum(desc string, values ...string) map[string]any {
return map[string]any{"type": "string", "enum": values, "description": desc}
}
+const (
+ // maxToolDescriptionRunes is the per-tool description budget TestToolSpecsHavePlaybookSections
+ // pins.
+ maxToolDescriptionRunes = 1200
+)
+
+// metadataSearchSpecForCatalog renders the metadata_search schema for a session's catalog: the
+// `key` enum becomes the fields the dataset offers, so a model can name any of them. The
+// description is dataset-independent (it points at AVAILABLE METADATA and never names a field),
+// so it needs no per-session rewriting and cannot outgrow its budget.
+//
+// An empty (or nil) catalog returns the base spec UNCHANGED: no field is advertised at all —
+// the `key` stays the free-form string the shipped spec carries, which is also how an empty
+// enum is avoided (some providers reject `"enum": []`).
+//
+// The base spec is the shared package-level ToolMap entry, so every map this touches is
+// COPIED — mutating them in place would leak one session's dataset fields into every other
+// session (and into a session's concurrent rag calls, see Toolset.mu).
+func metadataSearchSpecForCatalog(base ToolSpec, cat *MetadataCatalog) ToolSpec {
+ if cat == nil || cat.Empty() {
+ return base
+ }
+
+ baseProps, _ := base.Function.Parameters["properties"].(map[string]any)
+ filters, _ := baseProps["filters"].(map[string]any)
+ items, _ := filters["items"].(map[string]any)
+ itemProps, _ := items["properties"].(map[string]any)
+ if baseProps == nil || filters == nil || items == nil || itemProps == nil {
+ // The schema shape changed under us; the unpatched spec is still valid.
+ return base
+ }
+
+ patchedItemProps := copyAnyMap(itemProps)
+ patchedItemProps["key"] = paramEnum("one of this dataset's metadata fields (see AVAILABLE METADATA)", cat.Keys...)
+
+ patchedItems := copyAnyMap(items)
+ patchedItems["properties"] = patchedItemProps
+
+ patchedFilters := copyAnyMap(filters)
+ patchedFilters["items"] = patchedItems
+
+ patchedProps := copyAnyMap(baseProps)
+ patchedProps["filters"] = patchedFilters
+
+ patchedParams := copyAnyMap(base.Function.Parameters)
+ patchedParams["properties"] = patchedProps
+
+ out := base
+ out.Function.Parameters = patchedParams
+ return out
+}
+
+// copyAnyMap shallow-copies a JSON-shaped map, so a patched tool spec shares no map with
+// ToolMap.
+func copyAnyMap(m map[string]any) map[string]any {
+ out := make(map[string]any, len(m))
+ for k, v := range m {
+ out[k] = v
+ }
+ return out
+}
+
// ToolMap is the multi-tool registry.
// executeTool dispatches by name; add a tool by registering its schema here.
var ToolMap = map[string]ToolSpec{
"retrieve": retrieveToolSpec,
"search_chunks": searchChunksToolSpec,
+ "metadata_search": metadataSearchToolSpec,
"list_chunks": listChunksToolSpec,
"navigate_tree": navigateTreeToolSpec,
"navigate_structure": navigateStructureToolSpec,
@@ -1185,6 +1312,11 @@ type Toolset struct {
// HasWebSearch reports whether a web provider is configured. When false,
// web_search is hidden from the surface rather than merely discouraged.
HasWebSearch bool
+ // MetadataFields is the session's metadata catalog (see MetadataCatalogFor). It supplies
+ // the metadata_search key enum and rides the session seed, so a filter can name the fields
+ // the dataset really carries. Nil or empty advertises no field at all — there is no field
+ // name baked into the shipped schema to fall back on.
+ MetadataFields *MetadataCatalog
// DisabledTools holds tools proven unavailable this session (no compiled
// structure of their kind).
DisabledTools map[string]bool
@@ -1228,6 +1360,11 @@ func (t *Toolset) ActiveToolSpecs() []ToolSpec {
continue
}
if s, ok := ToolMap[name]; ok {
+ if name == "metadata_search" {
+ // Per-session rewrite: the catalog names the dataset's real fields. It
+ // returns the shared spec untouched when there is no catalog.
+ s = metadataSearchSpecForCatalog(s, t.MetadataFields)
+ }
out = append(out, s)
}
}
@@ -1778,6 +1915,11 @@ type SessionState struct {
SearchQueries []string
// SkippedDup counts near-duplicate retrievals suppressed so far.
SkippedDup int
+ // MetadataSearchUsed is the metadata_search ONE-SHOT: the tool SELECTS a document
+ // set, so a second call within the SAME direction is blocked with a nudge (Python's
+ // _metadata_search_used). It survives across the session's turns but not across
+ // directions — each direction runs its own session.
+ MetadataSearchUsed bool
// ToolStrikes counts dataset-level empties per tool.
ToolStrikes map[string]int
// ToolOutcomes is the audit trail of (name, status, reason, metrics).
@@ -1991,6 +2133,18 @@ func (s *SessionState) toolNode(ctx context.Context) error {
}}))
continue
}
+ // metadata_search ONE-SHOT guard: block any 2nd call within this direction.
+ // The tool SELECTS a document set — once the ids are in hand there is nothing a
+ // second call could add, and re-issuing it would burn the direction's turns
+ // re-applying a filter that is already in force.
+ if c.Name == "metadata_search" && s.MetadataSearchUsed {
+ _LOG.Printf("[Action Session] blocking 2nd metadata_search this direction (one-shot guard): %s", RenderToolArgs(c.Args))
+ s.Messages = appendMessages(s.Messages, toolMessage(c.ID, []any{map[string]any{
+ "kind": "metadata_search",
+ "note": "metadata_search is a ONE-SHOT metadata selector and was ALREADY used this direction. Spend the doc_ids it returned — list_chunks(doc_id), navigate_structure(doc_id, query), or retrieve(query, doc_scope=[...]) — do NOT call metadata_search again this direction.",
+ }}))
+ continue
+ }
// Unknown tool name — never execute it; answer with a correction so the
// model can recover. Models usually emit the XML protocol tags (state /
// answer) as tool names; they belong in the reply body as plain text.
@@ -2017,6 +2171,11 @@ func (s *SessionState) toolNode(ctx context.Context) error {
seenQueries = append(seenQueries, q)
}
evidenceIDs = append(evidenceIDs, oc.EvidenceIDs...)
+ if c.Name == "metadata_search" {
+ // Used whatever the status: the guard is about not re-filtering, not about
+ // the filter having matched.
+ s.MetadataSearchUsed = true
+ }
chunks := append([]any(nil), oc.Payload...)
// ── Policy: act on WHAT happened, not just on payload size ──────────
@@ -3544,6 +3703,17 @@ func RunActionSession(ctx context.Context, deps SessionDeps, direction string, p
}
}
+ // AVAILABLE METADATA: the dataset's real metadata fields, so a metadata_search filter
+ // can name one the dataset actually carries. Omitted entirely when the catalog is
+ // empty (no metadata, an unreadable index, or no resolver wired), which keeps a
+ // metadata-free corpus's prompt exactly as it shipped.
+ if deps.Tools != nil && deps.Tools.MetadataFields != nil {
+ if block := deps.Tools.MetadataFields.Render(); block != "" {
+ seedUser += "\n\n" + block
+ _LOG.Printf("[Action Session] metadata catalog in the seed (%d field(s))", len(deps.Tools.MetadataFields.Keys))
+ }
+ }
+
// ALREADY RETRIEVED: surface the evidence already in the shared pool so the model fills
// slots from it instead of re-retrieving the same ground. Without this the ReAct loop
// repeatedly searches evidence it already holds.
diff --git a/internal/rag/agentic-rag/runtime/action_session_test.go b/internal/rag/agentic-rag/runtime/action_session_test.go
index c59e502661..93e7cd1c2e 100644
--- a/internal/rag/agentic-rag/runtime/action_session_test.go
+++ b/internal/rag/agentic-rag/runtime/action_session_test.go
@@ -1087,12 +1087,14 @@ var playbookAnchors = []string{"WHEN TO CALL", "DO NOT CALL", "ARGUMENTS", "OUTP
// executorSupportedParams lists the params the executor actually consumes per
// tool (mirrors _EXECUTOR_SUPPORTED). The schema MUST NOT declare any param
// outside this set — otherwise the model is told to fill an argument the runtime
-// silently ignores (the list_chunks(chunk_ids) ghost bug). Note: doc_scope /
-// keywords are supported by the executor but intentionally NOT declared in the
-// schema (keep the description honest with the implementation).
+// silently ignores (the list_chunks(chunk_ids) ghost bug). Note: keywords are
+// supported by the executor but intentionally NOT declared in the schema (keep
+// the description honest with the implementation); doc_scope IS declared on the
+// two tools that consume it (retrieve, graph_explore).
var executorSupportedParams = map[string]map[string]bool{
"retrieve": {"query": true, "doc_scope": true},
"search_chunks": {"query": true},
+ "metadata_search": {"filters": true, "logic": true},
"list_chunks": {"doc_id": true},
"navigate_tree": {"query": true, "keywords": true},
"navigate_structure": {"doc_id": true, "query": true, "kind": true},
@@ -1100,8 +1102,8 @@ var executorSupportedParams = map[string]map[string]bool{
"web_search": {"query": true},
}
-// TestToolSpecsHavePlaybookSections pins the PR: each of the 7 tools documents
-// the 5-section contract, within the token budget (cap 1200 chars).
+// TestToolSpecsHavePlaybookSections pins the PR: every tool documents the
+// 5-section contract, within the token budget (cap 1200 chars).
func TestToolSpecsHavePlaybookSections(t *testing.T) {
for _, name := range allTools {
desc := ToolMap[name].Function.Description
@@ -1117,7 +1119,7 @@ func TestToolSpecsHavePlaybookSections(t *testing.T) {
}
// TestActiveToolSpecsToolSurface pins mode -> exposed tool count: low=0,
-// medium/high=7, ultra=8, web-hidden=6.
+// medium/high=8, ultra=9, web-hidden=7.
func TestActiveToolSpecsToolSurface(t *testing.T) {
cases := []struct {
mode string
@@ -1125,10 +1127,10 @@ func TestActiveToolSpecsToolSurface(t *testing.T) {
want int
}{
{"low", true, 0},
- {"medium", true, 7},
- {"high", true, 7},
- {"ultra", true, 8},
- {"medium", false, 6},
+ {"medium", true, 8},
+ {"high", true, 8},
+ {"ultra", true, 9},
+ {"medium", false, 7},
}
for _, c := range cases {
ts := &Toolset{ThinkingMode: c.mode, HasWebSearch: c.web}
@@ -1392,3 +1394,93 @@ func TestDigestShowsAPassageWholeEnoughToNameSomeone(t *testing.T) {
t.Errorf("digest cap = %d, want at least the 1200 an admitted passage carries", evidenceDigestChars)
}
}
+
+// seedRecordingModel captures the messages of every completion call, so a test can assert
+// what the session seed actually carried. The canned reply is an empty state patch, which
+// ends the session after its first turn.
+type seedRecordingModel struct{ seen [][]schema.Message }
+
+func (m *seedRecordingModel) Complete(_ context.Context, msgs []schema.Message, _ []ToolSpec) (*ModelReply, error) {
+ cp := make([]schema.Message, len(msgs))
+ copy(cp, msgs)
+ m.seen = append(m.seen, cp)
+ return &ModelReply{Content: `<state>{"new_states": []}</state>`}, nil
+}
+
+// TestRunActionSessionSeedCarriesMetadataCatalog pins the seed half of the catalog: the
+// session is TOLD which fields its dataset carries, so a metadata_search filter can name
+// one without a trial-and-error call first. Without a catalog the block is absent — a
+// metadata-free corpus's prompt stays exactly as it shipped.
+func TestRunActionSessionSeedCarriesMetadataCatalog(t *testing.T) {
+ cases := []struct {
+ name string
+ cat *MetadataCatalog
+ want bool
+ }{
+ {
+ name: "catalog",
+ cat: &MetadataCatalog{
+ Keys: []string{"author"},
+ Samples: map[string][]MetadataSample{"author": {{Value: "Alice", Docs: 1}}},
+ },
+ want: true,
+ },
+ {name: "no metadata", cat: nil, want: false},
+ }
+ for _, c := range cases {
+ mdl := &seedRecordingModel{}
+ deps := SessionDeps{
+ Tools: &Toolset{ThinkingMode: "high", MetadataFields: c.cat},
+ Model: mdl,
+ KB: &Kbinfos{},
+ }
+ RunActionSession(context.Background(), deps, "who wrote it", State{State: []Variable{{ID: 0, Type: "aspect"}}}, 60, "", nil, nil)
+ if len(mdl.seen) == 0 {
+ t.Fatalf("%s: the session never called the model", c.name)
+ }
+ var joined strings.Builder
+ for _, m := range mdl.seen[0] {
+ // Only the USER message is the seed: the system prompt names AVAILABLE
+ // METADATA in its playbook, so scanning every message would pass vacuously.
+ if m.Role != schema.User {
+ continue
+ }
+ joined.WriteString(m.Content)
+ joined.WriteString("\n")
+ }
+ seed := joined.String()
+ if got := strings.Contains(seed, "AVAILABLE METADATA"); got != c.want {
+ t.Errorf("%s: seed carries AVAILABLE METADATA = %v, want %v:\n%s", c.name, got, c.want, seed)
+ }
+ if c.want && !strings.Contains(seed, "author") {
+ t.Errorf("%s: the seed block must name the dataset's field:\n%s", c.name, seed)
+ }
+ }
+}
+
+// TestActiveToolSpecsDoesNotMutateSharedToolMap pins the copy-then-patch contract: the
+// catalog rewrites the spec a SESSION sees, never the package-level ToolMap entry every
+// other session (and every concurrent rag call in this one) reads from. Rendered under
+// -race as well, so the maps a patch touches cannot be written concurrently.
+func TestActiveToolSpecsDoesNotMutateSharedToolMap(t *testing.T) {
+ cat := &MetadataCatalog{Keys: []string{"author", "title"}, Samples: map[string][]MetadataSample{}}
+
+ var wg sync.WaitGroup
+ for i := 0; i < 16; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ ts := &Toolset{ThinkingMode: "high", MetadataFields: cat}
+ _ = ts.ActiveToolSpecs()
+ }()
+ }
+ wg.Wait()
+
+ shipped := ToolMap["metadata_search"]
+ if got := metadataKeyEnum(shipped); len(got) != 0 {
+ t.Errorf("shipped key enum = %v, want NO field baked into the shared spec", got)
+ }
+ if desc, _ := metadataKeyParam(shipped)["description"].(string); strings.Contains(desc, "this dataset's metadata fields") {
+ t.Errorf("a session rewrite leaked its catalog wording into the shipped key parameter: %q", desc)
+ }
+}
diff --git a/internal/rag/agentic-rag/runtime/config.go b/internal/rag/agentic-rag/runtime/config.go
index 41435dae3d..728bde379d 100644
--- a/internal/rag/agentic-rag/runtime/config.go
+++ b/internal/rag/agentic-rag/runtime/config.go
@@ -32,6 +32,7 @@ import "strings"
var allTools = []string{
"retrieve",
"search_chunks",
+ "metadata_search",
"list_chunks",
"navigate_tree",
"navigate_structure",
diff --git a/internal/rag/agentic-rag/runtime/grep_sed_narrow.go b/internal/rag/agentic-rag/runtime/grep_sed_narrow.go
index 0ded3da32b..5bdeaf2fa2 100644
--- a/internal/rag/agentic-rag/runtime/grep_sed_narrow.go
+++ b/internal/rag/agentic-rag/runtime/grep_sed_narrow.go
@@ -745,6 +745,15 @@ func ReachTermsOf(query string) []string {
// - still no hit -> narrowing abandoned, originals returned (matched=false);
// - when matched, a total-length budget is distributed across chunks.
//
+// Table exemption: chunks that look like tables (HTML <table>/<tr> markup, or >=3 pipe
+// rows — see IsTableChunk) are NEVER narrowed, by any caller of this engine, and are
+// exempt from the per-chunk/total char budget. Two reasons, both measured: the term
+// window either cuts the <table> opening tag, and then the downstream table view
+// refuses the fragment ("<table" not present) so the model is handed a partial
+// raw-HTML row dump; or it keeps the tag and silently drops the remaining rows, and row
+// order/coverage is exactly what decides table answers (a rank row can sit at 62% of a
+// 14.7K-char table). Tables come back VERBATIM.
+//
// Never raises.
func NarrowByTerms(chunks []map[string]any, terms []string, fallbackTerms []string, keywords string, context NarrowContext, maxOutCharsPerChunk, maxOutTotalChars int) NarrowResult {
before := clampInt(context.Before, 0, maxContext)
@@ -770,18 +779,27 @@ func NarrowByTerms(chunks []map[string]any, terms []string, fallbackTerms []stri
return NarrowResult{Kept: narrowed, Stats: stats}
}
+ // Whole-table exemption, computed once and reused by the char-budget pass below
+ // (that pass preserves order and length, so the two lists stay aligned).
+ // false = "this chunk was NOT narrowed" -> returned verbatim.
+ tableFlags := make([]bool, len(chunks))
+ for i, c := range chunks {
+ tableFlags[i] = IsTableChunk(c)
+ }
+
run := func(active []*regexp.Regexp) ([]map[string]any, []bool, int) {
var kept []map[string]any
var flags []bool
matched := 0
- for _, c := range chunks {
+ for i, c := range chunks {
raw := ChunkTextOf(c)
- if charLen(raw) <= minNarrowChars {
- // Short chunk: kept whole. Flagged as matched so it still
- // participates in the total-budget distribution; the text is unchanged and
- // "highlight" is popped.
+ if tableFlags[i] || charLen(raw) <= minNarrowChars {
+ // Table or short chunk: kept whole. The flag is false for a table so the
+ // char-budget pass below recognises it; a short chunk is flagged as
+ // matched so it still participates in the total-budget distribution. The
+ // text is unchanged and "highlight" is popped.
kept = append(kept, withNarrowedText(c, raw))
- flags = append(flags, true)
+ flags = append(flags, !tableFlags[i])
continue
}
text, ok := execOnText(raw, active, before, after, maxOutCharsPerChunk)
@@ -821,7 +839,18 @@ func NarrowByTerms(chunks []map[string]any, terms []string, fallbackTerms []stri
perChunk := max(200, min(maxOutCharsPerChunk, maxOutTotalChars/max(1, len(kept))))
acc := 0
var trimmed []map[string]any
- for _, c := range kept {
+ for i, c := range kept {
+ if tableFlags[i] {
+ // Tables are indivisible and exempt from the char budget: a head
+ // slice keeps the header and the first rows and drops the answer row,
+ // and the dropped rows carry no marker, so the model reads a
+ // truncated table as a complete one. The budget therefore bounds
+ // PROSE only; a large table can push the narrowed prose set past
+ // maxOutTotalChars, which is the intended trade
+ // (readability/correctness > char cap).
+ trimmed = append(trimmed, c)
+ continue
+ }
t := ChunkTextOf(c)
room := maxOutTotalChars - acc
if room <= 0 {
diff --git a/internal/rag/agentic-rag/runtime/grep_sed_narrow_test.go b/internal/rag/agentic-rag/runtime/grep_sed_narrow_test.go
index 5f7a9428a1..f7fb6dd3c4 100644
--- a/internal/rag/agentic-rag/runtime/grep_sed_narrow_test.go
+++ b/internal/rag/agentic-rag/runtime/grep_sed_narrow_test.go
@@ -324,3 +324,53 @@ func TestReachLineNamesWhatTheBatchMissed(t *testing.T) {
t.Errorf("empty reach = %q, want no line", got)
}
}
+
+// TestNarrowByTermsExemptsTables pins the whole-table exemption: a table chunk is never
+// re-windowed and never char-trimmed, even when the total budget is tight.
+//
+// A head slice keeps the header and the first rows and drops the answer row, and the
+// dropped rows carry no marker — the model then reads a truncated table as a complete
+// one. The budget therefore bounds prose only.
+func TestNarrowByTermsExemptsTables(t *testing.T) {
+ prose := strings.Repeat("曹操引军退去诸将皆惊。", 12) +
+ "关羽赶上荀正交马一合砍荀正于马下。" +
+ strings.Repeat("河北军大半落水。", 12)
+ table := "<table>" + strings.Repeat("<tr><td>19</td><td>Danilo</td></tr>", 100) + "</table>"
+ chunks := []map[string]any{
+ {"id": "c1", "content_with_weight": prose},
+ {"id": "c2", "content_with_weight": table},
+ }
+
+ res := NarrowByTerms(chunks, []string{"荀正"}, nil, "", NarrowContext{Before: 1, After: 0}, 200, 500)
+
+ if !res.Stats.Matched {
+ t.Fatalf("stats = %+v, want the prose hit to set matched", res.Stats)
+ }
+ if len(res.Kept) != 2 {
+ t.Fatalf("kept = %d chunk(s), want 2", len(res.Kept))
+ }
+ if got := ChunkTextOf(res.Kept[1]); got != table {
+ t.Errorf("table came back %d chars, want the %d-char original verbatim", len(got), len(table))
+ }
+ if got := ChunkTextOf(res.Kept[0]); len(got) >= len(prose) {
+ t.Errorf("prose kept %d of %d bytes: it was not narrowed", len(got), len(prose))
+ }
+}
+
+// TestNarrowByTermsKeepsTableOnlyInputVerbatim pins the boundary: with nothing but
+// tables there is nothing to locate, so narrowing reports no match and every table is
+// returned untouched (the caller must not read that as an answer failure).
+func TestNarrowByTermsKeepsTableOnlyInputVerbatim(t *testing.T) {
+ table := "| Rank | Rider |\n|---|---|\n" +
+ strings.Repeat("| 19 | Danilo |\n", 40)
+ chunks := []map[string]any{{"id": "c1", "content_with_weight": table}}
+
+ res := NarrowByTerms(chunks, []string{"Danilo"}, nil, "", NarrowContext{Before: 1, After: 0}, 200, 500)
+
+ if res.Stats.Matched {
+ t.Errorf("stats = %+v, want matched=false for a table-only input", res.Stats)
+ }
+ if len(res.Kept) != 1 || ChunkTextOf(res.Kept[0]) != table {
+ t.Errorf("kept = %d chunk(s), want the table verbatim", len(res.Kept))
+ }
+}
diff --git a/internal/rag/agentic-rag/runtime/orchestrator/sufficient_context.go b/internal/rag/agentic-rag/runtime/orchestrator/sufficient_context.go
index 15bc18eae7..2e9743f3ba 100644
--- a/internal/rag/agentic-rag/runtime/orchestrator/sufficient_context.go
+++ b/internal/rag/agentic-rag/runtime/orchestrator/sufficient_context.go
@@ -408,14 +408,19 @@ func scaChunkText(c map[string]any) string {
}
// boundedExcerpt: a bounded window around a
-// term from the draft. Table text is returned whole.
+// term from the draft. Table text is returned whole, serialized to Markdown.
func boundedExcerpt(text, hints string, maxChars int) string {
text = strings.TrimSpace(text)
if text == "" {
return ""
}
if isTableText(text) {
- return text
+ // The SCA is a plain LLM call: raw <table>/<td> markup makes it parse cells
+ // itself, and the same table costs ~61% more in HTML than in Markdown. The
+ // renderer never prunes rows (a row can carry the answer mid-table), so the
+ // SCA still sees the complete row set — just in a readable form. No-op for
+ // non-tables.
+ return runtime.TableViewOrRaw(text)
}
if maxChars < 80 {
maxChars = 80
diff --git a/internal/rag/agentic-rag/runtime/orchestrator/sufficient_context_test.go b/internal/rag/agentic-rag/runtime/orchestrator/sufficient_context_test.go
index 00e6b99981..5044892087 100644
--- a/internal/rag/agentic-rag/runtime/orchestrator/sufficient_context_test.go
+++ b/internal/rag/agentic-rag/runtime/orchestrator/sufficient_context_test.go
@@ -186,6 +186,21 @@ func TestBoundedExcerptKeepsTablesWhole(t *testing.T) {
if got := boundedExcerpt(table, "unrelated hint", 50); got != table {
t.Errorf("table text must be returned whole, got %q", got)
}
+ // An HTML table reaches the SCA as Markdown with every row: the SCA is a plain LLM
+ // call, so raw <table>/<td> markup makes it parse the cells itself, and the row set
+ // must stay complete (a row can carry the answer mid-table).
+ htmlTable := "<table><tr><th>Rank</th><th>Rider</th><th>Points</th></tr>" +
+ "<tr><td>19</td><td>Danilo</td><td>62</td></tr>" +
+ "<tr><td>20</td><td>Erik</td><td>61</td></tr></table>"
+ gotTable := boundedExcerpt(htmlTable, "unrelated hint", 50)
+ if strings.Contains(gotTable, "<td>") || strings.Contains(gotTable, "<table") {
+ t.Errorf("HTML table must reach the SCA as Markdown, got %q", gotTable)
+ }
+ for _, want := range []string{"| 19 |", "Danilo", "| 20 |", "Erik"} {
+ if !strings.Contains(gotTable, want) {
+ t.Errorf("anchor lost %q: %q", want, gotTable)
+ }
+ }
// Prose is windowed around a hint token.
prose := strings.Repeat("prefix filler ", 40) + "TARGET sentence here" + strings.Repeat(" trailing filler", 40)
got := boundedExcerpt(prose, "TARGET", 120)
diff --git a/internal/rag/agentic-rag/runtime/table_view.go b/internal/rag/agentic-rag/runtime/table_view.go
new file mode 100644
index 0000000000..b6491fb4bd
--- /dev/null
+++ b/internal/rag/agentic-rag/runtime/table_view.go
@@ -0,0 +1,274 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package runtime
+
+import (
+ "fmt"
+ "strings"
+
+ "golang.org/x/net/html"
+)
+
+// Render HTML tables into an LLM-friendly Markdown view.
+//
+// The compiled chunks of a Wikipedia-sourced KB carry machine-generated HTML tables.
+// Handing them over raw is both expensive and hard to read: a person infobox is 1-2K
+// chars of <table>/<td> markup, and a question like "how many children did all ten
+// nominees have" needs ten of them at once. The 2026-09-16 FRAMES attribution showed
+// the values ARE in the KB while the model still answers "cannot be determined" — the
+// numbers were never surfaced in a form it could aggregate.
+//
+// Two shapes, following the established practice for tables in RAG:
+//
+// - a two-column table (Wikipedia infobox) -> Markdown-KV lines: "Children: 3";
+// - any other table (ranked list, election results, timeline) -> a Markdown pipe
+// table carrying the header and EVERY row, because rank/order/completeness decide
+// those answers and row-window narrowing silently drops the answer row.
+//
+// Values are kept VERBATIM, entities/whitespace are collapsed, all-empty rows are
+// dropped. The raw HTML is never destroyed by this file: callers keep the original
+// chunk in the evidence pool (for citation) and use the view only for the
+// model-visible text.
+
+// tableViewMaxRows / tableViewMaxCharsPerTable are generous ceilings. A Wikipedia
+// election or standings table can run to 50K+ raw chars across 100+ rows; capping at
+// 4K chars / 60 rows silently dropped the answer row for exactly the
+// "large / multi-column" tables this renderer exists to serve (e.g. a 14.7K-char
+// standings table whose rank-19 row sat at ~62% of the table). The ceiling exists to
+// stop ONE pathological table from eating the whole evidence budget, not to truncate
+// normal tables — the caller still holds the raw chunk and can re-read it on demand.
+const (
+ tableViewMaxRows = 400
+ tableViewMaxCharsPerTable = 20000
+)
+
+// tableViewUnitTokens are the tokens of a Wikipedia table's "units" row — the row
+// right under the header that reads e.g. "No. | % | No. | %". It carries no data and
+// only pollutes a Markdown pipe table, so it is dropped before rendering.
+var tableViewUnitTokens = map[string]struct{}{
+ "": {}, "no.": {}, "no": {}, "n": {}, "%": {}, "#": {},
+ "—": {}, "-": {}, "•": {}, "·": {},
+}
+
+// RenderTables replaces every HTML table in text with a Markdown view.
+//
+// ok is false when text holds no renderable table, so callers keep their previous
+// behaviour untouched. A parse failure falls back to ok=false; this never panics and
+// never returns a partial view.
+func RenderTables(text string) (string, bool) {
+ if text == "" || !strings.Contains(strings.ToLower(text), "<table") {
+ return "", false
+ }
+ doc, err := html.Parse(strings.NewReader(text))
+ if err != nil {
+ return "", false
+ }
+ var views []string
+ var walk func(*html.Node)
+ walk = func(n *html.Node) {
+ if n.Type == html.ElementNode && n.Data == "table" {
+ if view := renderOneTable(n); view != "" {
+ views = append(views, view)
+ }
+ }
+ // Nested tables are visited too: the selector is recursive.
+ for c := n.FirstChild; c != nil; c = c.NextSibling {
+ walk(c)
+ }
+ }
+ walk(doc)
+ if len(views) == 0 {
+ return "", false
+ }
+ return strings.Join(views, "\n\n"), true
+}
+
+// TableViewOrRaw is RenderTables when it produces something, else the text unchanged.
+//
+// Small convenience for the call sites that only want "the best available
+// model-visible form of this chunk".
+func TableViewOrRaw(text string) string {
+ if view, ok := RenderTables(text); ok {
+ return view
+ }
+ return text
+}
+
+// renderOneTable renders a single <table>, or "" when it holds no renderable row.
+func renderOneTable(table *html.Node) string {
+ rows := tableRows(table)
+ if len(rows) == 0 {
+ return ""
+ }
+ // Infobox: two columns, a real key in the first cell and a value in the second (the
+ // photo-caption row has an empty second cell and is dropped here).
+ pairs := make([][2]string, 0, len(rows))
+ for _, r := range rows {
+ if len(r) == 2 && r[0] != "" && r[1] != "" {
+ pairs = append(pairs, [2]string{r[0], r[1]})
+ }
+ }
+ if len(pairs) >= 3 {
+ limit := min(len(pairs), tableViewMaxRows)
+ lines := make([]string, 0, limit)
+ for _, p := range pairs[:limit] {
+ lines = append(lines, p[0]+": "+p[1])
+ }
+ return truncateRunes(strings.Join(lines, "\n"), tableViewMaxCharsPerTable)
+ }
+
+ width := 0
+ for _, r := range rows {
+ width = max(width, len(r))
+ }
+ header := rows[0]
+ // Drop header-repeat / units rows so the pipe body starts at real data (otherwise a
+ // wide election table leads with a "No. | % | No. | %" junk row).
+ body := make([][]string, 0, len(rows))
+ for _, r := range rows[1:min(len(rows), tableViewMaxRows+1)] {
+ if !isUnitsRow(r) {
+ body = append(body, r)
+ }
+ }
+ if len(body) == 0 {
+ return ""
+ }
+ line := func(cells []string) string {
+ padded := make([]string, width)
+ for i := 0; i < width; i++ {
+ if i < len(cells) {
+ padded[i] = mdCell(cells[i])
+ }
+ }
+ return "| " + strings.Join(padded, " | ") + " |"
+ }
+
+ out := make([]string, 0, len(body)+3)
+ if caption := tableCaption(table); caption != "" {
+ out = append(out, "**Table: "+caption+"**")
+ }
+ out = append(out, line(header), "|"+strings.Repeat("---|", width))
+ for _, r := range body {
+ out = append(out, line(r))
+ }
+ if omitted := len(rows) - 1 - len(body); omitted > 0 {
+ out = append(out, fmt.Sprintf("... (%d more row(s) omitted)", omitted))
+ }
+ return truncateRunes(strings.Join(out, "\n"), tableViewMaxCharsPerTable)
+}
+
+// tableRows returns the non-empty rows of table as lists of cell strings.
+func tableRows(table *html.Node) [][]string {
+ var rows [][]string
+ for _, tr := range descendants(table, "tr") {
+ cells := descendants(tr, "td", "th")
+ if len(cells) == 0 {
+ continue
+ }
+ vals := make([]string, 0, len(cells))
+ nonEmpty := false
+ for _, cell := range cells {
+ v := cellText(cell)
+ if v != "" {
+ nonEmpty = true
+ }
+ vals = append(vals, v)
+ }
+ if nonEmpty {
+ rows = append(rows, vals)
+ }
+ }
+ return rows
+}
+
+// tableCaption returns the first <caption>'s text, "" when there is none.
+func tableCaption(table *html.Node) string {
+ captions := descendants(table, "caption")
+ if len(captions) == 0 {
+ return ""
+ }
+ return cellText(captions[0])
+}
+
+// cellText is the whitespace-collapsed cell text (tags stripped, entities resolved).
+//
+// Text pieces are joined with a single space and every whitespace run collapses to one
+// space, so a multi-line cell reads as one value. Comments carry no text and are
+// skipped.
+func cellText(cell *html.Node) string {
+ parts := make([]string, 0, 4)
+ var walk func(*html.Node)
+ walk = func(n *html.Node) {
+ switch n.Type {
+ case html.TextNode:
+ if s := strings.TrimSpace(n.Data); s != "" {
+ parts = append(parts, s)
+ }
+ return
+ case html.CommentNode, html.DoctypeNode:
+ return
+ }
+ for c := n.FirstChild; c != nil; c = c.NextSibling {
+ walk(c)
+ }
+ }
+ for c := cell.FirstChild; c != nil; c = c.NextSibling {
+ walk(c)
+ }
+ return strings.Join(strings.Fields(strings.Join(parts, " ")), " ")
+}
+
+// descendants lists the descendant elements named in names, in document order.
+func descendants(n *html.Node, names ...string) []*html.Node {
+ want := make(map[string]struct{}, len(names))
+ for _, name := range names {
+ want[name] = struct{}{}
+ }
+ var out []*html.Node
+ var walk func(*html.Node)
+ walk = func(x *html.Node) {
+ for c := x.FirstChild; c != nil; c = c.NextSibling {
+ if c.Type == html.ElementNode {
+ if _, ok := want[c.Data]; ok {
+ out = append(out, c)
+ }
+ }
+ walk(c)
+ }
+ }
+ walk(n)
+ return out
+}
+
+// isUnitsRow reports whether every cell of a row is a unit token — a row that carries
+// no data.
+func isUnitsRow(vals []string) bool {
+ if len(vals) == 0 {
+ return false
+ }
+ for _, v := range vals {
+ if _, ok := tableViewUnitTokens[strings.ToLower(strings.TrimSpace(v))]; !ok {
+ return false
+ }
+ }
+ return true
+}
+
+// mdCell escapes a value for a Markdown pipe cell (the delimiter must stay intact).
+func mdCell(value string) string {
+ return strings.NewReplacer(`\`, `\\`, "|", `\|`).Replace(value)
+}
diff --git a/internal/rag/agentic-rag/runtime/table_view_test.go b/internal/rag/agentic-rag/runtime/table_view_test.go
new file mode 100644
index 0000000000..1387ea251c
--- /dev/null
+++ b/internal/rag/agentic-rag/runtime/table_view_test.go
@@ -0,0 +1,219 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package runtime
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+)
+
+// TestTableViewInfoboxBecomesKeyValue pins the two-column shape: a Wikipedia infobox
+// renders as "key: value" lines, which is the form a field lookup reads best.
+func TestTableViewInfoboxBecomesKeyValue(t *testing.T) {
+ raw := `<table>
+ <tr><th>Born</th><td>1961</td></tr>
+ <tr><th>Children</th><td>3</td></tr>
+ <tr><th>Spouse</th><td>Jane Doe</td></tr>
+ </table>`
+ view, ok := RenderTables(raw)
+ if !ok {
+ t.Fatalf("RenderTables() reported no view for an infobox")
+ }
+ want := "Born: 1961\nChildren: 3\nSpouse: Jane Doe"
+ if view != want {
+ t.Errorf("infobox view = %q, want %q", view, want)
+ }
+}
+
+// TestTableViewRankedTableKeepsEveryRow pins the pipe shape: rank/order/completeness
+// decide ranked-table answers, so every data row must survive verbatim.
+func TestTableViewRankedTableKeepsEveryRow(t *testing.T) {
+ raw := `<table>
+ <tr><th>Rank</th><th>Name</th><th>Points</th></tr>
+ <tr><td>1</td><td>Alice</td><td>90</td></tr>
+ <tr><td>2</td><td>Bob</td><td>88</td></tr>
+ <tr><td>3</td><td>Carol</td><td>71</td></tr>
+ </table>`
+ view, ok := RenderTables(raw)
+ if !ok {
+ t.Fatalf("RenderTables() reported no view for a ranked table")
+ }
+ want := "| Rank | Name | Points |\n" +
+ "|---|---|---|\n" +
+ "| 1 | Alice | 90 |\n" +
+ "| 2 | Bob | 88 |\n" +
+ "| 3 | Carol | 71 |"
+ if view != want {
+ t.Errorf("ranked view = %q, want %q", view, want)
+ }
+}
+
+// TestTableViewCaptionAndUnitsRow covers the caption header and the units row a
+// Wikipedia table carries right under its header ("No. | % | No. | %"): the row holds
+// no data and would only pollute the pipe body.
+func TestTableViewCaptionAndUnitsRow(t *testing.T) {
+ raw := `<table>
+ <caption>Final standings</caption>
+ <tr><th>Rank</th><th>Rider</th><th>Points</th></tr>
+ <tr><td>No.</td><td>%</td><td>#</td></tr>
+ <tr><td>19</td><td>Danilo</td><td>62</td></tr>
+ </table>`
+ view, ok := RenderTables(raw)
+ if !ok {
+ t.Fatalf("RenderTables() reported no view")
+ }
+ if !strings.HasPrefix(view, "**Table: Final standings**\n") {
+ t.Errorf("view = %q, want the caption as a bold header line", view)
+ }
+ if !strings.Contains(view, "| 19 | Danilo | 62 |") {
+ t.Errorf("view = %q, want the rank-19 row kept", view)
+ }
+ if strings.Contains(view, "No.") || strings.Contains(view, "| % |") {
+ t.Errorf("view = %q, want the units row dropped", view)
+ }
+}
+
+// TestTableViewEscapesPipeAndBackslash pins the cell escaping: an unescaped "|" would
+// split the row into extra columns.
+func TestTableViewEscapesPipeAndBackslash(t *testing.T) {
+ raw := `<table>
+ <tr><th>Rank</th><th>Name</th><th>Note</th></tr>
+ <tr><td>1</td><td>Alice</td><td>a|b</td></tr>
+ <tr><td>2</td><td>Bob</td><td>c\d</td></tr>
+ </table>`
+ view, ok := RenderTables(raw)
+ if !ok {
+ t.Fatalf("RenderTables() reported no view")
+ }
+ if !strings.Contains(view, `| a\|b |`) {
+ t.Errorf("view = %q, want the pipe escaped", view)
+ }
+ if !strings.Contains(view, `| c\\d |`) {
+ t.Errorf("view = %q, want the backslash escaped", view)
+ }
+}
+
+// TestTableViewNoopForNonTable pins the no-op contract: plain text, markdown pipe
+// tables and table-less HTML must come back untouched so a caller can route every
+// chunk through TableViewOrRaw.
+func TestTableViewNoopForNonTable(t *testing.T) {
+ for _, raw := range []string{
+ "",
+ "plain prose with no markup at all",
+ "| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |",
+ "<p>html without a table</p>",
+ } {
+ if view, ok := RenderTables(raw); ok {
+ t.Errorf("RenderTables(%q) = (%q, true), want no view", raw, view)
+ }
+ if got := TableViewOrRaw(raw); got != raw {
+ t.Errorf("TableViewOrRaw(%q) = %q, want the raw text", raw, got)
+ }
+ }
+}
+
+// TestTableViewNoopForEmptyTable pins the all-empty path: a table whose rows carry no
+// text has nothing to render, so the caller keeps the raw chunk instead of receiving an
+// empty string.
+func TestTableViewNoopForEmptyTable(t *testing.T) {
+ for _, raw := range []string{
+ "<table></table>",
+ "<table><tr><td></td><td> </td></tr></table>",
+ "<table><tr><th>Rank</th></tr></table>",
+ } {
+ if view, ok := RenderTables(raw); ok {
+ t.Errorf("RenderTables(%q) = (%q, true), want no view", raw, view)
+ }
+ }
+}
+
+// TestTableViewTruncatedFragmentDoesNotPanic pins the fragment case the table
+// exemption exists for: a text window that cut the table mid-markup must never panic
+// and must never emit a partial pipe dump.
+func TestTableViewTruncatedFragmentDoesNotPanic(t *testing.T) {
+ for _, raw := range []string{
+ `<table><tr><td>only a fragment`,
+ `row text then a stray <table`,
+ `<tr><td>a</td></tr><tr><td>b</td></tr>`,
+ } {
+ if view, ok := RenderTables(raw); ok && strings.Contains(view, "\n") && !strings.Contains(raw, "<table") {
+ t.Errorf("RenderTables(%q) = %q: a table-less fragment must not render", raw, view)
+ }
+ if got := TableViewOrRaw(raw); got == "" && raw != "" {
+ t.Errorf("TableViewOrRaw(%q) returned an empty string", raw)
+ }
+ }
+}
+
+// TestTableViewJoinsMultipleTables pins the multi-table shape: a chunk that carries ten
+// nominee infoboxes hands the model ten blocks, separated by a blank line.
+func TestTableViewJoinsMultipleTables(t *testing.T) {
+ raw := `<table>
+ <tr><th>Born</th><td>1961</td></tr>
+ <tr><th>Children</th><td>3</td></tr>
+ <tr><th>Spouse</th><td>Jane</td></tr>
+ </table>
+ <table>
+ <tr><th>Born</th><td>1954</td></tr>
+ <tr><th>Children</th><td>2</td></tr>
+ <tr><th>Spouse</th><td>John</td></tr>
+ </table>`
+ view, ok := RenderTables(raw)
+ if !ok {
+ t.Fatalf("RenderTables() reported no view")
+ }
+ blocks := strings.Split(view, "\n\n")
+ if len(blocks) != 2 {
+ t.Fatalf("view = %q, want 2 blocks", view)
+ }
+ for i, block := range blocks {
+ if !strings.Contains(block, "Children: ") {
+ t.Errorf("block %d = %q, want a key-value view", i, block)
+ }
+ }
+}
+
+// TestTableViewCapsRowsAndReportsOmission pins the ceiling: an oversized table keeps
+// tableViewMaxRows data rows and SAYS how many were dropped, so a truncated table is
+// never read as a complete one.
+func TestTableViewCapsRowsAndReportsOmission(t *testing.T) {
+ var b strings.Builder
+ b.WriteString("<table><tr><th>Rank</th><th>Rider</th><th>Team</th></tr>")
+ for i := 1; i <= tableViewMaxRows+2; i++ {
+ fmt.Fprintf(&b, "<tr><td>%d</td><td>Rider %d</td><td>Team %d</td></tr>", i, i, i)
+ }
+ b.WriteString("</table>")
+
+ view, ok := RenderTables(b.String())
+ if !ok {
+ t.Fatalf("RenderTables() reported no view")
+ }
+ rows := 0
+ for _, line := range strings.Split(view, "\n") {
+ if strings.HasPrefix(line, "| ") {
+ rows++
+ }
+ }
+ // The header is a pipe line too, so the data rows are one fewer.
+ if rows != tableViewMaxRows+1 {
+ t.Errorf("rendered %d pipe lines, want %d data rows + 1 header", rows, tableViewMaxRows)
+ }
+ if !strings.HasSuffix(view, "... (2 more row(s) omitted)") {
+ t.Errorf("view tail = %q, want the omission marker", view[len(view)-40:])
+ }
+}
diff --git a/internal/rag/agentic-rag/runtime/tool_executor.go b/internal/rag/agentic-rag/runtime/tool_executor.go
index dee33a27be..725f1fe847 100644
--- a/internal/rag/agentic-rag/runtime/tool_executor.go
+++ b/internal/rag/agentic-rag/runtime/tool_executor.go
@@ -30,11 +30,13 @@ import (
"context"
"encoding/json"
"fmt"
+ "sort"
"strings"
"time"
"unicode/utf8"
"ragflow/internal/agent/runtime"
+ "ragflow/internal/common"
"ragflow/internal/service/nav"
)
@@ -213,6 +215,8 @@ func (e *searchExecutor) dispatch(ctx context.Context, name string, args map[str
switch name {
case "retrieve", "search_chunks", "grep_search", "grep_chunks":
return e.search(ctx, name, args)
+ case "metadata_search":
+ return e.metadataSearch(ctx, args)
case "navigate_tree":
return e.navigateTree(ctx, args)
case "navigate_structure":
@@ -1444,6 +1448,353 @@ func (e *searchExecutor) search(ctx context.Context, name string, args map[strin
}, nil
}
+// metadataKeysHintMax caps the available-keys list echoed back on a bad key.
+const metadataKeysHintMax = 30
+
+// metadataSearch is the metadata_search tool: a document-metadata SELECTOR. It resolves the
+// documents a filter matches and returns their doc_ids — it runs NO retrieval of its own.
+//
+// The ids are the whole output on purpose: a document handle can be spent on several
+// follow-up calls (list_chunks, navigate_structure, retrieve's doc_scope, and in ultra
+// mode graph_explore's doc_scope), whereas the passages an in-tool retrieval used to return
+// could only be read once. Keeping the selector free of retrieval is also what keeps its
+// answer "which documents match" independent of what the model meant to search for.
+//
+// The statuses are set explicitly rather than derived (see ReasonStatus): a missing filter
+// or a metadata key the dataset does not carry is MISS/bad_args — the model should change
+// the filter or switch tools, not read it as an infrastructure failure — a filter matching
+// no document is MISS/no_doc, and only a metadata-index read failure is ERROR/infra.
+// (Python folds a keys-query exception into "this dataset has no metadata", which tells the
+// model the wrong thing about the corpus.)
+func (e *searchExecutor) metadataSearch(ctx context.Context, args map[string]any) (ToolOutcome, error) {
+ // searchLogger falls back to the package logger: Logger is optional on SearchDeps,
+ // and a nil *log.Logger panics on the first Printf.
+ logger := searchLogger(e.deps)
+ badArgs := func(note string) (ToolOutcome, error) {
+ return ToolOutcome{
+ Payload: []any{map[string]any{"kind": "metadata_search", "note": note}},
+ Status: StatusMiss,
+ Reason: ReasonBadArgs,
+ Metrics: map[string]any{"docs": 0},
+ }, nil
+ }
+ filters := metadataFiltersOf(args)
+ if len(filters) == 0 {
+ return badArgs("No metadata conditions given. metadata_search needs at least one {key, value, op} filter — otherwise use search_chunks / retrieve.")
+ }
+ if e.deps.MetadataResolver == nil {
+ return ToolOutcome{
+ Payload: []any{map[string]any{
+ "kind": "metadata_search",
+ "note": "metadata_search is unavailable in this deployment (no metadata resolver is wired). Use search_chunks / retrieve.",
+ }},
+ Status: StatusError,
+ Reason: ReasonInfra,
+ Metrics: map[string]any{"docs": 0},
+ }, nil
+ }
+ targetIDs := metadataTargetIDs(e.deps)
+ if len(targetIDs) == 0 {
+ return ToolOutcome{
+ Payload: []any{},
+ Status: StatusError,
+ Reason: ReasonInfra,
+ Metrics: map[string]any{"docs": 0},
+ }, nil
+ }
+
+ // 1) Key validation against the dataset's OFFERED metadata fields — the same union of
+ // declared and indexed fields the tool schema advertises (see resolveMetadataFields).
+ // Validating against anything else would let the schema offer a key the tool then
+ // rejects; a dataset without the requested key must degrade to a hint, never to an
+ // empty retrieval the model retries forever.
+ known, _, declared, err := resolveMetadataFields(ctx, e.deps)
+ if err != nil {
+ logger.Printf("[Metadata search] metadata index read failed: %v", err)
+ return ToolOutcome{
+ Payload: []any{map[string]any{
+ "kind": "metadata_search",
+ "note": "The document-metadata index could not be read (infrastructure failure — NOT a statement about the dataset). Fall back to search_chunks / retrieve.",
+ }},
+ Status: StatusError,
+ Reason: ReasonInfra,
+ Metrics: map[string]any{"docs": 0},
+ }, nil
+ }
+ knownSet := make(map[string]bool, len(known))
+ for _, k := range known {
+ knownSet[k] = true
+ }
+ var bad []string
+ for _, f := range filters {
+ if key := asString(f["key"]); !knownSet[key] {
+ bad = append(bad, key)
+ }
+ }
+ if len(bad) > 0 {
+ available := strings.Join(capStrings(known, metadataKeysHintMax), ", ")
+ if available == "" {
+ available = "NONE — this dataset has no metadata; use search_chunks / retrieve"
+ }
+ logger.Printf("[Metadata search] bad key(s) %v — not in the dataset's metadata (available: %s)", bad, available)
+ return badArgs(fmt.Sprintf("Metadata key(s) %v do not exist in this dataset. Available: %s.", bad, available))
+ }
+
+ // 2) Normalize the filter values BEFORE they reach the push-down / in-memory filter, so
+ // a model that emits a list where one keyword is expected can never silently produce
+ // a no-match.
+ normalized := make([]map[string]any, 0, len(filters))
+ for _, f := range filters {
+ nf := make(map[string]any, len(f)+1)
+ for k, v := range f {
+ nf[k] = v
+ }
+ nf["value"] = NormalizeMetadataValue(f["value"], asString(f["op"]))
+ normalized = append(normalized, nf)
+ }
+ logic := argString(args, "logic")
+ if logic != "or" {
+ logic = "and"
+ }
+
+ // 3) Resolve the document set. This IS the tool's output: the ids are returned to the
+ // model so it can spend them on the search tools that take a document handle, and the
+ // filter itself is query-independent (it never needed a query).
+ docIDs, ok := MetadataDocIDs(ctx, e.deps, normalized, logic)
+ if !ok {
+ logger.Printf("[Metadata search] no documents matched filters=%v logic=%s", normalized, logic)
+ return ToolOutcome{
+ Payload: []any{map[string]any{
+ "kind": "metadata_search",
+ "note": "No documents match the given metadata conditions. Loosen or change the filters (try a shorter substring, or the space form instead of underscores), or use search_chunks / retrieve for unfiltered search.",
+ }},
+ Status: StatusMiss,
+ Reason: ReasonNoDoc,
+ Metrics: map[string]any{"docs": 0},
+ }, nil
+ }
+
+ // 4) Context block: the filter that was actually applied plus each matched document's
+ // own metadata values.
+ //
+ // WHY the values travel with the ids. The ids alone are a handle, not an answer, and
+ // the values are exactly what the filter matched ON: a model that must call
+ // list_chunks on every selected document just to learn its title, file name or
+ // timestamp spends a whole round re-reading what the selection already knew. Carrying
+ // them here is what makes the selection readable in one step — "these 3 documents were
+ // updated on 2026-09-20, and here are their titles and file names" — instead of
+ // N round-trips that each cost context.
+ //
+ // WHY it is context and NOT an interface. No other tool consumes these values: the
+ // machine-readable part of the result stays doc_ids (the argument retrieve's doc_scope,
+ // list_chunks and navigate_structure take). Keeping the values read-only matters
+ // because they are free-form text — a title or a file name spliced into a later
+ // search argument would let a value the model merely READ silently re-scope the
+ // search, while the document selection is the one thing the filter actually
+ // guarantees. The values therefore explain the selection; they never become input to
+ // the next one.
+ //
+ // The two halves are also reported separately for exactly this reason: `doc_ids` is
+ // complete (every match), while `documents` is capped (see metadataContextDocsMax) —
+ // truncating context must never truncate the result the model acts with.
+ item := map[string]any{
+ "kind": "metadata_search",
+ "doc_ids": docIDs,
+ "filters": normalized,
+ }
+ perDoc, ctxErr := e.deps.MetadataResolver.MetadataForDocIDs(ctx, targetIDs, docIDs)
+ if ctxErr != nil {
+ logger.Printf("[Metadata search] metadata context read degraded: %v", ctxErr)
+ }
+ if docs := metadataContextDocs(docIDs, perDoc, metadataContextKeys(normalized, declared)); len(docs) > 0 {
+ item["documents"] = docs
+ }
+
+ logger.Printf("[Metadata search] %d doc(s) selected via filters=%v logic=%s", len(docIDs), normalized, logic)
+ return ToolOutcome{
+ Payload: []any{item},
+ // No passages are retrieved here, so there is no evidence to admit: the ids reach
+ // the answer only through the tool the model spends them on.
+ EvidenceIDs: nil,
+ Status: StatusOK,
+ Reason: ReasonNone,
+ Metrics: map[string]any{"docs": len(docIDs)},
+ }, nil
+}
+
+// Metadata-search context caps: how many matched documents carry their metadata values in
+// the result, and how long one value may be.
+const (
+ metadataContextDocsMax = 20
+ metadataContextValueRunes = 200
+)
+
+// metadataContextKeys picks the fields the context block carries per document: first the
+// dataset's DECLARED fields (its curated schema — a title, a file name, a timestamp), then
+// any field the filter itself named, so the model can see WHY each document matched.
+//
+// Observed-only keys are deliberately left out: the metadata index also carries extraction
+// and annotation noise (a judge's rationale, a verdict) that the dataset never declared as
+// metadata, and dumping it into every result would spend context on fields no one can act on.
+func metadataContextKeys(filters []map[string]any, declared map[string]common.MetadataFieldDef) []string {
+ out := make([]string, 0, len(declared)+len(filters))
+ seen := map[string]bool{}
+ keys := make([]string, 0, len(declared))
+ for k := range declared {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys) // map iteration is randomised; the payload must not be
+ for _, k := range keys {
+ if k != "" && !seen[k] {
+ seen[k] = true
+ out = append(out, k)
+ }
+ }
+ for _, f := range filters {
+ k := asString(f["key"])
+ if k != "" && !seen[k] {
+ seen[k] = true
+ out = append(out, k)
+ }
+ }
+ return out
+}
+
+// metadataContextDocs renders the per-document context block: one {doc_id, metadata} entry
+// per matched document, in the selection's own order, capped at metadataContextDocsMax.
+// Missing and blank values are skipped, so the block never advertises a field as present
+// when the document does not carry it. A nil perDoc (the context read failed or no
+// resolver answered) yields nil — the ids alone are still a complete result.
+func metadataContextDocs(docIDs []string, perDoc map[string]map[string]any, keys []string) []any {
+ if len(perDoc) == 0 || len(keys) == 0 {
+ return nil
+ }
+ out := make([]any, 0, min(len(docIDs), metadataContextDocsMax))
+ for _, docID := range docIDs {
+ if len(out) >= metadataContextDocsMax {
+ break
+ }
+ fields, ok := perDoc[docID]
+ if !ok {
+ continue
+ }
+ values := make(map[string]any, len(keys))
+ for _, k := range keys {
+ if metadataCatalogExcluded(k) {
+ continue
+ }
+ v, exists := fields[k]
+ if !exists || v == nil {
+ continue
+ }
+ rendered := strings.TrimSpace(metadataValueString(v))
+ if rendered == "" {
+ continue
+ }
+ values[k] = Snippet(rendered, metadataContextValueRunes)
+ }
+ if len(values) == 0 {
+ continue
+ }
+ out = append(out, map[string]any{"doc_id": docID, "metadata": values})
+ }
+ return out
+}
+
+// metadataValueString renders one metadata value as text. The doc-metadata index merges a
+// document's per-chunk values into a list, so a list joins with ", " rather than reaching
+// the model as Go's "[a b]" rendering; a scalar renders as-is.
+func metadataValueString(v any) string {
+ switch t := v.(type) {
+ case nil:
+ return ""
+ case string:
+ return t
+ case []string:
+ return strings.Join(t, ", ")
+ case []any:
+ parts := make([]string, 0, len(t))
+ for _, item := range t {
+ if s := strings.TrimSpace(fmt.Sprint(item)); s != "" {
+ parts = append(parts, s)
+ }
+ }
+ return strings.Join(parts, ", ")
+ default:
+ return fmt.Sprint(t)
+ }
+}
+
+// metadataFiltersOf reads the filters argument: a list of {key, value, op} objects.
+// Entries without a key or an op are dropped, so a malformed entry cannot ride along into
+// the push-down as a condition that matches everything.
+func metadataFiltersOf(args map[string]any) []map[string]any {
+ raw, ok := args["filters"]
+ if !ok || raw == nil {
+ return nil
+ }
+ items, ok := raw.([]any)
+ if !ok {
+ return nil
+ }
+ out := make([]map[string]any, 0, len(items))
+ for _, item := range items {
+ m, ok := item.(map[string]any)
+ if !ok {
+ continue
+ }
+ key := strings.TrimSpace(asString(m["key"]))
+ op := strings.TrimSpace(asString(m["op"]))
+ if key == "" || op == "" {
+ continue
+ }
+ out = append(out, map[string]any{"key": key, "value": m["value"], "op": op})
+ }
+ return out
+}
+
+// NormalizeMetadataValue coerces a model-supplied filter value to the single value a
+// metadata filter expects. The string ops (contains / = / start with / end with /
+// not contains) take ONE keyword: a list that sneaks in collapses to its first non-empty
+// element (one condition = one keyword) and is logged, so the caller can re-issue per
+// keyword. 'in' / 'not in' keep their list (the value SET); empty / not empty take no value.
+//
+// Exported because the two callers that accept model-written metadata conditions — the
+// metadata_search tool and the pre-search fan-out channel — must coerce them identically.
+func NormalizeMetadataValue(value any, op string) any {
+ if op == "in" || op == "not in" {
+ return value
+ }
+ items, ok := value.([]any)
+ if !ok {
+ return value
+ }
+ flat := make([]string, 0, len(items))
+ for _, item := range items {
+ if item == nil {
+ continue
+ }
+ if s := strings.TrimSpace(fmt.Sprint(item)); s != "" {
+ flat = append(flat, s)
+ }
+ }
+ if len(flat) == 0 {
+ return nil
+ }
+ if len(flat) > 1 {
+ _LOG.Printf("[Metadata search] value list collapsed to the single keyword %q (ignored: %v); to match all, issue one condition per keyword", flat[0], flat[1:])
+ }
+ return flat[0]
+}
+
+// capStrings returns the first n elements of list (n <= 0 means "no cap").
+func capStrings(list []string, n int) []string {
+ if n <= 0 || len(list) <= n {
+ return list
+ }
+ return list[:n]
+}
+
// calculate derives a number the evidence does not state outright, by having the model
// write ONE
// expression and evaluating it against the AST whitelist (see arithmetic.go).
@@ -1570,9 +1921,9 @@ func toolQueries(args map[string]any) []string {
//
// so ONLY the "doc_scope" key is honoured: there is deliberately NO "doc_ids" alias and
// NO bare-string coercion (a string would be iterated char-wise; no tool schema advertises
-// either key, so both cases are unreachable). The other tools that used to call this —
-// search_chunks, navigate_tree, navigate_structure — must NOT read a scope: none of them
-// threads args["doc_scope"] into its impl.
+// a doc_ids alias or a bare string, so both cases are unreachable). The other tools that
+// used to call this — search_chunks, navigate_tree, navigate_structure — must NOT read a
+// scope: none of them threads args["doc_scope"] into its impl.
func toolDocScope(args map[string]any) []string {
raw, ok := args["doc_scope"]
if !ok {
@@ -1604,11 +1955,14 @@ func toolDocScope(args map[string]any) []string {
// merge reads it as entry["id"],
// so a "chunk_id" key silently disables the drill's structure_path attachment.
func passageFromChunk(c map[string]any) map[string]any {
- // Table chunks pass through un-truncated: the 1200-char cap would hide rows
- // mid/late in a long standings table.
+ // Table chunks are shown to the model as a Markdown view (key-value for infoboxes,
+ // a full-row pipe table for ranked/result tables) instead of raw <table> markup:
+ // same rows, a fraction of the tokens, and a form the model can aggregate. They
+ // also pass through un-truncated: the 1200-char cap would hide rows mid/late in a
+ // long standings table. The shared pool keeps the RAW chunk for citation.
var content string
if IsTableChunk(c) {
- content = ChunkTextOf(c)
+ content = TableViewOrRaw(ChunkTextOf(c))
} else {
// Content is a plain slice at 1200 chars (no trim, no ellipsis).
content = truncateRunes(ChunkTextOf(c), 1200)
diff --git a/internal/rag/agentic-rag/runtime/tool_executor_test.go b/internal/rag/agentic-rag/runtime/tool_executor_test.go
index 93fac48129..f638ea2ae7 100644
--- a/internal/rag/agentic-rag/runtime/tool_executor_test.go
+++ b/internal/rag/agentic-rag/runtime/tool_executor_test.go
@@ -26,6 +26,7 @@ import (
"unicode/utf8"
"ragflow/internal/agent/runtime"
+ "ragflow/internal/common"
"ragflow/internal/engine"
"gorm.io/gorm"
@@ -1365,6 +1366,412 @@ func TestPassageFromChunkTruncatesContent(t *testing.T) {
}
}
+// TestMetadataSearchToolBadArgsAndKeyHints pins the two "the model should change what it
+// asked for" outcomes: a call without filters, and a filter key the dataset does not
+// carry. Both are MISS/bad_args — a query-level miss, never a claim about the tool — and
+// the key case names the fields the dataset really has.
+func TestMetadataSearchToolBadArgsAndKeyHints(t *testing.T) {
+ deps, _ := newTestSearchDeps(&stubRetriever{})
+ deps.MetadataResolver = &stubMetadataResolver{
+ pushdownOK: true,
+ metas: common.MetaData{"author": {"Alice": {"d1"}}},
+ }
+ exec := NewSearchExecutor(deps, RunRequest{ThinkingMode: "high"})
+ ctx := context.Background()
+
+ out, err := exec.Execute(ctx, "metadata_search", map[string]any{})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ if out.Status != StatusMiss || out.Reason != ReasonBadArgs {
+ t.Errorf("status/reason = %s/%s, want miss/bad_args for a call without filters", out.Status, out.Reason)
+ }
+ if note := toolNote(out); !strings.Contains(note, "search_chunks") {
+ t.Errorf("note = %q, want the fallback tools named", note)
+ }
+
+ out, err = exec.Execute(ctx, "metadata_search", map[string]any{
+ "filters": []any{map[string]any{"key": "title", "op": "contains", "value": "New York"}},
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ if out.Status != StatusMiss || out.Reason != ReasonBadArgs {
+ t.Errorf("status/reason = %s/%s, want miss/bad_args for a missing key", out.Status, out.Reason)
+ }
+ if note := toolNote(out); !strings.Contains(note, "author") {
+ t.Errorf("note = %q, want the dataset's REAL keys listed", note)
+ }
+}
+
+// TestMetadataSearchToolInfraWhenIndexUnreadable pins the semantic split: a metadata-index
+// failure is ERROR/infra and must NOT be phrased as "this dataset has no metadata" — the
+// model would then give up on a filter that a working index would have honoured.
+func TestMetadataSearchToolInfraWhenIndexUnreadable(t *testing.T) {
+ deps, _ := newTestSearchDeps(&stubRetriever{})
+ deps.MetadataResolver = &stubMetadataResolver{flattenErr: errors.New("es down")}
+ exec := NewSearchExecutor(deps, RunRequest{ThinkingMode: "high"})
+
+ out, err := exec.Execute(context.Background(), "metadata_search", map[string]any{
+ "filters": []any{map[string]any{"key": "title", "op": "contains", "value": "New York"}},
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ if out.Status != StatusError || out.Reason != ReasonInfra {
+ t.Errorf("status/reason = %s/%s, want error/infra", out.Status, out.Reason)
+ }
+ if note := toolNote(out); !strings.Contains(note, "NOT a statement about the dataset") {
+ t.Errorf("note = %q, want an explicit infra framing", note)
+ }
+}
+
+// TestMetadataSearchToolReturnsMatchedDocIDsOnly pins the selector contract: the tool
+// resolves the matching documents and returns their doc_ids — it runs NO retrieval, admits
+// nothing to the shared pool and returns no passages. The ids are the whole output, because
+// that is what lets the model spend one filter on several follow-up tools.
+//
+// The result also carries the applied filter and each matched document's metadata values —
+// context the model reads, never an argument to hand to another tool (the ids are that
+// argument). Values are drawn from the dataset's DECLARED fields, so annotation noise the
+// dataset never declared cannot leak into every result.
+func TestMetadataSearchToolReturnsMatchedDocIDsOnly(t *testing.T) {
+ r := &stubRetriever{chunks: []map[string]any{
+ {"id": "c1", "doc_id": "d1", "content": "Culdcept was released in 1999 by OmiyaSoft."},
+ }}
+ deps, kb := newTestSearchDeps(r)
+ deps.MetadataResolver = &stubMetadataResolver{
+ pushdownOK: true,
+ pushdownIDs: []string{"d1", "d2"},
+ metas: common.MetaData{"title": {"Culdcept": {"d1", "d2"}}},
+ docMeta: map[string]map[string]any{
+ "d1": {
+ "title": "Culdcept",
+ "file_name": "culdcept.pdf",
+ "update_time": "2026-09-20 13:55:03",
+ "verdict": "incorrect", // observed-only noise: must not be carried
+ },
+ "d2": {"title": []any{"Culdcept", "Culdcept II"}},
+ },
+ }
+ deps.DeclaredMetadata = &stubDeclaredMetadata{defs: []common.MetadataFieldDef{
+ {Key: "title", Type: "string"},
+ {Key: "file_name", Type: "string"},
+ {Key: "update_time", Type: "time"},
+ }}
+ exec := NewSearchExecutor(deps, RunRequest{ThinkingMode: "high"})
+
+ out, err := exec.Execute(context.Background(), "metadata_search", map[string]any{
+ "filters": []any{map[string]any{"key": "title", "op": "contains", "value": "Culdcept"}},
+ "logic": "and",
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ if out.Status != StatusOK {
+ t.Fatalf("status = %s (reason %s), want ok", out.Status, out.Reason)
+ }
+ // A selector retrieves nothing: the retriever must not be called at all.
+ if len(r.requests) != 0 {
+ t.Errorf("retriever calls = %d, want 0 (metadata_search must not search)", len(r.requests))
+ }
+ if len(kb.Chunks) != 0 {
+ t.Errorf("pool chunks = %d, want none admitted by a selector", len(kb.Chunks))
+ }
+ if len(out.EvidenceIDs) != 0 {
+ t.Errorf("evidence ids = %v, want none", out.EvidenceIDs)
+ }
+ if len(out.Payload) != 1 {
+ t.Fatalf("payload = %v, want one doc_ids object", out.Payload)
+ }
+ m, ok := out.Payload[0].(map[string]any)
+ if !ok {
+ t.Fatalf("payload[0] = %#v, want a map", out.Payload[0])
+ }
+ if m["kind"] != "metadata_search" {
+ t.Errorf("payload kind = %v, want metadata_search", m["kind"])
+ }
+ ids, _ := m["doc_ids"].([]string)
+ if len(ids) != 2 || ids[0] != "d1" || ids[1] != "d2" {
+ t.Errorf("doc_ids = %v, want the matched documents", m["doc_ids"])
+ }
+ if docs, _ := out.Metrics["docs"].(int); docs != 2 {
+ t.Errorf("metrics docs = %v, want 2", out.Metrics["docs"])
+ }
+
+ // The applied filter travels with the result.
+ applied, _ := m["filters"].([]map[string]any)
+ if len(applied) != 1 || applied[0]["key"] != "title" || applied[0]["op"] != "contains" {
+ t.Errorf("payload filters = %v, want the applied condition", m["filters"])
+ }
+
+ // Per-document context: declared fields only, lists joined, noise excluded.
+ docsList, _ := m["documents"].([]any)
+ if len(docsList) != 2 {
+ t.Fatalf("payload documents = %v, want one entry per matched document", m["documents"])
+ }
+ first, _ := docsList[0].(map[string]any)
+ if first["doc_id"] != "d1" {
+ t.Errorf("documents[0].doc_id = %v, want d1", first["doc_id"])
+ }
+ fields, _ := first["metadata"].(map[string]any)
+ if fields["file_name"] != "culdcept.pdf" || fields["update_time"] != "2026-09-20 13:55:03" {
+ t.Errorf("documents[0].metadata = %v, want the document's declared values", fields)
+ }
+ if _, leaked := fields["verdict"]; leaked {
+ t.Errorf("documents[0].metadata carries an undeclared observed key: %v", fields)
+ }
+ second, _ := docsList[1].(map[string]any)
+ fields2, _ := second["metadata"].(map[string]any)
+ if fields2["title"] != "Culdcept, Culdcept II" {
+ t.Errorf("documents[1].metadata[title] = %v, want the list joined with \", \"", fields2["title"])
+ }
+}
+
+// TestMetadataSearchToolContextReadFailureKeepsTheSelection pins the best-effort contract of
+// the context block: the documents were already resolved, so a failed metadata read must
+// still return them (with the filter) rather than turning the call into an error.
+func TestMetadataSearchToolContextReadFailureKeepsTheSelection(t *testing.T) {
+ deps, _ := newTestSearchDeps(&stubRetriever{})
+ deps.MetadataResolver = &stubMetadataResolver{
+ pushdownOK: true,
+ pushdownIDs: []string{"d1"},
+ metas: common.MetaData{"title": {"Culdcept": {"d1"}}},
+ docMetaErr: errors.New("metadata index down"),
+ }
+ exec := NewSearchExecutor(deps, RunRequest{ThinkingMode: "high"})
+
+ out, err := exec.Execute(context.Background(), "metadata_search", map[string]any{
+ "filters": []any{map[string]any{"key": "title", "op": "contains", "value": "Culdcept"}},
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ if out.Status != StatusOK {
+ t.Fatalf("status = %s (reason %s), want ok — the ids resolved, only the context is missing", out.Status, out.Reason)
+ }
+ m, _ := out.Payload[0].(map[string]any)
+ if got := payloadDocIDs(out.Payload); len(got) != 1 || got[0] != "d1" {
+ t.Errorf("doc_ids = %v, want the matched document", got)
+ }
+ if _, present := m["documents"]; present {
+ t.Errorf("payload documents = %v, want the block omitted when nothing could be read", m["documents"])
+ }
+}
+
+// TestMetadataSearchToolAcceptsCatalogFieldKey pins the non-title path end to end at the
+// executor: a field the dataset really carries is accepted and the push-down resolves the
+// documents. Before the catalog the schema never let a model emit this filter, so the
+// executor's field-agnosticism was unreachable in practice.
+func TestMetadataSearchToolAcceptsCatalogFieldKey(t *testing.T) {
+ deps, _ := newTestSearchDeps(&stubRetriever{})
+ resolver := &stubMetadataResolver{
+ pushdownOK: true,
+ pushdownIDs: []string{"d1"},
+ metas: common.MetaData{"author": {"Alice": {"d1"}}},
+ }
+ deps.MetadataResolver = resolver
+ exec := NewSearchExecutor(deps, RunRequest{ThinkingMode: "high"})
+
+ out, err := exec.Execute(context.Background(), "metadata_search", map[string]any{
+ "filters": []any{map[string]any{"key": "author", "op": "contains", "value": "Alice"}},
+ "logic": "and",
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ if out.Status != StatusOK {
+ t.Fatalf("status = %s (reason %s), want ok — a field the dataset carries must not be rejected", out.Status, out.Reason)
+ }
+ if len(resolver.gotFilters) != 1 || resolver.gotFilters[0]["key"] != "author" {
+ t.Errorf("resolver filters = %v, want the author condition", resolver.gotFilters)
+ }
+ if got := payloadDocIDs(out.Payload); len(got) != 1 || got[0] != "d1" {
+ t.Errorf("doc_ids = %v, want the author-matched document", got)
+ }
+}
+
+// TestMetadataSearchToolWithoutMetadataIsMissNotError pins the metadata-free outcome: a
+// call against a dataset whose metadata index carries NOTHING is a query-level bad_args
+// miss with the fallback named — never an ERROR, which would tell the model the
+// infrastructure failed and it should give up on the whole line of search.
+func TestMetadataSearchToolWithoutMetadataIsMissNotError(t *testing.T) {
+ deps, _ := newTestSearchDeps(&stubRetriever{})
+ deps.MetadataResolver = &stubMetadataResolver{pushdownOK: true, metas: common.MetaData{}}
+ exec := NewSearchExecutor(deps, RunRequest{ThinkingMode: "high"})
+
+ out, err := exec.Execute(context.Background(), "metadata_search", map[string]any{
+ "filters": []any{map[string]any{"key": "title", "op": "contains", "value": "New York"}},
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ if out.Status == StatusError {
+ t.Fatalf("status = error (reason %s); a metadata-free dataset is NOT an infrastructure failure", out.Reason)
+ }
+ if out.Status != StatusMiss || out.Reason != ReasonBadArgs {
+ t.Errorf("status/reason = %s/%s, want miss/bad_args", out.Status, out.Reason)
+ }
+ note := toolNote(out)
+ if !strings.Contains(note, "NONE") {
+ t.Errorf("note = %q, want the explicit no-metadata hint", note)
+ }
+ if !strings.Contains(note, "search_chunks") {
+ t.Errorf("note = %q, want the fallback tools named", note)
+ }
+}
+
+// TestMetadataSearchToolAcceptsDeclaredOnlyField pins the consistency the declarative source
+// forces: a field the dataset DECLARES but has not indexed yet is advertised by the schema, so
+// the executor — which validates against the same union — must accept it rather than answer
+// "no such key" to the very filter it offered.
+func TestMetadataSearchToolAcceptsDeclaredOnlyField(t *testing.T) {
+ r := &stubRetriever{chunks: []map[string]any{
+ {"id": "c1", "doc_id": "d1", "content": "A report about towers."},
+ }}
+ deps, _ := newTestSearchDeps(r)
+ deps.MetadataResolver = &stubMetadataResolver{pushdownOK: true, pushdownIDs: []string{"d1"}, metas: common.MetaData{}}
+ deps.DeclaredMetadata = &stubDeclaredMetadata{defs: []common.MetadataFieldDef{
+ {Key: "doc_type", Description: "kind of document", Enum: []string{"report"}},
+ }}
+ exec := NewSearchExecutor(deps, RunRequest{ThinkingMode: "high"})
+
+ out, err := exec.Execute(context.Background(), "metadata_search", map[string]any{
+ "filters": []any{map[string]any{"key": "doc_type", "op": "=", "value": "report"}},
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ if out.Status != StatusOK {
+ t.Fatalf("status = %s (reason %s); a declared field must be accepted, not answered with bad_args", out.Status, out.Reason)
+ }
+ if got := payloadDocIDs(out.Payload); len(got) != 1 || got[0] != "d1" {
+ t.Errorf("doc_ids = %v, want the declared-field match", got)
+ }
+}
+
+// TestMetadataSearchToolRejectsSystemKey pins the blacklist at the enforcement point: a key
+// the catalog refuses to advertise (benchmark labels, connector fields) is ALSO refused when
+// the model names it anyway, so the leak cannot be reached by guessing.
+func TestMetadataSearchToolRejectsSystemKey(t *testing.T) {
+ deps, _ := newTestSearchDeps(&stubRetriever{})
+ deps.MetadataResolver = &stubMetadataResolver{pushdownOK: true, metas: common.MetaData{
+ "title": {"Culdcept": {"d1"}},
+ "question_id": {"444": {"d1"}},
+ }}
+ exec := NewSearchExecutor(deps, RunRequest{ThinkingMode: "high"})
+
+ out, err := exec.Execute(context.Background(), "metadata_search", map[string]any{
+ "filters": []any{map[string]any{"key": "question_id", "op": "=", "value": "444"}},
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ if out.Status != StatusMiss || out.Reason != ReasonBadArgs {
+ t.Fatalf("status/reason = %s/%s, want miss/bad_args for a blacklisted key", out.Status, out.Reason)
+ }
+ note := toolNote(out)
+ if !strings.Contains(note, "Available: title") {
+ t.Errorf("note = %q, want the offered fields only (no question_id)", note)
+ }
+ if strings.Contains(note, "444") {
+ t.Errorf("note = %q, must not echo a blacklisted key's value", note)
+ }
+}
+
+// TestNormalizeMetadataValue pins the value coercion: a list where one keyword is expected
+// collapses to its first non-empty element (one call = one keyword), 'in' keeps its list,
+// and an all-empty list becomes no value at all.
+func TestNormalizeMetadataValue(t *testing.T) {
+ cases := []struct {
+ value any
+ op string
+ want any
+ }{
+ {[]any{"New York", "Boston"}, "contains", "New York"},
+ {[]any{"", nil, "Boston"}, "contains", "Boston"},
+ {[]any{"", nil}, "contains", nil},
+ {[]any{"a", "b"}, "in", []any{"a", "b"}},
+ {"New York", "contains", "New York"},
+ }
+ for _, c := range cases {
+ if got := NormalizeMetadataValue(c.value, c.op); fmt.Sprint(got) != fmt.Sprint(c.want) {
+ t.Errorf("NormalizeMetadataValue(%v, %q) = %v, want %v", c.value, c.op, got, c.want)
+ }
+ }
+}
+
+// TestMetadataSearchOneShotGuardBlocksSecondCall pins the one-shot policy end to end at
+// the tool node: the first call runs, the second within the same session is answered with
+// a nudge and never executed.
+func TestMetadataSearchOneShotGuardBlocksSecondCall(t *testing.T) {
+ exec := &ladderExec{emptyFor: map[string]bool{}}
+ st := &SessionState{
+ Tools: &Toolset{Exec: exec, ThinkingMode: "high"},
+ DeadlineLeft: 60,
+ ToolCache: NewToolCache(),
+ PendingCalls: []ToolCall{{ID: "call-1", Name: "metadata_search"}},
+ }
+ if err := st.toolNode(context.Background()); err != nil {
+ t.Fatalf("toolNode: %v", err)
+ }
+ if len(exec.calls) != 1 || exec.calls[0] != "metadata_search" {
+ t.Fatalf("calls = %v, want the first metadata_search executed", exec.calls)
+ }
+ if !st.MetadataSearchUsed {
+ t.Error("MetadataSearchUsed must be set after the first call")
+ }
+
+ st.PendingCalls = []ToolCall{{ID: "call-2", Name: "metadata_search"}}
+ if err := st.toolNode(context.Background()); err != nil {
+ t.Fatalf("toolNode (second turn): %v", err)
+ }
+ if len(exec.calls) != 1 {
+ t.Errorf("calls = %v, want the second metadata_search blocked", exec.calls)
+ }
+ last := st.Messages[len(st.Messages)-1]
+ if !strings.Contains(last.Content, "ONE-SHOT") {
+ t.Errorf("second call's tool message = %q, want the one-shot nudge", last.Content)
+ }
+}
+
+// toolNote reads the note off a tool outcome whose payload is a single note object.
+func toolNote(out ToolOutcome) string {
+ if len(out.Payload) == 0 {
+ return ""
+ }
+ m, ok := out.Payload[0].(map[string]any)
+ if !ok {
+ return ""
+ }
+ note, _ := m["note"].(string)
+ return note
+}
+
+// TestPassageFromChunkRendersTablesAsMarkdown pins the action-session table shape: the
+// model sees a Markdown view (same rows, a fraction of the tokens) and never the raw
+// <table>/<td> markup. The chunk in the shared pool stays raw for citation.
+func TestPassageFromChunkRendersTablesAsMarkdown(t *testing.T) {
+ table := "<table><tr><th>Rank</th><th>Rider</th><th>Points</th></tr>" +
+ "<tr><td>19</td><td>Danilo</td><td>62</td></tr>" +
+ "<tr><td>20</td><td>Erik</td><td>61</td></tr></table>"
+ p := passageFromChunk(map[string]any{
+ "chunk_id": "c1", "doc_id": "d1", "content": table,
+ })
+ content, _ := p["content"].(string)
+ if strings.Contains(content, "<td>") || strings.Contains(content, "<table") {
+ t.Errorf("the model-visible passage still carries raw HTML: %q", content)
+ }
+ for _, want := range []string{"| 19 |", "Danilo", "| 20 |", "Erik"} {
+ if !strings.Contains(content, want) {
+ t.Errorf("passage lost %q: %q", want, content)
+ }
+ }
+ if p["doc_id"] != "d1" || p["id"] != "c1" {
+ t.Errorf("passage = %v", p)
+ }
+}
+
// seatRetriever answers a search by its query string, normalized to the DISTINCT
// tokens it carries: the engine receives "question keywords" (a seat search sends
// the same term twice), so a fixture must not depend on how that string is
diff --git a/internal/rag/agentic-rag/runtime/tool_search.go b/internal/rag/agentic-rag/runtime/tool_search.go
index 41438d5b37..3ebfe4c58a 100644
--- a/internal/rag/agentic-rag/runtime/tool_search.go
+++ b/internal/rag/agentic-rag/runtime/tool_search.go
@@ -27,8 +27,10 @@ import (
"sync"
"unicode/utf8"
+ "ragflow/internal/common"
"ragflow/internal/engine"
"ragflow/internal/entity"
+ "ragflow/internal/service"
"ragflow/internal/service/nlp"
)
@@ -148,6 +150,53 @@ type DocTenantResolver interface {
ResolveDocTenants(ctx context.Context, docIDs []string) (map[string]DocTenant, error)
}
+// MetadataResolver resolves document sets from document metadata for the metadata_search
+// tool. Like DocIDVerifier / DocTenantResolver the lookup is left to the caller, so the
+// search legs hold no metadata-index dependency of their own; the production
+// implementation is internal/service.MetadataService. Nil makes the metadata channel
+// unavailable (the tool reports a clean miss, the pre-search channel is skipped).
+//
+// Filters are the tool's own {key, value, op} condition maps, kept as maps so the
+// implementation needs no import of this package.
+type MetadataResolver interface {
+ // FilterDocIDsByMetaPushdown resolves the documents whose metadata matches filters
+ // (logic = "and" | "or") by pushing the predicate into the document-metadata index.
+ //
+ // ok=false means the push-down is NOT viable or errored and the caller must fall back
+ // to GetFlattedMetaByKBs + the in-memory filter. ok=true with an empty slice is the
+ // definitive "no document matches".
+ FilterDocIDsByMetaPushdown(ctx context.Context, kbIDs []string, filters []map[string]any, logic string) ([]string, bool)
+ // GetFlattedMetaByKBs returns field → value → doc_ids for the given datasets. It is
+ // the in-memory filter's input and the source of the "which fields exist" hint that
+ // turns "this dataset has no title" into advice instead of an empty retrieval the
+ // model retries forever.
+ GetFlattedMetaByKBs(ctx context.Context, kbIDs []string) (common.MetaData, error)
+ // MetadataForDocIDs returns doc_id → its metadata fields, reading ONLY the given
+ // documents. It backs the metadata_search result's context block: the ids stay the
+ // tool's machine-consumable output, while these values let the model answer FROM the
+ // selection (its titles, file names, timestamps) without spending another tool call.
+ //
+ // Best effort by contract: a dataset that cannot be read contributes nothing and the
+ // returned error says why, but the caller has already resolved the document ids and
+ // must not fail a successful selection over a missing context block.
+ MetadataForDocIDs(ctx context.Context, kbIDs []string, docIDs []string) (map[string]map[string]any, error)
+}
+
+// DeclaredMetadataResolver reads the metadata fields a dataset DECLARES in its
+// parser_config — the {key, type, description, enum} definitions a user configured for
+// extraction. Optional: nil leaves the catalog with only what the metadata index carries.
+//
+// It is separate from MetadataResolver because it answers a different question (what the
+// dataset is CONFIGURED to filter on, before anything is indexed) from a different store
+// (the KB row, not the doc-metadata index), and because the declarative read is cheap enough
+// to run per metadata_search call while the observational one scans documents.
+type DeclaredMetadataResolver interface {
+ // DeclaredMetadataFields returns the declared fields of the given datasets, in
+ // configuration order. An error means "no declarative source available"; callers degrade
+ // to the metadata index alone rather than failing.
+ DeclaredMetadataFields(ctx context.Context, kbIDs []string) ([]common.MetadataFieldDef, error)
+}
+
// RetrieveRequest is one retrieval call.
//
// Weight is the keyword-similarity weight: 0.7 hybrid (default), 0.0 vector-only,
@@ -369,6 +418,15 @@ type SearchDeps struct {
// behaviour: each bound dataset is searched with the whole DocScope (no per-document
// re-grouping).
DocTenantResolver DocTenantResolver
+ // MetadataResolver resolves document sets from document metadata, backing the
+ // metadata_search tool and the pre-search metadata channel. Nil leaves both
+ // unavailable: the tool reports a clean miss and the channel is skipped.
+ MetadataResolver MetadataResolver
+ // DeclaredMetadata reads the metadata fields the datasets DECLARE in their
+ // parser_config (description/enum included), which is what lets the metadata_search
+ // catalog say what a field MEANS and not just that it exists. Nil leaves the catalog
+ // with the metadata index alone.
+ DeclaredMetadata DeclaredMetadataResolver
// DoRefer: when true, summarize_document
// prefixes the citation rules so the model cites the blocks it summarises.
DoRefer bool
@@ -812,6 +870,343 @@ func HybridSearch(ctx context.Context, deps SearchDeps, p SearchParams) ([]map[s
})
}
+// MetadataDocIDs resolves the documents a metadata filter matches: metadata-index
+// push-down (ES / Infinity) -> in-memory filter when the push-down is not viable ->
+// intersect with the session document scope.
+//
+// ok=false means NO document is eligible — nothing matched, or the session scope removed
+// every match. That is a normal empty result, never an error: the caller reports a
+// query-level miss. The resolution is query-independent, so callers resolve once and then
+// search inside the returned documents.
+func MetadataDocIDs(ctx context.Context, deps SearchDeps, filters []map[string]any, logic string) ([]string, bool) {
+ logger := searchLogger(deps)
+ if len(filters) == 0 || deps.MetadataResolver == nil {
+ return nil, false
+ }
+ targetIDs := metadataTargetIDs(deps)
+ if len(targetIDs) == 0 {
+ return nil, false
+ }
+ docIDs, pushdownOK := deps.MetadataResolver.FilterDocIDsByMetaPushdown(ctx, targetIDs, filters, logic)
+ if !pushdownOK {
+ metas, err := deps.MetadataResolver.GetFlattedMetaByKBs(ctx, targetIDs)
+ if err != nil {
+ logger.Printf("[Metadata search] push-down unavailable and the in-memory fallback failed: %v", err)
+ return nil, false
+ }
+ docIDs = metaFilterDocIDs(metas, filters, logic)
+ }
+ if len(docIDs) == 0 {
+ logger.Printf("[Metadata search] no documents matched filters=%v logic=%s", filters, logic)
+ return nil, false
+ }
+ // The session's document scope is a ceiling: a document outside it stays unreachable
+ // even when its metadata matches.
+ scoped := scopedDocIDs(deps.DocScope, docIDs)
+ if len(scoped) == 0 {
+ logger.Printf("[Metadata search] 0 documents after the doc-scope intersection")
+ return nil, false
+ }
+ return scoped, true
+}
+
+// MetadataSearch: hybrid retrieval restricted to the documents a metadata filter matches
+// (MetadataDocIDs + HybridSearch), the leg the pre-search metadata channel runs.
+//
+// Compiled expansion stays OFF: it would pull in out-of-scope chunks and break the "only
+// these documents" contract.
+func MetadataSearch(ctx context.Context, deps SearchDeps, p SearchParams, filters []map[string]any, logic string) ([]map[string]any, []map[string]any) {
+ docIDs, ok := MetadataDocIDs(ctx, deps, filters, logic)
+ if !ok {
+ return nil, nil
+ }
+ searchLogger(deps).Printf("[Metadata search] %q searching %d matched doc(s) via filters=%v", trunc(p.Question, 80), len(docIDs), filters)
+ return HybridSearch(ctx, deps, SearchParams{
+ Question: p.Question,
+ Keywords: p.Keywords,
+ DocScope: docIDs,
+ TopN: p.TopN,
+ UseCompiled: false,
+ })
+}
+
+// metadataTargetIDs is the deduplicated dataset id list a metadata lookup spans: the
+// session's bound datasets plus its structured (SQL-backed) ones.
+func metadataTargetIDs(deps SearchDeps) []string {
+ merged := append(append([]string{}, deps.KbIDs...), deps.SQLKBs...)
+ out := make([]string, 0, len(merged))
+ seen := make(map[string]struct{}, len(merged))
+ for _, id := range merged {
+ if id == "" {
+ continue
+ }
+ if _, dup := seen[id]; dup {
+ continue
+ }
+ seen[id] = struct{}{}
+ out = append(out, id)
+ }
+ return out
+}
+
+// Metadata-search catalog caps: fields listed, values shown per field, and the rendered
+// block's length in CODE POINTS (a byte cap would cut CJK fields early).
+const (
+ metadataCatalogKeysMax = 20
+ metadataCatalogSamplesPerKey = 8
+ metadataCatalogRenderMax = 2000
+)
+
+// metadataCatalogSystemKeys are metadata keys that exist in the doc-metadata index but
+// must never be offered as filters: unique identifiers and benchmark annotations let a
+// model shrink retrieval to the answer's own documents (the FRAMES `question_id` stamps
+// every document of one question with the same id), and the PDF/connector-derived fields
+// describe the file rather than its content.
+var metadataCatalogSystemKeys = map[string]bool{
+ "question_id": true,
+ "source_uri": true,
+ "pageid": true,
+ "outline": true,
+}
+
+// MetadataSample is one value of a metadata field plus how many documents carry it.
+type MetadataSample struct {
+ Value string `json:"value"`
+ Docs int `json:"docs"`
+}
+
+// MetadataCatalog is what a dataset offers as metadata_search filters, drawn from BOTH
+// sources it has:
+//
+// - the DECLARATIVE one (Fields): the {key, type, description, enum} definitions stored in
+// the dataset's parser_config. They exist BEFORE anything is indexed, and they carry what
+// the observational source cannot: what a field MEANS and which values it accepts;
+// - the OBSERVATIONAL one (Samples): the values the doc-metadata index actually carries,
+// with document counts.
+//
+// It is rendered into three places: the metadata_search tool schema (the `key` enum), the
+// action-session seed (the AVAILABLE METADATA block) and the pre-search fan-out channel's
+// field vocabulary. Nothing is baked in as a fallback — no field is advertised, filtered on or
+// named in a prompt unless the dataset's catalog carries it. The tool's own key check reads the
+// same two sources (see resolveMetadataFields), so what is advertised is what is accepted.
+type MetadataCatalog struct {
+ Keys []string
+ Samples map[string][]MetadataSample
+ // Fields holds a key's DECLARED definition when the dataset declares one. A key present
+ // only here is declared but not yet indexed: still a legitimate filter, just with no value
+ // sample to show for it.
+ Fields map[string]common.MetadataFieldDef
+}
+
+// Empty reports whether the catalog carries no usable field. An empty catalog means
+// "leave the tool spec exactly as it ships" — never "offer a field list that is empty",
+// because some providers reject an empty enum.
+func (c MetadataCatalog) Empty() bool { return len(c.Keys) == 0 }
+
+// Render builds the seed block. Empty catalogs render as "" so the caller can append
+// unconditionally. Each field carries what is known about it — its declared meaning, the
+// values it accepts, and the values seen in the index — so the model fills a filter instead
+// of guessing. The result is capped at metadataCatalogRenderMax code points.
+func (c MetadataCatalog) Render() string {
+ if c.Empty() {
+ return ""
+ }
+ var b strings.Builder
+ b.WriteString("AVAILABLE METADATA (dataset fields usable as metadata_search filters):")
+ for _, k := range c.Keys {
+ b.WriteString("\n- ")
+ b.WriteString(k)
+ b.WriteString(describeMetadataField(c.Fields[k]))
+ if samples := c.Samples[k]; len(samples) > 0 {
+ b.WriteString("; values seen: ")
+ for i, s := range samples {
+ if i > 0 {
+ b.WriteString(", ")
+ }
+ fmt.Fprintf(&b, "%q (%d doc(s))", s.Value, s.Docs)
+ }
+ }
+ }
+ b.WriteString("\nFields NOT listed here are unusable as filters — never invent one.")
+ return truncateRunes(b.String(), metadataCatalogRenderMax)
+}
+
+// describeMetadataField renders a field's declared meaning and allowed values, shared by
+// Render and FieldList so the two can never describe the same field differently.
+func describeMetadataField(def common.MetadataFieldDef) string {
+ var b strings.Builder
+ if def.Description != "" {
+ b.WriteString(" — ")
+ b.WriteString(def.Description)
+ }
+ if len(def.Enum) > 0 {
+ b.WriteString(" (one of: ")
+ b.WriteString(strings.Join(def.Enum, " / "))
+ b.WriteString(")")
+ }
+ return b.String()
+}
+
+// MetadataCatalogFor reads the metadata fields the session's datasets offer, for the
+// metadata_search schema and the session seed.
+//
+// It is DELIBERATELY error-free: the observational read is the same GetFlattedMetaByKBs the
+// executor already performs for its key check, and a nil resolver, an unreadable index or an
+// empty KB set all degrade to whatever the other half provides — "keep today's behaviour"
+// rather than failing the session. (A resolver failure is still reported to the model by the
+// tool itself as ERROR/infra if a call reaches the executor.)
+func MetadataCatalogFor(ctx context.Context, deps SearchDeps) MetadataCatalog {
+ keys, metas, declared, err := resolveMetadataFields(ctx, deps)
+ if err != nil || len(keys) == 0 {
+ return MetadataCatalog{}
+ }
+ cat := MetadataCatalog{
+ Keys: keys,
+ Fields: declared,
+ Samples: make(map[string][]MetadataSample, len(keys)),
+ }
+ for _, k := range keys {
+ if samples := topMetadataSamples(metas[k], metadataCatalogSamplesPerKey); len(samples) > 0 {
+ cat.Samples[k] = samples
+ }
+ }
+ return cat
+}
+
+// MetadataCatalogPtr is MetadataCatalogFor returning nil for an empty catalog, so a
+// Toolset carries "no catalog" as nil and every render path skips it by construction.
+func MetadataCatalogPtr(ctx context.Context, deps SearchDeps) *MetadataCatalog {
+ cat := MetadataCatalogFor(ctx, deps)
+ if cat.Empty() {
+ return nil
+ }
+ return &cat
+}
+
+// resolveMetadataFields is the single resolution both the catalog (what to advertise) and the
+// executor (what to accept) run. It returns the offered keys in sorted order, the flattened
+// observational view (for value samples), the declared definitions by key, and — unlike the
+// catalog's own view — the metadata-index read error, which the executor reports as infra
+// rather than folding into "this dataset has no metadata".
+//
+// Both halves are best-effort and independent: no declared resolver or a failing parser_config
+// read leaves the observational half alone, and vice versa. A DECLARED key is offered even
+// when the index has no value for it yet (it is a real filter that currently matches nothing);
+// an OBSERVED key is offered only when it carries at least one usable value.
+func resolveMetadataFields(ctx context.Context, deps SearchDeps) ([]string, common.MetaData, map[string]common.MetadataFieldDef, error) {
+ targetIDs := metadataTargetIDs(deps)
+ if len(targetIDs) == 0 {
+ return nil, nil, nil, nil
+ }
+
+ declared := map[string]common.MetadataFieldDef{}
+ if deps.DeclaredMetadata != nil {
+ if defs, err := deps.DeclaredMetadata.DeclaredMetadataFields(ctx, targetIDs); err == nil {
+ for _, def := range defs {
+ if metadataCatalogExcluded(def.Key) {
+ continue
+ }
+ if _, dup := declared[def.Key]; dup {
+ continue
+ }
+ declared[def.Key] = def
+ }
+ }
+ }
+
+ metas := common.MetaData{}
+ if deps.MetadataResolver != nil {
+ got, err := deps.MetadataResolver.GetFlattedMetaByKBs(ctx, targetIDs)
+ if err != nil {
+ return nil, nil, declared, err
+ }
+ metas = got
+ }
+
+ seen := make(map[string]bool, len(declared)+len(metas))
+ keys := make([]string, 0, len(declared)+len(metas))
+ for k := range declared {
+ seen[k] = true
+ keys = append(keys, k)
+ }
+ for k := range metas {
+ if seen[k] || metadataCatalogExcluded(k) {
+ continue
+ }
+ if len(topMetadataSamples(metas[k], 1)) == 0 {
+ // No usable value: offering the key would only invite a call that cannot match.
+ continue
+ }
+ seen[k] = true
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ if len(keys) > metadataCatalogKeysMax {
+ keys = keys[:metadataCatalogKeysMax]
+ }
+ if len(declared) == 0 {
+ declared = nil
+ }
+ return keys, metas, declared, nil
+}
+
+// metadataCatalogExcluded reports whether a metadata key must stay out of the catalog:
+// blank, a connector/derived field (leading underscore is how they are namespaced), or a
+// system/label field (see metadataCatalogSystemKeys).
+func metadataCatalogExcluded(key string) bool {
+ k := strings.TrimSpace(key)
+ if k == "" || strings.HasPrefix(k, "_") {
+ return true
+ }
+ return metadataCatalogSystemKeys[k]
+}
+
+// topMetadataSamples orders one field's values by document count (descending) then value,
+// so the rendered sample is deterministic, and caps them at n (n <= 0 means "no cap").
+func topMetadataSamples(values common.MetaValueDocs, n int) []MetadataSample {
+ out := make([]MetadataSample, 0, len(values))
+ for v, docs := range values {
+ if strings.TrimSpace(v) == "" || len(docs) == 0 {
+ continue
+ }
+ out = append(out, MetadataSample{Value: v, Docs: len(docs)})
+ }
+ sort.Slice(out, func(i, j int) bool {
+ if out[i].Docs != out[j].Docs {
+ return out[i].Docs > out[j].Docs
+ }
+ return out[i].Value < out[j].Value
+ })
+ if n > 0 && len(out) > n {
+ out = out[:n]
+ }
+ return out
+}
+
+// metaFilterDocIDs is the in-memory metadata filter used when the index push-down is not
+// viable. The condition conversion and the operator normalisation stay in
+// internal/service, where the chat pipeline's own filter shares them.
+func metaFilterDocIDs(metas common.MetaData, filters []map[string]any, logic string) []string {
+ if len(metas) == 0 || len(filters) == 0 {
+ return nil
+ }
+ conditions := make([]service.MetaFilterCondition, 0, len(filters))
+ for _, f := range filters {
+ if f == nil {
+ continue
+ }
+ conditions = append(conditions, service.MetaFilterCondition{
+ Key: asString(f["key"]),
+ Value: f["value"],
+ Op: asString(f["op"]),
+ })
+ }
+ if len(conditions) == 0 {
+ return nil
+ }
+ return service.ApplyMetaFilter(metas, conditions, logic)
+}
+
// VectorSearch: the pure vector entry point. With no embedder it returns nothing,
// otherwise the vector weight is 1.0 and compiled rows are excluded.
func VectorSearch(ctx context.Context, deps SearchDeps, p SearchParams) ([]map[string]any, []map[string]any) {
diff --git a/internal/rag/agentic-rag/runtime/tool_search_test.go b/internal/rag/agentic-rag/runtime/tool_search_test.go
index 25e6ce382f..7850eba493 100644
--- a/internal/rag/agentic-rag/runtime/tool_search_test.go
+++ b/internal/rag/agentic-rag/runtime/tool_search_test.go
@@ -30,6 +30,7 @@ import (
"testing"
"unicode/utf8"
+ "ragflow/internal/common"
"ragflow/internal/entity"
)
@@ -337,6 +338,30 @@ func TestNarrowContentKeepsNeighboursAndHighlights(t *testing.T) {
}
}
+// TestNarrowContentRendersHTMLTablesAsMarkdown pins the table branch: an HTML table is
+// serialized to a Markdown view before the model sees it (raw <table>/<td> markup is the
+// expensive and least readable form), and the row set is not pruned.
+func TestNarrowContentRendersHTMLTablesAsMarkdown(t *testing.T) {
+ content := "<table><tr><th>Rank</th><th>Rider</th><th>Points</th></tr>" +
+ "<tr><td>19</td><td>Danilo</td><td>62</td></tr>" +
+ "<tr><td>20</td><td>Erik</td><td>61</td></tr></table>"
+ got, ok := NarrowContent(content, []string{"danilo"})
+ if !ok {
+ t.Fatal("NarrowContent must keep a table whole")
+ }
+ if strings.Contains(got, "<td>") || strings.Contains(got, "<table") {
+ t.Errorf("narrowed table still carries raw HTML: %q", got)
+ }
+ for _, want := range []string{"| 19 |", "Danilo", "| 20 |", "Erik"} {
+ if !strings.Contains(got, want) {
+ t.Errorf("narrowed table lost %q: %q", want, got)
+ }
+ }
+ if !strings.HasPrefix(got, "...") || !strings.HasSuffix(got, "...") {
+ t.Errorf("narrowed text must be wrapped in ellipses: %q", got)
+ }
+}
+
func TestSplitKeywordsFallsBackToBigrams(t *testing.T) {
// >=3 comma terms -> used as-is, lower-cased.
got := SplitKeywords("Alpha, Beta, Gamma")
@@ -530,6 +555,445 @@ func TestHybridSearchInvokesCompiledExpansion(t *testing.T) {
type stubExpander struct{ calls int }
+// stubMetadataResolver is a scripted MetadataResolver: the push-down answer, the
+// flattened view and the call log are all set per test.
+type stubMetadataResolver struct {
+ pushdownIDs []string
+ pushdownOK bool
+ metas common.MetaData
+ flattenErr error
+ pushdownCalls int
+ flattenCalls int
+ gotKbIDs []string
+ gotFilters []map[string]any
+ gotLogic string
+ // docMeta is the per-document metadata the context block is built from; docMetaErr lets
+ // a test pin that a failed context read still returns the selected ids.
+ docMeta map[string]map[string]any
+ docMetaErr error
+}
+
+func (s *stubMetadataResolver) FilterDocIDsByMetaPushdown(_ context.Context, kbIDs []string, filters []map[string]any, logic string) ([]string, bool) {
+ s.pushdownCalls++
+ s.gotKbIDs = kbIDs
+ s.gotFilters = filters
+ s.gotLogic = logic
+ return s.pushdownIDs, s.pushdownOK
+}
+
+func (s *stubMetadataResolver) GetFlattedMetaByKBs(context.Context, []string) (common.MetaData, error) {
+ s.flattenCalls++
+ return s.metas, s.flattenErr
+}
+
+func (s *stubMetadataResolver) MetadataForDocIDs(context.Context, []string, []string) (map[string]map[string]any, error) {
+ return s.docMeta, s.docMetaErr
+}
+
+// TestMetadataSearchScopesHybridToMatchedDocuments pins the retrieval leg: the metadata
+// match decides the document set, the hybrid search runs inside it (compiled expansion
+// OFF, so nothing outside the set can be pulled in), and the push-down hit means the
+// flattened view is never read.
+func TestMetadataSearchScopesHybridToMatchedDocuments(t *testing.T) {
+ r := &stubRetriever{chunks: []map[string]any{{"id": "c1", "doc_id": "d1", "content": "hit"}}}
+ deps, _ := newTestSearchDeps(r)
+ res := &stubMetadataResolver{pushdownOK: true, pushdownIDs: []string{"d1", "d2"}}
+ deps.MetadataResolver = res
+
+ filters := []map[string]any{{"key": "title", "op": "contains", "value": "New York"}}
+ chunks, _ := MetadataSearch(context.Background(), deps, SearchParams{Question: "how many?", TopN: 20}, filters, "and")
+
+ if len(chunks) != 1 {
+ t.Fatalf("chunks = %d, want 1", len(chunks))
+ }
+ if res.flattenCalls != 0 {
+ t.Errorf("flatten calls = %d: a push-down hit must not read the flattened view", res.flattenCalls)
+ }
+ if res.gotLogic != "and" || len(res.gotFilters) != 1 {
+ t.Errorf("resolver got filters=%v logic=%q", res.gotFilters, res.gotLogic)
+ }
+ if len(res.gotKbIDs) != 1 || res.gotKbIDs[0] != "kb1" {
+ t.Errorf("resolver kbIDs = %v, want the session's datasets", res.gotKbIDs)
+ }
+ if len(r.requests) != 1 {
+ t.Fatalf("requests = %d, want 1", len(r.requests))
+ }
+ scope := r.requests[0].DocScope
+ if len(scope) != 2 || scope[0] != "d1" || scope[1] != "d2" {
+ t.Errorf("doc_scope = %v, want the matched documents", scope)
+ }
+}
+
+// TestMetadataSearchFallsBackToInMemoryFilter pins the fallback: when the push-down is
+// not viable, the flattened metadata is filtered in memory with the same conditions.
+func TestMetadataSearchFallsBackToInMemoryFilter(t *testing.T) {
+ r := &stubRetriever{chunks: []map[string]any{{"id": "c1", "doc_id": "d1", "content": "hit"}}}
+ deps, _ := newTestSearchDeps(r)
+ res := &stubMetadataResolver{
+ pushdownOK: false,
+ metas: common.MetaData{
+ "title": {"New York City": {"d1"}, "Boston": {"d2"}},
+ },
+ }
+ deps.MetadataResolver = res
+
+ chunks, _ := MetadataSearch(context.Background(), deps, SearchParams{Question: "q"},
+ []map[string]any{{"key": "title", "op": "contains", "value": "New York"}}, "and")
+
+ if len(chunks) != 1 {
+ t.Fatalf("chunks = %d, want the in-memory hit", len(chunks))
+ }
+ if res.flattenCalls != 1 {
+ t.Errorf("flatten calls = %d, want 1", res.flattenCalls)
+ }
+ if scope := r.requests[0].DocScope; len(scope) != 1 || scope[0] != "d1" {
+ t.Errorf("doc_scope = %v, want the in-memory match", scope)
+ }
+}
+
+// TestMetadataSearchEmptyResultIsNotASearch pins the miss path: an empty match (definitive
+// from the push-down, or after the session ceiling) must reach the retriever zero times,
+// and must not be reported as an error.
+func TestMetadataSearchEmptyResultIsNotASearch(t *testing.T) {
+ filters := []map[string]any{{"key": "title", "op": "contains", "value": "nowhere"}}
+
+ // Push-down says: definitively no match.
+ r := &stubRetriever{chunks: []map[string]any{{"content": "x"}}}
+ deps, _ := newTestSearchDeps(r)
+ deps.MetadataResolver = &stubMetadataResolver{pushdownOK: true}
+ if chunks, _ := MetadataSearch(context.Background(), deps, SearchParams{Question: "q"}, filters, "and"); chunks != nil {
+ t.Errorf("chunks = %v, want nil", chunks)
+ }
+ if len(r.requests) != 0 {
+ t.Errorf("requests = %d: an empty match must not search", len(r.requests))
+ }
+
+ // The session ceiling removes every matched document.
+ r2 := &stubRetriever{chunks: []map[string]any{{"content": "x"}}}
+ deps2, _ := newTestSearchDeps(r2)
+ deps2.DocScope = []string{"d9"}
+ deps2.MetadataResolver = &stubMetadataResolver{pushdownOK: true, pushdownIDs: []string{"d1"}}
+ if chunks, _ := MetadataSearch(context.Background(), deps2, SearchParams{Question: "q"}, filters, "and"); chunks != nil {
+ t.Errorf("chunks = %v, want nil", chunks)
+ }
+ if len(r2.requests) != 0 {
+ t.Errorf("requests = %d: a scope that excludes everything must not search", len(r2.requests))
+ }
+}
+
+// TestMetadataSearchIntersectsTheSessionScope pins the ceiling: the metadata set cannot
+// escape the session's document restriction.
+func TestMetadataSearchIntersectsTheSessionScope(t *testing.T) {
+ r := &stubRetriever{chunks: []map[string]any{{"id": "c1", "doc_id": "d2", "content": "hit"}}}
+ deps, _ := newTestSearchDeps(r)
+ deps.DocScope = []string{"d2", "d3"}
+ deps.MetadataResolver = &stubMetadataResolver{pushdownOK: true, pushdownIDs: []string{"d1", "d2", "d3"}}
+
+ filters := []map[string]any{{"key": "title", "op": "contains", "value": "x"}}
+ if chunks, _ := MetadataSearch(context.Background(), deps, SearchParams{Question: "q"}, filters, "and"); len(chunks) != 1 {
+ t.Fatalf("chunks = %d, want 1", len(chunks))
+ }
+ scope := r.requests[0].DocScope
+ if len(scope) != 2 || scope[0] != "d2" || scope[1] != "d3" {
+ t.Errorf("doc_scope = %v, want the intersection with the session scope", scope)
+ }
+}
+
+// TestMetadataSearchWithoutResolverIsInert pins the unwired seam: no resolver (or no
+// filters) means the leg does nothing at all, never a failed search.
+func TestMetadataSearchWithoutResolverIsInert(t *testing.T) {
+ r := &stubRetriever{chunks: []map[string]any{{"content": "x"}}}
+ deps, _ := newTestSearchDeps(r)
+ filters := []map[string]any{{"key": "title", "op": "contains", "value": "x"}}
+
+ if chunks, _ := MetadataSearch(context.Background(), deps, SearchParams{Question: "q"}, filters, "and"); chunks != nil {
+ t.Errorf("chunks = %v, want nil without a resolver", chunks)
+ }
+ deps.MetadataResolver = &stubMetadataResolver{pushdownOK: true, pushdownIDs: []string{"d1"}}
+ if chunks, _ := MetadataSearch(context.Background(), deps, SearchParams{Question: "q"}, nil, "and"); chunks != nil {
+ t.Errorf("chunks = %v, want nil without filters", chunks)
+ }
+ if len(r.requests) != 0 {
+ t.Errorf("requests = %d, want none", len(r.requests))
+ }
+}
+
+// ===================== metadata catalog =====================
+
+// TestMetadataCatalogForBuildsSortedKeysWithSamples pins what the model gets to see: the
+// dataset's real fields, deterministically ordered, each with its strongest values.
+func TestMetadataCatalogForBuildsSortedKeysWithSamples(t *testing.T) {
+ deps, _ := newTestSearchDeps(&stubRetriever{})
+ deps.MetadataResolver = &stubMetadataResolver{metas: common.MetaData{
+ "title": {"Boston": {"d1"}, "New York City": {"d2", "d3", "d4"}},
+ "author": {"Alice": {"d1"}, "Bob": {"d2"}},
+ }}
+
+ cat := MetadataCatalogFor(context.Background(), deps)
+ if got := strings.Join(cat.Keys, ","); got != "author,title" {
+ t.Fatalf("keys = %q, want author,title (sorted, deterministic)", got)
+ }
+ samples := cat.Samples["title"]
+ if len(samples) != 2 {
+ t.Fatalf("title samples = %v, want 2", samples)
+ }
+ // Ordered by document count: the value most documents carry is the useful one to show.
+ if samples[0].Value != "New York City" || samples[0].Docs != 3 {
+ t.Errorf("first title sample = %+v, want New York City (3 docs)", samples[0])
+ }
+
+ render := cat.Render()
+ for _, want := range []string{"AVAILABLE METADATA", "title", "author", "New York City"} {
+ if !strings.Contains(render, want) {
+ t.Errorf("render missing %q:\n%s", want, render)
+ }
+ }
+ if n := utf8.RuneCountInString(render); n > metadataCatalogRenderMax {
+ t.Errorf("render = %d runes, cap is %d", n, metadataCatalogRenderMax)
+ }
+}
+
+// TestMetadataCatalogForDropsSystemAndLabelKeys pins the blacklist: identifiers and
+// benchmark annotations must never become filters — a `question_id` filter would let the
+// model shrink retrieval to the very documents that answer the question.
+func TestMetadataCatalogForDropsSystemAndLabelKeys(t *testing.T) {
+ deps, _ := newTestSearchDeps(&stubRetriever{})
+ deps.MetadataResolver = &stubMetadataResolver{metas: common.MetaData{
+ "title": {"A": {"d1"}},
+ "question_id": {"444": {"d1"}},
+ "source_uri": {"s3://x": {"d1"}},
+ "pageid": {"1": {"d1"}},
+ "outline": {"intro": {"d1"}},
+ "_version": {"2": {"d1"}},
+ }}
+
+ cat := MetadataCatalogFor(context.Background(), deps)
+ if got := strings.Join(cat.Keys, ","); got != "title" {
+ t.Fatalf("keys = %q, want only title", got)
+ }
+ if render := cat.Render(); strings.Contains(render, "question_id") {
+ t.Errorf("the benchmark-annotation key leaked into the catalog:\n%s", render)
+ }
+}
+
+// TestMetadataCatalogForDegradesToEmpty pins the failure contract every "no metadata" path
+// depends on: a nil resolver, an unreadable index, a metadata-free dataset or no bound
+// datasets all yield the EMPTY catalog — never an error and never a panic. An empty
+// catalog is what makes the session keep the shipped title-only schema.
+func TestMetadataCatalogForDegradesToEmpty(t *testing.T) {
+ ctx := context.Background()
+ base, _ := newTestSearchDeps(&stubRetriever{})
+
+ // No resolver wired (deployment without the metadata link).
+ if cat := MetadataCatalogFor(ctx, base); !cat.Empty() {
+ t.Errorf("keys = %v, want empty without a resolver", cat.Keys)
+ }
+ if ptr := MetadataCatalogPtr(ctx, base); ptr != nil {
+ t.Error("MetadataCatalogPtr must be nil for an empty catalog")
+ }
+
+ // Index unreadable.
+ broken := base
+ broken.MetadataResolver = &stubMetadataResolver{flattenErr: errors.New("es down")}
+ if cat := MetadataCatalogFor(ctx, broken); !cat.Empty() {
+ t.Errorf("keys = %v, want empty when the index is unreadable", cat.Keys)
+ }
+
+ // Dataset carries metadata rows but no usable field.
+ blank := base
+ blank.MetadataResolver = &stubMetadataResolver{metas: common.MetaData{
+ "_version": {"2": {"d1"}}, // hidden by the blacklist
+ "empty": {}, // no value to match
+ }}
+ if cat := MetadataCatalogFor(ctx, blank); !cat.Empty() {
+ t.Errorf("keys = %v, want empty when no field is usable", cat.Keys)
+ }
+
+ // No bound datasets at all.
+ unbound, _ := newTestSearchDeps(&stubRetriever{})
+ unbound.KbIDs = nil
+ unbound.MetadataResolver = &stubMetadataResolver{metas: common.MetaData{"title": {"A": {"d1"}}}}
+ if cat := MetadataCatalogFor(ctx, unbound); !cat.Empty() {
+ t.Errorf("keys = %v, want empty without datasets", cat.Keys)
+ }
+}
+
+// TestActiveToolSpecsRendersCatalogKeyEnum pins the payoff: the advertised `key` enum is
+// the dataset's real fields, so a model can name one. Before this it was ["title"] and no
+// other field could be asked for however plainly the question named it.
+func TestActiveToolSpecsRendersCatalogKeyEnum(t *testing.T) {
+ cat := &MetadataCatalog{
+ Keys: []string{"author", "title"},
+ Samples: map[string][]MetadataSample{"author": {{Value: "Alice", Docs: 1}}},
+ }
+ ts := &Toolset{ThinkingMode: "high", MetadataFields: cat}
+ spec, ok := findSpec(ts.ActiveToolSpecs(), "metadata_search")
+ if !ok {
+ t.Fatal("metadata_search missing from the high-mode surface")
+ }
+
+ if got := strings.Join(metadataKeyEnum(spec), ","); got != "author,title" {
+ t.Errorf("key enum = %q, want the catalog's fields", got)
+ }
+ desc := spec.Function.Description
+ for _, want := range []string{"WHEN TO CALL", "DO NOT CALL", "ARGUMENTS", "OUTPUT", "IF IT FAILS", "AVAILABLE METADATA"} {
+ if !strings.Contains(desc, want) {
+ t.Errorf("description missing %q:\n%s", want, desc)
+ }
+ }
+ // The key parameter's description is dataset-independent — it points at AVAILABLE METADATA
+ // and names no field, so a dataset's field list can never leak into another session's view
+ // of the tool; the fields themselves reach the model through the enum asserted above and
+ // through the seed's block.
+ const wantKeyDesc = "one of this dataset's metadata fields (see AVAILABLE METADATA)"
+ if got, _ := metadataKeyParam(spec)["description"].(string); got != wantKeyDesc {
+ t.Errorf("key description = %q, want %q", got, wantKeyDesc)
+ }
+ if n := utf8.RuneCountInString(desc); n > maxToolDescriptionRunes {
+ t.Errorf("description = %d runes, cap = %d", n, maxToolDescriptionRunes)
+ }
+}
+
+// TestActiveToolSpecsKeepsStaticSpecWithoutCatalog pins the "no metadata = no field
+// advertised" contract: without a catalog the shipped spec is returned untouched — same
+// struct — and it names NO field, so a model cannot be told `title` is filterable on a
+// dataset that never said so. That is also how an empty enum (which some providers reject)
+// is avoided.
+func TestActiveToolSpecsKeepsStaticSpecWithoutCatalog(t *testing.T) {
+ for _, cat := range []*MetadataCatalog{nil, &MetadataCatalog{}} {
+ ts := &Toolset{ThinkingMode: "high", MetadataFields: cat}
+ spec, ok := findSpec(ts.ActiveToolSpecs(), "metadata_search")
+ if !ok {
+ t.Fatal("metadata_search missing from the high-mode surface")
+ }
+ if !reflect.DeepEqual(spec, ToolMap["metadata_search"]) {
+ t.Errorf("catalog %v: an empty catalog must leave the shipped spec untouched", cat)
+ }
+ if got := metadataKeyEnum(spec); len(got) != 0 {
+ t.Errorf("key enum = %v, want NO advertised field without a catalog", got)
+ }
+ key, _ := metadataKeyParam(spec)["enum"]
+ if key != nil {
+ t.Errorf("key enum key = %v, want it absent (an empty enum is rejected by some providers)", key)
+ }
+ if strings.Contains(spec.Function.Description, "'title'") {
+ t.Errorf("the shipped description still names a field:\n%s", spec.Function.Description)
+ }
+ }
+}
+
+// metadataKeyParam reads the metadata_search `key` parameter object off a spec.
+func metadataKeyParam(spec ToolSpec) map[string]any {
+ props, _ := spec.Function.Parameters["properties"].(map[string]any)
+ filters, _ := props["filters"].(map[string]any)
+ items, _ := filters["items"].(map[string]any)
+ itemProps, _ := items["properties"].(map[string]any)
+ key, _ := itemProps["key"].(map[string]any)
+ return key
+}
+
+// stubDeclaredMetadata is a scripted DeclaredMetadataResolver.
+type stubDeclaredMetadata struct {
+ defs []common.MetadataFieldDef
+ err error
+}
+
+func (s *stubDeclaredMetadata) DeclaredMetadataFields(context.Context, []string) ([]common.MetadataFieldDef, error) {
+ return s.defs, s.err
+}
+
+// TestMetadataCatalogForIncludesDeclaredFields pins the declarative half: a dataset that
+// declares its fields is described with what each field MEANS and which values it accepts,
+// which is what the metadata index alone cannot supply. It also pins that the blacklist
+// applies to the declarative source too.
+func TestMetadataCatalogForIncludesDeclaredFields(t *testing.T) {
+ deps, _ := newTestSearchDeps(&stubRetriever{})
+ deps.MetadataResolver = &stubMetadataResolver{metas: common.MetaData{
+ "author": {"Alice": {"d1", "d2"}},
+ }}
+ deps.DeclaredMetadata = &stubDeclaredMetadata{defs: []common.MetadataFieldDef{
+ {Key: "author", Type: "string", Description: "who wrote it"},
+ {Key: "doc_type", Type: "string", Description: "kind of document", Enum: []string{"report", "paper"}},
+ {Key: "question_id", Description: "benchmark label"}, // blacklisted
+ }}
+
+ cat := MetadataCatalogFor(context.Background(), deps)
+ if got := strings.Join(cat.Keys, ","); got != "author,doc_type" {
+ t.Fatalf("keys = %q, want the declared fields (minus the blacklist), sorted", got)
+ }
+ if cat.Fields["author"].Description != "who wrote it" {
+ t.Errorf("declared definition lost: %+v", cat.Fields["author"])
+ }
+
+ render := cat.Render()
+ for _, want := range []string{
+ "author — who wrote it",
+ "doc_type — kind of document",
+ "one of: report / paper",
+ `values seen: "Alice" (2 doc(s))`,
+ } {
+ if !strings.Contains(render, want) {
+ t.Errorf("render missing %q:\n%s", want, render)
+ }
+ }
+ if strings.Contains(render, "question_id") {
+ t.Errorf("the blacklist must cover the declarative source too:\n%s", render)
+ }
+}
+
+// TestMetadataCatalogForOffersDeclaredFieldWithoutIndexedValues pins the case the
+// observational source cannot see at all: a field declared but not yet indexed is still a
+// legitimate filter, so it is offered (with its description) and advertised in the schema.
+func TestMetadataCatalogForOffersDeclaredFieldWithoutIndexedValues(t *testing.T) {
+ deps, _ := newTestSearchDeps(&stubRetriever{})
+ deps.MetadataResolver = &stubMetadataResolver{metas: common.MetaData{}}
+ deps.DeclaredMetadata = &stubDeclaredMetadata{defs: []common.MetadataFieldDef{
+ {Key: "doc_type", Description: "kind of document", Enum: []string{"report"}},
+ }}
+
+ cat := MetadataCatalogFor(context.Background(), deps)
+ if got := strings.Join(cat.Keys, ","); got != "doc_type" {
+ t.Fatalf("keys = %q, want the declared field even with no indexed value", got)
+ }
+ if len(cat.Samples["doc_type"]) != 0 {
+ t.Errorf("samples = %v, want none: the index carries no value yet", cat.Samples["doc_type"])
+ }
+
+ ts := &Toolset{ThinkingMode: "high", MetadataFields: &cat}
+ spec, ok := findSpec(ts.ActiveToolSpecs(), "metadata_search")
+ if !ok {
+ t.Fatal("metadata_search missing from the high-mode surface")
+ }
+ if got := strings.Join(metadataKeyEnum(spec), ","); got != "doc_type" {
+ t.Errorf("key enum = %q, want the declared field advertised", got)
+ }
+}
+
+// TestMetadataCatalogForDegradesWhenDeclaredReadFails pins the independence of the two
+// halves: an unreadable parser_config leaves the observational source untouched, and vice
+// versa (see TestMetadataCatalogForDegradesToEmpty for the index failure).
+func TestMetadataCatalogForDegradesWhenDeclaredReadFails(t *testing.T) {
+ deps, _ := newTestSearchDeps(&stubRetriever{})
+ deps.MetadataResolver = &stubMetadataResolver{metas: common.MetaData{"title": {"A": {"d1"}}}}
+ deps.DeclaredMetadata = &stubDeclaredMetadata{err: errors.New("kb row unreadable")}
+
+ cat := MetadataCatalogFor(context.Background(), deps)
+ if got := strings.Join(cat.Keys, ","); got != "title" {
+ t.Errorf("keys = %q, want the observational half alone", got)
+ }
+}
+
+// metadataKeyEnum reads the metadata_search `key` enum off a rendered spec.
+func metadataKeyEnum(spec ToolSpec) []string {
+ props, _ := spec.Function.Parameters["properties"].(map[string]any)
+ filters, _ := props["filters"].(map[string]any)
+ items, _ := filters["items"].(map[string]any)
+ itemProps, _ := items["properties"].(map[string]any)
+ key, _ := itemProps["key"].(map[string]any)
+ out, _ := key["enum"].([]string)
+ return out
+}
+
func (s *stubExpander) Expand(_ context.Context, _ *Kbinfos, _, _ string, _ []string) error {
s.calls++
return nil
diff --git a/internal/rag/agentic-rag/runtime/tool_text_processing.go b/internal/rag/agentic-rag/runtime/tool_text_processing.go
index ea4ef4c0e7..63ad93acb2 100644
--- a/internal/rag/agentic-rag/runtime/tool_text_processing.go
+++ b/internal/rag/agentic-rag/runtime/tool_text_processing.go
@@ -270,7 +270,13 @@ func NarrowContent(content string, kwds []string) (string, bool) {
}
lowContent := strings.ToLower(content)
if strings.Contains(lowContent, "<table") || strings.Contains(lowContent, "<tr") || strings.Contains(lowContent, "<td") {
- return "..." + HighlightKeywords(content, kwds) + "...", true
+ // Serialize the table to Markdown before the model sees it: the format
+ // comparison over 11 serializations ranks Markdown-KV first for field lookups
+ // (key: value beats header/position alignment) and a Markdown table as the
+ // cost/accuracy compromise; raw HTML is the expensive and least readable
+ // option. The row set is NOT pruned — rank/order and completeness decide table
+ // answers. Falls back to the raw text when nothing renders.
+ return "..." + HighlightKeywords(TableViewOrRaw(content), kwds) + "...", true
}
pipeRows := 0
for _, line := range strings.Split(content, "\n") {
diff --git a/internal/rag/prompts/action_run.md b/internal/rag/prompts/action_run.md
index b2f327c50a..16a0b70fe5 100644
--- a/internal/rag/prompts/action_run.md
+++ b/internal/rag/prompts/action_run.md
@@ -59,12 +59,18 @@ CRITICAL RULES
# TOOL PLAYBOOK
-You get tools only in medium / high (7 tools: `retrieve`, `search_chunks`, `list_chunks`, `navigate_tree`, `navigate_structure`, `calculate`, `web_search`) and ultra (those 7 + `graph_explore`). Low mode has NO tool loop — answer with plain retrieval. Every native tool call still REQUIRES the decision envelope from CRITICAL RULES (it is a mandatory tool parameter, not optional).
+Available tools: `retrieve`, `search_chunks`, `metadata_search`, `list_chunks`,
+`navigate_tree`, `navigate_structure`, `calculate`, and `web_search` (only when a
+web provider is configured); `graph_explore` joins them in ultra mode. Low mode
+has NO tool loop — answer with plain retrieval. Per-tool WHEN TO CALL /
+DO NOT CALL / ARGUMENTS / IF IT FAILS details live in each tool's own schema —
+this playbook covers only how to COMBINE tools and when to STOP.
## 1. Combination chains (call in this order)
- **You already hold a `doc_id`** → `navigate_structure(doc_id, query)` to find the right passage, then `list_chunks(doc_id)` to read it. Do NOT call `navigate_tree` first.
- **No `doc_id` yet, and the corpus is large** → `navigate_tree(query)` to route to candidate documents, take a `doc_id`, then `navigate_structure(doc_id, query)` → `list_chunks(doc_id)`.
+- **You can name the document / need to narrow the search** → `metadata_search(filters)` ONCE per direction to SELECT the matching documents by a metadata field (use only the fields listed under `AVAILABLE METADATA`; any other key is rejected). It returns `doc_ids` only — no passages — so spend them: `list_chunks(doc_id)` to read a document, `navigate_structure(doc_id, query)` to pinpoint a passage, or `retrieve(query, doc_scope=[ids])` to search INSIDE those documents.
- **Exact term / short answer** → `retrieve(query[1-3])` first; if snippets are insufficient, `search_chunks(query[1-2])` (semantic, may find passages with NO shared surface words); if you need the full document, `list_chunks(doc_id)`.
- **You must DERIVE a number** → first collect every needed number with any of the above, then `calculate(question, facts)` with the facts verbatim, and report the computed result as-is. If the answer is already one of the stated numbers, answer directly.
- **Relational multi-hop (ultra only)** → get a start entity from `search_chunks` / `navigate_structure`, then `graph_explore(query, doc_scope)`.
@@ -89,3 +95,8 @@ Each tool returns a status. Act on it:
| `poor` | Output returned but too weak to use | Add evidence with another tool |
| `redundant` | Every hit was already in your evidence | Stop re-searching; emit a `<state>` patch with what you have |
| `error` | Infrastructure / provider failure | Switch tools; do not retry the same call |
+
+Special case — `metadata_search` (at most ONCE per direction):
+- `ok` → it selected documents and returned their `doc_ids` (no passages). Spend them now: `list_chunks(doc_id)` / `navigate_structure(doc_id, query)` / `retrieve(query, doc_scope=[ids])`; do NOT call `metadata_search` again this direction.
+- `miss` / `empty` → nothing matched the filter; drop it (or retry once with a field/value from `AVAILABLE METADATA`) and fall back to `search_chunks` / `navigate_tree`. A call naming no usable field is answered with the dataset's real fields — do not repeat the same key.
+- `poor` → the filter was too narrow; widen it once, or abandon it for plain retrieval.
diff --git a/internal/service/chat_pipeline.go b/internal/service/chat_pipeline.go
index ce18d33f66..270cab2936 100644
--- a/internal/service/chat_pipeline.go
+++ b/internal/service/chat_pipeline.go
@@ -823,7 +823,12 @@ func (s *ChatPipelineService) AsyncChat(
if kwargs["store_history_messages"] == false {
history = messages
}
- hk, slotCites, citeChunkIDs, harnessAnswer, hErr := s.retrieveViaHarness(ctx, question, kbs, docIDs, imageFiles, attachments, thinkingMode, chat.TenantID, chat.LLMID, chat.ID, webSearch, sink, thinkSink, harnessSystemPrompt, history)
+ hk, slotCites, citeChunkIDs, harnessAnswer, hErr := s.retrieveViaHarness(ctx, question, kbs, docIDs, imageFiles, attachments, thinkingMode, chat.TenantID, chat.LLMID, chat.ID, HarnessRetrieval{
+ TopN: int(chat.TopN),
+ SimilarityThreshold: chat.SimilarityThreshold,
+ VectorSimilarityWeight: chat.VectorSimilarityWeight,
+ RerankCandidatesCount: int(chat.RerankCandidatesCount),
+ }, webSearch, sink, thinkSink, harnessSystemPrompt, history)
// The harness streams think-then-answer inside ONE compose call.
// Close the block here, once that call (and its trailing
// narration line) has returned: a reasoning-only run would
@@ -5052,6 +5057,19 @@ func harnessBoundDatasetNames(kbs []*entity.Knowledgebase) string {
return strings.Join(names, ", ")
}
+// HarnessRetrieval is the dialog-level retrieval tuning the chat pipeline hands
+// to the agentic harness. Without it the harness falls back to its package
+// defaults (top_n=12), silently overriding the dialog's configured top_n and
+// making a reasoning run retrieve a different passage set than the standard
+// path — a two-document comparison could come back with one document's chunks
+// filling the whole budget.
+type HarnessRetrieval struct {
+ TopN int
+ SimilarityThreshold float64
+ VectorSimilarityWeight float64
+ RerankCandidatesCount int
+}
+
// HarnessRequest carries the minimal inputs the chat pipeline hands to the
// agentic-RAG harness for evidence collection.
type HarnessRequest struct {
@@ -5100,6 +5118,9 @@ type HarnessRequest struct {
// its own evidence block). Empty when the dialog configures none — Python
// then composes without the "# Assistant configuration" block.
SystemPrompt string
+ // Retrieval is the dialog's own retrieval tuning, so the harness searches
+ // with the same budget as the standard path.
+ Retrieval HarnessRetrieval
}
// HarnessResult is the evidence the harness returns, normalized to the map
@@ -5186,7 +5207,7 @@ func harnessThinkSink(ctx context.Context, out chan<- AsyncChatResult) func(Thin
}
}
-func (s *ChatPipelineService) retrieveViaHarness(ctx context.Context, question string, kbs []*entity.Knowledgebase, docIDs []string, images []string, textAttachments string, thinkingMode, tenantID, modelID, sessionID string, webSearch func(context.Context, []string) ([]string, error), answerSink func(delta string, isThink bool), thinkSink func(ThinkEvent), dialogSystemPrompt string, messages []map[string]interface{}) (map[string]interface{}, map[string][]string, []string, string, error) {
+func (s *ChatPipelineService) retrieveViaHarness(ctx context.Context, question string, kbs []*entity.Knowledgebase, docIDs []string, images []string, textAttachments string, thinkingMode, tenantID, modelID, sessionID string, retrieval HarnessRetrieval, webSearch func(context.Context, []string) ([]string, error), answerSink func(delta string, isThink bool), thinkSink func(ThinkEvent), dialogSystemPrompt string, messages []map[string]interface{}) (map[string]interface{}, map[string][]string, []string, string, error) {
if harnessRetriever == nil {
return nil, nil, nil, "", fmt.Errorf("harness retriever not wired at bootstrap")
}
@@ -5211,6 +5232,7 @@ func (s *ChatPipelineService) retrieveViaHarness(ctx context.Context, question s
TextAttachments: textAttachments,
WebSearch: webSearch,
SystemPrompt: dialogSystemPrompt,
+ Retrieval: retrieval,
})
if err != nil {
return nil, nil, nil, "", err
diff --git a/internal/service/chat_pipeline_test.go b/internal/service/chat_pipeline_test.go
index a7c6f47ff1..b89ea8304e 100644
--- a/internal/service/chat_pipeline_test.go
+++ b/internal/service/chat_pipeline_test.go
@@ -1633,6 +1633,36 @@ func stubHarness(t *testing.T, answer string) {
}
}
+// TestRetrieveViaHarnessForwardsRetrievalTuning pins the fix for a harness that
+// ignored the dialog's retrieval settings: without them it falls back to its
+// package default top_n=12, so a dialog configured with top_n=8 retrieved a
+// different passage set than the standard path — the failure that answered a
+// two-document comparison from one document's chunks because that document's
+// nine chunks filled the widened budget.
+func TestRetrieveViaHarnessForwardsRetrievalTuning(t *testing.T) {
+ prev := harnessRetriever
+ t.Cleanup(func() { harnessRetriever = prev })
+ var got HarnessRequest
+ harnessRetriever = func(_ context.Context, req HarnessRequest) (HarnessResult, error) {
+ got = req
+ return HarnessResult{}, nil
+ }
+
+ s := &ChatPipelineService{}
+ want := HarnessRetrieval{
+ TopN: 8,
+ SimilarityThreshold: 0.2,
+ VectorSimilarityWeight: 0.3,
+ RerankCandidatesCount: 64,
+ }
+ if _, _, _, _, err := s.retrieveViaHarness(t.Context(), "q", nil, nil, nil, "", "low", "t", "m", "sess", want, nil, nil, nil, "", nil); err != nil {
+ t.Fatalf("retrieveViaHarness: %v", err)
+ }
+ if got.Retrieval != want {
+ t.Errorf("harness retrieval = %+v, want %+v", got.Retrieval, want)
+ }
+}
+
// collectSink records every delta with its isThink flag.
func collectSink(got *[]string, thinks *[]bool) func(string, bool) {
return func(delta string, isThink bool) {
@@ -1668,7 +1698,7 @@ func TestRetrieveViaHarnessDoesNotSynthesizeLoopLines(t *testing.T) {
var thinks []bool
var events []ThinkEvent
s := &ChatPipelineService{}
- _, _, _, answer, err := s.retrieveViaHarness(t.Context(), "q", nil, nil, nil, "", "high", "t", "m", "sess", nil, collectSink(&got, &thinks), collectThinkSink(&events), "", history)
+ _, _, _, answer, err := s.retrieveViaHarness(t.Context(), "q", nil, nil, nil, "", "high", "t", "m", "sess", HarnessRetrieval{}, nil, collectSink(&got, &thinks), collectThinkSink(&events), "", history)
if err != nil {
t.Fatalf("retrieveViaHarness: %v", err)
}
@@ -1709,7 +1739,7 @@ func TestRetrieveViaHarnessForwardsThinkSink(t *testing.T) {
// channel) and the local `got` below is the EVENT, so leave answerSink nil.
var events []ThinkEvent
s := &ChatPipelineService{}
- if _, _, _, _, err := s.retrieveViaHarness(t.Context(), "q", nil, nil, nil, "", "high", "t", "m", "sess", nil, nil, collectThinkSink(&events), "", nil); err != nil {
+ if _, _, _, _, err := s.retrieveViaHarness(t.Context(), "q", nil, nil, nil, "", "high", "t", "m", "sess", HarnessRetrieval{}, nil, nil, collectThinkSink(&events), "", nil); err != nil {
t.Fatalf("retrieveViaHarness: %v", err)
}
// Only what the harness reported: the pipeline adds nothing of its own.
@@ -1766,7 +1796,7 @@ func TestRetrieveViaHarnessNaiveEmitsNothing(t *testing.T) {
var got []string
var thinks []bool
s := &ChatPipelineService{}
- if _, _, _, _, err := s.retrieveViaHarness(t.Context(), "q", nil, nil, nil, "", "naive", "t", "m", "sess", nil, collectSink(&got, &thinks), nil, "", nil); err != nil {
+ if _, _, _, _, err := s.retrieveViaHarness(t.Context(), "q", nil, nil, nil, "", "naive", "t", "m", "sess", HarnessRetrieval{}, nil, collectSink(&got, &thinks), nil, "", nil); err != nil {
t.Fatalf("retrieveViaHarness: %v", err)
}
if len(got) != 0 {
diff --git a/internal/service/metadata.go b/internal/service/metadata.go
index f3354b88a5..552b9c6a51 100644
--- a/internal/service/metadata.go
+++ b/internal/service/metadata.go
@@ -158,6 +158,66 @@ func (s *MetadataService) SearchMetadataByKBs(ctx context.Context, kbIDs []strin
}, nil
}
+// MetadataForDocIDs returns doc_id → its metadata fields, reading ONLY the given documents
+// (the doc-scoped query runtime.MetadataResolver.MetadataForDocIDs needs).
+//
+// Best effort: a dataset whose tenant lookup or index read fails contributes nothing and
+// the failure is returned, but the documents another dataset answered for are still
+// returned. The caller has already resolved the document ids, so a missing context block
+// must not turn a successful selection into an error.
+func (s *MetadataService) MetadataForDocIDs(ctx context.Context, kbIDs, docIDs []string) (map[string]map[string]any, error) {
+ if s == nil || s.docEngine == nil || len(kbIDs) == 0 || len(docIDs) == 0 {
+ return nil, nil
+ }
+ out := make(map[string]map[string]any, len(docIDs))
+ var firstErr error
+ for _, kbID := range kbIDs {
+ tenantID, err := s.GetTenantIDByKBID(ctx, kbID)
+ if err != nil || tenantID == "" {
+ if err != nil && firstErr == nil {
+ firstErr = err
+ }
+ continue
+ }
+ res, err := s.SearchMetadata(ctx, kbID, tenantID, docIDs, len(docIDs))
+ if err != nil {
+ if firstErr == nil {
+ firstErr = err
+ }
+ continue
+ }
+ for docID, meta := range ConvertSearchResultToDocMeta(res.MetadataRecords) {
+ if _, exists := out[docID]; !exists {
+ out[docID] = meta
+ }
+ }
+ }
+ return out, firstErr
+}
+
+// DeclaredMetadataFields implements runtime.DeclaredMetadataResolver: it reads the metadata
+// fields each dataset DECLARES in its parser_config — the {key, type, description, enum}
+// definitions the metadata config API writes for extraction.
+//
+// One row read per dataset and no index scan, so it is cheap enough to run per
+// metadata_search call. An unknown dataset is skipped rather than failing the read, and a
+// dataset that declares nothing contributes nothing: the caller always has the metadata
+// index as its other half.
+func (s *MetadataService) DeclaredMetadataFields(ctx context.Context, kbIDs []string) ([]common.MetadataFieldDef, error) {
+ if len(kbIDs) == 0 {
+ return nil, nil
+ }
+ var out []common.MetadataFieldDef
+ for _, kbID := range kbIDs {
+ kb, err := s.kbDAO.GetByID(ctx, dao.DB, kbID)
+ if err != nil || kb == nil {
+ continue
+ }
+ out = append(out, common.DeclaredMetadataFieldsFromParserConfig(kb.ParserConfig)...)
+ }
+ return out, nil
+}
+
// GetFlattedMetaByKBs returns flattened metadata in the format:
// {field_name: {value: [doc_ids]}}
func (s *MetadataService) GetFlattedMetaByKBs(ctx context.Context, kbIDs []string) (common.MetaData, error) {
@@ -267,6 +327,25 @@ func (s *MetadataService) GetFlattedMetaByKBs(ctx context.Context, kbIDs []strin
return flattedMeta, nil
}
+// FilterDocIDsByMetaPushdown runs ONLY the metadata-index push-down, which is the first
+// half of the agentic metadata_search pipeline (the caller falls back to
+// GetFlattedMetaByKBs + ApplyMetaFilter when the push-down is not viable).
+//
+// ok=false means the push-down is not viable or errored; ok=true with an empty slice is
+// the definitive "no document matches". That split is the engine's own contract
+// (engine.DocEngine.FilterDocIdsByMetaPushdown returns nil for "not viable"), surfaced
+// here so the caller does not have to reach into the engine itself.
+func (s *MetadataService) FilterDocIDsByMetaPushdown(ctx context.Context, kbIDs []string, filters []map[string]any, logic string) ([]string, bool) {
+ if s == nil || s.docEngine == nil || len(kbIDs) == 0 || len(filters) == 0 {
+ return nil, false
+ }
+ docIDs := s.docEngine.FilterDocIdsByMetaPushdown(ctx, dao.DB, kbIDs, filters, logic)
+ if docIDs == nil {
+ return nil, false
+ }
+ return docIDs, true
+}
+
// CollectDocIDsByKB collects unique (kb_id, doc_id) pairs from chunks.
func CollectDocIDsByKB(chunks []map[string]interface{}) KBDocIDsMap {
seen := make(map[string]struct{})
diff --git a/internal/service/metadata_resolver_test.go b/internal/service/metadata_resolver_test.go
new file mode 100644
index 0000000000..842896fab9
--- /dev/null
+++ b/internal/service/metadata_resolver_test.go
@@ -0,0 +1,107 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package service
+
+import (
+ "context"
+ "testing"
+
+ "gorm.io/gorm"
+)
+
+// pushdownDocEngine is the shared fake with a scripted push-down answer: the agentic
+// metadata_search adapter is only interesting for what it does with the engine's
+// nil / non-nil contract.
+type pushdownDocEngine struct {
+ fakeChatDocEngine
+ ids []string
+ calls int
+ gotKbIDs []string
+ gotConds []map[string]interface{}
+ gotLogic string
+}
+
+func (e *pushdownDocEngine) FilterDocIdsByMetaPushdown(_ context.Context, _ *gorm.DB, kbIDs []string, conditions []map[string]interface{}, logic string) []string {
+ e.calls++
+ e.gotKbIDs = kbIDs
+ e.gotConds = conditions
+ e.gotLogic = logic
+ return e.ids
+}
+
+// TestFilterDocIDsByMetaPushdownSurfacesTheEngineContract pins the nil / non-nil split:
+// nil means "push-down not viable" and must reach the caller as ok=false (so it falls
+// back to the in-memory filter), while a non-nil slice — empty included — is definitive.
+func TestFilterDocIDsByMetaPushdownSurfacesTheEngineContract(t *testing.T) {
+ filters := []map[string]any{{"key": "title", "op": "contains", "value": "New York"}}
+
+ eng := &pushdownDocEngine{}
+ svc := NewMetadataServiceForTest(nil, eng)
+ if ids, ok := svc.FilterDocIDsByMetaPushdown(context.Background(), []string{"kb1"}, filters, "and"); ok || ids != nil {
+ t.Errorf("ids=%v ok=%v, want the not-viable signal", ids, ok)
+ }
+ if eng.calls != 1 {
+ t.Errorf("engine calls = %d, want 1", eng.calls)
+ }
+ if len(eng.gotKbIDs) != 1 || eng.gotKbIDs[0] != "kb1" {
+ t.Errorf("engine kbIDs = %v", eng.gotKbIDs)
+ }
+ if len(eng.gotConds) != 1 || eng.gotConds[0]["key"] != "title" {
+ t.Errorf("engine conditions = %v", eng.gotConds)
+ }
+
+ // An empty-but-definitive result must stay distinguishable from "not viable".
+ emptySvc := NewMetadataServiceForTest(nil, &pushdownDocEngine{ids: []string{}})
+ if ids, ok := emptySvc.FilterDocIDsByMetaPushdown(context.Background(), []string{"kb1"}, filters, "and"); !ok || len(ids) != 0 {
+ t.Errorf("ids=%v ok=%v, want a definitive empty result", ids, ok)
+ }
+
+ // Hits are forwarded verbatim, with logic intact.
+ hitEng := &pushdownDocEngine{ids: []string{"d1", "d2"}}
+ hitSvc := NewMetadataServiceForTest(nil, hitEng)
+ ids, ok := hitSvc.FilterDocIDsByMetaPushdown(context.Background(), []string{"kb1"}, filters, "or")
+ if !ok || len(ids) != 2 || ids[0] != "d1" || ids[1] != "d2" {
+ t.Errorf("ids=%v ok=%v, want the engine's hits", ids, ok)
+ }
+ if hitEng.gotLogic != "or" {
+ t.Errorf("engine logic = %q, want or", hitEng.gotLogic)
+ }
+}
+
+// TestFilterDocIDsByMetaPushdownGuards pins the guards: a missing engine, no datasets or
+// no conditions answer "not viable" WITHOUT reaching the engine (the caller then falls
+// back, or reports a miss when the fallback has nothing either).
+func TestFilterDocIDsByMetaPushdownGuards(t *testing.T) {
+ filters := []map[string]any{{"key": "title", "op": "contains", "value": "New York"}}
+ ctx := context.Background()
+
+ if ids, ok := NewMetadataServiceForTest(nil, nil).FilterDocIDsByMetaPushdown(ctx, []string{"kb1"}, filters, "and"); ok || ids != nil {
+ t.Errorf("ids=%v ok=%v, want not-viable without an engine", ids, ok)
+ }
+
+ eng := &pushdownDocEngine{ids: []string{"d1"}}
+ svc := NewMetadataServiceForTest(nil, eng)
+ if _, ok := svc.FilterDocIDsByMetaPushdown(ctx, nil, filters, "and"); ok {
+ t.Error("no datasets must report not-viable")
+ }
+ if _, ok := svc.FilterDocIDsByMetaPushdown(ctx, []string{"kb1"}, nil, "and"); ok {
+ t.Error("no conditions must report not-viable")
+ }
+ if eng.calls != 0 {
+ t.Errorf("engine calls = %d, want 0 for every guard", eng.calls)
+ }
+}