Coverage for core / src / sensorkit / sensor / execution.py: 98%
142 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
1# SPDX-License-Identifier: Apache-2.0
2"""Run workflow graphs, own cleanup and report aggregate outcomes.
4`DagRunner` schedules nodes. This executor supplies dispatch, interruption
5recording and cleanup sequencing. Eligible, armed cleanup runs after the main
6graph drains, including after a fail-fast failure.
8The caller classifies each cancellation as domain abort or hard cancellation.
9Domain abort returns an aborted report unless the main run already failed. Hard
10cancellation drains in-flight work, skips further cleanup and propagates. A
11later hard cancellation still takes precedence over an earlier domain abort.
13Cleanup graphs run sequentially under individual timeouts. Cancelling cleanup
14stops the sequence and drains current work; cleanup has no further cleanup. A
15timed-out graph fails, but subsequent eligible graphs may still run.
16`ExecutionState` retains attempts, node results and Abort outcomes even when
17hard cancellation propagates. These records do not prove hardware state or
18downstream data durability.
19"""
21from __future__ import annotations
23import asyncio
24from collections.abc import Callable, Mapping
25from dataclasses import dataclass, field
26from typing import Literal
28import sensorkit.api as sk
29from sensorkit.common.aio import AsyncObserver
30from sensorkit.common.dag import (
31 DagRunner,
32 Dispatch,
33 Node,
34 NodeResult,
35 RunReport,
36 log_summary,
37)
38from sensorkit.core.device import DeviceClient
39from sensorkit.sensor.binding import BoundSensor
40from sensorkit.sensor.dispatch import (
41 DeviceContexts,
42 Dispatcher,
43 InstrumentContexts,
44 Interruption,
45 InterruptionRecorder,
46 OperationEvent,
47)
48from sensorkit.sensor.workflow import (
49 Cleanup,
50 ExecutableWorkflow,
51 Operation,
52)
54type WorkflowOutcome = Literal["completed", "aborted"]
55"""Outcome of a returned report; hard cancellation propagates instead."""
57type AbortPredicate = Callable[[BaseException], bool]
58"""Caller predicate distinguishing a domain abort from hard cancellation.
60True recognizes a cancellation as a domain abort; false or no predicate causes hard
61cancellation. Classify each arrival separately until one is declined. The
62caller supplies intent because both arrive as `CancelledError`.
63"""
66@dataclass(frozen=True)
67class CleanupReport:
68 """One cleanup graph's results and whether its total timeout expired.
70 Timeout marks failure even if no node reports an error. Cancellation or
71 timeout marks the underlying run aborted.
72 """
74 cleanup: Cleanup
75 run: RunReport
76 expired: bool = False
78 @property
79 def failed(self) -> bool:
80 """Test for total timeout expiry or required node failures."""
81 return self.expired or bool(self.run.failures)
84@dataclass
85class ExecutionState:
86 """Caller-owned, single-use records of one execution.
88 Attempts are recorded when dispatch begins. Overrides and cancelled
89 delays send no command and do not count as attempts. Cleanup triggers use
90 operation identity.
92 `run` and `cleanup` hold node results; `interruptions` separately holds
93 Abort outcomes. Keep this state to inspect partial results after hard
94 cancellation. Reuse is rejected even if the first execution recorded no
95 attempts.
96 """
98 attempted: set[Operation] = field(default_factory=set)
99 interruptions: dict[Operation, Interruption] = field(default_factory=dict)
100 run: RunReport | None = None
101 cleanup: list[CleanupReport] = field(default_factory=list)
102 _used: bool = field(default=False, init=False, repr=False)
104 def begin(self, workflow: ExecutableWorkflow) -> dict[int, NodeResult]:
105 """Reserve this state and seed the main report with the runner's
106 result mapping.
108 Returns:
109 The mutable mapping where the runner records node results.
111 Raises:
112 ValueError: This state was already used; existing records are
113 unchanged.
114 """
115 if self._used:
116 raise ValueError(
117 f"{workflow.name}: an ExecutionState records one run, and this one already has"
118 )
120 self._used = True
121 self.run = RunReport(workflow.name, workflow.graph, {})
123 return self.run.results
125 def interrupted(self, operation: Operation) -> InterruptionRecorder:
126 """Return a callback that stores this operation's Abort outcome."""
128 def record(interruption: Interruption) -> None:
129 self.interruptions[operation] = interruption
131 return record
134@dataclass(frozen=True)
135class WorkflowReport:
136 """Main-run results, cleanup results, attempts and interruption
137 outcomes.
139 Cleanup reports retain execution order. `reason` records the first recognized
140 cancellation for an aborted workflow, otherwise `None`.
141 """
143 name: str
144 run: RunReport
145 cleanup: tuple[CleanupReport, ...] = ()
146 attempted: frozenset[Operation] = frozenset()
147 interruptions: Mapping[Operation, Interruption] = field(default_factory=dict)
148 outcome: WorkflowOutcome = "completed"
149 reason: str | None = None
152class WorkflowError(Exception):
153 """A required workflow or cleanup failure, with the complete workflow
154 report.
156 Main-run failures are reported before cleanup failures.
157 """
159 def __init__(self, message: str, report: WorkflowReport):
160 super().__init__(message)
161 self.report = report
163 @classmethod
164 def from_report(cls, report: WorkflowReport) -> WorkflowError:
165 """Build an error describing main and cleanup causes, including
166 required skipped work.
167 """
168 sections = []
170 if report.run.failures:
171 sections.append(f"in the run, {'; '.join(_causes(report.run))}")
173 for done in report.cleanup:
174 if done.failed:
175 expiry = (
176 f"exceeded its {done.cleanup.timeout_s}s deadline" if done.expired else None
177 )
178 causes = [*([expiry] if expiry else []), *_causes(done.run)]
179 sections.append(f"in cleanup '{done.cleanup.origin}', {'; '.join(causes)}")
181 return cls(f"{report.name}: {'. '.join(sections)}", report)
184class WorkflowExecutor:
185 """Run lifecycle or collect workflows against a bound sensor's clients.
187 Each execution uses a separate state and dispatcher. The observer spans
188 runs. Direct execution permits concurrent runs. `Sensor` permits one run
189 at a time and checks that it issued the workflow.
190 """
192 def __init__(
193 self,
194 sensor: BoundSensor,
195 clients: Mapping[str, DeviceClient],
196 *,
197 events: AsyncObserver[OperationEvent] | None = None,
198 ):
199 self.sensor = sensor
200 self.clients = clients
201 self.events = events
203 async def execute(
204 self,
205 workflow: ExecutableWorkflow,
206 *,
207 contexts: DeviceContexts | None = None,
208 instrument_contexts: InstrumentContexts | None = None,
209 base: sk.Context | None = None,
210 in_domain: AbortPredicate | None = None,
211 state: ExecutionState | None = None,
212 ) -> WorkflowReport:
213 """Run a compiled workflow, drain calls and attempt eligible
214 cleanup.
216 Args:
217 workflow: Compiled main and cleanup graphs.
218 contexts: Current device contexts, sampled for each acquisition.
219 instrument_contexts: Resolve controller keywords for each capture target.
220 base: Context shared by every acquisition in this run.
221 in_domain: Predicate recognizing cancellations as domain aborts. False
222 or no predicate means hard cancellation.
223 state: Fresh caller-owned state for inspecting results after
224 cancellation.
226 Returns:
227 An aggregate report, marked aborted for a recognized domain
228 cancellation.
230 Raises:
231 ValueError: The supplied state was already used; dispatch has not
232 begun.
233 WorkflowError: Required main work failed or did not run, or
234 required cleanup failed without a domain abort.
235 asyncio.CancelledError: A cancellation was declined, after draining
236 in-flight work and without starting further cleanup.
237 """
238 state = ExecutionState() if state is None else state
240 # Reserve state before yielding so concurrent reuse cannot pass.
241 results = state.begin(workflow)
242 dispatcher = Dispatcher(
243 self.sensor,
244 self.clients,
245 contexts=contexts,
246 instrument_contexts=instrument_contexts,
247 base=base,
248 events=self.events,
249 )
250 runner = DagRunner(_dispatching(dispatcher, state))
251 reasons: list[str] = []
253 def claimed(cancellation: BaseException) -> bool:
254 if in_domain is None or not in_domain(cancellation):
255 return False
257 reasons.append(str(cancellation) or "cancelled")
258 return True
260 state.run = await runner.execute(
261 workflow.graph, name=workflow.name, absorbed=claimed, results=results
262 )
263 log_summary(state.run)
265 ended = await _cleaned_up(workflow.cleanup, state.run, state, runner, claimed)
266 aborted = state.run.aborted or ended
267 report = WorkflowReport(
268 name=workflow.name,
269 run=state.run,
270 cleanup=tuple(state.cleanup),
271 attempted=frozenset(state.attempted),
272 interruptions=dict(state.interruptions),
273 outcome="aborted" if aborted else "completed",
274 reason=reasons[0] if aborted and reasons else None,
275 )
277 # Domain abort preserves established main failures but returns cleanup outcomes.
278 if state.run.failures or (not aborted and any(c.failed for c in report.cleanup)):
279 raise WorkflowError.from_report(report)
281 return report
284def _dispatching(dispatcher: Dispatcher, state: ExecutionState) -> Dispatch:
285 """Build node dispatch that records operations and resolves ordering
286 nodes locally.
287 """
289 async def dispatch(node: Node) -> object:
290 match node.payload:
291 case Operation() as operation:
292 return await dispatcher.perform(
293 operation, node, state.attempted.add, state.interrupted(operation)
294 )
295 case _:
296 return None
298 return dispatch
301async def _cleaned_up(
302 cleanups: tuple[Cleanup, ...],
303 run: RunReport,
304 state: ExecutionState,
305 runner: DagRunner,
306 claimed: Callable[[BaseException], bool],
307) -> bool:
308 """Run eligible, armed cleanup graphs sequentially until cancellation.
310 Select by the drained main run's outcome and recorded attempts.
312 Returns:
313 Whether caller cancellation ended the sequence as a domain abort.
315 Raises:
316 asyncio.CancelledError: A declined cancellation, after storing the
317 current cleanup report and draining its graph.
318 """
319 failed = bool(run.failures)
321 for cleanup in cleanups:
322 if not (cleanup.selected(failed, run.aborted) and cleanup.armed(state.attempted)):
323 continue
325 done, cancelled, declined = await _bounded(cleanup, runner, claimed)
326 state.cleanup.append(done)
327 log_summary(done.run)
329 if declined is not None:
330 raise declined
332 if cancelled:
333 return True
335 return False
338async def _bounded(
339 cleanup: Cleanup, runner: DagRunner, claimed: Callable[[BaseException], bool]
340) -> tuple[CleanupReport, bool, asyncio.CancelledError | None]:
341 """Own one cleanup task through timeout, cancellation and final drain.
343 Classify caller cancellations until one is declined. Forward cancellations
344 and timeout expiry to the runner, which absorbs them and drains its nodes.
345 After cancellation, wait for interruption handling without a separate
346 bound.
348 Returns:
349 Cleanup report, whether caller cancellation arrived, and the first
350 declined cancellation, if any.
351 """
352 name = str(cleanup.origin)
353 results: dict[int, NodeResult] = {}
354 running = asyncio.create_task(
355 runner.execute(cleanup.graph, name=name, absorbed=lambda _: True, results=results)
356 )
357 loop = asyncio.get_running_loop()
358 expiry = loop.time() + cleanup.timeout_s
359 expired = cancelled = False
360 declined: asyncio.CancelledError | None = None
362 while not running.done():
363 bounded = not (expired or cancelled)
365 try:
366 await asyncio.wait({running}, timeout=expiry - loop.time() if bounded else None)
367 except asyncio.CancelledError as e:
368 cancelled = True
370 if declined is None and not claimed(e):
371 declined = e
373 running.cancel()
374 continue
376 if bounded and not running.done():
377 expired = True
378 running.cancel()
380 # Synthesize a report if cancellation prevented the graph task from starting.
381 run = (
382 RunReport(name, cleanup.graph, results, aborted=True)
383 if running.cancelled()
384 else running.result()
385 )
387 return CleanupReport(cleanup, run, expired), cancelled, declined
390def _causes(report: RunReport) -> list[str]:
391 """Describe up to three root causes and count required nodes that never
392 ran.
393 """
394 causes = report.causes
395 missing = len(report.failures) - sum(not n.optional for n, _ in causes)
396 parts = [f"{n.label.strip()} ({e})" for n, e in causes[:3]]
398 if len(causes) > 3:
399 parts.append(f"and {len(causes) - 3} more")
401 if missing:
402 parts.append(f"{missing} required operation(s) did not run")
404 return parts