Pyrophone 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,42 @@
1
+ """Errors raised while declaring, configuring, and executing nodes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from ._node import Node
9
+
10
+
11
+ class PyrophoneError(Exception):
12
+ """Base class for errors reported by Pyrophone."""
13
+
14
+
15
+ class SchemaError(PyrophoneError, ValueError):
16
+ """A node declaration has an invalid or unresolved schema."""
17
+
18
+
19
+ class ConfigurationError(PyrophoneError, ValueError):
20
+ """Configuration does not satisfy a node's schema."""
21
+
22
+
23
+ class GraphError(PyrophoneError, ValueError):
24
+ """A graph connection or compiled graph is invalid."""
25
+
26
+
27
+ class EndOfStream(PyrophoneError):
28
+ """The input channel has closed and no more values can arrive."""
29
+
30
+
31
+ class ChannelClosedError(PyrophoneError):
32
+ """A value could not be accepted because the channel has closed."""
33
+
34
+
35
+ class NodeExecutionError(PyrophoneError):
36
+ """A node initializer or run method failed; __cause__ holds the original."""
37
+
38
+ def __init__(self, node_id: str, node_type: type[Node]) -> None:
39
+ self.node_id = node_id
40
+ self.node_type = node_type
41
+ self.node_type_name = node_type.__name__
42
+ super().__init__(f"node {self.node_type_name} ({node_id}) failed")
pyrophone/_graph.py ADDED
@@ -0,0 +1,283 @@
1
+ """Configured node occurrences and named graph connections."""
2
+
3
+ from collections.abc import Mapping
4
+ from dataclasses import dataclass, field, replace
5
+ from types import MappingProxyType
6
+ from typing import Literal, get_args
7
+ from uuid import uuid4
8
+
9
+ from ._exceptions import GraphError
10
+ from ._inspection import Printable, node_details, type_name
11
+ from ._node import Node, _resolve_configuration, node_type_schema
12
+ from ._schema import NodeTypeSchema, PortSchema, is_type_compatible
13
+
14
+ type Direction = Literal["input", "output"]
15
+
16
+
17
+ @dataclass(frozen=True, eq=False)
18
+ class NodeDeclaration(Printable):
19
+ """An occurrence, with independent configuration and a stable unique ID.
20
+
21
+ Configuration is shallowly read-only; nested values are copied on creation.
22
+ No live node or user initializer is involved in creating a declaration.
23
+ Named attributes expose ports; use ``port(name)`` for ports whose names
24
+ collide with declaration fields or methods (such as ``id`` or ``port``).
25
+ """
26
+
27
+ node_type: type[Node]
28
+ configuration: Mapping[str, object] = field(default_factory=dict)
29
+ id: str = field(default_factory=lambda: uuid4().hex, init=False)
30
+ schema: NodeTypeSchema = field(init=False)
31
+
32
+ def __post_init__(self) -> None:
33
+ schema = node_type_schema(self.node_type)
34
+ object.__setattr__(self, "schema", schema)
35
+ object.__setattr__(
36
+ self,
37
+ "configuration",
38
+ MappingProxyType(_resolve_configuration(schema, self.configuration)),
39
+ )
40
+
41
+ def __repr__(self) -> str:
42
+ return f"<Node {self.node_type.__name__}#{self.id[:8]}>"
43
+
44
+ def _describe(self) -> str:
45
+ return node_details(
46
+ self.node_type, self.configuration, self.schema, node_id=self.id
47
+ )
48
+
49
+ def port(self, name: str) -> "PortReference":
50
+ if name in self.schema.inputs:
51
+ return PortReference(self, name, "input")
52
+ if name in self.schema.outputs:
53
+ return PortReference(self, name, "output")
54
+ raise AttributeError(f"{self.schema.name}: no port named {name!r}")
55
+
56
+ def __getattr__(self, name: str) -> "PortReference":
57
+ return self.port(name)
58
+
59
+ def __or__(self, other: "NodeDeclaration") -> "Graph":
60
+ return Graph(self) | other
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class PortReference(Printable):
65
+ """A named port on one occurrence, never a live runtime endpoint."""
66
+
67
+ node: NodeDeclaration
68
+ name: str
69
+ direction: Direction
70
+
71
+ def __repr__(self) -> str:
72
+ return (
73
+ f"<Port {self.node.node_type.__name__}#{self.node.id[:8]}"
74
+ f".{self.name} ({self.direction})>"
75
+ )
76
+
77
+ def _describe(self) -> str:
78
+ return (
79
+ f"Port: {self.node.node_type.__name__}.{self.name}\n"
80
+ f" Node ID: {self.node.id}\n"
81
+ f" Direction: {self.direction}\n"
82
+ f" Type: {type_name(self.schema.type)}"
83
+ )
84
+
85
+ @property
86
+ def schema(self) -> PortSchema:
87
+ if self.direction not in ("input", "output"):
88
+ raise GraphError(f"invalid port direction {self.direction!r}")
89
+ ports = (
90
+ self.node.schema.inputs
91
+ if self.direction == "input"
92
+ else self.node.schema.outputs
93
+ )
94
+ if self.name not in ports:
95
+ raise GraphError(
96
+ f"{self.node.schema.name}: unknown {self.direction} port {self.name!r}"
97
+ )
98
+ return ports[self.name]
99
+
100
+
101
+ @dataclass(frozen=True)
102
+ class Edge(Printable):
103
+ source: PortReference
104
+ destination: PortReference
105
+
106
+ def __repr__(self) -> str:
107
+ source, destination = self.source, self.destination
108
+ return (
109
+ f"<Edge {source.node.node_type.__name__}#{source.node.id[:8]}"
110
+ f".{source.name} -> "
111
+ f"{destination.node.node_type.__name__}#{destination.node.id[:8]}"
112
+ f".{destination.name}>"
113
+ )
114
+
115
+ def _describe(self) -> str:
116
+ source, destination = self.source, self.destination
117
+ return (
118
+ "Edge:\n"
119
+ f" From: {source.node.node_type.__name__}#{source.node.id}.{source.name}"
120
+ f" ({type_name(source.schema.type)})\n"
121
+ f" To: {destination.node.node_type.__name__}#{destination.node.id}"
122
+ f".{destination.name} ({type_name(destination.schema.type)})"
123
+ )
124
+
125
+
126
+ def _output_type(
127
+ source: PortReference, incoming: Mapping[PortReference, PortReference]
128
+ ) -> object | None:
129
+ """Follow exact-value forwarding contracts without mutating declarations.
130
+
131
+ An open input or a cycle without a concrete producer cannot yet infer a type.
132
+ """
133
+ seen: set[PortReference] = set()
134
+ while source not in seen:
135
+ seen.add(source)
136
+ input_name = source.node.node_type._output_type_sources.get(source.name)
137
+ if input_name is None:
138
+ return source.schema.type
139
+ upstream = incoming.get(source.node.port(input_name))
140
+ if upstream is None:
141
+ return None
142
+ source = upstream
143
+ return None
144
+
145
+
146
+ def _resolved_schema(
147
+ node: NodeDeclaration, incoming: Mapping[PortReference, PortReference]
148
+ ) -> NodeTypeSchema:
149
+ """Specialize compiled output metadata for this graph only."""
150
+ outputs = dict(node.schema.outputs)
151
+ for name in node.node_type._output_type_sources:
152
+ inferred = _output_type(node.port(name), incoming)
153
+ if inferred is not None:
154
+ outputs[name] = replace(outputs[name], type=inferred)
155
+ return (
156
+ node.schema
157
+ if outputs == node.schema.outputs
158
+ else replace(node.schema, outputs=outputs)
159
+ )
160
+
161
+
162
+ def _validate_connection(
163
+ source: PortReference,
164
+ destination: PortReference,
165
+ connected: set[PortReference],
166
+ *,
167
+ incoming: Mapping[PortReference, PortReference],
168
+ allow_unbound: bool = False,
169
+ ) -> None:
170
+ if not isinstance(source, PortReference) or not isinstance(
171
+ destination, PortReference
172
+ ):
173
+ raise GraphError("connections require a named port reference at each end")
174
+ if source.direction != "output" or destination.direction != "input":
175
+ raise GraphError("connections must run from an output port to an input port")
176
+ source_schema, destination_schema = source.schema, destination.schema
177
+ if source in connected or destination in connected:
178
+ raise GraphError("port is already connected; each port permits one channel")
179
+ source_type = _output_type(source, incoming)
180
+ if source_type is None:
181
+ source_type = source_schema.type
182
+ # During editing a forwarder's input may be connected later. Only
183
+ # defer if at least one allowed input type could satisfy this edge.
184
+ if allow_unbound and any(
185
+ is_type_compatible(part, destination_schema.type)
186
+ for part in (get_args(source_type) or (source_type,))
187
+ ):
188
+ return
189
+ if not is_type_compatible(source_type, destination_schema.type):
190
+ raise GraphError(
191
+ f"incompatible port types: {source.name} ({source_type}) -> "
192
+ f"{destination.name} ({destination_schema.type})"
193
+ )
194
+
195
+
196
+ def _implicit_port(node: NodeDeclaration, direction: Direction) -> PortReference:
197
+ ports = node.schema.inputs if direction == "input" else node.schema.outputs
198
+ defaults = [port for port in ports.values() if port.default]
199
+ if defaults:
200
+ return node.port(defaults[0].name)
201
+ if len(ports) == 1:
202
+ return node.port(next(iter(ports)))
203
+ if not ports:
204
+ raise GraphError(
205
+ f"{node.schema.name}: no {direction} port for implicit connection"
206
+ )
207
+ raise GraphError(
208
+ f"{node.schema.name}: ambiguous {direction} ports; "
209
+ "choose a named port or declare default=True"
210
+ )
211
+
212
+
213
+ class Graph(Printable):
214
+ """Editable graph with stable tuple inspection views.
215
+
216
+ ``connect`` atomically adds endpoints and an edge, returning this graph.
217
+ ``graph | declaration`` returns a new graph, connecting from the last node
218
+ in insertion order. Implicit selection uses only declared direction/default
219
+ metadata; existing bindings and compatible types never change that choice.
220
+ """
221
+
222
+ def __init__(self, *nodes: NodeDeclaration) -> None:
223
+ self._nodes: dict[str, NodeDeclaration] = {}
224
+ self._edges: list[Edge] = []
225
+ for node in nodes:
226
+ if not isinstance(node, NodeDeclaration):
227
+ raise GraphError("graphs require node declarations")
228
+ self._nodes[node.id] = node
229
+
230
+ def __repr__(self) -> str:
231
+ return f"Graph(nodes={len(self._nodes)}, edges={len(self._edges)})"
232
+
233
+ def _describe(self) -> str:
234
+ from ._graph_display import format_graph
235
+
236
+ return format_graph(self)
237
+
238
+ @property
239
+ def nodes(self) -> tuple[NodeDeclaration, ...]:
240
+ return tuple(self._nodes.values())
241
+
242
+ @property
243
+ def edges(self) -> tuple[Edge, ...]:
244
+ return tuple(self._edges)
245
+
246
+ def connect(self, source: PortReference, destination: PortReference) -> "Graph":
247
+ connected = {
248
+ port for edge in self._edges for port in (edge.source, edge.destination)
249
+ }
250
+ incoming = {edge.destination: edge.source for edge in self._edges}
251
+ # Do structural validation before using caller-supplied endpoints as
252
+ # keys. Inference of the new edge uses all existing upstream links.
253
+ _validate_connection(
254
+ source, destination, connected, incoming=incoming, allow_unbound=True
255
+ )
256
+ incoming[destination] = source
257
+ # Binding an input can narrow downstream forwarders, including ones
258
+ # connected earlier. Recheck those edges before mutating the graph.
259
+ for edge in (*self._edges, Edge(source, destination)):
260
+ _validate_connection(
261
+ edge.source,
262
+ edge.destination,
263
+ set(),
264
+ incoming=incoming,
265
+ allow_unbound=True,
266
+ )
267
+ # Nothing mutates until every check has succeeded, including endpoints
268
+ # that were not already part of the graph.
269
+ self._nodes[source.node.id] = source.node
270
+ self._nodes[destination.node.id] = destination.node
271
+ self._edges.append(Edge(source, destination))
272
+ return self
273
+
274
+ def __or__(self, other: NodeDeclaration) -> "Graph":
275
+ if not isinstance(other, NodeDeclaration):
276
+ raise GraphError("implicit connections require a node declaration")
277
+ if not self._nodes:
278
+ raise GraphError("implicit connections require a source node")
279
+ source = _implicit_port(self.nodes[-1], "output")
280
+ destination = _implicit_port(other, "input")
281
+ result = Graph(*self.nodes)
282
+ result._edges = list(self._edges)
283
+ return result.connect(source, destination)
@@ -0,0 +1,117 @@
1
+ """Pretty, YAML, and Graphviz views of validated execution snapshots."""
2
+
3
+ import json
4
+ from collections.abc import Callable
5
+
6
+ import yaml
7
+ from yaml.representer import RepresenterError
8
+
9
+ from ._compile import CompiledGraph, CompiledNode
10
+ from ._exceptions import GraphError
11
+ from ._graph import Edge, Graph, NodeDeclaration
12
+ from ._inspection import node_details
13
+
14
+
15
+ def format_graph(graph: Graph | CompiledGraph, *, title: str = "Graph") -> str:
16
+ """Describe nodes and named connections without requiring compilation."""
17
+ nodes: tuple[NodeDeclaration | CompiledNode, ...] = graph.nodes
18
+ labels = {node.id: f"[{index}]" for index, node in enumerate(nodes, 1)}
19
+ lines = [f"{title}: {len(graph.nodes)} nodes, {len(graph.edges)} channels"]
20
+ for node in nodes:
21
+ details = node_details(node.node_type, node.configuration, node.schema)
22
+ heading, *body = details.splitlines()
23
+ lines.append(f" {labels[node.id]} {heading.removeprefix('Node: ')}")
24
+ lines.extend(f" {line}" for line in body)
25
+ if graph.edges:
26
+ lines.append("Connections:")
27
+ for edge in graph.edges:
28
+ if isinstance(edge, Edge):
29
+ source_id, source_port = edge.source.node.id, edge.source.name
30
+ destination_id = edge.destination.node.id
31
+ destination_port = edge.destination.name
32
+ else:
33
+ source_id, source_port = edge.source_id, edge.source_port
34
+ destination_id, destination_port = (
35
+ edge.destination_id,
36
+ edge.destination_port,
37
+ )
38
+ lines.append(
39
+ f" {labels[source_id]}.{source_port} -> "
40
+ f"{labels[destination_id]}.{destination_port}"
41
+ )
42
+ return "\n".join(lines)
43
+
44
+
45
+ def dump_graph(graph: CompiledGraph) -> str:
46
+ """Export identifiers, node types, resolved configuration, and port edges.
47
+
48
+ Configuration uses standard YAML representations, including binary data.
49
+ Unsupported Python objects fail rather than being converted to strings.
50
+ This exports a snapshot; it does not define a graph-loading API.
51
+ """
52
+ document = {
53
+ "version": 1,
54
+ "nodes": [
55
+ {
56
+ "id": node.id,
57
+ "type": f"{node.node_type.__module__}.{node.node_type.__qualname__}",
58
+ "configuration": dict(node.configuration),
59
+ }
60
+ for node in graph.nodes
61
+ ],
62
+ "edges": [
63
+ {
64
+ "source": {"node": edge.source_id, "port": edge.source_port},
65
+ "destination": {
66
+ "node": edge.destination_id,
67
+ "port": edge.destination_port,
68
+ },
69
+ }
70
+ for edge in graph.edges
71
+ ],
72
+ }
73
+ try:
74
+ return yaml.safe_dump(
75
+ document, sort_keys=False, allow_unicode=True, default_flow_style=False
76
+ )
77
+ except RepresenterError as error:
78
+ raise GraphError(
79
+ "Graph configuration contains a value unsupported by YAML"
80
+ ) from error
81
+
82
+
83
+ def graphviz_graph(graph: CompiledGraph) -> str:
84
+ """Export topology as DOT, retaining node identities and named connections.
85
+
86
+ Plain quoted labels avoid Graphviz HTML/record interpretation; escaping
87
+ protects quotes, backslashes, and newlines in user-defined type names.
88
+ Graphviz itself is needed only to render the exported text.
89
+ """
90
+
91
+ def quote(value: str) -> str:
92
+ return json.dumps(value, ensure_ascii=False)
93
+
94
+ lines = ["digraph pyrophone {", " rankdir=LR;", " node [shape=box];"]
95
+ for node in graph.nodes:
96
+ label = f"{node.node_type.__module__}.{node.node_type.__qualname__}"
97
+ lines.append(f" {quote(node.id)} [label={quote(label)}];")
98
+ for edge in graph.edges:
99
+ label = f"{edge.source_port} -> {edge.destination_port}"
100
+ lines.append(
101
+ f" {quote(edge.source_id)} -> {quote(edge.destination_id)} "
102
+ f"[label={quote(label)}];"
103
+ )
104
+ lines.append("}")
105
+ return "\n".join(lines)
106
+
107
+
108
+ GRAPH_FORMATS: dict[str, Callable[[CompiledGraph], str]] = {
109
+ "pretty": format_graph,
110
+ "yaml": dump_graph,
111
+ "graphviz": graphviz_graph,
112
+ }
113
+
114
+
115
+ def render_graph(graph: CompiledGraph, format_name: str) -> str:
116
+ """Render any supported format with exactly one trailing newline."""
117
+ return GRAPH_FORMATS[format_name](graph).rstrip("\n") + "\n"
@@ -0,0 +1,50 @@
1
+ """Shared text inspection helpers, independent of graph construction."""
2
+
3
+ from collections.abc import Mapping
4
+ from pprint import pformat
5
+ from typing import TextIO
6
+
7
+ from ._schema import NodeTypeSchema
8
+
9
+
10
+ class Printable:
11
+ """Print a detailed description to stdout or a supplied text stream."""
12
+
13
+ def print(self, *, file: TextIO | None = None) -> None:
14
+ """Write a pretty multiline description, followed by a newline."""
15
+ print(self._describe(), file=file)
16
+
17
+ def _describe(self) -> str:
18
+ raise NotImplementedError
19
+
20
+
21
+ def type_name(spec: object) -> str:
22
+ return spec.__name__ if isinstance(spec, type) else str(spec)
23
+
24
+
25
+ def node_details(
26
+ node_type: type,
27
+ configuration: Mapping[str, object],
28
+ schema: NodeTypeSchema,
29
+ *,
30
+ kind: str = "Node",
31
+ node_id: str | None = None,
32
+ ) -> str:
33
+ lines = [f"{kind}: {node_type.__module__}.{node_type.__qualname__}"]
34
+ if node_id is not None:
35
+ lines.append(f" ID: {node_id}")
36
+ lines.append(" Properties:")
37
+ for name, value in configuration.items():
38
+ value_lines = pformat(value, width=68, sort_dicts=False).splitlines()
39
+ lines.append(f" {name}: {value_lines[0]}")
40
+ lines.extend(f" {line}" for line in value_lines[1:])
41
+ if not configuration:
42
+ lines.append(" (none)")
43
+ for label, ports in (("Inputs", schema.inputs), ("Outputs", schema.outputs)):
44
+ lines.append(f" {label}:")
45
+ for name, port in ports.items():
46
+ default = " (default)" if port.default else ""
47
+ lines.append(f" {name}: {type_name(port.type)}{default}")
48
+ if not ports:
49
+ lines.append(" (none)")
50
+ return "\n".join(lines)