chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)

This commit is contained in:
runny committed 2026-11-13 17:54:56 +08:00
commit 9097ee699d
5769 files changed
+1446466

No files matched your search

@@ -0,0 +1,192 @@
// Package neo4j implements the knowledge graph storage and query adapters.
package neo4j
import (
"context"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
)
// NewGraphSearchRepository constructs the bounded public-query adapter.
func NewGraphSearchRepository(driver neo4j.Driver) interfaces.GraphSearchRepository {
return &Neo4jRepository{driver: driver, nodePrefix: "ENTITY"}
}
// graphSearchProjection bounds fields before they cross Bolt. One extra item
// (or character) lets the service report clipping instead of a false total.
func graphSearchProjection(alias string) string {
return alias + ` {
id: elementId(` + alias + `),
name: substring(` + alias + `.name, 0, 513),
knowledge_id: substring(` + alias + `.kg, 0, 129),
chunks: [c IN ` + alias + `.chunks[..513] | substring(c, 0, 129)],
attributes: [a IN ` + alias + `.attributes[..21] | substring(a, 0, 1001)]
}`
}
// graphSearchLabel quotes every identifier. KB IDs are data, never Cypher,
// including imported/legacy IDs containing punctuation or backticks.
func (n *Neo4jRepository) graphSearchLabel(namespace types.NameSpace) (string, error) {
if namespace.KnowledgeBase == "" || namespace.Knowledge != "" {
return "", fmt.Errorf("graph search requires exactly one knowledge base")
}
labels := n.Labels(namespace)
for i, label := range labels {
labels[i] = "`" + strings.ReplaceAll(label, "`", "``") + "`"
}
return strings.Join(labels, ":"), nil
}
// SearchGraph returns ranked seed entities and a bounded one-hop neighbourhood.
func (n *Neo4jRepository) SearchGraph(
ctx context.Context, namespace types.NameSpace, query string,
) (*types.GraphSearchCandidates, error) {
if n.driver == nil {
return nil, nil // Distinguished from an available backend with no matches.
}
label, err := n.graphSearchLabel(namespace)
if err != nil {
return nil, err
}
session := n.driver.NewSession(ctx, neo4j.SessionConfig{AccessMode: neo4j.AccessModeRead})
defer func() {
if err := session.Close(ctx); err != nil {
logger.Warnf(ctx, "Failed to close graph query session: %v", err)
}
}()
value, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
out := &types.GraphSearchCandidates{Graph: &types.GraphData{}}
seedResult, err := tx.Run(ctx, `
MATCH (n:`+label+`)
WHERE n.name CONTAINS $query
WITH n ORDER BY CASE WHEN n.name = $query THEN 0 ELSE 1 END,
size(n.name), n.name, n.kg, elementId(n)
LIMIT $probeLimit
RETURN `+graphSearchProjection("n")+` AS n`,
map[string]any{"query": query, "probeLimit": types.GraphSearchMaxSeeds + 1})
if err != nil {
return nil, err
}
seedIDs := []string{}
seen := map[string]bool{}
for seedResult.Next(ctx) {
if len(seedIDs) == types.GraphSearchMaxSeeds {
out.TruncationReasons = append(out.TruncationReasons, "candidate_seeds")
continue
}
node, err := decodeGraphSearchProjection(seedResult.Record(), "n")
if err != nil {
return nil, err
}
seedIDs = append(seedIDs, node.ID)
seen[node.ID] = true
out.Graph.Node = append(out.Graph.Node, node)
}
if err := seedResult.Err(); err != nil {
return nil, err
}
if len(seedIDs) == 0 {
return out, nil
}
// Keep relation-less seeds, and expand each stored edge only from its
// earliest seed. Target matches cannot reverse the stored direction or
// fill the budget twice. Both endpoints must carry the KB label.
rows, err := tx.Run(ctx, `
UNWIND range(0, size($seeds) - 1) AS seed_index
MATCH (n:`+label+`) WHERE elementId(n) = $seeds[seed_index]
MATCH (n)-[r]-(m:`+label+`)
WHERE NOT elementId(m) IN $seeds[0..seed_index]
WITH n, r, m, seed_index ORDER BY seed_index, elementId(r)
LIMIT $probeLimit
RETURN `+graphSearchProjection("n")+` AS n, `+graphSearchProjection("m")+` AS m,
elementId(r) AS id, elementId(startNode(r)) AS source_id,
elementId(endNode(r)) AS target_id, substring(type(r), 0, 129) AS type`,
map[string]any{"seeds": seedIDs, "probeLimit": types.GraphSearchMaxRows + 1})
if err != nil {
return nil, err
}
count := 0
for rows.Next(ctx) {
if count == types.GraphSearchMaxRows {
out.TruncationReasons = append(out.TruncationReasons, "candidate_relations")
continue
}
count++
for _, alias := range []string{"n", "m"} {
node, err := decodeGraphSearchProjection(rows.Record(), alias)
if err != nil {
return nil, err
}
if !seen[node.ID] {
out.Graph.Node = append(out.Graph.Node, node)
seen[node.ID] = true
}
}
relation := &types.GraphRelation{}
for field, dest := range map[string]*string{
"id": &relation.ID, "source_id": &relation.SourceID,
"target_id": &relation.TargetID, "type": &relation.Type,
} {
v, _, err := neo4j.GetRecordValue[string](rows.Record(), field)
if err != nil || v == "" {
return nil, fmt.Errorf("invalid graph relationship field %s", field)
}
*dest = v
}
if !seen[relation.SourceID] || !seen[relation.TargetID] {
return nil, fmt.Errorf("graph relationship has an unreturned endpoint")
}
out.Graph.Relation = append(out.Graph.Relation, relation)
}
if err := rows.Err(); err != nil {
return nil, err
}
return out, nil
}, neo4j.WithTxTimeout(types.GraphSearchTimeout))
if err != nil {
return nil, err
}
return value.(*types.GraphSearchCandidates), nil
}
func decodeGraphSearchProjection(record *neo4j.Record, alias string) (*types.GraphNode, error) {
if record == nil {
return nil, fmt.Errorf("nil graph search record")
}
value, ok := record.Get(alias)
props, isMap := value.(map[string]any)
if !ok || !isMap {
return nil, fmt.Errorf("invalid graph node projection")
}
node := &types.GraphNode{}
for key, dest := range map[string]*string{"id": &node.ID, "name": &node.Name, "knowledge_id": &node.KnowledgeID} {
value, ok := props[key].(string)
if !ok || value == "" {
return nil, fmt.Errorf("graph node has no %s", key)
}
*dest = value
}
for key, dest := range map[string]*[]string{"chunks": &node.Chunks, "attributes": &node.Attributes} {
*dest = []string{}
if props[key] == nil {
continue
}
values, ok := props[key].([]any)
if !ok {
return nil, fmt.Errorf("invalid graph node %s", key)
}
for _, value := range values {
text, ok := value.(string)
if !ok {
return nil, fmt.Errorf("invalid graph node %s item", key)
}
*dest = append(*dest, text)
}
}
return node, nil
}
@@ -0,0 +1,169 @@
package neo4j
import (
"context"
"fmt"
"os"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGraphSearchLabelAndDisabledBackend(t *testing.T) {
repo := &Neo4jRepository{nodePrefix: "ENTITY"}
label, err := repo.graphSearchLabel(types.NameSpace{KnowledgeBase: "kb-`):MATCH (x)"})
require.NoError(t, err)
require.Equal(t, "`ENTITYkb_``):MATCH (x)`", label)
_, err = repo.graphSearchLabel(types.NameSpace{})
require.Error(t, err)
_, err = repo.graphSearchLabel(types.NameSpace{KnowledgeBase: "kb", Knowledge: "doc"})
require.Error(t, err)
result, err := repo.SearchGraph(context.Background(), types.NameSpace{KnowledgeBase: "kb"}, "Acme")
require.NoError(t, err)
require.Nil(t, result)
}
func TestGraphSearchProjectionValidation(t *testing.T) {
valid := map[string]any{
"id": "n", "name": "Acme", "knowledge_id": "doc",
"chunks": []any{"c1"}, "attributes": []any{"attr"},
}
record := &neo4j.Record{Keys: []string{"n"}, Values: []any{valid}}
node, err := decodeGraphSearchProjection(record, "n")
require.NoError(t, err)
require.Equal(t, []string{"c1"}, node.Chunks)
_, err = decodeGraphSearchProjection(nil, "n")
require.Error(t, err)
for _, key := range []string{"id", "name", "knowledge_id", "chunks", "attributes"} {
props := map[string]any{}
for k, v := range valid {
props[k] = v
}
props[key] = 17
_, err = decodeGraphSearchProjection(&neo4j.Record{Keys: []string{"n"}, Values: []any{props}}, "n")
require.Error(t, err, key)
}
}
func TestGraphSearchIntegration(t *testing.T) {
uri := os.Getenv("WEKNORA_NEO4J_TEST_URI")
if uri == "" {
t.Skip("set WEKNORA_NEO4J_TEST_URI to run the live public graph-query regression")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
driver, err := neo4j.NewDriver(uri, neo4j.NoAuth())
require.NoError(t, err)
t.Cleanup(func() { assert.NoError(t, driver.Close(context.Background())) })
require.NoError(t, driver.VerifyConnectivity(ctx))
repo := NewGraphSearchRepository(driver).(*Neo4jRepository)
// Exercise escaping against a real engine, not only a string assertion.
ns := types.NameSpace{KnowledgeBase: fmt.Sprintf("public_graph_%d_`", time.Now().UnixNano())}
label, err := repo.graphSearchLabel(ns)
require.NoError(t, err)
outsideLabel, err := repo.graphSearchLabel(types.NameSpace{KnowledgeBase: ns.KnowledgeBase + "_outside"})
require.NoError(t, err)
t.Cleanup(func() {
cleanupCtx, stop := context.WithTimeout(context.Background(), 10*time.Second)
defer stop()
_, err := neo4j.ExecuteQuery(cleanupCtx, driver, "MATCH (n:"+label+") DETACH DELETE n",
nil, neo4j.EagerResultTransformer)
assert.NoError(t, err)
})
_, err = neo4j.ExecuteQuery(ctx, driver, `
CREATE (a:`+label+` {name:'Acme', kg:'doc1', chunks:['c1'], attributes:['attr1']}),
(b:`+label+` {name:'Acme Shanghai', kg:'doc1', chunks:['c1'], attributes:[]}),
(a2:`+label+` {name:'Acme', kg:'doc2', chunks:['c2'], attributes:['attr2']}),
(b2:`+label+` {name:'Acme Shanghai', kg:'doc2', chunks:['c2'], attributes:[]}),
(isolated:`+label+` {name:'Isolated', kg:'doc1', chunks:['c1'], attributes:[]}),
(outside:`+outsideLabel+` {name:'Outside', kg:'secret', chunks:['secret']}),
(a)-[:HEADQUARTERED_IN]->(b), (b)-[:RELATED_TO]->(a), (a)-[:SELF]->(a),
(a2)-[:HAS_BRANCH_IN]->(b2), (a)-[:MUST_NOT_LEAK]->(outside)
`, nil, neo4j.EagerResultTransformer)
require.NoError(t, err)
t.Cleanup(func() {
_, err := neo4j.ExecuteQuery(context.Background(), driver,
"MATCH (n:"+outsideLabel+") DETACH DELETE n", nil, neo4j.EagerResultTransformer)
assert.NoError(t, err)
})
for _, query := range []string{"Acme", "Shanghai"} {
result, err := repo.SearchGraph(ctx, ns, query)
require.NoError(t, err)
require.Len(t, result.Graph.Node, 4)
expectedRelations := 4
if query == "Shanghai" {
expectedRelations = 3 // Self-loop is outside this one-hop neighbourhood.
}
require.Len(t, result.Graph.Relation, expectedRelations)
names := map[string]string{}
for _, node := range result.Graph.Node {
names[node.ID] = node.Name
}
for _, relation := range result.Graph.Relation {
require.NotEqual(t, "MUST_NOT_LEAK", relation.Type)
if relation.Type == "HEADQUARTERED_IN" {
require.Equal(t, "Acme", names[relation.SourceID])
require.Equal(t, "Acme Shanghai", names[relation.TargetID])
}
}
require.Empty(t, result.TruncationReasons)
}
isolated, err := repo.SearchGraph(ctx, ns, "Isolated")
require.NoError(t, err)
require.Len(t, isolated.Graph.Node, 1)
require.Empty(t, isolated.Graph.Relation)
empty, err := repo.SearchGraph(ctx, ns, "no match")
require.NoError(t, err)
require.Empty(t, empty.Graph.Node)
// Full query text remains a parameter, including a Cypher-looking payload.
empty, err = repo.SearchGraph(ctx, ns, "' RETURN 1 //")
require.NoError(t, err)
require.Empty(t, empty.Graph.Node)
t.Run("seed cap and exact-name priority", func(t *testing.T) {
_, err := neo4j.ExecuteQuery(ctx, driver, `
UNWIND range(0, 104) AS i CREATE (n:`+label+`
{name:'Cap '+toString(i), kg:'doc', chunks:['c1'], attributes:[]})
WITH count(*) AS created
CREATE (exact:`+label+` {name:'Cap', kg:'doc', chunks:['c1'], attributes:[]})`,
nil, neo4j.EagerResultTransformer)
require.NoError(t, err)
result, err := repo.SearchGraph(ctx, ns, "Cap")
require.NoError(t, err)
require.Len(t, result.Graph.Node, types.GraphSearchMaxSeeds)
require.Equal(t, "Cap", result.Graph.Node[0].Name)
require.Contains(t, result.TruncationReasons, "candidate_seeds")
})
t.Run("row cap without duplicate edge expansion", func(t *testing.T) {
_, err := neo4j.ExecuteQuery(ctx, driver, `
CREATE (hub:`+label+` {name:'Hub', kg:'doc', chunks:['c1'], attributes:[]})
WITH hub UNWIND range(0, 512) AS i
CREATE (leaf:`+label+` {name:'Leaf '+toString(i), kg:'doc', chunks:['c1'], attributes:[]}),
(hub)-[:CONNECTS]->(leaf)`,
nil, neo4j.EagerResultTransformer)
require.NoError(t, err)
result, err := repo.SearchGraph(ctx, ns, "Hub")
require.NoError(t, err)
require.Len(t, result.Graph.Relation, types.GraphSearchMaxRows)
require.Contains(t, result.TruncationReasons, "candidate_relations")
})
t.Run("field projections are bounded before Bolt", func(t *testing.T) {
_, err := neo4j.ExecuteQuery(ctx, driver, `
CREATE (n:`+label+` {name:'Large', kg:'doc', chunks:$chunks, attributes:$attributes})`,
map[string]any{
"chunks": strings.Split(strings.Repeat("c,", 600), ","),
"attributes": []string{strings.Repeat("中", 3000)},
}, neo4j.EagerResultTransformer)
require.NoError(t, err)
result, err := repo.SearchGraph(ctx, ns, "Large")
require.NoError(t, err)
require.Len(t, result.Graph.Node, 1)
require.Len(t, result.Graph.Node[0].Chunks, 513)
require.Len(t, []rune(result.Graph.Node[0].Attributes[0]), 1001)
})
}
@@ -0,0 +1,360 @@
package neo4j
import (
"context"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
)
// Neo4jRepository is a repository for Neo4j
type Neo4jRepository struct {
driver neo4j.Driver
nodePrefix string
}
const (
// graphSearchMaxSeedNodes bounds how many entities a single graph search
// expands from. The match is a substring match, so this is the knob that
// keeps one vague entity name from pulling in the whole graph.
graphSearchMaxSeedNodes = 200
// graphSearchMaxRows bounds returned (node, relation) rows as a backstop
// for hub entities whose neighbourhood alone is huge.
graphSearchMaxRows = 2000
)
// NewNeo4jRepository creates a new Neo4j repository
func NewNeo4jRepository(driver neo4j.Driver) interfaces.RetrieveGraphRepository {
return &Neo4jRepository{driver: driver, nodePrefix: "ENTITY"}
}
// _remove_hyphen removes hyphens from a string
func _remove_hyphen(s string) string {
return strings.ReplaceAll(s, "-", "_")
}
// Labels returns the labels for a namespace
func (n *Neo4jRepository) Labels(namespace types.NameSpace) []string {
res := make([]string, 0)
for _, label := range namespace.Labels() {
res = append(res, n.nodePrefix+_remove_hyphen(label))
}
return res
}
// Label returns the label for a namespace
func (n *Neo4jRepository) Label(namespace types.NameSpace) string {
labels := n.Labels(namespace)
return strings.Join(labels, ":")
}
// AddGraph adds a graph to the Neo4j repository
func (n *Neo4jRepository) AddGraph(ctx context.Context, namespace types.NameSpace, graphs []*types.GraphData) error {
if n.driver == nil {
logger.Warnf(ctx, "NOT SUPPORT RETRIEVE GRAPH")
return nil
}
for _, graph := range graphs {
if err := n.addGraph(ctx, namespace, graph); err != nil {
return err
}
}
return nil
}
// addGraph adds a graph to the Neo4j repository
func (n *Neo4jRepository) addGraph(ctx context.Context, namespace types.NameSpace, graph *types.GraphData) error {
session := n.driver.NewSession(ctx, neo4j.SessionConfig{AccessMode: neo4j.AccessModeWrite})
defer session.Close(ctx)
_, err := session.ExecuteWrite(ctx, func(tx neo4j.ManagedTransaction) (interface{}, error) {
// Node import query
node_import_query := `
UNWIND $data AS row
CALL apoc.merge.node(row.labels, {name: row.name, kg: row.knowledge_id}, row.props, {}) YIELD node
SET node.chunks = apoc.coll.union(node.chunks, row.chunks)
RETURN distinct 'done' AS result
`
nodeData := []map[string]interface{}{}
for _, node := range graph.Node {
nodeData = append(nodeData, map[string]interface{}{
"name": node.Name,
"knowledge_id": namespace.Knowledge,
"props": map[string][]string{"attributes": node.Attributes},
"chunks": node.Chunks,
"labels": n.Labels(namespace),
})
}
if _, err := tx.Run(ctx, node_import_query, map[string]interface{}{"data": nodeData}); err != nil {
return nil, fmt.Errorf("failed to create nodes: %v", err)
}
// Relationship import query
rel_import_query := `
UNWIND $data AS row
CALL apoc.merge.node(row.source_labels, {name: row.source, kg: row.knowledge_id}, {}, {}) YIELD node as source
CALL apoc.merge.node(row.target_labels, {name: row.target, kg: row.knowledge_id}, {}, {}) YIELD node as target
CALL apoc.merge.relationship(source, row.type, {}, row.attributes, target) YIELD rel
RETURN distinct 'done'
`
relData := []map[string]interface{}{}
for _, rel := range graph.Relation {
relData = append(relData, map[string]interface{}{
"source": rel.Node1,
"target": rel.Node2,
"knowledge_id": namespace.Knowledge,
"type": rel.Type,
"source_labels": n.Labels(namespace),
"target_labels": n.Labels(namespace),
})
}
if _, err := tx.Run(ctx, rel_import_query, map[string]interface{}{"data": relData}); err != nil {
return nil, fmt.Errorf("failed to create relationships: %v", err)
}
return nil, nil
})
if err != nil {
logger.Errorf(ctx, "failed to add graph: %v", err)
return err
}
return nil
}
// DelGraph deletes a graph from the Neo4j repository
func (n *Neo4jRepository) DelGraph(ctx context.Context, namespaces []types.NameSpace) error {
if n.driver == nil {
logger.Warnf(ctx, "NOT SUPPORT RETRIEVE GRAPH")
return nil
}
session := n.driver.NewSession(ctx, neo4j.SessionConfig{AccessMode: neo4j.AccessModeWrite})
defer session.Close(ctx)
result, err := session.ExecuteWrite(ctx, func(tx neo4j.ManagedTransaction) (interface{}, error) {
for _, namespace := range namespaces {
labelExpr := n.Label(namespace)
deleteRelsQuery := `
CALL apoc.periodic.iterate(
"MATCH (n:` + labelExpr + ` {kg: $knowledge_id})-[r]-(m:` + labelExpr + ` {kg: $knowledge_id}) RETURN r",
"DELETE r",
{batchSize: 1000, parallel: true, params: {knowledge_id: $knowledge_id}}
) YIELD batches, total
RETURN total
`
if _, err := tx.Run(ctx, deleteRelsQuery, map[string]interface{}{"knowledge_id": namespace.Knowledge}); err != nil {
return nil, fmt.Errorf("failed to delete relationships: %v", err)
}
deleteNodesQuery := `
CALL apoc.periodic.iterate(
"MATCH (n:` + labelExpr + ` {kg: $knowledge_id}) RETURN n",
"DELETE n",
{batchSize: 1000, parallel: true, params: {knowledge_id: $knowledge_id}}
) YIELD batches, total
RETURN total
`
if _, err := tx.Run(ctx, deleteNodesQuery, map[string]interface{}{"knowledge_id": namespace.Knowledge}); err != nil {
return nil, fmt.Errorf("failed to delete nodes: %v", err)
}
}
return nil, nil
})
if err != nil {
return err
}
logger.Infof(ctx, "delete graph result: %v", result)
return nil
}
// SearchNode searches for nodes in the Neo4j repository.
//
// The result set is bounded twice; graphSearchCypher owns the query, its
// ordering and the parameters, so both caps can be pinned by a unit test
// without a live database.
func (n *Neo4jRepository) SearchNode(
ctx context.Context,
namespace types.NameSpace,
nodes []string,
) (*types.GraphData, error) {
if n.driver == nil {
logger.Warnf(ctx, "NOT SUPPORT RETRIEVE GRAPH")
return nil, nil
}
session := n.driver.NewSession(ctx, neo4j.SessionConfig{AccessMode: neo4j.AccessModeRead})
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (interface{}, error) {
query, params := graphSearchCypher(n.Label(namespace), nodes)
result, err := tx.Run(ctx, query, params)
if err != nil {
return nil, fmt.Errorf("failed to run query: %v", err)
}
graphData, err := decodeGraphSearchResult(ctx, result)
if err != nil {
return nil, err
}
// Make truncation visible. A silent cap reads as "the graph has no more
// matches" when in fact candidates were dropped.
if len(graphData.Relation) >= graphSearchMaxRows {
logger.Warnf(ctx,
"graph search hit the row cap: %d nodes / %d relations returned "+
"(seed cap %d, row cap %d) — results are truncated; "+
"narrow the entity or raise graphSearchMaxRows",
len(graphData.Node), len(graphData.Relation),
graphSearchMaxSeedNodes, graphSearchMaxRows)
} else {
// Debug, not Info: this runs on the retrieval path for every query.
logger.Debugf(ctx, "graph search: %d nodes / %d relations (seed cap %d, row cap %d)",
len(graphData.Node), len(graphData.Relation),
graphSearchMaxSeedNodes, graphSearchMaxRows)
}
return graphData, nil
})
if err != nil {
logger.Errorf(ctx, "search node failed: %v", err)
return nil, err
}
return result.(*types.GraphData), nil
}
// decodeGraphSearchResult keeps document instances distinct and restores the
// stored direction even when the seed is the target of an undirected match.
func decodeGraphSearchResult(ctx context.Context, result neo4j.Result) (*types.GraphData, error) {
graph := &types.GraphData{}
nodeSeen := make(map[string]*types.GraphNode)
relationSeen := make(map[string]bool)
for result.Next(ctx) {
record := result.Record()
if record == nil {
return nil, fmt.Errorf("graph query returned a nil record")
}
n, _, err := neo4j.GetRecordValue[neo4j.Node](record, "n")
if err != nil {
return nil, fmt.Errorf("failed to decode graph seed: %w", err)
}
m, _, err := neo4j.GetRecordValue[neo4j.Node](record, "m")
if err != nil {
return nil, fmt.Errorf("failed to decode graph neighbour: %w", err)
}
r, _, err := neo4j.GetRecordValue[neo4j.Relationship](record, "r")
if err != nil {
return nil, fmt.Errorf("failed to decode graph relationship: %w", err)
}
// Keep the matched seed first for evidence ranking, independently of direction.
for _, node := range []neo4j.Node{n, m} {
if nodeSeen[node.ElementId] != nil {
continue
}
decoded, err := decodeGraphNode(node)
if err != nil {
return nil, err
}
nodeSeen[node.ElementId] = decoded
graph.Node = append(graph.Node, decoded)
}
source, target := n, m
if r.StartElementId == m.ElementId && r.EndElementId == n.ElementId {
source, target = m, n
} else if r.StartElementId != n.ElementId || r.EndElementId != m.ElementId {
return nil, fmt.Errorf("graph relationship %q does not connect its returned endpoints", r.ElementId)
}
if r.ElementId == "" {
return nil, fmt.Errorf("graph relationship has no element identity")
}
if !relationSeen[r.ElementId] {
relationSeen[r.ElementId] = true
graph.Relation = append(graph.Relation, &types.GraphRelation{
Node1: nodeSeen[source.ElementId].Name, Node2: nodeSeen[target.ElementId].Name, Type: r.Type,
ID: r.ElementId, SourceID: source.ElementId, TargetID: target.ElementId,
})
}
}
if err := result.Err(); err != nil {
return nil, fmt.Errorf("failed to read graph query results: %w", err)
}
return graph, nil
}
func decodeGraphNode(node neo4j.Node) (*types.GraphNode, error) {
name, ok := node.Props["name"].(string)
if node.ElementId == "" || !ok || name == "" {
return nil, fmt.Errorf("graph node %q has no identity or name", node.ElementId)
}
chunks, ok := node.Props["chunks"].([]any)
if !ok && node.Props["chunks"] != nil {
return nil, fmt.Errorf("graph node %q has invalid chunks", node.ElementId)
}
attributes, ok := node.Props["attributes"].([]any)
if !ok && node.Props["attributes"] != nil {
return nil, fmt.Errorf("graph node %q has invalid attributes", node.ElementId)
}
knowledgeID, _ := node.Props["kg"].(string)
return &types.GraphNode{
Name: name, Chunks: listI2listS(chunks), Attributes: listI2listS(attributes),
ID: node.ElementId, KnowledgeID: knowledgeID,
}, nil
}
// graphSearchCypher builds the bounded graph-search query and its parameters
// for one label expression and one set of entity names.
//
// The WHERE clause is a substring match, so a short entity name (or one that is
// a component of many others) matches a large slice of the graph: without a
// bound this returned 1309 nodes / 1917 relations for a single query, which
// then exceeded the reranker's per-request limit and made chunk_merge walk the
// entire set. Three rules keep the caps from deciding the result by accident:
//
// - Only entities that have at least one relationship can seed an expansion —
// a relation-less match occupies one of the seed slots and then contributes
// nothing.
// - Exact name matches rank first, then the shortest names, then alphabetical
// order. Ordering by name alone lets an entity whose name *is* the query
// fall outside the cap once the substring matches exceed it.
// - The seed order is carried into the row LIMIT, so a truncated result keeps the
// neighbourhoods of the highest-ranked seeds rather than an arbitrary
// subset of the rows.
//
// Each edge is expanded only from its earliest seed, so duplicate endpoint
// matches cannot consume the row cap. Only the bounded seed list is collected;
// grouping every candidate relationship would require unbounded working memory.
func graphSearchCypher(labelExpr string, nodes []string) (string, map[string]interface{}) {
query := `
MATCH (n:` + labelExpr + `)
WHERE ANY(nodeText IN $nodes WHERE n.name CONTAINS nodeText)
AND EXISTS { (n)--() }
WITH n,
CASE WHEN n.name IN $nodes THEN 0 ELSE 1 END AS seed_rank,
size(n.name) AS name_len,
n.name AS name
ORDER BY seed_rank, name_len, name, n.kg, elementId(n)
LIMIT $maxSeedNodes
WITH collect(n) AS seeds
UNWIND range(0, size(seeds) - 1) AS seed_index
WITH seeds[seed_index] AS n, seeds[0..seed_index] AS earlier_seeds, seed_index
MATCH (n)-[r]-(m:` + labelExpr + `)
WHERE NOT m IN earlier_seeds
WITH n, r, m, seed_index
ORDER BY seed_index, elementId(r)
LIMIT $maxRows
RETURN n, r, m
`
params := map[string]interface{}{
"nodes": nodes,
"maxSeedNodes": graphSearchMaxSeedNodes,
"maxRows": graphSearchMaxRows,
}
return query, params
}
func listI2listS(list []any) []string {
result := make([]string, len(list))
for i, v := range list {
result[i] = fmt.Sprintf("%v", v)
}
return result
}
@@ -0,0 +1,224 @@
package neo4j
import (
"context"
"errors"
"strings"
"testing"
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestGraphSearchCypherBoundsAndOrders pins the three review points on #3550:
// relation-less seeds are excluded, exact name matches outrank substring-only
// hits, and both LIMITs are preceded by the same ordering key so a truncated
// result keeps the neighbourhoods of the highest-ranked seeds.
func TestGraphSearchCypherBoundsAndOrders(t *testing.T) {
query, params := graphSearchCypher("ENTITY_kb", []string{"安恒"})
for _, want := range []string{
"EXISTS { (n)--() }",
"CASE WHEN n.name IN $nodes THEN 0 ELSE 1 END AS seed_rank",
"ORDER BY seed_rank, name_len, name",
"WITH collect(n) AS seeds",
"UNWIND range(0, size(seeds) - 1) AS seed_index",
"WHERE NOT m IN earlier_seeds",
"ORDER BY seed_index, elementId(r)",
"LIMIT $maxSeedNodes",
"LIMIT $maxRows",
} {
if !strings.Contains(query, want) {
t.Errorf("query is missing %q:\n%s", want, query)
}
}
// Collect only the capped seeds, never the unbounded relationship candidates.
collectAt := strings.Index(query, "WITH collect(n) AS seeds")
if collectAt < strings.Index(query, "LIMIT $maxSeedNodes") || strings.Count(query, "collect(") != 1 {
t.Errorf("only the bounded seed list may be collected:\n%s", query)
}
if !strings.Contains(query, "name, n.kg, elementId(n)") {
t.Errorf("same-named document instances need stable tie breakers:\n%s", query)
}
if strings.Index(query, "WHERE NOT m IN earlier_seeds") > strings.Index(query, "LIMIT $maxRows") {
t.Errorf("duplicate endpoint matches must be removed before the row cap:\n%s", query)
}
if strings.Index(query, "LIMIT $maxSeedNodes") > strings.Index(query, "LIMIT $maxRows") {
t.Errorf("the seed cap must be applied before the row cap:\n%s", query)
}
// A relation-less seed expands to nothing, so it must not survive the first
// cap (the check has to sit in the first WHERE, before the seed ordering).
whereAt := strings.Index(query, "EXISTS { (n)--() }")
seedCapAt := strings.Index(query, "LIMIT $maxSeedNodes")
if whereAt < 0 || seedCapAt < 0 || whereAt > seedCapAt {
t.Errorf("the relationship check must precede the seed cap:\n%s", query)
}
if params["maxSeedNodes"] != graphSearchMaxSeedNodes {
t.Errorf("maxSeedNodes = %v, want %d", params["maxSeedNodes"], graphSearchMaxSeedNodes)
}
if params["maxRows"] != graphSearchMaxRows {
t.Errorf("maxRows = %v, want %d", params["maxRows"], graphSearchMaxRows)
}
if got, ok := params["nodes"].([]string); !ok || len(got) != 1 || got[0] != "安恒" {
t.Errorf("nodes param = %#v, want []string{\"安恒\"}", params["nodes"])
}
// The label expression is interpolated rather than parameterised, so it has
// to reach every match in the query.
if !strings.Contains(query, "MATCH (n:ENTITY_kb)") || !strings.Contains(query, "MATCH (n)-[r]-(m:ENTITY_kb)") {
t.Errorf("label expression not applied to both matches:\n%s", query)
}
}
type graphRecordResult struct {
neo4j.Result
records []*neo4j.Record
index int
err error
}
func (r *graphRecordResult) Next(context.Context) bool {
if r.index >= len(r.records) {
return false
}
r.index++
return true
}
func (r *graphRecordResult) Record() *neo4j.Record { return r.records[r.index-1] }
func (r *graphRecordResult) Err() error { return r.err }
func graphTestNode(id, name, document, chunk string, attributes ...string) neo4j.Node {
attrs := make([]any, len(attributes))
for i, attribute := range attributes {
attrs[i] = attribute
}
return neo4j.Node{ElementId: id, Props: map[string]any{
"name": name, "kg": document, "chunks": []any{chunk}, "attributes": attrs,
}}
}
func graphTestRecord(n, m neo4j.Node, r neo4j.Relationship) *neo4j.Record {
return &neo4j.Record{Keys: []string{"n", "r", "m"}, Values: []any{n, r, m}}
}
func TestDecodeGraphSearchDirectionAndIdentity(t *testing.T) {
a := graphTestNode("a", "Acme", "doc1", "c1")
b := graphTestNode("b", "Shanghai", "doc1", "c1")
r := neo4j.Relationship{ElementId: "r", StartElementId: "a", EndElementId: "b", Type: "LOCATED_IN"}
reverse := neo4j.Relationship{ElementId: "reverse", StartElementId: "b", EndElementId: "a", Type: "LOCATED_IN"}
self := neo4j.Relationship{ElementId: "self", StartElementId: "a", EndElementId: "a", Type: "RELATED_TO"}
for _, tt := range []struct {
name string
records []*neo4j.Record
nodeCount int
firstNode string
relations [][3]string
}{
{"outgoing", []*neo4j.Record{graphTestRecord(a, b, r)}, 2, "a", [][3]string{{"r", "a", "b"}}},
{"incoming", []*neo4j.Record{graphTestRecord(b, a, r)}, 2, "b", [][3]string{{"r", "a", "b"}}},
{
"both seeds",
[]*neo4j.Record{graphTestRecord(b, a, r), graphTestRecord(a, b, r)},
2, "b",
[][3]string{{"r", "a", "b"}},
},
{
"bidirectional",
[]*neo4j.Record{graphTestRecord(a, b, r), graphTestRecord(a, b, reverse)},
2, "a",
[][3]string{{"r", "a", "b"}, {"reverse", "b", "a"}},
},
{
"self loop",
[]*neo4j.Record{graphTestRecord(a, a, self), graphTestRecord(a, a, self)},
1, "a",
[][3]string{{"self", "a", "a"}},
},
} {
t.Run(tt.name, func(t *testing.T) {
graph, err := decodeGraphSearchResult(context.Background(), &graphRecordResult{records: tt.records})
require.NoError(t, err)
require.Len(t, graph.Node, tt.nodeCount)
assert.Equal(t, tt.firstNode, graph.Node[0].ID, "seed evidence priority must not change")
require.Len(t, graph.Relation, len(tt.relations))
for i, want := range tt.relations {
got := graph.Relation[i]
assert.Equal(t, want, [3]string{got.ID, got.SourceID, got.TargetID})
byID := map[string]string{"a": "Acme", "b": "Shanghai"}
assert.Equal(t, byID[want[1]], got.Node1)
assert.Equal(t, byID[want[2]], got.Node2)
}
})
}
}
func TestDecodeGraphSearchPreservesSameNamedDocumentSources(t *testing.T) {
a1 := graphTestNode("a1", "Acme", "doc1", "c1", "doc1 attribute")
b1 := graphTestNode("b1", "Shanghai", "doc1", "c1")
a2 := graphTestNode("a2", "Acme", "doc2", "c2", "doc2 attribute")
b2 := graphTestNode("b2", "Shanghai", "doc2", "c2")
r1 := neo4j.Relationship{ElementId: "r1", StartElementId: "a1", EndElementId: "b1", Type: "LOCATED_IN"}
r2 := neo4j.Relationship{ElementId: "r2", StartElementId: "a2", EndElementId: "b2", Type: "LOCATED_IN"}
for _, records := range [][]*neo4j.Record{
{graphTestRecord(b1, a1, r1), graphTestRecord(b2, a2, r2), graphTestRecord(a1, b1, r1)},
{graphTestRecord(b2, a2, r2), graphTestRecord(b1, a1, r1), graphTestRecord(a2, b2, r2)},
} {
graph, err := decodeGraphSearchResult(context.Background(), &graphRecordResult{records: records})
require.NoError(t, err)
require.Len(t, graph.Node, 4)
require.Len(t, graph.Relation, 2, "same names and type do not make two document edges identical")
var sources, attributes []string
for _, node := range graph.Node {
if node.Name == "Acme" {
sources = append(sources, node.KnowledgeID+":"+node.Chunks[0])
attributes = append(attributes, node.Attributes...)
}
}
assert.ElementsMatch(t, []string{"doc1:c1", "doc2:c2"}, sources)
assert.ElementsMatch(t, []string{"doc1 attribute", "doc2 attribute"}, attributes)
}
}
func TestDecodeGraphSearchReportsInvalidRecordsAndStreamErrors(t *testing.T) {
a := graphTestNode("a", "Acme", "doc", "c")
b := graphTestNode("b", "Shanghai", "doc", "c")
r := neo4j.Relationship{ElementId: "r", StartElementId: "a", EndElementId: "b", Type: "LOCATED_IN"}
streamErr := errors.New("stream interrupted")
graph, err := decodeGraphSearchResult(context.Background(), &graphRecordResult{
records: []*neo4j.Record{graphTestRecord(a, b, r)}, err: streamErr,
})
assert.Nil(t, graph, "a failed stream must not return a successful partial graph")
assert.ErrorIs(t, err, streamErr)
missingName := neo4j.Node{ElementId: "a", Props: map[string]any{}}
missingID := graphTestNode("", "Acme", "doc", "c")
wrongEndpoint := r
wrongEndpoint.EndElementId = "elsewhere"
missingRelationID := r
missingRelationID.ElementId = ""
for _, record := range []*neo4j.Record{
nil,
{Keys: []string{"n"}, Values: []any{"not a node"}},
graphTestRecord(missingName, b, r),
graphTestRecord(missingID, b, r),
graphTestRecord(a, b, wrongEndpoint),
graphTestRecord(a, b, missingRelationID),
} {
result := &graphRecordResult{records: []*neo4j.Record{record}}
graph, err := decodeGraphSearchResult(context.Background(), result)
assert.Error(t, err)
assert.Nil(t, graph)
}
// Optional properties may be absent in legacy graph data.
delete(a.Props, "attributes")
graph, err = decodeGraphSearchResult(context.Background(), &graphRecordResult{records: []*neo4j.Record{
graphTestRecord(a, b, r),
}})
require.NoError(t, err)
assert.Empty(t, graph.Node[0].Attributes)
}
@@ -0,0 +1,94 @@
package neo4j
import (
"context"
"fmt"
"os"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Run against a disposable Neo4j instance with authentication disabled:
// Set WEKNORA_NEO4J_TEST_URI=bolt://127.0.0.1:7687, then run:
// go test ./internal/application/repository/retriever/neo4j -run Integration
func TestSearchNodeIntegration(t *testing.T) {
uri := os.Getenv("WEKNORA_NEO4J_TEST_URI")
if uri == "" {
t.Skip("set WEKNORA_NEO4J_TEST_URI to run the live Neo4j regression")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
driver, err := neo4j.NewDriver(uri, neo4j.NoAuth())
require.NoError(t, err)
t.Cleanup(func() { assert.NoError(t, driver.Close(context.Background())) })
require.NoError(t, driver.VerifyConnectivity(ctx))
repo := NewNeo4jRepository(driver).(*Neo4jRepository)
namespace := types.NameSpace{KnowledgeBase: fmt.Sprintf("graph_regression_%d", time.Now().UnixNano())}
label := repo.Label(namespace)
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cleanupCancel()
_, cleanupErr := neo4j.ExecuteQuery(cleanupCtx, driver, "MATCH (n:"+label+") DETACH DELETE n",
nil, neo4j.EagerResultTransformer)
assert.NoError(t, cleanupErr)
})
_, err = neo4j.ExecuteQuery(ctx, driver, `
CREATE (a1:`+label+` {name: 'Acme', kg: 'doc1', chunks: ['c1'], attributes: ['doc1 attribute']}),
(b1:`+label+` {name: 'Shanghai', kg: 'doc1', chunks: ['c1'], attributes: []}),
(a2:`+label+` {name: 'Acme', kg: 'doc2', chunks: ['c2'], attributes: ['doc2 attribute']}),
(b2:`+label+` {name: 'Shanghai', kg: 'doc2', chunks: ['c2'], attributes: []}),
(a1)-[:HEADQUARTERED_IN]->(b1), (a2)-[:HAS_BRANCH_IN]->(b2),
(b1)-[:RELATED_TO]->(a1), (a1)-[:SELF]->(a1)
`, nil, neo4j.EagerResultTransformer)
require.NoError(t, err)
t.Run("deduplicate before the row cap", func(t *testing.T) {
query, params := graphSearchCypher(label, []string{"Acme", "Shanghai"})
params["maxRows"] = 5 // Four stored edges; duplicate endpoint matches must not fill this fifth slot.
result, queryErr := neo4j.ExecuteQuery(ctx, driver, query, params, neo4j.EagerResultTransformer)
require.NoError(t, queryErr)
require.Len(t, result.Records, 4)
params["maxRows"] = 1
result, queryErr = neo4j.ExecuteQuery(ctx, driver, query, params, neo4j.EagerResultTransformer)
require.NoError(t, queryErr)
require.Len(t, result.Records, 1)
})
for _, seeds := range [][]string{{"Shanghai"}, {"Acme"}, {"Acme", "Shanghai"}} {
t.Run(fmt.Sprint(seeds), func(t *testing.T) {
graph, searchErr := repo.SearchNode(ctx, namespace, seeds)
require.NoError(t, searchErr)
require.Len(t, graph.Node, 4)
assert.Equal(t, seeds[0], graph.Node[0].Name, "the best seed still supplies evidence first")
var sources, attributes []string
for _, node := range graph.Node {
if node.Name == "Acme" {
sources = append(sources, node.KnowledgeID+":"+node.Chunks[0])
attributes = append(attributes, node.Attributes...)
}
}
assert.ElementsMatch(t, []string{"doc1:c1", "doc2:c2"}, sources)
assert.ElementsMatch(t, []string{"doc1 attribute", "doc2 attribute"}, attributes)
wantRelations := 4
if len(seeds) == 1 && seeds[0] == "Shanghai" {
wantRelations = 3 // The self-loop has no Shanghai endpoint.
}
require.Len(t, graph.Relation, wantRelations)
for _, relation := range graph.Relation {
switch relation.Type {
case "HEADQUARTERED_IN", "HAS_BRANCH_IN":
assert.Equal(t, "Acme", relation.Node1)
assert.Equal(t, "Shanghai", relation.Node2)
case "RELATED_TO":
assert.Equal(t, "Shanghai", relation.Node1)
assert.Equal(t, "Acme", relation.Node2)
case "SELF":
assert.Equal(t, relation.SourceID, relation.TargetID)
}
}
})
}
}