Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

refactor(execution): isolate generic If activation compilation

JPPhotoa1ece0b6358c
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 9c1219ac4c..7d4faf4edf 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -94,22 +94,26 @@ Iterate/Collect sessions. This is evidence for the current adapters; it does not
ownership. `loop_linkage` remains association metadata and never becomes a data token.
`IfInvocation` now declares the same seam for branch activation: it emits one frame-scoped activation token for the
-selected branch, and the graph state validates and persists it after invocation. The generic opaque scheduler receives
-an activation readiness predicate and skip projection for `If`; the private branch adapter still computes legacy
-topology, resolves the gate, prunes the unselected edge, and writes the compatibility token before invocation.
-`apply()` replaces that token by stable identity, and activation effects are excluded from stream handling. This is a
-partial routing migration: author-time activation ports and literal successor IDs remain absent, while loop and
-saved-workflow control flow remain on their compatibility paths until differential coverage proves their generic
-replacements.
+selected branch, and the graph state validates and persists it after invocation. For a fresh generic `If`, the dedicated
+`_IfActivationCompiler` produces opaque, frame-local activation dependencies. `_GenericGraphSchedulerAdapter` consumes
+those dependencies through the opaque `ExecutionPlan` for readiness and rejects unselected prepared nodes through
+generic scheduler discard. It does not consult `_IfBranchScheduler` topology, call
+`_IfBranchScheduler._prune_unselected_if_inputs` or `_IfBranchScheduler.mark_exec_node_skipped`, or delete execution
+edges. Forced `_ExecutionScheduler` still retains
+`_IfBranchScheduler` legacy topology, input-edge pruning, and skip behavior for compatibility snapshots. `apply()`
+replaces the activation token by stable identity, and activation effects are excluded from stream handling. This is an
+ownership seam, not final removal of all legacy topology. Author-time activation ports and literal successor IDs remain
+absent, while loop and saved-workflow control flow remain on their compatibility paths until differential coverage
+proves their generic replacements.
The engine still owns runtime node materialization and queue readiness for loop-containing graphs and existing snapshots.
Ordinary static DAGs and legacy-shaped `If` graphs now use the generic opaque plan/scheduler through a compatibility
-projection. This is intentional:
+projection; a fresh generic `If` uses the compiler/adapter seam described above. This is intentional:
the generic records preserve tested loop semantics first, while the old execution graph remains the fallback for control
lowerings, legacy snapshots, and unsupported mixed loop shapes. No activation or stream ports are added to author-time
graph JSON.
This migration does not modify code under `invokeai/frontend/...`; the existing frontend/backend external interface
-remains frozen.
+remains frozen. The ownership seam does not remove all legacy topology yet.
The frontend and backend validate the same boundary rules. Saved workflows preserve node types, field handles, and the
direct linkage edge. The current invocation templates provide output-scope metadata when a workflow is loaded. The
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 7b1825d66c..4005778de2 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -8,10 +8,13 @@ Provide a typed, acyclic workflow model (**Graph**) plus a runtime scheduler (**
iterator patterns, tracks readiness via indegree (the number of incoming edges to a node in the directed graph), and
executes nodes from class-grouped ready queues. In normal execution, runtime expansion happens in a separate execution graph
instead of mutating the source graph. Ordinary static DAGs and legacy-shaped `If` graphs use the opaque `ExecutionPlan`
-and deterministic `ExecutionScheduler` in `execution_engine/scheduler.py`; a private graph adapter derives opaque,
-frame-local `If` activation dependencies, checks their private gate state plus persisted activation tokens, and retires
-unselected prepared nodes through generic scheduler discard. The forced compatibility `_ExecutionScheduler` path retains
-legacy `If` topology lowering, input-edge pruning, and skip behavior.
+and deterministic `ExecutionScheduler` in `execution_engine/scheduler.py`. For a fresh generic `If`, the dedicated
+`_IfActivationCompiler` produces opaque, frame-local activation dependencies; `_GenericGraphSchedulerAdapter` registers
+and consumes those dependencies through the opaque plan, then rejects unselected prepared nodes through generic scheduler
+discard. It does not consult `_IfBranchScheduler` topology or call its prune/skip methods, and it does not delete
+execution edges. The forced compatibility `_ExecutionScheduler` path retains legacy `If` topology lowering, input-edge
+pruning, and skip behavior for compatibility snapshots. This is an ownership seam, not final removal of all legacy
+topology.
The runtime also exposes an additive execution-engine seam: frame-scoped gates, ordered streams, continuations, and
authorized child-dependency records are stored in
`invokeai.app.services.shared.execution_engine`; legacy graph and queue behavior is retained behind adapters while
@@ -203,13 +206,14 @@ port against the producing invocation's declared activation fields and persists
rehydration, every activation token is bound to a currently prepared owner and its derived execution reference; its
declared port, value, canonical token id, mapping key, and known frame fields must match. Unknown extra frame metadata
remains forward-compatible.
-The generic plan stores opaque, frame-local activation-dependency records for `If` branch-local nodes. Its readiness
+For a fresh generic `If`, `_IfActivationCompiler` puts opaque, frame-local activation-dependency records on each
+branch-local plan node. `_GenericGraphSchedulerAdapter` consumes those records through the opaque plan: its readiness
callback accepts a node only when the required private `ActivationGate` runtime state is resolved and a matching
-persisted activation token is present for its frame; the activation token is therefore authoritative for generic
-successor readiness. Generic legacy-shaped `If` resolution retires unselected prepared nodes through generic scheduler
-discard. It does not call `_IfBranchScheduler._prune_unselected_if_inputs`,
+persisted activation token is present for its frame, while rejected dependencies cause generic scheduler discard. This
+path does not consult `_IfBranchScheduler` topology, call `_IfBranchScheduler._prune_unselected_if_inputs` or
`_IfBranchScheduler.mark_exec_node_skipped`, or delete execution edges. The forced compatibility `_ExecutionScheduler`
-path still uses `_IfBranchScheduler` for legacy branch topology, input-edge pruning, and skip behavior. `apply()`
+path still uses `_IfBranchScheduler` for legacy branch topology, input-edge pruning, and skip behavior. This is an
+ownership seam, not final removal of all legacy topology. `apply()`
validates and persists the invocation-emitted effect afterward, replacing the compatibility token by stable identity.
Activation effects are excluded from data-stream handling. `IterateInvocation` is the first stream-producing
control-flow invocation on this seam: each non-empty prepared copy emits one ordered `item` effect with its iteration
@@ -317,20 +321,22 @@ Workflow-call note:
ready work. It owns iterator expansion, collector grouping, prepared-parent selection, and creation of execution-graph
edges. When matching prepared parents for a downstream exec node, skipped prepared exec nodes are ignored and cannot
be selected as live inputs.
+- `_IfActivationCompiler` Compiles legacy-shaped `If` branch membership into opaque, frame-local activation dependency
+ records for the generic plan. It is separate from both schedulers and does not own execution-graph topology changes.
- `_GenericGraphSchedulerAdapter` Projects the generic `ExecutionPlan`/`ExecutionScheduler` into the existing state
fields for ordinary static DAGs and legacy-shaped `If` graphs; the generic scheduler owns opaque readiness,
- intentional discards, indegree transitions, deterministic ordering, claimed work, and completion. The adapter records
- frame-local activation dependencies, checks private gate state plus persisted activation tokens, and retires
- unselected prepared nodes through generic scheduler discard.
+ intentional discards, indegree transitions, deterministic ordering, claimed work, and completion. The adapter registers
+ the compiler's activation dependencies, checks private gate state plus persisted activation tokens, and rejects
+ unselected prepared nodes through generic scheduler discard. Fresh generic `If` scheduling does not call
+ `_IfBranchScheduler` topology, prune, or skip methods and does not delete execution edges.
- `_ExecutionScheduler` Owns materialized-graph indegree transitions, class-grouped ready queues, downstream release,
control-flow continuation scheduling, and forced-compatibility `If` topology for graphs that still require lowering.
- `_ExecutionRuntime` Owns iteration-path lookup, collect input ordering, and input hydration for prepared exec nodes.
- `_IfBranchScheduler` Computes legacy `If` topology, defers branch-local work until the condition is known, then
lowers the decision to private frame-scoped `ActivationGate` runtime state and a persisted internal activation token,
releases the selected branch, prunes unselected input edges, and marks unselected branch-local nodes skipped. Used
- only by forced compatibility `_ExecutionScheduler`; generic legacy-shaped `If` scheduling compiles opaque dependencies
- and retires unselected prepared nodes through generic scheduler discard. The opaque scheduler has no `If`-specific
- branch.
+ only by forced compatibility `_ExecutionScheduler`; it remains available for compatibility snapshots. Its retained
+ topology/pruning/skip ownership is an intentional seam, not a final removal of legacy topology.
- `ExecutionEngineRuntime` Owns the typed gate, stream, and continuation records used by compatibility adapters. The
canonical stream for a prepared `IterateInvocation` is keyed by the source iterator and its parent iteration path;
its item/close effects and legacy output mirroring update the same idempotent buffer. Direct `CollectInvocation.item`
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index b37262f21d..bcdfb1f3f1 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -328,72 +328,92 @@ class _PreparedExecRegistry:
self._on_iteration_path_change(exec_node_id)
-def _get_if_branch_exclusive_sources(state: "GraphExecutionState", if_node_id: str) -> dict[str, set[str]]:
- """Compile legacy If inputs into frame-independent branch source sets.
+class _IfActivationCompiler:
+ """Lower legacy-shaped ``If`` inputs into opaque activation requirements.
- This is a graph-compilation helper, not a scheduler transition. The
- generic adapter uses the result to attach opaque activation dependencies
- and retire unselected prepared nodes without mutating execution edges.
+ This compiler is deliberately separate from both schedulers. The generic
+ scheduler consumes the resulting dependency records and never consults
+ the compatibility branch scheduler; the latter remains available only to
+ resume execution graphs produced by the legacy lowering path.
"""
- cached = state._if_branch_exclusive_sources.get(if_node_id)
- if cached is not None:
- return cached
-
- source_graph = state._get_source_graph_flat()
- branch_sources: dict[str, set[str]] = {}
- for branch_field in ("true_input", "false_input"):
- direct_inputs = {edge.source.node_id for edge in state.graph._get_input_edges(if_node_id, branch_field)}
- expanded = set(direct_inputs)
- for node_id in list(expanded):
- expanded.update(nx.ancestors(source_graph, node_id))
-
- exclusive_sources = set(expanded)
- changed = True
- while changed:
- changed = False
- for node_id in list(exclusive_sources):
- output_edges = state.graph._get_output_edges(node_id)
- stays_in_branch = all(
- edge.destination.node_id in exclusive_sources
- or (edge.destination.node_id == if_node_id and edge.destination.field == branch_field)
- for edge in output_edges
+ def __init__(self, state: "GraphExecutionState") -> None:
+ self._state = state
+
+ def get_branch_exclusive_sources(self, if_node_id: str) -> dict[str, set[str]]:
+ cached = self._state._if_branch_exclusive_sources.get(if_node_id)
+ if cached is not None:
+ return cached
+
+ source_graph = self._state._get_source_graph_flat()
+ branch_sources: dict[str, set[str]] = {}
+ for branch_field in ("true_input", "false_input"):
+ direct_inputs = {
+ edge.source.node_id for edge in self._state.graph._get_input_edges(if_node_id, branch_field)
+ }
+ expanded = set(direct_inputs)
+ for node_id in list(expanded):
+ expanded.update(nx.ancestors(source_graph, node_id))
+
+ exclusive_sources = set(expanded)
+ changed = True
+ while changed:
+ changed = False
+ for node_id in list(exclusive_sources):
+ output_edges = self._state.graph._get_output_edges(node_id)
+ stays_in_branch = all(
+ edge.destination.node_id in exclusive_sources
+ or (edge.destination.node_id == if_node_id and edge.destination.field == branch_field)
+ for edge in output_edges
+ )
+ if not stays_in_branch:
+ exclusive_sources.remove(node_id)
+ changed = True
+ branch_sources[branch_field] = exclusive_sources
+
+ self._state._tx_set_mapping(self._state._if_branch_exclusive_sources, if_node_id, branch_sources)
+ return branch_sources
+
+ def get_activation_dependencies(self, exec_node_id: str) -> tuple[ActivationDependency, ...]:
+ """Compile opaque branch requirements for one prepared execution node."""
+
+ source_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
+ iteration_path = self._state._get_iteration_path(exec_node_id)
+ dependencies: list[ActivationDependency] = []
+ for source_if_id, source_if_node in self._state.graph.nodes.items():
+ if not isinstance(source_if_node, IfInvocation):
+ continue
+ branches = self.get_branch_exclusive_sources(source_if_id)
+ matching_fields = tuple(
+ branch_field
+ for branch_field in ("true_input", "false_input")
+ if source_node_id in branches[branch_field]
+ )
+ # A shared ancestor is live regardless of branch selection.
+ if len(matching_fields) != 1:
+ continue
+ dependencies.append(
+ ActivationDependency(
+ owner_id=source_if_id,
+ branch=matching_fields[0],
+ frame=iteration_path,
)
- if not stays_in_branch:
- exclusive_sources.remove(node_id)
- changed = True
- branch_sources[branch_field] = exclusive_sources
+ )
+ return tuple(dependencies)
+
- state._tx_set_mapping(state._if_branch_exclusive_sources, if_node_id, branch_sources)
- return branch_sources
+def _get_if_branch_exclusive_sources(state: "GraphExecutionState", if_node_id: str) -> dict[str, set[str]]:
+ """Compatibility entry point for legacy ``If`` topology lowering."""
+
+ return state._if_activation_compiler().get_branch_exclusive_sources(if_node_id)
def _get_if_activation_dependencies(
state: "GraphExecutionState", exec_node_id: str
) -> tuple[ActivationDependency, ...]:
- """Compile opaque branch requirements for one prepared execution node."""
-
- source_node_id = state._prepared_registry().get_source_node_id(exec_node_id)
- iteration_path = state._get_iteration_path(exec_node_id)
- dependencies: list[ActivationDependency] = []
- for source_if_id, source_if_node in state.graph.nodes.items():
- if not isinstance(source_if_node, IfInvocation):
- continue
- branches = _get_if_branch_exclusive_sources(state, source_if_id)
- matching_fields = tuple(
- branch_field for branch_field in ("true_input", "false_input") if source_node_id in branches[branch_field]
- )
- # A shared ancestor is live regardless of branch selection.
- if len(matching_fields) != 1:
- continue
- dependencies.append(
- ActivationDependency(
- owner_id=source_if_id,
- branch=matching_fields[0],
- frame=iteration_path,
- )
- )
- return tuple(dependencies)
+ """Compatibility entry point for callers that still request If dependencies."""
+
+ return state._if_activation_compiler().get_activation_dependencies(exec_node_id)
class _IfBranchScheduler:
@@ -402,40 +422,6 @@ class _IfBranchScheduler:
def __init__(self, state: "GraphExecutionState") -> None:
self._state = state
- def _get_branch_input_sources(self, if_node_id: str, branch_field: str) -> set[str]:
- return {e.source.node_id for e in self._state.graph._get_input_edges(if_node_id, branch_field)}
-
- def _expand_with_ancestors(self, node_ids: set[str]) -> set[str]:
- expanded = set(node_ids)
- source_graph = self._state._get_source_graph_flat()
- for node_id in list(expanded):
- expanded.update(nx.ancestors(source_graph, node_id))
- return expanded
-
- def _node_outputs_stay_in_branch(
- self, node_id: str, if_node_id: str, branch_field: str, branch_nodes: set[str]
- ) -> bool:
- output_edges = self._state.graph._get_output_edges(node_id)
- return all(
- edge.destination.node_id in branch_nodes
- or (edge.destination.node_id == if_node_id and edge.destination.field == branch_field)
- for edge in output_edges
- )
-
- def _prune_nonexclusive_branch_nodes(
- self, if_node_id: str, branch_field: str, candidate_nodes: set[str]
- ) -> set[str]:
- exclusive_nodes = set(candidate_nodes)
- changed = True
- while changed:
- changed = False
- for node_id in list(exclusive_nodes):
- if self._node_outputs_stay_in_branch(node_id, if_node_id, branch_field, exclusive_nodes):
- continue
- exclusive_nodes.remove(node_id)
- changed = True
- return exclusive_nodes
-
def _get_matching_prepared_if_ids(self, if_node_id: str, iteration_path: tuple[int, ...]) -> list[str]:
prepared_if_ids = self._state._prepared_registry().get_prepared_ids(if_node_id)
return [pid for pid in prepared_if_ids if self._state._get_iteration_path(pid) == iteration_path]
@@ -2275,19 +2261,6 @@ class _GenericGraphSchedulerAdapter:
if source_node_id not in self._state.executed:
self._state._mark_source_executed(source_node_id)
- def _retire_unselected_nodes(self, if_exec_node_id: str) -> None:
- source_if_node_id = self._state._prepared_registry().get_source_node_id(if_exec_node_id)
- branches = _get_if_branch_exclusive_sources(self._state, source_if_node_id)
- unselected_field = (
- "false_input" if self._state._resolved_if_exec_branches[if_exec_node_id] == "true_input" else "true_input"
- )
- iteration_path = self._state._get_iteration_path(if_exec_node_id)
- for prepared_id, prepared_source in tuple(self._state.prepared_source_mapping.items()):
- if self._state._get_iteration_path(prepared_id) != iteration_path:
- continue
- if prepared_source in branches[unselected_field]:
- self._retire_unselected_node(prepared_id)
-
def resolve_if_node(self, exec_node_id: str) -> None:
"""Resolve legacy If inputs without pruning graph edges or using type-specific skips."""
@@ -2303,11 +2276,11 @@ class _GenericGraphSchedulerAdapter:
self._state._resolve_activation_gate(exec_node_id, selected_field)
self._state._tx_set_mapping(self._state._resolved_if_exec_branches, exec_node_id, selected_field)
self._state._record_compatibility_activation_token(exec_node_id, selected_field)
- self._retire_unselected_nodes(exec_node_id)
+ self._discard_rejected_nodes()
self._sync_indegree()
self._project_ready_nodes()
- def _retire_if_rejected_node(self, exec_node_id: str) -> None:
+ def _discard_rejected_node(self, exec_node_id: str) -> None:
node = self._scheduler.plan.nodes.get(exec_node_id)
if node is None or not node.activation_dependencies:
return
@@ -2316,6 +2289,12 @@ class _GenericGraphSchedulerAdapter:
):
self._retire_unselected_node(exec_node_id)
+ def _discard_rejected_nodes(self) -> None:
+ """Discard plan nodes whose opaque activation requirements are rejected."""
+
+ for exec_node_id in tuple(self._scheduler.plan.nodes):
+ self._discard_rejected_node(exec_node_id)
+
def _sync_executed_state(self, excluded: Iterable[str] = ()) -> None:
excluded_ids = set(excluded)
self._scheduler.executed.update(
@@ -2352,7 +2331,7 @@ class _GenericGraphSchedulerAdapter:
)
)
self._state._tx_set_mapping(self._state.indegree, exec_node_id, self._scheduler.indegree[exec_node_id])
- self._retire_if_rejected_node(exec_node_id)
+ self._discard_rejected_node(exec_node_id)
if not self._initializing:
self._project_ready_node(exec_node_id)
@@ -4498,6 +4477,7 @@ class GraphExecutionState(BaseModel):
_prepared_exec_metadata: dict[str, _PreparedExecNodeMetadata] = PrivateAttr(default_factory=dict)
_prepared_exec_registry: Optional[_PreparedExecRegistry] = PrivateAttr(default=None)
_if_branch_scheduler: Optional[_IfBranchScheduler] = PrivateAttr(default=None)
+ _if_activation_compiler_instance: Optional[_IfActivationCompiler] = PrivateAttr(default=None)
_execution_materializer: Optional[_ExecutionMaterializer] = PrivateAttr(default=None)
_execution_scheduler: Optional[_ExecutionScheduler | _GenericGraphSchedulerAdapter] = PrivateAttr(default=None)
_execution_runtime: Optional[_ExecutionRuntime] = PrivateAttr(default=None)
@@ -4610,6 +4590,7 @@ class GraphExecutionState(BaseModel):
self._execution_materializer = None
self._execution_scheduler = None
self._generic_graph_scheduler = None
+ self._if_activation_compiler_instance = None
self._execution_runtime = None
self._if_branch_exclusive_sources = {}
self._source_graph_flat = None
@@ -4642,6 +4623,11 @@ class GraphExecutionState(BaseModel):
self._if_branch_scheduler = _IfBranchScheduler(self)
return self._if_branch_scheduler
+ def _if_activation_compiler(self) -> _IfActivationCompiler:
+ if self._if_activation_compiler_instance is None:
+ self._if_activation_compiler_instance = _IfActivationCompiler(self)
+ return self._if_activation_compiler_instance
+
def _get_source_graph_flat(self) -> Any:
if self._source_graph_flat is None:
self._source_graph_flat = self.graph.nx_graph_flat()
@@ -4822,7 +4808,13 @@ class GraphExecutionState(BaseModel):
]
for gate_id in matching_gate_ids:
gate = self._activation_gate(gate_id)
- if gate.frame != self._expected_execution_ref(gate_id).frame:
+ expected_frame = self._expected_execution_ref(gate_id).frame
+ if (
+ gate.frame.state_id != expected_frame.state_id
+ or gate.frame.frame_id != expected_frame.frame_id
+ or gate.frame.iteration_path != expected_frame.iteration_path
+ or gate.frame.workflow_call_depth != expected_frame.workflow_call_depth
+ ):
return False
if gate.resolved and gate.selected_branch != dependency.branch:
return True
@@ -5766,7 +5758,7 @@ class GraphExecutionState(BaseModel):
return self._if_scheduler().is_deferred_by_unresolved_if(exec_node_id)
def _get_activation_dependencies(self, exec_node_id: str) -> tuple[ActivationDependency, ...]:
- return _get_if_activation_dependencies(self, exec_node_id)
+ return self._if_activation_compiler().get_activation_dependencies(exec_node_id)
def _remove_from_ready_queues(self, exec_node_id: str) -> None:
self._scheduler().remove_from_ready_queues(exec_node_id)
@@ -5810,6 +5802,7 @@ class GraphExecutionState(BaseModel):
self._prepared_exec_metadata = {}
self._prepared_exec_registry = None
self._if_branch_scheduler = None
+ self._if_activation_compiler_instance = None
self._execution_materializer = None
self._execution_scheduler = None
self._generic_graph_scheduler = None
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index 9f1e766ca2..5bf3e6624e 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -11,6 +11,7 @@ from pydantic import ValidationError
from invokeai.app.invocations.logic import IfInvocation
from invokeai.app.invocations.math import AddInvocation
from invokeai.app.invocations.primitives import BooleanInvocation
+from invokeai.app.services.shared import graph as graph_module
from invokeai.app.services.shared.execution_state_migration import (
CURRENT_EXECUTION_STATE_VERSION,
UnsupportedExecutionStateVersionError,
@@ -23,6 +24,7 @@ from invokeai.app.services.shared.graph import (
Graph,
GraphExecutionState,
_ExecutionScheduler,
+ _GenericGraphSchedulerAdapter,
_IfBranchScheduler,
)
@@ -265,6 +267,117 @@ def _execution_identity_projection(state: GraphExecutionState) -> tuple[Any, ...
return references, tokens, effects
+def _execution_edge_projection(state: GraphExecutionState) -> tuple[tuple[str, str, str, str, str], ...]:
+ return tuple(
+ sorted(
+ (
+ state.prepared_source_mapping[edge.source.node_id],
+ edge.source.field,
+ state.prepared_source_mapping[edge.destination.node_id],
+ edge.destination.field,
+ edge.type,
+ )
+ for edge in state.execution_graph.edges
+ )
+ )
+
+
+def _source_edge_projection(graph: Graph) -> tuple[tuple[str, str, str, str, str], ...]:
+ return tuple(
+ sorted(
+ (
+ edge.source.node_id,
+ edge.source.field,
+ edge.destination.node_id,
+ edge.destination.field,
+ edge.type,
+ )
+ for edge in graph.edges
+ )
+ )
+
+
+def _expected_edge_projection(
+ graph: Graph,
+ *,
+ force_compatibility_scheduler: bool,
+ outer_condition: bool,
+ inner_condition: bool,
+) -> tuple[tuple[str, str, str, str, str], ...]:
+ """Project the source graph using the explicit compatibility If lowering rules."""
+ source_edges = _source_edge_projection(graph)
+ if not force_compatibility_scheduler:
+ return source_edges
+
+ # The compatibility scheduler prunes only the inactive input edge at each If that it resolves. If the outer
+ # branch is false, the inner If is never resolved, so its two branch edges remain in the compatibility graph.
+ pruned_edges = {
+ (
+ "outer_false" if outer_condition else "inner_if",
+ "value",
+ "outer_if",
+ "false_input" if outer_condition else "true_input",
+ "default",
+ ),
+ }
+ if outer_condition:
+ pruned_edges.add(
+ (
+ "inner_false" if inner_condition else "inner_true",
+ "value",
+ "inner_if",
+ "false_input" if inner_condition else "true_input",
+ "default",
+ )
+ )
+ return tuple(edge for edge in source_edges if edge not in pruned_edges)
+
+
+def _normalized_indegree(state: GraphExecutionState) -> tuple[tuple[str, tuple[int, ...]], ...]:
+ return tuple(
+ sorted(
+ (
+ source_id,
+ tuple(
+ sorted(
+ degree
+ for execution_id, degree in state.indegree.items()
+ if state.prepared_source_mapping.get(execution_id) == source_id
+ )
+ ),
+ )
+ for source_id in state.graph.nodes
+ )
+ )
+
+
+def _expected_remaining_input_indegree(
+ state: GraphExecutionState,
+ *,
+ force_compatibility_scheduler: bool,
+ outer_condition: bool,
+ inner_condition: bool,
+) -> dict[str, int]:
+ """Calculate remaining indegrees from source edges and durable source completion only."""
+ expected_edges = _expected_edge_projection(
+ state.graph,
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ outer_condition=outer_condition,
+ inner_condition=inner_condition,
+ )
+ completed_sources = {
+ source_id for execution_id, source_id in state.prepared_source_mapping.items() if execution_id in state.executed
+ }
+ return {
+ execution_id: sum(
+ source_id not in completed_sources
+ for source_id, _source_field, destination_id, _destination_field, _edge_type in expected_edges
+ if destination_id == state.prepared_source_mapping[execution_id]
+ )
+ for execution_id in state.prepared_source_mapping
+ }
+
+
def _assert_execution_identity_consistent(state: GraphExecutionState) -> None:
for exec_node_id, reference in state.execution_refs.items():
if exec_node_id not in state.prepared_source_mapping:
@@ -378,6 +491,30 @@ def test_nested_if_fresh_execution_matches_compatibility_scheduler(
== _activation_projection(compatibility_state)
== expected_activation_projection
)
+ assert _execution_edge_projection(generic_state) == _expected_edge_projection(
+ generic_state.graph,
+ force_compatibility_scheduler=False,
+ outer_condition=outer_condition,
+ inner_condition=inner_condition,
+ )
+ assert _execution_edge_projection(compatibility_state) == _expected_edge_projection(
+ compatibility_state.graph,
+ force_compatibility_scheduler=True,
+ outer_condition=outer_condition,
+ inner_condition=inner_condition,
+ )
+ assert dict(generic_state.indegree) == _expected_remaining_input_indegree(
+ generic_state,
+ force_compatibility_scheduler=False,
+ outer_condition=outer_condition,
+ inner_condition=inner_condition,
+ )
+ assert dict(compatibility_state.indegree) == _expected_remaining_input_indegree(
+ compatibility_state,
+ force_compatibility_scheduler=True,
+ outer_condition=outer_condition,
+ inner_condition=inner_condition,
+ )
assert generic_state.is_complete()
assert compatibility_state.is_complete()
@@ -564,11 +701,19 @@ def test_generic_legacy_shaped_if_does_not_prune_or_skip_during_resolution(
def fail_skip(*_: object, **__: object) -> None:
raise AssertionError("generic If execution called mark_exec_node_skipped")
+ def fail_topology(*_: object, **__: object) -> dict[str, set[str]]:
+ raise AssertionError("generic If execution consulted legacy branch topology")
+
+ def fail_legacy_scheduler(*_: object, **__: object) -> None:
+ raise AssertionError("generic If execution instantiated the legacy branch scheduler")
+
def record_deleted_edge(self: GraphExecutionState, edge: Edge) -> None:
deleted_edges.append(edge)
monkeypatch.setattr(_IfBranchScheduler, "_prune_unselected_if_inputs", fail_prune)
monkeypatch.setattr(_IfBranchScheduler, "mark_exec_node_skipped", fail_skip)
+ monkeypatch.setattr(_IfBranchScheduler, "__init__", fail_legacy_scheduler)
+ monkeypatch.setattr(graph_module, "_get_if_branch_exclusive_sources", fail_topology)
monkeypatch.setattr(GraphExecutionState, "_tx_delete_execution_edge", record_deleted_edge)
trace, state = _run_graph(state)
@@ -580,11 +725,127 @@ def test_generic_legacy_shaped_if_does_not_prune_or_skip_during_resolution(
assert deleted_edges == []
+ ("outer_condition", "inner_condition", "expected_trace", "expected_history", "expected_value"),
+ [
+ (
+ True,
+ True,
+ ["outer_condition", "inner_condition", "inner_true", "inner_if", "outer_if", "sink"],
+ [
+ "outer_condition",
+ "outer_false",
+ "inner_condition",
+ "inner_false",
+ "inner_true",
+ "inner_if",
+ "outer_if",
+ "sink",
+ ],
+ 5,
+ ),
+ (
+ True,
+ False,
+ ["outer_condition", "inner_condition", "inner_false", "inner_if", "outer_if", "sink"],
+ [
+ "outer_condition",
+ "outer_false",
+ "inner_condition",
+ "inner_true",
+ "inner_false",
+ "inner_if",
+ "outer_if",
+ "sink",
+ ],
+ 7,
+ ),
+ (
+ False,
+ True,
+ ["outer_condition", "outer_false", "outer_if", "sink"],
+ [
+ "outer_condition",
+ "inner_condition",
+ "inner_true",
+ "inner_false",
+ "inner_if",
+ "outer_false",
+ "outer_if",
+ "sink",
+ ],
+ 11,
+ ),
+ (
+ False,
+ False,
+ ["outer_condition", "outer_false", "outer_if", "sink"],
+ [
+ "outer_condition",
+ "inner_condition",
+ "inner_true",
+ "inner_false",
+ "inner_if",
+ "outer_false",
+ "outer_if",
+ "sink",
+ ],
+ 11,
+ ),
+ ],
+)
+def test_fresh_generic_nested_if_preserves_state_without_legacy_branch_projection(
+ outer_condition: bool,
+ inner_condition: bool,
+ expected_trace: list[str],
+ expected_history: list[str],
+ expected_value: int,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ graph = _nested_if_graph()
+ graph.get_node("outer_condition").value = outer_condition
+ graph.get_node("inner_condition").value = inner_condition
+
+ def fail_legacy_path(*_: object, **__: object) -> None:
+ raise AssertionError("fresh generic If execution used a legacy branch projection")
+
+ generic_retired_nodes: list[str] = []
+ original_discard = _GenericGraphSchedulerAdapter._retire_unselected_node
+
+ def record_generic_discard(adapter: _GenericGraphSchedulerAdapter, exec_node_id: str) -> None:
+ generic_retired_nodes.append(exec_node_id)
+ original_discard(adapter, exec_node_id)
+
+ monkeypatch.setattr(graph_module, "_get_if_branch_exclusive_sources", fail_legacy_path)
+ monkeypatch.setattr(_GenericGraphSchedulerAdapter, "_retire_unselected_node", record_generic_discard)
+ monkeypatch.setattr(_IfBranchScheduler, "_prune_unselected_if_inputs", fail_legacy_path)
+ monkeypatch.setattr(_IfBranchScheduler, "mark_exec_node_skipped", fail_legacy_path)
+ monkeypatch.setattr(GraphExecutionState, "_tx_delete_execution_edge", fail_legacy_path)
+
+ trace, state = _run_graph(GraphExecutionState(graph=graph))
+
+ assert trace == expected_trace
+ assert state.executed_history == expected_history
+ assert set(state.indegree) == set(state.prepared_source_mapping)
+ assert set(state.indegree.values()) == {0}
+ assert state.is_complete()
+ sink_id = next(iter(state.source_prepared_mapping["sink"]))
+ assert state.results[sink_id].value == expected_value
+ assert _execution_edge_projection(state) == _source_edge_projection(graph)
+ expected_retired_sources = (
+ {"inner_false" if inner_condition else "inner_true", "outer_false"}
+ if outer_condition
+ else {"inner_condition", "inner_true", "inner_false", "inner_if"}
+ )
+ assert {state.prepared_source_mapping[exec_id] for exec_id in generic_retired_nodes} == expected_retired_sources
+
+
@pytest.mark.parametrize("stop_after_source", ["outer_if", "inner_false"])
def test_if_partial_state_round_trip_rebuilds_fresh_runtime_and_matches_both_scheduler_paths(
stop_after_source: str,
) -> None:
"""A partial If state round-trips and a fresh runtime matches both scheduler paths."""
+ expected_trace, expected_state = _run_graph(GraphExecutionState(graph=_nested_if_graph()))
partial_projections: list[tuple[Any, ...]] = []
projections: list[tuple[list[str], GraphExecutionState]] = []
@@ -607,6 +868,12 @@ def test_if_partial_state_round_trip_rebuilds_fresh_runtime_and_matches_both_sch
canceled_state.prepared_source_mapping[execution_id] for execution_id in canceled_state.results
}
assert not canceled_state.is_complete()
+ assert dict(canceled_state.indegree) == _expected_remaining_input_indegree(
+ canceled_state,
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ outer_condition=True,
+ inner_condition=False,
+ )
assert _activation_projection(canceled_state) == (
("inner_if", "false_input", "false_input", ()),
("outer_if", "true_input", "true_input", ()),
@@ -622,10 +889,32 @@ def test_if_partial_state_round_trip_rebuilds_fresh_runtime_and_matches_both_sch
assert dump_execution_state(restored_canceled)["execution_effects"] == partial_snapshot["execution_effects"]
assert _execution_identity_projection(restored_canceled) == _execution_identity_projection(restored_expected)
_assert_execution_identity_consistent(restored_canceled)
+ assert dict(restored_canceled.indegree) == _expected_remaining_input_indegree(
+ restored_canceled,
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ outer_condition=True,
+ inner_condition=False,
+ )
partial_projections.append(
(_state_projection(restored_canceled), _execution_identity_projection(restored_canceled))
)
+ remaining_trace, resumed_state = _run_graph(
+ restored_canceled,
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ )
+ assert partial_trace + remaining_trace == expected_trace
+ assert resumed_state.executed_history == expected_state.executed_history
+ assert _state_projection(resumed_state) == _state_projection(expected_state)
+ assert resumed_state.results[next(iter(resumed_state.source_prepared_mapping["sink"]))].value == 7
+ assert resumed_state.is_complete()
+ assert dict(resumed_state.indegree) == _expected_remaining_input_indegree(
+ resumed_state,
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ outer_condition=True,
+ inner_condition=False,
+ )
+
retried_state = GraphExecutionState(graph=canceled_state.graph.model_copy(deep=True))
assert retried_state.id != canceled_state.id
assert retried_state.results == {}