Files
go-heartwood/batchMerge_test.go
T
2026-11-27 08:27:11 -05:00

430 lines
12 KiB
Go

package heartwood
import (
"context"
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"testing"
)
// ----------------------------------------------------------------------------
// Batch Keys
// ----------------------------------------------------------------------------
func TestNodeBatchKey(t *testing.T) {
matchLabel := "Event"
sortedLabels := []string{"AddressableEvent", "Event"}
expectedKey := "Event:AddressableEvent,Event"
// Test Serialization
// labels are expected to be pre-sorted
batchKey := createNodeBatchKey(matchLabel, sortedLabels)
assert.Equal(t, expectedKey, batchKey)
// Test Deserialization
returnedMatchLabel, returnedLabels, err := deserializeNodeBatchKey(batchKey)
assert.NoError(t, err)
assert.Equal(t, matchLabel, returnedMatchLabel)
assert.ElementsMatch(t, sortedLabels, returnedLabels)
}
func TestRelBatchKey(t *testing.T) {
rtype, startLabel, endLabel := "SIGNED", "User", "Event"
expectedKey := "SIGNED,User,Event"
// Test Serialization
batchKey := createRelBatchKey(rtype, startLabel, endLabel)
assert.Equal(t, expectedKey, batchKey)
// Test Deserialization
returnedRtype, returnedStartLabel, returnedEndLabel, err := deserializeRelBatchKey(batchKey)
assert.NoError(t, err)
assert.Equal(t, rtype, returnedRtype)
assert.Equal(t, startLabel, returnedStartLabel)
assert.Equal(t, endLabel, returnedEndLabel)
}
// ----------------------------------------------------------------------------
// Batch Subgraph
// ----------------------------------------------------------------------------
func TestBatchSubgraphAddNode(t *testing.T) {
matchKeys := NewSimpleMatchKeys()
subgraph := NewBatchSubgraph(matchKeys)
node := NewEventNode("abc123")
err := subgraph.AddNode(node)
assert.NoError(t, err)
assert.Equal(t, 1, subgraph.NodeCount())
assert.Equal(t, []*Node{node}, subgraph.nodes["Event:Event"])
}
func TestBatchSubgraphAddNodeInvalid(t *testing.T) {
matchKeys := NewSimpleMatchKeys()
subgraph := NewBatchSubgraph(matchKeys)
node := NewNode([]string{"Event"}, Properties{})
err := subgraph.AddNode(node)
assert.ErrorContains(t, err, "invalid node: missing property id")
assert.Equal(t, 0, subgraph.NodeCount())
}
func TestBatchSubgraphAddRel(t *testing.T) {
matchKeys := NewSimpleMatchKeys()
subgraph := NewBatchSubgraph(matchKeys)
userNode := NewUserNode("pubkey1")
eventNode := NewEventNode("abc123")
rel := NewSignedRel(userNode, eventNode, nil)
err := subgraph.AddRel(rel)
assert.NoError(t, err)
assert.Equal(t, 1, subgraph.RelCount())
assert.Equal(t, []*Relationship{rel}, subgraph.rels["SIGNED,User,Event"])
}
func TestNodeBatches(t *testing.T) {
matchKeys := NewSimpleMatchKeys()
subgraph := NewBatchSubgraph(matchKeys)
node := NewEventNode("abc123")
subgraph.AddNode(node)
batches, err := subgraph.NodeBatches()
assert.NoError(t, err)
assert.Len(t, batches, 1)
assert.Equal(t, "Event", batches[0].MatchLabel)
assert.ElementsMatch(t, []string{"Event"}, batches[0].Labels)
assert.ElementsMatch(t, []string{"id"}, batches[0].MatchKeys)
assert.Equal(t, []*Node{node}, batches[0].Nodes)
}
func TestRelBatches(t *testing.T) {
matchKeys := NewSimpleMatchKeys()
subgraph := NewBatchSubgraph(matchKeys)
userNode := NewUserNode("pubkey1")
eventNode := NewEventNode("abc123")
rel := NewSignedRel(userNode, eventNode, nil)
subgraph.AddRel(rel)
batches, err := subgraph.RelBatches()
assert.NoError(t, err)
assert.Len(t, batches, 1)
assert.Equal(t, "SIGNED", batches[0].Type)
assert.Equal(t, "User", batches[0].StartLabel)
assert.ElementsMatch(t, []string{"pubkey"}, batches[0].StartMatchKeys)
assert.Equal(t, "Event", batches[0].EndLabel)
assert.ElementsMatch(t, []string{"id"}, batches[0].EndMatchKeys)
assert.Equal(t, []*Relationship{rel}, batches[0].Rels)
}
// ----------------------------------------------------------------------------
// Merge Nodes
// ----------------------------------------------------------------------------
func TestMergeNodes(t *testing.T) {
s := freshStores(t)
ctx := t.Context()
session := s.graph.NewSession(ctx,
neo4j.SessionConfig{DatabaseName: "neo4j"},
)
defer session.Close(ctx)
batch := NodeBatch{
MatchLabel: "User",
Labels: []string{"User", "Admin"},
MatchKeys: []string{"id"},
Nodes: []*Node{
NewNode([]string{"User"}, Properties{"id": "1", "name": "Alice"}),
NewNode([]string{"User"}, Properties{"id": "2", "name": "Bob"}),
NewNode([]string{"User"}, Properties{"id": "3", "name": "Carol"}),
},
}
resultSummariesAny, err := session.ExecuteWrite(ctx,
func(tx neo4j.ManagedTransaction) (any, error) {
var resultSummaries []neo4j.ResultSummary
nodeResultSummary, err := MergeNodes(ctx, tx, batch)
if err != nil {
return nil, err
}
resultSummaries = append(resultSummaries, nodeResultSummary)
return resultSummaries, nil
},
)
require.NoError(t, err)
resultSummaries, ok := resultSummariesAny.([]neo4j.ResultSummary)
require.True(t, ok)
require.Len(t, resultSummaries, 1)
summary := resultSummaries[0]
assert.Equal(t, 3, summary.Counters().NodesCreated())
expected := NewSubgraph()
for _, n := range batch.Nodes {
expected.AddNode(n)
}
assertSubgraph(t, s.graph, expected)
}
// ----------------------------------------------------------------------------
// Merge Relationships
// ----------------------------------------------------------------------------
func runMergeRels(
t *testing.T, ctx context.Context, d neo4j.Driver, b RelBatch,
) neo4j.ResultSummary {
t.Helper()
session := d.NewSession(ctx,
neo4j.SessionConfig{DatabaseName: "neo4j"},
)
defer session.Close(ctx)
resultSummariesAny, err := session.ExecuteWrite(ctx,
func(tx neo4j.ManagedTransaction) (any, error) {
var resultSummaries []neo4j.ResultSummary
nodeResultSummary, err := MergeRels(ctx, tx, b)
if err != nil {
return nil, err
}
resultSummaries = append(resultSummaries, nodeResultSummary)
return resultSummaries, nil
},
)
require.NoError(t, err)
resultSummaries, ok := resultSummariesAny.([]neo4j.ResultSummary)
require.True(t, ok)
require.Len(t, resultSummaries, 1)
return resultSummaries[0]
}
func TestMergeRels(t *testing.T) {
s := freshStores(t)
ctx := t.Context()
// seed graph
seed := `
CREATE (u1:User { name: "alice" })
CREATE (u2:User { name: "bob" })
CREATE (u3:User { name: "carol" })
CREATE (r1:Resource { id: "disk" })
CREATE (r2:Resource { id: "memory" })
CREATE (r3:Resource { id: "cpu" })
`
_, err := execute(ctx, s.graph, seed, nil)
require.NoError(t, err)
nodes := map[string]*Node{
"alice": NewNode([]string{"User"}, Properties{"name": "alice"}),
"bob": NewNode([]string{"User"}, Properties{"name": "bob"}),
"carol": NewNode([]string{"User"}, Properties{"name": "carol"}),
"disk": NewNode([]string{"Resource"}, Properties{"id": "disk"}),
"memory": NewNode([]string{"Resource"}, Properties{"id": "memory"}),
"cpu": NewNode([]string{"Resource"}, Properties{"id": "cpu"}),
}
// Merge relationship batch
rels := []*Relationship{
NewRelationship("USES", nodes["alice"], nodes["disk"], nil),
NewRelationship("USES", nodes["bob"], nodes["memory"], Properties{"permission": "rw"}),
NewRelationship("USES", nodes["bob"], nodes["cpu"], Properties{"permission": "r"}),
NewRelationship("USES", nodes["carol"], nodes["cpu"], nil),
}
batch := RelBatch{
Type: "USES",
StartLabel: "User",
StartMatchKeys: []string{"name"},
EndLabel: "Resource",
EndMatchKeys: []string{"id"},
Rels: rels,
}
summary := runMergeRels(t, ctx, s.graph, batch)
assert.Equal(t, 4, summary.Counters().RelationshipsCreated())
// Expect relationships were created
expected := NewSubgraph()
for _, n := range nodes {
expected.AddNode(n)
}
for _, r := range rels {
expected.AddRel(r)
}
assertSubgraph(t, s.graph, expected)
}
func TestMergeRelsMissingEndpoint(t *testing.T) {
s := freshStores(t)
ctx := t.Context()
// seed graph
seed := `
CREATE (u1:User { name: "alice" })
`
_, err := execute(ctx, s.graph, seed, nil)
require.NoError(t, err)
nodes := map[string]*Node{
"alice": NewNode([]string{"User"}, Properties{"name": "alice"}),
"disk": NewNode([]string{"Resource"}, Properties{"id": "disk"}),
}
// Merge relationship batch
rels := []*Relationship{
// disk node does not exist
NewRelationship("USES", nodes["alice"], nodes["disk"], nil),
}
batch := RelBatch{
Type: "USES",
StartLabel: "User",
StartMatchKeys: []string{"name"},
EndLabel: "Resource",
EndMatchKeys: []string{"id"},
Rels: rels,
}
summary := runMergeRels(t, ctx, s.graph, batch)
// Expect no relationships were created
assert.Equal(t, 0, summary.Counters().RelationshipsCreated())
// graph only contains alice's node
expected := NewSubgraph()
expected.AddNode(nodes["alice"])
assertSubgraph(t, s.graph, expected)
}
func TestMergeRelsIdempotent(t *testing.T) {
s := freshStores(t)
ctx := t.Context()
// seed graph
seed := `
CREATE (u1:User { name: "alice" })
CREATE (r1:Resource { id: "disk" })
`
_, err := execute(ctx, s.graph, seed, nil)
require.NoError(t, err)
nodes := map[string]*Node{
"alice": NewNode([]string{"User"}, Properties{"name": "alice"}),
"disk": NewNode([]string{"Resource"}, Properties{"id": "disk"}),
}
// Merge relationship batch
rels := []*Relationship{
NewRelationship("USES", nodes["alice"], nodes["disk"], nil),
}
batch := RelBatch{
Type: "USES",
StartLabel: "User",
StartMatchKeys: []string{"name"},
EndLabel: "Resource",
EndMatchKeys: []string{"id"},
Rels: rels,
}
summary := runMergeRels(t, ctx, s.graph, batch)
assert.Equal(t, 1, summary.Counters().RelationshipsCreated())
// batch merge should be idempotent, no new relationships created
summary = runMergeRels(t, ctx, s.graph, batch)
assert.Equal(t, 0, summary.Counters().RelationshipsCreated())
// Expect that the relationship was created
expected := NewSubgraph()
for _, n := range nodes {
expected.AddNode(n)
}
for _, r := range rels {
expected.AddRel(r)
}
assertSubgraph(t, s.graph, expected)
}
// ----------------------------------------------------------------------------
// Merge Subgraph
// ----------------------------------------------------------------------------
func TestMergeSubgraph(t *testing.T) {
s := freshStores(t)
ctx := t.Context()
mk := &SimpleMatchKeys{
Keys: map[string][]string{
"User": {"name"},
"Resource": {"id"},
},
}
batch := NewBatchSubgraph(mk)
nodes := map[string]*Node{
"alice": NewNode([]string{"User"}, Properties{"name": "alice"}),
"bob": NewNode([]string{"User", "Admin"}, Properties{"name": "bob"}),
"disk": NewNode([]string{"Resource"}, Properties{"id": "disk"}),
"memory": NewNode([]string{"Resource"}, Properties{"id": "memory"}),
}
rels := []*Relationship{
NewRelationship("USES", nodes["alice"], nodes["disk"], nil),
NewRelationship("USES", nodes["bob"], nodes["memory"], Properties{"permission": "rw"}),
}
for _, n := range nodes {
batch.AddNode(n)
}
for _, r := range rels {
batch.AddRel(r)
}
summaries, err := MergeSubgraph(ctx, s.graph, batch)
assert.NoError(t, err)
assert.Len(t, summaries, 4)
// Batches are sorted by serialized key
// Each batch is identified by their created node and label counts
// Resources:Resources - two nodes, one label each
assert.Equal(t, 2, summaries[0].Counters().NodesCreated())
assert.Equal(t, 2, summaries[0].Counters().LabelsAdded())
// User:Admin,User - one node, two labels
assert.Equal(t, 1, summaries[1].Counters().NodesCreated())
assert.Equal(t, 2, summaries[1].Counters().LabelsAdded())
// User:User - one node, one label
assert.Equal(t, 1, summaries[2].Counters().NodesCreated())
assert.Equal(t, 1, summaries[2].Counters().LabelsAdded())
// USES,User,Resource
assert.Equal(t, 2, summaries[3].Counters().RelationshipsCreated())
assert.Equal(t, 1, summaries[3].Counters().PropertiesSet())
expected := NewSubgraph()
for _, n := range nodes {
expected.AddNode(n)
}
for _, r := range rels {
expected.AddRel(r)
}
assertSubgraph(t, s.graph, expected)
}