|
| 1 | +"""Graph builder: mutable construction → compile to immutable `CompiledGraph`. |
| 2 | +
|
| 3 | +Per spec §2: compilation MUST fail if the graph has no declared entry, |
| 4 | +unreachable nodes, dangling edges, a node with more than one outgoing edge, |
| 5 | +or a field with more than one declared reducer. |
| 6 | +""" |
| 7 | + |
| 8 | +from collections.abc import Awaitable, Callable, Mapping |
| 9 | +from typing import Any, Self |
| 10 | + |
| 11 | +from .compiled import CompiledGraph |
| 12 | +from .edges import ConditionalEdge, EndSentinel, StaticEdge |
| 13 | +from .errors import ( |
| 14 | + ConflictingReducers, |
| 15 | + DanglingEdge, |
| 16 | + MultipleOutgoingEdges, |
| 17 | + NoDeclaredEntry, |
| 18 | + UnreachableNode, |
| 19 | +) |
| 20 | +from .nodes import FunctionNode, Node |
| 21 | +from .projection import FieldNameMatching, ProjectionStrategy |
| 22 | +from .reducers import Reducer |
| 23 | +from .state import State, field_reducers, resolve_reducer |
| 24 | +from .subgraph import SubgraphNode |
| 25 | + |
| 26 | + |
| 27 | +class GraphBuilder: |
| 28 | + """Mutable builder for a graph; call `compile()` to produce a `CompiledGraph`.""" |
| 29 | + |
| 30 | + def __init__(self, state_cls: type[State]) -> None: |
| 31 | + self.state_cls = state_cls |
| 32 | + self._nodes: dict[str, Node] = {} |
| 33 | + self._edges: list[StaticEdge | ConditionalEdge] = [] |
| 34 | + self._entry: str | None = None |
| 35 | + |
| 36 | + def add_node( |
| 37 | + self, |
| 38 | + name: str, |
| 39 | + fn: Callable[[Any], Awaitable[Mapping[str, Any]]], |
| 40 | + ) -> Self: |
| 41 | + if name in self._nodes: |
| 42 | + raise ValueError(f"node {name!r} already declared") |
| 43 | + self._nodes[name] = FunctionNode(name=name, fn=fn) |
| 44 | + return self |
| 45 | + |
| 46 | + def add_subgraph( |
| 47 | + self, |
| 48 | + name: str, |
| 49 | + compiled: CompiledGraph, |
| 50 | + projection: ProjectionStrategy | None = None, |
| 51 | + ) -> Self: |
| 52 | + if name in self._nodes: |
| 53 | + raise ValueError(f"node {name!r} already declared") |
| 54 | + proj: ProjectionStrategy = projection if projection is not None else FieldNameMatching() |
| 55 | + self._nodes[name] = SubgraphNode(name=name, compiled=compiled, projection=proj) |
| 56 | + return self |
| 57 | + |
| 58 | + def add_edge(self, source: str, target: str | EndSentinel) -> Self: |
| 59 | + self._edges.append(StaticEdge(source=source, target=target)) |
| 60 | + return self |
| 61 | + |
| 62 | + def add_conditional( |
| 63 | + self, |
| 64 | + source: str, |
| 65 | + fn: Callable[[Any], str | EndSentinel], |
| 66 | + ) -> Self: |
| 67 | + self._edges.append(ConditionalEdge(source=source, fn=fn)) |
| 68 | + return self |
| 69 | + |
| 70 | + def set_entry(self, name: str) -> Self: |
| 71 | + self._entry = name |
| 72 | + return self |
| 73 | + |
| 74 | + def compile(self) -> CompiledGraph: |
| 75 | + # 1. ConflictingReducers — state schema check. |
| 76 | + per_field = field_reducers(self.state_cls) |
| 77 | + for fname, declared in per_field.items(): |
| 78 | + if len(declared) > 1: |
| 79 | + raise ConflictingReducers(fname) |
| 80 | + resolved: dict[str, Reducer] = { |
| 81 | + fname: resolve_reducer(declared) for fname, declared in per_field.items() |
| 82 | + } |
| 83 | + |
| 84 | + # 2. NoDeclaredEntry. |
| 85 | + if self._entry is None: |
| 86 | + raise NoDeclaredEntry() |
| 87 | + |
| 88 | + # 3. Entry must point to a declared node (treat as DanglingEdge). |
| 89 | + if self._entry not in self._nodes: |
| 90 | + raise DanglingEdge(source="<entry>", target=self._entry) |
| 91 | + |
| 92 | + # 4. DanglingEdge — both endpoints of every edge must be declared. |
| 93 | + for edge in self._edges: |
| 94 | + if edge.source not in self._nodes: |
| 95 | + raise DanglingEdge(source=edge.source, target=edge.source) |
| 96 | + if isinstance(edge, StaticEdge) and isinstance(edge.target, str): |
| 97 | + if edge.target not in self._nodes: |
| 98 | + raise DanglingEdge(source=edge.source, target=edge.target) |
| 99 | + |
| 100 | + # 5. MultipleOutgoingEdges + index by source for the reachability pass. |
| 101 | + edges_by_source: dict[str, StaticEdge | ConditionalEdge] = {} |
| 102 | + for edge in self._edges: |
| 103 | + if edge.source in edges_by_source: |
| 104 | + raise MultipleOutgoingEdges(edge.source) |
| 105 | + edges_by_source[edge.source] = edge |
| 106 | + |
| 107 | + # 6. UnreachableNode — BFS from entry. Conditional edges over-approximate |
| 108 | + # by reaching every declared node (we cannot statically know the fn's |
| 109 | + # range), which keeps the check sound (no false positives). |
| 110 | + reachable = self._reachable_nodes(edges_by_source) |
| 111 | + for node_name in self._nodes: |
| 112 | + if node_name not in reachable: |
| 113 | + raise UnreachableNode(node_name) |
| 114 | + |
| 115 | + return CompiledGraph( |
| 116 | + state_cls=self.state_cls, |
| 117 | + entry=self._entry, |
| 118 | + nodes=dict(self._nodes), |
| 119 | + edges=edges_by_source, |
| 120 | + reducers=resolved, |
| 121 | + ) |
| 122 | + |
| 123 | + def _reachable_nodes( |
| 124 | + self, |
| 125 | + edges_by_source: Mapping[str, StaticEdge | ConditionalEdge], |
| 126 | + ) -> set[str]: |
| 127 | + assert self._entry is not None |
| 128 | + reachable: set[str] = {self._entry} |
| 129 | + frontier = [self._entry] |
| 130 | + all_names = set(self._nodes.keys()) |
| 131 | + while frontier: |
| 132 | + current = frontier.pop() |
| 133 | + edge = edges_by_source.get(current) |
| 134 | + if edge is None: |
| 135 | + continue |
| 136 | + if isinstance(edge, StaticEdge): |
| 137 | + if isinstance(edge.target, str) and edge.target not in reachable: |
| 138 | + reachable.add(edge.target) |
| 139 | + frontier.append(edge.target) |
| 140 | + else: |
| 141 | + for name in all_names - reachable: |
| 142 | + reachable.add(name) |
| 143 | + frontier.append(name) |
| 144 | + return reachable |
0 commit comments