From b52088f89b67c75a2ecdb4acaa90ca825993a6ce Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Mon, 30 Nov 2026 09:00:31 -0500 Subject: [PATCH 1/3] perf(repository): read artifact text in one allocation, reuse the copy buffer (#79, #80) - #80: the text read went through a bytes.Buffer that doubles as it grows, then String() copied it again: about 3 times the file size. readText now reads into a strings.Builder sized from the file, one allocation. A 64 MB file allocated 192 MB, now about its size. The hash check that refuses a file changed between the two reads stays. - #79: io.Copy made a new 32 KB buffer for every file. readArtifact now takes one from a pool. On gitea v1.25.3 (2,843 non-Go files, 14 MB) discovery allocated 104 MB without text and 225 MB with text; now 11 MB and 26 MB. Time is unchanged (about 170 ms, about 1% of a run). Tests: the text read allocates about its size, discovery of 500 small files does not allocate a buffer per file, and a file changed during the read is refused. The first two fail on the old code. Co-Authored-By: Claude Opus 5.5 --- internal/repository/alloc_test.go | 83 +++++++++++++++++++++++++++++++ internal/repository/repository.go | 49 ++++++++++++++---- 2 files changed, 121 insertions(+), 11 deletions(-) create mode 100644 internal/repository/alloc_test.go diff --git a/internal/repository/alloc_test.go b/internal/repository/alloc_test.go new file mode 100644 index 0000000..b435c36 --- /dev/null +++ b/internal/repository/alloc_test.go @@ -0,0 +1,83 @@ +package repository + +import ( + "crypto/sha256" + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +// allocated returns the bytes fn allocates (garbage included). +func allocated(fn func()) uint64 { + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + fn() + runtime.ReadMemStats(&after) + return after.TotalAlloc - before.TotalAlloc +} + +// TestReadArtifact_TextReadAllocatesItsSize (#80): capturing a text file's +// source allocates about the file's size once, not a growing buffer plus a +// string copy (about 3 times the size). +func TestReadArtifact_TextReadAllocatesItsSize(t *testing.T) { + const size = 64 << 20 + p := filepath.Join(t.TempDir(), "data.csv") + if err := os.WriteFile(p, []byte(strings.Repeat("abcdefghij,0123456789\n", size/22)), 0o644); err != nil { + t.Fatal(err) + } + info, err := os.Stat(p) + if err != nil { + t.Fatal(err) + } + var art struct{ n int } + got := allocated(func() { + a, err := readArtifact(p, info, "data.csv", true) + if err != nil { + t.Fatal(err) + } + art.n = len(a.Source) + }) + if art.n != int(info.Size()) { + t.Fatalf("source has %d bytes, want %d", art.n, info.Size()) + } + if limit := uint64(float64(info.Size()) * 1.25); got > limit { + t.Errorf("text read allocated %d MB for a %d MB file; want at most %d MB (one copy)", got>>20, info.Size()>>20, limit>>20) + } +} + +// TestDiscover_ReusesTheCopyBuffer (#79): discovery of many small files does +// not allocate a new 32 KB copy buffer for each file. +func TestDiscover_ReusesTheCopyBuffer(t *testing.T) { + root := t.TempDir() + const files = 500 + for i := range files { + if err := os.WriteFile(filepath.Join(root, fmt.Sprintf("f%03d.txt", i)), []byte("small file\n"), 0o644); err != nil { + t.Fatal(err) + } + } + got := allocated(func() { + if _, err := Discover(root, Options{}); err != nil { + t.Fatal(err) + } + }) + if limit := uint64(files * 32 << 10 / 4); got > limit { + t.Errorf("discovery of %d small files allocated %d KB; want under %d KB (no 32 KB buffer per file)", files, got>>10, limit>>10) + } +} + +// TestReadText_ChangedDuringReadIsRefused: the text read hashes what it reads. +// If that is not what the first pass hashed, the file changed in between and +// its text is not captured. +func TestReadText_ChangedDuringReadIsRefused(t *testing.T) { + first := sha256.Sum256([]byte("port: 8080\n")) + if _, err := readText(strings.NewReader("port: 9090\n"), 11, first[:], nil); err == nil { + t.Error("a file that changed between the hash and the text read was captured") + } + text, err := readText(strings.NewReader("port: 8080\n"), 11, first[:], nil) + if err != nil || text != "port: 8080\n" { + t.Errorf("unchanged file: text %q, err %v", text, err) + } +} diff --git a/internal/repository/repository.go b/internal/repository/repository.go index 0414f29..e65e901 100644 --- a/internal/repository/repository.go +++ b/internal/repository/repository.go @@ -20,6 +20,7 @@ import ( "slices" "sort" "strings" + "sync" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" @@ -260,8 +261,10 @@ func readArtifact(abs string, info fs.FileInfo, rel string, captureText bool) (s return schema.GoArtifact{}, fmt.Errorf("replaced during analysis; not the file the walk saw") } + buf := copyBufs.Get().(*[]byte) + defer copyBufs.Put(buf) s := newSniff() - if _, err := io.Copy(s, f); err != nil { + if _, err := io.CopyBuffer(s, onlyReader{f}, *buf); err != nil { return schema.GoArtifact{}, err } s.finish() @@ -282,25 +285,49 @@ func readArtifact(abs string, info fs.FileInfo, rel string, captureText bool) (s return art, nil } - // Second read, for the text only. The bytes must hash to what the first pass - // hashed; otherwise the file changed in between, and its source would not match - // its recorded hash, so it is skipped with an error instead. + // Second read, for the text only. if _, err := f.Seek(0, io.SeekStart); err != nil { return schema.GoArtifact{}, err } - h := sha256.New() - var text bytes.Buffer - if _, err := io.Copy(io.MultiWriter(h, &text), f); err != nil { + text, err := readText(f, s.size, s.sum(), *buf) + if err != nil { return schema.GoArtifact{}, err } - if !bytes.Equal(h.Sum(nil), s.sum()) { - return schema.GoArtifact{}, fmt.Errorf("changed while it was read; not captured") - } - art.Source = text.String() + art.Source = text art.Extraction = "full" return art, nil } +// copyBufs holds the 32 KB copy buffers of readArtifact. io.Copy would make a +// new one for every file (#79): on a project of a few thousand small files that +// is most of what discovery allocates. +var copyBufs = sync.Pool{New: func() any { b := make([]byte, 32<<10); return &b }} + +// onlyReader hides an *os.File's WriteTo, so io.CopyBuffer uses the given +// buffer and does not allocate its own. +type onlyReader struct{ io.Reader } + +// readText reads r, which has size bytes, into one string allocated at that +// size (#80): a growing buffer and then a string copy cost about 3 times the +// size. The bytes must hash to want, the first pass's hash; otherwise the file +// changed in between, and its text would not match its recorded hash, so it is +// refused. buf is the copy buffer; nil makes one. +func readText(r io.Reader, size int64, want, buf []byte) (string, error) { + if buf == nil { + buf = make([]byte, 32<<10) + } + h := sha256.New() + var text strings.Builder + text.Grow(int(size)) + if _, err := io.CopyBuffer(io.MultiWriter(h, &text), onlyReader{r}, buf); err != nil { + return "", err + } + if !bytes.Equal(h.Sum(nil), want) { + return "", fmt.Errorf("changed while it was read; not captured") + } + return text.String(), nil +} + // formatOf names the file's format. go.mod and go.sum are named by their file name. // A binary is never a Dockerfile or a requirements file, whatever its name: the // name rules apply to text only, so binary bytes can never be captured as text. From de8f7867c030f87d135443db4705f24a12c65e5c Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Mon, 30 Nov 2026 09:08:09 -0500 Subject: [PATCH 2/3] perf(v2emit): write artifacts one at a time and stream each source (#80) The JSON writer streamed the symbol table one module at a time, but wrote the rest of application, with every artifact's text, in one json.Marshal: it built the escaped text in a growing buffer and then copied it. For one 512 MB text file that was about 1.1 GB on top of the text itself. The envelope now holds a stand-in for the artifacts. They are written one at a time in its place, and each source is escaped straight to the writer by writeJSONString, which writes the bytes encoding/json writes (HTML escaping, \b \f \n \r \t, \u00XX, U+2028/U+2029, U+FFFD for invalid UTF-8). The output is unchanged. Tests: writeJSONString equals json.Marshal on fixed cases and 2,000 random byte strings; Encode with artifacts equals json.Marshal; Encode of a 64 MB source allocates under 8 MB. Co-Authored-By: Claude Opus 5.5 --- .../v2emit/artifact_stream_test.go | 102 +++++++++ .../v2emit/artifacts_stream.go | 197 ++++++++++++++++++ internal/syntactic_analysis/v2emit/emit.go | 8 +- 3 files changed, 306 insertions(+), 1 deletion(-) create mode 100644 internal/syntactic_analysis/v2emit/artifact_stream_test.go create mode 100644 internal/syntactic_analysis/v2emit/artifacts_stream.go diff --git a/internal/syntactic_analysis/v2emit/artifact_stream_test.go b/internal/syntactic_analysis/v2emit/artifact_stream_test.go new file mode 100644 index 0000000..c9bea78 --- /dev/null +++ b/internal/syntactic_analysis/v2emit/artifact_stream_test.go @@ -0,0 +1,102 @@ +package v2emit + +import ( + "bytes" + "encoding/json" + "math/rand/v2" + "runtime" + "strings" + "testing" + + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" +) + +// TestWriteJSONString_EqualsMarshal: the streaming string writer writes the +// bytes json.Marshal writes for the same string: HTML escaping, \b \f \n \r +// \t, other control bytes as \u00XX, U+2028 / U+2029, and invalid UTF-8 as +// \ufffd. +func TestWriteJSONString_EqualsMarshal(t *testing.T) { + cases := []string{ + "", "plain", `quote " and backslash \`, "", + "\b\f\n\r\t\x00\x01\x1f\x7f", "line\u2028para\u2029end", "émoji 🙂 日本", + "bad \xff utf8 \xc3", "trail \xe2\x80", + } + r := rand.New(rand.NewPCG(1, 2)) + for range 2000 { + b := make([]byte, r.IntN(64)) + for i := range b { + b[i] = byte(r.IntN(256)) + } + cases = append(cases, string(b)) + } + for _, s := range cases { + want, err := json.Marshal(s) + if err != nil { + t.Fatal(err) + } + var got bytes.Buffer + if err := writeJSONString(&got, s); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got.Bytes(), want) { + t.Fatalf("writeJSONString(%q) = %s, want %s", s, got.Bytes(), want) + } + } +} + +func artifactTree(sources map[string]string) *v2.Analysis { + arts := map[string]v2.Artifact{} + for p, src := range sources { + ext := "none" + if src != "" { + ext = "full" + } + arts[p] = v2.Artifact{ID: "can://a/a/artifact/" + p, Kind: "artifact", Path: p, Format: "text", + SizeBytes: int64(len(src)), SHA256: "x", Source: src, Extraction: ext} + } + return &v2.Analysis{IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 1, + Application: v2.Application{IdentityVersion: 2, ID: "can://a/a", Kind: "application", + SymbolTable: map[string]v2.Module{}, Artifacts: arts, + Dependencies: []v2.Dependency{{Name: "example.com/x", Ecosystem: "golang", Kind: "runtime", Prov: []string{"declared"}}}}} +} + +// TestEncode_ArtifactsByteIdenticalToMarshal (#80): with the artifacts written +// one at a time and each source streamed, Encode still equals json.Marshal. +func TestEncode_ArtifactsByteIdenticalToMarshal(t *testing.T) { + tree := artifactTree(map[string]string{ + "b.yaml": "port: 8080\n<&>\u2028", "a/x.json": `{"k": "v"}`, "logo.png": "", "z.txt": "\x01\t\"\\", + }) + want, err := json.Marshal(tree) + if err != nil { + t.Fatal(err) + } + var got bytes.Buffer + if err := Encode(&got, tree); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got.Bytes(), want) { + t.Errorf("Encode differs from json.Marshal at byte %d:\n got %s\n want %s", firstDiff(got.Bytes(), want), got.Bytes(), want) + } +} + +// TestEncode_LargeSourceIsStreamed (#80): writing an artifact's source does not +// build its escaped JSON in memory. A 64 MB source allocates far less than its +// size (json.Marshal allocates about 2 to 3 times it). +func TestEncode_LargeSourceIsStreamed(t *testing.T) { + const size = 64 << 20 + tree := artifactTree(map[string]string{"data.csv": strings.Repeat("abcdefghij,<0123456789>\n", size/24)}) + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + if err := Encode(discardWriter{}, tree); err != nil { + t.Fatal(err) + } + runtime.ReadMemStats(&after) + if got := after.TotalAlloc - before.TotalAlloc; got > size/8 { + t.Errorf("Encode allocated %d MB for a %d MB source; want under %d MB (streamed)", got>>20, size>>20, size/8>>20) + } +} + +type discardWriter struct{} + +func (discardWriter) Write(p []byte) (int, error) { return len(p), nil } +func (discardWriter) WriteString(s string) (int, error) { return len(s), nil } diff --git a/internal/syntactic_analysis/v2emit/artifacts_stream.go b/internal/syntactic_analysis/v2emit/artifacts_stream.go new file mode 100644 index 0000000..0cadfcd --- /dev/null +++ b/internal/syntactic_analysis/v2emit/artifacts_stream.go @@ -0,0 +1,197 @@ +package v2emit + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "slices" + "unicode/utf8" + + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" +) + +// The artifacts are written one at a time, and each source is escaped straight +// to w (#80). json.Marshal of an artifact would build the escaped source in a +// growing buffer and then copy it: 2 to 3 times a large file's size. + +// artifactsHoleKey stands in for the artifacts when the envelope is marshalled. +// No artifact path contains a NUL byte, so it is not a real key. +const artifactsHoleKey = "\x00artifacts" + +// sourceMarker stands in for a non-empty source when one artifact is +// marshalled; the real source is streamed in its place. +const sourceMarker = "\x00source" + +// artifactsHole is the bytes json.Marshal writes for the stand-in map. +var artifactsHole = func() []byte { + b, err := json.Marshal(map[string]v2.Artifact{artifactsHoleKey: {}}) + if err != nil { + panic(err) + } + return b +}() + +var sourceNeedle = func() []byte { + b, err := json.Marshal(sourceMarker) + if err != nil { + panic(err) + } + return append([]byte(`"source":`), b...) +}() + +// writeWithArtifacts writes seg, with the stand-in artifacts map replaced by +// arts written one at a time. With no artifacts it writes seg unchanged. +func writeWithArtifacts(w io.Writer, seg []byte, arts map[string]v2.Artifact) error { + if len(arts) == 0 { + _, err := w.Write(seg) + return err + } + i := bytes.Index(seg, artifactsHole) + if i < 0 { + return fmt.Errorf("v2emit: no artifacts stand-in in the envelope") + } + if _, err := w.Write(seg[:i]); err != nil { + return err + } + if err := writeArtifacts(w, arts); err != nil { + return err + } + _, err := w.Write(seg[i+len(artifactsHole):]) + return err +} + +// writeArtifacts writes arts as json.Marshal writes the map: keys in sorted +// order, each a JSON string. +func writeArtifacts(w io.Writer, arts map[string]v2.Artifact) error { + keys := make([]string, 0, len(arts)) + for k := range arts { + keys = append(keys, k) + } + slices.Sort(keys) + if _, err := io.WriteString(w, "{"); err != nil { + return err + } + for i, k := range keys { + if i > 0 { + if _, err := io.WriteString(w, ","); err != nil { + return err + } + } + if err := writeJSONString(w, k); err != nil { + return err + } + if _, err := io.WriteString(w, ":"); err != nil { + return err + } + if err := writeArtifact(w, arts[k]); err != nil { + return err + } + } + _, err := io.WriteString(w, "}") + return err +} + +// writeArtifact writes a as json.Marshal does, with its source streamed. +func writeArtifact(w io.Writer, a v2.Artifact) error { + src := a.Source + if src != "" { + a.Source = sourceMarker + } + data, err := json.Marshal(a) + if err != nil { + return err + } + if src == "" { + _, err = w.Write(data) + return err + } + i := bytes.Index(data, sourceNeedle) + if i < 0 { + return fmt.Errorf("v2emit: no source stand-in in artifact %s", a.Path) + } + if _, err := w.Write(data[:i+len(`"source":`)]); err != nil { + return err + } + if err := writeJSONString(w, src); err != nil { + return err + } + _, err = w.Write(data[i+len(sourceNeedle):]) + return err +} + +// asciiEscapes holds, for each ASCII byte that encoding/json escapes, its +// escape; "" means the byte is written as it is. Built once, so a large source +// full of '<' or newlines makes no per-byte allocation. +var asciiEscapes = func() (t [utf8.RuneSelf]string) { + const hexDigits = "0123456789abcdef" + for b := range byte(0x20) { + t[b] = `\u00` + string(hexDigits[b>>4]) + string(hexDigits[b&0xF]) + } + t['"'], t['\\'] = `\"`, `\\` + t['\b'], t['\f'], t['\n'], t['\r'], t['\t'] = `\b`, `\f`, `\n`, `\r`, `\t` + t['<'], t['>'], t['&'] = `\u003c`, `\u003e`, `\u0026` + return t +}() + +// writeJSONString writes s as a JSON string, byte for byte as encoding/json +// writes it with HTML escaping (its default): '<', '>' and '&' as \u003c, +// \u003e, \u0026; \b \f \n \r \t; other bytes below 0x20 as \u00XX; U+2028 +// and U+2029 escaped; each invalid UTF-8 byte as the character U+FFFD. Runs of plain bytes are written +// as they are, so no escaped copy of s is built. +func writeJSONString(w io.Writer, s string) error { + if _, err := io.WriteString(w, `"`); err != nil { + return err + } + start := 0 + flush := func(i int, esc string) error { + if start < i { + if _, err := io.WriteString(w, s[start:i]); err != nil { + return err + } + } + _, err := io.WriteString(w, esc) + return err + } + for i := 0; i < len(s); { + b := s[i] + if b < utf8.RuneSelf { + esc := asciiEscapes[b] + if esc == "" { + i++ + continue + } + if err := flush(i, esc); err != nil { + return err + } + i++ + start = i + continue + } + r, size := utf8.DecodeRuneInString(s[i:]) + var esc string + switch { + case r == utf8.RuneError && size == 1: + esc = string(utf8.RuneError) // written as the character, not escaped + case r == '\u2028': + esc = `\u2028` + case r == '\u2029': + esc = `\u2029` + default: + i += size + continue + } + if err := flush(i, esc); err != nil { + return err + } + i += size + start = i + } + if start < len(s) { + if _, err := io.WriteString(w, s[start:]); err != nil { + return err + } + } + _, err := io.WriteString(w, `"`) + return err +} diff --git a/internal/syntactic_analysis/v2emit/emit.go b/internal/syntactic_analysis/v2emit/emit.go index 16dad46..5c19272 100644 --- a/internal/syntactic_analysis/v2emit/emit.go +++ b/internal/syntactic_analysis/v2emit/emit.go @@ -134,6 +134,12 @@ func encode(w io.Writer, env *v2.Analysis, modules iter.Seq2[string, v2.Module], shell := *env shell.Application.SymbolTable = map[string]v2.Module{} shell.Application.ParamIn, shell.Application.ParamOut, shell.Degraded = nil, nil, nil + // The artifacts follow symbol_table; they are written one at a time, each + // source streamed, in place of a stand-in (writeWithArtifacts). + arts := env.Application.Artifacts + if len(arts) > 0 { + shell.Application.Artifacts = map[string]v2.Artifact{artifactsHoleKey: {}} + } data, err := json.Marshal(&shell) if err != nil { return err @@ -158,7 +164,7 @@ func encode(w io.Writer, env *v2.Analysis, modules iter.Seq2[string, v2.Module], } first = false } - if _, err := w.Write(data[split : len(data)-2]); err != nil { + if err := writeWithArtifacts(w, data[split:len(data)-2], arts); err != nil { return err } lf := late() From b8618cff834d8b2847ae7bcb2c465d3c64028e08 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Mon, 30 Nov 2026 09:08:10 -0500 Subject: [PATCH 3/3] perf(neo4j): stream large values into the snapshot, limit Bolt node batches by size (#80) Since #83 the :Artifact node carries source, so the Neo4j writers handle whole files. - Snapshot: each node row was rendered as strings first (cypherString, then cypherMap's concatenation and strings.Join, then fmt.Fprintf): a 64 MB source allocated 553 MB. writeCypherValue, writeCypherString and writeCypherMap now write straight to the file, and cypherValue / cypherString / cypherMap wrap them, so the output is unchanged. - Bolt: a node batch was limited only by count (5,000 rows), so a batch of large files could exceed the server's transaction memory. A node group is now also flushed when its rows' text reaches boltBatchBytes (16 MiB); a larger row goes alone. With one 512 MB text file, both a JSON run and a Neo4j snapshot run now peak at 0.56 GB (before this branch: 2.72 GB and 3.57 GB). Tests: the value writers match the string functions; the snapshot of a 64 MB source allocates under 16 MB (553 MB on the old code); Bolt node batches stay under the byte limit and a larger row goes alone. All live Neo4j integration tests pass. Co-Authored-By: Claude Opus 5.5 --- .../specs/2026-11-24-neo4j-streaming-push.md | 1 + internal/neo4j/bolt.go | 42 ++++++- internal/neo4j/cypher.go | 6 +- internal/neo4j/large_text_test.go | 99 +++++++++++++++ internal/neo4j/rows.go | 117 ++++++++++++------ 5 files changed, 224 insertions(+), 41 deletions(-) create mode 100644 internal/neo4j/large_text_test.go diff --git a/docs/design/specs/2026-11-24-neo4j-streaming-push.md b/docs/design/specs/2026-11-24-neo4j-streaming-push.md index dfa2ac9..973860c 100644 --- a/docs/design/specs/2026-11-24-neo4j-streaming-push.md +++ b/docs/design/specs/2026-11-24-neo4j-streaming-push.md @@ -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 | diff --git a/internal/neo4j/bolt.go b/internal/neo4j/bolt.go index 24a047e..60d3e75 100644 --- a/internal/neo4j/bolt.go +++ b/internal/neo4j/bolt.go @@ -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. @@ -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). @@ -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) { @@ -608,6 +643,7 @@ func (w *boltWriter) flushNodes() error { } } clear(w.nodeBuf) + clear(w.nodeBytes) return nil } diff --git a/internal/neo4j/cypher.go b/internal/neo4j/cypher.go index 0d1b02d..d804efa 100644 --- a/internal/neo4j/cypher.go +++ b/internal/neo4j/cypher.go @@ -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) diff --git a/internal/neo4j/large_text_test.go b/internal/neo4j/large_text_test.go new file mode 100644 index 0000000..f965d86 --- /dev/null +++ b/internal/neo4j/large_text_test.go @@ -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) + } +} diff --git a/internal/neo4j/rows.go b/internal/neo4j/rows.go index b4c6787..b574547 100644 --- a/internal/neo4j/rows.go +++ b/internal/neo4j/rows.go @@ -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 @@ -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,