RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
package nlp
import (
"context"
"encoding/json"
"fmt"
"math"
"strings"
"testing"
"ragflow/internal/engine/types"
"ragflow/internal/service/nav"
"gorm.io/gorm"
)
// memNavEngine is an in-memory DocEngine double sufficient for the datasetnav
// minimal closed loop. It stores rows in a slice and supports the filtered
// search / insert / update / delete operations NavService uses. Dense-vector
// KNN is approximated by a deterministic cosine over a synthetic q_<dim>_vec.
type memNavEngine struct {
rows []map[string]interface{}
nextID int
// searches records every SearchRequest so a test can pin the request shape
// (e.g. that nav reads opt out of the retrieval-only available_int=1 default).
searches []*types.SearchRequest
}
func newMemNavEngine() *memNavEngine { return &memNavEngine{} }
func (m *memNavEngine) InsertChunks(_ context.Context, chunks []map[string]interface{}, _ string, datasetID string, _ string) ([]string, error) {
ids := make([]string, 0, len(chunks))
for _, c := range chunks {
// A caller-provided row id is kept, exactly as the real engines do it
// (elasticsearch: chunk["id"] becomes the document id; infinity: the id
// column is written verbatim). Nav addresses its cluster rows by the
// deterministic id they were written with, so generating a fresh one here
// would make every update/delete miss.
id, _ := c["id"].(string)
if id == "" {
m.nextID++
id = "nav" + strconvItoa(m.nextID)
}
cp := make(map[string]interface{}, len(c)+2)
for k, v := range c {
cp[k] = v
}
cp["id"] = id
cp["kb_id"] = datasetID
m.rows = append(m.rows, cp)
ids = append(ids, id)
}
return ids, nil
}
func (m *memNavEngine) UpdateChunks(_ context.Context, cond map[string]interface{}, newValue map[string]interface{}, _ string, _ string) error {
for _, r := range m.rows {
if matchNavRow(r, cond) {
for k, v := range newValue {
r[k] = v
}
}
}
return nil
}
func (m *memNavEngine) DeleteChunks(_ context.Context, cond map[string]interface{}, _ string, _ string) (int64, error) {
out := m.rows[:0]
var deleted int64
for _, r := range m.rows {
if matchNavRow(r, cond) {
deleted++
continue
}
out = append(out, r)
}
m.rows = out
return deleted, nil
}
func (m *memNavEngine) Search(_ context.Context, req *types.SearchRequest) (*types.SearchResult, error) {
m.searches = append(m.searches, req)
var matched []map[string]interface{}
// This engine implements the DENSE leg only. A lexical match expression is
// deliberately a no-op rather than a dense one: treating a text expression
// as dense would look for a q_0_vec column and silently drop every row, so a
// keyword search would look broken in tests.
hasDense := false
var queryVec []float64
if len(req.MatchExprs) > 0 {
if de, ok := req.MatchExprs[0].(*types.MatchDenseExpr); ok {
hasDense = true
queryVec = de.EmbeddingData
}
}
for _, r := range m.rows {
if !matchNavRow(r, req.Filter) {
continue
}
if hasDense {
col := "q_" + strconvItoa(len(queryVec)) + "_vec"
rv, ok := r[col].([]float64)
if !ok {
continue
}
r["_score"] = cosineNav(rv, queryVec)
}
matched = append(matched, r)
}
if hasDense {
for i := 1; i < len(matched); i++ {
for j := i; j > 0 && scoreNavOf(matched[j]) > scoreNavOf(matched[j-1]); j-- {
matched[j], matched[j-1] = matched[j-1], matched[j]
}
}
}
offset, limit := req.Offset, req.Limit
if offset > len(matched) {
offset = len(matched)
}
end := offset + limit
if limit <= 0 || end > len(matched) {
end = len(matched)
}
return &types.SearchResult{Chunks: matched[offset:end], Total: int64(len(matched))}, nil
}
func (m *memNavEngine) DropChunkStore(context.Context, string, string) error { return nil }
func (m *memNavEngine) ChunkStoreExists(context.Context, string, string) (bool, error) {
return true, nil
}
func (m *memNavEngine) Close() error { return nil }
func (m *memNavEngine) Ping(context.Context) error { return nil }
func (m *memNavEngine) GetType() string { return "mem" }
func (m *memNavEngine) SupportsPageRank() bool { return false }
func (m *memNavEngine) CreateChunkStore(context.Context, string, string, int, string, string) error {
return nil
}
func (m *memNavEngine) GetChunk(context.Context, string, string, []string) (interface{}, error) {
return nil, nil
}
func (m *memNavEngine) CreateMetadataStore(context.Context, string) error { return nil }
func (m *memNavEngine) InsertMetadata(context.Context, []map[string]interface{}, string) ([]string, error) {
return nil, nil
}
func (m *memNavEngine) UpdateMetadata(context.Context, string, string, map[string]interface{}, string) error {
return nil
}
func (m *memNavEngine) DeleteMetadata(context.Context, map[string]interface{}, string) (int64, error) {
return 0, nil
}
func (m *memNavEngine) DeleteMetadataKeys(context.Context, string, string, []string, string) error {
return nil
}
func (m *memNavEngine) DropMetadataStore(context.Context, string) error { return nil }
func (m *memNavEngine) MetadataStoreExists(context.Context, string) (bool, error) {
return true, nil
}
func (m *memNavEngine) SearchMetadata(context.Context, *types.SearchMetadataRequest) (*types.SearchMetadataResult, error) {
return nil, nil
}
func (m *memNavEngine) IndexDocument(context.Context, string, string, interface{}) error {
return nil
}
func (m *memNavEngine) DeleteDocument(context.Context, string, string) error { return nil }
func (m *memNavEngine) BulkIndex(context.Context, string, []interface{}) (interface{}, error) {
return nil, nil
}
func (m *memNavEngine) GetFields([]map[string]interface{}, []string) map[string]map[string]interface{} {
return nil
}
func (m *memNavEngine) GetAggregation([]map[string]interface{}, string) []map[string]interface{} {
return nil
}
func (m *memNavEngine) GetHighlight([]map[string]interface{}, []string, string) map[string]string {
return nil
}
func (m *memNavEngine) RunSQL(context.Context, string, string) ([]map[string]interface{}, error) {
return nil, nil
}
func (m *memNavEngine) GetChunkIDs([]map[string]interface{}) []string { return nil }
func (m *memNavEngine) KNNScores(context.Context, []map[string]interface{}, []float64, int) (map[string]interface{}, error) {
return nil, nil
}
func (m *memNavEngine) GetScores(map[string]interface{}) map[string]float64 { return nil }
func (m *memNavEngine) FilterDocIdsByMetaPushdown(context.Context, *gorm.DB, []string, []map[string]interface{}, string) []string {
return nil
}
const navCompileKwd = "dataset_nav"
// matchNavRow mirrors dataset_nav._matches_condition (dataset_nav.py:598-608):
// every field must have one of the row's values equal to one of the condition's
// values. A list condition therefore means intersection when the row's field is
// an array (the scope push for nav_cluster's doc_ids_kwd) and membership when
// the field is a scalar. The real engines give a list filter the same semantics
// (elasticsearch/chunk.go terms, serenedb list_contains, oceanbase
// ARRAY_CONTAINS).
func matchNavRow(row map[string]interface{}, cond map[string]interface{}) bool {
for k, v := range cond {
rv, ok := row[k]
if !ok {
return false
}
if !navValueMatches(rv, v) {
return false
}
}
return true
}
// navValueMatches compares one field the way `_matches_condition` does
// (`str(value) == str(item)`), with list-vs-list compared as an intersection.
func navValueMatches(actual, expected interface{}) bool {
actuals, actualIsList := navValueList(actual)
expecteds, expectedIsList := navValueList(expected)
if !actualIsList && !expectedIsList {
return fmt.Sprint(actual) == fmt.Sprint(expected)
}
for _, a := range actuals {
for _, e := range expecteds {
if a == e {
return true
}
}
}
return false
}
// navValueList normalizes a row or condition value to a list of comparable
// scalars, reporting whether it was already a list.
func navValueList(v interface{}) ([]interface{}, bool) {
switch t := v.(type) {
case []string:
out := make([]interface{}, 0, len(t))
for _, x := range t {
out = append(out, x)
}
return out, true
case []interface{}:
return t, true
default:
return []interface{}{v}, false
}
}
func scoreNavOf(r map[string]interface{}) float64 {
switch s := r["_score"].(type) {
case float64:
return s
case float32:
return float64(s)
}
return 0
}
func cosineNav(a, b []float64) float64 {
if len(a) == 0 || len(b) == 0 || len(a) != len(b) {
return 0
}
var dot, na, nb float64
for i := range a {
dot += a[i] * b[i]
na += a[i] * a[i]
nb += b[i] * b[i]
}
if na == 0 || nb == 0 {
return 0
}
return dot / (math.Sqrt(na) * math.Sqrt(nb))
}
func strconvItoa(n int) string {
if n == 0 {
return "0"
}
digits := []byte{}
for n > 0 {
digits = append([]byte{byte('0' + n%10)}, digits...)
n /= 10
}
return string(digits)
}
// stubNavEmbedder returns a fixed deterministic vector per distinct text.
type stubNavEmbedder struct{}
func (stubNavEmbedder) Encode(_ context.Context, _ string, texts []string) ([][]float32, error) {
out := make([][]float32, len(texts))
for i, t := range texts {
// The ES document index template (mapping.json, the ragflow_*
// dynamic_templates) maps any q_<dim>_vec field to dense_vector, so the
// synthetic vector may use any dimension. 1024 is the canonical
// RAGFlow embedding size.
dim := 1024
v := make([]float32, dim)
for d := 0; d < dim; d++ {
v[d] = float32(int(t[0]) + d)
}
out[i] = v
}
return out, nil
}
func newTestNav(eng *memNavEngine) *NavService {
ns := NewNavService(stubNavEmbedder{})
ns.engine = eng
return ns
}
func TestNavServicePageIndexRowsAndCleanup(t *testing.T) {
eng := &memNavEngine{}
ns := newTestNav(eng)
if err := ns.UpsertDoc(t.Context(), nav.UpsertDocInput{TenantID: "t1", KbID: "kb1", DocID: "d1", CompileKind: "page_index", Summary: "Page index summary"}); err != nil {
t.Fatal(err)
}
if len(eng.rows) != 2 {
t.Fatalf("rows = %d, want document and cluster", len(eng.rows))
}
for _, row := range eng.rows {
if row["compile_kwd"] != "page_index" {
t.Fatalf("compile_kwd = %v, want page_index", row["compile_kwd"])
}
wantScope := "doc"
if row["type_kwd"] == "nav_cluster" {
wantScope = "dataset"
}
if row["scope_kwd"] != wantScope {
t.Fatalf("scope_kwd = %v, want %s for %s", row["scope_kwd"], wantScope, row["type_kwd"])
}
if row["type_kwd"] == "nav_cluster" {
row["compile_kwd"] = "dataset_nav"
}
}
if err := ns.UpsertDoc(t.Context(), nav.UpsertDocInput{TenantID: "t1", KbID: "kb1", DocID: "d2", CompileKind: "page_index", Summary: "Page index summary"}); err != nil {
t.Fatal(err)
}
if len(eng.rows) != 3 {
t.Fatalf("rows = %d, want two documents in one cluster", len(eng.rows))
}
for _, row := range eng.rows {
if row["compile_kwd"] != "page_index" {
t.Fatalf("updated compile_kwd = %v, want page_index", row["compile_kwd"])
}
}
hits, err := ns.Search(t.Context(), "t1", "kb1", "Page index", nil, nil, 5)
if err != nil || len(hits) == 0 {
t.Fatalf("Search = %v, %v", hits, err)
}
if err := ns.RemoveDoc(t.Context(), "t1", "kb1", "d1"); err != nil {
t.Fatal(err)
}
if err := ns.RemoveDoc(t.Context(), "t1", "kb1", "d2"); err != nil {
t.Fatal(err)
}
if len(eng.rows) != 0 {
t.Fatalf("rows after RemoveDoc = %d, want 0", len(eng.rows))
}
}
// TestNavService_UpsertDoc_WritesNavRow asserts acceptance #1: after UpsertDoc
// the row carries both compile_kwd=dataset_nav and available_int=0.
func TestNavService_UpsertDoc_WritesNavRow(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", "alpha")); err != nil {
t.Fatalf("UpsertDoc: %v", err)
}
if len(eng.rows) == 0 {
t.Fatal("expected at least one nav row")
}
row := eng.rows[0]
if row["compile_kwd"] != "tree" {
t.Errorf("compile_kwd = %v, want tree", row["compile_kwd"])
}
if row["available_int"] != 0 {
t.Errorf("available_int = %v, want 0", row["available_int"])
}
if row["type_kwd"] != "nav_cluster" {
t.Errorf("type_kwd = %v, want nav_cluster", row["type_kwd"])
}
if row["parent_kwd"] != "root" {
t.Errorf("parent_kwd = %v, want root", row["parent_kwd"])
}
}
// TestNavService_ListClusters_FiltersRoot asserts acceptance #3.
func TestNavService_ListClusters_FiltersRoot(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", "aaa")); err != nil {
t.Fatal(err)
}
clusters, total, err := ns.ListClusters(t.Context(), "t1", "kb1", "", 0, 10)
if err != nil {
t.Fatal(err)
}
if total != 1 || len(clusters) != 1 {
t.Fatalf("expected 1 root cluster, got total=%d len=%d", total, len(clusters))
}
if clusters[0].Type != "cluster" {
t.Errorf("cluster type = %s, want cluster", clusters[0].Type)
}
if clusters[0].DocCount < 1 {
t.Errorf("cluster doc_count = %d, want >=1", clusters[0].DocCount)
}
}
// TestNavNode_JSONShape_SnakeCase locks the REST contract: the frontend
// DatasetNavNode and Python GET /navigation both use snake_case keys. If the
// Go field names leaked (Name/Description/DocCount...) the frontend tree would
// read undefined fields and render empty.
func TestNavNode_JSONShape_SnakeCase(t *testing.T) {
n := nav.NavNode{Name: "cluster_x", Description: "d", DocCount: 3, Type: "cluster", HasChildren: true}
b, err := json.Marshal(n)
if err != nil {
t.Fatal(err)
}
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
t.Fatal(err)
}
for _, want := range []string{"name", "description", "doc_count", "type", "has_children"} {
if _, ok := m[want]; !ok {
t.Errorf("NavNode JSON missing snake_case key %q; got %s", want, b)
}
}
for _, bad := range []string{"Name", "Description", "DocCount", "HasChildren"} {
if _, ok := m[bad]; ok {
t.Errorf("NavNode JSON leaked PascalCase key %q; got %s", bad, b)
}
}
// A search hit carries the tree edge and the hit flag. Both are optional:
// the ordinary tree reads (root clusters, children) never set them, so they
// must stay out of the payload there.
hit := nav.NavNode{Name: "doc.pdf", Type: "doc", Parent: "topic 8738e200", Matched: true}
hb, err := json.Marshal(hit)
if err != nil {
t.Fatal(err)
}
var hm map[string]interface{}
if err := json.Unmarshal(hb, &hm); err != nil {
t.Fatal(err)
}
if hm["parent_kwd"] != "topic 8738e200" || hm["matched"] != true {
t.Errorf("search hit JSON = %s, want parent_kwd + matched", hb)
}
if _, ok := m["matched"]; ok {
t.Errorf("a non-hit NavNode must not carry matched; got %s", b)
}
}
// TestNavService_ListClusters_SearchReturnsPrunedForest pins the search shape:
// the hits come back TOGETHER with the cluster path above them, so the caller
// nests the flat list into one tree per root cluster instead of rendering every
// hit — and every matched subtree — as its own tree.
func TestNavService_ListClusters_SearchReturnsPrunedForest(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
const (
rootCluster = "三国 11111111"
subCluster = "名将 22222222"
)
rows := []map[string]interface{}{
{
"compile_kwd": navCompileKwd, "type_kwd": nav.TypeNavCluster,
"title_kwd": rootCluster, "parent_kwd": navRootParent, "depth_int": 0,
"doc_count_int": 2, "doc_ids_kwd": []string{"d1", "d2"},
"content_with_weight": `{"type":"nav_cluster","description":"三国主题"}`,
},
{
"compile_kwd": navCompileKwd, "type_kwd": nav.TypeNavCluster,
"title_kwd": subCluster, "parent_kwd": rootCluster, "depth_int": 1,
"doc_count_int": 1, "doc_ids_kwd": []string{"d1"},
"content_with_weight": `{"type":"nav_cluster","description":"名将主题"}`,
},
{
"compile_kwd": navCompileKwd, "type_kwd": nav.TypeNavDoc,
"doc_id": "d1", "parent_kwd": subCluster, "depth_int": 2,
"title_kwd": "三国名将事迹概要", "doc_count_int": 1,
"content_with_weight": `{"type":"nav_doc","description":"三国名将事迹概要\n正文"}`,
},
// A second leaf in subCluster: two hits in ONE cluster must count once.
{
"compile_kwd": navCompileKwd, "type_kwd": nav.TypeNavDoc,
"doc_id": "d4", "parent_kwd": subCluster, "depth_int": 2,
"title_kwd": "名将功过评析", "doc_count_int": 1,
"content_with_weight": `{"type":"nav_doc","description":"名将功过评析"}`,
},
{
"compile_kwd": navCompileKwd, "type_kwd": nav.TypeNavDoc,
"doc_id": "d2", "parent_kwd": rootCluster, "depth_int": 1,
"title_kwd": "其他概要", "doc_count_int": 1,
"content_with_weight": `{"type":"nav_doc","description":"其他概要"}`,
},
// An orphan whose parent cluster is gone: the hit is still returned (as
// its own root) rather than dropped.
{
"compile_kwd": navCompileKwd, "type_kwd": nav.TypeNavDoc,
"doc_id": "d3", "parent_kwd": "missing-cluster", "depth_int": 1,
"title_kwd": "孤儿概要", "doc_count_int": 1,
"content_with_weight": `{"type":"nav_doc","description":"孤儿概要"}`,
},
}
if _, err := eng.InsertChunks(t.Context(), rows, "", "kb1", ""); err != nil {
t.Fatal(err)
}
nodes, total, err := ns.ListClusters(t.Context(), "t1", "kb1", "任意关键词", 0, 100)
if err != nil {
t.Fatal(err)
}
// The test engine ignores the lexical expression, so all four nav_doc rows
// are hits. total is the CLUSTER count — the same quantity the nav tree
// header shows while browsing — not the hit count: d1 and d4 share
// subCluster (one cluster, two hits), d2 sits directly in rootCluster, and
// d3's cluster edge dangles. The path rows above the hits are not counted.
if total != 3 {
t.Errorf("search total = %d, want 3 (the clusters the hits landed in, not the 4 hits)", total)
}
byID := make(map[string]nav.NavNode, len(nodes))
for _, n := range nodes {
if n.Type == "doc" {
byID[n.DocID] = n
}
}
if len(byID) != 4 {
t.Fatalf("search forest returned %d doc nodes, want 4: %+v", len(byID), nodes)
}
// The cluster path above d1 (sub-cluster then root) must be present so the
// tree stays ONE tree, and it must not be flagged as a hit.
var gotRoot, gotSub bool
for _, n := range nodes {
switch n.Name {
case rootCluster:
gotRoot = true
if n.Matched {
t.Errorf("path cluster %q marked as a hit", n.Name)
}
if n.Parent != navRootParent {
t.Errorf("root cluster parent = %q, want %q", n.Parent, navRootParent)
}
case subCluster:
gotSub = true
if n.Matched {
t.Errorf("path cluster %q marked as a hit", n.Name)
}
if n.Parent != rootCluster {
t.Errorf("sub cluster parent = %q, want %q", n.Parent, rootCluster)
}
}
}
if !gotRoot || !gotSub {
t.Fatalf("search forest is missing the path above d1 (root=%v sub=%v): %+v", gotRoot, gotSub, nodes)
}
// The leaf keeps both the tree edge and its label (title_kwd, the summary's
// first line — the same column the model-facing readers use).
if got := byID["d1"]; got.Parent != subCluster || !got.Matched || got.Name != "三国名将事迹概要" {
t.Errorf("hit d1 = %+v, want parent=%q matched=true name=三国名将事迹概要", got, subCluster)
}
if got := byID["d4"]; got.Parent != subCluster || !got.Matched {
t.Errorf("hit d4 = %+v, want parent=%q matched=true", got, subCluster)
}
if got := byID["d2"]; got.Parent != rootCluster || !got.Matched {
t.Errorf("hit d2 = %+v, want parent=%q matched=true", got, rootCluster)
}
if got := byID["d3"]; got.Parent != "missing-cluster" || !got.Matched {
t.Errorf("orphan hit d3 = %+v, want it still returned with its edge", got)
}
// The ordinary (no-keyword) read is unchanged: depth-0 clusters only.
clusters, rootTotal, err := ns.ListClusters(t.Context(), "t1", "kb1", "", 0, 100)
if err != nil {
t.Fatal(err)
}
if rootTotal != 1 || len(clusters) != 1 || clusters[0].Name != rootCluster {
t.Fatalf("root listing = %+v (total %d), want the single root cluster", clusters, rootTotal)
}
if clusters[0].Matched {
t.Error("a non-search read must not mark nodes as hits")
}
}
// TestSearchNavClusterCount pins the search header's number: how many clusters
// the hits landed in — not the hit count (which would make the header mean
// "documents" in search mode), and not every cluster row returned either, since
// an ancestor shared by two hits is a path row.
func TestSearchNavClusterCount(t *testing.T) {
hit := func(docID, parent string) map[string]interface{} {
return map[string]interface{}{"doc_id": docID, "parent_kwd": parent}
}
cases := []struct {
name string
matches []map[string]interface{}
want int64
}{
{
name: "no hits",
matches: nil,
want: 0,
},
{
name: "two hits in one cluster count once",
matches: []map[string]interface{}{hit("d1", "三国 11111111"), hit("d2", "三国 11111111")},
want: 1,
},
{
name: "two sub-clusters under one root count their own clusters, not the ancestor",
matches: []map[string]interface{}{
hit("d1", "名将 22222222"), hit("d2", "谋士 33333333"),
},
want: 2,
},
{
name: "hits in different root clusters",
matches: []map[string]interface{}{hit("d1", "三国 11111111"), hit("d2", "唐宋 44444444")},
want: 2,
},
{
name: "a leaf with no cluster edge is not counted",
matches: []map[string]interface{}{hit("d1", navRootParent), hit("d2", "")},
want: 0,
},
{
name: "an empty row is dropped",
matches: []map[string]interface{}{{}, hit("d1", "三国 11111111")},
want: 1,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := searchNavClusterCount(tc.matches); got != tc.want {
t.Errorf("searchNavClusterCount = %d, want %d", got, tc.want)
}
})
}
}
// TestNavNamingHelpers_Readable verifies the nav display-name helpers produce
// human-readable names (mirroring Python _clean_title/_fallback_title/
// _readable_cluster_name) instead of raw ids.
func TestNavNamingHelpers_Readable(t *testing.T) {
if cleanTitle(" hello world ") != "hello world" {
t.Errorf("cleanTitle = %q, want %q", cleanTitle(" hello world "), "hello world")
}
// fallbackTitle takes the first non-empty line and strips Markdown markers.
if got := fallbackTitle("a b c d e f g h"); got != "a b c d e f g h" {
t.Errorf("fallbackTitle = %q, want the first line", got)
}
if got := fallbackTitle("**何进诛阉与董后之废**\n\nbody text"); got != "何进诛阉与董后之废" {
t.Errorf("fallbackTitle = %q, want the stripped markdown title", got)
}
if got := fallbackTitle(""); got != "Cluster" {
t.Errorf("fallbackTitle('') = %q, want Cluster", got)
}
name := readableClusterName("何进诛阉", "seed-text")
if !strings.HasPrefix(name, "何进诛阉 ") {
t.Errorf("readableClusterName = %q, want prefix %q", name, "何进诛阉 ")
}
}
// TestNavNamingHelpers_RawIDDetection verifies meaningless ids are detected so
// nodeFromRow can fall back to a readable title.
func TestNavNamingHelpers_RawIDDetection(t *testing.T) {
for _, raw := range []string{"d3778ef9c0f5495fa4bdadc00a5bf15c", "cluster_abc12345", ""} {
if !graphIsRawID(raw) {
t.Errorf("graphIsRawID(%q) = false, want true", raw)
}
}
for _, ok := range []string{"何进诛阉", "NVIDIA financial performance 8738e200"} {
if graphIsRawID(ok) {
t.Errorf("graphIsRawID(%q) = true, want false", ok)
}
}
}
// TestNodeFromRow_ReadableName verifies nodeFromRow falls back to a readable
// title derived from the payload description when title_kwd is a raw id.
func TestNodeFromRow_ReadableName(t *testing.T) {
ns := &NavService{}
row := map[string]interface{}{
"title_kwd": "d3778ef9c0f5495fa4bdadc00a5bf15c",
"doc_id": "d3778ef9c0f5495fa4bdadc00a5bf15c",
"type_kwd": "nav_doc",
"doc_count_int": 1,
"content_with_weight": `{"type":"nav_doc","description":"刘备三战黄巾军与何进诛阉之议\nsecond line"}`,
}
node := ns.nodeFromRow(row, "doc")
if node.Name == "" || node.Name == "d3778ef9c0f5495fa4bdadc00a5bf15c" {
t.Fatalf("nodeFromRow name = %q, want readable fallback", node.Name)
}
if node.DocID != "d3778ef9c0f5495fa4bdadc00a5bf15c" {
t.Errorf("nodeFromRow DocID = %q, want the raw doc id preserved", node.DocID)
}
// A cluster row keeps its stored key verbatim (it is the child-lookup
// parent_kwd), even when it looks like a raw id (review Major).
clusterRow := map[string]interface{}{
"title_kwd": "cluster_abc12345",
"type_kwd": "nav_cluster",
"doc_count_int": 2,
}
cluster := ns.nodeFromRow(clusterRow, "cluster")
if cluster.Name != "cluster_abc12345" {
t.Errorf("cluster key = %q, want it kept verbatim as the parent_kwd lookup key", cluster.Name)
}
}
// TestNodeFromRow_LabelSource pins which column the nav tree renders: title_kwd
// (the summary's first line, the same label NavHit.Name carries to the model),
// overridden by an explicit readable `name` column when the row has one (Python's
// writer stores one; Go's rows do not). A cluster keeps its key from title_kwd.
func TestNodeFromRow_LabelSource(t *testing.T) {
ns := &NavService{}
cases := []struct {
name string
row map[string]interface{}
want string
}{
{
name: "the content title labels a document leaf",
row: map[string]interface{}{
"title_kwd": "三国名将事迹概要", "type_kwd": "nav_doc",
},
want: "三国名将事迹概要",
},
{
name: "the name column wins over the content title",
row: map[string]interface{}{
"name": "三国名将事迹概要", "title_kwd": "机器键_ab12cd34ef56", "type_kwd": "nav_doc",
},
want: "三国名将事迹概要",
},
{
name: "a cluster keeps its key from title_kwd",
row: map[string]interface{}{
"title_kwd": "三国名将事迹概要 3fdf14d0", "type_kwd": "nav_cluster", "doc_count_int": 3,
},
want: "三国名将事迹概要 3fdf14d0",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := ns.nodeFromRow(tc.row, "doc").Name; got != tc.want {
t.Errorf("nodeFromRow name = %q, want %q", got, tc.want)
}
})
}
}
// TestNavService_Search_ReturnsHit asserts acceptance #5.
func TestNavService_Search_ReturnsHit(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", "aaa")); err != nil {
t.Fatal(err)
}
hits, err := ns.Search(t.Context(), "t1", "kb1", "aaa", nil, nil, 5)
if err != nil {
t.Fatal(err)
}
if len(hits) == 0 {
t.Fatal("expected hits")
}
if hits[0].Name == "" {
t.Error("hit name empty")
}
}
// TestNavService_Search_DocScope pins search_dataset_nav's doc_scope semantics
// (dataset_nav.py:1364-1387, 1444-1465) on the nav-row read: a nav_doc leaf
// matches on doc_id, a nav_cluster row on coverage, a cluster's coverage is
// trimmed to the scope, and the scope is applied BEFORE the top_k truncation —
// a scoped read must not come back empty (or short) because out-of-scope rows
// ranked higher.
func TestNavService_Search_DocScope(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
const dim = 1024
vec := func(w float64) []float64 {
v := make([]float64, dim)
v[0] = w
return v
}
row := func(typ, docID, title string, docIDs []string, w float64) map[string]interface{} {
r := map[string]interface{}{
"compile_kwd": navCompileKwd,
"type_kwd": typ,
"doc_id": docID,
"title_kwd": title,
"q_1024_vec": vec(w),
}
if len(docIDs) > 0 {
r["doc_ids_kwd"] = docIDs
}
return r
}
// Three out-of-scope leaves outrank the single in-scope leaf (cosine 1.0 vs
// 0.5), so a scoped read truncated to one row only fills its cap if the
// scope is decided by the engine rather than after the truncation.
rows := []map[string]interface{}{
row(nav.TypeNavDoc, "dx1", "out 1", nil, 1),
row(nav.TypeNavDoc, "dx2", "out 2", nil, 1),
row(nav.TypeNavDoc, "dx3", "out 3", nil, 1),
row(nav.TypeNavDoc, "d1", "in scope", nil, 0.5),
row(nav.TypeNavCluster, "kb1", "covering d1+d2", []string{"d1", "d2"}, 0.4),
row(nav.TypeNavCluster, "kb1", "covering d2 only", []string{"d2"}, 1),
}
if _, err := eng.InsertChunks(t.Context(), rows, "", "kb1", ""); err != nil {
t.Fatal(err)
}
q := make([]float32, dim)
q[0] = 1
all, err := ns.Search(t.Context(), "t1", "kb1", "q", q, nil, 10)
if err != nil {
t.Fatal(err)
}
if len(all) != len(rows) {
t.Fatalf("unscoped hits = %d, want %d (nil scope must not restrict)", len(all), len(rows))
}
scoped, err := ns.Search(t.Context(), "t1", "kb1", "q", q, []string{" d1 "}, 10)
if err != nil {
t.Fatal(err)
}
var gotLeaf, gotCluster bool
for _, h := range scoped {
switch h.DocID {
case "d1":
gotLeaf = true
case "kb1":
gotCluster = true
if len(h.DocIDs) != 1 || h.DocIDs[0] != "d1" {
t.Errorf("cluster coverage = %v, want [d1] (trimmed to the scope)", h.DocIDs)
}
default:
t.Errorf("out-of-scope hit %q surfaced in a scoped read", h.DocID)
}
}
if !gotLeaf || !gotCluster {
t.Fatalf("scoped hits = %+v, want d1 plus the cluster covering it", scoped)
}
for _, h := range scoped {
if h.Name == "covering d2 only" {
t.Error("a cluster whose coverage does not intersect the scope must not surface")
}
}
// The scope is pushed into the query, not applied after the engine
// truncation: the top-ranked rows here are all out of scope, yet the
// in-scope leaf still comes back as the single hit.
one, err := ns.Search(t.Context(), "t1", "kb1", "q", q, []string{"d1"}, 1)
if err != nil {
t.Fatal(err)
}
if len(one) != 1 || one[0].DocID != "d1" {
t.Fatalf("top_k=1 scoped hits = %+v, want exactly the in-scope leaf d1", one)
}
}
// TestNavService_Search_DocScopeBeyondAnyPoolSize pins the engine-budget half of
// the scope contract: a scoped read must not come back empty just because more
// out-of-scope rows rank above every in-scope row than the engine budget can
// hold. The scope is pushed into the query as two type-pinned legs, so no pool
// size can hide an in-scope row — whereas the fixed 1000-row pool this read used
// to scan is exhausted by the 1200 out-of-scope rows below.
func TestNavService_Search_DocScopeBeyondAnyPoolSize(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
const dim = 4
vec := func(w float64) []float64 {
v := make([]float64, dim)
v[0] = w
return v
}
// 1200 out-of-scope leaves, all ranked above the in-scope rows (cosine 1.0
// vs 0.5 / 0.4).
rows := make([]map[string]interface{}, 0, 1202)
for i := 0; i < 1200; i++ {
rows = append(rows, map[string]interface{}{
"compile_kwd": navCompileKwd,
"type_kwd": nav.TypeNavDoc,
"doc_id": fmt.Sprintf("dx%d", i),
"title_kwd": fmt.Sprintf("out %d", i),
"q_4_vec": vec(1),
})
}
rows = append(rows,
map[string]interface{}{
"compile_kwd": navCompileKwd,
"type_kwd": nav.TypeNavDoc,
"doc_id": "d1",
"title_kwd": "in scope",
"q_4_vec": vec(0.5),
},
map[string]interface{}{
"compile_kwd": navCompileKwd,
"type_kwd": nav.TypeNavCluster,
"doc_id": "kb1",
"title_kwd": "covering d1+d2",
"doc_ids_kwd": []string{"d1", "d2"},
"q_4_vec": vec(0.4),
},
)
if _, err := eng.InsertChunks(t.Context(), rows, "", "kb1", ""); err != nil {
t.Fatal(err)
}
q := make([]float32, dim)
q[0] = 1
// Sanity: unscoped, the in-scope rows really do rank last, so a read that
// mixes the scope in only after the engine truncation comes back empty.
unscoped, err := ns.Search(t.Context(), "t1", "kb1", "q", q, nil, 2)
if err != nil {
t.Fatal(err)
}
if len(unscoped) != 2 {
t.Fatalf("unscoped hits = %d, want 2", len(unscoped))
}
for _, h := range unscoped {
if h.DocID == "d1" || h.DocID == "kb1" {
t.Fatalf("unscoped top 2 = %+v, want the two highest-ranked out-of-scope leaves", unscoped)
}
}
scoped, err := ns.Search(t.Context(), "t1", "kb1", "q", q, []string{"d1"}, 2)
if err != nil {
t.Fatal(err)
}
if len(scoped) != 2 || scoped[0].DocID != "d1" || scoped[1].DocID != "kb1" {
t.Fatalf("scoped hits = %+v, want [d1 (0.5), kb1 cluster (0.4)] despite 1200 higher-ranked out-of-scope rows", scoped)
}
if len(scoped[1].DocIDs) != 1 || scoped[1].DocIDs[0] != "d1" {
t.Errorf("cluster coverage = %v, want [d1] (trimmed to the scope)", scoped[1].DocIDs)
}
// A scope with no in-scope row at all stays empty rather than falling back
// to the out-of-scope pool.
none, err := ns.Search(t.Context(), "t1", "kb1", "q", q, []string{"d-absent"}, 2)
if err != nil {
t.Fatal(err)
}
if len(none) != 0 {
t.Fatalf("scoped hits for an absent doc = %+v, want none", none)
}
}
// TestNavService_Acceptance4_ListChildren asserts acceptance #4: ListChildren
// returns only the rows whose parent_kwd=name. Two docs with identical stub
// vectors merge into one root cluster: the first becomes the cluster itself,
// the second merges in as a nav_doc (parent_kwd=clusterName). So the cluster
// doc_count reflects both docs, and exactly one nav_doc sits under it.
func TestNavService_Acceptance4_ListChildren(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
// Two docs that merge into one root cluster (same first char -> identical
// stub vectors -> sim=1.0 >= merge threshold).
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", "aaa one")); err != nil {
t.Fatal(err)
}
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d2", "aaa two")); err != nil {
t.Fatal(err)
}
clusters, _, err := ns.ListClusters(t.Context(), "t1", "kb1", "", 0, 10)
if err != nil {
t.Fatal(err)
}
if len(clusters) != 1 {
t.Fatalf("expected 1 cluster, got %d", len(clusters))
}
if clusters[0].DocCount != 2 {
t.Fatalf("cluster doc_count = %d, want 2 (both docs merged into the cluster)", clusters[0].DocCount)
}
name := clusters[0].Name
children, total, err := ns.ListChildren(t.Context(), "t1", "kb1", name, "", 0, 10)
if err != nil {
t.Fatal(err)
}
// Every doc upserted under the cluster emits a nav_doc leaf (Python
// upsert_dataset_nav_doc), so d1 (which created the cluster) and d2 (which
// merged in) both sit under it: two nav_docs total.
if total != 2 || len(children) != 2 {
t.Fatalf("expected 2 children under cluster, got total=%d len=%d", total, len(children))
}
gotIDs := map[string]bool{}
for _, c := range children {
gotIDs[c.DocID] = true
if c.Type != "doc" {
t.Errorf("child type = %q, want doc", c.Type)
}
}
if !gotIDs["d1"] || !gotIDs["d2"] {
t.Errorf("expected nav_docs for both d1 and d2, got %v", gotIDs)
}
}
// TestNavService_NavDocDepth asserts a nav_doc merged under a root cluster
// (depth 0) gets depth_int = parentDepth+1 = 1, not a hard-coded value.
func TestNavService_NavDocDepth(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", "aaa one")); err != nil {
t.Fatal(err)
}
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d2", "aaa two")); err != nil {
t.Fatal(err)
}
// The nav_doc for d2 sits under the root cluster; its depth_int must be 1.
for _, row := range eng.rows {
if row["doc_id"] == "d2" {
if d, ok := row["depth_int"].(int); !ok || d != 1 {
t.Errorf("nav_doc d2 depth_int = %v, want 1 (parentDepth 0 + 1)", row["depth_int"])
}
}
}
}
// TestNavService_NavDocLabel pins the nav_doc leaf's label on both write sites:
// title_kwd carries the summary's first line, one column for both readers — the
// tree (nodeFromRow) and the model (NavHit.Name → the routed document's
// <summary>). No second label column is written.
func TestNavService_NavDocLabel(t *testing.T) {
summary := "三国名将事迹概要\n三国名将事迹概述:关羽斩颜良诛文丑。"
t.Run("the leaf label is the summary's first line", func(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", summary)); err != nil {
t.Fatalf("UpsertDoc: %v", err)
}
if got := navDocRowTitle(t, eng, "d1"); got != "三国名将事迹概要" {
t.Errorf("nav_doc title_kwd = %q, want the summary's first line", got)
}
if _, ok := navDocRow(t, eng, "d1")["docnm_kwd"]; ok {
t.Error("nav_doc carries a separate docnm_kwd label; the label lives in title_kwd")
}
})
t.Run("the merge path labels the leaf too", func(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
// d1 creates the root cluster; d2's summary embeds identically, so it
// merges into that cluster (the second nav_doc write site).
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", "aaa one")); err != nil {
t.Fatalf("UpsertDoc d1: %v", err)
}
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d2", "aaa two")); err != nil {
t.Fatalf("UpsertDoc d2: %v", err)
}
if got := navDocRowTitle(t, eng, "d2"); got != "aaa two" {
t.Errorf("merged nav_doc title_kwd = %q, want the summary's first line", got)
}
})
}
// TestNavService_UpsertDoc_RestoresContentLabel covers the recompile upgrade for
// legacy rows whose title_kwd holds the document file name (written by the
// earlier label rule): the refresh puts the leaf back on the summary's first
// line, in place (same row).
func TestNavService_UpsertDoc_RestoresContentLabel(t *testing.T) {
summary := "三国名将事迹概要\n三国名将事迹概述:关羽斩颜良诛文丑。"
eng := newMemNavEngine()
ns := newTestNav(eng)
in := navUpsertInput("t1", "kb1", "d1", summary)
if err := ns.UpsertDoc(t.Context(), in); err != nil {
t.Fatalf("UpsertDoc: %v", err)
}
// Simulate a legacy row whose leaf label holds the file name.
navDocRow(t, eng, "d1")["title_kwd"] = "三国人物.pdf"
if err := ns.UpsertDoc(t.Context(), in); err != nil {
t.Fatalf("re-upsert: %v", err)
}
if got := navDocRowTitle(t, eng, "d1"); got != "三国名将事迹概要" {
t.Errorf("nav_doc title_kwd = %q, want it restored to the summary's first line", got)
}
assertSingleNavDocRow(t, eng, "d1")
}
// TestNavService_UpsertDoc_PlacementBySimilarity pins where a similar-but-not-
// mergeable document opens its cluster, against the three similarity bands
// (Python _MERGE_THRESHOLD=0.80 / _MIN_SIM=0.50):
//
// - >= 0.80 → merge into the best cluster (the document leaf joins it);
// - < 0.80 → its own cluster, at the ROOT level when the best match is a
// root cluster (Python attaches it to the best cluster's parent, which is
// the root sentinel there), one level deeper when the best match is nested.
//
// The stub embedder's vectors are nearly collinear for any text, so the bands
// are driven with explicit vectors (UpsertDocInput.Embedd) and seeded cluster
// rows.
func TestNavService_UpsertDoc_PlacementBySimilarity(t *testing.T) {
const dim = 1024
navVec := navTestUnitVec
seedCluster := func(eng *memNavEngine, name, parentKwd string, depth int, vec []float64) {
row := map[string]interface{}{
"compile_kwd": navCompileKwd, "type_kwd": nav.TypeNavCluster,
"title_kwd": name, "parent_kwd": parentKwd, "depth_int": depth,
"doc_count_int": 0, "content_with_weight": `{"type":"nav_cluster","description":"topic"}`,
"q_1024_vec": vec,
}
if _, err := eng.InsertChunks(t.Context(), []map[string]interface{}{row}, "", "kb1", ""); err != nil {
t.Fatal(err)
}
}
findCluster := func(t *testing.T, eng *memNavEngine, parentKwd string) map[string]interface{} {
t.Helper()
for _, row := range eng.rows {
if row["type_kwd"] == nav.TypeNavCluster && row["parent_kwd"] == parentKwd {
return row
}
}
t.Fatalf("no nav_cluster row with parent_kwd=%q", parentKwd)
return nil
}
docRows := func(eng *memNavEngine, docID string) []map[string]interface{} {
out := []map[string]interface{}{}
for _, row := range eng.rows {
if row["type_kwd"] == nav.TypeNavDoc && row["doc_id"] == docID {
out = append(out, row)
}
}
return out
}
t.Run("an unrelated doc opens a root-level cluster", func(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
seedCluster(eng, "三国演义 aaaaaaaa", navRootParent, 0, navVec(1))
in := navUpsertInput("t1", "kb1", "d2", "出师表要义")
in.Embedd = f64ToF32Slice(navVec(0.60, 0.80)) // cos 0.60: related, not mergeable
if err := ns.UpsertDoc(t.Context(), in); err != nil {
t.Fatalf("UpsertDoc: %v", err)
}
// The seeded cluster keeps its name; the newly opened one is the other
// root-level cluster.
var opened map[string]interface{}
for _, row := range eng.rows {
if row["type_kwd"] == nav.TypeNavCluster && row["title_kwd"] != "三国演义 aaaaaaaa" {
opened = row
}
}
if opened == nil {
t.Fatal("no root-level cluster was opened for the unrelated document")
}
if opened["parent_kwd"] != navRootParent {
t.Errorf("new cluster parent_kwd = %v, want the root sentinel (top level, beside the existing cluster)", opened["parent_kwd"])
}
if d, _ := opened["depth_int"].(int); d != 0 {
t.Errorf("new cluster depth_int = %v, want 0 (a root cluster)", opened["depth_int"])
}
// Its document leaf sits one level below it.
rows := docRows(eng, "d2")
if len(rows) != 1 {
t.Fatalf("nav_doc rows for d2 = %d, want 1", len(rows))
}
if rows[0]["parent_kwd"] != opened["title_kwd"] {
t.Errorf("nav_doc parent = %v, want the new cluster %v", rows[0]["parent_kwd"], opened["title_kwd"])
}
if d, _ := rows[0]["depth_int"].(int); d != 1 {
t.Errorf("nav_doc depth_int = %v, want 1", rows[0]["depth_int"])
}
})
t.Run("a mergeable doc joins the best cluster", func(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
seedCluster(eng, "三国演义 aaaaaaaa", navRootParent, 0, navVec(1))
in := navUpsertInput("t1", "kb1", "d2", "三国名将")
in.Embedd = f64ToF32Slice(navVec(0.90, math.Sqrt(1-0.81))) // cos 0.90
if err := ns.UpsertDoc(t.Context(), in); err != nil {
t.Fatalf("UpsertDoc: %v", err)
}
rows := docRows(eng, "d2")
if len(rows) != 1 || rows[0]["parent_kwd"] != "三国演义 aaaaaaaa" {
t.Fatalf("nav_doc rows = %+v, want the leaf under the merged cluster", rows)
}
if clusters := countNavClusters(eng); clusters != 1 {
t.Errorf("nav_cluster rows = %d, want 1 (a merge must not open a cluster)", clusters)
}
})
t.Run("a nested best match keeps the child cluster", func(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
// Root cluster at cos 0.70 with the doc (>= _RECURSE_THRESHOLD, so the
// descent continues), nested cluster at 0.78 (< merge threshold, > the
// root's, so IT becomes the best match).
seedCluster(eng, "三国演义 aaaaaaaa", navRootParent, 0, navVec(1))
nested := "出师表要义 bbbbbbbb"
seedCluster(eng, nested, "三国演义 aaaaaaaa", 1, navVec(0.546, 0.5569, 0.6257))
in := navUpsertInput("t1", "kb1", "d3", "出师表陈情")
in.Embedd = f64ToF32Slice(navVec(0.70, 0.714)) // cos(root) 0.70, cos(child) 0.78
if err := ns.UpsertDoc(t.Context(), in); err != nil {
t.Fatalf("UpsertDoc: %v", err)
}
child := findCluster(t, eng, nested)
if d, _ := child["depth_int"].(int); d != 2 {
t.Errorf("new child cluster depth_int = %v, want 2 (best depth 1 + 1)", child["depth_int"])
}
rows := docRows(eng, "d3")
if len(rows) != 1 || rows[0]["parent_kwd"] != child["title_kwd"] {
t.Fatalf("nav_doc rows = %+v, want the leaf under the new child cluster %v", rows, child["title_kwd"])
}
if d, _ := rows[0]["depth_int"].(int); d != 3 {
t.Errorf("nav_doc depth_int = %v, want 3", rows[0]["depth_int"])
}
})
}
// navTestUnitVec builds a 1024-dim unit vector from the leading components (the
// rest zero), so a test can dial an exact cosine against a seeded cluster's
// vector. 1024 is the stub embedder's dimension.
func navTestUnitVec(components ...float64) []float64 {
v := make([]float64, 1024)
var norm float64
for i, c := range components {
v[i] = c
norm += c * c
}
if norm > 0 {
scale := 1 / math.Sqrt(norm)
for i := range v {
v[i] *= scale
}
}
return v
}
// TestNavService_FindBestCluster_DeepestMatchWins pins the descent result against
// Python _find_best_cluster: the returned match is the DEEPEST cluster reached
// while every step clears navRecurse (0.65) — not the strongest one seen — and a
// child below the threshold is not adopted at all. The placement branch decides
// from that (deeper, possibly lower) similarity, so this is what keeps the two
// implementations in step.
func TestNavService_FindBestCluster_DeepestMatchWins(t *testing.T) {
const (
rootName = "三国演义 aaaaaaaa"
childName = "出师表要义 bbbbbbbb"
)
seedCluster := func(eng *memNavEngine, name, parentKwd string, depth int, vec []float64) {
row := map[string]interface{}{
"compile_kwd": navCompileKwd, "type_kwd": nav.TypeNavCluster,
"title_kwd": name, "parent_kwd": parentKwd, "depth_int": depth,
"doc_count_int": 0, "content_with_weight": `{"type":"nav_cluster","description":"topic"}`,
"q_1024_vec": vec,
}
if _, err := eng.InsertChunks(t.Context(), []map[string]interface{}{row}, "", "kb1", ""); err != nil {
t.Fatal(err)
}
}
// doc/child pairs are built so the document's cosine against each seeded
// cluster vector is exactly the intended value.
cases := []struct {
name string
doc []float64
child []float64
wantName string
wantSim float64
wantDepth int
}{
{
// Root 0.85 (mergeable on its own) but the child still clears the
// recurse threshold at 0.70: Python descends and returns the CHILD,
// so the placement sees 0.70 and opens a new cluster instead of
// merging into the root.
name: "a recurseable descendant displaces a stronger ancestor",
doc: navTestUnitVec(0.85, 0.5268),
child: navTestUnitVec(0.595, 0.3688, 0.7141),
wantName: childName,
wantSim: 0.70,
wantDepth: 1,
},
{
// The child is below the threshold: it is not adopted at all, so the
// root (0.90) stays the answer and the document merges into it.
name: "a child below the recurse threshold is not adopted",
doc: navTestUnitVec(0.90, 0.4359),
child: navTestUnitVec(0.36, 0.1744, 0.9165),
wantName: rootName,
wantSim: 0.90,
wantDepth: 0,
},
{
// The root itself is returned even when it does not clear the
// threshold (Python seeds `best` with its top-1 root).
name: "an unrelated root is still returned",
doc: navTestUnitVec(0.40, 0.9165),
child: navTestUnitVec(0.36, 0.1744, 0.9165),
wantName: rootName,
wantSim: 0.40,
wantDepth: 0,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
seedCluster(eng, rootName, navRootParent, 0, navTestUnitVec(1))
seedCluster(eng, childName, rootName, 1, tc.child)
name, sim, depth, err := ns.findBestCluster(t.Context(), "t1", "kb1", f64ToF32Slice(tc.doc))
if err != nil {
t.Fatalf("findBestCluster: %v", err)
}
if name != tc.wantName || depth != tc.wantDepth {
t.Errorf("findBestCluster = (%q, %v, %d), want (%q, %v, %d)",
name, sim, depth, tc.wantName, tc.wantSim, tc.wantDepth)
}
if math.Abs(sim-tc.wantSim) > 1e-4 {
t.Errorf("findBestCluster sim = %v, want %v", sim, tc.wantSim)
}
})
}
}
// countNavClusters counts the nav_cluster rows of the mem engine.
func countNavClusters(eng *memNavEngine) int {
n := 0
for _, row := range eng.rows {
if row["type_kwd"] == nav.TypeNavCluster {
n++
}
}
return n
}
// f64ToF32Slice narrows an explicit test vector to the engine's float32 shape.
func f64ToF32Slice(in []float64) []float32 {
out := make([]float32, len(in))
for i, v := range in {
out[i] = float32(v)
}
return out
}
// assertSingleNavDocRow fails when docID has anything other than one nav_doc
// row: the label refresh must UPDATE, never duplicate the leaf.
func assertSingleNavDocRow(t *testing.T, eng *memNavEngine, docID string) {
t.Helper()
count := 0
for _, row := range eng.rows {
if row["type_kwd"] == "nav_doc" && row["doc_id"] == docID {
count++
}
}
if count != 1 {
t.Errorf("nav_doc rows for %s = %d, want 1 (refresh, not a duplicate)", docID, count)
}
}
// TestNavService_SummariesByDocIDs_DescriptionLabel pins the routed-document
// label — which callers render to the model as the document's <summary> — to the
// nav_doc's stored description, i.e. the document's own summary text (Python
// _nav_doc_summaries). The row's label is only the fallback: title_kwd carries
// the summary's first line, not the whole text.
func TestNavService_SummariesByDocIDs_DescriptionLabel(t *testing.T) {
summary := "三国名将事迹概要\n三国名将事迹概述:关羽斩颜良诛文丑。"
t.Run("the description wins over the tree label", func(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", summary)); err != nil {
t.Fatalf("UpsertDoc: %v", err)
}
got := ns.SummariesByDocIDs(t.Context(), "t1", "kb1", []string{"d1"})
if got["d1"] != summary {
t.Errorf("routed label = %q, want the stored description", got["d1"])
}
if got["d1"] == navDocRowTitle(t, eng, "d1") {
t.Error("routed label fell back to the tree label; the description must win")
}
})
t.Run("a row without a description falls back to its label", func(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
if _, err := eng.InsertChunks(t.Context(), []map[string]interface{}{
{
"compile_kwd": navCompileKwd, "type_kwd": nav.TypeNavDoc,
"doc_id": "d9", "title_kwd": "出师表全文内容与赏析",
"content_with_weight": `{"type":"nav_doc"}`,
},
}, "", "kb1", ""); err != nil {
t.Fatal(err)
}
got := ns.SummariesByDocIDs(t.Context(), "t1", "kb1", []string{"d9"})
if got["d9"] != "出师表全文内容与赏析" {
t.Errorf("label = %q, want the stored title_kwd fallback", got["d9"])
}
})
t.Run("a raw id is never a label", func(t *testing.T) {
const rawID = "6564be8a6564be8a6564be8a6564be8a"
eng := newMemNavEngine()
ns := newTestNav(eng)
if _, err := eng.InsertChunks(t.Context(), []map[string]interface{}{
{
"compile_kwd": navCompileKwd, "type_kwd": nav.TypeNavDoc,
"doc_id": rawID, "title_kwd": rawID,
"content_with_weight": `{"type":"nav_doc"}`,
},
}, "", "kb1", ""); err != nil {
t.Fatal(err)
}
got := ns.SummariesByDocIDs(t.Context(), "t1", "kb1", []string{rawID})
if _, ok := got[rawID]; ok {
t.Errorf("raw id used as a label: %+v", got)
}
})
}
// navDocRow returns the nav_doc row for docID.
func navDocRow(t *testing.T, eng *memNavEngine, docID string) map[string]interface{} {
t.Helper()
for _, row := range eng.rows {
if row["type_kwd"] == "nav_doc" && row["doc_id"] == docID {
return row
}
}
t.Fatalf("no nav_doc row for doc %s", docID)
return nil
}
// navDocRowTitle returns the title_kwd of the nav_doc row for docID.
func navDocRowTitle(t *testing.T, eng *memNavEngine, docID string) string {
t.Helper()
title, _ := navDocRow(t, eng, docID)["title_kwd"].(string)
return title
}
// TestNavService_RemoveDoc_CascadesToEmptyCluster covers A3: after removing a
// doc, a cluster left with no docs and no children is pruned (cleanupEmptyCluster),
// and the doc is dropped from its parent cluster's doc_ids_kwd.
func TestNavService_RemoveDoc_CascadesToEmptyCluster(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
// d1 creates a root cluster (name derived from its summary hash).
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", "alpha")); err != nil {
t.Fatal(err)
}
if err := ns.RemoveDoc(t.Context(), "t1", "kb1", "d1"); err != nil {
t.Fatal(err)
}
// The nav_doc is gone, and the root cluster (now empty) is pruned.
for _, row := range eng.rows {
if row["type_kwd"] == "nav_doc" && row["doc_id"] == "d1" {
t.Error("nav_doc for d1 should have been removed")
}
if row["type_kwd"] == "nav_cluster" && row["title_kwd"] != "" {
t.Error("root cluster should have been pruned when empty")
}
}
}
// TestNavService_MaybeSplitCluster_SplitsOverfull covers A2: a cluster with more
// than maxDocsPerCluster direct docs is split into two siblings. The overfull
// state is seeded directly (InsertChunks) rather than via UpsertDoc, because
// UpsertDoc triggers the split during seeding once the count crosses the
// threshold — the manual split trigger here must act on an already-overfull,
// not-yet-split cluster.
func TestNavService_MaybeSplitCluster_SplitsOverfull(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
clusterName := "root_cluster"
// Seed the overfull cluster directly: one nav_cluster (parent=root sentinel,
// depth 1) carrying 55 nav_doc children.
idx := sTestNavIndex(ns)
// The seeded rows carry the row ids production writes: nav addresses its
// clusters by id (navClusterID, exactly like Python's _nav_cluster_id), so a
// fixture without them would leave the locate/update/delete steps matching no
// row at all.
rows := []map[string]interface{}{
{
"id": navClusterID("t1", "kb1", clusterName),
"compile_kwd": navCompileKwd,
"available_int": 0,
"type_kwd": "nav_cluster",
"title_kwd": clusterName,
"parent_kwd": navRootParent,
"depth_int": 1,
"doc_count_int": 55, // over the maxDocsPerCluster=50 threshold
"doc_ids_kwd": []string{},
},
}
for i := 0; i < 55; i++ {
rows = append(rows, map[string]interface{}{
"id": navDocID("t1", "kb1", fmt.Sprintf("d%02d", i)),
"compile_kwd": navCompileKwd,
"available_int": 0,
"type_kwd": "nav_doc",
"title_kwd": fmt.Sprintf("d%02d", i),
"parent_kwd": clusterName,
"depth_int": 2,
"doc_id": fmt.Sprintf("d%02d", i),
"doc_count_int": 1,
})
}
if _, err := eng.InsertChunks(t.Context(), rows, idx, "kb1", ""); err != nil {
t.Fatal(err)
}
if err := ns.maybeSplitCluster(t.Context(), "t1", "kb1", clusterName, ""); err != nil {
t.Fatal(err)
}
splitA := clusterName + ":A"
splitB := clusterName + ":B"
foundA, foundB := false, false
var countA, countB int
var idsA, idsB []string
for _, row := range eng.rows {
if row["type_kwd"] == "nav_cluster" && row["title_kwd"] == splitA {
foundA = true
countA = intValAny(row["doc_count_int"])
idsA = firstStringSlice(row["doc_ids_kwd"])
}
if row["type_kwd"] == "nav_cluster" && row["title_kwd"] == splitB {
foundB = true
countB = intValAny(row["doc_count_int"])
idsB = firstStringSlice(row["doc_ids_kwd"])
}
}
if !foundA || !foundB {
t.Errorf("split clusters :A / :B missing (A=%v B=%v)", foundA, foundB)
}
// Review issue 5: the split clusters must inherit the aggregate doc count so
// they stay searchable and support deletion bookkeeping — they must not be
// empty shells.
if countA == 0 && countB == 0 {
t.Errorf("split clusters must carry aggregate doc_count_int (A=%d B=%d)", countA, countB)
}
if countA+countB != 55 {
t.Errorf("split clusters must preserve all 55 docs (A=%d B=%d)", countA, countB)
}
if len(idsA)+len(idsB) != 55 {
t.Errorf("split clusters must preserve all 55 doc ids (A=%v B=%v)", idsA, idsB)
}
// Review issue 5/6: every child must be reparented under :A or :B, and the
// original cluster must be gone (not left orphaned).
for _, row := range eng.rows {
if row["type_kwd"] == "nav_doc" {
p, _ := row["parent_kwd"].(string)
if p != splitA && p != splitB {
t.Errorf("nav_doc %v left orphaned under parent %q", row["title_kwd"], p)
}
}
}
origGone := true
for _, row := range eng.rows {
if row["type_kwd"] == "nav_cluster" && row["title_kwd"] == clusterName {
origGone = false
}
}
if !origGone {
t.Error("original cluster should have been deleted after split")
}
// A production nav_doc has doc_id but no doc_ids_kwd. Removing one after a
// split must update the replacement cluster that inherited its membership.
if err := ns.RemoveDoc(t.Context(), "t1", "kb1", "d00"); err != nil {
t.Fatalf("RemoveDoc after split: %v", err)
}
var remainingCount, remainingIDs int
for _, row := range eng.rows {
if row["type_kwd"] != "nav_cluster" {
continue
}
remainingCount += intValAny(row["doc_count_int"])
for _, id := range firstStringSlice(row["doc_ids_kwd"]) {
if id == "d00" {
t.Errorf("removed doc d00 still present in split cluster membership")
}
remainingIDs++
}
}
if remainingCount != 54 || remainingIDs != 54 {
t.Errorf("RemoveDoc after split must update count and membership: count=%d ids=%d", remainingCount, remainingIDs)
}
}
// stubNavMergeLLM is a canned nav.NavMergeLLM: it names every new cluster with
// the configured topic title and fuses merges into the configured text.
type stubNavMergeLLM struct {
name string
summary string
merged string
mergeSeen [][]string
}
func (s *stubNavMergeLLM) CreateSummary(_ context.Context, _, _ string) (string, string, error) {
return s.name, s.summary, nil
}
func (s *stubNavMergeLLM) Merge(_ context.Context, _ string, texts []string) (string, error) {
s.mergeSeen = append(s.mergeSeen, texts)
return s.merged, nil
}
// recordingNavEmbedder records every embedded text so a test can assert that a
// rewritten cluster description was re-embedded.
type recordingNavEmbedder struct {
texts []string
}
func (e *recordingNavEmbedder) Encode(ctx context.Context, tenantID string, texts []string) ([][]float32, error) {
e.texts = append(e.texts, texts...)
return stubNavEmbedder{}.Encode(ctx, tenantID, texts)
}
// navClusterRow returns the first nav_cluster row of the mem engine.
func navClusterRow(t *testing.T, eng *memNavEngine) map[string]interface{} {
t.Helper()
for _, row := range eng.rows {
if row["type_kwd"] == "nav_cluster" {
return row
}
}
t.Fatal("no nav_cluster row")
return nil
}
// navRowDescription parses a nav row payload's description.
func navRowDescription(t *testing.T, row map[string]interface{}) string {
t.Helper()
raw, _ := row["content_with_weight"].(string)
var m map[string]interface{}
if err := json.Unmarshal([]byte(raw), &m); err != nil {
t.Fatalf("parse nav payload %q: %v", raw, err)
}
desc, _ := m["description"].(string)
return desc
}
// TestNavService_LLMClusterNaming pins the wired naming path: the cluster takes
// the model's topic title as the title part and keeps the " <8-hex>" suffix —
// the name is also the cluster key (parent_kwd / row id), so it must stay unique
// per KB — and the model's summary becomes the cluster's description.
func TestNavService_LLMClusterNaming(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
ns.SetNavMergeLLM(&stubNavMergeLLM{name: "三国名将事迹", summary: "三国名将事迹概览。"})
summary := "三国名将事迹概要\n正文"
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", summary)); err != nil {
t.Fatalf("UpsertDoc: %v", err)
}
cluster := navClusterRow(t, eng)
if want := readableClusterName("三国名将事迹", summary); cluster["title_kwd"] != want {
t.Errorf("cluster title_kwd = %v, want %q (topic title + uniqueness suffix)", cluster["title_kwd"], want)
}
if got := navRowDescription(t, cluster); got != "三国名将事迹概览。" {
t.Errorf("cluster description = %q, want the model summary", got)
}
}
// TestNavService_MergeFusesClusterDescription pins the wired merge path: a
// document that joins an existing cluster fuses its summary into the cluster
// description (Python _llm_merge) and re-embeds the rewritten description, so
// later placements score against the merged topic.
func TestNavService_MergeFusesClusterDescription(t *testing.T) {
eng := newMemNavEngine()
embedder := &recordingNavEmbedder{}
ns := NewNavService(embedder)
ns.engine = eng
stub := &stubNavMergeLLM{name: "topic", summary: "first doc summary", merged: "fused description"}
ns.SetNavMergeLLM(stub)
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", "aaa one")); err != nil {
t.Fatalf("UpsertDoc d1: %v", err)
}
// d2's summary embeds identically under the deterministic stub embedder, so
// it is placed inside d1's cluster (the merge branch).
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d2", "aaa two")); err != nil {
t.Fatalf("UpsertDoc d2: %v", err)
}
clusters := 0
for _, row := range eng.rows {
if row["type_kwd"] == "nav_cluster" {
clusters++
}
}
if clusters != 1 {
t.Fatalf("nav_cluster rows = %d, want 1 (d2 must merge, not create a cluster)", clusters)
}
cluster := navClusterRow(t, eng)
if got := navRowDescription(t, cluster); got != "fused description" {
t.Errorf("cluster description = %q, want the merged text", got)
}
if ids := firstStringSlice(cluster["doc_ids_kwd"]); len(ids) != 2 {
t.Errorf("cluster doc_ids_kwd = %v, want both documents", ids)
}
if len(stub.mergeSeen) != 1 {
t.Fatalf("Merge calls = %d, want 1", len(stub.mergeSeen))
}
if texts := stub.mergeSeen[0]; len(texts) != 2 || texts[0] != "first doc summary" || texts[1] != "aaa two" {
t.Errorf("Merge texts = %v, want [existing description, new summary]", texts)
}
reEmbedded := false
for _, text := range embedder.texts {
if text == "fused description" {
reEmbedded = true
break
}
}
if !reEmbedded {
t.Errorf("merged description was not re-embedded; embedded texts = %v", embedder.texts)
}
}
// TestNavService_MergeKeepsDescriptionWithoutLLM pins the no-LLM fallback:
// without a NavMergeLLM the cluster keeps the description it was created with
// (Python _llm_merge returns the existing text when chat_mdl is nil) instead of
// accumulating a concatenation of every document summary.
func TestNavService_MergeKeepsDescriptionWithoutLLM(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", "aaa one")); err != nil {
t.Fatalf("UpsertDoc d1: %v", err)
}
cluster := navClusterRow(t, eng)
before := navRowDescription(t, cluster)
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d2", "aaa two")); err != nil {
t.Fatalf("UpsertDoc d2: %v", err)
}
if got := navRowDescription(t, cluster); got != before {
t.Errorf("cluster description = %q, want it unchanged (%q) without an LLM", got, before)
}
if ids := firstStringSlice(cluster["doc_ids_kwd"]); len(ids) != 2 {
t.Errorf("cluster doc_ids_kwd = %v, want both documents", ids)
}
}
// sTestNavIndex returns the nav index name for a test NavService (tenant "t1").
func sTestNavIndex(ns *NavService) string {
return "ragflow_t1"
}
func navUpsertInput(tenant, kb, doc, summary string) nav.UpsertDocInput {
return nav.UpsertDocInput{TenantID: tenant, KbID: kb, DocID: doc, Summary: summary}
}
// intValAny coerces a stored integer value (int/int64/float64) from the mem
// engine row into an int for assertions.
func intValAny(v any) int {
switch n := v.(type) {
case int:
return n
case int64:
return int(n)
case float64:
return int(n)
case float32:
return int(n)
}
return 0
}
// TestNavService_ReadsIncludeUnavailableRows pins that nav reads opt out of the
// retrieval-only available_int=1 default Infinity applies to every MATCH query:
// nav rows carry available_int=0, so without it the cluster descent and navScan
// would see an empty tree. ES never filters available_int.
func TestNavService_ReadsIncludeUnavailableRows(t *testing.T) {
eng := newMemNavEngine()
ns := newTestNav(eng)
if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", "aaa")); err != nil {
t.Fatal(err)
}
if len(eng.rows) == 0 {
t.Fatal("UpsertDoc wrote no nav row")
}
if v := eng.rows[0]["available_int"]; v != 0 {
t.Fatalf("nav row available_int = %#v, want 0", v)
}
if _, _, err := ns.ListClusters(t.Context(), "t1", "kb1", "", 0, 10); err != nil {
t.Fatal(err)
}
if len(eng.searches) == 0 {
t.Fatal("ListClusters issued no search")
}
for i, req := range eng.searches {
if !req.IncludeUnavailable {
t.Errorf("search %d did not opt out of the available_int=1 default (SelectFields=%#v)", i, req.SelectFields)
}
}
}
// TestNavService_MultiTokenClusterUpdatesByRowID pins the write path for a
// cluster whose label is multi-token and whose title_kwd is empty. Such a row is
// addressable only by its deterministic row id: a name filter on Infinity matched
// nothing, so the membership/count update and the cleanup lookup silently
// no-op'd.
func TestNavService_MultiTokenClusterUpdatesByRowID(t *testing.T) {
const clusterName = "Imperial Memorial and Governance Advice 59cbfbef"
clusterRowID := navClusterID("t1", "kb1", clusterName)
eng := newMemNavEngine()
eng.rows = append(eng.rows,
map[string]interface{}{
"id": clusterRowID,
"kb_id": "kb1", "compile_kwd": navCompileKwd, "type_kwd": "nav_cluster",
"available_int": 0,
// The legacy Infinity layout: the label only reached docnm.
"title_kwd": "", "docnm_kwd": clusterName,
"parent_kwd": navRootParent, "depth_int": 1,
"doc_count_int": 2, "doc_ids_kwd": []string{"d1", "d2"},
"content_with_weight": `{"description":"two memorials"}`,
},
map[string]interface{}{
"id": navDocID("t1", "kb1", "d1"),
"kb_id": "kb1", "compile_kwd": navCompileKwd, "type_kwd": "nav_doc",
"available_int": 0, "title_kwd": "memorial of d1",
"parent_kwd": clusterName, "depth_int": 2,
"doc_id": "d1", "doc_count_int": 1,
})
ns := newTestNav(eng)
// The read side must answer the stored key so the frontend can expand it.
clusters, _, err := ns.ListClusters(context.Background(), "t1", "kb1", "", 0, 10)
if err != nil {
t.Fatalf("ListClusters: %v", err)
}
if len(clusters) != 1 || clusters[0].Name != clusterName {
t.Fatalf("clusters = %#v, want the stored key %q", clusters, clusterName)
}
if err := ns.RemoveDoc(context.Background(), "t1", "kb1", "d1"); err != nil {
t.Fatalf("RemoveDoc: %v", err)
}
row := navRowByID(eng, clusterRowID)
if row == nil {
t.Fatal("cluster row vanished")
}
if got := intValAny(row["doc_count_int"]); got != 1 {
t.Errorf("cluster doc_count_int = %d, want 1 (the update must reach a row whose title_kwd is empty)", got)
}
if ids := firstStringSlice(row["doc_ids_kwd"]); len(ids) != 1 || ids[0] != "d2" {
t.Errorf("cluster doc_ids_kwd = %v, want [d2]", ids)
}
}
// TestNavService_MaybeSplitClusterRefusesUnidentifiableChild pins the guard that
// dropping blank keyword values made necessary: a child with neither a row id nor
// a document id must abort the split. Falling back to a label would leave a
// type-only condition, and with the blank label dropped before rendering that
// condition reparents every row of that type in the dataset instead of failing.
func TestNavService_MaybeSplitClusterRefusesUnidentifiableChild(t *testing.T) {
const clusterName = "overfull_no_ids"
eng := newMemNavEngine()
eng.rows = append(eng.rows, map[string]interface{}{
"id": navClusterID("t1", "kb1", clusterName), "kb_id": "kb1",
"compile_kwd": navCompileKwd, "type_kwd": "nav_cluster",
"title_kwd": clusterName, "docnm_kwd": clusterName,
"parent_kwd": navRootParent, "depth_int": 1,
"doc_count_int": navMaxDocsPerCluster + 1, "doc_ids_kwd": []string{},
})
// Directly seeded (not via InsertChunks) so they carry NO row id, and no
// doc_id either: every fallback the rehome could use is unavailable.
for i := 0; i <= navMaxDocsPerCluster; i++ {
eng.rows = append(eng.rows, map[string]interface{}{
"kb_id": "kb1", "compile_kwd": navCompileKwd, "type_kwd": "nav_doc",
"title_kwd": fmt.Sprintf("kid %02d", i), "parent_kwd": clusterName,
"depth_int": 2, "doc_count_int": 1,
})
}
ns := newTestNav(eng)
if err := ns.maybeSplitCluster(context.Background(), "t1", "kb1", clusterName, ""); err == nil {
t.Fatal("a child without a row id or document id must abort the split")
}
// Nothing may be reparented, and the original cluster must still be there.
reparented := 0
originalPresent := false
for _, row := range eng.rows {
if row["type_kwd"] == "nav_cluster" && row["title_kwd"] == clusterName {
originalPresent = true
}
if p, _ := row["parent_kwd"].(string); strings.HasSuffix(p, ":A") || strings.HasSuffix(p, ":B") {
reparented++
}
}
if reparented != 0 {
t.Errorf("%d rows were reparented by a type-only condition", reparented)
}
if !originalPresent {
t.Error("the original cluster must not be deleted when the split aborts")
}
}
// TestNavService_MaybeSplitClusterValidatesEveryChildFirst pins the pre-pass: an
// unaddressable child anywhere in the list must stop the split before the first
// write. The rehome points children at splitA/splitB, whose rows are inserted
// only after the original cluster is deleted, so aborting mid-loop would leave
// the already-moved children hanging off a name no query can reach.
func TestNavService_MaybeSplitClusterValidatesEveryChildFirst(t *testing.T) {
const clusterName = "overfull_second_child_broken"
eng := newMemNavEngine()
eng.rows = append(eng.rows, map[string]interface{}{
"id": navClusterID("t1", "kb1", clusterName), "kb_id": "kb1",
"compile_kwd": navCompileKwd, "type_kwd": "nav_cluster",
"title_kwd": clusterName, "docnm_kwd": clusterName,
"parent_kwd": navRootParent, "depth_int": 1,
"doc_count_int": navMaxDocsPerCluster + 1, "doc_ids_kwd": []string{},
})
// The first child IS addressable, so a loop that validated lazily would have
// reparented it before reaching the broken child below.
eng.rows = append(eng.rows, map[string]interface{}{
"id": navDocID("t1", "kb1", "d0"), "kb_id": "kb1", "compile_kwd": navCompileKwd,
"type_kwd": "nav_doc", "title_kwd": "good child", "doc_id": "d0",
"parent_kwd": clusterName, "depth_int": 2, "doc_count_int": 1,
})
for i := 1; i <= navMaxDocsPerCluster; i++ {
eng.rows = append(eng.rows, map[string]interface{}{
"kb_id": "kb1", "compile_kwd": navCompileKwd, "type_kwd": "nav_doc",
"title_kwd": fmt.Sprintf("broken %02d", i), "parent_kwd": clusterName,
"depth_int": 2, "doc_count_int": 1,
})
}
ns := newTestNav(eng)
if err := ns.maybeSplitCluster(context.Background(), "t1", "kb1", clusterName, ""); err == nil {
t.Fatal("an unaddressable child must abort the split")
}
for _, row := range eng.rows {
if p, _ := row["parent_kwd"].(string); strings.HasSuffix(p, ":A") || strings.HasSuffix(p, ":B") {
t.Fatalf("row %v was reparented before every child had been validated", row["id"])
}
}
if navRowByID(eng, navClusterID("t1", "kb1", clusterName)) == nil {
t.Error("the original cluster must not be deleted when the split aborts")
}
}
// navRowByID returns the stored row with the given id, or nil.
func navRowByID(eng *memNavEngine, id string) map[string]interface{} {
for _, r := range eng.rows {
if s, _ := r["id"].(string); s == id {
return r
}
}
return nil
}
// TestNavService_LabelsFallBackToDocnm pins the label read for rows persisted
// before Infinity kept title_kwd as its own column (the label reached docnm
// only). The name must be the STORED key, not a display fallback: the frontend
// looks children up with it, so a description-derived name left the tree flat.
func TestNavService_LabelsFallBackToDocnm(t *testing.T) {
const clusterName = "忠臣进谏与托孤遗志 27577543"
eng := newMemNavEngine()
eng.rows = append(eng.rows,
map[string]interface{}{
"id": "dataset_nav_cluster_1", "compile_kwd": navCompileKwd, "type_kwd": "nav_cluster",
"kb_id": "kb1", "available_int": 0, "title_kwd": "", "docnm_kwd": clusterName,
"parent_kwd": "root", "depth_int": 0, "doc_count_int": 1, "doc_ids_kwd": []string{"d1"},
},
map[string]interface{}{
"id": "dataset_nav_doc_1", "compile_kwd": navCompileKwd, "type_kwd": "nav_doc",
"kb_id": "kb1", "available_int": 0, "title_kwd": "", "docnm_kwd": "出师表中的忠诚与北伐决心",
"parent_kwd": clusterName, "depth_int": 1, "doc_count_int": 1, "doc_id": "d1",
})
ns := newTestNav(eng)
clusters, _, err := ns.ListClusters(context.Background(), "t1", "kb1", "", 0, 10)
if err != nil {
t.Fatalf("ListClusters: %v", err)
}
if len(clusters) != 1 {
t.Fatalf("clusters = %#v, want exactly one root cluster", clusters)
}
if clusters[0].Name != clusterName {
t.Fatalf("cluster name = %q, want the stored key %q", clusters[0].Name, clusterName)
}
if !clusters[0].HasChildren {
t.Error("cluster must expose has_children so the frontend can expand it")
}
// The frontend expands with the name it was given.
children, _, err := ns.ListChildren(context.Background(), "t1", "kb1", clusters[0].Name, "", 0, 10)
if err != nil {
t.Fatalf("ListChildren: %v", err)
}
if len(children) != 1 {
t.Fatalf("children = %#v, want the doc leaf", children)
}
if children[0].Name != "出师表中的忠诚与北伐决心" || children[0].DocID != "d1" {
t.Fatalf("child = %#v, want the doc leaf labelled from docnm_kwd", children[0])
}
}