Skip to content

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

fix(agent): validate graph relation evidence in every query scope (#3955)

knqiufan208d76cf5669
diff --git a/internal/agent/tools/query_knowledge_graph.go b/internal/agent/tools/query_knowledge_graph.go
index ee1fd1221..15c1ccd41 100644
--- a/internal/agent/tools/query_knowledge_graph.go
+++ b/internal/agent/tools/query_knowledge_graph.go
@@ -61,8 +61,13 @@ func (t *QueryKnowledgeGraphTool) WithGraph(
const (
// graphQueryMaxTerms bounds the entity-name terms sent to the graph store.
graphQueryMaxTerms = 8
- // graphQueryMaxChunks bounds the evidence chunks loaded per knowledge base.
+ // graphQueryMaxChunks bounds the evidence chunks displayed per knowledge base.
graphQueryMaxChunks = 10
+ // graphQueryChunkBatchSize bounds each evidence lookup, independently of the output cap.
+ graphQueryChunkBatchSize = 128
+ // graphQueryMaxEvidenceCandidates bounds validation work per knowledge base,
+ // including candidates that are missing, disabled or outside the query scope.
+ graphQueryMaxEvidenceCandidates = 512
// graphQueryMaxRelations bounds the relations returned to the model.
graphQueryMaxRelations = 30
)
@@ -72,17 +77,19 @@ const (
// list read without a marker is the entity's whole neighbourhood to the model,
// and it then answers "X is not related to Y" from a list that never held Y.
type graphTruncation struct {
- relationsShown int
- relationsTotal int
- chunksFetched int
- chunksTotal int
- termsMatched int
- termsTotal int
+ relationsShown int
+ relationsTotal int
+ chunksShown int
+ chunksTotal int
+ termsMatched int
+ termsTotal int
+ validationLimited bool
+ candidatesValidatedTotal int
}
// truncated reports whether any cap fired.
func (tr graphTruncation) truncated() bool {
- return tr.relationsTotal > tr.relationsShown || tr.chunksTotal > tr.chunksFetched ||
+ return tr.validationLimited || tr.relationsTotal > tr.relationsShown || tr.chunksTotal > tr.chunksShown ||
tr.termsTotal > tr.termsMatched
}
@@ -94,15 +101,25 @@ func (tr graphTruncation) statement() string {
}
var b strings.Builder
b.WriteString("=== ⚠️ Truncated ===\n")
+ qualifier := ""
+ if tr.validationLimited {
+ qualifier = "at least "
+ fmt.Fprintf(&b, " - Graph evidence validation stopped with unchecked candidates remaining "+
+ "(cap %d per knowledge base). %d candidates were validated in total. "+
+ "Some candidate evidence was not checked. "+
+ "Found at least %d valid in-scope evidence chunks and at least %d supported relations. "+
+ "Narrow the query before concluding that a relation does not exist.\n",
+ graphQueryMaxEvidenceCandidates, tr.candidatesValidatedTotal, tr.chunksTotal, tr.relationsTotal)
+ }
if tr.relationsTotal > tr.relationsShown {
- fmt.Fprintf(&b, " - Relations: %d of %d shown (cap %d per query). These entities have more relations "+
+ fmt.Fprintf(&b, " - Relations: %d of %s%d shown (cap %d per query). These entities have more relations "+
"than the ones listed below; query a single entity by name to see its neighbourhood.\n",
- tr.relationsShown, tr.relationsTotal, graphQueryMaxRelations)
+ tr.relationsShown, qualifier, tr.relationsTotal, graphQueryMaxRelations)
}
- if tr.chunksTotal > tr.chunksFetched {
- fmt.Fprintf(&b, " - Graph evidence chunks: %d of %d fetched (cap %d per knowledge base). Some of these "+
+ if tr.chunksTotal > tr.chunksShown {
+ fmt.Fprintf(&b, " - Graph evidence chunks: %d of %s%d shown (cap %d per knowledge base). Some of these "+
"entities' source chunks are not part of this result.\n",
- tr.chunksFetched, tr.chunksTotal, graphQueryMaxChunks)
+ tr.chunksShown, qualifier, tr.chunksTotal, graphQueryMaxChunks)
}
if tr.termsTotal > tr.termsMatched {
fmt.Fprintf(&b, " - Entity terms: %d of %d query words were matched against entity names (cap %d). A word "+
@@ -117,13 +134,20 @@ func (tr graphTruncation) statement() string {
// fired: an absent key means nothing was dropped. The model reads a view
// rebuilt from these keys, so the marker has to travel here too.
func (tr graphTruncation) addToData(data map[string]interface{}) {
- if tr.relationsTotal > tr.relationsShown {
+ if tr.relationsTotal > tr.relationsShown || tr.validationLimited {
data["relations_total"] = tr.relationsTotal
data["relations_omitted"] = tr.relationsTotal - tr.relationsShown
}
- if tr.chunksTotal > tr.chunksFetched {
+ if tr.chunksTotal > tr.chunksShown || tr.validationLimited {
data["graph_chunks_total"] = tr.chunksTotal
- data["graph_chunks_omitted"] = tr.chunksTotal - tr.chunksFetched
+ data["graph_chunks_omitted"] = tr.chunksTotal - tr.chunksShown
+ }
+ if tr.validationLimited {
+ data["graph_validation_truncated"] = true
+ data["graph_candidates_validated_total"] = tr.candidatesValidatedTotal
+ data["graph_validation_limit_per_kb"] = graphQueryMaxEvidenceCandidates
+ data["graph_chunks_total_is_lower_bound"] = true
+ data["relations_total_is_lower_bound"] = true
}
if tr.termsTotal > tr.termsMatched {
data["query_terms_total"] = tr.termsTotal
@@ -171,9 +195,9 @@ func graphSearchTerms(query string) (terms []string, dropped int) {
return terms, dropped
}
-// WithKnowledgeScope enables document/tag-level result filtering for Agent
-// calls. The graph backend queries by KB, so the tool must enforce narrower
-// SearchTargets before returning any result to the model.
+// WithKnowledgeScope supplies document existence/access checks for graph
+// evidence, as well as document/tag-level filtering for Agent calls. The graph
+// backend queries by KB, so narrower SearchTargets must be enforced here.
func (t *QueryKnowledgeGraphTool) WithKnowledgeScope(
knowledgeService interfaces.KnowledgeService,
) *QueryKnowledgeGraphTool {
@@ -230,6 +254,16 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
return &types.ToolResult{Success: false, Error: err.Error()}, err
}
}
+ // Repeated KB IDs must not multiply the per-KB validation budget or counts.
+ kbIDs := make([]string, 0, len(input.KnowledgeBaseIDs))
+ seenKBIDs := make(map[string]bool, len(input.KnowledgeBaseIDs))
+ for _, id := range input.KnowledgeBaseIDs {
+ if !seenKBIDs[id] {
+ seenKBIDs[id] = true
+ kbIDs = append(kbIDs, id)
+ }
+ }
+ input.KnowledgeBaseIDs = kbIDs
query := input.Query
if query == "" {
@@ -241,15 +275,17 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
// Concurrently query all knowledge bases
type graphQueryResult struct {
- kbID string
- kb *types.KnowledgeBase
- graphResults []*types.SearchResult // chunks the matched entities come from
- textResults []*types.SearchResult
- relations []*types.GraphRelation
- chunksFetched int // evidence chunks fetched, before scope filtering
- chunksTotal int // evidence chunks the matched entities reference
- warnings []string // failures of one source while the other returned results
- err error
+ kbID string
+ kb *types.KnowledgeBase
+ graphResults []*types.SearchResult // chunks the matched entities come from
+ textResults []*types.SearchResult
+ relations []*types.GraphRelation
+ chunksShown int // valid evidence chunks selected for display
+ chunksTotal int // valid in-scope evidence before the display cap
+ validationLimited bool
+ candidatesValidated int
+ warnings []string // failures of one source while the other returned results
+ err error
}
var wg sync.WaitGroup
@@ -294,7 +330,8 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
errs = append(errs, fmt.Sprintf("graph query failed: %v", err))
}
graphResults, graph := lookup.chunks, lookup.graph
- res.chunksFetched, res.chunksTotal = lookup.chunksFetched, lookup.chunksTotal
+ res.chunksShown, res.chunksTotal = lookup.chunksShown, lookup.chunksTotal
+ res.validationLimited, res.candidatesValidated = lookup.validationLimited, lookup.candidatesValidated
var relations []*types.GraphRelation
if graph != nil {
relations = graph.Relation
@@ -307,24 +344,12 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
errs = append(errs, fmt.Sprintf("text search failed: %v", err))
}
if t.scopeEnforced {
- if graphResults, err = filterSearchResultsInSearchTargets(
- ctx, t.searchTargets, id, graphResults, t.scopeKnowledgeService,
- ); err != nil {
- res.err = err
- return
- }
if textResults, err = filterSearchResultsInSearchTargets(
ctx, t.searchTargets, id, textResults, t.scopeKnowledgeService,
); err != nil {
res.err = err
return
}
- // The graph namespace is the whole knowledge base, so under a
- // document or tag scope only relations between entities backed
- // by an in-scope chunk may reach the model.
- if !searchTargetsCoverWholeKB(t.searchTargets, id) {
- relations = relationsBackedBy(graph, graphResults)
- }
}
res.graphResults, res.textResults, res.relations = graphResults, textResults, relations
if len(errs) > 0 && len(graphResults) == 0 && len(textResults) == 0 {
@@ -347,7 +372,8 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
var relations []*types.GraphRelation
seenRelations := make(map[string]bool)
relationsTotal := 0
- chunksFetched, chunksTotal := 0, 0
+ chunksShown, chunksTotal := 0, 0
+ validationLimited, candidatesValidatedTotal := false, 0
for _, kbID := range input.KnowledgeBaseIDs {
result := kbResults[kbID]
@@ -364,8 +390,10 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
}
kbCounts[kbID] = len(result.graphResults) + len(result.textResults)
- chunksFetched += result.chunksFetched
+ chunksShown += result.chunksShown
chunksTotal += result.chunksTotal
+ validationLimited = validationLimited || result.validationLimited
+ candidatesValidatedTotal += result.candidatesValidated
for _, r := range result.graphResults {
if !seenChunks[r.ID] {
seenChunks[r.ID] = true
@@ -395,12 +423,14 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
}
}
truncation := graphTruncation{
- relationsShown: len(relations),
- relationsTotal: relationsTotal,
- chunksFetched: chunksFetched,
- chunksTotal: chunksTotal,
- termsMatched: len(terms),
- termsTotal: len(terms) + termsDropped,
+ relationsShown: len(relations),
+ relationsTotal: relationsTotal,
+ chunksShown: chunksShown,
+ chunksTotal: chunksTotal,
+ termsMatched: len(terms),
+ termsTotal: len(terms) + termsDropped,
+ validationLimited: validationLimited,
+ candidatesValidatedTotal: candidatesValidatedTotal,
}
sort.SliceStable(textHits, func(i, j int) bool {
@@ -448,7 +478,10 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
output := "=== Knowledge Graph Query ===\n\n"
output += fmt.Sprintf("📊 Query: %s\n", query)
output += fmt.Sprintf("🎯 Target Knowledge Bases: %v\n", input.KnowledgeBaseIDs)
- if truncation.relationsTotal > truncation.relationsShown {
+ if truncation.validationLimited {
+ output += fmt.Sprintf("✓ Found at least %d supported relations; showing %d relations and %d relevant chunks "+
+ "(deduplicated)\n\n", truncation.relationsTotal, len(relations), len(allResults))
+ } else if truncation.relationsTotal > truncation.relationsShown {
output += fmt.Sprintf("✓ Found %d of %d relations and %d relevant chunks (deduplicated)\n\n",
len(relations), truncation.relationsTotal, len(allResults))
} else {
@@ -573,21 +606,22 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
}, nil
}
-// graphLookup is one knowledge base's graph lookup: the matched graph, the
-// evidence chunks fetched for it, and how many distinct chunks the matched
-// entities reference in total. The two counts travel back with the chunks so a
-// fetch that stopped at graphQueryMaxChunks can be reported as such.
+// graphLookup contains a validated graph and the evidence selected for display.
+// The counts describe valid in-scope evidence before and after the display cap.
+// They are lower bounds when the candidate validation limit stopped the scan.
type graphLookup struct {
- graph *types.GraphData
- chunks []*types.SearchResult
- chunksFetched int
- chunksTotal int
+ graph *types.GraphData
+ chunks []*types.SearchResult
+ chunksShown int
+ chunksTotal int
+ validationLimited bool
+ candidatesValidated int
}
// queryGraph looks the query's entity terms up in kbID's graph and returns
-// the chunks the matched entities were extracted from, plus the matched graph
-// (entities and relations). With no graph store wired, or none configured
-// (the store answers nil), it returns nothing.
+// up to ten valid evidence chunks and relations backed by validated evidence.
+// With no graph store wired, or none configured (the store answers nil), it
+// returns nothing.
func (t *QueryKnowledgeGraphTool) queryGraph(
ctx context.Context, kbID string, terms []string,
) (graphLookup, error) {
@@ -601,39 +635,90 @@ func (t *QueryKnowledgeGraphTool) queryGraph(
if graph == nil {
return graphLookup{}, nil
}
- // Without a chunk store nothing is fetched at all, and none of it was
- // dropped by the cap: leaving the counts at zero keeps that apart from a
- // capped fetch, which must be reported.
- lookup := graphLookup{graph: graph}
- if t.chunkRepo == nil {
- return lookup, nil
- }
- chunkIDs := make([]string, 0, graphQueryMaxChunks)
- referenced := make(map[string]bool)
+ chunkIDs := make([]string, 0, graphQueryMaxEvidenceCandidates)
+ seen := make(map[string]bool)
+ validationLimited := false
+candidateLoop:
for _, node := range graph.Node {
+ if node == nil {
+ continue
+ }
for _, id := range node.Chunks {
- if id == "" || referenced[id] {
- continue
- }
- referenced[id] = true
- // Past the cap a chunk is counted, not fetched: the counts are
- // what tells the caller the evidence is a subset.
- if len(chunkIDs) < graphQueryMaxChunks {
+ if id != "" && !seen[id] {
+ if len(chunkIDs) == graphQueryMaxEvidenceCandidates {
+ validationLimited = true
+ break candidateLoop
+ }
+ seen[id] = true
chunkIDs = append(chunkIDs, id)
}
}
}
- lookup.chunksFetched, lookup.chunksTotal = len(chunkIDs), len(referenced)
if len(chunkIDs) == 0 {
- return lookup, nil
+ return graphLookup{graph: &types.GraphData{Node: graph.Node}}, nil
+ }
+ if t.chunkRepo == nil {
+ return graphLookup{}, fmt.Errorf("chunk repository is unavailable for graph evidence validation")
+ }
+ // Validate a bounded prefix before limiting displayed text. Evidence beyond
+ // the tenth candidate can support an edge, but unchecked evidence never can.
+ // These lookups load metadata only; content is fetched for display IDs below.
+ var evidence []*types.SearchResult
+ selected := make([]*types.SearchResult, 0, graphQueryMaxChunks)
+ for start := 0; start < len(chunkIDs); start += graphQueryChunkBatchSize {
+ end := min(start+graphQueryChunkBatchSize, len(chunkIDs))
+ batch, err := t.graphEvidenceBatch(ctx, kbID, chunkIDs[start:end])
+ if err != nil {
+ // Never return an unchecked graph, including after a later batch fails.
+ return graphLookup{}, err
+ }
+ for _, result := range batch {
+ evidence = append(evidence, &types.SearchResult{ID: result.ID})
+ if len(selected) < graphQueryMaxChunks {
+ selected = append(selected, result)
+ }
+ }
+ }
+ results, err := t.graphEvidenceResults(ctx, kbID, selected)
+ if err != nil {
+ return graphLookup{}, err
+ }
+ // A selected chunk can disappear or become disabled between metadata and
+ // content reads. Remove it from endpoint evidence as well as the display.
+ if len(results) < len(selected) {
+ missing := make(map[string]bool, len(selected))
+ for _, result := range selected {
+ missing[result.ID] = true
+ }
+ for _, result := range results {
+ delete(missing, result.ID)
+ }
+ kept := evidence[:0]
+ for _, result := range evidence {
+ if !missing[result.ID] {
+ kept = append(kept, result)
+ }
+ }
+ evidence = kept
}
+ validated := *graph
+ validated.Relation = relationsBackedBy(graph, evidence)
+ return graphLookup{
+ graph: &validated, chunks: results, chunksShown: len(results), chunksTotal: len(evidence),
+ validationLimited: validationLimited, candidatesValidated: len(chunkIDs),
+ }, nil
+}
+
+// graphEvidenceBatch resolves live, enabled, accessible evidence in candidate
+// order. Scope filtering happens before the caller applies its presentation cap.
+func (t *QueryKnowledgeGraphTool) graphEvidenceBatch(
+ ctx context.Context, kbID string, chunkIDs []string,
+) ([]*types.SearchResult, error) {
// The graph namespace is the knowledge base, which the caller already
// authorized; a chunk ID is only trusted when its row belongs to it.
- chunks, err := t.chunkRepo.ListChunksByIDOnly(ctx, chunkIDs)
+ chunks, err := t.chunkRepo.ListChunkEvidenceByIDOnly(ctx, chunkIDs)
if err != nil {
- // A failed fetch is an error, not a capped fetch: dropping the counts
- // keeps it from being reported as truncation.
- return graphLookup{graph: graph}, err
+ return nil, fmt.Errorf("failed to load graph evidence chunks: %w", err)
}
byID := make(map[string]*types.Chunk, len(chunks))
knowledgeIDs := make([]string, 0, len(chunks))
@@ -645,7 +730,7 @@ func (t *QueryKnowledgeGraphTool) queryGraph(
}
titles, err := t.knowledgeTitles(ctx, knowledgeIDs)
if err != nil {
- return graphLookup{graph: graph}, err
+ return nil, err
}
results := make([]*types.SearchResult, 0, len(byID))
for _, id := range chunkIDs {
@@ -653,37 +738,73 @@ func (t *QueryKnowledgeGraphTool) queryGraph(
if c == nil {
continue
}
- // A chunk can outlive its soft-deleted document; titles holds only
- // documents that still exist (nil when there is no way to check).
- if _, exists := titles[c.KnowledgeID]; titles != nil && !exists {
+ // A chunk can outlive its soft-deleted document. Only documents returned
+ // by the shared-access lookup can establish valid evidence.
+ if _, exists := titles[c.KnowledgeID]; !exists {
continue
}
results = append(results, &types.SearchResult{
ID: c.ID,
- Content: c.Content,
KnowledgeID: c.KnowledgeID,
KnowledgeBaseID: c.KnowledgeBaseID,
KnowledgeTitle: titles[c.KnowledgeID],
- ChunkIndex: c.ChunkIndex,
- ChunkType: string(c.ChunkType),
- ParentChunkID: c.ParentChunkID,
MatchType: types.MatchTypeGraph,
})
}
- lookup.chunks = results
- return lookup, nil
+ if t.scopeEnforced {
+ return filterSearchResultsInSearchTargets(ctx, t.searchTargets, kbID, results, t.scopeKnowledgeService)
+ }
+ return results, nil
}
-// knowledgeTitles returns the titles of the knowledge IDs that still exist.
-// It returns nil when no knowledge service is wired to look them up.
-func (t *QueryKnowledgeGraphTool) knowledgeTitles(ctx context.Context, ids []string) (map[string]string, error) {
- if t.scopeKnowledgeService == nil {
+// graphEvidenceResults hydrates only the already validated display candidates.
+func (t *QueryKnowledgeGraphTool) graphEvidenceResults(
+ ctx context.Context, kbID string, selected []*types.SearchResult,
+) ([]*types.SearchResult, error) {
+ if len(selected) == 0 {
return nil, nil
}
+ ids := make([]string, 0, len(selected))
+ for _, result := range selected {
+ ids = append(ids, result.ID)
+ }
+ chunks, err := t.chunkRepo.ListChunksByIDOnly(ctx, ids)
+ if err != nil {
+ return nil, fmt.Errorf("failed to load graph evidence content: %w", err)
+ }
+ byID := make(map[string]*types.Chunk, len(chunks))
+ for _, chunk := range chunks {
+ if chunk != nil && chunk.KnowledgeBaseID == kbID && chunk.IsEnabled {
+ byID[chunk.ID] = chunk
+ }
+ }
+ results := make([]*types.SearchResult, 0, len(selected))
+ for _, metadata := range selected {
+ chunk := byID[metadata.ID]
+ if chunk == nil || chunk.KnowledgeID != metadata.KnowledgeID {
+ continue
+ }
+ result := *metadata
+ result.Content = chunk.Content
+ result.ChunkIndex = chunk.ChunkIndex
+ result.ChunkType = string(chunk.ChunkType)
+ result.ParentChunkID = chunk.ParentChunkID
+ results = append(results, &result)
+ }
+ return results, nil
+}
+
+// knowledgeTitles returns the titles of the knowledge IDs that still exist.
+// Missing document services fail closed rather than accepting unchecked chunks.
+func (t *QueryKnowledgeGraphTool) knowledgeTitles(ctx context.Context, ids []string) (map[string]string, error) {
titles := make(map[string]string, len(ids))
+ ids = dedupNonEmptyStrings(ids)
if len(ids) == 0 {
return titles, nil
}
+ if t.scopeKnowledgeService == nil {
+ return nil, fmt.Errorf("knowledge service is unavailable for graph evidence validation")
+ }
tenantID, _ := types.TenantIDFromContext(ctx)
knowledges, err := t.scopeKnowledgeService.GetKnowledgeBatchWithSharedAccess(ctx, tenantID, ids)
if err != nil {
@@ -697,17 +818,6 @@ func (t *QueryKnowledgeGraphTool) knowledgeTitles(ctx context.Context, ids []str
return titles, nil
}
-// searchTargetsCoverWholeKB reports whether targets grant the whole of kbID
-// rather than some of its documents or tags.
-func searchTargetsCoverWholeKB(targets types.SearchTargets, kbID string) bool {
- for _, target := range targets {
- if target != nil && target.KnowledgeBaseID == kbID && searchTargetIsWholeKB(target) {
- return true
- }
- }
- return false
-}
-
// relationsBackedBy checks the actual endpoint instances against scoped evidence.
// A same-named entity in another document cannot establish a relation's scope.
func relationsBackedBy(graph *types.GraphData, evidence []*types.SearchResult) []*types.GraphRelation {
diff --git a/internal/agent/tools/query_knowledge_graph_budget_test.go b/internal/agent/tools/query_knowledge_graph_budget_test.go
new file mode 100644
index 000000000..b9c2a280a
--- /dev/null
+++ b/internal/agent/tools/query_knowledge_graph_budget_test.go
@@ -0,0 +1,88 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/require"
+)
+
+type budgetGraphRepo struct {
+ interfaces.RetrieveGraphRepository
+ graphs map[string]*types.GraphData
+}
+
+func (s *budgetGraphRepo) SearchNode(
+ _ context.Context, namespace types.NameSpace, _ []string,
+) (*types.GraphData, error) {
+ return s.graphs[namespace.KnowledgeBase], nil
+}
+
+type budgetKnowledgeBaseService struct {
+ stubKnowledgeBaseService
+}
+
+func (*budgetKnowledgeBaseService) GetKnowledgeBaseByIDOnly(
+ _ context.Context, id string,
+) (*types.KnowledgeBase, error) {
+ return &types.KnowledgeBase{
+ ID: id, ExtractConfig: &types.ExtractConfig{Enabled: true, Nodes: []*types.GraphNode{{Name: "Company"}}},
+ }, nil
+}
+
+func TestQueryKnowledgeGraph_ReportsTotalValidationAcrossKnowledgeBases(t *testing.T) {
+ graphs := &budgetGraphRepo{graphs: make(map[string]*types.GraphData)}
+ chunks := &graphEvidenceChunkRepo{
+ stubGraphChunkRepo: stubGraphChunkRepo{chunks: make(map[string]*types.Chunk)},
+ }
+ documents := &graphEvidenceKnowledgeService{documents: make(map[string]*types.Knowledge)}
+ expected := make(map[string][]string)
+ for _, kbID := range []string{"kb-1", "kb-2"} {
+ docID := kbID + "-doc"
+ documents.documents[docID] = &types.Knowledge{ID: docID, KnowledgeBaseID: kbID}
+ var ids []string
+ for i := 0; i <= graphQueryMaxEvidenceCandidates; i++ {
+ id := fmt.Sprintf("%s-c-%04d", kbID, i)
+ ids = append(ids, id)
+ chunks.chunks[id] = &types.Chunk{
+ ID: id, KnowledgeID: docID, KnowledgeBaseID: kbID, Content: id, IsEnabled: true,
+ }
+ }
+ graph := graphEvidenceGraph(ids, []string{ids[10]})
+ graph.Relation[0].Type += kbID
+ graphs.graphs[kbID] = graph
+ expected[kbID] = ids[:graphQueryMaxEvidenceCandidates]
+ }
+ tool := NewQueryKnowledgeGraphTool(&budgetKnowledgeBaseService{}).
+ WithGraph(graphs, chunks).WithKnowledgeScope(documents)
+ result, err := tool.Execute(context.Background(),
+ json.RawMessage(`{"knowledge_base_ids":["kb-1","kb-2","kb-1"],"query":"Acme"}`))
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ require.Equal(t, true, result.Data["graph_validation_truncated"])
+ require.Equal(t, graphQueryMaxEvidenceCandidates*2, result.Data["graph_candidates_validated_total"])
+ require.Equal(t, graphQueryMaxEvidenceCandidates, result.Data["graph_validation_limit_per_kb"])
+ require.Contains(t, result.Output, "1024 candidates were validated in total")
+ require.Contains(t, result.Output, "cap 512 per knowledge base")
+ require.Len(t, result.Data["relations"], 2)
+
+ requested := make(map[string][]string)
+ for _, batch := range chunks.batches {
+ require.LessOrEqual(t, len(batch), graphQueryChunkBatchSize)
+ for _, id := range batch {
+ kbID := chunks.chunks[id].KnowledgeBaseID
+ requested[kbID] = append(requested[kbID], id)
+ }
+ }
+ require.Equal(t, expected, requested, "each distinct KB is validated once within its own budget")
+ require.Len(t, chunks.batches, 8)
+ require.Len(t, chunks.contentBatches, 2)
+ for _, batch := range chunks.contentBatches {
+ kbID := chunks.chunks[batch[0]].KnowledgeBaseID
+ require.Equal(t, expected[kbID][:graphQueryMaxChunks], batch)
+ }
+}
diff --git a/internal/agent/tools/query_knowledge_graph_evidence_test.go b/internal/agent/tools/query_knowledge_graph_evidence_test.go
new file mode 100644
index 000000000..750a27523
--- /dev/null
+++ b/internal/agent/tools/query_knowledge_graph_evidence_test.go
@@ -0,0 +1,505 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "sync"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type graphEvidenceChunkRepo struct {
+ stubGraphChunkRepo
+ mu sync.Mutex
+ batches [][]string
+ contentBatches [][]string
+ failAt int
+ contentErr error
+ beforeContent func()
+}
+
+func (s *graphEvidenceChunkRepo) ListChunksByIDOnly(ctx context.Context, ids []string) ([]*types.Chunk, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.contentBatches = append(s.contentBatches, append([]string(nil), ids...))
+ if s.contentErr != nil {
+ return nil, s.contentErr
+ }
+ if s.beforeContent != nil {
+ s.beforeContent()
+ }
+ return s.stubGraphChunkRepo.ListChunksByIDOnly(ctx, ids)
+}
+
+func (s *graphEvidenceChunkRepo) ListChunkEvidenceByIDOnly(ctx context.Context, ids []string) ([]*types.Chunk, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.batches = append(s.batches, append([]string(nil), ids...))
+ if len(s.batches) == s.failAt {
+ return nil, assert.AnError
+ }
+ return s.stubGraphChunkRepo.ListChunkEvidenceByIDOnly(ctx, ids)
+}
+
+type graphEvidenceKnowledgeService struct {
+ interfaces.KnowledgeService
+ mu sync.Mutex
+ documents map[string]*types.Knowledge
+ tags map[string][]*types.KnowledgeTag
+ err error
+ tagErr error
+ documentBatches [][]string
+ tagBatches [][]string
+}
+
+func (s *graphEvidenceKnowledgeService) GetKnowledgeBatchWithSharedAccess(
+ _ context.Context, _ uint64, ids []string,
+) ([]*types.Knowledge, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.documentBatches = append(s.documentBatches, append([]string(nil), ids...))
+ if s.err != nil {
+ return nil, s.err
+ }
+ var documents []*types.Knowledge
+ for _, id := range ids {
+ if document := s.documents[id]; document != nil {
+ documents = append(documents, document)
+ }
+ }
+ return documents, nil
+}
+
+func (s *graphEvidenceKnowledgeService) GetKnowledgeTags(
+ _ context.Context, ids []string,
+) (map[string][]*types.KnowledgeTag, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.tagBatches = append(s.tagBatches, append([]string(nil), ids...))
+ if s.tagErr != nil {
+ return nil, s.tagErr
+ }
+ return s.tags, nil
+}
+
+func graphEvidenceScopes() []struct {
+ name string
+ targets types.SearchTargets
+} {
+ return []struct {
+ name string
+ targets types.SearchTargets
+ }{
+ {"whole KB", types.SearchTargets{{Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb-1"}}},
+ {"document", types.SearchTargets{{
+ Type: types.SearchTargetTypeKnowledge, KnowledgeBaseID: "kb-1", KnowledgeIDs: []string{"doc"},
+ }}},
+ {"tag", types.SearchTargets{{
+ Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb-1", TagIDs: []string{"tag"},
+ }}},
+ {"without scope argument", nil},
+ }
+}
+
+func liveGraphEvidenceDocuments() *graphEvidenceKnowledgeService {
+ return &graphEvidenceKnowledgeService{
+ documents: map[string]*types.Knowledge{"doc": {ID: "doc", Title: "Evidence", KnowledgeBaseID: "kb-1"}},
+ tags: map[string][]*types.KnowledgeTag{"doc": {testKnowledgeTag("tag")}},
+ }
+}
+
+func graphEvidenceGraph(sourceChunks, targetChunks []string) *types.GraphData {
+ return &types.GraphData{
+ Node: []*types.GraphNode{
+ {Name: "Acme", ID: "acme-doc", KnowledgeID: "doc", Chunks: sourceChunks},
+ {Name: "Shanghai", ID: "city-doc", KnowledgeID: "doc", Chunks: targetChunks},
+ },
+ Relation: []*types.GraphRelation{{
+ Node1: "Acme", Type: "HEADQUARTERED_IN", Node2: "Shanghai", SourceID: "acme-doc", TargetID: "city-doc",
+ }},
+ }
+}
+
+func graphEvidenceTool(
+ graph *types.GraphData, chunks interfaces.ChunkRepository, documents interfaces.KnowledgeService,
+ targets types.SearchTargets,
+) *QueryKnowledgeGraphTool {
+ service := &stubKnowledgeBaseService{kb: &types.KnowledgeBase{
+ ID: "kb-1", ExtractConfig: &types.ExtractConfig{Enabled: true, Nodes: []*types.GraphNode{{Name: "Company"}}},
+ }}
+ tool := NewQueryKnowledgeGraphTool(service)
+ if targets != nil {
+ tool = NewQueryKnowledgeGraphTool(service, targets)
+ }
+ return tool.WithGraph(&stubGraphRepo{graph: graph}, chunks).WithKnowledgeScope(documents)
+}
+
+func executeGraphEvidenceTool(t *testing.T, tool *QueryKnowledgeGraphTool) *types.ToolResult {
+ t.Helper()
+ result, err := tool.Execute(context.Background(), json.RawMessage(`{"knowledge_base_ids":["kb-1"],"query":"Acme"}`))
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ return result
+}
+
+// Removing the original text must also remove unsupported relations, including
+// when whole-KB authorization succeeds and no narrower scope was requested.
+func TestQueryKnowledgeGraph_RejectsInvalidEndpointEvidenceInEveryScope(t *testing.T) {
+ for _, scope := range graphEvidenceScopes() {
+ for _, invalid := range []string{
+ "disabled chunk", "deleted chunk", "foreign KB", "deleted document",
+ "missing target evidence", "no chunk references",
+ } {
+ t.Run(scope.name+"/"+invalid, func(t *testing.T) {
+ chunk := &types.Chunk{ID: "c1", KnowledgeID: "doc", KnowledgeBaseID: "kb-1", IsEnabled: true}
+ chunks := &stubGraphChunkRepo{chunks: map[string]*types.Chunk{"c1": chunk}}
+ documents := liveGraphEvidenceDocuments()
+ graph := graphEvidenceGraph([]string{"c1"}, []string{"c1"})
+ switch invalid {
+ case "disabled chunk":
+ chunk.IsEnabled = false
+ case "deleted chunk":
+ delete(chunks.chunks, "c1")
+ case "foreign KB":
+ chunk.KnowledgeBaseID = "kb-other"
+ case "deleted document":
+ delete(documents.documents, "doc")
+ case "missing target evidence":
+ graph.Node[1].Chunks = []string{"missing"}
+ case "no chunk references":
+ graph.Node[0].Chunks, graph.Node[1].Chunks = nil, nil
+ }
+ result := executeGraphEvidenceTool(t, graphEvidenceTool(graph, chunks, documents, scope.targets))
+ assert.Empty(t, result.Data["relations"])
+ assert.NotContains(t, result.Output, "--[HEADQUARTERED_IN]-->")
+ assert.Len(t, graph.Relation, 1, "validation must not mutate the graph repository's result")
+ })
+ }
+ }
+}
+
+// A live entity with the same name cannot validate a stale document instance,
+// including when the caller is allowed to query the whole knowledge base.
+func TestQueryKnowledgeGraph_RejectsStaleSameNamedInstancesInEveryScope(t *testing.T) {
+ for _, scope := range graphEvidenceScopes() {
+ for _, invalid := range []string{"disabled chunk", "deleted document"} {
+ t.Run(scope.name+"/"+invalid, func(t *testing.T) {
+ documents := liveGraphEvidenceDocuments()
+ documents.documents["other"] = &types.Knowledge{ID: "other", KnowledgeBaseID: "kb-1"}
+ chunks := &stubGraphChunkRepo{chunks: map[string]*types.Chunk{
+ "stale": {ID: "stale", KnowledgeID: "doc", KnowledgeBaseID: "kb-1", IsEnabled: true},
+ "live": {ID: "live", KnowledgeID: "other", KnowledgeBaseID: "kb-1", IsEnabled: true},
+ }}
+ if invalid == "disabled chunk" {
+ chunks.chunks["stale"].IsEnabled = false
+ } else {
+ delete(documents.documents, "doc")
+ }
+ graph := graphEvidenceGraph([]string{"stale"}, []string{"stale"})
+ graph.Node = append(graph.Node,
+ &types.GraphNode{
+ Name: "Acme", ID: "acme-other", KnowledgeID: "other", Chunks: []string{"live"},
+ },
+ &types.GraphNode{
+ Name: "Shanghai", ID: "city-other", KnowledgeID: "other", Chunks: []string{"live"},
+ },
+ )
+ graph.Relation = append(graph.Relation, &types.GraphRelation{
+ Node1: "Acme", Node2: "Shanghai", Type: "HAS_BRANCH_IN",
+ SourceID: "acme-other", TargetID: "city-other",
+ })
+ result := executeGraphEvidenceTool(t, graphEvidenceTool(graph, chunks, documents, scope.targets))
+ assert.NotContains(t, result.Output, "--[HEADQUARTERED_IN]-->")
+ if scope.targets == nil || scope.name == "whole KB" {
+ relations, ok := result.Data["relations"].([]map[string]interface{})
+ require.True(t, ok)
+ require.Len(t, relations, 1)
+ assert.Equal(t, "HAS_BRANCH_IN", relations[0]["type"])
+ } else {
+ assert.Empty(t, result.Data["relations"])
+ }
+ })
+ }
+ }
+}
+
+// The eleventh chunk is the target's only evidence. It need not be displayed,
+// but its live row must still be considered when validating the relation.
+func TestQueryKnowledgeGraph_ValidatesBeyondEvidenceBudget(t *testing.T) {
+ for _, scope := range graphEvidenceScopes() {
+ t.Run(scope.name, func(t *testing.T) {
+ var ids []string
+ chunks := &stubGraphChunkRepo{chunks: make(map[string]*types.Chunk)}
+ for i := 0; i < 11; i++ {
+ id := fmt.Sprintf("c-%02d", i)
+ ids = append(ids, id)
+ chunks.chunks[id] = &types.Chunk{
+ ID: id, KnowledgeID: "doc", KnowledgeBaseID: "kb-1", Content: id, IsEnabled: true,
+ }
+ }
+ graph := graphEvidenceGraph(ids, []string{ids[10]})
+ result := executeGraphEvidenceTool(t, graphEvidenceTool(
+ graph, chunks, liveGraphEvidenceDocuments(), scope.targets,
+ ))
+ assert.Len(t, result.Data["relations"], 1)
+ assert.Equal(t, 11, result.Data["graph_chunks_total"])
+ assert.Equal(t, 1, result.Data["graph_chunks_omitted"])
+ rows, ok := result.Data["results"].([]map[string]interface{})
+ require.True(t, ok, "expected validated evidence rows")
+ require.Len(t, rows, 10)
+ for i, row := range rows {
+ assert.Equal(t, ids[i], row["chunk_id"])
+ }
+ })
+ }
+}
+
+func TestQueryKnowledgeGraph_FillsBudgetAfterScopeFiltering(t *testing.T) {
+ for _, scope := range graphEvidenceScopes()[1:3] {
+ t.Run(scope.name, func(t *testing.T) {
+ chunks := &stubGraphChunkRepo{chunks: make(map[string]*types.Chunk)}
+ documents := liveGraphEvidenceDocuments()
+ documents.documents["outside"] = &types.Knowledge{ID: "outside", KnowledgeBaseID: "kb-1"}
+ var ids []string
+ for i := 0; i < 22; i++ {
+ id := fmt.Sprintf("c-%02d", i)
+ ids = append(ids, id)
+ doc := "doc"
+ if i < 10 {
+ doc = "outside"
+ }
+ chunks.chunks[id] = &types.Chunk{ID: id, KnowledgeID: doc, KnowledgeBaseID: "kb-1", IsEnabled: true}
+ }
+ graph := graphEvidenceGraph(ids[10:], []string{ids[21]})
+ graph.Node = append([]*types.GraphNode{
+ {Name: "Outside", ID: "outside", KnowledgeID: "outside", Chunks: ids[:10]},
+ }, graph.Node...)
+ result := executeGraphEvidenceTool(t, graphEvidenceTool(graph, chunks, documents, scope.targets))
+ rows, ok := result.Data["results"].([]map[string]interface{})
+ require.True(t, ok, "expected validated evidence rows")
+ require.Len(t, rows, 10)
+ for i, row := range rows {
+ assert.Equal(t, ids[i+10], row["chunk_id"])
+ }
+ assert.Len(t, result.Data["relations"], 1)
+ assert.Equal(t, 12, result.Data["graph_chunks_total"], "out-of-scope chunks are not display omissions")
+ assert.Equal(t, 2, result.Data["graph_chunks_omitted"])
+ })
+ }
+}
+
+// Invalid rows cannot exhaust the display budget; lookups are bounded and IDs
+// shared by both endpoints are loaded only once, even across multiple batches.
+func TestQueryKnowledgeGraph_BatchesAndFiltersEvidenceBeforeBudget(t *testing.T) {
+ const candidates = 270
+ var ids []string
+ chunks := &graphEvidenceChunkRepo{stubGraphChunkRepo: stubGraphChunkRepo{chunks: make(map[string]*types.Chunk)}}
+ for i := 0; i < candidates; i++ {
+ id := fmt.Sprintf("c-%03d", i)
+ ids = append(ids, id)
+ chunks.chunks[id] = &types.Chunk{
+ ID: id, KnowledgeID: "doc", KnowledgeBaseID: "kb-1", IsEnabled: i >= candidates-12,
+ }
+ }
+ graph := graphEvidenceGraph(append([]string{""}, ids...), []string{ids[candidates-1], ids[0]})
+ result := executeGraphEvidenceTool(t, graphEvidenceTool(graph, chunks, liveGraphEvidenceDocuments(), nil))
+ require.Len(t, result.Data["results"], 10)
+ assert.Len(t, result.Data["relations"], 1)
+ assert.Equal(t, 12, result.Data["graph_chunks_total"], "invalid chunks are not display omissions")
+ assert.Equal(t, 2, result.Data["graph_chunks_omitted"])
+ var requested []string
+ for _, batch := range chunks.batches {
+ assert.LessOrEqual(t, len(batch), 128)
+ requested = append(requested, batch...)
+ }
+ assert.Equal(t, ids, requested)
+ require.Len(t, chunks.contentBatches, 1)
+ assert.Equal(t, ids[candidates-12:candidates-2], chunks.contentBatches[0])
+}
+
+func TestQueryKnowledgeGraph_BoundsCandidateValidation(t *testing.T) {
+ for _, scope := range graphEvidenceScopes() {
+ for _, tt := range []struct {
+ name string
+ candidates int
+ duplicates bool
+ invalid bool
+ unresolved bool
+ }{
+ {name: "exact limit", candidates: graphQueryMaxEvidenceCandidates},
+ {name: "only duplicates after limit", candidates: graphQueryMaxEvidenceCandidates, duplicates: true},
+ {name: "one over limit", candidates: graphQueryMaxEvidenceCandidates + 1},
+ {name: "many over limit", candidates: graphQueryMaxEvidenceCandidates*3 + 1},
+ {name: "all invalid", candidates: graphQueryMaxEvidenceCandidates + 1, invalid: true},
+ {name: "unresolved endpoint", candidates: graphQueryMaxEvidenceCandidates + 1, unresolved: true},
+ } {
+ t.Run(scope.name+"/"+tt.name, func(t *testing.T) {
+ chunks := &graphEvidenceChunkRepo{
+ stubGraphChunkRepo: stubGraphChunkRepo{chunks: make(map[string]*types.Chunk)},
+ }
+ var ids []string
+ for i := 0; i < tt.candidates; i++ {
+ id := fmt.Sprintf("c-%04d", i)
+ ids = append(ids, id)
+ chunks.chunks[id] = &types.Chunk{
+ ID: id, KnowledgeID: "doc", KnowledgeBaseID: "kb-1",
+ IsEnabled: !tt.invalid, Content: id,
+ }
+ }
+ target := ids[10] // beyond display cap, within validation budget
+ if tt.unresolved {
+ target = ids[len(ids)-1]
+ }
+ source := append([]string{""}, ids...)
+ if tt.duplicates {
+ source = append(source, ids...)
+ }
+ documents := liveGraphEvidenceDocuments()
+ graph := graphEvidenceGraph(source, []string{target})
+ result := executeGraphEvidenceTool(t, graphEvidenceTool(graph, chunks, documents, scope.targets))
+
+ scanned := min(tt.candidates, graphQueryMaxEvidenceCandidates)
+ require.Len(t, chunks.batches, (scanned+graphQueryChunkBatchSize-1)/graphQueryChunkBatchSize)
+ var requested []string
+ for _, batch := range chunks.batches {
+ require.LessOrEqual(t, len(batch), graphQueryChunkBatchSize)
+ requested = append(requested, batch...)
+ }
+ require.Equal(t, ids[:scanned], requested, "never query IDs outside the validation budget")
+ if tt.invalid {
+ require.Empty(t, chunks.contentBatches)
+ require.Empty(t, documents.documentBatches)
+ require.Empty(t, documents.tagBatches)
+ require.Empty(t, result.Data["results"])
+ } else {
+ require.Len(t, chunks.contentBatches, 1)
+ require.Equal(t, ids[:graphQueryMaxChunks], chunks.contentBatches[0])
+ require.Len(t, documents.documentBatches, len(chunks.batches))
+ if scope.name == "tag" {
+ require.Len(t, documents.tagBatches, len(chunks.batches))
+ }
+ }
+ if tt.invalid || tt.unresolved {
+ require.Empty(t, result.Data["relations"], "unchecked evidence must not validate an endpoint")
+ } else {
+ require.Len(t, result.Data["relations"], 1)
+ }
+ limited := tt.candidates > graphQueryMaxEvidenceCandidates
+ require.Equal(t, limited, result.Data["graph_validation_truncated"] == true)
+ if limited {
+ require.Equal(t, scanned, result.Data["graph_candidates_validated_total"])
+ require.Equal(t, graphQueryMaxEvidenceCandidates, result.Data["graph_validation_limit_per_kb"])
+ require.Equal(t, true, result.Data["graph_chunks_total_is_lower_bound"])
+ require.Equal(t, true, result.Data["relations_total_is_lower_bound"])
+ require.Contains(t, result.Output, "Some candidate evidence was not checked")
+ valid := scanned
+ if tt.invalid {
+ valid = 0
+ }
+ require.Equal(t, valid, result.Data["graph_chunks_total"])
+ require.Equal(t, max(0, valid-graphQueryMaxChunks), result.Data["graph_chunks_omitted"])
+ require.Contains(t, result.Output, fmt.Sprintf("at least %d valid in-scope evidence chunks", valid))
+ } else {
+ require.NotContains(t, result.Output, "validation stopped")
+ require.NotContains(t, result.Data, "graph_chunks_total_is_lower_bound")
+ }
+ })
+ }
+ }
+}
+
+func TestQueryKnowledgeGraph_RemovesEvidenceChangedBeforeContentRead(t *testing.T) {
+ for _, change := range []string{"disabled", "deleted", "foreign KB", "different document"} {
+ t.Run(change, func(t *testing.T) {
+ chunk := &types.Chunk{ID: "c1", KnowledgeID: "doc", KnowledgeBaseID: "kb-1", IsEnabled: true}
+ chunks := &graphEvidenceChunkRepo{
+ stubGraphChunkRepo: stubGraphChunkRepo{chunks: map[string]*types.Chunk{"c1": chunk}},
+ }
+ chunks.beforeContent = func() {
+ switch change {
+ case "disabled":
+ chunk.IsEnabled = false
+ case "deleted":
+ delete(chunks.chunks, chunk.ID)
+ case "foreign KB":
+ chunk.KnowledgeBaseID = "kb-other"
+ case "different document":
+ chunk.KnowledgeID = "other"
+ }
+ }
+ result := executeGraphEvidenceTool(t, graphEvidenceTool(
+ graphEvidenceGraph([]string{"c1"}, []string{"c1"}), chunks, liveGraphEvidenceDocuments(), nil,
+ ))
+ require.Empty(t, result.Data["results"])
+ require.Empty(t, result.Data["relations"])
+ })
+ }
+}
+
+func TestQueryKnowledgeGraph_ValidationFailuresExcludeGraphAndPreserveText(t *testing.T) {
+ for _, failure := range []string{
+ "chunk lookup", "document lookup", "missing chunk repository", "missing document service", "later batch",
+ "content lookup",
+ } {
+ t.Run(failure, func(t *testing.T) {
+ chunks := &graphEvidenceChunkRepo{stubGraphChunkRepo: stubGraphChunkRepo{chunks: map[string]*types.Chunk{
+ "c1": {ID: "c1", KnowledgeID: "doc", KnowledgeBaseID: "kb-1", IsEnabled: true},
+ }}}
+ var chunkRepo interfaces.ChunkRepository = chunks
+ documents := liveGraphEvidenceDocuments()
+ var documentService interfaces.KnowledgeService = documents
+ graph := graphEvidenceGraph([]string{"c1"}, []string{"c1"})
+ switch failure {
+ case "chunk lookup":
+ chunks.failAt = 1
+ case "document lookup":
+ documents.err = assert.AnError
+ case "content lookup":
+ chunks.contentErr = assert.AnError
+ case "missing chunk repository":
+ chunkRepo = nil
+ case "missing document service":
+ documentService = nil
+ case "later batch":
+ chunks.failAt = 2
+ for i := 0; i < 140; i++ {
+ graph.Node[0].Chunks = append(graph.Node[0].Chunks, fmt.Sprintf("missing-%03d", i))
+ }
+ }
+ tool := graphEvidenceTool(graph, chunkRepo, documentService, graphEvidenceScopes()[0].targets)
+ tool.knowledgeService.(*stubKnowledgeBaseService).results = []*types.SearchResult{
+ {ID: "text", KnowledgeID: "doc", KnowledgeBaseID: "kb-1", Content: "Text fallback"},
+ }
+ result := executeGraphEvidenceTool(t, tool)
+ assert.Empty(t, result.Data["relations"])
+ rows := result.Data["results"].([]map[string]interface{})
+ require.Len(t, rows, 1)
+ assert.Equal(t, "text", rows[0]["chunk_id"])
+ assert.NotEmpty(t, result.Data["errors"])
+ assert.Contains(t, result.Output, "graph query failed")
+ assert.NotContains(t, result.Output, "Truncated", "validation failures are not capped evidence")
+ _, hasChunkTotal := result.Data["graph_chunks_total"]
+ assert.False(t, hasChunkTotal)
+ })
+ }
+}
+
+func TestQueryKnowledgeGraph_RejectsRelationsWhenTagValidationFails(t *testing.T) {
+ documents := liveGraphEvidenceDocuments()
+ documents.tagErr = assert.AnError
+ chunks := &stubGraphChunkRepo{chunks: map[string]*types.Chunk{
+ "c1": {ID: "c1", KnowledgeID: "doc", KnowledgeBaseID: "kb-1", IsEnabled: true},
+ }}
+ result := executeGraphEvidenceTool(t, graphEvidenceTool(
+ graphEvidenceGraph([]string{"c1"}, []string{"c1"}), chunks, documents, graphEvidenceScopes()[2].targets,
+ ))
+ assert.Empty(t, result.Data["relations"])
+ assert.Empty(t, result.Data["results"])
+ assert.NotEmpty(t, result.Data["errors"])
+ assert.Contains(t, result.Output, "failed to validate graph result scope")
+}
diff --git a/internal/agent/tools/query_knowledge_graph_graph_test.go b/internal/agent/tools/query_knowledge_graph_graph_test.go
index ad5f1a50e..55e5455dd 100644
--- a/internal/agent/tools/query_knowledge_graph_graph_test.go
+++ b/internal/agent/tools/query_knowledge_graph_graph_test.go
@@ -37,16 +37,30 @@ func (s *stubGraphChunkRepo) ListChunksByIDOnly(_ context.Context, ids []string)
return out, nil
}
+func (s *stubGraphChunkRepo) ListChunkEvidenceByIDOnly(_ context.Context, ids []string) ([]*types.Chunk, error) {
+ var out []*types.Chunk
+ for _, id := range ids {
+ if c := s.chunks[id]; c != nil {
+ out = append(out, &types.Chunk{
+ ID: c.ID, KnowledgeBaseID: c.KnowledgeBaseID, KnowledgeID: c.KnowledgeID, IsEnabled: c.IsEnabled,
+ })
+ }
+ }
+ return out, nil
+}
+
// The tool used to run plain text search only. It now looks the entities up
// in the graph, returns their relations, and puts the chunks they came from
// first — only chunks of the queried, authorized knowledge base.
func TestQueryKnowledgeGraph_QueriesTheGraph(t *testing.T) {
graphRepo := &stubGraphRepo{graph: &types.GraphData{
Node: []*types.GraphNode{
- {Name: "Docker", Chunks: []string{"c-docker", "c-foreign", "c-disabled"}},
- {Name: "Kubernetes", Chunks: []string{"c-k8s"}},
+ {Name: "Docker", ID: "docker-doc", Chunks: []string{"c-docker", "c-foreign", "c-disabled"}},
+ {Name: "Kubernetes", ID: "k8s-doc", Chunks: []string{"c-k8s"}},
},
- Relation: []*types.GraphRelation{{Node1: "Kubernetes", Node2: "Docker", Type: "orchestrates"}},
+ Relation: []*types.GraphRelation{{
+ Node1: "Kubernetes", Node2: "Docker", Type: "orchestrates", SourceID: "k8s-doc", TargetID: "docker-doc",
+ }},
}}
chunkRepo := &stubGraphChunkRepo{chunks: map[string]*types.Chunk{
"c-docker": {
@@ -65,7 +79,7 @@ func TestQueryKnowledgeGraph_QueriesTheGraph(t *testing.T) {
Enabled: true, Nodes: []*types.GraphNode{{Name: "技术"}},
}},
results: []*types.SearchResult{{ID: "c-text", KnowledgeID: "doc", Content: "text hit", Score: 0.9}},
- }).WithGraph(graphRepo, chunkRepo)
+ }).WithGraph(graphRepo, chunkRepo).WithKnowledgeScope(liveGraphEvidenceDocuments())
args, err := json.Marshal(QueryKnowledgeGraphInput{KnowledgeBaseIDs: []string{"kb-1"}, Query: "Docker Kubernetes"})
require.NoError(t, err)
@@ -115,7 +129,12 @@ func TestQueryKnowledgeGraph_ScopesRelationsToDocuments(t *testing.T) {
err: assert.AnError,
}, types.SearchTargets{{
Type: types.SearchTargetTypeKnowledge, KnowledgeBaseID: "kb-1", KnowledgeIDs: []string{"doc-a"},
- }}).WithGraph(graphRepo, chunkRepo)
+ }}).WithGraph(graphRepo, chunkRepo).WithKnowledgeScope(&graphEvidenceKnowledgeService{
+ documents: map[string]*types.Knowledge{
+ "doc-a": {ID: "doc-a", Title: "doc-a", KnowledgeBaseID: "kb-1"},
+ "doc-b": {ID: "doc-b", Title: "doc-b", KnowledgeBaseID: "kb-1"},
+ },
+ })
args, err := json.Marshal(QueryKnowledgeGraphInput{KnowledgeBaseIDs: []string{"kb-1"}, Query: "Docker"})
require.NoError(t, err)
diff --git a/internal/agent/tools/query_knowledge_graph_truncation_test.go b/internal/agent/tools/query_knowledge_graph_truncation_test.go
index 25f95dabe..c700e918f 100644
--- a/internal/agent/tools/query_knowledge_graph_truncation_test.go
+++ b/internal/agent/tools/query_knowledge_graph_truncation_test.go
@@ -16,13 +16,18 @@ import (
// graphQueryMaxChunks+4 chunks referenced by it.
func graphToolOverEveryCap() *QueryKnowledgeGraphTool {
relations := make([]*types.GraphRelation, 0, graphQueryMaxRelations+13)
+ nodes := []*types.GraphNode{{Name: "Docker", ID: "docker-doc"}}
for i := 0; i < graphQueryMaxRelations+12; i++ {
+ name := fmt.Sprintf("Service%02d", i)
+ nodes = append(nodes, &types.GraphNode{Name: name, ID: name, Chunks: []string{"c-00"}})
relations = append(relations, &types.GraphRelation{
- Node1: "Docker", Node2: fmt.Sprintf("Service%02d", i), Type: "depends_on",
+ Node1: "Docker", Node2: name, Type: "depends_on", SourceID: "docker-doc", TargetID: name,
})
}
// A repeat of a relation already in the list must not inflate the total.
- relations = append(relations, &types.GraphRelation{Node1: "Docker", Node2: "Service00", Type: "depends_on"})
+ relations = append(relations, &types.GraphRelation{
+ Node1: "Docker", Node2: "Service00", Type: "depends_on", SourceID: "docker-doc", TargetID: "Service00",
+ })
chunks := make(map[string]*types.Chunk, graphQueryMaxChunks+4)
chunkIDs := make([]string, 0, graphQueryMaxChunks+4)
@@ -33,15 +38,16 @@ func graphToolOverEveryCap() *QueryKnowledgeGraphTool {
ID: id, KnowledgeBaseID: "kb-1", KnowledgeID: "doc", Content: "Docker evidence", IsEnabled: true,
}
}
+ nodes[0].Chunks = chunkIDs
graphRepo := &stubGraphRepo{graph: &types.GraphData{
- Node: []*types.GraphNode{{Name: "Docker", Chunks: chunkIDs}},
+ Node: nodes,
Relation: relations,
}}
return NewQueryKnowledgeGraphTool(&stubKnowledgeBaseService{
kb: &types.KnowledgeBase{ID: "kb-1", ExtractConfig: &types.ExtractConfig{
Enabled: true, Nodes: []*types.GraphNode{{Name: "技术"}},
}},
- }).WithGraph(graphRepo, &stubGraphChunkRepo{chunks: chunks})
+ }).WithGraph(graphRepo, &stubGraphChunkRepo{chunks: chunks}).WithKnowledgeScope(liveGraphEvidenceDocuments())
}
// A hub entity has far more relations than the tool returns. The cut has to be
@@ -62,7 +68,7 @@ func TestQueryKnowledgeGraph_MarksCappedRelationsAndChunks(t *testing.T) {
assert.Contains(t, result.Output, "=== ⚠️ Truncated ===")
assert.Contains(t, result.Output, fmt.Sprintf("Relations: %d of %d shown", graphQueryMaxRelations,
graphQueryMaxRelations+12))
- assert.Contains(t, result.Output, fmt.Sprintf("Graph evidence chunks: %d of %d fetched", graphQueryMaxChunks,
+ assert.Contains(t, result.Output, fmt.Sprintf("Graph evidence chunks: %d of %d shown", graphQueryMaxChunks,
graphQueryMaxChunks+4))
relations, ok := result.Data["relations"].([]map[string]interface{})
@@ -104,8 +110,13 @@ func TestQueryKnowledgeGraph_MarksCappedQueryTerms(t *testing.T) {
// no truncation marker and no total, so a marker always means a subset.
func TestQueryKnowledgeGraph_NoTruncationMarkerWhenNothingDropped(t *testing.T) {
graphRepo := &stubGraphRepo{graph: &types.GraphData{
- Node: []*types.GraphNode{{Name: "Docker", Chunks: []string{"c-1"}}},
- Relation: []*types.GraphRelation{{Node1: "Kubernetes", Node2: "Docker", Type: "orchestrates"}},
+ Node: []*types.GraphNode{
+ {Name: "Docker", ID: "docker-doc", Chunks: []string{"c-1"}},
+ {Name: "Kubernetes", ID: "k8s-doc", Chunks: []string{"c-1"}},
+ },
+ Relation: []*types.GraphRelation{{
+ Node1: "Kubernetes", Node2: "Docker", Type: "orchestrates", SourceID: "k8s-doc", TargetID: "docker-doc",
+ }},
}}
chunkRepo := &stubGraphChunkRepo{chunks: map[string]*types.Chunk{
"c-1": {ID: "c-1", KnowledgeBaseID: "kb-1", KnowledgeID: "doc", Content: "Docker", IsEnabled: true},
@@ -114,7 +125,7 @@ func TestQueryKnowledgeGraph_NoTruncationMarkerWhenNothingDropped(t *testing.T)
kb: &types.KnowledgeBase{ID: "kb-1", ExtractConfig: &types.ExtractConfig{
Enabled: true, Nodes: []*types.GraphNode{{Name: "技术"}},
}},
- }).WithGraph(graphRepo, chunkRepo)
+ }).WithGraph(graphRepo, chunkRepo).WithKnowledgeScope(liveGraphEvidenceDocuments())
args, err := json.Marshal(QueryKnowledgeGraphInput{KnowledgeBaseIDs: []string{"kb-1"}, Query: "Docker"})
require.NoError(t, err)
diff --git a/internal/application/repository/chunk.go b/internal/application/repository/chunk.go
index 66f16ea5e..3917c614e 100644
--- a/internal/application/repository/chunk.go
+++ b/internal/application/repository/chunk.go
@@ -156,6 +156,21 @@ func (r *chunkRepository) ListChunksByIDOnly(ctx context.Context, ids []string)
return chunks, nil
}
+// ListChunkEvidenceByIDOnly validates graph references without loading content.
+// Find retains Chunk's default soft-delete scope; the caller checks KB access.
+func (r *chunkRepository) ListChunkEvidenceByIDOnly(ctx context.Context, ids []string) ([]*types.Chunk, error) {
+ if len(ids) == 0 {
+ return nil, nil
+ }
+ var chunks []*types.Chunk
+ if err := r.db.WithContext(ctx).
+ Select("id, knowledge_base_id, knowledge_id, is_enabled").
+ Where("id IN ?", ids).Find(&chunks).Error; err != nil {
+ return nil, err
+ }
+ return chunks, nil
+}
+
// ListChunksBySeqID retrieves multiple chunks by their seq_ids
func (r *chunkRepository) ListChunksBySeqID(
ctx context.Context, tenantID uint64, seqIDs []int64,
diff --git a/internal/application/repository/chunk_evidence_test.go b/internal/application/repository/chunk_evidence_test.go
new file mode 100644
index 000000000..e08f4aa34
--- /dev/null
+++ b/internal/application/repository/chunk_evidence_test.go
@@ -0,0 +1,55 @@
+package repository
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+func TestListChunkEvidenceByIDOnlyLoadsMetadataAndExcludesSoftDeleted(t *testing.T) {
+ db := setupChunkTestDB(t)
+ repo := NewChunkRepository(db)
+ ctx := context.Background()
+ for i, id := range []string{"live", "shared", "disabled", "deleted"} {
+ chunk := makeChunk("kb", "doc", types.ChunkTypeText)
+ chunk.ID = id
+ chunk.TenantID = uint64(i + 1)
+ chunk.Content = "body that validation must not load"
+ chunk.ChunkIndex = 42
+ chunk.ParentChunkID = "parent"
+ require.NoError(t, repo.CreateChunks(ctx, []*types.Chunk{chunk}))
+ }
+ require.NoError(t, db.Model(&types.Chunk{}).Where("id = ?", "disabled").
+ Update("is_enabled", false).Error)
+ require.NoError(t, db.Delete(&types.Chunk{ID: "deleted"}).Error)
+
+ rows, err := repo.ListChunkEvidenceByIDOnly(ctx, []string{"live", "shared", "disabled", "deleted", "missing"})
+ require.NoError(t, err)
+ require.Len(t, rows, 3)
+ enabled := make(map[string]bool)
+ for _, row := range rows {
+ enabled[row.ID] = row.IsEnabled
+ require.Equal(t, "kb", row.KnowledgeBaseID)
+ require.Equal(t, "doc", row.KnowledgeID)
+ require.Empty(t, row.Content)
+ require.Zero(t, row.TenantID)
+ require.Zero(t, row.ChunkIndex)
+ require.Empty(t, row.ParentChunkID)
+ }
+ require.Equal(t, map[string]bool{"live": true, "shared": true, "disabled": false}, enabled)
+
+ full, err := repo.ListChunksByIDOnly(ctx, []string{"live"})
+ require.NoError(t, err)
+ require.Len(t, full, 1)
+ require.Equal(t, "body that validation must not load", full[0].Content,
+ "the existing content lookup must keep its full-row contract")
+}
+
+func TestListChunkEvidenceByIDOnlyEmptyIDsDoNotQuery(t *testing.T) {
+ repo := NewChunkRepository(nil)
+ rows, err := repo.ListChunkEvidenceByIDOnly(context.Background(), nil)
+ require.NoError(t, err)
+ require.Empty(t, rows)
+}
diff --git a/internal/modelcontext/graph_truncation_test.go b/internal/modelcontext/graph_truncation_test.go
index 64f175c97..813d32953 100644
--- a/internal/modelcontext/graph_truncation_test.go
+++ b/internal/modelcontext/graph_truncation_test.go
@@ -74,3 +74,61 @@ func TestModelOutputOmitsGraphTruncationMarkerWhenComplete(t *testing.T) {
require.Contains(t, output, `<relation source="Kubernetes" type="orchestrates" target="Docker" />`)
require.NotContains(t, output, "graph_truncated")
}
+
+func TestModelOutputMarksGraphValidationLimitIncludingZeroEvidence(t *testing.T) {
+ for _, valid := range []int{0, 7, 512} {
+ t.Run(fmt.Sprint(valid), func(t *testing.T) {
+ data := graphQueryResultData(nil, map[string]interface{}{
+ "graph_validation_truncated": true,
+ "graph_candidates_validated_total": 512,
+ "graph_validation_limit_per_kb": 512,
+ "graph_chunks_total": valid,
+ "graph_chunks_omitted": max(0, valid-10),
+ "graph_chunks_total_is_lower_bound": true,
+ "relations_total": 0,
+ "relations_omitted": 0,
+ "relations_total_is_lower_bound": true,
+ })
+ // The row may be a text fallback when graph validation found nothing.
+ output := newSourceRegistry().ModelOutput(&types.ToolResult{
+ Success: true, Output: "legacy output is replaced", Data: data,
+ })
+ require.Contains(t, output, `validation_stopped="true" candidates_validated_total="512" `+
+ `validation_limit_per_kb="512"`)
+ require.Contains(t, output, `relations_total_at_least="0"`)
+ require.Contains(t, output, fmt.Sprintf(`chunks_total_at_least="%d"`, valid))
+ require.Contains(t, output, "some candidate evidence was not checked")
+ require.Contains(t, output, fmt.Sprintf("at least %d valid in-scope evidence chunks", valid))
+ require.NotContains(t, output, `chunks_total="`)
+ require.NotContains(t, output, `relations_total="`)
+ })
+ }
+}
+
+func TestModelOutputPreservesValidationWarningOnEmptyGraphResult(t *testing.T) {
+ warning := "No relevant graph information found. Graph evidence validation stopped after 512 candidates. " +
+ "Some candidate evidence was not checked. Found at least 0 valid in-scope evidence chunks."
+ data := graphQueryResultData(nil, map[string]interface{}{
+ "graph_validation_truncated": true,
+ "graph_validation_limit_per_kb": 512,
+ "graph_candidates_validated_total": 512,
+ })
+ data["results"] = []map[string]interface{}{}
+ output := newSourceRegistry().ModelOutput(&types.ToolResult{Success: true, Output: warning, Data: data})
+ require.Contains(t, output, "validation stopped")
+ require.Contains(t, output, "Some candidate evidence was not checked")
+ require.Contains(t, output, "at least 0")
+}
+
+func TestModelOutputLabelsCandidateTotalSeparatelyFromPerKBLimit(t *testing.T) {
+ data := graphQueryResultData(nil, map[string]interface{}{
+ "graph_validation_truncated": true,
+ "graph_validation_limit_per_kb": 512,
+ "graph_candidates_validated_total": 1024,
+ "graph_chunks_total_is_lower_bound": true,
+ "relations_total_is_lower_bound": true,
+ })
+ output := newSourceRegistry().ModelOutput(&types.ToolResult{Success: true, Data: data})
+ require.Contains(t, output, `candidates_validated_total="1024" validation_limit_per_kb="512"`)
+ require.Contains(t, output, "512 candidates per knowledge base")
+}
diff --git a/internal/modelcontext/model_output.go b/internal/modelcontext/model_output.go
index c22e869be..04bb00fe7 100644
--- a/internal/modelcontext/model_output.go
+++ b/internal/modelcontext/model_output.go
@@ -338,29 +338,48 @@ func annotateGraphResult(output string, data map[string]interface{}) string {
// graphTruncationNote states inside the model's view the caps the graph query
// tool hit. shownRelations is how many relations that view carries; the tool
// reports the totals under relations_total / graph_chunks_total /
-// query_terms_total. It returns "" when nothing was dropped, so a complete
-// result stays clean.
+// query_terms_total. A validation-limit marker also travels independently of
+// those counts, including when no valid evidence was found.
func graphTruncationNote(data map[string]interface{}, shownRelations int) string {
totalRelations := intValue(data, "relations_total")
totalChunks := intValue(data, "graph_chunks_total")
fetchedChunks := totalChunks - intValue(data, "graph_chunks_omitted")
totalTerms := intValue(data, "query_terms_total")
- if totalRelations <= shownRelations && totalChunks <= fetchedChunks && totalTerms <= 0 {
+ validationLimited := boolValue(data, "graph_validation_truncated")
+ if !validationLimited && totalRelations <= shownRelations && totalChunks <= fetchedChunks && totalTerms <= 0 {
return ""
}
var b strings.Builder
b.WriteString(" <graph_truncated")
- if totalRelations > shownRelations {
- fmt.Fprintf(&b, " relations_shown=\"%d\" relations_total=\"%d\"", shownRelations, totalRelations)
+ if validationLimited {
+ fmt.Fprintf(&b, " validation_stopped=\"true\" candidates_validated_total=\"%d\" validation_limit_per_kb=\"%d\"",
+ intValue(data, "graph_candidates_validated_total"), intValue(data, "graph_validation_limit_per_kb"))
}
- if totalChunks > fetchedChunks {
- fmt.Fprintf(&b, " chunks_fetched=\"%d\" chunks_total=\"%d\"", fetchedChunks, totalChunks)
+ if totalRelations > shownRelations || validationLimited {
+ totalAttribute := "relations_total"
+ if boolValue(data, "relations_total_is_lower_bound") {
+ totalAttribute = "relations_total_at_least"
+ }
+ fmt.Fprintf(&b, " relations_shown=\"%d\" %s=\"%d\"", shownRelations, totalAttribute, totalRelations)
+ }
+ if totalChunks > fetchedChunks || validationLimited {
+ totalAttribute := "chunks_total"
+ if boolValue(data, "graph_chunks_total_is_lower_bound") {
+ totalAttribute = "chunks_total_at_least"
+ }
+ fmt.Fprintf(&b, " chunks_fetched=\"%d\" %s=\"%d\"", fetchedChunks, totalAttribute, totalChunks)
}
if totalTerms > 0 {
fmt.Fprintf(&b, " terms_shown=\"%d\" terms_total=\"%d\"",
totalTerms-intValue(data, "query_terms_omitted"), totalTerms)
}
b.WriteString(">This graph query stopped at a result cap, so it is not the complete picture: ")
+ if validationLimited {
+ fmt.Fprintf(&b, "evidence validation stopped at %d candidates per knowledge base; "+
+ "some candidate evidence was not checked. Found at least %d valid in-scope evidence chunks "+
+ "and at least %d supported relations. ",
+ intValue(data, "graph_validation_limit_per_kb"), totalChunks, totalRelations)
+ }
if totalRelations > shownRelations {
b.WriteString("the relations listed are a subset of these entities' relations, ")
}
diff --git a/internal/types/interfaces/chunk.go b/internal/types/interfaces/chunk.go
index 6db7bf000..add6d6180 100644
--- a/internal/types/interfaces/chunk.go
+++ b/internal/types/interfaces/chunk.go
@@ -30,6 +30,9 @@ type ChunkRepository interface {
ListChunksByID(ctx context.Context, tenantID uint64, ids []string) ([]*types.Chunk, error)
// ListChunksByIDOnly lists chunks by ids without tenant filter (for shared KB resolution).
ListChunksByIDOnly(ctx context.Context, ids []string) ([]*types.Chunk, error)
+ // ListChunkEvidenceByIDOnly loads only ID, KnowledgeBaseID, KnowledgeID and
+ // IsEnabled for live chunks, without a tenant filter for shared KB resolution.
+ ListChunkEvidenceByIDOnly(ctx context.Context, ids []string) ([]*types.Chunk, error)
// ListChunksBySeqID lists chunks by seq_ids
ListChunksBySeqID(ctx context.Context, tenantID uint64, seqIDs []int64) ([]*types.Chunk, error)
// ListChunksByKnowledgeID lists the knowledge's text chunks. Despite the name