From 75e0411ac60a36bee310bfd43514601680016ad1 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Thu, 19 Nov 2026 21:35:55 -0500 Subject: [PATCH 01/16] docs(design): repository-artifact and dependency datamodel for schema v2 Spec and CLAUDE.md schema decisions from the design loop: application.artifacts (all non-.go files, metadata-first, --artifact-text opt-in), can:///artifact ids, version-less pkg:golang package ids, go.mod requires as dependencies with go.sum locks, L1 at every level. Config keys deferred. Co-Authored-By: Claude Haiku 5.5 --- CLAUDE.md | 11 +++ docs/design/specs/v2-artifacts.md | 131 ++++++++++++++++++++++++++++++ 2 files changed, 142 insertions(+) create mode 100644 docs/design/specs/v2-artifacts.md diff --git a/CLAUDE.md b/CLAUDE.md index f4425d4..9091930 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -129,6 +129,17 @@ Reuses Group A ids/spans and the L3 vocabulary unchanged; every L4 fact is an ad - A Go-specific `select` cfg kind was not added (`select` is a `switch` with `switch_case` edges). +### Repository-artifact decisions (spec `docs/design/specs/v2-artifacts.md`, branch `feat/artifacts`) +Made with the user in the 2026-11-19 design loop, anchored on `codeanalyzer-python`'s `PyArtifact` / `PyDependency`. +- **Placement:** `application.artifacts{: artifact}` (map); `application.dependencies[]` (list). +- **Scope:** all non-`.go` project files [user, 2026-11-19]. Binaries are metadata only (`source:""`) [user]. +- **Artifact id:** `can:///artifact/`, app-scoped (Python parity) [user]. The Go projector's `:Artifact` flips to `CanNode=true`. +- **Package id:** version-less `pkg:golang/` [user]; version lives on the dependency edge. +- **Source text:** only with `--artifact-text`, default off [user]. `config_keys` deferred [user]. +- **Dependencies:** every `go.mod` require; `direct=false` on `// indirect`; `kind:"runtime"`; `go.sum` supplies `locked_version` only, `go.sum`-only entries excluded [user]. +- **`provides_imports`:** longest-prefix match against `go.mod` module paths [user]. +- **Level:** L1, every level, not gated [user]. + ## Neo4j-projection decisions The graph projection (`--emit neo4j`) is a **second projection of the same v2 envelope**, diff --git a/docs/design/specs/v2-artifacts.md b/docs/design/specs/v2-artifacts.md new file mode 100644 index 0000000..b06bfe8 --- /dev/null +++ b/docs/design/specs/v2-artifacts.md @@ -0,0 +1,131 @@ +# Spec: repository artifacts and dependencies (codeanalyzer-go) + +> **Cross-repo spec.** Canonical home is `codellm-devkit/.github → docs/design/specs/`, +> beside the coordinating parent issue. Staged locally on `feat/artifacts` until that repo +> is available (same precedent as `v2-l1-emission.md`). This is the design transcript of the +> datamodel loop, linked from the tracking record, not pasted into it. + +## Contract-Impact Triage + +**Does this change schema v2 output?** Yes. It adds two application-scoped fields +(`artifacts`, `dependencies`), new id shapes for artifact and package nodes, one new CLI flag +(`--artifact-text`), and populates the already-declared Neo4j neutral layer (`:Artifact`, +`:Package`, `HAS_ARTIFACT`, `DECLARES_DEPENDENCY`, `LOCKS`). + +| Change type | Analyzers | SDKs | Docs | +| --- | --- | --- | --- | +| Schema v2 evolution (additive) | **codeanalyzer-go** (emit + projector); codeanalyzer-python: none (parity adopted, no id change) | **python-sdk** (Go backend reconstruction of `:Artifact` / `:Package`) | `CLAUDE.md` § Schema decisions, this spec | + +Anchor: `codeanalyzer-python` already emits this layer (`PyArtifact`, `PyDependency`, +`PyConfigKey`, `application.artifacts`, `application.dependencies`, +`codeanalyzer/schema/py_schema.py`), and `python-sdk/cldk/analysis/commons/artifacts.py` +rebuilds it from Neo4j, with the neutral labels shared across analyzers. + +## Problem + +The v2 schema and projector declare the neutral repository-artifact layer, but the Go +analyzer never populates it. `go.mod` is read only for `go mod download`. Against the Go +analysis of `microservices-demo/src/frontend`, `MATCH (n:Artifact)` returns 0 rows. + +## Design-loop decisions (the transcript) + +Each decision was made with the user, one question per decision, in the order below. + +### Application placement +- **`application.artifacts`** is a **map keyed by repo-relative path**, as Python does. Stays + reachable from `application` by containment (keystone rule). +- **`application.dependencies`** is a **list** (Python parity). + +### Artifact scope and fields +- **Scope: all non-`.go` project files** (user decision, broader than the recommended manifests-only + scope). `.go` files are modules, not artifacts. Directories `.git/` and `vendor/` are excluded + (implementation default, see Open items). +- **Artifact fields** (Python `PyArtifact` parity): + | field | type | notes | + | --- | --- | --- | + | `id` | string | `can:///artifact/` | + | `kind` | string | `"artifact"` | + | `path` | string | repo-relative POSIX path (also the map key) | + | `format` | string | `toml\|yaml\|json\|ini\|properties\|requirements\|dockerfile\|text\|binary`, plus Go's `gomod` / `gosum` (Open items) | + | `roles` | string[] | `dependency-manifest` for `go.mod`, `lockfile` for `go.sum`; others only when recognized | + | `size_bytes` | int | always | + | `sha256` | string | full file hash, always | + | `source` | string | whole file text **only** with `--artifact-text`; otherwise `""` | + | `extraction` | string | `none` \| `partial` \| `full`; `full` when `source` is set, else `none` | +- **Binary files**: metadata only. `format:"binary"`, `size_bytes` and `sha256` set, + `source:""` (user decision). +- **`--artifact-text`** (default **off**): when on, `source` carries the whole file text + (user decision). Off keeps default output to metadata. +- **`config_keys`** is **deferred** (user decision): not emitted in this change. No + `:ConfigKey` rows are written. + +### Artifact id +- **`can:///artifact/`** (Python parity, user decision). App-scoped, so the + projector's `can:////` prefix scoping covers artifact nodes. This changes the + Go projector's `:Artifact` flag to `CanNode=true`; the current Go schema comment ("neutral, + not a can:// id") is superseded. + +### Package and dependencies +- **Package id: version-less `pkg:golang/`** (user decision), for example + `pkg:golang/github.com/gorilla/mux`. Mirrors Python's `pkg:pypi/`. The version lives + on the edge and the record, so every dependent app converges on one `:Package`. +- **Dependency records come from every `go.mod` `require`** (user decision). Direct and + indirect entries alike. + | field | source | + | --- | --- | + | `name` | module path | + | `ecosystem` | `"golang"` | + | `spec` | version in `go.mod` (for example `v1.8.0`) | + | `kind` | `"runtime"` for every entry (`go.mod` has no dev/optional split) | + | `direct` | `false` when the line carries `// indirect`, else `true` | + | `locked_version` | version pinned in `go.sum` for that module, when present | + | `declared_in` | the `go.mod` artifact id | + | `provides_imports` | import paths in the project that resolve to this module (see below) | + | `prov` | `["declared"]`, plus `"lockfile"` when `go.sum` supplies `locked_version` | +- **`go.sum`-only entries are not dependencies** (user decision, the non-recommended option + would have included them; the recommended default is not to, because `go.sum` retains + entries for pruned modules). `go.sum` contributes only `locked_version` and `prov`. +- **`provides_imports`**: populated by longest-prefix match of each project import path + against the `go.mod` module paths (user decision, Python parity). Import paths that match + no requirement are **not** recorded in this change (see Open items). + +### Analysis level +- **L1, every level** (user decision). Parse-only facts, identical at `-a 1` through `-a 4`. + Not gated. + +### Neo4j projection (the neutral layer, unchanged labels) +- `:Artifact {id, path, format}` (keyed by `id`, `CanNode=true`), under `HAS_ARTIFACT` + from `:GoApplication`. +- `:Package {id, ecosystem, name}` keyed by `id`. +- `DECLARES_DEPENDENCY` `(:Artifact)→(:Package)`, `_k = kind` (`runtime`), carrying `spec`, + `direct`, `prov` as properties. +- `LOCKS` `(:Artifact)→(:Package)` from `go.sum`, carrying `locked_version`. +- No `:ConfigKey` rows and no `DEFINES_CONFIG` rows in this change. + +## Open items (flagged for review, not asked) + +These are defaults I chose while writing the spec. Confirm them during review: + +1. **`format` values for go.mod and go.sum.** I used `gomod` and `gosum`, because the Python + enum has no Go case. The alternative is `text`. +2. **Excluded directories.** `.git/` and `vendor/` are skipped. `vendor/` is third-party + source, not project configuration. +3. **Imports with no matching requirement.** Not recorded. They are `unresolved_imports` in + Python. That field is deferred with the repository-provenance field. +4. **`locked_version` when `go.sum` has several lines for one module** (the `h1:` and + `/go.mod` hashes). Take the version common to both lines; error if they disagree. + +## Consumers + +- **codeanalyzer-go**: emits the fields; the projector writes the rows above. Tests: a fixture + with `go.mod` and `go.sum`, a projector test for the new rows, and a `--artifact-text` + on/off test. +- **python-sdk**: the Go backend reads `:Artifact` / `:Package` through the shared + `cldk/analysis/commons/artifacts.py` reconstructors. The Go backend needs its artifact getters + added. Scope of that rung is decided at decomposition. + +## Out of scope (deferred) + +- Config keys and `DEFINES_CONFIG` (user decision). +- `unresolved_imports`, repository provenance (`repository`), `config_uses`. +- Codeanalyzer-python: no change. From cf2cab1ab626901c59070d0c5421f78f50c86d6c Mon Sep 17 00:00:00 2001 From: lambertpw Date: Thu, 19 Nov 2026 22:08:12 -0500 Subject: [PATCH 02/16] feat(artifacts): emit repository artifacts and go.mod dependencies at L1 Adds application.artifacts (every non-.go project file: format, roles, size, sha256; source only with --artifact-text) and application.dependencies (go.mod requires with direct, locked_version from go.sum, provides_imports by longest prefix). The Neo4j projector writes :Artifact (app-scoped), :Package (pkg:golang/), HAS_ARTIFACT, DECLARES_DEPENDENCY and LOCKS. Config keys are deferred. Refs codellm-devkit/codeanalyzer-go#45 Co-Authored-By: Claude Haiku 5.5 --- README.md | 1 + cmd/codeanalyzer/main.go | 4 + docs/design/specs/v2-artifacts.md | 24 ++ internal/core/analyzer.go | 20 ++ internal/core/repository_test.go | 109 +++++++ internal/neo4j/project.go | 44 +++ internal/neo4j/repository_test.go | 97 ++++++ internal/neo4j/schema.go | 13 +- internal/options/options.go | 3 + internal/repository/repository.go | 279 ++++++++++++++++++ internal/repository/repository_test.go | 235 +++++++++++++++ internal/schema/schema.go | 38 +++ internal/schema/v2/schema.go | 34 +++ internal/syntactic_analysis/v2emit/emit.go | 1 + .../syntactic_analysis/v2emit/repository.go | 57 ++++ 15 files changed, 954 insertions(+), 5 deletions(-) create mode 100644 internal/core/repository_test.go create mode 100644 internal/neo4j/repository_test.go create mode 100644 internal/repository/repository.go create mode 100644 internal/repository/repository_test.go create mode 100644 internal/syntactic_analysis/v2emit/repository.go diff --git a/README.md b/README.md index 0d61c82..f063d6d 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,7 @@ Flags: -f, --format string Output format: json|msgpack (default "json") --graph-field-depth int Field-path depth bound for L3 dataflow nodes (k limit; applies at -a 3 and -a 4) (default 3) -h, --help help for cango + --artifact-text Capture each text artifact's whole source in analysis.json (default: metadata only) -i, --input string Project root to analyze (required) -j, --jobs int Worker parallelism (default: CPU cores) --library-models string JSON file of library stand-in flows overriding the all-to-all default (-a 4 and --emit neo4j only) diff --git a/cmd/codeanalyzer/main.go b/cmd/codeanalyzer/main.go index d2b5379..3cceee3 100644 --- a/cmd/codeanalyzer/main.go +++ b/cmd/codeanalyzer/main.go @@ -46,6 +46,7 @@ func rootCmd() *cobra.Command { libraryModels string targetFiles []string skipTests bool + artifactText bool eager bool cacheDir string jobs int @@ -172,6 +173,7 @@ via CLDK(language="go").analysis(project_path=...).`, AnalyzerVersion: version, TargetFiles: targetFiles, SkipTests: skipTests, + ArtifactText: artifactText, Eager: eager, CacheDir: cacheDir, Jobs: jobs, @@ -238,6 +240,8 @@ via CLDK(language="go").analysis(project_path=...).`, f.StringSliceVarP(&targetFiles, "target-files", "t", nil, "Restrict analysis to specific files (incremental mode)") f.BoolVar(&skipTests, "skip-tests", true, "Skip *_test.go files") + f.BoolVar(&artifactText, "artifact-text", false, + "Capture each text artifact's whole source in analysis.json (default: metadata only)") f.BoolVar(&eager, "eager", false, "Force clean rebuild (ignore cache)") f.StringVarP(&cacheDir, "cache-dir", "c", "", "Cache directory (default: ~/.cldk/go-cache)") f.IntVarP(&jobs, "jobs", "j", 0, "Worker parallelism (default: CPU cores)") diff --git a/docs/design/specs/v2-artifacts.md b/docs/design/specs/v2-artifacts.md index b06bfe8..6d8ed76 100644 --- a/docs/design/specs/v2-artifacts.md +++ b/docs/design/specs/v2-artifacts.md @@ -115,6 +115,30 @@ These are defaults I chose while writing the spec. Confirm them during review: 4. **`locked_version` when `go.sum` has several lines for one module** (the `h1:` and `/go.mod` hashes). Take the version common to both lines; error if they disagree. +## Resolution (implementation, branch `feat/artifacts`) + +The open items were resolved with the defaults below. Two are deviations from the wording +above, marked **(deviation)**: + +1. **`format`**: `gomod` for `go.mod`, `gosum` for `go.sum`, adopted. +2. **Excluded directories**: `.git/` and `vendor/` are skipped at any depth. The tool's own + outputs are also skipped when they sit in the project: `analysis.json` and `graph.cypher` + in the `-o` directory, and the `-c` cache subtree. Without this, a run that writes into the + project would capture the previous run's output. +3. **Unrecorded imports**: an import matching no `go.mod` requirement is not recorded. +4. **Locked version (deviation)**: a requirement is locked only when go.sum has **both** the + `h1:` and the `/go.mod` line for the exact required version. A version with only one line + is left unlocked (`locked_version` absent, `prov` without `lockfile`), with no error. A + disagreement cannot arise, since the lookup is keyed by the required version. +5. **Artifact id root (deviation)**: the code's grammar is `can:////…`, the + same root every other node uses, so an artifact id is + `can:////artifact/`. The `can:///artifact/` form in the + decisions above is shorthand for that root. + +Also decided at implementation: `source` is omitted from JSON when empty (`omitempty`), not +written as `""`; only the root `go.mod` contributes dependencies (nested modules are artifacts +only); `dependencies` is absent when there is no root `go.mod`. + ## Consumers - **codeanalyzer-go**: emits the fields; the projector writes the rows above. Tests: a fixture diff --git a/internal/core/analyzer.go b/internal/core/analyzer.go index a82ac2c..b9dbf34 100644 --- a/internal/core/analyzer.go +++ b/internal/core/analyzer.go @@ -32,6 +32,7 @@ import ( "github.com/codellm-devkit/codeanalyzer-go/internal/analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" "github.com/codellm-devkit/codeanalyzer-go/internal/options" + "github.com/codellm-devkit/codeanalyzer-go/internal/repository" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" @@ -93,6 +94,25 @@ func New(opts options.AnalysisOptions) *Analyzer { // Analyze runs the full analysis pipeline and returns a GoApplication. func (a *Analyzer) Analyze() (*schema.GoApplication, error) { + app, err := a.analyze() + if err != nil { + return nil, err + } + // The repository layer reads files outside the Go source, so it is computed + // on every run, after the (possibly cached) application is ready. + facts, err := repository.Facts(a.opts.InputPath, app, repository.Options{ + CaptureText: a.opts.ArtifactText, + OutputDir: a.opts.OutputDir, + CacheDir: a.opts.CacheDir, + }) + if err != nil { + return nil, fmt.Errorf("repository layer: %w", err) + } + app.Repository = facts + return app, nil +} + +func (a *Analyzer) analyze() (*schema.GoApplication, error) { if _, err := resolveIdentity(a.opts); err != nil { return nil, err } diff --git a/internal/core/repository_test.go b/internal/core/repository_test.go new file mode 100644 index 0000000..1f72580 --- /dev/null +++ b/internal/core/repository_test.go @@ -0,0 +1,109 @@ +package core_test + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/codellm-devkit/codeanalyzer-go/internal/core" + "github.com/codellm-devkit/codeanalyzer-go/internal/options" + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" +) + +// repoProject is a Go module with no requires (so no network materialization), +// one .go file, and two non-.go files. +func repoProject(t *testing.T) string { + t.Helper() + dir := t.TempDir() + files := map[string]string{ + "go.mod": "module example.com/repoapp\n\ngo 1.25.0\n", + "go.sum": "", + "main.go": "package main\n\nfunc main() {}\n", + "README.md": "# repo app\n", + } + for rel, content := range files { + if err := os.WriteFile(filepath.Join(dir, rel), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + return dir +} + +// emitJSON runs Analyze at level 1 and returns the v2 analysis.json bytes. +func emitJSON(t *testing.T, dir string, artifactText bool) []byte { + t.Helper() + opts := options.AnalysisOptions{ + InputPath: dir, AppName: "repoapp", Level: options.LevelSymbolTable, + SkipTests: true, CacheDir: t.TempDir(), OutputDir: t.TempDir(), ArtifactText: artifactText, + } + app, err := core.New(opts).Analyze() + if err != nil { + t.Fatal(err) + } + identity, err := v2.ResolveIdentity("repoapp", nil) + if err != nil { + t.Fatal(err) + } + payload := v2emit.Emit(app, identity, dir, int(opts.Level), "test", 0, nil, nil) + out, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + return out +} + +func TestAnalyze_ArtifactsDefaultMetadataOnly(t *testing.T) { + dir := repoProject(t) + var doc struct { + Application struct { + Artifacts map[string]v2.Artifact `json:"artifacts"` + } `json:"application"` + } + if err := json.Unmarshal(emitJSON(t, dir, false), &doc); err != nil { + t.Fatal(err) + } + art, ok := doc.Application.Artifacts["README.md"] + if !ok { + t.Fatalf("README.md missing from artifacts: %v", doc.Application.Artifacts) + } + if art.ID != "can://repoapp/repoapp/artifact/README.md" { + t.Errorf("artifact id = %q", art.ID) + } + if art.Format != "text" || art.Extraction != "none" || art.Source != "" { + t.Errorf("default artifact should be metadata only: %+v", art) + } + if _, ok := doc.Application.Artifacts["main.go"]; ok { + t.Errorf("a .go file became an artifact") + } +} + +func TestAnalyze_ArtifactTextCapturesSource(t *testing.T) { + dir := repoProject(t) + var doc struct { + Application struct { + Artifacts map[string]v2.Artifact `json:"artifacts"` + } `json:"application"` + } + if err := json.Unmarshal(emitJSON(t, dir, true), &doc); err != nil { + t.Fatal(err) + } + art := doc.Application.Artifacts["README.md"] + if art.Source != "# repo app\n" || art.Extraction != "full" { + t.Errorf("--artifact-text: source/extraction = %q/%q", art.Source, art.Extraction) + } + mod := doc.Application.Artifacts["go.mod"] + if mod.Format != "gomod" || len(mod.Roles) != 1 || mod.Roles[0] != "dependency-manifest" { + t.Errorf("go.mod artifact = %+v", mod) + } +} + +func TestAnalyze_ArtifactsReproducibleAcrossRuns(t *testing.T) { + dir := repoProject(t) + a := emitJSON(t, dir, false) + b := emitJSON(t, dir, false) + if string(a) != string(b) { + t.Errorf("two runs over the same project differ") + } +} diff --git a/internal/neo4j/project.go b/internal/neo4j/project.go index 78fde41..04111d1 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -2,6 +2,7 @@ package neo4j import ( "encoding/json" + "sort" "strings" v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" @@ -33,6 +34,7 @@ func Project(a *v2.Analysis) GraphRows { declared: collectDeclaredIDs(a), } p.projectApplication() + p.projectRepository() for _, mod := range a.Application.SymbolTable { p.projectModule(mod) } @@ -84,6 +86,48 @@ func (p *projector) appRef() NodeRef { return NodeRef{Label: LabelApplication, KeyProp: "id", Value: p.analysis.Application.ID} } +// ─── repository layer (spec v2-artifacts) ──────────────────────────────────── + +// projectRepository writes the artifact and dependency rows. An artifact is an +// app-scoped node (its id is a can:// id) hung off the application; a dependency +// is a neutral :Package keyed by its version-less purl, declared by the go.mod +// artifact and, when go.sum locks it, locked by the go.sum artifact. +func (p *projector) projectRepository() { + arts := p.analysis.Application.Artifacts + paths := make([]string, 0, len(arts)) + for path := range arts { + paths = append(paths, path) + } + sort.Strings(paths) + for _, path := range paths { + art := arts[path] + ref := p.b.Node( + []string{LabelArtifact, MarkerLabel}, + "id", art.ID, + Props{"path": art.Path, "format": art.Format}, + "", // an artifact belongs to no single module + ) + p.b.Edge(RelHasArtifact, p.appRef(), ref, nil, "") + } + + goSum, hasGoSum := arts["go.sum"] + for _, dep := range p.analysis.Application.Dependencies { + pkgRef := p.b.Node( + []string{LabelPackage}, + "id", "pkg:"+dep.Ecosystem+"/"+dep.Name, + Props{"ecosystem": dep.Ecosystem, "name": dep.Name}, + "", + ) + declaredBy := NodeRef{Label: LabelArtifact, KeyProp: "id", Value: dep.DeclaredIn} + p.b.Edge(RelDeclaresDependency, declaredBy, pkgRef, + Props{"spec": dep.Spec, "direct": dep.Direct, "prov": dep.Prov}, dep.Kind) + if dep.LockedVersion != "" && hasGoSum { + p.b.Edge(RelLocks, NodeRef{Label: LabelArtifact, KeyProp: "id", Value: goSum.ID}, pkgRef, + Props{"locked_version": dep.LockedVersion}, "") + } + } +} + // ─── module ────────────────────────────────────────────────────────────────── func (p *projector) projectModule(m v2.Module) { diff --git a/internal/neo4j/repository_test.go b/internal/neo4j/repository_test.go new file mode 100644 index 0000000..b2554f6 --- /dev/null +++ b/internal/neo4j/repository_test.go @@ -0,0 +1,97 @@ +package neo4j + +import ( + "testing" + + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" +) + +// repoAnalysis is a minimal L1 analysis carrying only the repository layer: +// go.mod and go.sum artifacts, and two dependencies (one locked, one not). +func repoAnalysis() *v2.Analysis { + const app = "can://frontend/frontend" + goMod := app + "/artifact/go.mod" + goSum := app + "/artifact/go.sum" + return &v2.Analysis{ + IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 1, + Application: v2.Application{ + IdentityVersion: 2, ID: app, Kind: "application", + Artifacts: map[string]v2.Artifact{ + "go.mod": {ID: goMod, Kind: "artifact", Path: "go.mod", Format: "gomod", Roles: []string{"dependency-manifest"}}, + "go.sum": {ID: goSum, Kind: "artifact", Path: "go.sum", Format: "gosum", Roles: []string{"lockfile"}}, + }, + Dependencies: []v2.Dependency{ + {Name: "github.com/gorilla/mux", Ecosystem: "golang", Spec: "v1.8.0", Kind: "runtime", Direct: true, + LockedVersion: "v1.8.0", DeclaredIn: goMod, Prov: []string{"declared", "lockfile"}}, + {Name: "golang.org/x/text", Ecosystem: "golang", Spec: "v0.14.0", Kind: "runtime", Direct: false, + DeclaredIn: goMod, Prov: []string{"declared"}}, + }, + }, + } +} + +func TestProject_RepositoryLayerRows(t *testing.T) { + rows := Project(repoAnalysis()) + + nodes := map[string]NodeRow{} + for _, n := range rows.Nodes { + nodes[n.Value] = n + } + + goMod := nodes["can://frontend/frontend/artifact/go.mod"] + if !hasLabel(goMod, LabelArtifact) || !hasLabel(goMod, MarkerLabel) { + t.Errorf("artifact node labels = %v, want Artifact + %s (app-scoped)", goMod.Labels, MarkerLabel) + } + mux := nodes["pkg:golang/github.com/gorilla/mux"] + if !hasLabel(mux, LabelPackage) || hasLabel(mux, MarkerLabel) { + t.Errorf("package node labels = %v, want Package only (neutral, no marker)", mux.Labels) + } + + edges := map[string][]EdgeRow{} + for _, e := range rows.Edges { + edges[e.Type] = append(edges[e.Type], e) + } + if len(edges[RelHasArtifact]) != 2 { + t.Errorf("HAS_ARTIFACT edges = %d, want 2 (go.mod, go.sum)", len(edges[RelHasArtifact])) + } + + decl := edges[RelDeclaresDependency] + if len(decl) != 2 { + t.Fatalf("DECLARES_DEPENDENCY edges = %d, want 2", len(decl)) + } + for _, e := range decl { + if e.From.Value != "can://frontend/frontend/artifact/go.mod" || e.To.Label != LabelPackage { + t.Errorf("DECLARES_DEPENDENCY wired %s -> %s:%s, want go.mod -> Package", e.From.Value, e.To.Label, e.To.Value) + } + if e.Key != "runtime" { + t.Errorf("DECLARES_DEPENDENCY _k = %q, want runtime", e.Key) + } + } + + locks := edges[RelLocks] + if len(locks) != 1 { + t.Fatalf("LOCKS edges = %d, want 1 (only the locked dependency)", len(locks)) + } + if locks[0].From.Value != "can://frontend/frontend/artifact/go.sum" || + locks[0].To.Value != "pkg:golang/github.com/gorilla/mux" || + locks[0].Props["locked_version"] != "v1.8.0" { + t.Errorf("LOCKS = %+v, want go.sum -> mux with locked_version v1.8.0", locks[0]) + } +} + +func TestProject_NoRepositoryLayerEmitsNoRows(t *testing.T) { + a := repoAnalysis() + a.Application.Artifacts, a.Application.Dependencies = nil, nil + rows := Project(a) + for _, n := range rows.Nodes { + if hasLabel(n, LabelArtifact) || hasLabel(n, LabelPackage) { + t.Errorf("repository node %v emitted without facts", n.Labels) + } + } + for _, e := range rows.Edges { + switch e.Type { + case RelHasArtifact, RelDeclaresDependency, RelLocks: + t.Errorf("repository edge %s emitted without facts", e.Type) + } + } +} diff --git a/internal/neo4j/schema.go b/internal/neo4j/schema.go index 18853b4..274d39d 100644 --- a/internal/neo4j/schema.go +++ b/internal/neo4j/schema.go @@ -227,12 +227,15 @@ var Nodes = []NodeSpec{ Props: []string{"name", "path", "signature", "module"}, }, - // Neutral layer. Keyed by own id (not a can:// id), so NO marker label and - // outside prefix scoping — a sibling analyzer converges on the same node. + // Repository layer. An artifact id is can:////artifact/ + // (spec v2-artifacts, Python parity), so it is app-scoped: it carries the + // :GoCanNode marker and falls under the prefix scope on wipe. { - Label: LabelArtifact, MergeLabel: LabelArtifact, Key: "id", CanNode: false, + Label: LabelArtifact, MergeLabel: LabelArtifact, Key: "id", CanNode: true, Props: []string{"path", "format"}, }, + // Neutral layer. Keyed by its pkg: purl (not a can:// id), so NO marker label + // and outside prefix scoping — a sibling analyzer converges on the same node. { Label: LabelPackage, MergeLabel: LabelPackage, Key: "id", CanNode: false, Props: []string{"ecosystem", "name"}, @@ -265,8 +268,8 @@ var Rels = []RelSpec{ // Repository layer. {Type: RelHasArtifact, From: []string{LabelApplication}, To: []string{LabelArtifact}}, - {Type: RelDeclaresDependency, From: []string{LabelArtifact}, To: []string{LabelPackage}, Discriminant: "kind"}, - {Type: RelLocks, From: []string{LabelArtifact}, To: []string{LabelPackage}}, + {Type: RelDeclaresDependency, From: []string{LabelArtifact}, To: []string{LabelPackage}, Props: []string{"spec", "direct", "prov"}, Discriminant: "kind"}, + {Type: RelLocks, From: []string{LabelArtifact}, To: []string{LabelPackage}, Props: []string{"locked_version"}}, {Type: RelDefinesConfig, From: []string{LabelArtifact}, To: []string{LabelConfigKey}}, {Type: RelProvides, From: []string{LabelPackage}, To: []string{LabelExternal}}, {Type: RelUnresolvedImport, From: []string{LabelApplication}, To: []string{LabelExternal}}, diff --git a/internal/options/options.go b/internal/options/options.go index 13f0af9..ebeb300 100644 --- a/internal/options/options.go +++ b/internal/options/options.go @@ -57,6 +57,9 @@ type AnalysisOptions struct { TargetFiles []string // SkipTests skips test files (files ending in _test.go). SkipTests bool + // ArtifactText captures each text artifact's whole source (--artifact-text). + // Off by default: artifacts carry metadata only. + ArtifactText bool // Eager forces a clean rebuild ignoring any cache. Eager bool // CacheDir is where per-file caches and intermediate data are stored. diff --git a/internal/repository/repository.go b/internal/repository/repository.go new file mode 100644 index 0000000..45906d1 --- /dev/null +++ b/internal/repository/repository.go @@ -0,0 +1,279 @@ +// Package repository collects the repository-artifact layer (spec +// docs/design/specs/v2-artifacts.md): every non-.go project file as an artifact, +// and the go.mod requires as dependencies, with go.sum supplying locked versions. +// +// It reads files outside the Go source the symbol table sees, so it runs on every +// analysis (never from the cache) and is independent of the analysis level. +package repository + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "fmt" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "unicode/utf8" + + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/utils" + "golang.org/x/mod/modfile" +) + +// Ecosystem is the purl type used for Go modules (pkg:golang/). +const Ecosystem = "golang" + +// Options controls discovery. +type Options struct { + // CaptureText puts each text artifact's whole source into Source (--artifact-text). + CaptureText bool + // OutputDir and CacheDir are the tool's own output locations. When either lies + // inside the project, its files are not artifacts: a run that writes analysis.json + // into the project must not capture the previous run's output. + OutputDir string + CacheDir string +} + +// skipDirNames are directories never walked: VCS metadata and vendored third-party code. +var skipDirNames = map[string]bool{".git": true, "vendor": true} + +// outputFileNames are the files this tool writes into OutputDir. +var outputFileNames = map[string]bool{"analysis.json": true, "graph.cypher": true} + +// Discover returns every non-.go regular file under root as an artifact, keyed by +// its repo-relative POSIX path. Files are visited in lexical order. +func Discover(root string, opts Options) (map[string]schema.GoArtifact, error) { + absRoot, err := filepath.Abs(root) + if err != nil { + return nil, err + } + outDir := absOrEmpty(opts.OutputDir) + cacheDir := absOrEmpty(opts.CacheDir) + out := map[string]schema.GoArtifact{} + err = filepath.WalkDir(absRoot, func(p string, d fs.DirEntry, werr error) error { + if werr != nil { + return werr + } + if d.IsDir() { + if p != absRoot && (skipDirNames[d.Name()] || (cacheDir != "" && p == cacheDir)) { + return filepath.SkipDir + } + return nil + } + if !d.Type().IsRegular() || strings.HasSuffix(d.Name(), ".go") { + return nil + } + if outDir != "" && filepath.Dir(p) == outDir && outputFileNames[d.Name()] { + return nil + } + rel, err := filepath.Rel(absRoot, p) + if err != nil { + return err + } + art, err := readArtifact(p, filepath.ToSlash(rel), opts.CaptureText) + if err != nil { + return err + } + out[art.Path] = art + return nil + }) + if err != nil { + return nil, fmt.Errorf("artifact discovery: %w", err) + } + return out, nil +} + +func absOrEmpty(p string) string { + if p == "" { + return "" + } + abs, err := filepath.Abs(p) + if err != nil { + return "" + } + return abs +} + +// readArtifact hashes the whole file and classifies it. Text source is kept only +// when captureText is set; binaries are never captured. +func readArtifact(abs, rel string, captureText bool) (schema.GoArtifact, error) { + data, err := os.ReadFile(abs) + if err != nil { + return schema.GoArtifact{}, err + } + sum := sha256.Sum256(data) + art := schema.GoArtifact{ + Path: rel, + Format: formatOf(rel, data), + SizeBytes: int64(len(data)), + SHA256: hex.EncodeToString(sum[:]), + Extraction: "none", + } + switch rel { + case "go.mod": + art.Roles = []string{"dependency-manifest"} + case "go.sum": + art.Roles = []string{"lockfile"} + } + if captureText && art.Format != "binary" { + art.Source = string(data) + art.Extraction = "full" + } + return art, nil +} + +// formatOf names the file's format. go.mod and go.sum have their own names; the +// rest follow the Python analyzer's enum. Binary is a NUL byte or invalid UTF-8. +func formatOf(rel string, data []byte) string { + base := filepath.Base(rel) + switch { + case base == "go.mod": + return "gomod" + case base == "go.sum": + return "gosum" + case base == "Dockerfile" || strings.HasPrefix(base, "Dockerfile.") || strings.HasSuffix(base, ".dockerfile"): + return "dockerfile" + case strings.HasPrefix(base, "requirements") && strings.HasSuffix(base, ".txt"): + return "requirements" + } + if bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data) { + return "binary" + } + switch strings.ToLower(filepath.Ext(base)) { + case ".toml": + return "toml" + case ".yaml", ".yml": + return "yaml" + case ".json": + return "json" + case ".ini", ".cfg": + return "ini" + case ".properties": + return "properties" + } + return "text" +} + +// Facts builds the repository layer for a project: its artifacts, and the +// dependencies declared by the root go.mod. imports are the project's import +// paths (from the symbol table), used to fill provides_imports. +func Facts(root string, app *schema.GoApplication, opts Options) (*schema.RepositoryFacts, error) { + artifacts, err := Discover(root, opts) + if err != nil { + return nil, err + } + facts := &schema.RepositoryFacts{Artifacts: artifacts} + modPath := filepath.Join(root, "go.mod") + modData, err := os.ReadFile(modPath) + if err != nil { + // No root go.mod: artifacts only, no dependencies. + return facts, nil + } + f, err := modfile.Parse("go.mod", modData, nil) + if err != nil { + utils.Warn("repository: go.mod does not parse, dependencies skipped: %v", err) + return facts, nil + } + locked := parseGoSum(filepath.Join(root, "go.sum")) + imports := projectImports(app) + + deps := make([]schema.GoDependency, 0, len(f.Require)) + for _, r := range f.Require { + dep := schema.GoDependency{ + Name: r.Mod.Path, + Ecosystem: Ecosystem, + Spec: r.Mod.Version, + Kind: "runtime", + Direct: !r.Indirect, + DeclaredIn: "go.mod", + Prov: []string{"declared"}, + } + if locked[r.Mod.Path][r.Mod.Version] { + dep.LockedVersion = r.Mod.Version + dep.Prov = append(dep.Prov, "lockfile") + } + deps = append(deps, dep) + } + sort.Slice(deps, func(i, j int) bool { return deps[i].Name < deps[j].Name }) + assignImports(deps, imports) + facts.Dependencies = deps + return facts, nil +} + +// parseGoSum returns, per module path and version, whether go.sum carries both +// the module's h1 line and its /go.mod line. Only such a version is a locked +// version. A missing or unreadable go.sum locks nothing. +func parseGoSum(path string) map[string]map[string]bool { + type seen struct{ h1, gomod bool } + entries := map[string]map[string]*seen{} + data, err := os.ReadFile(path) + if err != nil { + return map[string]map[string]bool{} + } + for _, line := range strings.Split(string(data), "\n") { + fields := strings.Fields(line) + if len(fields) != 3 { + continue + } + mod, ver := fields[0], fields[1] + gomod := strings.HasSuffix(ver, "/go.mod") + ver = strings.TrimSuffix(ver, "/go.mod") + if entries[mod] == nil { + entries[mod] = map[string]*seen{} + } + if entries[mod][ver] == nil { + entries[mod][ver] = &seen{} + } + if gomod { + entries[mod][ver].gomod = true + } else { + entries[mod][ver].h1 = true + } + } + out := map[string]map[string]bool{} + for mod, vers := range entries { + out[mod] = map[string]bool{} + for ver, s := range vers { + out[mod][ver] = s.h1 && s.gomod + } + } + return out +} + +// projectImports is the sorted, deduplicated set of import paths the project's +// (non-test, when the symbol table was built with --skip-tests) Go files use. +func projectImports(app *schema.GoApplication) []string { + seen := map[string]bool{} + for _, f := range app.SymbolTable { + for _, imp := range f.Imports { + seen[imp.Module] = true + } + } + out := make([]string, 0, len(seen)) + for p := range seen { + out = append(out, p) + } + sort.Strings(out) + return out +} + +// assignImports gives each import to the dependency whose module path is its +// longest prefix (the path itself, or a path under it followed by "/"). An +// import matching no requirement is not recorded. +func assignImports(deps []schema.GoDependency, imports []string) { + for _, imp := range imports { + best := -1 + bestLen := -1 + for i, d := range deps { + if (imp == d.Name || strings.HasPrefix(imp, d.Name+"/")) && len(d.Name) > bestLen { + best, bestLen = i, len(d.Name) + } + } + if best >= 0 { + deps[best].ProvidesImports = append(deps[best].ProvidesImports, imp) + } + } +} diff --git a/internal/repository/repository_test.go b/internal/repository/repository_test.go new file mode 100644 index 0000000..0c048ef --- /dev/null +++ b/internal/repository/repository_test.go @@ -0,0 +1,235 @@ +package repository + +import ( + "os" + "path/filepath" + "reflect" + "testing" + + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" +) + +// writeTree creates the files under root (path → content). A NUL in content +// makes a file binary. +func writeTree(t *testing.T, root string, files map[string]string) { + t.Helper() + for rel, content := range files { + p := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } +} + +// appWithImports is a symbol-table stub carrying the given import paths in one file. +func appWithImports(paths ...string) *schema.GoApplication { + imps := make([]schema.GoImport, 0, len(paths)) + for _, p := range paths { + imps = append(imps, schema.GoImport{Module: p}) + } + return &schema.GoApplication{SymbolTable: map[string]schema.GoFile{"main.go": {Imports: imps}}} +} + +const goMod = `module example.com/app + +go 1.25.0 + +require ( + cloud.google.com/go v0.1.0 + cloud.google.com/go/auth v0.2.0 + github.com/gorilla/mux v1.8.0 + golang.org/x/text v0.14.0 // indirect +) +` + +// go.sum: mux has both lines for its version (locked); auth too; cloud.google.com/go +// has only its h1 line (not locked); x/text has only its /go.mod line (not locked). +const goSum = `cloud.google.com/go v0.1.0 h1:AAA= +cloud.google.com/go/auth v0.2.0 h1:BBB= +cloud.google.com/go/auth v0.2.0/go.mod h1:CCC= +github.com/gorilla/mux v1.8.0 h1:DDD= +github.com/gorilla/mux v1.8.0/go.mod h1:EEE= +golang.org/x/text v0.14.0/go.mod h1:FFF= +` + +func TestFacts_DependenciesLocksAndImports(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{"go.mod": goMod, "go.sum": goSum, "main.go": "package main\n"}) + + facts, err := Facts(root, appWithImports( + "github.com/gorilla/mux", + "cloud.google.com/go/auth/credentials", // longest prefix: cloud.google.com/go/auth + "cloud.google.com/go/storage", // only cloud.google.com/go matches + "fmt", // stdlib: no requirement + ), Options{}) + if err != nil { + t.Fatal(err) + } + + want := []schema.GoDependency{ + {Name: "cloud.google.com/go", Ecosystem: "golang", Spec: "v0.1.0", Kind: "runtime", Direct: true, + DeclaredIn: "go.mod", ProvidesImports: []string{"cloud.google.com/go/storage"}, Prov: []string{"declared"}}, + {Name: "cloud.google.com/go/auth", Ecosystem: "golang", Spec: "v0.2.0", Kind: "runtime", Direct: true, + LockedVersion: "v0.2.0", DeclaredIn: "go.mod", ProvidesImports: []string{"cloud.google.com/go/auth/credentials"}, + Prov: []string{"declared", "lockfile"}}, + {Name: "github.com/gorilla/mux", Ecosystem: "golang", Spec: "v1.8.0", Kind: "runtime", Direct: true, + LockedVersion: "v1.8.0", DeclaredIn: "go.mod", ProvidesImports: []string{"github.com/gorilla/mux"}, + Prov: []string{"declared", "lockfile"}}, + {Name: "golang.org/x/text", Ecosystem: "golang", Spec: "v0.14.0", Kind: "runtime", Direct: false, + DeclaredIn: "go.mod", Prov: []string{"declared"}}, + } + if !reflect.DeepEqual(facts.Dependencies, want) { + t.Errorf("dependencies:\n got %+v\n want %+v", facts.Dependencies, want) + } +} + +func TestFacts_ArtifactsClassifiedAndSkipped(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{ + "go.mod": goMod, + "go.sum": goSum, + "main.go": "package main\n", + "main_test.go": "package main\n", + "Dockerfile": "FROM scratch\n", + "config/app.yaml": "a: 1\n", + "config/settings.env": "KEY=value\n", + "blob.dat": "ab\x00cd", + ".git/HEAD": "ref: refs/heads/main\n", + "vendor/x/y.txt": "vendored\n", + }) + + facts, err := Facts(root, appWithImports(), Options{}) + if err != nil { + t.Fatal(err) + } + got := map[string]schema.GoArtifact{} + for p, a := range facts.Artifacts { + got[p] = a + } + wantFormats := map[string]string{ + "go.mod": "gomod", + "go.sum": "gosum", + "Dockerfile": "dockerfile", + "config/app.yaml": "yaml", + "config/settings.env": "text", + "blob.dat": "binary", + } + if len(got) != len(wantFormats) { + t.Errorf("artifacts = %v, want exactly %v", keys(got), keys(wantFormats)) + } + for p, f := range wantFormats { + a, ok := got[p] + if !ok { + t.Errorf("missing artifact %s", p) + continue + } + if a.Format != f { + t.Errorf("%s format = %q, want %q", p, a.Format, f) + } + if a.Extraction != "none" || a.Source != "" { + t.Errorf("%s captured source without --artifact-text: %+v", p, a) + } + if len(a.SHA256) != 64 { + t.Errorf("%s sha256 = %q, want 64 hex chars", p, a.SHA256) + } + } + if r := got["go.mod"].Roles; !reflect.DeepEqual(r, []string{"dependency-manifest"}) { + t.Errorf("go.mod roles = %v", r) + } + if r := got["go.sum"].Roles; !reflect.DeepEqual(r, []string{"lockfile"}) { + t.Errorf("go.sum roles = %v", r) + } +} + +func TestDiscover_CaptureTextOnlyForText(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{"go.mod": goMod, "blob.dat": "ab\x00cd"}) + + on, err := Discover(root, Options{CaptureText: true}) + if err != nil { + t.Fatal(err) + } + if on["go.mod"].Source != goMod || on["go.mod"].Extraction != "full" { + t.Errorf("go.mod with --artifact-text: source/extraction = %q/%q", on["go.mod"].Source, on["go.mod"].Extraction) + } + if on["blob.dat"].Source != "" || on["blob.dat"].Extraction != "none" { + t.Errorf("binary captured source: %+v", on["blob.dat"]) + } +} + +func TestDiscover_ExcludesOwnOutputsAndCache(t *testing.T) { + root := t.TempDir() + cache := filepath.Join(root, "cache") + writeTree(t, root, map[string]string{ + "README.md": "# app\n", + "analysis.json": "{}", + "graph.cypher": "CREATE;", + "cache/entry.bin": "x\x00", + "notes/analysis.json": "{}", // not the output dir: kept + }) + + got, err := Discover(root, Options{OutputDir: root, CacheDir: cache}) + if err != nil { + t.Fatal(err) + } + if _, ok := got["analysis.json"]; ok { + t.Errorf("own output analysis.json was captured") + } + if _, ok := got["graph.cypher"]; ok { + t.Errorf("own output graph.cypher was captured") + } + if _, ok := got["cache/entry.bin"]; ok { + t.Errorf("cache subtree was captured") + } + if _, ok := got["notes/analysis.json"]; !ok { + t.Errorf("unrelated notes/analysis.json was wrongly excluded") + } + if _, ok := got["README.md"]; !ok { + t.Errorf("README.md missing") + } +} + +func TestFacts_NoGoModMeansArtifactsOnly(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{"Dockerfile": "FROM scratch\n"}) + + facts, err := Facts(root, appWithImports("fmt"), Options{}) + if err != nil { + t.Fatal(err) + } + if len(facts.Dependencies) != 0 { + t.Errorf("dependencies without go.mod: %+v", facts.Dependencies) + } + if _, ok := facts.Artifacts["Dockerfile"]; !ok { + t.Errorf("Dockerfile artifact missing") + } +} + +func TestParseGoSum_OnlyFullPairsLock(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{"go.sum": goSum}) + got := parseGoSum(filepath.Join(root, "go.sum")) + if !got["github.com/gorilla/mux"]["v1.8.0"] { + t.Errorf("mux v1.8.0 has both lines; want locked") + } + if got["cloud.google.com/go"]["v0.1.0"] { + t.Errorf("cloud.google.com/go has only h1; want not locked") + } + if got["golang.org/x/text"]["v0.14.0"] { + t.Errorf("golang.org/x/text has only /go.mod; want not locked") + } + if n := len(parseGoSum(filepath.Join(root, "absent"))); n != 0 { + t.Errorf("missing go.sum locked %d modules", n) + } +} + +func keys[V any](m map[string]V) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + return out +} diff --git a/internal/schema/schema.go b/internal/schema/schema.go index 84335d5..99bf2c2 100644 --- a/internal/schema/schema.go +++ b/internal/schema/schema.go @@ -214,6 +214,44 @@ type GoApplication struct { // Externals holds the library (out-of-project) functions the resolver saw // called, keyed by the full callee signature (".[Type.]Name"). Externals map[string]GoExternalCallee `json:"externals,omitempty"` + // Repository holds the repository-artifact facts (non-.go project files and + // go.mod/go.sum dependencies), set by the analyzer after symbol-table + // construction. Never cached or serialized in the v1 model: it is recomputed + // on every run, since it reads files outside the analyzed Go source. + Repository *RepositoryFacts `json:"-"` +} + +// RepositoryFacts is the repository-artifact layer (spec v2-artifacts): every +// non-.go project file as an artifact, and the go.mod requires as dependencies. +type RepositoryFacts struct { + // Artifacts is keyed by repo-relative POSIX path. + Artifacts map[string]GoArtifact + // Dependencies is sorted by module path. + Dependencies []GoDependency +} + +// GoArtifact is one non-.go project file. +type GoArtifact struct { + Path string + Format string + Roles []string + SizeBytes int64 + SHA256 string + Source string // whole file text, only when --artifact-text is on + Extraction string // none | full +} + +// GoDependency is one go.mod require, evidence-tagged by go.sum. +type GoDependency struct { + Name string + Ecosystem string + Spec string + Kind string + Direct bool + LockedVersion string // go.sum version of Spec, when both its h1 and /go.mod lines exist + DeclaredIn string // path of the go.mod artifact + ProvidesImports []string // project import paths that resolve to this module + Prov []string // declared | lockfile } // GoExternalCallee describes a library function or method called from the diff --git a/internal/schema/v2/schema.go b/internal/schema/v2/schema.go index 800c694..ce3eefa 100644 --- a/internal/schema/v2/schema.go +++ b/internal/schema/v2/schema.go @@ -97,6 +97,12 @@ type Application struct { // reaches, keyed by their `can:////@external//` id. // Absent when the analysis saw no library call. ExternalSymbols map[string]ExternalSymbol `json:"external_symbols,omitempty"` + // Artifacts holds every non-.go project file, keyed by its repo-relative path + // (spec v2-artifacts). Level-independent; absent when the project has no files. + Artifacts map[string]Artifact `json:"artifacts,omitempty"` + // Dependencies holds the go.mod requires, sorted by module path. Absent when + // the project has no root go.mod. + Dependencies []Dependency `json:"dependencies,omitempty"` // ParamIn and ParamOut are the L4 interprocedural parameter edges between // global body-node ids. Absent below -a 4. ParamIn []ParamEdge `json:"param_in,omitempty"` @@ -341,3 +347,31 @@ type Edge struct { // Weight accumulates when merging edges from multiple backends. Weight int `json:"weight,omitempty"` } + +// Artifact is one non-.go project file. Its id is can:////artifact/. +// Source is the whole file text only under --artifact-text; otherwise absent. +type Artifact struct { + ID string `json:"id"` + Kind string `json:"kind"` // always "artifact" + Path string `json:"path"` + Format string `json:"format"` + Roles []string `json:"roles,omitempty"` + SizeBytes int64 `json:"size_bytes"` + SHA256 string `json:"sha256"` + Source string `json:"source,omitempty"` + Extraction string `json:"extraction"` // none | full +} + +// Dependency is one declared module requirement from go.mod. Its package is +// pkg:/, version-less; the version lives on the record. +type Dependency struct { + Name string `json:"name"` + Ecosystem string `json:"ecosystem"` // always "golang" + Spec string `json:"spec"` // version required by go.mod + Kind string `json:"kind"` // always "runtime" (go.mod has no dev/optional split) + Direct bool `json:"direct"` // false for `// indirect` + LockedVersion string `json:"locked_version,omitempty"` + DeclaredIn string `json:"declared_in"` // the go.mod artifact id + ProvidesImports []string `json:"provides_imports,omitempty"` + Prov []string `json:"prov"` // declared | lockfile +} diff --git a/internal/syntactic_analysis/v2emit/emit.go b/internal/syntactic_analysis/v2emit/emit.go index 3f0279e..1371aa4 100644 --- a/internal/syntactic_analysis/v2emit/emit.go +++ b/internal/syntactic_analysis/v2emit/emit.go @@ -254,6 +254,7 @@ func (e *emitter) envelope(app *schema.GoApplication, maxLevel int, analyzerVers }, } out.Application.ExternalSymbols = emitExternalSymbols(e.appID, app.Externals, e.sdg.standIns()) + out.Application.Artifacts, out.Application.Dependencies = emitRepository(e.appID, app.Repository) if e.flow.on { out.KLimit = kLimit } diff --git a/internal/syntactic_analysis/v2emit/repository.go b/internal/syntactic_analysis/v2emit/repository.go new file mode 100644 index 0000000..b68924f --- /dev/null +++ b/internal/syntactic_analysis/v2emit/repository.go @@ -0,0 +1,57 @@ +package v2emit + +import ( + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" +) + +// artifactID is an artifact's durable id: the application root, then the +// artifact segment and the repo-relative path (spec v2-artifacts). +func artifactID(appID, relPath string) string { + return appID + "/artifact/" + relPath +} + +// emitRepository maps the repository facts onto the v2 layer. Artifacts are +// keyed by path; dependencies keep the facts' order (sorted by module path) and +// point at their go.mod artifact by id. A nil facts set emits nothing. +func emitRepository(appID string, facts *schema.RepositoryFacts) (map[string]v2.Artifact, []v2.Dependency) { + if facts == nil { + return nil, nil + } + var arts map[string]v2.Artifact + if len(facts.Artifacts) > 0 { + arts = make(map[string]v2.Artifact, len(facts.Artifacts)) + for path, a := range facts.Artifacts { + arts[path] = v2.Artifact{ + ID: artifactID(appID, path), + Kind: "artifact", + Path: a.Path, + Format: a.Format, + Roles: a.Roles, + SizeBytes: a.SizeBytes, + SHA256: a.SHA256, + Source: a.Source, + Extraction: a.Extraction, + } + } + } + var deps []v2.Dependency + for _, d := range facts.Dependencies { + declared := "" + if d.DeclaredIn != "" { + declared = artifactID(appID, d.DeclaredIn) + } + deps = append(deps, v2.Dependency{ + Name: d.Name, + Ecosystem: d.Ecosystem, + Spec: d.Spec, + Kind: d.Kind, + Direct: d.Direct, + LockedVersion: d.LockedVersion, + DeclaredIn: declared, + ProvidesImports: d.ProvidesImports, + Prov: d.Prov, + }) + } + return arts, deps +} From 99ec0b61b4706bf68933c87dfa052144d2bd243d Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Tue, 24 Nov 2026 14:04:54 -0500 Subject: [PATCH 03/16] fix(neo4j): batch Bolt upserts to bound transaction memory (#59) upsertNodes and upsertEdges sent each node or edge group as one UNWIND statement in one write transaction. On a large app at L4 one group holds millions of rows. On nats-server the push exceeded the Neo4j limit dbms.memory.transaction.total.max and failed with MemoryPoolOutOfMemoryError. Split each group into chunks of boltBatchSize (5000) rows. Each chunk runs in its own write transaction. Build the driver parameters for each chunk only. The snapshot writer already chunks its UNWIND batches. On nats-server the push now completes with 1858128 nodes and 10419341 relationships, exit 0. Client peak memory stays at about 25 GB. That is the second part of #59 and needs separate work. --- internal/neo4j/bolt.go | 34 ++++++++++++++++--------- internal/neo4j/bolt_session_test.go | 39 +++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 12 deletions(-) diff --git a/internal/neo4j/bolt.go b/internal/neo4j/bolt.go index da5b001..ac3aa70 100644 --- a/internal/neo4j/bolt.go +++ b/internal/neo4j/bolt.go @@ -60,6 +60,11 @@ type BoltConfig struct { FullRun bool } +// boltBatchSize is the most rows one UNWIND write transaction carries (#59). +// A whole group in one transaction can exceed the Neo4j transaction memory +// limit on a large app. The driver also encodes each message in client memory. +const boltBatchSize = 5000 + // WriteBolt pushes rows into the live DB per BoltConfig. appID scopes every // destructive statement; it must be the application root id. func WriteBolt(ctx context.Context, rows GraphRows, appID string, cfg BoltConfig) error { @@ -377,12 +382,10 @@ func (w *boltWriter) upsertNodes(nodes []NodeRow) error { } q := fmt.Sprintf("UNWIND $rows AS row MERGE (n:%s {%s: row.k}) SET n += row.p%s", mergeLabel, keyProp, setLabels) - params := map[string]any{"rows": nodeParams(g)} - if err := w.write(func(tx neo4j.ManagedTransaction) error { - _, err := tx.Run(w.ctx, q, params) - return err - }); err != nil { - return err + for _, chunk := range chunkNodes(g, boltBatchSize) { + if err := w.runBatch(q, nodeParams(chunk)); err != nil { + return err + } } } return nil @@ -408,17 +411,24 @@ func (w *boltWriter) upsertEdges(edges []EdgeRow) error { } q := fmt.Sprintf("UNWIND $rows AS row MATCH (a:%s {%s: row.a}) MATCH (b:%s {%s: row.b}) %s SET r += row.p", e0.From.Label, e0.From.KeyProp, e0.To.Label, e0.To.KeyProp, mergeClause) - params := map[string]any{"rows": edgeParams(g, keyed)} - if err := w.write(func(tx neo4j.ManagedTransaction) error { - _, err := tx.Run(w.ctx, q, params) - return err - }); err != nil { - return err + for _, chunk := range chunkEdges(g, boltBatchSize) { + if err := w.runBatch(q, edgeParams(chunk, keyed)); err != nil { + return err + } } } return nil } +// runBatch runs one UNWIND statement over rows in its own write transaction. +func (w *boltWriter) runBatch(q string, rows []map[string]any) error { + params := map[string]any{"rows": rows} + return w.write(func(tx neo4j.ManagedTransaction) error { + _, err := tx.Run(w.ctx, q, params) + return err + }) +} + // ─── tx helpers ─────────────────────────────────────────────────────────────── func (w *boltWriter) write(fn func(neo4j.ManagedTransaction) error) error { diff --git a/internal/neo4j/bolt_session_test.go b/internal/neo4j/bolt_session_test.go index 545d35d..5fcc2df 100644 --- a/internal/neo4j/bolt_session_test.go +++ b/internal/neo4j/bolt_session_test.go @@ -2,6 +2,7 @@ package neo4j import ( "context" + "fmt" "net/url" "reflect" "strings" @@ -95,6 +96,7 @@ type fakeDB struct { rawNamespace any rawLevel any writes []fakeStmt + txs int // ExecuteWrite calls (explicit write transactions) } type fakeStmt struct { @@ -113,6 +115,7 @@ func (s *fakeDB) Run(_ context.Context, q string, params map[string]any, _ ...fu } func (s *fakeDB) ExecuteWrite(ctx context.Context, work neo4j.ManagedTransactionWork, _ ...func(*neo4j.TransactionConfig)) (any, error) { + s.txs++ return work(fakeTx{db: s}) } @@ -534,3 +537,39 @@ func TestStoredOwnerAllowsFreshAndMatchingAnchor(t *testing.T) { } } } + +// TestBolt_UpsertsAreBatched (#59): a node or edge group larger than one batch +// must be split over several write transactions of at most boltBatchSize rows. +// One UNWIND of a whole group (millions of L4 rows on a large app) exceeds +// Neo4j's dbms.memory.transaction.total.max and the client's memory. +func TestBolt_UpsertsAreBatched(t *testing.T) { + const n = 2*boltBatchSize + 1 + nodes := make([]NodeRow, n) + edges := make([]EdgeRow, n) + for i := range nodes { + id := fmt.Sprintf("can://team/app/go/f.go/fn%d", i) + nodes[i] = NodeRow{Labels: []string{LabelCallable, SymbolLabel, MarkerLabel}, KeyProp: "id", Value: id, Props: Props{"name": id}} + ref := NodeRef{Label: LabelCallable, KeyProp: "id", Value: id} + edges[i] = EdgeRow{Type: RelCalls, From: ref, To: ref, Props: Props{"weight": 1}} + } + db := &fakeDB{} + w := &boltWriter{ctx: context.Background(), session: db} + if err := w.upsertNodes(nodes); err != nil { + t.Fatal(err) + } + if err := w.upsertEdges(edges); err != nil { + t.Fatal(err) + } + for _, st := range db.writes { + if rows, _ := st.params["rows"].([]map[string]any); len(rows) > boltBatchSize { + t.Errorf("one statement carries %d rows, want at most %d", len(rows), boltBatchSize) + } + } + if want := 2 * 3; db.txs != want || len(db.writes) != want { + t.Errorf("%d transactions, %d statements; want %d of each (3 node + 3 edge batches)", db.txs, len(db.writes), want) + } + gotNodes, gotEdges := db.pushed() + if len(gotNodes) != n || gotEdges[RelCalls] != n { + t.Errorf("pushed %d nodes, %d edges; want %d of each", len(gotNodes), gotEdges[RelCalls], n) + } +} From ca92152565b34a756da3bb4366c0a597cef4ca52 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Tue, 24 Nov 2026 17:05:43 -0500 Subject: [PATCH 04/16] docs(spec): streaming Neo4j push and memory-limit harness (#59) Design for part 2 of #59. Two passes over the emitter bound client memory. A testcontainers harness checks a 16 GB limit. Includes #62. --- .../specs/2026-11-24-neo4j-streaming-push.md | 239 ++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 docs/design/specs/2026-11-24-neo4j-streaming-push.md diff --git a/docs/design/specs/2026-11-24-neo4j-streaming-push.md b/docs/design/specs/2026-11-24-neo4j-streaming-push.md new file mode 100644 index 0000000..33bb13f --- /dev/null +++ b/docs/design/specs/2026-11-24-neo4j-streaming-push.md @@ -0,0 +1,239 @@ +# Design: streaming Neo4j push (#59, part 2) + +Status: approved by the user. Branch: `fix/issue-59-oom-on-large-apps`. + +## 1. Intent + +`cango --emit neo4j` must not hold the whole graph in client memory. +Today the client holds three full copies at the same time. On nats-server the push +exhausted a 69 GB machine. + +Part 1 of #59 (commit `99ec0b6`) bounded the Neo4j transaction size. +This design bounds the client memory of the projection and the push. + +## 2. Measurements (nats-server, L4, live heap after a forced GC) + +| Stage | Live heap | Note | +|---|---|---| +| After `Analyze` | 10.9 GB | analysis results (SSA, L3, L4) | +| After `v2emit.Emit`, analyzer kept | 34.1 GB | the full `v2` tree adds 23 GB | +| After `v2emit.Emit`, analyzer released | 24.5 GB | the tree alone is 13.6 GB | +| During `Project` | more than 69 GB (RAM) | `GraphRows` copy, heavy swap, stopped after 30 min | + +Largest parts of the `v2` tree: + +- `GlobalOrdinal` id strings use 10.2 GB. + The `param_in` / `param_out` endpoints use 6.2 GB of that, because `Emit` mints them all at once. +- The L4 vertex body nodes and the L4 `ddg` entries use about 11 GB. + +## 3. Goals, non-goals, anti-goals + +Goals: + +- The push never holds the full `v2` tree or the full `GraphRows`. +- The client peak is the analysis results, plus one module, plus small global sets. +- On nats-server the push completes with a peak RSS near the analysis heap (about 11 to 14 GB). +- nats-server and gitea each complete `--emit neo4j` at `-a 4` within a 16 GB container with no swap (§7, §8). +- The graph in the DB is the same as the graph the current code writes. + +Non-goals: + +- Push speed (larger batches, parallel writers). +- Changes to the graph vocabulary, ids, or the JSON output. + +Anti-goals (a failure even if memory goes down): + +- A missing edge. An edge `MATCH` drops an edge silently if an endpoint node is not in the DB. +- A change to the lazy-push rules (D5), the `--eager` purges, or the stored-level gate. +- A non-deterministic push or snapshot. + +## 4. Approaches + +1. **Two passes over the emitter (chosen by the user).** + Pass 1 emits each module, pushes its nodes, and drops it. + Pass 2 emits each module again and pushes its edges. + There is no full tree and no temporary file. Emission and projection run two times. +2. **One pass with the edges in a temporary file.** + The peak memory is the same as approach 1. + It needs an edge encoder and decoder, and several GB of disk for gitea. +3. **Keep `GraphRows`, but make it smaller (Steps A and B).** + This is the least work, but the peak still grows with the graph. + Gitea is about 4 times as large as nats-server, so this approach does not fit. + +## 5. Design + +### 5.1 Emitter: a re-iterable module stream (`internal/syntactic_analysis/v2emit`) + +Add an exported stream type next to `EmitTo`, for example `v2emit.Open(...) *Stream`. +It takes the same arguments as `Emit` and exposes: + +- `Envelope() *v2.Analysis`: the manifest, call graph, external symbols, artifacts and dependencies. + Its `SymbolTable`, `ParamIn`, `ParamOut` and `Degraded` fields are empty. +- `Modules() iter.Seq2[string, v2.Module]`: each module in `sortedFileKeys` order. + Each call emits the modules again. A module is garbage after its loop step. +- `ParamIn()`, `ParamOut() iter.Seq[v2.ParamEdge]`: the same streams `EmitTo` writes. + They are valid only after one full `Modules()` walk, because that walk fills the `l4Overlay` id map. +- `Degraded() []v2.Degraded`: valid only after one full `Modules()` walk. + +The second walk must not print the `l4Overlay.apply` warnings again. +`EmitTo` and `Emit` must keep their exact output (the JSON golden and parity tests prove this). + +### 5.2 Projector: per-module projection into a sink (`internal/neo4j`) + +Split `projector` so that it can project one module at a time into a row sink. +The sink receives node rows and edge rows. A pass selects which rows it keeps. + +The projector needs two global facts today. The streaming design gets them as follows: + +- **Declared ids** (`collectDeclaredIDs`): pass 1 records the type and callable ids of each module. + After pass 1 the set is complete. Pass 2 uses it for `GO_RESOLVES_TO` and `GO_CALLS`. +- **Ghost nodes** (`callEndpoint`, import ghosts): pass 1 records each referenced endpoint id. + After the last module, pass 1 pushes one ghost node for each referenced id that no module declares. + A ghost id appears one time in the push, with the same props that `Project` gives it. + +The `EdgeToSymbol` rule (`GO_EMBEDS`, `GO_SATISFIES`) checks its target against one set. +That set holds the declared ids and the ghost ids, which is every node with the `:GoSymbol` label. +It does not hold body-node ids, so it stays small. + +Within one module, a `RowBuilder` still removes duplicate nodes and duplicate edge facts. +Across modules, the DB `MERGE` makes a duplicate edge row a no-op. + +`Project(a *v2.Analysis) GraphRows` stays. +It drives the same per-module code over an in-memory tree and collects every row. +The unit tests and the parity gate (§6) use it as the reference. + +### 5.3 Bolt writer: the push order (`internal/neo4j/bolt.go`) + +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. +At the end of each phase it flushes every buffer. + +| Step | Action | Why the order matters | +|---|---|---| +| 0 | `validateIdentity` on the envelope application row. `storedAppStale`. DDL. Eager whole-app purge (full + eager only). | Same as today. Nothing is written before the identity checks. | +| 1 | Push the repository nodes from the envelope. | Shared nodes. They have no module. | +| 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. | + +A lazy push still upserts every edge, as it does today. +The push message reports the number of node rows and edge rows sent. + +### 5.4 CLI (`cmd/codeanalyzer/main.go`) + +The neo4j branch opens the stream and passes it to the new entry point. +It no longer calls `v2emit.Emit`. The analysis results stay live, because both passes read them. + +## 6. Verification + +- **Parity gate (the main test):** for the fixtures in `testdata` at `-a 4`, the streamed rows equal `Project(Emit(...))`. + The test collects the streamed rows through a fake sink. It sorts them, removes duplicates, and compares them with the reference rows. +- **Order test (fake DB):** no edge statement runs before the last node statement. + For each module, its purge runs before its nodes and its L4 vertices. +- **Existing tests:** every test in `bolt_session_test.go`, `project_test.go` and the v2emit golden tests passes without change. + The exception is a test that checks the internal call order which this design changes on purpose. +- **Live checks:** run the nats-server push against the `cango-neo4j` container. + Record the peak RSS and the wall time. + Compare the node and relationship counts in the DB with the counts from the `99ec0b6` run (1,858,128 nodes, 10,419,341 relationships). + Then run gitea and record the result. +- **Container check:** run the `memtest` test on nats-server and gitea with the 16 GB limit (§7), and record both peak values. + +## 7. Memory-limit test harness (from the user's review) + +The user asked for containers that test whether `cango` analyzes gitea and nats-server within a fixed memory limit. +The user chose testcontainers-go, as a Go test behind a build tag. + +### 7.1 Files + +- `scripts/memtest/Dockerfile.cango`: a two-stage build. + - Stage 1 (`golang`) builds `cango` from the repository. + - Stage 2 (`ubuntu:24.04`) holds the `cango` binary and a Go toolchain. + `cango` needs the toolchain at run time, because `go/packages` runs `go list`. +- `internal/memtest/memtest_test.go`, with the build tag `memtest`. + - It starts the official `neo4j:5.26-community` image and waits for Bolt. + - It builds the `cango` image from `Dockerfile.cango` and starts it on the same network. + - It runs one push for each app and checks the result. +- `go.mod` gets `github.com/testcontainers/testcontainers-go` and its `neo4j` module. Only the `memtest` test imports them. + +Run: `MEMTEST_APPS=[,...] go test -tags memtest ./internal/memtest -v -timeout 6h`. +The test skips when `MEMTEST_APPS` is empty or Docker is not available. + +### 7.2 Limits + +| Container | Memory limit | Swap | Other settings | +|---|---|---|---| +| `cango` | 16 GB (`HostConfig.Memory`) | none (`MemorySwap` = `Memory`) | `-j` = container CPUs | +| `neo4j` | 12 GB | none | heap 8 GB, page cache 2 GB, `dbms.memory.transaction.total.max` 5.6 GB (same as the local container) | + +`MEMTEST_MEMORY` changes the `cango` limit. The default is `16g`. +With no swap, the kernel stops `cango` when it exceeds the limit. +The test is therefore strict, and swap cannot hide a memory problem. + +### 7.3 Inputs and caches + +- The test mounts each app directory read-only at `/app`. The test apps stay outside the repository. +- A named volume holds the Go module cache (`GOMODCACHE`). The first run downloads the modules of the app, and later runs reuse them. +- Each run starts with an empty `cango` cache, so the analysis runs in full. + +### 7.4 Result + +For each app, the test passes when `cango` exits with code 0 and Docker reports `OOMKilled=false`. +The test also logs the peak memory of the `cango` container, from the cgroup file `memory.peak`. +The peak memory shows the margin under the limit. + +### 7.5 Expected results + +Both apps pass at 16 GB when this branch is complete. +nats-server needs only the streaming push (§5). +gitea also needs the analysis-memory work (§8). + +## 8. Analysis memory (#62, in this branch) + +The user moved #62 into this branch, so #59 closes only when both apps pass at 16 GB. +Gitea is about 4 times as large as nats-server. +At that ratio its analysis heap is about 40 GB, so the streaming push alone is not sufficient. + +This part has no design yet, because I did not profile `Analyze` on gitea. +The order of work is as follows: + +1. Ship the streaming push (§5) and the harness (§7). +2. Run the harness on nats-server at 16 GB. +3. Profile `Analyze` on gitea, stage by stage, with the probe from §2. +4. Write the analysis-memory design as an addendum to this spec, and get approval before any code changes. + +The nats-server profile gives the first candidates for step 4: + +- `sdg.(*sdgBuilder).fill` holds 10.1 GB (cumulative). +- `sdg.sortedPortEdges` holds 3.3 GB, and `sdg.(*ports).vertices` holds 1.9 GB. +- Step 4 also checks whether the analyzer can drop the SSA program before emission. + +## 9. Decision: the `graph.cypher` snapshot (no `--neo4j-uri`) + +Today the snapshot renders the full `GraphRows` into one string, and it writes that string in one call. +It has the same memory problem as the push. + +The user chose S1: the snapshot streams through the same two passes into a buffered file. +The file stays deterministic, but its row order changes. +The order is now modules in order, instead of one global sort. +The snapshot keeps its scoped wipe at the top, and all node statements stay above all edge statements. + +The rejected option S2 kept the snapshot on `Project`. With S2, large apps still run out of memory on the snapshot path. + +## 10. Calls made by the designer (check these) + +- The emitter emits each module two times, instead of a declared-id pre-pass. This adds about 30 s on nats-server. +- The writer pushes ghost nodes one time, after pass 1, instead of per module. +- 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. +- 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. + +## 11. Left to the builder + +- The names of the stream type, the sink interface, and the new entry point. +- How the second module walk suppresses duplicate warnings. +- The buffer structure in the Bolt writer, within the `boltBatchSize` limit. From 24cb5dac2d8c1fd4c033577788114ee48b425392 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Tue, 24 Nov 2026 20:17:56 -0500 Subject: [PATCH 05/16] feat(v2emit): re-iterable module stream for the Neo4j push (#59) Co-Authored-By: Claude Opus 5.5 --- internal/syntactic_analysis/v2emit/emit_l4.go | 19 ++++- .../syntactic_analysis/v2emit/emit_l4_test.go | 25 ++++++ .../syntactic_analysis/v2emit/gate_l4_test.go | 2 + internal/syntactic_analysis/v2emit/stream.go | 78 +++++++++++++++++++ .../syntactic_analysis/v2emit/stream_test.go | 68 ++++++++++++++++ 5 files changed, 190 insertions(+), 2 deletions(-) create mode 100644 internal/syntactic_analysis/v2emit/stream.go create mode 100644 internal/syntactic_analysis/v2emit/stream_test.go diff --git a/internal/syntactic_analysis/v2emit/emit_l4.go b/internal/syntactic_analysis/v2emit/emit_l4.go index feb3df3..6e9f6fa 100644 --- a/internal/syntactic_analysis/v2emit/emit_l4.go +++ b/internal/syntactic_analysis/v2emit/emit_l4.go @@ -41,6 +41,8 @@ type l4Overlay struct { ids map[sdg.Target]string // unresolved records the targets already warned about. unresolved map[sdg.Target]bool + // quiet silences apply's warnings (a repeated module walk). + quiet bool } func newL4Overlay(maxLevel int, res *sdg.Result, idx sigIndex) *l4Overlay { @@ -58,6 +60,19 @@ func newL4Overlay(maxLevel int, res *sdg.Result, idx sigIndex) *l4Overlay { return o } +// setQuiet stops the overlay warnings. A second module walk repeats the first walk's facts. +func (o *l4Overlay) setQuiet() { + if o != nil { + o.quiet = true + } +} + +func (o *l4Overlay) warn(format string, args ...any) { + if !o.quiet { + warnf(format, args...) + } +} + // apply records c's id under its target key (the callable's declaring file // and signature, the key the L3 overlay uses) and adds its L4 overlay: the // vertices to its body, the port edges to its ddg (re-sorted by (src, dst, @@ -72,7 +87,7 @@ func (o *l4Overlay) apply(c *v2.Callable, key dataflow.L3Key) { t := sdg.Target{Callable: key} prev, dup := o.ids[t] if dup && prev != c.ID { - warnf("L4 emit: %s and %s share the target key %s %s", prev, c.ID, key.Path, key.Signature) + o.warn("L4 emit: %s and %s share the target key %s %s", prev, c.ID, key.Path, key.Signature) } if !dup || c.ID < prev { o.ids[t] = c.ID @@ -83,7 +98,7 @@ func (o *l4Overlay) apply(c *v2.Callable, key dataflow.L3Key) { } for _, v := range r.Vertices { if _, clash := c.Body[v.Key]; clash { - warnf("L4 emit: vertex %s of %s collides with a body node; dropped", v.Key, c.ID) + o.warn("L4 emit: vertex %s of %s collides with a body node; dropped", v.Key, c.ID) continue } c.Body[v.Key] = vertexNode(c.ID, v) diff --git a/internal/syntactic_analysis/v2emit/emit_l4_test.go b/internal/syntactic_analysis/v2emit/emit_l4_test.go index 445ac9b..1357509 100644 --- a/internal/syntactic_analysis/v2emit/emit_l4_test.go +++ b/internal/syntactic_analysis/v2emit/emit_l4_test.go @@ -60,3 +60,28 @@ func TestL4Overlay_DuplicateKeyKeepsSmallerID(t *testing.T) { } } } + +// TestL4Overlay_QuietSecondWalk: after setQuiet, a second apply of the same callables warns nothing. +func TestL4Overlay_QuietSecondWalk(t *testing.T) { + key := dataflow.L3Key{Path: "a.go", Signature: "example.com/a.F"} + ids := []string{"can://app/app/go/a.go/example.com/a.F", "can://app/app/go/b.go/example.com/a.F"} + var warned []string + prev := warnf + warnf = func(format string, args ...any) { warned = append(warned, fmt.Sprintf(format, args...)) } + defer func() { warnf = prev }() + o := newL4Overlay(4, &sdg.Result{}, sigIndex{}) + walk := func() { + for _, id := range ids { + o.apply(&v2.Callable{ID: id, Body: map[string]v2.BodyNode{}}, key) + } + } + walk() + if len(warned) != 1 { + t.Fatalf("walk 1: %d warnings, want 1", len(warned)) + } + o.setQuiet() + walk() + if len(warned) != 1 { + t.Errorf("walk 2: %d warnings in total, want 1", len(warned)) + } +} diff --git a/internal/syntactic_analysis/v2emit/gate_l4_test.go b/internal/syntactic_analysis/v2emit/gate_l4_test.go index 582b2bc..fafbfba 100644 --- a/internal/syntactic_analysis/v2emit/gate_l4_test.go +++ b/internal/syntactic_analysis/v2emit/gate_l4_test.go @@ -32,6 +32,7 @@ type l4Fixture struct { l3, l4 *v2.Analysis res map[dataflow.L3Key]dataflow.Result sdg *sdg.Result + app *schema.GoApplication dir string } @@ -82,6 +83,7 @@ func buildL4Identity(t *testing.T, name string, identity *v2.Identity) *l4Fixtur Units: units, L3: res, K: 3, Jobs: 4, }) l4.ApplyTo(app) + fx.app = app fx.sdg = &l4 fx.l4 = Emit(app, resolved, dir, 4, "gate-test", 3, res, &l4) l4Cache[key] = fx diff --git a/internal/syntactic_analysis/v2emit/stream.go b/internal/syntactic_analysis/v2emit/stream.go new file mode 100644 index 0000000..a541e5a --- /dev/null +++ b/internal/syntactic_analysis/v2emit/stream.go @@ -0,0 +1,78 @@ +package v2emit + +import ( + "iter" + + "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" +) + +// Stream is the Emit payload as a module stream that a caller can walk more than one time. +// Each Modules walk emits the modules again, so no walk holds the whole tree. +type Stream struct { + app *schema.GoApplication + e *emitter + env *v2.Analysis + walked bool + lateCache lateFields + lateDone bool +} + +// Open prepares a Stream. It takes the same arguments as Emit. +func Open(app *schema.GoApplication, identity v2.Identity, projectDir string, maxLevel int, analyzerVersion string, kLimit int, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result) *Stream { + e := newEmitter(app, identity, projectDir, maxLevel, l3, l4) + return &Stream{app: app, e: e, env: e.envelope(app, maxLevel, analyzerVersion, kLimit)} +} + +// Envelope returns the payload without symbol_table, param_in, param_out and degraded. +func (s *Stream) Envelope() *v2.Analysis { return s.env } + +// ModuleKeys returns the sorted symbol_table keys. +func (s *Stream) ModuleKeys() []string { return sortedFileKeys(s.app.SymbolTable) } + +// Modules emits each module in symbol_table key order. +// The first complete walk fills the L4 id map. Later walks print no warnings. +func (s *Stream) Modules() iter.Seq2[string, v2.Module] { + return func(yield func(string, v2.Module) bool) { + if s.walked { + s.e.sdg.setQuiet() + } + for _, relPath := range sortedFileKeys(s.app.SymbolTable) { + if !yield(relPath, s.e.module(relPath, s.app.SymbolTable[relPath])) { + return + } + } + s.walked = true + } +} + +// ParamIn streams application.param_in. Call it after one complete Modules walk. +func (s *Stream) ParamIn() iter.Seq[v2.ParamEdge] { return orEmpty(s.late().paramIn) } + +// ParamOut streams application.param_out. Call it after one complete Modules walk. +func (s *Stream) ParamOut() iter.Seq[v2.ParamEdge] { return orEmpty(s.late().paramOut) } + +// Degraded returns the envelope degraded list. Call it after one complete Modules walk. +func (s *Stream) Degraded() []v2.Degraded { return s.late().degraded } + +// late mints the param lists and the degraded list once, after the first walk. +func (s *Stream) late() lateFields { + if !s.walked { + panic("v2emit: Stream late fields read before one complete Modules walk") + } + if s.lateDone { + return s.lateCache + } + s.lateCache, s.lateDone = s.e.sdg.late(), true + return s.lateCache +} + +// orEmpty replaces a nil sequence (no L4) with an empty one, so a range over it is safe. +func orEmpty(seq iter.Seq[v2.ParamEdge]) iter.Seq[v2.ParamEdge] { + if seq == nil { + return func(func(v2.ParamEdge) bool) {} + } + return seq +} diff --git a/internal/syntactic_analysis/v2emit/stream_test.go b/internal/syntactic_analysis/v2emit/stream_test.go new file mode 100644 index 0000000..b6f3787 --- /dev/null +++ b/internal/syntactic_analysis/v2emit/stream_test.go @@ -0,0 +1,68 @@ +package v2emit + +import ( + "bytes" + "encoding/json" + "fmt" + "slices" + "testing" + + "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" +) + +// TestStream_EqualsEmit: two walks of the stream rebuild the Emit payload exactly. +func TestStream_EqualsEmit(t *testing.T) { + for _, name := range append(slices.Clone(l4Fixtures), "rangefunc", "multipackage") { + fx := buildL4(t, name) + want := fx.l4 + s := Open(fx.app, testIdentity(name), fx.dir, 4, "gate-test", 3, fx.res, fx.sdg) + for range 2 { // the second walk must give the same modules + got := *s.Envelope() + got.Application.SymbolTable = map[string]v2.Module{} + for k, m := range s.Modules() { + got.Application.SymbolTable[k] = m + } + got.Application.ParamIn = slices.Collect(s.ParamIn()) + got.Application.ParamOut = slices.Collect(s.ParamOut()) + got.Degraded = s.Degraded() + a, _ := json.Marshal(want) + b, _ := json.Marshal(&got) + if !bytes.Equal(a, b) { + t.Fatalf("%s: stream differs from Emit at byte %d", name, firstDiff(a, b)) + } + } + } +} + +// TestStream_LateFieldsAreCached: the param lists are minted once. A second ParamIn +// walk does not resolve the targets again, so the resolve warning does not repeat. +// (This tests the late() cache, not setQuiet: resolve runs only inside late(). +// TestL4Overlay_QuietSecondWalk is the test of the quiet flag.) +func TestStream_LateFieldsAreCached(t *testing.T) { + fx := buildL4(t, "dataflow") + res := *fx.sdg + ghost := sdg.Target{Callable: dataflow.L3Key{Path: "nowhere.go", Signature: "example.com/nowhere.F"}} + res.ParamIn = append(slices.Clone(res.ParamIn), sdg.ParamEdge{ + Src: sdg.Ref{Owner: ghost, Key: "1:1/actual_in:0"}, + Dst: sdg.Ref{Owner: ghost, Key: "@formal_in:0"}, Var: "x", + }) + var warned []string + prev := warnf + warnf = func(format string, args ...any) { warned = append(warned, fmt.Sprintf(format, args...)) } + defer func() { warnf = prev }() + s := Open(fx.app, testIdentity("dataflow"), fx.dir, 4, "t", 3, fx.res, &res) + for range s.Modules() { + } + for range s.ParamIn() { + } + first := len(warned) + for range s.Modules() { + } + for range s.ParamIn() { + } + if first == 0 || len(warned) != first { + t.Errorf("warnings: %d after walk 1, %d after walk 2; want >0 and unchanged", first, len(warned)) + } +} From 08ab0b2e465b0a57e4d6a7b1b5c3f3a5334105b2 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Tue, 24 Nov 2026 20:19:37 -0500 Subject: [PATCH 06/16] feat(neo4j): module Source and node-only row builder (#59) Co-Authored-By: Claude Opus 5.5 --- internal/neo4j/rows.go | 26 ++++++++++++++--- internal/neo4j/rows_test.go | 44 ++++++++++++++++++++++++++++ internal/neo4j/source.go | 57 +++++++++++++++++++++++++++++++++++++ 3 files changed, 123 insertions(+), 4 deletions(-) create mode 100644 internal/neo4j/source.go diff --git a/internal/neo4j/rows.go b/internal/neo4j/rows.go index ea0ad8b..b4c6787 100644 --- a/internal/neo4j/rows.go +++ b/internal/neo4j/rows.go @@ -79,6 +79,7 @@ type RowBuilder struct { nodes []NodeRow edges []EdgeRow deferred []EdgeRow + noEdges bool // noEdges makes a node-only builder (pass 1). } // NewRowBuilder returns an empty builder. @@ -126,6 +127,9 @@ func (b *RowBuilder) Node(labels []string, keyProp, value string, props Props, m // Edge appends a relationship whose endpoints are known to exist this run. // Exact duplicate facts are collapsed at Finish. func (b *RowBuilder) Edge(relType string, from, to NodeRef, props Props, key string) { + if b.noEdges { + return + } b.edges = append(b.edges, EdgeRow{Type: relType, From: from, To: to, Props: prune(props), Key: key}) } @@ -135,6 +139,9 @@ func (b *RowBuilder) Edge(relType string, from, to NodeRef, props Props, key str // SATISFIES/RESOLVES_TO never dangle. targetLabel is the MERGE label the target // would carry if present (e.g. SymbolLabel). func (b *RowBuilder) EdgeToSymbol(relType string, from NodeRef, targetLabel, targetKey, targetValue string, props Props, key string) { + if b.noEdges { + return + } b.deferred = append(b.deferred, EdgeRow{ Type: relType, From: from, @@ -144,9 +151,7 @@ func (b *RowBuilder) EdgeToSymbol(relType string, from NodeRef, targetLabel, tar }) } -// Finish resolves deferred edges (keeping only those whose target was emitted), -// sorts nodes and edges by a stable key, and returns the GraphRows. Determinism -// matters: identical input must yield byte-identical output downstream. +// Finish resolves deferred edges against the nodes of this builder, then sorts. func (b *RowBuilder) Finish() GraphRows { emitted := make(map[string]bool, len(b.nodes)) for _, n := range b.nodes { @@ -154,8 +159,21 @@ func (b *RowBuilder) Finish() GraphRows { emitted[label+"\x00"+n.Value] = true } } + return b.finish(func(e EdgeRow) bool { return emitted[e.To.Label+"\x00"+e.To.Value] }) +} + +// finishWith resolves deferred edges against symbols, the ids of every :GoSymbol node. +// Every deferred edge targets SymbolLabel, so the id alone decides. +func (b *RowBuilder) finishWith(symbols map[string]bool) GraphRows { + return b.finish(func(e EdgeRow) bool { return e.To.Label == SymbolLabel && symbols[e.To.Value] }) +} + +// finish keeps the deferred edges that pass keep, removes duplicates, and sorts +// nodes and edges by a stable key. Determinism matters: identical input must +// yield byte-identical output downstream. +func (b *RowBuilder) finish(keep func(EdgeRow) bool) GraphRows { for _, e := range b.deferred { - if emitted[e.To.Label+"\x00"+e.To.Value] { + if keep(e) { b.edges = append(b.edges, e) } } diff --git a/internal/neo4j/rows_test.go b/internal/neo4j/rows_test.go index 4266406..1bc7789 100644 --- a/internal/neo4j/rows_test.go +++ b/internal/neo4j/rows_test.go @@ -2,6 +2,7 @@ package neo4j import ( "reflect" + "slices" "testing" ) @@ -230,3 +231,46 @@ func TestCanonicalEdgeFactOrder(t *testing.T) { t.Fatal("site order changes canonical graph") } } + +// TestTreeSource_WalksTheTree: treeSource gives back the tree, in sorted key order. +func TestTreeSource_WalksTheTree(t *testing.T) { + a := buildDataflowL4(t) + s := treeSource(a) + if s.Envelope().Application.SymbolTable != nil || s.Envelope().Application.ParamIn != nil { + t.Fatal("envelope must not carry symbol_table or param_in") + } + var keys []string + for k := range s.Modules() { + keys = append(keys, k) + } + if !slices.IsSorted(keys) || len(keys) != len(a.Application.SymbolTable) { + t.Errorf("module keys %v: want every key, sorted", keys) + } + if n := len(slices.Collect(s.ParamIn())); n != len(a.Application.ParamIn) { + t.Errorf("ParamIn: %d edges, want %d", n, len(a.Application.ParamIn)) + } +} + +// TestRowBuilder_FinishWithResolvesAgainstSymbols: a deferred edge resolves against the given set. +func TestRowBuilder_FinishWithResolvesAgainstSymbols(t *testing.T) { + b := NewRowBuilder() + from := b.Node([]string{SymbolLabel, LabelType, MarkerLabel}, "id", "can://a/a/go/x.go/T", nil, "m") + b.EdgeToSymbol(RelEmbeds, from, SymbolLabel, "id", "can://a/a/go/y.go/U", nil, "") + b.EdgeToSymbol(RelEmbeds, from, SymbolLabel, "id", "can://a/a/go/y.go/V", nil, "") + rows := b.finishWith(map[string]bool{"can://a/a/go/y.go/U": true}) + if len(rows.Edges) != 1 || rows.Edges[0].To.Value != "can://a/a/go/y.go/U" { + t.Errorf("edges %+v: want only the edge to U", rows.Edges) + } +} + +// TestRowBuilder_NoEdgesDropsEdges: a node-only builder keeps no edge. +func TestRowBuilder_NoEdgesDropsEdges(t *testing.T) { + b := NewRowBuilder() + b.noEdges = true + r := b.Node([]string{LabelModule, MarkerLabel}, "id", "can://a/a/go/x.go", nil, "m") + b.Edge(RelHasModule, r, r, nil, "") + b.EdgeToSymbol(RelEmbeds, r, SymbolLabel, "id", "can://a/a/go/x.go", nil, "") + if rows := b.Finish(); len(rows.Edges) != 0 || len(rows.Nodes) != 1 { + t.Errorf("rows %+v: want one node and no edge", rows) + } +} diff --git a/internal/neo4j/source.go b/internal/neo4j/source.go new file mode 100644 index 0000000..efcdfe5 --- /dev/null +++ b/internal/neo4j/source.go @@ -0,0 +1,57 @@ +package neo4j + +import ( + "iter" + "maps" + "slices" + + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" +) + +// Source is the v2 payload as a module stream. *v2emit.Stream satisfies it. +// ParamIn, ParamOut and Degraded are valid only after one complete Modules walk. +type Source interface { + Envelope() *v2.Analysis + ModuleKeys() []string + Modules() iter.Seq2[string, v2.Module] + ParamIn() iter.Seq[v2.ParamEdge] + ParamOut() iter.Seq[v2.ParamEdge] + Degraded() []v2.Degraded +} + +// TreeSource adapts an in-memory tree to a Source. Tests and Project use it. +func TreeSource(a *v2.Analysis) Source { return treeSource(a) } + +type tree struct { + a *v2.Analysis + env *v2.Analysis +} + +func treeSource(a *v2.Analysis) *tree { + env := *a + env.Application.SymbolTable = nil + env.Application.ParamIn = nil + env.Application.ParamOut = nil + env.Degraded = nil + return &tree{a: a, env: &env} +} + +func (t *tree) Envelope() *v2.Analysis { return t.env } + +func (t *tree) ModuleKeys() []string { + return slices.Sorted(maps.Keys(t.a.Application.SymbolTable)) +} + +func (t *tree) Modules() iter.Seq2[string, v2.Module] { + return func(yield func(string, v2.Module) bool) { + for _, k := range t.ModuleKeys() { + if !yield(k, t.a.Application.SymbolTable[k]) { + return + } + } + } +} + +func (t *tree) ParamIn() iter.Seq[v2.ParamEdge] { return slices.Values(t.a.Application.ParamIn) } +func (t *tree) ParamOut() iter.Seq[v2.ParamEdge] { return slices.Values(t.a.Application.ParamOut) } +func (t *tree) Degraded() []v2.Degraded { return t.a.Degraded } From bbb0655e9b9eace32a9534b1d4cdaa5c7118fb28 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Tue, 24 Nov 2026 20:26:54 -0500 Subject: [PATCH 07/16] feat(neo4j): two-pass module projection with a parity gate (#59) Co-Authored-By: Claude Opus 5.5 --- internal/neo4j/project.go | 85 ++++++---- internal/neo4j/project_test.go | 104 +++++++----- internal/neo4j/stream.go | 231 +++++++++++++++++++++++++++ internal/neo4j/stream_test.go | 284 +++++++++++++++++++++++++++++++++ 4 files changed, 637 insertions(+), 67 deletions(-) create mode 100644 internal/neo4j/stream.go create mode 100644 internal/neo4j/stream_test.go diff --git a/internal/neo4j/project.go b/internal/neo4j/project.go index 04111d1..7df42af 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -2,6 +2,7 @@ package neo4j import ( "encoding/json" + "iter" "sort" "strings" @@ -26,33 +27,37 @@ import ( // Project is the pure (tree) → GraphRows function. appID is analysis.Application.ID // (the can:/// root); it is read from the envelope, never recomposed. func Project(a *v2.Analysis) GraphRows { + src := treeSource(a) p := &projector{ b: NewRowBuilder(), - analysis: a, + analysis: src.Envelope(), + modules: keySet(src.ModuleKeys()), // Index of every emitted callable/type id, so call_graph endpoints and // body callees can tell a declared target from an external one. declared: collectDeclaredIDs(a), } - p.projectApplication() + p.projectApplication(src.Degraded()) p.projectRepository() - for _, mod := range a.Application.SymbolTable { - p.projectModule(mod) + for _, m := range src.Modules() { + p.projectModule(m) } p.projectCallGraph() p.projectStandIns() - p.projectParamEdges() + p.projectParamEdges(src.ParamIn(), src.ParamOut()) return p.b.Finish() } type projector struct { - b *RowBuilder - analysis *v2.Analysis - declared map[string]bool + b *RowBuilder + analysis *v2.Analysis // the envelope: id, externals, call graph, repository + modules map[string]bool // symbol_table keys, for the in-project import check + declared map[string]bool // declared type and callable ids + calleeIDs map[string]bool // pass 1 only: @external body callees, which get a ghost later } // ─── application ───────────────────────────────────────────────────────────── -func (p *projector) projectApplication() { +func (p *projector) projectApplication(degraded []v2.Degraded) { a := p.analysis p.b.Node( []string{LabelApplication, MarkerLabel}, @@ -63,7 +68,7 @@ func (p *projector) projectApplication() { "max_level": a.MaxLevel, "analyzer_name": a.Analyzer.Name, "analyzer_version": a.Analyzer.Version, - "degraded_json": degradedJSON(a.Degraded), + "degraded_json": degradedJSON(degraded), }, "", // the application root belongs to no single module ) @@ -270,6 +275,14 @@ func (p *projector) projectBodyNode(callableRef NodeRef, module, callableID, loc // @external id, which routes to its ghost via callEndpoint. if bn.Callee != nil { _, external := p.analysis.Application.ExternalSymbols[*bn.Callee] + if p.b.noEdges { + // Pass 1: declared is not complete yet, so the ghost waits until + // after the module walk. An @external id is never a declared id. + if external { + p.calleeIDs[*bn.Callee] = true + } + return + } if p.declared[*bn.Callee] || external { p.b.Edge(RelResolvesTo, bRef, p.callEndpoint(*bn.Callee), nil, "") } @@ -322,18 +335,25 @@ func (p *projector) projectStandIns() { } // projectParamEdges emits GO_PARAM_IN / GO_PARAM_OUT {var}, one row per JSON -// param_in / param_out edge. Endpoints are body node ids already (the -// emitter minted them), addressed as :GoBodyNode. -func (p *projector) projectParamEdges() { - ref := func(id string) NodeRef { return NodeRef{Label: LabelBodyNode, KeyProp: "id", Value: id} } - for _, e := range p.analysis.Application.ParamIn { - p.b.Edge(RelParamIn, ref(e.Src), ref(e.Dst), Props{"var": e.Var}, "") +// param_in / param_out edge. +func (p *projector) projectParamEdges(in, out iter.Seq[v2.ParamEdge]) { + for e := range in { + r := paramEdgeRow(RelParamIn, e) + p.b.Edge(r.Type, r.From, r.To, r.Props, r.Key) } - for _, e := range p.analysis.Application.ParamOut { - p.b.Edge(RelParamOut, ref(e.Src), ref(e.Dst), Props{"var": e.Var}, "") + for e := range out { + r := paramEdgeRow(RelParamOut, e) + p.b.Edge(r.Type, r.From, r.To, r.Props, r.Key) } } +// paramEdgeRow is the row of one param edge. Endpoints are body node ids +// already (the emitter minted them), addressed as :GoBodyNode. +func paramEdgeRow(rel string, e v2.ParamEdge) EdgeRow { + ref := func(id string) NodeRef { return NodeRef{Label: LabelBodyNode, KeyProp: "id", Value: id} } + return EdgeRow{Type: rel, From: ref(e.Src), To: ref(e.Dst), Props: Props{"var": e.Var}} +} + // ─── imports ────────────────────────────────────────────────────────────────── // projectImports aggregates a module's imports into one GO_IMPORTS edge per @@ -347,7 +367,7 @@ func (p *projector) projectImports(modRef NodeRef, m v2.Module) { // relative file path; Go imports name a package path, not a file — so an // in-project hit is rare and handled conservatively via the id space.) targetModuleID := v2.ModuleID(appID, imp.Path) - if _, ok := p.analysis.Application.SymbolTable[imp.Path]; ok { + if p.modules[imp.Path] { p.b.Edge(RelImports, modRef, NodeRef{Label: LabelModule, KeyProp: "id", Value: targetModuleID}, Props{"alias": emptyToNil(imp.Alias)}, imp.Path) @@ -409,25 +429,30 @@ func (p *projector) callEndpoint(id string) NodeRef { // external one without emitting it twice. func collectDeclaredIDs(a *v2.Analysis) map[string]bool { ids := make(map[string]bool) + for _, m := range a.Application.SymbolTable { + moduleDeclared(m, ids) + } + return ids +} + +// moduleDeclared adds the type and callable ids that module m declares to into. +func moduleDeclared(m v2.Module, into map[string]bool) { var walkCallable func(c v2.Callable) walkCallable = func(c v2.Callable) { - ids[c.ID] = true + into[c.ID] = true for _, inner := range c.Callables { walkCallable(inner) } } - for _, m := range a.Application.SymbolTable { - for _, t := range m.Types { - ids[t.ID] = true - for _, meth := range t.Callables { - walkCallable(meth) - } - } - for _, fn := range m.Functions { - walkCallable(fn) + for _, t := range m.Types { + into[t.ID] = true + for _, meth := range t.Callables { + walkCallable(meth) } } - return ids + for _, fn := range m.Functions { + walkCallable(fn) + } } // ─── flattening helpers ────────────────────────────────────────────────────── diff --git a/internal/neo4j/project_test.go b/internal/neo4j/project_test.go index 04a9a4b..ff3af9a 100644 --- a/internal/neo4j/project_test.go +++ b/internal/neo4j/project_test.go @@ -546,49 +546,79 @@ func TestProject_CallNodeResolvesWithinOwner(t *testing.T) { // ─── L4 overlay ────────────────────────────────────────────────────────────── +// l4Inputs are the arguments v2emit.Emit and v2emit.Open take for a fixture at -a 4. +type l4Inputs struct { + app *schema.GoApplication + identity v2.Identity + dir string + l3 map[dataflow.L3Key]dataflow.Result + l4 *sdg.Result +} + var ( - l4Once sync.Once - l4Analysis *v2.Analysis + l4Mu sync.Mutex + l4InCache = map[string]*l4Inputs{} + l4OutCache = map[string]*v2.Analysis{} ) -// buildDataflowL4 builds testdata/dataflow through the real -a 4 wiring -// (symbol table, resolver, dataflow, sdg.Run merged into the application) -// and emits the v2 L4 analysis. Built once: the projection never mutates it. -func buildDataflowL4(t *testing.T) *v2.Analysis { +// buildL4Inputs builds testdata/ through the real -a 4 wiring (symbol +// table, resolver, dataflow, sdg.Run merged into the application) and returns +// the emitter inputs. Built once per name: Emit and Open never mutate them. +func buildL4Inputs(t *testing.T, name string) *l4Inputs { t.Helper() - l4Once.Do(func() { - _, thisFile, _, _ := runtime.Caller(0) - dir, err := filepath.Abs(filepath.Join(filepath.Dir(thisFile), "..", "..", "testdata", "dataflow")) - if err != nil { - t.Fatalf("resolving fixture dir: %v", err) - } - b := syntactic_analysis.NewSymbolTableBuilder(dir) - st, err := b.Build(nil, true) - if err != nil { - t.Fatalf("symbol table build failed: %v", err) - } - cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) - edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} - units := b.L3Units(st) - res := dataflow.RunWithSideTables(b.Fset(), units, 3, 4) - l4 := sdg.Run(sdg.Input{ - Fset: b.Fset(), Pkgs: b.Pkgs(), ProjectDir: dir, SymbolTable: st, - Externals: app.Externals, CallGraph: app.CallGraph, Units: units, L3: res, K: 3, Jobs: 4, - }) - l4.ApplyTo(app) - l4Analysis = v2emit.Emit(app, func() v2.Identity { - i, e := v2.ResolveIdentity("dataflow", nil) - if e != nil { - panic(e) - } - return i - }(), dir, 4, "neo4j-gate", 3, res, &l4) + l4Mu.Lock() + defer l4Mu.Unlock() + if in, ok := l4InCache[name]; ok { + return in + } + _, thisFile, _, _ := runtime.Caller(0) + dir, err := filepath.Abs(filepath.Join(filepath.Dir(thisFile), "..", "..", "testdata", name)) + if err != nil { + t.Fatalf("resolving fixture dir: %v", err) + } + b := syntactic_analysis.NewSymbolTableBuilder(dir) + st, err := b.Build(nil, true) + if err != nil { + t.Fatalf("%s: symbol table build failed: %v", name, err) + } + cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) + edges := cg.Build(st) + app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + units := b.L3Units(st) + res := dataflow.RunWithSideTables(b.Fset(), units, 3, 4) + l4 := sdg.Run(sdg.Input{ + Fset: b.Fset(), Pkgs: b.Pkgs(), ProjectDir: dir, SymbolTable: st, + Externals: app.Externals, CallGraph: app.CallGraph, Units: units, L3: res, K: 3, Jobs: 4, }) - if l4Analysis == nil { - t.Fatal("L4 fixture build failed") + l4.ApplyTo(app) + identity, err := v2.ResolveIdentity(name, nil) + if err != nil { + t.Fatalf("%s: identity: %v", name, err) } - return l4Analysis + in := &l4Inputs{app: app, identity: identity, dir: dir, l3: res, l4: &l4} + l4InCache[name] = in + return in +} + +// buildFixtureL4 emits testdata/ at -a 4. Built once per name: the +// projection never mutates it. +func buildFixtureL4(t *testing.T, name string) *v2.Analysis { + t.Helper() + in := buildL4Inputs(t, name) + l4Mu.Lock() + defer l4Mu.Unlock() + if a, ok := l4OutCache[name]; ok { + return a + } + a := v2emit.Emit(in.app, in.identity, in.dir, 4, "neo4j-gate", 3, in.l3, in.l4) + l4OutCache[name] = a + return a +} + +// buildDataflowL4 is buildFixtureL4 over testdata/dataflow. +func buildDataflowL4(t *testing.T) *v2.Analysis { + t.Helper() + return buildFixtureL4(t, "dataflow") } func isVertex(kind string) bool { diff --git a/internal/neo4j/stream.go b/internal/neo4j/stream.go new file mode 100644 index 0000000..c7ce280 --- /dev/null +++ b/internal/neo4j/stream.go @@ -0,0 +1,231 @@ +package neo4j + +import ( + "iter" + "maps" + "slices" + + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" +) + +// stager consumes the projection in push order (spec §5.3): every node stage +// runs before the first edge stage, so no edge MATCH misses its endpoint. +// +// A stager must not keep a slice passed to module, shared, late or edges after +// it returns: the caller may reuse it (streamParamEdges reuses its chunk). +// Copying the row values out, for example with append(buf, rows...), is fine. +type stager interface { + begin(app NodeRow) error // step 0: identity, stale check, DDL, eager purge + shared(nodes []NodeRow) error // step 1: repository nodes + module(id string, nodes []NodeRow) error // step 2: every node row of one module + 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 +} + +// streamGraph projects src into st in two module walks. Pass 1 sends the node +// rows of each module and collects the declared ids; the ghosts, stand-ins and +// the application row follow once that set is complete. Pass 2 sends the edge +// rows. No step holds more than one module's rows, or one chunk of param edges. +// Across modules a duplicate edge row may reach st; MERGE makes it a no-op. +func streamGraph(src Source, st stager) (nodes, edges int, err error) { + env := src.Envelope() + keys := src.ModuleKeys() + modSet := keySet(keys) + calleeIDs := map[string]bool{} + mk := func(b *RowBuilder, declared map[string]bool) *projector { + return &projector{b: b, analysis: env, modules: modSet, declared: declared, calleeIDs: calleeIDs} + } + // Step 0. The identity check needs the application row before any write. + // Its degraded_json is not known yet, so begin gets the row without it. + if err = st.begin(appRow(env)); err != nil { + return + } + // Step 1: repository nodes. + repo := mk(nodeOnly(), nil) + repo.projectRepository() + shared := repo.b.Finish().Nodes + if err = st.shared(shared); err != nil { + return + } + nodes += len(shared) + // Step 2, pass 1: module nodes. Ghost nodes (Module == "") move to the late builder. + declared := map[string]bool{} + late := mk(nodeOnly(), declared) + for _, m := range src.Modules() { + moduleDeclared(m, declared) + p := mk(nodeOnly(), declared) + p.projectModule(m) + var own []NodeRow + for _, n := range p.b.Finish().Nodes { + if n.Module == "" { + late.b.Node(n.Labels, n.KeyProp, n.Value, n.Props, "") + continue + } + own = append(own, n) + } + if err = st.module(m.ID, own); err != nil { + return + } + nodes += len(own) + } + // Step 3: against the complete declared set, the body-callee ghosts, the + // call-graph ghosts, the stand-in vertices, and the application row, which + // now carries degraded_json. + for _, id := range slices.Sorted(maps.Keys(calleeIDs)) { + late.callEndpoint(id) + } + late.projectCallGraph() + late.projectStandIns() + late.projectApplication(src.Degraded()) + lateRows := late.b.Finish().Nodes + if err = st.late(lateRows); err != nil { + return + } + nodes += len(lateRows) + + // Step 4, pass 2: edges. GO_EMBEDS / GO_SATISFIES resolve against every + // :GoSymbol id: the declared ids and the late ghosts. + symbols := maps.Clone(declared) + for _, n := range lateRows { + if slices.Contains(n.Labels, SymbolLabel) { + symbols[n.Value] = true + } + } + for _, m := range src.Modules() { + p := mk(NewRowBuilder(), declared) + p.projectModule(m) + r := p.b.finishWith(symbols) + if err = st.edges(r.Edges); err != nil { + return + } + edges += len(r.Edges) + } + // The repository edges, GO_CALLS and the stand-in GO_HAS_BODY_NODE edges. + // No deferred edge here: EdgeToSymbol only runs in projectType. + tail := mk(NewRowBuilder(), declared) + tail.projectRepository() + tail.projectCallGraph() + tail.projectStandIns() + r := tail.b.Finish() + if err = st.edges(r.Edges); err != nil { + return + } + edges += len(r.Edges) + n, err := streamParamEdges(src, st) + edges += n + if err != nil { + 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) + return +} + +// streamParamEdges sends GO_PARAM_IN then GO_PARAM_OUT to st in chunks of +// boltBatchSize. The param edges bypass every RowBuilder: the emitter already +// sorts and deduplicates them, and on a large app their ids are gigabytes. +// The chunk is reused, so st must not keep it (see stager). +func streamParamEdges(src Source, st stager) (int, error) { + chunk := make([]EdgeRow, 0, boltBatchSize) + sent := 0 + flush := func() error { + if len(chunk) == 0 { + return nil + } + if err := st.edges(chunk); err != nil { + return err + } + sent += len(chunk) + chunk = chunk[:0] + return nil + } + for _, s := range []struct { + rel string + edges iter.Seq[v2.ParamEdge] + }{{RelParamIn, src.ParamIn()}, {RelParamOut, src.ParamOut()}} { + for e := range s.edges { + chunk = append(chunk, paramEdgeRow(s.rel, e)) + if len(chunk) == boltBatchSize { + if err := flush(); err != nil { + return sent, err + } + } + } + } + return sent, flush() +} + +// replayRows feeds a ready GraphRows through the stages of st: the +// application row to begin (and again to shared, with the other module-less +// rows), each module's rows (its L4 vertices included) in module order, the +// stand-in vertices to late, then every edge in one call. +func replayRows(rows GraphRows, st stager) (nodes, edges int, err error) { + var app NodeRow + var shared, late []NodeRow + byModule := map[string][]NodeRow{} + for _, n := range rows.Nodes { + if n.Labels[0] == LabelApplication { + app = n + } + switch { + case n.Module == "" && isL4Node(n): + late = append(late, n) + case n.Module == "": + shared = append(shared, n) + default: + byModule[n.Module] = append(byModule[n.Module], n) + } + } + if err = st.begin(app); err != nil { + return + } + if err = st.shared(shared); err != nil { + return + } + nodes += len(shared) + ids := sortedModuleKeys(byModule) + for _, id := range ids { + if err = st.module(id, byModule[id]); err != nil { + return + } + nodes += len(byModule[id]) + } + if err = st.late(late); err != nil { + return + } + nodes += len(late) + if err = st.edges(rows.Edges); err != nil { + return + } + edges = len(rows.Edges) + err = st.end(ids) + return +} + +// appRow is the application row projectApplication makes, without +// degraded_json, which is known only after the module walk. +func appRow(env *v2.Analysis) NodeRow { + p := &projector{b: NewRowBuilder(), analysis: env} + p.projectApplication(nil) + return p.b.Finish().Nodes[0] +} + +// nodeOnly returns a builder that drops every edge (pass 1). +func nodeOnly() *RowBuilder { + b := NewRowBuilder() + b.noEdges = true + return b +} + +func keySet(keys []string) map[string]bool { + s := make(map[string]bool, len(keys)) + for _, k := range keys { + s[k] = true + } + return s +} diff --git a/internal/neo4j/stream_test.go b/internal/neo4j/stream_test.go new file mode 100644 index 0000000..0d82d65 --- /dev/null +++ b/internal/neo4j/stream_test.go @@ -0,0 +1,284 @@ +package neo4j + +import ( + "fmt" + "regexp" + "slices" + "strings" + "testing" + + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" +) + +// collectStager records the stages in order. +type collectStager struct { + stages []string + nodes []NodeRow + edgeRows []EdgeRow + mods []string + endIDs []string +} + +func (c *collectStager) begin(app NodeRow) error { + c.stages = append(c.stages, "begin") + c.nodes = append(c.nodes, app) + return nil +} + +func (c *collectStager) shared(n []NodeRow) error { + c.stages = append(c.stages, "shared") + c.nodes = append(c.nodes, n...) + return nil +} + +func (c *collectStager) module(id string, n []NodeRow) error { + c.stages = append(c.stages, "module") + c.mods = append(c.mods, id) + c.nodes = append(c.nodes, n...) + return nil +} + +func (c *collectStager) late(n []NodeRow) error { + c.stages = append(c.stages, "late") + c.nodes = append(c.nodes, n...) + return nil +} + +func (c *collectStager) edges(e []EdgeRow) error { + c.stages = append(c.stages, "edges") + c.edgeRows = append(c.edgeRows, e...) + return nil +} + +func (c *collectStager) end(ids []string) error { + c.stages = append(c.stages, "end") + c.endIDs = ids + return nil +} + +// parityFixtures are the trees the parity gate projects both ways. +func parityFixtures(t *testing.T) map[string]*v2.Analysis { + t.Helper() + fx := map[string]*v2.Analysis{ + "multipackage L2": buildMultipackageL2(t), + "dataflow L1": buildDataflowAt(t, 1), + "dataflow L3": buildDataflowL3(t), + "dataflow L4": buildDataflowL4(t), + } + for _, name := range []string{"chi", "generics", "storedlit", "rangefunc"} { + fx[name+" L4"] = buildFixtureL4(t, name) + } + fx["repository"] = repoAnalysis() + fx["cross-module"] = crossModuleAnalysis() + return fx +} + +// crossModuleAnalysis is a hand-built tree whose facts cross modules the way +// pass 1 cannot see: a.go's body callee and embedded type live in b.go, a.go's +// type embeds a call-graph ghost, and one external is reached by a body callee only. +func crossModuleAnalysis() *v2.Analysis { + const app = "can://x/x" + a, b := v2.ModuleID(app, "a.go"), v2.ModuleID(app, "b.go") + typeB, iface := v2.TypeID(b, "B"), v2.TypeID(b, "I") + f, g := v2.CallableID(a, "F()"), v2.CallableID(b, "G()") + ghost := v2.ExternalID(app, "lib", "Q") // call graph only + bodyOnly := v2.ExternalID(app, "lib", "E") // body callee only + return &v2.Analysis{ + IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 2, + Application: v2.Application{ + IdentityVersion: 2, ID: app, Kind: "application", + SymbolTable: map[string]v2.Module{ + "a.go": {ID: a, Kind: "module", Package: "x", + Imports: []v2.Import{{Name: "b", Path: "b.go"}, {Name: "fmt", Path: "fmt"}}, + Types: map[string]v2.Type{"A": {ID: v2.TypeID(a, "A"), Kind: "struct", + BaseTypes: []string{typeB, ghost, "raw.Unresolved"}, Interfaces: []string{iface}}}, + Functions: map[string]v2.Callable{"F()": {ID: f, Kind: "function", Signature: "F()", + Body: map[string]v2.BodyNode{ + "0": {Kind: "call", Callee: &g}, + "1": {Kind: "call", Callee: new(bodyOnly)}, + }}}, + }, + "b.go": {ID: b, Kind: "module", Package: "x", + Types: map[string]v2.Type{ + "B": {ID: typeB, Kind: "struct"}, + "I": {ID: iface, Kind: "interface"}, + }, + Functions: map[string]v2.Callable{"G()": {ID: g, Kind: "function", Signature: "G()"}}, + }, + }, + CallGraph: []v2.Edge{{Src: f, Dst: g, Weight: 1}, {Src: f, Dst: ghost, Weight: 1}}, + ExternalSymbols: map[string]v2.ExternalSymbol{ + bodyOnly: {ID: bodyOnly, Kind: "external", Name: "E", Module: "lib", Signature: "E"}, + }, + }, + } +} + +// mergeRows collapses streamed rows the way one RowBuilder would: nodes on +// the builder key (labels union, props merged), duplicate edges on the Finish key. +func mergeRows(nodes []NodeRow, edges []EdgeRow) GraphRows { + b := NewRowBuilder() + for _, n := range nodes { + b.Node(n.Labels, n.KeyProp, n.Value, n.Props, n.Module) + } + for _, e := range edges { + b.Edge(e.Type, e.From, e.To, e.Props, e.Key) + } + return b.Finish() +} + +// diffRows reports the first five missing and extra rows of each kind, "" when equal. +func diffRows(want, got GraphRows) string { + nodeKey := func(n NodeRow) string { + return fmt.Sprintf("%v %s %v module=%q", n.Labels, n.Value, n.Props, n.Module) + } + var out strings.Builder + report := func(kind string, want, got []string) { + w, g := map[string]bool{}, map[string]bool{} + for _, k := range want { + w[k] = true + } + for _, k := range got { + g[k] = true + } + for _, side := range []struct { + name string + from, in map[string]bool + keys []string + }{{"missing", w, g, want}, {"extra", g, w, got}} { + n := 0 + for _, k := range side.keys { + if !side.in[k] { + if n < 5 { + fmt.Fprintf(&out, "%s %s: %s\n", side.name, kind, strings.ReplaceAll(k, "\x00", " | ")) + } + n++ + } + } + if n > 5 { + fmt.Fprintf(&out, "... %d more %s %s\n", n-5, side.name, kind) + } + } + } + var wn, gn, we, ge []string + for _, n := range want.Nodes { + wn = append(wn, nodeKey(n)) + } + for _, n := range got.Nodes { + gn = append(gn, nodeKey(n)) + } + for _, e := range want.Edges { + we = append(we, edgeSortKey(e)) + } + for _, e := range got.Edges { + ge = append(ge, edgeSortKey(e)) + } + report("node", wn, gn) + report("edge", we, ge) + return out.String() +} + +// TestStream_ParityWithProject: the streamed rows, merged and deduplicated, equal Project. +func TestStream_ParityWithProject(t *testing.T) { + for name, a := range parityFixtures(t) { + want := Project(a) + c := &collectStager{} + if _, _, err := streamGraph(treeSource(a), c); err != nil { + t.Fatal(err) + } + got := mergeRows(c.nodes, c.edgeRows) + if d := diffRows(want, got); d != "" { + t.Errorf("%s: streamed rows differ from Project:\n%s", name, d) + } + } +} + +// TestStream_ParityThroughEmitterStream: streamGraph over v2emit.Open equals Project(v2emit.Emit(...)). +func TestStream_ParityThroughEmitterStream(t *testing.T) { + for _, name := range []string{"dataflow", "chi", "generics", "storedlit", "rangefunc"} { + in := buildL4Inputs(t, name) + want := Project(v2emit.Emit(in.app, in.identity, in.dir, 4, "neo4j-gate", 3, in.l3, in.l4)) + c := &collectStager{} + src := v2emit.Open(in.app, in.identity, in.dir, 4, "neo4j-gate", 3, in.l3, in.l4) + if _, _, err := streamGraph(src, c); err != nil { + t.Fatal(err) + } + if d := diffRows(want, mergeRows(c.nodes, c.edgeRows)); d != "" { + t.Errorf("%s: streamed rows differ from Project(Emit):\n%s", name, d) + } + } +} + +// TestStream_StageOrder: every node stage runs before the first edge stage. +func TestStream_StageOrder(t *testing.T) { + a := buildDataflowL4(t) + c := &collectStager{} + if _, _, err := streamGraph(treeSource(a), c); err != nil { + t.Fatal(err) + } + s := strings.Join(c.stages, ",") + if !regexp.MustCompile(`^begin,shared,(module,)+late,(edges,)+end$`).MatchString(s) { + t.Errorf("stages %s", s) + } + 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) { + t.Errorf("late application row degraded_json present=%v, degraded=%d", ok, len(a.Degraded)) + } + } + } +} + +// TestStream_CrossModuleFixtureHasTheHardRows keeps the cross-module parity +// fixture honest: Project must make each row that pass 1 alone would get wrong. +func TestStream_CrossModuleFixtureHasTheHardRows(t *testing.T) { + rows := Project(crossModuleAnalysis()) + got := map[string]int{} + for _, e := range rows.Edges { + got[e.Type+" "+lastSegment(e.To.Value)]++ + } + for _, want := range []string{ + RelEmbeds + " B", RelEmbeds + " Q", RelSatisfies + " I", + RelResolvesTo + " G()", RelResolvesTo + " E", RelImports + " b.go", RelImports + " fmt", + } { + if got[want] != 1 { + t.Errorf("want one %q edge, got %d", want, got[want]) + } + } + for _, n := range rows.Nodes { + if hasLabel(n, LabelExternal) && lastSegment(n.Value) == "G()" { + t.Errorf("false ghost for the declared callee %s", n.Value) + } + } +} + +// TestReplayRows_SplitsAReadyGraphRows: replayRows sends every row once, in +// stage order, with the stand-in vertices in late and the modules sorted. +func TestReplayRows_SplitsAReadyGraphRows(t *testing.T) { + a := buildDataflowL4(t) + rows := Project(a) + c := &collectStager{} + nodes, edges, err := replayRows(rows, c) + if err != nil { + t.Fatal(err) + } + if nodes != len(rows.Nodes) || edges != len(rows.Edges) { + t.Errorf("counts %d/%d, want %d/%d", nodes, edges, len(rows.Nodes), len(rows.Edges)) + } + 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 d := diffRows(rows, mergeRows(c.nodes, c.edgeRows)); d != "" { + t.Errorf("replayed rows differ:\n%s", d) + } +} From c4bd3b4d245f565d2f5c959b9f2c53189fdd8544 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Tue, 24 Nov 2026 20:33:51 -0500 Subject: [PATCH 08/16] feat(neo4j): stream the Bolt push in two passes (#59) Co-Authored-By: Claude Opus 5.5 --- internal/neo4j/bolt.go | 374 +++++++++++++++++----------- internal/neo4j/bolt_session_test.go | 301 +++++++++++++--------- 2 files changed, 413 insertions(+), 262 deletions(-) diff --git a/internal/neo4j/bolt.go b/internal/neo4j/bolt.go index ac3aa70..718fb5b 100644 --- a/internal/neo4j/bolt.go +++ b/internal/neo4j/bolt.go @@ -15,33 +15,33 @@ import ( // CGO_ENABLED=0 static build still links; it is only exercised when EmitNeo4j // runs with a --neo4j-uri, never on the JSON path. // -// Algorithm: -// 1. ensure constraints + indexes; -// 2. stored-application gate: read :GoApplication.schema_version and +// The writer is a stager (stream.go); its stages run in push order (spec §5.3): +// 1. begin: stored-application gate — read :GoApplication.schema_version and // max_level scoped to this app's id; a version mismatch, or a stored level // below this push's, forces a full re-UPSERT (never a delete — that is -// --eager's job); -// 3. partition nodes by owning module (NodeRow.module); shared nodes (externals, -// neutral repo nodes) have none and are MERGE-only, always upserted; L4 -// vertex nodes (a callable's or a stand-in's formal/actual vertices) are -// their own group; -// 4. --eager? scoped purge of everything under the app prefix, then rebuild; -// 5. diff each module's content_hash against the DB → the changed set; -// 6. per changed module: on --eager, purge its owned edges + stale decls, then -// upsert its nodes; WITHOUT --eager the push only adds/updates; -// 7. upsert every L4 vertex node, changed module or not (D5, below); -// 8. upsert every edge (an unchanged edge's MERGE is a no-op); -// 9. on a full --eager run, orphan-prune modules whose source vanished. +// --eager's job); ensure constraints + indexes; --eager? scoped purge of +// everything under the app prefix, then rebuild; +// 2. shared: upsert the module-less repository nodes (MERGE-only, always); +// 3. module, per module: diff its content_hash against the DB; when changed, +// on --eager purge its owned edges + stale decls, then upsert its L1–L3 +// nodes (WITHOUT --eager the push only adds/updates); upsert its L4 vertex +// nodes, changed module or not (D5, below); +// 4. late: upsert the ghosts, stand-in vertices and application row, and +// flush every node buffer; +// 5. edges: upsert every edge (an unchanged edge's MERGE is a no-op); +// 6. end: flush the edges; on a full --eager run, orphan-prune modules whose +// source vanished. // // D5 (spec §4.11): L4 facts are not module-local — editing a callee changes // its callers' summary edges, actual vertices and even formal_in indices — // so the content_hash diff gates the L1–L3 rows only. A lazy push upserts -// every L4 row on every push: the vertex nodes (step 7), the stand-in +// every L4 row on every push: the vertex nodes (steps 3–4), the stand-in // bodies among them, and the GO_PARAM_IN / GO_PARAM_OUT / GO_SUMMARY rows -// and the port GO_DDG rows (prov ≠ ssa) with every other edge (step 8). It +// and the port GO_DDG rows (prov ≠ ssa) with every other edge (step 5). It // is additive: a stale L4 row stays until an --eager push. // -// A push NEVER deletes by default (#171): steps 4/6/8 run under --eager only. +// A push NEVER deletes by default (#171): the purges and the prune run under +// --eager only. // Every destructive statement is scoped on the can://// id prefix (#173), // anchored on :GoCanNode so it seeks an index. @@ -65,12 +65,36 @@ type BoltConfig struct { // limit on a large app. The driver also encodes each message in client memory. const boltBatchSize = 5000 -// WriteBolt pushes rows into the live DB per BoltConfig. appID scopes every -// destructive statement; it must be the application root id. +// 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. func WriteBolt(ctx context.Context, rows GraphRows, appID string, cfg BoltConfig) error { if err := validateIdentity(rows, appID); err != nil { return err } + return withSession(ctx, cfg, func(s neo4j.SessionWithContext) error { + _, _, err := replayRows(rows, newBoltWriter(ctx, s, appID, cfg)) + return err + }) +} + +// PushBolt streams src into the DB in the two-pass order (spec §5.3). It +// returns the row counts. +func PushBolt(ctx context.Context, src Source, cfg BoltConfig) (nodes, edges int, err error) { + env := src.Envelope() + appID := env.Application.ID + if err = validateIdentity(GraphRows{Nodes: []NodeRow{appRow(env)}}, appID); err != nil { + return + } + err = withSession(ctx, cfg, func(s neo4j.SessionWithContext) error { + nodes, edges, err = streamGraph(src, newBoltWriter(ctx, s, appID, cfg)) + return err + }) + return +} + +// withSession opens a driver and a session per cfg, runs fn, and closes both. +func withSession(ctx context.Context, cfg BoltConfig, fn func(neo4j.SessionWithContext) error) error { driver, err := neo4j.NewDriverWithContext(cfg.URI, neo4j.BasicAuth(cfg.User, cfg.Password, "")) if err != nil { return fmt.Errorf("neo4j driver: %w", err) @@ -82,92 +106,121 @@ func WriteBolt(ctx context.Context, rows GraphRows, appID string, cfg BoltConfig session := driver.NewSession(ctx, neo4j.SessionConfig{DatabaseName: cfg.Database}) defer func() { _ = session.Close(ctx) }() - - w := &boltWriter{ctx: ctx, session: session, rows: rows, appID: appID, cfg: cfg} - return w.run() + return fn(session) } +// boltWriter is the Bolt stager. Node rows are buffered per MERGE group and a +// group runs once it holds boltBatchSize rows; every node buffer is flushed by +// late, before the first edge statement, so no edge MATCH misses its endpoint. type boltWriter struct { ctx context.Context session neo4j.SessionWithContext - rows GraphRows appID string cfg BoltConfig + level int // max_level of the begin row + forced bool // forceFull || cfg.Eager: every module counts as changed + scoped bool + nodeBuf map[string][]NodeRow + edgeBuf map[string][]EdgeRow } -func (w *boltWriter) run() error { +func newBoltWriter(ctx context.Context, s neo4j.SessionWithContext, appID string, cfg BoltConfig) *boltWriter { + return &boltWriter{ctx: ctx, session: s, appID: appID, cfg: cfg, + nodeBuf: map[string][]NodeRow{}, edgeBuf: map[string][]EdgeRow{}} +} - // Stored-application gate: a producer/consumer version mismatch, or a - // graph pushed at a lower level, forces a full re-upsert (it never - // deletes). The upsert path below is already a full MERGE of every - // current node, so it simply means we don't trust the per-module - // content_hash diff and upsert everything. +// begin runs the stored-application gate, the DDL and the eager purge. A +// producer/consumer version mismatch, or a graph pushed at a lower level, +// forces a full re-upsert (it never deletes): the per-module content_hash +// diff is not trusted and every module is upserted. +func (w *boltWriter) begin(app NodeRow) error { + w.level, _ = app.Props["max_level"].(int) forceFull, err := w.storedAppStale() if err != nil { return err } - if err := w.ensureDDL(); err != nil { return err } root, scoped := applicationPrefix(w.appID) + w.scoped = scoped if w.shouldEagerPurge(scoped) { if err := w.eagerPurge(root); err != nil { return err } } + w.forced = forceFull || w.cfg.Eager + return nil +} - // Partition nodes by owning module; shared nodes (module == "") and L4 - // vertex nodes are always upserted. - byModule, shared, l4 := partitionNodes(w.rows.Nodes) +// shared upserts the module-less nodes (MERGE-only, every run). +func (w *boltWriter) shared(nodes []NodeRow) error { + if err := w.bufferNodes(nodes); err != nil { + return err + } + return w.flushNodes() +} - // Diff content_hash per module unless a mismatch/eager forces everything. - changed := map[string]bool{} - if forceFull || w.cfg.Eager { - for m := range byModule { - changed[m] = true +// module buffers one module's L1–L3 nodes when it changed (on --eager, after +// purging its owned edges and stale decls), and its L4 vertex nodes always, +// after the purge so it cannot delete them (D5). +func (w *boltWriter) module(id string, nodes []NodeRow) error { + var core, l4 []NodeRow + for _, n := range nodes { + if isL4Node(n) { + l4 = append(l4, n) + } else { + core = append(core, n) } - } else { - changed, err = w.changedModules(byModule) - if err != nil { + } + changed := w.forced + if !changed { + var err error + if changed, err = w.moduleChanged(id, moduleHash(core)); err != nil { return err } } - - // Upsert shared nodes (MERGE-only, every run) then changed-module nodes. - if err := w.upsertNodes(shared); err != nil { - return err - } - for _, m := range sortedModuleKeys(byModule) { - if !changed[m] { - continue - } - if w.cfg.Eager && scoped { - if err := w.purgeModule(m); err != nil { + if changed { + if w.cfg.Eager && w.scoped { + // Flushed first so the DB order matches the statement order; + // the purge only matches ids under this module's prefix. + if err := w.flushNodes(); err != nil { + return err + } + if err := w.purgeModule(id); err != nil { return err } } - if err := w.upsertNodes(byModule[m]); err != nil { + if err := w.bufferNodes(core); err != nil { return err } } - // L4 vertex nodes, after the module purges so an --eager purge of a - // changed module cannot delete them (D5). - if err := w.upsertNodes(l4); err != nil { + return w.bufferNodes(l4) +} + +// late upserts the ghosts, the stand-in vertices and the application row, +// and flushes every node buffer before the first edge statement. +func (w *boltWriter) late(nodes []NodeRow) error { + if err := w.bufferNodes(nodes); err != nil { return err } + return w.flushNodes() +} + +// edges buffers every edge: the L4 rows must be upserted (D5), and for the +// L1–L3 rows the precise owner buys nothing — a MERGE-upsert of an unchanged +// edge is a harmless no-op. +func (w *boltWriter) edges(edges []EdgeRow) error { + return w.bufferEdges(edges) +} - // Upsert every edge: the L4 rows must be (D5), and for the L1–L3 rows - // the precise owner (the source node's module) buys nothing — a - // MERGE-upsert of an unchanged edge is a harmless no-op. - if err := w.upsertEdges(w.rows.Edges); err != nil { +// 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 && scoped { - if err := w.pruneVanishedModules(byModule); err != nil { - return err - } + if w.cfg.Eager && w.cfg.FullRun && w.scoped { + return w.pruneVanishedModules(moduleIDs) } return nil } @@ -250,20 +303,7 @@ func (w *boltWriter) storedAppStale() (bool, error) { if stored != "" && stored != SchemaVersion || badLevel { return true, nil } - return haveLevel && storedLevel < int64(w.pushLevel()), nil -} - -// pushLevel is the max_level of the application row this push carries (0 -// when it carries none). -func (w *boltWriter) pushLevel() int { - for _, n := range w.rows.Nodes { - if n.Labels[0] == LabelApplication && n.Value == w.appID { - if l, ok := n.Props["max_level"].(int); ok { - return l - } - } - } - return 0 + return haveLevel && storedLevel < int64(w.level), nil } // ─── destructive steps (--eager only) ───────────────────────────────────────── @@ -311,11 +351,7 @@ func purgeModuleQuery(moduleID string) (string, map[string]any) { // pruneVanishedModules removes modules under the app prefix that this run no // longer emits (their source file vanished). Full + eager only. -func (w *boltWriter) pruneVanishedModules(byModule map[string][]NodeRow) error { - present := make([]string, 0, len(byModule)) - for m := range byModule { - present = append(present, m) - } +func (w *boltWriter) pruneVanishedModules(present []string) error { root, _ := applicationPrefix(w.appID) desc := descendantPrefix(root) return w.write(func(tx neo4j.ManagedTransaction) error { @@ -329,97 +365,141 @@ func (w *boltWriter) pruneVanishedModules(byModule map[string][]NodeRow) error { // ─── diff ───────────────────────────────────────────────────────────────────── -// changedModules compares each module's content_hash in rows against the DB. -func (w *boltWriter) changedModules(byModule map[string][]NodeRow) (map[string]bool, error) { - changed := map[string]bool{} - for _, m := range sortedModuleKeys(byModule) { - localHash := moduleHash(byModule[m]) - var dbHash string - err := w.read(func(tx neo4j.ManagedTransaction) error { - res, err := tx.Run(w.ctx, - "MATCH (m:GoModule {id: $id}) RETURN m.content_hash AS h", - map[string]any{"id": m}) - if err != nil { - return err - } - if res.Next(w.ctx) { - if h, ok := res.Record().Get("h"); ok && h != nil { - dbHash, _ = h.(string) - } - } - return res.Err() - }) +// moduleChanged compares a module's local content_hash against the DB's. +func (w *boltWriter) moduleChanged(id, localHash string) (bool, error) { + var dbHash string + err := w.read(func(tx neo4j.ManagedTransaction) error { + res, err := tx.Run(w.ctx, + "MATCH (m:GoModule {id: $id}) RETURN m.content_hash AS h", + map[string]any{"id": id}) if err != nil { - return nil, err + return err } - // Changed when the hash differs or the module is new, or when either side - // has no hash (can't prove unchanged → upsert). - if localHash == "" || dbHash == "" || localHash != dbHash { - changed[m] = true + if res.Next(w.ctx) { + if h, ok := res.Record().Get("h"); ok && h != nil { + dbHash, _ = h.(string) + } } + return res.Err() + }) + if err != nil { + return false, err } - return changed, nil + // Changed when the hash differs or the module is new, or when either side + // has no hash (can't prove unchanged → upsert). + return localHash == "" || dbHash == "" || localHash != dbHash, nil } // ─── upserts ────────────────────────────────────────────────────────────────── +// upsertNodes and upsertEdges write a ready slice: buffer, then flush. func (w *boltWriter) upsertNodes(nodes []NodeRow) error { - if len(nodes) == 0 { - return nil + if err := w.bufferNodes(nodes); err != nil { + return err + } + return w.flushNodes() +} + +func (w *boltWriter) upsertEdges(edges []EdgeRow) error { + if err := w.bufferEdges(edges); err != nil { + return err + } + return w.flushEdges() +} + +// bufferNodes appends each node to its MERGE group and runs a group as soon +// as it holds boltBatchSize rows. +func (w *boltWriter) bufferNodes(nodes []NodeRow) error { + if w.nodeBuf == nil { + w.nodeBuf = map[string][]NodeRow{} } - groups := map[string][]NodeRow{} for _, n := range nodes { - groups[nodeGroupKey(n)] = append(groups[nodeGroupKey(n)], n) - } - for _, gk := range sortedKeys(groups) { - g := groups[gk] - mergeLabel := g[0].Labels[0] - keyProp := g[0].KeyProp - extra := g[0].Labels[1:] - setLabels := "" - for _, l := range extra { - setLabels += " SET n:" + l + gk := nodeGroupKey(n) + g := append(w.nodeBuf[gk], n) + if len(g) == boltBatchSize { + if err := w.runNodes(g); err != nil { + return err + } + g = g[:0] } - q := fmt.Sprintf("UNWIND $rows AS row MERGE (n:%s {%s: row.k}) SET n += row.p%s", - mergeLabel, keyProp, setLabels) - for _, chunk := range chunkNodes(g, boltBatchSize) { - if err := w.runBatch(q, nodeParams(chunk)); err != nil { + w.nodeBuf[gk] = g + } + return nil +} + +// flushNodes runs every buffered node group in key order and clears the buffer. +func (w *boltWriter) flushNodes() error { + for _, gk := range sortedKeys(w.nodeBuf) { + if g := w.nodeBuf[gk]; len(g) > 0 { + if err := w.runNodes(g); err != nil { return err } } } + clear(w.nodeBuf) return nil } -func (w *boltWriter) upsertEdges(edges []EdgeRow) error { - if len(edges) == 0 { - return nil +// runNodes upserts one chunk of a node group (same labels and key property). +func (w *boltWriter) runNodes(g []NodeRow) error { + setLabels := "" + for _, l := range g[0].Labels[1:] { + setLabels += " SET n:" + l } - groups := map[string][]EdgeRow{} - for _, e := range edges { - groups[edgeGroupKey(e)] = append(groups[edgeGroupKey(e)], e) + q := fmt.Sprintf("UNWIND $rows AS row MERGE (n:%s {%s: row.k}) SET n += row.p%s", + g[0].Labels[0], g[0].KeyProp, setLabels) + return w.runBatch(q, nodeParams(g)) +} + +// bufferEdges appends each edge to its MERGE group and runs a group as soon +// as it holds boltBatchSize rows. +func (w *boltWriter) bufferEdges(edges []EdgeRow) error { + if w.edgeBuf == nil { + w.edgeBuf = map[string][]EdgeRow{} } - for _, gk := range sortedEdgeKeys(groups) { - g := groups[gk] - e0 := g[0] - keyed := e0.Key != "" - var mergeClause string - if keyed { - mergeClause = fmt.Sprintf("MERGE (a)-[r:%s {_k: row.k, %s: row.f}]->(b)", e0.Type, RelationshipFactProperty) - } else { - mergeClause = fmt.Sprintf("MERGE (a)-[r:%s {%s: row.f}]->(b)", e0.Type, RelationshipFactProperty) + for _, e := range edges { + gk := edgeGroupKey(e) + g := append(w.edgeBuf[gk], e) + if len(g) == boltBatchSize { + if err := w.runEdges(g); err != nil { + return err + } + g = g[:0] } - q := fmt.Sprintf("UNWIND $rows AS row MATCH (a:%s {%s: row.a}) MATCH (b:%s {%s: row.b}) %s SET r += row.p", - e0.From.Label, e0.From.KeyProp, e0.To.Label, e0.To.KeyProp, mergeClause) - for _, chunk := range chunkEdges(g, boltBatchSize) { - if err := w.runBatch(q, edgeParams(chunk, keyed)); err != nil { + w.edgeBuf[gk] = g + } + return nil +} + +// flushEdges runs every buffered edge group in key order and clears the buffer. +func (w *boltWriter) flushEdges() error { + for _, gk := range sortedEdgeKeys(w.edgeBuf) { + if g := w.edgeBuf[gk]; len(g) > 0 { + if err := w.runEdges(g); err != nil { return err } } } + clear(w.edgeBuf) return nil } +// runEdges upserts one chunk of an edge group (same type, endpoint labels and +// keyedness). +func (w *boltWriter) runEdges(g []EdgeRow) error { + e0 := g[0] + keyed := e0.Key != "" + var mergeClause string + if keyed { + mergeClause = fmt.Sprintf("MERGE (a)-[r:%s {_k: row.k, %s: row.f}]->(b)", e0.Type, RelationshipFactProperty) + } else { + mergeClause = fmt.Sprintf("MERGE (a)-[r:%s {%s: row.f}]->(b)", e0.Type, RelationshipFactProperty) + } + q := fmt.Sprintf("UNWIND $rows AS row MATCH (a:%s {%s: row.a}) MATCH (b:%s {%s: row.b}) %s SET r += row.p", + e0.From.Label, e0.From.KeyProp, e0.To.Label, e0.To.KeyProp, mergeClause) + return w.runBatch(q, edgeParams(g, keyed)) +} + // runBatch runs one UNWIND statement over rows in its own write transaction. func (w *boltWriter) runBatch(q string, rows []map[string]any) error { params := map[string]any{"rows": rows} diff --git a/internal/neo4j/bolt_session_test.go b/internal/neo4j/bolt_session_test.go index 5fcc2df..7bcabc1 100644 --- a/internal/neo4j/bolt_session_test.go +++ b/internal/neo4j/bolt_session_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/neo4j/neo4j-go-driver/v5/neo4j" ) @@ -208,6 +209,29 @@ func (s *fakeDB) pushed() (nodes map[string]bool, edges map[string]int) { return nodes, edges } +// pushRows replays rows through a fresh writer on db. +func pushRows(t *testing.T, db *fakeDB, rows GraphRows, appID string, cfg BoltConfig) { + t.Helper() + if _, _, err := replayRows(rows, newBoltWriter(context.Background(), db, appID, cfg)); err != nil { + t.Fatal(err) + } +} + +// pushPaths runs body once with a replay of Project(a) and once, in a +// "stream" subtest, with a streamGraph push of a's tree. +func pushPaths(t *testing.T, a *v2.Analysis, body func(t *testing.T, push func(*fakeDB, BoltConfig))) { + rows := Project(a) + body(t, func(db *fakeDB, cfg BoltConfig) { pushRows(t, db, rows, a.Application.ID, cfg) }) + t.Run("stream", func(t *testing.T) { + body(t, func(db *fakeDB, cfg BoltConfig) { + t.Helper() + if _, _, err := streamGraph(treeSource(a), newBoltWriter(context.Background(), db, a.Application.ID, cfg)); err != nil { + t.Fatal(err) + } + }) + }) +} + // TestBolt_LazyPushUpsertsL4RowsOfUnchangedModules (D5): on a lazy push // where every module's content_hash matches the DB, the L1–L3 nodes of the // (unchanged) modules are skipped, but every L4 row is upserted — each param @@ -225,74 +249,70 @@ func TestBolt_LazyPushUpsertsL4RowsOfUnchangedModules(t *testing.T) { t.Fatalf("module %s has no content_hash", m) } } - db := &fakeDB{hashes: hashes} - w := &boltWriter{ctx: context.Background(), session: db, rows: rows, appID: a.Application.ID} - if err := w.run(); err != nil { - t.Fatal(err) - } - nodes, edges := db.pushed() + pushPaths(t, a, func(t *testing.T, push func(*fakeDB, BoltConfig)) { + db := &fakeDB{hashes: hashes} + push(db, BoltConfig{}) + nodes, edges := db.pushed() - var vertices, l3Skipped int - for _, n := range rows.Nodes { - if n.Labels[0] != LabelBodyNode { - continue - } - kind, _ := n.Props["kind"].(string) - switch { - case isVertex(kind): - vertices++ - if !nodes[n.Value] { - t.Errorf("L4 vertex %s of an unchanged module not upserted", n.Value) + var vertices, l3Skipped int + for _, n := range rows.Nodes { + if n.Labels[0] != LabelBodyNode { + continue } - case n.Module != "": - if nodes[n.Value] { - t.Errorf("L3 body node %s of an unchanged module upserted on a lazy push", n.Value) + kind, _ := n.Props["kind"].(string) + switch { + case isVertex(kind): + vertices++ + if !nodes[n.Value] { + t.Errorf("L4 vertex %s of an unchanged module not upserted", n.Value) + } + case n.Module != "": + if nodes[n.Value] { + t.Errorf("L3 body node %s of an unchanged module upserted on a lazy push", n.Value) + } + l3Skipped++ } - l3Skipped++ } - } - if vertices == 0 || l3Skipped == 0 { - t.Fatalf("fixture: %d vertices, %d L3 body nodes", vertices, l3Skipped) - } - standIns := 0 - for _, ext := range a.Application.ExternalSymbols { - for _, n := range ext.Body { - standIns++ - if !nodes[n.ID] { - t.Errorf("stand-in vertex %s not upserted", n.ID) + if vertices == 0 || l3Skipped == 0 { + t.Fatalf("fixture: %d vertices, %d L3 body nodes", vertices, l3Skipped) + } + standIns := 0 + for _, ext := range a.Application.ExternalSymbols { + for _, n := range ext.Body { + standIns++ + if !nodes[n.ID] { + t.Errorf("stand-in vertex %s not upserted", n.ID) + } } } - } - if standIns == 0 { - t.Fatal("fixture has no stand-in body") - } - portRows := 0 - for _, e := range rows.Edges { - if p, _ := e.Props["prov"].([]string); e.Type == RelDDG && strings.Join(p, ",") != "ssa" { - portRows++ + if standIns == 0 { + t.Fatal("fixture has no stand-in body") } - } - for _, rel := range []string{RelParamIn, RelParamOut, RelSummary, RelDDG} { - if want := countEdges(rows, rel); want == 0 || edges[rel] != want { - t.Errorf("%s: pushed %d rows, projected %d", rel, edges[rel], want) + portRows := 0 + for _, e := range rows.Edges { + if p, _ := e.Props["prov"].([]string); e.Type == RelDDG && strings.Join(p, ",") != "ssa" { + portRows++ + } + } + for _, rel := range []string{RelParamIn, RelParamOut, RelSummary, RelDDG} { + if want := countEdges(rows, rel); want == 0 || edges[rel] != want { + t.Errorf("%s: pushed %d rows, projected %d", rel, edges[rel], want) + } + } + if portRows == 0 { + t.Error("fixture has no port GO_DDG row") } - } - if portRows == 0 { - t.Error("fixture has no port GO_DDG row") - } - // Eager: every node of every module is upserted. - db = &fakeDB{hashes: hashes} - w = &boltWriter{ctx: context.Background(), session: db, rows: rows, appID: a.Application.ID, cfg: BoltConfig{Eager: true, FullRun: true}} - if err := w.run(); err != nil { - t.Fatal(err) - } - nodes, _ = db.pushed() - for _, n := range rows.Nodes { - if !nodes[n.Value] { - t.Fatalf("eager push skipped %s", n.Value) + // Eager: every node of every module is upserted. + db = &fakeDB{hashes: hashes} + push(db, BoltConfig{Eager: true, FullRun: true}) + nodes, _ = db.pushed() + for _, n := range rows.Nodes { + if !nodes[n.Value] { + t.Fatalf("eager push skipped %s", n.Value) + } } - } + }) } // TestBolt_LazyPushForcesFullOnLowerStoredLevel: a graph first pushed at a @@ -312,42 +332,41 @@ func TestBolt_LazyPushForcesFullOnLowerStoredLevel(t *testing.T) { for m, ns := range byModule { hashes[m] = moduleHash(ns) } - push := func(stored int64) map[string]bool { - db := &fakeDB{hashes: hashes, level: stored} - w := &boltWriter{ctx: context.Background(), session: db, rows: rows, appID: a.Application.ID} - if err := w.run(); err != nil { - t.Fatal(err) + pushPaths(t, a, func(t *testing.T, pushWith func(*fakeDB, BoltConfig)) { + push := func(stored int64) map[string]bool { + db := &fakeDB{hashes: hashes, level: stored} + pushWith(db, BoltConfig{}) + nodes, _ := db.pushed() + return nodes } - nodes, _ := db.pushed() - return nodes - } - moduleNodes := 0 - for _, ns := range byModule { - moduleNodes += len(ns) - } - if moduleNodes == 0 { - t.Fatal("fixture has no module-owned nodes") - } - for _, stored := range []int64{1, 3} { - nodes := push(stored) - for m, ns := range byModule { - for _, n := range ns { - if !nodes[n.Value] { - t.Fatalf("stored level %d: module %s node %s not upserted", stored, m, n.Value) + moduleNodes := 0 + for _, ns := range byModule { + moduleNodes += len(ns) + } + if moduleNodes == 0 { + t.Fatal("fixture has no module-owned nodes") + } + for _, stored := range []int64{1, 3} { + nodes := push(stored) + for m, ns := range byModule { + for _, n := range ns { + if !nodes[n.Value] { + t.Fatalf("stored level %d: module %s node %s not upserted", stored, m, n.Value) + } } } } - } - for _, stored := range []int64{4, 5} { - nodes := push(stored) - for _, ns := range byModule { - for _, n := range ns { - if nodes[n.Value] { - t.Fatalf("stored level %d: unchanged module node %s upserted", stored, n.Value) + for _, stored := range []int64{4, 5} { + nodes := push(stored) + for _, ns := range byModule { + for _, n := range ns { + if nodes[n.Value] { + t.Fatalf("stored level %d: unchanged module node %s upserted", stored, n.Value) + } } } } - } + }) } // TestBolt_LazyPushForcesFullOnUnreadableStoredLevel: a stored max_level @@ -362,21 +381,20 @@ func TestBolt_LazyPushForcesFullOnUnreadableStoredLevel(t *testing.T) { for m, ns := range byModule { hashes[m] = moduleHash(ns) } - for _, raw := range []any{float64(4), "4", true} { - db := &fakeDB{hashes: hashes, rawLevel: raw} - w := &boltWriter{ctx: context.Background(), session: db, rows: rows, appID: a.Application.ID} - if err := w.run(); err != nil { - t.Fatal(err) - } - nodes, _ := db.pushed() - for m, ns := range byModule { - for _, n := range ns { - if !nodes[n.Value] { - t.Fatalf("stored max_level %T(%v): module %s node %s not upserted", raw, raw, m, n.Value) + pushPaths(t, a, func(t *testing.T, push func(*fakeDB, BoltConfig)) { + for _, raw := range []any{float64(4), "4", true} { + db := &fakeDB{hashes: hashes, rawLevel: raw} + push(db, BoltConfig{}) + nodes, _ := db.pushed() + for m, ns := range byModule { + for _, n := range ns { + if !nodes[n.Value] { + t.Fatalf("stored max_level %T(%v): module %s node %s not upserted", raw, raw, m, n.Value) + } } } } - } + }) } // TestBolt_CleanPushClearsDegradedJSON (F6): the projector prunes a nil @@ -391,13 +409,8 @@ func TestBolt_CleanPushClearsDegradedJSON(t *testing.T) { if len(a.Degraded) != 0 { t.Fatalf("fixture degraded: %+v", a.Degraded) } - appProps := func(rows GraphRows) map[string]any { + appPropsOf := func(t *testing.T, db *fakeDB) map[string]any { t.Helper() - db := &fakeDB{level: 4} - w := &boltWriter{ctx: context.Background(), session: db, rows: rows, appID: a.Application.ID} - if err := w.run(); err != nil { - t.Fatal(err) - } for _, st := range db.writes { if !strings.Contains(st.q, "MERGE (n:"+LabelApplication+" ") { continue @@ -411,10 +424,26 @@ func TestBolt_CleanPushClearsDegradedJSON(t *testing.T) { t.Fatal("no :GoApplication upsert") return nil } - p := appProps(Project(a)) - if v, has := p["degraded_json"]; !has || v != nil { - t.Errorf("clean push: degraded_json = %v (present %v), want an explicit null", v, has) + appProps := func(rows GraphRows) map[string]any { + t.Helper() + db := &fakeDB{level: 4} + pushRows(t, db, rows, a.Application.ID, BoltConfig{}) + return appPropsOf(t, db) } + clean := func(t *testing.T, p map[string]any) { + t.Helper() + if v, has := p["degraded_json"]; !has || v != nil { + t.Errorf("clean push: degraded_json = %v (present %v), want an explicit null", v, has) + } + } + clean(t, appProps(Project(a))) + t.Run("stream", func(t *testing.T) { + db := &fakeDB{level: 4} + if _, _, err := streamGraph(treeSource(a), newBoltWriter(context.Background(), db, a.Application.ID, BoltConfig{})); err != nil { + t.Fatal(err) + } + clean(t, appPropsOf(t, db)) + }) rows := Project(a) for i, n := range rows.Nodes { if n.Labels[0] == LabelApplication { @@ -429,8 +458,8 @@ func TestBolt_CleanPushClearsDegradedJSON(t *testing.T) { func TestIncompatibleIdentityReadOnly(t *testing.T) { for _, iv := range []any{int64(1), "2", float64(2), true} { db := &fakeDB{rawIdentity: iv} - w := &boltWriter{ctx: context.Background(), session: db, appID: "can://team/app"} - if err := w.run(); err == nil { + w := newBoltWriter(context.Background(), db, "can://team/app", BoltConfig{}) + if err := w.begin(NodeRow{}); err == nil { t.Errorf("accepted %v", iv) } if len(db.writes) != 0 { @@ -441,8 +470,8 @@ func TestIncompatibleIdentityReadOnly(t *testing.T) { func TestMissingStoredIdentityReadOnly(t *testing.T) { db := &fakeDB{missingIdentity: true} - w := &boltWriter{ctx: context.Background(), session: db, appID: "can://team/app"} - if err := w.run(); err == nil { + w := newBoltWriter(context.Background(), db, "can://team/app", BoltConfig{}) + if err := w.begin(NodeRow{}); err == nil { t.Fatal("accepted legacy anchor") } if len(db.writes) != 0 { @@ -516,8 +545,8 @@ func TestWritersPreserveDistinctEdgeFacts(t *testing.T) { func TestStoredOwnerMismatchReadOnly(t *testing.T) { for _, db := range []*fakeDB{{missingName: true}, {missingNamespace: true}, {rawName: "other"}, {rawNamespace: "other"}, {rawName: 42}, {rawNamespace: 42}} { - w := &boltWriter{ctx: context.Background(), session: db, appID: "can://team/app"} - if err := w.run(); err == nil { + w := newBoltWriter(context.Background(), db, "can://team/app", BoltConfig{}) + if err := w.begin(NodeRow{}); err == nil { t.Fatal("accepted contradictory stored owner") } if len(db.writes) != 0 { @@ -528,7 +557,7 @@ func TestStoredOwnerMismatchReadOnly(t *testing.T) { func TestStoredOwnerAllowsFreshAndMatchingAnchor(t *testing.T) { for _, db := range []*fakeDB{{missingAnchor: true}, {}} { - w := &boltWriter{ctx: context.Background(), session: db, appID: "can://team/app"} + w := newBoltWriter(context.Background(), db, "can://team/app", BoltConfig{}) if _, err := w.storedAppStale(); err != nil { t.Fatal(err) } @@ -573,3 +602,45 @@ func TestBolt_UpsertsAreBatched(t *testing.T) { t.Errorf("pushed %d nodes, %d edges; want %d of each", len(gotNodes), gotEdges[RelCalls], n) } } + +// TestBolt_StreamPushOrder (spec §6): no edge statement runs before the last node statement, +// and an eager push purges each module before it writes that module's nodes. +func TestBolt_StreamPushOrder(t *testing.T) { + a := buildDataflowL4(t) + db := &fakeDB{} + w := newBoltWriter(context.Background(), db, a.Application.ID, BoltConfig{Eager: true, FullRun: true}) + if _, _, err := streamGraph(treeSource(a), w); err != nil { + t.Fatal(err) + } + lastNode, firstEdge := -1, len(db.writes) + purgedAt := map[string]int{} // module id -> statement index of its purge + firstWrite := map[string]int{} // node id -> statement index of its first MERGE + for i, st := range db.writes { + switch { + case strings.Contains(st.q, "MERGE (n:"): + lastNode = i + for _, r := range st.params["rows"].([]map[string]any) { + if _, seen := firstWrite[r["k"].(string)]; !seen { + firstWrite[r["k"].(string)] = i + } + } + case strings.Contains(st.q, "MERGE (a)-[r:"): + firstEdge = min(firstEdge, i) + case strings.Contains(st.q, "DETACH DELETE n") && st.params["m"] != nil: + purgedAt[st.params["m"].(string)] = i + } + } + if lastNode > firstEdge { + t.Errorf("node statement %d runs after edge statement %d", lastNode, firstEdge) + } + if len(purgedAt) != len(a.Application.SymbolTable) { + t.Errorf("%d module purges, want %d", len(purgedAt), len(a.Application.SymbolTable)) + } + for id, at := range firstWrite { + for m, p := range purgedAt { + if (id == m || strings.HasPrefix(id, m+"/")) && at < p { + t.Errorf("node %s written at %d, before the purge of %s at %d", id, at, m, p) + } + } + } +} From 48e4de23b5a183db80ed2a202b1c9c85934c63ef Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Tue, 24 Nov 2026 20:39:52 -0500 Subject: [PATCH 09/16] feat(neo4j): stream graph.cypher and drive the CLI push from v2emit.Open (#59) Co-Authored-By: Claude Opus 5.5 --- cmd/codeanalyzer/main.go | 9 +- internal/neo4j/cypher.go | 266 +++++++++++++++++++++++++++------- internal/neo4j/cypher_test.go | 80 +++++++++- internal/neo4j/emit.go | 38 ++--- 4 files changed, 310 insertions(+), 83 deletions(-) diff --git a/cmd/codeanalyzer/main.go b/cmd/codeanalyzer/main.go index 3cceee3..6c2103c 100644 --- a/cmd/codeanalyzer/main.go +++ b/cmd/codeanalyzer/main.go @@ -191,11 +191,12 @@ via CLDK(language="go").analysis(project_path=...).`, return err } - // Neo4j projection: build the canonical v2 payload (the SAME tree the - // JSON path emits) and project it. --neo4j-uri set → live Bolt push; + // Neo4j projection: stream the canonical v2 payload (the SAME modules + // the JSON path emits) one module at a time into the projection, so + // the full tree is never held (#59). --neo4j-uri set → live Bolt push; // absent → a graph.cypher snapshot in the output dir. if emitTarget == options.EmitNeo4j { - payload := v2emit.Emit(app, identity, opts.InputPath, int(opts.Level), opts.AnalyzerVersion, core.KLimit(opts), analyzer.L3(), analyzer.L4()) + src := v2emit.Open(app, identity, opts.InputPath, int(opts.Level), opts.AnalyzerVersion, core.KLimit(opts), analyzer.L3(), analyzer.L4()) boltCfg := neo4j.BoltConfig{ URI: opts.Neo4jURI, User: opts.Neo4jUser, @@ -204,7 +205,7 @@ via CLDK(language="go").analysis(project_path=...).`, Eager: opts.Eager, FullRun: len(opts.TargetFiles) == 0, } - msg, err := neo4j.EmitNeo4j(cmd.Context(), payload, outputDir, boltCfg) + msg, err := neo4j.EmitNeo4j(cmd.Context(), src, outputDir, boltCfg) if err != nil { return err } diff --git a/internal/neo4j/cypher.go b/internal/neo4j/cypher.go index 3b883b3..d2b8966 100644 --- a/internal/neo4j/cypher.go +++ b/internal/neo4j/cypher.go @@ -1,10 +1,15 @@ package neo4j import ( + "bufio" "fmt" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "io" + "os" + "path/filepath" "sort" "strings" + + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" ) // Milestone M4: the snapshot writer. RenderCypher turns a GraphRows bag into a @@ -28,6 +33,13 @@ import ( // batchSize is the UNWIND batch size (parity with the siblings' 500). const batchSize = 500 +// scriptWriter is the part of strings.Builder and bufio.Writer that the renderer uses. +type scriptWriter interface { + io.Writer + io.StringWriter + io.ByteWriter +} + // RenderCypher renders the full snapshot script. appID is the application root // id used to scope the wipe; it is normally rows' application node value. func validateIdentity(rows GraphRows, appID string) error { @@ -80,7 +92,7 @@ func renderCypher(rows GraphRows, appID string) string { return b.String() } -func writeDDL(b *strings.Builder) { +func writeDDL(b scriptWriter) { b.WriteString("// ─── constraints & indexes ───\n") for _, c := range UniquenessConstraints() { fmt.Fprintf(b, "CREATE CONSTRAINT %s IF NOT EXISTS FOR (n:%s) REQUIRE n.%s IS UNIQUE;\n", @@ -98,7 +110,7 @@ func writeDDL(b *strings.Builder) { // blast radius is exactly one application — never the whole store, never a // sibling analyzer's :Go* graph (they lack :GoCanNode), never a second Go app // sharing a module path. -func writeScopedWipe(b *strings.Builder, appID string) { +func writeScopedWipe(b scriptWriter, appID string) { root, ok := applicationPrefix(appID) if !ok { b.WriteString("// ─── scoped wipe SKIPPED: no bare application root id ───\n\n") @@ -117,11 +129,11 @@ func writeScopedWipe(b *strings.Builder, appID string) { // ─── node batches ───────────────────────────────────────────────────────────── -func writeNodeBatches(b *strings.Builder, nodes []NodeRow) { +func writeNodeBatches(b scriptWriter, nodes []NodeRow) { if len(nodes) == 0 { return } - b.WriteString("// ─── nodes ───\n") + b.WriteString(nodesHeader) // Group by (full label set + key prop) so one UNWIND handles a homogeneous // batch. Keys sorted for deterministic output. groups := map[string][]NodeRow{} @@ -129,77 +141,219 @@ func writeNodeBatches(b *strings.Builder, nodes []NodeRow) { groups[nodeGroupKey(n)] = append(groups[nodeGroupKey(n)], n) } for _, gk := range sortedKeys(groups) { - g := groups[gk] - mergeLabel := g[0].Labels[0] - keyProp := g[0].KeyProp - extraLabels := g[0].Labels[1:] - - for _, chunk := range chunkNodes(g, batchSize) { - b.WriteString("UNWIND [\n") - for i, n := range chunk { - sep := "," - if i == len(chunk)-1 { - sep = "" - } - fmt.Fprintf(b, " {k: %s, p: %s}%s\n", cypherString(n.Value), cypherMap(n.Props), sep) - } - b.WriteString("] AS row\n") - fmt.Fprintf(b, "MERGE (n:%s {%s: row.k})\n", mergeLabel, keyProp) - b.WriteString("SET n += row.p") - for _, l := range extraLabels { - fmt.Fprintf(b, "\nSET n:%s", l) - } - b.WriteString(";\n") + for _, chunk := range chunkNodes(groups[gk], batchSize) { + writeNodeChunk(b, chunk) } } b.WriteByte('\n') } +const ( + nodesHeader = "// ─── nodes ───\n" + edgesHeader = "// ─── relationships ───\n" +) + +// writeNodeChunk writes one UNWIND … MERGE statement for a non-empty chunk of +// one node group (same labels and key property). +func writeNodeChunk(b scriptWriter, chunk []NodeRow) { + mergeLabel := chunk[0].Labels[0] + keyProp := chunk[0].KeyProp + extraLabels := chunk[0].Labels[1:] + b.WriteString("UNWIND [\n") + for i, n := range chunk { + sep := "," + if i == len(chunk)-1 { + sep = "" + } + fmt.Fprintf(b, " {k: %s, p: %s}%s\n", cypherString(n.Value), cypherMap(n.Props), sep) + } + b.WriteString("] AS row\n") + fmt.Fprintf(b, "MERGE (n:%s {%s: row.k})\n", mergeLabel, keyProp) + b.WriteString("SET n += row.p") + for _, l := range extraLabels { + fmt.Fprintf(b, "\nSET n:%s", l) + } + b.WriteString(";\n") +} + // ─── edge batches ───────────────────────────────────────────────────────────── -func writeEdgeBatches(b *strings.Builder, edges []EdgeRow) { +func writeEdgeBatches(b scriptWriter, edges []EdgeRow) { if len(edges) == 0 { return } - b.WriteString("// ─── relationships ───\n") + b.WriteString(edgesHeader) groups := map[string][]EdgeRow{} for _, e := range edges { groups[edgeGroupKey(e)] = append(groups[edgeGroupKey(e)], e) } for _, gk := range sortedEdgeKeys(groups) { - g := groups[gk] - e0 := g[0] - keyed := e0.Key != "" - - for _, chunk := range chunkEdges(g, batchSize) { - b.WriteString("UNWIND [\n") - for i, e := range chunk { - sep := "," - if i == len(chunk)-1 { - sep = "" - } - if keyed { - fmt.Fprintf(b, " {a: %s, b: %s, k: %s, f: %s, p: %s}%s\n", - cypherString(e.From.Value), cypherString(e.To.Value), cypherString(e.Key), cypherString(edgeFactID(e)), cypherMap(e.Props), sep) - } else { - fmt.Fprintf(b, " {a: %s, b: %s, f: %s, p: %s}%s\n", - cypherString(e.From.Value), cypherString(e.To.Value), cypherString(edgeFactID(e)), cypherMap(e.Props), sep) - } - } - b.WriteString("] AS row\n") - fmt.Fprintf(b, "MATCH (a:%s {%s: row.a})\n", e0.From.Label, e0.From.KeyProp) - fmt.Fprintf(b, "MATCH (b:%s {%s: row.b})\n", e0.To.Label, e0.To.KeyProp) - if keyed { - fmt.Fprintf(b, "MERGE (a)-[r:%s {_k: row.k, %s: row.f}]->(b)\n", e0.Type, RelationshipFactProperty) - } else { - fmt.Fprintf(b, "MERGE (a)-[r:%s {%s: row.f}]->(b)\n", e0.Type, RelationshipFactProperty) - } - b.WriteString("SET r += row.p;\n") + for _, chunk := range chunkEdges(groups[gk], batchSize) { + writeEdgeChunk(b, chunk) } } b.WriteByte('\n') } +// writeEdgeChunk writes one UNWIND … MERGE statement for a non-empty chunk of +// one edge group (same type, endpoint labels and keys, keyed or not). +func writeEdgeChunk(b scriptWriter, chunk []EdgeRow) { + e0 := chunk[0] + keyed := e0.Key != "" + b.WriteString("UNWIND [\n") + for i, e := range chunk { + sep := "," + if i == len(chunk)-1 { + sep = "" + } + if keyed { + fmt.Fprintf(b, " {a: %s, b: %s, k: %s, f: %s, p: %s}%s\n", + cypherString(e.From.Value), cypherString(e.To.Value), cypherString(e.Key), cypherString(edgeFactID(e)), cypherMap(e.Props), sep) + } else { + fmt.Fprintf(b, " {a: %s, b: %s, f: %s, p: %s}%s\n", + cypherString(e.From.Value), cypherString(e.To.Value), cypherString(edgeFactID(e)), cypherMap(e.Props), sep) + } + } + b.WriteString("] AS row\n") + fmt.Fprintf(b, "MATCH (a:%s {%s: row.a})\n", e0.From.Label, e0.From.KeyProp) + fmt.Fprintf(b, "MATCH (b:%s {%s: row.b})\n", e0.To.Label, e0.To.KeyProp) + if keyed { + fmt.Fprintf(b, "MERGE (a)-[r:%s {_k: row.k, %s: row.f}]->(b)\n", e0.Type, RelationshipFactProperty) + } else { + fmt.Fprintf(b, "MERGE (a)-[r:%s {%s: row.f}]->(b)\n", e0.Type, RelationshipFactProperty) + } + b.WriteString("SET r += row.p;\n") +} + +// ─── streamed snapshot (#59, spec §5.4) ─────────────────────────────────────── + +// cypherWriter is the snapshot stager. It writes the same statements as +// renderCypher, with the node and edge groups flushed per batchSize chunk as +// the stream goes, so it never holds more than one chunk per group. Every node +// statement precedes every edge statement: late flushes all node groups. +type cypherWriter struct { + w *bufio.Writer + appID string + nodeBuf map[string][]NodeRow + edgeBuf map[string][]EdgeRow + inEdges bool // the relationships header is written +} + +func newCypherWriter(w *bufio.Writer, appID string) *cypherWriter { + return &cypherWriter{w: w, appID: appID, nodeBuf: map[string][]NodeRow{}, edgeBuf: map[string][]EdgeRow{}} +} + +// begin writes the DDL, the scoped wipe and the nodes header. The node +// section is never empty (late always holds the application row), so the +// header is unconditional; the row begin gets is written by late. +func (c *cypherWriter) begin(NodeRow) error { + writeDDL(c.w) + writeScopedWipe(c.w, c.appID) + c.w.WriteString(nodesHeader) + return nil +} + +func (c *cypherWriter) shared(nodes []NodeRow) error { c.bufferNodes(nodes); return nil } +func (c *cypherWriter) module(_ string, nodes []NodeRow) error { c.bufferNodes(nodes); return nil } + +// late buffers the last node rows and flushes every node group in key order. +func (c *cypherWriter) late(nodes []NodeRow) error { + c.bufferNodes(nodes) + for _, gk := range sortedKeys(c.nodeBuf) { + if g := c.nodeBuf[gk]; len(g) > 0 { + writeNodeChunk(c.w, g) + } + } + clear(c.nodeBuf) + return nil +} + +// edges closes the node section and writes the relationships header on its +// first non-empty call, then buffers per edge group. +func (c *cypherWriter) edges(edges []EdgeRow) error { + if len(edges) == 0 { + return nil + } + if !c.inEdges { + c.w.WriteByte('\n') + c.w.WriteString(edgesHeader) + c.inEdges = true + } + for _, e := range edges { + gk := edgeGroupKey(e) + g := append(c.edgeBuf[gk], e) + if len(g) == batchSize { + writeEdgeChunk(c.w, g) + g = g[:0] + } + c.edgeBuf[gk] = g + } + return nil +} + +// end flushes the edge groups in key order and closes the last section. +func (c *cypherWriter) end([]string) error { + for _, gk := range sortedEdgeKeys(c.edgeBuf) { + if g := c.edgeBuf[gk]; len(g) > 0 { + writeEdgeChunk(c.w, g) + } + } + clear(c.edgeBuf) + c.w.WriteByte('\n') + return nil +} + +func (c *cypherWriter) bufferNodes(nodes []NodeRow) { + for _, n := range nodes { + gk := nodeGroupKey(n) + g := append(c.nodeBuf[gk], n) + if len(g) == batchSize { + writeNodeChunk(c.w, g) + g = g[:0] + } + c.nodeBuf[gk] = g + } +} + +// WriteCypher streams src into path. It writes a temporary file and renames it at the end, +// so a failed run leaves an earlier graph.cypher unchanged. +func WriteCypher(src Source, path string) (nodes, edges int, err error) { + env := src.Envelope() + if env == nil || env.IdentityVersion != 2 || env.Application.IdentityVersion != 2 { + return 0, 0, fmt.Errorf("incompatible identity_version") + } + appID := env.Application.ID + if err := validateIdentity(GraphRows{Nodes: []NodeRow{appRow(env)}}, appID); err != nil { + return 0, 0, err + } + f, err := os.CreateTemp(filepath.Dir(path), ".graph-*.cypher") + if err != nil { + return 0, 0, fmt.Errorf("write %s: %w", path, err) + } + tmp := f.Name() + defer func() { + if err != nil { + _ = f.Close() + _ = os.Remove(tmp) + } + }() + w := bufio.NewWriterSize(f, 1<<20) + if nodes, edges, err = streamGraph(src, newCypherWriter(w, appID)); err != nil { + return 0, 0, fmt.Errorf("write %s: %w", path, err) + } + if err = w.Flush(); err == nil { + if err = f.Chmod(0o644); err == nil { + if err = f.Close(); err == nil { + err = os.Rename(tmp, path) + } + } + } + if err != nil { + return 0, 0, fmt.Errorf("write %s: %w", path, err) + } + return nodes, edges, nil +} + // ─── grouping keys & chunking ───────────────────────────────────────────────── func nodeGroupKey(n NodeRow) string { diff --git a/internal/neo4j/cypher_test.go b/internal/neo4j/cypher_test.go index 8e829db..7a7a8cb 100644 --- a/internal/neo4j/cypher_test.go +++ b/internal/neo4j/cypher_test.go @@ -2,6 +2,7 @@ package neo4j import ( "context" + "maps" "os" "path/filepath" "strings" @@ -123,7 +124,7 @@ func TestEmitNeo4jInvalidIdentityLeavesOutput(t *testing.T) { if err := os.WriteFile(path, []byte("original"), 0600); err != nil { t.Fatal(err) } - if _, err := EmitNeo4j(context.Background(), a, dir, BoltConfig{}); err == nil { + if _, err := EmitNeo4j(context.Background(), TreeSource(a), dir, BoltConfig{}); err == nil { t.Fatal("accepted mismatched app marker") } b, err := os.ReadFile(path) @@ -131,3 +132,80 @@ func TestEmitNeo4jInvalidIdentityLeavesOutput(t *testing.T) { t.Fatalf("output changed: %s %v", b, err) } } + +// TestCypher_StreamedScriptHasTheSameRows (S1): the streamed script holds the same row lines as +// RenderCypher(Project(a)), with the same header, and every node line comes before every edge line. +// A hand-built fixture with no identity metadata is refused by both. +func TestCypher_StreamedScriptHasTheSameRows(t *testing.T) { + for name, a := range parityFixtures(t) { + path := filepath.Join(t.TempDir(), GraphFileName) + want, err := RenderCypher(Project(a), a.Application.ID) + if err != nil { + if _, _, werr := WriteCypher(treeSource(a), path); werr == nil { + t.Errorf("%s: RenderCypher refuses (%v), WriteCypher accepts", name, err) + } + continue + } + if _, _, err := WriteCypher(treeSource(a), path); err != nil { + t.Fatalf("%s: %v", name, err) + } + b, _ := os.ReadFile(path) + got := string(b) + head := want[:strings.Index(want, "UNWIND")] + if !strings.HasPrefix(got, head) { + t.Errorf("%s: header differs", name) + } + if w, g := rowLines(want), rowLines(got); !maps.Equal(w, g) { + t.Errorf("%s: %d row lines, want %d", name, len(g), len(w)) + } + if strings.LastIndex(got, "MERGE (n:") > strings.Index(got, "MERGE (a)-[r:") { + t.Errorf("%s: a node statement follows an edge statement", name) + } + } +} + +// rowLines is the set of UNWIND row lines, the lines that start with " {". +func rowLines(script string) map[string]bool { + out := map[string]bool{} + for _, l := range strings.Split(script, "\n") { + if strings.HasPrefix(l, " {") { + out[strings.TrimSuffix(l, ",")] = true + } + } + return out +} + +// TestWriteCypher_FailureLeavesOutput: a run that fails, before the temporary +// file (identity) or after it (rename onto a directory), leaves an earlier +// graph.cypher as it was and no temporary file behind. +func TestWriteCypher_FailureLeavesOutput(t *testing.T) { + a := buildMultipackageL2(t) + bad := *a + bad.Application.IdentityVersion = 1 + dir := t.TempDir() + path := filepath.Join(dir, GraphFileName) + if err := os.WriteFile(path, []byte("original"), 0o600); err != nil { + t.Fatal(err) + } + if _, _, err := WriteCypher(TreeSource(&bad), path); err == nil { + t.Fatal("accepted mismatched app marker") + } + if b, err := os.ReadFile(path); err != nil || string(b) != "original" { + t.Fatalf("output changed: %s %v", b, err) + } + // The rename fails: the target is a non-empty directory. + target := filepath.Join(dir, "occupied") + if err := os.MkdirAll(filepath.Join(target, "x"), 0o755); err != nil { + t.Fatal(err) + } + _, _, err := WriteCypher(TreeSource(a), target) + if err == nil || !strings.Contains(err.Error(), target) { + t.Fatalf("err = %v, want a write error naming %s", err, target) + } + entries, _ := os.ReadDir(dir) + for _, e := range entries { + if strings.HasPrefix(e.Name(), ".graph-") { + t.Errorf("temporary file %s left behind", e.Name()) + } + } +} diff --git a/internal/neo4j/emit.go b/internal/neo4j/emit.go index c627b41..9d79da4 100644 --- a/internal/neo4j/emit.go +++ b/internal/neo4j/emit.go @@ -6,40 +6,34 @@ import ( "fmt" "os" "path/filepath" - - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" ) // Facade between the CLI and the Neo4j backend: EmitSchema (static contract, -// needs no project) and EmitNeo4j (project the v2 tree, then write — graph.cypher -// snapshot when no URI, live Bolt push when a URI is set). +// needs no project) and EmitNeo4j (stream the v2 payload into a graph.cypher +// snapshot when no URI is set, or into a live Bolt push when one is). // GraphFileName is the snapshot script written when no --neo4j-uri is given. const GraphFileName = "graph.cypher" -// EmitNeo4j projects the v2 Analysis into GraphRows and writes it. The projection -// is pure and shared; only the write target differs. When cfg.URI is set it -// pushes over Bolt (incremental, additive unless cfg.Eager); otherwise it writes -// a self-contained graph.cypher snapshot into outputDir (default: current dir). -// It returns a short human-readable description of what was written. -func EmitNeo4j(ctx context.Context, a *v2.Analysis, outputDir string, cfg BoltConfig) (string, error) { - if a == nil || a.IdentityVersion != 2 || a.Application.IdentityVersion != 2 { +// EmitNeo4j streams src, one module at a time, into the write target. When +// cfg.URI is set it pushes over Bolt (incremental, additive unless cfg.Eager); +// otherwise it writes a self-contained graph.cypher snapshot into outputDir +// (default: current dir). Neither target holds the whole tree or every row +// (#59). It returns a short human-readable description of what was written. +// The counts are rows sent: a duplicate edge row across modules counts twice. +func EmitNeo4j(ctx context.Context, src Source, outputDir string, cfg BoltConfig) (string, error) { + env := src.Envelope() + if env == nil || env.IdentityVersion != 2 || env.Application.IdentityVersion != 2 { return "", fmt.Errorf("incompatible identity_version") } - rows := Project(a) - appID := a.Application.ID - if cfg.URI != "" { - if err := WriteBolt(ctx, rows, appID, cfg); err != nil { + nodes, edges, err := PushBolt(ctx, src, cfg) + if err != nil { return "", err } - return fmt.Sprintf("pushed %d nodes, %d relationships to %s", len(rows.Nodes), len(rows.Edges), cfg.URI), nil + return fmt.Sprintf("pushed %d nodes, %d relationships to %s", nodes, edges, cfg.URI), nil } - script, err := RenderCypher(rows, appID) - if err != nil { - return "", err - } if outputDir == "" { outputDir = "." } @@ -47,8 +41,8 @@ func EmitNeo4j(ctx context.Context, a *v2.Analysis, outputDir string, cfg BoltCo return "", fmt.Errorf("create output dir %q: %w", outputDir, err) } path := filepath.Join(outputDir, GraphFileName) - if err := os.WriteFile(path, []byte(script), 0o644); err != nil { - return "", fmt.Errorf("write %s: %w", path, err) + if _, _, err := WriteCypher(src, path); err != nil { + return "", err } return "wrote " + path, nil } From b28a311f7fbd4bf032376121032fff0be6a004f3 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Tue, 24 Nov 2026 20:46:02 -0500 Subject: [PATCH 10/16] test(memtest): memory-limit harness for the Neo4j push (#59) Co-Authored-By: Claude Opus 5.5 --- .dockerignore | 10 ++ go.mod | 52 ++++++++- go.sum | 129 +++++++++++++++++++++- internal/memtest/memtest_test.go | 184 +++++++++++++++++++++++++++++++ scripts/memtest/Dockerfile.cango | 15 +++ 5 files changed, 387 insertions(+), 3 deletions(-) create mode 100644 .dockerignore create mode 100644 internal/memtest/memtest_test.go create mode 100644 scripts/memtest/Dockerfile.cango diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..6b2c156 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +# Build context of scripts/memtest/Dockerfile.cango (the repository root). +# testcontainers-go tars the context itself and reads only this root file; +# it does not use BuildKit, so a per-Dockerfile ignore file would be ignored. +/cango +.git +.envrc +.claude +.superpowers +internal/zz_memprobe +**/*.test diff --git a/go.mod b/go.mod index dcc5ee5..e77b48d 100644 --- a/go.mod +++ b/go.mod @@ -3,14 +3,64 @@ module github.com/codellm-devkit/codeanalyzer-go go 1.26.0 require ( + github.com/moby/moby/api v1.56.1 github.com/neo4j/neo4j-go-driver/v5 v5.28.5 github.com/spf13/cobra v1.8.0 + github.com/testcontainers/testcontainers-go v0.45.0 + github.com/testcontainers/testcontainers-go/modules/neo4j v0.45.0 + golang.org/x/mod v0.42.0 golang.org/x/tools v0.52.0 ) require ( + dario.cat/mergo v1.0.2 // indirect + github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 // indirect + github.com/Microsoft/go-winio v0.6.2 // indirect + github.com/cenkalti/backoff/v4 v4.3.0 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/containerd/errdefs v1.0.0 // indirect + github.com/containerd/errdefs/pkg v0.3.0 // indirect + github.com/containerd/log v0.1.0 // indirect + github.com/containerd/platforms v0.2.1 // indirect + github.com/cpuguy83/dockercfg v0.3.2 // indirect + github.com/distribution/reference v0.6.0 // indirect + github.com/docker/go-connections v0.8.2 // indirect + github.com/docker/go-units v0.5.0 // indirect + github.com/ebitengine/purego v0.10.1 // indirect + github.com/felixge/httpsnoop v1.1.0 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-ole/go-ole v1.3.0 // indirect + github.com/google/uuid v1.6.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/klauspost/compress v1.18.7 // indirect + github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect + github.com/magiconair/properties v1.18.12 // indirect + github.com/moby/docker-image-spec v1.3.1 // indirect + github.com/moby/go-archive v0.3.3 // indirect + github.com/moby/moby/client v0.6.2 // indirect + github.com/moby/patternmatcher v0.6.1 // indirect + github.com/moby/sys/sequential v0.7.0 // indirect + github.com/moby/sys/user v0.4.1 // indirect + github.com/moby/sys/userns v0.1.0 // indirect + github.com/moby/term v0.5.2 // indirect + github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/opencontainers/image-spec v1.1.1 // indirect + github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect + github.com/shirou/gopsutil/v4 v4.26.6 // indirect + github.com/sirupsen/logrus v1.9.4 // indirect github.com/spf13/pflag v1.0.5 // indirect - golang.org/x/mod v0.42.0 // indirect + github.com/stretchr/testify v1.12.1 // indirect + github.com/tklauser/go-sysconf v0.4.0 // indirect + github.com/tklauser/numcpus v0.12.0 // indirect + github.com/yusufpapurcu/wmi v1.2.4 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect + go.opentelemetry.io/otel v1.44.0 // indirect + go.opentelemetry.io/otel/metric v1.44.0 // indirect + go.opentelemetry.io/otel/trace v1.44.0 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/crypto v0.58.0 // indirect golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.49.0 // indirect ) diff --git a/go.sum b/go.sum index 33b67a0..44edb93 100644 --- a/go.sum +++ b/go.sum @@ -1,20 +1,145 @@ +dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= +dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8= +github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 h1:m2xcjRABtG288vnlV3U/PKh/HnPURxZp50RKNUwBxM8= +github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4/go.mod h1:MTUE7ZuZO89FAtAwozGg6AWD83pcdefnEq5gF82MB8s= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= +github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= +github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= +github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= +github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= +github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= +github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= +github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= +github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= +github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw= +github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA= +github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc= github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= +github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/docker/go-connections v0.8.2 h1:9d9DEokx5W7qlr0shkFXIxEA7+TTD+llwzcykSlxMNc= +github.com/docker/go-connections v0.8.2/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= +github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= +github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= +github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw= +github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak= +github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= +github.com/magiconair/properties v1.18.12 h1:sT9zQpvTB3B4gzrX0tmZNTEaGyg8Zw55MFYRE32Mr9I= +github.com/magiconair/properties v1.18.12/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= +github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= +github.com/moby/go-archive v0.3.3 h1:OxxR9paxsluYi+zDUEXTTaIxtkK3viymW+Ka7vRhhME= +github.com/moby/go-archive v0.3.3/go.mod h1:Npdv43fFqlhZW7Xo8fbm3ZMYFvAGNviUPqX21VERbcE= +github.com/moby/moby/api v1.56.1 h1:PpWkvVPB7Fr/No8w+TfyJ/I6rWZ2YPZhT3JorIg+06c= +github.com/moby/moby/api v1.56.1/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk= +github.com/moby/moby/client v0.6.2 h1:ekSPlMccrZGcw6Scb8T9D39qE0mB+XupU/yS0zNw9N4= +github.com/moby/moby/client v0.6.2/go.mod h1:DGcnO7qmPJrqobx/ggQgQ/AUk+2wgVdQv7uxB0/mEsc= +github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U= +github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc= +github.com/moby/sys/mount v0.3.5 h1:eS3fsZTjHaBihwjp4/+5Z3jxqLXYsbwxqpVSfFv3M00= +github.com/moby/sys/mount v0.3.5/go.mod h1:WUQDO+/uCiCIkIztx8SrwIDVn2dtMFRBebRhpDFT71M= +github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9KouLrg= +github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4= +github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8= +github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o= +github.com/moby/sys/user v0.4.1 h1:RgjRlaDKi/Xmyrz4t8lyzXT6v2ooFeO/7xtchmhVWE0= +github.com/moby/sys/user v0.4.1/go.mod h1:E9QsW5WRe1kUAf7kW8hXKwu1uhsZEAdPLYHYSDudF4Y= +github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g= +github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= +github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= +github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/neo4j/neo4j-go-driver/v5 v5.28.5 h1:YfqEKXt8AxsXRMGu73eNipYWCSXodVI4dl2I8iwcavA= github.com/neo4j/neo4j-go-driver/v5 v5.28.5/go.mod h1:Vff8OwT7QpLm7L2yYr85XNWe9Rbqlbeb9asNXJTHO4k= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= +github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs= +github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= +github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= +github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/testcontainers/testcontainers-go v0.45.0 h1:ss9Stm9KDX6JLgGL4jr2fC5dwpabTbCBsRcGadBPR9k= +github.com/testcontainers/testcontainers-go v0.45.0/go.mod h1:VMJZ7M+qhgfEHWNbtjm596OyEOraULSTDaus/h0hmJI= +github.com/testcontainers/testcontainers-go/modules/neo4j v0.45.0 h1:YT4M3DYYLmbLjFUPtP2Nf1aInWgowlCMTb2yER8emOQ= +github.com/testcontainers/testcontainers-go/modules/neo4j v0.45.0/go.mod h1:PG//aBu857lQGKnZKxfrJ6bCNQpZfgx3JWmKqRh8GQ4= +github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU= +github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI= +github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4= +github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= +github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI= +go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= +go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= +go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= +go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= +go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= +go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= +go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= +go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= +go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= +go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= +gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= +pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk= +pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= diff --git a/internal/memtest/memtest_test.go b/internal/memtest/memtest_test.go new file mode 100644 index 0000000..c9c765c --- /dev/null +++ b/internal/memtest/memtest_test.go @@ -0,0 +1,184 @@ +//go:build memtest + +// Package memtest checks that cango pushes a large app to Neo4j inside a fixed memory limit (spec §7). +// Run: MEMTEST_APPS=[,...] go test -tags memtest ./internal/memtest -v -timeout 6h +// +// testcontainers-go does not read the docker CLI context. With Colima (or another non-default +// socket), set DOCKER_HOST to the socket and TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE=/var/run/docker.sock. +package memtest + +import ( + "cmp" + "context" + "io" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + "time" + + "github.com/moby/moby/api/types/container" + "github.com/moby/moby/api/types/mount" + "github.com/testcontainers/testcontainers-go" + tcneo4j "github.com/testcontainers/testcontainers-go/modules/neo4j" + "github.com/testcontainers/testcontainers-go/network" + "github.com/testcontainers/testcontainers-go/wait" +) + +const ( + neo4jImage = "neo4j:5.26-community" + neo4jPass = "memtest-pass" + gib = int64(1) << 30 +) + +func TestPushWithinMemoryLimit(t *testing.T) { + apps := os.Getenv("MEMTEST_APPS") + if apps == "" { + t.Skip("set MEMTEST_APPS to run the memory-limit test") + } + testcontainers.SkipIfProviderIsNotHealthy(t) + limit := parseBytes(t, cmp.Or(os.Getenv("MEMTEST_MEMORY"), "16g")) + ctx := context.Background() + + nw, err := network.New(ctx) + if err != nil { + t.Fatal(err) + } + testcontainers.CleanupNetwork(t, nw) + + db, err := tcneo4j.Run(ctx, neo4jImage, + tcneo4j.WithAdminPassword(neo4jPass), + tcneo4j.WithNeo4jSettings(map[string]string{ + "server.memory.heap.initial_size": "8G", + "server.memory.heap.max_size": "8G", + "server.memory.pagecache.size": "2G", + "dbms.memory.transaction.total.max": "5600m", + }), + network.WithNetwork([]string{"neo4j"}, nw), + testcontainers.WithHostConfigModifier(func(h *container.HostConfig) { + h.Memory, h.MemorySwap = 12*gib, 12*gib + }), + ) + testcontainers.CleanupContainer(t, db) + if err != nil { + t.Fatal(err) + } + + for _, dir := range strings.Split(apps, ",") { + dir, _ = filepath.Abs(strings.TrimSpace(dir)) + t.Run(filepath.Base(dir), func(t *testing.T) { runCango(t, ctx, nw, dir, limit) }) + } +} + +// runCango starts the cango container on nw, waits for it to exit, and checks the exit state. +func runCango(t *testing.T, ctx context.Context, nw *testcontainers.DockerNetwork, dir string, limit int64) { + _, thisFile, _, _ := runtime.Caller(0) + repo := filepath.Join(filepath.Dir(thisFile), "..", "..") + // The app is mounted read-only at /src-app and copied to /app, because GOFLAGS=-mod=mod + // lets go list rewrite go.mod or go.sum, and that must not touch the host checkout. + script := "cp -a /src-app /app && " + + "cango -i /app --emit neo4j -j \"$(nproc)\" -v -c /tmp/cango-cache; rc=$?; " + + "echo MEMTEST_PEAK=$(cat /sys/fs/cgroup/memory.peak); exit $rc" + c, err := testcontainers.Run(ctx, "", + testcontainers.WithDockerfile(testcontainers.FromDockerfile{ + Context: repo, Dockerfile: "scripts/memtest/Dockerfile.cango", + Repo: "cango-memtest", Tag: "latest", KeepImage: true, + }), + testcontainers.WithCmd(script), + testcontainers.WithEnv(map[string]string{ + "NEO4J_URI": "bolt://neo4j:7687", "NEO4J_USERNAME": "neo4j", "NEO4J_PASSWORD": neo4jPass, + "GOMODCACHE": "/gomod", + }), + network.WithNetwork(nil, nw), + testcontainers.WithHostConfigModifier(func(h *container.HostConfig) { + h.Memory, h.MemorySwap = limit, limit + h.Mounts = append(h.Mounts, + mount.Mount{Type: mount.TypeBind, Source: dir, Target: "/src-app", ReadOnly: true}, + mount.Mount{Type: mount.TypeVolume, Source: "cango-memtest-gomod", Target: "/gomod"}) + }), + testcontainers.WithWaitStrategy(wait.ForExit().WithExitTimeout(5*time.Hour)), + ) + testcontainers.CleanupContainer(t, c) + if err != nil { + t.Fatal(err) + } + st, err := c.State(ctx) + if err != nil { + t.Fatal(err) + } + logs := containerLogs(t, ctx, c) + peakText := "peak unknown (killed)" + if peak := peakFrom(logs); peak > 0 { + peakText = "peak " + strconv.FormatFloat(float64(peak)/float64(gib), 'f', 1, 64) + " GiB" + } + t.Logf("%s: exit %d, OOMKilled=%v, %s of %.1f GiB", filepath.Base(dir), st.ExitCode, st.OOMKilled, + peakText, float64(limit)/float64(gib)) + // The kernel OOM killer usually kills only cango (Docker does not set memory.oom.group), + // so the sh survives, prints the peak and exits 137. OOMKilled may stay false then: + // exit 137 counts as an OOM kill on its own. + if st.ExitCode != 0 || st.OOMKilled { + t.Errorf("cango failed. Last log lines:\n%s", tail(logs, 40)) + } +} + +// parseBytes reads a byte count with an optional k, m or g suffix (powers of 1024), as in "16g". +func parseBytes(t *testing.T, in string) int64 { + t.Helper() + s := strings.ToLower(strings.TrimSpace(in)) + mult := int64(1) + switch { + case strings.HasSuffix(s, "k"): + mult = 1 << 10 + case strings.HasSuffix(s, "m"): + mult = 1 << 20 + case strings.HasSuffix(s, "g"): + mult = gib + } + if mult != 1 { + s = s[:len(s)-1] + } + n, err := strconv.ParseInt(s, 10, 64) + if err != nil || n <= 0 { + t.Fatalf("bad memory size %q", in) + } + return n * mult +} + +// containerLogs reads the container's stdout and stderr into one string. +func containerLogs(t *testing.T, ctx context.Context, c testcontainers.Container) string { + t.Helper() + rc, err := c.Logs(ctx) + if err != nil { + t.Fatal(err) + } + defer rc.Close() + b, err := io.ReadAll(rc) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// peakFrom returns the byte count on the last MEMTEST_PEAK= line, or 0 when there is none. +func peakFrom(logs string) int64 { + var peak int64 + for line := range strings.Lines(logs) { + if v, ok := strings.CutPrefix(strings.TrimSpace(line), "MEMTEST_PEAK="); ok { + if n, err := strconv.ParseInt(v, 10, 64); err == nil { + peak = n + } + } + } + return peak +} + +// tail returns the last n lines of s. +func tail(s string, n int) string { + lines := strings.Split(strings.TrimRight(s, "\n"), "\n") + if len(lines) > n { + lines = lines[len(lines)-n:] + } + return strings.Join(lines, "\n") +} diff --git a/scripts/memtest/Dockerfile.cango b/scripts/memtest/Dockerfile.cango new file mode 100644 index 0000000..72ae116 --- /dev/null +++ b/scripts/memtest/Dockerfile.cango @@ -0,0 +1,15 @@ +# Two-stage image for the memory-limit test (spec §7). +# cango needs a Go toolchain at run time, because go/packages runs `go list`. +FROM golang:1.26 AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN CGO_ENABLED=0 go build -o /out/cango ./cmd/codeanalyzer + +FROM ubuntu:24.04 +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates git gcc libc6-dev && rm -rf /var/lib/apt/lists/* +COPY --from=build /usr/local/go /usr/local/go +COPY --from=build /out/cango /usr/local/bin/cango +ENV PATH=/usr/local/go/bin:$PATH GOTOOLCHAIN=auto GOFLAGS=-mod=mod +ENTRYPOINT ["/bin/sh", "-c"] From a2062e1e081ddb3c8ee49f4f162e4a6e1c6c4251 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Tue, 24 Nov 2026 20:50:01 -0500 Subject: [PATCH 11/16] test(memtest): per-app --app-name and unit-tested pass/fail decision (#59) Each app runs as --app-name , passed through MEMTEST_APP_NAME, so every push owns its own can:// keyspace in the fresh Neo4j container; duplicate names fail before any container starts. The pure helpers and the exit/OOMKilled/peak decision move to an untagged file with table tests, so plain go test covers them without Docker. Co-Authored-By: Claude Opus 5.5 --- internal/memtest/memtest.go | 125 ++++++++++++++++++++++ internal/memtest/memtest_test.go | 112 ++++++++------------ internal/memtest/memtest_unit_test.go | 143 ++++++++++++++++++++++++++ 3 files changed, 309 insertions(+), 71 deletions(-) create mode 100644 internal/memtest/memtest.go create mode 100644 internal/memtest/memtest_unit_test.go diff --git a/internal/memtest/memtest.go b/internal/memtest/memtest.go new file mode 100644 index 0000000..53f990a --- /dev/null +++ b/internal/memtest/memtest.go @@ -0,0 +1,125 @@ +// Package memtest checks that cango pushes a large app to Neo4j inside a fixed memory limit (spec §7). +// +// The container test is in memtest_test.go behind the memtest build tag. This file holds its +// pure helpers and its pass/fail decision, untagged, so plain `go test` covers them without Docker. +package memtest + +import ( + "errors" + "fmt" + "strconv" + "strings" +) + +const gib = int64(1) << 30 + +// peakMarker prefixes the line the cango container prints with its cgroup memory.peak. +const peakMarker = "MEMTEST_PEAK=" + +// ParseBytes reads a positive byte count with an optional k, m or g suffix (powers of 1024), as in "16g". +func ParseBytes(in string) (int64, error) { + s := strings.ToLower(strings.TrimSpace(in)) + mult := int64(1) + switch { + case strings.HasSuffix(s, "k"): + mult = 1 << 10 + case strings.HasSuffix(s, "m"): + mult = 1 << 20 + case strings.HasSuffix(s, "g"): + mult = gib + } + if mult != 1 { + s = s[:len(s)-1] + } + n, err := strconv.ParseInt(s, 10, 64) + if err != nil || n <= 0 || n > (1<<62)/mult { + return 0, fmt.Errorf("bad memory size %q", in) + } + return n * mult, nil +} + +// PeakFrom returns the byte count on the last MEMTEST_PEAK= line of logs, or 0 when there is none +// (the whole cgroup was killed, or memory.peak could not be read). +func PeakFrom(logs string) int64 { + var peak int64 + for line := range strings.Lines(logs) { + if v, ok := strings.CutPrefix(strings.TrimSpace(line), peakMarker); ok { + if n, err := strconv.ParseInt(v, 10, 64); err == nil && n > 0 { + peak = n + } + } + } + return peak +} + +// Tail returns the last n lines of s. +func Tail(s string, n int) string { + lines := strings.Split(strings.TrimRight(s, "\n"), "\n") + if len(lines) > n { + lines = lines[len(lines)-n:] + } + return strings.Join(lines, "\n") +} + +// 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. +func AppName(base string) (string, error) { + b := []byte(base) + for i, c := range b { + if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-') { + b[i] = '-' + } + } + name := string(b) + if strings.Trim(name, "-") == "" || name == "." || name == ".." { + return "", fmt.Errorf("app directory %q gives no usable app name", base) + } + return name, nil +} + +// AppNames maps each app directory base name to its app name, in order. +// Two apps with the same app name would share one can:// keyspace in Neo4j, +// so the second push would not be a clean full push: that is an error. +func AppNames(bases []string) ([]string, error) { + names := make([]string, 0, len(bases)) + seen := map[string]string{} + var errs []error + for _, base := range bases { + name, err := AppName(base) + if err != nil { + errs = append(errs, err) + continue + } + if prev, dup := seen[name]; dup { + errs = append(errs, fmt.Errorf("apps %q and %q both get app name %q; rename one directory", prev, base, name)) + continue + } + seen[name] = base + names = append(names, name) + } + return names, errors.Join(errs...) +} + +// Verdict is the result of one cango container run. +type Verdict struct { + Failed bool // the run failed: non-zero exit (137 = OOM kill of cango) or Docker's OOMKilled + Line string // the log line: ": exit N, OOMKilled=B, peak X GiB of Y GiB" +} + +// Decide judges one run from the container's exit code, Docker's OOMKilled flag, its logs and the limit. +// +// Docker does not set memory.oom.group, so the kernel OOM killer usually kills only cango. +// The sh that is PID 1 survives, prints the peak and exits 137, and OOMKilled may stay false: +// any non-zero exit therefore fails on its own, and OOMKilled fails even with exit 0. +func Decide(app string, exitCode int, oomKilled bool, logs string, limit int64) Verdict { + peak := "peak unavailable" + if p := PeakFrom(logs); p > 0 { + peak = fmt.Sprintf("peak %.1f GiB", float64(p)/float64(gib)) + } + return Verdict{ + Failed: exitCode != 0 || oomKilled, + Line: fmt.Sprintf("%s: exit %d, OOMKilled=%v, %s of %.1f GiB", app, exitCode, oomKilled, + peak, float64(limit)/float64(gib)), + } +} diff --git a/internal/memtest/memtest_test.go b/internal/memtest/memtest_test.go index c9c765c..0bc26d6 100644 --- a/internal/memtest/memtest_test.go +++ b/internal/memtest/memtest_test.go @@ -1,10 +1,11 @@ //go:build memtest -// Package memtest checks that cango pushes a large app to Neo4j inside a fixed memory limit (spec §7). +// The memory-limit container test (spec §7). // Run: MEMTEST_APPS=[,...] go test -tags memtest ./internal/memtest -v -timeout 6h // // testcontainers-go does not read the docker CLI context. With Colima (or another non-default // socket), set DOCKER_HOST to the socket and TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE=/var/run/docker.sock. + package memtest import ( @@ -14,7 +15,6 @@ import ( "os" "path/filepath" "runtime" - "strconv" "strings" "testing" "time" @@ -30,7 +30,6 @@ import ( const ( neo4jImage = "neo4j:5.26-community" neo4jPass = "memtest-pass" - gib = int64(1) << 30 ) func TestPushWithinMemoryLimit(t *testing.T) { @@ -38,8 +37,25 @@ func TestPushWithinMemoryLimit(t *testing.T) { if apps == "" { t.Skip("set MEMTEST_APPS to run the memory-limit test") } + limit, err := ParseBytes(cmp.Or(os.Getenv("MEMTEST_MEMORY"), "16g")) + if err != nil { + t.Fatal(err) + } + var dirs, bases []string + for _, dir := range strings.Split(apps, ",") { + dir, err := filepath.Abs(strings.TrimSpace(dir)) + if err != nil { + t.Fatal(err) + } + dirs, bases = append(dirs, dir), append(bases, filepath.Base(dir)) + } + // Each app gets its own can:// keyspace in the fresh Neo4j container, so every push is a + // clean full push. Duplicate names fail here, before any container starts. + names, err := AppNames(bases) + if err != nil { + t.Fatal(err) + } testcontainers.SkipIfProviderIsNotHealthy(t) - limit := parseBytes(t, cmp.Or(os.Getenv("MEMTEST_MEMORY"), "16g")) ctx := context.Background() nw, err := network.New(ctx) @@ -66,21 +82,21 @@ func TestPushWithinMemoryLimit(t *testing.T) { t.Fatal(err) } - for _, dir := range strings.Split(apps, ",") { - dir, _ = filepath.Abs(strings.TrimSpace(dir)) - t.Run(filepath.Base(dir), func(t *testing.T) { runCango(t, ctx, nw, dir, limit) }) + for i, dir := range dirs { + t.Run(names[i], func(t *testing.T) { runCango(t, ctx, nw, dir, names[i], limit) }) } } -// runCango starts the cango container on nw, waits for it to exit, and checks the exit state. -func runCango(t *testing.T, ctx context.Context, nw *testcontainers.DockerNetwork, dir string, limit int64) { +// runCango starts the cango container on nw, waits for it to exit, and judges the run with Decide. +func runCango(t *testing.T, ctx context.Context, nw *testcontainers.DockerNetwork, dir, app string, limit int64) { _, thisFile, _, _ := runtime.Caller(0) repo := filepath.Join(filepath.Dir(thisFile), "..", "..") // The app is mounted read-only at /src-app and copied to /app, because GOFLAGS=-mod=mod // lets go list rewrite go.mod or go.sum, and that must not touch the host checkout. + // The app name comes in through MEMTEST_APP_NAME, never spliced into the script. script := "cp -a /src-app /app && " + - "cango -i /app --emit neo4j -j \"$(nproc)\" -v -c /tmp/cango-cache; rc=$?; " + - "echo MEMTEST_PEAK=$(cat /sys/fs/cgroup/memory.peak); exit $rc" + "cango -i /app --app-name \"$MEMTEST_APP_NAME\" --emit neo4j -j \"$(nproc)\" -v -c /tmp/cango-cache; rc=$?; " + + "echo " + peakMarker + "$(cat /sys/fs/cgroup/memory.peak); exit $rc" c, err := testcontainers.Run(ctx, "", testcontainers.WithDockerfile(testcontainers.FromDockerfile{ Context: repo, Dockerfile: "scripts/memtest/Dockerfile.cango", @@ -89,7 +105,7 @@ func runCango(t *testing.T, ctx context.Context, nw *testcontainers.DockerNetwor testcontainers.WithCmd(script), testcontainers.WithEnv(map[string]string{ "NEO4J_URI": "bolt://neo4j:7687", "NEO4J_USERNAME": "neo4j", "NEO4J_PASSWORD": neo4jPass, - "GOMODCACHE": "/gomod", + "GOMODCACHE": "/gomod", "MEMTEST_APP_NAME": app, }), network.WithNetwork(nil, nw), testcontainers.WithHostConfigModifier(func(h *container.HostConfig) { @@ -98,10 +114,15 @@ func runCango(t *testing.T, ctx context.Context, nw *testcontainers.DockerNetwor mount.Mount{Type: mount.TypeBind, Source: dir, Target: "/src-app", ReadOnly: true}, mount.Mount{Type: mount.TypeVolume, Source: "cango-memtest-gomod", Target: "/gomod"}) }), + // ForExit returns nil as soon as the container is not running, whatever its exit code, + // so a non-zero exit reaches Decide below, not this error path. testcontainers.WithWaitStrategy(wait.ForExit().WithExitTimeout(5*time.Hour)), ) testcontainers.CleanupContainer(t, c) if err != nil { + if c != nil { + t.Logf("last log lines:\n%s", Tail(containerLogs(t, ctx, c), 40)) + } t.Fatal(err) } st, err := c.State(ctx) @@ -109,76 +130,25 @@ func runCango(t *testing.T, ctx context.Context, nw *testcontainers.DockerNetwor t.Fatal(err) } logs := containerLogs(t, ctx, c) - peakText := "peak unknown (killed)" - if peak := peakFrom(logs); peak > 0 { - peakText = "peak " + strconv.FormatFloat(float64(peak)/float64(gib), 'f', 1, 64) + " GiB" - } - t.Logf("%s: exit %d, OOMKilled=%v, %s of %.1f GiB", filepath.Base(dir), st.ExitCode, st.OOMKilled, - peakText, float64(limit)/float64(gib)) - // The kernel OOM killer usually kills only cango (Docker does not set memory.oom.group), - // so the sh survives, prints the peak and exits 137. OOMKilled may stay false then: - // exit 137 counts as an OOM kill on its own. - if st.ExitCode != 0 || st.OOMKilled { - t.Errorf("cango failed. Last log lines:\n%s", tail(logs, 40)) - } -} - -// parseBytes reads a byte count with an optional k, m or g suffix (powers of 1024), as in "16g". -func parseBytes(t *testing.T, in string) int64 { - t.Helper() - s := strings.ToLower(strings.TrimSpace(in)) - mult := int64(1) - switch { - case strings.HasSuffix(s, "k"): - mult = 1 << 10 - case strings.HasSuffix(s, "m"): - mult = 1 << 20 - case strings.HasSuffix(s, "g"): - mult = gib - } - if mult != 1 { - s = s[:len(s)-1] + v := Decide(app, st.ExitCode, st.OOMKilled, logs, limit) + t.Log(v.Line) + if v.Failed { + t.Errorf("cango failed. Last log lines:\n%s", Tail(logs, 40)) } - n, err := strconv.ParseInt(s, 10, 64) - if err != nil || n <= 0 { - t.Fatalf("bad memory size %q", in) - } - return n * mult } -// containerLogs reads the container's stdout and stderr into one string. +// containerLogs reads the container's stdout and stderr into one string ("" if they cannot be read). func containerLogs(t *testing.T, ctx context.Context, c testcontainers.Container) string { t.Helper() rc, err := c.Logs(ctx) if err != nil { - t.Fatal(err) + t.Logf("read logs: %v", err) + return "" } defer rc.Close() b, err := io.ReadAll(rc) if err != nil { - t.Fatal(err) + t.Logf("read logs: %v", err) } return string(b) } - -// peakFrom returns the byte count on the last MEMTEST_PEAK= line, or 0 when there is none. -func peakFrom(logs string) int64 { - var peak int64 - for line := range strings.Lines(logs) { - if v, ok := strings.CutPrefix(strings.TrimSpace(line), "MEMTEST_PEAK="); ok { - if n, err := strconv.ParseInt(v, 10, 64); err == nil { - peak = n - } - } - } - return peak -} - -// tail returns the last n lines of s. -func tail(s string, n int) string { - lines := strings.Split(strings.TrimRight(s, "\n"), "\n") - if len(lines) > n { - lines = lines[len(lines)-n:] - } - return strings.Join(lines, "\n") -} diff --git a/internal/memtest/memtest_unit_test.go b/internal/memtest/memtest_unit_test.go new file mode 100644 index 0000000..2c6cdbe --- /dev/null +++ b/internal/memtest/memtest_unit_test.go @@ -0,0 +1,143 @@ +package memtest + +import ( + "strings" + "testing" +) + +func TestParseBytes(t *testing.T) { + for _, tc := range []struct { + in string + want int64 + bad bool + }{ + {in: "16g", want: 16 << 30}, + {in: " 16G ", want: 16 << 30}, + {in: "512m", want: 512 << 20}, + {in: "64k", want: 64 << 10}, + {in: "1000", want: 1000}, + {in: "", bad: true}, + {in: "g", bad: true}, + {in: "0g", bad: true}, + {in: "-1g", bad: true}, + {in: "1.5g", bad: true}, + {in: "16gb", bad: true}, + {in: "99999999999g", bad: true}, // overflows int64 + } { + got, err := ParseBytes(tc.in) + if tc.bad { + if err == nil { + t.Errorf("ParseBytes(%q) = %d, want an error", tc.in, got) + } + continue + } + if err != nil || got != tc.want { + t.Errorf("ParseBytes(%q) = %d, %v; want %d", tc.in, got, err, tc.want) + } + } +} + +func TestPeakFrom(t *testing.T) { + for _, tc := range []struct { + name, logs string + want int64 + }{ + {"present", "analyzing\nMEMTEST_PEAK=2147483648\n", 2 << 30}, + {"crlf and spaces", "x\r\n MEMTEST_PEAK=1024\r\n", 1024}, + {"last wins", "MEMTEST_PEAK=1\nMEMTEST_PEAK=2\n", 2}, + {"absent (cgroup killed)", "analyzing\nKilled\n", 0}, + {"empty value (memory.peak unreadable)", "MEMTEST_PEAK=\n", 0}, + {"garbage", "MEMTEST_PEAK=max\n", 0}, + {"not at line start", "echo MEMTEST_PEAK=5\n", 0}, + {"no trailing newline", "MEMTEST_PEAK=7", 7}, + {"empty", "", 0}, + } { + if got := PeakFrom(tc.logs); got != tc.want { + t.Errorf("%s: PeakFrom = %d, want %d", tc.name, got, tc.want) + } + } +} + +func TestTail(t *testing.T) { + for _, tc := range []struct { + s string + n int + want string + }{ + {"a\nb\nc\n", 2, "b\nc"}, + {"a\nb\nc", 5, "a\nb\nc"}, + {"a\nb\nc\n", 3, "a\nb\nc"}, + {"", 3, ""}, + } { + if got := Tail(tc.s, tc.n); got != tc.want { + t.Errorf("Tail(%q, %d) = %q, want %q", tc.s, tc.n, got, tc.want) + } + } +} + +func TestAppName(t *testing.T) { + for _, tc := range []struct { + in, want string + bad bool + }{ + {in: "nats-server", want: "nats-server"}, + {in: "gitea_1.22", want: "gitea_1.22"}, + {in: "my app", want: "my-app"}, + {in: "naïve", want: "na--ve"}, // each UTF-8 byte of ï becomes '-' + {in: "a\tb", want: "a-b"}, + {in: ".", bad: true}, + {in: "..", bad: true}, + {in: "", bad: true}, + {in: "!!", bad: true}, + } { + got, err := AppName(tc.in) + if tc.bad { + if err == nil { + t.Errorf("AppName(%q) = %q, want an error", tc.in, got) + } + continue + } + if err != nil || got != tc.want { + t.Errorf("AppName(%q) = %q, %v; want %q", tc.in, got, err, tc.want) + } + } +} + +func TestAppNames(t *testing.T) { + got, err := AppNames([]string{"nats-server", "gitea"}) + if err != nil || strings.Join(got, ",") != "nats-server,gitea" { + t.Fatalf("AppNames = %v, %v", got, err) + } + // Two directories with one base name (or names that sanitise alike) share a keyspace. + if _, err := AppNames([]string{"app", "app"}); err == nil || !strings.Contains(err.Error(), `both get app name "app"`) { + t.Errorf("duplicate base names: err = %v", err) + } + if _, err := AppNames([]string{"my app", "my-app"}); err == nil { + t.Error("names that sanitise alike: want an error") + } +} + +func TestDecide(t *testing.T) { + const limit = 16 << 30 + peakLog := "MEMTEST_PEAK=3435973837\n" // 3.2 GiB + for _, tc := range []struct { + name string + exit int + oom bool + logs string + failed bool + wantLine string + }{ + {"clean exit", 0, false, peakLog, false, "app: exit 0, OOMKilled=false, peak 3.2 GiB of 16.0 GiB"}, + {"cango OOM-killed, sh survives", 137, false, "MEMTEST_PEAK=17179869184\n", true, + "app: exit 137, OOMKilled=false, peak 16.0 GiB of 16.0 GiB"}, + {"whole cgroup killed", 137, true, "analyzing\n", true, "app: exit 137, OOMKilled=true, peak unavailable of 16.0 GiB"}, + {"OOMKilled with exit 0", 0, true, peakLog, true, "app: exit 0, OOMKilled=true, peak 3.2 GiB of 16.0 GiB"}, + {"cango error", 1, false, peakLog, true, "app: exit 1, OOMKilled=false, peak 3.2 GiB of 16.0 GiB"}, + } { + v := Decide("app", tc.exit, tc.oom, tc.logs, limit) + if v.Failed != tc.failed || v.Line != tc.wantLine { + t.Errorf("%s: Decide = %+v, want Failed=%v Line=%q", tc.name, v, tc.failed, tc.wantLine) + } + } +} From 69bb16d27ffcc6e67ac2eada5f12bd2bff414419 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Tue, 24 Nov 2026 21:20:12 -0500 Subject: [PATCH 12/16] test(memtest): let the cango wait run for the full 5 h bound (#59) WithWaitStrategy wraps the strategy in wait.ForAll with a 60 s deadline, which capped every cango run at about 60 s whatever ForExit's exit timeout. Use WithWaitStrategyAndDeadline with the same 5 h run bound. Co-Authored-By: Claude Opus 5.5 --- internal/memtest/memtest_test.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/internal/memtest/memtest_test.go b/internal/memtest/memtest_test.go index 0bc26d6..65ecd4a 100644 --- a/internal/memtest/memtest_test.go +++ b/internal/memtest/memtest_test.go @@ -30,6 +30,8 @@ import ( const ( neo4jImage = "neo4j:5.26-community" neo4jPass = "memtest-pass" + // runTimeout bounds one cango run (analysis and push). + runTimeout = 5 * time.Hour ) func TestPushWithinMemoryLimit(t *testing.T) { @@ -116,7 +118,10 @@ func runCango(t *testing.T, ctx context.Context, nw *testcontainers.DockerNetwor }), // ForExit returns nil as soon as the container is not running, whatever its exit code, // so a non-zero exit reaches Decide below, not this error path. - testcontainers.WithWaitStrategy(wait.ForExit().WithExitTimeout(5*time.Hour)), + // The wait is the readiness ("started") hook of Run. WithWaitStrategy would wrap it in + // wait.ForAll with a 60 s deadline that caps the whole run, whatever the exit timeout: + // the ForAll deadline must be the run bound too. + testcontainers.WithWaitStrategyAndDeadline(runTimeout, wait.ForExit().WithExitTimeout(runTimeout)), ) testcontainers.CleanupContainer(t, c) if err != nil { From 0b9345cc040a93469a00feda7478d4952a54edda Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Wed, 25 Nov 2026 11:30:24 -0500 Subject: [PATCH 13/16] docs(spec): split analysis memory back out to #62 (#59) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Gitea passes at 16 GB with the streaming push alone (peak 15.8 GiB, the same under a 24 GB limit), so #59 closes on the push. §8 records the split and the results; §7.5 drops the expectation that gitea needs the analysis-memory work. Co-Authored-By: Claude Opus 5.5 --- .../specs/2026-11-24-neo4j-streaming-push.md | 26 ++++++------------- 1 file changed, 8 insertions(+), 18 deletions(-) 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 33bb13f..43521b7 100644 --- a/docs/design/specs/2026-11-24-neo4j-streaming-push.md +++ b/docs/design/specs/2026-11-24-neo4j-streaming-push.md @@ -186,27 +186,17 @@ The peak memory shows the margin under the limit. Both apps pass at 16 GB when this branch is complete. nats-server needs only the streaming push (§5). -gitea also needs the analysis-memory work (§8). +gitea was expected to need the analysis-memory work too, but it passed with the streaming push alone, with about 0.2 GiB of margin (§8). -## 8. Analysis memory (#62, in this branch) +## 8. Analysis memory (#62, split out) -The user moved #62 into this branch, so #59 closes only when both apps pass at 16 GB. -Gitea is about 4 times as large as nats-server. -At that ratio its analysis heap is about 40 GB, so the streaming push alone is not sufficient. +The user first moved #62 into this branch, then split it back out on 2026-11-25, after the streaming push passed on both apps. +#59 closes on the streaming push alone. -This part has no design yet, because I did not profile `Analyze` on gitea. -The order of work is as follows: - -1. Ship the streaming push (§5) and the harness (§7). -2. Run the harness on nats-server at 16 GB. -3. Profile `Analyze` on gitea, stage by stage, with the probe from §2. -4. Write the analysis-memory design as an addendum to this spec, and get approval before any code changes. - -The nats-server profile gives the first candidates for step 4: - -- `sdg.(*sdgBuilder).fill` holds 10.1 GB (cumulative). -- `sdg.sortedPortEdges` holds 3.3 GB, and `sdg.(*ports).vertices` holds 1.9 GB. -- Step 4 also checks whether the analyzer can drop the SSA program before emission. +Result at 16 GB, no swap: nats-server peaks at 7.8 GiB and gitea at 15.8 GiB; both pass. +Gitea also peaks at 15.8 GiB under a 24 GB limit, so its margin at 16 GB is about 0.2 GiB. +Widening that margin is #62's job. +Its draft design, with the gitea profile, is `docs/design/specs/2026-11-25-analysis-memory.md`. ## 9. Decision: the `graph.cypher` snapshot (no `--neo4j-uri`) From 3c953afb2f29305604c1c06cc6a4351b1c5e58ee Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Wed, 25 Nov 2026 11:40:27 -0500 Subject: [PATCH 14/16] fix(neo4j): stamp module content_hash after all nodes land (#59) Node groups flush in group-key order and in 5000-row chunks, so a :GoModule row could land with its content_hash before the rest of its module's nodes. A push that died in between left a matching hash; the next lazy push skipped the module and MATCH dropped the edges into its missing nodes. The Bolt writer now upserts :GoModule rows with content_hash = null and keeps only the (id, hash) pairs; late stamps them in boltBatchSize UNWIND batches after the final node flush. The final graph is unchanged and graph.cypher is untouched. Also: align the package doc's stage numbers with the stager (0-5), mark upsertNodes/upsertEdges/partitionNodes as test seams, run pushPaths' replay in its own subtest, and cover the lazy push in StreamPushOrder. Co-Authored-By: Claude Opus 5.5 --- internal/neo4j/bolt.go | 106 +++++++++++++++++++++++----- internal/neo4j/bolt_session_test.go | 91 ++++++++++++++++++++++-- 2 files changed, 172 insertions(+), 25 deletions(-) diff --git a/internal/neo4j/bolt.go b/internal/neo4j/bolt.go index 718fb5b..50b57e4 100644 --- a/internal/neo4j/bolt.go +++ b/internal/neo4j/bolt.go @@ -3,9 +3,12 @@ package neo4j import ( "context" "fmt" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "maps" + "slices" "sort" + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/neo4j/neo4j-go-driver/v5/neo4j" ) @@ -15,29 +18,42 @@ import ( // CGO_ENABLED=0 static build still links; it is only exercised when EmitNeo4j // runs with a --neo4j-uri, never on the JSON path. // -// The writer is a stager (stream.go); its stages run in push order (spec §5.3): -// 1. begin: stored-application gate — read :GoApplication.schema_version and +// The writer is a stager (stream.go); its stages run in push order (spec §5.3), +// numbered as the stager numbers them: +// 0. begin: stored-application gate — read :GoApplication.schema_version and // max_level scoped to this app's id; a version mismatch, or a stored level // below this push's, forces a full re-UPSERT (never a delete — that is // --eager's job); ensure constraints + indexes; --eager? scoped purge of // everything under the app prefix, then rebuild; -// 2. shared: upsert the module-less repository nodes (MERGE-only, always); -// 3. module, per module: diff its content_hash against the DB; when changed, +// 1. shared: upsert the module-less repository nodes (MERGE-only, always); +// 2. module, per module: diff its content_hash against the DB; when changed, // on --eager purge its owned edges + stale decls, then upsert its L1–L3 -// nodes (WITHOUT --eager the push only adds/updates); upsert its L4 vertex -// nodes, changed module or not (D5, below); -// 4. late: upsert the ghosts, stand-in vertices and application row, and -// flush every node buffer; -// 5. edges: upsert every edge (an unchanged edge's MERGE is a no-op); -// 6. end: flush the edges; on a full --eager run, orphan-prune modules whose +// nodes (WITHOUT --eager the push only adds/updates) with content_hash +// cleared; upsert its L4 vertex nodes, changed module or not (D5, below); +// 3. late: upsert the ghosts, stand-in vertices and application row, flush +// every node buffer, then stamp the content_hash of every module upserted +// in step 2; +// 4. edges: upsert every edge (an unchanged edge's MERGE is a no-op); +// 5. end: flush the edges; on a full --eager run, orphan-prune modules whose // source vanished. // +// The content_hash is stamped only after every node row of every module has +// landed. Node groups flush in group-key order and in boltBatchSize chunks, so +// a :GoModule row can land before the rest of its module's nodes; a hash +// written with it would survive a push that dies before those nodes land, the +// next lazy push would skip the module as unchanged, and the edges into its +// missing nodes would be dropped by MATCH. The :GoModule row is therefore +// written with content_hash = null (clearing a stored hash) and the hash set +// by batched UNWIND statements (boltBatchSize rows each) after the final node +// flush. Edges need no such +// guard: every push upserts every edge. +// // D5 (spec §4.11): L4 facts are not module-local — editing a callee changes // its callers' summary edges, actual vertices and even formal_in indices — // so the content_hash diff gates the L1–L3 rows only. A lazy push upserts -// every L4 row on every push: the vertex nodes (steps 3–4), the stand-in +// every L4 row on every push: the vertex nodes (steps 2–3), the stand-in // bodies among them, and the GO_PARAM_IN / GO_PARAM_OUT / GO_SUMMARY rows -// and the port GO_DDG rows (prov ≠ ssa) with every other edge (step 5). It +// and the port GO_DDG rows (prov ≠ ssa) with every other edge (step 4). It // is additive: a stale L4 row stays until an --eager push. // // A push NEVER deletes by default (#171): the purges and the prune run under @@ -122,8 +138,15 @@ type boltWriter struct { scoped bool nodeBuf map[string][]NodeRow 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). + hashes []moduleHashRow } +// moduleHashRow is one deferred content_hash stamp. +type moduleHashRow struct{ id, hash string } + func newBoltWriter(ctx context.Context, s neo4j.SessionWithContext, appID string, cfg BoltConfig) *boltWriter { return &boltWriter{ctx: ctx, session: s, appID: appID, cfg: cfg, nodeBuf: map[string][]NodeRow{}, edgeBuf: map[string][]EdgeRow{}} @@ -191,20 +214,65 @@ func (w *boltWriter) module(id string, nodes []NodeRow) error { return err } } - if err := w.bufferNodes(core); err != nil { + if err := w.bufferNodes(w.deferHashes(core)); err != nil { return err } } return w.bufferNodes(l4) } +// deferHashes returns core with each :GoModule row's content_hash replaced by +// an explicit null (SET += removes a stored hash) and records the hash for +// stampHashes. The rows passed in are not modified: the caller may reuse them. +func (w *boltWriter) deferHashes(core []NodeRow) []NodeRow { + var out []NodeRow + for i, n := range core { + h, ok := n.Props["content_hash"].(string) + if n.Labels[0] != LabelModule || !ok { + continue + } + if out == nil { + out = slices.Clone(core) + } + p := maps.Clone(n.Props) + p["content_hash"] = nil + out[i].Props = p + w.hashes = append(w.hashes, moduleHashRow{n.Value, h}) + } + if out == nil { + return core + } + return out +} + // late upserts the ghosts, the stand-in vertices and the application row, -// and flushes every node buffer before the first edge statement. +// flushes every node buffer before the first edge statement, and then stamps +// the deferred module content_hash values (see the package doc). func (w *boltWriter) late(nodes []NodeRow) error { if err := w.bufferNodes(nodes); err != nil { return err } - return w.flushNodes() + if err := w.flushNodes(); err != nil { + return err + } + return w.stampHashes() +} + +// stampHashes sets the content_hash of every module recorded by deferHashes, +// in batches of boltBatchSize, once all node rows have landed. +func (w *boltWriter) stampHashes() error { + const q = "UNWIND $rows AS r MATCH (m:GoModule {id: r.id}) SET m.content_hash = r.h" + for chunk := range slices.Chunk(w.hashes, boltBatchSize) { + rows := make([]map[string]any, len(chunk)) + for i, h := range chunk { + rows[i] = map[string]any{"id": h.id, "h": h.hash} + } + if err := w.runBatch(q, rows); err != nil { + return err + } + } + w.hashes = nil + return nil } // edges buffers every edge: the L4 rows must be upserted (D5), and for the @@ -392,7 +460,8 @@ func (w *boltWriter) moduleChanged(id, localHash string) (bool, error) { // ─── upserts ────────────────────────────────────────────────────────────────── -// upsertNodes and upsertEdges write a ready slice: buffer, then flush. +// upsertNodes and upsertEdges write a ready slice: buffer, then flush. They +// are test seams: the push path goes through the stager stages. func (w *boltWriter) upsertNodes(nodes []NodeRow) error { if err := w.bufferNodes(nodes); err != nil { return err @@ -590,7 +659,8 @@ func propsToAny(p Props) map[string]any { // partitionNodes splits nodes into the module-owned L1–L3 nodes (by owning // module), the shared nodes (no module), and the L4 vertex nodes, owned by -// a module or by a stand-in, which a push always upserts (D5). +// a module or by a stand-in, which a push always upserts (D5). It is a test +// seam: the push path partitions through replayRows and the stager stages. func partitionNodes(nodes []NodeRow) (byModule map[string][]NodeRow, shared, l4 []NodeRow) { byModule = map[string][]NodeRow{} for _, n := range nodes { diff --git a/internal/neo4j/bolt_session_test.go b/internal/neo4j/bolt_session_test.go index 7bcabc1..d46b88d 100644 --- a/internal/neo4j/bolt_session_test.go +++ b/internal/neo4j/bolt_session_test.go @@ -162,7 +162,7 @@ func (tx fakeTx) Run(_ context.Context, q string, params map[string]any) (neo4j. rawNamespace = tx.db.rawNamespace } return &fakeResult{rec: &neo4j.Record{Keys: []string{"v", "l", "iv", "an", "ns"}, Values: []any{SchemaVersion, lvl, identity, rawName, rawNamespace}}}, nil - case strings.Contains(q, "m.content_hash"): + case strings.Contains(q, "RETURN m.content_hash"): h, ok := tx.db.hashes[params["id"].(string)] if !ok { return &fakeResult{}, nil @@ -217,11 +217,15 @@ func pushRows(t *testing.T, db *fakeDB, rows GraphRows, appID string, cfg BoltCo } } -// pushPaths runs body once with a replay of Project(a) and once, in a -// "stream" subtest, with a streamGraph push of a's tree. +// pushPaths runs body once, in a "replay" subtest, with a replay of +// Project(a) and once, in a "stream" subtest, with a streamGraph push of a's +// tree. func pushPaths(t *testing.T, a *v2.Analysis, body func(t *testing.T, push func(*fakeDB, BoltConfig))) { + t.Helper() rows := Project(a) - body(t, func(db *fakeDB, cfg BoltConfig) { pushRows(t, db, rows, a.Application.ID, cfg) }) + t.Run("replay", func(t *testing.T) { + body(t, func(db *fakeDB, cfg BoltConfig) { pushRows(t, db, rows, a.Application.ID, cfg) }) + }) t.Run("stream", func(t *testing.T) { body(t, func(db *fakeDB, cfg BoltConfig) { t.Helper() @@ -603,12 +607,18 @@ func TestBolt_UpsertsAreBatched(t *testing.T) { } } -// TestBolt_StreamPushOrder (spec §6): no edge statement runs before the last node statement, -// and an eager push purges each module before it writes that module's nodes. +// TestBolt_StreamPushOrder (spec §6): no edge statement runs before the last +// node statement, on an eager and on a lazy push, and an eager push purges +// each module before it writes that module's nodes. func TestBolt_StreamPushOrder(t *testing.T) { a := buildDataflowL4(t) + t.Run("eager", func(t *testing.T) { streamPushOrder(t, a, BoltConfig{Eager: true, FullRun: true}) }) + t.Run("lazy", func(t *testing.T) { streamPushOrder(t, a, BoltConfig{}) }) +} + +func streamPushOrder(t *testing.T, a *v2.Analysis, cfg BoltConfig) { db := &fakeDB{} - w := newBoltWriter(context.Background(), db, a.Application.ID, BoltConfig{Eager: true, FullRun: true}) + w := newBoltWriter(context.Background(), db, a.Application.ID, cfg) if _, _, err := streamGraph(treeSource(a), w); err != nil { t.Fatal(err) } @@ -630,9 +640,18 @@ func TestBolt_StreamPushOrder(t *testing.T) { purgedAt[st.params["m"].(string)] = i } } + if lastNode < 0 || firstEdge == len(db.writes) { + t.Fatalf("no node (%d) or no edge (%d) statement", lastNode, firstEdge) + } if lastNode > firstEdge { t.Errorf("node statement %d runs after edge statement %d", lastNode, firstEdge) } + if !cfg.Eager { + if len(purgedAt) != 0 { + t.Errorf("lazy push purged %d modules", len(purgedAt)) + } + return + } if len(purgedAt) != len(a.Application.SymbolTable) { t.Errorf("%d module purges, want %d", len(purgedAt), len(a.Application.SymbolTable)) } @@ -644,3 +663,61 @@ func TestBolt_StreamPushOrder(t *testing.T) { } } } + +// TestBolt_ContentHashStampedAfterAllNodes (#59): a :GoModule row is written +// without its content_hash, and every hash is stamped only after the last +// node-upsert statement. Otherwise a push that dies between a :GoModule batch +// and the rest of that module's nodes would leave a matching hash, and the +// next lazy push would skip the module and drop the edges into its missing +// nodes. After the push every upserted module carries its hash. +func TestBolt_ContentHashStampedAfterAllNodes(t *testing.T) { + a := buildDataflowL4(t) + byModule, _, _ := partitionNodes(Project(a).Nodes) + want := map[string]string{} + for m, ns := range byModule { + if want[m] = moduleHash(ns); want[m] == "" { + t.Fatalf("module %s has no content_hash", m) + } + } + pushPaths(t, a, func(t *testing.T, push func(*fakeDB, BoltConfig)) { + for _, cfg := range []BoltConfig{{}, {Eager: true, FullRun: true}} { + db := &fakeDB{} + push(db, cfg) + lastNode, firstStamp := -1, -1 + got := map[string]string{} + for i, st := range db.writes { + rows, _ := st.params["rows"].([]map[string]any) + switch { + case strings.Contains(st.q, "MERGE (n:"): + lastNode = i + for _, r := range rows { + if h, has := r["p"].(map[string]any)["content_hash"]; has && h != nil { + t.Errorf("eager=%v: node %v upserted with content_hash %v", cfg.Eager, r["k"], h) + } + } + case strings.Contains(st.q, "content_hash"): + if firstStamp < 0 { + firstStamp = i + } + for _, r := range rows { + got[r["id"].(string)] = r["h"].(string) + } + } + } + if firstStamp < 0 || firstStamp < lastNode { + t.Errorf("eager=%v: first content_hash statement %d, last node statement %d", cfg.Eager, firstStamp, lastNode) + } + if fmt.Sprint(got) != fmt.Sprint(want) { + t.Errorf("eager=%v: stamped %v, want %v", cfg.Eager, got, want) + } + } + // A lazy push whose modules are all unchanged stamps nothing. + db := &fakeDB{hashes: want, level: 4} + push(db, BoltConfig{}) + for _, st := range db.writes { + if strings.Contains(st.q, "content_hash") { + t.Errorf("unchanged modules: content_hash statement %q", st.q) + } + } + }) +} From ac05ce3b430e6c7feba03ec904f077da8052ee12 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Wed, 25 Nov 2026 11:40:28 -0500 Subject: [PATCH 15/16] docs(neo4j): tighten streaming docs and snapshot tests (#59) - spec 7.3: the harness mounts the app at /src-app and copies it to /app; - WriteCypher: a killed process leaves its hidden temp file behind; - cypher.go header: WriteCypher is deterministic by module key order plus each builder's sort; add a byte-for-byte determinism test; - streamGraph doc: the late and tail builders are app-wide; - v2emit.Stream is not safe for concurrent use; - the streamed-script test compares row lines as a multiset keyed by statement, and checks its ReadFile error; - the parity tests name the failing fixture. Co-Authored-By: Claude Opus 5.5 --- .../specs/2026-11-24-neo4j-streaming-push.md | 2 +- internal/neo4j/cypher.go | 10 ++- internal/neo4j/cypher_test.go | 64 ++++++++++++++++--- internal/neo4j/stream.go | 4 +- internal/neo4j/stream_test.go | 4 +- internal/syntactic_analysis/v2emit/stream.go | 1 + 6 files changed, 70 insertions(+), 15 deletions(-) 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 43521b7..3b0b22e 100644 --- a/docs/design/specs/2026-11-24-neo4j-streaming-push.md +++ b/docs/design/specs/2026-11-24-neo4j-streaming-push.md @@ -172,7 +172,7 @@ The test is therefore strict, and swap cannot hide a memory problem. ### 7.3 Inputs and caches -- The test mounts each app directory read-only at `/app`. The test apps stay outside the repository. +- The test mounts each app directory read-only at `/src-app` and copies it to `/app` inside the container, because `GOFLAGS=-mod=mod` lets `go list` rewrite `go.mod` or `go.sum`, and that must not touch the host checkout. The test apps stay outside the repository. - A named volume holds the Go module cache (`GOMODCACHE`). The first run downloads the modules of the app, and later runs reuse them. - Each run starts with an empty `cango` cache, so the analysis runs in full. diff --git a/internal/neo4j/cypher.go b/internal/neo4j/cypher.go index d2b8966..a720a3e 100644 --- a/internal/neo4j/cypher.go +++ b/internal/neo4j/cypher.go @@ -27,8 +27,10 @@ import ( // keyed?). // // A static script has no view of the live DB, so it expresses the FULL truth; -// incremental updates are the Bolt writer's job (M5). Determinism: identical -// GraphRows → byte-identical script (RowBuilder.Finish already sorted the bag). +// incremental updates are the Bolt writer's job (M5). Determinism: for +// RenderCypher, identical GraphRows → byte-identical script (RowBuilder.Finish +// already sorted the bag). WriteCypher (the CLI path) streams instead, and is +// deterministic by the Source's module key order plus each RowBuilder's sort. // batchSize is the UNWIND batch size (parity with the siblings' 500). const batchSize = 500 @@ -316,7 +318,9 @@ func (c *cypherWriter) bufferNodes(nodes []NodeRow) { } // WriteCypher streams src into path. It writes a temporary file and renames it at the end, -// so a failed run leaves an earlier graph.cypher unchanged. +// so a failed run leaves an earlier graph.cypher unchanged. The temporary file is removed on +// an error return only: a process killed mid-write (SIGKILL, the OOM killer) skips the +// deferred cleanup and leaves a hidden .graph-*.cypher file next to path. func WriteCypher(src Source, path string) (nodes, edges int, err error) { env := src.Envelope() if env == nil || env.IdentityVersion != 2 || env.Application.IdentityVersion != 2 { diff --git a/internal/neo4j/cypher_test.go b/internal/neo4j/cypher_test.go index 7a7a8cb..a765c9a 100644 --- a/internal/neo4j/cypher_test.go +++ b/internal/neo4j/cypher_test.go @@ -1,12 +1,15 @@ package neo4j import ( + "bytes" "context" "maps" "os" "path/filepath" "strings" "testing" + + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" ) // M4 gate: the snapshot writer. The DDL + scoped wipe + batched node/edge MERGE @@ -149,14 +152,17 @@ func TestCypher_StreamedScriptHasTheSameRows(t *testing.T) { if _, _, err := WriteCypher(treeSource(a), path); err != nil { t.Fatalf("%s: %v", name, err) } - b, _ := os.ReadFile(path) + b, err := os.ReadFile(path) + if err != nil { + t.Fatalf("%s: %v", name, err) + } got := string(b) head := want[:strings.Index(want, "UNWIND")] if !strings.HasPrefix(got, head) { t.Errorf("%s: header differs", name) } - if w, g := rowLines(want), rowLines(got); !maps.Equal(w, g) { - t.Errorf("%s: %d row lines, want %d", name, len(g), len(w)) + if w, g := rowLines(want), rowLines(got); len(w) == 0 || !maps.Equal(w, g) { + t.Errorf("%s: %d distinct row lines, want %d", name, len(g), len(w)) } if strings.LastIndex(got, "MERGE (n:") > strings.Index(got, "MERGE (a)-[r:") { t.Errorf("%s: a node statement follows an edge statement", name) @@ -164,12 +170,28 @@ func TestCypher_StreamedScriptHasTheSameRows(t *testing.T) { } } -// rowLines is the set of UNWIND row lines, the lines that start with " {". -func rowLines(script string) map[string]bool { - out := map[string]bool{} +// rowLines is the multiset of UNWIND row lines, the lines that start with +// " {", each keyed by the statement it feeds (the lines after "] AS row" up +// to the closing ";") and counted. +func rowLines(script string) map[string]int { + out := map[string]int{} + var rows []string + stmt := "" + inStmt := false for _, l := range strings.Split(script, "\n") { - if strings.HasPrefix(l, " {") { - out[strings.TrimSuffix(l, ",")] = true + switch { + case strings.HasPrefix(l, " {"): + rows = append(rows, strings.TrimSuffix(l, ",")) + case l == "] AS row": + inStmt, stmt = true, "" + case inStmt: + stmt += l + "\n" + if strings.HasSuffix(l, ";") { + for _, r := range rows { + out[stmt+r]++ + } + rows, inStmt = rows[:0], false + } } } return out @@ -209,3 +231,29 @@ func TestWriteCypher_FailureLeavesOutput(t *testing.T) { } } } + +// TestWriteCypher_Deterministic: writing the snapshot twice for the same input +// gives byte-identical files (module key order plus each builder's sort). +func TestWriteCypher_Deterministic(t *testing.T) { + for name, a := range map[string]*v2.Analysis{ + "multipackage L2": buildMultipackageL2(t), + "dataflow L4": buildDataflowL4(t), + "chi L4": buildFixtureL4(t, "chi"), + } { + var out [2][]byte + for i := range out { + path := filepath.Join(t.TempDir(), GraphFileName) + if _, _, err := WriteCypher(treeSource(a), path); err != nil { + t.Fatalf("%s: %v", name, err) + } + b, err := os.ReadFile(path) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + out[i] = b + } + if len(out[0]) == 0 || !bytes.Equal(out[0], out[1]) { + t.Errorf("%s: two writes differ (%d and %d bytes)", name, len(out[0]), len(out[1])) + } + } +} diff --git a/internal/neo4j/stream.go b/internal/neo4j/stream.go index c7ce280..18585c9 100644 --- a/internal/neo4j/stream.go +++ b/internal/neo4j/stream.go @@ -26,7 +26,9 @@ type stager interface { // streamGraph projects src into st in two module walks. Pass 1 sends the node // rows of each module and collects the declared ids; the ghosts, stand-ins and // the application row follow once that set is complete. Pass 2 sends the edge -// rows. No step holds more than one module's rows, or one chunk of param edges. +// rows. No module step holds more than one module's rows, and the param edges +// go in chunks; the late and tail builders are app-wide, though: they hold +// every GO_CALLS row, call-graph and callee ghost, and stand-in. // Across modules a duplicate edge row may reach st; MERGE makes it a no-op. func streamGraph(src Source, st stager) (nodes, edges int, err error) { env := src.Envelope() diff --git a/internal/neo4j/stream_test.go b/internal/neo4j/stream_test.go index 0d82d65..20b87e3 100644 --- a/internal/neo4j/stream_test.go +++ b/internal/neo4j/stream_test.go @@ -185,7 +185,7 @@ func TestStream_ParityWithProject(t *testing.T) { want := Project(a) c := &collectStager{} if _, _, err := streamGraph(treeSource(a), c); err != nil { - t.Fatal(err) + t.Fatalf("%s: %v", name, err) } got := mergeRows(c.nodes, c.edgeRows) if d := diffRows(want, got); d != "" { @@ -202,7 +202,7 @@ func TestStream_ParityThroughEmitterStream(t *testing.T) { c := &collectStager{} src := v2emit.Open(in.app, in.identity, in.dir, 4, "neo4j-gate", 3, in.l3, in.l4) if _, _, err := streamGraph(src, c); err != nil { - t.Fatal(err) + t.Fatalf("%s: %v", name, err) } if d := diffRows(want, mergeRows(c.nodes, c.edgeRows)); d != "" { t.Errorf("%s: streamed rows differ from Project(Emit):\n%s", name, d) diff --git a/internal/syntactic_analysis/v2emit/stream.go b/internal/syntactic_analysis/v2emit/stream.go index a541e5a..b010017 100644 --- a/internal/syntactic_analysis/v2emit/stream.go +++ b/internal/syntactic_analysis/v2emit/stream.go @@ -11,6 +11,7 @@ import ( // Stream is the Emit payload as a module stream that a caller can walk more than one time. // Each Modules walk emits the modules again, so no walk holds the whole tree. +// A Stream is not safe for concurrent use. type Stream struct { app *schema.GoApplication e *emitter From 7ffa1a2e39a4ae81998f4428c45a32520f799efe Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Wed, 25 Nov 2026 13:47:19 -0500 Subject: [PATCH 16/16] fix(neo4j): satisfy errcheck on the snapshot writes (#59) Since the renderer writes through a scriptWriter interface instead of *strings.Builder, golangci-lint's errcheck flags every unchecked WriteString/WriteByte. Route the writes through put, which drops the error on purpose: a strings.Builder never fails, and a bufio.Writer keeps its first error and WriteCypher checks it at Flush. Co-Authored-By: Claude Opus 5.5 --- internal/neo4j/cypher.go | 46 ++++++++++++++++++++++------------------ 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/internal/neo4j/cypher.go b/internal/neo4j/cypher.go index a720a3e..48af592 100644 --- a/internal/neo4j/cypher.go +++ b/internal/neo4j/cypher.go @@ -39,9 +39,13 @@ const batchSize = 500 type scriptWriter interface { io.Writer io.StringWriter - io.ByteWriter } +// put writes s to b and drops the error: a strings.Builder never fails, and a +// bufio.Writer keeps its first error and returns it from Flush (WriteCypher +// checks it there). +func put(b scriptWriter, s string) { _, _ = b.WriteString(s) } + // RenderCypher renders the full snapshot script. appID is the application root // id used to scope the wipe; it is normally rows' application node value. func validateIdentity(rows GraphRows, appID string) error { @@ -95,7 +99,7 @@ func renderCypher(rows GraphRows, appID string) string { } func writeDDL(b scriptWriter) { - b.WriteString("// ─── constraints & indexes ───\n") + put(b, "// ─── constraints & indexes ───\n") for _, c := range UniquenessConstraints() { fmt.Fprintf(b, "CREATE CONSTRAINT %s IF NOT EXISTS FOR (n:%s) REQUIRE n.%s IS UNIQUE;\n", c.Name, c.Label, c.Property) @@ -104,7 +108,7 @@ func writeDDL(b scriptWriter) { fmt.Fprintf(b, "CREATE INDEX %s IF NOT EXISTS FOR (n:%s) ON (n.%s);\n", idx.Name, idx.Label, idx.Property) } - b.WriteByte('\n') + put(b, "\n") } // writeScopedWipe emits the DETACH DELETE scoped to this app. It refuses to emit @@ -115,18 +119,18 @@ func writeDDL(b scriptWriter) { func writeScopedWipe(b scriptWriter, appID string) { root, ok := applicationPrefix(appID) if !ok { - b.WriteString("// ─── scoped wipe SKIPPED: no bare application root id ───\n\n") + put(b, "// ─── scoped wipe SKIPPED: no bare application root id ───\n\n") return } desc := descendantPrefix(root) - b.WriteString("// ─── scoped wipe (this application only) ───\n") + put(b, "// ─── scoped wipe (this application only) ───\n") // Descendants: everything under can:////. fmt.Fprintf(b, "MATCH (n:%s) WHERE n.id STARTS WITH %s DETACH DELETE n;\n", MarkerLabel, cypherString(desc)) // The root itself is outside its own descendant prefix. fmt.Fprintf(b, "MATCH (n:%s) WHERE n.id = %s DETACH DELETE n;\n", MarkerLabel, cypherString(root)) - b.WriteByte('\n') + put(b, "\n") } // ─── node batches ───────────────────────────────────────────────────────────── @@ -135,7 +139,7 @@ func writeNodeBatches(b scriptWriter, nodes []NodeRow) { if len(nodes) == 0 { return } - b.WriteString(nodesHeader) + put(b, nodesHeader) // Group by (full label set + key prop) so one UNWIND handles a homogeneous // batch. Keys sorted for deterministic output. groups := map[string][]NodeRow{} @@ -147,7 +151,7 @@ func writeNodeBatches(b scriptWriter, nodes []NodeRow) { writeNodeChunk(b, chunk) } } - b.WriteByte('\n') + put(b, "\n") } const ( @@ -161,7 +165,7 @@ func writeNodeChunk(b scriptWriter, chunk []NodeRow) { mergeLabel := chunk[0].Labels[0] keyProp := chunk[0].KeyProp extraLabels := chunk[0].Labels[1:] - b.WriteString("UNWIND [\n") + put(b, "UNWIND [\n") for i, n := range chunk { sep := "," if i == len(chunk)-1 { @@ -169,13 +173,13 @@ func writeNodeChunk(b scriptWriter, chunk []NodeRow) { } fmt.Fprintf(b, " {k: %s, p: %s}%s\n", cypherString(n.Value), cypherMap(n.Props), sep) } - b.WriteString("] AS row\n") + put(b, "] AS row\n") fmt.Fprintf(b, "MERGE (n:%s {%s: row.k})\n", mergeLabel, keyProp) - b.WriteString("SET n += row.p") + put(b, "SET n += row.p") for _, l := range extraLabels { fmt.Fprintf(b, "\nSET n:%s", l) } - b.WriteString(";\n") + put(b, ";\n") } // ─── edge batches ───────────────────────────────────────────────────────────── @@ -184,7 +188,7 @@ func writeEdgeBatches(b scriptWriter, edges []EdgeRow) { if len(edges) == 0 { return } - b.WriteString(edgesHeader) + put(b, edgesHeader) groups := map[string][]EdgeRow{} for _, e := range edges { groups[edgeGroupKey(e)] = append(groups[edgeGroupKey(e)], e) @@ -194,7 +198,7 @@ func writeEdgeBatches(b scriptWriter, edges []EdgeRow) { writeEdgeChunk(b, chunk) } } - b.WriteByte('\n') + put(b, "\n") } // writeEdgeChunk writes one UNWIND … MERGE statement for a non-empty chunk of @@ -202,7 +206,7 @@ func writeEdgeBatches(b scriptWriter, edges []EdgeRow) { func writeEdgeChunk(b scriptWriter, chunk []EdgeRow) { e0 := chunk[0] keyed := e0.Key != "" - b.WriteString("UNWIND [\n") + put(b, "UNWIND [\n") for i, e := range chunk { sep := "," if i == len(chunk)-1 { @@ -216,7 +220,7 @@ func writeEdgeChunk(b scriptWriter, chunk []EdgeRow) { cypherString(e.From.Value), cypherString(e.To.Value), cypherString(edgeFactID(e)), cypherMap(e.Props), sep) } } - b.WriteString("] AS row\n") + put(b, "] AS row\n") fmt.Fprintf(b, "MATCH (a:%s {%s: row.a})\n", e0.From.Label, e0.From.KeyProp) fmt.Fprintf(b, "MATCH (b:%s {%s: row.b})\n", e0.To.Label, e0.To.KeyProp) if keyed { @@ -224,7 +228,7 @@ func writeEdgeChunk(b scriptWriter, chunk []EdgeRow) { } else { fmt.Fprintf(b, "MERGE (a)-[r:%s {%s: row.f}]->(b)\n", e0.Type, RelationshipFactProperty) } - b.WriteString("SET r += row.p;\n") + put(b, "SET r += row.p;\n") } // ─── streamed snapshot (#59, spec §5.4) ─────────────────────────────────────── @@ -251,7 +255,7 @@ func newCypherWriter(w *bufio.Writer, appID string) *cypherWriter { func (c *cypherWriter) begin(NodeRow) error { writeDDL(c.w) writeScopedWipe(c.w, c.appID) - c.w.WriteString(nodesHeader) + put(c.w, nodesHeader) return nil } @@ -277,8 +281,8 @@ func (c *cypherWriter) edges(edges []EdgeRow) error { return nil } if !c.inEdges { - c.w.WriteByte('\n') - c.w.WriteString(edgesHeader) + put(c.w, "\n") + put(c.w, edgesHeader) c.inEdges = true } for _, e := range edges { @@ -301,7 +305,7 @@ func (c *cypherWriter) end([]string) error { } } clear(c.edgeBuf) - c.w.WriteByte('\n') + put(c.w, "\n") return nil }