stageflow-framework 0.13.1__tar.gz → 0.14.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.
Files changed (86) hide show
  1. {stageflow_framework-0.13.1/stageflow_framework.egg-info → stageflow_framework-0.14.0}/PKG-INFO +1 -1
  2. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/pyproject.toml +1 -1
  3. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/budget.py +123 -13
  4. stageflow_framework-0.14.0/stageflow/core/nodes/fanout.py +72 -0
  5. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/nodes/map_block.py +14 -21
  6. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/nodes/parallel.py +20 -37
  7. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/session.py +35 -3
  8. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0/stageflow_framework.egg-info}/PKG-INFO +1 -1
  9. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow_framework.egg-info/SOURCES.txt +2 -0
  10. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_budget_meters.py +14 -1
  11. stageflow_framework-0.14.0/tests/test_fanout.py +148 -0
  12. stageflow_framework-0.14.0/tests/test_snapshot.py +131 -0
  13. stageflow_framework-0.13.1/tests/test_snapshot.py +0 -45
  14. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/LICENSE +0 -0
  15. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/README.md +0 -0
  16. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/setup.cfg +0 -0
  17. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/__init__.py +0 -0
  18. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/builtins/__init__.py +0 -0
  19. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/builtins/_args.py +0 -0
  20. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/builtins/_base.py +0 -0
  21. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/builtins/dicts.py +0 -0
  22. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/builtins/lists.py +0 -0
  23. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/builtins/logic.py +0 -0
  24. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/builtins/strings.py +0 -0
  25. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/builtins/vars.py +0 -0
  26. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/capabilities.py +0 -0
  27. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/__init__.py +0 -0
  28. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/cel.py +0 -0
  29. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/context.py +0 -0
  30. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/debug.py +0 -0
  31. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/event.py +0 -0
  32. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/inputs.py +0 -0
  33. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/nodes/__init__.py +0 -0
  34. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/nodes/base.py +0 -0
  35. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/nodes/bindings.py +0 -0
  36. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/nodes/branching.py +0 -0
  37. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/nodes/entry.py +0 -0
  38. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/nodes/recovery.py +0 -0
  39. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/nodes/stage.py +0 -0
  40. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/nodes/subpipeline.py +0 -0
  41. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/nodes/terminal.py +0 -0
  42. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/nodes/try_block.py +0 -0
  43. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/payload_schema.py +0 -0
  44. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/pipeline.py +0 -0
  45. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/policy.py +0 -0
  46. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/registry.py +0 -0
  47. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/spec.py +0 -0
  48. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/stage.py +0 -0
  49. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/core/typesys.py +0 -0
  50. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/docs/__init__.py +0 -0
  51. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/docs/schema.py +0 -0
  52. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/docs/schemas/pipeline.json +0 -0
  53. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/exceptions.py +0 -0
  54. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/i18n.py +0 -0
  55. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/locale/ru/LC_MESSAGES/stageflow.mo +0 -0
  56. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/locale/ru/LC_MESSAGES/stageflow.po +0 -0
  57. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/locale/stageflow.pot +0 -0
  58. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/py.typed +0 -0
  59. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow/testing.py +0 -0
  60. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow_framework.egg-info/dependency_links.txt +0 -0
  61. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow_framework.egg-info/requires.txt +0 -0
  62. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/stageflow_framework.egg-info/top_level.txt +0 -0
  63. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_budget.py +0 -0
  64. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_budget_spending.py +0 -0
  65. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_capabilities.py +0 -0
  66. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_core_flow.py +0 -0
  67. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_cycles.py +0 -0
  68. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_debug.py +0 -0
  69. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_docs_schema.py +0 -0
  70. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_entry_node.py +0 -0
  71. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_full_pipeline.py +0 -0
  72. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_i18n.py +0 -0
  73. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_map.py +0 -0
  74. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_packaging.py +0 -0
  75. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_parallel.py +0 -0
  76. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_payload_validation.py +0 -0
  77. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_pipeline_tester.py +0 -0
  78. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_policy.py +0 -0
  79. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_removed_local_scope.py +0 -0
  80. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_schema_errors.py +0 -0
  81. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_session_control.py +0 -0
  82. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_session_wait_input.py +0 -0
  83. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_std_stages.py +0 -0
  84. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_subpipeline.py +0 -0
  85. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_try_block.py +0 -0
  86. {stageflow_framework-0.13.1 → stageflow_framework-0.14.0}/tests/test_typesystem.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stageflow-framework
3
- Version: 0.13.1
3
+ Version: 0.14.0
4
4
  Summary: StageFlow: pipeline framework for stages
5
5
  Author-email: лень <pzrnqt1vrss@protonmail.com>
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "stageflow-framework"
7
- version = "0.13.1"
7
+ version = "0.14.0"
8
8
  description = "StageFlow: pipeline framework for stages"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -1,12 +1,32 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import asyncio
4
+ import contextvars
4
5
  import time
5
6
  from contextlib import asynccontextmanager, contextmanager
6
7
  from dataclasses import dataclass, field
7
8
  from typing import AsyncIterator, Iterator
8
9
 
9
10
 
11
+ class _Ticket:
12
+ """One unit a task holds — or held, until it gave it back for a wait."""
13
+
14
+ __slots__ = ("held",)
15
+
16
+ def __init__(self) -> None:
17
+ self.held = True
18
+
19
+
20
+ #: The slots the current task holds, by meter. A context variable because a
21
+ #: task is what holds one: `asyncio.create_task` copies the context, so a
22
+ #: child task starts out believing it holds whatever its parent held — which
23
+ #: is why children are only ever created inside `Budget.released`, where the
24
+ #: parent has given its slot back and the copy says so.
25
+ _HOLDING: contextvars.ContextVar[dict[str, _Ticket]] = contextvars.ContextVar(
26
+ "stageflow_budget_holding", default={}
27
+ )
28
+
29
+
10
30
  class BudgetExceeded(BaseException):
11
31
  """A session ran past what it was allowed.
12
32
 
@@ -112,6 +132,25 @@ class Budget:
112
132
  self._idle: float = 0.0
113
133
  self._idle_since: float | None = None
114
134
  self._idle_depth = 0
135
+ #: busy time spent before this object existed — a session restored
136
+ #: from a snapshot carries on from what it had already used
137
+ self._carried: float = 0.0
138
+
139
+ def restore(self, spent: dict[str, float] | None) -> None:
140
+ """Carry the running total over from a snapshot's `meters`.
141
+
142
+ Without it a session restored mid-run starts from zero, and stopping
143
+ and restoring a session is a way to get a fresh allowance whenever the
144
+ old one runs out. Only counters travel: gauges are instantaneous and
145
+ nothing is being held by a session that is not running.
146
+ """
147
+ for meter, amount in (spent or {}).items():
148
+ if meter.startswith("peak_"):
149
+ continue
150
+ if meter == "seconds":
151
+ self._carried = float(amount)
152
+ else:
153
+ self.counters[meter] = float(amount)
115
154
 
116
155
  # ------------------------------------------------------------- the clock
117
156
 
@@ -137,7 +176,7 @@ class Budget:
137
176
  if self._started is None:
138
177
  return 0.0
139
178
  until = self._stopped if self._stopped is not None else time.monotonic()
140
- return until - self._started - self.idle_seconds
179
+ return self._carried + until - self._started - self.idle_seconds
141
180
 
142
181
  def begin_idle(self) -> None:
143
182
  """Stop the clock: from here the session is waiting, not working.
@@ -249,21 +288,92 @@ class Budget:
249
288
  not have a hundred calls in the air at once. Failing it would refuse
250
289
  legitimate work for being wide; holding it back runs the same work
251
290
  within the allowance.
291
+
292
+ Re-entrant within a task: a sequential `map` inside a `parallel`
293
+ branch runs in the branch's own task and adds no concurrency, so it
294
+ does not take a second unit. A task waiting for children of its own
295
+ gives its unit back for the wait — see `released`.
252
296
  """
253
- limit = self.limits.gauges.get(meter)
254
- if limit is None:
255
- with self._hold(meter):
256
- yield
297
+ if meter in _HOLDING.get():
298
+ yield
299
+ return
300
+ await self._acquire(meter)
301
+ ticket = _Ticket()
302
+ token = _HOLDING.set({**_HOLDING.get(), meter: ticket})
303
+ try:
304
+ yield
305
+ finally:
306
+ _HOLDING.reset(token)
307
+ # not held when taking it back after a wait was cut short — by a
308
+ # cancellation or the deadline — and then there is nothing to give
309
+ if ticket.held:
310
+ self._release(meter)
311
+
312
+ @asynccontextmanager
313
+ async def released(self, meter: str = "concurrency") -> AsyncIterator[None]:
314
+ """Give this task's unit back while it waits for its children.
315
+
316
+ A `parallel` branch that runs a `map` holds a unit and then waits for
317
+ items that each need one. With the limit at 1 that is a deadlock, and
318
+ with any limit it is one as soon as the nesting is wider than the
319
+ allowance — the waiting parent occupies the very unit its children
320
+ need. A task that is waiting is not working, so for the length of the
321
+ wait it is not counted: the limit bounds the work actually in the
322
+ air, and the parent takes its unit back once the children are done.
323
+
324
+ Children must be created *inside* this block: they copy the context,
325
+ and only here does it say the parent holds nothing.
326
+ """
327
+ ticket = _HOLDING.get().get(meter)
328
+ if ticket is None or not ticket.held:
329
+ yield
257
330
  return
331
+ self._release(meter)
332
+ ticket.held = False
333
+ token = _HOLDING.set({k: v for k, v in _HOLDING.get().items() if k != meter})
334
+ try:
335
+ yield
336
+ finally:
337
+ _HOLDING.reset(token)
338
+ await self._acquire(meter)
339
+ ticket.held = True
340
+
341
+ async def _acquire(self, meter: str) -> None:
342
+ limit = self.limits.gauges.get(meter)
343
+ if limit is not None:
344
+ slot = self._slots.get(meter)
345
+ if slot is None:
346
+ # a throttle of nothing would deadlock, so nonsense serialises
347
+ slot = self._slots[meter] = asyncio.Semaphore(max(1, int(limit)))
348
+ await self._within_deadline(slot.acquire())
349
+ # the semaphore is the enforcement; holding only records the peak, or
350
+ # the two would have to agree about the boundary twice
351
+ held = self._held.get(meter, 0.0) + 1
352
+ self._held[meter] = held
353
+ self.peaks[meter] = max(self.peaks.get(meter, 0.0), held)
354
+
355
+ def _release(self, meter: str) -> None:
356
+ self._held[meter] = self._held.get(meter, 0.0) - 1
258
357
  slot = self._slots.get(meter)
259
- if slot is None:
260
- # a throttle of nothing would deadlock, so nonsense serialises
261
- slot = self._slots[meter] = asyncio.Semaphore(max(1, int(limit)))
262
- async with slot:
263
- # the semaphore is the enforcement here; holding only records the
264
- # peak, or the two would have to agree about the boundary twice
265
- with self._hold(meter):
266
- yield
358
+ if slot is not None:
359
+ slot.release()
360
+
361
+ async def _within_deadline(self, waiting) -> None:
362
+ """Wait for a turn, but not past the session's deadline.
363
+
364
+ The deadline is otherwise checked between nodes, and a task waiting
365
+ for a unit is between nothing: without this, a run whose units are
366
+ all taken would wait for as long as they are, whatever `seconds` says.
367
+ """
368
+ left = self.remaining_seconds()
369
+ if left is None:
370
+ await waiting
371
+ return
372
+ try:
373
+ await asyncio.wait_for(waiting, timeout=max(left, 0))
374
+ except asyncio.TimeoutError:
375
+ raise BudgetExceeded("seconds", self.deadline_seconds,
376
+ self.busy_seconds) from None
267
377
 
268
378
  @contextmanager
269
379
  def gauge(self, meter: str, amount: float = 1) -> Iterator[None]:
@@ -0,0 +1,72 @@
1
+ """Running children concurrently: what `parallel` and a parallel `map` share.
2
+
3
+ Two things both of them have to get right, and used to get right separately
4
+ or not at all.
5
+
6
+ The parent gives its unit of concurrency back while it waits. A branch of a
7
+ `parallel` that holds a unit and then waits for a `map` whose items each need
8
+ one is a deadlock the moment the nesting is wider than the allowance — see
9
+ `Budget.released`. The children are created inside that block, so they start
10
+ out holding nothing.
11
+
12
+ A terminal in one child ends the run, the way a terminal inside a `try` or a
13
+ `map` does. The siblings are cancelled rather than left to run on into a
14
+ graph that has finished, and the parent does not carry on to its `next`.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import asyncio
19
+ from typing import TYPE_CHECKING, Awaitable, Callable, Hashable, TypeVar
20
+
21
+ if TYPE_CHECKING: # pragma: no cover
22
+ from ..session import Session
23
+
24
+ K = TypeVar("K", bound=Hashable)
25
+ T = TypeVar("T")
26
+
27
+
28
+ async def run_children(
29
+ session: "Session",
30
+ children: dict[K, Callable[[], Awaitable[T]]],
31
+ cancel_on_error: bool,
32
+ ) -> tuple[dict[K, asyncio.Task], list[K]]:
33
+ """Start every child, wait until they are done or no longer wanted.
34
+
35
+ @returns the tasks by key, and the keys of those that were cancelled.
36
+ The caller reads results and exceptions off the tasks.
37
+ """
38
+ async with session.budget.released("concurrency"):
39
+ tasks = {key: asyncio.create_task(make()) for key, make in children.items()}
40
+ pending: set[asyncio.Task] = set(tasks.values())
41
+ try:
42
+ while pending:
43
+ done, pending = await asyncio.wait(
44
+ pending, return_when=asyncio.FIRST_COMPLETED
45
+ )
46
+ if session.finished:
47
+ break
48
+ if cancel_on_error and any(
49
+ not task.cancelled() and task.exception() is not None
50
+ for task in done
51
+ ):
52
+ break
53
+ except asyncio.CancelledError:
54
+ for task in tasks.values():
55
+ task.cancel()
56
+ await asyncio.gather(*tasks.values(), return_exceptions=True)
57
+ raise
58
+
59
+ cancelled = [key for key, task in tasks.items() if task in pending]
60
+ for task in pending:
61
+ task.cancel()
62
+ if pending:
63
+ await asyncio.gather(*pending, return_exceptions=True)
64
+ return tasks, cancelled
65
+
66
+
67
+ def first_failure(tasks: dict[K, asyncio.Task]) -> tuple[K, BaseException] | None:
68
+ """The first child, in the order given, that raised — not one cancelled."""
69
+ for key, task in tasks.items():
70
+ if not task.cancelled() and task.exception() is not None:
71
+ return key, task.exception()
72
+ return None
@@ -1,6 +1,5 @@
1
1
  from __future__ import annotations
2
2
 
3
- import asyncio
4
3
  from typing import TYPE_CHECKING, Any
5
4
 
6
5
  from ...exceptions import PipelineDefinitionError, StageOutputError, TypeCheckError
@@ -8,6 +7,7 @@ from ...i18n import _
8
7
  from ..context import Context
9
8
  from .base import Node, register_node
10
9
  from .bindings import normalize_bucket
10
+ from .fanout import run_children
11
11
  from .recovery import error_name, run_with_retry
12
12
 
13
13
  if TYPE_CHECKING: # pragma: no cover
@@ -216,33 +216,26 @@ class MapNode(Node):
216
216
  async def _run_parallel(
217
217
  self, session: "Session", ctx: Context, scope: frozenset[str], items: list
218
218
  ) -> list[Context | None]:
219
- tasks = [
220
- asyncio.create_task(self._run_item(session, ctx, scope, index, item))
221
- for index, item in enumerate(items)
222
- ]
223
- if not tasks:
219
+ if not items:
224
220
  return []
225
-
226
- mode = asyncio.FIRST_EXCEPTION if self.cancel_on_error else asyncio.ALL_COMPLETED
227
- try:
228
- _, pending = await asyncio.wait(tasks, return_when=mode)
229
- except asyncio.CancelledError:
230
- for task in tasks:
231
- task.cancel()
232
- raise
233
- if pending:
234
- cancelled = [index for index, task in enumerate(tasks) if task in pending]
235
- for task in pending:
236
- task.cancel()
237
- await asyncio.gather(*pending, return_exceptions=True)
221
+ tasks, cancelled = await run_children(
222
+ session,
223
+ {
224
+ index: (lambda index=index, item=item:
225
+ self._run_item(session, ctx, scope, index, item))
226
+ for index, item in enumerate(items)
227
+ },
228
+ self.cancel_on_error,
229
+ )
230
+ if cancelled:
238
231
  session.emit_node_event("map_cancelled", self, {"items": sorted(cancelled)})
239
232
 
240
- for index, task in enumerate(tasks):
233
+ for index, task in tasks.items():
241
234
  if task.cancelled() or task.exception() is None:
242
235
  continue
243
236
  self._emit_failure(session, index, task.exception())
244
237
  raise task.exception()
245
- return [None if task.cancelled() else task.result() for task in tasks]
238
+ return [None if task.cancelled() else task.result() for task in tasks.values()]
246
239
 
247
240
  async def _run_item(
248
241
  self,
@@ -1,6 +1,5 @@
1
1
  from __future__ import annotations
2
2
 
3
- import asyncio
4
3
  from typing import TYPE_CHECKING
5
4
 
6
5
  from ...exceptions import BranchError
@@ -8,6 +7,7 @@ from ...i18n import _
8
7
  from ..budget import BudgetExceeded
9
8
  from ..context import Context
10
9
  from .base import Node, register_node
10
+ from .fanout import first_failure, run_children
11
11
  from .recovery import run_with_retry
12
12
 
13
13
  if TYPE_CHECKING: # pragma: no cover
@@ -79,22 +79,19 @@ class ParallelNode(Node):
79
79
  async def body() -> tuple[Node | None, Context]:
80
80
  baseline_keys = ctx.var_names()
81
81
 
82
- tasks = {
83
- branch["id"]: asyncio.create_task(
84
- self._branch(session, branch["entry"], ctx)
85
- )
86
- for branch in self.branches
87
- }
88
- await self._wait_branches(session, tasks)
89
-
90
- failure = next(
91
- (
92
- (branch_id, task.exception())
93
- for branch_id, task in tasks.items()
94
- if not task.cancelled() and task.exception() is not None
95
- ),
96
- None,
82
+ tasks, cancelled = await run_children(
83
+ session,
84
+ {
85
+ branch["id"]: (lambda entry=branch["entry"]: self._branch(session, entry, ctx))
86
+ for branch in self.branches
87
+ },
88
+ self.cancel_on_error,
97
89
  )
90
+ if cancelled:
91
+ session.emit_node_event(
92
+ "parallel_cancelled", self, {"branches": sorted(cancelled)}
93
+ )
94
+ failure = first_failure(tasks)
98
95
  if failure is not None:
99
96
  branch_id, exc = failure
100
97
  # BranchError is an ordinary exception and a `try` block can
@@ -105,19 +102,20 @@ class ParallelNode(Node):
105
102
  raise BranchError(
106
103
  _("branch '{branch}' failed: {reason}", branch=branch_id, reason=exc)
107
104
  ) from exc
105
+ # a terminal in a branch has ended the run: the other branches are
106
+ # cancelled, and there is no `next` to go on to
107
+ if session.finished:
108
+ return None, ctx
108
109
 
109
- merged = self._merge(
110
- ctx, baseline_keys, {bid: task.result() for bid, task in tasks.items()}
111
- )
110
+ results = {bid: task.result() for bid, task in tasks.items()}
111
+ merged = self._merge(ctx, baseline_keys, results)
112
112
  merged = self.apply_expose(session, merged)
113
113
  session.emit_node_event(
114
114
  "parallel_completed",
115
115
  self,
116
116
  {
117
117
  "merged": sorted(merged.var_names() - baseline_keys),
118
- "dropped": self._dropped(
119
- ctx, baseline_keys, {bid: task.result() for bid, task in tasks.items()}
120
- ),
118
+ "dropped": self._dropped(ctx, baseline_keys, results),
121
119
  },
122
120
  )
123
121
  return self._goto(session, self.next), merged
@@ -133,21 +131,6 @@ class ParallelNode(Node):
133
131
  async with session.budget.slot("concurrency"):
134
132
  return await session.run_subgraph(entry, ctx)
135
133
 
136
- async def _wait_branches(self, session: "Session", tasks: dict[str, asyncio.Task]) -> None:
137
- mode = asyncio.FIRST_EXCEPTION if self.cancel_on_error else asyncio.ALL_COMPLETED
138
- try:
139
- _, pending = await asyncio.wait(tasks.values(), return_when=mode)
140
- except asyncio.CancelledError:
141
- for task in tasks.values():
142
- task.cancel()
143
- raise
144
- if pending:
145
- cancelled = [branch_id for branch_id, task in tasks.items() if task in pending]
146
- for task in pending:
147
- task.cancel()
148
- await asyncio.gather(*pending, return_exceptions=True)
149
- session.emit_node_event("parallel_cancelled", self, {"branches": sorted(cancelled)})
150
-
151
134
  def _merge(
152
135
  self,
153
136
  base: Context,
@@ -25,6 +25,8 @@ EventHandler = Callable[[Event], None]
25
25
 
26
26
  _STOPPED_RESULT = {"result": "stopped"}
27
27
 
28
+ _NO_FRAME = Context()
29
+
28
30
  #: How many events one session keeps. A cyclic graph emits tens of thousands
29
31
  #: a second, and an unbounded list is the cheapest way for a pipeline to take
30
32
  #: a process down — the log is a window, not an archive.
@@ -285,7 +287,9 @@ class Session:
285
287
  return {}
286
288
  amounts: dict[str, float] = {}
287
289
  for meter, spec in declared.items():
288
- value = (self.cel.eval(spec, self.context, args=kwargs)
290
+ # over `args` only, as documented: a reservation is read before
291
+ # the stage runs and has to be knowable from what it is given
292
+ value = (self.cel.eval(spec, _NO_FRAME, args=kwargs)
289
293
  if isinstance(spec, str) else spec)
290
294
  try:
291
295
  amounts[meter] = float(value)
@@ -387,11 +391,16 @@ class Session:
387
391
 
388
392
  async def run_subgraph(self, start_id: str, ctx: Context) -> Context:
389
393
  node: Node | None = self.pipeline.get_node(start_id)
390
- while node is not None:
394
+ # a terminal elsewhere — in a sibling branch — has ended the run
395
+ while node is not None and not self.finished:
391
396
  node, ctx = await self.execute_node(node, ctx)
392
397
  return ctx
393
398
 
394
399
  def finish(self, node: TerminalNode, ctx: Context) -> None:
400
+ # two branches of a `parallel` can both reach a terminal; the first
401
+ # one ends the run, and the second is not allowed to rewrite it
402
+ if self.finished:
403
+ return
395
404
  self.artifacts = {name: ctx.get_var(name) for name in node.artifacts}
396
405
  self.result = node.result
397
406
  self.finished = True
@@ -427,6 +436,9 @@ class Session:
427
436
  self.result = dict(_STOPPED_RESULT)
428
437
  break
429
438
  node, ctx = step.result()
439
+ # kept current so that a snapshot taken between nodes resumes
440
+ # with the frame as it is, not as the run started
441
+ self.context = ctx
430
442
  except BudgetExceeded as over:
431
443
  # the one place that catches it. A pipeline cannot: `try` blocks
432
444
  # and `run_with_retry` catch Exception, and this is not one. The
@@ -500,6 +512,9 @@ class Session:
500
512
  "paused": self.paused,
501
513
  "skip_requested": self._skip_requested,
502
514
  "pipeline": self.pipeline.raw_json,
515
+ # what the run has spent, so that a restored one goes on from it
516
+ # rather than from a fresh allowance
517
+ "meters": self.budget.report(),
503
518
  }
504
519
 
505
520
  @classmethod
@@ -508,7 +523,18 @@ class Session:
508
523
  snapshot: dict,
509
524
  pipeline: Pipeline | None = None,
510
525
  event_handler: EventHandler | None = None,
526
+ *,
527
+ policy: Policy,
528
+ limits: Limits | None = None,
511
529
  ) -> "Session":
530
+ """Restore a session, under the policy the host gives it now.
531
+
532
+ `policy` is required, and is deliberately not part of the snapshot. A
533
+ snapshot is data — stored, passed around, possibly edited — and an
534
+ allowance read back out of data is one the data can widen. The host
535
+ says again what this session may do; `OPEN` is a valid answer, but it
536
+ has to be given. The spent meters do travel, and are carried over.
537
+ """
512
538
  if pipeline is None:
513
539
  raw = snapshot.get("pipeline")
514
540
  if not raw:
@@ -522,12 +548,18 @@ class Session:
522
548
  pipeline=pipeline,
523
549
  context=Context.from_dict(snapshot.get("context", {})),
524
550
  event_handler=event_handler,
551
+ policy=policy,
552
+ limits=limits,
525
553
  )
554
+ session.budget.restore(snapshot.get("meters"))
526
555
  session._current_node_id = snapshot.get("current_node_id")
527
556
  session.result = snapshot.get("result")
528
557
  session.artifacts = snapshot.get("artifacts", {})
529
558
  session.inputs.history.extend(snapshot.get("input_history", []))
530
- session.event_history = [Event.from_dict(e) for e in snapshot.get("event_history", [])]
559
+ session.event_history = deque(
560
+ (Event.from_dict(e) for e in snapshot.get("event_history", [])),
561
+ maxlen=EVENT_HISTORY,
562
+ )
531
563
  session._skip_requested = snapshot.get("skip_requested", False)
532
564
  if snapshot.get("stopped", False):
533
565
  session._stop_requested.set()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stageflow-framework
3
- Version: 0.13.1
3
+ Version: 0.14.0
4
4
  Summary: StageFlow: pipeline framework for stages
5
5
  Author-email: лень <pzrnqt1vrss@protonmail.com>
6
6
  License-Expression: MIT
@@ -35,6 +35,7 @@ stageflow/core/nodes/base.py
35
35
  stageflow/core/nodes/bindings.py
36
36
  stageflow/core/nodes/branching.py
37
37
  stageflow/core/nodes/entry.py
38
+ stageflow/core/nodes/fanout.py
38
39
  stageflow/core/nodes/map_block.py
39
40
  stageflow/core/nodes/parallel.py
40
41
  stageflow/core/nodes/recovery.py
@@ -62,6 +63,7 @@ tests/test_cycles.py
62
63
  tests/test_debug.py
63
64
  tests/test_docs_schema.py
64
65
  tests/test_entry_node.py
66
+ tests/test_fanout.py
65
67
  tests/test_full_pipeline.py
66
68
  tests/test_i18n.py
67
69
  tests/test_map.py
@@ -171,10 +171,23 @@ class SlotTests(unittest.IsolatedAsyncioTestCase):
171
171
 
172
172
  async def test_an_unlimited_slot_lets_everything_through(self):
173
173
  budget = Budget()
174
+
175
+ async def worker():
176
+ async with budget.slot("concurrency"):
177
+ await asyncio.sleep(0.01)
178
+
179
+ await asyncio.gather(worker(), worker())
180
+ self.assertEqual(budget.report()["peak_concurrency"], 2)
181
+
182
+ async def test_a_slot_is_reentrant_within_one_task(self):
183
+ # a sequential loop inside a branch runs in the branch's task and adds
184
+ # no concurrency: it must not need — and with the limit at 1, wait
185
+ # forever for — a second unit
186
+ budget = Budget(Limits(gauges={"concurrency": 1}))
174
187
  async with budget.slot("concurrency"):
175
188
  async with budget.slot("concurrency"):
176
189
  pass
177
- self.assertEqual(budget.report()["peak_concurrency"], 2)
190
+ self.assertEqual(budget.report()["peak_concurrency"], 1)
178
191
 
179
192
  async def test_a_slot_is_released_when_the_body_raises(self):
180
193
  budget = Budget(Limits(gauges={"concurrency": 1}))
@@ -0,0 +1,148 @@
1
+ """Nested fan-out under a concurrency limit, and a terminal inside a branch."""
2
+ import asyncio
3
+ import unittest
4
+
5
+ from stageflow import BaseStage, Limits, Pipeline, Session, register_stage
6
+
7
+
8
+ @register_stage("FanoutTick")
9
+ class FanoutTick(BaseStage):
10
+ """
11
+ description: "Takes a moment and says it ran"
12
+ arguments:
13
+ tag: any
14
+ outputs:
15
+ seen: any
16
+ """
17
+
18
+ live = 0
19
+ peak = 0
20
+
21
+ async def run(self):
22
+ cls = type(self)
23
+ cls.live += 1
24
+ cls.peak = max(cls.peak, cls.live)
25
+ try:
26
+ await asyncio.sleep(0.01)
27
+ finally:
28
+ cls.live -= 1
29
+ self.set_outputs({"seen": self.get_arguments().get("tag")})
30
+
31
+
32
+ @register_stage("FanoutSlow")
33
+ class FanoutSlow(BaseStage):
34
+ """
35
+ description: "Never finishes on its own"
36
+ """
37
+
38
+ timeout = None
39
+ cancelled = False
40
+
41
+ async def run(self):
42
+ try:
43
+ await asyncio.sleep(10)
44
+ except asyncio.CancelledError:
45
+ type(self).cancelled = True
46
+ raise
47
+
48
+
49
+ def _run(data, **kwargs):
50
+ async def go():
51
+ return await asyncio.wait_for(
52
+ Session(id="s", pipeline=Pipeline.from_dict(data), **kwargs).run(), 5
53
+ )
54
+ return asyncio.run(go())
55
+
56
+
57
+ def _map_in_branches(branches: int, mode: str) -> dict:
58
+ nodes = [{"id": "start", "type": "entry", "variables": {"xs": [1, 2, 3]},
59
+ "next": "par"},
60
+ {"id": "par", "type": "parallel",
61
+ "branches": [f"m{i}" for i in range(branches)], "next": "end"}]
62
+ for i in range(branches):
63
+ nodes += [
64
+ {"id": f"m{i}", "type": "map", "items": "vars.xs", "body": f"b{i}",
65
+ "mode": mode, "collect": {"seen": f"out{i}"}},
66
+ {"id": f"b{i}", "type": "stage", "stage": "FanoutTick",
67
+ "arguments": {"vars": {"tag": "item"}}, "outputs": {"seen": "seen"}},
68
+ ]
69
+ nodes.append({"id": "end", "type": "terminal",
70
+ "artifacts": [f"out{i}" for i in range(branches)]})
71
+ return {"nodes": nodes}
72
+
73
+
74
+ class NestedConcurrencyTests(unittest.TestCase):
75
+ def setUp(self):
76
+ FanoutTick.live = FanoutTick.peak = 0
77
+
78
+ def test_a_map_inside_a_branch_does_not_deadlock_at_one(self):
79
+ for mode in ("sequential", "parallel"):
80
+ with self.subTest(mode=mode):
81
+ FanoutTick.peak = 0
82
+ result = _run(_map_in_branches(1, mode),
83
+ limits=Limits(gauges={"concurrency": 1}))
84
+ self.assertEqual(result.artifacts, {"out0": [1, 2, 3]})
85
+ self.assertEqual(FanoutTick.peak, 1)
86
+
87
+ def test_nesting_wider_than_the_allowance_still_finishes(self):
88
+ result = _run(_map_in_branches(4, "parallel"),
89
+ limits=Limits(gauges={"concurrency": 2}))
90
+ self.assertEqual(result.artifacts,
91
+ {f"out{i}": [1, 2, 3] for i in range(4)})
92
+ # what the limit bounds is the work in the air, nested or not
93
+ self.assertLessEqual(FanoutTick.peak, 2)
94
+ self.assertLessEqual(result.meters["peak_concurrency"], 2)
95
+
96
+ def test_waiting_for_a_unit_is_bounded_by_the_deadline(self):
97
+ data = {"nodes": [
98
+ {"id": "start", "type": "entry", "next": "par"},
99
+ {"id": "par", "type": "parallel", "branches": ["a", "b"], "next": "end"},
100
+ {"id": "a", "type": "stage", "stage": "FanoutSlow"},
101
+ {"id": "b", "type": "stage", "stage": "FanoutSlow"},
102
+ {"id": "end", "type": "terminal"},
103
+ ]}
104
+ result = _run(data, limits=Limits(counters={"seconds": 0.2},
105
+ gauges={"concurrency": 1}))
106
+ self.assertEqual(result.result["status"], "budget_exceeded")
107
+ self.assertEqual(result.result["meter"], "seconds")
108
+
109
+
110
+ class TerminalInBranchTests(unittest.TestCase):
111
+ def test_a_terminal_in_a_branch_ends_the_run(self):
112
+ FanoutSlow.cancelled = False
113
+ data = {"nodes": [
114
+ {"id": "start", "type": "entry", "next": "par"},
115
+ {"id": "par", "type": "parallel", "branches": ["first", "slow"],
116
+ "next": "after"},
117
+ # a moment first, so that the slow branch is already running
118
+ {"id": "first", "type": "stage", "stage": "FanoutTick", "next": "t"},
119
+ {"id": "t", "type": "terminal", "result": {"status": "from_branch"}},
120
+ {"id": "slow", "type": "stage", "stage": "FanoutSlow"},
121
+ {"id": "after", "type": "stage", "stage": "FanoutTick",
122
+ "next": "end"},
123
+ {"id": "end", "type": "terminal", "result": {"status": "main"}},
124
+ ]}
125
+ result = _run(data)
126
+ self.assertEqual(result.result, {"status": "from_branch"})
127
+ self.assertTrue(FanoutSlow.cancelled)
128
+ types = [event.type for event in result.history]
129
+ self.assertIn("parallel_cancelled", types)
130
+ self.assertNotIn("parallel_completed", types)
131
+
132
+ def test_a_terminal_in_a_parallel_map_item_ends_the_run(self):
133
+ data = {"nodes": [
134
+ {"id": "start", "type": "entry", "variables": {"xs": [0, 1]},
135
+ "next": "m"},
136
+ {"id": "m", "type": "map", "items": "vars.xs", "body": "pick",
137
+ "mode": "parallel", "next": "end"},
138
+ {"id": "pick", "type": "condition", "condition": "vars.item == 0",
139
+ "then": "stop", "else": "slow"},
140
+ {"id": "stop", "type": "terminal", "result": {"status": "early"}},
141
+ {"id": "slow", "type": "stage", "stage": "FanoutSlow"},
142
+ {"id": "end", "type": "terminal", "result": {"status": "main"}},
143
+ ]}
144
+ self.assertEqual(_run(data).result, {"status": "early"})
145
+
146
+
147
+ if __name__ == "__main__":
148
+ unittest.main()
@@ -0,0 +1,131 @@
1
+ import asyncio
2
+ import unittest
3
+
4
+ from stageflow import BaseStage, Context, Limits, Pipeline, Policy, Session, register_stage
5
+ from stageflow.core.policy import OPEN
6
+
7
+
8
+ @register_stage("SnapshotWaitStage")
9
+ class SnapshotWaitStage(BaseStage):
10
+ async def run(self):
11
+ await self.wait_input("go", timeout=0.5)
12
+
13
+
14
+ class SessionSnapshotTests(unittest.IsolatedAsyncioTestCase):
15
+ async def test_snapshot_round_trip_and_resume(self):
16
+ pipeline_json = {
17
+ "entry": "wait",
18
+ "nodes": [
19
+ {"id": "wait", "type": "stage", "stage": "SnapshotWaitStage", "next": "end"},
20
+ {"id": "end", "type": "terminal", "result": {"status": "done"}},
21
+ ],
22
+ }
23
+ pipeline = Pipeline.from_dict(pipeline_json)
24
+ session = Session(id="snap", pipeline=pipeline, context=Context())
25
+
26
+ task = asyncio.create_task(session.run())
27
+ while not session.is_waiting_for("go"):
28
+ await asyncio.sleep(0.01)
29
+ snap = session.snapshot()
30
+ await session.input("go", {"v": 1})
31
+ await task
32
+
33
+ self.assertEqual(snap["current_node_id"], "wait")
34
+ self.assertEqual(snap.get("context", {}).get("vars", {}), {})
35
+
36
+ restored = Session.from_snapshot(snap, policy=OPEN)
37
+ resume_task = asyncio.create_task(restored.run())
38
+ while not restored.is_waiting_for("go"):
39
+ await asyncio.sleep(0.01)
40
+ await restored.input("go", {"v": 2})
41
+ result = await resume_task
42
+ self.assertEqual(result.result, {"status": "done"})
43
+
44
+
45
+ @register_stage("SnapshotSetStage")
46
+ class SnapshotSetStage(BaseStage):
47
+ """
48
+ description: "Writes a value"
49
+ arguments:
50
+ v: any
51
+ outputs:
52
+ v: any
53
+ """
54
+
55
+ async def run(self):
56
+ self.set_outputs({"v": self.get_arguments()["v"]})
57
+
58
+
59
+ class SnapshotMidRunTests(unittest.IsolatedAsyncioTestCase):
60
+ PIPELINE = {
61
+ "entry": "set",
62
+ "nodes": [
63
+ {"id": "set", "type": "stage", "stage": "SnapshotSetStage",
64
+ "arguments": {"const": {"v": 42}}, "outputs": {"v": "v"}, "next": "wait"},
65
+ {"id": "wait", "type": "stage", "stage": "SnapshotWaitStage", "next": "end"},
66
+ {"id": "end", "type": "terminal", "artifacts": ["v"]},
67
+ ],
68
+ }
69
+
70
+ async def _paused_snapshot(self, **kwargs):
71
+ session = Session(id="mid", pipeline=Pipeline.from_dict(self.PIPELINE), **kwargs)
72
+ task = asyncio.create_task(session.run())
73
+ while not session.is_waiting_for("go"):
74
+ await asyncio.sleep(0.01)
75
+ snap = session.snapshot()
76
+ session.stop()
77
+ await task
78
+ return snap
79
+
80
+ async def test_the_frame_is_the_current_one(self):
81
+ snap = await self._paused_snapshot()
82
+ self.assertEqual(snap["current_node_id"], "wait")
83
+ self.assertEqual(snap["context"]["vars"], {"v": 42})
84
+
85
+ restored = Session.from_snapshot(snap, policy=OPEN)
86
+ task = asyncio.create_task(restored.run())
87
+ while not restored.is_waiting_for("go"):
88
+ await asyncio.sleep(0.01)
89
+ await restored.input("go", {})
90
+ result = await task
91
+ self.assertEqual(result.artifacts, {"v": 42})
92
+
93
+ async def test_a_policy_must_be_given(self):
94
+ snap = await self._paused_snapshot()
95
+ with self.assertRaises(TypeError):
96
+ Session.from_snapshot(snap)
97
+
98
+ async def test_the_policy_given_is_the_one_enforced(self):
99
+ snap = await self._paused_snapshot()
100
+ narrow = Policy(stages={"SnapshotSetStage"})
101
+ from stageflow.exceptions import PipelineValidationError
102
+ with self.assertRaises(PipelineValidationError):
103
+ Session.from_snapshot(snap, policy=narrow)
104
+
105
+ async def test_spending_carries_over(self):
106
+ limits = Limits(counters={"steps": 100})
107
+ snap = await self._paused_snapshot(limits=limits)
108
+ spent = snap["meters"]["steps"]
109
+ self.assertGreater(spent, 0)
110
+ restored = Session.from_snapshot(snap, policy=Policy(limits=limits))
111
+ self.assertEqual(restored.budget.spent("steps"), spent)
112
+ # a restore cannot be a way to a fresh allowance
113
+ # set and wait are spent; one more step fits validation (the shortest
114
+ # road is three nodes) and not the run that is left
115
+ self.assertEqual(spent, 2)
116
+ tight = Limits(counters={"steps": spent + 1})
117
+ restored = Session.from_snapshot(snap, policy=Policy(limits=tight))
118
+ task = asyncio.create_task(restored.run())
119
+ result = await asyncio.wait_for(task, 2)
120
+ self.assertEqual(result.result["status"], "budget_exceeded")
121
+
122
+ async def test_the_event_log_stays_bounded(self):
123
+ from collections import deque
124
+ snap = await self._paused_snapshot()
125
+ restored = Session.from_snapshot(snap, policy=OPEN)
126
+ self.assertIsInstance(restored.event_history, deque)
127
+ self.assertIsNotNone(restored.event_history.maxlen)
128
+
129
+
130
+ if __name__ == "__main__":
131
+ unittest.main()
@@ -1,45 +0,0 @@
1
- import asyncio
2
- import unittest
3
-
4
- from stageflow import BaseStage, Context, Pipeline, Session, register_stage
5
-
6
-
7
- @register_stage("SnapshotWaitStage")
8
- class SnapshotWaitStage(BaseStage):
9
- async def run(self):
10
- await self.wait_input("go", timeout=0.5)
11
-
12
-
13
- class SessionSnapshotTests(unittest.IsolatedAsyncioTestCase):
14
- async def test_snapshot_round_trip_and_resume(self):
15
- pipeline_json = {
16
- "entry": "wait",
17
- "nodes": [
18
- {"id": "wait", "type": "stage", "stage": "SnapshotWaitStage", "next": "end"},
19
- {"id": "end", "type": "terminal", "result": {"status": "done"}},
20
- ],
21
- }
22
- pipeline = Pipeline.from_dict(pipeline_json)
23
- session = Session(id="snap", pipeline=pipeline, context=Context())
24
-
25
- task = asyncio.create_task(session.run())
26
- while not session.is_waiting_for("go"):
27
- await asyncio.sleep(0.01)
28
- snap = session.snapshot()
29
- await session.input("go", {"v": 1})
30
- await task
31
-
32
- self.assertEqual(snap["current_node_id"], "wait")
33
- self.assertEqual(snap.get("context", {}).get("vars", {}), {})
34
-
35
- restored = Session.from_snapshot(snap)
36
- resume_task = asyncio.create_task(restored.run())
37
- while not restored.is_waiting_for("go"):
38
- await asyncio.sleep(0.01)
39
- await restored.input("go", {"v": 2})
40
- result = await resume_task
41
- self.assertEqual(result.result, {"status": "done"})
42
-
43
-
44
- if __name__ == "__main__":
45
- unittest.main()