Coverage for core / src / sensorkit / sensor / lifecycle.py: 99%
303 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"""Author and compile lifecycle tables such as bring-up and shutdown.
4Tables contain phases of entries. Each entry selects placements and runs an
5ordered list of commands on each. Entries in one phase must select disjoint
6placements. Compilation emits planned steps for shared workflow graph compilation.
8A phase normally follows the preceding phase with completion dependencies.
9Explicit `after` lists change that order. `require` clauses can refine a wait
10on a followed phase by selecting operations on the same device or chain and
11requiring success or completion. Other inherited phase waits remain intact.
13`sequence` controls each command's dependency on the preceding command at its
14placement. `fail_fast` controls whether failure stops the whole run. Teardown
15that should keep going needs completion sequencing and non-fail-fast policy.
16"""
18from __future__ import annotations
20from collections.abc import Iterable, Mapping
21from dataclasses import replace
22from typing import Annotated, Literal
24from pydantic import BaseModel, BeforeValidator, model_validator
26from sensorkit.common.dag import GraphBuilder
27from sensorkit.core.device import DeviceCommand
28from sensorkit.sensor.binding import BoundSensor
29from sensorkit.sensor.selection import AnySelection
30from sensorkit.sensor.topology import Placement
31from sensorkit.sensor.workflow import (
32 CleanupPlan,
33 DeadlineRule,
34 Dependency,
35 ExecutableWorkflow,
36 OperatorRule,
37 Origin,
38 PlannedStep,
39 lower,
40)
43def _accept_str_command(v: object) -> object:
44 """Convert a bare command name to the tagged command model input."""
45 return {"command_id": v} if isinstance(v, str) else v
48class Join(BaseModel, frozen=True, extra="forbid"):
49 """A dependency on a named phase or entry, optionally narrowed by
50 placement.
52 `on` requires success or completion. `join` selects all target operations,
53 operations on the same device, or operations at the same path or above it
54 (`same-chain`). A bare string uses `all` and `success`.
55 """
57 name: str
58 join: Literal["all", "same-device", "same-chain"] = "all"
59 on: Literal["success", "completion"] = "success"
61 @model_validator(mode="before")
62 @classmethod
63 def _str_shorthand(cls, v: object) -> object:
64 if isinstance(v, str):
65 return {"name": v}
67 if not isinstance(v, Mapping) or True not in v:
68 return v
70 # Restore `on` after YAML 1.1 parses the key as boolean True.
71 return {("on" if key is True else key): value for key, value in v.items()}
74class OpSpec(BaseModel, frozen=True, extra="forbid"):
75 """A command and execution policy applied at each selected placement.
77 A bare command name is shorthand for a command using default arguments.
78 `sequence` requires success or completion of the preceding command at the
79 same placement. It has no effect on the first command.
81 `unsupported` chooses compilation error or omission. `optional` controls
82 whether an unsuccessful result fails the run. `fail_fast` controls whether
83 failure stops dispatch and inherits from the phase, then table, when unset.
84 `timeout_s` overrides configured deadlines. `None` inherits them.
85 """
87 command: Annotated[DeviceCommand, BeforeValidator(_accept_str_command)]
88 optional: bool = False
89 unsupported: Literal["error", "omit"] = "error"
90 fail_fast: bool | None = None
91 sequence: Literal["success", "completion"] = "success"
92 timeout_s: float | None = None
94 @model_validator(mode="before")
95 @classmethod
96 def _shorthand(cls, v: object) -> object:
97 return {"command": v} if isinstance(v, str | DeviceCommand) else v
99 @property
100 def op(self) -> str:
101 """Return the command identifier used by reports and rules."""
102 return self.command.model_tag()
104 def effective_fail_fast(self, phase: bool | None, table: bool) -> bool:
105 """Resolve failure policy from the operation, phase, then table."""
106 if self.fail_fast is not None:
107 return self.fail_fast
109 return table if phase is None else phase
112def _one_or_many(v: object) -> object:
113 """Accept one operation wherever a sequence of operations is expected."""
114 return [v] if isinstance(v, str | Mapping | OpSpec | DeviceCommand) else v
117def _accept_bare_require(v: object) -> object:
118 """Accept one dependency clause wherever a sequence is expected."""
119 return [v] if isinstance(v, str | Mapping | Join) else v
122class Entry(BaseModel, frozen=True, extra="forbid"):
123 """A selection of placements and the commands to run on each.
125 `select` is evaluated over all placements before `exclude` removes matches
126 from the result. Entries within a phase or cleanup must not overlap.
127 Commands run serially per placement. Different placements may run
128 concurrently.
130 `require` adds dependencies or refines inherited waits on named phases.
131 Each clause specifies its join and success or completion condition.
132 """
134 select: AnySelection
135 ops: Annotated[tuple[OpSpec, ...], BeforeValidator(_one_or_many)]
136 exclude: AnySelection | None = None
137 id: str | None = None
138 require: Annotated[
139 tuple[Join, ...],
140 BeforeValidator(
141 _accept_bare_require, json_schema_input_type=Join | str | tuple[Join | str, ...]
142 ),
143 ] = ()
145 @model_validator(mode="after")
146 def _declares_ops(self) -> Entry:
147 if not self.ops:
148 raise ValueError("entry declares no ops")
150 return self
152 def describe(self) -> str:
153 """Serialize the authored selection for diagnostic messages."""
154 return self.select.model_dump_json(by_alias=True)
156 def targets(self, sensor: BoundSensor) -> tuple[Placement, ...]:
157 """Return selected placements after exclusions, in topology order.
159 This query may return no placements; compilation rejects empty entries.
160 """
161 return tuple(
162 placement
163 for placement in self.select.matching(sensor.topology.placements(), sensor)
164 if self.exclude is None or not self.exclude.matches(placement, sensor)
165 )
168class Phase(BaseModel, frozen=True, extra="forbid"):
169 """A named group of entries with inherited completion dependencies.
171 `after=None` follows the preceding phase. An empty tuple follows none.
172 `after` names earlier phases. Entry requirements may narrow their inherited
173 waits. An unset `fail_fast` inherits the table default.
174 """
176 name: str
177 entries: tuple[Entry, ...]
178 after: tuple[str, ...] | None = None
179 fail_fast: bool | None = None
182class CleanupSpec(BaseModel, frozen=True, extra="forbid"):
183 """A separate cleanup graph selected after the main workflow drains.
185 Entries are ordered only by their own `require` clauses, which may
186 reference entries in this spec. Each spec has its own entry-id namespace.
188 `armed_by` names main-workflow entries. An attempted operation from any
189 named entry arms cleanup. `None` is unconditional. An empty tuple never
190 arms it. `when` selects by run outcome, with `cancelled` meaning a domain
191 abort. Hard cancellation skips cleanup. `timeout_s` bounds the graph.
193 Keep cleanup to stopping ongoing work; it cannot provide crash recovery.
194 """
196 name: str
197 entries: tuple[Entry, ...]
198 when: Literal["always", "failure", "cancelled", "failure_or_cancelled"] = "always"
199 timeout_s: float = 60.0
200 armed_by: tuple[str, ...] | None = None
203class LifecycleWorkflow(BaseModel, frozen=True, extra="forbid"):
204 """A named lifecycle table with phases, cleanup and a failure-policy
205 default.
207 `fail_fast` is required. True stops the run on failure. False allows other
208 work to continue subject to dependencies. Operations can override it.
209 Definition mappings supply `name` from the table's mapping key.
210 """
212 name: str
213 phases: tuple[Phase, ...]
214 fail_fast: bool
215 cleanup: tuple[CleanupSpec, ...] = ()
217 def follows(self, index: int) -> tuple[str, ...]:
218 """Return explicit predecessors, or the preceding phase when `after`
219 is unset.
220 """
221 after = self.phases[index].after
223 if after is not None:
224 return after
226 return (self.phases[index - 1].name,) if index else ()
228 def check(self) -> None:
229 """Check names, references and symbolic cycles without device facts.
231 Compilation additionally checks declaration order and selected
232 operations.
234 Raises:
235 ValueError: Names repeat, references are invalid, or dependencies
236 cycle. The error includes the table name.
237 """
238 try:
239 self._check()
240 except ValueError as e:
241 raise ValueError(f"table '{self.name}': {e}") from e
243 def _check(self) -> None:
244 """Validate phase, entry and cleanup namespaces and dependencies.
246 Raises:
247 ValueError: Names collide, references are invalid, or dependencies
248 cycle.
249 """
250 phases = [phase.name for phase in self.phases]
251 rows = [entry for phase in self.phases for entry in phase.entries]
252 ids = [entry.id for entry in rows if entry.id is not None]
254 _unique(phases, "a phase is named twice")
255 _unique([spec.name for spec in self.cleanup], "a cleanup is named twice")
256 _unique(ids, "an entry id is used twice")
257 _disjoint(phases, ids)
258 _acyclic(self._dependencies(set(phases) | set(ids), set(ids)))
260 for spec in self.cleanup:
261 _check_cleanup(spec, set(ids))
263 def _dependencies(
264 self, known: set[str], ids: set[str]
265 ) -> dict[tuple[str, str], set[tuple[str, str]]]:
266 """Build symbolic phase and entry dependencies, validating
267 references.
269 A phase depends on its entries so cycles through an entry include its
270 phase.
271 """
272 phases = {phase.name for phase in self.phases}
273 deps: dict[tuple[str, str], set[tuple[str, str]]] = {}
275 for index, phase in enumerate(self.phases):
276 follows = self.follows(index)
277 _resolves(follows, phases, f"phase '{phase.name}' after")
278 node = ("phase", phase.name)
279 deps[node] = set()
281 for position, entry in enumerate(phase.entries):
282 row = ("entry", entry.id or f"{phase.name}[{position}]")
283 deps[node].add(row)
284 deps[row] = {("phase", name) for name in follows} | _required(entry, known, ids)
286 return deps
289def compile_lifecycle(
290 workflow: LifecycleWorkflow,
291 sensor: BoundSensor,
292 *,
293 deadlines: tuple[DeadlineRule, ...] = (),
294 rules: tuple[OperatorRule, ...] = (),
295) -> ExecutableWorkflow:
296 """Compile a lifecycle table against a bound sensor without device
297 calls.
299 The result can be inspected before running.
301 Raises:
302 ValueError: References or declaration order are invalid, entries
303 overlap or select nothing, joins match no operations, a required
304 command is unsupported, or shared graph compilation rejects the workflow.
305 """
306 return TableCompiler(workflow, sensor, deadlines=deadlines, rules=rules).run()
309class TableCompiler:
310 """Single-use state for expanding a table into planned steps.
312 Phases may reference earlier phases; entries may also reference peers in
313 their own phase. Dependencies are accumulated separately, then attached to
314 frozen steps before shared graph compilation.
315 """
317 def __init__(
318 self,
319 table: LifecycleWorkflow,
320 sensor: BoundSensor,
321 *,
322 deadlines: tuple[DeadlineRule, ...] = (),
323 rules: tuple[OperatorRule, ...] = (),
324 ):
325 self.table = table
326 self.sensor = sensor
327 self.deadlines = deadlines
328 self.rules = rules
329 self.steps: list[PlannedStep] = []
330 self.deps: dict[str, list[Dependency]] = {}
331 self.where: dict[str, Placement] = {}
332 self.phase_steps: dict[str, list[str]] = {}
333 self.phase_after: dict[str, tuple[str, ...]] = {}
334 self.entry_steps: dict[str, list[str]] = {}
335 self.entry_phase: dict[str, str] = {}
336 self.emitted = 0
338 def run(self) -> ExecutableWorkflow:
339 """Expand phases and cleanup specs, then compile their planned steps."""
340 previous: str | None = None
342 for phase in self.table.phases:
343 self._compile_phase(phase, previous)
344 previous = phase.name
346 # Compile cleanup after all main-workflow trigger entries are indexed.
347 plans = tuple(self._cleanup(spec) for spec in self.table.cleanup)
349 return lower(
350 self.table.name,
351 self._settled(self.steps),
352 self.sensor,
353 cleanup=plans,
354 deadlines=self.deadlines,
355 rules=self.rules,
356 )
358 def _compile_phase(self, phase: Phase, previous: str | None) -> None:
359 """Emit a phase and attach inherited and explicit dependencies."""
360 where = f"phase '{phase.name}'"
361 after = self._declare_phase(phase, previous)
362 chosen = self._selected(phase.entries, where)
363 heads: list[tuple[Entry, Placement, str]] = []
365 for position, entry in enumerate(phase.entries):
366 emitted, entry_heads = self._emit_entry(
367 entry,
368 chosen[position],
369 self._soft_links(entry, after, where),
370 group=phase.name,
371 origin=(phase.name, entry.id or position),
372 stated=phase.fail_fast,
373 )
374 self.steps += emitted
375 heads += [(entry, placement, head) for placement, head in entry_heads]
376 names = [step.name for step in emitted]
377 self.phase_steps[phase.name] += names
379 if entry.id is not None:
380 self.entry_steps.setdefault(entry.id, []).extend(names)
382 self._resolve_requires(heads, where)
384 def _declare_phase(self, phase: Phase, previous: str | None) -> tuple[str, ...]:
385 """Register a phase and its entry ids before emitting operations.
387 Registering peer ids first allows requirements to reference later
388 entries in the same phase.
390 Raises:
391 ValueError: Names repeat or `after` references an undeclared phase.
392 """
393 if phase.name in self.phase_steps:
394 raise ValueError(f"duplicate phase name '{phase.name}'")
396 after = phase.after if phase.after is not None else (previous,) if previous else ()
397 unknown = [name for name in after if name not in self.phase_steps]
399 if unknown:
400 raise ValueError(
401 f"phase '{phase.name}': after names unknown or later phase(s) "
402 f"{unknown}; phases may only follow earlier ones"
403 )
405 self.phase_after[phase.name] = after
406 self.phase_steps[phase.name] = []
408 for entry in phase.entries:
409 if entry.id is None:
410 continue
412 if entry.id in self.entry_phase:
413 raise ValueError(f"duplicate entry id '{entry.id}'")
415 self.entry_phase[entry.id] = phase.name
417 return after
419 def _selected(self, entries: tuple[Entry, ...], where: str) -> list[tuple[Placement, ...]]:
420 """Select targets for a group and check that entries do not overlap.
422 Check selection before unsupported-command omission.
424 Raises:
425 ValueError: An entry selects nothing or entries share a placement.
426 """
427 chosen = [self._targets(entry, where) for entry in entries]
428 reached: dict[Placement, Entry] = {}
430 for entry, targets in zip(entries, chosen, strict=True):
431 for placement in targets:
432 held = reached.setdefault(placement, entry)
434 if held is not entry:
435 raise ValueError(
436 f"{where}: '{placement.device}' is reached by two "
437 f"entries, {held.describe()} and {entry.describe()}; "
438 f"narrow one with exclude"
439 )
441 return chosen
443 def _targets(self, entry: Entry, where: str) -> tuple[Placement, ...]:
444 """Return an entry's targets in topology order.
446 Raises:
447 ValueError: The entry selects no placement on this sensor.
448 """
449 targets = entry.targets(self.sensor)
451 if not targets:
452 raise ValueError(
453 f"{where}: entry selects no device on this sensor ({entry.describe()})"
454 )
456 return targets
458 def _soft_links(self, entry: Entry, after: tuple[str, ...], where: str) -> list[str]:
459 """Collect inherited phase waits that explicit requirements do not
460 replace.
462 A requirement on a followed phase, or one of its entries, replaces that
463 phase's blanket completion wait for this entry.
465 Raises:
466 ValueError: A requirement names an unknown or later phase or entry.
467 """
468 required = {self._declaring_phase(clause.name, where) for clause in entry.require}
469 shadowed = required & set(after)
471 return list(
472 dict.fromkeys(
473 name
474 for followed in after
475 if followed not in shadowed
476 for name in self._effective_steps(followed)
477 )
478 )
480 def _declaring_phase(self, target: str, where: str) -> str:
481 """Return a target phase or the phase declaring a target entry.
483 Raises:
484 ValueError: The target has not been declared.
485 """
486 if target in self.entry_phase:
487 return self.entry_phase[target]
489 if target in self.phase_after:
490 return target
492 raise ValueError(f"{where}: require names unknown or later phase/entry '{target}'")
494 def _effective_steps(self, phase: str) -> list[str]:
495 """Return a phase's steps, or recursively its predecessors when
496 empty.
497 """
498 names = self.phase_steps[phase]
500 if names:
501 return names
503 return list(
504 dict.fromkeys(
505 name
506 for followed in self.phase_after[phase]
507 for name in self._effective_steps(followed)
508 )
509 )
511 def _emit_entry(
512 self,
513 entry: Entry,
514 targets: tuple[Placement, ...],
515 soft: list[str],
516 *,
517 group: str,
518 origin: tuple[str | int, ...],
519 stated: bool | None,
520 ) -> tuple[list[PlannedStep], list[tuple[Placement, str]]]:
521 """Emit serial commands per placement and return each placement's
522 first step.
524 Entry requirements attach to the first step; subsequent steps inherit
525 the wait through their sequence dependencies.
526 """
527 steps: list[PlannedStep] = []
528 heads: list[tuple[Placement, str]] = []
530 for placement in targets:
531 previous: str | None = None
533 for index, spec in enumerate(entry.ops):
534 step = self._step(
535 spec, placement, group=group, origin=origin + (index,), stated=stated
536 )
537 self.deps[step.name] = (
538 list(Dependency.completion(soft))
539 if previous is None
540 else [Dependency(on=previous, kind=spec.sequence)]
541 )
543 if previous is None:
544 heads.append((placement, step.name))
546 previous = step.name
547 steps.append(step)
549 return steps, heads
551 def _step(
552 self,
553 spec: OpSpec,
554 placement: Placement,
555 *,
556 group: str,
557 origin: tuple[str | int, ...],
558 stated: bool | None,
559 ) -> PlannedStep:
560 """Build a planned command with a unique internal name and resolved
561 failure policy.
562 """
563 self.emitted += 1
564 step = PlannedStep(
565 name=f"{group}/{placement.device}/{self.emitted}",
566 origin=Origin(source=self.table.name, path=origin),
567 group=group,
568 target=placement,
569 command=spec.command,
570 optional=spec.optional,
571 fail_fast=spec.effective_fail_fast(stated, self.table.fail_fast),
572 unsupported=spec.unsupported,
573 timeout_s=spec.timeout_s,
574 )
575 self.where[step.name] = placement
577 return step
579 def _resolve_requires(self, heads: list[tuple[Entry, Placement, str]], where: str) -> None:
580 """Resolve entry requirements after emitting the whole phase,
581 including peers.
582 """
583 for entry, placement, head in heads:
584 for clause in entry.require:
585 named = (
586 self.entry_steps.get(clause.name, [])
587 if clause.name in self.entry_phase
588 else self._effective_steps(clause.name)
589 )
590 self._join(clause, named, placement, head, where)
592 def _join(
593 self, clause: Join, named: list[str], placement: Placement, head: str, where: str
594 ) -> None:
595 """Filter a requirement's target steps and attach dependencies to
596 the entry head.
598 Raises:
599 ValueError: The target has no steps or the join selects none.
600 """
601 if not named:
602 raise ValueError(f"{where}: require '{clause.name}' matches no step on this sensor")
604 narrowed = self._narrowed(clause, named, placement)
606 # An empty join would remove the inherited phase wait without replacing it.
607 if not narrowed:
608 raise ValueError(
609 f"{where}: require '{clause.name}' with join='{clause.join}' "
610 f"matches no step for '{placement.device}'"
611 )
613 self.deps[head] += [Dependency(on=name, kind=clause.on) for name in narrowed]
615 def _narrowed(self, clause: Join, named: list[str], placement: Placement) -> list[str]:
616 """Filter target steps by the clause's device or path relationship."""
617 match clause.join:
618 case "same-device":
619 return [name for name in named if self.where[name].device == placement.device]
620 case "same-chain":
621 return [
622 name
623 for name in named
624 if placement.path[: len(self.where[name].path)] == self.where[name].path
625 ]
627 return named
629 def _cleanup(self, spec: CleanupSpec) -> CleanupPlan:
630 """Compile a cleanup spec with internal dependencies and main-graph
631 triggers.
633 No phase-order waits apply inside cleanup.
635 Raises:
636 ValueError: Entry ids or references are invalid, entries overlap or
637 select nothing, or a trigger names no main-workflow entry.
638 """
639 where = f"cleanup '{spec.name}'"
640 declared = self._declare_cleanup(spec, where)
641 chosen = self._selected(spec.entries, where)
642 steps: list[PlannedStep] = []
643 heads: list[tuple[Entry, Placement, str]] = []
645 for position, entry in enumerate(spec.entries):
646 emitted, entry_heads = self._emit_entry(
647 entry,
648 chosen[position],
649 [],
650 group=spec.name,
651 origin=("cleanup", spec.name, entry.id or position),
652 stated=None,
653 )
654 steps += emitted
655 heads += [(entry, placement, head) for placement, head in entry_heads]
657 if entry.id is not None:
658 declared[entry.id] += [step.name for step in emitted]
660 for entry, placement, head in heads:
661 for clause in entry.require:
662 self._join(clause, declared[clause.name], placement, head, where)
664 return CleanupPlan(
665 steps=self._settled(steps),
666 origin=Origin(source=spec.name),
667 when=spec.when,
668 timeout_s=spec.timeout_s,
669 armed_by=self._arming(spec, where),
670 )
672 def _declare_cleanup(self, spec: CleanupSpec, where: str) -> dict[str, list[str]]:
673 """Register entry ids and validate requirements within one cleanup
674 spec.
676 Raises:
677 ValueError: Ids repeat or requirements reference entries outside
678 the spec.
679 """
680 declared: dict[str, list[str]] = {}
682 for entry in spec.entries:
683 if entry.id is None:
684 continue
686 if entry.id in declared:
687 raise ValueError(f"{where}: duplicate entry id '{entry.id}'")
689 declared[entry.id] = []
691 outside = sorted(
692 {clause.name for entry in spec.entries for clause in entry.require} - set(declared)
693 )
695 if outside:
696 raise ValueError(
697 f"{where}: require names entries outside it, "
698 f"{', '.join(outside)}; a cleanup is ordered against itself "
699 f"alone"
700 )
702 return declared
704 def _arming(self, spec: CleanupSpec, where: str) -> tuple[str, ...] | None:
705 """Expand main-workflow entry ids into cleanup trigger step names.
707 Preserve `None` as unconditional and an empty tuple as never armed.
709 Raises:
710 ValueError: A trigger names an entry absent from the main workflow.
711 """
712 if spec.armed_by is None:
713 return None
715 unknown = sorted(set(spec.armed_by) - set(self.entry_phase))
717 if unknown:
718 raise ValueError(
719 f"{where}: armed_by names entries no phase declares, {', '.join(unknown)}"
720 )
722 return tuple(name for entry in spec.armed_by for name in self.entry_steps[entry])
724 def _settled(self, steps: list[PlannedStep]) -> tuple[PlannedStep, ...]:
725 """Copy emitted steps with their accumulated dependencies attached."""
726 return tuple(replace(step, deps=tuple(self.deps[step.name])) for step in steps)
729def _unique(names: list[str], what: str) -> None:
730 """Reject repeated names in a namespace.
732 Raises:
733 ValueError: A name occurs more than once.
734 """
735 dupes = sorted({n for n in names if names.count(n) > 1})
737 if dupes:
738 raise ValueError(f"{what}: {', '.join(dupes)}")
741def _disjoint(phases: list[str], ids: list[str]) -> None:
742 """Require phase names and entry ids to occupy separate namespaces.
744 Raises:
745 ValueError: A phase and an entry share a name.
746 """
747 shared = sorted(set(phases) & set(ids))
749 if shared:
750 raise ValueError(f"a phase and an entry share a name: {', '.join(shared)}")
753def _resolves(names: Iterable[str], known: set[str], what: str) -> None:
754 """Check that each referenced name is declared.
756 Raises:
757 ValueError: A reference names no declaration.
758 """
759 unknown = sorted(n for n in names if n not in known)
761 if unknown:
762 raise ValueError(f"{what} names nothing: {', '.join(unknown)}")
765def _required(entry: Entry, known: set[str], ids: set[str]) -> set[tuple[str, str]]:
766 """Resolve requirement names to symbolic phase or entry nodes."""
767 named = [clause.name for clause in entry.require]
768 _resolves(named, known, "require")
770 return {("entry", name) if name in ids else ("phase", name) for name in named}
773def _check_cleanup(spec: CleanupSpec, armable: set[str]) -> None:
774 """Validate a cleanup's local references and main-workflow trigger ids.
776 Requirements stay inside the spec; only arming references main entries.
778 Raises:
779 ValueError: Ids repeat, references are invalid, or dependencies cycle.
780 """
781 ids = [entry.id for entry in spec.entries if entry.id is not None]
782 named = {clause.name for entry in spec.entries for clause in entry.require}
784 _unique(ids, f"cleanup '{spec.name}' uses an entry id twice")
785 _resolves(spec.armed_by or (), armable, f"cleanup '{spec.name}' armed_by")
787 outside = sorted(named - set(ids))
789 if outside:
790 raise ValueError(
791 f"cleanup '{spec.name}' require names entries outside it: {', '.join(outside)}"
792 )
794 deps: dict[tuple[str, str], set[tuple[str, str]]] = {}
796 for position, entry in enumerate(spec.entries):
797 row = ("entry", entry.id or f"{spec.name}[{position}]")
798 deps[row] = {("entry", clause.name) for clause in entry.require}
800 _acyclic(deps)
803def _acyclic(deps: dict[tuple[str, str], set[tuple[str, str]]]) -> None:
804 """Check symbolic dependencies with the DAG builder, without device
805 facts.
807 Raises:
808 ValueError: Dependencies contain a cycle.
809 """
810 builder = GraphBuilder()
811 ids = {
812 (kind, name): builder.add(f"{kind} '{name}'", kind, None) for kind, name in sorted(deps)
813 }
815 for node, following in deps.items():
816 builder.order(ids[node], (ids[f] for f in following))
818 builder.build()