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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(execution): route exact four nested Ifs
JPPhoto3e159d59c05f
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.mdindex 8bfcaec6a4..a3775e5cb3 100644--- a/docs/src/content/docs/contributing/loop-nodes.md+++ b/docs/src/content/docs/contributing/loop-nodes.md@@ -168,14 +168,15 @@ valid. A loaded terminal legacy state may retain its empty in-memory ledger for`dump_execution_state()` upgrades missing loop buckets in the versioned snapshot.`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. Fresh graphs with one ordinary-node-`If`, the exact one-level nested shape with two `If` nodes where the inner value feeds one outer branch and has no-other consumer, the exact bounded three-`If` chain with direct inner-to-middle-to-outer branch edges, or exactly two-or exactly three independent ordinary-node sibling `If`s compile opaque, frame-local activation dependencies in graph-state. The three-`If` admission requires `default` edges, all branch inputs (`condition`, `true_input`, `false_input`) on-each `If`, and no output from inner or middle `If` except its direct nested branch edge. Four-or-more nesting, fan-out,-mixed, loop-containing, saved-workflow, legacy, and four-or-more sibling shapes use the compatibility scheduler with the-dedicated `_IfActivationController` fallback. Legacy snapshots retain their generic compatibility+selected branch, and the graph state validates and persists it after invocation. Fresh graphs with one ordinary-node `If`,+the exact one-level nested shape with two `If` nodes where the inner value feeds one outer branch and has no other+consumer, the exact bounded three-`If` chain with direct inner-to-middle-to-outer branch edges, the exact four-`If` nested+chain, or exactly two, exactly three, or exactly four independent ordinary-node sibling `If`s compile opaque, frame-local+activation dependencies in graph state. The three- and four-`If` admissions require `default` edges, all branch inputs+(`condition`, `true_input`, `false_input`) on each `If`, and no output from inner or middle `If` except its direct nested+branch edge; the four-`If` chain permits no extra output fan-out. Five-or-more nested `If`s, other fan-out, mixed,+loop-containing, saved-workflow, legacy, and five-or-more sibling shapes use the compatibility scheduler with the dedicated+`_IfActivationController` fallback. Legacy snapshots retain their generic compatibilityprojection. Legacyskipped-state projection remains only for old snapshots. Fresh materialization prepares the condition boundary,resolves the activation token, and attaches only the selected branch input; unselected branch nodes remain unprepared.diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex b4a7795443..19ccd14304 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -11,13 +11,17 @@ instead of mutating the source graph. Ordinary static DAGs and legacy-shaped `Ifand deterministic `ExecutionScheduler` in `execution_engine/scheduler.py`. Fresh graphs with one ordinary-node `If`, theexact one-level nested shape with two `If` nodes where the inner value feeds one outer branch and has no otherconsumer, the exact bounded three-`If` chain where inner `value` feeds a middle branch and middle `value` feeds an outer-branch, or exactly two, exactly three, or exactly four independent ordinary-node sibling `If`s compile opaque, frame-local activation+branch, the exact four-`If` nested chain where each `If.value` feeds one+branch port of the next `If`, or exactly two, exactly three, or exactly four+independent ordinary-node sibling `If`s compile opaque, frame-local activationdependencies in `GraphExecutionState`; unsupported fresh shapes use the compatibility scheduler with the dedicated`_IfActivationController` fallback, while legacy snapshots retain their generic compatibility projection.Current fresh sibling support includes exactly four independent `If`s with no nesting, fan-out, or other control-flownodes. The bounded three-`If` chain requires direct `default` edges, all three `If`s to have `condition`, `true_input`,-and `false_input` inputs, and inner/middle `If`s to have no output except their direct nested branch edge. Four or more-nested `If`s, other fan-out, mixed, loop-containing, saved-workflow, legacy, and five-or-more sibling shapes remain on the+and `false_input` inputs, and inner/middle `If`s to have no output except their direct nested branch edge. The exact+four-`If` chain has the same input and direct-edge requirements, with no extra+output fan-out. Five or more nested `If`s, other fan-out, mixed, loop-containing,+saved-workflow, legacy, and five-or-more sibling shapes remain on thecompatibility fallback. Legacy snapshots retain their generic compatibility projection and legacy skipped-state metadata.Legacy skipped-state projection remains only for old snapshots. Fresh `If` materialization prepares the condition boundary first,resolves the activation token, and attaches only the selected branch input.@@ -268,9 +272,10 @@ rehydration, every activation token is bound to a currently prepared owner and ideclared port, value, canonical token id, mapping key, and known frame fields must match. Unknown extra frame metadataremains forward-compatible.For a fresh generic `If` graph with one ordinary-node `If`, the exact one-level nested shape described above, the exact-bounded three-`If` inner/middle/outer chain, or exactly two, exactly three, or exactly four independent sibling `If`s,+bounded three-`If` inner/middle/outer chain, the exact four-`If` nested chain,+or exactly two, exactly three, or exactly four independent sibling `If`s,`GraphExecutionState` compiles opaque, frame-local activation-dependency records privately on each branch-local plan-node. Four-or-more nesting, five-or-more sibling `If`s, other fan-out, mixed, loop-containing, and saved-workflow shapes use+node. Five-or-more nesting, five-or-more sibling `If`s, other fan-out, mixed, loop-containing, and saved-workflow shapes usethe compatibility scheduler and `_IfActivationController` for the same records; legacy snapshots retain the genericcompatibility projection and legacy skipped-state metadata. The controllerremains the fallback runtime dependency owner, and the schedulers no longer call a legacy compiler. Fresh materialization prepares the condition boundary, resolves the activation token,@@ -462,7 +467,7 @@ Workflow-call note:points. The planner continues to use the graph state's journal, mappings, caches, and scheduler.- `_IfActivationController` Owns fallback runtime `If` admission and compiles opaque, frame-local activation dependencyrecords 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, exactly three, or exactly four independent sibling `If`s+ nested pair, the exact bounded three-`If` inner/middle/outer chain, the exact four-`If` nested chain, and exactly two, exactly three, or exactly four independent sibling `If`scompile those dependencies in graph state. The bounded three-`If` chain also admits one middle-`If` value fan-out toone ordinary leaf consumer; that leaf inherits only the outer branch dependency, not middle-`If` polarity. Otherfan-out remains fallback. Fresh admission leaves rejecteddiff --git a/invokeai/app/services/shared/graph_if_dependencies.py b/invokeai/app/services/shared/graph_if_dependencies.pyindex ef77682396..b13596a5a3 100644--- a/invokeai/app/services/shared/graph_if_dependencies.py+++ b/invokeai/app/services/shared/graph_if_dependencies.py@@ -77,7 +77,7 @@ def _can_use_fresh_flat_if_activation(state: "GraphExecutionState") -> bool:return Falseif any(edge.source.node_id in if_node_ids for edge in input_edges):return False- elif len(if_nodes) in {2, 3} and len(nested_edges) == len(if_nodes) - 1:+ elif len(if_nodes) in {2, 3, 4} and len(nested_edges) == len(if_nodes) - 1:if any(edge.source.field != "value" or edge.destination.field not in {"true_input", "false_input"}for edge in nested_edges@@ -105,6 +105,8 @@ def _can_use_fresh_flat_if_activation(state: "GraphExecutionState") -> bool:chain_path.append(current_if_id)if current_if_id not in chain_end_ids:return False+ if len(state.graph._get_output_edges(current_if_id)) > 1:+ return Falsemiddle_if_id = chain_path[-2]middle_nested_edge = nested_edge_by_source[middle_if_id]diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.pyindex 968fc705cf..8fe051d47e 100644--- a/tests/app/services/shared/test_execution_engine_differential.py+++ b/tests/app/services/shared/test_execution_engine_differential.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+from itertools import productfrom pathlib import Pathfrom typing import Anyfrom unittest.mock import Mock, patch@@ -216,6 +217,96 @@ def _three_nested_if_graph_with_shared_ancestor(**kwargs: bool) -> Graph:return graph+def _four_nested_if_graph(+ *,+ root_condition: bool = True,+ outer_condition: bool = True,+ middle_condition: bool = True,+ inner_condition: bool = True,+ middle_branch: str = "true_input",+ outer_branch: str = "true_input",+ root_branch: str = "true_input",+ with_shared_ancestor: bool = False,+) -> Graph:+ branches = (middle_branch, outer_branch, root_branch)+ assert all(branch in {"true_input", "false_input"} for branch in branches)++ graph = Graph()+ graph.add_node(BooleanInvocation(id="root_condition", value=root_condition))+ graph.add_node(BooleanInvocation(id="outer_condition", value=outer_condition))+ graph.add_node(BooleanInvocation(id="middle_condition", value=middle_condition))+ graph.add_node(BooleanInvocation(id="inner_condition", value=inner_condition))+ graph.add_node(AddInvocation(id="inner_true", b=2))+ graph.add_node(AddInvocation(id="inner_false", b=3))+ graph.add_node(+ AddInvocation(+ id="middle_false" if middle_branch == "true_input" else "middle_true",+ a=10,+ b=0,+ )+ )+ graph.add_node(+ AddInvocation(+ id="outer_false" if outer_branch == "true_input" else "outer_true",+ a=20,+ b=0,+ )+ )+ graph.add_node(+ AddInvocation(+ id="root_false" if root_branch == "true_input" else "root_true",+ a=30,+ b=0,+ )+ )+ graph.add_node(IfInvocation(id="inner_if"))+ graph.add_node(IfInvocation(id="middle_if"))+ graph.add_node(IfInvocation(id="outer_if"))+ graph.add_node(IfInvocation(id="root_if"))+ graph.add_node(AddInvocation(id="sink", b=1))++ def connect(source: str, source_field: str, destination: str, destination_field: str) -> None:+ graph.add_edge(create_edge(source, source_field, destination, destination_field))++ connect("root_condition", "value", "root_if", "condition")+ connect("outer_condition", "value", "outer_if", "condition")+ connect("middle_condition", "value", "middle_if", "condition")+ connect("inner_condition", "value", "inner_if", "condition")+ connect("inner_true", "value", "inner_if", "true_input")+ connect("inner_false", "value", "inner_if", "false_input")+ connect("inner_if", "value", "middle_if", middle_branch)+ connect(+ "middle_false" if middle_branch == "true_input" else "middle_true",+ "value",+ "middle_if",+ "false_input" if middle_branch == "true_input" else "true_input",+ )+ connect("middle_if", "value", "outer_if", outer_branch)+ connect(+ "outer_false" if outer_branch == "true_input" else "outer_true",+ "value",+ "outer_if",+ "false_input" if outer_branch == "true_input" else "true_input",+ )+ connect("outer_if", "value", "root_if", root_branch)+ connect(+ "root_false" if root_branch == "true_input" else "root_true",+ "value",+ "root_if",+ "false_input" if root_branch == "true_input" else "true_input",+ )+ connect("root_if", "value", "sink", "a")++ if with_shared_ancestor:+ graph.add_node(AddInvocation(id="shared", a=1, b=1))+ connect("shared", "value", "inner_true", "a")+ connect("shared", "value", "inner_false", "a")+ else:+ graph.get_node("inner_true").a = 2+ graph.get_node("inner_false").a = 3+ return graph++def _flat_if_graph(*, condition: bool = True) -> Graph:graph = Graph()graph.add_node(BooleanInvocation(id="condition", value=condition))@@ -5442,3 +5533,176 @@ def test_rehydrated_activation_token_allows_unknown_frame_metadata() -> None:restored = load_execution_state(snapshot)assert restored.execution_tokens[token_id].frame.model_extra["future_frame_metadata"] == "preserved"+++def _expected_four_nested_if_run(conditions: tuple[bool, bool, bool, bool]) -> tuple[list[str], int]:+ root_condition, outer_condition, middle_condition, inner_condition = conditions+ trace = ["root_condition"]+ if not root_condition:+ return trace + ["root_false", "root_if", "sink"], 31++ trace.append("outer_condition")+ if not outer_condition:+ return trace + ["outer_false", "outer_if", "root_if", "sink"], 21++ trace.append("middle_condition")+ if not middle_condition:+ return trace + ["middle_false", "middle_if", "outer_if", "root_if", "sink"], 11++ trace.extend(["inner_condition", "inner_true" if inner_condition else "inner_false"])+ return trace + ["inner_if", "middle_if", "outer_if", "root_if", "sink"], 5 if inner_condition else 7++[email protected]("conditions", list(product((True, False), repeat=4)))+def test_fresh_four_nested_ifs_select_only_branches_and_match_compatibility(+ conditions: tuple[bool, bool, bool, bool],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh four-nested If used controller-owned branch analysis")++ def fail_controller_access(*_: object, **__: object) -> Any:+ raise AssertionError("fresh four-nested If instantiated the compatibility controller")++ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ monkeypatch.setattr(GraphExecutionState, "_if_activation_controller", fail_controller_access)+ expected_trace, expected_value = _expected_four_nested_if_run(conditions)+ runs: list[tuple[list[str], GraphExecutionState]] = []+ for force_compatibility_scheduler in (False, True):+ state = GraphExecutionState(+ graph=_four_nested_if_graph(+ root_condition=conditions[0],+ outer_condition=conditions[1],+ middle_condition=conditions[2],+ inner_condition=conditions[3],+ )+ )+ assert state._can_use_fresh_flat_if_activation()+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ runs.append((trace, state))++ assert trace == expected_trace+ assert set(state.source_prepared_mapping) == set(expected_trace)+ assert all(+ state._get_prepared_exec_metadata(exec_node_id).state != "skipped"+ for exec_node_id in state.prepared_source_mapping+ )+ assert state.results[next(iter(state.source_prepared_mapping["sink"]))].value == expected_value+ assert state.is_complete()++ _assert_generic_and_compatibility_schedulers(runs[0][1], runs[1][1])+ assert runs[0][0] == runs[1][0]+ assert _state_projection(runs[0][1]) == _state_projection(runs[1][1])+ assert _activation_projection(runs[0][1]) == _activation_projection(runs[1][1])+ assert _execution_token_projection(runs[0][1]) == _execution_token_projection(runs[1][1])++[email protected]("middle_branch", ["true_input", "false_input"])[email protected]("outer_branch", ["true_input", "false_input"])[email protected]("root_branch", ["true_input", "false_input"])+def test_fresh_four_nested_ifs_support_all_direct_parent_branch_ports(+ middle_branch: str,+ outer_branch: str,+ root_branch: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh four-nested If used controller-owned branch analysis")++ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ graph = _four_nested_if_graph(+ middle_branch=middle_branch,+ outer_branch=outer_branch,+ root_branch=root_branch,+ middle_condition=middle_branch == "true_input",+ outer_condition=outer_branch == "true_input",+ root_condition=root_branch == "true_input",+ )+ expected_trace = [+ "root_condition",+ "outer_condition",+ "middle_condition",+ "inner_condition",+ "inner_true",+ "inner_if",+ "middle_if",+ "outer_if",+ "root_if",+ "sink",+ ]+ runs: list[tuple[list[str], GraphExecutionState]] = []+ for force_compatibility_scheduler in (False, True):+ state = GraphExecutionState(graph=graph.model_copy(deep=True))+ assert state._can_use_fresh_flat_if_activation()+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ runs.append((trace, state))++ assert trace == expected_trace+ assert state.is_complete()+ assert {+ (dependency.owner_id, dependency.branch, dependency.frame)+ for dependency in state._get_source_activation_dependencies("inner_true")+ } == {+ ("inner_if", "true_input", ()),+ ("middle_if", middle_branch, ()),+ ("outer_if", outer_branch, ()),+ ("root_if", root_branch, ()),+ }++ _assert_generic_and_compatibility_schedulers(runs[0][1], runs[1][1])+ assert runs[0][0] == runs[1][0]+ assert _state_projection(runs[0][1]) == _state_projection(runs[1][1])+ assert _activation_projection(runs[0][1]) == _activation_projection(runs[1][1])++[email protected]("force_compatibility_scheduler", [False, True])[email protected]("stop_after", range(1, 12))+def test_fresh_four_nested_ifs_shared_ancestor_checkpoint_resume_matches_both_schedulers(+ force_compatibility_scheduler: bool,+ stop_after: int,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh four-nested If used controller-owned branch analysis")++ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ graph = _four_nested_if_graph(+ root_condition=True,+ outer_condition=True,+ middle_condition=True,+ inner_condition=False,+ with_shared_ancestor=True,+ )+ expected_trace = [+ "root_condition",+ "outer_condition",+ "middle_condition",+ "inner_condition",+ "shared",+ "inner_false",+ "inner_if",+ "middle_if",+ "outer_if",+ "root_if",+ "sink",+ ]+ expected_trace_run, expected_state = _run_graph(GraphExecutionState(graph=graph.model_copy(deep=True)))+ assert expected_trace_run == expected_trace+ 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.results[next(iter(resumed_state.source_prepared_mapping["sink"]))].value == 6+ assert _state_projection(resumed_state) == _state_projection(expected_state)+ assert _activation_projection(resumed_state) == _activation_projection(expected_state)+ assert _execution_token_projection(resumed_state) == _execution_token_projection(expected_state)+ assert resumed_state.is_complete()diff --git a/tests/app/services/shared/test_graph_if_dependencies.py b/tests/app/services/shared/test_graph_if_dependencies.pyindex 0e1cfef4b4..36973a7e6c 100644--- a/tests/app/services/shared/test_graph_if_dependencies.py+++ b/tests/app/services/shared/test_graph_if_dependencies.py@@ -149,6 +149,34 @@ def _four_nested_if_graph() -> Graph:return graph+def _five_nested_if_graph() -> Graph:+ graph = _four_nested_if_graph()+ graph.delete_node("sink")+ graph.add_node(BooleanInvocation(id="fifth_condition", value=True))+ graph.add_node(AddInvocation(id="fifth_false", a=40, b=0))+ graph.add_node(IfInvocation(id="fifth_if"))+ graph.add_node(AddInvocation(id="sink", b=1))+ graph.add_edge(_edge("fifth_condition", "value", "fifth_if", "condition"))+ graph.add_edge(_edge("deepest_if", "value", "fifth_if", "true_input"))+ graph.add_edge(_edge("fifth_false", "value", "fifth_if", "false_input"))+ graph.add_edge(_edge("fifth_if", "value", "sink", "a"))+ return graph+++def _four_nested_if_fanout_graph() -> Graph:+ graph = _four_nested_if_graph()+ graph.add_node(AddInvocation(id="outer_side_consumer", b=1))+ graph.add_edge(_edge("outer_if", "value", "outer_side_consumer", "a"))+ return graph+++def _four_nested_if_terminal_fanout_graph() -> Graph:+ graph = _four_nested_if_graph()+ graph.add_node(AddInvocation(id="deepest_side_consumer", b=1))+ graph.add_edge(_edge("deepest_if", "value", "deepest_side_consumer", "a"))+ return graph++def _three_nested_if_fanout_graph() -> Graph:graph = _three_nested_if_graph()graph.add_node(AddInvocation(id="middle_side_consumer", b=1))@@ -399,7 +427,9 @@ def test_four_independent_sibling_ifs_admit_owner_local_frame_local_dependencies[pytest.param(lambda: _sibling_if_graph_with_count(5), "first_true", id="five-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(_five_nested_if_graph, "inner_true", id="five-nested-ifs"),+ pytest.param(_four_nested_if_fanout_graph, "inner_true", id="four-nested-if-fanout"),+ pytest.param(_four_nested_if_terminal_fanout_graph, "inner_true", id="four-nested-if-terminal-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"),@@ -480,6 +510,25 @@ def test_three_nested_ifs_with_one_middle_leaf_fanout_admit_exact_dependencies())+def test_four_nested_ifs_admit_owner_and_frame_dependencies() -> None:+ state = GraphExecutionState(graph=_four_nested_if_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,)),+ ActivationDependency(owner_id="deepest_if", branch="true_input", frame=(1,)),+ )+ assert state._get_source_activation_dependencies("outer_false", (2,)) == (+ ActivationDependency(owner_id="outer_if", branch="false_input", frame=(2,)),+ ActivationDependency(owner_id="deepest_if", branch="true_input", frame=(2,)),+ )+ assert state._get_source_activation_dependencies("deepest_false", (3,)) == (+ ActivationDependency(owner_id="deepest_if", branch="false_input", frame=(3,)),+ )++@pytest.mark.parametrize("middle_branch", ["true_input", "false_input"])@pytest.mark.parametrize("outer_branch", ["true_input", "false_input"])def test_three_nested_ifs_with_one_middle_leaf_fanout_preserve_parent_branch_ports(