grapher.DependencyGraph
Mutable workbook dependency graph.
Usage
grapher.DependencyGraph()Node identity is the canonical sheet-qualified cell address (CellKey). get_node(key) looks up that exact stored key.
get_dependencies / get_dependents / get_edge_attrs return endpoints exactly as stored. Topology is uint32 CSR+CSC after rebuild_adjacency; _edges / _reverse_edges are a mutation staging buffer and are empty once compact. Edge guards and provenance are nnz-parallel intern-id arrays beside CSR; _guards / _edge_provenance are the same kind of staging buffer and are empty once compact. Missing adjacency is empty (no per-node empty set()). resolve_endpoint / get_dependency_nodes resolve to stored cell keys when present (evaluation order, export, codegen). Rebuild drops non-node endpoints.
formula_shapes is an optional acceleration overlay from warm_formula_shapes (unset by default). Node.formula_ast is authoritative; eval and codegen fall back to AST when the overlay is missing. Compression, formula rewrite, and JSON/pickle load drop it (None). Callers who want shapes again must rewarm; a live FormulaEvaluator does not pick up a rewarm automatically.
Parameter Attributes
_nodes: dict[NodeKey, Node] = dict()_edges: dict[NodeKey, set[NodeKey]] = dict()_reverse_edges: dict[NodeKey, set[NodeKey]] = dict()_staging: bool = True_csr_keys: list[NodeKey] = list()_node_index: dict[NodeKey, int] = dict()_row_ptr: array.array[int] = _empty_uint32()_col_idx: array.array[int] = _empty_uint32()_col_ptr: array.array[int] = _empty_uint32()_row_idx: array.array[int] = _empty_uint32()_guard_id: array.array[int] = _empty_uint32()_prov_id: array.array[int] = _empty_uint32()_guard_exprs: list[GuardExpr | None] = _empty_guard_intern()_provenances: list[EdgeProvenance | None] = _empty_prov_intern()_guards: dict[EdgeKey, GuardExpr] = dict()_edge_provenance: dict[EdgeKey, EdgeProvenance] = dict()_hooks: list[NodeHook] = list()leaf_classification: dict[str, str] | None = Nonesheet_order: list[str] | None = Nonesheet_bounds: dict[str, tuple[int, int]] | None = Nonenamed_ranges: dict[str, tuple[str, str]] | None = Nonenamed_range_ranges: dict[str, tuple[str, str, str]] | None = Nonepreparsed_formulas: dict[str, AstNode] | None = Noneformula_shapes: FormulaShapeTable | None = Nonecell_type_env: CellTypeEnv | None = Nonedomains: SeriesDomainIndex | None = None_domains_handle: Any = None_value_generation: int = 0
Methods
| Name | Description |
|---|---|
| __deepcopy__() | Clone without going through the pickle blob reduce path. |
| __reduce_ex__() | Pickle via a multipart blob so unpickle peak stays near final size. |
| add_edge() | Add edge: from_key depends on to_key (from_key -> to_key). |
| attach_domains() | Attach a lazy series-domain index without rebuilding the graph. |
| compress_identity_transits() | Remove identity transit nodes and rewire dependents. |
| compress_optimal() | Remove identity transits and inline single-call-site formula nodes. |
| consistency_issues() | Return structured formula/edge/flag disagreements (empty if consistent). |
| copy() | Return a deep copy of this graph (node hooks are not copied). |
| cycle_report() | Classify must-cycles vs may-cycles, dropping guard-infeasible SCCs. |
| domain_for() | Return the bindings-owned domain for key, if one is attached. |
| edge_count() | Return the number of stored dependency edges. |
| evaluation_order() | Return nodes in dependency-first order (leaves before formulas that use them). |
| formula_keys() | Return sorted list of keys for nodes that contain formulas. |
| formula_nodes() | Iterate over (key, node) pairs for nodes that contain formulas. |
| get_dependencies() | Return an immutable snapshot of key’s dependencies (cells it reads). |
| get_dependency_nodes() | Return dependencies that exist as stored graph node keys. |
| get_dependents() | Return an immutable snapshot of cells that depend on key. |
| get_edge_attrs() |
Return a typed snapshot of the attributes on edge from_key -> to_key.
|
| get_edge_guard() |
Return the guard on edge from_key -> to_key, or None if none.
|
| get_node() |
Return an immutable NodeView snapshot, or None if missing.
|
| is_guarded() |
Return whether edge from_key -> to_key carries a guard.
|
| keys() |
Return node keys from source (or the graph) using the selected order.
|
| leaf_keys() | Return sorted list of keys for nodes with no dependency edges (leaves). |
| leaf_node_items() | Iterate over (key, node) pairs for leaf nodes (no cell dependencies). |
| leaves() | Iterate over keys of leaf nodes (no dependencies). |
| move_node() | Move a node to a new cell, preserving resolved formula targets. |
| rebuild_adjacency() | Materialize CSR+CSC from current topology and drop dict maps. |
| remove_node() | Remove a node and all of its incident edges. |
| replace_node_formula() | Replace a node’s formula and rewire outgoing edges from extraction. |
| resolve_endpoint() | Map an edge endpoint to a stored node key when present. |
| roots() | Iterate keys with no in-graph dependents. |
| set_node_ast() |
Set a node’s formula from formula_ast.
|
| set_node_formula() |
Set a node’s formula and parse it into formula_ast.
|
| set_node_metadata() | Replace a node’s metadata mapping durably. |
| set_node_value() |
Set a node’s value field durably. Raises KeyError if missing.
|
| target_keys() | Return sorted list of keys marked as original build targets. |
| validate_consistency() | Raise GraphConsistencyError if formulas, edges, or flags disagree. |
__deepcopy__()
Clone without going through the pickle blob reduce path.
Usage
__deepcopy__(memo)__reduce_ex__()
Pickle via a multipart blob so unpickle peak stays near final size.
Usage
__reduce_ex__(protocol)add_edge()
Add edge: from_key depends on to_key (from_key -> to_key).
Usage
add_edge(from_key, to_key, *, guard=None, provenance=None)Endpoints are stored as given (after normalize_key). Member-cell keys are allowed; callers that need owner nodes should resolve via resolve_endpoint / get_dependency_nodes.
Re-adding an existing edge merges guards with or_guard and merges provenance via merge_edge_provenance. Omitting provenance on a re-add leaves any existing provenance unchanged.
attach_domains()
Attach a lazy series-domain index without rebuilding the graph.
Usage
attach_domains(bindings, *, workbook=None, bindings_path=None)Parameters
bindings: Mapping[str, Any]-
Loaded (merged) series binding manifest.
workbook: Path | str | None = None-
Workbook path for range expansion and
from_workbookreads. bindings_path: Path | str | None = None- Sidecar path stored on the pickle/JSON handle.
Returns
SeriesDomainIndex-
The attached SeriesDomainIndex (also exposed as
cell_type_env).
compress_identity_transits()
Remove identity transit nodes and rewire dependents.
Usage
compress_identity_transits(*, preserve=None, record=None)Transit nodes whose formula is a single cell reference to one dependency are removed, dependents’ formulas are rewritten, and edges are rewired. Requires dependency provenance from graph construction with capture_dependency_provenance=True for safe edges.
Identity forwarding rewrites CellRefNode leaves only. If a dependent mentions the transit as a RangeNode endpoint or a whole-column/row leaf, the transit is left in place so the formula cannot keep naming a removed node and range geometry is not rewritten.
Skips is_target nodes and any keys in preserve so public extraction and series-bound addresses stay in the graph.
Node hooks are not invoked for removed or updated nodes. Drops formula_shapes; callers who want the overlay must rewarm after compression. write_workbook persists this rewrite into a new .xlsx; prefer IdentityTransitCompression().project when the canonical graph must stay unchanged.
Parameters
preserve: set[NodeKey] | None = None-
Node keys that must not be forwarded. Always unioned with target_keys() so marked targets stay public.
record: IdentityTransitCompressionRecord | None = None- When provided, populate with removal lineage for projection manifests.
Returns
list[NodeKey]- Keys of removed transit nodes, in removal order.
compress_optimal()
Remove identity transits and inline single-call-site formula nodes.
Usage
compress_optimal(*, preserve=None, record=None)Collapses nodes when substitution is safe. Both identity-transit forwarding and formula inlining skip is_target nodes and any keys in preserve (external consumers such as series-bound public addresses). Forwarding targets are also protected from later inlining. Identity forwarding is cell-ref-only: a transit mentioned as a range endpoint or whole-column/row leaf is left in place. Drops formula_shapes; callers who want the overlay must rewarm after compression. write_workbook persists this rewrite into a new .xlsx; prefer OptimalCompression().project when the canonical graph must stay unchanged.
Parameters
preserve: set[NodeKey] | None = None-
Node keys that must not be collapsed (forwarded or inlined). Always unioned with target_keys() so marked targets stay public.
record: OptimalCompressionRecord | None = None- When provided, populate with removal lineage for projection.
Returns
list[NodeKey]- Keys of removed nodes, in removal order.
consistency_issues()
Return structured formula/edge/flag disagreements (empty if consistent).
Usage
consistency_issues()copy()
Return a deep copy of this graph (node hooks are not copied).
Usage
copy()cycle_report()
Classify must-cycles vs may-cycles, dropping guard-infeasible SCCs.
Usage
cycle_report(*, cell_type_env=None)When cell_type_env is omitted, uses self.cell_type_env (set by create_dependency_graph from DynamicRefConfig). Identity-formula cells are rewritten to their copied cell before guards are conjoined, so singleton leaf domains apply through aliases. Guard comparisons are first decided, where possible, from an affine/interval abstraction of the guard cells (GuardConeAbstraction).
Each may-cycle is a residual component: the cyclic part of an SCC left after dropping edges whose guard alone is infeasible, and that still contains a guard-feasible cycle. It can be smaller than the SCC of the full graph.
The env is the whole contract for leaf values: a leaf with a declared domain ranges over it, even when the workbook holds a literal there, and a leaf without one is unconstrained. Cycle analysis never assumes a leaf keeps its workbook value; pin such a leaf with a singleton domain (for example Literal[0]) to make it a constant.
domain_for()
Return the bindings-owned domain for key, if one is attached.
Usage
domain_for(key)edge_count()
Return the number of stored dependency edges.
Usage
edge_count()evaluation_order()
Return nodes in dependency-first order (leaves before formulas that use them).
Usage
evaluation_order(*, strict=True, iterate_enabled=None, cell_type_env=None)Edge direction is A -> B meaning A depends on B. This method returns an ordering suitable for sequential evaluation (dependencies first).
If iterate_enabled is True (workbook has iterative calculation on), any must-cycle or may-cycle is rejected: generated Python does not emulate Excel’s iterative convergence. Pass False or None to apply the usual strict / non-strict rules without this check.
cell_type_env is forwarded to cycle_report so leaf-domain constraints can prove guarded cycles infeasible.
formula_keys()
Return sorted list of keys for nodes that contain formulas.
Usage
formula_keys()formula_nodes()
Iterate over (key, node) pairs for nodes that contain formulas.
Usage
formula_nodes()Formula cells are identified by has_formula (formula_ast or unparseable formula text). normalized_formula is a derived view.
get_dependencies()
Return an immutable snapshot of key’s dependencies (cells it reads).
Usage
get_dependencies(key)Endpoints are returned exactly as stored. Use get_dependency_nodes when only endpoints that exist as graph nodes are required.
get_dependency_nodes()
Return dependencies that exist as stored graph node keys.
Usage
get_dependency_nodes(key)Unresolvable dangling endpoints are omitted.
get_dependents()
Return an immutable snapshot of cells that depend on key.
Usage
get_dependents(key)Endpoints are returned exactly as stored.
get_edge_attrs()
Return a typed snapshot of the attributes on edge from_key -> to_key.
Usage
get_edge_attrs(from_key, to_key)Lookup uses exact stored endpoints. When the edge does not exist, returns an EdgeAttrs with all fields set to None.
get_edge_guard()
Return the guard on edge from_key -> to_key, or None if none.
Usage
get_edge_guard(from_key, to_key)Lookup uses exact stored endpoints.
get_node()
Return an immutable NodeView snapshot, or None if missing.
Usage
get_node(key)is_guarded()
Return whether edge from_key -> to_key carries a guard.
Usage
is_guarded(from_key, to_key)Membership-only: does not retrieve the guard AST. Prefer this over get_edge_guard(...) is not None when the expression is unused.
keys()
Return node keys from source (or the graph) using the selected order.
Usage
keys(*, order="insertion", source=None)leaf_keys()
Return sorted list of keys for nodes with no dependency edges (leaves).
Usage
leaf_keys()leaf_node_items()
Iterate over (key, node) pairs for leaf nodes (no cell dependencies).
Usage
leaf_node_items()leaves()
Iterate over keys of leaf nodes (no dependencies).
Usage
leaves()move_node()
Move a node to a new cell, preserving resolved formula targets.
Usage
move_node(old_key, new_key)Excel cut/move: relative axes on the moved host are rewritten so they still resolve to the same cells against new_key. Dependents that resolved to old_key are rewritten to resolve to new_key. Absolute axes keep their kind. normalized_formula is a derived absolute-A1 view and follows the rewritten AST. When formula_shapes is warmed, affected bindings are re-interned (shared relative params may split or join).
Incoming edges from occupancy (range expansion, whole-column/row members) are dropped when the dependent formula was not rewritten to mention new_key. Remaining GuardExpr trees rewrite CellRef keys and RangeRef endpoints. If the destination already has an incoming edge from the same dependent, guards merge with or_guard (None unconditional wins) and provenance merges with merge_edge_provenance.
Assigning Node.address directly raises; geometry edits must go through this method.
Parameters
old_key: NodeKey-
Existing node key.
new_key: NodeKey- Destination single-cell key.
Raises
KeyError-
If
old_keyis missing. ValueError-
If
new_keyis not a single cell, already exists, an affected formula is unparseable, or a range guard would split across sheets.
rebuild_adjacency()
Materialize CSR+CSC from current topology and drop dict maps.
Usage
rebuild_adjacency()Index space is _nodes insertion order. Non-node endpoints are dropped. Scratch is O(n) uint32; a second Python edge index is not built. After rebuild, _edges, _reverse_edges, _guards, and _edge_provenance are empty. Edge metadata lives in nnz-parallel intern-id arrays beside CSR.
remove_node()
Remove a node and all of its incident edges.
Usage
remove_node(key)Both outgoing dependency edges and incoming dependent edges are dropped, along with their guards and provenance. Dependent formulas are not rewritten; callers collapsing nodes must update dependents explicitly. Node hooks are not invoked. Absent keys are a no-op. Does not validate remaining formulas; call validate_consistency after collapsing nodes.
replace_node_formula()
Replace a node’s formula and rewire outgoing edges from extraction.
Usage
replace_node_formula(
key,
formula,
normalized_formula,
*,
workbook=None,
dynamic_refs=None,
use_cached_dynamic_refs=False,
load_values=True,
capture_dependency_provenance=True,
max_depth=50,
expand_ranges=True,
max_range_cells=None
)Unlike set_node_formula (the projection primitive), this recomputes leaf/formula state, outgoing guards, and provenance from the new formula. Newly referenced cells are materialized when workbook is provided. Named ranges that are not on the graph, dynamic OFFSET/INDIRECT/INDEX that need the book, and missing subgraph cells fail closed with WorkbookContextRequiredError when workbook is omitted — the graph is left unchanged.
Incoming edges (dependents of this cell) are preserved. formula_shapes is dropped; callers who want the overlay must rewarm.
Parameters
key: NodeKey-
Existing node to edit.
formula: str | None-
New raw formula text, or
Noneto clear the formula and become a leaf. normalized_formula: str | None-
Fallback parse text when
formulais unparseable. Ignored whenformulaparses. workbook: str | Path | None = None-
Source
.xlsxused to resolve named ranges, dynamic refs, and to materialize off-path cells. dynamic_refs: DynamicRefConfig | None = None-
Constraint-based dynamic-ref config forwarded to extraction when
workbookis set. use_cached_dynamic_refs: bool = False-
Resolve OFFSET/INDIRECT/INDEX from cached workbook values (requires
workbook). load_values: bool = True-
Load cached Excel values for newly materialized cells.
capture_dependency_provenance: bool = True-
Record extraction provenance on new edges (default True).
max_depth: int = 50-
BFS depth when materializing from
workbook. expand_ranges: bool = True-
Expand rectangular refs to member cells.
max_range_cells: int | None = None- Expansion budget; defaults to DEFAULT_MAX_RANGE_CELLS.
Raises
KeyError-
If the node is missing.
WorkbookContextRequiredError-
If workbook context is required and
workbookis omitted.
resolve_endpoint()
Map an edge endpoint to a stored node key when present.
Usage
resolve_endpoint(key)Returns None when the key is not a graph node.
roots()
Iterate keys with no in-graph dependents.
Usage
roots()set_node_ast()
Set a node’s formula from formula_ast.
Usage
set_node_ast(key, formula_ast, *, formula=_FORMULA_UNSET)Derives normalized_formula as absolute A1. Omit formula to leave the raw audit string unchanged. Pass formula= to set or clear it. Unset formula_ast clears the derived formula view and, unless formula= is passed, the raw audit string. Edges are not recomputed; callers rewiring dependencies must update edges explicitly. Drops formula_shapes; callers who want the overlay must rewarm. Does not validate formula/edge agreement; call validate_consistency after rewiring.
Raises
KeyError- If the node is missing.
set_node_formula()
Set a node’s formula and parse it into formula_ast.
Usage
set_node_formula(key, formula, normalized_formula)Parses raw formula with axis intent when present; otherwise parses normalized_formula with the host cell as anchor when available (absolute-only when it is not). A successful parse is the source of the derived normalized_formula view. Unparseable formulas leave formula_ast unset and keep normalized_formula as fallback text. Edges are not recomputed; callers rewiring dependencies must update edges explicitly. Intended for projection authors building export-only graph views. For a topology-aware durable edit, use replace_node_formula. Drops formula_shapes; callers who want the overlay must rewarm. Does not validate formula/edge agreement; call validate_consistency after rewiring.
Raises
KeyError- If the node is missing.
set_node_metadata()
Replace a node’s metadata mapping durably.
Usage
set_node_metadata(key, metadata)The provided mapping is copied; subsequent mutations to the caller’s object do not affect graph state. Raises KeyError if the node is missing.
set_node_value()
Set a node’s value field durably. Raises KeyError if missing.
Usage
set_node_value(key, value)Increments _value_generation so evaluators can skip polling every leaf when no durable write has occurred since the last scan.
target_keys()
Return sorted list of keys marked as original build targets.
Usage
target_keys()validate_consistency()
Raise GraphConsistencyError if formulas, edges, or flags disagree.
Usage
validate_consistency()Does not rewrite the graph. Opt-in for projection authors after set_node_formula / add_edge / remove_node.
Raises
GraphConsistencyError- If any structured consistency issue is found.