Coverage for core / src / sensorkit / sensor / audit.py: 98%
312 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"""Explain sensor definitions and compiled workflows without contacting
3hardware.
5Definition audits check structure and references. They render selections
6symbolically and defer capability-dependent checks to binding or compilation.
7Workflow audits describe stored nodes, edges, deadlines, overrides, omissions
8and cleanup conditions.
10Audits read their inputs without modifying them. Compiled workflows are
11rendered as supplied rather than revalidated.
12"""
14from __future__ import annotations
16import json
17from collections.abc import Iterable, Iterator
18from dataclasses import dataclass
19from enum import StrEnum
20from typing import Literal
22from pydantic_core import to_jsonable_python
24from sensorkit.common.dag import Graph, Node, OnFailure
25from sensorkit.sensor.definition import SensorDefinition
26from sensorkit.sensor.lifecycle import (
27 CleanupSpec,
28 Entry,
29 Join,
30 LifecycleWorkflow,
31 OpSpec,
32 Phase,
33)
34from sensorkit.sensor.selection import (
35 AllOf,
36 AnyOf,
37 HasTag,
38 HasTrait,
39 IsInstrument,
40 IsKind,
41 IsRef,
42 KeywordMatch,
43 Not,
44 Publishes,
45 Selection,
46 Supports,
47)
48from sensorkit.sensor.topology import (
49 Component,
50 Device,
51 Selector,
52 Structure,
53 Topology,
54 Unit,
55)
56from sensorkit.sensor.workflow import (
57 Acquisition,
58 Cleanup,
59 DeadlineRule,
60 DeadlineTarget,
61 ExecutableWorkflow,
62 Omission,
63 Operation,
64 Origin,
65 format_command,
66)
69class When(StrEnum):
70 """Human-readable descriptions indexed by cleanup eligibility."""
72 always = "however the run ended"
73 failure = "after a required failure"
74 cancelled = "after a domain abort"
75 failure_or_cancelled = (
76 "after a required failure, a domain abort or both, and once where both hold"
77 )
80@dataclass(frozen=True)
81class Finding:
82 """A validation result or a question deferred until device facts are
83 available.
85 `deferred` indicates an unanswered question, not a pass or failure.
86 """
88 status: Literal["valid", "invalid", "deferred"]
89 message: str
90 origin: Origin
93@dataclass(frozen=True)
94class AuditReport:
95 """Structured findings and a deterministic, human-readable description."""
97 findings: tuple[Finding, ...]
98 description: str
101def audit_definition(definition: SensorDefinition, *, name: str | None = None) -> AuditReport:
102 """Check an existing definition and describe its authored structure and
103 tables.
105 Report structural and reference checks as valid or invalid. Target
106 selection, trait assertions, command support and trait deadlines remain
107 deferred until device facts are supplied. Predicates are shown as authored.
109 Check each part separately so a Python-built definition can report multiple
110 errors. YAML parsing and model validation belong to the loader.
112 Args:
113 definition: The definition to check and describe.
114 name: Label for the sensor in the description, such as its entity ID.
115 """
116 label = f" '{name}'" if name else ""
117 topology, structure = _structure_checked(definition.sensor, label)
118 checked = (
119 structure,
120 *(_table_checked(t) for t in definition.tables),
121 *_deadlines_checked(definition, topology),
122 )
123 findings = (
124 *checked,
125 *_document_checked(definition, checked),
126 *_asserted(topology),
127 *(finding for table in definition.tables for finding in _entries_deferred(table)),
128 *_deadlines_deferred(definition.deadlines),
129 )
131 lines = [
132 f"definition of sensor{label}, without device facts",
133 " Which placements a selection reaches and what each device supports "
134 "are answered at binding, so selections are shown as authored.",
135 "",
136 f"structure{label}",
137 *_structure(definition.sensor.components, 1),
138 "",
139 *_deadlines(definition.deadlines),
140 ]
142 for table in definition.tables:
143 lines += ["", *_table(table)]
145 return AuditReport(findings=findings, description="\n".join(lines))
148def audit_workflow(workflow: ExecutableWorkflow) -> AuditReport:
149 """Describe stored graphs, policies, metadata and cleanup in a compiled
150 workflow.
152 Include dependency kinds, target placements, deadlines, delays, acquisition
153 keywords, omissions, outcome overrides and cleanup triggers. Findings are
154 empty because the workflow is rendered without revalidation.
156 Outcome overrides include operator reasons. Rules changing only failure
157 policy or optionality appear as effective policy without their reasons.
158 """
159 lines = [
160 f"workflow '{workflow.name}', as compiled",
161 "",
162 *_graph("run", workflow.graph),
163 "",
164 *_omitted(workflow.omissions),
165 "",
166 *_overridden(workflow),
167 ]
169 for cleanup in workflow.cleanup:
170 lines += ["", *_cleanup(cleanup)]
172 lines += [
173 "",
174 "Reading this audit",
175 " A command completing means the device answered, not that it reached "
176 "the requested state.",
177 " An acknowledged Abort does not show that the hardware stopped.",
178 " A completed acquisition does not show that its data product was "
179 "written or delivered downstream.",
180 " Hard cancellation, such as process teardown, runs no cleanup.",
181 ]
183 return AuditReport(findings=(), description="\n".join(lines))
186# TODO: Support concrete offline previews from saved device capability details.
189def _structure_checked(structure: Structure, label: str) -> tuple[Topology | None, Finding]:
190 """Try building topology and return it with a structural validation
191 finding.
192 """
193 origin = Origin(source="structure")
195 try:
196 topology = Topology(structure)
197 except ValueError as e:
198 return None, Finding("invalid", str(e), origin)
200 return topology, Finding(
201 "valid",
202 f"structure{label} places every device once and names every position once",
203 origin,
204 )
207def _table_checked(table: LifecycleWorkflow) -> Finding:
208 """Report a table's symbolic name, reference and cycle checks."""
209 origin = Origin(source=table.name)
211 try:
212 table.check()
213 except ValueError as e:
214 return Finding("invalid", str(e), origin)
216 return Finding(
217 "valid", f"table '{table.name}' names resolve and nothing it orders is circular", origin
218 )
221def _deadlines_checked(definition: SensorDefinition, topology: Topology | None) -> list[Finding]:
222 """Report device-target membership when a valid topology is available.
224 Invalid structure is reported elsewhere; non-device rules need no
225 membership check.
226 """
227 if topology is None or not any(r.target[0] == "device" for r in definition.deadlines):
228 return []
230 origin = Origin(source="deadlines")
232 try:
233 definition.check_deadlines(topology)
234 except ValueError as e:
235 return [Finding("invalid", str(e), origin)]
237 return [Finding("valid", "every device a deadline rule targets is in the structure", origin)]
240def _document_checked(definition: SensorDefinition, found: Iterable[Finding]) -> list[Finding]:
241 """Report the whole-definition error unless a part already reported the
242 same message.
243 """
244 try:
245 definition.check()
246 except ValueError as e:
247 if str(e) not in {f.message for f in found}:
248 return [Finding("invalid", str(e), Origin(source="definition"))]
250 return []
253def _asserted(topology: Topology | None) -> list[Finding]:
254 """Defer authored trait assertions for placements in a valid topology."""
255 if topology is None:
256 return []
258 findings: list[Finding] = []
260 for placement in topology.placements():
261 traits = topology.record(placement).traits
263 if traits:
264 findings.append(
265 Finding(
266 "deferred",
267 f"'{placement.device}' asserts {', '.join(traits)}; "
268 f"whether it satisfies them is answered at binding",
269 Origin(source="structure", path=(placement.device,)),
270 )
271 )
273 return findings
276def _rows(table: LifecycleWorkflow) -> Iterator[tuple[tuple[str | int, ...], Entry]]:
277 """Yield phase and cleanup entries with their authored origin paths."""
278 for phase in table.phases:
279 for position, entry in enumerate(phase.entries):
280 yield (phase.name, entry.id or position), entry
282 for spec in table.cleanup:
283 for position, entry in enumerate(spec.entries):
284 yield ("cleanup", spec.name, entry.id or position), entry
287def _entries_deferred(table: LifecycleWorkflow) -> list[Finding]:
288 """Record deferred target selection and command-support checks for each
289 entry.
290 """
291 return [
292 Finding(
293 "deferred",
294 f"which placements match {_targets(entry)}, and whether each "
295 f"supports {', '.join(spec.op for spec in entry.ops)}, is "
296 f"answered at binding",
297 Origin(source=table.name, path=path),
298 )
299 for path, entry in _rows(table)
300 ]
303def _deadlines_deferred(rules: tuple[DeadlineRule, ...]) -> list[Finding]:
304 """Record deferred trait matching for each trait-specific deadline rule."""
305 return [
306 Finding(
307 "deferred",
308 f"which placements satisfy trait {rule.target[1]}, and so take "
309 f"this {_commanded(rule)} deadline, is answered at binding",
310 Origin(source="deadlines", path=(index,)),
311 )
312 for index, rule in enumerate(rules)
313 if rule.target[0] == "trait"
314 ]
317def _symbolic(selection: Selection) -> str:
318 """Format an authored selection without evaluating it."""
319 match selection:
320 case HasTrait():
321 return f"trait {selection.trait}"
322 case HasTag():
323 return f"tag {selection.tag}"
324 case IsRef():
325 return f"device {selection.device}"
326 case IsKind():
327 return f"kind {selection.kind}"
328 case IsInstrument():
329 return f"instrument {str(selection.instrument).lower()}"
330 case Supports():
331 return f"supports {selection.supports}"
332 case Publishes():
333 return f"publishes {selection.publishes}"
334 case KeywordMatch(field=None):
335 return f"keyword {selection.keyword} {selection.predicate.model_dump_json()}"
336 case KeywordMatch():
337 return (
338 f"keyword {selection.keyword}.{selection.field} "
339 f"{selection.predicate.model_dump_json()}"
340 )
341 case AllOf():
342 return f"all of ({', '.join(map(_symbolic, selection.all_of))})"
343 case AnyOf():
344 return f"any of ({', '.join(map(_symbolic, selection.any_of))})"
345 case Not():
346 return f"not ({_symbolic(selection.negated)})"
348 return selection.model_dump_json(by_alias=True)
351def _targets(entry: Entry) -> str:
352 """Describe an entry's selection and exclusion symbolically."""
353 if entry.exclude is None:
354 return _symbolic(entry.select)
356 return f"{_symbolic(entry.select)} excluding {_symbolic(entry.exclude)}"
359def _structure(components: tuple[Component, ...], depth: int) -> Iterator[str]:
360 """Render components as an indented tree in authored order."""
361 indent = " " * depth
363 for node in components:
364 match node:
365 case Device():
366 yield indent + _record(node.device, node.traits, node.tags, node.instrument)
367 case Unit():
368 yield f"{indent}unit {node.unit}"
369 yield from _structure(node.components, depth + 1)
370 case Selector():
371 yield f"{indent}selector " + _record(node.selector, node.traits, node.tags, False)
373 for port in node.ports:
374 yield f"{indent} port {port.name}"
375 yield from _structure(port.components, depth + 2)
378def _record(key: str, traits: tuple[str, ...], tags: tuple[str, ...], instrument: bool) -> str:
379 """Describe a device key, instrument status, trait assertions and tags."""
380 parts = [key]
382 if instrument:
383 parts.append("instrument")
385 if traits:
386 parts.append(f"asserting {', '.join(traits)}")
388 if tags:
389 parts.append(f"tagged {', '.join(tags)}")
391 return ", ".join(parts)
394def _seconds(value: float) -> str:
395 return f"{value:g} s"
398def _addressed(target: DeadlineTarget) -> str:
399 """Format a deadline target for the audit description."""
400 kind, name = target
402 return "any placement" if name is None else f"{kind} {name}"
405def _deadlines(rules: tuple[DeadlineRule, ...]) -> Iterator[str]:
406 """Describe authored deadline rules in their supplied order."""
407 if not rules:
408 yield "no deadline rules"
409 return
411 yield (
412 "deadline rules, where an operation states no timeout, device "
413 "first, then trait, then any, and rules for every command last"
414 )
416 for rule in rules:
417 yield f" {_commanded(rule)} on {_addressed(rule.target)}, {_seconds(rule.seconds)}"
420def _commanded(rule: DeadlineRule) -> str:
421 """Name the command a deadline rule limits."""
422 return "every command" if rule.command is None else rule.command
425def _policy(fail_fast: bool) -> str:
426 return "fail-fast" if fail_fast else "not fail-fast"
429def _table(table: LifecycleWorkflow) -> Iterator[str]:
430 """Describe a table's phases, entries and cleanup specs."""
431 declared = {
432 entry.id: phase.name
433 for phase in table.phases
434 for entry in phase.entries
435 if entry.id is not None
436 }
438 yield (
439 f"table '{table.name}', {_policy(table.fail_fast)} unless a phase "
440 f"or an operation says otherwise"
441 )
443 for index, phase in enumerate(table.phases):
444 follows = table.follows(index)
445 yield f" phase '{phase.name}', {_ordered(phase, follows)}"
447 for position, entry in enumerate(phase.entries):
448 yield from _entry(entry, position, follows, declared, phase.fail_fast, table.fail_fast)
450 for spec in table.cleanup:
451 yield from _cleanup_spec(spec, table.fail_fast)
454def _ordered(phase: Phase, follows: tuple[str, ...]) -> str:
455 """Describe phase ordering and any explicit failure-policy override."""
456 if not follows:
457 text = "after nothing"
458 elif phase.after is None:
459 text = f"after the completion of '{follows[0]}', which precedes it"
460 else:
461 text = f"after the completion of {_quoted(follows)}"
463 if phase.fail_fast is not None:
464 text += f", {_policy(phase.fail_fast)} unless an operation says otherwise"
466 return text
469def _quoted(names: Iterable[str]) -> str:
470 return ", ".join(f"'{name}'" for name in names)
473def _entry(
474 entry: Entry,
475 position: int,
476 follows: tuple[str, ...],
477 declared: dict[str, str],
478 phase: bool | None,
479 table: bool,
480) -> Iterator[str]:
481 """Describe an entry's authored selection, requirements and commands."""
482 yield f" entry '{entry.id}'" if entry.id else f" entry {position}"
483 yield f" select {_symbolic(entry.select)}"
485 if entry.exclude is not None:
486 yield f" exclude {_symbolic(entry.exclude)}"
488 yield " targets answered at binding"
490 for clause in entry.require:
491 yield f" {_clause(clause, follows, declared)}"
493 yield " operations, serial at each target"
495 for index, spec in enumerate(entry.ops):
496 yield f" {_op(spec, index, phase, table)}"
499def _clause(clause: Join, follows: tuple[str, ...], declared: dict[str, str]) -> str:
500 """Describe a requirement and any inherited phase wait it replaces."""
501 text = f"requires '{clause.name}' on {clause.on}"
503 if clause.join != "all":
504 text += f", joining {clause.join}"
506 phase = declared.get(clause.name, clause.name)
508 if phase in follows:
509 text += f", in place of the wait on all of '{phase}'"
511 return text
514def _op(spec: OpSpec, index: int, phase: bool | None, table: bool) -> str:
515 """Describe an authored command with sequencing, failure policy and
516 timeout source.
517 """
518 parts = [
519 format_command(spec.command),
520 "first at each target" if index == 0 else f"after the {spec.sequence} of the previous",
521 _effective(spec.fail_fast, phase, table),
522 ]
524 if spec.optional:
525 parts.append("optional")
527 parts.append(
528 "omitted where unsupported" if spec.unsupported == "omit" else "an error where unsupported"
529 )
530 parts.append(
531 "deadline from the rules"
532 if spec.timeout_s is None
533 else f"deadline {_seconds(spec.timeout_s)}, explicit"
534 )
536 return "; ".join(parts)
539def _effective(operation: bool | None, phase: bool | None, table: bool) -> str:
540 """Describe failure policy resolved from operation, phase, then table."""
541 match operation, phase:
542 case bool(), _:
543 return f"{_policy(operation)}, as the operation states"
544 case None, bool():
545 return f"{_policy(phase)}, from the phase"
547 return f"{_policy(table)}, from the table"
550def _cleanup_spec(spec: CleanupSpec, table: bool) -> Iterator[str]:
551 """Describe a cleanup spec's eligibility, arming, timeout and entries."""
552 declared = {entry.id: spec.name for entry in spec.entries if entry.id is not None}
554 yield f" cleanup '{spec.name}', runs {When[spec.when]}"
555 yield f" total deadline {_seconds(spec.timeout_s)}"
556 yield f" {_armed_by_entries(spec.armed_by)}"
558 for position, entry in enumerate(spec.entries):
559 yield from _entry(entry, position, (), declared, None, table)
562def _armed_by_entries(armed_by: tuple[str, ...] | None) -> str:
563 match armed_by:
564 case None:
565 return "armed unconditionally"
566 case ():
567 return "never armed, so it never runs"
569 return f"armed once any operation of {_quoted(armed_by)} is attempted"
572def _name(node: Node) -> str:
573 """Use an operation label or ordering-node description in dependency
574 references.
575 """
576 if isinstance(node.payload, Operation):
577 return node.payload.id
579 return f"ordering '{node.label}'"
582def _graph(title: str, graph: Graph) -> Iterator[str]:
583 """Describe graph nodes in topological order, including their
584 dependencies.
585 """
586 names = {node.id: _name(node) for node in graph.nodes}
587 by_id = {node.id: node for node in graph.nodes}
588 operations = sum(isinstance(n.payload, Operation) for n in graph.nodes)
590 yield (
591 f"{title}, {_count(operations, 'operation')} and "
592 f"{_count(len(graph.nodes) - operations, 'ordering node')}"
593 )
595 for nid in graph.topo_order():
596 yield from _node(by_id[nid], graph, names)
599def _count(count: int, noun: str) -> str:
600 return f"{count} {noun}" if count == 1 else f"{count} {noun}s"
603def _node(node: Node, graph: Graph, names: dict[int, str]) -> Iterator[str]:
604 """Describe a node's payload, policy, delays, overrides and
605 dependencies.
606 """
607 yield f" {names[node.id]}, in '{node.group}'"
609 match node.payload:
610 case Operation() as operation:
611 yield f" {node.label}"
612 yield (
613 " no deadline"
614 if operation.timeout_s is None
615 else f" deadline {_seconds(operation.timeout_s)}"
616 )
618 if operation.acquisition is not None:
619 yield from _acquisition(operation.acquisition)
620 case _:
621 yield " sends nothing, and resolves once what it waits on has"
623 yield f" on failure, {_on_failure(node.on_failure)}"
625 if node.optional:
626 yield " optional, so a failure degrades the run without failing it"
628 if node.override is not None:
629 yield (
630 f" overridden, recorded {node.override.outcome} without "
631 f"dispatching, because {node.override.reason}"
632 )
634 if node.delay_s:
635 yield f" starts {_seconds(node.delay_s)} after what it waits on has resolved"
637 yield from _edges(node, graph, names)
640def _on_failure(on_failure: OnFailure) -> str:
641 match on_failure:
642 case "stop":
643 return "stops dispatching anything further in its graph, fail-fast"
644 case "skip":
645 return "skips whatever needs its success, not fail-fast"
647 return "lets whatever needs its success run anyway"
650def _edges(node: Node, graph: Graph, names: dict[int, str]) -> Iterator[str]:
651 """Describe incoming success and completion edges in predecessor-id
652 order.
653 """
654 deps = sorted(graph.deps[node.id])
656 if not deps:
657 yield " waits on nothing"
659 for dep in deps:
660 kind = (
661 "needs the success of" if dep in graph.hard[node.id] else "waits for the completion of"
662 )
663 yield f" {kind} {names[dep]}"
666def _acquisition(acquisition: Acquisition) -> Iterator[str]:
667 """Describe frame identity, planned keywords and dispatch-time header
668 sampling.
669 """
670 yield (
671 f" acquisition of request '{acquisition.request}', "
672 f"index {acquisition.index}, frame {acquisition.frame_number}"
673 )
675 if acquisition.keywords:
676 yield " planned keywords, as requested rather than as achieved"
678 for key in sorted(acquisition.keywords):
679 value = to_jsonable_python(acquisition.keywords[key], fallback=repr)
680 yield f" {key} = {json.dumps(value, sort_keys=True)}"
682 yield (
683 " header sampled at dispatch, so the command above is planned "
684 "and is not the header-bearing command sent"
685 )
688def _omitted(omissions: tuple[Omission, ...]) -> Iterator[str]:
689 """Describe capability omissions separately from operator overrides."""
690 if not omissions:
691 yield "nothing omitted at compile"
692 return
694 yield (
695 "omitted at compile where the device lacks the command, by "
696 "capability and not by an operator"
697 )
699 for omission in omissions:
700 yield (
701 f" {omission.command} on {omission.target.device} @ {omission.target.path_str}, "
702 f"from {omission.origin}, because {omission.reason}"
703 )
705 yield " What waited on an omitted operation waits on what it waited on."
708def _overridden(workflow: ExecutableWorkflow) -> Iterator[str]:
709 """Describe recorded outcome overrides and reasons across main and
710 cleanup graphs.
711 """
712 graphs = (workflow.graph, *(c.graph for c in workflow.cleanup))
713 overridden = [
714 (_name(node), override)
715 for graph in graphs
716 for node in graph.nodes
717 if (override := node.override) is not None
718 ]
720 if not overridden:
721 yield "no operator overrides"
722 return
724 yield "operator overrides, each recorded without dispatching"
726 for name, override in overridden:
727 yield f" {name}, {override.outcome}, because {override.reason}"
730def _cleanup(cleanup: Cleanup) -> Iterator[str]:
731 """Describe a compiled cleanup's eligibility, arming, timeout and graph."""
732 yield f"cleanup '{cleanup.origin}', runs {When[cleanup.when]} once the run has drained"
733 yield f" total deadline {_seconds(cleanup.timeout_s)}, beside each command's own"
735 match cleanup.armed_by:
736 case None:
737 yield " armed unconditionally"
738 case ():
739 yield " never armed, so it will not run"
740 case operations:
741 yield " armed once any of these is attempted"
742 yield from (f" {operation.id}" for operation in operations)
744 yield from _graph(" its graph", cleanup.graph)