graphite-ir 0.1.0__tar.gz

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,169 @@
1
+ Metadata-Version: 2.4
2
+ Name: graphite-ir
3
+ Version: 0.1.0
4
+ Summary: Heterograph schemas, matching, rewriting, and contracts
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: heterograph
8
+ Requires-Dist: pydantic>=2
9
+
10
+ # Graphite
11
+
12
+ Graphite is a Python toolkit for describing, validating, matching, and
13
+ rewriting Heterograph-based intermediate representations (IRs). It also
14
+ provides contracts for checking the output of a graph workflow. Graphite has no
15
+ Loom dependency; any object with an `output` attribute can be verified.
16
+
17
+ ## Install
18
+
19
+ Graphite requires Python 3.10+, [Heterograph](https://pypi.org/project/heterograph/),
20
+ Pydantic 2, and `graph-tool` for graph matching. For local development:
21
+
22
+ ```bash
23
+ conda env create graphite
24
+ conda activate graphite
25
+ conda install -c conda-forge graph-tool=3.0 graphviz python-graphviz
26
+ pip install -e .
27
+ ```
28
+
29
+ The runnable examples are in [`examples/`](examples). `validation` and
30
+ `processor_tests` require Graphite only; `lowering` and `agent` are Graphite
31
+ and Loom integration examples.
32
+
33
+ ## IR schemas
34
+
35
+ `GraphSchema` defines the accepted graph, vertex, and edge metadata with
36
+ Pydantic models. It constructs correctly typed graph elements and returns a
37
+ `ValidationReport` instead of failing at the first invalid element. Each graph
38
+ element uses `_type` to select its model.
39
+
40
+ ```python
41
+ from typing import Literal
42
+
43
+ from pydantic import BaseModel, Field
44
+ from graphite import GraphSchema
45
+
46
+
47
+ class ConstantProps(BaseModel):
48
+ type_: Literal["Constant"] = Field(alias="_type")
49
+ value: float
50
+
51
+
52
+ class NegateProps(BaseModel):
53
+ type_: Literal["Negate"] = Field(alias="_type")
54
+
55
+
56
+ class DataEdgeProps(BaseModel):
57
+ type_: Literal["data"] = Field(alias="_type")
58
+
59
+
60
+ ir = GraphSchema(
61
+ name="ArithmeticIR",
62
+ vertex={"Constant": ConstantProps, "Negate": NegateProps},
63
+ edge={"data": DataEdgeProps},
64
+ )
65
+
66
+ graph = ir.new_graph()
67
+ constant = ir.new_vertex(graph, "Constant", value=3.0)
68
+ negate = ir.new_vertex(graph, "Negate")
69
+ ir.new_edge(graph, constant, negate, "data")
70
+
71
+ report = ir.validate(graph)
72
+ assert report.ok
73
+ ```
74
+
75
+ Pass `rules` to `GraphSchema` for structural validation such as arity,
76
+ acyclicity, or required inputs and outputs. A rule receives the `HGraph` and
77
+ returns a list of `Issue` values. `update_vertex()` and `update_edge()` apply
78
+ the same Pydantic validation when metadata changes.
79
+
80
+ ## Graph processor
81
+
82
+ `GraphProcessor` finds AQL patterns and applies one in-place rewrite pass. A
83
+ result contains `matches`, the parsed `pattern`, and a `modified` flag.
84
+
85
+ ```python
86
+ from heterograph import HGraph
87
+ from graphite import GraphProcessor
88
+
89
+ graph = HGraph()
90
+ graph.add_vx(3)
91
+ graph.add_edge(0, 1)
92
+ graph.add_edge(1, 2)
93
+
94
+ processor = GraphProcessor(snapshot=False)
95
+ result = processor.run(
96
+ graph,
97
+ select="a => b => c",
98
+ rewrite="a => c",
99
+ )
100
+
101
+ assert result["modified"]
102
+ assert set(graph.edges) == {(0, 2)}
103
+ ```
104
+
105
+ Use `where(graph, **match)` to filter matches and `finalize(graph, **match)`
106
+ to initialize created vertices or metadata. `finalize` must return a boolean.
107
+ Rewrites require disjoint matches; Graphite rejects overlapping matches before
108
+ mutating the graph. Rewire annotations preserve boundary connections when a
109
+ matched vertex is replaced:
110
+
111
+ ```python
112
+ processor.run(
113
+ graph,
114
+ select="a => b => c",
115
+ rewrite="a => x {rewire: b} => c",
116
+ )
117
+ ```
118
+
119
+ `GraphProcessor(snapshot=True)` is the default and records graphs in a
120
+ Heterograph WebView. Use `snapshot=False` for scripts and tests without a
121
+ viewer.
122
+
123
+ ## Contracts
124
+
125
+ `Contract` evaluates one object with an `output` attribute and returns a
126
+ `ContractResult`. `Verifier` runs a collection of contracts, retaining all
127
+ results; if any fail, it raises `ContractException` with the individual
128
+ failures.
129
+
130
+ `GraphSchemaContract` validates a result's graph output against a schema:
131
+
132
+ ```python
133
+ from dataclasses import dataclass
134
+
135
+ from graphite import GraphSchemaContract, Verifier
136
+
137
+
138
+ @dataclass
139
+ class BuildResult:
140
+ output: object
141
+
142
+
143
+ checks = Verifier([GraphSchemaContract(ir)])
144
+ contract_results = checks.verify(BuildResult(output=graph))
145
+ assert contract_results["valid-ArithmeticIR"].passed
146
+ ```
147
+
148
+ Custom contracts can check domain-specific properties:
149
+
150
+ ```python
151
+ from graphite import Contract, ContractResult
152
+
153
+
154
+ class HasVertices(Contract):
155
+ def __init__(self):
156
+ super().__init__(name="has-vertices")
157
+
158
+ def evaluate(self, result):
159
+ count = len(result.output.vertices)
160
+ return ContractResult(
161
+ passed=count > 0,
162
+ output=result.output,
163
+ metrics={"vertex_count": count},
164
+ )
165
+ ```
166
+
167
+ For complete examples, see [`examples/validation`](examples/validation),
168
+ [`examples/processor_tests`](examples/processor_tests), and the Loom-backed
169
+ [`examples/lowering`](examples/lowering) workflow.
@@ -0,0 +1,160 @@
1
+ # Graphite
2
+
3
+ Graphite is a Python toolkit for describing, validating, matching, and
4
+ rewriting Heterograph-based intermediate representations (IRs). It also
5
+ provides contracts for checking the output of a graph workflow. Graphite has no
6
+ Loom dependency; any object with an `output` attribute can be verified.
7
+
8
+ ## Install
9
+
10
+ Graphite requires Python 3.10+, [Heterograph](https://pypi.org/project/heterograph/),
11
+ Pydantic 2, and `graph-tool` for graph matching. For local development:
12
+
13
+ ```bash
14
+ conda env create graphite
15
+ conda activate graphite
16
+ conda install -c conda-forge graph-tool=3.0 graphviz python-graphviz
17
+ pip install -e .
18
+ ```
19
+
20
+ The runnable examples are in [`examples/`](examples). `validation` and
21
+ `processor_tests` require Graphite only; `lowering` and `agent` are Graphite
22
+ and Loom integration examples.
23
+
24
+ ## IR schemas
25
+
26
+ `GraphSchema` defines the accepted graph, vertex, and edge metadata with
27
+ Pydantic models. It constructs correctly typed graph elements and returns a
28
+ `ValidationReport` instead of failing at the first invalid element. Each graph
29
+ element uses `_type` to select its model.
30
+
31
+ ```python
32
+ from typing import Literal
33
+
34
+ from pydantic import BaseModel, Field
35
+ from graphite import GraphSchema
36
+
37
+
38
+ class ConstantProps(BaseModel):
39
+ type_: Literal["Constant"] = Field(alias="_type")
40
+ value: float
41
+
42
+
43
+ class NegateProps(BaseModel):
44
+ type_: Literal["Negate"] = Field(alias="_type")
45
+
46
+
47
+ class DataEdgeProps(BaseModel):
48
+ type_: Literal["data"] = Field(alias="_type")
49
+
50
+
51
+ ir = GraphSchema(
52
+ name="ArithmeticIR",
53
+ vertex={"Constant": ConstantProps, "Negate": NegateProps},
54
+ edge={"data": DataEdgeProps},
55
+ )
56
+
57
+ graph = ir.new_graph()
58
+ constant = ir.new_vertex(graph, "Constant", value=3.0)
59
+ negate = ir.new_vertex(graph, "Negate")
60
+ ir.new_edge(graph, constant, negate, "data")
61
+
62
+ report = ir.validate(graph)
63
+ assert report.ok
64
+ ```
65
+
66
+ Pass `rules` to `GraphSchema` for structural validation such as arity,
67
+ acyclicity, or required inputs and outputs. A rule receives the `HGraph` and
68
+ returns a list of `Issue` values. `update_vertex()` and `update_edge()` apply
69
+ the same Pydantic validation when metadata changes.
70
+
71
+ ## Graph processor
72
+
73
+ `GraphProcessor` finds AQL patterns and applies one in-place rewrite pass. A
74
+ result contains `matches`, the parsed `pattern`, and a `modified` flag.
75
+
76
+ ```python
77
+ from heterograph import HGraph
78
+ from graphite import GraphProcessor
79
+
80
+ graph = HGraph()
81
+ graph.add_vx(3)
82
+ graph.add_edge(0, 1)
83
+ graph.add_edge(1, 2)
84
+
85
+ processor = GraphProcessor(snapshot=False)
86
+ result = processor.run(
87
+ graph,
88
+ select="a => b => c",
89
+ rewrite="a => c",
90
+ )
91
+
92
+ assert result["modified"]
93
+ assert set(graph.edges) == {(0, 2)}
94
+ ```
95
+
96
+ Use `where(graph, **match)` to filter matches and `finalize(graph, **match)`
97
+ to initialize created vertices or metadata. `finalize` must return a boolean.
98
+ Rewrites require disjoint matches; Graphite rejects overlapping matches before
99
+ mutating the graph. Rewire annotations preserve boundary connections when a
100
+ matched vertex is replaced:
101
+
102
+ ```python
103
+ processor.run(
104
+ graph,
105
+ select="a => b => c",
106
+ rewrite="a => x {rewire: b} => c",
107
+ )
108
+ ```
109
+
110
+ `GraphProcessor(snapshot=True)` is the default and records graphs in a
111
+ Heterograph WebView. Use `snapshot=False` for scripts and tests without a
112
+ viewer.
113
+
114
+ ## Contracts
115
+
116
+ `Contract` evaluates one object with an `output` attribute and returns a
117
+ `ContractResult`. `Verifier` runs a collection of contracts, retaining all
118
+ results; if any fail, it raises `ContractException` with the individual
119
+ failures.
120
+
121
+ `GraphSchemaContract` validates a result's graph output against a schema:
122
+
123
+ ```python
124
+ from dataclasses import dataclass
125
+
126
+ from graphite import GraphSchemaContract, Verifier
127
+
128
+
129
+ @dataclass
130
+ class BuildResult:
131
+ output: object
132
+
133
+
134
+ checks = Verifier([GraphSchemaContract(ir)])
135
+ contract_results = checks.verify(BuildResult(output=graph))
136
+ assert contract_results["valid-ArithmeticIR"].passed
137
+ ```
138
+
139
+ Custom contracts can check domain-specific properties:
140
+
141
+ ```python
142
+ from graphite import Contract, ContractResult
143
+
144
+
145
+ class HasVertices(Contract):
146
+ def __init__(self):
147
+ super().__init__(name="has-vertices")
148
+
149
+ def evaluate(self, result):
150
+ count = len(result.output.vertices)
151
+ return ContractResult(
152
+ passed=count > 0,
153
+ output=result.output,
154
+ metrics={"vertex_count": count},
155
+ )
156
+ ```
157
+
158
+ For complete examples, see [`examples/validation`](examples/validation),
159
+ [`examples/processor_tests`](examples/processor_tests), and the Loom-backed
160
+ [`examples/lowering`](examples/lowering) workflow.
@@ -0,0 +1,23 @@
1
+ """Graph-IR schemas, matching, and rewriting built on Heterograph."""
2
+
3
+ from .processor import GraphProcessor
4
+ from .match_strategy import DfsMatchStrategy, IsoMatchStrategy, MatchStrategy
5
+ from .schema import GraphSchema, Issue, Severity, ValidationReport
6
+ from .schema_contract import GraphSchemaContract
7
+ from .contract import Contract, ContractException, ContractResult, Verifier
8
+
9
+ __all__ = [
10
+ "GraphProcessor",
11
+ "MatchStrategy",
12
+ "IsoMatchStrategy",
13
+ "DfsMatchStrategy",
14
+ "GraphSchema",
15
+ "Issue",
16
+ "Severity",
17
+ "ValidationReport",
18
+ "GraphSchemaContract",
19
+ "Contract",
20
+ "ContractException",
21
+ "ContractResult",
22
+ "Verifier",
23
+ ]
@@ -0,0 +1,105 @@
1
+ """Contracts for validating objects produced by graph workflows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from dataclasses import dataclass, field
7
+ from typing import Any, Iterable, Protocol
8
+
9
+
10
+ class ResultLike(Protocol):
11
+ """The minimal result interface accepted by a contract."""
12
+
13
+ output: Any
14
+
15
+
16
+ class ContractException(Exception):
17
+ """Raised when a contract rejects an execution result."""
18
+
19
+ def __init__(
20
+ self,
21
+ result: ResultLike,
22
+ contract_results: dict[str, ContractResult],
23
+ ):
24
+ self.result = result
25
+ self.contract_results = contract_results
26
+ self.failures = {
27
+ name: contract_result
28
+ for name, contract_result in contract_results.items()
29
+ if not contract_result.passed
30
+ }
31
+ super().__init__(
32
+ f"{len(self.failures)} contract(s) failed: {list(self.failures)}"
33
+ )
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class ContractResult:
38
+ """Result of verifying one execution result."""
39
+
40
+ passed: bool
41
+ output: Any = None
42
+ failures: list[Any] = field(default_factory=list)
43
+ metrics: dict[str, Any] = field(default_factory=dict)
44
+
45
+ def __post_init__(self) -> None:
46
+ if type(self.passed) is not bool:
47
+ raise TypeError(
48
+ "ContractResult.passed must be an actual bool, "
49
+ f"got {type(self.passed).__name__}."
50
+ )
51
+
52
+
53
+ class Contract(ABC):
54
+ """Human-defined acceptance criteria for an object with ``output``."""
55
+
56
+ def __init__(self, *, name: str):
57
+ if not name:
58
+ raise ValueError("Contract must have a name.")
59
+ self.name = name
60
+
61
+ def verify(self, result: ResultLike) -> ContractResult:
62
+ """Evaluate one explicit result-like object."""
63
+ if not hasattr(result, "output"):
64
+ raise TypeError("Contract.verify() requires an object with output.")
65
+ contract_result = self.evaluate(result)
66
+ if not isinstance(contract_result, ContractResult):
67
+ raise RuntimeError(
68
+ f"contract {self.name} returned {type(contract_result).__name__}; "
69
+ "Contract.evaluate() must return ContractResult"
70
+ )
71
+ return contract_result
72
+
73
+ @abstractmethod
74
+ def evaluate(self, result: ResultLike) -> ContractResult:
75
+ """Evaluate one explicit result-like object."""
76
+
77
+
78
+ class Verifier:
79
+ """Run every Contract and aggregate the individual results."""
80
+
81
+ def __init__(self, contracts: Iterable[Contract]):
82
+ self.contracts = list(contracts)
83
+ if not all(isinstance(contract, Contract) for contract in self.contracts):
84
+ raise TypeError("contracts must contain only Contract instances.")
85
+
86
+ def verify(self, result: ResultLike) -> dict[str, ContractResult]:
87
+ """Run all contracts, retaining failures from each contract."""
88
+ results: dict[str, ContractResult] = {}
89
+ for contract in self.contracts:
90
+ try:
91
+ results[contract.name] = contract.verify(result)
92
+ except Exception as error:
93
+ results[contract.name] = ContractResult(
94
+ passed=False,
95
+ failures=[f"{type(error).__name__}: {error}"],
96
+ )
97
+ if not self.passed(results):
98
+ raise ContractException(result, results)
99
+ return results
100
+
101
+ @staticmethod
102
+ def passed(results: dict[str, ContractResult]) -> bool:
103
+ """Return whether every Contract passed."""
104
+ return all(result.passed for result in results.values())
105
+
@@ -0,0 +1,111 @@
1
+ """Matching strategies and domain-specific match constraints."""
2
+ from __future__ import annotations
3
+
4
+ import inspect
5
+ from abc import ABC, abstractmethod
6
+
7
+ from graph_tool.topology import subgraph_isomorphism
8
+ from heterograph.hgraph import HGraph
9
+ from heterograph.query.processor_dfs import QueryProcessorDFS
10
+ from heterograph.query.qgraph import QGraph
11
+
12
+ class MatchStrategy(ABC):
13
+ """Interface for matching algorithms and semantic match constraints."""
14
+
15
+ @staticmethod
16
+ def vx_annotation(qgraph, vx, **kwargs):
17
+ pass
18
+
19
+ @staticmethod
20
+ def eg_annotation(qgraph, eg, **kwargs):
21
+ pass
22
+
23
+ @staticmethod
24
+ def vx_check(g, qgraph, vx, qvx):
25
+ return True
26
+
27
+ @staticmethod
28
+ def eg_check(g, qgraph, eg, qeg):
29
+ return True
30
+
31
+ @staticmethod
32
+ def check(g, qgraph, match):
33
+ return True
34
+
35
+ @abstractmethod
36
+ def find_matches(self, *, g: HGraph, select: str, where=None, **kwargs):
37
+ """Return bindings from the host graph and the parsed query graph.
38
+
39
+ Implementations may use different search strategies, but both apply
40
+ structural matching first and then semantic `where` filtering.
41
+ """
42
+
43
+
44
+ def deduplicate_matches(matches):
45
+ """Remove matches covering the same host vertices, preserving order."""
46
+ unique = {}
47
+ for match in matches:
48
+ unique.setdefault(frozenset(match.values()), match)
49
+ return list(unique.values())
50
+
51
+
52
+ class IsoMatchStrategy(MatchStrategy):
53
+ """Match patterns using graph-tool subgraph isomorphism."""
54
+
55
+ def find_matches(self, *, g, select, where=None, **kwargs):
56
+ deduplicate = kwargs.get('deduplicate', True)
57
+ max_n = kwargs.get('max_n', 0)
58
+ pattern = QGraph(select, vx_args=self.vx_annotation, eg_args=self.eg_annotation)
59
+ maps = subgraph_isomorphism(
60
+ pattern.igraph, g.igraph, induced=True, subgraph=True, generator=True
61
+ )
62
+ matches = []
63
+ for vmap in maps:
64
+ bind, qvx_to_vx = {}, {}
65
+ for q_ivx in pattern.igraph.vertices():
66
+ q_vx = pattern.to_vx[int(q_ivx)]
67
+ host_vx = g.to_vx[int(vmap[q_ivx])]
68
+ if not self.vx_check(g, pattern, host_vx, q_vx):
69
+ break
70
+ bind[pattern.pmap[q_vx]['id']] = host_vx
71
+ qvx_to_vx[q_vx] = host_vx
72
+ else:
73
+ if all(self.eg_check(g, pattern, (qvx_to_vx[e[0]], qvx_to_vx[e[1]]), e)
74
+ for e in pattern.edges) and self.check(g, pattern, bind) \
75
+ and (where is None or where(g, **bind)):
76
+ matches.append(bind)
77
+ if deduplicate:
78
+ matches = deduplicate_matches(matches)
79
+ if max_n > 0:
80
+ matches = matches[:max_n]
81
+ return matches, pattern
82
+
83
+
84
+ class DfsMatchStrategy(MatchStrategy):
85
+ """Match patterns using Heterograph's DFS query processor."""
86
+
87
+ def find_matches(self, *, g, select, where=None, **kwargs):
88
+ deduplicate = kwargs.get('deduplicate', True)
89
+ max_n = kwargs.get('max_n', 0)
90
+ pattern = QGraph(select, vx_args=self.vx_annotation, eg_args=self.eg_annotation)
91
+ params = set(inspect.signature(where).parameters) - {'g'} if where else set()
92
+
93
+ def match_filter(graph, qgraph, match):
94
+ if not self.check(graph, qgraph, match):
95
+ return False
96
+ return where(graph, **{k: v for k, v in match.items() if k in params}) if where else True
97
+
98
+ def distance_check(graph, qgraph, chain, qchain):
99
+ if qchain[0] is None or qchain[1] is None:
100
+ return True
101
+ constraint = qgraph.pmap[qchain]['xdist']
102
+ return constraint == 'any' or graph.pmap['dfs.depths'][chain[1]] - graph.pmap['dfs.depths'][chain[0]] == constraint
103
+
104
+ matches = QueryProcessorDFS().run(g=g, qgraph=pattern, path_check=distance_check,
105
+ match_filter=match_filter)
106
+ if deduplicate:
107
+ matches = deduplicate_matches(matches)
108
+ if max_n > 0:
109
+ matches = matches[:max_n]
110
+ return matches, pattern
111
+