fix(agent): exclude disabled FAQ entries

main
wizardchen 2026-07-29 14:33:44 +08:00 committed by lyingbug
parent c291c6a59f
commit 7d2a6311cb
21 changed files with 221 additions and 19 deletions

View File

@ -85,6 +85,7 @@ func (t *DataSchemaTool) Execute(ctx context.Context, args json.RawMessage) (*ty
Page: 1,
PageSize: 100, // Should be enough for schema chunks
}
enabled := true
chunks, _, err := t.chunkRepo.ListPagedChunksByKnowledgeID(
ctx,
@ -97,6 +98,7 @@ func (t *DataSchemaTool) Execute(ctx context.Context, args json.RawMessage) (*ty
"", // searchField
"", // sortOrder
"", // knowledgeType
&enabled,
)
if err != nil {
return &types.ToolResult{

View File

@ -259,6 +259,7 @@ func (t *DatabaseQueryTool) validateAndSecureSQL(sqlQuery string, tenantID uint6
utils.WithSecurityDefaults(tenantID),
utils.WithSoftDeleteFilter("knowledge_bases", "knowledges", "chunks"),
utils.WithHiddenKBFilter(),
utils.WithChunkEnabledFilter(),
utils.WithInjectionRiskCheck(),
utils.WithSearchScopes(searchScopes),
)

View File

@ -0,0 +1,26 @@
package tools
import (
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestDatabaseQueryInjectsEnabledChunkFilter(t *testing.T) {
tool := NewDatabaseQueryTool(nil, types.SearchTargets{{
Type: types.SearchTargetTypeKnowledgeBase,
KnowledgeBaseID: "kb-1",
}})
securedSQL, err := tool.validateAndSecureSQL(
"SELECT c.id, c.content FROM chunks c WHERE c.chunk_type = 'faq'",
1,
)
if err != nil {
t.Fatalf("validateAndSecureSQL() error = %v", err)
}
if !strings.Contains(securedSQL, "c.is_enabled = true") {
t.Fatalf("Agent SQL must exclude disabled chunks:\n%s", securedSQL)
}
}

View File

@ -122,6 +122,7 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
var wg sync.WaitGroup
var mu sync.Mutex
results := make(map[string]*docInfo)
enabled := true
for _, faqID := range faqIDs {
faqID = strings.TrimSpace(faqID)
@ -174,7 +175,7 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
ListPagedChunksByKnowledgeID(ctx, knowledge.TenantID, id, &types.Pagination{
Page: 1,
PageSize: 1,
}, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, nil, "", "", "", "")
}, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, nil, "", "", "", "", &enabled)
if err != nil {
mu.Lock()
results[id] = &docInfo{

View File

@ -1184,6 +1184,7 @@ func (t *KnowledgeSearchTool) formatOutput(
writeKnowledgeMetadataHeader(&ob, results)
formattedResults := make([]map[string]interface{}, 0, len(results))
enabled := true
faqMetadataCache := make(map[string]*types.FAQChunkMetadata)
@ -1223,6 +1224,7 @@ func (t *KnowledgeSearchTool) formatOutput(
effectiveTenantID, result.KnowledgeID,
&types.Pagination{Page: 1, PageSize: 1},
[]types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, nil, "", "", "", "",
&enabled,
)
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to get total chunks for knowledge %s: %v", result.KnowledgeID, err)

View File

@ -145,8 +145,9 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMess
PageSize: chunkLimit,
}
enabled := true
chunks, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
effectiveTenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, nil, "", "", "", "")
effectiveTenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, nil, "", "", "", "", &enabled)
if err != nil {
return &types.ToolResult{
Success: false,

View File

@ -116,6 +116,9 @@ func authorizeChunkInSearchTargets(
}
return nil, fmt.Errorf("chunk %s not found: %w", chunkID, err)
}
if !chunk.IsEnabled {
return nil, fmt.Errorf("chunk %s is disabled", chunk.ID)
}
if !searchTargets.ContainsKB(chunk.KnowledgeBaseID) {
return nil, fmt.Errorf("knowledge base %s is not within the current Agent scope", chunk.KnowledgeBaseID)
}

View File

@ -14,6 +14,15 @@ type scopeKnowledgeService struct {
tags map[string][]*types.KnowledgeTag
}
type scopeChunkService struct {
interfaces.ChunkService
chunk *types.Chunk
}
func (s *scopeChunkService) GetChunkByIDOnly(context.Context, string) (*types.Chunk, error) {
return s.chunk, nil
}
func (s *scopeKnowledgeService) GetKnowledgeByIDOnly(context.Context, string) (*types.Knowledge, error) {
return s.knowledge, nil
}
@ -81,6 +90,25 @@ func TestAuthorizeKnowledgeInSearchTargetsAllowsBoundDocument(t *testing.T) {
}
}
func TestAuthorizeChunkInSearchTargetsRejectsDisabledFAQ(t *testing.T) {
chunkService := &scopeChunkService{chunk: &types.Chunk{
ID: "faq-1", KnowledgeID: "faq-document", KnowledgeBaseID: "kb-1",
ChunkType: types.ChunkTypeFAQ, IsEnabled: false,
}}
knowledgeService := &scopeKnowledgeService{knowledge: &types.Knowledge{
ID: "faq-document", KnowledgeBaseID: "kb-1",
}}
targets := types.SearchTargets{{
Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb-1",
}}
if _, err := authorizeChunkInSearchTargets(
context.Background(), targets, "faq-1", chunkService, knowledgeService,
); err == nil {
t.Fatal("disabled FAQ chunk must not be authorized for Agent tools")
}
}
// A tag-scoped mention is resolved into KnowledgeIDs (intersected with any
// explicitly mentioned documents) while the tag is retained as the logical
// scope record. Re-admitting every document carrying that tag would undo the

View File

@ -206,6 +206,7 @@ func (t *wikiReadSourceDocTool) Execute(ctx context.Context, args json.RawMessag
}
for {
enabled := true
pagination := &types.Pagination{
Page: page,
PageSize: pageSize,
@ -217,7 +218,7 @@ func (t *wikiReadSourceDocTool) Execute(ctx context.Context, args json.RawMessag
knowledgeID,
pagination,
[]types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ},
nil, "", "", "", "",
nil, "", "", "", "", &enabled,
)
if err != nil {
return &types.ToolResult{Success: false, Error: fmt.Sprintf("Failed to list chunks: %v", err)}, nil

View File

@ -171,6 +171,7 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
searchField string,
sortOrder string,
knowledgeType string,
isEnabled *bool,
) ([]*types.Chunk, int64, error) {
var chunks []*types.Chunk
var total int64
@ -182,6 +183,9 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
if len(tagIDs) > 0 {
db = db.Where("tag_id IN ?", tagIDs)
}
if isEnabled != nil {
db = db.Where("is_enabled = ?", *isEnabled)
}
if keyword != "" {
like := "%" + keyword + "%"

View File

@ -216,6 +216,37 @@ func TestUpdateChunk_SQLite_NoNOWError(t *testing.T) {
assert.Equal(t, "updated content", saved.Content)
}
func TestListPagedChunksByKnowledgeID_FiltersEnabledState(t *testing.T) {
db := setupChunkTestDB(t)
repo := NewChunkRepository(db)
ctx := context.Background()
enabledChunk := makeChunk("kb-1", "faq-knowledge", types.ChunkTypeFAQ)
disabledChunk := makeChunk("kb-1", "faq-knowledge", types.ChunkTypeFAQ)
require.NoError(t, repo.CreateChunks(ctx, []*types.Chunk{enabledChunk, disabledChunk}))
require.NoError(t, db.Model(&types.Chunk{}).
Where("id = ?", disabledChunk.ID).
Update("is_enabled", false).Error)
enabled := true
chunks, total, err := repo.ListPagedChunksByKnowledgeID(
ctx, 1, "faq-knowledge", &types.Pagination{Page: 1, PageSize: 20},
[]types.ChunkType{types.ChunkTypeFAQ}, nil, "", "", "", types.KnowledgeTypeFAQ, &enabled,
)
require.NoError(t, err)
require.Equal(t, int64(1), total)
require.Len(t, chunks, 1)
assert.Equal(t, enabledChunk.ID, chunks[0].ID)
allChunks, allTotal, err := repo.ListPagedChunksByKnowledgeID(
ctx, 1, "faq-knowledge", &types.Pagination{Page: 1, PageSize: 20},
[]types.ChunkType{types.ChunkTypeFAQ}, nil, "", "", "", types.KnowledgeTypeFAQ, nil,
)
require.NoError(t, err)
assert.Equal(t, int64(2), allTotal)
assert.Len(t, allChunks, 2)
}
func makeSuggestedFAQChunk(t *testing.T, kbID, knowledgeID, tagID, question string) *types.Chunk {
t.Helper()
chunk := makeChunk(kbID, knowledgeID, types.ChunkTypeFAQ)

View File

@ -2,6 +2,7 @@ package milvus
import (
"context"
"errors"
"fmt"
"maps"
"os"
@ -429,25 +430,44 @@ func (m *milvusRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, ch
}
}
// Update in all matching collections
for _, collectionName := range collections {
// Only process collections that start with our base name
if len(collectionName) <= len(m.collectionBaseName) ||
collectionName[:len(m.collectionBaseName)] != m.collectionBaseName {
continue
}
if err := m.updateChunkEnabledStatusInCollection(ctx, collectionName, enabledChunkIDs, true); err != nil {
log.Warnf("[Milvus] Failed to update enabled chunks in %s: %v", collectionName, err)
}
if err := m.updateChunkEnabledStatusInCollection(ctx, collectionName, disabledChunkIDs, false); err != nil {
log.Warnf("[Milvus] Failed to update disabled chunks in %s: %v", collectionName, err)
}
// A disabled row in the primary DB must never remain searchable because an
// index update failed silently.
if err := updateChunkEnabledStatusInCollections(
ctx, collections, m.collectionBaseName, enabledChunkIDs, disabledChunkIDs,
m.updateChunkEnabledStatusInCollection,
); err != nil {
log.Warnf("[Milvus] Failed to update chunk enabled status: %v", err)
return err
}
log.Infof("[Milvus] Batch update chunk enabled status completed")
return nil
}
func updateChunkEnabledStatusInCollections(
ctx context.Context,
collections []string,
collectionBaseName string,
enabledChunkIDs []string,
disabledChunkIDs []string,
update func(context.Context, string, []string, bool) error,
) error {
var updateErrs []error
for _, collectionName := range collections {
if len(collectionName) <= len(collectionBaseName) ||
collectionName[:len(collectionBaseName)] != collectionBaseName {
continue
}
if err := update(ctx, collectionName, enabledChunkIDs, true); err != nil {
updateErrs = append(updateErrs, fmt.Errorf("update enabled chunks in %s: %w", collectionName, err))
}
if err := update(ctx, collectionName, disabledChunkIDs, false); err != nil {
updateErrs = append(updateErrs, fmt.Errorf("update disabled chunks in %s: %w", collectionName, err))
}
}
return errors.Join(updateErrs...)
}
func (m *milvusRepository) updateChunkEnabledStatusInCollection(
ctx context.Context,
collectionName string,

View File

@ -2,6 +2,7 @@ package milvus
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/require"
@ -23,3 +24,21 @@ func TestUpdateChunkEnabledStatusInCollectionSkipsEmptyChunkIDs(t *testing.T) {
true,
))
}
func TestUpdateChunkEnabledStatusInCollectionsPropagatesFailure(t *testing.T) {
wantErr := errors.New("upsert failed")
err := updateChunkEnabledStatusInCollections(
context.Background(),
[]string{"other_collection", "weknora_embeddings_1024"},
"weknora_embeddings",
nil,
[]string{"chunk-1"},
func(_ context.Context, collection string, _ []string, enabled bool) error {
if collection == "weknora_embeddings_1024" && !enabled {
return wantErr
}
return nil
},
)
require.ErrorIs(t, err, wantErr)
}

View File

@ -192,6 +192,7 @@ func (s *chunkService) ListPagedChunksByKnowledgeID(ctx context.Context,
"",
"",
"",
nil,
)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{

View File

@ -322,6 +322,7 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowl
"",
"",
"",
nil,
)
chunkPage++
if err != nil {

View File

@ -79,6 +79,7 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
chunkType := []types.ChunkType{types.ChunkTypeFAQ}
chunks, total, err := s.chunkRepo.ListPagedChunksByKnowledgeID(
ctx, effectiveTenantID, faqKnowledge.ID, page, chunkType, tagUUIDs, keyword, searchField, sortOrder, types.KnowledgeTypeFAQ,
nil,
)
if err != nil {
return nil, err

View File

@ -334,6 +334,9 @@ func (s *knowledgeBaseService) buildSearchResult(chunk *types.Chunk,
// isSearchableChunk checks if a chunk type should be included in search results.
func (s *knowledgeBaseService) isSearchableChunk(chunk *types.Chunk) bool {
if chunk == nil || !chunk.IsEnabled {
return false
}
// An edit is persisted before its retrieval artifacts are synchronized.
// Do not hydrate stale vector hits while that synchronization is pending or
// failed. Empty is accepted for legacy rows created before index_status.

View File

@ -9,15 +9,27 @@ import (
func TestIsSearchableChunkSkipsUnsynchronizedEdits(t *testing.T) {
service := &knowledgeBaseService{}
for _, status := range []string{"processing", "failed"} {
chunk := &types.Chunk{ChunkType: types.ChunkTypeText, IndexStatus: status}
chunk := &types.Chunk{ChunkType: types.ChunkTypeText, IndexStatus: status, IsEnabled: true}
if service.isSearchableChunk(chunk) {
t.Fatalf("chunk with index status %q should not be searchable", status)
}
}
for _, status := range []string{"", "ready"} {
chunk := &types.Chunk{ChunkType: types.ChunkTypeText, IndexStatus: status}
chunk := &types.Chunk{ChunkType: types.ChunkTypeText, IndexStatus: status, IsEnabled: true}
if !service.isSearchableChunk(chunk) {
t.Fatalf("chunk with index status %q should be searchable", status)
}
}
}
func TestIsSearchableChunkSkipsDisabledChunk(t *testing.T) {
service := &knowledgeBaseService{}
chunk := &types.Chunk{
ChunkType: types.ChunkTypeFAQ,
IndexStatus: "ready",
IsEnabled: false,
}
if service.isSearchableChunk(chunk) {
t.Fatal("disabled FAQ chunk should never be searchable")
}
}

View File

@ -37,6 +37,8 @@ type ChunkRepository interface {
// - Document (manual): sorts by chunk_index, keyword searches content only
// sortOrder: "asc" for ascending, default is descending
// searchField: specifies which field to search in (only applicable for FAQ type)
// isEnabled: when non-nil, filters chunks by their enabled state. Agent/model
// consumers must pass true so disabled content never enters model context.
ListPagedChunksByKnowledgeID(
ctx context.Context,
tenantID uint64,
@ -48,6 +50,7 @@ type ChunkRepository interface {
searchField string,
sortOrder string,
knowledgeType string,
isEnabled *bool,
) ([]*types.Chunk, int64, error)
ListChunkByParentID(ctx context.Context, tenantID uint64, parentID string) ([]*types.Chunk, error)
// ListChunksByParentIDs lists chunks whose parent_chunk_id is in the given list

View File

@ -140,6 +140,9 @@ type sqlValidator struct {
// Hidden knowledge base filtering (is_temporary = false)
enableHiddenKBFilter bool
// Enabled chunk filtering (is_enabled = true)
enableChunkEnabledFilter bool
// Search scope filtering (restrict to specific KBs and knowledges)
enableSearchScopeFilter bool
searchScopeKBIDs []string
@ -624,6 +627,15 @@ func WithHiddenKBFilter() SQLValidationOption {
}
}
// WithChunkEnabledFilter excludes disabled chunks from model-visible SQL
// queries. It is intentionally opt-in because administrative queries may need
// to inspect disabled rows.
func WithChunkEnabledFilter() SQLValidationOption {
return func(v *sqlValidator) {
v.enableChunkEnabledFilter = true
}
}
// WithSearchScopeFilter restricts queries to the specified knowledge bases and
// (optionally) specific knowledge documents. For the knowledge_bases table it
// filters by id; for knowledges it filters by knowledge_base_id (and id when
@ -857,7 +869,8 @@ func ValidateAndSecureSQL(sql string, opts ...SQLValidationOption) (string, *SQL
}
// If no SQL rewriting is enabled, return original SQL
if !validator.enableTenantInjection && !validator.enableSoftDeleteInjection && !validator.enableHiddenKBFilter && !validator.enableSearchScopeFilter {
if !validator.enableTenantInjection && !validator.enableSoftDeleteInjection && !validator.enableHiddenKBFilter &&
!validator.enableChunkEnabledFilter && !validator.enableSearchScopeFilter {
return sql, validationResult, nil
}
@ -882,6 +895,8 @@ func ValidateAndSecureSQL(sql string, opts ...SQLValidationOption) (string, *SQL
securedSQL = validator.injectSoftDeleteConditions(securedSQL, tablesInQuery)
// Inject hidden KB filter (exclude is_temporary = true knowledge bases)
securedSQL = validator.injectHiddenKBFilter(securedSQL, tablesInQuery)
// Exclude disabled chunks from model-visible query results.
securedSQL = validator.injectChunkEnabledFilter(securedSQL, tablesInQuery)
// Inject search scope filter (restrict to allowed KBs and knowledges)
securedSQL = validator.injectSearchScopeConditions(securedSQL, tablesInQuery)
@ -1032,6 +1047,17 @@ func (v *sqlValidator) injectHiddenKBFilter(sql string, tablesInQuery map[string
return InjectAndConditions(sql, fmt.Sprintf("%s.is_temporary = false", alias))
}
func (v *sqlValidator) injectChunkEnabledFilter(sql string, tablesInQuery map[string]string) string {
if !v.enableChunkEnabledFilter {
return sql
}
alias, ok := tablesInQuery["chunks"]
if !ok {
return sql
}
return InjectAndConditions(sql, fmt.Sprintf("%s.is_enabled = true", alias))
}
// injectSearchScopeConditions restricts queries to the allowed knowledge bases
// and (optionally) specific knowledge documents.
func (v *sqlValidator) injectSearchScopeConditions(sql string, tablesInQuery map[string]string) string {

View File

@ -481,6 +481,22 @@ func TestValidateAndSecureSQL_WithStructuredSearchScopes(t *testing.T) {
}
}
func TestValidateAndSecureSQL_WithChunkEnabledFilter(t *testing.T) {
securedSQL, validation, err := ValidateAndSecureSQL(
"SELECT c.id, c.content FROM chunks c WHERE c.chunk_type = 'faq'",
WithChunkEnabledFilter(),
)
if err != nil {
t.Fatalf("ValidateAndSecureSQL() error = %v", err)
}
if !validation.Valid {
t.Fatalf("expected validation to pass, got %#v", validation.Errors)
}
if !strings.Contains(securedSQL, "c.is_enabled = true") {
t.Fatalf("secured SQL must exclude disabled chunks:\n%s", securedSQL)
}
}
// A scope carrying both a document whitelist and a tag filter must apply both.
// Emitting only one of them would admit rows the other excludes.
func TestValidateAndSecureSQL_ScopeCombinesDocumentAndTagFilters(t *testing.T) {