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): route bounded If fanout

JPPhoto6c31797d42a6
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index e9643305c6..ed4eb12f86 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -449,7 +449,9 @@ Workflow-call note:
- `_IfActivationController` Owns fallback runtime `If` admission and compiles opaque, frame-local activation dependency
records for unsupported fresh shapes and legacy prepared nodes. Fresh ordinary-node single-`If` graphs, the bounded
nested pair, the exact bounded three-`If` inner/middle/outer chain, and exactly two or three independent sibling `If`s
- compile those dependencies in graph state. Fresh admission leaves rejected
+ compile those dependencies in graph state. The bounded three-`If` chain also admits one middle-`If` value fan-out to
+ one ordinary leaf consumer; that leaf inherits only the outer branch dependency, not middle-`If` polarity. Other
+ fan-out remains fallback. Fresh admission leaves rejected
branch sources unprepared; legacy skipped-state projections remain loadable.
- Private `graph_if_dependencies.py` compiles fresh activation dependencies, and
`graph_if_runtime.py` records dependencies and evaluates admission against gates and tokens.
@@ -480,7 +482,9 @@ JSON/model round trip. Rehydration reconstructs prepared exec metadata, cached i
gate state from condition results or persisted activation tokens, non-empty iteration streams from durable effects and
legacy Iterate results, explicit empty-source closes, For continuation identity, and ready queues from
`execution_graph`, `indegree`, `executed`, and `results`. Activation tokens persist; private `ActivationGate` runtime
-state does not and is reconstructed from condition results or persisted activation tokens. Before token validation,
+state does not and is reconstructed from condition results or persisted activation tokens. Pending selected `If` inputs
+remain excluded from ready-queue projection during rehydration, preserving ready-node order across checkpoints before
+the pending `If` is admitted. Before token validation,
missing legacy iteration-path metadata is rebuilt from the prepared execution graph. Persisted activation identity is
then validated fail-closed
against prepared owners, derived references, declared activation fields, canonical ids, and known frame fields; extra
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 16cd8639cd..1be291d44a 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -2210,7 +2210,7 @@ class GraphExecutionState(BaseModel):
def _try_resolve_if_node(self, exec_node_id: str, *, enqueue: bool = True) -> None:
scheduler = self._execution_scheduler
if isinstance(scheduler, _GenericGraphSchedulerAdapter):
- scheduler.resolve_if_node(exec_node_id)
+ scheduler.resolve_if_node(exec_node_id, enqueue=enqueue)
return
if exec_node_id in self._resolved_if_exec_branches:
@@ -2257,6 +2257,7 @@ class GraphExecutionState(BaseModel):
def _prepare_until_node_ready(self) -> Optional[BaseInvocation]:
base_graph = self._get_source_graph_flat()
self._materializer()._attach_pending_if_inputs()
+ self._rehydrate_ready_queues()
next_node = self._get_next_node()
if next_node is not None:
return next_node
@@ -2584,6 +2585,8 @@ class GraphExecutionState(BaseModel):
for exec_node_id in nx.topological_sort(execution_graph):
if exec_node_id in self.executed:
continue
+ if exec_node_id in self._pending_if_exec_nodes:
+ continue
if self.indegree.get(exec_node_id) != 0:
continue
self._enqueue_if_ready(exec_node_id)
@@ -2593,8 +2596,8 @@ class GraphExecutionState(BaseModel):
self._rehydrate_prepared_exec_metadata()
self._rehydrate_resolved_if_exec_branches()
self._rehydrate_generic_runtime_state()
- self._materializer()._attach_pending_if_inputs()
self._rehydrate_ready_queues()
+ self._materializer()._attach_pending_if_inputs(enqueue=False)
def model_post_init(self, __context: Any) -> None:
if isinstance(__context, dict) and "execution_effects_persisted" in __context:
diff --git a/invokeai/app/services/shared/graph_if_dependencies.py b/invokeai/app/services/shared/graph_if_dependencies.py
index bb3ffc3d23..f7d91e815d 100644
--- a/invokeai/app/services/shared/graph_if_dependencies.py
+++ b/invokeai/app/services/shared/graph_if_dependencies.py
@@ -95,16 +95,40 @@ def _can_use_fresh_flat_if_activation(state: "GraphExecutionState") -> bool:
return False
current_if_id = next(iter(chain_start_ids))
+ chain_path = [current_if_id]
for _ in range(len(nested_edges)):
nested_edge = nested_edge_by_source.get(current_if_id)
if nested_edge is None:
return False
- if any(edge.source.node_id == current_if_id and edge != nested_edge for edge in state.graph.edges):
- return False
- current_if_id = nested_edge.destination.node_id
+ next_if_id = nested_edge.destination.node_id
+ current_if_id = next_if_id
+ chain_path.append(current_if_id)
if current_if_id not in chain_end_ids:
return False
+ middle_if_id = chain_path[-2]
+ middle_nested_edge = nested_edge_by_source[middle_if_id]
+ for chain_source_id in chain_path[:-1]:
+ if chain_source_id == middle_if_id and len(if_nodes) == 3:
+ continue
+ nested_edge = nested_edge_by_source[chain_source_id]
+ if any(edge.source.node_id == chain_source_id and edge != nested_edge for edge in state.graph.edges):
+ return False
+ middle_extra_edges = [
+ edge for edge in state.graph.edges if edge.source.node_id == middle_if_id and edge != middle_nested_edge
+ ]
+ if len(middle_extra_edges) > 1:
+ return False
+ if middle_extra_edges:
+ fanout_edge = middle_extra_edges[0]
+ fanout_node = state.graph.get_node(fanout_edge.destination.node_id)
+ if (
+ fanout_edge.source.field != "value"
+ or isinstance(fanout_node, IfInvocation)
+ or state.graph._get_output_edges(fanout_node.id)
+ ):
+ return False
+
expected_input_fields = {"condition", "true_input", "false_input"}
for if_node in if_nodes:
input_edges = state.graph._get_input_edges(if_node.id)
@@ -131,6 +155,14 @@ def _get_fresh_if_branch_sources(state: "GraphExecutionState", if_node_id: str,
branch_sources = set(direct_sources)
for source_node_id in direct_sources:
branch_sources.update(nx.ancestors(source_graph, source_node_id))
+ source_node = state.graph.get_node(source_node_id)
+ if isinstance(source_node, IfInvocation):
+ branch_sources.update(
+ edge.destination.node_id
+ for edge in state.graph._get_output_edges(source_node_id)
+ if not isinstance(state.graph.get_node(edge.destination.node_id), IfInvocation)
+ and not state.graph._get_output_edges(edge.destination.node_id)
+ )
changed = True
while changed:
diff --git a/invokeai/app/services/shared/graph_materializer.py b/invokeai/app/services/shared/graph_materializer.py
index 3c89257b37..f3c0b330cf 100644
--- a/invokeai/app/services/shared/graph_materializer.py
+++ b/invokeai/app/services/shared/graph_materializer.py
@@ -1188,7 +1188,7 @@ class _ExecutionMaterializer:
for edge in self._state.graph._get_input_edges(node_id, "condition")
)
- def _attach_pending_if_inputs(self) -> None:
+ def _attach_pending_if_inputs(self, *, enqueue: bool = True) -> None:
"""Attach only the selected branch edge to condition-ready If executions."""
source_graph = self._state._get_source_graph_flat()
@@ -1210,7 +1210,8 @@ class _ExecutionMaterializer:
edge.destination.field == selected_field
for edge in self._state.execution_graph._get_input_edges(exec_node_id)
):
- self._state._tx_discard_set(self._state._pending_if_exec_nodes, exec_node_id)
+ if enqueue:
+ self._state._tx_discard_set(self._state._pending_if_exec_nodes, exec_node_id)
continue
source_if_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
@@ -1249,11 +1250,13 @@ class _ExecutionMaterializer:
input_edges = self._state.execution_graph._get_input_edges(exec_node_id)
unmet = sum(1 for edge in input_edges if edge.source.node_id not in self._state.executed)
self._state._tx_set_mapping(self._state.indegree, exec_node_id, unmet)
- self._state._tx_discard_set(self._state._pending_if_exec_nodes, exec_node_id)
+ if enqueue:
+ self._state._tx_discard_set(self._state._pending_if_exec_nodes, exec_node_id)
scheduler = self._state._scheduler()
if self._state._is_generic_graph_scheduler(scheduler):
scheduler.register_node(exec_node_id)
- self._state._enqueue_if_ready(exec_node_id)
+ if enqueue:
+ self._state._enqueue_if_ready(exec_node_id)
def iterator_graph(self, base: Optional["nx.DiGraph"] = None) -> "nx.DiGraph":
"""Gets a DiGraph with edges to collectors removed so an ancestor search produces all active iterators for any node"""
diff --git a/invokeai/app/services/shared/graph_scheduler.py b/invokeai/app/services/shared/graph_scheduler.py
index b6ace14a74..d593a728b0 100644
--- a/invokeai/app/services/shared/graph_scheduler.py
+++ b/invokeai/app/services/shared/graph_scheduler.py
@@ -386,7 +386,7 @@ class _GenericGraphSchedulerAdapter:
if source_node_id not in self._state.executed:
self._state._mark_source_executed(source_node_id)
- def resolve_if_node(self, exec_node_id: str) -> None:
+ def resolve_if_node(self, exec_node_id: str, *, enqueue: bool = True) -> None:
"""Resolve legacy If inputs without pruning graph edges or using type-specific skips."""
if exec_node_id in self._state._resolved_if_exec_branches:
@@ -403,7 +403,8 @@ class _GenericGraphSchedulerAdapter:
self._state._record_compatibility_activation_token(exec_node_id, selected_field)
self._discard_rejected_nodes()
self._sync_indegree()
- self._project_ready_nodes()
+ if enqueue:
+ self._project_ready_nodes()
def _discard_rejected_node(self, exec_node_id: str) -> None:
node = self._scheduler.plan.nodes.get(exec_node_id)
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index fce9eee064..2c78141e89 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -172,6 +172,42 @@ def _three_nested_if_graph(
return graph
+def _three_nested_if_graph_with_middle_leaf_fanout(**kwargs: Any) -> Graph:
+ graph = _three_nested_if_graph(**kwargs)
+ graph.add_node(AddInvocation(id="middle_side_consumer", b=1))
+ graph.add_edge(create_edge("middle_if", "value", "middle_side_consumer", "a"))
+ return graph
+
+
+def _three_nested_if_graph_with_middle_leaf_fanout_and_shared_ancestor(**kwargs: Any) -> Graph:
+ graph = _three_nested_if_graph_with_middle_leaf_fanout(**kwargs)
+ graph.add_node(AddInvocation(id="shared", a=1, b=1))
+ graph.add_edge(create_edge("shared", "value", "inner_true", "a"))
+ graph.add_edge(create_edge("shared", "value", "inner_false", "a"))
+ return graph
+
+
+def _three_nested_if_graph_with_extra_middle_fanout() -> Graph:
+ graph = _three_nested_if_graph_with_middle_leaf_fanout()
+ graph.add_node(AddInvocation(id="middle_side_consumer_2", b=2))
+ graph.add_edge(create_edge("middle_if", "value", "middle_side_consumer_2", "a"))
+ return graph
+
+
+def _three_nested_if_graph_with_non_leaf_middle_fanout() -> Graph:
+ graph = _three_nested_if_graph_with_middle_leaf_fanout()
+ graph.add_node(AddInvocation(id="middle_side_tail", b=2))
+ graph.add_edge(create_edge("middle_side_consumer", "value", "middle_side_tail", "a"))
+ return graph
+
+
+def _three_nested_if_graph_with_inner_fanout() -> Graph:
+ graph = _three_nested_if_graph_with_middle_leaf_fanout()
+ graph.add_node(AddInvocation(id="inner_side_consumer", b=2))
+ graph.add_edge(create_edge("inner_if", "value", "inner_side_consumer", "a"))
+ return graph
+
+
def _three_nested_if_graph_with_shared_ancestor(**kwargs: bool) -> Graph:
graph = _three_nested_if_graph(**kwargs)
graph.add_node(AddInvocation(id="shared", a=1, b=1))
@@ -4496,6 +4532,226 @@ def test_fresh_three_nested_ifs_shared_ancestor_isolated_and_checkpoint_resumes(
assert _activation_projection(resumed_state) == _activation_projection(expected_state)
[email protected]("force_compatibility_scheduler", [False, True])
+ ("outer_condition", "middle_condition", "inner_condition", "expected_trace", "expected_value"),
+ [
+ (
+ True,
+ True,
+ True,
+ [
+ "outer_condition",
+ "middle_condition",
+ "inner_condition",
+ "inner_true",
+ "inner_if",
+ "middle_if",
+ "middle_side_consumer",
+ "outer_if",
+ "sink",
+ ],
+ 5,
+ ),
+ (
+ True,
+ True,
+ False,
+ [
+ "outer_condition",
+ "middle_condition",
+ "inner_condition",
+ "inner_false",
+ "inner_if",
+ "middle_if",
+ "middle_side_consumer",
+ "outer_if",
+ "sink",
+ ],
+ 7,
+ ),
+ (
+ True,
+ False,
+ True,
+ [
+ "outer_condition",
+ "middle_condition",
+ "middle_false",
+ "middle_if",
+ "middle_side_consumer",
+ "outer_if",
+ "sink",
+ ],
+ 11,
+ ),
+ (
+ True,
+ False,
+ False,
+ [
+ "outer_condition",
+ "middle_condition",
+ "middle_false",
+ "middle_if",
+ "middle_side_consumer",
+ "outer_if",
+ "sink",
+ ],
+ 11,
+ ),
+ (False, True, True, ["outer_condition", "outer_false", "outer_if", "sink"], 21),
+ (False, True, False, ["outer_condition", "outer_false", "outer_if", "sink"], 21),
+ (False, False, True, ["outer_condition", "outer_false", "outer_if", "sink"], 21),
+ (False, False, False, ["outer_condition", "outer_false", "outer_if", "sink"], 21),
+ ],
+)
+def test_fresh_three_nested_middle_leaf_fanout_matches_compatibility(
+ force_compatibility_scheduler: bool,
+ outer_condition: bool,
+ middle_condition: bool,
+ inner_condition: bool,
+ expected_trace: list[str],
+ expected_value: int,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:
+ raise AssertionError("fresh middle fanout If used controller-owned branch analysis")
+
+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)
+ graph = _three_nested_if_graph_with_middle_leaf_fanout(
+ outer_condition=outer_condition,
+ middle_condition=middle_condition,
+ inner_condition=inner_condition,
+ )
+ state = GraphExecutionState(graph=graph)
+
+ assert state._can_use_fresh_flat_if_activation()
+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)
+
+ assert trace == expected_trace
+ assert set(state.source_prepared_mapping) == set(expected_trace)
+ assert state.results[next(iter(state.source_prepared_mapping["sink"]))].value == expected_value
+ if outer_condition:
+ side_consumer_id = next(iter(state.source_prepared_mapping["middle_side_consumer"]))
+ expected_side_value = expected_value
+ assert state.results[side_consumer_id].value == expected_side_value
+ else:
+ assert "middle_side_consumer" not in state.source_prepared_mapping
+ assert state.is_complete()
+
+
[email protected]("middle_branch", ["true_input", "false_input"])
[email protected]("outer_branch", ["true_input", "false_input"])
+def test_fresh_three_nested_middle_leaf_fanout_supports_direct_parent_branch_ports(
+ middle_branch: str,
+ outer_branch: str,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:
+ raise AssertionError("fresh middle fanout If used controller-owned branch analysis")
+
+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)
+ graph = _three_nested_if_graph_with_middle_leaf_fanout(
+ outer_condition=outer_branch == "true_input",
+ middle_condition=middle_branch == "true_input",
+ inner_condition=True,
+ middle_branch=middle_branch,
+ outer_branch=outer_branch,
+ )
+ expected_trace = [
+ "outer_condition",
+ "middle_condition",
+ "inner_condition",
+ "inner_true",
+ "inner_if",
+ "middle_if",
+ "middle_side_consumer",
+ "outer_if",
+ "sink",
+ ]
+ runs: list[tuple[list[str], GraphExecutionState]] = []
+ for force_compatibility_scheduler in (False, True):
+ trace, state = _run_graph(
+ GraphExecutionState(graph=graph.model_copy(deep=True)),
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ )
+ runs.append((trace, state))
+ assert trace == expected_trace
+ assert state.is_complete()
+
+ assert runs[0][0] == runs[1][0]
+ assert _state_projection(runs[0][1]) == _state_projection(runs[1][1])
+
+
[email protected]("force_compatibility_scheduler", [False, True])
[email protected]("stop_after", range(1, 11))
+def test_fresh_three_nested_middle_leaf_fanout_shared_checkpoint_resumes(
+ force_compatibility_scheduler: bool,
+ stop_after: int,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:
+ raise AssertionError("fresh middle fanout If used controller-owned branch analysis")
+
+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)
+ graph = _three_nested_if_graph_with_middle_leaf_fanout_and_shared_ancestor(
+ outer_condition=True,
+ middle_condition=True,
+ inner_condition=False,
+ )
+ expected_trace, expected_state = _run_graph(GraphExecutionState(graph=graph.model_copy(deep=True)))
+ checkpoint_trace, checkpoint_state = _run_graph(
+ GraphExecutionState(graph=graph.model_copy(deep=True)),
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ stop_after=stop_after,
+ )
+ restored = load_execution_state(dump_execution_state(checkpoint_state))
+ if force_compatibility_scheduler:
+ _restore_compatibility_scheduler(restored)
+ resumed_trace, resumed_state = _run_graph(restored, force_compatibility_scheduler=force_compatibility_scheduler)
+
+ assert checkpoint_trace + resumed_trace == expected_trace
+ assert resumed_state.executed_history == expected_state.executed_history
+ assert resumed_state.executed_history.count("shared") == 1
+ assert resumed_state.executed_history.count("middle_side_consumer") == 1
+ assert _state_projection(resumed_state) == _state_projection(expected_state)
+ assert _activation_projection(resumed_state) == _activation_projection(expected_state)
+ assert resumed_state.is_complete()
+
+
+ "graph_factory",
+ [
+ pytest.param(_three_nested_if_graph_with_extra_middle_fanout, id="extra-middle-fanout"),
+ pytest.param(_three_nested_if_graph_with_non_leaf_middle_fanout, id="non-leaf-middle-fanout"),
+ pytest.param(_three_nested_if_graph_with_inner_fanout, id="inner-fanout"),
+ ],
+)
+def test_fresh_three_nested_invalid_fanout_shapes_use_controller_fallback(
+ graph_factory: Any,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ branch_analysis_calls: list[tuple[str, str]] = []
+ original_branch_sources = graph_module._IfActivationController._branch_sources
+
+ def record_branch_analysis(
+ controller: graph_module._IfActivationController,
+ if_node_id: str,
+ branch_field: str,
+ source_graph: Any,
+ ) -> set[str]:
+ branch_analysis_calls.append((if_node_id, branch_field))
+ return original_branch_sources(controller, if_node_id, branch_field, source_graph)
+
+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", record_branch_analysis)
+ state = GraphExecutionState(graph=graph_factory())
+
+ assert not state._can_use_fresh_flat_if_activation()
+ state._get_source_activation_dependencies("inner_true")
+ assert branch_analysis_calls
+
+
@pytest.mark.parametrize(
("outer_condition", "inner_condition", "expected_value"),
[(True, True, 5), (True, False, 6), (False, True, 11), (False, False, 11)],
diff --git a/tests/app/services/shared/test_graph_if_dependencies.py b/tests/app/services/shared/test_graph_if_dependencies.py
index 7ea5baf7c8..ccf6164bb7 100644
--- a/tests/app/services/shared/test_graph_if_dependencies.py
+++ b/tests/app/services/shared/test_graph_if_dependencies.py
@@ -103,15 +103,21 @@ def _sibling_if_graph_with_count(count: int) -> Graph:
return graph
-def _three_nested_if_graph() -> Graph:
+def _three_nested_if_graph(*, middle_branch: str = "true_input", outer_branch: str = "true_input") -> Graph:
+ assert middle_branch in {"true_input", "false_input"}
+ assert outer_branch in {"true_input", "false_input"}
+ middle_other_branch = "false_input" if middle_branch == "true_input" else "true_input"
+ outer_other_branch = "false_input" if outer_branch == "true_input" else "true_input"
+ middle_other_id = "middle_false" if middle_branch == "true_input" else "middle_true"
+ outer_other_id = "outer_false" if outer_branch == "true_input" else "outer_true"
graph = Graph()
graph.add_node(BooleanInvocation(id="outer_condition", value=True))
graph.add_node(BooleanInvocation(id="middle_condition", value=False))
graph.add_node(BooleanInvocation(id="inner_condition", value=True))
graph.add_node(AddInvocation(id="inner_true", a=2, b=2))
graph.add_node(AddInvocation(id="inner_false", a=3, b=3))
- graph.add_node(AddInvocation(id="middle_false", a=10, b=0))
- graph.add_node(AddInvocation(id="outer_false", a=20, b=0))
+ graph.add_node(AddInvocation(id=middle_other_id, a=10, b=0))
+ graph.add_node(AddInvocation(id=outer_other_id, a=20, b=0))
graph.add_node(IfInvocation(id="inner_if"))
graph.add_node(IfInvocation(id="middle_if"))
graph.add_node(IfInvocation(id="outer_if"))
@@ -120,11 +126,11 @@ def _three_nested_if_graph() -> Graph:
graph.add_edge(_edge("inner_true", "value", "inner_if", "true_input"))
graph.add_edge(_edge("inner_false", "value", "inner_if", "false_input"))
graph.add_edge(_edge("middle_condition", "value", "middle_if", "condition"))
- graph.add_edge(_edge("inner_if", "value", "middle_if", "true_input"))
- graph.add_edge(_edge("middle_false", "value", "middle_if", "false_input"))
+ graph.add_edge(_edge("inner_if", "value", "middle_if", middle_branch))
+ graph.add_edge(_edge(middle_other_id, "value", "middle_if", middle_other_branch))
graph.add_edge(_edge("outer_condition", "value", "outer_if", "condition"))
- graph.add_edge(_edge("middle_if", "value", "outer_if", "true_input"))
- graph.add_edge(_edge("outer_false", "value", "outer_if", "false_input"))
+ graph.add_edge(_edge("middle_if", "value", "outer_if", outer_branch))
+ graph.add_edge(_edge(outer_other_id, "value", "outer_if", outer_other_branch))
graph.add_edge(_edge("outer_if", "value", "sink", "a"))
return graph
@@ -150,6 +156,27 @@ def _three_nested_if_fanout_graph() -> Graph:
return graph
+def _three_nested_if_extra_fanout_graph() -> Graph:
+ graph = _three_nested_if_fanout_graph()
+ graph.add_node(AddInvocation(id="middle_side_consumer_2", b=2))
+ graph.add_edge(_edge("middle_if", "value", "middle_side_consumer_2", "a"))
+ return graph
+
+
+def _three_nested_if_non_leaf_fanout_graph() -> Graph:
+ graph = _three_nested_if_fanout_graph()
+ graph.add_node(AddInvocation(id="middle_side_tail", b=2))
+ graph.add_edge(_edge("middle_side_consumer", "value", "middle_side_tail", "a"))
+ return graph
+
+
+def _three_nested_if_inner_fanout_graph() -> Graph:
+ graph = _three_nested_if_fanout_graph()
+ graph.add_node(AddInvocation(id="inner_side_consumer", b=2))
+ graph.add_edge(_edge("inner_if", "value", "inner_side_consumer", "a"))
+ return graph
+
+
def _indirectly_connected_if_graph() -> Graph:
graph = Graph()
graph.add_node(BooleanInvocation(id="first_condition", value=True))
@@ -358,7 +385,9 @@ def test_three_independent_sibling_ifs_admit_owner_local_frame_local_dependencie
pytest.param(lambda: _sibling_if_graph_with_count(4), "first_true", id="four-sibling-ifs"),
pytest.param(_indirectly_connected_if_graph, "first_true", id="indirect-chain"),
pytest.param(_four_nested_if_graph, "inner_true", id="four-nested-ifs"),
- pytest.param(_three_nested_if_fanout_graph, "inner_true", id="three-nested-if-fanout"),
+ pytest.param(_three_nested_if_extra_fanout_graph, "inner_true", id="three-nested-if-extra-fanout"),
+ pytest.param(_three_nested_if_non_leaf_fanout_graph, "inner_true", id="three-nested-if-non-leaf-fanout"),
+ pytest.param(_three_nested_if_inner_fanout_graph, "inner_true", id="three-nested-if-inner-fanout"),
],
)
def test_unsupported_if_shapes_use_controller_fallback(
@@ -415,6 +444,48 @@ def test_three_nested_ifs_admit_owner_and_frame_dependencies(
)
+def test_three_nested_ifs_with_one_middle_leaf_fanout_admit_exact_dependencies() -> None:
+ state = GraphExecutionState(graph=_three_nested_if_fanout_graph())
+
+ assert state._can_use_fresh_flat_if_activation()
+ assert state._get_source_activation_dependencies("inner_true", (1,)) == (
+ ActivationDependency(owner_id="inner_if", branch="true_input", frame=(1,)),
+ ActivationDependency(owner_id="middle_if", branch="true_input", frame=(1,)),
+ ActivationDependency(owner_id="outer_if", branch="true_input", frame=(1,)),
+ )
+ assert state._get_source_activation_dependencies("middle_false", (2,)) == (
+ ActivationDependency(owner_id="middle_if", branch="false_input", frame=(2,)),
+ ActivationDependency(owner_id="outer_if", branch="true_input", frame=(2,)),
+ )
+ assert state._get_source_activation_dependencies("outer_false", (3,)) == (
+ ActivationDependency(owner_id="outer_if", branch="false_input", frame=(3,)),
+ )
+ assert state._get_source_activation_dependencies("middle_side_consumer", (4,)) == (
+ ActivationDependency(owner_id="outer_if", branch="true_input", frame=(4,)),
+ )
+
+
[email protected]("middle_branch", ["true_input", "false_input"])
[email protected]("outer_branch", ["true_input", "false_input"])
+def test_three_nested_ifs_with_one_middle_leaf_fanout_preserve_parent_branch_ports(
+ middle_branch: str, outer_branch: str
+) -> None:
+ state = GraphExecutionState(
+ graph=_three_nested_if_graph(
+ middle_branch=middle_branch,
+ outer_branch=outer_branch,
+ )
+ )
+ # This fixture does not include fan-out. Add the exact permitted side leaf.
+ state.graph.add_node(AddInvocation(id="middle_side_consumer", b=1))
+ state.graph.add_edge(_edge("middle_if", "value", "middle_side_consumer", "a"))
+
+ assert state._can_use_fresh_flat_if_activation()
+ assert state._get_source_activation_dependencies("middle_side_consumer", (4,)) == (
+ ActivationDependency(owner_id="outer_if", branch=outer_branch, frame=(4,)),
+ )
+
+
def test_indirectly_connected_ifs_retain_controller_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
state = GraphExecutionState(graph=_indirectly_connected_if_graph())
calls: list[tuple[str, str]] = []