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): exclude disabled FAQ entries

wizardchen7d2a6311cb38
diff --git a/internal/agent/tools/data_schema.go b/internal/agent/tools/data_schema.go
index c4b00a781..605469c44 100644
--- a/internal/agent/tools/data_schema.go
+++ b/internal/agent/tools/data_schema.go
@@ -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{
diff --git a/internal/agent/tools/database_query.go b/internal/agent/tools/database_query.go
index ea66595f0..20bda0b78 100644
--- a/internal/agent/tools/database_query.go
+++ b/internal/agent/tools/database_query.go
@@ -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),
)
diff --git a/internal/agent/tools/database_query_test.go b/internal/agent/tools/database_query_test.go
new file mode 100644
index 000000000..ab389ed1d
--- /dev/null
+++ b/internal/agent/tools/database_query_test.go
@@ -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)
+ }
+}
diff --git a/internal/agent/tools/get_document_info.go b/internal/agent/tools/get_document_info.go
index 1a7974dfd..27b31f498 100644
--- a/internal/agent/tools/get_document_info.go
+++ b/internal/agent/tools/get_document_info.go
@@ -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{
diff --git a/internal/agent/tools/knowledge_search.go b/internal/agent/tools/knowledge_search.go
index 9870c72b8..2b44a51d8 100644
--- a/internal/agent/tools/knowledge_search.go
+++ b/internal/agent/tools/knowledge_search.go
@@ -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)
diff --git a/internal/agent/tools/list_knowledge_chunks.go b/internal/agent/tools/list_knowledge_chunks.go
index ca2fd0c98..b192ee26a 100644
--- a/internal/agent/tools/list_knowledge_chunks.go
+++ b/internal/agent/tools/list_knowledge_chunks.go
@@ -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,
diff --git a/internal/agent/tools/scope_authorization.go b/internal/agent/tools/scope_authorization.go
index 62f4b1be0..f28aa203d 100644
--- a/internal/agent/tools/scope_authorization.go
+++ b/internal/agent/tools/scope_authorization.go
@@ -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)
}
diff --git a/internal/agent/tools/scope_authorization_test.go b/internal/agent/tools/scope_authorization_test.go
index c90debc6a..fdf28241b 100644
--- a/internal/agent/tools/scope_authorization_test.go
+++ b/internal/agent/tools/scope_authorization_test.go
@@ -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
diff --git a/internal/agent/tools/wiki_read_source_doc.go b/internal/agent/tools/wiki_read_source_doc.go
index 723ac2f12..461e9f76a 100644
--- a/internal/agent/tools/wiki_read_source_doc.go
+++ b/internal/agent/tools/wiki_read_source_doc.go
@@ -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
diff --git a/internal/application/repository/chunk.go b/internal/application/repository/chunk.go
index a010617e2..08723f3b6 100644
--- a/internal/application/repository/chunk.go
+++ b/internal/application/repository/chunk.go
@@ -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 + "%"
diff --git a/internal/application/repository/chunk_sqlite_test.go b/internal/application/repository/chunk_sqlite_test.go
index a332259cd..34163c819 100644
--- a/internal/application/repository/chunk_sqlite_test.go
+++ b/internal/application/repository/chunk_sqlite_test.go
@@ -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)
diff --git a/internal/application/repository/retriever/milvus/repository.go b/internal/application/repository/retriever/milvus/repository.go
index c5d2ed26c..874ac9c5c 100644
--- a/internal/application/repository/retriever/milvus/repository.go
+++ b/internal/application/repository/retriever/milvus/repository.go
@@ -2,6 +2,7 @@ package milvus
import (
"context"
+ "errors"
"fmt"
"maps"
"os"
@@ -429,23 +430,42 @@ func (m *milvusRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, ch
}
}
- // Update in all matching collections
+ // 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 {
- // Only process collections that start with our base name
- if len(collectionName) <= len(m.collectionBaseName) ||
- collectionName[:len(m.collectionBaseName)] != m.collectionBaseName {
+ if len(collectionName) <= len(collectionBaseName) ||
+ collectionName[:len(collectionBaseName)] != 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 := update(ctx, collectionName, enabledChunkIDs, true); err != nil {
+ updateErrs = append(updateErrs, fmt.Errorf("update enabled chunks in %s: %w", 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)
+ if err := update(ctx, collectionName, disabledChunkIDs, false); err != nil {
+ updateErrs = append(updateErrs, fmt.Errorf("update disabled chunks in %s: %w", collectionName, err))
}
}
-
- log.Infof("[Milvus] Batch update chunk enabled status completed")
- return nil
+ return errors.Join(updateErrs...)
}
func (m *milvusRepository) updateChunkEnabledStatusInCollection(
diff --git a/internal/application/repository/retriever/milvus/repository_test.go b/internal/application/repository/retriever/milvus/repository_test.go
index ae6d3311f..179561e50 100644
--- a/internal/application/repository/retriever/milvus/repository_test.go
+++ b/internal/application/repository/retriever/milvus/repository_test.go
@@ -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)
+}
diff --git a/internal/application/service/chunk.go b/internal/application/service/chunk.go
index 43fcba7d5..de8ac9513 100644
--- a/internal/application/service/chunk.go
+++ b/internal/application/service/chunk.go
@@ -192,6 +192,7 @@ func (s *chunkService) ListPagedChunksByKnowledgeID(ctx context.Context,
"",
"",
"",
+ nil,
)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
diff --git a/internal/application/service/knowledge_clone_move.go b/internal/application/service/knowledge_clone_move.go
index bce9c5d16..6f2b0e2ab 100644
--- a/internal/application/service/knowledge_clone_move.go
+++ b/internal/application/service/knowledge_clone_move.go
@@ -322,6 +322,7 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowl
"",
"",
"",
+ nil,
)
chunkPage++
if err != nil {
diff --git a/internal/application/service/knowledge_faq.go b/internal/application/service/knowledge_faq.go
index 74aa91a02..ed82eabb9 100644
--- a/internal/application/service/knowledge_faq.go
+++ b/internal/application/service/knowledge_faq.go
@@ -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
diff --git a/internal/application/service/knowledgebase_search_results.go b/internal/application/service/knowledgebase_search_results.go
index e899740da..9c8e068c1 100644
--- a/internal/application/service/knowledgebase_search_results.go
+++ b/internal/application/service/knowledgebase_search_results.go
@@ -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.
diff --git a/internal/application/service/knowledgebase_search_results_edit_test.go b/internal/application/service/knowledgebase_search_results_edit_test.go
index 407f44f1c..8a6bd9809 100644
--- a/internal/application/service/knowledgebase_search_results_edit_test.go
+++ b/internal/application/service/knowledgebase_search_results_edit_test.go
@@ -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")
+ }
+}
diff --git a/internal/types/interfaces/chunk.go b/internal/types/interfaces/chunk.go
index f0de9aea2..9f6434d61 100644
--- a/internal/types/interfaces/chunk.go
+++ b/internal/types/interfaces/chunk.go
@@ -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
diff --git a/internal/utils/inject.go b/internal/utils/inject.go
index 8c57adce4..07ca425fc 100644
--- a/internal/utils/inject.go
+++ b/internal/utils/inject.go
@@ -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 {
diff --git a/internal/utils/inject_test.go b/internal/utils/inject_test.go
index b3a896634..1326a89bc 100644
--- a/internal/utils/inject_test.go
+++ b/internal/utils/inject_test.go
@@ -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) {