Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/design/specs/2026-11-24-neo4j-streaming-push.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ The unit tests and the parity gate (§6) use it as the reference.

The writer receives rows from the sink and buffers them per group key.
When a group buffer reaches `boltBatchSize` rows, the writer runs one `UNWIND` transaction.
A node group is also flushed when its rows' text reaches `boltBatchBytes` (16 MiB), because artifact and module rows carry whole files. A row larger than that goes alone (#80).
At the end of each phase it flushes every buffer.

| Step | Action | Why the order matters |
Expand Down
42 changes: 39 additions & 3 deletions internal/neo4j/bolt.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ type BoltConfig struct {
// limit on a large app. The driver also encodes each message in client memory.
const boltBatchSize = 5000

// boltBatchBytes limits the text in one node batch (#80). Artifact and module
// rows carry whole files (source), so a count-only batch of large files could
// exceed the server's transaction memory. A row larger than the limit is sent
// alone.
const boltBatchBytes = 16 << 20

// WriteBolt pushes ready rows into the live DB per BoltConfig. appID scopes
// every destructive statement; it must be the application root id. Tests and
// small graphs use it.
Expand Down Expand Up @@ -144,7 +150,9 @@ type boltWriter struct {
// so owned applies the same decision to the rows that arrive later.
changed map[string]bool
nodeBuf map[string][]NodeRow
edgeBuf map[string][]EdgeRow
// nodeBytes is the text size of each node group's buffered rows.
nodeBytes map[string]int
edgeBuf map[string][]EdgeRow
// hashes are the content_hash values of the modules whose nodes were
// upserted, stamped by late after the final node flush. Only the
// (id, hash) pairs are kept, never the :GoModule rows (they carry source).
Expand Down Expand Up @@ -584,20 +592,47 @@ func (w *boltWriter) bufferNodes(nodes []NodeRow) error {
if w.nodeBuf == nil {
w.nodeBuf = map[string][]NodeRow{}
}
if w.nodeBytes == nil {
w.nodeBytes = map[string]int{}
}
for _, n := range nodes {
gk := nodeGroupKey(n)
g := append(w.nodeBuf[gk], n)
g, size := w.nodeBuf[gk], rowTextBytes(n)
if len(g) > 0 && w.nodeBytes[gk]+size > boltBatchBytes {
if err := w.runNodes(g); err != nil {
return err
}
g, w.nodeBytes[gk] = g[:0], 0
}
g = append(g, n)
w.nodeBytes[gk] += size
if len(g) == boltBatchSize {
if err := w.runNodes(g); err != nil {
return err
}
g = g[:0]
g, w.nodeBytes[gk] = g[:0], 0
}
w.nodeBuf[gk] = g
}
return nil
}

// rowTextBytes is the size of a node row's string values, for boltBatchBytes.
func rowTextBytes(n NodeRow) int {
size := len(n.Value)
for _, v := range n.Props {
switch x := v.(type) {
case string:
size += len(x)
case []string:
for _, s := range x {
size += len(s)
}
}
}
return size
}

// flushNodes runs every buffered node group in key order and clears the buffer.
func (w *boltWriter) flushNodes() error {
for _, gk := range sortedKeys(w.nodeBuf) {
Expand All @@ -608,6 +643,7 @@ func (w *boltWriter) flushNodes() error {
}
}
clear(w.nodeBuf)
clear(w.nodeBytes)
return nil
}

Expand Down
6 changes: 5 additions & 1 deletion internal/neo4j/cypher.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,11 @@ func writeNodeChunk(b scriptWriter, chunk []NodeRow) {
if i == len(chunk)-1 {
sep = ""
}
fmt.Fprintf(b, " {k: %s, p: %s}%s\n", cypherString(n.Value), cypherMap(n.Props), sep)
put(b, " {k: ")
writeCypherString(b, n.Value)
put(b, ", p: ")
writeCypherMap(b, n.Props)
put(b, "}"+sep+"\n")
}
put(b, "] AS row\n")
fmt.Fprintf(b, "MERGE (n:%s {%s: row.k})\n", mergeLabel, keyProp)
Expand Down
99 changes: 99 additions & 0 deletions internal/neo4j/large_text_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package neo4j

import (
"bufio"
"bytes"
"context"
"runtime"
"strings"
"testing"

v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2"
)

// TestCypherValueWriters_MatchStrings: the streaming value writers write the
// same text as cypherValue and cypherMap, so the snapshot does not change.
func TestCypherValueWriters_MatchStrings(t *testing.T) {
props := Props{
"s": "it's \\ a\nb\r\tc ünï 🙂", "b": true, "f": false, "i": 3, "n": int64(-7),
"l": []string{"x'y", "z"}, "e": []string{}, "nil": nil, "o": struct{ A int }{1},
}
var b strings.Builder
writeCypherMap(&b, props)
if got, want := b.String(), cypherMap(props); got != want {
t.Errorf("writeCypherMap = %s\nwant %s", got, want)
}
for k, v := range props {
b.Reset()
writeCypherValue(&b, v)
if got, want := b.String(), cypherValue(v); got != want {
t.Errorf("%s: writeCypherValue = %s, want %s", k, got, want)
}
}
}

func largeTextAnalysis(t *testing.T, sources ...string) *v2.Analysis {
t.Helper()
a := buildMultipackageL2(t)
app := a.Application.ID
a.Application.Artifacts = map[string]v2.Artifact{}
for i, src := range sources {
p := string(rune('a'+i)) + ".csv"
a.Application.Artifacts[p] = v2.Artifact{ID: app + "/artifact/" + p, Kind: "artifact", Path: p,
Format: "text", SizeBytes: int64(len(src)), Source: src, Extraction: "full"}
}
return a
}

// TestWriteCypher_LargeSourceIsStreamed (#80): the snapshot writes a large
// artifact source without building escaped copies of it.
func TestWriteCypher_LargeSourceIsStreamed(t *testing.T) {
const size = 64 << 20
a := largeTextAnalysis(t, strings.Repeat("abc,'def'\n", size/10))
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
var out bytes.Buffer
out.Grow(size + size/2) // the output itself is not what this test measures
runtime.ReadMemStats(&before)
bw := bufio.NewWriterSize(&out, 64<<10)
if _, _, err := streamGraph(treeSource(a), newCypherWriter(bw, a.Application.ID)); err != nil {
t.Fatal(err)
}
runtime.ReadMemStats(&after)
if got := after.TotalAlloc - before.TotalAlloc; got > size/4 {
t.Errorf("the snapshot allocated %d MB for a %d MB source; want under %d MB (streamed)", got>>20, size>>20, size/4>>20)
}
}

// TestBolt_NodeBatchesAreLimitedBySize (#80): a node batch is flushed when its
// rows' text reaches boltBatchBytes, so large sources do not go to the server
// in one transaction. A single row larger than the limit goes alone.
func TestBolt_NodeBatchesAreLimitedBySize(t *testing.T) {
big := strings.Repeat("x", boltBatchBytes/3)
huge := strings.Repeat("y", boltBatchBytes*2)
a := largeTextAnalysis(t, big, big, big, big, big, huge)
db := &fakeDB{}
if _, _, err := streamGraph(treeSource(a), newBoltWriter(context.Background(), db, a.Application.ID, BoltConfig{})); err != nil {
t.Fatal(err)
}
artifactRows := 0
for _, st := range db.writes {
if !strings.Contains(st.q, "MERGE (n:"+LabelArtifact) {
continue
}
rows, _ := st.params["rows"].([]map[string]any)
artifactRows += len(rows)
total := 0
for _, r := range rows {
if s, ok := r["p"].(map[string]any)["source"].(string); ok {
total += len(s)
}
}
if len(rows) > 1 && total > boltBatchBytes {
t.Errorf("one batch carries %d rows with %d bytes of text; want at most %d", len(rows), total, boltBatchBytes)
}
}
if artifactRows != 6 {
t.Errorf("%d artifact rows pushed, want 6", artifactRows)
}
}
117 changes: 80 additions & 37 deletions internal/neo4j/rows.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"
"unicode/utf8"
)

// Milestone M2: the output-agnostic row IR and the RowBuilder. GraphRows is a
Expand Down Expand Up @@ -267,72 +269,113 @@ func prune(p Props) Props {
// cypherValue renders a Neo4j-legal value as a Cypher literal (used by the
// snapshot writer; the Bolt writer passes values as parameters instead).
func cypherValue(v Value) string {
var b strings.Builder
writeCypherValue(&b, v)
return b.String()
}

// cypherString renders a Cypher single-quoted string literal with escaping.
func cypherString(s string) string {
var b strings.Builder
writeCypherString(&b, s)
return b.String()
}

func cypherMap(p Props) string {
var b strings.Builder
writeCypherMap(&b, p)
return b.String()
}

// writeCypherValue writes v as a Cypher literal to b. The snapshot writes
// values straight to its file this way, so a large artifact source is never
// copied into a string first (#80).
func writeCypherValue(b scriptWriter, v Value) {
switch x := v.(type) {
case nil:
return "null"
put(b, "null")
case string:
return cypherString(x)
writeCypherString(b, x)
case bool:
if x {
return "true"
put(b, "true")
} else {
put(b, "false")
}
return "false"
case int:
return fmt.Sprintf("%d", x)
put(b, strconv.Itoa(x))
case int64:
return fmt.Sprintf("%d", x)
put(b, strconv.FormatInt(x, 10))
case []string:
parts := make([]string, len(x))
put(b, "[")
for i, s := range x {
parts[i] = cypherString(s)
if i > 0 {
put(b, ", ")
}
writeCypherString(b, s)
}
return "[" + strings.Join(parts, ", ") + "]"
put(b, "]")
default:
// Fall back to a quoted Go rendering rather than emit something illegal.
return cypherString(fmt.Sprintf("%v", x))
writeCypherString(b, fmt.Sprintf("%v", x))
}
}

// cypherString renders a Cypher single-quoted string literal with escaping.
func cypherString(s string) string {
var b strings.Builder
b.WriteByte('\'')
for _, r := range s {
switch r {
case '\'':
b.WriteString("\\'")
case '\\':
b.WriteString("\\\\")
case '\n':
b.WriteString("\\n")
case '\r':
b.WriteString("\\r")
case '\t':
b.WriteString("\\t")
// writeCypherString writes s as a Cypher single-quoted string literal: ', \\,
// newline, carriage return and tab escaped, each invalid UTF-8 byte written as
// U+FFFD. Runs of plain text are written as they are.
func writeCypherString(b scriptWriter, s string) {
put(b, "'")
start := 0
for i := 0; i < len(s); {
r, size := utf8.DecodeRuneInString(s[i:])
var esc string
switch {
case r == '\'':
esc = `\'`
case r == '\\':
esc = `\\`
case r == '\n':
esc = `\n`
case r == '\r':
esc = `\r`
case r == '\t':
esc = `\t`
case r == utf8.RuneError && size == 1:
esc = string(utf8.RuneError)
default:
b.WriteRune(r)
i += size
continue
}
put(b, s[start:i])
put(b, esc)
i += size
start = i
}
b.WriteByte('\'')
return b.String()
put(b, s[start:])
put(b, "'")
}

// cypherMap renders a Props bag as a Cypher map literal with sorted keys (so
// output is deterministic). An empty bag renders as "{}".
func cypherMap(p Props) string {
// writeCypherMap writes p as a Cypher map literal, keys sorted.
func writeCypherMap(b scriptWriter, p Props) {
if len(p) == 0 {
return "{}"
put(b, "{}")
return
}
keys := make([]string, 0, len(p))
for k := range p {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys))
for _, k := range keys {
parts = append(parts, k+": "+cypherValue(p[k]))
put(b, "{")
for i, k := range keys {
if i > 0 {
put(b, ", ")
}
put(b, k+": ")
writeCypherValue(b, p[k])
}
return "{" + strings.Join(parts, ", ") + "}"
put(b, "}")
}

// unionLabels merges two label slices preserving order and de-duplicating,
Expand Down
Loading
Loading