Documentation
¶
Overview ¶
Package graph answers "what is reachable from here" over the code knowledge graph, under bounds the caller sets and the results honestly declare.
It is the substrate for impact analysis, callers/callees and the context engine. Three properties shape every decision in this package:
Bounded, and honest about it ¶
A traversal that quietly stops at a limit and returns a partial answer as if it were complete is worse than an error: an impact analysis built on it under-reports risk, and nothing downstream can tell. So every Result carries Truncated and a reason, and both are set whenever the answer is not the complete reachable set — including when the caller's own MaxDepth is what cut it short.
Confidence survives the walk ¶
Edges carry confidence (see model.Confidence). Expanding through a guess and then presenting a depth-3 result as fact compounds uncertainty into a claim nothing supports. Every Node therefore reports the MINIMUM confidence along the path that reached it, so a caller can tell "definitely reachable" from "possibly reachable" without re-deriving it.
One query per level, never one per node ¶
The performance requirement is not decoration: a 10,920-file tree yields ~94k symbols and hundreds of thousands of edges, and this package sits in front of an interactive agent. The traversal is therefore level-synchronous — each BFS frontier becomes a single indexed `src_id IN (...)` query (chunked to stay inside SQLite's variable limit), so a depth-3 walk costs 3 round trips, not one per node discovered. A node-at-a-time DFS over the same data is the obvious implementation and is two orders of magnitude slower.
Memory is bounded by the result, not the graph: nothing here materialises the edge table, and rows are consumed through a callback as they are scanned.
Measured performance ¶
From bench_test.go on a 100k-symbol / 500k-edge fixture (Apple M-series, -benchtime 30x), p95 wall time for a depth-3 walk from 100 roots:
MaxNodes 1,000 -> 2.9ms MaxNodes 10,000 -> 39.6ms MaxNodes 50,000 -> 86.5ms (28,193 nodes reached)
The 500ms budget is met with an order of magnitude to spare at any node cap a caller should be using. It is NOT met by the one shape that ignores the bound: Direction=Both, depth 3, no filters, no effective node cap reaches 99,821 of the 100,000 symbols in 1.6s. That is a whole-graph load wearing a traversal's clothes, and the honest conclusion is that MaxNodes, not depth, is what keeps this interactive — which is why it defaults to a small value rather than to unlimited.
Hub pruning ¶
Query.HubDegreeLimit refuses to expand THROUGH nodes wider than a limit, which is the largest accuracy win available here and, incidentally, a performance one. On the same fixture, the depth-3 impact walk above:
unpruned -> 81.4ms p50, 28,193 nodes HubDegreeLimit 50 -> 35.8ms p50, 7,699 nodes
It is OFF by default, and the default path issues no extra queries.
Query.HubPercentile derives that limit from the run's own distribution instead, in one grouped and ranked pass over the edge table. That pass costs ~476ms on 500k edges — alone more than this package's whole latency budget — so it is memoised per (run, filters) on the Graph and a warm percentile walk costs the same 36.1ms as an explicit limit. A caller that constructs a fresh Graph per request pays the 476ms every time and should pass an explicit HubDegreeLimit.
A Graph performs no database writes and is safe for concurrent use.
Index ¶
- Constants
- Variables
- func EdgeCost(c model.Confidence) int
- func PathCost(confs []model.Confidence) int
- type CSREdge
- type CSRGraph
- type Direction
- type EdgeRecord
- type Graph
- func (g *Graph) Callees(ctx context.Context, symbolID int64, minConf model.Confidence) ([]Neighbour, error)
- func (g *Graph) Callers(ctx context.Context, symbolID int64, minConf model.Confidence) ([]Neighbour, error)
- func (g *Graph) LoadCSR(ctx context.Context, runID int64) (*CSRGraph, error)
- func (g *Graph) Neighbours(ctx context.Context, symbolID int64, dir Direction, kinds []model.EdgeKind, ...) ([]Neighbour, error)
- func (g *Graph) NeighboursDetailed(ctx context.Context, symbolID int64, dir Direction, kinds []model.EdgeKind, ...) (NeighboursResult, error)
- func (g *Graph) Paths(ctx context.Context, from, to int64, maxPaths, maxDepth int) ([][]int64, error)
- func (g *Graph) PathsMatching(ctx context.Context, from, to int64, maxPaths, maxDepth int, ...) ([][]int64, error)
- func (g *Graph) PathsMatchingVia(ctx context.Context, from, via, to int64, maxPaths, maxDepth int, ...) ([][]int64, error)
- func (g *Graph) PathsThrough(ctx context.Context, from int64, waypoints []int64, to int64, ...) ([][]int64, error)
- func (g *Graph) Traverse(ctx context.Context, q Query) (Result, error)
- func (g *Graph) Warm(ctx context.Context) error
- type Neighbour
- type NeighboursResult
- type Node
- type Option
- type PrunedHub
- type Query
- type Result
Constants ¶
const ( DefaultMaxDepth = 3 DefaultMaxNodes = 1000 )
Default bounds applied when a Query leaves them unset.
The defaults are deliberately small. An unbounded traversal over a real repository's edge table is not a slow query, it is an out-of-memory condition, and a caller that forgot to set a limit should get a usable answer with Truncated set rather than take the process down.
const DefaultMaxNeighbours = 50_000
DefaultMaxNeighbours is a defensive memory ceiling on single-node neighbour scans to prevent out-of-memory states on extreme hub symbols (e.g. Object, fmt.Stringer).
const DefaultMaxPaths = 10
DefaultMaxPaths bounds Paths when the caller passes no limit. An agent asking "how does A reach B" wants a handful of concrete routes, not an enumeration.
const MaxWaypoints = 4
MaxWaypoints bounds how many intermediate symbols one path query may name. Each waypoint is one more bounded search, so the bound keeps the query's cost a small multiple of a single path search.
Variables ¶
var ErrNeighboursTruncated = errors.New("graph: neighbours capped at limit")
ErrNeighboursTruncated is reported when neighbours query exceeds the safety ceiling.
Functions ¶
func EdgeCost ¶
func EdgeCost(c model.Confidence) int
EdgeCost returns the traversal cost of crossing one edge of this confidence.
An unset or unrecognised confidence costs as much as low. Treating unknown provenance as proven is the failure this guards: a new edge kind that forgets to set confidence would otherwise silently become the cheapest path in the graph.
func PathCost ¶
func PathCost(confs []model.Confidence) int
PathCost sums the cost of a walk. Zero edges cost zero.
Types ¶
type CSREdge ¶
type CSREdge struct {
Target int32
Kind model.EdgeKind
Confidence model.Confidence
}
CSREdge is one directed hop in the in-memory graph index.
type CSRGraph ¶
type CSRGraph struct {
// contains filtered or unexported fields
}
CSRGraph is an in-memory Compressed Sparse Row graph for high-throughput traversals. It maps symbol IDs to dense contiguous 32-bit indices and stores edge arrays in flat contiguous slices, achieving sub-millisecond graph traversals over hundreds of thousands of edges with zero garbage-collector overhead.
func NewCSRGraph ¶
func NewCSRGraph(runID int64, records []EdgeRecord) (*CSRGraph, error)
NewCSRGraph constructs an in-memory Compressed Sparse Row representation from a slice of edges. It returns an error if the graph is too large for int32 indexing.
type Direction ¶
type Direction int
Direction selects which way edges are followed.
const ( // Outgoing follows edges away from the root: "what does this reach". Outgoing Direction = iota // Incoming follows edges into the root: "what reaches this". This is the // direction impact analysis needs — changing a symbol affects its callers, // not its callees. Incoming // Both treats the graph as undirected. Useful for blast-radius questions // where a shared dependency matters regardless of arrow direction. Both )
type EdgeRecord ¶
EdgeRecord is a raw edge loaded from storage or memory.
type Graph ¶
type Graph struct {
// contains filtered or unexported fields
}
Graph is a read-only traversal facade over one index run's edges.
func New ¶
New returns a Graph that reads whichever run is currently committed.
Resolving the run per call rather than at construction is deliberate: a Graph held by a long-lived MCP server would otherwise keep answering from a run that CommitRun has already deleted out from under it.
func NewForRun ¶
NewForRun pins a Graph to a specific run, committed or not. Intended for doctor-style tooling that must inspect a staging run; query paths should use New so invariant 3 (readers see only committed runs) holds automatically.
func (*Graph) Callees ¶
func (g *Graph) Callees(ctx context.Context, symbolID int64, minConf model.Confidence) ([]Neighbour, error)
Callees returns the symbols symbolID calls.
func (*Graph) Callers ¶
func (g *Graph) Callers(ctx context.Context, symbolID int64, minConf model.Confidence) ([]Neighbour, error)
Callers returns the symbols that call symbolID — the direction that answers "who breaks if I change this".
func (*Graph) LoadCSR ¶
LoadCSR reads all edges for runID from the graph's database into an in-memory CSRGraph snapshot. It streams edges in two passes directly from SQLite:
- Pass 1 streams (src_id, dst_id) to map node IDs and compute degree counts, calculating offsets and pre-allocating exact-size edge buffers.
- Pass 2 streams (src_id, dst_id, kind, confidence) directly into outEdges and inEdges, avoiding holding all intermediate EdgeRecord structs in memory simultaneously with CSRGraph.
func (*Graph) Neighbours ¶
func (g *Graph) Neighbours( ctx context.Context, symbolID int64, dir Direction, kinds []model.EdgeKind, minConf model.Confidence, ) ([]Neighbour, error)
Neighbours returns the symbols one edge away from symbolID.
This is a separate path from Traverse because depth 1 is overwhelmingly the most common request and does not need any of the traversal machinery: no visited set, no frontier, no path arithmetic. It is a single indexed lookup on idx_edges_src or idx_edges_dst.
func (*Graph) NeighboursDetailed ¶
func (g *Graph) NeighboursDetailed( ctx context.Context, symbolID int64, dir Direction, kinds []model.EdgeKind, minConf model.Confidence, ) (NeighboursResult, error)
NeighboursDetailed returns the symbols one edge away from symbolID with explicit truncation state.
func (*Graph) Paths ¶
func (g *Graph) Paths(ctx context.Context, from, to int64, maxPaths, maxDepth int) ([][]int64, error)
Paths returns up to maxPaths shortest routes from `from` to `to`, each a slice of symbol ids beginning with from and ending with to.
Only SHORTEST paths are returned. This is a bound, not an oversight: the number of distinct paths between two nodes in a dense code graph is exponential, so any complete answer is unusable, and the most direct routes are what actually explains a relationship. A longer, more circuitous route that happens to exist will not appear.
An unreachable target is not an error; it returns no paths.
The search is the same level-synchronous expansion Traverse uses — one query per depth, not one per node — with the predecessors of each newly discovered node recorded. Enumeration then walks that layered DAG backwards from `to`. Because every node in it was discovered by BFS, every backward step reaches a strictly shallower node and every walk terminates at `from`: the enumeration never backtracks out of a dead end, so producing maxPaths routes costs O(maxPaths x depth) rather than an exponential search.
func (*Graph) PathsMatching ¶
func (g *Graph) PathsMatching(ctx context.Context, from, to int64, maxPaths, maxDepth int, kinds []model.EdgeKind, minConf model.Confidence, exclude func(id int64) bool) ([][]int64, error)
PathsMatching returns up to maxPaths shortest directed routes from `from` to `to`, filtered by edge kinds, minimum confidence, and excluded nodes.
func (*Graph) PathsMatchingVia ¶
func (g *Graph) PathsMatchingVia( ctx context.Context, from, via, to int64, maxPaths, maxDepth int, kinds []model.EdgeKind, minConf model.Confidence, exclude func(id int64) bool, ) ([][]int64, error)
PathsMatchingVia returns up to maxPaths shortest directed routes from `from` to `to` optionally through `via`, filtered by edge kinds, minimum confidence, and excluded nodes.
func (*Graph) PathsThrough ¶
func (g *Graph) PathsThrough( ctx context.Context, from int64, waypoints []int64, to int64, maxPaths, maxDepth int, kinds []model.EdgeKind, minConf model.Confidence, exclude func(id int64) bool, ) ([][]int64, error)
PathsThrough returns up to maxPaths directed routes from `from` to `to` that pass through every waypoint, in order. Each leg is a shortest-path search with the same kinds, confidence floor and exclusions; legs are joined only where the result revisits no symbol, and the whole route must fit maxDepth. With no waypoints it is PathsMatching.
func (*Graph) Traverse ¶
Traverse walks the graph outward from q.Roots within the bounds in q.
Semantics worth knowing before relying on the output:
Each node is visited once, at its SHALLOWEST depth. Cycles therefore terminate and diamonds are not double-counted.
Node.Confidence is the strongest path-minimum among the shortest paths to that node. A longer path built from stronger edges is not preferred, so a node's reported confidence can be weaker than the best that exists in the graph. That bias is intentional and one-directional: this package will under-claim certainty, never over-claim it.
func (*Graph) Warm ¶
Warm loads what traversals of the current run read, the CSR snapshot, if they read one and it is not loaded yet. A caller about to run many traversals calls it to overlap that load with work of its own; it changes no answer. A Graph that traverses through SQL has nothing to load.
type Neighbour ¶
type Neighbour struct {
SymbolID int64 `json:"symbol_id"`
Kind model.EdgeKind `json:"kind"`
Confidence model.Confidence `json:"confidence"`
Evidence model.Evidence `json:"evidence"`
}
Neighbour is one directly connected symbol and the edge that connects it.
Unlike Node this carries full evidence. Depth-1 results are small and are what an agent shows a human, so the file and line that justify the relationship are worth the extra columns — a relationship the caller cannot verify is an assertion.
type NeighboursResult ¶
type NeighboursResult struct {
Neighbours []Neighbour `json:"neighbours"`
Truncated bool `json:"truncated"`
TruncatedReason string `json:"truncated_reason,omitempty"`
}
NeighboursResult carries the neighbours of a symbol and whether the result was truncated.
type Node ¶
type Node struct {
SymbolID int64 `json:"symbol_id"`
// Depth is hops from the nearest root. Roots are 0.
Depth int `json:"depth"`
// Via is the edge kind of the final hop that reached this node. Empty for
// roots.
Via model.EdgeKind `json:"via,omitempty"`
// Confidence is the MINIMUM confidence along the path that reached this
// node — how strongly the reachability itself is believed, not how strongly
// any one edge is. Roots are exact because a root is an input, not an
// inference.
Confidence model.Confidence `json:"confidence"`
// contains filtered or unexported fields
}
Node is one reachable symbol.
It deliberately carries no evidence. A node is usually reachable by many edges, so there is no single location that justifies it; use Neighbours or Paths when the caller needs to show its work.
func (Node) Cost ¶
Cost is the accumulated EdgeCost of the path recorded for this node.
It is exposed as a read-only accessor, not a field, because it is not a score to present to a reader: the units are arbitrary and deliberately uncalibrated (see cost.go). It exists so a caller that re-groups or merges Nodes — impact's diff path merges one traversal per changed symbol — can reproduce Result.finish's ranking instead of inventing a second one. A caller that only consumes Nodes in the order given never needs it.
type PrunedHub ¶
type PrunedHub struct {
SymbolID int64 `json:"symbol_id"`
// Degree is the number of edges this node has in the direction(s) being
// traversed, counted under the same kind and confidence filters as the
// walk itself — so it is the number of hops actually declined, not a
// context-free property of the node.
Degree int `json:"degree"`
// Depth is the hop count at which the node sat when it was refused.
Depth int `json:"depth"`
}
PrunedHub records one node whose expansion was refused.
It is a struct of ints rather than a list of ids because a bare id does not let the caller act. Degree is what a caller needs to choose the next limit ("400 wide, and I asked for 50"), and Depth says where in the walk the hole is — a hub refused at depth 1 hid far more than one refused at the last level. SymbolID is int64 to match Node.SymbolID: identity in this package is the symbols table's primary key, not a rendered name, and formatting an id into a string here would force every caller to parse it back to look the symbol up.
type Query ¶
type Query struct {
// Roots are the symbols to start from. They are returned as depth-0 nodes.
// Duplicates and unknown ids are harmless.
Roots []int64
// Kinds restricts which edge kinds may be traversed. Empty means all.
Kinds []model.EdgeKind
// MinConfidence excludes weaker edges from expansion entirely, so they
// neither appear in the result nor contribute paths through themselves.
// Zero value means no threshold.
MinConfidence model.Confidence
// MaxDepth bounds hops from the nearest root. <= 0 uses DefaultMaxDepth.
MaxDepth int
// MaxNodes is a hard cap on returned nodes, roots included. <= 0 uses
// DefaultMaxNodes. Hitting it sets Truncated.
MaxNodes int
// Direction selects which way edges are followed.
Direction Direction
// HubDegreeLimit stops the walk from expanding THROUGH a node whose degree
// exceeds it. The node is still reported — it is reachable and the caller
// should see it — but its neighbours are not explored.
//
// This is the cheapest accuracy win available here. A depth-3 walk that
// crosses a logging helper reaches most of the repository and returns an
// answer that is technically correct and practically useless. Cutting the
// traversal beats cutting the response, because by the time the response is
// cut the walk has already been paid for.
//
// Zero disables pruning, and disabling it is the default: an existing
// caller's results must not change under it. Roots are never pruned — a
// caller asking about a hub must still get its neighbours.
HubDegreeLimit int
// HubPercentile derives HubDegreeLimit from the run's own degree
// distribution when HubDegreeLimit is zero — 0.99 means "wider than 99% of
// nodes in this index". A fixed limit does not transfer between a
// 5k-symbol service and a 500k-symbol monolith; a percentile does.
//
// The derived value is floored at minHubDegree, because the widest node in
// a narrow graph is not a hub. Values outside (0,1] are an error rather
// than a silent clamp: a caller who wrote 99 meaning 99% has a bug, and
// quietly pruning at the maximum degree would hide it.
HubPercentile float64
}
Query describes one bounded traversal.
type Result ¶
type Result struct {
// Nodes is ordered by (Depth, SymbolID) so output is stable across runs.
Nodes []Node `json:"nodes"`
// Truncated reports that the reachable set is larger than what Nodes
// contains. It is set for the caller's own MaxDepth as well as for
// MaxNodes: a bound the caller chose still produces an incomplete answer,
// and anything computing a risk score from this needs to know.
//
// TruncatedReason states every bound that fired, joined by "; ". That
// separator is RESERVED: it separates independent reasons and appears
// nowhere inside one. A caller that aggregates many walks — impact's diff
// path merges one per changed symbol — splits on it to count each fact
// once, and a "; " inside a single sentence would split that sentence in
// half and report the two halves as separate facts with different counts.
Truncated bool `json:"truncated"`
TruncatedReason string `json:"truncated_reason,omitempty"`
// PrunedHubs names every node whose expansion was refused by
// Query.HubDegreeLimit, ordered by (Depth, SymbolID) so runs agree. A
// traversal that quietly declined to explore somewhere is the same failure
// as one that quietly hit a limit: the caller cannot tell a complete answer
// from a bounded one. Empty unless hub pruning was asked for.
PrunedHubs []PrunedHub `json:"pruned_hubs,omitempty"`
}
Result is a traversal's answer plus an honest account of its completeness.