tickflow-py 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.
- tickflow/__init__.py +79 -0
- tickflow/__main__.py +6 -0
- tickflow/async_runner.py +247 -0
- tickflow/checker.py +294 -0
- tickflow/cli.py +161 -0
- tickflow/engine.py +306 -0
- tickflow/ir.py +209 -0
- tickflow/parser.py +273 -0
- tickflow/persistence.py +597 -0
- tickflow/registry.py +103 -0
- tickflow/runner.py +579 -0
- tickflow/state.py +498 -0
- tickflow/views.py +140 -0
- tickflow_py-0.1.0.dist-info/METADATA +565 -0
- tickflow_py-0.1.0.dist-info/RECORD +18 -0
- tickflow_py-0.1.0.dist-info/WHEEL +5 -0
- tickflow_py-0.1.0.dist-info/licenses/LICENSE +21 -0
- tickflow_py-0.1.0.dist-info/top_level.txt +1 -0
tickflow/__init__.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""flow — a small Petri-style workflow control framework.
|
|
2
|
+
|
|
3
|
+
Public surface:
|
|
4
|
+
|
|
5
|
+
from tickflow import Graph, parse, check, Runner, Registry
|
|
6
|
+
|
|
7
|
+
Quick sketch::
|
|
8
|
+
|
|
9
|
+
[start]-->B
|
|
10
|
+
B.body: decide
|
|
11
|
+
B--|go_a|-->A
|
|
12
|
+
B--|go_d|-->D
|
|
13
|
+
A-->Merge
|
|
14
|
+
D-->Merge
|
|
15
|
+
Merge.body: merge
|
|
16
|
+
|
|
17
|
+
Each node carries a boolean "slot" per incoming edge. A node fires when its
|
|
18
|
+
join predicate (AND: all slots True; OR: >=1 slot True) holds over the current
|
|
19
|
+
marking. Firing consumes its input slots (resets to False) and, after every
|
|
20
|
+
node in the tick has fired, produces a True/False into each downstream slot
|
|
21
|
+
via the edge (plain edges always True, guarded edges evaluate the guard
|
|
22
|
+
function against a read-only view of history). Outputs land in an append-only
|
|
23
|
+
history keyed by (node, tick); reads default to ``latest_before(t)`` and may
|
|
24
|
+
pin a specific fire with ``A[k]`` syntax.
|
|
25
|
+
|
|
26
|
+
Because the engine is a pure function ``f(marking_t, history_{<t}) ->
|
|
27
|
+
(marking_{t+1}, firings_t)`` with no hidden in-flight state, snapshots are a
|
|
28
|
+
cheap JSON triple (marking + history + tick) and ``restore`` is a trivial
|
|
29
|
+
rewind. See ``runner.Runner``.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from .ir import Graph, Node, Edge, InputPolicy, Failure
|
|
33
|
+
from .parser import parse, ParseError
|
|
34
|
+
from .checker import (
|
|
35
|
+
check,
|
|
36
|
+
promote,
|
|
37
|
+
resolve_or_raise,
|
|
38
|
+
DeadlockSuggestion,
|
|
39
|
+
DeadlockError,
|
|
40
|
+
check_unguarded_cycles,
|
|
41
|
+
UnguardedCycleWarning,
|
|
42
|
+
)
|
|
43
|
+
from .registry import Registry, registry, Body, Guard
|
|
44
|
+
from .engine import Marking, tick, bootstrap
|
|
45
|
+
from .state import NodeState, RunState
|
|
46
|
+
from .runner import Runner, RunStatus
|
|
47
|
+
from .persistence import Backend, JsonBackend, NullBackend, SqliteBackend
|
|
48
|
+
|
|
49
|
+
__all__ = [
|
|
50
|
+
"Graph",
|
|
51
|
+
"Node",
|
|
52
|
+
"Edge",
|
|
53
|
+
"InputPolicy",
|
|
54
|
+
"Failure",
|
|
55
|
+
"parse",
|
|
56
|
+
"ParseError",
|
|
57
|
+
"check",
|
|
58
|
+
"promote",
|
|
59
|
+
"resolve_or_raise",
|
|
60
|
+
"DeadlockSuggestion",
|
|
61
|
+
"DeadlockError",
|
|
62
|
+
"check_unguarded_cycles",
|
|
63
|
+
"UnguardedCycleWarning",
|
|
64
|
+
"Registry",
|
|
65
|
+
"registry",
|
|
66
|
+
"Body",
|
|
67
|
+
"Guard",
|
|
68
|
+
"Marking",
|
|
69
|
+
"NodeState",
|
|
70
|
+
"RunState",
|
|
71
|
+
"tick",
|
|
72
|
+
"bootstrap",
|
|
73
|
+
"Runner",
|
|
74
|
+
"RunStatus",
|
|
75
|
+
"Backend",
|
|
76
|
+
"JsonBackend",
|
|
77
|
+
"NullBackend",
|
|
78
|
+
"SqliteBackend",
|
|
79
|
+
]
|
tickflow/__main__.py
ADDED
tickflow/async_runner.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Asynchronous runner: async bodies + concurrent firing.
|
|
2
|
+
|
|
3
|
+
Mirrors :class:`tickflow.runner.Runner` but allows node bodies and edge guards to
|
|
4
|
+
be ``async def``. Within a tick, all fireable nodes fire **concurrently** via
|
|
5
|
+
``asyncio.gather`` (matching the Petri step semantics -- fireable transitions
|
|
6
|
+
fire together, each seeing only prior-tick state).
|
|
7
|
+
|
|
8
|
+
When to use
|
|
9
|
+
-----------
|
|
10
|
+
Use AsyncRunner when a body does IO (LLM calls, HTTP, DB) -- i.e. the
|
|
11
|
+
ModuleHarness case where each node runs a Harness (LLM + tools). The sync
|
|
12
|
+
Runner is fine for pure-computation graphs and tests.
|
|
13
|
+
|
|
14
|
+
Since D6 the default backend is a temp SQLite file (auto-cleaned), so an
|
|
15
|
+
AsyncRunner created without an explicit ``backend=`` performs a small
|
|
16
|
+
synchronous SQLite write at the end of every tick — fine when LLM latency
|
|
17
|
+
dominates, but pass ``NullBackend()`` for zero-I/O async runs.
|
|
18
|
+
|
|
19
|
+
A body or guard may be sync *or* async; the runner detects via
|
|
20
|
+
``inspect.iscoroutinefunction`` and awaits accordingly. Mixing is fine.
|
|
21
|
+
|
|
22
|
+
Semantics are identical to the sync engine: marking-step concurrency (peers
|
|
23
|
+
can't see same-tick writes), Failure propagation (infra -> ABORTED), node_state,
|
|
24
|
+
hooks (async hooks supported), backend persistence, checkpoints.
|
|
25
|
+
|
|
26
|
+
All shared logic (snapshot/restore, remap, checkpoints, audit, etc.) lives in
|
|
27
|
+
:class:`tickflow.runner._BaseRunner`.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import asyncio
|
|
33
|
+
import inspect
|
|
34
|
+
import logging
|
|
35
|
+
from typing import Any, Awaitable, Callable, Iterable
|
|
36
|
+
|
|
37
|
+
from .ir import Graph, Failure
|
|
38
|
+
from .registry import Registry, registry as _default_registry
|
|
39
|
+
from .engine import (
|
|
40
|
+
Marking, bootstrap, _join_satisfied, _resolve_inputs, _guard_view, _NodeStateView,
|
|
41
|
+
)
|
|
42
|
+
from .state import NodeState, RunState, _jsonable
|
|
43
|
+
from .views import DictView
|
|
44
|
+
from .runner import (
|
|
45
|
+
_BaseRunner, RunStatus, _TERMINAL, FireHook, TickEndHook,
|
|
46
|
+
_validate_registry_for_graph, _warn_graph_changes,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
log = logging.getLogger(__name__)
|
|
50
|
+
|
|
51
|
+
# Async hook type aliases.
|
|
52
|
+
AsyncFireHook = Callable[[NodeState], Awaitable[None]]
|
|
53
|
+
AsyncTickEndHook = Callable[[int, list[NodeState]], Awaitable[None]]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def _maybe_await(fn: Any, *args: Any, **kw: Any) -> Any:
|
|
57
|
+
"""Call ``fn`` and await if it returns a coroutine."""
|
|
58
|
+
result = fn(*args, **kw)
|
|
59
|
+
if inspect.isawaitable(result):
|
|
60
|
+
result = await result
|
|
61
|
+
return result
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
async def async_tick(
|
|
65
|
+
graph: Graph,
|
|
66
|
+
marking: Marking,
|
|
67
|
+
run_state: RunState,
|
|
68
|
+
t: int,
|
|
69
|
+
registry: Registry,
|
|
70
|
+
fireable: list[str] | None = None,
|
|
71
|
+
) -> tuple[Marking, list[NodeState], bool]:
|
|
72
|
+
"""Async counterpart of :func:`tickflow.engine.tick`.
|
|
73
|
+
|
|
74
|
+
``fireable``: precomputed fireable set for ``marking`` (see
|
|
75
|
+
:func:`tickflow.engine.tick`); default None computes internally. Caller
|
|
76
|
+
responsibility: the list must match ``marking`` exactly and must not be
|
|
77
|
+
mutated afterwards -- an inconsistent set silently changes firing
|
|
78
|
+
behaviour.
|
|
79
|
+
"""
|
|
80
|
+
from typing import Literal
|
|
81
|
+
|
|
82
|
+
if fireable is None:
|
|
83
|
+
fireable = [n for n in graph.nodes if _join_satisfied(graph, n, marking)]
|
|
84
|
+
if not fireable:
|
|
85
|
+
return marking.copy(), [], False
|
|
86
|
+
|
|
87
|
+
m_next = marking.copy()
|
|
88
|
+
|
|
89
|
+
async def _fire(node: str) -> NodeState:
|
|
90
|
+
resolved = _resolve_inputs(graph, node, run_state, t, registry)
|
|
91
|
+
initial_state = run_state.mutable_state(node)
|
|
92
|
+
state_view = _NodeStateView(initial_state)
|
|
93
|
+
view = DictView(resolved, state_view, node)
|
|
94
|
+
body = registry.get_body(graph.nodes[node].body)
|
|
95
|
+
output = await _maybe_await(body, view)
|
|
96
|
+
is_fail = isinstance(output, Failure)
|
|
97
|
+
status: Literal["ok", "failed", "aborted"] = "ok"
|
|
98
|
+
error: str | None = None
|
|
99
|
+
if is_fail:
|
|
100
|
+
error = output.error
|
|
101
|
+
status = "aborted" if output.type == "infrastructure" else "failed"
|
|
102
|
+
return NodeState(
|
|
103
|
+
tick=t, node=node,
|
|
104
|
+
inputs={k: v.value for k, v in resolved.items()},
|
|
105
|
+
output=output, edges_fired=[],
|
|
106
|
+
status=status, error=error,
|
|
107
|
+
mutable_state=initial_state,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
firings = list(await asyncio.gather(*[_fire(n) for n in fireable]))
|
|
111
|
+
aborted = any(f.status == "aborted" for f in firings)
|
|
112
|
+
|
|
113
|
+
for f in firings:
|
|
114
|
+
run_state.record(f)
|
|
115
|
+
|
|
116
|
+
for f in firings:
|
|
117
|
+
for p in graph.producers(f.node):
|
|
118
|
+
m_next.slots[(f.node, p)] = False
|
|
119
|
+
m_next.armed_starts.discard(f.node)
|
|
120
|
+
|
|
121
|
+
async def _produce(f: NodeState) -> None:
|
|
122
|
+
failed = f.status in ("failed", "aborted")
|
|
123
|
+
for e in graph.out_edges(f.node):
|
|
124
|
+
if failed:
|
|
125
|
+
v = False
|
|
126
|
+
elif e.guard is None:
|
|
127
|
+
v = True
|
|
128
|
+
else:
|
|
129
|
+
gview = _guard_view(
|
|
130
|
+
graph, e.src, f.output, run_state, t, registry,
|
|
131
|
+
)
|
|
132
|
+
v = bool(await _maybe_await(registry.get_guard(e.guard), gview))
|
|
133
|
+
m_next.slots[(e.dst, e.src)] = v
|
|
134
|
+
f.edges_fired.append((e.dst, e.guard, v))
|
|
135
|
+
|
|
136
|
+
await asyncio.gather(*[_produce(f) for f in firings])
|
|
137
|
+
return m_next, firings, aborted
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class AsyncRunner(_BaseRunner):
|
|
141
|
+
"""Async counterpart of :class:`tickflow.runner.Runner`.
|
|
142
|
+
|
|
143
|
+
All shared logic (snapshot, restore, remap, checkpoints, audit, etc.) is
|
|
144
|
+
inherited from :class:`_BaseRunner`.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
def __init__(
|
|
148
|
+
self,
|
|
149
|
+
graph: Graph,
|
|
150
|
+
registry: Registry | None = None,
|
|
151
|
+
*,
|
|
152
|
+
strict_deadlock: bool = True,
|
|
153
|
+
backend: Any = None,
|
|
154
|
+
session_id: str | None = None,
|
|
155
|
+
keep_records: bool = True,
|
|
156
|
+
) -> None:
|
|
157
|
+
from .checker import check, DeadlockError
|
|
158
|
+
super().__init__(
|
|
159
|
+
graph, registry,
|
|
160
|
+
strict_deadlock=strict_deadlock,
|
|
161
|
+
backend=backend, session_id=session_id,
|
|
162
|
+
keep_records=keep_records,
|
|
163
|
+
)
|
|
164
|
+
self._fire_hooks: list = []
|
|
165
|
+
self._tick_end_hooks: list = []
|
|
166
|
+
self._tick_start_hooks: list = []
|
|
167
|
+
|
|
168
|
+
# --- hooks ------------------------------------------------------------
|
|
169
|
+
|
|
170
|
+
def on_fire(self, callback) -> None:
|
|
171
|
+
self._fire_hooks.append(callback)
|
|
172
|
+
|
|
173
|
+
def on_tick_end(self, callback) -> None:
|
|
174
|
+
self._tick_end_hooks.append(callback)
|
|
175
|
+
|
|
176
|
+
def on_tick_start(self, callback) -> None:
|
|
177
|
+
self._tick_start_hooks.append(callback)
|
|
178
|
+
|
|
179
|
+
async def _run_fire_hooks(self, firing: NodeState) -> None:
|
|
180
|
+
for cb in self._fire_hooks:
|
|
181
|
+
try:
|
|
182
|
+
await _maybe_await(cb, firing)
|
|
183
|
+
except Exception:
|
|
184
|
+
log.exception("on_fire hook raised; swallowed")
|
|
185
|
+
|
|
186
|
+
async def _run_tick_end_hooks(self, tick: int, firings: list[NodeState]) -> None:
|
|
187
|
+
for cb in self._tick_end_hooks:
|
|
188
|
+
try:
|
|
189
|
+
await _maybe_await(cb, tick, firings)
|
|
190
|
+
except Exception:
|
|
191
|
+
log.exception("on_tick_end hook raised; swallowed")
|
|
192
|
+
|
|
193
|
+
async def _run_tick_start_hooks(self, tick: int, fireable: list[str]) -> None:
|
|
194
|
+
for cb in self._tick_start_hooks:
|
|
195
|
+
try:
|
|
196
|
+
await _maybe_await(cb, tick, fireable)
|
|
197
|
+
except Exception:
|
|
198
|
+
log.exception("on_tick_start hook raised; swallowed")
|
|
199
|
+
|
|
200
|
+
# --- core -------------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
async def tick(self) -> list[NodeState]:
|
|
203
|
+
"""Advance exactly one tick."""
|
|
204
|
+
if self.status in _TERMINAL:
|
|
205
|
+
return []
|
|
206
|
+
fireable = self.fireable()
|
|
207
|
+
await self._run_tick_start_hooks(self.tick_count, fireable)
|
|
208
|
+
next_marking, firings, aborted = await async_tick(
|
|
209
|
+
self.graph, self.marking, self.run_state, self.tick_count, self.registry,
|
|
210
|
+
fireable=fireable,
|
|
211
|
+
)
|
|
212
|
+
self.marking = next_marking
|
|
213
|
+
for f in firings:
|
|
214
|
+
await self._run_fire_hooks(f)
|
|
215
|
+
self.tick_count += 1
|
|
216
|
+
if aborted:
|
|
217
|
+
self.status = RunStatus.ABORTED
|
|
218
|
+
elif not firings:
|
|
219
|
+
self.status = RunStatus.IDLE
|
|
220
|
+
else:
|
|
221
|
+
self.status = RunStatus.RUNNING
|
|
222
|
+
await self._run_tick_end_hooks(self.tick_count - 1, firings)
|
|
223
|
+
self._persist_tick([f.node for f in firings])
|
|
224
|
+
return firings
|
|
225
|
+
|
|
226
|
+
async def run_until_idle(
|
|
227
|
+
self,
|
|
228
|
+
max_ticks: int = 1000,
|
|
229
|
+
pause_at: Iterable[int] | None = None,
|
|
230
|
+
) -> list[NodeState]:
|
|
231
|
+
"""Tick until idle/terminal or ``max_ticks`` reached."""
|
|
232
|
+
pauses = set(pause_at or ())
|
|
233
|
+
seen: list[NodeState] = []
|
|
234
|
+
while self.tick_count < max_ticks:
|
|
235
|
+
if self.tick_count in pauses:
|
|
236
|
+
break
|
|
237
|
+
if self.status in _TERMINAL:
|
|
238
|
+
break
|
|
239
|
+
if self.status == RunStatus.IDLE and self.tick_count > 0 and not self._has_pending():
|
|
240
|
+
break
|
|
241
|
+
firings = await self.tick()
|
|
242
|
+
if not firings:
|
|
243
|
+
break
|
|
244
|
+
seen.extend(firings)
|
|
245
|
+
if self.status in _TERMINAL:
|
|
246
|
+
break
|
|
247
|
+
return seen
|
tickflow/checker.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
"""Static deadlock detection and OR-join promotion.
|
|
4
|
+
|
|
5
|
+
Deadlock pattern
|
|
6
|
+
----------------
|
|
7
|
+
A node ``M`` is an AND-join with >=2 producers ``P1..Pn``. There exists an
|
|
8
|
+
*XOR-splitter* ``B`` (a node with >=2 guarded out-edges ``--|g|-->``) such
|
|
9
|
+
that >=2 of ``M``'s producers lie on distinct, mutually-exclusive branches
|
|
10
|
+
reaching from ``B``. Under AND-join, ``M`` waits for *all* producers' slots
|
|
11
|
+
to be True, but each fire of ``B`` sets at most one branch's slots True (the
|
|
12
|
+
other branch's guard returns False that tick). The "other half" never arrives
|
|
13
|
+
within one ``B`` cycle, so ``M`` never fires -> deadlock.
|
|
14
|
+
|
|
15
|
+
Solution
|
|
16
|
+
--------
|
|
17
|
+
Promote ``M`` to OR-join: ``M`` fires when >=1 input slot is True. With the
|
|
18
|
+
synchronous step semantics here, this is *decidable* -- we never need to
|
|
19
|
+
answer "could more tokens still arrive?" (the open Petri-net OR-join
|
|
20
|
+
problem). A failing branch simply leaves its slot False; OR-join ignores
|
|
21
|
+
it. Each tick ``M`` fires at most once (after firing it consumes all its
|
|
22
|
+
slots -> False), so no double-firing.
|
|
23
|
+
|
|
24
|
+
Workflow
|
|
25
|
+
--------
|
|
26
|
+
``check(graph)`` returns a list of :class:`DeadlockSuggestion` -- it does
|
|
27
|
+
**not** mutate. The caller (CLI) prompts the user; on confirm it calls
|
|
28
|
+
``promote(suggestion)`` which flips ``M.join`` to "OR". Re-running ``check``
|
|
29
|
+
yields no further suggestion for ``M`` (OR-joins don't match the pattern).
|
|
30
|
+
Suggestions left un-promoted cause :class:`DeadlockError` when the
|
|
31
|
+
:class:`Runner` is constructed -- we never silently run a graph that will
|
|
32
|
+
hang.
|
|
33
|
+
|
|
34
|
+
Branch analysis
|
|
35
|
+
---------------
|
|
36
|
+
We compute, for each splitter ``B``, the set of nodes reachable from each
|
|
37
|
+
guarded out-edge of ``B`` *before re-merging*: two branches are
|
|
38
|
+
"mutually exclusive" if their downstream reachable sets are disjoint.
|
|
39
|
+
Concretely: branch_i = reachable from (B's i-th guarded edge) *without*
|
|
40
|
+
passing back through any of B's guarded edges' dsts' shared join points.
|
|
41
|
+
We use a simpler, conservative approximation that is sound (no false
|
|
42
|
+
negatives, only over-approximation of reach):
|
|
43
|
+
|
|
44
|
+
branch_i = the set of nodes reachable from e_i.dst by walking
|
|
45
|
+
out-edges, *stopping* when we reach any node that has >=2
|
|
46
|
+
producers (a potential merge) -- because past a merge the
|
|
47
|
+
branch's exclusivity is no longer locally provable.
|
|
48
|
+
|
|
49
|
+
Two producers P_a, P_b of M are "on distinct branches of B" if there exist
|
|
50
|
+
guarded out-edges e_a, e_b of B with e_a != e_b and P_a in branch(e_a) and
|
|
51
|
+
P_b in branch(e_b). This is sufficient to flag the deadlock; the user
|
|
52
|
+
confirms intent.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
import logging
|
|
56
|
+
from dataclasses import dataclass
|
|
57
|
+
from typing import Iterable
|
|
58
|
+
|
|
59
|
+
from .ir import Graph
|
|
60
|
+
|
|
61
|
+
log = logging.getLogger(__name__)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class DeadlockSuggestion:
|
|
66
|
+
node: str # the AND-join M that would deadlock
|
|
67
|
+
producers: list[str]# the >=2 producers of M lying on distinct branches
|
|
68
|
+
splitter: str # the XOR-splitter B responsible
|
|
69
|
+
branches: dict[str, list[str]]
|
|
70
|
+
# branches: guard name -> list of downstream node names on that branch
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def msg(self) -> str:
|
|
74
|
+
return (
|
|
75
|
+
f"AND-join {self.node!r} has producers {self.producers} on mutually-"
|
|
76
|
+
f"exclusive branches of XOR-splitter {self.splitter!r} "
|
|
77
|
+
f"(branches={ {g: v for g, v in self.branches.items()} }). "
|
|
78
|
+
f"It would deadlock under AND-join; promote to OR-join?"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class DeadlockError(RuntimeError):
|
|
83
|
+
"""Raised when a graph still has unresolved AND-join deadlocks at run
|
|
84
|
+
time (i.e. ``check`` returned suggestions the caller did not promote)."""
|
|
85
|
+
|
|
86
|
+
def __init__(self, suggestions: list[DeadlockSuggestion]) -> None:
|
|
87
|
+
self.suggestions = suggestions
|
|
88
|
+
super().__init__(
|
|
89
|
+
"unresolved AND-join deadlock(s):\n" + "\n".join(s.msg for s in suggestions)
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _reachable_until_merge(graph: Graph, start: str) -> set[str]:
|
|
94
|
+
"""BFS from ``start`` over out-edges, stopping at any node that has >=2
|
|
95
|
+
producers (a candidate merge) -- beyond which exclusivity is not locally
|
|
96
|
+
provable. ``start`` itself is included."""
|
|
97
|
+
seen: set[str] = {start}
|
|
98
|
+
frontier: list[str] = [start]
|
|
99
|
+
while frontier:
|
|
100
|
+
n = frontier.pop()
|
|
101
|
+
# Stop expanding this node if it's a candidate merge (>=2 producers).
|
|
102
|
+
if n != start and len(graph.producers(n)) >= 2:
|
|
103
|
+
continue
|
|
104
|
+
for e in graph.out_edges(n):
|
|
105
|
+
if e.dst not in seen:
|
|
106
|
+
seen.add(e.dst)
|
|
107
|
+
frontier.append(e.dst)
|
|
108
|
+
return seen
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _branches_of(graph: Graph, splitter: str) -> dict[str, list[str]]:
|
|
112
|
+
"""For an XOR-splitter B, map each guarded-out-edge's guard name to the
|
|
113
|
+
reachable-until-merge set of its destination."""
|
|
114
|
+
branches: dict[str, list[str]] = {}
|
|
115
|
+
for e in graph.out_edges(splitter):
|
|
116
|
+
if e.guard is None:
|
|
117
|
+
continue
|
|
118
|
+
reach = _reachable_until_merge(graph, e.dst)
|
|
119
|
+
# record the branch; remove the splitter itself from the branch
|
|
120
|
+
reach.discard(splitter)
|
|
121
|
+
branches.setdefault(e.guard, sorted(reach))
|
|
122
|
+
return branches
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _producers_on_distinct_branches(
|
|
126
|
+
graph: Graph, m: str, branches: dict[str, list[str]]
|
|
127
|
+
) -> tuple[list[str], str] | None:
|
|
128
|
+
"""Given branches (guard -> node list) for one splitter, return a pair of
|
|
129
|
+
M's producers that lie on two distinct branches, plus the splitter name --
|
|
130
|
+
or None if no such pair exists. We pick the first qualifying pair."""
|
|
131
|
+
prods = graph.producers(m)
|
|
132
|
+
# Map each producer to the set of guards whose branch contains it.
|
|
133
|
+
prod_to_guards: dict[str, set[str]] = {}
|
|
134
|
+
for p in prods:
|
|
135
|
+
gs = {g for g, lst in branches.items() if p in lst}
|
|
136
|
+
if gs:
|
|
137
|
+
prod_to_guards[p] = gs
|
|
138
|
+
# Find two producers with disjoint guard sets (different branches).
|
|
139
|
+
pairs = list(prod_to_guards.items())
|
|
140
|
+
for i in range(len(pairs)):
|
|
141
|
+
for j in range(i + 1, len(pairs)):
|
|
142
|
+
if not (pairs[i][1] & pairs[j][1]): # disjoint -> distinct branches
|
|
143
|
+
return [pairs[i][0], pairs[j][0]], ""
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def check(graph: Graph) -> list[DeadlockSuggestion]:
|
|
148
|
+
"""Return all deadlock suggestions for ``graph``. Does not mutate."""
|
|
149
|
+
out: list[DeadlockSuggestion] = []
|
|
150
|
+
# Branch reachability depends only on the splitter, not on the candidate
|
|
151
|
+
# AND-join m -- precompute once and look up (C3): O(S·(V+E)) instead of
|
|
152
|
+
# O(K·S·(V+E)). Same-splitter suggestions share one branches dict (the
|
|
153
|
+
# only consumer, DeadlockSuggestion.msg, is read-only).
|
|
154
|
+
splitters: dict[str, dict[str, list[str]]] = {
|
|
155
|
+
b: _branches_of(graph, b) for b in graph.nodes if graph.is_xor_splitter(b)
|
|
156
|
+
}
|
|
157
|
+
for m, node in graph.nodes.items():
|
|
158
|
+
if node.join != "AND":
|
|
159
|
+
continue
|
|
160
|
+
prods = graph.producers(m)
|
|
161
|
+
if len(prods) < 2:
|
|
162
|
+
continue
|
|
163
|
+
# Find any XOR-splitter B such that >=2 of M's producers lie on
|
|
164
|
+
# distinct branches of B.
|
|
165
|
+
for b, branches in splitters.items():
|
|
166
|
+
res = _producers_on_distinct_branches(graph, m, branches)
|
|
167
|
+
if res is not None:
|
|
168
|
+
pair = res[0]
|
|
169
|
+
out.append(
|
|
170
|
+
DeadlockSuggestion(
|
|
171
|
+
node=m,
|
|
172
|
+
producers=pair,
|
|
173
|
+
splitter=b,
|
|
174
|
+
branches=branches,
|
|
175
|
+
)
|
|
176
|
+
)
|
|
177
|
+
# Dedupe by (node, splitter) -- multiple producer pairs on same splitter
|
|
178
|
+
# collapse to one suggestion.
|
|
179
|
+
seen: set[tuple[str, str]] = set()
|
|
180
|
+
deduped: list[DeadlockSuggestion] = []
|
|
181
|
+
for s in out:
|
|
182
|
+
key = (s.node, s.splitter)
|
|
183
|
+
if key in seen:
|
|
184
|
+
continue
|
|
185
|
+
seen.add(key)
|
|
186
|
+
deduped.append(s)
|
|
187
|
+
return deduped
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def promote(suggestion: DeadlockSuggestion, graph: Graph) -> None:
|
|
191
|
+
"""Flip ``suggestion.node``'s join to OR in ``graph``. Idempotent."""
|
|
192
|
+
graph.nodes[suggestion.node].join = "OR"
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# --- unguarded cycle detection -----------------------------------------------
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@dataclass
|
|
199
|
+
class UnguardedCycleWarning:
|
|
200
|
+
"""Warning: a cycle with no guarded edge will loop forever."""
|
|
201
|
+
|
|
202
|
+
nodes: list[str] # node names in the strongly connected component
|
|
203
|
+
|
|
204
|
+
@property
|
|
205
|
+
def msg(self) -> str:
|
|
206
|
+
names = ", ".join(self.nodes)
|
|
207
|
+
return (
|
|
208
|
+
f"Cycle [{names}] has no guarded edge — it will loop forever "
|
|
209
|
+
f"without an exit condition. Add a guard (--|guard|-->) to at "
|
|
210
|
+
f"least one edge in the cycle."
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _find_sccs(graph: Graph) -> list[set[str]]:
|
|
215
|
+
"""Tarjan's algorithm: return all strongly connected components."""
|
|
216
|
+
index_counter = 0
|
|
217
|
+
indices: dict[str, int] = {}
|
|
218
|
+
lowlink: dict[str, int] = {}
|
|
219
|
+
on_stack: set[str] = set()
|
|
220
|
+
stack: list[str] = []
|
|
221
|
+
sccs: list[set[str]] = []
|
|
222
|
+
|
|
223
|
+
def _strongconnect(v: str) -> None:
|
|
224
|
+
nonlocal index_counter
|
|
225
|
+
indices[v] = index_counter
|
|
226
|
+
lowlink[v] = index_counter
|
|
227
|
+
index_counter += 1
|
|
228
|
+
stack.append(v)
|
|
229
|
+
on_stack.add(v)
|
|
230
|
+
|
|
231
|
+
for e in graph.out_edges(v):
|
|
232
|
+
w = e.dst
|
|
233
|
+
if w not in indices:
|
|
234
|
+
_strongconnect(w)
|
|
235
|
+
lowlink[v] = min(lowlink[v], lowlink[w])
|
|
236
|
+
elif w in on_stack:
|
|
237
|
+
lowlink[v] = min(lowlink[v], indices[w])
|
|
238
|
+
|
|
239
|
+
if lowlink[v] == indices[v]:
|
|
240
|
+
scc: set[str] = set()
|
|
241
|
+
while True:
|
|
242
|
+
w = stack.pop()
|
|
243
|
+
on_stack.discard(w)
|
|
244
|
+
scc.add(w)
|
|
245
|
+
if w == v:
|
|
246
|
+
break
|
|
247
|
+
sccs.append(scc)
|
|
248
|
+
|
|
249
|
+
for node in graph.nodes:
|
|
250
|
+
if node not in indices:
|
|
251
|
+
_strongconnect(node)
|
|
252
|
+
|
|
253
|
+
return sccs
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def check_unguarded_cycles(graph: Graph) -> list[UnguardedCycleWarning]:
|
|
257
|
+
"""Find cycles that have no guarded edge and will therefore loop forever.
|
|
258
|
+
|
|
259
|
+
Returns a list of warnings; does **not** mutate the graph.
|
|
260
|
+
"""
|
|
261
|
+
sccs = _find_sccs(graph)
|
|
262
|
+
warnings: list[UnguardedCycleWarning] = []
|
|
263
|
+
|
|
264
|
+
for scc in sccs:
|
|
265
|
+
# Single-node SCC: only warn if it has a self-loop.
|
|
266
|
+
if len(scc) == 1:
|
|
267
|
+
node = next(iter(scc))
|
|
268
|
+
has_self_loop = any(
|
|
269
|
+
e.src == node and e.dst == node for e in graph.edges
|
|
270
|
+
)
|
|
271
|
+
if not has_self_loop:
|
|
272
|
+
continue
|
|
273
|
+
|
|
274
|
+
# Edges where both src and dst are inside this SCC.
|
|
275
|
+
internal = [e for e in graph.edges if e.src in scc and e.dst in scc]
|
|
276
|
+
if not internal:
|
|
277
|
+
continue
|
|
278
|
+
|
|
279
|
+
# If NO internal edge is guarded → guaranteed infinite loop.
|
|
280
|
+
if not any(e.guard is not None for e in internal):
|
|
281
|
+
warnings.append(UnguardedCycleWarning(nodes=sorted(scc)))
|
|
282
|
+
|
|
283
|
+
return warnings
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def resolve_or_raise(graph: Graph, suggestions: Iterable[DeadlockSuggestion]) -> None:
|
|
287
|
+
"""Convenience: promote every suggestion in ``suggestions``. If after
|
|
288
|
+
promotion ``check`` still yields suggestions (impossible in v1 unless the
|
|
289
|
+
caller promoted some but not all), raise."""
|
|
290
|
+
for s in suggestions:
|
|
291
|
+
promote(s, graph)
|
|
292
|
+
remaining = check(graph)
|
|
293
|
+
if remaining:
|
|
294
|
+
raise DeadlockError(remaining)
|