Documentation
¶
Overview ¶
Package diffgraph compares two committed index runs and reports what CHANGED ABOUT THE CODE'S FACTS, not about its lines.
A line diff says "these 40 lines moved". This package says: this endpoint now writes `refunds`; this symbol lost its last caller; this CALLS edge fell from `exact` to `high` because the compiler stopped proving it; this table gained a writer. Those are answers a reviewer can act on without reading the patch.
Why this is sound here and nowhere else ¶
A graph delta between two runs is only meaningful if the two runs are themselves reproducible. Otherwise "this edge disappeared" may mean the code changed, or may mean the second run's worker pool interleaved differently.
GraphLume already proves the stronger property. `registry.RegistryDigest` is a sha256 over one run's content that is stable across 1/2/4/8 workers and sensitive to a single added symbol (docs/architecture.md, "The determinism digest"). Three of its rules are what make this package possible:
- Order independence — rows are read under an explicit total ORDER BY over content columns, never by rowid.
- No synthetic identity — autoincrement ids are excluded, and edges reference their endpoints by (file path, fqn, start line, start col) rather than by src_id/dst_id, which are allocation artefacts that legitimately differ between two identical runs.
- No timestamps — content is covered by content_hash and size instead.
This package inherits rule two exactly: every identity below is content-based and no comparison ever touches a row id. A delta therefore means "the code changed" rather than "the scheduler differed" — a guarantee an LLM-backed competitor, whose two passes over the same repository do not even agree with each other, cannot offer.
Where the comparison key deliberately DIVERGES from the digest key ¶
The digest and the diff want opposite things from position.
The digest hashes (path, fqn, start line, start col) because its job is to flip on ANY content change — a symbol that moved is a different digest, and that is correct for a reproducibility gate.
The diff's job is the opposite: a symbol that moved down ten lines because somebody added an import is THE SAME SYMBOL. If the diff called it removed-and-added, a one-line import would produce a thousand-line report and the feature would be noise. So position is demoted from identity to attribute:
symbol identity = (file path, fqn, kind [, ordinal]) symbol attribute = start/end position, signature, exported, confidence edge identity = (src symbol identity, dst symbol identity, edge kind) edge attribute = confidence, evidence sites
A position change on a matched key is reported as Moved. A confidence change on a matched edge key is reported as a transition with a direction, because `exact -> high` means a compiler stopped proving something and is worth surfacing on its own — it is invisible to every line-based tool.
Ordinal exists only for the rare case where one file legitimately holds several symbols sharing (fqn, kind); it is assigned in position order so a uniform shift still matches. Its known limit is recorded on SymbolKey.
Honesty about what could not be compared ¶
A missing edge is not always a code change. If either run was `degraded`, or a file's parse status was not `ok`, or the two runs were indexed in different accuracy modes (a run without a compiler index cannot produce `exact` at all), then an absence may be an indexing gap. Report.Caveats states this explicitly and individual changes carry Uncertain. Saying so is the difference between a diff and a guess.
Bounding ¶
A diff across distant commits can be enormous. Every section is sorted by a total content order and then capped; Report.Truncations records exactly how many entries each section omitted, so a bounded report never silently lies about its own completeness.
Where the two runs come from ¶
registry.CommitRun publishes a run and DELETES the rows of the one it replaces, so a single index database holds exactly one committed run. The two sides of a real `graphlume diff <ref>..<ref>` therefore normally live in two index files — the working index and a second index built at the other ref — which is why Compare takes a Side (source + run id) per end rather than one source and two ids. Two runs inside one store work equally well; nothing here assumes either arrangement.
Determinism of the output itself ¶
Identical inputs produce a byte-identical Report and a byte-identical Render. No ordering decision anywhere in this package iterates a Go map; maps are used for lookup only, and every emitted sequence is derived from an explicitly sorted slice.
Example (RefundEndpoint) ¶
Example_refundEndpoint shows the shape of the output for the change the package doc leads with: a route that now writes a table, a call the compiler stopped proving, and a helper that lost its last caller.
It doubles as a determinism check the toolchain enforces for free: go test compares this output byte for byte, so any map iteration that reached an ordering decision would make it flake.
src := newFakeSource()
newRun(src, 1, 0, model.StatusReady, "v1.4.0", "exact").
file("pkg/api.go", "ok").
file("pkg/service.go", "ok").
file("db/schema.sql", "ok").
sym("pkg/api.go", "pkg/api.go:GET /refunds", "GET /refunds", model.KindEndpoint, 10).
sym("pkg/api.go", "pkg/api.go:handleRefund", "handleRefund", model.KindFunction, 20).
sym("pkg/service.go", "pkg/service.go:Refund", "Refund", model.KindMethod, 5).
sym("pkg/service.go", "pkg/service.go:legacyRefund", "legacyRefund", model.KindMethod, 80).
sym("db/schema.sql", "db/schema.sql:refunds", "refunds", model.KindTable, 1).
edge("pkg/api.go:handleRefund", "pkg/service.go:Refund", model.EdgeCalls,
model.ConfidenceExact, model.SourceCompiler, "pkg/api.go", 22).
edge("pkg/api.go:handleRefund", "pkg/service.go:legacyRefund", model.EdgeCalls,
model.ConfidenceExact, model.SourceCompiler, "pkg/api.go", 23).
edge("pkg/service.go:Refund", "db/schema.sql:refunds", model.EdgeReads,
model.ConfidenceHigh, model.SourceSourceCode, "pkg/service.go", 8).
endpoint("GET /refunds", "pkg/api.go", 10, "handleRefund", "pkg/api.go").
table("refunds", true, 1, 0)
newRun(src, 2, 9_000, model.StatusReady, "v1.5.0", "exact").
file("pkg/api.go", "ok").
file("pkg/service.go", "ok").
file("db/schema.sql", "ok").
sym("pkg/api.go", "pkg/api.go:GET /refunds", "GET /refunds", model.KindEndpoint, 12).
sym("pkg/api.go", "pkg/api.go:handleRefund", "handleRefund", model.KindFunction, 22).
sym("pkg/service.go", "pkg/service.go:Refund", "Refund", model.KindMethod, 5).
sym("pkg/service.go", "pkg/service.go:legacyRefund", "legacyRefund", model.KindMethod, 80).
sym("db/schema.sql", "db/schema.sql:refunds", "refunds", model.KindTable, 1).
edge("pkg/api.go:handleRefund", "pkg/service.go:Refund", model.EdgeCalls,
model.ConfidenceHigh, model.SourceSourceCode, "pkg/api.go", 24).
edge("pkg/service.go:Refund", "db/schema.sql:refunds", model.EdgeWrites,
model.ConfidenceHigh, model.SourceSourceCode, "pkg/service.go", 9).
endpoint("GET /refunds", "pkg/api.go", 12, "handleRefundV2", "pkg/api.go").
table("refunds", true, 0, 1)
d, err := New()
if err != nil {
fmt.Println(err)
return
}
rep, err := d.Compare(context.Background(),
Side{Source: src, RunID: 1}, Side{Source: src, RunID: 2})
if err != nil {
fmt.Println(err)
return
}
if err := Render(os.Stdout, rep); err != nil {
fmt.Println(err)
}
Output: diff v1.4.0..v1.5.0 (runs 1..2) base: status=ready accuracy=exact digest=- head: status=ready accuracy=exact digest=- SYMBOLS moved pkg/api.go:GET /refunds (endpoint) line 10 -> 12 (+2) moved pkg/api.go:handleRefund (function) line 20 -> 22 (+2) orphaned pkg/service.go:legacyRefund (method) inbound 1 -> 0 EDGES downgraded pkg/api.go:handleRefund (function) -[CALLS]-> pkg/service.go:Refund (method) exact -> high was: exact/compiler at pkg/api.go:22:4 now: high/source_code at pkg/api.go:24:4 removed pkg/api.go:handleRefund (function) -[CALLS]-> pkg/service.go:legacyRefund (method) exact/compiler at pkg/api.go:23:4 removed pkg/service.go:Refund (method) -[READS]-> db/schema.sql:refunds (table) high/source_code at pkg/service.go:8:4 added pkg/service.go:Refund (method) -[WRITES]-> db/schema.sql:refunds (table) high/source_code at pkg/service.go:9:4 ENDPOINTS handler GET /refunds (pkg/api.go): pkg/api.go:handleRefund -> pkg/api.go:handleRefundV2 TABLES changed refunds readers 1 -> 0 (-1), writers 0 -> 1 (+1) COULD NOT COMPARE nothing: both runs were complete and comparable
Index ¶
- Constants
- func Render(w io.Writer, r *Report) error
- type Caveats
- type ChangeKind
- type Differ
- type Direction
- type EdgeChange
- type EdgeFact
- type EdgeKey
- type EndpointChange
- type EndpointFact
- type EndpointKey
- type IndexSource
- type Option
- type Report
- type RunInfo
- type Side
- type Site
- type SymbolChange
- type SymbolFact
- type SymbolKey
- type TableChange
- type TableFact
- type Truncation
Examples ¶
Constants ¶
const ( DefaultMaxPerSection = 200 DefaultMaxEvidenceSites = 3 DefaultMaxCaveatPaths = 25 )
Defaults for the bounds. A diff across distant commits is unbounded in principle, and an unbounded report is unreadable and unshippable.
Variables ¶
This section is empty.
Functions ¶
func Render ¶
Render writes a report as plain text.
It lives here rather than in the CLI for one reason: byte-identical output is a property of this package and has to be testable without a terminal. The CLI is free to format differently, but if it does, this is the reference for what "deterministic" meant.
Every line is derived from the already-sorted sections, so two calls on equal reports produce equal bytes.
Types ¶
type Caveats ¶
type Caveats struct {
// Comparable is false when a run is in a state where absence proves
// nothing at all (failed, or still indexing).
Comparable bool `json:"comparable"`
// DigestsEqual means the two runs hashed identically under
// registry.RegistryDigest, in which case the change sections MUST be
// empty; if they are not, the comparison itself is wrong and Notes says so.
DigestsEqual bool `json:"digests_equal"`
// Notes are human-readable, emitted in a fixed order.
Notes []string `json:"notes,omitempty"`
// UnreliablePaths are files whose parse status was not "ok" in at least
// one run. Bounded; UnreliableFiles is the true count.
UnreliablePaths []string `json:"unreliable_paths,omitempty"`
UnreliableFiles int `json:"unreliable_files"`
// DanglingEdges counts edges whose endpoint symbol was not present in the
// same run. They are excluded from the comparison rather than silently
// counted as removals.
DanglingEdges int `json:"dangling_edges,omitempty"`
}
Caveats is the report's statement of what it could NOT compare.
This section is not decoration and it is not optional. If one run was `degraded`, a missing edge may be an indexing gap rather than a deleted call. If the two runs used different accuracy modes, every confidence transition in the report may describe the indexer rather than the code — a run with no compiler index cannot emit `exact` at all. A tool that presented those two situations identically to a clean comparison would be guessing.
type ChangeKind ¶
type ChangeKind string
ChangeKind names one class of semantic difference. Grouping is by the THING that changed — a symbol, an edge, an endpoint, a table — not by the file it lives in, because "this endpoint now writes refunds" is the sentence a reviewer needs and "12 lines changed in PaymentController.java" is not.
const ( SymbolAdded ChangeKind = "symbol_added" SymbolRemoved ChangeKind = "symbol_removed" SymbolMoved ChangeKind = "symbol_moved" SymbolOrphaned ChangeKind = "symbol_orphaned" // lost its last inbound reference EdgeAdded ChangeKind = "edge_added" EdgeRemoved ChangeKind = "edge_removed" EdgeConfidenceChanged ChangeKind = "edge_confidence_changed" EndpointAdded ChangeKind = "endpoint_added" EndpointRemoved ChangeKind = "endpoint_removed" EndpointHandlerChanged ChangeKind = "endpoint_handler_changed" TableAccessAdded ChangeKind = "table_access_added" TableAccessRemoved ChangeKind = "table_access_removed" TableAccessChanged ChangeKind = "table_access_changed" )
type Differ ¶
type Differ struct {
// contains filtered or unexported fields
}
Differ compares two index runs.
Holds no mutable state at all: the sources arrive per call and the snapshots and report are per-Compare locals, so one Differ is safe to share across goroutines and cannot leak facts from one comparison into the next.
func (*Differ) Compare ¶
Compare diffs base (the older side) against head (the newer side).
Comparing a run against itself returns a report where Empty() is true. That is the property the whole feature rests on: if a run does not compare equal to itself, every other output is noise. There is deliberately no short-circuit for "same source, same run id" — the equal case is loaded and compared like any other, so the property is actually tested rather than asserted by an early return.
type Direction ¶
type Direction string
Direction records which way a confidence transition went. `exact -> high` is a downgrade and is the interesting one: a compiler stopped proving a relationship that it used to prove, and no line-based tool can see that.
type EdgeChange ¶
type EdgeChange struct {
Change ChangeKind `json:"change"`
Key EdgeKey `json:"key"`
From *EdgeFact `json:"from,omitempty"`
To *EdgeFact `json:"to,omitempty"`
Direction Direction `json:"direction,omitempty"`
Uncertain bool `json:"uncertain,omitempty"`
Reason string `json:"reason,omitempty"`
}
EdgeChange is one difference about one relationship.
type EdgeFact ¶
type EdgeFact struct {
Confidence model.Confidence `json:"confidence"`
Source model.SourceType `json:"source"`
Sites []Site `json:"sites,omitempty"` // bounded sample, sorted
SiteCount int `json:"site_count"`
}
EdgeFact is everything the diff reports ABOUT a relationship.
Confidence is the STRONGEST of the edges that collapsed into this fact. If a compiler proves one of two call sites, the relationship is proven; reporting the weaker value would understate what is known.
type EdgeKey ¶
type EdgeKey struct {
Src SymbolKey `json:"src"`
Dst SymbolKey `json:"dst"`
Kind model.EdgeKind `json:"kind"`
}
EdgeKey is a relationship's content identity: which two entities, and what kind of relationship. Confidence and evidence are attributes, so a compiler that stops proving a call reports as a transition on one fact rather than as a removal plus an addition of two unrelated ones.
Several edges of the same kind between the same pair (two call sites in one function) collapse into ONE fact, because "A calls B" is one fact about the code. The sites are retained on EdgeFact and counted.
type EndpointChange ¶
type EndpointChange struct {
Change ChangeKind `json:"change"`
Key EndpointKey `json:"key"`
From *EndpointFact `json:"from,omitempty"`
To *EndpointFact `json:"to,omitempty"`
}
EndpointChange is one difference about one route.
type EndpointFact ¶
type EndpointFact struct {
Line int `json:"line"`
// Handlers is the sorted set of "path:name" handlers the route exposes.
// A set rather than a scalar because a route may resolve to more than one
// EXPOSES edge, and an empty set is meaningful: the route is real, its
// target simply was not revealed by the framework's syntax.
Handlers []string `json:"handlers,omitempty"`
Detail string `json:"detail,omitempty"`
}
EndpointFact is the mutable half of an endpoint.
type EndpointKey ¶
EndpointKey identifies an HTTP endpoint by the route as the framework spells it plus the file that declares it. The handler is an attribute, so re-pointing a route at a different function is a change to one endpoint rather than the disappearance of one and the arrival of another.
func (EndpointKey) String ¶
func (k EndpointKey) String() string
type IndexSource ¶
type IndexSource interface {
Run(ctx context.Context, id int64) (*model.IndexRun, error)
Files(ctx context.Context, runID int64) ([]model.File, error)
Symbols(ctx context.Context, runID int64) ([]model.Symbol, error)
Edges(ctx context.Context, runID int64) ([]model.Edge, error)
// TopLevelCalls is the calls made outside every definition and the
// synthetic per-file callers that make them.
TopLevelCalls(ctx context.Context, runID int64) (registry.TopLevel, error)
EndpointReport(ctx context.Context, runID int64) ([]registry.Endpoint, error)
TableUsageReport(ctx context.Context, runID int64) ([]registry.TableUsage, error)
}
IndexSource is the port this package needs from the index, declared here at the consumer rather than imported as a concrete type — docs/development.md §1 and §3, and the pattern already set by internal/context/ports.go.
Six methods, and each one is load-bearing for a class of fact this package classifies:
- Run supplies status, accuracy mode and digest. Without it the report could not state what it was unable to compare, which is the difference between a diff and a guess.
- Files supplies the id->path map (symbols carry a file id, not a path) AND per-file parse status, which is what marks a change uncertain.
- Symbols and Edges are the graph itself.
- EndpointReport and TableUsageReport are the two derived views the product already exposes; recomputing them from edges here would duplicate a join that internal/registry owns.
HONEST LIMIT, in the same spirit as internal/context/ports.go: the last two signatures name registry.Endpoint and registry.TableUsage, so this package still imports internal/registry for those DTOs and `go list -deps` still reaches the SQLite driver transitively. What the port buys is substitutability and testability — every behavioural test in this package runs against a hand-built fake and never opens a database. Severing the transitive import would mean relocating those DTOs into pkg/model, which is a change to a package this work does not own.
type Option ¶
Option configures a Differ. Functional options per docs/development.md §2 — the alternative is a config struct that grows a field per caller.
func WithMaxCaveatPaths ¶
WithMaxCaveatPaths caps the sample of unreliable file paths.
func WithMaxEvidenceSites ¶
WithMaxEvidenceSites caps how many evidence sites each edge fact carries.
func WithMaxPerSection ¶
WithMaxPerSection caps how many changes each section reports.
type Report ¶
type Report struct {
Base RunInfo `json:"base"`
Head RunInfo `json:"head"`
Symbols []SymbolChange `json:"symbols,omitempty"`
Edges []EdgeChange `json:"edges,omitempty"`
Endpoints []EndpointChange `json:"endpoints,omitempty"`
Tables []TableChange `json:"tables,omitempty"`
Caveats Caveats `json:"caveats"`
Truncations []Truncation `json:"truncations,omitempty"`
}
Report is the whole comparison. Identical inputs produce a byte-identical Report and a byte-identical Render.
type RunInfo ¶
type RunInfo struct {
RunID int64 `json:"run_id"`
Status model.IndexStatus `json:"status"`
GitRevision string `json:"git_revision,omitempty"`
AccuracyMode string `json:"accuracy_mode,omitempty"`
Digest string `json:"digest,omitempty"`
Files int64 `json:"files"`
Symbols int64 `json:"symbols"`
Edges int64 `json:"edges"`
// ParseFailures is why a missing fact may not be a code change.
ParseFailures int64 `json:"parse_failures"`
}
RunInfo is the identifying half of one side of the comparison.
type Side ¶
type Side struct {
Source IndexSource
RunID int64
}
Side names one end of the comparison: which index to read, and which run inside it.
Source is per-side rather than per-Differ because of a fact about the registry that the CLI has to live with: CommitRun retires the previous committed run and deletes its rows, so ONE index database holds exactly one committed run. The two sides of `graphlume diff <ref>..<ref>` therefore normally live in two databases — the working index and a second index built at the other ref. Nothing here assumes they share a store, and nothing assumes they do not: two Sides over the same *registry.Registry with two run ids is equally valid.
type Site ¶
type Site struct {
Path string `json:"path"`
Line int `json:"line"`
Col int `json:"col"`
Detail string `json:"detail,omitempty"`
}
Site is one piece of evidence for an edge fact.
type SymbolChange ¶
type SymbolChange struct {
Change ChangeKind `json:"change"`
Key SymbolKey `json:"key"`
// From and To are the evidence on each side. Exactly one is nil for an
// addition or a removal; both are set for a move or an orphaning.
From *SymbolFact `json:"from,omitempty"`
To *SymbolFact `json:"to,omitempty"`
// LineDelta is set for a move: how far the definition shifted. A
// cross-file move also sets FromKey.
LineDelta int `json:"line_delta,omitempty"`
FromKey *SymbolKey `json:"from_key,omitempty"`
// Uncertain marks a change whose file did not parse cleanly in one of the
// runs, so the difference may be an indexing gap rather than a code change.
Uncertain bool `json:"uncertain,omitempty"`
Reason string `json:"reason,omitempty"`
}
SymbolChange is one difference about one symbol.
type SymbolFact ¶
type SymbolFact struct {
Path string `json:"path"`
FQN string `json:"fqn"`
Kind model.EntityKind `json:"kind"`
Name string `json:"name"`
Start model.Position `json:"start"`
End model.Position `json:"end"`
Signature string `json:"signature,omitempty"`
Exported bool `json:"exported"`
Confidence model.Confidence `json:"confidence"`
Source model.SourceType `json:"source"`
// Inbound counts distinct referencing edge facts pointing at this symbol.
// Structural containment and provenance edges are excluded — see
// isReferencingEdge.
Inbound int `json:"inbound"`
}
SymbolFact is everything the diff reports ABOUT a symbol, as opposed to the part of it that establishes identity (SymbolKey).
type SymbolKey ¶
type SymbolKey struct {
Path string `json:"path"`
FQN string `json:"fqn"`
Kind model.EntityKind `json:"kind"`
Ordinal int `json:"ordinal,omitempty"`
}
SymbolKey is a symbol's content identity.
It is deliberately NOT the digest's symbol key. The digest hashes position because any content change must flip it; this key excludes position because a symbol that moved is still the same symbol. See the package doc.
KNOWN LIMIT of Ordinal: it disambiguates several symbols sharing (path, fqn, kind) inside one file, assigned in position order. Migration 0001 makes (path, fqn, start_line) unique, so duplicates are rare; when they do occur and one of them is deleted, the survivor inherits the lower ordinal and is reported as moved rather than as "the other one was removed". That is a strictly quieter failure than the alternative, and it is recorded here rather than assumed away.
func (SymbolKey) String ¶
String renders the key for display. The path prefix is dropped when the FQN already carries it — model.DefaultFQN is path-qualified, so printing both gives "pkg/api.go:pkg/api.go:handleRefund". Identity is unaffected; this is presentation only, and it stays a pure function of the key so the rendered report remains deterministic.
type TableChange ¶
type TableChange struct {
Change ChangeKind `json:"change"`
Table string `json:"table"`
From *TableFact `json:"from,omitempty"`
To *TableFact `json:"to,omitempty"`
ReadersDelta int `json:"readers_delta,omitempty"`
WritersDelta int `json:"writers_delta,omitempty"`
}
TableChange is one difference about one table's access profile.
type TableFact ¶
type TableFact struct {
// Declared is false for a table this repository uses but does not own.
Declared bool `json:"declared"`
Readers int `json:"readers"`
Writers int `json:"writers"`
Accesses int `json:"accesses"`
Uncertain int `json:"uncertain"`
}
TableFact aggregates one table's access profile across the whole run.
type Truncation ¶
type Truncation struct {
Section string `json:"section"`
Shown int `json:"shown"`
Total int `json:"total"`
Omitted int `json:"omitted"`
OrderedBy string `json:"ordered_by"`
}
Truncation records that a section was capped, and by how much. A bounded report that did not say so would be indistinguishable from a complete one.