loom-workflow 0.3.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.
- loom/__init__.py +25 -0
- loom/agent/__init__.py +17 -0
- loom/agent/loop.py +129 -0
- loom/agent/provider.py +70 -0
- loom/agent/task_gen.py +101 -0
- loom/core/__init__.py +18 -0
- loom/core/contract.py +103 -0
- loom/core/pipeline.py +111 -0
- loom/core/result.py +40 -0
- loom/core/task.py +34 -0
- loom/graphite/__init__.py +18 -0
- loom/graphite/match_strategy.py +110 -0
- loom/graphite/processor.py +343 -0
- loom/graphite/schema.py +201 -0
- loom/graphite/schema_constraints.py +34 -0
- loom/graphite/schema_contract.py +21 -0
- loom_workflow-0.3.0.dist-info/METADATA +221 -0
- loom_workflow-0.3.0.dist-info/RECORD +20 -0
- loom_workflow-0.3.0.dist-info/WHEEL +5 -0
- loom_workflow-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,110 @@
|
|
|
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
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
from heterograph.hgraph import HGraph
|
|
2
|
+
from heterograph.query.qgraph import QGraph
|
|
3
|
+
from .match_strategy import IsoMatchStrategy
|
|
4
|
+
|
|
5
|
+
class GraphProcessor:
|
|
6
|
+
"""Match AQL patterns and apply one in-place rewrite pass."""
|
|
7
|
+
def __init__(self, *, match_strategy=None, snapshot=True):
|
|
8
|
+
"""Create a processor with an optional match strategy and snapshots."""
|
|
9
|
+
self.match_strategy = (
|
|
10
|
+
IsoMatchStrategy() if match_strategy is None else match_strategy
|
|
11
|
+
)
|
|
12
|
+
self.snapshot = snapshot
|
|
13
|
+
if snapshot:
|
|
14
|
+
from heterograph.webview import WebView
|
|
15
|
+
self.webview = WebView()
|
|
16
|
+
else:
|
|
17
|
+
self.webview = None
|
|
18
|
+
self._snapshot_count = 0
|
|
19
|
+
|
|
20
|
+
# where(g, **match) -> bool
|
|
21
|
+
# finalize(g, **match) -> None (in-place modification)
|
|
22
|
+
def run(self, g:HGraph, *,
|
|
23
|
+
select:str,
|
|
24
|
+
where=None,
|
|
25
|
+
rewrite:str|None=None,
|
|
26
|
+
finalize=None, **kwargs):
|
|
27
|
+
|
|
28
|
+
snapshot_number = self._snapshot_count
|
|
29
|
+
capture = self.snapshot and rewrite is not None
|
|
30
|
+
if capture:
|
|
31
|
+
self.webview.add_graph(g, title=f"original #{snapshot_number}")
|
|
32
|
+
|
|
33
|
+
matches, pattern = self.match_strategy.find_matches(
|
|
34
|
+
g=g, select=select, where=where, **kwargs)
|
|
35
|
+
|
|
36
|
+
modified = False
|
|
37
|
+
|
|
38
|
+
if rewrite and matches:
|
|
39
|
+
modified = self._rewrite(
|
|
40
|
+
g=g,
|
|
41
|
+
rewrite=rewrite,
|
|
42
|
+
finalize=finalize,
|
|
43
|
+
matches=matches,
|
|
44
|
+
find_pattern_graph=pattern
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
if capture:
|
|
48
|
+
self.webview.add_graph(g, title=f"rewrite #{snapshot_number}")
|
|
49
|
+
self._snapshot_count += 1
|
|
50
|
+
|
|
51
|
+
return {'matches': matches, 'pattern': pattern, 'modified': modified}
|
|
52
|
+
|
|
53
|
+
def snapshot_view(self):
|
|
54
|
+
"""Display the captured snapshots in the processor's WebView."""
|
|
55
|
+
if self.webview is None:
|
|
56
|
+
raise RuntimeError("snapshot_view() requires GraphProcessor(snapshot=True).")
|
|
57
|
+
return self.webview.run()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _rewrite(self, *, g, rewrite, finalize, matches, find_pattern_graph) -> bool:
|
|
61
|
+
"""Apply a parsed RHS to a disjoint set of LHS bindings.
|
|
62
|
+
|
|
63
|
+
The rewrite is performed in stages: create RHS-only vertices, add RHS
|
|
64
|
+
edges, redirect annotated boundary edges, run ``finalize``, remove
|
|
65
|
+
obsolete preserved-preserved edges, and finally delete LHS-only
|
|
66
|
+
vertices. Keeping cleanup last lets ``finalize`` inspect the complete
|
|
67
|
+
replacement while protecting the cleanup targets from accidental
|
|
68
|
+
removal.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# ---- Overlap detection (mandatory for rewrite) ----
|
|
73
|
+
used = set()
|
|
74
|
+
for m in matches:
|
|
75
|
+
vs = set(m.values())
|
|
76
|
+
overlap = used & vs
|
|
77
|
+
if overlap:
|
|
78
|
+
raise RuntimeError(
|
|
79
|
+
f"Overlapping matches detected on vertices {overlap}. "
|
|
80
|
+
"Rewrites require disjoint matches."
|
|
81
|
+
)
|
|
82
|
+
used |= vs
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
modified = False
|
|
86
|
+
|
|
87
|
+
# a{rewire:c}
|
|
88
|
+
# a :=> {in: c, out:c}
|
|
89
|
+
rewire_dict = { }
|
|
90
|
+
def node_pattern_annotations(qgraph, vx, rewire=None, rewire_in=None, rewire_out=None):
|
|
91
|
+
if all(r is None for r in [rewire, rewire_in, rewire_out]):
|
|
92
|
+
return
|
|
93
|
+
target = qgraph.pmap[vx]['id']
|
|
94
|
+
if target in rewire_dict:
|
|
95
|
+
raise RuntimeError(
|
|
96
|
+
f"Multiple rewire annotations on the same pattern node [{target}] are not allowed."
|
|
97
|
+
)
|
|
98
|
+
if rewire is not None:
|
|
99
|
+
rewire_dict[target] = { 'in': rewire, 'out': rewire }
|
|
100
|
+
if rewire_in is not None:
|
|
101
|
+
rewire_dict[target] = { 'in': rewire_in, 'out': None }
|
|
102
|
+
if rewire_out is not None:
|
|
103
|
+
rewire_dict[target] = { 'in': None, 'out': rewire_out }
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
rewrite_pattern_graph = QGraph(rewrite,
|
|
107
|
+
vx_args=node_pattern_annotations)
|
|
108
|
+
|
|
109
|
+
# --- Precompute pattern-level sets
|
|
110
|
+
L = set(find_pattern_graph.pmap['ids'].keys())
|
|
111
|
+
R = set(rewrite_pattern_graph.pmap['ids'].keys())
|
|
112
|
+
|
|
113
|
+
preserved_ids = L & R
|
|
114
|
+
deleted_ids = L - R
|
|
115
|
+
created_ids = R - L
|
|
116
|
+
|
|
117
|
+
LE = set([(find_pattern_graph.pmap[s]['id'],
|
|
118
|
+
find_pattern_graph.pmap[t]['id']) for (s, t) in find_pattern_graph.edges])
|
|
119
|
+
|
|
120
|
+
RE = set([(rewrite_pattern_graph.pmap[s]['id'],
|
|
121
|
+
rewrite_pattern_graph.pmap[t]['id']) for (s, t) in rewrite_pattern_graph.edges])
|
|
122
|
+
|
|
123
|
+
add_internal_edges = RE - LE
|
|
124
|
+
remove_internal_edges = LE - RE
|
|
125
|
+
|
|
126
|
+
if 0:
|
|
127
|
+
print(f"preserved_ids: {preserved_ids}")
|
|
128
|
+
print(f"deleted_ids: {deleted_ids}")
|
|
129
|
+
print(f"created_ids: {created_ids}")
|
|
130
|
+
print(f"LE: {LE}")
|
|
131
|
+
print(f"RE: {RE}")
|
|
132
|
+
print(f"add_internal_edges: {add_internal_edges}")
|
|
133
|
+
print(f"remove_internal_edges: {remove_internal_edges}")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# --- Validate rewire annotations ---
|
|
137
|
+
# The annotated node is the receiver and must exist in the RHS.
|
|
138
|
+
# The referenced node is the deleted source and must be LHS-only.
|
|
139
|
+
for receiver_id, info in rewire_dict.items():
|
|
140
|
+
if receiver_id not in R:
|
|
141
|
+
raise RuntimeError(
|
|
142
|
+
f"rewire receiver [{receiver_id}] must exist in the RHS."
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
for direction in ("in", "out"):
|
|
146
|
+
source_id = info[direction]
|
|
147
|
+
if source_id is not None and source_id not in deleted_ids:
|
|
148
|
+
raise RuntimeError(
|
|
149
|
+
f"rewire source [{source_id}] must be deleted by the rewrite."
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
# --- Apply rewrites for this single pass
|
|
153
|
+
for m in matches:
|
|
154
|
+
# step 1: Detect invalidated matches (some vx may have been deleted by earlier rewrites)
|
|
155
|
+
# Ensure all LHS ids in m still exist in graph
|
|
156
|
+
|
|
157
|
+
if not g.check_vx(list(m.values()), verify=False):
|
|
158
|
+
vx_removed = { vx for vx in m.values() if not g.check_vx(vx, verify=False) }
|
|
159
|
+
|
|
160
|
+
raise RuntimeError("[x] Match contains vertices that no longer exist in the graph. "
|
|
161
|
+
"This indicates integrity issues with the rewrite rules. "
|
|
162
|
+
f"Match: {m} / Removed vertices: {vx_removed}")
|
|
163
|
+
|
|
164
|
+
# step 2: Build initial bindings
|
|
165
|
+
bind = dict(m)
|
|
166
|
+
|
|
167
|
+
# step 3: Add new vertices for RHS-only ids
|
|
168
|
+
for rid in created_ids:
|
|
169
|
+
new_vx = g.add_vx(1) # returns single vx
|
|
170
|
+
bind[rid] = new_vx
|
|
171
|
+
modified = True
|
|
172
|
+
|
|
173
|
+
# add reverse_bind
|
|
174
|
+
matched_vs = set(bind.values()) # host vertices in match
|
|
175
|
+
# Build reverse lookup: host_vx -> pattern_id
|
|
176
|
+
reverse_bind = {vx: pid for pid, vx in bind.items()}
|
|
177
|
+
|
|
178
|
+
if 0:
|
|
179
|
+
print(f"bind: {bind}")
|
|
180
|
+
print(f"reverse_bind: {reverse_bind}")
|
|
181
|
+
|
|
182
|
+
# step 4: adding RHS-only edges: internal edge additions
|
|
183
|
+
for (sid, tid) in add_internal_edges:
|
|
184
|
+
s_vx = bind[sid]
|
|
185
|
+
t_vx = bind[tid]
|
|
186
|
+
ret = g.add_edge(s_vx, t_vx)
|
|
187
|
+
if ret:
|
|
188
|
+
modified = True
|
|
189
|
+
|
|
190
|
+
# For each deleted id X that is inherited by RHS id Y
|
|
191
|
+
# {'matmul': {'in': 'd', 'out': None}, 'act': {'in': None, 'out': 'd'}}
|
|
192
|
+
for y_id, info in rewire_dict.items():
|
|
193
|
+
y_vx = bind[y_id]
|
|
194
|
+
x_id_in = info["in"]
|
|
195
|
+
x_id_out = info["out"]
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
# ---- Conflict Detection ----
|
|
199
|
+
# Rewiring only redirects edges crossing the match boundary.
|
|
200
|
+
# If the other endpoint is inside the match and is preserved,
|
|
201
|
+
# redirecting it would implicitly create an internal RHS edge.
|
|
202
|
+
# That edge must be written explicitly in RE; otherwise the
|
|
203
|
+
# rewrite would silently change the internal graph structure.
|
|
204
|
+
# E.g., the follwowing is invalid because the internal edge (a, c) is not in the RHS:
|
|
205
|
+
# select="a => b",
|
|
206
|
+
# rewrite="a; c {rewire_in:b}",
|
|
207
|
+
|
|
208
|
+
# Incoming edge: preserved source -> deleted source
|
|
209
|
+
# becomes preserved source -> receiver.
|
|
210
|
+
if info["in"] is not None:
|
|
211
|
+
source_id = info["in"]
|
|
212
|
+
source_vx = bind[source_id]
|
|
213
|
+
for src_vx in g.in_vx(source_vx):
|
|
214
|
+
if src_vx in matched_vs:
|
|
215
|
+
src_id = reverse_bind[src_vx]
|
|
216
|
+
if src_id in preserved_ids and src_id != y_id: # we allow self-edges
|
|
217
|
+
if (src_id, y_id) not in RE:
|
|
218
|
+
raise RuntimeError(
|
|
219
|
+
f"rewire_in conflict: deleting '{source_id}' and rewiring "
|
|
220
|
+
f"would create internal edge {(src_id, y_id)}, "
|
|
221
|
+
f"but RHS does not contain this edge."
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
# Outgoing edge: deleted source -> preserved destination
|
|
225
|
+
# becomes receiver -> preserved destination.
|
|
226
|
+
if info["out"] is not None:
|
|
227
|
+
source_id = info["out"]
|
|
228
|
+
source_vx = bind[source_id]
|
|
229
|
+
for dst_vx in g.out_vx(source_vx):
|
|
230
|
+
if dst_vx in matched_vs:
|
|
231
|
+
dst_id = reverse_bind[dst_vx]
|
|
232
|
+
if dst_id in preserved_ids and dst_id != y_id: # we allow self-edges
|
|
233
|
+
if (y_id, dst_id) not in RE:
|
|
234
|
+
raise RuntimeError(
|
|
235
|
+
f"rewire_out conflict: deleting '{source_id}' and rewiring "
|
|
236
|
+
f"would create internal edge {(y_id, dst_id)}, "
|
|
237
|
+
f"but RHS does not contain this edge."
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
# ---- MUTATION PASS ----
|
|
241
|
+
# Conflict detection has passed. Redirect only edges that
|
|
242
|
+
# cross the match boundary. The old edges remain until the
|
|
243
|
+
# deleted source vertices are removed below.
|
|
244
|
+
|
|
245
|
+
# Incoming rewiring:
|
|
246
|
+
# external_source -> deleted_source
|
|
247
|
+
# becomes:
|
|
248
|
+
# external_source -> receiver
|
|
249
|
+
if x_id_in is not None:
|
|
250
|
+
x_vx = bind[x_id_in]
|
|
251
|
+
for src_vx in g.in_vx(x_vx):
|
|
252
|
+
# Internal edges are controlled explicitly by the RHS;
|
|
253
|
+
# they must not be redirected in this pass.
|
|
254
|
+
if src_vx not in matched_vs:
|
|
255
|
+
ret = g.add_edge(src_vx, y_vx)
|
|
256
|
+
if ret:
|
|
257
|
+
# Preserve edge metadata such as ports,
|
|
258
|
+
# channels, and indices.
|
|
259
|
+
g.pmap[ret[0]] = g.pmap[(src_vx, x_vx)].copy() # copy properties from source vertex to new edge
|
|
260
|
+
|
|
261
|
+
# Outgoing rewiring:
|
|
262
|
+
# deleted_source -> external_destination
|
|
263
|
+
# becomes:
|
|
264
|
+
# receiver -> external_destination
|
|
265
|
+
if x_id_out is not None:
|
|
266
|
+
x_vx = bind[x_id_out]
|
|
267
|
+
for dst_vx in g.out_vx(x_vx):
|
|
268
|
+
# As above, leave internal edges to the explicit RHS
|
|
269
|
+
# edge additions and removals.
|
|
270
|
+
if dst_vx not in matched_vs:
|
|
271
|
+
ret = g.add_edge(y_vx, dst_vx)
|
|
272
|
+
if ret:
|
|
273
|
+
# Copy metadata before the old source vertex
|
|
274
|
+
# is removed together with its original edge.
|
|
275
|
+
g.pmap[ret[0]] = g.pmap[(x_vx, dst_vx)].copy()
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
if finalize:
|
|
279
|
+
deleted_vxs = {bind[did] for did in deleted_ids}
|
|
280
|
+
planned_removed_edges = {
|
|
281
|
+
edge for edge in g.edges
|
|
282
|
+
if edge[0] in deleted_vxs or edge[1] in deleted_vxs
|
|
283
|
+
}
|
|
284
|
+
planned_removed_edges.update(
|
|
285
|
+
(bind[sid], bind[tid])
|
|
286
|
+
for sid, tid in remove_internal_edges
|
|
287
|
+
if sid in preserved_ids and tid in preserved_ids
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
finalize_result = finalize(g, **bind)
|
|
291
|
+
|
|
292
|
+
# finalize may perform other graph updates, but it must not
|
|
293
|
+
# preempt this rewrite's cleanup. Deleted vertices must still
|
|
294
|
+
# exist so the rewrite can remove them, and LHS-only edges
|
|
295
|
+
# between preserved vertices must still exist so they can be
|
|
296
|
+
# removed below.
|
|
297
|
+
missing_deleted = [
|
|
298
|
+
did for did in deleted_ids
|
|
299
|
+
if not g.check_vx(bind[did], verify=False)
|
|
300
|
+
]
|
|
301
|
+
if missing_deleted:
|
|
302
|
+
raise RuntimeError(
|
|
303
|
+
"finalize removed vertices that the rewrite must remove: "
|
|
304
|
+
f"{missing_deleted}."
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
missing_edges = [
|
|
308
|
+
edge for edge in planned_removed_edges
|
|
309
|
+
if not g.check_edge(edge)
|
|
310
|
+
]
|
|
311
|
+
if missing_edges:
|
|
312
|
+
raise RuntimeError(
|
|
313
|
+
"finalize removed edges that the rewrite must remove: "
|
|
314
|
+
f"{missing_edges}."
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
if type(finalize_result) is not bool:
|
|
318
|
+
raise RuntimeError(
|
|
319
|
+
"finalize callback must return a bool, "
|
|
320
|
+
f"got {type(finalize_result).__name__}."
|
|
321
|
+
)
|
|
322
|
+
if finalize_result:
|
|
323
|
+
modified = True
|
|
324
|
+
|
|
325
|
+
# -- remove internal edges (LHS edges not in RHS)
|
|
326
|
+
# -- also, we want to make sure that both source and target
|
|
327
|
+
# -- nodes are preserved
|
|
328
|
+
for (sid, tid) in remove_internal_edges:
|
|
329
|
+
if sid in preserved_ids and tid in preserved_ids:
|
|
330
|
+
s_vx = bind[sid]
|
|
331
|
+
t_vx = bind[tid]
|
|
332
|
+
if g.check_edge((s_vx, t_vx)):
|
|
333
|
+
g.rm_edge((s_vx, t_vx))
|
|
334
|
+
modified = True
|
|
335
|
+
|
|
336
|
+
# -- remove vertices marked to be removed
|
|
337
|
+
for did in deleted_ids:
|
|
338
|
+
vx = bind[did]
|
|
339
|
+
if g.check_vx(vx, verify=False):
|
|
340
|
+
g.rm_vx(vx)
|
|
341
|
+
modified = True
|
|
342
|
+
|
|
343
|
+
return modified
|
loom/graphite/schema.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""Schema validation framework for Heterograph-based intermediate representations."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from typing import Callable, Type
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ValidationError
|
|
9
|
+
from heterograph import HGraph
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Severity(str, Enum):
|
|
13
|
+
ERROR = "error"
|
|
14
|
+
WARNING = "warning"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class Issue:
|
|
19
|
+
severity: Severity
|
|
20
|
+
location: str
|
|
21
|
+
message: str
|
|
22
|
+
|
|
23
|
+
def __str__(self) -> str:
|
|
24
|
+
return f"[{self.severity.value}] {self.location}: {self.message}"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class ValidationReport:
|
|
29
|
+
schema: str
|
|
30
|
+
issues: list[Issue] = field(default_factory=list)
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def errors(self) -> list[Issue]:
|
|
34
|
+
return [issue for issue in self.issues if issue.severity == Severity.ERROR]
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def ok(self) -> bool:
|
|
38
|
+
return not self.errors
|
|
39
|
+
|
|
40
|
+
def __str__(self) -> str:
|
|
41
|
+
if not self.issues:
|
|
42
|
+
return f"OK {self.schema}: 0 issues"
|
|
43
|
+
errors = len(self.errors)
|
|
44
|
+
warnings = len(self.issues) - errors
|
|
45
|
+
head = f"FAIL {self.schema}: {errors} error(s), {warnings} warning(s)"
|
|
46
|
+
return "\n".join([head] + [f" {issue}" for issue in self.issues])
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
Rule = Callable[[HGraph], list[Issue]]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class GraphSchema:
|
|
54
|
+
"""Declarative metadata schema, validation, construction, and styling."""
|
|
55
|
+
name: str
|
|
56
|
+
graph: Type[BaseModel] | None = None
|
|
57
|
+
vertex: dict[str, Type[BaseModel]] = field(default_factory=dict)
|
|
58
|
+
edge: dict[str, Type[BaseModel]] = field(default_factory=dict)
|
|
59
|
+
rules: list[Rule] = field(default_factory=list)
|
|
60
|
+
|
|
61
|
+
def style(self, graph: HGraph) -> None:
|
|
62
|
+
"""Apply the default visualization style for this IR.
|
|
63
|
+
|
|
64
|
+
Subclasses may override this method to provide IR-specific labels,
|
|
65
|
+
colours, or layout options. Styling is deliberately separate from
|
|
66
|
+
validation so visualization metadata never affects IR correctness.
|
|
67
|
+
"""
|
|
68
|
+
graph.style = {
|
|
69
|
+
"rankdir": "LR",
|
|
70
|
+
"label": self.name,
|
|
71
|
+
"labelloc": "t",
|
|
72
|
+
}
|
|
73
|
+
graph.vstyle = {
|
|
74
|
+
"label": lambda g, vertex: g.pmap[vertex].get("_type", "?"),
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
def new_graph(self) -> HGraph:
|
|
78
|
+
"""Create an empty graph identified by this schema and style it."""
|
|
79
|
+
graph = HGraph()
|
|
80
|
+
graph.pmap["_type"] = self.name
|
|
81
|
+
self.style(graph)
|
|
82
|
+
return graph
|
|
83
|
+
|
|
84
|
+
def new_vertex(self, graph: HGraph, _type: str, **props: object) -> int:
|
|
85
|
+
"""Validate and add a typed vertex, returning its host ID."""
|
|
86
|
+
data = self._vertex_data(_type, props)
|
|
87
|
+
vertex = graph.add_vx()
|
|
88
|
+
graph.pmap[vertex] = data
|
|
89
|
+
return vertex
|
|
90
|
+
|
|
91
|
+
def new_edge(self, graph: HGraph, source: int, target: int,
|
|
92
|
+
_type: str, **props: object) -> tuple[int, int]:
|
|
93
|
+
"""Validate and add a typed directed edge."""
|
|
94
|
+
data = self._edge_data(_type, props)
|
|
95
|
+
graph.add_edge(source, target)
|
|
96
|
+
edge = (source, target)
|
|
97
|
+
graph.pmap[edge] = data
|
|
98
|
+
return edge
|
|
99
|
+
|
|
100
|
+
def update_vertex(self, graph: HGraph, vertex: int, **changes: object) -> None:
|
|
101
|
+
"""Validate and replace selected properties on an existing vertex."""
|
|
102
|
+
current = dict(graph.pmap[vertex])
|
|
103
|
+
current.update(changes)
|
|
104
|
+
graph.pmap[vertex] = self._vertex_data(current["_type"], current)
|
|
105
|
+
|
|
106
|
+
def update_edge(self, graph: HGraph, edge: tuple[int, int], **changes: object) -> None:
|
|
107
|
+
"""Validate and replace selected properties on an existing edge."""
|
|
108
|
+
current = dict(graph.pmap[edge])
|
|
109
|
+
current.update(changes)
|
|
110
|
+
graph.pmap[edge] = self._edge_data(current["_type"], current)
|
|
111
|
+
|
|
112
|
+
def _vertex_data(self, _type: str, props: dict[str, object]) -> dict:
|
|
113
|
+
"""Validate properties for one vertex type and serialize aliases."""
|
|
114
|
+
if _type not in self.vertex:
|
|
115
|
+
raise KeyError(f"unknown vertex schema {_type!r}")
|
|
116
|
+
values = dict(props)
|
|
117
|
+
values["_type"] = _type
|
|
118
|
+
return self.vertex[_type].model_validate(
|
|
119
|
+
values, extra="forbid"
|
|
120
|
+
).model_dump(by_alias=True)
|
|
121
|
+
|
|
122
|
+
def _edge_data(self, _type: str, props: dict[str, object]) -> dict:
|
|
123
|
+
"""Validate properties for one edge type and serialize aliases."""
|
|
124
|
+
if _type not in self.edge:
|
|
125
|
+
raise KeyError(f"unknown edge schema {_type!r}")
|
|
126
|
+
values = dict(props)
|
|
127
|
+
values["_type"] = _type
|
|
128
|
+
return self.edge[_type].model_validate(
|
|
129
|
+
values, extra="forbid"
|
|
130
|
+
).model_dump(by_alias=True)
|
|
131
|
+
|
|
132
|
+
def validate(self, graph: HGraph) -> ValidationReport:
|
|
133
|
+
"""Return a report covering graph, item metadata, and structural rules."""
|
|
134
|
+
issues: list[Issue] = []
|
|
135
|
+
|
|
136
|
+
from .schema_constraints import require_graph_type, require_type
|
|
137
|
+
issues += require_graph_type(graph, self.name)
|
|
138
|
+
issues += require_type(graph)
|
|
139
|
+
|
|
140
|
+
if self.graph is not None:
|
|
141
|
+
issues += _check_model(
|
|
142
|
+
self.graph,
|
|
143
|
+
graph.pmap,
|
|
144
|
+
"graph",
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
for vertex in graph.vertices:
|
|
148
|
+
data = graph.pmap[vertex]
|
|
149
|
+
if not self.vertex:
|
|
150
|
+
continue
|
|
151
|
+
if not isinstance(data, dict):
|
|
152
|
+
issues.append(Issue(Severity.ERROR, f"vertex {vertex}",
|
|
153
|
+
"vertex properties must be a dict"))
|
|
154
|
+
continue
|
|
155
|
+
kind = data.get("_type")
|
|
156
|
+
if kind is None:
|
|
157
|
+
issues.append(Issue(Severity.ERROR, f"vertex {vertex}",
|
|
158
|
+
"missing _type"))
|
|
159
|
+
continue
|
|
160
|
+
model = self.vertex.get(kind)
|
|
161
|
+
if model is None:
|
|
162
|
+
issues.append(Issue(Severity.ERROR, f"vertex {vertex}",
|
|
163
|
+
f"unknown _type {kind!r} in schema {self.name}"))
|
|
164
|
+
continue
|
|
165
|
+
issues += _check_model(model, data, f"vertex {vertex}")
|
|
166
|
+
|
|
167
|
+
if self.edge:
|
|
168
|
+
for edge in graph.edges:
|
|
169
|
+
data = graph.pmap[edge]
|
|
170
|
+
if not isinstance(data, dict):
|
|
171
|
+
issues.append(Issue(Severity.ERROR, f"edge {edge}",
|
|
172
|
+
"edge properties must be a dict"))
|
|
173
|
+
continue
|
|
174
|
+
kind = data.get("_type")
|
|
175
|
+
if kind is None:
|
|
176
|
+
issues.append(Issue(Severity.ERROR, f"edge {edge}",
|
|
177
|
+
"missing _type"))
|
|
178
|
+
continue
|
|
179
|
+
model = self.edge.get(kind)
|
|
180
|
+
if model is None:
|
|
181
|
+
issues.append(Issue(Severity.ERROR, f"edge {edge}",
|
|
182
|
+
f"unknown _type {kind!r} in schema {self.name}"))
|
|
183
|
+
continue
|
|
184
|
+
issues += _check_model(model, data, f"edge {edge}")
|
|
185
|
+
|
|
186
|
+
for rule in self.rules:
|
|
187
|
+
issues += rule(graph)
|
|
188
|
+
return ValidationReport(self.name, issues)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _check_model(model: Type[BaseModel], data: object, location: str) -> list[Issue]:
|
|
192
|
+
if not isinstance(data, dict):
|
|
193
|
+
return [Issue(Severity.ERROR, location,
|
|
194
|
+
f"properties must be a dict, got {type(data).__name__}")]
|
|
195
|
+
try:
|
|
196
|
+
model.model_validate(data, extra="forbid")
|
|
197
|
+
except ValidationError as error:
|
|
198
|
+
return [Issue(Severity.ERROR, location,
|
|
199
|
+
f"{'.'.join(str(p) for p in item['loc'])}: {item['msg']}")
|
|
200
|
+
for item in error.errors()]
|
|
201
|
+
return []
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Validation rules shared by every IR schema."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from heterograph import HGraph
|
|
5
|
+
|
|
6
|
+
from .schema import Issue, Severity
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def require_type(graph: HGraph) -> list[Issue]:
|
|
10
|
+
"""Require every vertex and edge property map to have ``_type``."""
|
|
11
|
+
issues: list[Issue] = []
|
|
12
|
+
for vertex in graph.vertices:
|
|
13
|
+
props = graph.pmap[vertex]
|
|
14
|
+
if not isinstance(props, dict) or "_type" not in props:
|
|
15
|
+
issues.append(Issue(Severity.ERROR, f"vertex {vertex}",
|
|
16
|
+
"missing _type"))
|
|
17
|
+
for edge in graph.edges:
|
|
18
|
+
props = graph.pmap[edge]
|
|
19
|
+
if not isinstance(props, dict) or "_type" not in props:
|
|
20
|
+
issues.append(Issue(Severity.ERROR, f"edge {edge}",
|
|
21
|
+
"missing _type"))
|
|
22
|
+
return issues
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def require_graph_type(graph: HGraph, schema_name: str) -> list[Issue]:
|
|
26
|
+
"""Require graph-level ``_type`` to identify the active IR schema."""
|
|
27
|
+
actual = graph.pmap.get("_type")
|
|
28
|
+
if actual != schema_name:
|
|
29
|
+
return [Issue(Severity.ERROR, "graph._type",
|
|
30
|
+
f"expected {schema_name!r}, got {actual!r}")]
|
|
31
|
+
return []
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
SCHEMA_CONSTRAINTS = [require_graph_type, require_type]
|