From 581595818a69960337afda6b3c5d03df6b99c0c9 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Mon, 30 Nov 2026 11:19:46 -0500 Subject: [PATCH 1/3] fix(neo4j): batch the module purge, and drop the prune that deleted nothing (#61) An --eager -t push purged each changed module in one transaction, so a large module could exceed the server's transaction memory limit. The purge now runs as CALL { DETACH DELETE } IN TRANSACTIONS OF 5000 ROWS, like the whole-app purge. pruneVanishedModules ran on an eager full push after the whole-app purge had already deleted every Go node of the app, so it never found anything. It is removed, and the stager's end no longer takes the module ids. A live test pins that an eager full push leaves no vanished module. The batched-purge live test needs a database with a per-transaction limit (db.memory.transaction.max=128m) and skips without one. --- .../specs/2026-11-24-neo4j-streaming-push.md | 4 +- .../neo4j/batched_delete_integration_test.go | 109 ++++++++++++++++++ internal/neo4j/bolt.go | 46 +++----- internal/neo4j/bolt_integration_test.go | 36 ++++++ internal/neo4j/bolt_test.go | 8 ++ internal/neo4j/cypher.go | 2 +- internal/neo4j/stream.go | 13 +-- internal/neo4j/stream_test.go | 11 +- 8 files changed, 180 insertions(+), 49 deletions(-) create mode 100644 internal/neo4j/batched_delete_integration_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 973860c..62ceedb 100644 --- a/docs/design/specs/2026-11-24-neo4j-streaming-push.md +++ b/docs/design/specs/2026-11-24-neo4j-streaming-push.md @@ -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. @@ -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. diff --git a/internal/neo4j/batched_delete_integration_test.go b/internal/neo4j/batched_delete_integration_test.go new file mode 100644 index 0000000..a59a54d --- /dev/null +++ b/internal/neo4j/batched_delete_integration_test.go @@ -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] +} diff --git a/internal/neo4j/bolt.go b/internal/neo4j/bolt.go index 60d3e75..bb956f7 100644 --- a/internal/neo4j/bolt.go +++ b/internal/neo4j/bolt.go @@ -6,6 +6,7 @@ import ( "maps" "slices" "sort" + "strconv" v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" @@ -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. @@ -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 ─────────────────────────────────────────────────────── @@ -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 @@ -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} } @@ -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. diff --git a/internal/neo4j/bolt_integration_test.go b/internal/neo4j/bolt_integration_test.go index d9a675c..fea22b3 100644 --- a/internal/neo4j/bolt_integration_test.go +++ b/internal/neo4j/bolt_integration_test.go @@ -18,6 +18,8 @@ import ( "context" "fmt" "os" + "slices" + "strings" "testing" "github.com/neo4j/neo4j-go-driver/v5/neo4j" @@ -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) }) +} diff --git a/internal/neo4j/bolt_test.go b/internal/neo4j/bolt_test.go index 87065a9..b9f42bf 100644 --- a/internal/neo4j/bolt_test.go +++ b/internal/neo4j/bolt_test.go @@ -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) { diff --git a/internal/neo4j/cypher.go b/internal/neo4j/cypher.go index d804efa..d0c637f 100644 --- a/internal/neo4j/cypher.go +++ b/internal/neo4j/cypher.go @@ -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) diff --git a/internal/neo4j/stream.go b/internal/neo4j/stream.go index 27ff599..51faedd 100644 --- a/internal/neo4j/stream.go +++ b/internal/neo4j/stream.go @@ -21,7 +21,7 @@ type stager interface { owned(id string, nodes []NodeRow) error // step 2: more rows of a module already staged late(nodes []NodeRow) error // step 3: ghosts, stand-ins, application row edges(edges []EdgeRow) error // step 4: called many times - end(moduleIDs []string) error // step 5: flush, prune + end() error // step 5: flush } // streamGraph projects src into st in two module walks. Pass 1 sends the node @@ -150,11 +150,7 @@ func streamGraph(src Source, st stager) (nodes, edges int, err error) { return } // Step 5. - moduleIDs := make([]string, len(keys)) - for i, k := range keys { - moduleIDs[i] = v2.ModuleID(env.Application.ID, k) - } - err = st.end(moduleIDs) + err = st.end() return } @@ -220,8 +216,7 @@ func replayRows(rows GraphRows, st stager) (nodes, edges int, err error) { return } nodes += len(shared) - ids := sortedModuleKeys(byModule) - for _, id := range ids { + for _, id := range sortedModuleKeys(byModule) { if err = st.module(id, byModule[id]); err != nil { return } @@ -235,7 +230,7 @@ func replayRows(rows GraphRows, st stager) (nodes, edges int, err error) { return } edges = len(rows.Edges) - err = st.end(ids) + err = st.end() return } diff --git a/internal/neo4j/stream_test.go b/internal/neo4j/stream_test.go index 01b0ad4..bbebe48 100644 --- a/internal/neo4j/stream_test.go +++ b/internal/neo4j/stream_test.go @@ -17,7 +17,6 @@ type collectStager struct { nodes []NodeRow edgeRows []EdgeRow mods []string - endIDs []string } func (c *collectStager) begin(app NodeRow) error { @@ -57,9 +56,8 @@ func (c *collectStager) edges(e []EdgeRow) error { return nil } -func (c *collectStager) end(ids []string) error { +func (c *collectStager) end() error { c.stages = append(c.stages, "end") - c.endIDs = ids return nil } @@ -230,9 +228,6 @@ func TestStream_StageOrder(t *testing.T) { if !slices.IsSorted(c.mods) || len(c.mods) != len(a.Application.SymbolTable) { t.Errorf("modules %v", c.mods) } - if !slices.Equal(c.endIDs, c.mods) { - t.Errorf("end ids %v, module ids %v", c.endIDs, c.mods) - } for _, n := range c.nodes[1:] { // c.nodes[0] is the begin row if n.Labels[0] == LabelApplication { if _, ok := n.Props["degraded_json"]; ok != (len(a.Degraded) > 0) { @@ -281,8 +276,8 @@ func TestReplayRows_SplitsAReadyGraphRows(t *testing.T) { if s := strings.Join(c.stages, ","); !regexp.MustCompile(`^begin,shared,(module,)+late,edges,end$`).MatchString(s) { t.Errorf("stages %s", s) } - if c.nodes[0].Labels[0] != LabelApplication || !slices.IsSorted(c.mods) || !slices.Equal(c.endIDs, c.mods) { - t.Errorf("begin row %v, modules %v, end ids %v", c.nodes[0].Labels, c.mods, c.endIDs) + if c.nodes[0].Labels[0] != LabelApplication || !slices.IsSorted(c.mods) { + t.Errorf("begin row %v, modules %v", c.nodes[0].Labels, c.mods) } if d := diffRows(rows, mergeRows(c.nodes, c.edgeRows)); d != "" { t.Errorf("replayed rows differ:\n%s", d) From 655923d324911086a75c0890336ec9bc383478dd Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Mon, 30 Nov 2026 11:24:03 -0500 Subject: [PATCH 2/3] perf(cli): set a Go memory limit from the container's, and log memory per stage (#62) In a container with a cgroup v2 memory limit, cango now sets the Go memory limit to 85 % of it, unless GOMEMLIMIT is set. The GC then collects harder near the limit, instead of letting garbage push the process over it. With no cgroup limit (macOS, a plain host) nothing changes. Under -v, cango logs the live heap, the memory held from the OS and the peak RSS after the analysis, after each Neo4j pass and after the JSON output, so a run's log shows which stage reaches the peak. --- cmd/codeanalyzer/main.go | 15 +++++++++-- internal/neo4j/stream.go | 3 +++ internal/utils/memlimit.go | 38 +++++++++++++++++++++++++++ internal/utils/memlimit_test.go | 46 +++++++++++++++++++++++++++++++++ internal/utils/memory.go | 41 +++++++++++++++++++++++++++++ internal/utils/memory_darwin.go | 12 +++++++++ internal/utils/memory_linux.go | 12 +++++++++ internal/utils/memory_other.go | 6 +++++ 8 files changed, 171 insertions(+), 2 deletions(-) create mode 100644 internal/utils/memlimit.go create mode 100644 internal/utils/memlimit_test.go create mode 100644 internal/utils/memory.go create mode 100644 internal/utils/memory_darwin.go create mode 100644 internal/utils/memory_linux.go create mode 100644 internal/utils/memory_other.go diff --git a/cmd/codeanalyzer/main.go b/cmd/codeanalyzer/main.go index 480f391..bb33a28 100644 --- a/cmd/codeanalyzer/main.go +++ b/cmd/codeanalyzer/main.go @@ -10,6 +10,7 @@ import ( "os" "path/filepath" "runtime" + "runtime/debug" "github.com/spf13/cobra" @@ -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() @@ -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 @@ -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 }, } diff --git a/internal/neo4j/stream.go b/internal/neo4j/stream.go index 51faedd..add4ecf 100644 --- a/internal/neo4j/stream.go +++ b/internal/neo4j/stream.go @@ -6,6 +6,7 @@ import ( "slices" v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/utils" ) // stager consumes the projection in push order (spec §5.3): every node stage @@ -115,6 +116,7 @@ func streamGraph(src Source, st stager) (nodes, edges int, err error) { return } nodes += len(lateRows) + utils.LogMemory("Neo4j pass 1") // Step 4, pass 2: edges. GO_EMBEDS / GO_SATISFIES resolve against every // :GoSymbol id: the declared ids and the late ghosts. @@ -151,6 +153,7 @@ func streamGraph(src Source, st stager) (nodes, edges int, err error) { } // Step 5. err = st.end() + utils.LogMemory("Neo4j pass 2") return } diff --git a/internal/utils/memlimit.go b/internal/utils/memlimit.go new file mode 100644 index 0000000..b543cc5 --- /dev/null +++ b/internal/utils/memlimit.go @@ -0,0 +1,38 @@ +package utils + +import ( + "os" + "strconv" + "strings" +) + +// cgroupMemoryMax is the cgroup v2 memory limit of the process's container. +const cgroupMemoryMax = "/sys/fs/cgroup/memory.max" + +// memoryLimitShare is the part of the cgroup limit the Go heap may use. The +// rest covers the page cache, goroutine stacks and the runtime's own use. +const memoryLimitShare = 0.85 + +// CgroupMemoryLimit returns the Go memory limit for this process: 85 % of the +// cgroup's memory.max (#62). It returns false when the user set GOMEMLIMIT +// (which wins), or when there is no cgroup limit (no file, or "max"), as on +// macOS or a plain host. +func CgroupMemoryLimit(getenv func(string) string, readFile func(string) ([]byte, error)) (int64, bool) { + if getenv("GOMEMLIMIT") != "" { + return 0, false + } + data, err := readFile(cgroupMemoryMax) + if err != nil { + return 0, false + } + n, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64) + if err != nil || n <= 0 { + return 0, false // "max": no limit + } + return int64(float64(n) * memoryLimitShare), true +} + +// SystemCgroupMemoryLimit is CgroupMemoryLimit for this process. +func SystemCgroupMemoryLimit() (int64, bool) { + return CgroupMemoryLimit(os.Getenv, os.ReadFile) +} diff --git a/internal/utils/memlimit_test.go b/internal/utils/memlimit_test.go new file mode 100644 index 0000000..4cd8d42 --- /dev/null +++ b/internal/utils/memlimit_test.go @@ -0,0 +1,46 @@ +package utils + +import ( + "errors" + "io/fs" + "testing" +) + +func TestCgroupMemoryLimit(t *testing.T) { + file := func(content string) func(string) ([]byte, error) { + return func(p string) ([]byte, error) { + if p != cgroupMemoryMax { + t.Fatalf("read %s, want %s", p, cgroupMemoryMax) + } + return []byte(content), nil + } + } + missing := func(string) ([]byte, error) { return nil, fs.ErrNotExist } + noEnv := func(string) string { return "" } + userLimit := func(k string) string { + if k == "GOMEMLIMIT" { + return "10GiB" + } + return "" + } + + for _, c := range []struct { + name string + getenv func(string) string + readFile func(string) ([]byte, error) + want int64 + ok bool + }{ + {"16 GiB limit", noEnv, file("17179869184\n"), 14602888806, true}, + {"no limit", noEnv, file("max\n"), 0, false}, + {"no cgroup file", noEnv, missing, 0, false}, + {"unreadable", noEnv, func(string) ([]byte, error) { return nil, errors.New("denied") }, 0, false}, + {"garbage", noEnv, file("lots"), 0, false}, + {"GOMEMLIMIT wins", userLimit, file("17179869184\n"), 0, false}, + } { + got, ok := CgroupMemoryLimit(c.getenv, c.readFile) + if got != c.want || ok != c.ok { + t.Errorf("%s: got %d, %v; want %d, %v", c.name, got, ok, c.want, c.ok) + } + } +} diff --git a/internal/utils/memory.go b/internal/utils/memory.go new file mode 100644 index 0000000..7d411ca --- /dev/null +++ b/internal/utils/memory.go @@ -0,0 +1,41 @@ +package utils + +import ( + "fmt" + "runtime/metrics" +) + +// memorySamples are the runtime metrics LogMemory reads. +var memorySamples = []string{ + "/gc/heap/live:bytes", // live heap after the last GC + "/memory/classes/total:bytes", // everything the runtime mapped + "/memory/classes/heap/released:bytes", // of that, returned to the OS +} + +// LogMemory logs, under -v, the live heap and the memory the process holds +// from the OS after stage, and the process's peak resident memory so far, so +// a run's log shows which stage reaches the peak (#62). +func LogMemory(stage string) { + if verbosity < 1 { + return + } + s := make([]metrics.Sample, len(memorySamples)) + for i, name := range memorySamples { + s[i].Name = name + } + metrics.Read(s) + live, total, released := s[0].Value.Uint64(), s[1].Value.Uint64(), s[2].Value.Uint64() + msg := fmt.Sprintf("memory after %s: live heap %s, from the OS %s", stage, FormatBytes(live), FormatBytes(total-released)) + if peak := peakRSS(); peak > 0 { + msg += ", peak RSS " + FormatBytes(peak) + } + Info("%s", msg) +} + +// FormatBytes renders n in GiB, or in MiB below 1 GiB. +func FormatBytes(n uint64) string { + if n >= 1<<30 { + return fmt.Sprintf("%.2f GiB", float64(n)/(1<<30)) + } + return fmt.Sprintf("%.0f MiB", float64(n)/(1<<20)) +} diff --git a/internal/utils/memory_darwin.go b/internal/utils/memory_darwin.go new file mode 100644 index 0000000..37ecb22 --- /dev/null +++ b/internal/utils/memory_darwin.go @@ -0,0 +1,12 @@ +package utils + +import "syscall" + +// peakRSS is the process's peak resident memory; macOS reports ru_maxrss in bytes. +func peakRSS() uint64 { + var ru syscall.Rusage + if syscall.Getrusage(syscall.RUSAGE_SELF, &ru) != nil { + return 0 + } + return uint64(ru.Maxrss) +} diff --git a/internal/utils/memory_linux.go b/internal/utils/memory_linux.go new file mode 100644 index 0000000..977fb46 --- /dev/null +++ b/internal/utils/memory_linux.go @@ -0,0 +1,12 @@ +package utils + +import "syscall" + +// peakRSS is the process's peak resident memory; Linux reports ru_maxrss in KiB. +func peakRSS() uint64 { + var ru syscall.Rusage + if syscall.Getrusage(syscall.RUSAGE_SELF, &ru) != nil { + return 0 + } + return uint64(ru.Maxrss) * 1024 +} diff --git a/internal/utils/memory_other.go b/internal/utils/memory_other.go new file mode 100644 index 0000000..6605073 --- /dev/null +++ b/internal/utils/memory_other.go @@ -0,0 +1,6 @@ +//go:build !linux && !darwin + +package utils + +// peakRSS is not read on this platform; LogMemory then leaves it out. +func peakRSS() uint64 { return 0 } From c95e56beb1576d6f5eadaba5d1ce73021ec49410 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Mon, 30 Nov 2026 15:28:50 -0500 Subject: [PATCH 3/3] test(memtest): print cango's memory lines from a passing run (#62) --- internal/memtest/memtest.go | 12 ++++++++++++ internal/memtest/memtest_test.go | 3 +++ internal/memtest/memtest_unit_test.go | 13 +++++++++++++ 3 files changed, 28 insertions(+) diff --git a/internal/memtest/memtest.go b/internal/memtest/memtest.go index 53f990a..66315e3 100644 --- a/internal/memtest/memtest.go +++ b/internal/memtest/memtest.go @@ -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. diff --git a/internal/memtest/memtest_test.go b/internal/memtest/memtest_test.go index 65ecd4a..8eb616b 100644 --- a/internal/memtest/memtest_test.go +++ b/internal/memtest/memtest_test.go @@ -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)) } diff --git a/internal/memtest/memtest_unit_test.go b/internal/memtest/memtest_unit_test.go index 2c6cdbe..fb90d96 100644 --- a/internal/memtest/memtest_unit_test.go +++ b/internal/memtest/memtest_unit_test.go @@ -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) + } +}