vgraph 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.
- vgraph/__init__.py +25 -0
- vgraph/api.py +45 -0
- vgraph/cli.py +41 -0
- vgraph/compile.py +247 -0
- vgraph/engine.py +314 -0
- vgraph/graph.schema.json +56 -0
- vgraph/inputs.py +82 -0
- vgraph/model.py +63 -0
- vgraph/py.typed +0 -0
- vgraph/registry.py +183 -0
- vgraph/server/__init__.py +1 -0
- vgraph/server/app.py +248 -0
- vgraph/server/state.py +96 -0
- vgraph/server/views.py +89 -0
- vgraph/server/watch.py +48 -0
- vgraph/static/assets/index-BAxILRja.js +64 -0
- vgraph/static/assets/index-CsCg66zj.css +1 -0
- vgraph/static/index.html +14 -0
- vgraph/topology.py +129 -0
- vgraph/typing_utils.py +88 -0
- vgraph-0.1.0.dist-info/METADATA +213 -0
- vgraph-0.1.0.dist-info/RECORD +25 -0
- vgraph-0.1.0.dist-info/WHEEL +4 -0
- vgraph-0.1.0.dist-info/entry_points.txt +3 -0
- vgraph-0.1.0.dist-info/licenses/LICENSE +201 -0
vgraph/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""vgraph: typed function graphs with a local web UI."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
|
|
5
|
+
from vgraph.api import Graph, GraphValidationError, load
|
|
6
|
+
from vgraph.engine import Execution, RunResult, RunStatus, Status
|
|
7
|
+
from vgraph.inputs import InputError
|
|
8
|
+
from vgraph.registry import Param, branch, node
|
|
9
|
+
|
|
10
|
+
__version__ = version("vgraph")
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"node",
|
|
14
|
+
"branch",
|
|
15
|
+
"load",
|
|
16
|
+
"Graph",
|
|
17
|
+
"GraphValidationError",
|
|
18
|
+
"InputError",
|
|
19
|
+
"Param",
|
|
20
|
+
"Execution",
|
|
21
|
+
"RunResult",
|
|
22
|
+
"RunStatus",
|
|
23
|
+
"Status",
|
|
24
|
+
"__version__",
|
|
25
|
+
]
|
vgraph/api.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Public Python API: ``load(path, functions).run(**inputs)`` (spec §4.6)."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from vgraph.compile import CompiledGraph, Issue, compile_graph
|
|
8
|
+
from vgraph.engine import RunResult, execute
|
|
9
|
+
from vgraph.inputs import coerce_inputs
|
|
10
|
+
from vgraph.model import parse_graph_yaml
|
|
11
|
+
from vgraph.registry import Param, discover
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class GraphValidationError(ValueError):
|
|
15
|
+
def __init__(self, issues: list[Issue], context: list[str] | None = None):
|
|
16
|
+
super().__init__("\n".join([f"{i.code}: {i.message}" for i in issues] + (context or [])))
|
|
17
|
+
self.issues = issues
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Graph:
|
|
21
|
+
def __init__(self, compiled: CompiledGraph):
|
|
22
|
+
self._compiled = compiled
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def inputs(self) -> dict[str, Param]:
|
|
26
|
+
return self._compiled.inputs
|
|
27
|
+
|
|
28
|
+
def run(self, **inputs: Any) -> RunResult:
|
|
29
|
+
try:
|
|
30
|
+
asyncio.get_running_loop()
|
|
31
|
+
except RuntimeError:
|
|
32
|
+
return asyncio.run(self.arun(**inputs))
|
|
33
|
+
raise RuntimeError("use 'await graph.arun(...)' inside an event loop")
|
|
34
|
+
|
|
35
|
+
async def arun(self, **inputs: Any) -> RunResult:
|
|
36
|
+
return await execute(self._compiled, coerce_inputs(self._compiled, inputs))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def load(path: str | Path, functions: str | Path) -> Graph:
|
|
40
|
+
"""Load and validate a graph file against the functions found in ``functions``."""
|
|
41
|
+
registry = discover(functions)
|
|
42
|
+
compiled, issues = compile_graph(parse_graph_yaml(Path(path).read_text()), registry)
|
|
43
|
+
if issues or compiled is None:
|
|
44
|
+
raise GraphValidationError(issues, [f"{i.module}: {i.message}" for i in registry.issues])
|
|
45
|
+
return Graph(compiled)
|
vgraph/cli.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""The `vgraph` command line."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
import webbrowser
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import uvicorn
|
|
13
|
+
|
|
14
|
+
from vgraph.server.app import create_app
|
|
15
|
+
|
|
16
|
+
HOST = "127.0.0.1"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def main(argv: list[str] | None = None) -> int:
|
|
20
|
+
parser = argparse.ArgumentParser(prog="vgraph")
|
|
21
|
+
sub = parser.add_subparsers(dest="command")
|
|
22
|
+
serve = sub.add_parser(
|
|
23
|
+
"serve", help="serve the graph editor for a module, package or directory"
|
|
24
|
+
)
|
|
25
|
+
serve.add_argument("target")
|
|
26
|
+
serve.add_argument("--graphs", type=Path, default=Path("graphs"))
|
|
27
|
+
serve.add_argument("--port", type=int, default=8765)
|
|
28
|
+
serve.add_argument("--no-browser", action="store_true")
|
|
29
|
+
args = parser.parse_args(argv)
|
|
30
|
+
if args.command != "serve":
|
|
31
|
+
parser.print_help()
|
|
32
|
+
return 2
|
|
33
|
+
if os.getcwd() not in sys.path: # console scripts put their bin/ there instead
|
|
34
|
+
sys.path.insert(0, os.getcwd())
|
|
35
|
+
args.graphs.mkdir(parents=True, exist_ok=True)
|
|
36
|
+
if not args.no_browser:
|
|
37
|
+
timer = threading.Timer(1.0, webbrowser.open, [f"http://{HOST}:{args.port}/"])
|
|
38
|
+
timer.daemon = True
|
|
39
|
+
timer.start()
|
|
40
|
+
uvicorn.run(create_app(args.target, args.graphs), host=HOST, port=args.port)
|
|
41
|
+
return 0
|
vgraph/compile.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Compile a graph file against a registry: input bindings plus every static check."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from itertools import combinations, product
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from vgraph.model import GraphFile
|
|
9
|
+
from vgraph.registry import FunctionSpec, Param, Registry
|
|
10
|
+
from vgraph.topology import Topology, build_topology
|
|
11
|
+
from vgraph.typing_utils import is_compatible
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class Issue:
|
|
16
|
+
code: str
|
|
17
|
+
message: str
|
|
18
|
+
node: str | None = None
|
|
19
|
+
edge: tuple[str, str] | None = None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Binding:
|
|
24
|
+
param: str
|
|
25
|
+
producers: tuple[str, ...] # forward ancestors producing the name (mutually exclusive)
|
|
26
|
+
feedback: tuple[str, ...] # in-loop producers reached only via back edge
|
|
27
|
+
graph_input: bool
|
|
28
|
+
has_default: bool
|
|
29
|
+
default: Any
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class CompiledGraph:
|
|
34
|
+
file: GraphFile
|
|
35
|
+
topology: Topology
|
|
36
|
+
specs: dict[str, FunctionSpec] # by node id
|
|
37
|
+
bindings: dict[str, dict[str, Binding]] # node id -> param -> binding
|
|
38
|
+
inputs: dict[str, Param] # graph inputs (required + optional)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _cyclic_reach(topo: Topology, start: str) -> set[str]:
|
|
42
|
+
"""Nodes reachable from ``start`` following forward and back edges."""
|
|
43
|
+
edges = topo.forward + topo.back
|
|
44
|
+
seen: set[str] = set()
|
|
45
|
+
todo = [start]
|
|
46
|
+
while todo:
|
|
47
|
+
n = todo.pop()
|
|
48
|
+
for e in edges:
|
|
49
|
+
if e.src == n and e.dst not in seen:
|
|
50
|
+
seen.add(e.dst)
|
|
51
|
+
todo.append(e.dst)
|
|
52
|
+
return seen
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _runs(topo: Topology, n: str, chosen: dict[str, str], memo: dict[str, bool]) -> bool:
|
|
56
|
+
"""Whether ``n`` runs in a pass where each branch in ``chosen`` takes that exit."""
|
|
57
|
+
if n not in memo:
|
|
58
|
+
memo[n] = n in topo.entries or any(
|
|
59
|
+
(e.exit is None or chosen[e.src] == e.exit) and _runs(topo, e.src, chosen, memo)
|
|
60
|
+
for e in topo.preds(n)
|
|
61
|
+
)
|
|
62
|
+
return memo[n]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _bypassed(graph: GraphFile, topo: Topology, c: str, producers: list[str]) -> bool:
|
|
66
|
+
"""Whether some choice of one exit per upstream branch runs ``c`` but none of ``producers``."""
|
|
67
|
+
ups = topo.ancestors(c)
|
|
68
|
+
branches = [n for n in topo.nodes if n in ups and isinstance(graph.nodes[n].next, dict)]
|
|
69
|
+
exits = [list(graph.nodes[n].next) for n in branches]
|
|
70
|
+
if math.prod(len(m) for m in exits) > 4096:
|
|
71
|
+
# shortcut: exhaustive branch enumeration capped at 4096 combinations,
|
|
72
|
+
# fall back to path check beyond that
|
|
73
|
+
return topo.reachable_avoiding(c, set(producers))
|
|
74
|
+
for picked in product(*exits):
|
|
75
|
+
chosen, memo = dict(zip(branches, picked, strict=True)), {}
|
|
76
|
+
if _runs(topo, c, chosen, memo) and not any(
|
|
77
|
+
_runs(topo, q, chosen, memo) for q in producers
|
|
78
|
+
):
|
|
79
|
+
return True
|
|
80
|
+
return False
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _structure(graph: GraphFile, registry: Registry, topo: Topology) -> list[Issue]:
|
|
84
|
+
issues: list[Issue] = []
|
|
85
|
+
if not topo.entries:
|
|
86
|
+
issues.append(Issue("no_entry", "graph has no entry node"))
|
|
87
|
+
for name, ns in graph.nodes.items():
|
|
88
|
+
targets = ns.next if isinstance(ns.next, list) else list(ns.next.values())
|
|
89
|
+
for t in dict.fromkeys(targets):
|
|
90
|
+
if t not in graph.nodes:
|
|
91
|
+
issues.append(
|
|
92
|
+
Issue("unknown_node", f"'{name}' -> unknown node '{t}'", name, (name, t))
|
|
93
|
+
)
|
|
94
|
+
spec = registry.functions.get(ns.fn)
|
|
95
|
+
if spec is None:
|
|
96
|
+
issues.append(
|
|
97
|
+
Issue("unknown_function", f"node '{name}': unknown function '{ns.fn}'", name)
|
|
98
|
+
)
|
|
99
|
+
continue
|
|
100
|
+
if spec.kind == "node" and isinstance(ns.next, dict):
|
|
101
|
+
issues.append(
|
|
102
|
+
Issue("next_kind", f"node '{name}' is a @node: 'next' must be a list", name)
|
|
103
|
+
)
|
|
104
|
+
elif spec.kind == "branch" and ns.next and isinstance(ns.next, list):
|
|
105
|
+
issues.append(
|
|
106
|
+
Issue(
|
|
107
|
+
"next_kind",
|
|
108
|
+
f"node '{name}' is a @branch: 'next' must map members to nodes",
|
|
109
|
+
name,
|
|
110
|
+
)
|
|
111
|
+
)
|
|
112
|
+
elif spec.kind == "branch":
|
|
113
|
+
mapped = ns.next if isinstance(ns.next, dict) else {}
|
|
114
|
+
if missing := [m for m in spec.members if m not in mapped]:
|
|
115
|
+
issues.append(
|
|
116
|
+
Issue(
|
|
117
|
+
"branch_uncovered",
|
|
118
|
+
f"branch '{name}' does not map member(s) {', '.join(missing)}",
|
|
119
|
+
name,
|
|
120
|
+
)
|
|
121
|
+
)
|
|
122
|
+
if extra := [m for m in mapped if m not in spec.members]:
|
|
123
|
+
issues.append(
|
|
124
|
+
Issue(
|
|
125
|
+
"branch_unknown_member",
|
|
126
|
+
f"branch '{name}' maps unknown member(s) {', '.join(extra)}"
|
|
127
|
+
f" (known: {', '.join(spec.members)})",
|
|
128
|
+
name,
|
|
129
|
+
)
|
|
130
|
+
)
|
|
131
|
+
for e in topo.back:
|
|
132
|
+
if e.exit is None:
|
|
133
|
+
issues.append(
|
|
134
|
+
Issue(
|
|
135
|
+
"back_edge_not_from_branch",
|
|
136
|
+
f"edge '{e.src}' -> '{e.dst}' closes a loop but does not leave a @branch exit;"
|
|
137
|
+
" put the @branch at the end of the loop so its exit closes the cycle",
|
|
138
|
+
e.src,
|
|
139
|
+
(e.src, e.dst),
|
|
140
|
+
)
|
|
141
|
+
)
|
|
142
|
+
return issues
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def compile_graph(graph: GraphFile, registry: Registry) -> tuple[CompiledGraph | None, list[Issue]]:
|
|
146
|
+
"""Bind every parameter to its producers; ``None`` is returned iff there are issues."""
|
|
147
|
+
topo = build_topology(graph)
|
|
148
|
+
issues = _structure(graph, registry, topo)
|
|
149
|
+
specs = {
|
|
150
|
+
n: registry.functions[ns.fn] for n, ns in graph.nodes.items() if ns.fn in registry.functions
|
|
151
|
+
}
|
|
152
|
+
bindings: dict[str, dict[str, Binding]] = {}
|
|
153
|
+
inputs: dict[str, tuple[str, Param]] = {} # name -> (first node declaring it, param)
|
|
154
|
+
|
|
155
|
+
def producing(x: str, among: set[str]) -> list[str]:
|
|
156
|
+
return [n for n in topo.nodes if n in among and n in specs and x in specs[n].outputs]
|
|
157
|
+
|
|
158
|
+
def check_types(c: str, p: Param, producers: list[str]) -> None:
|
|
159
|
+
for prod in producers:
|
|
160
|
+
hint = specs[prod].outputs[p.name]
|
|
161
|
+
if not is_compatible(hint, p.hint):
|
|
162
|
+
issues.append(
|
|
163
|
+
Issue(
|
|
164
|
+
"type_mismatch",
|
|
165
|
+
f"'{prod}' produces '{p.name}' as {hint!r}, but '{c}' expects {p.hint!r}",
|
|
166
|
+
c,
|
|
167
|
+
)
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
for c, spec in specs.items():
|
|
171
|
+
bindings[c] = {}
|
|
172
|
+
for p in spec.params:
|
|
173
|
+
x = p.name
|
|
174
|
+
producers = producing(x, topo.ancestors(c))
|
|
175
|
+
feedback = [f for f in producing(x, topo.reachable(c)) if c in _cyclic_reach(topo, f)]
|
|
176
|
+
if producers and feedback:
|
|
177
|
+
issues.append(
|
|
178
|
+
Issue(
|
|
179
|
+
"name_conflict",
|
|
180
|
+
f"'{x}' read by '{c}' is produced both upstream ({', '.join(producers)})"
|
|
181
|
+
f" and in its loop ({', '.join(feedback)});"
|
|
182
|
+
f" rename one output (e.g. 'clean_{x}')",
|
|
183
|
+
c,
|
|
184
|
+
)
|
|
185
|
+
)
|
|
186
|
+
elif clashes := [
|
|
187
|
+
(a, b)
|
|
188
|
+
for a, b in combinations(producers or feedback, 2)
|
|
189
|
+
if not topo.exclusive(a, b)
|
|
190
|
+
]:
|
|
191
|
+
for a, b in clashes:
|
|
192
|
+
issues.append(
|
|
193
|
+
Issue(
|
|
194
|
+
"name_conflict",
|
|
195
|
+
f"'{x}' read by '{c}' is produced by both '{a}' and '{b}' on the same"
|
|
196
|
+
f" path; rename one output (e.g. 'clean_{x}')",
|
|
197
|
+
c,
|
|
198
|
+
)
|
|
199
|
+
)
|
|
200
|
+
elif producers:
|
|
201
|
+
if not p.has_default and _bypassed(graph, topo, c, producers):
|
|
202
|
+
issues.append(
|
|
203
|
+
Issue(
|
|
204
|
+
"missing_input",
|
|
205
|
+
f"'{c}' needs '{x}' but some choice of branch exits runs it without"
|
|
206
|
+
f" running {', '.join(f"'{n}'" for n in producers)}",
|
|
207
|
+
c,
|
|
208
|
+
)
|
|
209
|
+
)
|
|
210
|
+
check_types(c, p, producers)
|
|
211
|
+
elif feedback:
|
|
212
|
+
if not p.has_default:
|
|
213
|
+
issues.append(
|
|
214
|
+
Issue(
|
|
215
|
+
"feedback_needs_default",
|
|
216
|
+
f"'{x}' reaches '{c}' only from a later pass"
|
|
217
|
+
f" ({', '.join(f"'{n}'" for n in feedback)}); give it a Python default",
|
|
218
|
+
c,
|
|
219
|
+
)
|
|
220
|
+
)
|
|
221
|
+
check_types(c, p, feedback)
|
|
222
|
+
elif x in inputs:
|
|
223
|
+
first, q = inputs[x]
|
|
224
|
+
if not (is_compatible(p.hint, q.hint) or is_compatible(q.hint, p.hint)):
|
|
225
|
+
issues.append(
|
|
226
|
+
Issue(
|
|
227
|
+
"input_type_conflict",
|
|
228
|
+
f"graph input '{x}' is {q.hint!r} in '{first}' but {p.hint!r} in '{c}'",
|
|
229
|
+
c,
|
|
230
|
+
)
|
|
231
|
+
)
|
|
232
|
+
elif q.has_default and not p.has_default: # required anywhere -> required
|
|
233
|
+
inputs[x] = (c, p)
|
|
234
|
+
else:
|
|
235
|
+
inputs[x] = (c, p)
|
|
236
|
+
bindings[c][x] = Binding(
|
|
237
|
+
x,
|
|
238
|
+
tuple(producers),
|
|
239
|
+
tuple(feedback),
|
|
240
|
+
not producers and not feedback,
|
|
241
|
+
p.has_default,
|
|
242
|
+
p.default,
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
if issues:
|
|
246
|
+
return None, issues
|
|
247
|
+
return CompiledGraph(graph, topo, specs, bindings, {k: v for k, (_, v) in inputs.items()}), []
|
vgraph/engine.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
"""Asyncio execution engine: join rule, exceptions as values, loops, stop and events."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import traceback
|
|
7
|
+
import uuid
|
|
8
|
+
from collections.abc import Callable, Mapping
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import UTC, datetime
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
from typing import Any
|
|
13
|
+
from uuid import UUID
|
|
14
|
+
|
|
15
|
+
from vgraph.compile import Binding, CompiledGraph
|
|
16
|
+
from vgraph.registry import FunctionSpec
|
|
17
|
+
from vgraph.typing_utils import extract_outputs
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Status(StrEnum):
|
|
21
|
+
PENDING = "pending"
|
|
22
|
+
RUNNING = "running"
|
|
23
|
+
OK = "ok"
|
|
24
|
+
FAILED = "failed"
|
|
25
|
+
SKIPPED = "skipped"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class RunStatus(StrEnum):
|
|
29
|
+
RUNNING = "running"
|
|
30
|
+
OK = "ok"
|
|
31
|
+
FAILED = "failed"
|
|
32
|
+
STOPPED = "stopped"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Execution:
|
|
37
|
+
node: str
|
|
38
|
+
number: int
|
|
39
|
+
status: Status
|
|
40
|
+
inputs: dict[str, Any] = field(default_factory=dict)
|
|
41
|
+
outputs: dict[str, Any] = field(default_factory=dict)
|
|
42
|
+
error: Exception | None = None
|
|
43
|
+
traceback: str | None = None
|
|
44
|
+
skip_reason: str | None = None
|
|
45
|
+
branch_exit: str | None = None
|
|
46
|
+
started_at: datetime | None = None
|
|
47
|
+
ended_at: datetime | None = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class NodeEvent:
|
|
52
|
+
run_id: UUID
|
|
53
|
+
execution: Execution
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class PassEvent:
|
|
58
|
+
run_id: UUID
|
|
59
|
+
target: str
|
|
60
|
+
reset: tuple[str, ...]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class RunEvent:
|
|
65
|
+
run_id: UUID
|
|
66
|
+
status: RunStatus
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
Event = NodeEvent | PassEvent | RunEvent
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class RunResult:
|
|
74
|
+
run_id: UUID
|
|
75
|
+
status: RunStatus
|
|
76
|
+
outputs: dict[str, dict[str, Any]] # terminal node id -> outputs of its latest OK execution
|
|
77
|
+
executions: dict[str, list[Execution]]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
_MISSING = object()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _now() -> datetime:
|
|
84
|
+
return datetime.now(UTC)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
async def _invoke(spec: FunctionSpec, kwargs: dict[str, Any]) -> tuple[Any, BaseException | None]:
|
|
88
|
+
try:
|
|
89
|
+
if spec.is_async:
|
|
90
|
+
return await spec.fn(**kwargs), None
|
|
91
|
+
return await asyncio.to_thread(spec.fn, **kwargs), None
|
|
92
|
+
except asyncio.CancelledError:
|
|
93
|
+
raise
|
|
94
|
+
except BaseException as e: # noqa: BLE001 - returned so the scheduler can re-raise non-Exceptions
|
|
95
|
+
return None, e
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class _Run:
|
|
99
|
+
def __init__(
|
|
100
|
+
self,
|
|
101
|
+
cg: CompiledGraph,
|
|
102
|
+
inputs: Mapping[str, Any],
|
|
103
|
+
run_id: UUID,
|
|
104
|
+
on_event: Callable[[Event], None] | None,
|
|
105
|
+
stop: asyncio.Event | None,
|
|
106
|
+
) -> None:
|
|
107
|
+
self.cg, self.topo, self.inputs, self.run_id = cg, cg.topology, inputs, run_id
|
|
108
|
+
self.on_event, self.stop = on_event, stop or asyncio.Event()
|
|
109
|
+
self.executions: dict[str, list[Execution]] = {n: [] for n in self.topo.nodes}
|
|
110
|
+
self.current: dict[str, Execution | None] = dict.fromkeys(self.topo.nodes) # None: pending
|
|
111
|
+
self.finished: dict[str, tuple[int, Execution]] = {} # latest OK/FAILED, with finish order
|
|
112
|
+
self.handled: set[int] = set() # id() of FAILED executions read by a direct successor
|
|
113
|
+
self.tasks: dict[asyncio.Task[tuple[Any, BaseException | None]], Execution] = {}
|
|
114
|
+
self.passes: list[
|
|
115
|
+
tuple[str, tuple[str, ...]]
|
|
116
|
+
] = [] # back edges waiting for in-flight nodes
|
|
117
|
+
self.seq = 0
|
|
118
|
+
self.foreign_failure = False # a node skipped for a failure it could not legally handle
|
|
119
|
+
|
|
120
|
+
def emit(self, event: Event) -> None:
|
|
121
|
+
if self.on_event is not None:
|
|
122
|
+
self.on_event(event)
|
|
123
|
+
|
|
124
|
+
def record(self, node: str, status: Status, **kw: Any) -> Execution:
|
|
125
|
+
ex = Execution(node, len(self.executions[node]) + 1, status, **kw)
|
|
126
|
+
self.executions[node].append(ex)
|
|
127
|
+
self.current[node] = ex
|
|
128
|
+
self.emit(NodeEvent(self.run_id, ex))
|
|
129
|
+
return ex
|
|
130
|
+
|
|
131
|
+
# --- inputs ---------------------------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
def resolve(self, b: Binding) -> tuple[Any, Execution | None]:
|
|
134
|
+
"""Value for a binding and the execution it comes from (None: graph input / default).
|
|
135
|
+
|
|
136
|
+
The value is ``_MISSING`` when nothing produced it and there is no default.
|
|
137
|
+
"""
|
|
138
|
+
found = [self.finished[p] for p in b.producers + b.feedback if p in self.finished]
|
|
139
|
+
if found:
|
|
140
|
+
ex = max(found, key=lambda f: f[0])[1]
|
|
141
|
+
return (ex.error if ex.status == Status.FAILED else ex.outputs[b.param]), ex
|
|
142
|
+
if b.graph_input and b.param in self.inputs:
|
|
143
|
+
return self.inputs[b.param], None
|
|
144
|
+
return (b.default if b.has_default else _MISSING), None
|
|
145
|
+
|
|
146
|
+
# --- join rule, R1-R3 -------------------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
def pred_state(self, p: str, n: str) -> tuple[Status, str | None] | None:
|
|
149
|
+
"""State of forward predecessor ``p`` as seen by ``n``; None while unfinished."""
|
|
150
|
+
ex = self.current[p]
|
|
151
|
+
if ex is None or ex.status == Status.RUNNING:
|
|
152
|
+
return None
|
|
153
|
+
if ex.status == Status.OK and ex.branch_exit is not None:
|
|
154
|
+
exits = {e.exit for e in self.topo.preds(n) if e.src == p}
|
|
155
|
+
if ex.branch_exit not in exits:
|
|
156
|
+
return Status.SKIPPED, f"branch not taken ({p}={ex.branch_exit})"
|
|
157
|
+
return ex.status, None
|
|
158
|
+
|
|
159
|
+
def decide(self, n: str) -> bool:
|
|
160
|
+
"""Start or skip a pending node whose predecessors are all finished."""
|
|
161
|
+
preds = list(dict.fromkeys(e.src for e in self.topo.preds(n)))
|
|
162
|
+
states = {p: self.pred_state(p, n) for p in preds}
|
|
163
|
+
if any(s is None for s in states.values()):
|
|
164
|
+
return False
|
|
165
|
+
if preds and all(s[0] == Status.SKIPPED for s in states.values() if s):
|
|
166
|
+
reasons = [s[1] for s in states.values() if s]
|
|
167
|
+
reason = reasons[0] if all(reasons) else "all predecessors skipped"
|
|
168
|
+
self.record(n, Status.SKIPPED, skip_reason=reason, ended_at=_now())
|
|
169
|
+
return True
|
|
170
|
+
spec = self.cg.specs[n]
|
|
171
|
+
accepts = {p.name: p.accepts for p in spec.params}
|
|
172
|
+
resolved = {x: self.resolve(b) for x, b in self.cg.bindings[n].items()}
|
|
173
|
+
sources = [src for _, src in resolved.values()]
|
|
174
|
+
# R2: a failed direct predecessor must be read; R3: only its current failure, if accepted.
|
|
175
|
+
unread = [
|
|
176
|
+
p
|
|
177
|
+
for p, s in states.items()
|
|
178
|
+
if s and s[0] == Status.FAILED and not any(src is self.current[p] for src in sources)
|
|
179
|
+
]
|
|
180
|
+
rejected = [
|
|
181
|
+
src
|
|
182
|
+
for x, (v, src) in resolved.items()
|
|
183
|
+
if src is not None and src.status == Status.FAILED and not isinstance(v, accepts[x])
|
|
184
|
+
]
|
|
185
|
+
foreign = [ # a failure from a non-predecessor or an earlier pass: never handleable here
|
|
186
|
+
src
|
|
187
|
+
for src in sources
|
|
188
|
+
if src is not None
|
|
189
|
+
and src.status == Status.FAILED
|
|
190
|
+
and not (src.node in preds and src is self.current[src.node])
|
|
191
|
+
]
|
|
192
|
+
self.foreign_failure |= bool(foreign)
|
|
193
|
+
if unhandled := unread + [src.node for src in foreign + rejected]:
|
|
194
|
+
reason = f"upstream failed: {unhandled[0]}"
|
|
195
|
+
self.record(n, Status.SKIPPED, skip_reason=reason, ended_at=_now())
|
|
196
|
+
return True
|
|
197
|
+
if missing := [x for x, (v, _) in resolved.items() if v is _MISSING]:
|
|
198
|
+
reason = f"missing input: {missing[0]}"
|
|
199
|
+
self.record(n, Status.SKIPPED, skip_reason=reason, ended_at=_now())
|
|
200
|
+
return True
|
|
201
|
+
self.handled.update(id(src) for src in sources if src and src.status == Status.FAILED)
|
|
202
|
+
ex = self.record(
|
|
203
|
+
n, Status.RUNNING, inputs={x: v for x, (v, _) in resolved.items()}, started_at=_now()
|
|
204
|
+
)
|
|
205
|
+
self.tasks[asyncio.create_task(_invoke(spec, ex.inputs))] = ex
|
|
206
|
+
return True
|
|
207
|
+
|
|
208
|
+
# --- completion, back edges ---------------------------------------------------------
|
|
209
|
+
|
|
210
|
+
def complete(self, ex: Execution, value: Any, error: BaseException | None) -> None:
|
|
211
|
+
spec = self.cg.specs[ex.node]
|
|
212
|
+
if error is not None and not isinstance(error, Exception):
|
|
213
|
+
raise error
|
|
214
|
+
ex.ended_at = _now()
|
|
215
|
+
if error is None:
|
|
216
|
+
try:
|
|
217
|
+
if spec.enum is not None and not isinstance(value, spec.enum):
|
|
218
|
+
raise TypeError(f"{ex.node} returned {value!r}, expected {spec.enum.__name__}")
|
|
219
|
+
ex.outputs = extract_outputs(spec.return_hint, spec.outputs, value)
|
|
220
|
+
ex.status = Status.OK
|
|
221
|
+
ex.branch_exit = value.name if spec.enum is not None else None
|
|
222
|
+
except Exception as e: # noqa: BLE001 - a bad return value fails this node only
|
|
223
|
+
error = e
|
|
224
|
+
if error is not None:
|
|
225
|
+
ex.status = Status.FAILED
|
|
226
|
+
ex.error = error
|
|
227
|
+
ex.traceback = "".join(traceback.format_exception(error))
|
|
228
|
+
ex.outputs = dict.fromkeys(spec.outputs, error)
|
|
229
|
+
self.seq += 1
|
|
230
|
+
self.finished[ex.node] = (self.seq, ex)
|
|
231
|
+
self.emit(NodeEvent(self.run_id, ex))
|
|
232
|
+
back = [e.dst for e in self.topo.back if e.src == ex.node and e.exit == ex.branch_exit]
|
|
233
|
+
if ex.status == Status.OK and back and not self.stop.is_set():
|
|
234
|
+
target = back[0]
|
|
235
|
+
loop = self.topo.reachable(target) | {target}
|
|
236
|
+
reset = tuple(m for m in self.topo.nodes if m in loop)
|
|
237
|
+
self.passes.append((target, reset))
|
|
238
|
+
|
|
239
|
+
def blocked(self) -> set[str]:
|
|
240
|
+
return {m for _, reset in self.passes for m in reset}
|
|
241
|
+
|
|
242
|
+
def start_passes(self) -> bool:
|
|
243
|
+
running = {ex.node for ex in self.tasks.values()}
|
|
244
|
+
if not self.passes or running & set(self.passes[0][1]):
|
|
245
|
+
return False
|
|
246
|
+
target, reset = self.passes.pop(0)
|
|
247
|
+
for m in reset:
|
|
248
|
+
self.current[m] = None
|
|
249
|
+
self.emit(PassEvent(self.run_id, target, reset))
|
|
250
|
+
return True
|
|
251
|
+
|
|
252
|
+
# --- scheduler ----------------------------------------------------------------------
|
|
253
|
+
|
|
254
|
+
async def run(self) -> RunResult:
|
|
255
|
+
self.emit(RunEvent(self.run_id, RunStatus.RUNNING))
|
|
256
|
+
# shortcut: no iteration limit, add max_iterations in YAML if runaway loops become a problem
|
|
257
|
+
stopper = asyncio.create_task(self.stop.wait())
|
|
258
|
+
try:
|
|
259
|
+
while True:
|
|
260
|
+
progress = True
|
|
261
|
+
while progress and not self.stop.is_set():
|
|
262
|
+
progress = self.start_passes()
|
|
263
|
+
blocked = self.blocked()
|
|
264
|
+
for n in self.topo.nodes:
|
|
265
|
+
if self.stop.is_set(): # may be set by an on_event callback mid-sweep
|
|
266
|
+
break
|
|
267
|
+
if self.current[n] is None and n not in blocked and self.decide(n):
|
|
268
|
+
progress = True
|
|
269
|
+
if not self.tasks:
|
|
270
|
+
break
|
|
271
|
+
waits = [*self.tasks] if stopper.done() else [*self.tasks, stopper]
|
|
272
|
+
done, _ = await asyncio.wait(waits, return_when=asyncio.FIRST_COMPLETED)
|
|
273
|
+
for task in done:
|
|
274
|
+
if task is not stopper:
|
|
275
|
+
self.complete(self.tasks.pop(task), *task.result()) # type: ignore[misc]
|
|
276
|
+
finally:
|
|
277
|
+
stopper.cancel()
|
|
278
|
+
reason = "stopped by user" if self.stop.is_set() else "all predecessors skipped"
|
|
279
|
+
for n in self.topo.nodes:
|
|
280
|
+
if self.current[n] is None:
|
|
281
|
+
self.record(n, Status.SKIPPED, skip_reason=reason, ended_at=_now())
|
|
282
|
+
return self.result()
|
|
283
|
+
|
|
284
|
+
def result(self) -> RunResult:
|
|
285
|
+
if self.stop.is_set():
|
|
286
|
+
status = RunStatus.STOPPED
|
|
287
|
+
elif self.foreign_failure or any(
|
|
288
|
+
ex.status == Status.FAILED and id(ex) not in self.handled
|
|
289
|
+
for exs in self.executions.values()
|
|
290
|
+
for ex in exs
|
|
291
|
+
):
|
|
292
|
+
status = RunStatus.FAILED
|
|
293
|
+
else:
|
|
294
|
+
status = RunStatus.OK
|
|
295
|
+
sources = {e.src for e in self.topo.forward + self.topo.back}
|
|
296
|
+
outputs = {}
|
|
297
|
+
for n in self.topo.nodes:
|
|
298
|
+
ok = [ex for ex in self.executions[n] if ex.status == Status.OK]
|
|
299
|
+
if n not in sources and ok:
|
|
300
|
+
outputs[n] = ok[-1].outputs
|
|
301
|
+
self.emit(RunEvent(self.run_id, status))
|
|
302
|
+
return RunResult(self.run_id, status, outputs, self.executions)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
async def execute(
|
|
306
|
+
cg: CompiledGraph,
|
|
307
|
+
inputs: Mapping[str, Any],
|
|
308
|
+
*,
|
|
309
|
+
run_id: UUID | None = None,
|
|
310
|
+
on_event: Callable[[Event], None] | None = None,
|
|
311
|
+
stop: asyncio.Event | None = None,
|
|
312
|
+
) -> RunResult:
|
|
313
|
+
"""Run a compiled graph with already-validated inputs (spec §4.3-4.6)."""
|
|
314
|
+
return await _Run(cg, inputs, run_id or uuid.uuid4(), on_event, stop).run()
|