WeKnora/internal/agent/tools/read_document_test.go

602 lines
22 KiB
Go
Raw Normal View History

refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
package tools
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
func TestReadDocumentCitationIdentitySurvivesClientAndHistoryCompaction(t *testing.T) {
knowledge := &types.Knowledge{
ID: "doc-1", KnowledgeBaseID: "kb-1", Title: "Proposal.pptx", FileName: "Proposal.pptx",
}
rows := []readChunkRow{
{chunk: &types.Chunk{ID: "chunk-1", Content: "First body"}},
{chunk: &types.Chunk{
ID: "chunk-2", Content: "Cited body",
SourceLocators: types.SourceLocators{{Type: types.SourceLocatorSlide, Slide: 8}},
}},
}
data := (&ReadDocumentTool{}).buildData(knowledge, 2, rows)
result := &types.ToolResult{Success: true, Data: data, Output: "full model-only output"}
steps := []types.AgentStep{{ToolCalls: []types.ToolCall{{Name: ToolReadDocument, Result: result}}}}
stored := SanitizeAgentStepsForStorage(steps)[0].ToolCalls[0].Result
for name, compact := range map[string]map[string]interface{}{
"live": SanitizeToolResultForClient(ToolReadDocument, result),
"history": stored.Data,
} {
t.Run(name, func(t *testing.T) {
if compact["knowledge_id"] != "doc-1" || compact["knowledge_base_id"] != "kb-1" ||
compact["source_chunk_id"] != "chunk-2" {
t.Fatalf("lost citation provenance: %#v", compact)
}
if !reflect.DeepEqual(compact["chunk_ids"], []string{"chunk-1", "chunk-2"}) {
t.Fatalf("lost cited chunk IDs: %#v", compact["chunk_ids"])
}
if _, exists := compact["chunks"]; exists {
t.Fatal("chunk bodies should still be omitted")
}
})
}
if len(data["chunks"].([]map[string]interface{})) != 2 || result.Output != "full model-only output" {
t.Fatal("compaction must not mutate the full model result")
}
}
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
// ---- fakes -----------------------------------------------------------------
type readDocKnowledgeService struct {
interfaces.KnowledgeService
docs map[string]*types.Knowledge
pages map[string]*types.PageResult // keyed by kb id
tags map[string][]*types.KnowledgeTag
listFilters []types.KnowledgeListFilter
}
func (f *readDocKnowledgeService) GetKnowledgeBatch(
_ context.Context, _ uint64, ids []string,
) ([]*types.Knowledge, error) {
out := make([]*types.Knowledge, 0, len(ids))
for _, id := range ids {
if k, ok := f.docs[id]; ok {
out = append(out, k)
}
}
return out, nil
}
func (f *readDocKnowledgeService) GetKnowledgeByIDOnly(_ context.Context, id string) (*types.Knowledge, error) {
if k, ok := f.docs[id]; ok {
return k, nil
}
return nil, errors.New("record not found")
}
func (f *readDocKnowledgeService) GetKnowledgeTags(
_ context.Context, ids []string,
) (map[string][]*types.KnowledgeTag, error) {
out := make(map[string][]*types.KnowledgeTag, len(ids))
for _, id := range ids {
if tags, ok := f.tags[id]; ok {
out[id] = tags
}
}
return out, nil
}
func (f *readDocKnowledgeService) ListPagedKnowledgeByKnowledgeBaseID(
_ context.Context, kbID string, page *types.Pagination, filter types.KnowledgeListFilter,
) (*types.PageResult, error) {
f.listFilters = append(f.listFilters, filter)
result, ok := f.pages[kbID]
if !ok {
return &types.PageResult{Page: page.Page, PageSize: page.PageSize, Data: []*types.Knowledge{}}, nil
}
rows, _ := result.Data.([]*types.Knowledge)
if len(filter.TagIDs) > 0 {
wanted := make(map[string]bool, len(filter.TagIDs))
for _, id := range filter.TagIDs {
wanted[id] = true
}
tagged := make([]*types.Knowledge, 0, len(rows))
for _, k := range rows {
for _, tag := range f.tags[k.ID] {
if wanted[tag.ID] {
tagged = append(tagged, k)
break
}
}
}
rows = tagged
}
if filter.Keyword != "" {
filtered := make([]*types.Knowledge, 0, len(rows))
for _, k := range rows {
if strings.Contains(strings.ToLower(k.Title), strings.ToLower(filter.Keyword)) {
filtered = append(filtered, k)
}
}
rows = filtered
}
total := int64(len(rows))
start := (page.Page - 1) * page.PageSize
if start > len(rows) {
start = len(rows)
}
end := start + page.PageSize
if end > len(rows) {
end = len(rows)
}
return &types.PageResult{Total: total, Page: page.Page, PageSize: page.PageSize, Data: rows[start:end]}, nil
}
type readDocChunkRepo struct {
interfaces.ChunkRepository
ordered []*types.Chunk // document order
listErr error
requests []types.Pagination
}
func (r *readDocChunkRepo) ListPagedChunksByKnowledgeID(
_ context.Context, _ uint64, _ string, page *types.Pagination, _ []types.ChunkType,
_ []string, _ string, _ string, _ string, _ string, _ *bool,
) ([]*types.Chunk, int64, error) {
if r.listErr != nil {
return nil, 0, r.listErr
}
r.requests = append(r.requests, *page)
start := (page.Page - 1) * page.PageSize
end := start + page.PageSize
total := int64(len(r.ordered))
if start >= len(r.ordered) {
return nil, total, nil
}
if end > len(r.ordered) {
end = len(r.ordered)
}
out := make([]*types.Chunk, end-start)
copy(out, r.ordered[start:end])
return out, total, nil
}
func (r *readDocChunkRepo) ListChunksByParentIDs(context.Context, uint64, []string) ([]*types.Chunk, error) {
return nil, nil
}
func (r *readDocChunkRepo) ListChunkNeighbors(
_ context.Context, _ uint64, _ string, chunkIndex, before, after int, _ []types.ChunkType,
) ([]*types.Chunk, error) {
var preceding, following []*types.Chunk
for _, c := range r.ordered {
switch {
case c.ChunkIndex < chunkIndex:
preceding = append(preceding, c)
case c.ChunkIndex > chunkIndex && len(following) < after:
following = append(following, c)
}
}
if len(preceding) > before {
preceding = preceding[len(preceding)-before:]
}
return append(preceding, following...), nil
}
type readDocChunkService struct {
interfaces.ChunkService
repo *readDocChunkRepo
}
func (s *readDocChunkService) GetChunkByIDOnly(_ context.Context, id string) (*types.Chunk, error) {
for _, c := range s.repo.ordered {
if c.ID == id {
return c, nil
}
}
return nil, errors.New("chunk not found")
}
func (s *readDocChunkService) GetRepository() interfaces.ChunkRepository { return s.repo }
func testDocumentChunks(knowledgeID string, n int) []*types.Chunk {
chunks := make([]*types.Chunk, 0, n)
for i := 0; i < n; i++ {
chunks = append(chunks, &types.Chunk{
ID: fmt.Sprintf("chunk-%d", i), TenantID: 7, KnowledgeID: knowledgeID, KnowledgeBaseID: "kb-1",
ChunkIndex: i, ChunkType: types.ChunkTypeText, IsEnabled: true,
Content: fmt.Sprintf("Section %d body. %s", i, engineSentence(i == 4 || i == 9)),
})
}
return chunks
}
func engineSentence(present bool) string {
if present {
return "The psionic engine is here."
}
return ""
}
func newReadDocumentFixture(chunkCount int) (*ReadDocumentTool, *readDocChunkRepo) {
doc := &types.Knowledge{
ID: "doc-1", TenantID: 7, KnowledgeBaseID: "kb-1", Title: "Engine Manual", Type: "file",
FileName: "manual.pdf", FileType: "pdf", FileSize: 2048, ParseStatus: "completed",
Description: "How the engine works",
}
repo := &readDocChunkRepo{ordered: testDocumentChunks(doc.ID, chunkCount)}
tool := NewReadDocumentTool(
&readDocKnowledgeService{docs: map[string]*types.Knowledge{doc.ID: doc}},
&readDocChunkService{repo: repo},
types.SearchTargets{{Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb-1", TenantID: 7}},
)
return tool, repo
}
func chunkIDsFromData(t *testing.T, data map[string]interface{}) []string {
t.Helper()
rows, ok := data["chunks"].([]map[string]interface{})
if !ok {
t.Fatalf("chunks payload = %#v", data["chunks"])
}
ids := make([]string, 0, len(rows))
for _, r := range rows {
ids = append(ids, fmt.Sprint(r["chunk_id"]))
}
return ids
}
// ---- tests -----------------------------------------------------------------
func TestReadDocumentRequiresID(t *testing.T) {
tool, _ := newReadDocumentFixture(3)
res, err := tool.Execute(context.Background(), json.RawMessage(`{}`))
if err == nil || res.Success || !strings.Contains(res.Error, "id is required") {
t.Fatalf("res=%+v err=%v", res, err)
}
}
func TestReadDocumentPagesFromExactOffset(t *testing.T) {
tool, repo := newReadDocumentFixture(12)
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-1","offset":5,"limit":4}`))
if err != nil || !res.Success {
t.Fatalf("res=%+v err=%v", res, err)
}
if got := chunkIDsFromData(t, res.Data); strings.Join(got, ",") != "chunk-5,chunk-6,chunk-7,chunk-8" {
t.Fatalf("window = %v", got)
}
if res.Data["next_offset"] != 9 || res.Data["total_chunks"] != int64(12) || res.Data["fetched_chunks"] != 4 {
t.Fatalf("pagination data = %+v", res.Data)
}
if len(repo.requests) != 2 {
t.Fatalf("an unaligned window needs exactly two page fetches, got %v", repo.requests)
}
info, _ := res.Data["document"].(map[string]interface{})
if info["title"] != "Engine Manual" || info["file_type"] != "pdf" || info["chunk_count"] != int64(12) {
t.Fatalf("document header = %+v", info)
}
if !strings.Contains(res.Output, `title="Engine Manual"`) ||
!strings.Contains(res.Output, "<description>How the engine works</description>") {
t.Fatalf("output header missing: %s", res.Output)
}
}
func TestReadDocumentUnalignedWindowReachesDocumentEnd(t *testing.T) {
tool, repo := newReadDocumentFixture(9)
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-1","offset":6,"limit":4}`))
if err != nil || !res.Success {
t.Fatalf("res=%+v err=%v", res, err)
}
if got := chunkIDsFromData(t, res.Data); strings.Join(got, ",") != "chunk-6,chunk-7,chunk-8" {
t.Fatalf("window past the document end = %v, want every remaining chunk", got)
}
if _, ok := res.Data["next_offset"]; ok {
t.Fatalf("nothing remains after chunk-8: %+v", res.Data)
}
if len(repo.requests) != 2 {
t.Fatalf("expected the second page to be fetched, requests=%v", repo.requests)
}
}
func TestReadDocumentChunkContextNearDocumentEnd(t *testing.T) {
tool, _ := newReadDocumentFixture(9)
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"chunk-7","context":2}`))
if err != nil || !res.Success {
t.Fatalf("res=%+v err=%v", res, err)
}
if got := chunkIDsFromData(t, res.Data); strings.Join(got, ",") != "chunk-5,chunk-6,chunk-7,chunk-8" {
t.Fatalf("context near the end = %v", got)
}
if res.Data["total_chunks"] != int64(9) {
t.Fatalf("total = %+v", res.Data)
}
}
// Parent, summary and image chunks share the chunk_index sequence but are not
// readable text, so readable chunks have gaps in their indexes. Neighbours
// must follow the index order, not list positions derived from it.
func TestReadDocumentChunkContextFollowsIndexesAcrossGaps(t *testing.T) {
tool, repo := newReadDocumentFixture(6)
for i, c := range repo.ordered {
c.ChunkIndex = i * 3 // 0, 3, 6, 9, 12, 15
}
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"chunk-3","context":1}`))
if err != nil || !res.Success {
t.Fatalf("res=%+v err=%v", res, err)
}
if got := chunkIDsFromData(t, res.Data); strings.Join(got, ",") != "chunk-2,chunk-3,chunk-4" {
t.Fatalf("neighbours across index gaps = %v", got)
}
rows := res.Data["chunks"].([]map[string]interface{})
if rows[0]["role"] != "context_before" || rows[1]["role"] != "focus" || rows[2]["role"] != "context_after" {
t.Fatalf("roles = %v %v %v", rows[0]["role"], rows[1]["role"], rows[2]["role"])
}
}
func TestReadDocumentQueryWithChunkHandleSearchesOwningDocument(t *testing.T) {
tool, _ := newReadDocumentFixture(12)
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"chunk-1","query":"psionic"}`))
if err != nil || !res.Success {
t.Fatalf("res=%+v err=%v", res, err)
}
if res.Data["match_count"] != 2 || res.Data["query"] != "psionic" {
t.Fatalf("query must run against the owning document, data=%+v", res.Data)
}
}
func TestReadDocumentQueryStopsAtOutputBudget(t *testing.T) {
tool, repo := newReadDocumentFixture(12)
for _, c := range repo.ordered {
c.Content = "needle " + strings.Repeat("x", 400)
}
ctx := WithOutputBudget(context.Background(), 1500)
res, err := tool.Execute(ctx, json.RawMessage(`{"id":"doc-1","query":"needle"}`))
if err != nil || !res.Success {
t.Fatalf("res=%+v err=%v", res, err)
}
if res.Data["truncated"] != true {
t.Fatalf("budget exhaustion must be reported: %+v", res.Data)
}
if fetched := res.Data["fetched_chunks"].(int); fetched == 0 || fetched >= 12 {
t.Fatalf("expected a partial, budget-bound result, fetched=%d", fetched)
}
}
func TestReadDocumentPageStopsAtOutputBudget(t *testing.T) {
tool, repo := newReadDocumentFixture(12)
for _, c := range repo.ordered {
c.Content = strings.Repeat("x", 400)
}
ctx := WithOutputBudget(context.Background(), 2000)
res, err := tool.Execute(ctx, json.RawMessage(`{"id":"doc-1","offset":2,"limit":10}`))
if err != nil || !res.Success {
t.Fatalf("res=%+v err=%v", res, err)
}
got := chunkIDsFromData(t, res.Data)
if len(got) == 0 || len(got) >= 10 {
t.Fatalf("expected a partial, budget-bound page, got %v", got)
}
if res.Data["next_offset"] != 2+len(got) {
t.Fatalf("next_offset must resume after the last returned chunk: %+v", res.Data)
}
// A single chunk larger than the budget is still returned so paging
// always advances.
repo.ordered[0].Content = strings.Repeat("y", 5000)
res, err = tool.Execute(ctx, json.RawMessage(`{"id":"doc-1","limit":10}`))
if err != nil || !res.Success || res.Data["next_offset"] != 1 {
t.Fatalf("oversized first chunk: res=%+v err=%v", res, err)
}
}
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
func TestReadDocumentLastPageHasNoNextOffset(t *testing.T) {
tool, _ := newReadDocumentFixture(5)
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-1","offset":0,"limit":20}`))
if err != nil || !res.Success {
t.Fatalf("res=%+v err=%v", res, err)
}
if _, ok := res.Data["next_offset"]; ok {
t.Fatalf("complete read must not advertise a next page: %+v", res.Data)
}
if got := chunkIDsFromData(t, res.Data); len(got) != 5 {
t.Fatalf("expected all 5 chunks, got %v", got)
}
}
func TestReadDocumentOffsetOutOfRangeSuggestsValidOffset(t *testing.T) {
tool, _ := newReadDocumentFixture(5)
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-1","offset":40,"limit":20}`))
if err != nil {
t.Fatalf("out-of-range is a tool-level error, not a Go error: %v", err)
}
if res.Success || !strings.Contains(res.Error, "offset 40 is out of range") ||
!strings.Contains(res.Error, "offset=0") {
t.Fatalf("res=%+v", res)
}
}
func TestReadDocumentByChunkHandleWithContext(t *testing.T) {
tool, _ := newReadDocumentFixture(10)
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"chunk-4","context":1}`))
if err != nil || !res.Success {
t.Fatalf("res=%+v err=%v", res, err)
}
if got := chunkIDsFromData(t, res.Data); strings.Join(got, ",") != "chunk-3,chunk-4,chunk-5" {
t.Fatalf("context window = %v", got)
}
rows := res.Data["chunks"].([]map[string]interface{})
if rows[0]["role"] != "context_before" || rows[1]["role"] != "focus" || rows[2]["role"] != "context_after" {
t.Fatalf("roles = %v %v %v", rows[0]["role"], rows[1]["role"], rows[2]["role"])
}
if res.Data["focus_chunk_id"] != "chunk-4" || res.Data["single_chunk"] != false {
t.Fatalf("data = %+v", res.Data)
}
}
func TestReadDocumentByChunkHandleAloneIsSingleChunk(t *testing.T) {
tool, _ := newReadDocumentFixture(3)
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"chunk-2"}`))
if err != nil || !res.Success {
t.Fatalf("res=%+v err=%v", res, err)
}
if got := chunkIDsFromData(t, res.Data); strings.Join(got, ",") != "chunk-2" {
t.Fatalf("chunks = %v", got)
}
if res.Data["single_chunk"] != true || res.Data["knowledge_title"] != "Engine Manual" {
t.Fatalf("data = %+v", res.Data)
}
}
func TestReadDocumentQueryReturnsMatchesWithContext(t *testing.T) {
tool, _ := newReadDocumentFixture(12)
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-1","query":"PSIONIC engine"}`))
if err != nil || !res.Success {
t.Fatalf("res=%+v err=%v", res, err)
}
want := "chunk-3,chunk-4,chunk-5,chunk-8,chunk-9,chunk-10"
if got := chunkIDsFromData(t, res.Data); strings.Join(got, ",") != want {
t.Fatalf("matches with context = %v", got)
}
if res.Data["match_count"] != 2 || res.Data["truncated"] != false || res.Data["query"] != "PSIONIC engine" {
t.Fatalf("data = %+v", res.Data)
}
rows := res.Data["chunks"].([]map[string]interface{})
if rows[1]["role"] != "match" || rows[1]["match_snippet"] == nil {
t.Fatalf("match row = %+v", rows[1])
}
if !strings.Contains(res.Output, "<query>PSIONIC engine</query>") {
t.Fatalf("output = %s", res.Output)
}
}
func TestReadDocumentQueryIsLiteralUnlessRegex(t *testing.T) {
tool, repo := newReadDocumentFixture(3)
repo.ordered[1].Content = "Compile with C++ and check v1.2"
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-1","query":"C++"}`))
if err != nil || !res.Success || res.Data["match_count"] != 1 {
t.Fatalf("literal C++ should match once: res=%+v err=%v", res, err)
}
res, err = tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-1","query":"C++","regex":true}`))
if err == nil || res.Success || !strings.Contains(res.Error, "invalid regex") {
t.Fatalf("C++ is not a valid regex: res=%+v err=%v", res, err)
}
alternation := json.RawMessage(`{"id":"doc-1","query":"v1\\.2|nothing","regex":true}`)
res, err = tool.Execute(context.Background(), alternation)
if err != nil || !res.Success || res.Data["match_count"] != 1 {
t.Fatalf("regex alternation: res=%+v err=%v", res, err)
}
}
func TestReadDocumentQueryMatchesEveryWordInAnyOrder(t *testing.T) {
tool, repo := newReadDocumentFixture(4)
repo.ordered[1].Content = "Let f(n,k) be the least size forcing a sunflower."
repo.ordered[2].Content = "A sunflower alone."
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-1","query":"Sunflower f(n,k)"}`))
if err != nil || !res.Success || res.Data["match_count"] != 1 {
t.Fatalf("words should match in any order, and only together: res=%+v err=%v", res, err)
}
rows := res.Data["chunks"].([]map[string]interface{})
if rows[1]["chunk_id"] != "chunk-1" || rows[1]["role"] != "match" {
t.Fatalf("rows = %+v", rows)
}
}
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
func TestReadDocumentQueryWithoutMatchesKeepsHeader(t *testing.T) {
tool, _ := newReadDocumentFixture(3)
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-1","query":"absent"}`))
if err != nil || !res.Success {
t.Fatalf("res=%+v err=%v", res, err)
}
if res.Data["match_count"] != 0 || res.Data["fetched_chunks"] != 0 {
t.Fatalf("data = %+v", res.Data)
}
if info, _ := res.Data["document"].(map[string]interface{}); info["title"] != "Engine Manual" {
t.Fatalf("header must survive an empty match set: %+v", res.Data)
}
}
func TestReadDocumentRejectsUnknownIDAndOutOfScopeDocument(t *testing.T) {
tool, _ := newReadDocumentFixture(3)
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"nope"}`))
if err == nil || res.Success || !strings.Contains(res.Error, "neither a document") {
t.Fatalf("unknown id: res=%+v err=%v", res, err)
}
foreign := &types.Knowledge{ID: "doc-2", TenantID: 9, KnowledgeBaseID: "kb-9", Title: "Other"}
tool.knowledgeService = &readDocKnowledgeService{docs: map[string]*types.Knowledge{"doc-2": foreign}}
res, err = tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-2"}`))
if err == nil || res.Success || !strings.Contains(res.Error, "not accessible") {
t.Fatalf("out-of-scope document: res=%+v err=%v", res, err)
}
}
func TestReadDocumentSurfacesRepositoryFailure(t *testing.T) {
tool, repo := newReadDocumentFixture(3)
repo.listErr = errors.New("db down")
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-1"}`))
if err == nil || res.Success || !strings.Contains(res.Error, "db down") {
t.Fatalf("res=%+v err=%v", res, err)
}
}
func TestReadDocumentFAQChunkExposesQuestion(t *testing.T) {
tool, repo := newReadDocumentFixture(2)
faq := repo.ordered[0]
faq.ChunkType = types.ChunkTypeFAQ
meta := &types.FAQChunkMetadata{StandardQuestion: "How to reset?", Answers: []string{"Hold the button."}}
if err := faq.SetFAQMetadata(meta); err != nil {
t.Fatal(err)
}
res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"chunk-0"}`))
if err != nil || !res.Success {
t.Fatalf("res=%+v err=%v", res, err)
}
if res.Data["faq_question"] != "How to reset?" || res.Data["faq_id"] != "chunk-0" {
t.Fatalf("data = %+v", res.Data)
}
if !strings.Contains(res.Output, "<answer>Hold the button.</answer>") {
t.Fatalf("output = %s", res.Output)
}
}
fix(retrieval): fix recall correctness, score scales, cost and agent tools (#3687) * fix(retrieval): keep index writes and shared-KB lookups correct Index writes - Image OCR/caption chunks were indexed without IsEnabled, so every engine but Postgres stored them disabled and retrieval never returned them. The SQLite engine re-enables the affected rows at startup. - FAQ edits, similar-question additions and import merges re-index under the old SourceID and relied on the engine overwriting it. Postgres and SQLite kept the stale row (ON CONFLICT DO NOTHING); ES v8 and Qdrant mint a new document ID and kept both. FAQ re-indexing now deletes the old rows first, and Postgres/SQLite BatchSave upserts by (source_id, source_type). - Postgres: drop the GORM default tag on is_enabled, which replaced false with true on insert and indexed disabled chunks as enabled. - SQLite: BatchSave no longer attaches vectors and FTS rows to the wrong rows when part of a batch already exists, and vecTables is guarded against concurrent map writes. - CopyIndices: Postgres filters to the copied knowledge, pages by id and keeps is_enabled; SQLite copies every row of a chunk (generated questions included) with stable source IDs and enabled state. Shared knowledge bases - Chat merge: FAQ answer population and neighbor expansion look chunks up without the caller-tenant filter, like parent resolution (#3342). - Neighbor expansion never cuts the retrieval hit; the length budget goes to the text adjacent to it. - FAQ negative questions are applied whenever an FAQ KB is in scope and to chunks of shared FAQ KBs. - Search results get image_info for shared-KB chunks. - search_knowledge reads FAQ metadata from the search result instead of one tenant-scoped query per hit, so shared FAQs render their answers. * fix(retrieval): put every retrieval score on one scale Scores from different retrieval paths were ranked together while living on different scales, so ordering depended on which path produced a hit. Fusion - RRF ranked a chunk by its position in the concatenation of every vector (or keyword) list, appended in goroutine completion order. The second list's best hit ranked behind every hit of the first, and the order changed between identical requests. Each list is now ranked on its own by score and a chunk takes its best rank. - RRF is divided by its maximum, so hybrid scores land in [0, 1] like vector-only (cosine) and keyword-only (rescaled BM25) results. Raw RRF topped out near 0.016 and lost to any single-retriever hit it was ranked against across searches (document targets, model groups, FAQ calls); rerank's base-score term and MMR's relevance term had nothing to use. - Keyword-only BM25 is rescaled per list; engines' BM25 is not comparable. - FAQ iterative retrieval fuses each round like the first pass instead of sorting raw BM25 and cosine together, starts at twice the depth already searched, triggers when any single vector list is full (the old summed count never matched with more than one list) and replaces results per round. Rerank and chat pipeline - The FAQ boost is no longer capped at 1; capping made strong FAQs tie at 1.0 and fall to the tie-breaker. The composite score before boosts is kept as composite_score. - The FAQ direct-answer threshold is compared against that pre-boost score, and the FAQ that cleared it is the one marked match="exact" rather than the first FAQ. - Graph hits no longer carry a fabricated retrieval score of 1.0, which ranked them above every scored hit when rerank did not run; the composite score uses the model score in its place. Engines - OpenSearch and Weaviate return (1 + cos) / 2; their drivers now report cosine similarity and map thresholds onto the engine scale, so a threshold means the same on every engine. - Milvus L2 returned squared distance, ranked farthest-first downstream, and took the threshold as a radius; scores and radius are converted. - The multi-store normalizer no longer maps Milvus through (s + 1) / 2, which put it on a different scale from every other engine and from its own single-store results. Docs updated for fusion, normalization, FAQ boost and iterative recall. * perf(retrieval): bound rerank, agent and pipeline cost; stop failing on slow or missing models Rerank - Rerankers report the longest document a request can carry (max_document_chars / max_request_chars minus the query) and the rerank stage fits its own passages to it, trimming appended captions, OCR and generated questions first. One chunk with a large screenshot's OCR used to exceed the vendor limit and fail the whole batch, so every candidate lost its score and the threshold stopped applying. - Rerank HTTP requests default to a 60 s timeout; chat and agent contexts carry no deadline, so a stalled self-hosted rerank server held the turn open. - OCR and caption chunks no longer repeat their own text from image_info in the passage. - The chat pipeline and the agent tool rerank at most 200 candidates, best retrieval score first. - A rerank model that cannot be loaded degrades to retrieval order instead of failing every chat turn, as the search APIs already do; without rerank results the merge stage keeps only RerankTopK hits instead of enriching every one. Retrieval APIs - knowledge-search match_count and rerank.top_k are capped at 200 (unbounded values multiplied into tens of thousands of billed rerank passages); normalizedMatchCount clamps to the pool size so the over-retrieval arithmetic cannot overflow. - hybrid-search with rerank recalls at least rerank.top_k deep. Agent - search_knowledge fits its rendered output to four fifths of the tool output budget, dropping the lowest-ranked rows and telling the model how many it omitted; the model's view is rebuilt from Data, which registry truncation never reached. - Agent searches skip neighbor/parent/related enrichment rows, which were never retrieved yet tripled the rerank input. - ParallelToolCalls is enabled. The model was always told it may call tools in parallel while the engine ran them one by one; only read-only tools overlap, anything else stays a barrier. Chat pipeline - Query expansion searches keywords only (its variants are local rewrites whose embeddings repeat the main search) and is skipped when keyword matching is off. - Entity extraction, a second LLM call, is skipped for intents that need no KB retrieval and uses the rewritten query. - Partial-overlap dedup tokenizes each text once instead of per pair, and only compares token overlap between texts within 3x of each other's size. Storage - Migration 000112 adds btree indexes on embeddings(knowledge_id) and (chunk_id); document deletes, chunk re-index and enable/tag updates scanned the whole table. - Shared-KB knowledge rows are fetched in one query instead of one per ID. - Drop GORM Debug() from the ParadeDB keyword query and the knowledge batch lookup, which logged SQL and user queries on every search. Docs updated for the API limits, rerank timeout and passage fitting, agent parallel tools and output budget, and pipeline changes. * fix(retrieval): make agent tools and pipeline stages report what they did Agent tools - query_knowledge_graph now queries the graph store: entity names from the query are matched in each KB's graph, relations are returned (and shown to the model), and the entities' source chunks lead the results, with text search as a supplement. It used to run text search only, so a graph-only KB always answered "no relevant graph information". - search_knowledge reports failures instead of "no matching chunks": when every search fails the tool fails with the reason; partial failures are listed. A failed query embedding falls back to keyword search for hybrid KBs, as the chat pipeline does. - Keyword mode uses rerank to order hits, not to reject them (identifiers score low), and the empty-result hint no longer sends keyword mode back to keyword mode. - Dedup keeps siblings under one parent, no longer merges every image chunk of a document through chunk_index 0, and keeps the better-scored copy. - Search rows omit a <match> excerpt that only repeats the content; snippet terms are segmented for Chinese queries and skip stopwords, and FAQ matched questions are chosen by match strength. - read_document query mode returns next_offset when truncated and resumes from offset. - wiki_search over-fetches under document/tag scopes before filtering and says when every match was out of scope. - Prompts point to read_document(id=cN, context=k) for surrounding text. - The agent editor hides the retrieval-strategy section in agent mode, where search_knowledge uses the global retrieval settings. Chat pipeline - Intent labels are normalized; an unknown label retrieves instead of silently skipping the knowledge base, and web_search without web search enabled searches the knowledge bases. - Image turns get a 2048-token rewrite budget, and a reply cut off by the cap is salvaged field by field instead of being discarded. - History references are matched by how much of the query they cover; Jaccard against chunk-sized text never reached its threshold. - Entity search resolves chunks of org-shared KBs within the turn's KB scope, skips chunks whose document is gone (it used to panic) and caps graph chunks at 30. - Empty history is not fetched twice; fetched pages are cut on a rune boundary. Retrieval - A multi-KB search whose primary KB has no vectors embeds the query with a vector KB's model instead of failing on an empty model ID. - Rerank passages include the chunk's heading breadcrumb, which is part of what was embedded. - SQLite FTS searches the content column only and turns a lone Han character into a prefix query; TencentVectorDB ef follows TopK. Docs updated for the agent tools and pipeline stages. * fix(retrieval): address review findings on the retrieval fixes - Restore NeedsRetrieval for web_search without web search enabled: the intent prompt "web_search" is how the user learns web search is off, and running KB retrieval instead bypassed it. - query_knowledge_graph keeps the case of entity terms; Neo4j matches node names with case-sensitive CONTAINS, so lowercased terms never matched English entities. - An empty search_knowledge or query_knowledge_graph result states partial failures in its text, which is all the model sees for an empty result. - SQLite BatchSave replaces a source in one transaction, so a failed insert keeps the old rows instead of leaving the source unindexed. - Reuse stringSliceValue and an exported searchutil.ContainsChinese instead of new copies; drop an unused named return and the FAQ obsolete-source delete that the full per-chunk delete now covers. * fix(retrieval): address second review of the retrieval fixes - query_knowledge_graph: under a document/tag scope, keep only relations whose entities come from an in-scope evidence chunk (the graph namespace is the whole KB); drop chunks whose document no longer exists; report a graph or text search failure even when the other source returned hits. - search_knowledge: record the hybrid -> keyword fallback taken when the query embedding fails in mode_fallbacks, so an empty result is not read as "no semantic match". - query understanding salvage: take a cut-off value only for the image description; a truncated rewrite_query or intent is dropped instead of replacing the user's query. - Graph hits (no retrieval score) are kept past the no-rerank RerankTopK cut and the rerank candidate cap instead of always falling below them. - FAQ boost is capped at 1 again so scores stay on the [0, 1] scale; FAQs tied at the cap are ordered by their pre-boost score. - Negative-question filtering loads only candidates of FAQ knowledge bases. - read_document query continuation starts one chunk before offset so the first match keeps its preceding context at a page boundary. - graphSearchTerms and searchQueryTokens share one queryTerms splitter.
2026-09-25 02:48:18 +00:00
// A truncated query result says where to continue, and offset resumes the
// scan there; matches past the cap used to be reachable only by paging the
// whole document.
func TestReadDocumentQueryContinuesFromNextOffset(t *testing.T) {
tool, repo := newReadDocumentFixture(12)
for _, c := range repo.ordered {
c.Content = "needle " + strings.Repeat("x", 400)
}
ctx := WithOutputBudget(context.Background(), 1500)
first, err := tool.Execute(ctx, json.RawMessage(`{"id":"doc-1","query":"needle"}`))
if err != nil || !first.Success || first.Data["truncated"] != true {
t.Fatalf("first=%+v err=%v", first, err)
}
next, ok := first.Data["next_offset"].(int)
if !ok || next <= 0 || next >= 12 {
t.Fatalf("next_offset = %v", first.Data["next_offset"])
}
firstIDs := chunkIDsFromData(t, first.Data)
second, err := tool.Execute(ctx, json.RawMessage(fmt.Sprintf(`{"id":"doc-1","query":"needle","offset":%d}`, next)))
if err != nil || !second.Success {
t.Fatalf("second=%+v err=%v", second, err)
}
secondIDs := chunkIDsFromData(t, second.Data)
if len(secondIDs) == 0 {
t.Fatal("continuation returned nothing")
}
for _, id := range secondIDs {
for _, seen := range firstIDs {
if id == seen && id != secondIDs[0] {
t.Fatalf("continuation repeated %s: first=%v second=%v", id, firstIDs, secondIDs)
}
}
}
}