stageflow-framework 0.13.0__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 (88) hide show
  1. {stageflow_framework-0.13.0/stageflow_framework.egg-info → stageflow_framework-0.14.0}/PKG-INFO +1 -1
  2. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/pyproject.toml +1 -1
  3. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/capabilities.py +8 -0
  4. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/budget.py +123 -13
  5. stageflow_framework-0.14.0/stageflow/core/nodes/fanout.py +72 -0
  6. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/nodes/map_block.py +14 -21
  7. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/nodes/parallel.py +20 -37
  8. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/pipeline.py +63 -15
  9. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/policy.py +20 -0
  10. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/session.py +35 -3
  11. stageflow_framework-0.14.0/stageflow/locale/ru/LC_MESSAGES/stageflow.mo +0 -0
  12. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/locale/ru/LC_MESSAGES/stageflow.po +17 -12
  13. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/locale/stageflow.pot +18 -13
  14. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0/stageflow_framework.egg-info}/PKG-INFO +1 -1
  15. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow_framework.egg-info/SOURCES.txt +3 -0
  16. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_budget_meters.py +14 -1
  17. stageflow_framework-0.14.0/tests/test_cycles.py +224 -0
  18. stageflow_framework-0.14.0/tests/test_fanout.py +148 -0
  19. stageflow_framework-0.14.0/tests/test_schema_errors.py +98 -0
  20. stageflow_framework-0.14.0/tests/test_snapshot.py +131 -0
  21. stageflow_framework-0.13.0/stageflow/locale/ru/LC_MESSAGES/stageflow.mo +0 -0
  22. stageflow_framework-0.13.0/tests/test_cycles.py +0 -105
  23. stageflow_framework-0.13.0/tests/test_snapshot.py +0 -45
  24. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/LICENSE +0 -0
  25. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/README.md +0 -0
  26. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/setup.cfg +0 -0
  27. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/__init__.py +0 -0
  28. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/builtins/__init__.py +0 -0
  29. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/builtins/_args.py +0 -0
  30. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/builtins/_base.py +0 -0
  31. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/builtins/dicts.py +0 -0
  32. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/builtins/lists.py +0 -0
  33. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/builtins/logic.py +0 -0
  34. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/builtins/strings.py +0 -0
  35. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/builtins/vars.py +0 -0
  36. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/__init__.py +0 -0
  37. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/cel.py +0 -0
  38. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/context.py +0 -0
  39. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/debug.py +0 -0
  40. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/event.py +0 -0
  41. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/inputs.py +0 -0
  42. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/nodes/__init__.py +0 -0
  43. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/nodes/base.py +0 -0
  44. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/nodes/bindings.py +0 -0
  45. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/nodes/branching.py +0 -0
  46. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/nodes/entry.py +0 -0
  47. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/nodes/recovery.py +0 -0
  48. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/nodes/stage.py +0 -0
  49. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/nodes/subpipeline.py +0 -0
  50. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/nodes/terminal.py +0 -0
  51. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/nodes/try_block.py +0 -0
  52. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/payload_schema.py +0 -0
  53. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/registry.py +0 -0
  54. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/spec.py +0 -0
  55. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/stage.py +0 -0
  56. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/core/typesys.py +0 -0
  57. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/docs/__init__.py +0 -0
  58. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/docs/schema.py +0 -0
  59. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/docs/schemas/pipeline.json +0 -0
  60. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/exceptions.py +0 -0
  61. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/i18n.py +0 -0
  62. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/py.typed +0 -0
  63. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow/testing.py +0 -0
  64. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow_framework.egg-info/dependency_links.txt +0 -0
  65. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow_framework.egg-info/requires.txt +0 -0
  66. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/stageflow_framework.egg-info/top_level.txt +0 -0
  67. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_budget.py +0 -0
  68. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_budget_spending.py +0 -0
  69. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_capabilities.py +0 -0
  70. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_core_flow.py +0 -0
  71. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_debug.py +0 -0
  72. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_docs_schema.py +0 -0
  73. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_entry_node.py +0 -0
  74. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_full_pipeline.py +0 -0
  75. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_i18n.py +0 -0
  76. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_map.py +0 -0
  77. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_packaging.py +0 -0
  78. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_parallel.py +0 -0
  79. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_payload_validation.py +0 -0
  80. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_pipeline_tester.py +0 -0
  81. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_policy.py +0 -0
  82. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_removed_local_scope.py +0 -0
  83. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_session_control.py +0 -0
  84. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_session_wait_input.py +0 -0
  85. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_std_stages.py +0 -0
  86. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_subpipeline.py +0 -0
  87. {stageflow_framework-0.13.0 → stageflow_framework-0.14.0}/tests/test_try_block.py +0 -0
  88. {stageflow_framework-0.13.0 → 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.0
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.0"
7
+ version = "0.14.0"
8
8
  description = "StageFlow: pipeline framework for stages"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -42,6 +42,9 @@ def capabilities(policy: Policy | None = None) -> dict[str, Any]:
42
42
  - `locales` — the languages the core can put its own text into, the source
43
43
  language first. A client cannot guess this: a catalog is a file in the
44
44
  build, so the build has to say.
45
+ - `cycles` — whether this caller may write a road that comes back to where
46
+ it has been (`Policy.allow_cycles`). Off unless a policy says otherwise,
47
+ including when there is no policy at all.
45
48
 
46
49
  With a `policy` the answer narrows to what that policy allows, which is
47
50
  what a backend should serve to a client: an editor needs to know what
@@ -64,4 +67,9 @@ def capabilities(policy: Policy | None = None) -> dict[str, Any]:
64
67
  "node_types": node_types,
65
68
  "stages": len(stages),
66
69
  "locales": available_locales(),
70
+ # whether a road may come back to where it has been. A client that
71
+ # draws graphs needs this before it offers one: a back edge is refused
72
+ # at validation, and finding that out after writing it is the worst
73
+ # moment to learn a rule
74
+ "cycles": bool(policy is not None and policy.allow_cycles),
67
75
  }
@@ -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,
@@ -1,7 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
- from jsonschema import ValidationError as _SchemaError
4
- from jsonschema import validate as _json_validate
3
+ from jsonschema import Draft202012Validator as _VALIDATOR
5
4
 
6
5
  from stageflow.docs.schema import load_pipeline_schema
7
6
 
@@ -16,6 +15,30 @@ from .policy import Policy
16
15
  from .typesys import TypeSystem
17
16
 
18
17
 
18
+ #: How many shape problems are worth listing before the list stops helping.
19
+ _MAX_SCHEMA_ERRORS = 10
20
+
21
+
22
+ def _located(data: dict, exc) -> str:
23
+ """One schema complaint with the place it belongs to in front of it.
24
+
25
+ The place is the node's `id` when the path runs through `nodes`, because an
26
+ index is something the author has to count and an id is something they
27
+ wrote. Anything else keeps the dotted path it came with.
28
+ """
29
+ path = list(exc.absolute_path)
30
+ where = ""
31
+ if len(path) >= 2 and path[0] == "nodes" and isinstance(path[1], int):
32
+ node = (data.get("nodes") or [])[path[1]] if path[1] < len(data.get("nodes") or []) else {}
33
+ named = node.get("id") if isinstance(node, dict) else None
34
+ rest = "".join(f"[{p}]" if isinstance(p, int) else f".{p}" for p in path[2:])
35
+ where = f"{named or f'nodes[{path[1]}]'}{rest}"
36
+ elif path:
37
+ where = "".join(f"[{p}]" if isinstance(p, int) else (f".{p}" if i else str(p))
38
+ for i, p in enumerate(path))
39
+ return f"{where}: {exc.message}" if where else exc.message
40
+
41
+
19
42
  class Pipeline:
20
43
  def __init__(
21
44
  self,
@@ -62,18 +85,36 @@ class Pipeline:
62
85
 
63
86
  @staticmethod
64
87
  def _check_schema(data: dict, schema: dict, sub_id: str | None = None) -> None:
65
- try:
66
- _json_validate(instance=data, schema=schema)
67
- except _SchemaError as exc:
68
- # a whole sentence per case rather than a noun filled into one —
69
- # the reason is in `registry.py`
70
- if sub_id is None:
71
- message = _("Pipeline schema validation failed: {reason}",
72
- reason=exc.message)
73
- else:
74
- message = _("Subpipeline '{name}' schema validation failed: {reason}",
75
- name=sub_id, reason=exc.message)
76
- raise PipelineDefinitionError(message) from exc
88
+ """Everything wrong with the SHAPE of a pipeline, at once and located.
89
+
90
+ Two things the first-error-only version could not do, and both of them
91
+ are what the author of a graph actually needs.
92
+
93
+ It says WHERE. `'next' is a required property` is a true sentence about
94
+ a graph with forty nodes and a useless one; `nodes[4].except[0]: 'next'
95
+ is a required property` names the thing to go and fix. The path is the
96
+ node's id where there is one, because that is what the author typed and
97
+ what the editor shows — an index means counting.
98
+
99
+ And it says everything, the way the cross-graph checks already do (see
100
+ `collect_errors`). A shape is usually wrong in the same way in several
101
+ places, and fixing them one round trip at a time is the difference
102
+ between a correction and a conversation.
103
+ """
104
+ found = sorted(_VALIDATOR(schema).iter_errors(data), key=lambda e: list(e.absolute_path))
105
+ if not found:
106
+ return
107
+ reason = "; ".join(_located(data, exc) for exc in found[:_MAX_SCHEMA_ERRORS])
108
+ if len(found) > _MAX_SCHEMA_ERRORS:
109
+ reason += _("; and {more} more", more=len(found) - _MAX_SCHEMA_ERRORS)
110
+ # a whole sentence per case rather than a noun filled into one —
111
+ # the reason is in `registry.py`
112
+ if sub_id is None:
113
+ message = _("Pipeline schema validation failed: {reason}", reason=reason)
114
+ else:
115
+ message = _("Subpipeline '{name}' schema validation failed: {reason}",
116
+ name=sub_id, reason=reason)
117
+ raise PipelineDefinitionError(message) from found[0]
77
118
 
78
119
  def has_node(self, node_id: str) -> bool:
79
120
  return node_id in self._nodes_map
@@ -152,7 +193,10 @@ class Pipeline:
152
193
  errors.append(_("Duplicate node id: '{node}'", node=node.id))
153
194
  seen.add(node.id)
154
195
  errors.extend(node.validate(self))
155
- errors.extend(self._cycle_errors())
196
+ # a road that comes back is refused unless the caller's policy says it
197
+ # has something to stop it with (see Policy.allow_cycles)
198
+ if policy is None or not policy.allow_cycles:
199
+ errors.extend(self._cycle_errors())
156
200
  return errors
157
201
 
158
202
  def _cycle_errors(self) -> list[str]:
@@ -164,6 +208,10 @@ class Pipeline:
164
208
  and it is almost always a `next` pointed at the wrong id. Saying so
165
209
  at validation costs one walk of the graph and saves finding out by
166
210
  watching a server fall over.
211
+
212
+ A host with something to stop one with — a budget, a timeout a layer
213
+ above — says so with `Policy(allow_cycles=True)`, and then this is not
214
+ called at all. See `collect_errors`.
167
215
  """
168
216
  colour: dict[str, int] = {} # 0 — on the current path, 1 — done with
169
217
  found: list[str] = []
@@ -35,6 +35,23 @@ class Policy:
35
35
 
36
36
  stages: frozenset[str] | None = None
37
37
  node_types: frozenset[str] | None = None
38
+ #: Whether a road may come back to where it has been.
39
+ #:
40
+ #: Off, and the only field here whose default is a restriction rather than
41
+ #: an absence of one. The reason is that a cycle in the order edges is not
42
+ #: a narrower version of something — it is a shape the language does not
43
+ #: otherwise have, and one nothing in the graph bounds. `map` loops over a
44
+ #: list and stops when the list does; a cycle stops when something outside
45
+ #: the graph stops it, and it is far more often a `next` pointed at the
46
+ #: wrong id than a loop somebody meant.
47
+ #:
48
+ #: Turning it on is a host saying "I have something that will stop this".
49
+ #: Usually that is `limits=Limits(counters={"steps": …})` — a run that
50
+ #: cannot be ended by its own graph is ended by its budget. It can also be
51
+ #: a timeout a layer above, which is why this does not refuse to be set
52
+ #: without a ceiling: a platform that already bounds its work should not
53
+ #: have to argue with a framework about it.
54
+ allow_cycles: bool = False
38
55
  #: how much a session under this policy may spend. A plan is one object:
39
56
  #: which blocks, and how many of anything. Built fresh rather than shared
40
57
  #: with every other default policy — one `Limits` handed round and then
@@ -47,6 +64,9 @@ class Policy:
47
64
 
48
65
  @property
49
66
  def unrestricted(self) -> bool:
67
+ """Nothing is narrowed. `allow_cycles` is not part of this: it widens
68
+ what may be written rather than narrowing it, and a policy that permits
69
+ a loop is not thereby an absence of a policy."""
50
70
  return (self.stages is None and self.node_types is None
51
71
  and self.limits.unlimited)
52
72