Coverage for core / src / sensorkit / sensor / workflow.py: 99%
302 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"""Shared workflow models and graph compilation for lifecycle and collect compilers.
4Compilers emit named `PlannedStep` records with dependencies. `lower` checks
5capabilities, resolves deadlines and operator rules, and builds graphs for
6`sensorkit.common.dag`. Nodes carry an `Operation` or `None` for ordering only.
8Success dependencies become hard edges; completion dependencies become soft
9edges. Fail-fast failures stop the whole run, so a soft edge cannot guarantee
10subsequent work. Cleanup uses separate graphs run after the main graph drains.
12Unsupported steps marked `omit` produce no node. Their dependents inherit their
13dependencies, with success required only when both links require it. When
14several paths reach the same predecessor, any success requirement wins.
15Omissions are recorded separately from operator-imposed outcomes.
16"""
18from __future__ import annotations
20import itertools
21import math
22from collections import Counter
23from collections.abc import Iterable, Iterator, Mapping
24from dataclasses import dataclass
25from typing import Literal
27from pydantic import BaseModel, model_validator
29from sensorkit.common.dag import (
30 Graph,
31 GraphBuilder,
32 NodeOverride,
33 OnFailure,
34)
35from sensorkit.common.keyword import KeywordDict
36from sensorkit.core.device import DeviceCommand
37from sensorkit.sensor.binding import BoundSensor
38from sensorkit.sensor.selection import Selection
39from sensorkit.sensor.topology import Placement
42@dataclass(frozen=True)
43class Origin:
44 """Authored source, path and explanatory reason used in diagnostics and
45 labels.
46 """
48 source: str
49 path: tuple[str | int, ...] = ()
50 reason: str = ""
52 def __str__(self) -> str:
53 return "/".join(str(part) for part in (self.source, *self.path))
56@dataclass(frozen=True)
57class Acquisition:
58 """One frame's request identity, numbering and planned keywords.
60 `request` is the authored request label. `index` is the request ordinal,
61 continuing across segments and repeated for each instrument during fan-out.
62 `frame_number` is unique per instrument across the collect. The pair
63 (instrument, frame_number) identifies a frame.
65 Keywords travel with the acquisition through packing and compilation.
66 """
68 request: str
69 index: int
70 frame_number: int
71 keywords: KeywordDict
74@dataclass(frozen=True)
75class Dependency:
76 """A named predecessor and the condition required before a step may run.
78 `success` requires a successful result; `completion` waits for a terminal
79 result regardless of outcome. A run-wide stop can still prevent dispatch.
80 """
82 on: str
83 kind: Literal["success", "completion"] = "success"
85 @classmethod
86 def completion(cls, names: Iterable[str]) -> tuple[Dependency, ...]:
87 """Build completion dependencies for the supplied step names."""
88 return tuple(cls(on=name, kind="completion") for name in names)
91@dataclass(frozen=True)
92class PlannedStep:
93 """A compiler's command or ordering step before graph construction.
95 `name` is unique within the step list; dependencies may name later steps.
96 `command` and `target` must be set together or both absent. With neither,
97 the step becomes an ordering node; `delay_s` can provide an alignment
98 delay.
100 `timeout_s` overrides deadline rules. An unset value inherits those rules
101 and may remain unbounded if none match. Resolved numeric deadlines must be
102 finite and positive.
103 """
105 name: str
106 origin: Origin
107 group: str
108 target: Placement | None = None
109 command: DeviceCommand | None = None
110 deps: tuple[Dependency, ...] = ()
111 optional: bool = False
112 fail_fast: bool = True
113 unsupported: Literal["error", "omit"] = "error"
114 timeout_s: float | None = None
115 acquisition: Acquisition | None = None
116 delay_s: float = 0.0
118 @property
119 def label(self) -> str:
120 """Describe the command and target, or the origin of an ordering
121 step.
122 """
123 if self.command is None or self.target is None:
124 return self.origin.reason or self.name
126 return f"{format_command(self.command):<18} {self.target.device} @ {self.target.path_str}"
129@dataclass(frozen=True, eq=False)
130class Operation:
131 """A graph payload containing one command for one placement.
133 Operations compare and hash by object identity so execution and cleanup
134 can distinguish attempts with identical fields.
136 `timeout_s` is resolved; `None` means unbounded. An acquisition marks a
137 command that needs a header at dispatch.
138 """
140 target: Placement
141 command: DeviceCommand
142 origin: Origin
143 timeout_s: float | None = None
144 acquisition: Acquisition | None = None
146 @property
147 def id(self) -> str:
148 """Return the origin and target device label used in logs and audits."""
149 return f"{self.origin}@{self.target.device}"
151 @classmethod
152 def planned(cls, step: PlannedStep, timeout_s: float | None) -> Operation:
153 """Build an operation with a deep-copied command.
155 Copying detaches the caller's command; it does not make exposed nested
156 values immutable. Callers must not mutate compiled workflows.
158 Raises:
159 ValueError: The step has no command or target.
160 """
161 if step.command is None or step.target is None:
162 raise ValueError(
163 f"step '{step.name}' has no command, so there is no operation to build"
164 )
166 return cls(
167 target=step.target,
168 command=step.command.model_copy(deep=True),
169 origin=step.origin,
170 timeout_s=timeout_s,
171 acquisition=step.acquisition,
172 )
175@dataclass(frozen=True)
176class Omission:
177 """An unsupported step removed during graph compilation, with its origin and
178 reason.
179 """
181 origin: Origin
182 target: Placement
183 command: str
184 reason: str
187type DeadlineTarget = (
188 tuple[Literal["device"], str] | tuple[Literal["trait"], str] | tuple[Literal["any"], None]
189)
190"""A deadline target tagged as a device key, trait name or universal match."""
192_NAMESPACES = ("device", "trait", "any")
195class DeadlineRule(BaseModel, frozen=True, extra="forbid"):
196 """A time limit for one command, or every command, on a device, trait or
197 any target.
199 Author targets as `device: cam-1`, `trait: MustConnect` or `any: true`.
200 More specific rules take precedence during graph compilation. A rule without a
201 command is a default that yields to every rule naming the command.
202 """
204 target: DeadlineTarget
205 command: str | None = None
206 seconds: float
208 @model_validator(mode="before")
209 @classmethod
210 def _namespaced(cls, v: object) -> object:
211 if not isinstance(v, Mapping) or "target" in v:
212 return v
214 named = [k for k in _NAMESPACES if k in v]
216 if len(named) != 1:
217 raise ValueError(f"a deadline rule names exactly one of {', '.join(_NAMESPACES)}")
219 key = named[0]
220 rest = {k: v[k] for k in v if k not in _NAMESPACES}
222 return {**rest, "target": (key, None if key == "any" else v[key])}
225def _named_target(target: DeadlineTarget) -> str:
226 """Format a deadline target for a diagnostic message."""
227 kind, name = target
229 return kind if name is None else f"{kind} '{name}'"
232def resolve_deadline(
233 command: str,
234 target: Placement,
235 stated: tuple[DeadlineRule, ...],
236 explicit: float | None,
237 facts: BoundSensor,
238) -> float | None:
239 """Resolve an operation timeout from an explicit value or deadline rules.
241 An explicit value takes precedence. Rules naming the command precede
242 defaults. Within each group, device rules precede trait rules, which
243 precede universal rules.
245 Return `None` if neither an explicit value nor a matching rule exists.
246 Graph compilation validates the result and stores it on the operation.
248 Raises:
249 ValueError: Multiple rules match at the winning specificity.
250 """
251 if explicit is not None:
252 return explicit
254 named = tuple(r for r in stated if r.command == command)
255 every = tuple(r for r in stated if r.command is None)
256 traits = facts.traits(target)
258 for rules, rung in itertools.product((named, every), ("device", "trait", "any")):
259 if matched := _addressing(rules, rung, target, traits):
260 return _the_rule(matched, command, target).seconds
262 return None
265def _addressing(
266 rules: tuple[DeadlineRule, ...], rung: str, target: Placement, traits: frozenset[str]
267) -> tuple[DeadlineRule, ...]:
268 """Return rules at one specificity that match the placement."""
269 match rung:
270 case "device":
271 return tuple(r for r in rules if r.target == ("device", target.device))
272 case "trait":
273 return tuple(r for r in rules if r.target[0] == "trait" and r.target[1] in traits)
275 return tuple(r for r in rules if r.target[0] == "any")
278def _the_rule(matched: tuple[DeadlineRule, ...], command: str, target: Placement) -> DeadlineRule:
279 """Require exactly one matching rule at the winning specificity.
281 Raises:
282 ValueError: Multiple rules match the placement.
283 """
284 if len(matched) == 1:
285 return matched[0]
287 # Multiple traits may match; a device rule can disambiguate their deadlines.
288 named = ", ".join(sorted(_named_target(r.target) for r in matched))
290 raise ValueError(
291 f"'{command}' on '{target.device}' is given a deadline by {named}; "
292 f"nothing ranks them, so name the device instead"
293 )
296@dataclass(frozen=True)
297class OperatorRule:
298 """An explained override of selected operations' outcomes or failure
299 policy.
301 Set `select`, `commands`, or both; when both are set, both must match. An
302 `outcome` replaces dispatch with a recorded result and cannot be combined
303 with failure-policy changes. Capability omissions are recorded separately.
304 """
306 # Explain the operator decision in reports.
307 reason: str
309 select: Selection | None = None
310 commands: tuple[str, ...] = ()
312 outcome: Literal["ok", "skipped"] | None = None
313 fail_fast: bool | None = None
314 optional: bool | None = None
316 def __post_init__(self) -> None:
317 if self.select is None and not self.commands:
318 raise ValueError("an operator rule addresses nothing; set select or commands")
320 if (self.outcome, self.fail_fast, self.optional) == (None, None, None):
321 raise ValueError(
322 "an operator rule changes nothing; set outcome, fail_fast or optional"
323 )
325 if self.outcome is not None and not (self.fail_fast is None and self.optional is None):
326 raise ValueError(
327 "an operator rule sets an outcome and a failure policy; an "
328 "operation that will not be dispatched cannot fail"
329 )
331 def matches(self, step: PlannedStep, facts: BoundSensor) -> bool:
332 """Test the command and placement filters against a planned step.
334 Ordering steps never match. Placement selection covers all commands on
335 that placement unless the rule also limits command identifiers.
336 """
337 if step.command is None or step.target is None:
338 return False
340 if self.select is not None and not self.select.matches(step.target, facts):
341 return False
343 return not self.commands or step.command.model_tag() in self.commands
346@dataclass(frozen=True)
347class Cleanup:
348 """A separate graph eligible to run after the main graph drains.
350 `when` selects by run outcome. Domain aborts select `cancelled` cleanup;
351 hard cancellation skips all cleanup, including `always`.
353 `armed_by` identifies triggers by operation identity. `None` is always
354 armed. An empty tuple is never armed. A nonempty tuple is armed when any
355 trigger is attempted, even if it fails, since hardware may have started
356 moving.
358 `timeout_s` bounds the whole graph independently of per-operation
359 deadlines. Cleanup is not durable crash recovery; keep it to stopping
360 ongoing work and leave recovery to the agent.
361 """
363 graph: Graph
364 when: Literal["always", "failure", "cancelled", "failure_or_cancelled"]
365 timeout_s: float
366 origin: Origin
367 armed_by: tuple[Operation, ...] | None = None
369 def selected(self, failed: bool, aborted: bool) -> bool:
370 """Test whether the run outcome satisfies `when`.
372 `failure_or_cancelled` selects on either required failure or domain
373 abort, but still represents one cleanup graph.
374 """
375 match self.when:
376 case "always":
377 return True
378 case "failure":
379 return failed
380 case "cancelled":
381 return aborted
382 case "failure_or_cancelled":
383 return failed or aborted
385 def armed(self, attempted: set[Operation]) -> bool:
386 """Test whether cleanup is unconditional or one of its triggers was
387 attempted.
388 """
389 if self.armed_by is None:
390 return True
392 return any(operation in attempted for operation in self.armed_by)
395@dataclass(frozen=True)
396class CleanupPlan:
397 """Planned cleanup steps with outcome, timeout and arming conditions.
399 `armed_by` names main-workflow steps until graph compilation resolves operations.
400 `None` is always armed; an empty tuple is never armed. Omitted triggers do
401 not arm cleanup, and omitting every trigger preserves the empty tuple. The
402 whole-graph timeout must be finite and positive, even for an empty graph.
403 """
405 steps: tuple[PlannedStep, ...]
406 origin: Origin
407 when: Literal["always", "failure", "cancelled", "failure_or_cancelled"] = "always"
408 timeout_s: float = 60.0
409 armed_by: tuple[str, ...] | None = None
412@dataclass(frozen=True, eq=False)
413class ExecutableWorkflow:
414 """A compiled graph with cleanup graphs and omissions.
416 Preparation is ordinary work in the main graph. Cleanup runs separately
417 after it drains.
419 Workflows compare by object identity so sessions can track which they
420 issued. Callers must not mutate their graphs, commands or nested metadata.
421 """
423 name: str
424 graph: Graph
425 cleanup: tuple[Cleanup, ...] = ()
426 omissions: tuple[Omission, ...] = ()
429def lower(
430 name: str,
431 steps: tuple[PlannedStep, ...],
432 facts: BoundSensor,
433 *,
434 cleanup: tuple[CleanupPlan, ...] = (),
435 deadlines: tuple[DeadlineRule, ...] = (),
436 rules: tuple[OperatorRule, ...] = (),
437) -> ExecutableWorkflow:
438 """Build executable main and cleanup graphs from planned steps.
440 Both compilers use this pass for capability omission, deadline resolution,
441 operator rules and failure policy. It contacts no devices.
443 Raises:
444 ValueError: Step names or dependencies are invalid, a required command
445 is unsupported, deadlines are invalid, operation labels repeat,
446 cleanup triggers are outside the main graph, or a graph is cyclic.
447 """
448 graph, operations, omissions = _compile(steps, facts, deadlines, rules)
449 plans: list[Cleanup] = []
450 refused = list(omissions)
452 for plan in cleanup:
453 teardown, _, unbuilt = _compile(plan.steps, facts, deadlines, rules)
454 refused += unbuilt
455 plans.append(
456 Cleanup(
457 graph=teardown,
458 when=plan.when,
459 timeout_s=plan.timeout_s,
460 origin=plan.origin,
461 armed_by=_arming(plan, steps, operations),
462 )
463 )
465 workflow = ExecutableWorkflow(
466 name=name,
467 graph=graph,
468 cleanup=tuple(plans),
469 omissions=tuple(refused),
470 )
472 _validated(workflow)
474 return workflow
477def _compile(
478 steps: tuple[PlannedStep, ...],
479 facts: BoundSensor,
480 deadlines: tuple[DeadlineRule, ...],
481 rules: tuple[OperatorRule, ...],
482) -> tuple[Graph, dict[str, Operation], tuple[Omission, ...]]:
483 """Compile one step list into a graph, operation index and omission
484 records.
485 """
486 by_name = _checked(steps)
487 omitted, omissions = _fates(steps, facts)
488 resolved = _resolved(by_name, omitted)
490 builder = GraphBuilder()
491 nodes: dict[str, int] = {}
492 operations: dict[str, Operation] = {}
494 for step in steps:
495 if step.name in omitted:
496 continue
498 payload = None
500 if step.command is not None and step.target is not None:
501 payload = Operation.planned(
502 step,
503 resolve_deadline(
504 step.command.model_tag(), step.target, deadlines, step.timeout_s, facts
505 ),
506 )
507 operations[step.name] = payload
509 on_failure, optional, override = _effects(step, rules, facts)
510 nodes[step.name] = builder.add(
511 step.label,
512 step.group,
513 payload,
514 on_failure=on_failure,
515 optional=optional,
516 delay_s=step.delay_s,
517 override=override,
518 )
520 # Add edges after allocating all node ids to support forward references.
521 for named, nid in nodes.items():
522 builder.require(nid, (nodes[d.on] for d in resolved[named] if d.kind == "success"))
523 builder.order(nid, (nodes[d.on] for d in resolved[named] if d.kind == "completion"))
525 return builder.build(), operations, tuple(omissions)
528def _checked(steps: tuple[PlannedStep, ...]) -> dict[str, PlannedStep]:
529 """Index steps after checking names, command-target pairs and
530 dependencies.
532 Raises:
533 ValueError: Names repeat, only one of command and target is set, or a
534 dependency names an absent step.
535 """
536 by_name: dict[str, PlannedStep] = {}
538 for step in steps:
539 if step.name in by_name:
540 raise ValueError(f"two steps are named '{step.name}'")
542 if (step.command is None) != (step.target is None):
543 missing = "target" if step.target is None else "command"
544 raise ValueError(
545 f"step '{step.name}' has no {missing}; a command and the "
546 f"placement receiving it are set together or not at all"
547 )
549 by_name[step.name] = step
551 dangling = sorted({d.on for step in steps for d in step.deps} - set(by_name))
553 if dangling:
554 raise ValueError(f"steps depend on names nothing emitted: {', '.join(dangling)}")
556 return by_name
559def _fates(
560 steps: tuple[PlannedStep, ...], facts: BoundSensor
561) -> tuple[frozenset[str], list[Omission]]:
562 """Find unsupported steps to omit and record their reasons.
564 Ordering steps are always retained.
566 Raises:
567 ValueError: An unsupported command has `unsupported="error"`.
568 """
569 omitted: list[str] = []
570 omissions: list[Omission] = []
572 for step in steps:
573 if step.command is None or step.target is None:
574 continue
576 named = step.command.model_tag()
578 if named in facts.supported_commands(step.target.device):
579 continue
581 reason = f"'{step.target.device}' does not support '{named}'"
583 if step.unsupported == "error":
584 raise ValueError(f"step '{step.name}': {reason}")
586 omitted.append(step.name)
587 omissions.append(
588 Omission(origin=step.origin, target=step.target, command=named, reason=reason)
589 )
591 return frozenset(omitted), omissions
594def _resolved(
595 by_name: dict[str, PlannedStep], omitted: frozenset[str]
596) -> dict[str, tuple[Dependency, ...]]:
597 """Resolve each step's dependencies through omitted predecessors."""
598 resolved: dict[str, tuple[Dependency, ...]] = {}
600 for name in by_name:
601 _resolve(name, by_name, omitted, resolved, frozenset())
603 return resolved
606def _resolve(
607 name: str,
608 by_name: dict[str, PlannedStep],
609 omitted: frozenset[str],
610 resolved: dict[str, tuple[Dependency, ...]],
611 seen: frozenset[str],
612) -> tuple[Dependency, ...]:
613 """Replace omitted predecessors with their dependencies recursively.
615 Inherited dependencies require success only if every link requires it. An
616 omitted predecessor with no dependencies adds no constraint.
618 Raises:
619 ValueError: Dependency traversal encounters a cycle through omissions.
620 """
621 if name in resolved:
622 return resolved[name]
624 if name in seen:
625 raise ValueError(f"omitted steps depend on each other, through '{name}'")
627 here: list[Dependency] = []
629 for dep in by_name[name].deps:
630 if dep.on in omitted:
631 here += [
632 Dependency(
633 on=inherited.on,
634 kind="success" if dep.kind == inherited.kind == "success" else "completion",
635 )
636 for inherited in _resolve(dep.on, by_name, omitted, resolved, seen | {name})
637 ]
638 else:
639 here.append(dep)
641 resolved[name] = _merged(here)
643 return resolved[name]
646def _merged(deps: list[Dependency]) -> tuple[Dependency, ...]:
647 """Merge duplicate predecessors in first-seen order, retaining success
648 requirements.
649 """
650 kinds: dict[str, Literal["success", "completion"]] = {}
652 for dep in deps:
653 if kinds.get(dep.on) != "success":
654 kinds[dep.on] = dep.kind
656 return tuple(Dependency(on=name, kind=kind) for name, kind in kinds.items())
659def _effects(
660 step: PlannedStep, rules: tuple[OperatorRule, ...], facts: BoundSensor
661) -> tuple[OnFailure, bool, NodeOverride | None]:
662 """Resolve node failure policy and the first matching operator rule.
664 Fail-fast maps to `stop`; otherwise failures map to `skip`. Order operator
665 rules by precedence, since only the first match applies.
666 """
667 on_failure: OnFailure = "stop" if step.fail_fast else "skip"
668 rule = next((r for r in rules if r.matches(step, facts)), None)
670 if rule is None:
671 return on_failure, step.optional, None
673 if rule.fail_fast is not None:
674 on_failure = "stop" if rule.fail_fast else "skip"
676 return (
677 on_failure,
678 step.optional if rule.optional is None else rule.optional,
679 NodeOverride(rule.outcome, rule.reason) if rule.outcome is not None else None,
680 )
683def _arming(
684 plan: CleanupPlan, steps: tuple[PlannedStep, ...], operations: Mapping[str, Operation]
685) -> tuple[Operation, ...] | None:
686 """Resolve named cleanup triggers to emitted main-workflow operations.
688 Omitted and ordering steps contribute no trigger. Cleanup with an empty
689 result is never armed.
691 Raises:
692 ValueError: A trigger names a step outside the main workflow.
693 """
694 if plan.armed_by is None:
695 return None
697 unknown = sorted(set(plan.armed_by) - {s.name for s in steps})
699 if unknown:
700 raise ValueError(
701 f"cleanup '{plan.origin.source}' arms on steps the run does not "
702 f"hold: {', '.join(unknown)}"
703 )
705 return tuple(operations[name] for name in plan.armed_by if name in operations)
708def _validated(workflow: ExecutableWorkflow) -> None:
709 """Check operation labels, deadlines and cleanup trigger membership.
711 Graph construction already checks cycles. Ordering nodes have no operation.
713 Raises:
714 ValueError: Operation labels repeat, a numeric deadline is invalid, or
715 cleanup references an operation outside the main graph.
716 """
717 operations = tuple(_operations(workflow.graph))
718 counted = Counter(op.id for op in operations)
719 dupes = sorted(i for i, n in counted.items() if n > 1)
721 if dupes:
722 raise ValueError(f"operations share an id: {', '.join(dupes)}")
724 _deadlines_within(operations, "the run")
725 held = set(operations)
727 for plan in workflow.cleanup:
728 _bounded(plan)
729 _armed_within(plan, held)
732def _usable(seconds: float) -> bool:
733 """Test whether a timeout is finite and positive."""
734 return math.isfinite(seconds) and seconds > 0
737def _deadlines_within(operations: Iterable[Operation], graph: str) -> None:
738 """Validate numeric operation deadlines, allowing `None` for unbounded
739 work.
741 Raises:
742 ValueError: A numeric deadline is not finite and positive.
743 """
744 for operation in operations:
745 if operation.timeout_s is not None and not _usable(operation.timeout_s):
746 raise ValueError(
747 f"operation '{operation.id}' in {graph} resolved to a deadline "
748 f"of {operation.timeout_s} seconds"
749 )
752def _bounded(plan: Cleanup) -> None:
753 """Validate a cleanup graph's timeout and its operation deadlines
754 separately.
756 Raises:
757 ValueError: The total timeout or a numeric operation deadline is
758 invalid.
759 """
760 named = f"cleanup '{plan.origin.source}'"
762 if not _usable(plan.timeout_s):
763 raise ValueError(f"{named} has a total deadline of {plan.timeout_s} seconds")
765 _deadlines_within(_operations(plan.graph), named)
768def _armed_within(plan: Cleanup, held: set[Operation]) -> None:
769 """Check that cleanup triggers belong to the main graph.
771 Raises:
772 ValueError: A trigger operation is outside the graph.
773 """
774 outside = [op.id for op in plan.armed_by or () if op not in held]
776 if outside:
777 raise ValueError(
778 f"cleanup '{plan.origin.source}' arms on operations the run does "
779 f"not hold: {', '.join(outside)}"
780 )
783def _operations(graph: Graph) -> Iterator[Operation]:
784 """Yield operation payloads, skipping ordering nodes."""
785 for node in graph.nodes:
786 if isinstance(node.payload, Operation):
787 yield node.payload
790def format_command(command: DeviceCommand) -> str:
791 """Format a command name and its nondefault arguments for logs and
792 audits.
794 Serialize nested models as values and exclude the command discriminator.
795 """
796 args = ", ".join(
797 f"{k}={v!r}"
798 for k, v in command.model_dump(
799 mode="json", exclude={"command_id"}, exclude_defaults=True
800 ).items()
801 )
803 return f"{command.model_tag()}({args})" if args else command.model_tag()