diff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yaml index 6399c969..871dd395 100644 --- a/config/prompt_templates/agent_system_prompt.yaml +++ b/config/prompt_templates/agent_system_prompt.yaml @@ -71,8 +71,8 @@ templates: You are WeKnora Data Analyst, specializing in analysis of the user's CSV and Excel data with DuckDB. For a data-analysis task: - Inspect the target table with data_schema before writing SQL if its current schema is not already available. Reuse a schema obtained for the same unchanged table during this task. - - Use data_analysis with the supplied document handle and a read-only query. Follow its tool definition and reported validation errors; do not modify source data. - - Use exact table and column names from the schema. Quote identifiers with double quotes. Limit exploratory output, then compute the aggregates needed to answer the question. + - Use data_analysis with the supplied document handle in knowledge_id and a read-only query. The selected document is always the table "dataset"; never write the document handle or ID inside the SQL. Follow its tool definition and reported validation errors; do not modify source data. + - Use exact column names from the schema. Quote identifiers with double quotes. Limit exploratory output, then compute the aggregates needed to answer the question. - Check units, time ranges, nulls, joins, and aggregation assumptions before interpreting the result. Distinguish observed values from inference. - Present an appropriate table, chart, or explanation, including assumptions and material limitations. Do not force a SQL call for a question that needs no data access. Use only tools available in this turn; source selection and output conventions are defined by the runtime sections. diff --git a/internal/agent/think.go b/internal/agent/think.go index c4d63040..94bfec21 100644 --- a/internal/agent/think.go +++ b/internal/agent/think.go @@ -13,6 +13,7 @@ import ( "github.com/Tencent/WeKnora/internal/common" "github.com/Tencent/WeKnora/internal/event" "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/modelcontext" "github.com/Tencent/WeKnora/internal/models/chat" "github.com/Tencent/WeKnora/internal/types" ) @@ -53,6 +54,7 @@ func (e *AgentEngine) streamLLMToEventBus( // Model-context encoding owns codec ordering and temporary-handle lifecycle. messages = e.modelContext.EncodeMessages(messages) + reportModelContextLeaks(ctx, "Agent", e.modelContext, messages) prefixFingerprint := chat.PromptPrefixFingerprint(messages, opts) llmCtx = types.WithLLMCallMetadata(llmCtx, "agent_round", prefixFingerprint) stream, err := e.chatModel.ChatStream(llmCtx, messages, opts) @@ -624,3 +626,17 @@ func (e *AgentEngine) callLLMWithRetry( return response, nil } + +// reportModelContextLeaks logs any durable identifier that survived encoding. +// Each line names the producing role or tool so the leak can be fixed at its +// source; see modelcontext/leaks.go. +func reportModelContextLeaks( + ctx context.Context, scope string, registry *modelcontext.Registry, messages []chat.Message, +) { + leaks := registry.LeakedIdentifiers(messages) + if len(leaks) == 0 { + return + } + logger.Warnf(ctx, "[%s][ModelContext] %d message field(s) carry raw identifiers after encoding: %s", + scope, len(leaks), modelcontext.SummarizeLeaks(leaks)) +} diff --git a/internal/agent/tools/data_analysis.go b/internal/agent/tools/data_analysis.go index 4654749d..561db4d7 100644 --- a/internal/agent/tools/data_analysis.go +++ b/internal/agent/tools/data_analysis.go @@ -18,11 +18,24 @@ import ( "github.com/Tencent/WeKnora/internal/utils" ) +// DataAnalysisTableName is the only table name the model needs to know when +// querying a CSV/Excel document through data_analysis. Each document is loaded +// into a physical DuckDB table named after its knowledge ID; that name is +// never shown to the model. Every query runs on a private connection where +// "dataset" is a temporary view over the selected document, so the model +// references the same fixed identifier for every document and the knowledge +// ID never has to appear inside SQL text. +const DataAnalysisTableName = "dataset" + var dataAnalysisTool = BaseTool{ name: ToolDataAnalysis, - description: "Use this tool when the knowledge is CSV or Excel files. It loads the data into memory and executes SQL for data analysis. " + - "For Excel files with multiple sheets, every sheet is loaded into the same table and the source sheet name is exposed as a '__sheet_name' column so you can filter/aggregate per sheet. " + - "If the user's question requires data statistics, convert the question into SQL and execute it.", + description: "Use this tool when the knowledge is CSV or Excel files. It loads the document into DuckDB " + + "and executes a read-only SQL query for data analysis. The selected document is always exposed as " + + "the single table \"" + DataAnalysisTableName + "\"; write SQL against that table name and never put " + + "the document ID inside the SQL. For Excel files with multiple sheets, every sheet is loaded into " + + "the same table and the source sheet name is exposed as a '__sheet_name' column so you can " + + "filter/aggregate per sheet. If the user's question requires data statistics, convert the " + + "question into SQL and execute it.", schema: utils.GenerateSchema[DataAnalysisInput](), } @@ -105,7 +118,7 @@ func buildMissingColumnSuggestion(sqlErr error, schema *TableSchema) string { type DataAnalysisInput struct { KnowledgeID string `json:"knowledge_id" jsonschema:"short dN document ID to query"` - Sql string `json:"sql" jsonschema:"SQL to be executed on knowledge"` + SQL string `json:"sql" jsonschema:"Read-only SELECT executed on the document. Reference the document as the table \"dataset\" (for example SELECT COUNT(*) FROM dataset); it is the only table available"` //nolint:lll // jsonschema tag } type DataAnalysisTool struct { @@ -230,20 +243,18 @@ func (t *DataAnalysisTool) Execute(ctx context.Context, args json.RawMessage) (* }, err } - // Replace knowledge ID with table name - input.Sql = strings.ReplaceAll(input.Sql, input.KnowledgeID, schema.TableName) - if rewrittenSQL, fixes := reconcileSQLColumnsWithSchema(input.Sql, schema); len(fixes) > 0 { + if rewrittenSQL, fixes := reconcileSQLColumnsWithSchema(input.SQL, schema); len(fixes) > 0 { logger.Infof(ctx, "[Tool][DataAnalysis] Auto-rewrote SQL identifiers for session %s: %v", t.sessionID, fixes) - input.Sql = rewrittenSQL + input.SQL = rewrittenSQL } // Check if this is a read-only query - normalizedSQL := strings.TrimSpace(strings.ToLower(input.Sql)) + normalizedSQL := strings.TrimSpace(strings.ToLower(input.SQL)) isReadOnly := strings.HasPrefix(normalizedSQL, "select") if !isReadOnly { // Reject modification queries - logger.Warnf(ctx, "[Tool][DataAnalysis] Modification query rejected for session %s: %s", t.sessionID, input.Sql) + logger.Warnf(ctx, "[Tool][DataAnalysis] Modification query rejected for session %s: %s", t.sessionID, input.SQL) return &types.ToolResult{ Success: false, Error: "DuckDB tool only supports read-only SELECT queries. " + @@ -251,25 +262,17 @@ func (t *DataAnalysisTool) Execute(ctx context.Context, args json.RawMessage) (* }, fmt.Errorf("modification queries are not allowed") } - // Validate SQL with comprehensive security checks - // IMPORTANT: Must enable validateSelectStmt to block RangeFunction attacks - _, validation := utils.ValidateSQL(input.Sql, - utils.WithAllowedTables(schema.TableName), - utils.WithSelectOnly(), - utils.WithSingleStatement(), // Block multiple statements - utils.WithNoDangerousFunctions(), // Block dangerous functions - ) - if !validation.Valid { - logger.Warnf(ctx, "[Tool][DataAnalysis] SQL validation failed for session %s: %v", t.sessionID, validation.Errors) + if err := validateDataAnalysisSQL(input.SQL, schema); err != nil { + logger.Warnf(ctx, "[Tool][DataAnalysis] SQL validation failed for session %s: %v", t.sessionID, err) return &types.ToolResult{ Success: false, - Error: fmt.Sprintf("SQL validation failed: %v", validation.Errors), - }, fmt.Errorf("SQL validation failed: %v", validation.Errors) + Error: err.Error(), + }, err } - logger.Infof(ctx, "[Tool][DataAnalysis] Received SQL query for session %s: %s", t.sessionID, input.Sql) + logger.Infof(ctx, "[Tool][DataAnalysis] Received SQL query for session %s: %s", t.sessionID, input.SQL) // Execute single query and get results - results, err := t.executeSingleQuery(ctx, input.Sql) + results, err := t.executeSingleQuery(ctx, input.SQL, schema.TableName) if err != nil { if suggestion := buildMissingColumnSuggestion(err, schema); suggestion != "" { return &types.ToolResult{ @@ -283,7 +286,7 @@ func (t *DataAnalysisTool) Execute(ctx context.Context, args json.RawMessage) (* }, err } - queryOutput := t.formatQueryResults(results, input.Sql) + queryOutput := t.formatQueryResults(results, input.SQL) logger.Infof(ctx, "[Tool][DataAnalysis] Completed execution query, total %d rows for session %s", len(results), t.sessionID) return &types.ToolResult{ Success: true, @@ -291,7 +294,7 @@ func (t *DataAnalysisTool) Execute(ctx context.Context, args json.RawMessage) (* Data: map[string]interface{}{ "rows": results, "row_count": len(results), - "query": input.Sql, + "query": input.SQL, "display_type": ToolDataAnalysis, "session_id": t.sessionID, }, @@ -308,8 +311,68 @@ func (t *DataAnalysisTool) Execute(ctx context.Context, args json.RawMessage) (* // - []string: merged column names (existing + new columns, deduplicated) // - []map[string]string: query results // - error: any error that occurred during execution -func (t *DataAnalysisTool) executeSingleQuery(ctx context.Context, sqlQuery string) ([]map[string]string, error) { - rows, err := t.db.QueryContext(ctx, sqlQuery) +// +// validateDataAnalysisSQL enforces the read-only, single-table contract. The +// model-facing DataAnalysisTableName and the physical table are both accepted +// so that internal callers (ingest sampling, older stored schema summaries) +// keep working; a query against anything else is rejected with an error that +// names the table the model should have used. +func validateDataAnalysisSQL(sqlQuery string, schema *TableSchema) error { + // IMPORTANT: Must enable validateSelectStmt to block RangeFunction attacks + _, validation := utils.ValidateSQL(sqlQuery, + utils.WithAllowedTables(DataAnalysisTableName, schema.TableName), + utils.WithSelectOnly(), + utils.WithSingleStatement(), // Block multiple statements + utils.WithNoDangerousFunctions(), // Block dangerous functions + ) + if validation.Valid { + return nil + } + for _, validationErr := range validation.Errors { + if validationErr.Type == "table_not_allowed" { + return fmt.Errorf( + "SQL validation failed: %s. The selected document is exposed as the single table %q; "+ + "write the query against that table name and pass the document only through knowledge_id", + validationErr.Message, DataAnalysisTableName, + ) + } + } + return fmt.Errorf("SQL validation failed: %v", validation.Errors) +} + +// executeSingleQuery runs a validated query on a dedicated connection where +// DataAnalysisTableName is a temporary view over the document's physical +// table. Temporary objects are connection-local in DuckDB, so concurrent +// sessions analysing different documents never observe each other's view; the +// view is replaced on entry and dropped on exit so a pooled connection carries +// nothing over to its next user. +func (t *DataAnalysisTool) executeSingleQuery( + ctx context.Context, sqlQuery string, physicalTable string, +) ([]map[string]string, error) { + conn, err := t.db.Conn(ctx) + if err != nil { + logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to acquire connection: %v", err) + return nil, fmt.Errorf("failed to acquire database connection: %w", err) + } + defer func() { _ = conn.Close() }() + + viewSQL := fmt.Sprintf( + `CREATE OR REPLACE TEMPORARY VIEW "%s" AS SELECT * FROM "%s"`, + DataAnalysisTableName, physicalTable, + ) + if _, err := conn.ExecContext(ctx, viewSQL); err != nil { + logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to expose table '%s' as %s: %v", + physicalTable, DataAnalysisTableName, err) + return nil, fmt.Errorf("failed to expose document table: %w", err) + } + defer func() { + dropSQL := fmt.Sprintf(`DROP VIEW IF EXISTS "%s"`, DataAnalysisTableName) + if _, err := conn.ExecContext(context.WithoutCancel(ctx), dropSQL); err != nil { + logger.Warnf(ctx, "[Tool][DataAnalysis] Failed to drop temporary view %s: %v", DataAnalysisTableName, err) + } + }() + + rows, err := conn.QueryContext(ctx, sqlQuery) if err != nil { logger.Errorf(ctx, "[Tool][DataAnalysis] Query execution failed: %v", err) return nil, fmt.Errorf("query execution failed: %w", err) @@ -767,10 +830,12 @@ func (t *DataAnalysisTool) TableName(knowledge *types.Knowledge) string { return "k_" + strings.ReplaceAll(knowledge.ID, "-", "_") } -// buildSchemaDescription builds a formatted schema description +// Description builds the model-facing schema description. It names the table +// as DataAnalysisTableName, the identifier the model must use in SQL; the +// physical TableName stays internal. func (t *TableSchema) Description() string { var builder strings.Builder - builder.WriteString(fmt.Sprintf("Table name: %s\n", t.TableName)) + fmt.Fprintf(&builder, "Table name: %s\n", DataAnalysisTableName) builder.WriteString(fmt.Sprintf("Columns: %d\n", len(t.Columns))) builder.WriteString(fmt.Sprintf("Rows: %d\n\n", t.RowCount)) builder.WriteString("Column info:\n") diff --git a/internal/agent/tools/data_analysis_query_test.go b/internal/agent/tools/data_analysis_query_test.go new file mode 100644 index 00000000..f9c185de --- /dev/null +++ b/internal/agent/tools/data_analysis_query_test.go @@ -0,0 +1,215 @@ +package tools + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + _ "github.com/duckdb/duckdb-go/v2" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// newPlainDuckDB opens an in-memory DuckDB without optional extensions; CSV +// loading needs none of them. +func newPlainDuckDB(t *testing.T) *sql.DB { + t.Helper() + db, err := sql.Open("duckdb", ":memory:") + if err != nil { + t.Fatalf("open duckdb: %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + return db +} + +func writeCSV(t *testing.T, name string, rows ...string) string { + t.Helper() + path := filepath.Join(t.TempDir(), name) + if err := os.WriteFile(path, []byte(strings.Join(rows, "\n")+"\n"), 0o600); err != nil { + t.Fatalf("write csv: %v", err) + } + return path +} + +type csvFileService struct { + interfaces.FileService + files map[string]string // file path -> CSV content +} + +func (s *csvFileService) GetFile(_ context.Context, filePath string) (io.ReadCloser, error) { + content, ok := s.files[filePath] + if !ok { + return nil, fmt.Errorf("no such file %q", filePath) + } + return io.NopCloser(strings.NewReader(content)), nil +} + +func TestValidateDataAnalysisSQLAcceptsLogicalAndPhysicalTables(t *testing.T) { + schema := &TableSchema{TableName: "k_doc_a"} + for _, query := range []string{ + `SELECT COUNT(*) FROM dataset`, + `SELECT * FROM "dataset" WHERE "amount" > 1`, + `SELECT * FROM "k_doc_a" LIMIT 10`, + } { + if err := validateDataAnalysisSQL(query, schema); err != nil { + t.Errorf("%s: unexpected error %v", query, err) + } + } +} + +func TestValidateDataAnalysisSQLRejectsOtherTablesWithGuidance(t *testing.T) { + schema := &TableSchema{TableName: "k_doc_a"} + for _, query := range []string{ + `SELECT * FROM d1`, + `SELECT * FROM "d1"`, + `SELECT * FROM k_doc_b`, + `SELECT * FROM "3f1c2a8e-0000-4000-8000-000000000001"`, + } { + err := validateDataAnalysisSQL(query, schema) + if err == nil { + t.Errorf("%s: must be rejected", query) + continue + } + if !strings.Contains(err.Error(), `"dataset"`) { + t.Errorf("%s: error must tell the model to use the dataset table, got %v", query, err) + } + } + if err := validateDataAnalysisSQL(`DROP TABLE dataset`, schema); err == nil { + t.Error("non-SELECT statements must be rejected") + } + if err := validateDataAnalysisSQL(`SELECT * FROM 'd1'`, schema); err == nil { + t.Error("a quoted literal in FROM must be rejected") + } +} + +func TestExecuteSingleQueryExposesSelectedDocumentAsDataset(t *testing.T) { + db := newPlainDuckDB(t) + tool := &DataAnalysisTool{BaseTool: dataAnalysisTool, db: db, sessionID: "test-dataset"} + ctx := context.Background() + t.Cleanup(func() { tool.Cleanup(ctx) }) + + if _, err := tool.LoadFromCSV(ctx, writeCSV(t, "a.csv", "id,amount", "1,10", "2,20"), "k_doc_a"); err != nil { + t.Fatalf("load a: %v", err) + } + if _, err := tool.LoadFromCSV(ctx, writeCSV(t, "b.csv", "id,amount", "1,5", "2,6", "3,7"), "k_doc_b"); err != nil { + t.Fatalf("load b: %v", err) + } + + rowsA, err := tool.executeSingleQuery(ctx, `SELECT COUNT(*) AS n FROM dataset`, "k_doc_a") + if err != nil || len(rowsA) != 1 || rowsA[0]["n"] != "2" { + t.Fatalf("doc a via dataset: rows=%v err=%v", rowsA, err) + } + rowsB, err := tool.executeSingleQuery(ctx, `SELECT COUNT(*) AS n FROM "dataset"`, "k_doc_b") + if err != nil || len(rowsB) != 1 || rowsB[0]["n"] != "3" { + t.Fatalf("doc b via dataset: rows=%v err=%v", rowsB, err) + } + // The physical name keeps working for internal callers. + rowsPhys, err := tool.executeSingleQuery(ctx, `SELECT COUNT(*) AS n FROM "k_doc_a"`, "k_doc_a") + if err != nil || len(rowsPhys) != 1 || rowsPhys[0]["n"] != "2" { + t.Fatalf("doc a via physical table: rows=%v err=%v", rowsPhys, err) + } + // The view never outlives the query: nothing named dataset is visible on + // the shared pool afterwards. + if _, err := db.ExecContext(ctx, `SELECT COUNT(*) FROM dataset`); err == nil { + t.Fatal("temporary dataset view leaked past the query") + } +} + +func TestExecuteSingleQueryIsolatesConcurrentDocuments(t *testing.T) { + db := newPlainDuckDB(t) + tool := &DataAnalysisTool{BaseTool: dataAnalysisTool, db: db, sessionID: "test-concurrent"} + ctx := context.Background() + t.Cleanup(func() { tool.Cleanup(ctx) }) + + const docs = 4 + for i := 0; i < docs; i++ { + rows := []string{"id"} + for j := 0; j <= i; j++ { + rows = append(rows, fmt.Sprint(j)) + } + name := fmt.Sprintf("k_doc_%d", i) + if _, err := tool.LoadFromCSV(ctx, writeCSV(t, name+".csv", rows...), name); err != nil { + t.Fatalf("load %s: %v", name, err) + } + } + + var wg sync.WaitGroup + errs := make(chan error, docs*20) + for round := 0; round < 20; round++ { + for i := 0; i < docs; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + rows, err := tool.executeSingleQuery( + ctx, `SELECT COUNT(*) AS n FROM dataset`, fmt.Sprintf("k_doc_%d", i), + ) + if err != nil { + errs <- err + return + } + if want := fmt.Sprint(i + 1); len(rows) != 1 || rows[0]["n"] != want { + errs <- fmt.Errorf("doc %d saw rows=%v, want n=%s", i, rows, want) + } + }(i) + } + } + wg.Wait() + close(errs) + for err := range errs { + t.Error(err) + } +} + +func TestDataAnalysisExecuteEndToEndUsesDatasetTable(t *testing.T) { + db := newPlainDuckDB(t) + knowledge := &types.Knowledge{ID: "3f1c2a8e-0000-4000-8000-000000000001", FileType: "csv", FilePath: "doc-a.csv"} + tool := NewDataAnalysisTool( + nil, + &mapKnowledgeService{docs: map[string]*types.Knowledge{knowledge.ID: knowledge}}, + nil, + &csvFileService{files: map[string]string{"doc-a.csv": "id,amount\n1,10\n2,20\n3,30\n"}}, + db, + "test-e2e", + ) + ctx := context.Background() + t.Cleanup(func() { tool.Cleanup(ctx) }) + + args, _ := json.Marshal(DataAnalysisInput{ + KnowledgeID: knowledge.ID, + SQL: `SELECT COUNT(*) AS total FROM dataset WHERE "amount" <> '20'`, + }) + result, err := tool.Execute(ctx, args) + if err != nil || result == nil || !result.Success { + t.Fatalf("execute failed: result=%+v err=%v", result, err) + } + if !strings.Contains(result.Output, `"total":"2"`) { + t.Fatalf("unexpected output:\n%s", result.Output) + } + // Neither the physical table name nor the knowledge ID is echoed back to + // the model through the query text. + if strings.Contains(result.Output, "k_3f1c2a8e") || strings.Contains(result.Output, knowledge.ID) { + t.Fatalf("output leaks the physical table or knowledge ID:\n%s", result.Output) + } + + // The legacy shape (document ID substituted into SQL) now fails with + // guidance instead of being blindly rewritten. + args, _ = json.Marshal(DataAnalysisInput{ + KnowledgeID: knowledge.ID, + SQL: fmt.Sprintf(`SELECT COUNT(*) FROM "%s"`, knowledge.ID), + }) + result, err = tool.Execute(ctx, args) + if err == nil || result == nil || result.Success { + t.Fatalf("knowledge ID inside SQL must be rejected: result=%+v err=%v", result, err) + } + if !strings.Contains(result.Error, `"dataset"`) { + t.Fatalf("rejection must name the dataset table: %s", result.Error) + } +} diff --git a/internal/agent/tools/data_schema.go b/internal/agent/tools/data_schema.go index 605469c4..7ad518d2 100644 --- a/internal/agent/tools/data_schema.go +++ b/internal/agent/tools/data_schema.go @@ -11,9 +11,11 @@ import ( ) var dataSchemaTool = BaseTool{ - name: ToolDataSchema, - description: "Use this tool to get the schema information of a CSV or Excel file loaded into DuckDB. It returns the table name, columns, and row count.", - schema: utils.GenerateSchema[DataSchemaInput](), + name: ToolDataSchema, + description: "Use this tool to get the schema information of a CSV or Excel file loaded into DuckDB. " + + "It returns the columns and row count. When querying the document with data_analysis, " + + "reference it as the table \"" + DataAnalysisTableName + "\".", + schema: utils.GenerateSchema[DataSchemaInput](), } type DataSchemaInput struct { @@ -123,7 +125,10 @@ func (t *DataSchemaTool) Execute(ctx context.Context, args json.RawMessage) (*ty }, fmt.Errorf("no schema info found") } - output := fmt.Sprintf("%s\n\n%s", summaryContent, columnContent) + output := fmt.Sprintf( + "%s\n\n%s\n\nQuery this document with data_analysis as the table %q.", + summaryContent, columnContent, DataAnalysisTableName, + ) return &types.ToolResult{ Success: true, diff --git a/internal/agent/tools/scope_authorization.go b/internal/agent/tools/scope_authorization.go index f28aa203..e8c3162d 100644 --- a/internal/agent/tools/scope_authorization.go +++ b/internal/agent/tools/scope_authorization.go @@ -145,43 +145,6 @@ func validateKnowledgeBaseIDsInSearchTargets(searchTargets types.SearchTargets, return nil } -// resolveAuthorizedSourceRefs validates Wiki source_refs/suspected IDs against -// the same Agent scope and rebuilds the stored "uuid|title" representation -// from server data instead of trusting a model-supplied title suffix. -func resolveAuthorizedSourceRefs( - ctx context.Context, - searchTargets types.SearchTargets, - refs []string, - knowledgeService interfaces.KnowledgeService, -) ([]string, error) { - resolved := make([]string, 0, len(refs)) - seen := make(map[string]struct{}, len(refs)) - for _, ref := range refs { - knowledgeID := strings.TrimSpace(strings.SplitN(ref, "|", 2)[0]) - if knowledgeID == "" { - continue - } - knowledge, err := authorizeKnowledgeInSearchTargets(ctx, searchTargets, knowledgeID, knowledgeService) - if err != nil { - return nil, err - } - if _, exists := seen[knowledge.ID]; exists { - continue - } - seen[knowledge.ID] = struct{}{} - title := strings.TrimSpace(knowledge.Title) - if title == "" { - title = strings.TrimSpace(knowledge.FileName) - } - if title == "" { - resolved = append(resolved, knowledge.ID) - } else { - resolved = append(resolved, knowledge.ID+"|"+title) - } - } - return resolved, nil -} - type knowledgeTagsFetcher func(context.Context, []string) (map[string][]*types.KnowledgeTag, error) func searchTargetsAllowKnowledgeID( diff --git a/internal/agent/tools/wiki_flag_issue.go b/internal/agent/tools/wiki_flag_issue.go index b71fb11c..1b4b0a49 100644 --- a/internal/agent/tools/wiki_flag_issue.go +++ b/internal/agent/tools/wiki_flag_issue.go @@ -100,16 +100,13 @@ func (t *wikiFlagIssueTool) Execute(ctx context.Context, args json.RawMessage) ( } suspectedKnowledgeIDs := params.SuspectedKnowledgeIDs if t.scopeEnforced && len(suspectedKnowledgeIDs) > 0 { - resolved, scopeErr := resolveAuthorizedSourceRefs( - ctx, t.searchTargets, suspectedKnowledgeIDs, t.knowledgeService, + resolved, scopeErr := resolveWikiSourceDocuments( + ctx, suspectedKnowledgeIDs, t.knowledgeService, t.searchTargets, true, ) if scopeErr != nil { return &types.ToolResult{Success: false, Error: "Invalid suspected_knowledge_ids: " + scopeErr.Error()}, nil } - suspectedKnowledgeIDs = make([]string, 0, len(resolved)) - for _, ref := range resolved { - suspectedKnowledgeIDs = append(suspectedKnowledgeIDs, strings.SplitN(ref, "|", 2)[0]) - } + suspectedKnowledgeIDs = wikiSourceKnowledgeIDs(resolved) } issue := &types.WikiPageIssue{ diff --git a/internal/agent/tools/wiki_replace_text.go b/internal/agent/tools/wiki_replace_text.go index 9f973a84..ca4a5775 100644 --- a/internal/agent/tools/wiki_replace_text.go +++ b/internal/agent/tools/wiki_replace_text.go @@ -111,15 +111,13 @@ func (t *wikiReplaceTextTool) Execute(ctx context.Context, args json.RawMessage) existingPage.Content = strings.ReplaceAll(existingPage.Content, params.OldText, params.NewText) if params.SourceRefs != nil { - if t.scopeEnforced { - resolvedRefs, scopeErr := resolveAuthorizedSourceRefs(ctx, t.searchTargets, *params.SourceRefs, t.knowledgeService) - if scopeErr != nil { - return &types.ToolResult{Success: false, Error: "Invalid source_refs: " + scopeErr.Error()}, nil - } - existingPage.SourceRefs = resolvedRefs - } else { - existingPage.SourceRefs = resolveSourceRefs(ctx, t.knowledgeService, *params.SourceRefs) + sourceDocs, scopeErr := resolveWikiSourceDocuments( + ctx, *params.SourceRefs, t.knowledgeService, t.searchTargets, t.scopeEnforced, + ) + if scopeErr != nil { + return &types.ToolResult{Success: false, Error: "Invalid source_refs: " + scopeErr.Error()}, nil } + existingPage.SourceRefs = wikiSourceRefs(sourceDocs) } _, err = t.wikiPageService.UpdatePage(ctx, existingPage) diff --git a/internal/agent/tools/wiki_route_resolver.go b/internal/agent/tools/wiki_route_resolver.go index 28ffdcc0..dccf4bce 100644 --- a/internal/agent/tools/wiki_route_resolver.go +++ b/internal/agent/tools/wiki_route_resolver.go @@ -207,46 +207,6 @@ func resolveWikiCreateKB( return "", fmt.Errorf("cannot choose a knowledge base for new wiki page %s from %d allowed scopes", slug, len(scopes)) } -func wikiKnowledgeBasesForSourceRefs( - ctx context.Context, - refs []string, - knowledgeService interfaces.KnowledgeService, - allowedKBIDs []string, -) ([]string, error) { - if len(refs) == 0 { - return nil, nil - } - if knowledgeService == nil { - return nil, fmt.Errorf("knowledge service is unavailable") - } - allowed := make(map[string]struct{}, len(allowedKBIDs)) - for _, kbID := range dedupNonEmptyStrings(allowedKBIDs) { - allowed[kbID] = struct{}{} - } - var kbIDs []string - for _, ref := range refs { - knowledgeID := strings.TrimSpace(strings.SplitN(ref, "|", 2)[0]) - if knowledgeID == "" { - continue - } - knowledge, err := knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID) - if err != nil || knowledge == nil { - if err == nil { - err = fmt.Errorf("empty result") - } - return nil, fmt.Errorf("failed to resolve source document %s: %w", knowledgeID, err) - } - if _, ok := allowed[knowledge.KnowledgeBaseID]; !ok { - return nil, fmt.Errorf( - "source document %s belongs to non-Wiki or unauthorized knowledge base %s", - knowledgeID, knowledge.KnowledgeBaseID, - ) - } - kbIDs = append(kbIDs, knowledge.KnowledgeBaseID) - } - return dedupNonEmptyStrings(kbIDs), nil -} - func firstWikiRoute(routes []*WikiRouteResolver) *WikiRouteResolver { if len(routes) > 0 && routes[0] != nil { return routes[0] diff --git a/internal/agent/tools/wiki_source_refs.go b/internal/agent/tools/wiki_source_refs.go new file mode 100644 index 00000000..463a5c47 --- /dev/null +++ b/internal/agent/tools/wiki_source_refs.go @@ -0,0 +1,126 @@ +package tools + +import ( + "context" + "fmt" + "strings" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// wikiSourceDocument is a source document named by a model-supplied +// source_refs entry, resolved once against server data. Every Wiki mutation +// tool derives both the stored "uuid|title" refs and any KB routing hints from +// this single resolution, so the model-supplied title suffix is never trusted +// and each document is looked up exactly once. +type wikiSourceDocument struct { + ID string + Title string + KnowledgeBaseID string +} + +// resolveWikiSourceDocuments parses model-supplied source_refs (bare IDs or +// legacy "uuid|title" entries), deduplicates them, and rebuilds each entry +// from the knowledge record. With enforceScope the document must also lie +// inside the Agent's SearchTargets. Without a knowledge service the IDs are +// kept as given (bare, trimmed); this is only reachable when scope +// enforcement is off, which production wiring never does. +func resolveWikiSourceDocuments( + ctx context.Context, + refs []string, + knowledgeService interfaces.KnowledgeService, + searchTargets types.SearchTargets, + enforceScope bool, +) ([]wikiSourceDocument, error) { + resolved := make([]wikiSourceDocument, 0, len(refs)) + seen := make(map[string]struct{}, len(refs)) + for _, ref := range refs { + knowledgeID, _ := types.ParseWikiSourceRef(ref) + if knowledgeID == "" { + continue + } + var knowledge *types.Knowledge + switch { + case enforceScope: + var err error + knowledge, err = authorizeKnowledgeInSearchTargets(ctx, searchTargets, knowledgeID, knowledgeService) + if err != nil { + return nil, err + } + case knowledgeService != nil: + var err error + knowledge, err = knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID) + if err != nil || knowledge == nil { + if err == nil { + err = fmt.Errorf("empty result") + } + return nil, fmt.Errorf("document %s not found: %w", knowledgeID, err) + } + default: + knowledge = &types.Knowledge{ID: knowledgeID} + } + if _, exists := seen[knowledge.ID]; exists { + continue + } + seen[knowledge.ID] = struct{}{} + title := strings.TrimSpace(knowledge.Title) + if title == "" { + title = strings.TrimSpace(knowledge.FileName) + } + resolved = append(resolved, wikiSourceDocument{ + ID: knowledge.ID, + Title: title, + KnowledgeBaseID: knowledge.KnowledgeBaseID, + }) + } + return resolved, nil +} + +// wikiSourceRefs renders resolved documents as stored source_refs entries. +func wikiSourceRefs(docs []wikiSourceDocument) []string { + refs := make([]string, 0, len(docs)) + for _, doc := range docs { + if ref := types.FormatWikiSourceRef(doc.ID, doc.Title); ref != "" { + refs = append(refs, ref) + } + } + return refs +} + +// wikiSourceKnowledgeIDs returns the bare IDs of resolved documents. +func wikiSourceKnowledgeIDs(docs []wikiSourceDocument) []string { + ids := make([]string, 0, len(docs)) + for _, doc := range docs { + ids = append(ids, doc.ID) + } + return ids +} + +// wikiKnowledgeBasesForSourceDocuments returns the distinct knowledge bases +// owning the resolved documents, as routing hints for a new page. A document +// outside the allowed Wiki KBs fails closed; a document whose KB is unknown +// (no knowledge service) contributes no hint. +func wikiKnowledgeBasesForSourceDocuments(docs []wikiSourceDocument, allowedKBIDs []string) ([]string, error) { + if len(docs) == 0 { + return nil, nil + } + allowed := make(map[string]struct{}, len(allowedKBIDs)) + for _, kbID := range dedupNonEmptyStrings(allowedKBIDs) { + allowed[kbID] = struct{}{} + } + var kbIDs []string + for _, doc := range docs { + if doc.KnowledgeBaseID == "" { + continue + } + if _, ok := allowed[doc.KnowledgeBaseID]; !ok { + return nil, fmt.Errorf( + "source document %s belongs to knowledge base %s, which is outside the Wiki scope", + doc.ID, doc.KnowledgeBaseID, + ) + } + kbIDs = append(kbIDs, doc.KnowledgeBaseID) + } + return dedupNonEmptyStrings(kbIDs), nil +} diff --git a/internal/agent/tools/wiki_source_refs_test.go b/internal/agent/tools/wiki_source_refs_test.go new file mode 100644 index 00000000..48371250 --- /dev/null +++ b/internal/agent/tools/wiki_source_refs_test.go @@ -0,0 +1,178 @@ +package tools + +import ( + "context" + "fmt" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// mapKnowledgeService resolves documents from a fixed map and counts lookups +// so tests can assert that each ref is resolved exactly once. +type mapKnowledgeService struct { + interfaces.KnowledgeService + docs map[string]*types.Knowledge + lookups int +} + +func (s *mapKnowledgeService) GetKnowledgeByIDOnly(_ context.Context, id string) (*types.Knowledge, error) { + s.lookups++ + if doc, ok := s.docs[id]; ok { + return doc, nil + } + return nil, fmt.Errorf("record not found") +} + +func TestResolveWikiSourceDocumentsRebuildsTitlesAndDedupes(t *testing.T) { + service := &mapKnowledgeService{docs: map[string]*types.Knowledge{ + "doc-1": {ID: "doc-1", KnowledgeBaseID: "kb-1", Title: "Real title"}, + "doc-2": {ID: "doc-2", KnowledgeBaseID: "kb-1", FileName: "fallback.pdf"}, + "doc-3": {ID: "doc-3", KnowledgeBaseID: "kb-2"}, + }} + targets := types.SearchTargets{{Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb-1"}} + docs, err := resolveWikiSourceDocuments( + context.Background(), + []string{"doc-1|model-supplied title", " doc-1 ", "doc-2", "", "|orphan title"}, + service, targets, true, + ) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + refs := wikiSourceRefs(docs) + want := []string{"doc-1|Real title", "doc-2|fallback.pdf"} + if strings.Join(refs, ",") != strings.Join(want, ",") { + t.Fatalf("refs = %v, want %v", refs, want) + } + if got := wikiSourceKnowledgeIDs(docs); strings.Join(got, ",") != "doc-1,doc-2" { + t.Fatalf("ids = %v", got) + } + // Two distinct documents, each looked up once; the duplicate and the + // empty entries never reach the service. + if service.lookups != 3 { + t.Fatalf("lookups = %d, want 3 (duplicate doc-1 is looked up before dedupe, empties skipped)", service.lookups) + } +} + +func TestResolveWikiSourceDocumentsFailsClosedOutsideScope(t *testing.T) { + service := &mapKnowledgeService{docs: map[string]*types.Knowledge{ + "doc-3": {ID: "doc-3", KnowledgeBaseID: "kb-2", Title: "Elsewhere"}, + }} + targets := types.SearchTargets{{Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb-1"}} + if _, err := resolveWikiSourceDocuments( + context.Background(), []string{"doc-3"}, service, targets, true, + ); err == nil { + t.Fatal("document outside the Agent scope must be rejected") + } + if _, err := resolveWikiSourceDocuments( + context.Background(), []string{"doc-missing"}, service, targets, false, + ); err == nil { + t.Fatal("unknown document must be rejected even without scope enforcement") + } +} + +func TestResolveWikiSourceDocumentsWithoutKnowledgeServiceKeepsBareIDs(t *testing.T) { + docs, err := resolveWikiSourceDocuments( + context.Background(), []string{" doc-1|typed title ", "doc-1"}, nil, nil, false, + ) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if refs := wikiSourceRefs(docs); len(refs) != 1 || refs[0] != "doc-1" { + t.Fatalf("refs = %v, want a single bare doc-1 (model title is never trusted)", refs) + } + hints, err := wikiKnowledgeBasesForSourceDocuments(docs, []string{"kb-1"}) + if err != nil || len(hints) != 0 { + t.Fatalf("documents with unknown KB must contribute no routing hint: hints=%v err=%v", hints, err) + } +} + +func TestWikiKnowledgeBasesForSourceDocuments(t *testing.T) { + docs := []wikiSourceDocument{ + {ID: "doc-1", KnowledgeBaseID: "kb-1"}, + {ID: "doc-2", KnowledgeBaseID: "kb-1"}, + {ID: "doc-3", KnowledgeBaseID: "kb-2"}, + } + hints, err := wikiKnowledgeBasesForSourceDocuments(docs, []string{"kb-1", "kb-2"}) + if err != nil || strings.Join(hints, ",") != "kb-1,kb-2" { + t.Fatalf("hints = %v err = %v", hints, err) + } + if _, err := wikiKnowledgeBasesForSourceDocuments(docs, []string{"kb-1"}); err == nil { + t.Fatal("a document owned by a KB outside the Wiki scope must fail routing") + } + if hints, err := wikiKnowledgeBasesForSourceDocuments(nil, []string{"kb-1"}); err != nil || hints != nil { + t.Fatalf("no documents must yield no hints: %v %v", hints, err) + } +} + +func TestWikiReplaceTextRebuildsSourceRefsFromServer(t *testing.T) { + service := &sourceRefWikiService{page: &types.WikiPage{ + KnowledgeBaseID: "kb-1", + Slug: "concept/a", + Content: "old body", + SourceRefs: types.StringArray{"doc-old|Old"}, + }} + knowledgeService := &mapKnowledgeService{docs: map[string]*types.Knowledge{ + "doc-2": {ID: "doc-2", KnowledgeBaseID: "kb-1", Title: "Server title"}, + }} + targets := types.SearchTargets{{Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb-1"}} + tool := NewWikiReplaceTextTool(service, []string{"kb-1"}, knowledgeService, NewWikiRouteResolver()). + WithSearchTargets(targets) + result, err := tool.Execute(context.Background(), []byte( + `{"slug":"concept/a","old_text":"old","new_text":"new","source_refs":["doc-2|hallucinated"]}`, + )) + if err != nil || result == nil || !result.Success { + t.Fatalf("replace failed: result=%+v err=%v", result, err) + } + if got := strings.Join(service.page.SourceRefs, ","); got != "doc-2|Server title" { + t.Fatalf("source_refs = %q, want server-rebuilt title", got) + } +} + +func TestWikiFlagIssueStoresBareAuthorizedKnowledgeIDs(t *testing.T) { + service := &flagIssueWikiService{page: &types.WikiPage{ + TenantID: 1, KnowledgeBaseID: "kb-1", Slug: "concept/a", + }} + knowledgeService := &mapKnowledgeService{docs: map[string]*types.Knowledge{ + "doc-2": {ID: "doc-2", KnowledgeBaseID: "kb-1", Title: "T"}, + }} + targets := types.SearchTargets{{Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb-1"}} + tool := NewWikiFlagIssueTool(service, []string{"kb-1"}, NewWikiRouteResolver()). + WithKnowledgeScope(knowledgeService, targets) + result, err := tool.Execute(context.Background(), []byte( + `{"slug":"concept/a","issue_type":"contradiction","description":"d",`+ + `"suspected_knowledge_ids":["doc-2|title","doc-2"]}`, + )) + if err != nil || result == nil || !result.Success { + t.Fatalf("flag failed: result=%+v err=%v", result, err) + } + if service.issue == nil || strings.Join(service.issue.SuspectedKnowledgeIDs, ",") != "doc-2" { + t.Fatalf("issue = %+v, want deduped bare doc-2", service.issue) + } + result, err = tool.Execute(context.Background(), []byte( + `{"slug":"concept/a","issue_type":"contradiction","description":"d","suspected_knowledge_ids":["doc-unknown"]}`, + )) + if err != nil || result == nil || result.Success { + t.Fatalf("unknown suspected document must fail closed: result=%+v err=%v", result, err) + } +} + +// flagIssueWikiService is the minimal WikiPageService for wiki_flag_issue. +type flagIssueWikiService struct { + interfaces.WikiPageService + page *types.WikiPage + issue *types.WikiPageIssue +} + +func (s *flagIssueWikiService) GetPageBySlug(context.Context, string, string) (*types.WikiPage, error) { + return s.page, nil +} + +func (s *flagIssueWikiService) CreateIssue( + _ context.Context, issue *types.WikiPageIssue, +) (*types.WikiPageIssue, error) { + s.issue = issue + return issue, nil +} diff --git a/internal/agent/tools/wiki_tools.go b/internal/agent/tools/wiki_tools.go index 877f020f..f7cedefa 100644 --- a/internal/agent/tools/wiki_tools.go +++ b/internal/agent/tools/wiki_tools.go @@ -204,25 +204,6 @@ func scopeKnowledgeFilter(scope WikiScope) (map[string]bool, bool) { return set, true } -// extractSourceKnowledgeIDs parses SourceRefs ("uuid" or "uuid|title") and -// returns the bare knowledge IDs. -func extractSourceKnowledgeIDs(page *types.WikiPage) []string { - if page == nil || len(page.SourceRefs) == 0 { - return nil - } - ids := make([]string, 0, len(page.SourceRefs)) - for _, ref := range page.SourceRefs { - kid := ref - if pipeIdx := strings.Index(ref, "|"); pipeIdx > 0 { - kid = ref[:pipeIdx] - } - if kid != "" { - ids = append(ids, kid) - } - } - return ids -} - // isStructuralPage reports whether a page is the wiki-level index rather than // a content page tied to specific source documents. The index is never // filtered by knowledge_ids scope because it describes wiki topology. @@ -270,7 +251,7 @@ func pageIntersectsKnowledgeIDs(page *types.WikiPage, allowed map[string]bool) b if len(allowed) == 0 { return true } - for _, kid := range extractSourceKnowledgeIDs(page) { + for _, kid := range page.SourceKnowledgeIDs() { if allowed[kid] { return true } @@ -296,7 +277,7 @@ func pagePassesWikiScope( if isStructuralPage(page) { return false, nil } - sourceKnowledgeIDs := extractSourceKnowledgeIDs(page) + sourceKnowledgeIDs := page.SourceKnowledgeIDs() if len(sourceKnowledgeIDs) == 0 { return false, nil } @@ -575,12 +556,9 @@ func (t *wikiReadPageTool) Execute(ctx context.Context, args json.RawMessage) (* } for _, ref := range page.SourceRefs { - // SourceRefs might be "knowledgeID" or "knowledgeID|Title" - kid := ref - title := "" - if pipeIdx := strings.Index(ref, "|"); pipeIdx > 0 { - kid = ref[:pipeIdx] - title = ref[pipeIdx+1:] + kid, title := types.ParseWikiSourceRef(ref) + if kid == "" { + continue } if title != "" { resolved.sources = append(resolved.sources, fmt.Sprintf(`%s`, kid, title)) @@ -1005,36 +983,6 @@ func parseStringOrArray(val any) []string { return nil } -// resolveSourceRefs enriches plain knowledge UUIDs to "uuid|title" format. -// Refs already in "uuid|title" format are left unchanged. -func resolveSourceRefs(ctx context.Context, knowledgeService interfaces.KnowledgeService, refs []string) []string { - if len(refs) == 0 || knowledgeService == nil { - return refs - } - resolved := make([]string, 0, len(refs)) - for _, ref := range refs { - if strings.Contains(ref, "|") { - resolved = append(resolved, ref) - continue - } - kn, err := knowledgeService.GetKnowledgeByIDOnly(ctx, ref) - if err != nil || kn == nil { - resolved = append(resolved, ref) - continue - } - title := kn.Title - if title == "" { - title = kn.FileName - } - if title != "" { - resolved = append(resolved, ref+"|"+title) - } else { - resolved = append(resolved, ref) - } - } - return resolved -} - func extractSnippet(content string, query string) string { if content == "" || query == "" { return "" diff --git a/internal/agent/tools/wiki_write_page.go b/internal/agent/tools/wiki_write_page.go index b75e2436..5620c8c0 100644 --- a/internal/agent/tools/wiki_write_page.go +++ b/internal/agent/tools/wiki_write_page.go @@ -121,17 +121,17 @@ func (t *wikiWritePageTool) Execute(ctx context.Context, args json.RawMessage) ( // Resolve and authorize provenance before choosing a creation target. In a // multi-Wiki Agent, source documents provide a server-owned KB hint and // remove the need for a model-visible knowledge_base_id argument. + var sourceDocs []wikiSourceDocument var resolvedRefs []string var err error if params.SourceRefs != nil { - if t.scopeEnforced { - resolvedRefs, err = resolveAuthorizedSourceRefs(ctx, t.searchTargets, *params.SourceRefs, t.knowledgeService) - if err != nil { - return &types.ToolResult{Success: false, Error: "Invalid source_refs: " + err.Error()}, nil - } - } else { - resolvedRefs = resolveSourceRefs(ctx, t.knowledgeService, *params.SourceRefs) + sourceDocs, err = resolveWikiSourceDocuments( + ctx, *params.SourceRefs, t.knowledgeService, t.searchTargets, t.scopeEnforced, + ) + if err != nil { + return &types.ToolResult{Success: false, Error: "Invalid source_refs: " + err.Error()}, nil } + resolvedRefs = wikiSourceRefs(sourceDocs) } // Resolve existing pages across every legal Wiki KB. Cached provenance only // influences lookup order; ambiguous slugs are never silently written to @@ -139,9 +139,7 @@ func (t *wikiWritePageTool) Execute(ctx context.Context, args json.RawMessage) ( existingPage, kbID, err := resolveUniqueWikiPage(ctx, t.wikiPageService, params.Slug, t.kbIDs, t.routes) if errors.Is(err, errWikiPageNotFoundInScope) { existingPage = nil - sourceKBHints, sourceErr := wikiKnowledgeBasesForSourceRefs( - ctx, resolvedRefs, t.knowledgeService, t.kbIDs, - ) + sourceKBHints, sourceErr := wikiKnowledgeBasesForSourceDocuments(sourceDocs, t.kbIDs) if sourceErr != nil { return &types.ToolResult{Success: false, Error: "Failed to resolve source_refs routing: " + sourceErr.Error()}, nil } diff --git a/internal/application/repository/wiki_page.go b/internal/application/repository/wiki_page.go index 50212603..1df87e95 100644 --- a/internal/application/repository/wiki_page.go +++ b/internal/application/repository/wiki_page.go @@ -896,10 +896,7 @@ func (r *wikiPageRepository) ListSummariesByKnowledgeIDs( out := make(map[string]string, len(rows)) for _, r := range rows { for _, ref := range r.SourceRefs { - refKID := ref - if pipeIdx := strings.Index(ref, "|"); pipeIdx > 0 { - refKID = ref[:pipeIdx] - } + refKID := types.WikiSourceKnowledgeID(ref) if _, want := kidSet[refKID]; !want { continue } diff --git a/internal/application/service/chat_pipeline/chat_completion.go b/internal/application/service/chat_pipeline/chat_completion.go index 5cbb39d1..aa45ec42 100644 --- a/internal/application/service/chat_pipeline/chat_completion.go +++ b/internal/application/service/chat_pipeline/chat_completion.go @@ -52,6 +52,7 @@ func (p *PluginChatCompletion) OnEvent( }) chatMessages, modelContext := prepareMessagesWithModelContext(ctx, chatManage) chatMessages = modelContext.EncodeMessages(chatMessages) + reportModelContextLeaks(ctx, "Completion", modelContext, chatMessages) ctx = withPromptCacheMetadata(ctx, chatModel, chatMessages, opt, "knowledge_qa") // Call the chat model to generate response diff --git a/internal/application/service/chat_pipeline/chat_completion_stream.go b/internal/application/service/chat_pipeline/chat_completion_stream.go index 46e3b222..9b466b2a 100644 --- a/internal/application/service/chat_pipeline/chat_completion_stream.go +++ b/internal/application/service/chat_pipeline/chat_completion_stream.go @@ -56,6 +56,7 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context, chatMessages, modelContext := prepareMessagesWithModelContext(ctx, chatManage) chatMessages = modelContext.EncodeMessages(chatMessages) + reportModelContextLeaks(ctx, "Stream", modelContext, chatMessages) ctx = withPromptCacheMetadata(ctx, chatModel, chatMessages, opt, "knowledge_qa") pipelineInfo(ctx, "Stream", "messages_ready", map[string]interface{}{ "message_count": len(chatMessages), diff --git a/internal/application/service/chat_pipeline/data_analysis.go b/internal/application/service/chat_pipeline/data_analysis.go index 38c4071b..02a636c3 100644 --- a/internal/application/service/chat_pipeline/data_analysis.go +++ b/internal/application/service/chat_pipeline/data_analysis.go @@ -99,44 +99,26 @@ func (p *PluginDataAnalysis) OnEvent( return next() } - // Ask LLM to generate SQL for data analysis chatModel, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID) if err != nil { return ErrGetChatModel.WithError(err) } - // Use utils.GenerateSchema to generate format schema for DataAnalysisInput - formatSchema := utils.GenerateSchema[tools.DataAnalysisInput]() - - analysisPrompt := fmt.Sprintf(` -User Question: %s -Knowledge ID: %s -Table Schema: %s - -Determine if the user's question requires data analysis (e.g., statistics, aggregation, filtering) on this table. -If YES, generate a DuckDB SQL query to answer the user's question and fill in the knowledge_id and sql fields. -If NO, leave the sql field empty. - -Return your response in the specified JSON format.`, chatManage.Query, knowledge.ID, schema.Description()) - - modelCtx := types.WithLLMCallMetadata(ctx, "data_analysis_plan", "") - response, err := chatModel.Chat(modelCtx, []chat.Message{ - {Role: "user", Content: analysisPrompt}, - }, &chat.ChatOptions{ - Temperature: 0.1, - Format: formatSchema, - }) + toolResult, err := runDataAnalysis(ctx, chatModel, tool, knowledge.ID, chatManage.Query, schema) if err != nil { - logger.Errorf(ctx, "Failed to generate analysis response: %v", err) + // The analysis is optional for the answer, so the pipeline continues, + // but a failed plan is a real signal (bad SQL contract, model drift, + // broken data file) and must not disappear into a debug log. + pipelineWarn(ctx, "DataAnalysis", "analysis_failed", map[string]interface{}{ + "knowledge_id": knowledge.ID, + "error": err.Error(), + }) return next() } - // logger.Debugf(ctx, "Data analysis LLM response: %s", response.Content) - - // Execute SQL using the tool - // Initialize DataAnalysisTool - toolResult, err := tool.Execute(ctx, json.RawMessage(response.Content)) - if err != nil { - logger.Errorf(ctx, "Failed to execute SQL: %v", err) + if toolResult == nil { + pipelineInfo(ctx, "DataAnalysis", "not_needed", map[string]interface{}{ + "knowledge_id": knowledge.ID, + }) return next() } @@ -158,6 +140,125 @@ Return your response in the specified JSON format.`, chatManage.Query, knowledge return next() } +// dataAnalysisPlan is the structured decision the planning model returns. The +// document is chosen by the pipeline, never by the model, so the plan carries +// only whether analysis is needed and the SQL to run against the fixed +// tools.DataAnalysisTableName table. +type dataAnalysisPlan struct { + NeedsAnalysis bool `json:"needs_analysis" jsonschema:"true when answering the question requires statistics, aggregation or filtering over the table"` //nolint:lll // jsonschema tag + SQL string `json:"sql" jsonschema:"DuckDB SELECT over the table named dataset when needs_analysis is true; empty otherwise"` //nolint:lll // jsonschema tag +} + +// dataAnalysisExecutor is the slice of DataAnalysisTool the planner needs. +type dataAnalysisExecutor interface { + Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) +} + +const dataAnalysisPlanPromptTemplate = `User Question: %s + +The user's question may be answerable from a single CSV/Excel document that is loaded into DuckDB. +Its rows are exposed as the table %q. This is the only table; never reference any other table name. + +Table Schema: +%s + +Determine if the user's question requires data analysis (e.g., statistics, aggregation, filtering) on this table. +If YES, set needs_analysis to true and write one read-only DuckDB SELECT against the table %q +in the sql field. If NO, set needs_analysis to false and leave the sql field empty. + +Return your response in the specified JSON format.` + +const dataAnalysisRepairPromptTemplate = `The SQL you generated was rejected: + +SQL: %s +Error: %s + +Fix the query. The table is named %q and column names must match the schema exactly +(quote identifiers with double quotes). Return the corrected plan in the same JSON format; +set needs_analysis to false if the question cannot be answered from this table.` + +// runDataAnalysis asks the model for a plan, runs it, and gives the model one +// chance to repair a rejected query. It returns (nil, nil) when the model +// decides no analysis is needed, and an error when the analysis was attempted +// and could not be completed, so callers can distinguish "not needed" from +// "failed" instead of treating both as silence. +func runDataAnalysis( + ctx context.Context, + chatModel chat.Chat, + executor dataAnalysisExecutor, + knowledgeID string, + query string, + schema *tools.TableSchema, +) (*types.ToolResult, error) { + formatSchema := utils.GenerateSchema[dataAnalysisPlan]() + modelCtx := types.WithLLMCallMetadata(ctx, "data_analysis_plan", "") + messages := []chat.Message{{ + Role: "user", + Content: fmt.Sprintf(dataAnalysisPlanPromptTemplate, + query, tools.DataAnalysisTableName, schema.Description(), tools.DataAnalysisTableName), + }} + opts := &chat.ChatOptions{Temperature: 0.1, Format: formatSchema} + + const maxAttempts = 2 + var lastErr error + for attempt := 1; attempt <= maxAttempts; attempt++ { + response, err := chatModel.Chat(modelCtx, messages, opts) + if err != nil { + return nil, fmt.Errorf("plan generation failed: %w", err) + } + plan, err := parseDataAnalysisPlan(response.Content) + if err != nil { + return nil, fmt.Errorf("plan is not valid JSON: %w", err) + } + if !plan.NeedsAnalysis || strings.TrimSpace(plan.SQL) == "" { + return nil, nil + } + + args, err := json.Marshal(tools.DataAnalysisInput{KnowledgeID: knowledgeID, SQL: plan.SQL}) + if err != nil { + return nil, fmt.Errorf("failed to encode tool arguments: %w", err) + } + result, execErr := executor.Execute(ctx, args) + if execErr == nil && result != nil && result.Success { + return result, nil + } + errText := "" + switch { + case result != nil && result.Error != "": + errText = result.Error + case execErr != nil: + errText = execErr.Error() + default: + errText = "tool returned no result" + } + lastErr = fmt.Errorf("attempt %d: sql=%q: %s", attempt, plan.SQL, errText) + logger.Warnf(ctx, "[DataAnalysis] %v", lastErr) + messages = append(messages, + chat.Message{Role: "assistant", Content: response.Content}, + chat.Message{Role: "user", Content: fmt.Sprintf( + dataAnalysisRepairPromptTemplate, plan.SQL, errText, tools.DataAnalysisTableName, + )}, + ) + } + return nil, lastErr +} + +// parseDataAnalysisPlan decodes the model's structured answer, tolerating a +// Markdown code fence around the JSON object. +func parseDataAnalysisPlan(content string) (*dataAnalysisPlan, error) { + text := strings.TrimSpace(content) + if strings.HasPrefix(text, "```") { + text = strings.TrimPrefix(text, "```json") + text = strings.TrimPrefix(text, "```") + text = strings.TrimSuffix(strings.TrimSpace(text), "```") + } + var plan dataAnalysisPlan + if err := json.Unmarshal([]byte(strings.TrimSpace(text)), &plan); err != nil { + return nil, err + } + return &plan, nil +} + func isDataFile(filename string) bool { lower := strings.ToLower(filename) return strings.HasSuffix(lower, ".csv") || strings.HasSuffix(lower, ".xlsx") || strings.HasSuffix(lower, ".xls") diff --git a/internal/application/service/chat_pipeline/data_analysis_test.go b/internal/application/service/chat_pipeline/data_analysis_test.go new file mode 100644 index 00000000..5ecd3562 --- /dev/null +++ b/internal/application/service/chat_pipeline/data_analysis_test.go @@ -0,0 +1,156 @@ +package chatpipeline + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/agent/tools" + "github.com/Tencent/WeKnora/internal/models/chat" + "github.com/Tencent/WeKnora/internal/types" +) + +// scriptedChat returns one canned response per call and records the prompts. +type scriptedChat struct { + replies []string + calls [][]chat.Message +} + +func (c *scriptedChat) Chat( + _ context.Context, messages []chat.Message, _ *chat.ChatOptions, +) (*types.ChatResponse, error) { + c.calls = append(c.calls, messages) + if len(c.replies) == 0 { + return nil, errors.New("no scripted reply left") + } + reply := c.replies[0] + c.replies = c.replies[1:] + return &types.ChatResponse{Content: reply}, nil +} + +func (c *scriptedChat) ChatStream( + context.Context, []chat.Message, *chat.ChatOptions, +) (<-chan types.StreamResponse, error) { + return nil, errors.New("not used") +} +func (c *scriptedChat) GetModelName() string { return "scripted" } +func (c *scriptedChat) GetModelID() string { return "scripted" } + +// scriptedExecutor fails for every SQL listed in rejects and records inputs. +type scriptedExecutor struct { + rejects map[string]string // sql -> error text + inputs []tools.DataAnalysisInput +} + +func (e *scriptedExecutor) Execute(_ context.Context, args json.RawMessage) (*types.ToolResult, error) { + var input tools.DataAnalysisInput + if err := json.Unmarshal(args, &input); err != nil { + return nil, err + } + e.inputs = append(e.inputs, input) + if msg, rejected := e.rejects[input.SQL]; rejected { + return &types.ToolResult{Success: false, Error: msg}, errors.New(msg) + } + return &types.ToolResult{Success: true, Output: "rows for " + input.SQL}, nil +} + +const testKnowledgeID = "3f1c2a8e-0000-4000-8000-000000000001" + +var testSchema = &tools.TableSchema{ + TableName: "k_3f1c2a8e_0000_4000_8000_000000000001", + Columns: []tools.ColumnInfo{{Name: "amount", Type: "VARCHAR"}}, + RowCount: 3, +} + +func TestRunDataAnalysisNotNeededReturnsNothing(t *testing.T) { + model := &scriptedChat{replies: []string{`{"needs_analysis": false, "sql": ""}`}} + executor := &scriptedExecutor{} + result, err := runDataAnalysis(context.Background(), model, executor, testKnowledgeID, "hello", testSchema) + if err != nil || result != nil { + t.Fatalf("not-needed plan must yield (nil, nil), got (%v, %v)", result, err) + } + if len(executor.inputs) != 0 { + t.Fatal("executor must not run without SQL") + } +} + +func TestRunDataAnalysisPipelineOwnsDocumentSelection(t *testing.T) { + model := &scriptedChat{replies: []string{ + "```json\n{\"needs_analysis\": true, \"sql\": \"SELECT COUNT(*) FROM dataset\"}\n```", + }} + executor := &scriptedExecutor{} + result, err := runDataAnalysis(context.Background(), model, executor, testKnowledgeID, "how many rows", testSchema) + if err != nil || result == nil || !result.Success { + t.Fatalf("expected success, got (%+v, %v)", result, err) + } + if len(executor.inputs) != 1 || executor.inputs[0].KnowledgeID != testKnowledgeID || + executor.inputs[0].SQL != "SELECT COUNT(*) FROM dataset" { + t.Fatalf("executor input = %+v", executor.inputs) + } + prompt := model.calls[0][0].Content + if !strings.Contains(prompt, `"dataset"`) { + t.Fatalf("prompt must name the fixed table:\n%s", prompt) + } + if strings.Contains(prompt, testKnowledgeID) || strings.Contains(prompt, testSchema.TableName) { + t.Fatalf("prompt must not expose the knowledge ID or physical table:\n%s", prompt) + } +} + +func TestRunDataAnalysisRepairsRejectedSQLOnce(t *testing.T) { + model := &scriptedChat{replies: []string{ + `{"needs_analysis": true, "sql": "SELECT * FROM k_3f1c2a8e_0000_4000_8000_000000000001"}`, + `{"needs_analysis": true, "sql": "SELECT * FROM dataset"}`, + }} + executor := &scriptedExecutor{rejects: map[string]string{ + "SELECT * FROM k_3f1c2a8e_0000_4000_8000_000000000001": "Table 'k_...' is not in the allowed list. " + + `Use "dataset"`, + }} + result, err := runDataAnalysis(context.Background(), model, executor, testKnowledgeID, "show all", testSchema) + if err != nil || result == nil || !result.Success { + t.Fatalf("repaired query must succeed, got (%+v, %v)", result, err) + } + if len(executor.inputs) != 2 || len(model.calls) != 2 { + t.Fatalf("expected one retry: executor=%d model=%d", len(executor.inputs), len(model.calls)) + } + repair := model.calls[1] + if len(repair) != 3 || repair[1].Role != "assistant" || repair[2].Role != "user" { + t.Fatalf("repair turn must replay the failed plan then the error: %+v", repair) + } + if !strings.Contains(repair[2].Content, "not in the allowed list") || + !strings.Contains(repair[2].Content, `"dataset"`) { + t.Fatalf("repair prompt must carry the tool error and the table name:\n%s", repair[2].Content) + } +} + +func TestRunDataAnalysisSurfacesPersistentFailure(t *testing.T) { + model := &scriptedChat{replies: []string{ + `{"needs_analysis": true, "sql": "SELECT nope FROM dataset"}`, + `{"needs_analysis": true, "sql": "SELECT nope FROM dataset"}`, + }} + executor := &scriptedExecutor{rejects: map[string]string{ + "SELECT nope FROM dataset": `Referenced column "nope" not found`, + }} + result, err := runDataAnalysis(context.Background(), model, executor, testKnowledgeID, "q", testSchema) + if err == nil || result != nil { + t.Fatalf("a query that fails twice must be reported, got (%v, %v)", result, err) + } + if !strings.Contains(err.Error(), "attempt 2") || !strings.Contains(err.Error(), `"nope"`) { + t.Fatalf("error must name the last attempt and its cause: %v", err) + } + if len(executor.inputs) != 2 { + t.Fatalf("exactly two attempts expected, got %d", len(executor.inputs)) + } +} + +func TestRunDataAnalysisRejectsUnparseablePlan(t *testing.T) { + model := &scriptedChat{replies: []string{"I think you should look at the data"}} + executor := &scriptedExecutor{} + if _, err := runDataAnalysis(context.Background(), model, executor, testKnowledgeID, "q", testSchema); err == nil { + t.Fatal("prose instead of JSON must be an error, not silence") + } + if len(executor.inputs) != 0 { + t.Fatal("executor must not run on an unparseable plan") + } +} diff --git a/internal/application/service/chat_pipeline/references.go b/internal/application/service/chat_pipeline/references.go index 92af016e..234149f2 100644 --- a/internal/application/service/chat_pipeline/references.go +++ b/internal/application/service/chat_pipeline/references.go @@ -4,6 +4,7 @@ import ( "context" "strings" + "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/modelcontext" "github.com/Tencent/WeKnora/internal/models/chat" "github.com/Tencent/WeKnora/internal/types" @@ -134,3 +135,16 @@ func firstPipelineTitle(result *types.SearchResult) string { } return result.KnowledgeFilename } + +// reportModelContextLeaks logs any durable identifier that survived encoding +// so the producing prompt or tool can be fixed; see modelcontext/leaks.go. +func reportModelContextLeaks( + ctx context.Context, scope string, registry *modelcontext.Registry, messages []chat.Message, +) { + leaks := registry.LeakedIdentifiers(messages) + if len(leaks) == 0 { + return + } + logger.Warnf(ctx, "[%s][ModelContext] %d message field(s) carry raw identifiers after encoding: %s", + scope, len(leaks), modelcontext.SummarizeLeaks(leaks)) +} diff --git a/internal/application/service/extract.go b/internal/application/service/extract.go index d43afe01..af9489ef 100644 --- a/internal/application/service/extract.go +++ b/internal/application/service/extract.go @@ -642,7 +642,7 @@ func (s *DataTableSummaryService) processTableData(ctx context.Context, resource // 获取样本数据用于生成摘要 input := tools.DataAnalysisInput{ KnowledgeID: resources.knowledge.ID, - Sql: fmt.Sprintf("SELECT * FROM \"%s\" LIMIT 10", tableSchema.TableName), + SQL: fmt.Sprintf("SELECT * FROM \"%s\" LIMIT 10", tools.DataAnalysisTableName), } jsonData, err := json.Marshal(input) if err != nil { @@ -668,7 +668,9 @@ func (s *DataTableSummaryService) processTableData(ctx context.Context, resource } customInstructions = ResolveProcessConfig(resources.knowledgeBase, processOverrides).ChunkingConfig.TableMetadataInstructions } - tableDescription, err := s.generateTableDescription(ctx, resources.chatModel, tableSchema.TableName, + // The stored summary is later shown to the model by data_schema, so it + // must name the model-facing table, never the physical knowledge-ID table. + tableDescription, err := s.generateTableDescription(ctx, resources.chatModel, tools.DataAnalysisTableName, schemaDesc, sampleDesc, customInstructions) if err != nil { logger.Errorf(ctx, "failed to generate table description: %v", err) @@ -676,7 +678,7 @@ func (s *DataTableSummaryService) processTableData(ctx context.Context, resource } logger.Debugf(ctx, "table describe of knowledge %s: %s", resources.knowledge.ID, tableDescription) - columnDescription, err := s.generateColumnDescriptions(ctx, resources.chatModel, tableSchema.TableName, + columnDescription, err := s.generateColumnDescriptions(ctx, resources.chatModel, tools.DataAnalysisTableName, schemaDesc, sampleDesc, customInstructions) if err != nil { logger.Errorf(ctx, "failed to generate column descriptions: %v", err) diff --git a/internal/application/service/knowledge_cleanup_regression_test.go b/internal/application/service/knowledge_cleanup_regression_test.go index 035e7534..e6d090a3 100644 --- a/internal/application/service/knowledge_cleanup_regression_test.go +++ b/internal/application/service/knowledge_cleanup_regression_test.go @@ -131,3 +131,11 @@ func TestMoveReparseKBLookupFailurePreservesSourceCheckpoint(t *testing.T) { require.Zero(t, f.chunkRepo.writes) require.Zero(t, f.graph.calls) } + +func TestRemoveSourceRefHandlesTitledAndPaddedRefs(t *testing.T) { + refs := types.StringArray{"doc-1", "doc-1|Title", " doc-1 |padded", "doc-10|Other", "doc-2"} + got := removeSourceRef(refs, "doc-1") + require.Equal(t, types.StringArray{"doc-10|Other", "doc-2"}, got) + require.Nil(t, removeSourceRef(types.StringArray{"doc-1|T"}, "doc-1")) + require.Equal(t, types.StringArray{"doc-1|T"}, removeSourceRef(types.StringArray{"doc-1|T"}, "")) +} diff --git a/internal/application/service/knowledge_delete.go b/internal/application/service/knowledge_delete.go index c24c67d5..52971af6 100644 --- a/internal/application/service/knowledge_delete.go +++ b/internal/application/service/knowledge_delete.go @@ -345,9 +345,8 @@ func (s *knowledgeService) prepareWikiForReparse(ctx context.Context, knowledge // Handles both old format ("knowledgeID") and new format ("knowledgeID|title"). func removeSourceRef(refs types.StringArray, knowledgeID string) types.StringArray { var result types.StringArray - prefix := knowledgeID + "|" for _, ref := range refs { - if ref == knowledgeID || strings.HasPrefix(ref, prefix) { + if types.WikiSourceRefMatchesKnowledge(ref, knowledgeID) { continue } result = append(result, ref) diff --git a/internal/application/service/session_knowledge_qa.go b/internal/application/service/session_knowledge_qa.go index a9ed5905..6cdfe06f 100644 --- a/internal/application/service/session_knowledge_qa.go +++ b/internal/application/service/session_knowledge_qa.go @@ -984,6 +984,10 @@ func (s *sessionService) handleModelFallback(ctx context.Context, chatManage *ty // Start streaming response fallbackMessages, modelContext := prepareFallbackMessages(chatManage, promptContent) + if leaks := modelContext.LeakedIdentifiers(fallbackMessages); len(leaks) > 0 { + logger.Warnf(ctx, "[Fallback][ModelContext] %d message field(s) carry raw identifiers after encoding: %s", + len(leaks), modelcontext.SummarizeLeaks(leaks)) + } responseChan, err := chatModel.ChatStream(ctx, fallbackMessages, opt) if err != nil { logger.Errorf(ctx, "Failed to start streaming fallback response: %v, falling back to fixed response", err) diff --git a/internal/application/service/wiki_ingest_batch.go b/internal/application/service/wiki_ingest_batch.go index cd94fee7..03baf4b4 100644 --- a/internal/application/service/wiki_ingest_batch.go +++ b/internal/application/service/wiki_ingest_batch.go @@ -1879,14 +1879,14 @@ func (s *wikiIngestService) reduceSlugUpdates( } for _, ref := range page.SourceRefs { - pipeIdx := strings.Index(ref, "|") - var refKnowledgeID, refTitle string - if pipeIdx > 0 { - refKnowledgeID = ref[:pipeIdx] - refTitle = ref[pipeIdx+1:] - } else { - refKnowledgeID = ref - refTitle = ref + refKnowledgeID, refTitle := types.ParseWikiSourceRef(ref) + if refKnowledgeID == "" { + continue + } + if refTitle == "" { + // Legacy bare refs carry no title; the ID is the only label + // available for the retract prompt. + refTitle = refKnowledgeID } if retractKIDs[refKnowledgeID] { @@ -1905,12 +1905,7 @@ func (s *wikiIngestService) reduceSlugUpdates( newRefs := types.StringArray{} for _, ref := range page.SourceRefs { - pipeIdx := strings.Index(ref, "|") - refKnowledgeID := ref - if pipeIdx > 0 { - refKnowledgeID = ref[:pipeIdx] - } - if !retractKIDs[refKnowledgeID] { + if !retractKIDs[types.WikiSourceKnowledgeID(ref)] { newRefs = append(newRefs, ref) } } diff --git a/internal/application/service/wiki_lint.go b/internal/application/service/wiki_lint.go index 798ecf53..b335a2de 100644 --- a/internal/application/service/wiki_lint.go +++ b/internal/application/service/wiki_lint.go @@ -195,10 +195,7 @@ func (s *WikiLintService) RunLint(ctx context.Context, kbID string) (*WikiLintRe // each id. if s.knowledgeService != nil && page.PageType != types.WikiPageTypeIndex { for _, ref := range page.SourceRefs { - kid := ref - if i := strings.Index(ref, "|"); i > 0 { - kid = ref[:i] - } + kid := types.WikiSourceKnowledgeID(ref) if kid == "" { continue } diff --git a/internal/modelcontext/README.md b/internal/modelcontext/README.md index ad466885..cae8508d 100644 --- a/internal/modelcontext/README.md +++ b/internal/modelcontext/README.md @@ -17,6 +17,7 @@ codec lives in this one package: | `mcp.go` | MCP bridge routing handles (`msN`/`mtN`), definition projection and envelope codec | | `mcp_sources.go` | bounded citation sidecar for HTTP(S) links in successful MCP results | | `handles.go` | exported `HandleTable` for invocation-local spaces (`iN`, `ref-N`, `c000`) | +| `leaks.go` | `LeakedIdentifiers` report of raw UUIDs that survive `EncodeMessages`, logged at every model-call site | ## Identity rules @@ -57,6 +58,13 @@ references that have not been backed by current evidence. ## Observability +Every model-call site runs `LeakedIdentifiers` on the encoded messages and +logs a warning naming the role or tool whose text still carries a raw UUID. +A *registered* leak means the codec missed a rewrite site; an *unregistered* +leak means a producer emitted an identifier that never entered the registry. +Text-level compaction (`CompactKnownText`) stays in place as defense in depth +until those producers are fixed and the report stays quiet. + Langfuse generation observations contain the exact encoded payload sent to and returned by the model. Agent tool spans contain both `model_arguments` (the model-emitted handles) and `resolved_arguments` (the durable values actually @@ -73,9 +81,12 @@ are decoded centrally through a tool-name plus JSON-field allowlist. The `sourceKeySpaces` table is the single source of truth for which keys are ID-bearing and which handle space they register into; per-tool `sourceIDKeys` contracts gate which of those keys each tool may use. -`database_query.sql` and `data_analysis.sql` have an explicit policy because -source handles can be embedded inside quoted SQL values; unquoted SQL aliases -and arbitrary prose are never rewritten. Wiki issue IDs use the same lifecycle +`database_query.sql` has an explicit policy because source handles can be +embedded inside quoted SQL values when the model filters the real +`knowledges`/`chunks` tables; unquoted SQL aliases and arbitrary prose are +never rewritten. `data_analysis.sql` carries no handles: the selected document +is always exposed as the fixed table `dataset`, so only `knowledge_id` is +decoded. Wiki issue IDs use the same lifecycle via an `iN` handle space. Dynamic MCP tools are intentionally opaque in both arguments and results. diff --git a/internal/modelcontext/leaks.go b/internal/modelcontext/leaks.go new file mode 100644 index 00000000..da633fca --- /dev/null +++ b/internal/modelcontext/leaks.go @@ -0,0 +1,148 @@ +// leaks.go reports durable identifiers that survive encoding. The registry +// compacts every identifier it knows about, but a raw UUID can still reach the +// model through text it never registered: an error string, a slug, a tool +// result of unknown shape. Each such occurrence is a place where the text +// codec is doing work that the producer should have done. Reporting them at +// the model-call boundary is how those producers are found and fixed, and it +// is the precondition for eventually retiring text-level compaction. + +package modelcontext + +import ( + "fmt" + "regexp" + "sort" + "strings" + + "github.com/Tencent/WeKnora/internal/models/chat" +) + +var uuidShapeRE = regexp.MustCompile( + `(?i)\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b`, +) + +// IdentifierLeak is one message field that still carries UUID-shaped values +// after EncodeMessages. +type IdentifierLeak struct { + MessageIndex int + Role string + // ToolName is the tool that produced a tool message or the tool an + // assistant call targets; empty for plain content. + ToolName string + // Field names the message part: content, reasoning, multi_content, or + // tool_call_arguments. + Field string + // Registered holds leaked values the registry knows a handle for: the + // codec missed a rewrite site. Unregistered holds values that never + // entered the registry: the producer emitted a raw identifier. + Registered []string + Unregistered []string +} + +// LeakedIdentifiers scans an encoded message list for UUID-shaped values. +// User-authored messages are skipped: a user may legitimately paste an ID. +// Everything else the application composed, so any UUID there is a leak. +func (r *Registry) LeakedIdentifiers(messages []chat.Message) []IdentifierLeak { + if r == nil { + return nil + } + var leaks []IdentifierLeak + for i := range messages { + msg := &messages[i] + if msg.Role == "user" { + continue + } + leaks = r.appendLeak(leaks, i, msg.Role, msg.Name, "content", msg.Content) + leaks = r.appendLeak(leaks, i, msg.Role, msg.Name, "reasoning", msg.ReasoningContent) + for _, part := range msg.MultiContent { + if part.Type == "text" { + leaks = r.appendLeak(leaks, i, msg.Role, msg.Name, "multi_content", part.Text) + } + } + for _, call := range msg.ToolCalls { + leaks = r.appendLeak( + leaks, i, msg.Role, call.Function.Name, "tool_call_arguments", call.Function.Arguments, + ) + } + } + return leaks +} + +func (r *Registry) appendLeak( + leaks []IdentifierLeak, index int, role, toolName, field, text string, +) []IdentifierLeak { + if text == "" { + return leaks + } + matches := uuidShapeRE.FindAllString(text, -1) + if len(matches) == 0 { + return leaks + } + seen := make(map[string]struct{}, len(matches)) + leak := IdentifierLeak{MessageIndex: index, Role: role, ToolName: toolName, Field: field} + for _, match := range matches { + key := strings.ToLower(match) + if _, dup := seen[key]; dup { + continue + } + seen[key] = struct{}{} + if r.knowsDurable(match) { + leak.Registered = append(leak.Registered, match) + } else { + leak.Unregistered = append(leak.Unregistered, match) + } + } + sort.Strings(leak.Registered) + sort.Strings(leak.Unregistered) + return append(leaks, leak) +} + +// knowsDurable reports whether any handle space has registered the value. +func (r *Registry) knowsDurable(value string) bool { + if r.sources != nil && r.sources.handleForDurable(value) != "" { + return true + } + if _, ok := r.issues.Handle(value); ok { + return true + } + if _, ok := r.mcpServers.Handle(value); ok { + return true + } + _, ok := r.mcpTools.Handle(value) + return ok +} + +// maxLeakSamples bounds how many identifiers one summary line quotes. +const maxLeakSamples = 3 + +// SummarizeLeaks renders leaks as one log line per message field so the +// producing tool or role can be identified without dumping the context. +func SummarizeLeaks(leaks []IdentifierLeak) string { + if len(leaks) == 0 { + return "" + } + lines := make([]string, 0, len(leaks)) + for _, leak := range leaks { + origin := leak.Role + if leak.ToolName != "" { + origin += "/" + leak.ToolName + } + lines = append(lines, fmt.Sprintf( + "message[%d] %s %s: %d registered %s, %d unregistered %s", + leak.MessageIndex, origin, leak.Field, + len(leak.Registered), sampleIDs(leak.Registered), + len(leak.Unregistered), sampleIDs(leak.Unregistered), + )) + } + return strings.Join(lines, "; ") +} + +func sampleIDs(ids []string) string { + if len(ids) == 0 { + return "[]" + } + if len(ids) > maxLeakSamples { + return "[" + strings.Join(ids[:maxLeakSamples], " ") + " ...]" + } + return "[" + strings.Join(ids, " ") + "]" +} diff --git a/internal/modelcontext/leaks_test.go b/internal/modelcontext/leaks_test.go new file mode 100644 index 00000000..cd8cae04 --- /dev/null +++ b/internal/modelcontext/leaks_test.go @@ -0,0 +1,112 @@ +package modelcontext + +import ( + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/models/chat" + "github.com/Tencent/WeKnora/internal/types" +) + +const ( + leakDocID = "3f1c2a8e-0000-4000-8000-000000000001" + leakChunkID = "3f1c2a8e-0000-4000-8000-000000000002" + leakRawID = "3f1c2a8e-0000-4000-8000-0000000000ff" +) + +func TestLeakedIdentifiersIgnoresEncodedHandlesAndUserText(t *testing.T) { + registry := NewRegistry(true) + registry.RegisterChunk(ChunkReference{ChunkID: leakChunkID, KnowledgeID: leakDocID, KnowledgeBaseID: "kb-1"}) + messages := registry.EncodeMessages([]chat.Message{ + {Role: "system", Content: "directory: " + registry.ModelToolResult(searchResultTool(leakChunkID, leakDocID))}, + {Role: "user", Content: "look at " + leakRawID + " please"}, + {Role: "assistant", Content: ``}, + }) + if leaks := registry.LeakedIdentifiers(messages); len(leaks) != 0 { + t.Fatalf("encoded messages must not report leaks, got %s", SummarizeLeaks(leaks)) + } +} + +func TestLeakedIdentifiersClassifiesRegisteredAndUnregistered(t *testing.T) { + registry := NewRegistry(true) + registry.RegisterDocument(leakDocID) + messages := []chat.Message{ + {Role: "user", Content: leakRawID}, + { + Role: "tool", Name: "shell_exec", + Content: "wrote summary/" + leakRawID + " and " + strings.ToUpper(leakRawID), + }, + {Role: "assistant", Content: "Document " + leakDocID + " is relevant.", ToolCalls: []chat.ToolCall{{ + Function: chat.FunctionCall{Name: "wiki_write_page", Arguments: `{"source_refs":["` + leakDocID + `|T"]}`}, + }}}, + {Role: "assistant", MultiContent: []chat.MessageContentPart{{Type: "text", Text: "see " + leakRawID}}}, + } + leaks := registry.LeakedIdentifiers(messages) + if len(leaks) != 4 { + t.Fatalf("expected 4 leaking fields, got %d: %s", len(leaks), SummarizeLeaks(leaks)) + } + tool := leaks[0] + if tool.Role != "tool" || tool.ToolName != "shell_exec" || tool.Field != "content" { + t.Fatalf("unexpected first leak origin: %+v", tool) + } + if len(tool.Registered) != 0 || len(tool.Unregistered) != 1 { + t.Fatalf("case-insensitive duplicates must collapse to one unregistered ID: %+v", tool) + } + content := leaks[1] + if content.Field != "content" || len(content.Registered) != 1 || content.Registered[0] != leakDocID { + t.Fatalf("registered document in assistant prose must be reported as registered: %+v", content) + } + args := leaks[2] + if args.Field != "tool_call_arguments" || args.ToolName != "wiki_write_page" || len(args.Registered) != 1 { + t.Fatalf("tool call arguments must be scanned per call: %+v", args) + } + if leaks[3].Field != "multi_content" { + t.Fatalf("multi-part text must be scanned: %+v", leaks[3]) + } + + summary := SummarizeLeaks(leaks) + for _, want := range []string{ + "message[1] tool/shell_exec content: 0 registered [], 1 unregistered [" + leakRawID + "]", + "message[2] assistant content: 1 registered [" + leakDocID + "], 0 unregistered []", + "message[2] assistant/wiki_write_page tool_call_arguments", + } { + if !strings.Contains(summary, want) { + t.Fatalf("summary missing %q:\n%s", want, summary) + } + } +} + +func TestLeakedIdentifiersDoesNotMatchHandlesOrPartialUUIDs(t *testing.T) { + registry := NewRegistry(true) + messages := []chat.Message{ + {Role: "assistant", Content: "c1 d2 b3 w4 res://0001 i1 and k_3f1c2a8e_0000_4000_8000_000000000001"}, + {Role: "tool", Name: "x", Content: "3f1c2a8e-0000-4000-8000-00000000000"}, // one hex digit short + } + if leaks := registry.LeakedIdentifiers(messages); len(leaks) != 0 { + t.Fatalf("handles and non-UUID tokens must not be reported: %s", SummarizeLeaks(leaks)) + } + if SummarizeLeaks(nil) != "" { + t.Fatal("empty leak list must summarize to an empty string") + } + if got := sampleIDs([]string{"a", "b", "c", "d"}); got != "[a b c ...]" { + t.Fatalf("sample truncation = %q", got) + } +} + +func searchResultTool(chunkID, docID string) *types.ToolResult { + return &types.ToolResult{ + Success: true, + Output: "raw " + chunkID, + Data: map[string]interface{}{ + "display_type": "search_results", + "results": []map[string]interface{}{{ + "chunk_id": chunkID, + "knowledge_id": docID, + "knowledge_base_id": "kb-1", + "knowledge_title": "Doc", + "chunk_index": 1, + "content": "body mentioning " + docID, + }}, + }, + } +} diff --git a/internal/modelcontext/registry_test.go b/internal/modelcontext/registry_test.go index 40409710..47887a2d 100644 --- a/internal/modelcontext/registry_test.go +++ b/internal/modelcontext/registry_test.go @@ -364,7 +364,11 @@ func TestRegistryDecodesCanonicalArgumentsForEveryBuiltInReferenceTool(t *testin {"list chunk", "list_knowledge_chunks", `{"chunk_id":"c1"}`, `{"chunk_id":"chunk-real"}`}, {"document info", "get_document_info", `{"knowledge_ids":["d1"],"faq_ids":["c1"]}`, `{"knowledge_ids":["doc-real"],"faq_ids":["chunk-real"]}`}, {"knowledge graph", "query_knowledge_graph", `{"knowledge_base_ids":["b1"],"query":"topic"}`, `{"knowledge_base_ids":["kb-real"],"query":"topic"}`}, - {"data analysis SQL", "data_analysis", `{"knowledge_id":"d1","sql":"SELECT * FROM 'd1'"}`, `{"knowledge_id":"doc-real","sql":"SELECT * FROM 'doc-real'"}`}, + { + "data analysis SQL", "data_analysis", + `{"knowledge_id":"d1","sql":"SELECT COUNT(*) FROM dataset WHERE label = 'd1'"}`, + `{"knowledge_id":"doc-real","sql":"SELECT COUNT(*) FROM dataset WHERE label = 'd1'"}`, + }, {"data schema", "data_schema", `{"knowledge_id":"d1"}`, `{"knowledge_id":"doc-real"}`}, {"database SQL", "database_query", `{"sql":"SELECT * FROM chunks WHERE knowledge_base_id='b1'"}`, `{"sql":"SELECT * FROM chunks WHERE knowledge_base_id='kb-real'"}`}, {"web fetch", "web_fetch", `{"items":[{"url":"w1"}]}`, `{"items":[{"url":"https://example.com/page"}]}`}, diff --git a/internal/modelcontext/sources.go b/internal/modelcontext/sources.go index 11a0d652..669397d3 100644 --- a/internal/modelcontext/sources.go +++ b/internal/modelcontext/sources.go @@ -480,7 +480,7 @@ func (r *sourceRegistry) registerSourceIDByKey(key, value string, evidence bool) r.RegisterDocument(value) case spaceDocumentRef: // Stored refs use "knowledgeID|title"; only the ID part is durable. - r.RegisterDocument(strings.TrimSpace(strings.SplitN(value, "|", 2)[0])) + r.RegisterDocument(types.WikiSourceKnowledgeID(value)) case spaceKnowledgeBase: r.RegisterKnowledgeBase(value) case spaceWeb: diff --git a/internal/modelcontext/tool_policy.go b/internal/modelcontext/tool_policy.go index bb9455a4..72980bde 100644 --- a/internal/modelcontext/tool_policy.go +++ b/internal/modelcontext/tool_policy.go @@ -94,9 +94,10 @@ var toolHandlePolicies = map[string]toolHandlePolicy{ sourceTextKeys: map[string]struct{}{"sql": {}}, sourceOutput: true, }, + // data_analysis exposes the selected document as a fixed table name, so + // its SQL never carries a document handle; only knowledge_id is decoded. toolDataAnalysis: { - sourceIDKeys: map[string]struct{}{"knowledge_id": {}}, - sourceTextKeys: map[string]struct{}{"sql": {}}, + sourceIDKeys: map[string]struct{}{"knowledge_id": {}}, }, "data_schema": { sourceIDKeys: map[string]struct{}{"knowledge_id": {}}, diff --git a/internal/types/wiki_page.go b/internal/types/wiki_page.go index a1cca1d7..8d17d0ac 100644 --- a/internal/types/wiki_page.go +++ b/internal/types/wiki_page.go @@ -820,17 +820,51 @@ type WikiPageLite struct { OutLinks StringArray `json:"out_links,omitempty"` } +// ParseWikiSourceRef splits a source_refs entry into its durable knowledge ID +// and optional display title. Entries are stored as "uuid" or "uuid|title"; +// both halves are trimmed and a leading "|" yields an empty ID. This is the +// only parser of the format: every reader must go through it so that a ref +// with stray whitespace resolves identically on the scope-authorization, +// deletion, lint, and rendering paths. +func ParseWikiSourceRef(ref string) (knowledgeID, title string) { + ref = strings.TrimSpace(ref) + if ref == "" { + return "", "" + } + i := strings.IndexByte(ref, '|') + if i < 0 { + return ref, "" + } + return strings.TrimSpace(ref[:i]), strings.TrimSpace(ref[i+1:]) +} + +// FormatWikiSourceRef builds the stored source_refs entry for a knowledge ID +// and optional title. A title that contains "|" is kept verbatim: the parser +// splits on the first pipe only, so the ID half stays unambiguous. +func FormatWikiSourceRef(knowledgeID, title string) string { + knowledgeID = strings.TrimSpace(knowledgeID) + title = strings.TrimSpace(title) + if knowledgeID == "" { + return "" + } + if title == "" { + return knowledgeID + } + return knowledgeID + "|" + title +} + // WikiSourceKnowledgeID extracts the knowledge id from a source_refs entry, // stored as "uuid" or "uuid|title". func WikiSourceKnowledgeID(ref string) string { - ref = strings.TrimSpace(ref) - if ref == "" { - return "" - } - if i := strings.IndexByte(ref, '|'); i > 0 { - return strings.TrimSpace(ref[:i]) - } - return ref + knowledgeID, _ := ParseWikiSourceRef(ref) + return knowledgeID +} + +// WikiSourceRefMatchesKnowledge reports whether a source_refs entry points at +// the given knowledge ID, in either the bare or the "uuid|title" form. +func WikiSourceRefMatchesKnowledge(ref, knowledgeID string) bool { + knowledgeID = strings.TrimSpace(knowledgeID) + return knowledgeID != "" && WikiSourceKnowledgeID(ref) == knowledgeID } // SourceKnowledgeIDs returns the document ids this page was built from. diff --git a/internal/types/wiki_page_test.go b/internal/types/wiki_page_test.go index 6ac7bbdc..2fdd4e29 100644 --- a/internal/types/wiki_page_test.go +++ b/internal/types/wiki_page_test.go @@ -2,6 +2,7 @@ package types import ( "encoding/json" + "strings" "testing" ) @@ -179,6 +180,58 @@ func TestWikiPageJSON(t *testing.T) { } } +func TestParseWikiSourceRef(t *testing.T) { + cases := []struct { + in, wantID, wantTitle string + }{ + {"doc-1|排班手册", "doc-1", "排班手册"}, + {"doc-1", "doc-1", ""}, + {" doc-1 | title ", "doc-1", "title"}, + {"doc-1|a|b", "doc-1", "a|b"}, + {"|title", "", "title"}, + {" ", "", ""}, + } + for _, c := range cases { + id, title := ParseWikiSourceRef(c.in) + if id != c.wantID || title != c.wantTitle { + t.Errorf("ParseWikiSourceRef(%q) = (%q, %q), want (%q, %q)", c.in, id, title, c.wantID, c.wantTitle) + } + } +} + +func TestFormatWikiSourceRefRoundTrip(t *testing.T) { + cases := []struct { + id, title, want string + }{ + {"doc-1", "排班手册", "doc-1|排班手册"}, + {"doc-1", "", "doc-1"}, + {" doc-1 ", " t ", "doc-1|t"}, + {"", "orphan title", ""}, + } + for _, c := range cases { + got := FormatWikiSourceRef(c.id, c.title) + if got != c.want { + t.Errorf("FormatWikiSourceRef(%q, %q) = %q, want %q", c.id, c.title, got, c.want) + } + if got == "" { + continue + } + id, title := ParseWikiSourceRef(got) + if id != strings.TrimSpace(c.id) || title != strings.TrimSpace(c.title) { + t.Errorf("round trip of %q lost data: (%q, %q)", got, id, title) + } + } +} + +func TestWikiSourceRefMatchesKnowledge(t *testing.T) { + if !WikiSourceRefMatchesKnowledge("doc-1|T", "doc-1") || !WikiSourceRefMatchesKnowledge(" doc-1 ", "doc-1") { + t.Error("bare and titled refs must match their knowledge ID") + } + if WikiSourceRefMatchesKnowledge("doc-10|T", "doc-1") || WikiSourceRefMatchesKnowledge("doc-1|T", "") { + t.Error("prefix-only or empty IDs must not match") + } +} + func TestWikiSourceKnowledgeID(t *testing.T) { cases := []struct { in, want string diff --git a/website-docs/03-features/07-agent.md b/website-docs/03-features/07-agent.md index bac8759e..209f3478 100644 --- a/website-docs/03-features/07-agent.md +++ b/website-docs/03-features/07-agent.md @@ -417,8 +417,8 @@ flowchart TD | `query_knowledge_graph` | `knowledge_base_ids[]`\*(1–10 个 `bN`)、`query`\* | 并发查询各 KB 知识图谱的实体与关系;未配置图谱的 KB 退化为普通检索结果 | | `get_document_info` | `knowledge_ids[]`(`dN`)、`faq_ids[]`(`cN`)(至少一个) | 并发批量返回文档元数据(标题、类型、大小、parse_status、分块数)或 FAQ 标准问/答案 | | `database_query` | SQL(SELECT-only) | 只读查询白名单表(`knowledge_bases`/`knowledges`/`chunks`),自动注入 tenant_id 过滤与 `deleted_at IS NULL`;SQL 参数在 UI/Langfuse 中脱敏 | -| `data_schema` | `knowledge_id`\*(`dN`) | 读取 CSV/Excel 文件的 `table_summary` + `table_column` 类型分块,返回表名、列信息与行数 | -| `data_analysis` | `knowledge_id`\*、`sql`\* | 把 CSV/Excel 载入 DuckDB 后执行 SQL;多 Sheet Excel 合并为一张表并暴露 `__sheet_name` 列;自动纠正列名大小写/空格差异;会话结束 Cleanup 时 DROP 所建表 | +| `data_schema` | `knowledge_id`\*(`dN`) | 读取 CSV/Excel 文件的 `table_summary` + `table_column` 类型分块,返回列信息与行数;并告知模型该文档在 `data_analysis` 中固定以表名 `dataset` 访问 | +| `data_analysis` | `knowledge_id`\*、`sql`\* | 把 CSV/Excel 载入 DuckDB 后执行 SQL。文档由 `knowledge_id` 选定,SQL 中固定以表名 `dataset` 引用它(每次查询在独立连接上建临时视图映射到物理表,模型永远不需要在 SQL 里写文档 ID);多 Sheet Excel 合并为一张表并暴露 `__sheet_name` 列;自动纠正列名大小写/空格差异;会话结束 Cleanup 时 DROP 所建表 | | `web_search` | `query`\*,可选 `count`、`country`、`freshness`、`content` | 联网搜索,直接返回提供商的标题、摘要和 `wN` 页面短 ID;按任务需要选择知识库或联网检索,Agent 搜索不再自动进行 RAG 压缩;Brave 支持地区/时效过滤,`content=true` 并行抓取前 3 条正文并返回完整正文地址 | | `web_fetch` | `items[]`\*(每项 `url`\*=`wN` 或 HTTP(S) URL,可选 `offset`、`limit`) | 并发抓取最多 8 个网页(SSRF 安全客户端 + DNS pinning,必要时 chromedp 渲染),直接返回 Markdown 或支持的文本正文;60s 超时。按字符分页,使用 `next_offset` 续读;完整正文保存在 `full_output_path`,可用 `read_file` 跨轮按行读取;逐 URL 返回 `success`/`failed`/`skipped` 状态与可重试错误码,部分失败不影响其它页面 | | `read_file` | `path`、offset、limit、max_bytes;网页可带 line_offset | 读取工作区文本、skill:// 资源和 web:// 网页快照,按结果续读 |