Coverage for src/governed_harness/orchestration/workflow.py: 92%
92 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""The phase graph of a workflow (#3).
3Under ``governance.enforceWorkflow`` the engine asks this graph which phase follows a passed
4one, whether a phase may start (every ``dependsOn`` phase passed), which conditions a passed
5attempt must meet (the ``exitGate`` and the condition of the transition it takes) and which
6work may overlap (``parallelizable``). The nine normative phases and their order stay fixed
7(``WorkflowDefinition.validate_graph``); the graph only orders, gates and groups them.
8"""
10from __future__ import annotations
12from collections.abc import Collection, Iterable
14from governed_harness.configuration.models import (
15 ValidatorDefinition,
16 WorkflowDefinition,
17 WorkflowPhaseDefinition,
18 WorkflowTransitionDefinition,
19)
20from governed_harness.configuration.workflow_rules import canonical_condition
21from governed_harness.domain.enums import PhaseId
23WRITE_CAPABILITY = "filesystem.write"
26class WorkflowGraph:
27 def __init__(self, definition: WorkflowDefinition) -> None:
28 self.definition = definition
29 self._phases = {phase.phase_id: phase for phase in definition.phases}
30 self._transitions = {(item.source, item.target): item for item in definition.transitions}
32 def phase(self, phase_id: PhaseId) -> WorkflowPhaseDefinition:
33 return self._phases[phase_id]
35 def next_primary(self, phase_id: PhaseId) -> PhaseId | None:
36 primary = [phase.phase_id for phase in self.definition.phases]
37 index = primary.index(phase_id)
38 return primary[index + 1] if index + 1 < len(primary) else None
40 def dependencies(self, phase_id: PhaseId) -> tuple[PhaseId, ...]:
41 return self._phases[phase_id].depends_on
43 def transition_allowed(self, source: PhaseId, target: PhaseId) -> bool:
44 return (source, target) in self._transitions
46 # ----- ordering (dependsOn) ----------------------------------------------------------
47 def order(self) -> tuple[PhaseId, ...]:
48 """The phases in an order that respects ``dependsOn``: each phase comes after its
49 dependencies and, among the phases that are ready, the declared order decides (so the
50 result is deterministic). Raises ``ValueError`` on a cycle or an unknown dependency."""
51 declared = [phase.phase_id for phase in self.definition.phases]
52 remaining = {phase_id: set(self._phases[phase_id].depends_on) for phase_id in declared}
53 for phase_id, needs in remaining.items():
54 unknown = needs - set(declared)
55 if unknown: 55 ↛ 56line 55 didn't jump to line 56 because the condition on line 55 was never true
56 names = ", ".join(sorted(item.value for item in unknown))
57 raise ValueError(f"{phase_id.value} depends on unknown phase(s) {names}")
58 ordered: list[PhaseId] = []
59 while remaining:
60 ready = [phase_id for phase_id in declared if remaining.get(phase_id) == set()]
61 if not ready:
62 names = ", ".join(sorted(item.value for item in remaining))
63 raise ValueError(f"dependsOn has a cycle among {names}")
64 chosen = ready[0]
65 ordered.append(chosen)
66 del remaining[chosen]
67 for needs in remaining.values():
68 needs.discard(chosen)
69 return tuple(ordered)
71 def next_phase(self, phase_id: PhaseId) -> PhaseId | None:
72 """The phase that may start after ``phase_id`` passed (``None`` after the last)."""
73 order = self.order()
74 index = order.index(phase_id)
75 return order[index + 1] if index + 1 < len(order) else None
77 def unmet_dependencies(
78 self, phase_id: PhaseId, passed: Collection[PhaseId]
79 ) -> tuple[PhaseId, ...]:
80 """The ``dependsOn`` phases of ``phase_id`` that are not in ``passed``."""
81 return tuple(item for item in self.dependencies(phase_id) if item not in passed)
83 def ancestors(self, phase_id: PhaseId) -> frozenset[PhaseId]:
84 """Every phase ``phase_id`` depends on, directly or through another phase."""
85 seen: set[PhaseId] = set()
86 pending = list(self.dependencies(phase_id))
87 while pending:
88 item = pending.pop()
89 if item in seen or item not in self._phases: 89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true
90 continue
91 seen.add(item)
92 pending.extend(self.dependencies(item))
93 return frozenset(seen)
95 def transition(self, source: PhaseId, target: PhaseId) -> WorkflowTransitionDefinition | None:
96 return self._transitions.get((source, target))
98 # ----- exit gates ----------------------------------------------------------------------
99 def exit_conditions(self, phase_id: PhaseId) -> tuple[str, ...]:
100 """The conditions a passed attempt of ``phase_id`` must meet, without repeats: its
101 ``exitGate`` and the condition of the transition to the next phase (the built-in
102 DECISION names ``decision_recorded`` and ``decision_approved``, one check)."""
103 names = [self._phases[phase_id].exit_gate]
104 target = self.next_phase(phase_id)
105 if target is not None:
106 transition = self.transition(phase_id, target)
107 if transition is not None: 107 ↛ 109line 107 didn't jump to line 109 because the condition on line 107 was always true
108 names.append(transition.condition)
109 return tuple(dict.fromkeys(canonical_condition(name) for name in names))
111 # ----- parallelism ---------------------------------------------------------------------
112 def independent(self, first: PhaseId, second: PhaseId) -> bool:
113 """Neither phase depends on the other, directly or through another phase."""
114 return (
115 first != second
116 and first not in self.ancestors(second)
117 and second not in self.ancestors(first)
118 )
120 def may_overlap(self, first: PhaseId, second: PhaseId) -> bool:
121 """Two phases may run at once only when both are parallelizable, independent and
122 read-only: a run has one workspace, so a phase that may write it never overlaps."""
123 one, other = self._phases[first], self._phases[second]
124 return (
125 one.parallelizable
126 and other.parallelizable
127 and WRITE_CAPABILITY not in one.allowed_capabilities
128 and WRITE_CAPABILITY not in other.allowed_capabilities
129 and self.independent(first, second)
130 )
132 def parallel_groups(self) -> tuple[tuple[PhaseId, ...], ...]:
133 """The phases in ``order()``, consecutive ones grouped when every pair may overlap."""
134 groups: list[list[PhaseId]] = []
135 for phase_id in self.order():
136 if groups and all(self.may_overlap(item, phase_id) for item in groups[-1]):
137 groups[-1].append(phase_id)
138 else:
139 groups.append([phase_id])
140 return tuple(tuple(group) for group in groups)
142 def runs_parallel_work(self, phase_id: PhaseId) -> bool:
143 """Whether the read-only work inside the phase (its parallel-safe validators) may run
144 at once: the phase is parallelizable and does not write the workspace."""
145 phase = self._phases[phase_id]
146 return phase.parallelizable and WRITE_CAPABILITY not in phase.allowed_capabilities
149def validator_batches(
150 definitions: Iterable[ValidatorDefinition], *, parallel: bool
151) -> tuple[tuple[ValidatorDefinition, ...], ...]:
152 """The validators of a VERIFICATION in their declared order, consecutive validators
153 declared ``parallelSafe`` grouped into one batch when ``parallel`` holds; every other
154 validator is a batch of its own. The grouping depends only on the declarations."""
155 batches: list[list[ValidatorDefinition]] = []
156 previous_safe = False
157 for definition in definitions:
158 safe = parallel and bool(definition.parallel_safe)
159 if safe and previous_safe:
160 batches[-1].append(definition)
161 else:
162 batches.append([definition])
163 previous_safe = safe
164 return tuple(tuple(batch) for batch in batches)