codenib.graph
¶
Graph-related modules for CodeNib.
Modules:
| Name | Description |
|---|---|
backend_alignment |
Backend-alignment checks for CodeGraph-producing indexers. |
code_graph |
|
dependency |
Dependency / impact analysis over the code call-graph. |
hierarchy |
Repo-level compound graph model for code visualization. |
incremental |
LSP-based incremental patching for CodeGraph updates. |
layers |
Layered graph views over a single :class: |
roi_subgraph |
|
setup |
Repository-aware setup diagnostics for the optional symbol graph. |
traverse_graph |
|
Classes:
| Name | Description |
|---|---|
CodeGraph |
A class to represent and manipulate a code graph using igraph. |
GraphPatcher |
Orchestrates incremental graph updates using LSP. |
LSPClient |
Synchronous LSP client that communicates with a language server via stdio. |
PatcherBase |
Base class for language-specific incremental patchers. |
MultiGraphIndex |
Layer index for a :class: |
ROISubgraph |
Region of Interest (ROI) subgraph extraction for code graphs. |
Functions:
| Name | Description |
|---|---|
build_graph_layers |
Build a layer index for |
traverse_tree_structure |
Traverse tree structure starting from a root node |
CodeGraph
¶
A class to represent and manipulate a code graph using igraph. start_line uses 0-based index.
Methods:
| Name | Description |
|---|---|
add_file_node |
Add a file node to the graph and set it as the current file and scope. |
add_symbol_node |
Add a symbol node to the graph. |
add_symbol_reference |
Add a reference to a symbol. |
update_current_scope |
Update the current scope to the given symbol with its range. |
exit_scopes_by_line |
Exit scopes that have ended based on current line number. |
add_containment_edge |
Add a containment edge from current scope to a symbol. |
batch_edges |
Defer igraph edge insertion until the block exits, flushing all |
build_range_indexes |
Rebuild per-file line-range indexes from current graph state. |
merge_from |
Merge another |
query_range |
Query the graph by source-file line range (LSP-aligned). |
query_range_by_symbol |
Range-query by symbol identity ( |
layers |
Build a multi-graph layer index over this graph. |
layer |
Return one named graph layer view. |
add_root_node |
Add the root node to the graph |
add_directory_node |
Add a directory node to the graph |
save_graph |
Save the graph to a pickle file for fast serialization. |
load_graph |
Load a graph from a pickle file. |
get_graph |
Get the igraph Graph object. |
unified_index |
Readable |
display_name |
Readable label for a canonical name ( |
resolve_symbol |
Map a readable/bare symbol to (canonical_name | None, candidates). |
get_node_info_by_name |
Get information about a node in the graph. |
get_node_info_by_id |
Get information about a node in the graph. |
get_node_content |
Get the content of a node in the graph. |
get_neighbors |
Get the neighbors of a node in the graph. |
get_successors |
Get the successors of a node_name (outgoing edges). |
get_predecessors |
Get the predecessors of a node_name (incoming edges). |
print_graph_basic_info |
Print basic information about the graph. |
visualize_graph |
Visualize the code graph with different colors for different node and edge types. |
Source code in codenib/graph/code_graph.py
add_file_node
¶
Add a file node to the graph and set it as the current file and scope.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path of the file to add |
required |
Source code in codenib/graph/code_graph.py
add_symbol_node
¶
Add a symbol node to the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Symbol name |
required | |
line
|
Line number of the symbol |
required | |
scope_start_line
|
Start line of the symbol's scope (optional) |
None
|
|
scope_end_line
|
End line of the symbol's scope (optional) |
None
|
|
symbol_type
|
Type of symbol (NODE_TYPE_CLASS, NODE_TYPE_METHOD, NODE_TYPE_FUNCTION) (optional) |
None
|
Source code in codenib/graph/code_graph.py
add_symbol_reference
¶
add_symbol_reference(
symbol,
module_path=None,
symbol_type=None,
anchor_file: str | None = None,
anchor_line: int | None = None,
)
Add a reference to a symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Symbol being referenced |
required | |
module_path
|
Path of the module containing the symbol (optional) |
None
|
|
symbol_type
|
Type of symbol (NODE_TYPE_CLASS, NODE_TYPE_METHOD, NODE_TYPE_FUNCTION) (optional) |
None
|
|
anchor_file
|
str | None
|
File where the reference site is located (optional) |
None
|
anchor_line
|
int | None
|
0-based line of the reference site (optional) |
None
|
Source code in codenib/graph/code_graph.py
update_current_scope
¶
Update the current scope to the given symbol with its range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Symbol to set as current scope |
required | |
start_line
|
Start line of the symbol's scope |
None
|
|
end_line
|
End line of the symbol's scope |
None
|
Source code in codenib/graph/code_graph.py
exit_scopes_by_line
¶
Exit scopes that have ended based on current line number. File scope (with None range) is never popped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_line
|
Current line number being processed |
required |
Source code in codenib/graph/code_graph.py
add_containment_edge
¶
Add a containment edge from current scope to a symbol.
CONTAIN edges deliberately carry no anchor — containment is a
structural relation, not a call/reference site. (See anchor invariant
ii on query_range.)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_symbol
|
Symbol being contained. |
required |
Source code in codenib/graph/code_graph.py
batch_edges
¶
Defer igraph edge insertion until the block exits, flushing all
buffered edges in a single add_edges call.
igraph rebuilds its internal adjacency index on every add_edges
call, so inserting one edge at a time (as bare _add_edge does) is
O(E^2) in the number of edges — the dominant cost when decoding a large
repo. Wrapping a build loop in this context collapses that to O(E):
with graph.batch_edges():
# ... many add_symbol_reference / _add_edge calls ...
Edge dedup is unaffected (the dedup index is updated as edges are
buffered). Edge ids returned by _add_edge while buffering are
provisional and only become real after flush; no caller relies on them
mid-build. Outside this block _add_edge inserts immediately, so the
incremental patcher and all other callers are unchanged. Nesting is a
no-op (the outermost block owns the flush).
Source code in codenib/graph/code_graph.py
build_range_indexes
¶
Rebuild per-file line-range indexes from current graph state.
Call this after the graph is fully constructed by a decoder, and
again after any incremental patcher batch. The two indexes are
pickled with the graph by save_graph, so subsequent load_graph
calls do not need to rebuild.
Cost: O(V + E) — one linear pass over vertices and edges.
Source code in codenib/graph/code_graph.py
merge_from
¶
merge_from(other: CodeGraph) -> None
Merge another CodeGraph into this one.
Vertices are keyed by their canonical name attribute. Existing
vertices receive any attributes from other; missing vertices are
inserted. Edges are copied through _add_edge so structural edge
deduplication and anchored reference multi-edges keep the same
semantics as decoder-built graphs.
Source code in codenib/graph/code_graph.py
query_range
¶
query_range(
file: str,
start_line: int,
end_line: int,
kinds: set | None = None,
depth: int = 1,
*,
layer: str | None = None
) -> RangeQueryResult
Query the graph by source-file line range (LSP-aligned).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
str
|
source file (graph-relative path). |
required |
start_line
|
int
|
first line of the inclusive 0-based span. |
required |
end_line
|
int
|
last line of the inclusive 0-based span. |
required |
kinds
|
set | None
|
edge kinds to include in |
None
|
depth
|
int
|
reserved for future multi-hop expansion. Only |
1
|
layer
|
str | None
|
optional named graph layer ( |
None
|
Returns: RangeQueryResult with typed NodeRef/EdgeRef records.
Anchor invariants
(i) anchor_file == source.file (anchor lives at the call site, never the target). (ii) anchor_* is meaningful only on EDGE_TYPE_REFERENCE; CONTAIN edges leave both fields None. (iii) outgoing ∩ incoming = ∅ for any single query (call site and target are in distinct scopes by definition).
Source code in codenib/graph/code_graph.py
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 | |
query_range_by_symbol
¶
query_range_by_symbol(
name: str, kinds: set | None = None, depth: int = 1, *, layer: str | None = None
) -> RangeQueryResult
Range-query by symbol identity (name).
Resolves name -> vid -> (file, start_line, end_line) and forwards
to query_range. name is the globally-unique identity attribute
(semi-raw SCIP symbol), not the unified_name display.
Returns an empty RangeQueryResult if the symbol is unknown or has no associated file/range (e.g. a SCIP reference-only vertex).
Source code in codenib/graph/code_graph.py
layers
¶
layer
¶
add_root_node
¶
add_directory_node
¶
save_graph
¶
Save the graph to a pickle file for fast serialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
Path to save the pickle file |
required |
Source code in codenib/graph/code_graph.py
load_graph
classmethod
¶
Load a graph from a pickle file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
Path to the pickle file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
CodeGraph |
Loaded graph instance |
Source code in codenib/graph/code_graph.py
get_graph
¶
unified_index
¶
Readable unified_name (full + bare) -> [canonical names], cached.
Rebuilds from vertex attributes when the persisted _unified_to_names
is empty (older prebuilt graphs ship it empty even though every vertex
carries a unified_name).
Source code in codenib/graph/code_graph.py
display_name
¶
Readable label for a canonical name (unified_name or itself).
resolve_symbol
¶
Map a readable/bare symbol to (canonical_name | None, candidates).
Tries the canonical name first, then the readable unified_name
(full display, then bare token), then a substring match. None when
ambiguous or missing; candidates are readable display names.
Source code in codenib/graph/code_graph.py
get_node_info_by_name
¶
Get information about a node in the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_name
|
Name of the node |
required |
Returns:
| Type | Description |
|---|---|
|
Dictionary with vertex attributes or None if not found |
Source code in codenib/graph/code_graph.py
get_node_info_by_id
¶
Get information about a node in the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_id
|
ID of the node |
required |
Returns:
| Type | Description |
|---|---|
|
Dictionary with vertex attributes or None if not found |
Source code in codenib/graph/code_graph.py
get_node_content
¶
Get the content of a node in the graph. Read the file from start_line to end_line. If the node is a file, return the file content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_id
|
ID of the node |
required |
Returns:
| Type | Description |
|---|---|
|
Content of the node or None if not found |
Source code in codenib/graph/code_graph.py
get_neighbors
¶
Get the neighbors of a node in the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_name
|
Name of the node |
required |
Returns:
| Type | Description |
|---|---|
|
List of neighbor vertex IDs |
Source code in codenib/graph/code_graph.py
get_successors
¶
Get the successors of a node_name (outgoing edges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_name
|
Name of the node |
required | |
edge_types
|
Optional edge types to retain. Typed traversal returns unique neighbors even when the graph contains multi-edges. |
None
|
Returns:
| Type | Description |
|---|---|
|
List of successor vertex IDs |
Source code in codenib/graph/code_graph.py
get_predecessors
¶
Get the predecessors of a node_name (incoming edges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_name
|
Name of the node |
required | |
edge_types
|
Optional edge types to retain. Typed traversal returns unique neighbors even when the graph contains multi-edges. |
None
|
Returns:
| Type | Description |
|---|---|
|
List of predecessor vertex IDs |
Source code in codenib/graph/code_graph.py
print_graph_basic_info
¶
Print basic information about the graph.
Source code in codenib/graph/code_graph.py
visualize_graph
¶
Visualize the code graph with different colors for different node and edge types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
Path to save the visualization (optional) |
None
|
|
width
|
Width of the plot in pixels |
800
|
|
height
|
Height of the plot in pixels |
600
|
|
layout
|
Layout algorithm to use ('fruchterman_reingold', 'kk', 'grid', etc.) |
'fruchterman_reingold'
|
Returns:
| Type | Description |
|---|---|
|
A matplotlib figure object if output_path is not provided |
Source code in codenib/graph/code_graph.py
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 | |
GraphPatcher
¶
GraphPatcher(
project_root: str, code_graph: CodeGraph | None, language: str, mode: str = "symbol"
)
Orchestrates incremental graph updates using LSP.
Thin router that delegates to language-specific PatcherBase subclasses.
Usage::
graph = CodeGraph.load_graph("graph.pkl")
patcher = GraphPatcher("/path/to/project", graph, "rust")
changed = GraphPatcher.detect_changed_files(
"/path/to/project", "abc123", "HEAD"
)
stats = patcher.patch_files(changed)
graph.save_graph("graph.pkl")
Methods:
| Name | Description |
|---|---|
start_lsp |
Start the LSP server for warm-up. |
stop_lsp |
Stop the LSP server. |
patch_files |
Apply incremental patch for all changed files. |
detect_changed_files |
Detect changed files between two commits. |
get_changed_line_ranges |
Get line ranges changed between two commits. |
Source code in codenib/graph/incremental/graph_patcher.py
start_lsp
¶
stop_lsp
¶
patch_files
¶
detect_changed_files
staticmethod
¶
detect_changed_files(
project_root: str,
base_commit: str,
target_commit: str = "HEAD",
extensions: set[str] | None = None,
) -> dict
Detect changed files between two commits.
Source code in codenib/graph/incremental/graph_patcher.py
get_changed_line_ranges
staticmethod
¶
get_changed_line_ranges(
project_root: str, file_path: str, base_commit: str, target_commit: str = "HEAD"
) -> list[tuple[int, int, int, int]]
Get line ranges changed between two commits.
Each hunk is reported as (old_start, old_end, new_start, new_end) in 0-indexed inclusive form so callers can compare line counts.
Source code in codenib/graph/incremental/graph_patcher.py
LSPClient
¶
LSPClient(
command: list[str],
project_root: str,
language: str,
init_options: dict | None = None,
)
Synchronous LSP client that communicates with a language server via stdio.
Usage::
with LSPClient(["rust-analyzer"], "/path/to/project", "rust") as client:
symbols = client.document_symbol("src/main.rs")
refs = client.references("src/main.rs", 10, 4)
Methods:
| Name | Description |
|---|---|
start |
Start the LSP server and send initialize/initialized. |
shutdown |
Gracefully shut down the LSP server. |
open_document |
Send textDocument/didOpen for a file (idempotent). |
close_document |
Send textDocument/didClose for a file. |
wait_for_analysis |
Wait for the LSP server to finish analyzing a file. |
document_symbol |
Get hierarchical document symbols for a file. |
semantic_tokens_full |
Get semantic tokens for the entire file. |
semantic_tokens_range |
Get semantic tokens for a specific line range. |
decode_semantic_tokens |
Decode semantic tokens response into a list of token dicts. |
drain_notifications |
Drain any pending notifications without waiting for a response. |
wait_until_idle |
Wait until no |
get_lsp_command |
Get the default LSP server command for a language. |
check_lsp_available |
Check if the LSP server binary is available. |
Source code in codenib/graph/incremental/lsp_client.py
start
¶
Start the LSP server and send initialize/initialized.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
skip_probe
|
bool
|
If True, skip the blocking readiness probe. Use this when starting early for warm-up — the server will analyze the project in the background. |
False
|
Source code in codenib/graph/incremental/lsp_client.py
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
shutdown
¶
Gracefully shut down the LSP server.
Source code in codenib/graph/incremental/lsp_client.py
open_document
¶
Send textDocument/didOpen for a file (idempotent).
Source code in codenib/graph/incremental/lsp_client.py
close_document
¶
Send textDocument/didClose for a file.
Source code in codenib/graph/incremental/lsp_client.py
wait_for_analysis
¶
Wait for the LSP server to finish analyzing a file.
After didOpen/didChange, servers like pyright need time to re-analyze before references() returns correct results. We poll with a lightweight hover request until it responds quickly, indicating analysis is complete.
Source code in codenib/graph/incremental/lsp_client.py
document_symbol
¶
Get hierarchical document symbols for a file.
Default retries=0 — null is a legitimate "no symbols" answer
per LSP spec. Previous default of 5 retries × 5s sleep wasted up
to 25s/call when servers returned null. If the server is still
loading at warmup time, callers should wait at the call-site,
not inside this primitive.
Source code in codenib/graph/incremental/lsp_client.py
semantic_tokens_full
¶
Get semantic tokens for the entire file.
Returns raw response with data field (delta-encoded integers).
Use decode_semantic_tokens() to decode.
Returns None on timeout or error (details logged by _request).
Default timeout 15s: a server that needs longer is pathological (basedpyright on sklearn's test_pls.py used to take 60s). The patcher tolerates None — that file simply skips outgoing-ref discovery for this run. 60s × N pathological files dominated runtime before this cap.
Source code in codenib/graph/incremental/lsp_client.py
semantic_tokens_range
¶
semantic_tokens_range(
file_path: str, start_line: int, end_line: int, timeout: float = 30
) -> dict | None
Get semantic tokens for a specific line range.
Faster than full for large files when only a small range is needed. Returns None if not supported or on error.
Source code in codenib/graph/incremental/lsp_client.py
decode_semantic_tokens
¶
Decode semantic tokens response into a list of token dicts.
Each token dict has: line, character, length, token_type, modifiers, text.
Source code in codenib/graph/incremental/lsp_client.py
drain_notifications
¶
Drain any pending notifications without waiting for a response.
Returns the number of messages drained. Used by wait_until_idle
to keep the progress map fresh while polling.
Source code in codenib/graph/incremental/lsp_client.py
wait_until_idle
¶
Wait until no $/progress tokens are active for idle_grace_s.
Returns True if the server became idle within max_wait_s,
False on timeout. Useful before timed regions so background
indexing (rust-analyzer cache priming, gopls workspace load,
basedpyright type analysis) doesn't bleed into measurements.
Source code in codenib/graph/incremental/lsp_client.py
get_lsp_command
staticmethod
¶
Get the default LSP server command for a language.
Source code in codenib/graph/incremental/lsp_client.py
check_lsp_available
staticmethod
¶
Check if the LSP server binary is available.
Source code in codenib/graph/incremental/lsp_client.py
PatcherBase
¶
PatcherBase(
project_root: str,
code_graph: CodeGraph,
lsp_client: LSPClient | None = None,
mode: str = "symbol",
)
Bases: SubgraphMgr
Base class for language-specific incremental patchers.
Inherits SubgraphMgr for subgraph operations. Adds: - patch_files: top-level entry point - _rebuild_prepare_vertices / _rebuild_connect_edges: full rebuild for added/renamed - _incremental_prepare_vertices / _incremental_connect_edges: symbol-level diff - _classify_symbols, _remap_severed_edges, etc.
Subclasses must implement: - _build_unified_name: construct unified_name from LSP symbol info - _get_crossfile_token_types: which semanticToken types to query
Subclasses may override: - get_lsp_command: custom LSP server command - _language_id: custom LSP language id - flatten_symbols: convert LSP documentSymbol to flat dict (default provided) - get_old_symbols: extract old symbols from graph (default provided) - GRAPH_SYMBOL_KINDS: which SymbolKinds to process (default provided)
"symbol"(default): the actual symbol-level incremental patcher."naive": file-granularity baseline used by the sequential benchmark (issue #129). For modified files, every old symbol is classified as deleted and every new symbol as added — no shifted / affected / unchanged / invisible buckets. Untouched files are still left alone. Only the classifier behaviour changes; the rest of the pipeline (LSP queries, edge reconnection) is identical to symbol mode, which is exactly what makes it the right A/B comparison.
Methods:
| Name | Description |
|---|---|
get_lsp_command |
Return the LSP server command for this language. |
flatten_symbols |
Convert LSP documentSymbol to flat {unified_name: metadata} dict. |
get_old_symbols |
Extract existing definition vertices from the graph for a file. |
start_lsp |
Start the LSP server, resolving binary path. |
stop_lsp |
Stop the LSP server. |
patch_files |
Apply incremental patch for all changed files. |
Source code in codenib/graph/incremental/patcher_base.py
get_lsp_command
¶
Return the LSP server command for this language.
Source code in codenib/graph/incremental/patcher_base.py
flatten_symbols
abstractmethod
¶
Convert LSP documentSymbol to flat {unified_name: metadata} dict.
Must filter by GRAPH_SYMBOL_KINDS and handle language-specific naming (e.g. Rust impl blocks, Go pointer receivers).
Source code in codenib/graph/incremental/patcher_base.py
get_old_symbols
¶
Extract existing definition vertices from the graph for a file.
Default implementation: returns symbols with valid start_line (skips SCIP reference-only vertices). Override for language-specific filtering.
Source code in codenib/graph/incremental/patcher_base.py
start_lsp
¶
Start the LSP server, resolving binary path.
Source code in codenib/graph/incremental/patcher_base.py
stop_lsp
¶
patch_files
¶
Apply incremental patch for all changed files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
changed_files
|
dict
|
dict with modified/added/deleted/renamed lists. |
required |
earlier_commit
|
str
|
base commit (required for modified files). |
None
|
later_commit
|
str
|
target commit. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Stats dict. |
Source code in codenib/graph/incremental/patcher_base.py
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | |
MultiGraphIndex
¶
MultiGraphIndex(
code_graph: CodeGraph,
specs: Mapping[str, GraphLayerSpec] | None = None,
*,
use_core: bool = True
)
Layer index for a :class:CodeGraph.
The index stores edge-id lists per layer. Layers can overlap; today every
reference edge also belongs to dependency and all.
Source code in codenib/graph/layers.py
ROISubgraph
¶
ROISubgraph(code_graph: CodeGraph)
Region of Interest (ROI) subgraph extraction for code graphs.
This class takes search results from CodeSearchEngine and extracts a focused subgraph containing the most relevant code elements and their neighborhood.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code_graph
|
CodeGraph
|
The full code graph from which to extract subgraphs |
required |
Methods:
| Name | Description |
|---|---|
expand_ppr |
Expand seed nodes using Personalized PageRank. |
extract_subgraph |
Extract a subgraph around specified node names. |
get_filtered_subgraph_nodes |
Extract useful nodes from a subgraph, filtering out nodes where |
get_node_info_by_id |
Get information about a node in the original graph. |
get_node_content |
Get the content of a node in the original graph. |
Source code in codenib/graph/roi_subgraph.py
expand_ppr
¶
expand_ppr(
node_names: list[str],
top_k: int = 50,
damping: float = 0.85,
filter_tests: bool = True,
) -> list[NodeInfo]
Expand seed nodes using Personalized PageRank.
Runs PPR on the full graph with seed nodes as the personalization vector, then returns the top-k nodes ranked by PPR score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_names
|
list[str]
|
Seed node names (e.g. from BM25). |
required |
top_k
|
int
|
Maximum number of nodes to return. |
50
|
damping
|
float
|
PPR damping factor (0–1). Higher = more global. |
0.85
|
filter_tests
|
bool
|
Whether to exclude test files. |
True
|
Returns:
| Type | Description |
|---|---|
list[NodeInfo]
|
List of NodeInfo objects sorted by PPR score (descending). |
Source code in codenib/graph/roi_subgraph.py
extract_subgraph
¶
extract_subgraph(
node_names: list[str],
k_hop: int = 2,
edge_types: list[str] | None = None,
direction: str = "both",
) -> Graph
Extract a subgraph around specified node names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_names
|
list[str]
|
List of node names to use as seeds for the subgraph |
required |
k_hop
|
int
|
Number of hops to expand from each seed node |
2
|
edge_types
|
list[str] | None
|
Optional list of edge types to consider (None for all types) |
None
|
direction
|
str
|
Direction to traverse - "forward", "backward", or "both" |
'both'
|
Returns:
| Type | Description |
|---|---|
Graph
|
An igraph Graph object representing the extracted subgraph |
Source code in codenib/graph/roi_subgraph.py
get_filtered_subgraph_nodes
¶
get_filtered_subgraph_nodes(
subgraph: Graph,
exclude_nodes: list[str] | None = None,
filter_tests: bool = True,
node_types: list[str] | None = None,
) -> list[NodeInfo]
Extract useful nodes from a subgraph, filtering out nodes where start_line equals end_line (unless explicitly included).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subgraph
|
Graph
|
An igraph Graph object (from extract_subgraph or extract_roi_from_search_results) |
required |
node_types
|
list[str] | None
|
Optional list of node types to include (None for all types) |
None
|
Returns:
| Type | Description |
|---|---|
list[NodeInfo]
|
List of NodeInfo objects including the node content |
Source code in codenib/graph/roi_subgraph.py
get_node_info_by_id
¶
get_node_info_by_id(node_id: int) -> NodeInfo
Get information about a node in the original graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_id
|
int
|
ID of the node in the original graph |
required |
Returns:
| Type | Description |
|---|---|
NodeInfo
|
NodeInfo containing the node attributes |
Source code in codenib/graph/roi_subgraph.py
get_node_content
¶
Get the content of a node in the original graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_id
|
int
|
ID of the node in the original graph |
required |
Returns: The content of the node, or None if not available
Source code in codenib/graph/roi_subgraph.py
build_graph_layers
¶
build_graph_layers(
code_graph: CodeGraph,
specs: Mapping[str, GraphLayerSpec] | None = None,
*,
use_core: bool = True
) -> MultiGraphIndex
Build a layer index for code_graph.
Source code in codenib/graph/layers.py
traverse_tree_structure
¶
traverse_tree_structure(
code_graph: CodeGraph,
root,
direction="downstream",
hops=2,
node_type_filter: list[str] | None = None,
edge_type_filter: list[str] | None = None,
)
Traverse tree structure starting from a root node
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code_graph
|
CodeGraph
|
CodeGraph instance |
required |
root
|
Root node ID to start traversal from |
required | |
direction
|
'downstream', 'upstream', or 'both' |
'downstream'
|
|
hops
|
Maximum number of hops to traverse (-1 for unlimited) |
2
|
|
node_type_filter
|
list[str] | None
|
Filter by node types |
None
|
edge_type_filter
|
list[str] | None
|
Filter by edge types |
None
|
Returns:
| Type | Description |
|---|---|
|
String representation of the tree structure |
Source code in codenib/graph/traverse_graph.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | |