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
15 changes: 13 additions & 2 deletions cmd/codeanalyzer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"os"
"path/filepath"
"runtime"
"runtime/debug"

"github.com/spf13/cobra"

Expand Down Expand Up @@ -137,6 +138,12 @@ via CLDK(language="go").analysis(project_path=...).`,
return fmt.Errorf("unsupported output format %q; supported: json", format)
}
utils.SetVerbosity(verbosity)
// In a container, let the GC collect harder near the container's
// limit instead of letting garbage push the process over it (#62).
if limit, ok := utils.SystemCgroupMemoryLimit(); ok {
debug.SetMemoryLimit(limit)
utils.Info("Go memory limit %s (85%% of the container's memory limit)", utils.FormatBytes(uint64(limit)))
}

if cacheDir == "" {
home, _ := os.UserHomeDir()
Expand Down Expand Up @@ -191,6 +198,7 @@ via CLDK(language="go").analysis(project_path=...).`,
if err != nil {
return err
}
utils.LogMemory("analysis")

// Neo4j projection: stream the canonical v2 payload (the SAME modules
// the JSON path emits) one module at a time into the projection, so
Expand Down Expand Up @@ -218,9 +226,12 @@ via CLDK(language="go").analysis(project_path=...).`,
// writer so tests can capture it via cmd.SetOut. Both paths render
// through core so the schema selection stays in one place.
if outputDir == "" {
return core.StreamJSON(cmd.OutOrStdout(), app, analyzer.L3(), analyzer.L4(), opts)
err = core.StreamJSON(cmd.OutOrStdout(), app, analyzer.L3(), analyzer.L4(), opts)
} else {
err = core.WriteOutput(app, analyzer.L3(), analyzer.L4(), opts)
}
return core.WriteOutput(app, analyzer.L3(), analyzer.L4(), opts)
utils.LogMemory("JSON output")
return err
},
}

Expand Down
4 changes: 2 additions & 2 deletions docs/design/specs/2026-11-24-neo4j-streaming-push.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ At the end of each phase it flushes every buffer.
| 2 | Pass 1, for each module in order: read its stored `content_hash`. If the module changed or a full upsert is forced, purge it (`--eager` only) and push its L1–L3 nodes. Always push its L4 vertex nodes, after its purge. | A module purge deletes only ids under that module prefix. So "purge m, then upsert m's L4 vertices" keeps D5 for each module. |
| 3 | Push the ghost nodes, the stand-in vertex nodes, and the application node with `degraded_json`. | The degraded list is complete only after pass 1. |
| 4 | Pass 2, for each module: push every edge. Then push `GO_CALLS`, the stand-in `GO_HAS_BODY_NODE` edges, `GO_PARAM_IN` and `GO_PARAM_OUT`. | Every node is in the DB before the first edge, so no edge `MATCH` fails. |
| 5 | `pruneVanishedModules` (full + eager only), with the module ids from the symbol table keys. | Same as today. |
| 5 | Flush the edges. A full eager push prunes nothing here: step 0 deleted every Go node of the app, and the push wrote back only the present modules (#61 removed `pruneVanishedModules`). | Nothing is left to delete. |

Step 2 stages each node row with the module that owns it (`NodeRow.Module`), not with the module that is projected.
These are different for a cross-file method: it nests under its receiver's type, but its declaring file owns it and its id has that file's prefix.
Expand Down Expand Up @@ -229,7 +229,7 @@ The rejected option S2 kept the snapshot on `Project`. With S2, large apps still
- The writer pushes the application node after pass 1, because `degraded_json` needs the full module walk.
- The client does not remove duplicate edge rows across modules. `MERGE` makes them no-ops.
- The emitter source cache keeps every file's source text for the whole run, as it does today. On nats-server this is small.
- `pruneVanishedModules` and `purgeModuleQuery` stay unbatched. A follow-up issue can batch them.
- `pruneVanishedModules` and `purgeModuleQuery` stay unbatched. A follow-up issue can batch them. (#61 batched `purgeModuleQuery` and removed `pruneVanishedModules`, which deleted nothing after the whole-app purge.)
- The Neo4j container uses the official image with environment settings. A separate Neo4j Dockerfile adds nothing.
- The two containers together need 28 GB. The local Docker VM has 33.6 GB.
- The harness reads the peak from `memory.peak` inside the `cango` container, after `cango` exits. A wrapper shell command prints it.
Expand Down
12 changes: 12 additions & 0 deletions internal/memtest/memtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ func Tail(s string, n int) string {
return strings.Join(lines, "\n")
}

// MemoryLines returns cango's memory log lines from logs: the Go memory limit
// and the memory after each stage (-v), in order.
func MemoryLines(logs string) []string {
var out []string
for _, l := range strings.Split(logs, "\n") {
if strings.Contains(l, "memory after ") || strings.Contains(l, "Go memory limit ") {
out = append(out, strings.TrimSpace(l))
}
}
return out
}

// AppName turns an app directory's base name into the cango --app-name value.
// Bytes outside [A-Za-z0-9._-] become '-', so the name is valid for v2.ResolveIdentity
// (no slash, no control character, valid UTF-8) and needs no escaping in the can:// id.
Expand Down
3 changes: 3 additions & 0 deletions internal/memtest/memtest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ func runCango(t *testing.T, ctx context.Context, nw *testcontainers.DockerNetwor
logs := containerLogs(t, ctx, c)
v := Decide(app, st.ExitCode, st.OOMKilled, logs, limit)
t.Log(v.Line)
for _, l := range MemoryLines(logs) {
t.Log(l)
}
if v.Failed {
t.Errorf("cango failed. Last log lines:\n%s", Tail(logs, 40))
}
Expand Down
13 changes: 13 additions & 0 deletions internal/memtest/memtest_unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,16 @@ func TestDecide(t *testing.T) {
}
}
}

func TestMemoryLines(t *testing.T) {
logs := "[codeanalyzer-go] Go memory limit 13.60 GiB (85% of the container's memory limit)\n" +
"[codeanalyzer-go] L4: VTA over 10 functions\n" +
"[codeanalyzer-go] memory after analysis: live heap 5.00 GiB, from the OS 9.00 GiB\n" +
"MEMTEST_PEAK=123\n"
got := strings.Join(MemoryLines(logs), "|")
want := "[codeanalyzer-go] Go memory limit 13.60 GiB (85% of the container's memory limit)|" +
"[codeanalyzer-go] memory after analysis: live heap 5.00 GiB, from the OS 9.00 GiB"
if got != want {
t.Errorf("MemoryLines = %q, want %q", got, want)
}
}
109 changes: 109 additions & 0 deletions internal/neo4j/batched_delete_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
//go:build neo4j_it

package neo4j

import (
"context"
"fmt"
"slices"
"testing"

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

// Live tests for the batched deletes (#61). They need a database with a small
// per-transaction memory limit, so an unbatched delete of a large module is
// refused:
//
// docker run --rm -p7687:7687 -e NEO4J_AUTH=neo4j/testpass \
// -e NEO4J_db_memory_transaction_max=128m neo4j:5
//
// They skip when the database has no such limit.

// withBigModule adds bigModuleFunctions functions with bigModuleClosures
// closures each. Deleting them and their GO_DECLARES edges in one transaction
// needs more than the test limit; no node has more than about 600
// relationships, as in a real graph, so a batch of nodes stays small.
const (
bigModuleFunctions = 600
bigModuleClosures = 100
)

// requireTxLimit skips the test unless the database limits the memory of one
// transaction (db.memory.transaction.max is not 0).
func requireTxLimit(t *testing.T, ctx context.Context, cfg BoltConfig) {
t.Helper()
n := countIT(t, ctx, cfg,
"SHOW SETTINGS YIELD name, value WHERE name = 'db.memory.transaction.max' AND NOT value STARTS WITH '0' RETURN count(*)", nil)
if n == 0 {
t.Skip("set db.memory.transaction.max (for example 128m) to run the batched-delete tests")
}
}

// withBigModule grows a's first module and sets its content_hash to hash.
func withBigModule(a *v2.Analysis, hash string) {
k := firstModuleFile(a)
m := a.Application.SymbolTable[k]
if m.Functions == nil {
m.Functions = map[string]v2.Callable{}
}
for i := range bigModuleFunctions {
name := fmt.Sprintf("generated%d", i)
fn := v2.Callable{ID: m.ID + "/" + name, Kind: "function", Signature: m.Package + "." + name,
Callables: map[string]v2.Callable{}}
for j := 1; j <= bigModuleClosures; j++ {
c := fmt.Sprintf("closure_%d", j)
fn.Callables[c] = v2.Callable{ID: fn.ID + "/" + c, Kind: "lambda", Signature: fn.Signature + "." + c}
}
m.Functions[name] = fn
}
m.ContentHash = hash
a.Application.SymbolTable[k] = m
}

// An --eager -t push purges each changed module before it upserts it again.
// A large module must be purged in batches, not in one transaction.
func TestIntegration_EagerPartialPushPurgesLargeModuleInBatches(t *testing.T) {
ctx := context.Background()
cfg := itConfig(t)
requireTxLimit(t, ctx, cfg)

a := buildMultipackageL2(t)
withBigModule(a, "before")
full := cfg
full.Eager, full.FullRun = true, true
pushIT(t, ctx, a, full)
t.Cleanup(func() { pushIT(t, ctx, buildMultipackageL2(t), full) })

app := a.Application.ID
gen := "MATCH (n:GoCallable) WHERE n.id STARTS WITH $p AND n.id CONTAINS '/generated' RETURN count(n)"
p := map[string]any{"p": app + "/"}
want := bigModuleFunctions * (1 + bigModuleClosures)
if got := countIT(t, ctx, cfg, gen, p); got != want {
t.Fatalf("seed: %d generated callables, want %d", got, want)
}

// The module changed and lost its generated functions.
b := buildMultipackageL2(t)
k := firstModuleFile(b)
m := b.Application.SymbolTable[k]
m.ContentHash = "after"
b.Application.SymbolTable[k] = m
partial := cfg
partial.Eager = true
pushIT(t, ctx, b, partial)

if got := countIT(t, ctx, cfg, gen, p); got != 0 {
t.Errorf("after the --eager -t push: %d generated callables, want 0 (the module purge removes them)", got)
}
}

// firstModuleFile is the first symbol_table key, the module withBigModule grows.
func firstModuleFile(a *v2.Analysis) string {
keys := make([]string, 0, len(a.Application.SymbolTable))
for k := range a.Application.SymbolTable {
keys = append(keys, k)
}
slices.Sort(keys)
return keys[0]
}
46 changes: 17 additions & 29 deletions internal/neo4j/bolt.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"maps"
"slices"
"sort"
"strconv"

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

Expand Down Expand Up @@ -87,6 +88,10 @@ const boltBatchSize = 5000
// alone.
const boltBatchBytes = 16 << 20

// deleteBatchSize is the most nodes one transaction of a batched DETACH DELETE
// removes (#61). A node's relationships go in the same transaction.
const deleteBatchSize = 5000

// 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 @@ -321,15 +326,11 @@ func (w *boltWriter) edges(edges []EdgeRow) error {
return w.bufferEdges(edges)
}

// end flushes the edges and, on a full --eager run, prunes vanished modules.
func (w *boltWriter) end(moduleIDs []string) error {
if err := w.flushEdges(); err != nil {
return err
}
if w.cfg.Eager && w.cfg.FullRun && w.scoped {
return w.pruneVanishedModules(moduleIDs)
}
return nil
// end flushes the edges. A full --eager run has nothing left to prune: begin
// deleted every Go node of the app, and this run wrote back only the present
// modules.
func (w *boltWriter) end() error {
return w.flushEdges()
}

// ─── DDL + version gate ───────────────────────────────────────────────────────
Expand Down Expand Up @@ -433,12 +434,10 @@ func (w *boltWriter) eagerPurge(root string) error {

// purgeModule deletes the edges and declarations a module owned, scoped to its
// id prefix, so a re-analyzed module's stale facts are removed before re-upsert.
// It is batched, so it runs as an implicit transaction.
func (w *boltWriter) purgeModule(moduleID string) error {
q, params := purgeModuleQuery(moduleID)
return w.write(func(tx neo4j.ManagedTransaction) error {
_, err := tx.Run(w.ctx, q, params)
return err
})
return w.autoCommit(q, params)
}

// eagerPurgeQuery / purgeModuleQuery are pure so the destructive-scope gate can
Expand All @@ -449,7 +448,7 @@ func eagerPurgeQuery(root string) (string, map[string]any) {
// :Artifact is shared with the sibling analyzers, so it is reconciled
// (reconcileArtifacts), never deleted wholesale here.
return "MATCH (n:GoCanNode) WHERE (n.id STARTS WITH $p OR n.id = $root) AND NOT n:" + LabelArtifact + " " +
"CALL (n) { DETACH DELETE n } IN TRANSACTIONS OF 5000 ROWS",
"CALL (n) { DETACH DELETE n } IN TRANSACTIONS OF " + strconv.Itoa(deleteBatchSize) + " ROWS",
map[string]any{"p": descendantPrefix(root), "root": root}
}

Expand Down Expand Up @@ -504,25 +503,14 @@ func (w *boltWriter) reconcileArtifacts(nodes []NodeRow) error {
return w.autoCommit(q, p)
}

// purgeModuleQuery is batched like eagerPurgeQuery: a large module in one
// transaction can exceed the server's transaction memory limit (#61).
func purgeModuleQuery(moduleID string) (string, map[string]any) {
return "MATCH (n:GoCanNode) WHERE n.id = $m OR n.id STARTS WITH $p DETACH DELETE n",
return "MATCH (n:GoCanNode) WHERE n.id = $m OR n.id STARTS WITH $p " +
"CALL (n) { DETACH DELETE n } IN TRANSACTIONS OF " + strconv.Itoa(deleteBatchSize) + " ROWS",
map[string]any{"m": moduleID, "p": descendantPrefix(moduleID)}
}

// pruneVanishedModules removes modules under the app prefix that this run no
// longer emits (their source file vanished). Full + eager only.
func (w *boltWriter) pruneVanishedModules(present []string) error {
root, _ := applicationPrefix(w.appID)
desc := descendantPrefix(root)
return w.write(func(tx neo4j.ManagedTransaction) error {
_, err := tx.Run(w.ctx,
"MATCH (m:GoModule) WHERE m.id STARTS WITH $p AND NOT m.id IN $present "+
"MATCH (n:GoCanNode) WHERE n.id = m.id OR n.id STARTS WITH m.id + '/' DETACH DELETE n",
map[string]any{"p": desc, "present": present})
return err
})
}

// ─── diff ─────────────────────────────────────────────────────────────────────

// moduleChanged compares a module's local content_hash against the DB's.
Expand Down
36 changes: 36 additions & 0 deletions internal/neo4j/bolt_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import (
"context"
"fmt"
"os"
"slices"
"strings"
"testing"

"github.com/neo4j/neo4j-go-driver/v5/neo4j"
Expand Down Expand Up @@ -303,3 +305,37 @@ func TestIntegration_CleanLazyPushClearsDegradedJSON(t *testing.T) {
t.Errorf("clean lazy push left degraded_json = %v", v)
}
}

// An eager full push leaves no module the run no longer has: begin deletes the
// app's Go nodes, and the push writes back only the present modules (#61).
func TestIntegration_EagerFullPushRemovesVanishedModule(t *testing.T) {
ctx := context.Background()
cfg := itConfig(t)
cfg.Eager, cfg.FullRun = true, true

a := buildMultipackageL2(t)
if err := WriteBolt(ctx, Project(a), a.Application.ID, cfg); err != nil {
t.Fatalf("seed: %v", err)
}
gone := firstModuleFile(a)
id := a.Application.SymbolTable[gone].ID
under := "MATCH (n:GoCanNode) WHERE n.id = $m OR n.id STARTS WITH $p RETURN count(n)"
p := map[string]any{"m": id, "p": id + "/"}
if got := countIT(t, ctx, cfg, under, p); got == 0 {
t.Fatalf("seed wrote no node under %s", id)
}

// The run no longer has the file, so it has none of its calls either.
b := buildMultipackageL2(t)
delete(b.Application.SymbolTable, gone)
b.Application.CallGraph = slices.DeleteFunc(b.Application.CallGraph, func(e v2.Edge) bool {
return strings.HasPrefix(e.Src, id+"/") || strings.HasPrefix(e.Dst, id+"/")
})
if err := WriteBolt(ctx, Project(b), b.Application.ID, cfg); err != nil {
t.Fatalf("push without %s: %v", gone, err)
}
if got := countIT(t, ctx, cfg, under, p); got != 0 {
t.Errorf("%d nodes under the vanished module %s, want 0", got, id)
}
t.Cleanup(func() { _ = WriteBolt(ctx, Project(buildMultipackageL2(t)), a.Application.ID, cfg) })
}
8 changes: 8 additions & 0 deletions internal/neo4j/bolt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@ func TestDestructiveQueries_AreScopedAndAnchored(t *testing.T) {
if pp["p"] != "can://app/app/go/x.go/" || pp["m"] != "can://app/app/go/x.go" {
t.Errorf("purgeModule params not the module prefix+id: %v", pp)
}

// Both run in batches: one transaction over a large app or module can
// exceed the server's transaction memory limit (#61).
for name, q := range map[string]string{"eagerPurge": eq, "purgeModule": pq} {
if !strings.Contains(q, "IN TRANSACTIONS OF 5000 ROWS") {
t.Errorf("%s: not batched: %q", name, q)
}
}
}

func assertScoped(t *testing.T, name, q string, params map[string]any) {
Expand Down
2 changes: 1 addition & 1 deletion internal/neo4j/cypher.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ func (c *cypherWriter) edges(edges []EdgeRow) error {
}

// end flushes the edge groups in key order and closes the last section.
func (c *cypherWriter) end([]string) error {
func (c *cypherWriter) end() error {
for _, gk := range sortedEdgeKeys(c.edgeBuf) {
if g := c.edgeBuf[gk]; len(g) > 0 {
writeEdgeChunk(c.w, g)
Expand Down
Loading
Loading