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
fix(graph): default If branches to eager execution (#10032)
Jonathan7e9a3b99ec93
diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.ymlindex 76fb54e409..d4051e0297 100644--- a/.github/workflows/python-tests.yml+++ b/.github/workflows/python-tests.yml@@ -107,8 +107,9 @@ jobs:# A per-test timeout turns a hang into a failure with a traceback, so pytest still reaches its summary# inside the job timeout.pytest-args: '--timeout=600'- # About 1.6x the slowest measured job (37 min, 31 of them pytest; another run took 28).- timeout-minutes: 60+ # The latest main-synced run reached 98% before hitting the 60-minute job limit.+ # Keep the per-test timeout and allow the suite 15 more minutes to report its result.+ timeout-minutes: 75name: 'py${{ matrix.python-version }}: ${{ matrix.platform }}'runs-on: ${{ matrix.os }}# Per platform: expected run time is 8-14 min on linux and macos. See the matrix for windows.diff --git a/docs/src/content/docs/Users Guide/08.Workflows/loop-nodes.mdx b/docs/src/content/docs/Users Guide/08.Workflows/loop-nodes.mdxindex a568db104c..7fadbef110 100644--- a/docs/src/content/docs/Users Guide/08.Workflows/loop-nodes.mdx+++ b/docs/src/content/docs/Users Guide/08.Workflows/loop-nodes.mdx@@ -3,7 +3,7 @@ title: Loop Nodesdescription: Repeat workflow steps over a collection and optionally carry values from one iteration to the next.sidebar:order: 4-lastUpdated: 2026-09-28+lastUpdated: 2026-11-07---Loop nodes let a workflow repeat the same group of steps for every item in a collection. For example, a workflow can@@ -225,14 +225,38 @@ An empty collection is a successful loop with zero body iterations:Set `ForReturn.continue_condition` to `False` when the loop should stop after the current item. The results and statefrom completed iterations remain available through the normal final outputs.+## If Branch Execution++An `If` returns the value from its selected branch. In most workflows, after its condition resolves, the execution+engine admits both branch paths but attaches only the selected branch value to the `If`. The other path's work may be+unused, but its nodes can still run.++This has a few consequences:++- A failure in an unselected branch can fail the workflow.+- In nested `If` graphs, an input from an unselected upstream path can be `None`; a downstream node can fail when it+ uses that value.+- A `Collect` on a per-item branch can include values from items where that branch was not selected; it does not+ filter the items by the `If` condition.+- Adding unrelated control flow can change whether an `If` matches one of the narrow lazy shapes below.+- Unselected paths can perform work or side effects, such as saving a file or calling a provider, before execution+ ends.++Two narrow shapes remain lazy: a root `If` with private branch paths and no other control flow or iterator axes; and an+exact six-node, seven-edge single-axis `Iterate -> If -> Collect` graph. In the mixed graph, one inputless collection+source feeds one `Iterate`; its `item` directly feeds `If.condition` and one producer for each branch; each producer+consumes that same item and feeds only its corresponding branch input; and `If.value` is the sole input to a terminal+`Collect.item`. Extra nodes or edges make the `If` eager. Errors or cancellation can also stop a workflow early, so eager+execution does not guarantee that every node completes.+## Collection Type ChecksBefore a workflow runs, InvokeAI checks the item types flowing through `Collect`, `Iterate`, and connected `If` nodes.An `int` and a `float` collected together have the common item type `float`, so an iterator consumer must accept afloat. If both resolved branches of an `If` feed one `Collect.collection`, their possible item types must share onecompatible root. For example, `If(Collect[int], StringCollection) -> Collect.collection` is rejected even though only-one branch runs at a time; the resulting collection cannot have one statically known item type. Complete both `If`-branches before relying on strict type validation or queueing the workflow.+the selected branch value is returned; the resulting collection cannot have one statically known item type. Complete+both `If` branches before relying on strict type validation or queueing the workflow.A workflow saved before stricter collection checks may now fail validation when queued. Follow the validation error tothe collector or iterator connection, then update the workflow so its collection item types and consumers agree.diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.mdindex c3c561ea50..5d25adfe42 100644--- a/docs/src/content/docs/contributing/loop-nodes.md+++ b/docs/src/content/docs/contributing/loop-nodes.md@@ -235,26 +235,20 @@ 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, 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`. The three-`If` chain permits one-extra `middle If.value` edge to an ordinary leaf consumer with no outputs; that leaf inherits only the outer branch-dependency. Other inner/middle outputs must be direct nested branch edges, and the four-`If` chain permits no extra-output fan-out. Five-or-more nested `If`s, other fan-out, mixed shapes outside the bounded per-item-`Iterate`/`If`/`Collect` topology, loop-containing `For`/`ForReturn`, saved-workflow, legacy, and five-or-more sibling-shapes use the compatibility scheduler with the dedicated `_IfActivationController` fallback. Legacy snapshots retain-their generic compatibility projection. Legacy skipped-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. The generic and compatibility adapters consume the same decisions and-append-only execution edges; no type-specific branch scheduler prunes edges or propagates skips. Legacy skipped-state-metadata remains only for snapshots that already contain the old projection. `apply()` replaces the activation token by-stable identity, and activation effects are excluded from stream handling. Graph state derives branch membership for-the supported fresh shape; the fallback controller retains it for unsupported and legacy shapes. Author-time activation-ports and literal successor IDs remain absent, while unsupported loop shapes 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. Fresh ordinary-node `If` graphs are+eager by default: both branch paths may be admitted and evaluated after the condition gate resolves, while the pending+`If` attaches and hydrates only the selected branch input. Lazy execution is limited to two exact shapes: one root+ordinary `If` with no control-flow nodes or iterator axes and private branch dependency closures, and a six-node,+seven-edge single-axis `Iterate`/`If`/`Collect` graph. In the mixed graph, one inputless collection producer feeds one+`Iterate`; its `item` directly feeds `If.condition` and one producer for each branch; each branch producer consumes+that same item and outputs only to its corresponding branch input; and `If.value` is the sole input to a terminal+`Collect.item`. No extra nodes or edges are admitted. The generic and+compatibility adapters consume the same frame-local dependency decisions and append-only execution edges; no+type-specific branch scheduler prunes edges or propagates skips. Legacy snapshots retain their generic compatibility+projection and old skipped-state metadata. Loop-containing `For`/`ForReturn`, saved-workflow control flow, and other+unsupported mixed shapes retain compatibility ownership. `apply()` replaces activation tokens by stable identity, and+activation effects are excluded from stream handling. Author-time activation ports and literal successor IDs remain+absent.The engine keeps compatibility materialization and queue readiness for loop-containing graphs outside the routingmatrix and for existing snapshots. Admitted fresh `For` graphs use the generic opaque plan/scheduler plus@@ -267,8 +261,9 @@ rehydration, source completion, and failure parity. Nine-level or deeper chains,sibling nested loops, and unsupported mixed shapes remain compatibility-owned. The exact fresh two-sibling`For`/`ForReturn` `CollectionConcat` fan-in shape, the exact fresh three-level serial nested-`For` shape with itsbounded static `CollectionConcat` producer, and the exact fresh four-level serial nested-`For` shape are-generic-routed. The execution engine does not modify any file under `invokeai/frontend/...`, including generated-schemas; the existing frontend/backend external interface remains stable. Branch-membership analysis remains internal,+generic-routed. The only frontend/API artifacts changed are generated OpenAPI and TypeScript declarations for the+optional persisted `prepared_iteration_axes` field in the queue-session response. Author-time workflow JSON and+invocation contracts are unchanged. Branch-membership analysis remains internal,while fresh execution no longer creates skipped-state projection and old snapshots retain it for compatibility.The frontend and backend validate the same boundary rules. Saved workflows preserve node types, field handles, and thediff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex ec7518fe6b..8e4cdeebd0 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -7,48 +7,32 @@ High-level design for the graph module. Focuses on responsibilities, data flow,Provide a typed, acyclic workflow model (**Graph**) plus a runtime scheduler (**GraphExecutionState**) that expandsiterator patterns, tracks readiness via indegree (the number of incoming edges to a node in the directed graph), andexecutes 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`. 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 where inner `value` feeds a middle branch and middle-`value` feeds an outer 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 activation dependencies 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-flow nodes. The bounded three-`If` chain requires direct `default` edges, all three `If`s to have `condition`,-`true_input`, and `false_input` inputs. The inner `If` has only its direct nested branch output; the middle `If.value`-may also feed one ordinary leaf consumer with no outputs. That leaf inherits the outer branch dependency, not-middle-`If` polarity. 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 graphs outside the bounded per-item `Iterate`/`If`/`Collect`-topology, loop-containing, saved-workflow, legacy, and five-or-more sibling shapes remain on the compatibility-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. Nodes exclusive to the unselected-branch are not materialized or invoked. `executed_history` records source-level completion and retirement: a branch-source retired as empty can appear there without an invocation or an execution result. It is bookkeeping, not an-invocation trace. Both scheduler adapters consume the same dependency decisions without pruning execution edges or-calling a type-specific branch scheduler. Legacy skipped-state metadata remains only for snapshots that already contain-the old projection. Branch-membership analysis remains an internal author-graph-admission decision. The focused fresh-shape ownership matrix also verifies that supported flat, nested, bounded-fan-out, and four-sibling graphs do not instantiate the compatibility controller or project fresh skipped nodes in-either scheduler route. This proves the current ownership boundary; it does not remove the controller, which remains-required for unsupported fresh shapes and legacy snapshots. The bounded mixed-control-flow gate admits one exact-per-item topology: exactly six nodes and seven edges consisting of an inputless ordinary collection source feeding-`Iterate.collection`, `Iterate.item` feeding `If.condition` and two distinct ordinary one-input branch adapters, those-adapters feeding `If.true_input` and `If.false_input`, and `If.value` feeding `Collect.item`. Only this topology uses-fresh generic scheduling and frame-local activation dependencies; alternating true/false items and empty collections-preserve ordered completion. `For`, `ForReturn`, saved-workflow calls, nested/sibling/fan-in/extra-node variants,-legacy snapshots, and all other mixed graphs remain compatibility-owned. This is backend-only and changes no-invocation, frontend, generated-schema, image, or external-interface contract. The token-authoritative topology is used-for every currently supported fresh shape listed above. The controller remains required for unsupported fresh shapes-and legacy snapshots. The execution ledgers (`execution_refs`, `execution_tokens`, `execution_effects`, and+graph instead of mutating the source graph. Fresh `If` graphs are eager by default: both branch paths are admitted and+evaluated after the condition gate resolves, while the pending `If` attaches and hydrates only the selected branch+edge/value. Lazy execution is limited to two shapes, which run only the selected branch: one root ordinary `If` with no+other control-flow nodes or iterator axes, where both branch dependency closures are private; and the exact connected+single-axis `Iterate -> If -> Collect` topology of six nodes and seven edges. In that mixed shape, one inputless+collection producer feeds `Iterate`; `Iterate.item` feeds `If.condition` and one direct producer for each branch; each+branch producer consumes that same item and outputs only to its corresponding `If` branch; and `If.value` is the sole+input to a terminal `Collect.item`. No other nodes or edges are admitted.+Nested, sibling, fan-out, loop, saved-workflow, and other valid shapes keep eager branch behavior; frame/control-flow+combinations rejected by validation still fail before invocation. Legacy snapshots retain their generic compatibility+projection and skipped-state metadata. Both scheduler adapters consume frame-local activation dependencies without+pruning execution edges or calling a type-specific branch scheduler. `executed_history` records source-level completion+and retirement, not an invocation trace. The persisted `GraphExecutionState` adds optional `prepared_iteration_axes`,+which is exposed as an additive field in the queue-session schema. This changes no invocation or image contract. The+token-authoritative topology is used+for fresh ordinary-node If graphs. The compatibility controller remains for legacy snapshots and mixed control-flow+graphs outside the bounded Iterate/If/Collect case. The execution ledgers (`execution_refs`, `execution_tokens`, `execution_effects`, and`execution_child_dependencies`) are internal persistence data. They are not part of public API schemas or client-responses. Version-2 `dump_execution_state()` writes a compact projection: execution references and ordinary output-tokens are rebuilt from the prepared graph, mappings, and results; frame-scoped activation tokens remain durable;-effects remain durable when needed for stream, continuation, or active workflow-call recovery; completed workflow-call+responses. Version-3 `dump_execution_state()` omits derived execution references and ordinary output tokens; loading+rebuilds execution references and runtime indexes/state from the prepared graph, mappings, and results, while ordinary+output tokens remain omitted from the persisted projection. Frame-scoped activation tokens and effects needed for+stream, continuation, or active workflow-call recovery persist; completed workflow-calllifecycle effects and completed child-dependency records are omitted. Attached child state is retained only while its-parent call is active. Direct `Iterate`/`Collect` graphs that do not contain `If`, `For`, `ForReturn`, or saved-workflow control flow+parent call is active. The versioned loader continues to accept version-2 snapshots; when the additive+`prepared_iteration_axes` field is absent, it reconstructs the axes from prepared execution and source-edge context.+Direct `Iterate`/`Collect` graphs that do not contain `If`, `For`, `ForReturn`, or saved-workflow control flowalso use the generic adapter. Its adapter-level readiness predicate waits for canonical Iterate streams to close, andgeneric completion mirrors each Iterate result into that ledger before releasing `Collect`. The exact fresh four-nodeshape `literal collection source -> Iterate -> one ordinary body -> Collect`, plus any number of ordinary downstream@@ -136,8 +120,8 @@ continuations, and authorized child-dependency records are stored in `invokeai.alegacy graph and queue behavior is retained behind adapters while those records provide the generic runtime projectionfor admitted shapes.-The graph runtime is backend-only. It does not add author-time fields or frontend/backend external fields; the existing-frontend/backend interface remains stable.+The graph runtime adds no author-time graph or invocation fields and does not change web UI interactions. Queue-session+serialization exposes the additive optional `prepared_iteration_axes` runtime metadata field described above.## 2) Major Data Types@@ -329,9 +313,10 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre- `graph: Graph` - source graph for the run; treated as stable during normal execution.- `execution_graph: Graph` - materialized runtime nodes/edges. This is mutable runtime state, not an immutable audit- log. Fresh `If` admission adds only the condition and selected-branch edges; legacy loaded execution graphs may still- contain append-only discarded nodes without deleted input edges. Retry paths rebuild from `graph`, not from a- previously persisted `execution_graph`.+ log. Fresh eager `If`s admit both branch paths after the condition gate resolves, but attach and hydrate only the+ selected branch edge/value; the two private lazy candidates run only that selected path. Legacy loaded execution+ graphs may still contain their recorded selected-only projection and skipped nodes. Retry paths rebuild from `graph`,+ not from a previously persisted `execution_graph`.- `executed: set[str]`, `executed_history: list[str]`.- `results: dict[str, AnyInvocationOutput]`, `errors: dict[str, str]`.- `prepared_source_mapping: dict[str, str]` - exec id -> source id.@@ -357,9 +342,9 @@ mutation helpers. Those helpers reject changes once the affected nodes have alreA restored state rebuilds the index once; newly prepared nodes extend it. The index is derived runtime state, notsnapshot data.- `execution_refs: dict[str, ExecutionReference]` - in-memory stable references for prepared execution nodes, including- their source node and execution frame; version-2 snapshots rebuild these references instead of storing them.+ their source node and execution frame; versioned snapshots rebuild these references instead of storing them.- `execution_tokens: dict[str, ExecutionToken]` - in-memory output tokens produced by applied execution results;- version-2 snapshots retain only frame-scoped activation tokens.+ version-3 snapshots retain only frame-scoped activation tokens.- `execution_effects: dict[str, list[Any]]` - JSON-safe effects accepted for each execution reference.- **Ready queues grouped by class** (private projection): `_ready_queues: dict[class_name, deque[str]]` and`_active_class: Optional[str]`. Ordinary static DAGs and legacy-shaped `If` graphs derive readiness from the generic@@ -407,23 +392,24 @@ activation token for the selected `true_input` or `false_input` port; `GraphExecthe producing invocation's declared activation fields and persists it without creating a data stream. On 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. 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 (including its single middle-value leaf-consumer), 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. Five-or-more nesting, five-or-more sibling `If`s, other fan-out, mixed graphs outside the bounded per-item-`Iterate`/`If`/`Collect` topology, loop-containing, and saved-workflow shapes use the compatibility scheduler and-`_IfActivationController` for the same records; legacy snapshots retain the generic compatibility projection and legacy-skipped-state metadata. The controller remains the fallback runtime dependency owner, and the schedulers no longer call-a legacy compiler. Fresh materialization prepares the condition boundary, resolves the activation token, and attaches-only the selected branch input; rejected branch sources remain unprepared. `_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, while-rejected dependencies cause scheduler discard. Both scheduler adapters consume these dependency records; neither prunes-execution edges or calls a type-specific branch scheduler. The compatibility path still projects discarded prepared-nodes into legacy skipped metadata for rehydration and completion accounting when loading old execution graphs; fresh-runs do not create those nodes. `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`+forward-compatible. `GraphExecutionState` compiles opaque, frame-local activation dependencies for fresh acyclic+ordinary-node `If` graphs without a nested or sibling count limit. The compiled dependencies keep only the gate+frontier: a nested `If`'s own admission prerequisites imply its outer gates, while incomparable owners and branch+labels remain explicit. With `V` source nodes, `E` edges, `I` If owners and machine word width `w`, the packed masks+use `O(VI/w)` words and analysis takes `O((V+E)I/w)` word operations; a nested chain with `I = Θ(V)` is therefore+quadratic in graph size. The materializer's prepared-context path/axis prefix index has worst-case `O(P D_path D_axes)`+work and entries for `P` prepared contexts, path depth `D_path` and axis depth `D_axes`; its near-linear frame-count+scaling holds at fixed depths. Fresh `If` execution is eager except for the two+private-branch candidates described above. Loop and saved-workflow graphs outside the exact connected per-item+`Iterate`/`If`/`Collect` candidate use the compatibility scheduler and `_IfActivationController`; legacy snapshots+retain their generic compatibility projection and skipped-state metadata. The controller remains the fallback runtime+dependency owner, and the schedulers do not call a legacy compiler. `_GenericGraphSchedulerAdapter` consumes these+records through the opaque plan: its readiness callback requires a resolved private `ActivationGate` and matching+persisted activation token for the frame. Both scheduler adapters consume the same dependency decisions without+pruning execution edges or calling a type-specific branch scheduler. The compatibility path still projects discarded+prepared nodes into legacy skipped metadata when loading old execution graphs; fresh runs do not create that+projection. `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 index, and the final copy emits one `close_stream` effect. Direct Iterate/Collect-onlygraphs now run through the generic scheduler adapter; its completion maps these results/effects to the existing@@ -513,12 +499,13 @@ materialization and linkage ownership. The supported fresh static flat `For`/`Foinput-driven flat shape, the narrow canonical two-level and exact fresh three-level and four-level serial nested-`For`shapes (including the exact three-level producer-driven outer variant), and the canonical bounded internal`Iterate`/`Collect` shape use the generic adapter. For `If`, generic readiness consumes opaque frame-local plan-dependencies and requires both matching private `ActivationGate` runtime state and a persisted activation token. Fresh-resolution attaches only the selected branch edge; the forced compatibility `_ExecutionScheduler` path preserves this-behavior for fresh states, while legacy skipped metadata remains only when loading old discarded projections. This is-not token-built successor topology. Loop and workflow-call adapters still own materialization for unsupported shapes-and durable queue lifecycle. The frontend boundary remains frozen: the graph runtime does not modify-`invokeai/frontend/...` or existing web/webv2 interactions.+dependencies and requires a resolved private `ActivationGate` plus a persisted activation token. Fresh ordinary-node+graphs admit and evaluate both branch paths by default, then attach only the selected branch edge/value to the pending+`If`; only the two bounded candidates run just the selected path. Legacy snapshots retain their recorded selected-only+projection and skipped metadata. This is not token-built successor topology. Loop and+workflow-call adapters still own materialization for unsupported shapes+and durable queue lifecycle. Web UI interactions remain unchanged; the generated queue-session API contracts add the+optional `prepared_iteration_axes` runtime metadata field described above.The test-only differential harness at `tests/app/services/shared/test_execution_engine_differential.py` comparesgeneric and forced-compatibility scheduling for static DAGs, a constructed mixed/nested `If` graph, the supported@@ -597,13 +584,11 @@ Workflow-call note:read `GraphExecutionState._loop_topology()` instead of re-recognizing shapes per completed node. Classificationreads only node types and edges, so it is dropped with the cached flat source graph (graph mutation, transactionrollback, or a runtime-cache reset) and rebuilt from the next one.-- `_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, the exact four-`If` nested chain, and exactly- two, exactly three, or exactly four independent sibling `If`s 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.+- `_IfActivationController` Owns fallback `If` dependency analysis for legacy snapshots and control-flow graphs that+ use compatibility materialization. Fresh acyclic ordinary-node `If` graphs compile opaque, frame-local dependency+ records in graph state, regardless of nesting or sibling count. Fresh branches are eager unless the exact lazy+ candidate predicate admits one private root `If` or the connected per-item `Iterate`/`If`/`Collect` topology.+ External consumers of branch producers force eager execution; legacy skipped-state projections remain loadable.- Private `graph_if_dependencies.py` compiles fresh activation dependencies, and `graph_if_runtime.py` recordsdependencies and evaluates admission against gates and tokens. `GraphExecutionState` retains the method entry points,durable token/reference/effect storage, derived caches, transaction journal, and fallback controller selection.@@ -638,13 +623,13 @@ remain excluded from ready-queue projection during rehydration, preserving readythe pending `If` is admitted. Before token validation, missing legacy iteration-path metadata is rebuilt from theprepared execution graph. Persisted activation identity is then validated fail-closed against prepared owners, derivedreferences, declared activation fields, canonical ids, and known frame fields; extra frame metadata is retained.-Version-2 `dump_execution_state()` omits derived execution references and ordinary output tokens, keeps activation+Version-3 `dump_execution_state()` omits derived execution references and ordinary output tokens, keeps activationtokens, retains stream/continuation effects needed to resume, and drops terminal saved-workflow lifecycle effects andcompleted child-dependency records. Active workflow-call child state remains attached for recovery; completed calls usetheir workflow-call history instead. Ordinary model serialization and public schemas omit these four internal ledgers;private helper objects are not serialized. Queue snapshots carry an additive execution-state version marker and use a-version-aware loader; legacy unmarked snapshots are treated as version 0, while unreadable snapshots are quarantined by-queue service.+version-aware loader; version-2 snapshots remain readable, including snapshots predating `prepared_iteration_axes`,+while legacy unmarked snapshots are treated as version 0 and unreadable snapshots are quarantined by queue service.### 4.4 Compatibility preparation (`_prepare()`)@@ -665,21 +650,26 @@ materialization.enclosing iterator paths. This lets a shape such as`outer_iter -> inner_collection -> inner_iter -> collect -> consumer` produce one collected result per outeriteration instead of mixing all inner items into one global collection. Incoming `collection` inputs are treated as- ancestor groups and are copied into each matching descendant item group.+ ancestor groups and are copied into each matching descendant item group. Root `item` inputs are also broadcast into+ every deeper item group; when deeper groups exist, they do not create an extra root-only result. Empty enclosing+ groups remain at their original frame path, even when a deeper nested stream has no items; no deeper child frame is+ fabricated to hold an empty group.- Otherwise: compute all combinations of prepared iterator ancestors. For each combination, choose the prepared parentfor each upstream by matching iterator ancestry, then create **one** exec node. If a node no longer has visibleiterator ancestors because the source path crosses a collector, prepared parent iteration paths are still used tomaterialize one downstream exec node for each preserved collector path.-- For an IfInvocation with a wired condition, prepare condition inputs first. Readiness waits for condition source nodes+- For an `IfInvocation` with a wired condition, prepare condition inputs first. Readiness waits for condition source nodesand their ancestors, and for the iterators in the `If`'s own iterator ancestry, which give it its frames and are nevergated by it; other iterator ancestry on a branch cannot hold the gate open. After the condition resolves, activation- dependencies admit selected branch contexts and attach only the selected branch input. A literal condition is gated by- the ancestry of its known selected branch; an iterator that only feeds the unselected branch, such as one closed by a- branch `Collect`, cannot hold it back. Its frames still wait for the iterators open at it. Unsupported fresh shapes- and legacy snapshots use the compatibility controller. Rejected branch sources are retired empty without invocation.- Pending If state is reconstructed from durable execution edges, prepared mappings, and the activation token after+ dependencies gate branch work. Fresh eager graphs admit both branch paths but attach only the selected input+ edge/value; the exact private lazy candidates run only that selected path. Legacy snapshots retain their selected-only+ projection. A literal condition is+ gated by the ancestry of its known selected branch; an iterator that only feeds the unselected branch, such as one+ closed by a branch `Collect`, cannot hold it back. Its frames still wait for the iterators open at it. Unsupported+ mixed control-flow shapes use the compatibility controller. Rejected lazy-branch sources are retired empty without+ invocation. Pending `If` state is reconstructed from durable execution edges, prepared mappings, and the activation token afterrehydration.- A branch `Collect` whose `item` source combines exactly two sibling `Iterate` axes can close the axis beside the@@ -764,13 +754,13 @@ depth requires converting that path inference to an explicit stack.### 4.5 Readiness and class ordering- `_enqueue_if_ready(nid)` applies generic readiness: `indegree == 0`, not executed or claimed, and, for an `If`- branch-local node, both matching private `ActivationGate` runtime state and a persisted activation token are present- for its frame. Fresh admission prevents rejected branch nodes from reaching this queue. For direct `Collect` nodes,+ branch-local node, a resolved matching private `ActivationGate` and persisted activation token are present for its+ frame. Lazy candidates admit only selected branch nodes; eager shapes admit both after the gate resolves. For direct `Collect` nodes,the adapter also requires available Iterate streams to be closed. Compatibility uses the same opaque activationdependencies; legacy skipped metadata remains for old snapshots.-- `_get_next_node()` uses the generic scheduler for ordinary static DAGs, legacy-shaped `If` graphs, and the admitted- fresh control-flow shapes described above, projecting deterministic class/frame order into the compatibility queues.- Fallback control-flow graphs, including saved-workflow calls, use `_active_class` and the legacy class queues. No+- `_get_next_node()` uses the generic scheduler for ordinary static DAGs and fresh acyclic ordinary-node `If` graphs,+ projecting deterministic class/frame order into the compatibility queues. The exact per-item Iterate/If/Collect+ candidate also uses it. Other loop and saved-workflow graphs use `_active_class` and the legacy class queues. Nobatch-size or fairness cap is currently implemented.#### 4.5.1 Indegree (what it is and how it's used)@@ -794,35 +784,36 @@ Run `C` -> `D:0` -> enqueue `D`. Run `D` -> done.`Iterate.item` edge uses its closed canonical stream ledger, preserving stream sequence order; an open stream is nothydrated, and a missing stream falls back to the materialized source result for legacy snapshots. Materialized inputsare still grouped by iteration path, so hydration only sees inputs belonging to that collector exec node.-- For **IfInvocation**: hydrate only `condition` and the selected branch input. As a defensive guard against- inconsistent runtime or deserialized session state, the runtime raises if the selected input edge points at an exec- node with no stored runtime output. In normal scheduling this path should be unreachable.+- For **IfInvocation**: hydrate `condition` and the branch inputs attached by the current execution mode. Eager shapes+ admit and evaluate both branch paths, but attach and hydrate only the selected input edge/value; lazy candidates run+ only the selected path. Legacy snapshots retain their recorded projection. As a defensive guard against inconsistent+ runtime or deserialized session state, the runtime raises if an attached input edge points at an exec node with no+ stored runtime output. In normal scheduling this path should be unreachable.- For all others: deep-copy each incoming edge's value into the destination field. This prevents cross-node mutationthrough shared references.### 4.7 Lazy `If` semantics-`IfInvocation` now acts as a lazy branch boundary rather than a simple value multiplexer.+`IfInvocation` is eager by default and acts as a lazy branch boundary only for two bounded candidates.- The `condition` input must resolve first.-- Nodes that are exclusive to the true or false branch remain unmaterialized until their branch is admitted, even when- their indegree would otherwise be zero.-- Once the condition resolves, graph-state activation logic records the selected activation token and attaches only the- selected branch input to the pending `If` execution. Branch-exclusive ancestors of the unselected branch are not- invoked or materialized into execution results. Their source IDs can appear in `executed_history` after empty- retirement; the history is not an invocation trace. Unsupported fresh shapes and legacy snapshots use the- compatibility controller. Both scheduler adapters use append-only execution edges; no type-specific branch scheduler- performs pruning or skip propagation.-- Legacy snapshots that already contain skipped prepared nodes retain their compatibility metadata and scheduler- projection. Fresh execution does not create that projection.+- By default, once the frame-local condition gate resolves, both branch paths are admitted and evaluated; the pending+ `If` attaches and hydrates only the selected branch edge/value. Shared ancestors run once and remain shared.+- Lazy execution applies only to one root ordinary `If` with private branch dependency closures and no other control+ flow or iterator axes, or the exact six-node, seven-edge single-axis shape described above. A branch producer with any+ external consumer makes the whole `If` eager.+- Legacy snapshots keep their recorded selected-only and skipped-node projection. Fresh eager execution does not create+ skipped nodes. Both scheduler adapters use append-only execution edges; no type-specific branch scheduler performs+ pruning or skip propagation.- An `If` runs once per frame of the innermost iterator in its iterator ancestry, whichever branch is selected. When acondition, literal or computed in the root frame, selects a root value while the other branch carries an open- `Iterate`, the `If` keeps that per-item cardinality and returns the root value in each item frame; the unselected- per-item computation stays inactive. A branch `For`'s final output carries no axis into that ancestry, so selecting- the root value over such a branch runs the `If` once in the root frame, while selecting it runs the `If` per item of- the iterator the `For` runs under.-- The iterators whose frames are open at an `If`, including one reached through a `For` final output (which closes only- the `For`'s own axis), run regardless of the condition and are never gated by it.+ `Iterate`, the `If` keeps that per-item cardinality and returns the root value in each item frame. Eager fallback+ admits both branch paths in each frame; a private lazy candidate leaves the unselected branch inactive.+- Open iterator frames run regardless of the `If` condition. A selected `For` final output closes only its own axis+ while keeping enclosing axes open; an unselected `For`-final-only axis adds no `If` frames unless the same axis also+ reaches the `If` directly.+- Iterating a root `For.output_collection` opens a new `Iterate` axis; a downstream `Collect.item` closes it into the+ root group.- Before invocation, graph validation raises `UnsupportedIfIterationAxesError` for these frame sets:- Two unrelated iterators open at the `If` (neither stays open inside the other, judged by iterator ancestry, where a`Collect.item` input closes an axis), unless the input that decides the `If`'s frames carries both: the condition,@@ -837,32 +828,53 @@ Run `C` -> `D:0` -> enqueue `D`. Run `D` -> done.(a node between the `Collect` and the `Iterate`, or extra collected items) can change the length, and selectingthe upstream axis over its reopening pairs it with per-group frames; both would drop or invent frames.- A branch whose open axes, or the axes a branch `Collect` keeps, are deeper than a per-item condition's, unless- both branches carry the same deeper axes.- - A root-frame condition choosing between branches with different deeper axes. When both branches share nested- deeper axes, a root-frame condition runs the `If` once per frame of the innermost one.- Selected-branch frame cardinality is not supported.+ both branches carry the same deeper axes. Each `Collect.item` closes its innermost axis and keeps the outer axes;+ this identity is followed through chained `Collect`s and ordinary passthrough nodes. Separate branch Collect chains+ may retain the same axis identities and frames; sharing a Collect node is not required. Matching lengths alone do+ not establish alignment. An asymmetric or distinct-axis Collect chain is rejected before invocation. Unrelated+ sibling `Iterate` streams that reach one `Collect` directly or through literal `If` nodes close into their own+ sibling group, with values kept in stream order; they are not paired by numeric iteration index. An `Iterate`+ directly fed by `Collect.collection` consumes each prepared Collect run independently and preserves its parent+ frames. A downstream `Collect` retains empty outer groups. A `For.output_collection` passed through zero or more+ literal-`True` `If`+ nodes into `Collect.item` keeps the `For`'s parent frame for every chain length; the `For` final closes only its+ own axis. When a wired Boolean condition resolves per parent frame to select a `For.output_collection`, its `If`+ output retains those parent-frame groups through `Collect`, including through an outer literal-`True` `If`. Root+ `Collect.item` inputs broadcast into each such selected-For parent group; they do not add a separate root result.+ - A root-frame condition choosing between branches with different deeper axes. When both branches retain the same+ nested axes, a root-frame condition runs the `If` once per available frame of the innermost axis. Selecting a root+ value over an axis reached only through an unselected `For` final output is the root-frame exception described+ above; literal and computed root conditions have the same result cardinality.+ Validation and frame inference use graph topology and statically known conditions only; they do not depend on+ unresolved runtime branch selections.- A completed `Collect` on a branch closes its item axis; the `If` does not wait for an `Iterate` that only that- `Collect` consumes. When the `Collect` keeps an outer frame open and is selected, the `If` runs once per preserved- group; when it is rejected, it never runs and the `If` runs in the frames of its remaining iterators. A `Collect` of a- `For` final output groups in the `For`'s parent frame, so it keeps that frame open.+ `Collect` consumes. Runtime groups after the `If` follow the selected output's frame provenance: a selected `Collect`+ keeps its preserved outer groups, while a `Collect` or `For` on the unselected branch contributes no groups. Numeric+ iteration indexes alone do not align unrelated sources. A selected `For` final output keeps its parent frame grouped+ when the condition establishes that frame, including through `Collect`; selecting the other branch does not retain+ those parent groups. This runtime behavior is separate from static graph validation and admissibility. A `Collect` of+ a `For` final output groups in the `For`'s parent frame, so it keeps that frame open.- A `For` whose loop body belongs to an `If` branch (its body feeds the `ForReturn`, which reaches the `For` only- through the loop linkage) is gated with that branch: for a frame that rejects the branch, neither the `For` nor its- body runs. A gated `For` brings in a `For` nested in its body together with that body. Two `For`s stay ungated. A- `For` nested in the body of an ungated `For` runs with that loop. A `For` whose final output feeds the `If` directly- is attached only after it finalizes, and the `If` is not prepared before that, so gating it on the `If` would- deadlock. Known limitation: with a per-item condition, such a `For` and its body run even for items that reject the- branch, and an error they raise is recorded.+ through the loop linkage) is admitted when that branch's frame gate opens; a `For` nested in that body comes along+ with the branch closure. After the frame-local condition resolves, eager execution admits both closures, so an+ unselected branch's `For`, body, or nested `For` may run and a failure there fails the execution. A `For` nested in+ the body of an ungated `For` runs with that loop, while two sibling `For`s remain independent. A `For` whose final+ output feeds the `If` directly attaches its output after finalization. With a per-item condition, selected frames wait+ for that final output before the `If` input is attached, while eager execution may run the unselected final-output+ branch as well; the `If` attaches only the selected value after all required inputs are ready. A literal condition+ establishes the initial gate from its selected-branch ancestry, then admits the other branch before the `If` resolves.- An `If` has no execution in a frame where the innermost iterator in its ancestry has no items. When an `Iterate` inits iterator ancestry, whether it feeds `If.condition` or a branch, has no items at all, no `If` execution is created,the branch sources are retired empty, the downstream `Collect` produces an empty collection, and the state completeswithout an error. The same holds for a literal condition whose selected branch runs under an empty `Iterate` reachedonly through a `For` final output. Retirement may add the branch source IDs to `executed_history`; neither branch- invocation runs and no branch result is created. Known limitation: with a wired condition, an `If` whose branch- reaches an empty `Iterate` only through a `For` final output stalls, whether the condition is root-frame or per item- of that `Iterate`.+ invocation runs and no branch result is created. With a wired root-frame condition and one parent `Iterate` carried+ through a selected `For` final output, the `If` broadcasts over the parent frames; an empty parent `Iterate` gives it+ no executions and the downstream `Collect` remains empty. Multiple unrelated open frames that cannot be paired still+ fail validation before execution.- The SQLite queue/processor path has evidence for cancellation before and after `If` resolution and retry from eachboundary for both condition polarities. A canceled attempt keeps its activation ledger and cannot resume; retry- starts a fresh state and must emit a fresh matching activation token before selected-only completion.+ starts a fresh state and must emit a fresh matching activation token before successful completion.- Legacy retired or skipped branch-local exec nodes may still be treated as executed for compatibility scheduling, butthey do not create entries in `results`.- Shared ancestors still execute if they are required by the selected branch or by any other live path in the graph.@@ -880,8 +892,12 @@ This behavior is implemented in the runtime scheduler, not in the invocation bod- `node = state.next()` -> may trigger `_prepare()` expansion.- Execute node externally -> `run_result`.- `state.apply(execution_ref, run_result)` -> updates indegrees, `If` state, ready queues, and the execution ledger.+ - Apply each result before requesting the next node; the compatibility scheduler is sequential. The generic scheduler+ may return `None` while a previously returned invocation is still claimed and in flight.-1. Finish when `next()` returns `None` and the execution state is not paused waiting on a workflow call boundary.+1. `next()` returns `None` when the graph is complete, when workflow-call/lifecycle work is suspended externally, or+ while the generic scheduler has claimed in-flight work. If preparation finds no ready invocation for an incomplete+ state with no such pending work, it raises `GraphExecutionStalledError`.When an invocation reuses cached media, `BaseInvocation.invoke_internal()` registers a temporary hold for the consumingqueue session before returning the cached output. The intermediates service checks that every referenced image/video@@ -943,13 +959,15 @@ active invocation can also grow; the compact record is not universally a singleprivate planner closes empty streams for the exact fresh source/Iterate/body/Collect, exact two- or three-streamfan-in, and exact two-branch body-mediated fan-in shapes; broader body-mediated fan-in, four or more streams, andother fallback shapes retain materializer compatibility ownership.-- Collectors wait for available direct Iterate streams to close, then aggregate their ledger values in stream order and- may also merge incoming `collection` inputs during runtime hydration. A missing ledger remains a legacy snapshot+- Collectors wait for available direct Iterate streams to close, then aggregate their ledger values in stream order;+ order across sources is unspecified, and repeated values are preserved. They may also merge incoming `collection`+ inputs during runtime hydration. A missing ledger remains a legacy snapshotfallback; stale legacy Iterate result mirrors do not override durable effects. Collectors nested under iteratorspreserve enclosing iteration paths, so downstream consumers materialize per enclosing iteration instead of receivinga mixed collection from unrelated outer iterations.-- Branch-exclusive nodes behind an unselected fresh `If` branch remain unmaterialized. Legacy snapshots may retain- skipped nodes for compatibility; they are not failed.+- Fresh eager fallback may materialize and run both branch paths. Only the two private lazy candidates leave+ unselected branch-exclusive nodes unmaterialized. Legacy snapshots may retain skipped nodes for compatibility; they+ are not failed.## 7) Extensibilitydiff --git a/invokeai/app/services/shared/execution_state_migration.py b/invokeai/app/services/shared/execution_state_migration.pyindex b6aee7229e..fa5b0b29cd 100644--- a/invokeai/app/services/shared/execution_state_migration.py+++ b/invokeai/app/services/shared/execution_state_migration.py@@ -7,7 +7,7 @@ from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocafrom invokeai.app.services.shared.execution_effects import normalize_persisted_execution_effectsfrom invokeai.app.services.shared.graph import GraphExecutionState-CURRENT_EXECUTION_STATE_VERSION: Final[int] = 2+CURRENT_EXECUTION_STATE_VERSION: Final[int] = 3LEGACY_EXECUTION_STATE_VERSION: Final[int] = 0@@ -226,6 +226,7 @@ def load_execution_state(snapshot: Mapping[str, Any]) -> GraphExecutionState:raise UnsupportedExecutionStateVersionError(f"Execution state snapshot version {version} is unsupported")legacy_execution_snapshot = version == LEGACY_EXECUTION_STATE_VERSION+ missing_v2_iteration_axes = version == 2 and "prepared_iteration_axes" not in payloadexecution_effects_persisted = "execution_effects" in payload and not legacy_execution_snapshotnormalized_payload = _normalize_persisted_ledgers(payload)return GraphExecutionState.model_validate(@@ -234,5 +235,6 @@ def load_execution_state(snapshot: Mapping[str, Any]) -> GraphExecutionState:context={"execution_effects_persisted": execution_effects_persisted,"legacy_execution_snapshot": legacy_execution_snapshot,+ "missing_v2_iteration_axes": missing_v2_iteration_axes,},)diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex 743b51d13f..9de0e3406a 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -244,6 +244,7 @@ class _GraphExecutionStateRuntime:"final_prepared_for_index","prepared_for_index_by_exec","source_graph_flat",+ "if_graph_analysis","execution_graph_flat","completed_source_ids_cache","unexecuted_prepared_counts",@@ -295,6 +296,7 @@ class _GraphExecutionStateRuntime:self.final_prepared_for_index: Optional[dict[tuple[str, tuple[int, ...]], str]] = Noneself.prepared_for_index_by_exec: dict[str, tuple[str, tuple[int, ...], tuple[int, ...]]] = {}self.source_graph_flat: Any | None = None+ self.if_graph_analysis: Any | None = Noneself.execution_graph_flat: Any | None = Noneself.completed_source_ids_cache: Optional[set[str]] = Noneself.unexecuted_prepared_counts: Optional[dict[str, int]] = None@@ -311,6 +313,10 @@ class _GraphExecutionStateRuntime:self.if_iteration_axes_validated = False+class GraphExecutionStalledError(RuntimeError):+ """Raised when an incomplete graph has no ready or in-flight work."""++class GraphExecutionState(BaseModel):"""Tracks source-graph expansion, execution progress, and runtime results."""@@ -386,6 +392,10 @@ class GraphExecutionState(BaseModel):description="The iteration coordinates of each prepared execution node",default_factory=dict,)+ prepared_iteration_axes: dict[str, tuple[str, ...]] = Field(+ description="The named iteration axes of each prepared execution node",+ default_factory=dict,+ )execution_refs: SkipJsonSchema[dict[str, ExecutionReference]] = Field(default_factory=dict,description="Stable frame-aware references for prepared execution nodes",@@ -559,6 +569,7 @@ class GraphExecutionState(BaseModel):self._if_activation_controller_instance = Noneself._pending_if_exec_nodes = set()self._if_branch_sources_cache = {}+ self._if_graph_analysis = Noneself._if_activation_dependencies_by_source = {}self._if_activation_dependencies_by_exec = {}self._if_activation_dependents_by_dependency = {}@@ -602,6 +613,7 @@ class GraphExecutionState(BaseModel):source_prepared_mapping=self.source_prepared_mapping,prepared_iteration_paths=self.prepared_iteration_paths,metadata=runtime.prepared_exec_metadata,+ prepared_iteration_axes=self.prepared_iteration_axes,on_iteration_path_change=self._invalidate_loop_caches_for_exec_node,state=self,)@@ -674,6 +686,9 @@ class GraphExecutionState(BaseModel):def _can_use_fresh_mixed_if_iterate_collect(self) -> bool:return graph_if_dependencies._can_use_fresh_mixed_if_iterate_collect(self)+ def _is_fresh_lazy_if_candidate(self, if_node_id: str) -> bool:+ return graph_if_dependencies._is_fresh_lazy_if_candidate(self, if_node_id)+def _get_fresh_if_branch_sources(self, if_node_id: str, branch_field: str) -> set[str]:return graph_if_dependencies._get_fresh_if_branch_sources(self, if_node_id, branch_field)@@ -849,6 +864,7 @@ class GraphExecutionState(BaseModel):runtime = self.__pydantic_private__["_runtime_state"]self._invalidate_selected_if_frames_for_preparation()runtime.source_graph_flat = None+ runtime.if_graph_analysis = Noneruntime.loop_topology = Noneruntime.fresh_flat_if_activation = Noneruntime.if_iteration_axes_validated = False@@ -3459,16 +3475,73 @@ class GraphExecutionState(BaseModel):node = self.execution_graph.nodes.get(exec_node_id)if not isinstance(node, IfInvocation):return False+ if not self._legacy_snapshot_loaded and not self._if_branch_inputs_attached(exec_node_id):+ return Trueselected_field = self._resolved_if_exec_branches.get(exec_node_id)if selected_field is None:return Truesource_node_id = self.prepared_source_mapping.get(exec_node_id)if source_node_id is None or not self.graph._get_input_edges(source_node_id, selected_field):return False+ selected_edges = self.graph._get_input_edges(source_node_id, selected_field)+ if not self._legacy_snapshot_loaded and all(edge.source.node_id in self.executed for edge in selected_edges):+ return Falsereturn not any(edge.destination.field == selected_field for edge in self.execution_graph._get_input_edges(exec_node_id))+ def _if_branch_inputs_attached(self, exec_node_id: str) -> bool:+ source_node_id = self.prepared_source_mapping.get(exec_node_id)+ if source_node_id is None:+ return False+ attached_fields = {edge.destination.field for edge in self.execution_graph._get_input_edges(exec_node_id)}+ target_path = self._get_iteration_path(exec_node_id)+ materializer = self._materializer()+ registry = self._prepared_registry()+ selected_field = self._resolved_if_exec_branches.get(exec_node_id)+ branches = (selected_field,) if selected_field is not None else ("true_input", "false_input")++ def get_overlapping_prepared_ids(edge: Edge) -> Iterable[str]:+ source_node = self.graph.get_node(edge.source.node_id)+ if not (+ isinstance(source_node, ForInvocation)+ and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final+ ):+ return registry.get_prepared_ids_with_overlapping_path(edge.source.node_id, target_path)++ source_axes = materializer._get_iteration_axes(source_node.id)+ target_axes = registry.get_iteration_axes(exec_node_id)+ if target_axes is None:+ target_axes = materializer._get_iteration_axes(source_node_id) or None+ if len(source_axes) > len(target_path) or (+ target_axes is not None and target_axes[: len(source_axes)] != source_axes+ ):+ return ()+ self._get_prepared_for_index()+ assert self._final_prepared_for_index is not None+ prepared_id = self._final_prepared_for_index.get((source_node.id, target_path[: len(source_axes)]))+ return (prepared_id,) if prepared_id is not None else ()++ return all(+ not (edges := self.graph._get_input_edges(source_node_id, branch))+ or branch in attached_fields+ or all(+ edge.source.node_id in self.executed+ and not (+ not self._legacy_snapshot_loaded+ and isinstance(self.graph.get_node(edge.source.node_id), IfInvocation)+ and not self.source_prepared_mapping.get(edge.source.node_id)+ )+ and not any(+ registry.get_metadata(prepared_id).state != "skipped"+ and materializer._prepared_node_has_edge_output(edge, prepared_id)+ for prepared_id in get_overlapping_prepared_ids(edge)+ )+ for edge in edges+ )+ for branch in branches+ )+def set_ready_order(self, order: Iterable[Type[BaseInvocation] | str]) -> None:names: list[str] = []for x in order:@@ -3620,6 +3693,399 @@ class GraphExecutionState(BaseModel):else:metadata.state = "pending"+ def _reconstruct_prepared_iteration_axes(self) -> None:+ """Rebuild omitted v2 axes from prepared iterator provenance and observed source-edge contexts."""+ registry = self._prepared_registry()+ materializer = self._materializer()+ execution_graph = self._get_execution_graph_flat()+ iterator_ancestry = materializer._get_iterator_ancestry(materializer.iterator_graph())+ source_graph = self._get_source_graph_flat()+ source_context_is_static: dict[str, bool] = {}+ for source_node_id in nx.topological_sort(source_graph):+ source_node = self.graph.get_node(source_node_id)+ has_dynamic_if = (+ isinstance(source_node, IfInvocation)+ and graph_if_runtime._get_static_if_selection(self, source_node_id) is None+ )+ data_predecessors = (+ edge.source.node_id+ for edge in self.graph._get_input_edges(source_node_id)+ if edge.destination.field != LOOP_LINKAGE_FIELD+ )+ source_context_is_static[source_node_id] = not has_dynamic_if and all(+ source_context_is_static.get(predecessor, False) for predecessor in data_predecessors+ )++ def edge_identity(edge: Edge) -> tuple[str, str, str, str]:+ return (+ edge.source.node_id,+ edge.source.field,+ edge.destination.node_id,+ edge.destination.field,+ )++ source_edges: dict[tuple[str, str, str, str], Edge] = {edge_identity(edge): edge for edge in self.graph.edges}+ static_edge_axes: dict[tuple[str, str, str, str], tuple[str, ...] | None] = {}+ static_frame_axes_cache: dict[str, Optional[tuple[str, ...]]] = {}++ def get_static_edge_axes(edge: Edge) -> tuple[str, ...] | None:+ if not source_context_is_static.get(edge.source.node_id, False):+ return None+ identity = edge_identity(edge)+ if identity not in static_edge_axes:+ static_edge_axes[identity] = graph_if_runtime._get_edge_frame_axes(+ self,+ iterator_ancestry,+ edge,+ static_frame_axes_cache,+ use_runtime_if_selection=False,+ )+ return static_edge_axes[identity]++ static_source_output_axes: dict[str, tuple[str, ...] | None] = {}++ def get_static_source_output_axes(source_node_id: str) -> tuple[str, ...] | None:+ if source_node_id not in static_source_output_axes:+ candidates = {+ axes+ for edge in self.graph._get_output_edges(source_node_id)+ if (axes := get_static_edge_axes(edge))+ }+ static_source_output_axes[source_node_id] = next(iter(candidates)) if len(candidates) == 1 else None+ return static_source_output_axes[source_node_id]++ static_iterator_axes: dict[str, tuple[str, ...] | None] = {}++ def get_static_iterator_axes(source_node_id: str) -> tuple[str, ...] | None:+ if source_node_id not in static_iterator_axes:+ node = self.graph.get_node(source_node_id)+ candidates: set[tuple[str, ...]] = set()+ if isinstance(node, (ForInvocation, IterateInvocation)):+ for edge in self.graph._get_output_edges(source_node_id):+ axes = get_static_edge_axes(edge)+ if axes is None:+ continue+ if (+ isinstance(node, ForInvocation)+ and get_output_field_scope(node, edge.source.field) == OutputScope.Final+ ):+ axes = (*axes, source_node_id)+ elif axes[-1] != source_node_id:+ axes = (*axes, source_node_id)+ candidates.add(axes)+ static_iterator_axes[source_node_id] = next(iter(candidates)) if len(candidates) == 1 else None+ return static_iterator_axes[source_node_id]++ def edge_path(edge: Edge, exec_node_id: str) -> tuple[int, ...]:+ source_node = self.graph.get_node(edge.source.node_id)+ if (+ isinstance(source_node, ForInvocation)+ and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final+ ):+ return self._get_for_parent_iteration_path(exec_node_id)+ return self._get_iteration_path(exec_node_id)++ def edge_axes(edge: Edge, axes: tuple[str, ...]) -> tuple[str, ...] | None:+ source_node = self.graph.get_node(edge.source.node_id)+ if (+ isinstance(source_node, ForInvocation)+ and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final+ and axes+ and axes[-1] == source_node.id+ ):+ return axes[:-1]+ if not axes:+ return get_static_edge_axes(edge)+ return axes++ def choose_unique_axes(candidates: list[tuple[str, ...]], path_depth: int) -> tuple[str, ...] | None:+ matching = {candidate for candidate in candidates if len(candidate) == path_depth and candidate}+ return next(iter(matching)) if len(matching) == 1 else None++ prepared_axes: dict[str, tuple[str, ...]] = {}+ source_edge_contexts: dict[tuple[tuple[str, str, str, str], tuple[int, ...], str], set[tuple[str, ...]]] = {}+ topological_order = nx.topological_sort(execution_graph)+ for exec_node_id in topological_order:+ source_node_id = self.prepared_source_mapping.get(exec_node_id)+ if source_node_id is None:+ continue+ node = self.execution_graph.get_node(exec_node_id)+ path = self._get_iteration_path(exec_node_id)+ parents: list[tuple[str, tuple[str, ...]]] = []+ for incoming in self.execution_graph._get_input_edges(exec_node_id):+ parent_exec_id = incoming.source.node_id+ parent_source_id = self.prepared_source_mapping.get(parent_exec_id)+ parent_axes = prepared_axes.get(parent_exec_id)+ if parent_axes is None:+ parent_axes = registry.get_iteration_axes(parent_exec_id)+ if parent_source_id is None or parent_axes is None:+ continue+ identity = (+ parent_source_id,+ incoming.source.field,+ source_node_id,+ incoming.destination.field,+ )+ edge = source_edges.get(identity)+ if edge is None:+ continue+ candidate = edge_axes(edge, parent_axes)+ if candidate is not None and len(edge_path(edge, parent_exec_id)) <= len(path):+ parents.append((identity[3], candidate))++ parent_candidates = [candidate for _, candidate in parents]+ has_own_iteration_axis = isinstance(node, (ForInvocation, IterateInvocation)) and node.index >= 0+ parent_depth = len(path) - 1 if has_own_iteration_axis else len(path)+ axes = choose_unique_axes(parent_candidates, parent_depth)+ if axes is None and parent_candidates:+ longest = max(parent_candidates, key=len)+ static_axes = get_static_source_output_axes(source_node_id)+ if static_axes is not None and len(longest) < parent_depth and static_axes[: len(longest)] == longest:+ axes = choose_unique_axes([static_axes], parent_depth)++ if has_own_iteration_axis:+ if axes is not None and (not axes or axes[-1] != source_node_id):+ axes = (*axes, source_node_id)+ elif axes is None:+ static_axes = get_static_iterator_axes(source_node_id)+ axes = static_axes if static_axes is not None and len(static_axes) == len(path) else None++ if axes is None and not path:+ axes = ()+ if axes is not None and len(axes) == len(path):+ prepared_axes[exec_node_id] = axes++ # Preserve observed axis tuples separately so equal numeric paths from distinct lineages do not collapse.+ for edge in self.graph._get_output_edges(source_node_id):+ identity = edge_identity(edge)+ branch_signature = edge.destination.field+ projected_axes = edge_axes(edge, axes) if axes is not None else None+ if projected_axes is not None:+ context_key = (identity, edge_path(edge, exec_node_id), branch_signature)+ source_edge_contexts.setdefault(context_key, set()).add(projected_axes)++ sibling_axes_by_collect: dict[str, set[str]] = {}+ for source_node_id, source_node in self.graph.nodes.items():+ if not isinstance(source_node, IterateInvocation):+ continue+ collection_edges = self.graph._get_input_edges(source_node_id, COLLECTION_FIELD)+ if len(collection_edges) != 1 or not isinstance(+ self.graph.get_node(collection_edges[0].source.node_id), CollectInvocation+ ):+ continue+ collect_id = collection_edges[0].source.node_id+ sibling_axes_by_collect.setdefault(collect_id, set()).add(source_node_id)++ sibling_axes: set[str] = set()+ for collect_id in sibling_axes_by_collect:+ item_edges = self.graph._get_input_edges(collect_id, ITEM_FIELD)+ item_axes = [get_static_edge_axes(edge) for edge in item_edges]+ if any(axes is None for axes in item_axes):+ continue+ iterator_ids = [axes[-1:] for axes in item_axes if axes is not None]+ axis_ids = [axes[0] if axes else None for axes in iterator_ids]+ has_final_input = any(+ isinstance((source_node := self.graph.get_node(edge.source.node_id)), ForInvocation)+ and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final+ for edge in item_edges+ )+ if (+ len(axis_ids) > 1+ and not has_final_input+ and all(axis_id is not None for axis_id in axis_ids)+ and len(set(axis_ids)) == len(axis_ids)+ and all(isinstance(self.graph.get_node(axis_id), IterateInvocation) for axis_id in axis_ids)+ ):+ sibling_axes.update(sibling_axes_by_collect[collect_id])++ prepared_frames_by_source: dict[str, list[tuple[tuple[int, ...], tuple[str, ...]]]] = {}+ for exec_node_id, source_node_id in self.prepared_source_mapping.items():+ axes = prepared_axes.get(exec_node_id)+ if axes is None:+ axes = registry.get_iteration_axes(exec_node_id)+ if axes is not None:+ prepared_frames_by_source.setdefault(source_node_id, []).append(+ (self._get_iteration_path(exec_node_id), axes)+ )++ source_projection_valid: set[str] = set()+ for source_node_id, frames in prepared_frames_by_source.items():+ if isinstance(self.graph.get_node(source_node_id), IterateInvocation):+ prepared_ids = self.source_prepared_mapping.get(source_node_id, ())+ if (+ len(frames) == len(prepared_ids)+ and graph_if_runtime._project_prepared_iteration_paths(frames, sibling_axes) is not None+ ):+ source_projection_valid.add(source_node_id)++ projection_group_axes: dict[tuple[tuple[str, str, str, str], str, tuple[int, ...]], tuple[str, ...]] = {}+ invalid_projection_groups: set[tuple[tuple[str, str, str, str], str, tuple[int, ...]]] = set()+ context_projection_groups: dict[+ tuple[tuple[str, str, str, str], tuple[int, ...], str],+ tuple[tuple[str, str, str, str], str, tuple[int, ...]],+ ] = {}+ for context_key, candidate_axes in source_edge_contexts.items():+ identity, path, destination_field = context_key+ if len(candidate_axes) != 1:+ continue+ axes = next(iter(candidate_axes))+ if len(axes) != len(path):+ continue+ if any(axis_id in sibling_axes and axis_id not in source_projection_valid for axis_id in axes):+ continue+ projected_path = tuple(+ coordinate for axis_id, coordinate in zip(axes, path, strict=True) if axis_id not in sibling_axes+ )+ projected_axes = tuple(axis_id for axis_id in axes if axis_id not in sibling_axes)+ group_key = (identity, destination_field, projected_path)+ previous_axes = projection_group_axes.setdefault(group_key, projected_axes)+ if previous_axes != projected_axes:+ invalid_projection_groups.add(group_key)+ else:+ context_projection_groups[context_key] = group_key+ context_projection_valid = {+ context_key+ for context_key, group_key in context_projection_groups.items()+ if group_key not in invalid_projection_groups+ }++ branch_edge_ids: dict[tuple[str, str], tuple[tuple[str, str, str, str], ...]] = {}+ branch_static_axes_by_depth: dict[tuple[str, str, int], tuple[str, ...]] = {}+ branch_static_axes: dict[tuple[str, str], tuple[str, ...]] = {}+ branch_final_axes: dict[tuple[str, str], set[str]] = {}+ root_selected_fields: dict[str, set[str]] = {}+ edge_branch_owner: dict[tuple[str, str, str, str], tuple[str, str]] = {}+ edge_for_final_only_axes: dict[tuple[str, str, str, str], set[str]] = {}+ static_if_selections: dict[str, str | None] = {}+ for source_node_id, source_node in self.graph.nodes.items():+ if not isinstance(source_node, IfInvocation):+ continue+ static_if_selections[source_node_id] = graph_if_runtime._get_static_if_selection(self, source_node_id)+ axes_by_branch, final_axes_by_branch = graph_if_runtime._get_if_static_frame_analysis(+ self, iterator_ancestry, source_node_id+ )+ for branch_field in ("true_input", "false_input"):+ edges = self.graph._get_input_edges(source_node_id, branch_field)+ identities = tuple(edge_identity(edge) for edge in edges)+ branch_edge_ids[(source_node_id, branch_field)] = identities+ branch_static_axes[(source_node_id, branch_field)] = axes_by_branch[branch_field]+ branch_final_axes[(source_node_id, branch_field)] = final_axes_by_branch[branch_field]+ static_axes = [get_static_edge_axes(edge) for edge in edges]+ if edges and all(axes is not None for axes in static_axes):+ axes_by_depth: dict[int, set[tuple[str, ...]]] = {}+ for axes in static_axes:+ assert axes is not None+ axes_by_depth.setdefault(len(axes), set()).add(axes)+ for depth, candidates in axes_by_depth.items():+ if len(candidates) == 1:+ branch_static_axes_by_depth[(source_node_id, branch_field, depth)] = next(iter(candidates))+ if all(axes == () for axes in static_axes):+ root_selected_fields.setdefault(source_node_id, set()).add(branch_field)+ for edge in edges:+ identity = edge_identity(edge)+ edge_branch_owner[identity] = (source_node_id, branch_field)+ final_axes, direct_axes = graph_if_runtime._get_if_final_axes_for_edge(+ self, iterator_ancestry, edge+ )+ edge_for_final_only_axes[identity] = final_axes - direct_axes++ observed: dict[+ tuple[str, tuple[int, ...], str],+ dict[tuple[str, str, str, str], tuple[set[tuple[str, ...]], bool]],+ ] = {}+ summary_safe: dict[tuple[str, tuple[int, ...], str], bool] = {}+ summary_axes: dict[tuple[str, tuple[int, ...], str], tuple[str, ...]] = {}+ ambiguous_summaries: set[tuple[str, tuple[int, ...], str]] = set()+ for context_key, candidate_axes in source_edge_contexts.items():+ identity, path, branch_field = context_key+ owner = edge_branch_owner.get(identity)+ if owner is None or owner[1] != branch_field:+ continue+ source_node_id = owner[0]+ summary_key = (source_node_id, path, branch_field)+ valid_projection = context_key in context_projection_valid+ observed.setdefault(summary_key, {})[identity] = (candidate_axes, valid_projection)++ branch_path_axes: dict[tuple[str, tuple[int, ...], str], tuple[str, ...]] = {}+ for summary_key, edge_records in observed.items():+ source_node_id, _path, branch_field = summary_key+ path = summary_key[1]+ for identity, (candidate_axes, valid_projection) in edge_records.items():+ safe = valid_projection and len(candidate_axes) == 1+ if safe:+ axes = next(iter(candidate_axes))+ safe = len(axes) == len(path) and not (set(axes) & edge_for_final_only_axes[identity])+ if not safe:+ summary_safe[summary_key] = False+ continue+ summary_safe.setdefault(summary_key, True)+ previous_axes = summary_axes.setdefault(summary_key, axes)+ if previous_axes != axes:+ ambiguous_summaries.add(summary_key)+ if (+ len(edge_records) == len(branch_edge_ids[(source_node_id, branch_field)])+ and summary_safe.get(summary_key, False)+ and summary_key not in ambiguous_summaries+ ):+ branch_path_axes[summary_key] = summary_axes[summary_key]++ activation_fields_by_owner: dict[str, set[str]] = {}+ for token in self.execution_tokens.values():+ if token.token_kind == "activation":+ activation_fields_by_owner.setdefault(token.owner_node_id, set()).add(token.port)++ for exec_node_id, source_node_id in self.prepared_source_mapping.items():+ if registry.get_iteration_axes(exec_node_id) is not None:+ continue+ if exec_node_id not in prepared_axes:+ node = self.graph.get_node(source_node_id)+ if isinstance(node, IfInvocation):+ path = self._get_iteration_path(exec_node_id)+ static_selection = static_if_selections[source_node_id]+ token_fields = activation_fields_by_owner.get(exec_node_id, set())+ selected_field = (+ static_selection+ if static_selection is not None+ else next(iter(token_fields))+ if len(token_fields) == 1+ else None+ )+ axes = None+ if selected_field is not None:+ selected_key = (source_node_id, path, selected_field)+ if selected_key in branch_path_axes:+ axes = branch_path_axes[selected_key]+ else:+ axes = branch_static_axes_by_depth.get((source_node_id, selected_field, len(path)))+ if axes is None and selected_field in root_selected_fields.get(source_node_id, set()):+ other_field = "false_input" if selected_field == "true_input" else "true_input"+ opposite_key = (source_node_id, path, other_field)+ expected_axes = branch_static_axes[(source_node_id, other_field)]+ if (+ opposite_key in branch_path_axes+ and branch_path_axes[opposite_key] == expected_axes+ and expected_axes+ and not any(+ axis in branch_final_axes[(source_node_id, other_field)]+ for axis in expected_axes+ )+ ):+ axes = expected_axes+ else:+ true_key = (source_node_id, path, "true_input")+ false_key = (source_node_id, path, "false_input")+ if (+ true_key in branch_path_axes+ and false_key in branch_path_axes+ and branch_path_axes[true_key] == branch_path_axes[false_key]+ ):+ axes = branch_path_axes[true_key]+ if axes is not None:+ prepared_axes[exec_node_id] = axes++ if (axes := prepared_axes.get(exec_node_id)) is not None:+ registry.set_iteration_axes(exec_node_id, axes)+def _apply_if_condition_inputs(self, exec_node_id: str, node: IfInvocation) -> bool:condition_edges = self.execution_graph._get_input_edges(exec_node_id, "condition")if any(edge.source.node_id not in self.executed for edge in condition_edges):@@ -3910,9 +4376,11 @@ class GraphExecutionState(BaseModel):continueself._enqueue_if_ready(exec_node_id)- def _rehydrate_runtime_state(self) -> None:+ def _rehydrate_runtime_state(self, *, reconstruct_iteration_axes: bool = False) -> None:self._reset_runtime_caches()self._rehydrate_prepared_exec_metadata()+ if reconstruct_iteration_axes:+ self._reconstruct_prepared_iteration_axes()self._rehydrate_resolved_if_exec_branches()self._rehydrate_generic_runtime_state()if self.has_error():@@ -3945,7 +4413,8 @@ class GraphExecutionState(BaseModel):and reference.exec_node_id not in self.errorsand self._is_pending_lifecycle_execution(reference.exec_node_id, effects)}- self._rehydrate_runtime_state()+ reconstruct_iteration_axes = isinstance(__context, dict) and __context.get("missing_v2_iteration_axes", False)+ self._rehydrate_runtime_state(reconstruct_iteration_axes=reconstruct_iteration_axes)model_config = ConfigDict(json_schema_extra=_hide_execution_state_runtime_fields)@@ -3977,6 +4446,14 @@ class GraphExecutionState(BaseModel):if next_node is None:next_node = self._prepare_until_node_ready()+ if next_node is None and not self.is_complete():+ scheduler = self._scheduler()+ if isinstance(scheduler, _GenericGraphSchedulerAdapter) and scheduler._scheduler._claimed:+ return None+ raise GraphExecutionStalledError(+ f"Execution state {self.id} is incomplete, but no invocation is ready or in flight."+ )+# Get values from edgesif next_node is not None:try:@@ -3984,7 +4461,6 @@ class GraphExecutionState(BaseModel):except ValidationError as e:raise NodeInputError(next_node, e)- # If next is still none, there's no next node, return Nonereturn next_nodedef complete(self, node_id: str, output: BaseInvocationOutput) -> list[tuple[BaseInvocation, BaseInvocationOutput]]:@@ -4352,6 +4828,7 @@ _GRAPH_RUNTIME_ATTRIBUTE_NAMES = ("final_prepared_for_index","prepared_for_index_by_exec","source_graph_flat",+ "if_graph_analysis","execution_graph_flat","completed_source_ids_cache","unexecuted_prepared_counts",diff --git a/invokeai/app/services/shared/graph_execution_runtime.py b/invokeai/app/services/shared/graph_execution_runtime.pyindex b15790b655..31d279a04a 100644--- a/invokeai/app/services/shared/graph_execution_runtime.py+++ b/invokeai/app/services/shared/graph_execution_runtime.py@@ -43,6 +43,7 @@ class _ExecutionRuntime:def __init__(self, state: "GraphExecutionState") -> None:self._state = stateself._iterator_ancestry = _IteratorAncestry(state)+ self._static_selected_collect_iterate_owners: Optional[dict[str, tuple[tuple[str, str], ...]]] = Nonedef _get_cached_iteration_path(self, exec_node_id: str) -> Optional[tuple[int, ...]]:return self._state._prepared_registry().get_iteration_path(exec_node_id)@@ -224,7 +225,14 @@ class _ExecutionRuntime:def _prepare_if_inputs(self, node: IfInvocation, input_edges: list[Edge]) -> None:selected_field = self._state._resolved_if_exec_branches.get(node.id)- allowed_fields = {"condition", selected_field} if selected_field is not None else {"condition"}+ if selected_field is None:+ allowed_fields = {"condition"}+ elif self._state._legacy_snapshot_loaded:+ allowed_fields = {"condition", selected_field}+ elif self._state._is_fresh_lazy_if_candidate(self._state.prepared_source_mapping[node.id]):+ allowed_fields = {"condition", selected_field}+ else:+ allowed_fields = {"condition", "true_input", "false_input"}for edge in input_edges:if edge.destination.field not in allowed_fields:diff --git a/invokeai/app/services/shared/graph_if_activation.py b/invokeai/app/services/shared/graph_if_activation.pyindex 86db0eb3c1..ad9191f9c7 100644--- a/invokeai/app/services/shared/graph_if_activation.py+++ b/invokeai/app/services/shared/graph_if_activation.py@@ -9,11 +9,11 @@ if TYPE_CHECKING:class _IfActivationController:- """Own activation admission for concrete execution nodes.+ """Compile activation dependencies for source nodes on compatibility paths.Unlike the legacy compiler, this controller does not lower or cache a- branch projection. It answers one readiness question for one prepared- execution node from the current source graph and durable execution frame.+ branch projection. It derives frame-scoped branch requirements from the+ current source graph for the fallback scheduler."""def __init__(self, state: "GraphExecutionState") -> None:@@ -45,8 +45,8 @@ class _IfActivationController:# A For's loop body feeds its ForReturn, which reaches the For only through the loop linkage. The body belongs# to the branch whenever its For does, and leaves it with the For. Fors are visited outermost first, so a gated# For brings in a For nested in its body together with that body. Two Fors stay ungated. One whose final- # output enters the If directly is attached only after it finalizes, and the If is not prepared before that,- # so the For cannot wait for the If's verdict. One nested in an ungated For's body is expanded by that loop,+ # output enters the If directly is attached after it finalizes. With a wired condition the For and its body+ # can still be gated once that condition resolves. One nested in an ungated For's body is expanded by that loop,# which needs it to run. (A For enclosing the If is a frame iterator of the If and was removed above.)for_by_return_id: dict[str, str] = {}if any(isinstance(self._state.graph.nodes.get(node_id), ForInvocation) for node_id in branch_sources):@@ -61,6 +61,7 @@ class _IfActivationController:if (for_id not in branch_sourcesor for_id in direct_sources+ and branch_field == self._get_source_level_selected_field(if_node_id)or any(for_id in body_ids_by_for[enclosing_id] and enclosing_id not in for_by_return_id.values()for enclosing_id in body_ids_by_for@@ -127,14 +128,6 @@ class _IfActivationController:self._branch_memberships_by_source[source_node_id] = membershipsreturn memberships- def get_dependencies(self, exec_node_id: str) -> tuple[ActivationDependency, ...]:- """Return activation requirements for one concrete prepared node."""-- source_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)- if not self._get_if_node_ids():- return ()- return self.get_source_dependencies(source_node_id, self._state._get_iteration_path(exec_node_id))-def get_source_dependencies(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> tuple[ActivationDependency, ...]:@@ -145,43 +138,3 @@ class _IfActivationController:for if_node_id, fields in self._branch_memberships(source_node_id)if len(fields) == 1)-- def is_source_admitted(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:- dependencies = self.get_source_dependencies(source_node_id, iteration_path)- return bool(- not dependencies- or all(self._state._is_activation_dependency_satisfied(dependency) for dependency in dependencies)- )-- def is_source_rejected(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:- return any(- self._state._is_activation_dependency_rejected(dependency)- for dependency in self.get_source_dependencies(source_node_id, iteration_path)- )-- def is_source_inactive(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:- """Return whether a source belongs exclusively to a rejected If branch."""-- if iteration_path:- return self.is_source_rejected(source_node_id, iteration_path)-- relevant_if_ids = {if_node_id for if_node_id, _ in self._branch_memberships(source_node_id)}- if not relevant_if_ids:- return False-- frames: set[tuple[int, ...]] = set()- for if_node_id in relevant_if_ids:- frames.update(- self._state._get_iteration_path(exec_node_id)- for exec_node_id in self._state._prepared_registry().get_prepared_ids(if_node_id)- )- if not frames:- return False-- for frame in frames:- dependencies = self.get_source_dependencies(source_node_id, frame)- if dependencies and not any(- self._state._is_activation_dependency_rejected(dependency) for dependency in dependencies- ):- return False- return Truediff --git a/invokeai/app/services/shared/graph_if_dependencies.py b/invokeai/app/services/shared/graph_if_dependencies.pyindex 0c4198542b..57532a64f2 100644--- a/invokeai/app/services/shared/graph_if_dependencies.py+++ b/invokeai/app/services/shared/graph_if_dependencies.py@@ -1,4 +1,6 @@-from typing import TYPE_CHECKING+from collections import deque+from dataclasses import dataclass, field+from typing import TYPE_CHECKING, Any, Optionalfrom invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocationfrom invokeai.app.invocations.logic import IfInvocation@@ -8,6 +10,7 @@ from invokeai.app.services.shared.graph_validation import (COLLECTION_FIELD,ITEM_FIELD,CollectInvocation,+ Edge,IterateInvocation,nx,)@@ -16,23 +19,174 @@ if TYPE_CHECKING:from invokeai.app.services.shared.graph import GraphExecutionState-def _get_fresh_if_nodes(state: "GraphExecutionState") -> tuple[IfInvocation, ...]:+@dataclass(slots=True)+class _IfGraphAnalysis:+ source_graph: Any+ nodes_by_id: dict[str, Any]+ if_node_ids: tuple[str, ...]+ input_edges: dict[str, list[Edge]]+ output_edges: dict[str, list[Edge]]+ has_forbidden_activation_node: bool+ has_iterate_or_collect: bool+ topological_order: Optional[tuple[str, ...]] = None+ is_dag: Optional[bool] = None+ ancestors_by_node: dict[str, frozenset[str]] = field(default_factory=dict)+ lazy_if_candidates: dict[str, bool] = field(default_factory=dict)+ activation_owner_order: Optional[tuple[tuple[str, str], ...]] = None+ activation_owner_masks_by_source: Optional[dict[str, int]] = None+++def _get_if_graph_analysis(state: "GraphExecutionState") -> _IfGraphAnalysis:source_graph = state._get_source_graph_flat()- source_order = {node_id: index for index, node_id in enumerate(nx.topological_sort(source_graph))}- return tuple(- sorted(- (node for node in state.graph.nodes.values() if isinstance(node, IfInvocation)),- key=lambda node: (source_order.get(node.id, len(source_order)), node.id),- )+ analysis = state._if_graph_analysis+ if analysis is not None and analysis.source_graph is source_graph:+ return analysis++ nodes_by_id = dict(state.graph.nodes.items())+ if_node_ids = tuple(node_id for node_id, node in nodes_by_id.items() if isinstance(node, IfInvocation))+ has_forbidden_activation_node = any(+ isinstance(node, (CallSavedWorkflowInvocation, ForInvocation, ForReturnInvocation))+ for node in nodes_by_id.values()+ )+ has_iterate_or_collect = any(+ isinstance(node, (IterateInvocation, CollectInvocation)) for node in nodes_by_id.values()+ )++ input_edges: dict[str, list[Edge]] = {}+ output_edges: dict[str, list[Edge]] = {}+ for edge in state.graph.edges:+ if edge.type != "default":+ continue+ input_edges.setdefault(edge.destination.node_id, []).append(edge)+ output_edges.setdefault(edge.source.node_id, []).append(edge)++ analysis = _IfGraphAnalysis(+ source_graph=source_graph,+ nodes_by_id=nodes_by_id,+ if_node_ids=if_node_ids,+ input_edges=input_edges,+ output_edges=output_edges,+ has_forbidden_activation_node=has_forbidden_activation_node,+ has_iterate_or_collect=has_iterate_or_collect,)+ state._if_graph_analysis = analysis+ return analysis-def _can_use_fresh_mixed_if_iterate_collect(state: "GraphExecutionState") -> bool:- """Admit the bounded per-item Iterate/If/Collect topology."""+def _get_if_topological_order(analysis: _IfGraphAnalysis) -> Optional[tuple[str, ...]]:+ if analysis.is_dag is None:+ try:+ analysis.topological_order = tuple(nx.topological_sort(analysis.source_graph))+ except nx.NetworkXUnfeasible:+ analysis.is_dag = False+ else:+ analysis.is_dag = True+ return analysis.topological_order+++def _get_if_ancestors(analysis: _IfGraphAnalysis, node_id: str) -> frozenset[str]:+ ancestors = analysis.ancestors_by_node.get(node_id)+ if ancestors is None:+ ancestors = frozenset(nx.ancestors(analysis.source_graph, node_id))+ analysis.ancestors_by_node[node_id] = ancestors+ return ancestors- if _can_use_fresh_literal_if_iterate_collect(state):- return True+def _get_fresh_if_nodes(state: "GraphExecutionState") -> tuple[IfInvocation, ...]:+ analysis = _get_if_graph_analysis(state)+ if_node_ids = set(analysis.if_node_ids)+ topological_order = _get_if_topological_order(analysis)+ if topological_order is not None:+ return tuple(analysis.nodes_by_id[node_id] for node_id in topological_order if node_id in if_node_ids)+ return tuple(sorted((analysis.nodes_by_id[node_id] for node_id in if_node_ids), key=lambda node: node.id))+++def _get_flat_activation_owner_masks_by_source(+ state: "GraphExecutionState", analysis: _IfGraphAnalysis+) -> dict[str, int]:+ cached = analysis.activation_owner_masks_by_source+ if cached is not None:+ return cached++ if_nodes = _get_fresh_if_nodes(state)+ owners = tuple((node.id, branch) for node in if_nodes for branch in ("true_input", "false_input"))+ owner_bits = {owner: 1 << index for index, owner in enumerate(owners)}+ analysis.activation_owner_order = owners+ endpoint_bits = {(node_id, branch): bit for (node_id, branch), bit in owner_bits.items()}+ candidate_bits: dict[str, int] = {}+ extra_candidate_bits: dict[str, int] = {}++ for (if_node_id, branch_field), bit in owner_bits.items():+ direct_sources = {+ edge.source.node_id+ for edge in analysis.input_edges.get(if_node_id, ())+ if edge.destination.field == branch_field+ }+ for source_id in direct_sources:+ candidate_bits[source_id] = candidate_bits.get(source_id, 0) | bit+ if isinstance(analysis.nodes_by_id[source_id], IfInvocation):+ for edge in analysis.output_edges.get(source_id, ()):+ destination_id = edge.destination.node_id+ if not isinstance(+ analysis.nodes_by_id[destination_id], IfInvocation+ ) and not analysis.output_edges.get(destination_id):+ extra_candidate_bits[destination_id] = extra_candidate_bits.get(destination_id, 0) | bit++ # Propagate branch roots to their ancestors once for every owner in parallel.+ for node_id in reversed(analysis.topological_order or ()):+ bits = candidate_bits.get(node_id, 0)+ if bits:+ for edge in analysis.input_edges.get(node_id, ()):+ parent_id = edge.source.node_id+ candidate_bits[parent_id] = candidate_bits.get(parent_id, 0) | bits+ for node_id, bits in extra_candidate_bits.items():+ candidate_bits[node_id] = candidate_bits.get(node_id, 0) | bits++ owned_bits: dict[str, int] = {}+ for node_id in reversed(analysis.topological_order or ()):+ bits = candidate_bits.get(node_id, 0)+ for edge in analysis.output_edges.get(node_id, ()):+ destination_id = edge.destination.node_id+ allowed = owned_bits.get(destination_id, 0) | endpoint_bits.get((destination_id, edge.destination.field), 0)+ bits &= allowed+ if not bits:+ break+ if bits:+ owned_bits[node_id] = bits++ # A nested If cannot run until the dependencies gating its own execution are open. Those+ # prerequisites are implied by either branch gate it owns, so retain only the gate frontier.+ owner_prerequisites = {if_node_id: owned_bits.get(if_node_id, 0) for if_node_id in analysis.if_node_ids}+ _reduce_activation_owner_masks_to_frontier(owned_bits, owners, owner_prerequisites)++ analysis.activation_owner_masks_by_source = owned_bits+ return owned_bits+++def _reduce_activation_owner_masks_to_frontier(+ owner_masks_by_source: dict[str, int],+ owners: tuple[tuple[str, str], ...],+ owner_prerequisites: dict[str, int],+) -> None:+ """Drop only gates implied by a nested If's own admission dependencies."""+ for source_id, source_mask in tuple(owner_masks_by_source.items()):+ remaining_mask = source_mask+ frontier_mask = 0+ while remaining_mask:+ # Owners follow graph topological order, so nested gates precede the outer gates they imply.+ bit = remaining_mask & -remaining_mask+ owner_id, _branch = owners[bit.bit_length() - 1]+ frontier_mask |= bit+ remaining_mask &= ~bit+ remaining_mask &= ~owner_prerequisites.get(owner_id, 0)+ if frontier_mask:+ owner_masks_by_source[source_id] = frontier_mask+ else:+ del owner_masks_by_source[source_id]+++def _can_use_fresh_mixed_if_iterate_collect(state: "GraphExecutionState") -> bool:+ """Admit the bounded per-item Iterate/If/Collect topology."""if state._legacy_snapshot_loaded or len(state.graph.nodes) != 6 or len(state.graph.edges) != 7:return False@@ -104,212 +258,77 @@ def _can_use_fresh_mixed_if_iterate_collect(state: "GraphExecutionState") -> boo)-def _can_use_fresh_literal_if_iterate_collect(state: "GraphExecutionState") -> bool:- """Admit a literal If whose unselected item branch establishes its Iterate frame."""+def _can_use_fresh_flat_if_activation(state: "GraphExecutionState") -> bool:+ """Compile dependencies for every fresh acyclic, non-loop If graph."""if state._legacy_snapshot_loaded:return False- if_nodes = [node for node in state.graph.nodes.values() if isinstance(node, IfInvocation)]- iterate_nodes = [node for node in state.graph.nodes.values() if isinstance(node, IterateInvocation)]- collect_nodes = [node for node in state.graph.nodes.values() if isinstance(node, CollectInvocation)]- if len(if_nodes) != 1 or len(iterate_nodes) != 1 or len(collect_nodes) != 1:- return False- if any(- isinstance(node, (CallSavedWorkflowInvocation, ForInvocation, ForReturnInvocation))- for node in state.graph.nodes.values()- ):+ analysis = _get_if_graph_analysis(state)+ if analysis.has_forbidden_activation_node:return False+ if analysis.has_iterate_or_collect:+ return _can_use_fresh_mixed_if_iterate_collect(state)- if_node = if_nodes[0]- iterate_node = iterate_nodes[0]- collect_node = collect_nodes[0]- if state.graph._get_input_edges(if_node.id, "condition"):- return False+ return _get_if_topological_order(analysis) is not None- collection_edges = state.graph._get_input_edges(iterate_node.id, COLLECTION_FIELD)- if len(collection_edges) != 1:- return False- collection_edge = collection_edges[0]- collection_source = state.graph.get_node(collection_edge.source.node_id)- if (- collection_edge.source.field != COLLECTION_FIELD- or state.graph._get_input_edges(collection_source.id)- or state.graph._get_output_edges(collection_source.id) != [collection_edge]- ):- return False- collect_edges = state.graph._get_input_edges(collect_node.id, ITEM_FIELD)- if (- len(collect_edges) != 1- or collect_edges[0].source.node_id != if_node.id- or collect_edges[0].source.field != "value"- or state.graph._get_output_edges(if_node.id) != [collect_edges[0]]- or state.graph._get_input_edges(collect_node.id, COLLECTION_FIELD)- or state.graph._get_output_edges(collect_node.id)- ):+def _is_fresh_lazy_if_candidate(state: "GraphExecutionState", if_node_id: str) -> bool:+ """Return whether this If's unselected branch has no externally visible work."""+ if state._legacy_snapshot_loaded:return False- item_branch_sources: set[str] = set()- branch_sources: set[str] = set()- for branch_field in ("true_input", "false_input"):- branch_edges = state.graph._get_input_edges(if_node.id, branch_field)- if len(branch_edges) > 1:- return False- if not branch_edges:- continue- branch_edge = branch_edges[0]- branch_node = state.graph.get_node(branch_edge.source.node_id)- branch_inputs = state.graph._get_input_edges(branch_node.id)- if state.graph._get_output_edges(branch_node.id) != [branch_edge]:- return False- if not branch_inputs:- branch_sources.add(branch_node.id)- elif (- len(branch_inputs) == 1- and branch_inputs[0].source.node_id == iterate_node.id- and branch_inputs[0].source.field == ITEM_FIELD- ):- item_branch_sources.add(branch_node.id)- branch_sources.add(branch_node.id)- else:- return False-- item_branch_edges = [- edge for branch_source_id in item_branch_sources for edge in state.graph._get_input_edges(branch_source_id)- ]- if not item_branch_sources or state.graph._get_output_edges(iterate_node.id, ITEM_FIELD) != item_branch_edges:+ analysis = _get_if_graph_analysis(state)+ if len(analysis.if_node_ids) != 1 or analysis.if_node_ids[0] != if_node_id:return False+ cached = analysis.lazy_if_candidates.get(if_node_id)+ if cached is not None:+ return cached- expected_nodes = {- collection_source.id,- iterate_node.id,- if_node.id,- collect_node.id,- *branch_sources,- }- expected_edges = 2 + len(branch_sources) + len(item_branch_sources)- return set(state.graph.nodes) == expected_nodes and len(state.graph.edges) == expected_edges---def _can_use_fresh_flat_if_activation(state: "GraphExecutionState") -> bool:- """Admit fresh bounded independent-sibling or nested-If dependency compilation."""-- if state._legacy_snapshot_loaded:- return False+ condition_edges = [+ edge for edge in analysis.input_edges.get(if_node_id, ()) if edge.destination.field == "condition"+ ]+ if condition_edges and _can_use_fresh_mixed_if_iterate_collect(state):+ analysis.lazy_if_candidates[if_node_id] = True+ return True- if any(- isinstance(node, (CallSavedWorkflowInvocation, ForInvocation, ForReturnInvocation))- for node in state.graph.nodes.values()- ):+ if analysis.has_forbidden_activation_node or analysis.has_iterate_or_collect:+ analysis.lazy_if_candidates[if_node_id] = Falsereturn False- if any(isinstance(node, (IterateInvocation, CollectInvocation)) for node in state.graph.nodes.values()):- return _can_use_fresh_mixed_if_iterate_collect(state)- try:- source_graph = state._get_source_graph_flat()- if not nx.is_directed_acyclic_graph(source_graph):- return False- if_nodes = _get_fresh_if_nodes(state)- except nx.NetworkXUnfeasible:+ if _get_if_topological_order(analysis) is None:+ analysis.lazy_if_candidates[if_node_id] = Falsereturn False- if len(if_nodes) != 1:- if len(if_nodes) not in {2, 3, 4}:- return False-- if any(edge.type != "default" for edge in state.graph.edges):- return False-- if_node_ids = {node.id for node in if_nodes}- nested_edges = [- edge- for edge in state.graph.edges- if edge.source.node_id in if_node_ids and edge.destination.node_id in if_node_ids- ]- if not nested_edges:- expected_input_fields = {"condition", "true_input", "false_input"}- if any(- source_if.id != destination_if.id and nx.has_path(source_graph, source_if.id, destination_if.id)- for source_if in if_nodes- for destination_if in if_nodes- ):- return False- for if_node in if_nodes:- input_edges = state.graph._get_input_edges(if_node.id)- if (- len(input_edges) != len(expected_input_fields)- or {edge.destination.field for edge in input_edges} != expected_input_fields- ):- return False- if any(edge.source.node_id in if_node_ids for edge in input_edges):- return False- 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- ):- return False-- nested_edge_by_source = {edge.source.node_id: edge for edge in nested_edges}- nested_destinations = {edge.destination.node_id for edge in nested_edges}- if len(nested_edge_by_source) != len(nested_edges) or len(nested_destinations) != len(nested_edges):- return False-- chain_start_ids = if_node_ids - nested_destinations- chain_end_ids = if_node_ids - set(nested_edge_by_source)- if len(chain_start_ids) != 1 or len(chain_end_ids) != 1:- 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- 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- if len(state.graph._get_output_edges(current_if_id)) > 1:- return False+ condition_sources = {+ node_id+ for edge in condition_edges+ for node_id in (edge.source.node_id, *_get_if_ancestors(analysis, edge.source.node_id))+ }+ branch_sources = {+ branch: {+ node_id+ for edge in analysis.input_edges.get(if_node_id, ())+ if edge.destination.field == branch+ for node_id in (edge.source.node_id, *_get_if_ancestors(analysis, edge.source.node_id))+ }+ for branch in ("true_input", "false_input")+ }+ shared_sources = (branch_sources["true_input"] & branch_sources["false_input"]) | (+ (branch_sources["true_input"] | branch_sources["false_input"]) & condition_sources+ )- 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:+ for branch, sources in branch_sources.items():+ private_sources = sources - shared_sources+ for source_id in private_sources:+ for edge in analysis.output_edges.get(source_id, ()):+ if edge.destination.node_id in private_sources:+ continue+ if edge.destination.node_id == if_node_id and edge.destination.field == branch: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:+ analysis.lazy_if_candidates[if_node_id] = Falsereturn 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)- if (- len(input_edges) != len(expected_input_fields)- or {edge.destination.field for edge in input_edges} != expected_input_fields- or any(edge.source.node_id in if_node_ids and edge not in nested_edges for edge in input_edges)- ):- return False- else:- return False-+ analysis.lazy_if_candidates[if_node_id] = Truereturn True@@ -319,43 +338,57 @@ def _get_fresh_if_branch_sources(state: "GraphExecutionState", if_node_id: str,if cached is not None:return set(cached)- source_graph = state._get_source_graph_flat()- direct_sources = {edge.source.node_id for edge in state.graph._get_input_edges(if_node_id, branch_field)}+ analysis = _get_if_graph_analysis(state)+ direct_sources = {+ edge.source.node_id+ for edge in analysis.input_edges.get(if_node_id, ())+ if edge.destination.field == branch_field+ }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)+ branch_sources.update(_get_if_ancestors(analysis, source_node_id))+ source_node = analysis.nodes_by_id[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)+ for edge in analysis.output_edges.get(source_node_id, ())+ if not isinstance(analysis.nodes_by_id[edge.destination.node_id], IfInvocation)+ and not analysis.output_edges.get(edge.destination.node_id))if not state.graph._get_input_edges(if_node_id, "condition"):- iterator_graph = state._iterator_graph(source_graph)+ iterator_graph = state._iterator_graph(analysis.source_graph)frame_iterators = {ancestor_idfor ancestor_id in nx.ancestors(iterator_graph, if_node_id)- if isinstance(state.graph.get_node(ancestor_id), (ForInvocation, IterateInvocation))+ if isinstance(analysis.nodes_by_id[ancestor_id], (ForInvocation, IterateInvocation))}for iterator_id in frame_iterators:branch_sources.discard(iterator_id)- branch_sources.difference_update(nx.ancestors(source_graph, iterator_id))-- changed = True- while changed:- changed = False- for source_node_id in tuple(branch_sources):- if all(- edge.destination.node_id in branch_sources- or (edge.destination.node_id == if_node_id and edge.destination.field == branch_field)- for edge in state.graph._get_output_edges(source_node_id)- ):- continue- branch_sources.remove(source_node_id)- changed = True+ branch_sources.difference_update(_get_if_ancestors(analysis, iterator_id))++ invalid_output_counts: dict[str, int] = {}+ pending = deque()+ for source_node_id in branch_sources:+ invalid_count = sum(+ edge.destination.node_id not in branch_sources+ and not (edge.destination.node_id == if_node_id and edge.destination.field == branch_field)+ for edge in analysis.output_edges.get(source_node_id, ())+ )+ invalid_output_counts[source_node_id] = invalid_count+ if invalid_count:+ pending.append(source_node_id)+ while pending:+ source_node_id = pending.popleft()+ if source_node_id not in branch_sources:+ continue+ branch_sources.remove(source_node_id)+ for edge in analysis.input_edges.get(source_node_id, ()):+ parent_id = edge.source.node_id+ if parent_id in branch_sources:+ invalid_output_counts[parent_id] += 1+ if invalid_output_counts[parent_id] == 1:+ pending.append(parent_id)state._if_branch_sources_cache[cache_key] = frozenset(branch_sources)return branch_sources@@ -370,11 +403,30 @@ def _get_source_activation_dependencies(if not state._can_use_fresh_flat_if_activation():return state._if_activation_controller().get_source_dependencies(source_node_id, iteration_path)- dependencies = tuple(- ActivationDependency(owner_id=if_node.id, branch=branch_field, frame=iteration_path)- for if_node in _get_fresh_if_nodes(state)- for branch_field in ("true_input", "false_input")- if source_node_id in _get_fresh_if_branch_sources(state, if_node.id, branch_field)- )+ analysis = _get_if_graph_analysis(state)+ if analysis.has_iterate_or_collect:+ owners = tuple(+ (if_node.id, branch_field)+ for if_node in _get_fresh_if_nodes(state)+ for branch_field in ("true_input", "false_input")+ if source_node_id in _get_fresh_if_branch_sources(state, if_node.id, branch_field)+ )+ dependencies = tuple(+ ActivationDependency(owner_id=if_node_id, branch=branch_field, frame=iteration_path)+ for if_node_id, branch_field in owners+ )+ else:+ owner_masks_by_source = _get_flat_activation_owner_masks_by_source(state, analysis)+ owner_order = analysis.activation_owner_order or ()+ owner_mask = owner_masks_by_source.get(source_node_id, 0)+ dependencies_list = []+ while owner_mask:+ bit = owner_mask & -owner_mask+ if_node_id, branch_field = owner_order[bit.bit_length() - 1]+ dependencies_list.append(+ ActivationDependency(owner_id=if_node_id, branch=branch_field, frame=iteration_path)+ )+ owner_mask ^= bit+ dependencies = tuple(dependencies_list)state._tx_set_mapping(state._if_activation_dependencies_by_source, key, dependencies)return dependenciesdiff --git a/invokeai/app/services/shared/graph_if_runtime.py b/invokeai/app/services/shared/graph_if_runtime.pyindex c9a75e9438..f26e824f48 100644--- a/invokeai/app/services/shared/graph_if_runtime.py+++ b/invokeai/app/services/shared/graph_if_runtime.py@@ -1,9 +1,10 @@"""If activation and selected-branch context helpers operating on graph execution state."""-from typing import TYPE_CHECKING, Callable, Optional+from typing import TYPE_CHECKING, Any, Callable, Optionalfrom invokeai.app.invocations.fields import OutputScopefrom invokeai.app.invocations.logic import IfInvocation+from invokeai.app.invocations.primitives import BooleanInvocationfrom invokeai.app.services.shared.execution_engine.primitives import ActivationGatefrom invokeai.app.services.shared.execution_engine.scheduler import ActivationDependencyfrom invokeai.app.services.shared.graph_iterator_ancestry import _IteratorAncestry@@ -15,6 +16,7 @@ from invokeai.app.services.shared.graph_validation import (ForInvocation,IterateInvocation,get_output_field_scope,+ nx,)if TYPE_CHECKING:@@ -25,16 +27,193 @@ class UnsupportedIfIterationAxesError(ValueError):"""Raised when an If condition and its branches cannot share a supported open-axis scope."""+def _get_static_if_selection(state: "GraphExecutionState", node_id: str) -> Optional[str]:+ """Return the selected branch when the condition is a graph literal."""+ node = state.graph.get_node(node_id)+ assert isinstance(node, IfInvocation)+ condition_edges = state.graph._get_input_edges(node_id, "condition")+ if not condition_edges:+ return "true_input" if node.condition else "false_input"+ condition_edge = condition_edges[0]+ condition_source = state.graph.get_node(condition_edge.source.node_id)+ if (+ isinstance(condition_source, BooleanInvocation)+ and condition_edge.source.field == "value"+ and not state.graph._get_input_edges(condition_source.id, "value")+ ):+ return "true_input" if condition_source.value else "false_input"+ return None+++def _get_collects_before_iteration_boundary(state: "GraphExecutionState", edges: list[Edge]) -> set[str]:+ """Find Collects in an input's open ancestry, stopping where iteration or collection closes it."""+ collects: set[str] = set()+ visited: set[str] = set()+ pending = [edge.source.node_id for edge in edges]+ while pending:+ node_id = pending.pop()+ if node_id in visited:+ continue+ visited.add(node_id)+ node = state.graph.get_node(node_id)+ if isinstance(node, CollectInvocation):+ collects.add(node_id)+ continue+ if isinstance(node, (ForInvocation, IterateInvocation)):+ continue+ pending.extend(edge.source.node_id for edge in state.graph._get_input_edges(node_id))+ return collects+++def _is_sibling_collect_iterate_axis(+ state: "GraphExecutionState", iterator_ancestry: _IteratorAncestry, axis_id: str+) -> bool:+ """Return whether an Iterate axis replays a Collect fed by sibling Iterates."""+ prepared_ids = state.source_prepared_mapping.get(axis_id, ())+ cached = iterator_ancestry.sibling_collect_iterate_axis_cache.get(axis_id)+ if cached is not None and cached[0] is prepared_ids and cached[1] == len(prepared_ids):+ return cached[2]++ def cache_result(result: bool) -> bool:+ iterator_ancestry.sibling_collect_iterate_axis_cache[axis_id] = (prepared_ids, len(prepared_ids), result)+ return result++ collection_edges = state.graph._get_input_edges(axis_id, COLLECTION_FIELD)+ if len(collection_edges) != 1 or not isinstance(+ state.graph.get_node(collection_edges[0].source.node_id), CollectInvocation+ ):+ return cache_result(False)+ collect_id = collection_edges[0].source.node_id+ item_edges = state.graph._get_input_edges(collect_id, ITEM_FIELD)+ iterator_ids = [+ (axes[-1] if axes else None)+ for axes in (+ _get_edge_frame_axes(state, iterator_ancestry, edge, iterator_ancestry.frame_axes_cache)+ for edge in item_edges+ )+ ]+ is_sibling_collect = (+ len(iterator_ids) > 1+ and not any(_get_if_final_axes_for_edge(state, iterator_ancestry, edge)[0] for edge in item_edges)+ and all(iterator_id is not None for iterator_id in iterator_ids)+ and len(set(iterator_ids)) == len(iterator_ids)+ and all(+ isinstance(state.graph.get_node(iterator_id), IterateInvocation)+ for iterator_id in iterator_ids+ if iterator_id+ )+ )+ if not is_sibling_collect:+ return cache_result(False)++ # A numeric path alone is insufficient when prepared frames at that path carry different axes.+ registry = state._prepared_registry()+ axes_by_path: dict[tuple[int, ...], tuple[str, ...]] = {}+ projected_axes_by_path: dict[tuple[int, ...], tuple[str, ...]] = {}+ for prepared_id in prepared_ids:+ path = registry.get_iteration_path(prepared_id)+ axes = registry.get_iteration_axes(prepared_id)+ if path is None or axes is None or len(path) != len(axes):+ return cache_result(False)+ previous_axes = axes_by_path.setdefault(path, axes)+ if previous_axes != axes:+ return cache_result(False)+ projected_path = tuple(coordinate for axis, coordinate in zip(axes, path, strict=True) if axis != axis_id)+ projected_axes = tuple(axis for axis in axes if axis != axis_id)+ previous_projected_axes = projected_axes_by_path.setdefault(projected_path, projected_axes)+ if previous_projected_axes != projected_axes:+ return cache_result(False)+ return cache_result(True)+++def _project_prepared_iteration_paths(+ prepared_frames: list[tuple[tuple[int, ...], tuple[str, ...]]], reiterated_axes: set[str]+) -> Optional[dict[tuple[int, ...], tuple[int, ...]]]:+ """Project prepared paths only when the resulting numeric paths retain unique axis identities."""+ axes_by_path: dict[tuple[int, ...], tuple[str, ...]] = {}+ projected_axes_by_path: dict[tuple[int, ...], tuple[str, ...]] = {}+ projected_paths: dict[tuple[int, ...], tuple[int, ...]] = {}+ for path, axes in prepared_frames:+ if len(path) != len(axes):+ return None+ previous_axes = axes_by_path.setdefault(path, axes)+ if previous_axes != axes:+ return None+ projected_path = tuple(+ coordinate for axis_id, coordinate in zip(axes, path, strict=True) if axis_id not in reiterated_axes+ )+ projected_axes = tuple(axis_id for axis_id in axes if axis_id not in reiterated_axes)+ previous_projected_axes = projected_axes_by_path.setdefault(projected_path, projected_axes)+ if previous_projected_axes != projected_axes:+ return None+ projected_paths[path] = projected_path+ return projected_paths+++def _get_sibling_collect_iterate_axes_to_project(+ state: "GraphExecutionState", iterator_ancestry: _IteratorAncestry, axis_ids: list[str] | tuple[str, ...]+) -> set[str]:+ """Return the sibling Collect re-Iterate axes whose combined projection preserves frame identity."""+ if not axis_ids:+ return set()+ cache_key = tuple(axis_ids)+ prepared_sets = tuple(state.source_prepared_mapping.get(axis_id, ()) for axis_id in cache_key)+ prepared_set_token = tuple((prepared_ids, len(prepared_ids)) for prepared_ids in prepared_sets)+ prepared_ids = state.source_prepared_mapping.get(cache_key[-1], ())+ cached = iterator_ancestry.sibling_collect_iterate_projection_cache.get(cache_key)+ if (+ cached is not None+ and len(cached[0]) == len(prepared_set_token)+ and all(+ cached_set is current_set and cached_count == current_count+ for (cached_set, cached_count), (current_set, current_count) in zip(+ cached[0], prepared_set_token, strict=True+ )+ )+ ):+ return set(cached[1])++ def cache_result(result: set[str]) -> set[str]:+ iterator_ancestry.sibling_collect_iterate_projection_cache[cache_key] = (+ prepared_set_token,+ frozenset(result),+ )+ return result++ reiterated_axes = {+ axis_id+ for axis_id in axis_ids+ if isinstance(state.graph.get_node(axis_id), IterateInvocation)+ and _is_sibling_collect_iterate_axis(state, iterator_ancestry, axis_id)+ }+ reiterated_axes.intersection_update(axis_ids[-1:])+ if not reiterated_axes:+ return cache_result(set())++ registry = state._prepared_registry()+ prepared_frames = [+ (registry.get_iteration_path(prepared_id), registry.get_iteration_axes(prepared_id))+ for prepared_id in prepared_ids+ ]+ if prepared_ids and (+ len(prepared_frames) != len(prepared_ids)+ or any(path is None or axes is None for path, axes in prepared_frames)+ or _project_prepared_iteration_paths(prepared_frames, reiterated_axes) is None+ ):+ return cache_result(set())+ return cache_result(reiterated_axes)++def validate_if_iteration_axes(state: "GraphExecutionState") -> None:"""Reject unrelated condition and branch axes using graph topology alone."""iterator_ancestry = _IteratorAncestry(state)- collect_axes_cache: dict[str, Optional[tuple[str, ...]]] = {}+ frame_axes_cache: dict[str, Optional[tuple[str, ...]]] = {}for node_id, node in state.graph.nodes.items():if not isinstance(node, IfInvocation):continuecondition_edges = state.graph._get_input_edges(node_id, "condition")if not condition_edges:- _validate_frame_axes(state, iterator_ancestry, node_id, condition_edges, collect_axes_cache)+ _validate_frame_axes(state, iterator_ancestry, node_id, condition_edges, frame_axes_cache)continuecondition_iterators = iterator_ancestry.get_iterator_ancestors_for_edge(condition_edges[0])branch_edges = {@@ -72,7 +251,7 @@ def validate_if_iteration_axes(state: "GraphExecutionState") -> None:f"unrelated open iterator axes: condition {sorted(condition_iterators)}, "f"branch {sorted(branch_iterators)}")- _validate_frame_axes(state, iterator_ancestry, node_id, condition_edges, collect_axes_cache)+ _validate_frame_axes(state, iterator_ancestry, node_id, condition_edges, frame_axes_cache)def _validate_frame_axes(@@ -80,7 +259,7 @@ def _validate_frame_axes(iterator_ancestry: _IteratorAncestry,node_id: str,condition_edges: list[Edge],- collect_axes_cache: dict[str, Optional[tuple[str, ...]]],+ frame_axes_cache: dict[str, Optional[tuple[str, ...]]],) -> None:"""Reject frame sets an If cannot run in.@@ -97,7 +276,7 @@ def _validate_frame_axes(A root-frame condition cannot select between branches with different deeper axes."""if condition_edges:- _validate_collect_branch_axes(state, iterator_ancestry, node_id, condition_edges[0])+ _validate_collect_branch_axes(state, iterator_ancestry, node_id, condition_edges[0], frame_axes_cache)frame_iterators = iterator_ancestry.get_frame_iterators(node_id)if condition_edges:deciding_edges = condition_edges@@ -120,9 +299,7 @@ def _validate_frame_axes()if unselected_id not in iterator_ancestry.get_ordered_iterator_ancestors(node_id):continue- if unselected_id in _get_reopened_source_axes(- state, iterator_ancestry, selected_id, collect_axes_cache- ):+ if unselected_id in _get_reopened_source_axes(state, iterator_ancestry, selected_id, frame_axes_cache):continueraise UnsupportedIfIterationAxesError(f"If node '{node_id}' cannot run in the frames of unrelated open iterator axes: "@@ -150,7 +327,7 @@ def _get_reopened_source_axes(state: "GraphExecutionState",iterator_ancestry: _IteratorAncestry,axis_id: str,- collect_axes_cache: dict[str, Optional[tuple[str, ...]]],+ frame_axes_cache: dict[str, Optional[tuple[str, ...]]],) -> set[str]:"""Return the axes whose frames an axis, or an iterator enclosing it, reopens one-to-one.@@ -181,7 +358,7 @@ def _get_reopened_source_axes(collect_inputs = state.graph._get_input_edges(collect_id)if len(collect_inputs) != 1 or collect_inputs[0].destination.field != ITEM_FIELD:continue- item_axes = _get_edge_frame_axes(state, iterator_ancestry, collect_inputs[0], collect_axes_cache)+ item_axes = _get_edge_frame_axes(state, iterator_ancestry, collect_inputs[0], frame_axes_cache)if item_axes is None or not _is_nested_chain(iterator_ancestry, item_axes):continuesources.update(item_axes)@@ -190,40 +367,68 @@ def _get_reopened_source_axes(def _validate_collect_branch_axes(- state: "GraphExecutionState", iterator_ancestry: _IteratorAncestry, node_id: str, condition_edge: Edge+ state: "GraphExecutionState",+ iterator_ancestry: _IteratorAncestry,+ node_id: str,+ condition_edge: Edge,+ frame_axes_cache: dict[str, Optional[tuple[str, ...]]],) -> None:"""Reject a branch Collect that keeps axes open below a per-item condition unless the other branch shares them."""condition_axes = set(iterator_ancestry.get_frame_axes_for_edge(condition_edge))if not condition_axes:return- branch_axes: dict[str, set[str]] = {}+ branch_axes = {+ branch_field: set(axes)+ for branch_field, axes in _get_if_branch_frame_axes(state, iterator_ancestry, node_id, frame_axes_cache).items()+ }+ branch_collect_axes: dict[str, tuple[tuple[str, ...], ...]] = {}for branch_field in ("true_input", "false_input"):- axes: set[str] = set()- for edge in state.graph._get_input_edges(node_id, branch_field):- if isinstance(state.graph.get_node(edge.source.node_id), CollectInvocation):- axes.update(_get_collect_kept_axes(state, iterator_ancestry, edge.source.node_id))- else:- axes.update(iterator_ancestry.get_frame_axes_for_edge(edge))- branch_axes[branch_field] = axes+ branch_edges = state.graph._get_input_edges(node_id, branch_field)+ branch_nodes: set[str] = set()+ pending = [edge.source.node_id for edge in branch_edges]+ while pending:+ source_id = pending.pop()+ if source_id in branch_nodes:+ continue+ branch_nodes.add(source_id)+ source_node = state.graph.get_node(source_id)+ selected_field = (+ _get_static_if_selection(state, source_id) if isinstance(source_node, IfInvocation) else None+ )+ input_edges = state.graph._get_input_edges(source_id)+ if selected_field is not None:+ input_edges = [+ edge+ for edge in input_edges+ if edge.destination.field not in ("true_input", "false_input")+ or edge.destination.field == selected_field+ ]+ pending.extend(edge.source.node_id for edge in input_edges)+ retained_axes = set()+ branch_destinations = branch_nodes | {node_id}+ for collect_id in branch_nodes:+ if not isinstance(state.graph.get_node(collect_id), CollectInvocation):+ continue+ for edge in state.graph._get_output_edges(collect_id, COLLECTION_FIELD):+ if edge.destination.node_id not in branch_destinations or (+ edge.destination.node_id == node_id and edge.destination.field != branch_field+ ):+ continue+ axes = _get_edge_frame_axes(state, iterator_ancestry, edge, frame_axes_cache)+ if axes is not None and set(axes) > condition_axes:+ retained_axes.add(tuple(axes))+ branch_collect_axes[branch_field] = tuple(sorted(retained_axes))for branch_field, other_field in (("true_input", "false_input"), ("false_input", "true_input")):axes = branch_axes[branch_field]- if axes > condition_axes and axes != branch_axes[other_field]:+ if axes > condition_axes and (+ axes != branch_axes[other_field] or branch_collect_axes[branch_field] != branch_collect_axes[other_field]+ ):raise UnsupportedIfIterationAxesError(f"If node '{node_id}' cannot select branch input '{branch_field}' from deeper open iterator axes "f"kept by a Collect: condition {sorted(condition_axes)}, branch {sorted(axes)}")-def _get_collect_kept_axes(- state: "GraphExecutionState", iterator_ancestry: _IteratorAncestry, collect_id: str-) -> set[str]:- """Return the axes a Collect's output stays in: its item's axes except the innermost one, which it closes."""- kept: set[str] = set()- for edge in state.graph._get_input_edges(collect_id):- kept.update(_without_closed_axis(state, edge, iterator_ancestry.get_frame_axes_for_edge(edge)))- return kept--def _without_closed_axis(state: "GraphExecutionState", edge: Edge, axes: tuple[str, ...]) -> tuple[str, ...]:"""Return the axes a Collect input keeps: an item closes its innermost axis unless it is a For's final output."""source = state.graph.get_node(edge.source.node_id)@@ -247,54 +452,255 @@ def _get_edge_frame_axes(state: "GraphExecutionState",iterator_ancestry: _IteratorAncestry,edge: Edge,- collect_axes_cache: dict[str, Optional[tuple[str, ...]]],+ frame_axes_cache: dict[str, Optional[tuple[str, ...]]],+ *,+ use_runtime_if_selection: bool = False,) -> Optional[tuple[str, ...]]:- """Return the frames open on an edge, outer to inner, following a Collect source into the axes it keeps.+ """Resolve open axes through Collects and ordinary nodes that pass their collection output through.- Iterator ancestry stops at a Collect, so a Collect's output would otherwise look like it runs in no frames. A- Collect whose kept axes are not one nested chain, or that collects such a Collect, has no frame order a reopen could- pair with, so it yields None. Results are cached per Collect for one validation run and resolved with an explicit- stack, so a lattice or a long chain of Collects costs one pass per node.+ Iterator ancestry stops at a Collect, so following its output requires closing its item axis and retaining the+ outer axes. A result that is not one nested chain has no frame order to pair with and yields None. Results are+ cached for one validation run; Collect chains are resolved with an explicit stack."""- if not isinstance(state.graph.get_node(edge.source.node_id), CollectInvocation):- return iterator_ancestry.get_frame_axes_for_edge(edge)- pending = [edge.source.node_id]++ def can_use_static_axes(source_id: str) -> bool:+ if source_id not in iterator_ancestry.frame_axes_cache:+ return False+ source_node = state.graph.get_node(source_id)+ if not isinstance(source_node, IfInvocation):+ return True+ if not use_runtime_if_selection:+ return _get_static_if_selection(state, source_id) is None+ static_branches = _get_if_branch_frame_axes(+ state, iterator_ancestry, source_id, iterator_ancestry.frame_axes_cache+ )+ return static_branches["true_input"] == static_branches["false_input"]++ pending: list[tuple[Edge, bool]] = [(edge, False)]while pending:- collect_id = pending[-1]- if collect_id in collect_axes_cache:- pending.pop()+ current_edge, exiting = pending.pop()+ source_id = current_edge.source.node_id+ source_node = state.graph.get_node(source_id)+ if isinstance(source_node, (ForInvocation, IterateInvocation)):continue- input_edges = state.graph._get_input_edges(collect_id)- unresolved = [- input_edge.source.node_id- for input_edge in input_edges- if isinstance(state.graph.get_node(input_edge.source.node_id), CollectInvocation)- and input_edge.source.node_id not in collect_axes_cache- ]- if unresolved:- pending.extend(unresolved)+ if source_id in frame_axes_cache:continue- pending.pop()- kept: Optional[set[str]] = set()- for input_edge in input_edges:- source_id = input_edge.source.node_id- if isinstance(state.graph.get_node(source_id), CollectInvocation):- input_axes = collect_axes_cache[source_id]+ if can_use_static_axes(source_id):+ frame_axes_cache[source_id] = iterator_ancestry.frame_axes_cache[source_id]+ continue+ input_edges = state.graph._get_input_edges(source_id)+ if not exiting:+ pending.append((current_edge, True))+ pending.extend(+ (input_edge, False)+ for input_edge in reversed(input_edges)+ if input_edge.source.node_id not in frame_axes_cache+ and not can_use_static_axes(input_edge.source.node_id)+ )+ continue++ def get_input_axes(input_edge: Edge) -> Optional[tuple[str, ...]]:+ input_node = state.graph.get_node(input_edge.source.node_id)+ return (+ iterator_ancestry.get_frame_axes_for_edge(input_edge)+ if isinstance(input_node, (ForInvocation, IterateInvocation))+ else frame_axes_cache[input_edge.source.node_id]+ if input_edge.source.node_id in frame_axes_cache+ else iterator_ancestry.frame_axes_cache[input_edge.source.node_id]+ )++ axes: Optional[set[str]] = set()+ if isinstance(source_node, IfInvocation) and use_runtime_if_selection:+ branch_axes = {+ branch: {+ axis_id+ for input_edge in state.graph._get_input_edges(source_id, branch)+ for axis_id in (get_input_axes(input_edge) or ())+ }+ for branch in ("true_input", "false_input")+ }+ condition_edges = state.graph._get_input_edges(source_id, "condition")+ condition_axes = {+ axis_id for input_edge in condition_edges for axis_id in (get_input_axes(input_edge) or ())+ }+ if not condition_edges:+ selected = "true_input" if source_node.condition else "false_input"+ axes.update(+ branch_axes[selected]+ if any(branch_axes.values())+ else iterator_ancestry.get_frame_axes_for_edge(current_edge)+ )+ elif condition_axes:+ axes.update(condition_axes | branch_axes["true_input"] | branch_axes["false_input"])else:- input_axes = iterator_ancestry.get_frame_axes_for_edge(input_edge)- if input_axes is None:- kept = None- break- kept.update(_without_closed_axis(state, input_edge, input_axes))- ordered = None- if kept is not None:- ordered = tuple(- sorted(kept, key=lambda axis_id: (len(iterator_ancestry.get_frame_iterators(axis_id)), axis_id))+ selected_fields = {+ state._resolved_if_exec_branches.get(prepared_id)+ for prepared_id in state.source_prepared_mapping.get(source_id, ())+ }+ selected_fields.discard(None)+ axes.update(+ set().union(*(branch_axes[field] for field in selected_fields))+ if selected_fields+ else branch_axes["true_input"].intersection(branch_axes["false_input"])+ )+ elif isinstance(source_node, IfInvocation):+ selected_field = _get_static_if_selection(state, source_id)+ if selected_field is None:+ for input_edge in input_edges:+ input_axes = get_input_axes(input_edge)+ if input_axes is None:+ axes = None+ break+ axes.update(input_axes)+ else:+ other_field = "false_input" if selected_field == "true_input" else "true_input"+ branch_axes = {+ branch: {+ axis_id+ for input_edge in state.graph._get_input_edges(source_id, branch)+ for axis_id in (get_input_axes(input_edge) or ())+ }+ for branch in ("true_input", "false_input")+ }+ axes.update(branch_axes[selected_field])+ other_edges = state.graph._get_input_edges(source_id, other_field)+ if _get_collects_before_iteration_boundary(state, other_edges):+ axes.update(branch_axes[other_field] & branch_axes[selected_field])+ else:+ for input_edge in other_edges:+ final_axes, direct_axes = _get_if_final_axes_for_edge(state, iterator_ancestry, input_edge)+ axes.update(branch_axes[other_field] - (final_axes - direct_axes))+ for input_edge in state.graph._get_input_edges(source_id, "condition"):+ input_axes = get_input_axes(input_edge)+ if input_axes is None:+ axes = None+ break+ axes.update(input_axes)+ else:+ for input_edge in input_edges:+ input_axes = get_input_axes(input_edge)+ if input_axes is None:+ axes = None+ break+ if isinstance(source_node, CollectInvocation):+ axes.update(_without_closed_axis(state, input_edge, input_axes))+ else:+ axes.update(input_axes)+ ordered = (+ None+ if axes is None+ else tuple(sorted(axes, key=lambda axis_id: (len(iterator_ancestry.get_frame_iterators(axis_id)), axis_id)))+ )+ if ordered is not None and not _is_nested_chain(iterator_ancestry, ordered):+ ordered = None+ frame_axes_cache[source_id] = ordered+ if isinstance(state.graph.get_node(edge.source.node_id), (ForInvocation, IterateInvocation)):+ return iterator_ancestry.get_frame_axes_for_edge(edge)+ return frame_axes_cache[edge.source.node_id]+++def _get_if_branch_frame_axes(+ state: "GraphExecutionState",+ iterator_ancestry: _IteratorAncestry,+ node_id: str,+ frame_axes_cache: dict[str, Optional[tuple[str, ...]]],+) -> dict[str, tuple[str, ...]]:+ """Return each If branch's ordered open axes, resolving Collect-backed sources once per call."""+ result: dict[str, tuple[str, ...]] = {}+ for branch in ("true_input", "false_input"):+ axes: list[str] = []+ seen: set[str] = set()+ for edge in state.graph._get_input_edges(node_id, branch):+ for axis_id in _get_edge_frame_axes(state, iterator_ancestry, edge, frame_axes_cache) or ():+ if axis_id not in seen:+ seen.add(axis_id)+ axes.append(axis_id)+ result[branch] = tuple(axes)+ return result+++def _get_if_runtime_branch_frame_axes(+ state: "GraphExecutionState", iterator_ancestry: _IteratorAncestry, node_id: str+) -> dict[str, tuple[str, ...]]:+ """Resolve branch axes using the selections known to the current execution state."""+ result: dict[str, tuple[str, ...]] = {}+ frame_axes_cache: dict[str, Optional[tuple[str, ...]]] = {}+ for branch in ("true_input", "false_input"):+ axes: list[str] = []+ seen: set[str] = set()+ for edge in state.graph._get_input_edges(node_id, branch):+ for axis_id in (+ _get_edge_frame_axes(state, iterator_ancestry, edge, frame_axes_cache, use_runtime_if_selection=True)+ or ()+ ):+ if axis_id not in seen:+ seen.add(axis_id)+ axes.append(axis_id)+ result[branch] = tuple(axes)+ return result+++def _get_if_final_axes_for_edge(+ state: "GraphExecutionState", iterator_ancestry: _IteratorAncestry, edge: Edge+) -> tuple[set[str], set[str]]:+ """Return cached For-final and direct iterator axes reachable upstream of an edge."""+ cache = iterator_ancestry.if_final_axes_by_edge+ pending: list[tuple[Edge, bool]] = [(edge, False)]+ while pending:+ current_edge, exiting = pending.pop()+ if current_edge in cache:+ continue+ source_id = current_edge.source.node_id+ source_node = state.graph.get_node(source_id)+ if isinstance(source_node, ForInvocation):+ cache[current_edge] = (+ (set(iterator_ancestry.get_frame_axes_for_edge(current_edge)), set())+ if get_output_field_scope(source_node, current_edge.source.field) == OutputScope.Final+ else (set(), set(iterator_ancestry.get_frame_axes_for_edge(current_edge))))- if not _is_nested_chain(iterator_ancestry, ordered):- ordered = None- collect_axes_cache[collect_id] = ordered- return collect_axes_cache[edge.source.node_id]+ continue+ if isinstance(source_node, IterateInvocation):+ cache[current_edge] = (set(), set(iterator_ancestry.get_frame_axes_for_edge(current_edge)))+ continue+ input_edges = state.graph._get_input_edges(source_id)+ if not exiting:+ pending.append((current_edge, True))+ pending.extend((input_edge, False) for input_edge in reversed(input_edges) if input_edge not in cache)+ continue+ final_axes: set[str] = set()+ direct_axes: set[str] = set()+ for input_edge in input_edges:+ input_final, input_direct = cache[input_edge]+ final_axes.update(input_final)+ direct_axes.update(input_direct)+ cache[current_edge] = (final_axes, direct_axes)+ return cache[edge]+++def _get_if_static_frame_analysis(+ state: "GraphExecutionState", iterator_ancestry: _IteratorAncestry, node_id: str+) -> tuple[dict[str, tuple[str, ...]], dict[str, set[str]]]:+ """Cache branch axes and exclusively For-final axes for one source topology."""+ cache = getattr(iterator_ancestry, "_if_static_frame_analysis", None)+ if cache is None:+ cache = {}+ iterator_ancestry._if_static_frame_analysis = cache+ if node_id in cache:+ return cache[node_id]++ branch_axes = _get_if_branch_frame_axes(state, iterator_ancestry, node_id, iterator_ancestry.frame_axes_cache)+ final_axes: dict[str, set[str]] = {}+ for branch_field in ("true_input", "false_input"):+ branch_final_axes: set[str] = set()+ direct_axes: set[str] = set()+ for edge in state.graph._get_input_edges(node_id, branch_field):+ edge_final, edge_direct = _get_if_final_axes_for_edge(state, iterator_ancestry, edge)+ branch_final_axes.update(edge_final)+ direct_axes.update(edge_direct)+ final_axes[branch_field] = branch_final_axes - direct_axes++ cache[node_id] = (branch_axes, final_axes)+ return branch_axes, final_axesdef _get_effective_iteration_paths_for_edge(@@ -304,28 +710,22 @@ def _get_effective_iteration_paths_for_edge(get_prepared_nodes_for_source: Callable[[str], set[str]],get_prepared_edge_iteration_path: Callable[[Edge, str], tuple[int, ...]],iterator_ancestry: _IteratorAncestry,- effective_paths_by_edge: Optional[dict[tuple[str, str], set[tuple[int, ...]]]] = None,+ effective_paths_by_edge: Optional[dict[Edge, set[tuple[int, ...]]]] = None,) -> set[tuple[int, ...]]:- cache = effective_paths_by_edge if effective_paths_by_edge is not None else {}+ cache = (+ effective_paths_by_edge+ if effective_paths_by_edge is not None+ else iterator_ancestry.effective_iteration_paths_by_edge+ )pending: list[tuple[Edge, bool]] = [(edge, False)]while pending:current_edge, exiting_source = pending.pop()current_source_id = current_edge.source.node_id- cache_key = (current_source_id, current_edge.source.field)+ cache_key = current_edgeif cache_key in cache:continue- if exiting_source:- input_edges = state.graph._get_input_edges(current_source_id)- if not input_edges:- cache[cache_key] = {()}- else:- cache[cache_key] = set().union(- *(cache[(input_edge.source.node_id, input_edge.source.field)] for input_edge in input_edges)- )- continue-if current_source_id in visited_source_ids:cache[cache_key] = set()continue@@ -342,29 +742,66 @@ def _get_effective_iteration_paths_for_edge(continuesource_node = state.graph.get_node(current_source_id)+ if (+ isinstance(source_node, ForInvocation)+ and get_output_field_scope(source_node, current_edge.source.field) == OutputScope.Final+ ):+ frame_axes = iterator_ancestry.get_frame_axes_for_edge(current_edge)+ if not frame_axes:+ cache[cache_key] = {()}+ continue+ axis_id = frame_axes[-1]+ axis_edges = state.graph._get_output_edges(axis_id, ITEM_FIELD)+ cache[cache_key] = (+ {+ get_prepared_edge_iteration_path(axis_edges[0], prepared_id)+ for prepared_id in (+ get_prepared_nodes_for_source(axis_id) if axis_id in state.source_prepared_mapping else set()+ )+ }+ if axis_edges+ else set()+ )+ continue+ input_edges = state.graph._get_input_edges(current_source_id)+ if not exiting_source:+ pending.append((current_edge, True))+ pending.extend((input_edge, False) for input_edge in reversed(input_edges))+ continueif isinstance(source_node, CollectInvocation) and current_edge.source.field == COLLECTION_FIELD:input_edges = state.graph._get_input_edges(current_source_id)collapsed_paths: set[tuple[int, ...]] = set()- # Collect.item collapses its final open axis even before its own execution frame exists.- for input_edge in input_edges:- input_paths = _get_effective_iteration_paths_for_edge(+ frame_axes_cache = iterator_ancestry.frame_axes_cache+ retained_axes_by_edge = {+ input_edge: _without_closed_axis(state,input_edge,- visited_source_ids,- get_prepared_nodes_for_source,- get_prepared_edge_iteration_path,- iterator_ancestry,- cache,+ _get_edge_frame_axes(state, iterator_ancestry, input_edge, frame_axes_cache) or (),)- group_depth = len(iterator_ancestry.get_iterator_axes_for_edge(input_edge))- input_source = state.graph.get_node(input_edge.source.node_id)- # A For's final output already excludes the For's own axis, so the Collect closes nothing more.- is_for_final = isinstance(input_source, ForInvocation) and (- get_output_field_scope(input_source, input_edge.source.field) == OutputScope.Final- )- if input_edge.destination.field == ITEM_FIELD and not is_for_final:- group_depth = max(group_depth - 1, 0)+ for input_edge in input_edges+ }+ # Collect.item collapses its final open axis even before its own execution frame exists.+ for input_edge in input_edges:+ input_paths = cache[input_edge]+ group_depth = len(retained_axes_by_edge[input_edge])collapsed_paths.update(path[:group_depth] for path in input_paths)+ if not collapsed_paths and input_edges:+ for input_edge in input_edges:+ group_axes = retained_axes_by_edge[input_edge]+ if not group_axes:+ collapsed_paths.add(())+ continue+ axis_id = group_axes[-1]+ axis_edges = state.graph._get_output_edges(axis_id, ITEM_FIELD)+ if axis_edges:+ collapsed_paths.update(+ get_prepared_edge_iteration_path(axis_edges[0], prepared_id)+ for prepared_id in (+ get_prepared_nodes_for_source(axis_id)+ if axis_id in state.source_prepared_mapping+ else set()+ )+ )cache[cache_key] = collapsed_paths or ({()} if not input_edges else set())continueif isinstance(source_node, IfInvocation):@@ -378,16 +815,30 @@ def _get_effective_iteration_paths_for_edge(iterator_ancestry,))+ if not cache[cache_key] and current_edge.destination.field == ITEM_FIELD:+ branch_axes = _get_if_branch_frame_axes(+ state, iterator_ancestry, current_source_id, iterator_ancestry.frame_axes_cache+ )+ if branch_axes["true_input"] == branch_axes["false_input"]:+ group_axes = _without_closed_axis(state, current_edge, branch_axes["true_input"])+ if not group_axes:+ cache[cache_key] = {()}+ else:+ axis_edges = state.graph._get_output_edges(group_axes[-1], ITEM_FIELD)+ if axis_edges:+ cache[cache_key] = {+ get_prepared_edge_iteration_path(axis_edges[0], prepared_id)+ for prepared_id in (+ get_prepared_nodes_for_source(group_axes[-1])+ if group_axes[-1] in state.source_prepared_mapping+ else set()+ )+ }continue- input_edges = state.graph._get_input_edges(current_source_id)- if not input_edges:- cache[cache_key] = {()}- continue- pending.append((current_edge, True))- pending.extend((input_edge, False) for input_edge in reversed(input_edges))+ cache[cache_key] = set().union(*(cache[input_edge] for input_edge in input_edges)) if input_edges else {()}- return cache[(edge.source.node_id, edge.source.field)]+ return cache[edge]def _get_if_iteration_paths_with_ancestry(@@ -398,12 +849,65 @@ def _get_if_iteration_paths_with_ancestry(get_prepared_edge_iteration_path: Callable[[Edge, str], tuple[int, ...]],iterator_ancestry: _IteratorAncestry,) -> list[tuple[int, ...]]:- """Infer selected branch paths using one ancestry context for all recursion."""+ """Infer selected branch paths using the ancestry context's iterative edge traversal."""+ path_terminal = object()+ has_descendant = object()++ def make_path_index(paths: set[tuple[int, ...]]) -> dict[object, Any]:+ index: dict[object, Any] = {}+ for path in paths:+ node = index+ if path:+ node[has_descendant] = True+ for path_index, coordinate in enumerate(path):+ node = node.setdefault(coordinate, {})+ if path_index < len(path) - 1:+ node[has_descendant] = True+ node[path_terminal] = True+ return index++ def has_path_prefix(path: tuple[int, ...], index: dict[object, Any]) -> bool:+ node = index+ if path_terminal in node:+ return True+ for coordinate in path:+ node = node.get(coordinate)+ if not isinstance(node, dict):+ return False+ if path_terminal in node:+ return True+ return False++ def has_longer_path(path: tuple[int, ...], index: dict[object, Any]) -> bool:+ node = index+ for coordinate in path:+ node = node.get(coordinate)+ if not isinstance(node, dict):+ return False+ return has_descendant in node+effective_paths_by_edge = iterator_ancestry.effective_iteration_paths_by_edgenode = state.graph.get_node(node_id)assert isinstance(node, IfInvocation)next_visited_source_ids = {*visited_source_ids, node_id}condition_edges = state.graph._get_input_edges(node_id, "condition")+ condition_axes: set[str] = set()+ for edge in condition_edges:+ try:+ condition_axes.update(iterator_ancestry.get_frame_axes_for_edge(edge))+ except nx.NetworkXError:+ # A filtered materialization view can omit unresolved condition sources.+ continue+ _, branch_for_final_axes = _get_if_static_frame_analysis(state, iterator_ancestry, node_id)+ branch_axes = {+ branch: set(axes)+ for branch, axes in _get_if_runtime_branch_frame_axes(state, iterator_ancestry, node_id).items()+ }+ shared_deeper_branch_axes = (+ bool(branch_axes["true_input"])+ and branch_axes["true_input"] == branch_axes["false_input"]+ and branch_axes["true_input"] > condition_axes+ )condition_selections: list[tuple[Optional[tuple[int, ...]], str]] = []if condition_edges:@@ -422,9 +926,13 @@ def _get_if_iteration_paths_with_ancestry(condition_selections.append((None, selected_field))paths: set[tuple[int, ...]] = set()+ unselected_final_axes: set[str] = set()has_selected_edges = Falsehas_unresolved_selected_source = Falsefor condition_path, selected_field in condition_selections:+ if condition_path in (None, ()):+ other_field = "false_input" if selected_field == "true_input" else "true_input"+ unselected_final_axes.update(branch_for_final_axes[other_field] - branch_axes[selected_field])selected_edges = state.graph._get_input_edges(node_id, selected_field)has_selected_edges = has_selected_edges or bool(selected_edges)has_unresolved_selected_source = has_unresolved_selected_source or any(@@ -457,8 +965,47 @@ def _get_if_iteration_paths_with_ancestry(for edge in selected_edges)):- # The selected branch is not materialized yet; the If still runs in the condition's frame.- branch_paths = {condition_path}+ if shared_deeper_branch_axes:+ other_field = "false_input" if selected_field == "true_input" else "true_input"+ other_edges = state.graph._get_input_edges(node_id, other_field)+ branch_paths = (+ set().union(+ *(+ _get_effective_iteration_paths_for_edge(+ state,+ edge,+ next_visited_source_ids,+ get_prepared_nodes_for_source,+ get_prepared_edge_iteration_path,+ iterator_ancestry,+ effective_paths_by_edge,+ )+ for edge in other_edges+ )+ )+ if other_edges+ else set()+ )+ else:+ # The selected branch is not materialized yet; the If still runs in the condition's frame.+ branch_paths = {condition_path}++ if shared_deeper_branch_axes and condition_path is not None:+ branch_paths = {+ branch_path+ for branch_path in branch_paths+ if len(branch_path) > len(condition_path) and branch_path[: len(condition_path)] == condition_path+ }+ if not branch_paths:+ ordered_branch_axes = _get_if_branch_frame_axes(+ state, iterator_ancestry, node_id, iterator_ancestry.frame_axes_cache+ )[selected_field]+ axis_edges = state.graph._get_output_edges(ordered_branch_axes[-1], ITEM_FIELD)+ if axis_edges and ordered_branch_axes[-1] in state.source_prepared_mapping:+ branch_paths = {+ get_prepared_edge_iteration_path(axis_edges[0], prepared_id)+ for prepared_id in get_prepared_nodes_for_source(ordered_branch_axes[-1])+ }for branch_path in branch_paths:if condition_path is None:@@ -471,7 +1018,42 @@ def _get_if_iteration_paths_with_ancestry(# The If runs once per frame of the innermost iterator open at it; validation keeps those iterators nested. An# iterator that has not run leaves the frames unknown, and one with no items leaves the If no frames. An iterator# reaching the If only through a For's final output does not add frames here.- frame_iterators = iterator_ancestry.get_ordered_iterator_ancestors(node_id)+ frame_iterators = [+ axis_id+ for axis_id in iterator_ancestry.get_ordered_iterator_ancestors(node_id)+ if axis_id not in unselected_final_axes+ ]+ if condition_selections:+ selected_axes_by_field = {+ branch_field: {+ axis_id+ for edge in state.graph._get_input_edges(node_id, branch_field)+ for axis_id in (+ _get_edge_frame_axes(+ state,+ iterator_ancestry,+ edge,+ iterator_ancestry.frame_axes_cache,+ use_runtime_if_selection=True,+ )+ or ()+ )+ }+ for branch_field in ("true_input", "false_input")+ }+ for _, selected_field in condition_selections:+ selected_axes = condition_axes | selected_axes_by_field[selected_field]+ if not selected_axes:+ continue+ other_field = "false_input" if selected_field == "true_input" else "true_input"+ other_edges = state.graph._get_input_edges(node_id, other_field)+ if _get_collects_before_iteration_boundary(state, other_edges):+ frame_iterators = [+ axis_id+ for axis_id in frame_iterators+ if axis_id not in selected_axes_by_field[other_field] or axis_id in selected_axes+ ]+ preserve_projected_prefixes = Falseif frame_iterators:innermost_id = frame_iterators[-1]if innermost_id not in state.executed and innermost_id not in state.source_prepared_mapping:@@ -487,12 +1069,40 @@ def _get_if_iteration_paths_with_ancestry(if iterator_edgeselse {state._get_iteration_path(prepared_id) for prepared_id in prepared_ids})+ branch_paths = paths+ reiterated_axes = _get_sibling_collect_iterate_axes_to_project(state, iterator_ancestry, frame_iterators)+ if reiterated_axes:+ registry = state._prepared_registry()+ prepared_frames: list[tuple[tuple[int, ...], tuple[str, ...]]] = []+ for prepared_id in prepared_ids:+ path = (+ get_prepared_edge_iteration_path(iterator_edges[0], prepared_id)+ if iterator_edges+ else state._get_iteration_path(prepared_id)+ )+ axes = registry.get_iteration_axes(prepared_id)+ if axes is None:+ prepared_frames = []+ break+ prepared_frames.append((path, axes))+ projected_paths = _project_prepared_iteration_paths(prepared_frames, reiterated_axes)+ if projected_paths:+ frame_paths = set(projected_paths.values())+ paths = {projected_paths.get(path, path) for path in paths}+ preserve_projected_prefixes = True+ branch_path_index = make_path_index(branch_paths)+ frame_path_index = make_path_index(frame_paths)paths = {- frame_path if frame_path[: len(branch_path)] == branch_path else branch_path- for branch_path in paths+ frame_pathfor frame_path in frame_paths- if frame_path[: len(branch_path)] == branch_path or branch_path[: len(frame_path)] == frame_path- }+ if not (+ preserve_projected_prefixes+ and frame_path+ and frame_path not in branch_paths+ and has_longer_path(frame_path, branch_path_index)+ )+ and has_path_prefix(frame_path, branch_path_index)+ } | {branch_path for branch_path in branch_paths if has_path_prefix(branch_path, frame_path_index)}if not paths:if not has_selected_edges:@@ -501,7 +1111,10 @@ def _get_if_iteration_paths_with_ancestry(if not iterator_ancestry.has_iterator_ancestor(node_id):return [()]return []- return sorted(path for path in paths if not any(path != other and other[: len(path)] == path for other in paths))+ if preserve_projected_prefixes:+ return sorted(paths)+ paths_index = make_path_index(paths)+ return sorted(path for path in paths if not has_longer_path(path, paths_index))def _record_activation_dependencies(@@ -527,6 +1140,9 @@ def _get_source_activation_dependencies_for_preparation(state: "GraphExecutionState", source_node_id: str, iteration_path: tuple[int, ...]) -> tuple[ActivationDependency, ...]:dependencies = state._get_source_activation_dependencies(source_node_id, iteration_path)+ for extra_dependency in _get_static_selected_collect_iterate_dependencies(state, source_node_id, iteration_path):+ if extra_dependency not in dependencies:+ dependencies = (*dependencies, extra_dependency)if not dependencies:return dependencies@@ -545,17 +1161,43 @@ def _get_source_activation_dependencies_for_preparation(shared_axis_indices = [(owner_axes.index(axis_id), source_axes.index(axis_id)) for axis_id in owner_axes if axis_id in source_axes]- candidate_frames = state._prepared_if_exec_frames(dependency.owner_id)- matching_frames = [- frame- for frame in candidate_frames- if all(- owner_index < len(frame)- and source_index < len(iteration_path)- and frame[owner_index] == iteration_path[source_index]- for owner_index, source_index in shared_axis_indices+ if not shared_axis_indices and owner_axes and iteration_path:+ iterator_ancestry = runtime._iterator_ancestry+ edge_axes = list(+ dict.fromkeys(+ axis_id+ for edge in state.graph._get_input_edges(source_node_id)+ for axis_id in iterator_ancestry.get_frame_axes_for_edge(edge)+ if axis_id in owner_axes+ ))- ]+ shared_axis_indices = [+ (owner_axes.index(axis_id), edge_axes.index(axis_id)) for axis_id in owner_axes if axis_id in edge_axes+ ]+ exact_frame_mapping = (+ len(iteration_path) == len(owner_axes) == len(source_axes)+ and len(shared_axis_indices) == len(owner_axes)+ and all(owner_index == source_index for owner_index, source_index in shared_axis_indices)+ )+ matching_frames = (+ [iteration_path]+ if exact_frame_mapping and state._prepared_if_exec_ids(dependency.owner_id, iteration_path)+ else []+ )+ if not matching_frames:+ candidate_frames = state._prepared_if_exec_frames(dependency.owner_id)+ matching_frames = [+ frame+ for frame in candidate_frames+ if all(+ owner_index < len(frame)+ and source_index < len(iteration_path)+ and frame[owner_index] == iteration_path[source_index]+ for owner_index, source_index in shared_axis_indices+ )+ ]+ if not matching_frames and iteration_path and candidate_frames == ((),):+ matching_frames = [()]if not matching_frames:resolved_dependencies.append(dependency)continue@@ -573,6 +1215,51 @@ def _get_source_activation_dependencies_for_preparation(return tuple(resolved_dependencies)+def _get_static_selected_collect_iterate_dependencies(+ state: "GraphExecutionState", source_node_id: str, iteration_path: tuple[int, ...]+) -> tuple[ActivationDependency, ...]:+ """Return selected-branch dependencies for sources owned by empty Collect-fed Iterate scopes."""+ runtime = state._runtime()+ owners_by_source = runtime._static_selected_collect_iterate_owners+ if owners_by_source is None:+ ancestry = runtime._iterator_ancestry+ owner_sources: dict[str, list[tuple[str, str]]] = {}+ for if_node_id, node in state.graph.nodes.items():+ if not isinstance(node, IfInvocation):+ continue+ selected_field = _get_static_if_selection(state, if_node_id)+ if selected_field is None:+ continue+ other_field = "false_input" if selected_field == "true_input" else "true_input"+ selected_axes = {+ axis_id+ for edge in state.graph._get_input_edges(if_node_id, selected_field)+ for axis_id in ancestry.get_frame_axes_for_edge(edge)+ }+ other_axes = {+ axis_id+ for edge in state.graph._get_input_edges(if_node_id, other_field)+ for axis_id in ancestry.get_frame_axes_for_edge(edge)+ }+ if not any(+ isinstance(state.graph.get_node(axis_id), IterateInvocation)+ and _get_collects_before_iteration_boundary(+ state, state.graph._get_input_edges(axis_id, COLLECTION_FIELD)+ )+ for axis_id in other_axes - selected_axes+ ):+ continue+ for source_id in state._get_fresh_if_branch_sources(if_node_id, selected_field):+ owner_sources.setdefault(source_id, []).append((if_node_id, selected_field))+ owners_by_source = {source_id: tuple(owners) for source_id, owners in owner_sources.items()}+ runtime._static_selected_collect_iterate_owners = owners_by_source++ return tuple(+ ActivationDependency(owner_id=owner_id, branch=branch, frame=iteration_path)+ for owner_id, branch in owners_by_source.get(source_node_id, ())+ )++def _get_selected_if_frames_for_preparation(state: "GraphExecutionState", if_node_id: str, branch_field: Optional[str]) -> tuple[tuple[int, ...], ...]:@@ -625,18 +1312,47 @@ def _is_activation_axis_complete(state: "GraphExecutionState", axis_source_id: sdef _is_source_inactive(state: "GraphExecutionState", source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:- dependencies = state._get_source_activation_dependencies(source_node_id, iteration_path)+ dependencies = _get_source_activation_dependencies_for_preparation(state, source_node_id, iteration_path)if not dependencies:return False++ if any(+ axis_id in state.executed and not state.source_prepared_mapping.get(axis_id)+ for axis_id in state._runtime()._get_ordered_iterator_sources(source_node_id)+ ):+ return Trueif iteration_path:- prepared_dependencies = _get_source_activation_dependencies_for_preparation(- state, source_node_id, iteration_path+ return any(state._is_activation_dependency_rejected(dependency) for dependency in dependencies)++ def has_completed_empty_if(dependency: ActivationDependency) -> bool:+ owner_id = dependency.owner_id+ if (+ state._legacy_snapshot_loaded+ or not isinstance(state.graph.nodes.get(owner_id), IfInvocation)+ or state._is_fresh_lazy_if_candidate(owner_id)+ or owner_id not in state.executed+ or owner_id not in state.source_prepared_mapping+ or state.source_prepared_mapping[owner_id]+ ):+ return False+ return not any(+ source_id == owner_id and isinstance(state.execution_graph.nodes.get(exec_node_id), IfInvocation)+ for exec_node_id, source_id in state.prepared_source_mapping.items())- return any(state._is_activation_dependency_rejected(dependency) for dependency in prepared_dependencies)frames = {frame for dependency in dependencies for frame in state._prepared_if_exec_frames(dependency.owner_id)}if not frames:- return all(_has_empty_if_frame(state, dependency.owner_id) for dependency in dependencies)+ if any(has_completed_empty_if(dependency) for dependency in dependencies):+ return True+ if any(+ isinstance((owner := state.graph.get_node(dependency.owner_id)), IfInvocation)+ and state._is_fresh_lazy_if_candidate(dependency.owner_id)+ and not state.graph._get_input_edges(dependency.owner_id, "condition")+ and dependency.branch != ("true_input" if owner.condition else "false_input")+ for dependency in dependencies+ ):+ return True+ return any(_has_empty_if_frame(state, dependency.owner_id) for dependency in dependencies)source_axes = set(state._runtime()._get_ordered_iterator_sources(source_node_id))for dependency in dependencies:@@ -644,11 +1360,33 @@ def _is_source_inactive(if axis_source_id not in source_axes and not _is_activation_axis_complete(state, axis_source_id):return False- return all(- (prepared_dependencies := _get_source_activation_dependencies_for_preparation(state, source_node_id, frame))- and any(state._is_activation_dependency_rejected(dependency) for dependency in prepared_dependencies)- for frame in frames- )+ materializer = state._materializer()+ source_iterator_axes = materializer._get_collect_source_iterator_ids(source_node_id)++ def is_inactive_at_frame(frame: tuple[int, ...]) -> bool:+ prepared_dependencies = _get_source_activation_dependencies_for_preparation(state, source_node_id, frame)+ if not prepared_dependencies:+ return False+ if any(has_completed_empty_if(dependency) for dependency in prepared_dependencies):+ return True+ if any(state._is_activation_dependency_rejected(dependency) for dependency in prepared_dependencies):+ return True+ if not all(state._is_activation_dependency_satisfied(dependency) for dependency in prepared_dependencies):+ return False++ for dependency in prepared_dependencies:+ owner_axes = tuple(state._runtime()._get_ordered_iterator_sources(dependency.owner_id))+ if (+ len(source_iterator_axes) > len(owner_axes)+ and tuple(source_iterator_axes[: len(owner_axes)]) == owner_axes+ and materializer._has_empty_iterate_parent_group(+ source_iterator_axes[len(owner_axes)], owner_axes, dependency.frame+ )+ ):+ return True+ return False++ return all(is_inactive_at_frame(frame) for frame in frames)def _has_empty_if_frame(state: "GraphExecutionState", if_node_id: str) -> bool:@@ -656,11 +1394,94 @@ def _has_empty_if_frame(state: "GraphExecutionState", if_node_id: str) -> bool:if not isinstance(state.graph.nodes.get(if_node_id), IfInvocation):return False+ ancestry = state._runtime()._iterator_ancestry+ condition_edges = state.graph._get_input_edges(if_node_id, "condition")+ axes = {axis_id for edge in condition_edges for axis_id in ancestry.get_frame_axes_for_edge(edge)}+ static_selection = _get_static_if_selection(state, if_node_id)+ branch_axes = (+ _get_if_static_frame_analysis(state, ancestry, if_node_id)[0]+ if static_selection is not None+ else _get_if_runtime_branch_frame_axes(state, ancestry, if_node_id)+ )+ _, branch_final_axes = _get_if_static_frame_analysis(state, ancestry, if_node_id)++ selected_fields: set[str] = set()+ if static_selection is not None:+ selected_fields.add(static_selection)+ else:+ condition_edge = condition_edges[0]+ for exec_id in state.source_prepared_mapping.get(condition_edge.source.node_id, ()):+ if exec_id in state.results:+ value = getattr(state.results[exec_id], condition_edge.source.field)+ selected_fields.add("true_input" if value else "false_input")++ for branch_field, branch_axis_ids in branch_axes.items():+ branch_for_final_axes = branch_final_axes[branch_field]+ if branch_field in selected_fields:+ axes.update(branch_axis_ids)+ elif static_selection is not None:+ branch_edges = state.graph._get_input_edges(if_node_id, branch_field)+ if _get_collects_before_iteration_boundary(state, branch_edges):+ selected_axes = branch_axes[static_selection]+ axes.update((set(branch_axis_ids) & set(selected_axes)) - branch_for_final_axes)+ else:+ axes.update(set(branch_axis_ids) - branch_for_final_axes)+ else:+ # Preserve the If's old empty-iterator behavior, but an unselected For final must not add frames.+ axes.update(set(branch_axis_ids) - branch_for_final_axes)return any(isinstance(state.graph.get_node(iterator_id), IterateInvocation)and iterator_id in state.executedand not state.source_prepared_mapping.get(iterator_id)- for iterator_id in state._runtime()._iterator_ancestry.get_frame_iterators(if_node_id)+ for iterator_id in axes+ )+++def _has_empty_selected_for_final_frame(+ state: "GraphExecutionState", iterator_ancestry: _IteratorAncestry, if_node_id: str+) -> bool:+ """Check for an empty root-selected branch whose open axes all come from For final outputs."""+ condition_edges = state.graph._get_input_edges(if_node_id, "condition")+ if not condition_edges or any(iterator_ancestry.get_frame_axes_for_edge(edge) for edge in condition_edges):+ return False+ branch_axes, branch_final_axes = _get_if_static_frame_analysis(state, iterator_ancestry, if_node_id)+ condition_edge = condition_edges[0]+ for exec_id in state.source_prepared_mapping.get(condition_edge.source.node_id, ()):+ if exec_id not in state.results:+ continue+ value = getattr(state.results[exec_id], condition_edge.source.field)+ selected_field = "true_input" if value else "false_input"+ selected_axes = set(branch_axes[selected_field])+ final_axes = branch_final_axes[selected_field]+ if not selected_axes or not selected_axes <= final_axes:+ continue+ if not set(iterator_ancestry.get_ordered_iterator_ancestors(if_node_id)) <= final_axes:+ continue+ if any(+ isinstance(state.graph.get_node(axis_id), IterateInvocation)+ and axis_id in state.executed+ and not state.source_prepared_mapping.get(axis_id)+ for axis_id in final_axes+ ):+ return True+ return False+++def _has_unresolved_if_frame_axes(+ state: "GraphExecutionState", if_node_id: str, iterator_ancestry: _IteratorAncestry+) -> bool:+ condition_axes = {+ axis_id+ for edge in state.graph._get_input_edges(if_node_id, "condition")+ for axis_id in iterator_ancestry.get_frame_axes_for_edge(edge)+ }+ branch_axes = _get_if_runtime_branch_frame_axes(state, iterator_ancestry, if_node_id)+ axes = branch_axes["true_input"]+ return (+ bool(axes)+ and axes == branch_axes["false_input"]+ and set(axes) > condition_axes+ and any(axis_id not in state.source_prepared_mapping and axis_id not in state.executed for axis_id in axes))@@ -700,7 +1521,17 @@ def _record_compatibility_activation_token(def _is_activation_dependency_satisfied(state: "GraphExecutionState", dependency: ActivationDependency) -> bool:"""Check one opaque plan requirement against durable gate and token state."""- matching_gate_ids = state._prepared_if_exec_ids(dependency.owner_id, dependency.frame)+ lazy_candidate = not state._legacy_snapshot_loaded and state._is_fresh_lazy_if_candidate(dependency.owner_id)+ if lazy_candidate:+ matching_gate_ids = state._prepared_if_exec_ids(dependency.owner_id, dependency.frame)+ else:+ matching_gate_ids = tuple(+ exec_node_id+ for exec_node_id in state._prepared_registry().get_prepared_ids_with_overlapping_path(+ dependency.owner_id, dependency.frame+ )+ if isinstance(state.execution_graph.nodes.get(exec_node_id), IfInvocation)+ )if not matching_gate_ids:return False@@ -712,19 +1543,24 @@ def _is_activation_dependency_satisfied(state: "GraphExecutionState", dependencyor gate.frame.frame_id != expected_ref.frame.frame_idor gate.frame.iteration_path != expected_ref.frame.iteration_pathor gate.frame.workflow_call_depth != expected_ref.frame.workflow_call_depth- or gate.frame.iteration_path != dependency.frame+ or (lazy_candidate and gate.frame.iteration_path != dependency.frame)):return False- if not gate.is_active(dependency.branch, owner_id=gate_id, frame=gate.frame):+ activation_branch = dependency.branch+ if not state._legacy_snapshot_loaded:+ if not gate.resolved or gate.selected_branch is None:+ return False+ activation_branch = gate.selected_branch+ if not gate.is_active(activation_branch, owner_id=gate_id, frame=gate.frame):return False- token = state.execution_tokens.get(f"{expected_ref.reference_id}:activation:{dependency.branch}")+ token = state.execution_tokens.get(f"{expected_ref.reference_id}:activation:{activation_branch}")if token is None or not (- token.token_id == f"{expected_ref.reference_id}:activation:{dependency.branch}"+ token.token_id == f"{expected_ref.reference_id}:activation:{activation_branch}"and token.reference_id == expected_ref.reference_idand token.owner_node_id == gate_idand token.token_kind == "activation"- and token.port == dependency.branch- and token.value == dependency.branch+ and token.port == activation_branch+ and token.value == activation_branchand token.frame.state_id == expected_ref.frame.state_idand token.frame.frame_id == expected_ref.frame.frame_idand token.frame.iteration_path == expected_ref.frame.iteration_path@@ -737,6 +1573,9 @@ def _is_activation_dependency_satisfied(state: "GraphExecutionState", dependencydef _is_activation_dependency_rejected(state: "GraphExecutionState", dependency: ActivationDependency) -> bool:"""Return whether a resolved gate explicitly selected another branch."""+ if not state._legacy_snapshot_loaded and not state._is_fresh_lazy_if_candidate(dependency.owner_id):+ return False+matching_gate_ids = state._prepared_if_exec_ids(dependency.owner_id, dependency.frame)for gate_id in matching_gate_ids:gate = state._activation_gate(gate_id)@@ -769,9 +1608,12 @@ def _resolve_activation_gate(state: "GraphExecutionState", exec_node_id: str, brstate._completed_source_ids_cache = Nonestate._tx_record(lambda: runtime.replace_gate(previous))materializer = state.__pydantic_private__["_runtime_state"].execution_materializer- if materializer is not None:+ if materializer is not None and state._legacy_snapshot_loaded:source_if_id = state._prepared_registry().get_source_node_id(exec_node_id)materializer._queue_rejected_activation_branch(source_if_id, branch)+ materializer._queue_selected_empty_iterate_branch_retirements(+ source_if_id, branch, gate.frame.iteration_path+ )return changeddiff --git a/invokeai/app/services/shared/graph_iterator_ancestry.py b/invokeai/app/services/shared/graph_iterator_ancestry.pyindex e28570dbe4..338eff451d 100644--- a/invokeai/app/services/shared/graph_iterator_ancestry.py+++ b/invokeai/app/services/shared/graph_iterator_ancestry.py@@ -3,12 +3,23 @@ from typing import TYPE_CHECKING, Optionalfrom invokeai.app.invocations.fields import OutputScopefrom invokeai.app.invocations.loops import ForInvocationfrom invokeai.app.services.shared.graph_models import Edge-from invokeai.app.services.shared.graph_validation import IterateInvocation, get_output_field_scope, nx+from invokeai.app.services.shared.graph_validation import Graph, IterateInvocation, get_output_field_scope, nxif TYPE_CHECKING:from invokeai.app.services.shared.graph import GraphExecutionState+def _get_ordered_input_edges(graph: Graph, input_edges: list[Edge]) -> list[Edge]:+ if not input_edges:+ return []+ destination = graph.get_node(input_edges[0].destination.node_id)+ field_order = {field: index for index, field in enumerate(type(destination).model_fields)}+ return sorted(+ input_edges,+ key=lambda edge: (field_order.get(edge.destination.field, len(field_order)), edge.source.node_id),+ )++class _IteratorAncestry:"""Own the ordered open For/Iterate axes for one source-graph traversal."""@@ -25,11 +36,19 @@ class _IteratorAncestry:self._has_iterator_ancestor: dict[str, bool] | None = Noneself._ordered_iterator_ancestors: dict[str, tuple[str, ...]] = {}self._frame_iterators: dict[str, tuple[str, ...]] = {}- self.effective_iteration_paths_by_edge: dict[tuple[str, str], set[tuple[int, ...]]] = {}+ self.frame_axes_cache: dict[str, Optional[tuple[str, ...]]] = {}+ self.if_final_axes_by_edge: dict[Edge, tuple[set[str], set[str]]] = {}+ self.effective_iteration_paths_by_edge: dict[Edge, set[tuple[int, ...]]] = {}+ self.sibling_collect_iterate_axis_cache: dict[str, tuple[object, int, bool]] = {}+ self.sibling_collect_iterate_projection_cache: dict[+ tuple[str, ...], tuple[tuple[tuple[object, int], ...], frozenset[str]]+ ] = {}def clear_effective_iteration_paths(self) -> None:"""Invalidate prepared-path results when execution materialization advances."""self.effective_iteration_paths_by_edge.clear()+ self.sibling_collect_iterate_axis_cache.clear()+ self.sibling_collect_iterate_projection_cache.clear()def has_iterator_ancestor(self, node_id: str) -> bool:if self._has_iterator_ancestor is None:@@ -76,12 +95,8 @@ class _IteratorAncestry:continuevisited.add(current_node_id)pending.append((current_node_id, True))- current_node = self._state.graph.get_node(current_node_id)- input_fields = list(type(current_node).model_fields)- field_order = {field: index for index, field in enumerate(input_fields)}- input_edges = sorted(- self._state.graph._get_input_edges(current_node_id),- key=lambda edge: (field_order.get(edge.destination.field, len(field_order)), edge.source.node_id),+ input_edges = _get_ordered_input_edges(+ self._state.graph, self._state.graph._get_input_edges(current_node_id))for edge in reversed(input_edges):source_node_id = edge.source.node_id@@ -136,11 +151,8 @@ class _IteratorAncestry:continuevisited.add((current_node_id, opens))pending.append((current_node_id, True, opens))- current_node = self._state.graph.get_node(current_node_id)- field_order = {field: index for index, field in enumerate(type(current_node).model_fields)}- input_edges = sorted(- self._state.graph._get_input_edges(current_node_id),- key=lambda edge: (field_order.get(edge.destination.field, len(field_order)), edge.source.node_id),+ input_edges = _get_ordered_input_edges(+ self._state.graph, self._state.graph._get_input_edges(current_node_id))for edge in reversed(input_edges):source_node_id = edge.source.node_iddiff --git a/invokeai/app/services/shared/graph_materializer.py b/invokeai/app/services/shared/graph_materializer.pyindex 816fd4ddee..fdb2dd8d03 100644--- a/invokeai/app/services/shared/graph_materializer.py+++ b/invokeai/app/services/shared/graph_materializer.py@@ -1,6 +1,7 @@"""Compatibility materialization for graph execution state."""import itertools+from collections import defaultdict, dequefrom typing import TYPE_CHECKING, Any, Iterable, Optionalfrom invokeai.app.invocations.baseinvocation import BaseInvocation@@ -15,7 +16,7 @@ from invokeai.app.invocations.loops import ()from invokeai.app.services.shared import graph_if_runtimefrom invokeai.app.services.shared.execution_engine.primitives import ActivationGate-from invokeai.app.services.shared.graph_iterator_ancestry import _IteratorAncestry+from invokeai.app.services.shared.graph_iterator_ancestry import _get_ordered_input_edges, _IteratorAncestryfrom invokeai.app.services.shared.graph_loop_topology import NestedForBody, NestedIterateBody, NestedIterateChainfrom invokeai.app.services.shared.graph_models import Edge, EdgeConnectionfrom invokeai.app.services.shared.graph_validation import (@@ -32,6 +33,9 @@ if TYPE_CHECKING:from invokeai.app.services.shared.graph import GraphExecutionState+_ProjectedRootIfFrames = dict[tuple[int, ...], list[tuple[tuple[int, ...], tuple[str, ...]]]]++class UnsupportedSharedIfCollectBranchesError(ValueError):"""Raised when one sibling Collect-backed Iterate must serve multiple If owners."""@@ -51,6 +55,7 @@ class _ExecutionNodeBuilder:self._activation_candidate_topological_order: tuple[str, ...] = ()self._activation_candidate_topological_index: dict[str, int] = {}self._activation_sources_by_dependency: dict[tuple[str, str], set[str]] = {}+ self._activation_sources_by_iterator: dict[str, set[str]] = {}self._empty_condition_if_sources: dict[str, tuple[str, ...]] = {}self._pending_activation_retirement_candidates: set[str] = set()self._activation_retirement_rebuild_required = False@@ -62,6 +67,9 @@ class _ExecutionNodeBuilder:self._flat_iterator_graph: Optional[tuple["nx.DiGraph", "nx.DiGraph"]] = Noneself._iterator_ancestry_graph: Optional["nx.DiGraph"] = Noneself._iterator_ancestry: Optional[_IteratorAncestry] = None+ self._collect_group_axes_source_graph: Optional["nx.DiGraph"] = None+ self._collect_group_axes_by_parent: dict[str, tuple[str, ...]] = {}+ self._sibling_iterate_collect_by_parent: dict[str, bool] = {}def _get_iteration_axes(self, source_node_id: str) -> tuple[str, ...]:cached = self._iteration_axes_by_source.get(source_node_id)@@ -99,15 +107,7 @@ class _ExecutionNodeBuilder:if not input_edges:return ()- destination = self._state.graph.get_node(input_edges[0].destination.node_id)- input_field_order = {field: index for index, field in enumerate(type(destination).model_fields)}- ordered_edges = sorted(- input_edges,- key=lambda edge: (- input_field_order.get(edge.destination.field, len(input_field_order)),- edge.source.node_id,- ),- )+ ordered_edges = _get_ordered_input_edges(self._state.graph, input_edges)axes: list[str] = []for edge in ordered_edges:for axis_id in self._get_iteration_axes(edge.source.node_id):@@ -130,6 +130,9 @@ class _ExecutionNodeBuilder:parent_path = registry.get_iteration_path(prepared_id)if parent_path is None:return None+ parent_axes = registry.get_iteration_axes(prepared_id)+ if parent_axes is None:+ parent_axes = self._get_iteration_axes(source_node_id)source_edges = input_edges_by_source.get(source_node_id)if source_edges:parent_path = max(@@ -137,7 +140,16 @@ class _ExecutionNodeBuilder:key=lambda path: (len(path), path),)if parent_path:- parent_contexts.append((parent_path, self._get_iteration_axes(source_node_id)))+ if (+ source_edges+ and isinstance(self._state.graph.get_node(source_node_id), ForInvocation)+ and get_output_field_scope(self._state.graph.get_node(source_node_id), source_edges[0].source.field)+ == OutputScope.Final+ and parent_axes+ and parent_axes[-1] == source_node_id+ ):+ parent_axes = parent_axes[:-1]+ parent_contexts.append((parent_path, parent_axes))deepest_path = max((path for path, _ in parent_contexts), key=len, default=())deepest_axes = max((axes for _, axes in parent_contexts), key=len, default=())@@ -253,6 +265,7 @@ class _ExecutionNodeBuilder:self._activation_candidate_topological_order = ()self._activation_candidate_topological_index = {}self._activation_sources_by_dependency = {}+ self._activation_sources_by_iterator = {}self._empty_condition_if_sources = {}self._pending_activation_retirement_candidates.clear()if not self._has_if_nodes:@@ -264,6 +277,7 @@ class _ExecutionNodeBuilder:source_node_id: index for index, source_node_id in enumerate(self._activation_candidate_topological_order)}self._activation_sources_by_dependency = {}+ self._activation_sources_by_iterator = {}self._empty_condition_if_sources = {}self._pending_activation_retirement_candidates.clear()for source_node_id in self._activation_candidate_topological_order:@@ -271,16 +285,28 @@ class _ExecutionNodeBuilder:self._activation_sources_by_dependency.setdefault((dependency.owner_id, dependency.branch), set()).add(source_node_id)+ for iterator_id in self._state._runtime()._get_ordered_iterator_sources(source_node_id):+ self._activation_sources_by_iterator.setdefault(iterator_id, set()).add(source_node_id)for if_node_id in graph.nodes:if not isinstance(self._state.graph.get_node(if_node_id), IfInvocation):continuecondition_edges = self._state.graph._get_input_edges(if_node_id, "condition")- if len(condition_edges) != 1:- continue- condition_source_id = condition_edges[0].source.node_id- if isinstance(self._state.graph.get_node(condition_source_id), IterateInvocation):- self._empty_condition_if_sources.setdefault(condition_source_id, ())- self._empty_condition_if_sources[condition_source_id] += (if_node_id,)+ iterator_graph = self.iterator_graph(graph)+ ancestry = self._get_iterator_ancestry(iterator_graph)+ empty_frame_sources = tuple(+ dict.fromkeys(+ [+ axis_id+ for edge in condition_edges+ if iterator_graph.has_node(edge.source.node_id)+ for axis_id in ancestry.get_iterator_axes_for_edge(edge)+ ]+ + list(ancestry.get_frame_iterators(if_node_id))+ )+ )+ for source_id in empty_frame_sources:+ self._empty_condition_if_sources.setdefault(source_id, ())+ self._empty_condition_if_sources[source_id] += (if_node_id,)self._activation_retirement_rebuild_required = Trueself._rebuild_activation_retirement_candidates()@@ -296,6 +322,8 @@ class _ExecutionNodeBuilder:self._pending_activation_retirement_candidates.update(self._activation_sources_by_dependency.get((owner_id, opposite_branch[selected_branch]), ()))+ frame = self._state._activation_gate(exec_node_id).frame.iteration_path+ self._queue_selected_empty_iterate_branch_retirements(owner_id, selected_branch, frame)for condition_source_id, if_node_ids in self._empty_condition_if_sources.items():if condition_source_id not in self._state.executed or self._state.source_prepared_mapping.get(condition_source_id@@ -318,6 +346,26 @@ class _ExecutionNodeBuilder:for source_node_id in self._activation_sources_by_dependency.get((if_node_id, opposite_branch), ()):self._state._tx_add_set(self._pending_activation_retirement_candidates, source_node_id)+ def _queue_selected_empty_iterate_branch_retirements(+ self, if_node_id: str, selected_branch: str, frame: tuple[int, ...]+ ) -> None:+ """Queue item sources whose selected branch frame has a persisted empty Iterate input."""+ self._ensure_activation_candidate_index(self._state._get_source_graph_flat())+ owner_axes = tuple(self._state._runtime()._get_ordered_iterator_sources(if_node_id))+ if_axes_count = len(owner_axes)+ for source_node_id in self._activation_sources_by_dependency.get((if_node_id, selected_branch), ()):+ source_node = self._state.graph.get_node(source_node_id)+ if isinstance(source_node, (IfInvocation, IterateInvocation, CollectInvocation)):+ continue++ source_axes = self._get_collect_source_iterator_ids(source_node_id)+ if len(source_axes) <= if_axes_count or tuple(source_axes[:if_axes_count]) != owner_axes:+ continue++ iterator_id = source_axes[if_axes_count]+ if self._has_empty_iterate_parent_group(iterator_id, owner_axes, frame):+ self._state._tx_add_set(self._pending_activation_retirement_candidates, source_node_id)+def _queue_empty_condition_retirements(self, condition_source_id: str) -> None:self._ensure_activation_candidate_index(self._state._get_source_graph_flat())for if_node_id in self._empty_condition_if_sources.get(condition_source_id, ()):@@ -339,7 +387,12 @@ class _ExecutionNodeBuilder:def _has_unmaterializable_for_final_input(self, node_id: str) -> bool:final_for_source_ids = set()- for edge in self._state.graph._get_input_edges(node_id):+ node = self._state.graph.get_node(node_id)+ input_edges = self._state.graph._get_input_edges(node_id)+ if isinstance(node, IfInvocation) and not self._state.graph._get_input_edges(node_id, "condition"):+ selected_field = "true_input" if node.condition else "false_input"+ input_edges = self._state.graph._get_input_edges(node_id, selected_field)+ for edge in input_edges:source_node = self._state.graph.get_node(edge.source.node_id)if not isinstance(source_node, ForInvocation):continue@@ -1227,26 +1280,340 @@ class _ExecutionNodeBuilder:returnself._state._enqueue_if_ready(exec_node_id)- def _get_collect_iteration_group_key(self, edge: Edge, sibling_depth: Optional[int] = None) -> tuple[int, ...]:- path = self._state._get_iteration_path(edge.source.node_id)- source_node = self._state.execution_graph.get_node(edge.source.node_id)+ def _get_collect_group_axes(+ self,+ edge: Edge,+ prepared_id: Optional[str] = None,+ context_deepest_path_depth_by_axes_prefix: Optional[dict[tuple[str, ...], int]] = None,+ max_collected_path_depth: Optional[int] = None,+ ) -> tuple[str, ...]:+ source_node = self._state.graph.get_node(edge.source.node_id)+ if prepared_id is None:+ prepared_ids = self._get_ordered_prepared_nodes_for_edge(edge)+ prepared_id = prepared_ids[0] if prepared_ids else None+ if prepared_id is None:+ return self._get_static_collect_group_axes(edge)++ axes = self._get_prepared_edge_iteration_axes(edge, prepared_id)+ if edge.destination.field != ITEM_FIELD:+ return axesif (isinstance(source_node, ForInvocation)and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final):- return self._state._get_for_parent_iteration_path(edge.source.node_id)+ return axes+ if max_collected_path_depth is None:+ collection_edges = self._state.graph._get_input_edges(source_node.id, COLLECTION_FIELD)+ max_collected_path_depth = max(+ (+ len(self._get_prepared_edge_iteration_path(collection_edge, collect_prepared_id))+ for collection_edge in collection_edges+ if isinstance(self._state.graph.get_node(collection_edge.source.node_id), CollectInvocation)+ for collect_prepared_id in self._get_ordered_prepared_nodes_for_edge(collection_edge)+ ),+ default=0,+ )+ if max_collected_path_depth and len(self._state._get_iteration_path(prepared_id)) < max_collected_path_depth:+ return axes+ if isinstance(source_node, IfInvocation):+ ancestry = self._get_iterator_ancestry(self.iterator_graph())+ retained_axes = self._get_selected_for_final_parent_axes(source_node.id, ancestry)+ if retained_axes and self._collect_has_selected_for_final_input(edge.destination.node_id):+ prepared_retained_axes = self._get_selected_for_final_parent_axes(source_node.id, ancestry, prepared_id)+ if prepared_retained_axes:+ return prepared_retained_axes+ return tuple(axis for axis in axes if axis in retained_axes)+ selected_field = self._state._resolved_if_exec_branches.get(prepared_id)+ condition_edges = self._state.graph._get_input_edges(source_node.id, "condition")+ if (+ condition_edges+ and selected_field is not None+ and not any(ancestry.get_frame_axes_for_edge(condition_edge) for condition_edge in condition_edges)+ ):+ branch_axes, final_axes = graph_if_runtime._get_if_static_frame_analysis(+ self._state, ancestry, source_node.id+ )+ direct_axes = {+ axis_id+ for branch_edge in self._state.graph._get_input_edges(source_node.id, selected_field)+ for axis_id in ancestry.get_iterator_axes_for_edge(branch_edge)+ }+ selected_axes = branch_axes[selected_field]+ other_field = "false_input" if selected_field == "true_input" else "true_input"+ other_axes = branch_axes[other_field]+ if (+ other_axes+ and set(selected_axes) - direct_axes - final_axes[selected_field]+ and len(selected_axes) > len(other_axes)+ and selected_axes[: len(other_axes)] == other_axes+ and selected_axes[: len(axes)] == axes+ ):+ # Preserve groups only when a root If extends a shared branch-frame prefix.+ return axes+ if not condition_edges:+ selected_field = graph_if_runtime._get_static_if_selection(self._state, source_node.id)+ if selected_field is not None:+ branch_axes, _ = graph_if_runtime._get_if_static_frame_analysis(+ self._state, ancestry, source_node.id+ )+ other_field = "false_input" if selected_field == "true_input" else "true_input"+ selected_axes = branch_axes[selected_field]+ reopened_axes = set().union(+ *(+ graph_if_runtime._get_reopened_source_axes(+ self._state, ancestry, selected_axis, ancestry.frame_axes_cache+ )+ for selected_axis in selected_axes+ )+ )+ if branch_axes[selected_field] and set(branch_axes[other_field]).intersection(reopened_axes):+ return axes+ for other_edge in self._state.graph._get_input_edges(edge.destination.node_id, ITEM_FIELD):+ if other_edge == edge:+ continue+ other_axes = tuple(self._get_collect_source_iterator_ids(other_edge.source.node_id))+ if len(other_axes) > len(axes) and other_axes[: len(axes)] == axes:+ return axes+ if context_deepest_path_depth_by_axes_prefix is None:+ context_deepest_path_depth_by_axes_prefix = self._get_collect_deepest_path_depth_by_axes_prefix(+ edge.destination.node_id+ )+ context_depth = context_deepest_path_depth_by_axes_prefix.get(axes)+ if context_depth is not None and context_depth > len(self._get_prepared_edge_iteration_path(edge, prepared_id)):+ return axes+ group_depth = max(len(self._get_collect_source_iterator_ids(source_node.id)) - 1, 0)+ if len(axes) <= group_depth:+ return axes+ return axes[:-1]++ def _get_collect_deepest_path_depth_by_axes_prefix(self, collect_node_id: str) -> dict[tuple[str, ...], int]:+ context_depth_by_axes_prefix: dict[tuple[str, ...], int] = {}+ for context_edge in self._state.graph._get_input_edges(collect_node_id, ITEM_FIELD):+ prepared_ids = self._get_ordered_prepared_nodes_for_edge(context_edge)+ if not prepared_ids:+ continue+ prepared_paths = [+ (candidate_id, self._get_prepared_edge_iteration_path(context_edge, candidate_id))+ for candidate_id in prepared_ids+ ]+ deepest_id, deepest_path = max(prepared_paths, key=lambda candidate: (len(candidate[1]), candidate[1]))+ deepest_axes = self._get_prepared_edge_iteration_axes(context_edge, deepest_id)+ for prefix_length in range(len(deepest_axes)):+ prefix = deepest_axes[:prefix_length]+ context_depth_by_axes_prefix[prefix] = max(+ len(deepest_path), context_depth_by_axes_prefix.get(prefix, 0)+ )+ return context_depth_by_axes_prefix++ def _get_static_collect_group_axes(self, edge: Edge) -> tuple[str, ...]:+ iterator_node_ids = self._get_collect_source_iterator_ids(edge.source.node_id)+ group_depth = len(iterator_node_ids)+ source_node = self._state.graph.get_node(edge.source.node_id)if edge.destination.field == ITEM_FIELD:- if isinstance(source_node, ForInvocation) and source_node.index == -1:- return path- # Ragged siblings need the deepest path to identify their shared outer group.- depth = len(path) if sibling_depth is None else sibling_depth- return path[: max(depth - 1, 0)]- return path+ if (+ isinstance(source_node, ForInvocation)+ and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final+ ):+ return tuple(iterator_node_ids)+ if isinstance(source_node, IfInvocation):+ ancestry = self._get_iterator_ancestry(self.iterator_graph())+ retained_axes = self._get_selected_for_final_parent_axes(source_node.id, ancestry)+ if retained_axes and self._collect_has_selected_for_final_input(edge.destination.node_id):+ return retained_axes+ group_depth = max(group_depth - 1, 0)+ return tuple(iterator_node_ids[:group_depth])++ def _get_shared_static_collect_group_axes(self, collect_node_id: str) -> tuple[str, ...]:+ self._refresh_collect_group_caches()+ cached = self._collect_group_axes_by_parent.get(collect_node_id)+ if cached is not None:+ return cached++ item_axes = [+ self._get_static_collect_group_axes(item_edge)+ for item_edge in self._state.graph._get_input_edges(collect_node_id, ITEM_FIELD)+ ]+ parent_axes: list[str] = []+ for axis_candidates in zip(*item_axes, strict=False):+ if len(set(axis_candidates)) != 1:+ break+ parent_axes.append(axis_candidates[0])+ result = tuple(parent_axes)+ self._collect_group_axes_by_parent[collect_node_id] = result+ return result++ def _refresh_collect_group_caches(self) -> None:+ source_graph = self._state._get_source_graph_flat()+ if source_graph is self._collect_group_axes_source_graph:+ return+ self._collect_group_axes_source_graph = source_graph+ self._collect_group_axes_by_parent.clear()+ self._sibling_iterate_collect_by_parent.clear()++ def _is_sibling_iterate_collect(self, collect_node_id: str) -> bool:+ self._refresh_collect_group_caches()+ cached = self._sibling_iterate_collect_by_parent.get(collect_node_id)+ if cached is not None:+ return cached++ item_edges = self._state.graph._get_input_edges(collect_node_id, ITEM_FIELD)+ ancestry = self._get_iterator_ancestry(self.iterator_graph())+ iterator_ids = [+ (axes[-1] if axes else None)+ for axes in (self._get_collect_source_iterator_ids(edge.source.node_id) for edge in item_edges)+ ]+ result = (+ len(iterator_ids) > 1+ and not any(self._get_selected_for_final_parent_axes(edge.source.node_id, ancestry) for edge in item_edges)+ and all(iterator_id is not None for iterator_id in iterator_ids)+ and len(set(iterator_ids)) == len(iterator_ids)+ and all(+ isinstance(self._state.graph.get_node(iterator_id), IterateInvocation)+ for iterator_id in iterator_ids+ if iterator_id is not None+ )+ )+ self._sibling_iterate_collect_by_parent[collect_node_id] = result+ return result++ def _is_sibling_collect_reiteration(self, source_node_id: str) -> bool:+ source_axes = self._get_collect_source_iterator_ids(source_node_id)+ if not source_axes or not isinstance(self._state.graph.get_node(source_axes[-1]), IterateInvocation):+ return False+ collection_edges = self._state.graph._get_input_edges(source_axes[-1], COLLECTION_FIELD)+ return (+ len(collection_edges) == 1+ and isinstance(self._state.graph.get_node(collection_edges[0].source.node_id), CollectInvocation)+ and self._is_sibling_iterate_collect(collection_edges[0].source.node_id)+ )++ def _get_prepared_edge_iteration_axes(self, edge: Edge, prepared_id: str) -> tuple[str, ...]:+ """Identify frame axes from the prepared node's real execution ancestors."""+ path = self._get_prepared_edge_iteration_path(edge, prepared_id)+ recorded_axes = self._state._prepared_registry().get_iteration_axes(prepared_id)+ static_axes = tuple(self._get_collect_source_iterator_ids(edge.source.node_id))+ if not path:+ source_node = self._state.graph.get_node(edge.source.node_id)+ if (+ isinstance(source_node, ForInvocation)+ and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final+ ):+ return tuple(axis for axis in (static_axes or recorded_axes or ()) if axis != source_node.id)+ if static_axes:+ first_axis = self._state.graph.get_node(static_axes[0])+ if isinstance(first_axis, (IterateInvocation, ForInvocation)):+ collection_edges = self._state.graph._get_input_edges(static_axes[0], COLLECTION_FIELD)+ if len(collection_edges) == 1:+ parent_node = self._state.graph.get_node(collection_edges[0].source.node_id)+ if isinstance(parent_node, CollectInvocation):+ parent_axes = self._get_shared_static_collect_group_axes(parent_node.id)+ if parent_axes:+ return (*parent_axes, *static_axes)+ return static_axes or (recorded_axes or ())+ if recorded_axes is not None and len(recorded_axes) == len(path):+ return recorded_axes++ if static_axes and len(static_axes) < len(path):+ missing_prefix_depth = len(path) - len(static_axes)+ first_axis_id = static_axes[0]+ first_axis = self._state.graph.get_node(first_axis_id)+ if isinstance(first_axis, (IterateInvocation, ForInvocation)):+ collection_edges = self._state.graph._get_input_edges(first_axis_id, COLLECTION_FIELD)+ if len(collection_edges) == 1:+ collection_edge = collection_edges[0]+ parent_node = self._state.graph.get_node(collection_edge.source.node_id)+ if isinstance(parent_node, CollectInvocation):+ parent_axes = self._get_shared_static_collect_group_axes(parent_node.id)+ parent_exec_id = self._state._prepared_registry().get_prepared_id_at_path(+ parent_node.id, path[:missing_prefix_depth]+ )+ if parent_exec_id is not None and len(parent_axes) == missing_prefix_depth:+ static_axes = (*parent_axes, *static_axes)+ if len(static_axes) == len(path):+ return static_axes++ execution_graph = self._state._get_execution_graph_flat()+ pending = deque([(prepared_id, 0)])+ visited = {prepared_id}+ candidates: dict[int, list[tuple[int, str]]] = {}+ while pending:+ exec_id, distance = pending.popleft()+ source_id = self._state.prepared_source_mapping.get(exec_id)+ if source_id is not None:+ source_node = self._state.graph.get_node(source_id)+ prepared_node = self._state.execution_graph.get_node(exec_id)+ if isinstance(source_node, IterateInvocation) or (+ isinstance(source_node, ForInvocation)+ and isinstance(prepared_node, ForInvocation)+ and prepared_node.index >= 0+ ):+ frame_path = self._state._get_iteration_path(exec_id)+ if frame_path and len(frame_path) <= len(path) and path[: len(frame_path)] == frame_path:+ candidates.setdefault(len(frame_path) - 1, []).append((distance, source_id))+ for parent_id in execution_graph.predecessors(exec_id):+ if parent_id not in visited:+ visited.add(parent_id)+ pending.append((parent_id, distance + 1))++ edge_axes: Optional[tuple[str, ...]] = None+ axes: list[str] = []+ for axis_index in range(len(path)):+ axis_candidates = candidates.get(axis_index, [])+ preferred_axis = next(+ (axis_id for axis_id in static_axes if any(candidate == axis_id for _, candidate in axis_candidates)),+ None,+ )+ axis_id = preferred_axis or (min(axis_candidates)[1] if axis_candidates else None)+ if axis_id is None:+ if len(static_axes) >= len(path):+ axis_id = static_axes[axis_index]+ else:+ if edge_axes is None:+ iterator_ancestry = _IteratorAncestry(self._state, iterator_graph=self.iterator_graph())+ edge_axes = (+ graph_if_runtime._get_edge_frame_axes(+ self._state, iterator_ancestry, edge, {}, use_runtime_if_selection=True+ )+ or ()+ )+ axis_id = edge_axes[axis_index] if axis_index < len(edge_axes) else None+ if axis_id is None:+ break+ axes.append(axis_id)+ source_node = self._state.graph.get_node(edge.source.node_id)+ if not axes and isinstance(source_node, CollectInvocation):+ collect_axes = self._get_shared_static_collect_group_axes(source_node.id)+ if len(collect_axes) == len(path):+ return collect_axes+ return tuple(axes)def _get_collect_source_iterator_ids(self, source_node_id: str, iterator_graph: Optional["nx.DiGraph"] = None) -> list[str]:+ if isinstance(self._state.graph.get_node(source_node_id), IfInvocation):+ iterator_ancestry = self._get_iterator_ancestry(iterator_graph or self.iterator_graph())+ branch_axes_by_field = graph_if_runtime._get_if_runtime_branch_frame_axes(+ self._state, iterator_ancestry, source_node_id+ )+ branch_axes = [branch_axes_by_field[branch] for branch in ("true_input", "false_input")]+ condition_axes = {+ axis_id+ for edge in self._state.graph._get_input_edges(source_node_id, "condition")+ for axis_id in iterator_ancestry.get_frame_axes_for_edge(edge)+ }+ if branch_axes[0] and branch_axes[0] == branch_axes[1] and set(branch_axes[0]) > condition_axes:+ return list(branch_axes[0])++ iterator_graph = iterator_graph or self.iterator_graph()+ iterator_ancestry = self._get_iterator_ancestry(iterator_graph)iterator_node_ids = self.get_node_iterators(source_node_id, iterator_graph)+ parent_frame_axes = [+ axis_id+ for iterator_node_id in iterator_node_ids+ for edge in self._state.graph._get_input_edges(iterator_node_id, COLLECTION_FIELD)+ for axis_id in iterator_ancestry.get_frame_axes_for_edge(edge)+ ]+ iterator_node_ids = list(dict.fromkeys([*parent_frame_axes, *iterator_node_ids]))if isinstance(self._state.graph.get_node(source_node_id), IterateInvocation):iterator_node_ids.append(source_node_id)return iterator_node_ids@@ -1305,111 +1672,507 @@ class _ExecutionNodeBuilder:return self._state._get_for_parent_iteration_path(prepared_id)return self._state._get_iteration_path(prepared_id)- def _get_iterator_input_iteration_paths(self, iterator_node_id: str) -> set[tuple[int, ...]]:- iteration_paths: set[tuple[int, ...]] = set()+ def _get_iterator_input_iteration_groups(+ self, iterator_node_id: str+ ) -> set[tuple[str, tuple[str, ...], tuple[int, ...]]]:+ iteration_groups: set[tuple[str, tuple[str, ...], tuple[int, ...]]] = set()for edge in self._state.graph._get_input_edges(iterator_node_id, COLLECTION_FIELD):- source_node_id = edge.source.node_id- prepared_nodes = self._get_ordered_prepared_nodes_for_source(source_node_id)- iteration_paths.update(- self._get_prepared_edge_iteration_path(edge, prepared_id) for prepared_id in prepared_nodes+ iteration_groups.update(+ (+ edge.source.node_id,+ self._get_prepared_edge_iteration_axes(edge, prepared_id),+ self._get_prepared_edge_iteration_path(edge, prepared_id),+ )+ for prepared_id in self._get_ordered_prepared_nodes_for_edge(edge))- return iteration_paths+ return iteration_groups- def _get_collect_candidate_group_keys(self, edge: Edge) -> set[tuple[int, ...]]:+ def _get_empty_iterate_parent_groups(self, iterator_node_id: str) -> set[tuple[tuple[str, ...], tuple[int, ...]]]:+ """Derive empty parent frames from persisted collection results feeding an Iterate."""+ if not isinstance(self._state.graph.get_node(iterator_node_id), IterateInvocation):+ return set()++ groups: set[tuple[tuple[str, ...], tuple[int, ...]]] = set()+ for edge in self._state.graph._get_input_edges(iterator_node_id, COLLECTION_FIELD):+ for prepared_id in self._get_ordered_prepared_nodes_for_edge(edge):+ result = self._state.results.get(prepared_id)+ if (+ result is None+ or not isinstance((collection := getattr(result, edge.source.field, None)), list)+ or collection+ ):+ continue+ path = self._get_prepared_edge_iteration_path(edge, prepared_id)+ axes = self._get_prepared_edge_iteration_axes(edge, prepared_id)+ if len(axes) == len(path):+ groups.add((axes, path))+ return groups++ def _has_empty_iterate_parent_group(+ self, iterator_node_id: str, group_axes: tuple[str, ...], group_path: tuple[int, ...]+ ) -> bool:+ return (group_axes, group_path) in self._get_empty_iterate_parent_groups(iterator_node_id)++ def _has_empty_iterate_anchor_for_collect_group(+ self, item_edge: Edge, group_axes: tuple[str, ...], group_path: tuple[int, ...]+ ) -> bool:+ source_axes = self._get_collect_source_iterator_ids(item_edge.source.node_id)+ if len(source_axes) <= len(group_axes) or tuple(source_axes[: len(group_axes)]) != group_axes:+ return False++ iterator_id = source_axes[len(group_axes)]+ return self._has_empty_iterate_parent_group(iterator_id, group_axes, group_path)++ def _has_empty_collect_group_anchor(+ self, collect_id: str, group_axes: tuple[str, ...], group_path: tuple[int, ...]+ ) -> bool:+ collect_inputs = self._state.graph._get_input_edges(collect_id)+ missing_item_edges = [+ edge+ for edge in collect_inputs+ if edge.destination.field == ITEM_FIELD+ and edge.source.node_id not in self._state.source_prepared_mapping+ and edge.source.node_id not in self._state.executed+ ]+ if not missing_item_edges:+ return False+ return self._state._is_source_activation_admitted(collect_id, group_path) and all(+ self._has_empty_iterate_anchor_for_collect_group(edge, group_axes, group_path)+ for edge in missing_item_edges+ )++ def _has_ready_empty_collect_group(self, collect_id: str) -> bool:+ """Allow an empty Collect frame only when its missing item source has a persisted empty Iterate input."""+ groups = self._get_collect_iteration_mapping_groups(self._state.graph._get_input_edges(collect_id))+ active_empty_groups = [+ (group_axes, group_path)+ for group_axes, group_path, iteration_mappings in groups+ if not iteration_mappings and self._state._is_source_activation_admitted(collect_id, group_path)+ ]+ return bool(active_empty_groups) and all(+ self._has_empty_collect_group_anchor(collect_id, group_axes, group_path)+ for group_axes, group_path in active_empty_groups+ )++ def _collect_has_selected_for_final_input(self, collect_id: str) -> bool:+ ancestry = self._get_iterator_ancestry(self.iterator_graph())+ return any(+ self._get_selected_for_final_parent_axes(edge.source.node_id, ancestry)+ for edge in self._state.graph._get_input_edges(collect_id, ITEM_FIELD)+ )++ def _get_selected_if_fields(self, if_node_id: str, prepared_id: Optional[str] = None) -> tuple[str, ...]:+ if prepared_id is not None:+ selected_field = self._state._resolved_if_exec_branches.get(prepared_id)+ if selected_field is not None:+ return (selected_field,)+ selected_field = graph_if_runtime._get_static_if_selection(self._state, if_node_id)+ if selected_field is not None:+ return (selected_field,)+ prepared_ids = self._state.source_prepared_mapping.get(if_node_id, ())+ selected_fields = {self._state._resolved_if_exec_branches.get(prepared_id) for prepared_id in prepared_ids}+ selected_fields.discard(None)+ if not selected_fields or any(+ prepared_id not in self._state._resolved_if_exec_branches for prepared_id in prepared_ids+ ):+ return ("true_input", "false_input")+ return tuple(field for field in ("true_input", "false_input") if field in selected_fields)++ def _get_selected_for_final_parent_axes(+ self, if_node_id: str, ancestry: _IteratorAncestry, prepared_id: Optional[str] = None+ ) -> tuple[str, ...]:+ """Return For-final parent frames retained by this If's selection and condition scope."""+ if not isinstance(self._state.graph.get_node(if_node_id), IfInvocation):+ return ()+ root_selection = (+ graph_if_runtime._get_static_if_selection(self._state, if_node_id)+ if not self._state.graph._get_input_edges(if_node_id, "condition")+ else None+ )+ selected_fields = self._get_selected_if_fields(if_node_id, prepared_id)+ condition_axes = {+ axis_id+ for edge in self._state.graph._get_input_edges(if_node_id, "condition")+ for axis_id in ancestry.get_frame_axes_for_edge(edge)+ }+ pending_edges = [+ (edge, False)+ for branch_field in selected_fields+ for edge in self._state.graph._get_input_edges(if_node_id, branch_field)+ ]+ visited: set[tuple[str, bool]] = set()+ retained_axes: list[str] = []+ while pending_edges:+ edge, nested_condition = pending_edges.pop()+ source_id = edge.source.node_id+ source_node = self._state.graph.get_node(source_id)+ if (+ isinstance(source_node, ForInvocation)+ and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final+ ):+ if prepared_id is not None:+ prepared_path = self._state._get_iteration_path(prepared_id)+ final_output_paths = {+ self._get_prepared_edge_iteration_path(edge, final_id)+ for final_id in self._get_ordered_prepared_nodes_for_edge(edge)+ }+ if prepared_path not in final_output_paths:+ continue+ final_parent_axes = ancestry.get_frame_axes_for_edge(edge)+ for axis_id in final_parent_axes:+ if (+ root_selection is not None or nested_condition or axis_id in condition_axes+ ) and axis_id not in retained_axes:+ retained_axes.append(axis_id)+ continue+ visit_key = (source_id, nested_condition)+ if visit_key in visited:+ continue+ visited.add(visit_key)+ if isinstance(source_node, IfInvocation):+ nested_fields = self._get_selected_if_fields(source_id)+ pending_edges.extend(+ (edge, nested_condition or bool(self._state.graph._get_input_edges(source_id, "condition")))+ for branch_field in nested_fields+ for edge in self._state.graph._get_input_edges(source_id, branch_field)+ )+ continue+ if isinstance(source_node, (ForInvocation, IterateInvocation, CollectInvocation)):+ continue+ pending_edges.extend(+ (input_edge, nested_condition) for input_edge in self._state.graph._get_input_edges(source_id)+ )+ return tuple(retained_axes)++ def _get_collect_candidate_group_keys(+ self, edge: Edge, group_axes: Optional[tuple[str, ...]] = None+ ) -> set[tuple[tuple[str, ...], tuple[int, ...]]]:source_node_id = edge.source.node_iditerator_node_ids = self._get_collect_source_iterator_ids(source_node_id)+ group_axes = group_axes if group_axes is not None else self._get_collect_group_axes(edge)+ group_depth = len(group_axes)+ prepared_ids = self._get_ordered_prepared_nodes_for_edge(edge)+ if group_depth == 0:+ if prepared_ids and not self._is_sibling_collect_reiteration(edge.source.node_id):+ return {((), ())}+ group_keys = {((), ())}+ for iterator_node_id in iterator_node_ids:+ for _, input_axes, input_path in self._get_iterator_input_iteration_groups(iterator_node_id):+ candidate_axes = list(input_axes[: len(input_path)])+ if input_path and len(candidate_axes) == len(input_path):+ group_keys.add((tuple(candidate_axes), input_path))+ return group_keys- group_depth = len(iterator_node_ids)- if edge.destination.field == ITEM_FIELD:- group_depth = max(group_depth - 1, 0)-- group_keys: set[tuple[int, ...]] = set()+ group_keys: set[tuple[tuple[str, ...], tuple[int, ...]]] = set()+ iterator_input_group_keys: set[tuple[tuple[str, ...], tuple[int, ...]]] = set()# A Collect.item edge groups by the outer `group_depth` axes. Read input paths from the current item axis# too: an empty stream still carries its parent groups even when it has no prepared items.for axis_index, iterator_node_id in enumerate(iterator_node_ids[: group_depth + 1]):- prepared_nodes = self._get_ordered_prepared_nodes_for_source(iterator_node_id)+ iterator_axes = tuple(self._get_collect_source_iterator_ids(iterator_node_id))# Only outer group axes contribute prepared paths; the current item axis is collapsed by Collect.- if axis_index < group_depth and prepared_nodes:- group_keys.update(- iteration_path[:group_depth]- for prepared_id in prepared_nodes- if len(iteration_path := self._state._get_iteration_path(prepared_id)) >= group_depth- )- group_keys.update(self._get_iterator_input_iteration_paths(iterator_node_id))+ if axis_index < group_depth:+ for prepared_id in self._get_ordered_prepared_nodes_for_source(iterator_node_id):+ iteration_path = self._state._get_iteration_path(prepared_id)[:group_depth]+ candidate_axes = iterator_axes[: len(iteration_path)]+ if (+ iteration_path+ and len(candidate_axes) == len(iteration_path)+ and group_axes[: len(candidate_axes)] == candidate_axes+ ):+ group_keys.add((candidate_axes, iteration_path))+ for _, input_axes, input_path in self._get_iterator_input_iteration_groups(iterator_node_id):+ candidate_path = input_path[:group_depth]+ candidate_axes = input_axes[: len(candidate_path)]+ if (+ candidate_path+ and len(candidate_axes) == len(candidate_path)+ and group_axes[: len(candidate_axes)] == candidate_axes+ ):+ candidate_group_key = (candidate_axes, candidate_path)+ group_keys.add(candidate_group_key)+ iterator_input_group_keys.add(candidate_group_key)- if group_keys:- return group_keys- if group_depth == 0:- return {()}- return set()+ prepared_contexts = [+ (+ self._get_prepared_edge_iteration_axes(edge, prepared_id),+ self._get_prepared_edge_iteration_path(edge, prepared_id),+ )+ for prepared_id in prepared_ids+ ]+ if prepared_contexts:+ axes_by_path_prefix: dict[tuple[int, ...], set[tuple[str, ...]]] = {}+ path_prefixes: set[tuple[int, ...]] = set()+ for source_axes, source_path in prepared_contexts:+ source_axis_prefixes = [source_axes[:axes_depth] for axes_depth in range(len(source_axes) + 1)]+ for path_depth in range(len(source_path) + 1):+ path_prefix = source_path[:path_depth]+ path_prefixes.add(path_prefix)+ axes_by_path_prefix.setdefault(path_prefix, set()).update(source_axis_prefixes)+ group_keys = {+ (candidate_axes, candidate_path)+ for candidate_axes, candidate_path in group_keys+ if not candidate_path+ or candidate_path not in path_prefixes+ or candidate_axes in axes_by_path_prefix[candidate_path]+ or (candidate_axes, candidate_path) in iterator_input_group_keys+ }++ return group_keysdef _get_collect_iteration_mapping_groups(self, input_edges: list[Edge]- ) -> list[tuple[tuple[int, ...], list[tuple[str, str]]]]:- prepared_inputs: list[tuple[Edge, str, str, tuple[int, ...]]] = []- group_keys: set[tuple[int, ...]] = set()+ ) -> list[tuple[tuple[str, ...], tuple[int, ...], list[tuple[str, str]]]]:+ prepared_inputs: list[tuple[Edge, str, str, tuple[str, ...], tuple[int, ...], bool]] = []+ group_keys: set[tuple[tuple[str, ...], tuple[int, ...]]] = set()+ context_deepest_path_depth_by_axes_prefix = (+ self._get_collect_deepest_path_depth_by_axes_prefix(input_edges[0].destination.node_id)+ if input_edges+ else {}+ )+ context_axes_prefixes_with_paths = {+ axes[:prefix_depth] for axes, path in group_keys if path for prefix_depth in range(1, len(axes) + 1)+ }+ root_context_axes: set[tuple[str, ...]] = set()+ max_collected_path_depth_by_output: dict[tuple[str, str, str], int] = {}for edge in input_edges:- group_keys.update(self._get_collect_candidate_group_keys(edge))- prepared_nodes = self._get_ordered_prepared_nodes_for_edge(edge)- sibling_depth = max(- (len(self._get_prepared_edge_iteration_path(edge, prepared_id)) for prepared_id in prepared_nodes),- default=0,+ prepared_ids = self._get_ordered_prepared_nodes_for_edge(edge)+ depth_key = (edge.source.node_id, edge.source.field, edge.destination.field)+ if depth_key not in max_collected_path_depth_by_output:+ source_node = self._state.graph.get_node(edge.source.node_id)+ if edge.destination.field == ITEM_FIELD and not (+ isinstance(source_node, ForInvocation)+ and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final+ ):+ collection_edges = self._state.graph._get_input_edges(edge.source.node_id, COLLECTION_FIELD)+ max_collected_path_depth_by_output[depth_key] = max(+ (+ len(self._get_prepared_edge_iteration_path(collection_edge, collect_prepared_id))+ for collection_edge in collection_edges+ if isinstance(self._state.graph.get_node(collection_edge.source.node_id), CollectInvocation)+ for collect_prepared_id in self._get_ordered_prepared_nodes_for_edge(collection_edge)+ ),+ default=0,+ )+ else:+ max_collected_path_depth_by_output[depth_key] = 0+ max_collected_path_depth = max_collected_path_depth_by_output[depth_key]+ edge_group_axes = list(+ self._get_collect_group_axes(+ edge,+ context_deepest_path_depth_by_axes_prefix=context_deepest_path_depth_by_axes_prefix,+ max_collected_path_depth=max_collected_path_depth,+ ))- for prepared_id in prepared_nodes:- prepared_edge = Edge(- source=EdgeConnection(node_id=prepared_id, field=edge.source.field),- destination=edge.destination,+ prepared_group_axes_by_id = {+ prepared_id: self._get_collect_group_axes(+ edge,+ prepared_id,+ context_deepest_path_depth_by_axes_prefix,+ max_collected_path_depth,)- group_key = self._get_collect_iteration_group_key(prepared_edge, sibling_depth)- group_keys.add(group_key)- prepared_inputs.append(- (- prepared_edge,- edge.source.node_id,- prepared_id,- self._get_prepared_edge_iteration_path(edge, prepared_id),+ for prepared_id in prepared_ids+ }+ known_axes: list[Optional[str]] = []+ for prepared_group_axes in prepared_group_axes_by_id.values():+ for axis_index, axis_id in enumerate(prepared_group_axes):+ if axis_index >= len(known_axes):+ known_axes.extend([None] * (axis_index + 1 - len(known_axes)))+ if known_axes[axis_index] is None:+ known_axes[axis_index] = axis_id+ if len(edge_group_axes) < len(known_axes):+ edge_group_axes.extend(axis_id for axis_id in known_axes[len(edge_group_axes) :] if axis_id is not None)+ edge_group_axes = tuple(edge_group_axes)+ candidate_group_keys = self._get_collect_candidate_group_keys(edge, edge_group_axes)+ group_keys.update(candidate_group_keys)+ context_axes_prefixes_with_paths.update(+ group_axes[:prefix_depth]+ for group_axes, group_path in candidate_group_keys+ if group_path+ for prefix_depth in range(1, len(group_axes) + 1)+ )+ for prepared_id in prepared_ids:+ prepared_group_axes = list(prepared_group_axes_by_id[prepared_id])+ prepared_path = self._get_prepared_edge_iteration_path(edge, prepared_id)+ if prepared_path:+ prepared_group_axes = prepared_group_axes[: len(prepared_path)]+ prepared_group_axes = tuple(prepared_group_axes)+ group_path = prepared_path[: len(prepared_group_axes)]+ group_key = (prepared_group_axes, group_path)+ has_matching_context_group = not prepared_path and any(+ prepared_group_axes[:prefix_depth] in context_axes_prefixes_with_paths+ for prefix_depth in range(1, len(prepared_group_axes) + 1)+ )+ if not has_matching_context_group:+ group_keys.add(group_key)+ if prepared_path:+ context_axes_prefixes_with_paths.update(+ prepared_group_axes[:prefix_depth] for prefix_depth in range(1, len(prepared_group_axes) + 1))+ is_root_source = not self._get_collect_source_iterator_ids(edge.source.node_id)+ is_root_source = is_root_source and not self._get_prepared_edge_iteration_path(edge, prepared_id)+ if not group_path and prepared_group_axes and not is_root_source:+ root_context_axes.add(prepared_group_axes)+ prepared_inputs.append(+ (edge, edge.source.node_id, prepared_id, prepared_group_axes, group_path, is_root_source))+ if root_context_axes and context_axes_prefixes_with_paths:+ group_keys = {+ group_key+ for group_key in group_keys+ if not (+ not group_key[1]+ and group_key[0] in root_context_axes+ and any(+ group_key[0][:prefix_depth] in context_axes_prefixes_with_paths+ for prefix_depth in range(1, len(group_key[0]) + 1)+ )+ )+ }if not group_keys:- group_keys.add(())+ group_keys.add(((), ()))final_group_keys = sorted(- group_key- for group_key in group_keys- if not any(- group_key != other_group_key and other_group_key[: len(group_key)] == group_key- for other_group_key in group_keys- )+ self._remove_collect_group_prefixes(group_keys), key=lambda group_key: (group_key[1], group_key[0]))+ has_root_item_group = any(+ edge.destination.field == ITEM_FIELD and not is_root_source and not group_axes and not group_path+ for edge, _, _, group_axes, group_path, is_root_source in prepared_inputs+ )+ has_non_item_input = any(edge.destination.field != ITEM_FIELD for edge in input_edges)++ # Index prepared inputs by contexts and prefixes so each group visits only compatible candidates.+ prepared_by_context: dict[tuple[tuple[str, ...], tuple[int, ...]], list[int]] = {}+ prepared_by_prefix_context: dict[tuple[tuple[str, ...], tuple[int, ...]], list[int]] = {}+ prepared_root_sources_by_axes: dict[tuple[str, ...], list[int]] = {}+ prepared_root_items_by_axes: dict[tuple[str, ...], list[int]] = {}+ prepared_root_items_by_axes_prefix: dict[tuple[str, ...], list[int]] = {}+ prepared_with_axes: list[int] = []+ for prepared_input_index, (+ edge,+ _,+ _,+ source_axes,+ source_path,+ is_root_source,+ ) in enumerate(prepared_inputs):+ prepared_by_context.setdefault((source_axes, source_path), []).append(prepared_input_index)+ for prefix_depth in range(len(source_axes) + 1):+ axis_prefix = source_axes[:prefix_depth]+ path_prefix = source_path[:prefix_depth]+ prepared_by_prefix_context.setdefault((axis_prefix, path_prefix), []).append(prepared_input_index)+ if source_axes:+ prepared_with_axes.append(prepared_input_index)+ if is_root_source:+ prepared_root_sources_by_axes.setdefault(source_axes, []).append(prepared_input_index)+ if edge.destination.field == ITEM_FIELD and not source_path and source_axes:+ prepared_root_items_by_axes.setdefault(source_axes, []).append(prepared_input_index)+ for prefix_depth in range(len(source_axes) + 1):+ prepared_root_items_by_axes_prefix.setdefault(source_axes[:prefix_depth], []).append(+ prepared_input_index+ )+ def matches_group(+ edge: Edge,+ source_axes: tuple[str, ...],+ source_path: tuple[int, ...],+ group_axes: tuple[str, ...],+ group_path: tuple[int, ...],+ is_root_source: bool,+ ) -> bool:+ if edge.destination.field == ITEM_FIELD and not source_path and source_axes:+ return source_axes[: len(group_axes)] == group_axes or group_axes[: len(source_axes)] == source_axes+ if group_axes == source_axes:+ return group_path == source_path+ if len(group_axes) < len(source_axes) and source_axes[: len(group_axes)] == group_axes:+ return (+ edge.destination.field != ITEM_FIELD+ if not group_axes+ else group_path == source_path[: len(group_axes)]+ )+ if len(source_axes) < len(group_axes) and group_axes[: len(source_axes)] == source_axes:+ if is_root_source:+ return True+ return (+ edge.destination.field != ITEM_FIELD+ if not source_axes+ else source_path == group_path[: len(source_axes)]+ )+ return False++ iteration_mapping_groups = []+ for group_key in final_group_keys:+ group_axes, group_path = group_key+ candidate_prepared_indices = set(prepared_by_prefix_context.get(group_key, ()))+ for prefix_depth in range(len(group_axes)):+ candidate_axes = group_axes[:prefix_depth]+ candidate_path = group_path[:prefix_depth]+ candidate_prepared_indices.update(prepared_by_context.get((candidate_axes, candidate_path), ()))+ candidate_prepared_indices.update(prepared_root_sources_by_axes.get(candidate_axes, ()))+ if not group_axes and has_non_item_input:+ candidate_prepared_indices.update(prepared_with_axes)+ candidate_prepared_indices.update(prepared_root_items_by_axes_prefix.get(group_axes, ()))+ for prefix_depth in range(len(group_axes) + 1):+ candidate_prepared_indices.update(prepared_root_items_by_axes.get(group_axes[:prefix_depth], ()))+ iteration_mappings = []+ for prepared_input_index in sorted(candidate_prepared_indices):+ edge, source_node_id, prepared_id, source_axes, source_path, is_root_source = prepared_inputs[+ prepared_input_index+ ]+ if (+ is_root_source+ and not group_axes+ and any(key[0] for key in final_group_keys)+ and (edge.destination.field == ITEM_FIELD or not has_root_item_group)+ ):+ continue+ if matches_group(edge, source_axes, source_path, group_axes, group_path, is_root_source):+ iteration_mappings.append((source_node_id, prepared_id))+ iteration_mapping_groups.append((group_axes, group_path, iteration_mappings))+ has_deeper_group = any(group_path for _, group_path, _ in iteration_mapping_groups)return [- (- group_key,- [- (source_node_id, prepared_id)- for prepared_edge, source_node_id, prepared_id, iteration_path in prepared_inputs- if (- prepared_edge.destination.field == ITEM_FIELD- and (- group_key[: len(iteration_path)] == iteration_path- or iteration_path[: len(group_key)] == group_key- )- )- or (- prepared_edge.destination.field != ITEM_FIELD- and group_key[: len(iteration_path)] == iteration_path- )- ],- )- for group_key in final_group_keys+ (group_axes, iteration_path, iteration_mappings)+ for group_axes, iteration_path, iteration_mappings in iteration_mapping_groups+ if iteration_mappings or iteration_path or not has_deeper_group]+ @staticmethod+ def _remove_collect_group_prefixes(+ group_keys: set[tuple[tuple[str, ...], tuple[int, ...]]],+ ) -> set[tuple[tuple[str, ...], tuple[int, ...]]]:+ deepest_axes_by_prefix: dict[tuple[tuple[str, ...], tuple[int, ...]], int] = {}+ for axes, path in group_keys:+ for axes_prefix_depth in range(len(axes) + 1):+ axes_prefix = axes[:axes_prefix_depth]+ for path_prefix_depth in range(len(path) + 1):+ prefix = (axes_prefix, path[:path_prefix_depth])+ deepest_axes_by_prefix[prefix] = max(len(axes), deepest_axes_by_prefix.get(prefix, 0))+ return {+ group_key+ for group_key in group_keys+ if not group_key[0] or deepest_axes_by_prefix.get(group_key, len(group_key[0])) <= len(group_key[0])+ }+def _get_parent_iteration_mappings_without_iterators(self, next_node_id: str, input_edges: Optional[list[Edge]] = None) -> list[list[tuple[str, str]]]:input_edges = input_edges or self._state.graph._get_input_edges(next_node_id)- parent_node_ids = list(dict.fromkeys(edge.source.node_id for edge in input_edges))+ empty_if_item_sources = {+ edge.source.node_id+ for edge in input_edges+ if isinstance(self._state.graph.get_node(next_node_id), CollectInvocation)+ and edge.destination.field == ITEM_FIELD+ and isinstance(self._state.graph.get_node(edge.source.node_id), IfInvocation)+ and edge.source.node_id in self._state.executed+ and not self._state.source_prepared_mapping.get(edge.source.node_id)+ }+ parent_node_ids = [+ node_id+ for node_id in dict.fromkeys(edge.source.node_id for edge in input_edges)+ if node_id not in empty_if_item_sources+ ]+ if not parent_node_ids:+ return [[]]parent_prepared_nodes = {node_id: list(dict.fromkeys(@@ -1427,37 +2190,39 @@ class _ExecutionNodeBuilder:for _prepared_id, iteration_path in prepared_nodesif iteration_path != ()}- iteration_paths = sorted(- iteration_path+ proper_prefixes = {+ iteration_path[:prefix_length]for iteration_path in all_iteration_paths- if not any(- iteration_path != other_path and other_path[: len(iteration_path)] == iteration_path- for other_path in all_iteration_paths- )+ for prefix_length in range(len(iteration_path))+ }+ iteration_paths = sorted(+ iteration_path for iteration_path in all_iteration_paths if iteration_path not in proper_prefixes)if not iteration_paths:iteration_paths = [()]+ prepared_ids_by_node_and_path: dict[str, dict[tuple[int, ...], str]] = {}+ for node_id, prepared_nodes in parent_prepared_nodes.items():+ prepared_by_path: dict[tuple[int, ...], str] = {}+ for prepared_id, prepared_path in prepared_nodes:+ if prepared_path not in prepared_by_path or prepared_id < prepared_by_path[prepared_path]:+ prepared_by_path[prepared_path] = prepared_id+ prepared_ids_by_node_and_path[node_id] = prepared_by_pathmappings: list[list[tuple[str, str]]] = []for iteration_path in iteration_paths:mapping: list[tuple[str, str]] = []- for node_id, prepared_nodes in parent_prepared_nodes.items():- matching_prepared = next(- iter(- sorted(- (- (prepared_id, prepared_path)- for prepared_id, prepared_path in prepared_nodes- if iteration_path[: len(prepared_path)] == prepared_path- ),- key=lambda prepared: (-len(prepared[1]), prepared[0]),- )+ for node_id, prepared_by_path in prepared_ids_by_node_and_path.items():+ prepared_id = next(+ (+ prepared_by_path[iteration_path[:prefix_length]]+ for prefix_length in range(len(iteration_path), -1, -1)+ if iteration_path[:prefix_length] in prepared_by_path),None,)- if matching_prepared is None:+ if prepared_id is None:break- mapping.append((node_id, matching_prepared[0]))+ mapping.append((node_id, prepared_id))if len(mapping) == len(parent_node_ids):mappings.append(mapping)return mappings@@ -1466,8 +2231,46 @@ class _ExecutionNodeBuilder:self._state._tx_set_mapping(self._state.source_prepared_mapping, source_node_id, set())self._state._reset_unexecuted_prepared(source_node_id)self._state._mark_source_executed(source_node_id)+ if isinstance(self._state.graph.get_node(source_node_id), IfInvocation):+ self._queue_empty_if_branch_retirements(source_node_id)if isinstance(self._state.graph.get_node(source_node_id), IterateInvocation):self._state._record_empty_iterate_stream(source_node_id, iteration_path)+ self._queue_empty_iterator_retirements(source_node_id)++ def _queue_empty_if_branch_retirements(self, if_node_id: str) -> None:+ self._ensure_activation_candidate_index(self._state._get_source_graph_flat())+ for branch in ("true_input", "false_input"):+ for source_node_id in self._activation_sources_by_dependency.get((if_node_id, branch), ()):+ self._state._tx_add_set(self._pending_activation_retirement_candidates, source_node_id)++ def _queue_empty_iterator_retirements(self, iterator_id: str) -> None:+ self._ensure_activation_candidate_index(self._state._get_source_graph_flat())+ for source_node_id in self._activation_sources_by_iterator.get(iterator_id, ()):+ self._state._tx_add_set(self._pending_activation_retirement_candidates, source_node_id)++ def _has_completed_empty_nested_if_branch(self, node_id: str) -> bool:+ node = self._state.graph.get_node(node_id)+ if not isinstance(node, IfInvocation) or self._state.graph._get_input_edges(node_id, "condition"):+ return False+ selected_field = "true_input" if node.condition else "false_input"+ selected_edges = self._state.graph._get_input_edges(node_id, selected_field)+ if bool(selected_edges) and all(+ isinstance(self._state.graph.get_node(edge.source.node_id), IfInvocation)+ and edge.source.node_id in self._state.executed+ and not self._state.source_prepared_mapping.get(edge.source.node_id)+ for edge in selected_edges+ ):+ return True++ # A root If can have no frames when an unselected nested If is itself framed by an empty Iterate.+ unselected_field = "false_input" if node.condition else "true_input"+ unselected_edges = self._state.graph._get_input_edges(node_id, unselected_field)+ return bool(unselected_edges) and all(+ isinstance(self._state.graph.get_node(edge.source.node_id), IfInvocation)+ and not self._state.source_prepared_mapping.get(edge.source.node_id)+ and graph_if_runtime._has_empty_if_frame(self._state, edge.source.node_id)+ for edge in unselected_edges+ )def _index_prepared_nodes_by_iteration_path(self, prepared_nodes: set[str], input_edges: list[Edge]@@ -1556,6 +2359,19 @@ class _ExecutionNodeBuilder:iterator_node_ids: Optional[list[str]] = None,) -> Iterable[list[tuple[str, str]]]:input_edges = input_edges or self._state.graph._get_input_edges(next_node_id)+ next_node = self._state.graph.get_node(next_node_id)+ if isinstance(next_node, IterateInvocation) and len(input_edges) == 1:+ collection_edge = input_edges[0]+ if (+ collection_edge.destination.field == COLLECTION_FIELD+ and collection_edge.source.field == COLLECTION_FIELD+ and isinstance(self._state.graph.get_node(collection_edge.source.node_id), CollectInvocation)+ ):+ source_node_id = collection_edge.source.node_id+ return iter(+ [(source_node_id, prepared_id)]+ for prepared_id in self._get_ordered_prepared_nodes_for_edge(collection_edge)+ )parent_node_ids = list(dict.fromkeys(edge.source.node_id for edge in input_edges))iterator_graph = self.iterator_graph(graph)iterator_nodes = (@@ -1636,6 +2452,7 @@ class _ExecutionNodeBuilder:iteration_path: Optional[tuple[int, ...]] = None,input_fields: Optional[set[str]] = None,enforce_admission: bool = True,+ iteration_axes: Optional[tuple[str, ...]] = None,) -> list[str]:"""Prepares an iteration node and connects all edges, returning the new node id"""@@ -1666,6 +2483,44 @@ class _ExecutionNodeBuilder:new_node = self._create_execution_node_copy(node, node_id, iteration_index)if new_node_iteration_path is not None:self._state._prepared_registry().set_iteration_path(new_node.id, new_node_iteration_path)+ new_node_axes = iteration_axes+ if new_node_axes is None:+ parent_axes = []+ for source_node_id, prepared_id in iteration_node_map:+ axes = self._state._prepared_registry().get_iteration_axes(prepared_id)+ if axes is None:+ axes = self._get_iteration_axes(source_node_id)+ if isinstance(self._state.graph.get_node(source_node_id), ForInvocation) and axes:+ source_edges = [+ edge+ for edge in input_edges+ if edge.source.node_id == source_node_id+ and get_output_field_scope(+ self._state.graph.get_node(source_node_id), edge.source.field+ )+ == OutputScope.Final+ ]+ if source_edges and axes[-1] == source_node_id:+ axes = axes[:-1]+ parent_axes.append(axes)+ new_node_axes = max(parent_axes, key=len, default=())+ if any(new_node_axes[: len(axes)] != axes for axes in parent_axes):+ new_node_axes = None+ if new_node_axes is not None:+ if isinstance(node, (ForInvocation, IterateInvocation)) and iteration_index >= 0:+ new_node_axes = (*new_node_axes, node_id)+ if len(new_node_axes) < len(new_node_iteration_path):+ static_axes = self._get_iteration_axes(node_id)+ if static_axes[: len(new_node_axes)] == new_node_axes and len(static_axes) >= len(+ new_node_iteration_path+ ):+ new_node_axes = static_axes[: len(new_node_iteration_path)]+ else:+ new_node_axes = None+ elif len(new_node_axes) > len(new_node_iteration_path):+ new_node_axes = new_node_axes[: len(new_node_iteration_path)]+ if new_node_axes is not None:+ self._state._prepared_registry().set_iteration_axes(new_node.id, new_node_axes)attached_edges = self._attach_execution_edges(new_node.id, new_edges)self._state._record_activation_dependencies(new_node.id)self._initialize_execution_node(new_node.id, attached_edges)@@ -1678,6 +2533,17 @@ class _ExecutionNodeBuilder:) -> bool:if not self._has_if_nodes:return True+ if isinstance(self._state.graph.get_node(node_id), CollectInvocation):+ if any(+ edge.destination.field == ITEM_FIELD+ and isinstance(self._state.graph.get_node(edge.source.node_id), IfInvocation)+ and any(+ self._state._prepared_registry().get_source_node_id(exec_node_id) == edge.source.node_id+ for exec_node_id in self._state._pending_if_exec_nodes+ )+ for edge in self._state.graph._get_input_edges(node_id)+ ):+ return Falseif isinstance(self._state.graph.get_node(node_id), IfInvocation):condition_edges = self._state.graph._get_input_edges(node_id, "condition")if not condition_edges:@@ -1691,7 +2557,9 @@ class _ExecutionNodeBuilder:)if not iteration_paths:# An empty Iterate giving the If its frames leaves it no executions; preparing it closes it empty.- return graph_if_runtime._has_empty_if_frame(self._state, node_id)+ return self._has_completed_empty_nested_if_branch(node_id) or graph_if_runtime._has_empty_if_frame(+ self._state, node_id+ )return any(self._state._is_source_activation_admitted(node_id, iteration_path)for iteration_path in iteration_paths@@ -1737,18 +2605,124 @@ class _ExecutionNodeBuilder:return iterator_nodes[-1:]return iterator_nodes+ def _get_root_if_projected_sibling_frame_counts(+ self,+ node_id: str,+ selected_field: str,+ iterator_graph: "nx.DiGraph",+ iterator_ancestry: _IteratorAncestry,+ iteration_paths: list[tuple[int, ...]],+ ) -> tuple[+ dict[tuple[int, ...], int],+ Optional[_ProjectedRootIfFrames],+ ]:+ """Count each root If copy at its deepest matching path and retain valid sibling frame identities."""+ counts = dict.fromkeys(iteration_paths, 1)+ selected_edges = self._state.graph._get_input_edges(node_id, selected_field)+ if self._get_ordered_iterator_axes_for_edges(selected_edges, iterator_graph):+ return counts, None++ other_field = "false_input" if selected_field == "true_input" else "true_input"+ other_edges = self._state.graph._get_input_edges(node_id, other_field)+ other_axes = self._get_ordered_iterator_axes_for_edges(other_edges, iterator_graph)+ reiterated_axes = graph_if_runtime._get_sibling_collect_iterate_axes_to_project(+ self._state, iterator_ancestry, other_axes+ )+ axis_id = next((axis_id for axis_id in reversed(other_axes) if axis_id in reiterated_axes), None)+ if axis_id is None:+ return counts, None++ prepared_ids = self._get_prepared_nodes_for_source(axis_id)+ if not prepared_ids:+ return counts, None++ counts = dict.fromkeys(iteration_paths, 0)+ requested_prefixes_by_depth: dict[int, set[tuple[int, ...]]] = defaultdict(set)+ for iteration_path in iteration_paths:+ requested_prefixes_by_depth[len(iteration_path)].add(iteration_path)+ registry = self._state._prepared_registry()+ prepared_frames: list[tuple[tuple[int, ...], tuple[str, ...]]] = []+ has_missing_axes = False+ requested_depths = sorted(requested_prefixes_by_depth, reverse=True)+ for prepared_id in prepared_ids:+ prepared_path = self._state._get_iteration_path(prepared_id)+ for depth in requested_depths:+ prefix = prepared_path[:depth]+ if prefix in requested_prefixes_by_depth[depth]:+ counts[prefix] += 1+ break+ prepared_axes = registry.get_iteration_axes(prepared_id)+ if prepared_axes is None:+ has_missing_axes = True+ continue+ prepared_frames.append((prepared_path, prepared_axes))++ projected_paths = graph_if_runtime._project_prepared_iteration_paths(prepared_frames, reiterated_axes)+ prepared_paths = [path for path, _ in prepared_frames]+ if has_missing_axes or projected_paths is None or len(prepared_paths) != len(set(prepared_paths)):+ return counts, None++ frames_by_path = {path: [] for path in iteration_paths}+ for prepared_path, prepared_axes in prepared_frames:+ projected_path = projected_paths[prepared_path]+ if projected_path in frames_by_path:+ frames_by_path[projected_path].append((prepared_path, prepared_axes))+ if any(len(frames_by_path[path]) != counts[path] for path in iteration_paths):+ return counts, None+ return counts, frames_by_path+def _get_if_condition_iteration_mappings(self, node_id: str, graph: "nx.DiGraph") -> Iterable[list[tuple[str, str]]]:condition_edges = self._state.graph._get_input_edges(node_id, "condition")iterator_graph = self.iterator_graph(graph)+ iterator_ancestry = self._get_iterator_ancestry(iterator_graph)if condition_edges:condition_axes = self._get_ordered_iterator_axes_for_edges(condition_edges, iterator_graph)condition_iterator_ids = set(condition_axes)if condition_iterator_ids:iterator_nodes = condition_axeselse:- iterator_nodes = self.get_node_iterators(node_id, iterator_graph)+ # A root condition's frames come from its resolved selected branch. Mapping every open axis here+ # duplicates root results when only the unselected branch carries an axis.+ condition_mappings = self._get_parent_iteration_mappings(+ node_id, graph, input_edges=condition_edges, iterator_node_ids=[]+ )+ branch_edges = {+ branch: self._state.graph._get_input_edges(node_id, branch)+ for branch in ("true_input", "false_input")+ }+ branch_axes_by_field: dict[str, list[str]] = {}+ for branch_field, edges in branch_edges.items():+ axes = self._get_ordered_iterator_axes_for_edges(edges, iterator_graph)+ reiterated_axes = graph_if_runtime._get_sibling_collect_iterate_axes_to_project(+ self._state, iterator_ancestry, axes+ )+ branch_axes_by_field[branch_field] = [axis_id for axis_id in axes if axis_id not in reiterated_axes]++ def get_root_condition_mappings() -> Iterable[list[tuple[str, str]]]:+ for mapping in condition_mappings:+ condition_exec_id = dict(mapping)[condition_edges[0].source.node_id]+ if condition_exec_id not in self._state.results:+ continue+ condition_value = getattr(+ self._state.results[condition_exec_id], condition_edges[0].source.field+ )+ selected_field = "true_input" if condition_value else "false_input"+ axes = branch_axes_by_field[selected_field]+ if not axes:+ yield mapping+ continue+ axis_id = axes[-1]+ prepared_axis_ids = (+ self._get_prepared_nodes_for_source(axis_id)+ if axis_id in self._state.source_prepared_mapping+ else set()+ )+ for prepared_axis_id in sorted(prepared_axis_ids, key=self._state._get_iteration_path):+ yield [*mapping, (axis_id, prepared_axis_id)]++ return get_root_condition_mappings()else:iterator_nodes = self.get_node_iterators(node_id, iterator_graph)if condition_edges and not iterator_nodes:@@ -1767,8 +2741,14 @@ class _ExecutionNodeBuilder:# This specialization derives one branch axis against a root-frame condition. Mixed or nested condition# axes use the general parent-mapping path.- iterator_ancestry = self._get_iterator_ancestry(iterator_graph)- iterator_nodes = self._get_if_frame_iterator_nodes(node_id, iterator_graph)+ if condition_edges:+ if all(+ outer_id in iterator_ancestry.get_ordered_iterator_ancestors(inner_id)+ for outer_id, inner_id in itertools.pairwise(iterator_nodes)+ ):+ iterator_nodes = iterator_nodes[-1:]+ else:+ iterator_nodes = self._get_if_frame_iterator_nodes(node_id, iterator_graph)if len(iterator_nodes) != 1:return iter([[]])for branch_field in ("true_input", "false_input"):@@ -1832,9 +2812,19 @@ class _ExecutionNodeBuilder:node = self._state.graph.get_node(node_id)assert isinstance(node, IfInvocation)selected_field = "true_input" if node.condition else "false_input"+ other_field = "false_input" if node.condition else "true_input"gating_source_ids = [edge.source.node_id for edge in self._state.graph._get_input_edges(node_id, selected_field)]+ iterator_ancestry = self._get_iterator_ancestry(self.iterator_graph(graph))+ branch_axes = graph_if_runtime._get_if_static_frame_analysis(self._state, iterator_ancestry, node_id)[0]+ selected_axes = set(branch_axes[selected_field])+ for axis_id in set(branch_axes[other_field]) - selected_axes:+ if not isinstance(self._state.graph.get_node(axis_id), IterateInvocation):+ continue+ collection_edges = self._state.graph._get_input_edges(axis_id, COLLECTION_FIELD)+ if graph_if_runtime._get_collects_before_iteration_boundary(self._state, collection_edges):+ gating_source_ids.append(axis_id)ancestors: set[str] = set()for source_node_id in gating_source_ids:ancestors.update(nx.ancestors(graph, source_node_id))@@ -1932,13 +2922,15 @@ class _ExecutionNodeBuilder:return self._get_sibling_iterate_if_collect_branches().get(iterate_node_id)def _attach_pending_if_inputs(self, *, enqueue: bool = True) -> None:- """Attach only the selected branch edge to condition-ready If executions."""+ """Resolve fresh If conditions before admitting branches; attach only the selected value input."""source_graph = self._state._get_source_graph_flat()+ self._ensure_activation_candidate_index(source_graph)# Prepared branch sources do not change during this sweep. Index them by frame once per source edge;# keeping the index local means graph edits, rollback, and restore rebuild it on the next call.prepared_exec_by_edge_path: dict[tuple[str, str], dict[tuple[int, ...], str]] = {}- source_order = {node_id: index for index, node_id in enumerate(nx.topological_sort(source_graph))}+ prepared_exec_by_edge_context: dict[tuple[str, str], dict[tuple[tuple[str, ...], tuple[int, ...]], str]] = {}+ source_order = self._activation_candidate_topological_indexpending_exec_nodes = sorted(self._state._pending_if_exec_nodes,key=lambda exec_node_id: (@@ -1948,53 +2940,118 @@ class _ExecutionNodeBuilder:),)for exec_node_id in pending_exec_nodes:+ source_if_id = self._state._prepared_registry().get_source_node_id(exec_node_id)+ fresh_if = not self._state._legacy_snapshot_loadedself._state._try_resolve_if_node(exec_node_id, enqueue=False)- selected_field = self._state._resolved_if_exec_branches.get(exec_node_id)- if selected_field is None:- continue- if any(- edge.destination.field == selected_field- for edge in self._state.execution_graph._get_input_edges(exec_node_id)+ if fresh_if:+ selected_field = self._state._resolved_if_exec_branches.get(exec_node_id)+ if selected_field is None:+ continue+ required_branch_fields = (+ (selected_field,)+ if self._state._is_fresh_lazy_if_candidate(source_if_id)+ else ("true_input", "false_input")+ )+ branch_fields = (selected_field,)+ if any(+ edge.source.node_id not in self._state.executed+ for branch_field in required_branch_fields+ for edge in self._state.graph._get_input_edges(source_if_id, branch_field)+ ):+ continue+ else:+ selected_field = self._state._resolved_if_exec_branches.get(exec_node_id)+ if selected_field is None:+ continue+ required_branch_fields = (selected_field,)+ branch_fields = (selected_field,)+ if all(+ not self._state.graph._get_input_edges(source_if_id, branch_field)+ or any(+ edge.destination.field == branch_field+ for edge in self._state.execution_graph._get_input_edges(exec_node_id)+ )+ for branch_field in branch_fields):+ if fresh_if:+ self._state._try_resolve_if_node(exec_node_id, enqueue=False)+ if exec_node_id not in self._state._resolved_if_exec_branches:+ continueif 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)target_path = self._state._get_iteration_path(exec_node_id)- selected_edges = self._state.graph._get_input_edges(source_if_id, selected_field)+ target_axes = self._state._prepared_registry().get_iteration_axes(exec_node_id)+ branch_edges = [+ (branch_field, edge)+ for branch_field in branch_fields+ for edge in self._state.graph._get_input_edges(source_if_id, branch_field)+ ]+ if any(+ isinstance(source_node := self._state.graph.get_node(edge.source.node_id), ForInvocation)+ and get_output_field_scope(source_node, edge.source.field) == OutputScope.Final+ and not self._state._all_for_contexts_finalized(source_node.id)+ for _, edge in branch_edges+ ):+ continue+ if (+ selected_field is not None+ and self._state.graph._get_input_edges(source_if_id, selected_field)+ and all(+ source_edge.source.node_id in self._state.executed+ and not self._state.source_prepared_mapping.get(source_edge.source.node_id)+ for source_edge in self._state.graph._get_input_edges(source_if_id, selected_field)+ )+ ):+ # A selected branch can be a completed nested If with no executions. Eagerly running+ # the other branch must not turn that empty selected value into a None result.+ self._mark_source_node_empty(source_if_id)+ self._state._mark_exec_node_executed(exec_node_id)+ self._state._set_prepared_exec_state(exec_node_id, "skipped")+ if enqueue:+ self._state._tx_discard_set(self._state._pending_if_exec_nodes, exec_node_id)+ continueattached_edges: list[Edge] = []selected_exec_ids: list[str] = []- for source_edge in selected_edges:+ for branch_field, source_edge in branch_edges:if source_edge.source.node_id not in self._state.source_prepared_mapping:continueedge_key = (source_edge.source.node_id, source_edge.source.field)if edge_key not in prepared_exec_by_edge_path:prepared_exec_by_path: dict[tuple[int, ...], str] = {}+ prepared_exec_by_context: dict[tuple[tuple[str, ...], tuple[int, ...]], str] = {}for prepared_id in self._get_ordered_prepared_nodes_for_edge(source_edge):prepared_path = self._get_prepared_edge_iteration_path(source_edge, prepared_id)prepared_exec_by_path.setdefault(prepared_path, prepared_id)+ prepared_axes = self._get_prepared_edge_iteration_axes(source_edge, prepared_id)+ prepared_exec_by_context.setdefault((prepared_axes, prepared_path), prepared_id)prepared_exec_by_edge_path[edge_key] = prepared_exec_by_path+ prepared_exec_by_edge_context[edge_key] = prepared_exec_by_contextprepared_exec_by_path = prepared_exec_by_edge_path[edge_key]- selected_exec_id = next(- (- prepared_exec_by_path[target_path[:path_depth]]- for path_depth in range(len(target_path), -1, -1)- if target_path[:path_depth] in prepared_exec_by_path- ),- None,- )+ selected_exec_id = None+ if target_axes is not None:+ selected_exec_id = prepared_exec_by_edge_context[edge_key].get((target_axes, target_path))+ if selected_exec_id is None:+ selected_exec_id = next(+ (+ prepared_exec_by_path[target_path[:path_depth]]+ for path_depth in range(len(target_path), -1, -1)+ if target_path[:path_depth] in prepared_exec_by_path+ ),+ None,+ )if selected_exec_id is None:continueselected_exec_ids.append(selected_exec_id)attached_edges.append(Edge(source=EdgeConnection(node_id=selected_exec_id, field=source_edge.source.field),- destination=EdgeConnection(node_id=exec_node_id, field=selected_field),+ destination=EdgeConnection(node_id=exec_node_id, field=branch_field),))- if not attached_edges or any(+ if any(self._state._is_pending_if(candidate_id)or (isinstance(self._state.execution_graph.get_node(candidate_id), IfInvocation)@@ -2004,7 +3061,21 @@ class _ExecutionNodeBuilder:):continue- self._attach_execution_edges(exec_node_id, attached_edges)+ if attached_edges:+ self._attach_execution_edges(exec_node_id, attached_edges)+ if fresh_if and any(+ self._state.graph._get_input_edges(source_if_id, branch_field)+ and not any(+ edge.destination.field == branch_field+ for edge in self._state.execution_graph._get_input_edges(exec_node_id)+ )+ for branch_field in branch_fields+ ):+ continue+ if fresh_if:+ self._state._try_resolve_if_node(exec_node_id, enqueue=False)+ if exec_node_id not in self._state._resolved_if_exec_branches:+ continueinput_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)@@ -2064,7 +3135,7 @@ class _ExecutionNodeBuilder:def _get_prepared_nodes_for_source(self, source_node_id: str) -> set[str]:return {exec_node_id- for exec_node_id in self._state.source_prepared_mapping[source_node_id]+ for exec_node_id in self._state.source_prepared_mapping.get(source_node_id, ())if self._state._get_prepared_exec_metadata(exec_node_id).state != "skipped"}@@ -2167,16 +3238,37 @@ class _ExecutionNodeBuilder:if_exec_ids = self._state.source_prepared_mapping.get(if_node_id, set())return not if_exec_ids or not all(exec_id in self._state._resolved_if_exec_branches for exec_id in if_exec_ids)+ def _should_defer_shared_collect_if(self, node_id: str, iterator_ancestry: _IteratorAncestry) -> bool:+ if not isinstance(self._state.graph.get_node(node_id), IfInvocation):+ return False+ condition_edges = self._state.graph._get_input_edges(node_id, "condition")+ branch_edges = [self._state.graph._get_input_edges(node_id, field) for field in ("true_input", "false_input")]+ if not condition_edges or any(not edges for edges in branch_edges):+ return False++ branch_axes = graph_if_runtime._get_if_runtime_branch_frame_axes(self._state, iterator_ancestry, node_id)+ axes = [set(branch_axes[field]) for field in ("true_input", "false_input")]+ condition_axes = {+ axis_id for edge in condition_edges for axis_id in iterator_ancestry.get_frame_axes_for_edge(edge)+ }+ if axes[0] != axes[1] or not axes[0] > condition_axes:+ return False++ branch_collects = [+ graph_if_runtime._get_collects_before_iteration_boundary(self._state, edges) for edges in branch_edges+ ]+ shared_collects = branch_collects[0] & branch_collects[1]+ return any(source_id not in self._state.executed for source_id in shared_collects)+def _expand_root_if_for_completed_collect_branch(self, graph: "nx.DiGraph") -> Optional[str]:- """Align a root-conditioned If frame with each completed selected Collect frame."""+ """Align a root If frame with each completed selected nested-If frame."""iterator_graph = self.iterator_graph(graph)for if_node_id, node in self._state.graph.nodes.items():if not isinstance(node, IfInvocation):continuecondition_edges = self._state.graph._get_input_edges(if_node_id, "condition")- if (- not condition_edges- or any(edge.source.node_id not in iterator_graph for edge in condition_edges)+ if condition_edges and (+ any(edge.source.node_id not in iterator_graph for edge in condition_edges)or any(self._get_iterator_ancestry(iterator_graph).get_iterator_axes_for_edge(edge)for edge in condition_edges@@ -2184,20 +3276,28 @@ class _ExecutionNodeBuilder:):continue- root_exec_ids = [+ pending_if_exec_ids = [exec_idfor exec_id in self._state.source_prepared_mapping.get(if_node_id, ())- if self._state._get_iteration_path(exec_id) == ()- and self._state._is_pending_if(exec_id)- and (selected_field := self._state._resolved_if_exec_branches.get(exec_id)) is not None+ if self._state._is_pending_if(exec_id)+ and self._state._resolved_if_exec_branches.get(exec_id) is not None]- if len(root_exec_ids) != 1:+ if not pending_if_exec_ids:continue- root_exec_id = root_exec_ids[0]+ root_exec_id = pending_if_exec_ids[0]selected_field = self._state._resolved_if_exec_branches[root_exec_id]selected_edges = self._state.graph._get_input_edges(if_node_id, selected_field)if not selected_edges or any(- not isinstance(self._state.graph.get_node(edge.source.node_id), CollectInvocation)+ (+ isinstance(self._state.graph.get_node(edge.source.node_id), IfInvocation)+ and (+ edge.source.node_id not in self._state.executed+ or any(+ prepared_id not in self._state.results+ for prepared_id in self._state.source_prepared_mapping.get(edge.source.node_id, ())+ )+ )+ )or edge.source.node_id not in self._state.executedor any(prepared_id not in self._state.results@@ -2207,38 +3307,84 @@ class _ExecutionNodeBuilder:):continue- branch_paths = sorted(- {- self._state._get_iteration_path(prepared_id)- for edge in selected_edges- for prepared_id in self._state.source_prepared_mapping.get(edge.source.node_id, ())- }+ branch_paths = graph_if_runtime._get_if_iteration_paths_with_ancestry(+ self._state,+ if_node_id,+ set(),+ self._get_prepared_nodes_for_source,+ self._get_prepared_edge_iteration_path,+ self._get_iterator_ancestry(iterator_graph),)if not branch_paths or branch_paths[0] == ():continue- existing_paths = {- self._state._get_iteration_path(exec_id)- for exec_id in self._state.source_prepared_mapping.get(if_node_id, ())- }- if existing_paths != {()}:+ prepared_if_ids = self._state.source_prepared_mapping.get(if_node_id, ())+ exec_ids_by_path: dict[tuple[int, ...], list[str]] = {}+ for exec_id in prepared_if_ids:+ exec_ids_by_path.setdefault(self._state._get_iteration_path(exec_id), []).append(exec_id)+ if any(len(exec_ids) > 1 for exec_ids in exec_ids_by_path.values()):continue- condition_mapping = [- (self._state.prepared_source_mapping[edge.source.node_id], edge.source.node_id)- for edge in self._state.execution_graph._get_input_edges(root_exec_id)- if edge.destination.field == "condition"- ]- if not condition_mapping:+ # A root condition can be prepared at an outer prefix before its selected branch reveals inner frames.+ # Graph validation keeps the open axes nested, so the integer path prefix has the same axis identity.+ frame_expansions: list[tuple[str, tuple[int, ...], list[tuple[str, str]], list[tuple[int, ...]]]] = []+ existing_paths = set(exec_ids_by_path)+ if any(+ self._state._resolved_if_exec_branches.get(exec_id) != selected_field for exec_id in prepared_if_ids+ ):+ continue+ missing_paths = set(branch_paths) - existing_paths+ if not missing_paths:+ continue+ targets_by_prefix: dict[tuple[int, ...], list[tuple[int, ...]]] = {}+ valid_expansion = True+ for path in missing_paths:+ prefixes = [+ existing_path+ for existing_path in existing_paths+ if len(existing_path) < len(path) and path[: len(existing_path)] == existing_path+ ]+ if not prefixes:+ valid_expansion = False+ break+ targets_by_prefix.setdefault(max(prefixes, key=len), []).append(path)+ if not valid_expansion or any(+ existing_path not in targets_by_prefix for existing_path in existing_paths - set(branch_paths)+ ):+ continue+ if any(+ exec_id not in pending_if_exec_ids+ for existing_path in targets_by_prefix+ if existing_path not in branch_paths+ for exec_id in exec_ids_by_path[existing_path]+ ):+ continue+ for existing_path, target_paths in targets_by_prefix.items():+ exec_id = exec_ids_by_path[existing_path][0]+ first_frame_path = existing_path if existing_path in branch_paths else target_paths[0]+ clone_paths = target_paths if existing_path in branch_paths else target_paths[1:]+ condition_mapping = [+ (self._state.prepared_source_mapping[edge.source.node_id], edge.source.node_id)+ for edge in self._state.execution_graph._get_input_edges(exec_id)+ if edge.destination.field == "condition"+ ]+ frame_expansions.append((exec_id, first_frame_path, condition_mapping, clone_paths))+ if not frame_expansions:+ continue+ expanded_paths = {+ path+ for _, first_path, _, remaining_paths in frame_expansions+ for path in (first_path, *remaining_paths)+ }+ if expanded_paths | (existing_paths & set(branch_paths)) != set(branch_paths):continue-return self._state._run_materialization_transaction(lambda graph=graph,if_node_id=if_node_id,root_exec_id=root_exec_id,- condition_mapping=condition_mapping,+ frame_expansions=frame_expansions,branch_paths=branch_paths: self._materialize_root_if_for_completed_collect_branch(- graph, if_node_id, root_exec_id, condition_mapping, branch_paths+ graph, if_node_id, root_exec_id, frame_expansions, branch_paths))@@ -2249,39 +3395,52 @@ class _ExecutionNodeBuilder:graph: "nx.DiGraph",if_node_id: str,root_exec_id: str,- condition_mapping: list[tuple[str, str]],+ frame_expansions: list[tuple[str, tuple[int, ...], list[tuple[str, str]], list[tuple[int, ...]]]],branch_paths: list[tuple[int, ...]],) -> str:- """Expand resolved root If state into its completed Collect frames atomically."""- # The root If already resolved the branch gate so its iterators could run. Reuse that- # execution as the first selected frame, then create one If execution for every other- # closed Collect frame. Keep the durable activation token and generic gate frame aligned.+ """Expand resolved root If prefixes into their selected nested frames atomically."""first_path, *remaining_paths = branch_paths- self._state._prepared_registry().set_iteration_path(root_exec_id, first_path)- frame = self._state._get_execution_frame(root_exec_id)- engine_frame = self._state._engine_frame(first_path)generic_runtime = self._state._generic_runtime()- gate = generic_runtime.gates.get(root_exec_id)- if gate is not None:- previous_gate = ActivationGate.model_validate(gate.model_dump(mode="python"))- generic_runtime.replace_gate(- ActivationGate(- gate_id=gate.gate_id,- owner_id=gate.owner_id,- frame=engine_frame,- branches=gate.branches,- status=gate.status,- selected_branch=gate.selected_branch,- )- )- self._state._tx_record(lambda gate=previous_gate, runtime=generic_runtime: runtime.replace_gate(gate))- for token_id, token in tuple(self._state.execution_tokens.items()):- if token.owner_node_id == root_exec_id and token.token_kind == "activation":- self._state._tx_set_mapping(- self._state.execution_tokens,- token_id,- token.model_copy(update={"frame": frame}),- )+ for exec_id, first_frame_path, condition_mapping, remaining_frame_paths in frame_expansions:+ if self._state._get_iteration_path(exec_id) != first_frame_path:+ self._state._prepared_registry().set_iteration_path(exec_id, first_frame_path)+ frame = self._state._get_execution_frame(exec_id)+ engine_frame = self._state._engine_frame(first_frame_path)+ gate = generic_runtime.gates.get(exec_id)+ if gate is not None:+ previous_gate = ActivationGate.model_validate(gate.model_dump(mode="python"))+ generic_runtime.replace_gate(+ ActivationGate(+ gate_id=gate.gate_id,+ owner_id=gate.owner_id,+ frame=engine_frame,+ branches=gate.branches,+ status=gate.status,+ selected_branch=gate.selected_branch,+ )+ )+ self._state._tx_record(+ lambda gate=previous_gate, runtime=generic_runtime: runtime.replace_gate(gate)+ )+ for token_id, token in tuple(self._state.execution_tokens.items()):+ if token.owner_node_id == exec_id and token.token_kind == "activation":+ self._state._tx_set_mapping(+ self._state.execution_tokens,+ token_id,+ token.model_copy(update={"frame": frame}),+ )++ for iteration_path in remaining_frame_paths:+ if condition_mapping:+ self.create_execution_node(+ if_node_id,+ condition_mapping,+ iteration_path,+ input_fields={"condition"},+ )+ else:+ self.create_execution_node(if_node_id, [], iteration_path)+self._state._invalidate_selected_if_frames_for_preparation(if_node_id)self._state._prepared_if_exec_indexed_sources.discard(if_node_id)for key in tuple(self._state._prepared_if_exec_ids_by_source_and_frame):@@ -2289,18 +3448,10 @@ class _ExecutionNodeBuilder:self._state._prepared_if_exec_ids_by_source_and_frame.pop(key, None)self._state._prepared_if_exec_frames_by_source.pop(if_node_id, None)- for iteration_path in remaining_paths:- self.create_execution_node(- if_node_id,- condition_mapping,- iteration_path,- input_fields={"condition"},- )-for consumer_id in graph.successors(if_node_id):if isinstance(self._state.graph.get_node(consumer_id),- (IfInvocation, CollectInvocation, ForInvocation, IterateInvocation),+ (IfInvocation, ForInvocation, IterateInvocation),):continueconsumer_exec_ids = self._state.source_prepared_mapping.get(consumer_id, ())@@ -2318,10 +3469,13 @@ class _ExecutionNodeBuilder:):continue- self._state._prepared_registry().set_iteration_path(root_consumer_id, first_path)- for iteration_path in remaining_paths:- iteration_mapping = []- for edge in self._state.graph._get_input_edges(consumer_id):+ def get_iteration_mapping(+ iteration_path: tuple[int, ...], consumer_source_id: str = consumer_id+ ) -> Optional[list[tuple[str, str]]]:+ mapping_by_source: dict[str, str] = {}+ for edge in self._state.graph._get_input_edges(consumer_source_id):+ if edge.source.node_id in mapping_by_source:+ continueprepared_sources = self._state.source_prepared_mapping.get(edge.source.node_id, ())matching_source = next((@@ -2337,10 +3491,41 @@ class _ExecutionNodeBuilder:None,)if matching_source is None and prepared_sources:- break+ return Noneif matching_source is not None:- iteration_mapping.append((edge.source.node_id, matching_source))- else:+ mapping_by_source[edge.source.node_id] = matching_source+ return list(mapping_by_source.items())++ root_iteration_mapping = get_iteration_mapping(first_path)+ if root_iteration_mapping is None:+ continue+ self._state._prepared_registry().set_iteration_path(root_consumer_id, first_path)+ scheduler = self._state._scheduler()+ scheduler.remove_from_ready_queues(root_consumer_id)+ old_input_edges = self._state.execution_graph._get_input_edges(root_consumer_id)+ execution_graph_flat = self._state.__pydantic_private__["_runtime_state"].execution_graph_flat+ for edge in old_input_edges:+ self._state._tx_delete_execution_edge(edge)+ if (+ execution_graph_flat is not None+ and edge.type == "default"+ and execution_graph_flat.has_edge(edge.source.node_id, root_consumer_id)+ and not any(+ candidate.type == "default"+ and candidate.source.node_id == edge.source.node_id+ and candidate.destination.node_id == root_consumer_id+ for candidate in self._state.execution_graph.edges+ )+ ):+ execution_graph_flat.remove_edge(edge.source.node_id, root_consumer_id)+ attached_edges = self._attach_execution_edges(+ root_consumer_id,+ self._build_execution_edges(consumer_id, root_iteration_mapping),+ )+ self._initialize_execution_node(root_consumer_id, attached_edges)+ for iteration_path in remaining_paths:+ iteration_mapping = get_iteration_mapping(iteration_path)+ if iteration_mapping is not None:self.create_execution_node(consumer_id, iteration_mapping, iteration_path)return root_exec_id@@ -2385,13 +3570,13 @@ class _ExecutionNodeBuilder:def prepare(self, base_g: Optional["nx.DiGraph"] = None) -> Optional[str]:g = base_g if base_g is not None else self._state._get_source_graph_flat()self._get_sibling_iterate_if_collect_branches()- iterator_ancestry = self._get_iterator_ancestry(self.iterator_graph(g))+ iterator_graph = self.iterator_graph(g)+ iterator_ancestry = self._get_iterator_ancestry(iterator_graph)iterator_ancestry.clear_effective_iteration_paths()self._attach_pending_if_inputs()expanded_if_id = self._expand_root_if_for_completed_collect_branch(g)if expanded_if_id is not None:return expanded_if_id- self._attach_pending_if_inputs()self._ensure_activation_candidate_index(g)deferred_root_collect_if_descendants = self._get_unexecuted_root_collect_if_descendants(g)if self._has_if_nodes:@@ -2419,7 +3604,11 @@ class _ExecutionNodeBuilder:isinstance(self._state.graph.get_node(node_id), ForReturnInvocation)and self._is_deferred_nested_for_return(node_id))- and not self._has_unmaterializable_for_final_input(node_id)+ and (+ isinstance(self._state.graph.get_node(node_id), IfInvocation)+ and bool(self._state.graph._get_input_edges(node_id, "condition"))+ or not self._has_unmaterializable_for_final_input(node_id)+ )and node_id not in deferred_root_collect_if_descendantsand (all(@@ -2432,12 +3621,20 @@ class _ExecutionNodeBuilder:source_id in self._state.source_prepared_mapping or source_id in self._state.executedfor source_id, _ in g.in_edges(node_id))+ or isinstance(self._state.graph.get_node(node_id), CollectInvocation)+ and self._has_ready_empty_collect_group(node_id))and (isinstance(self._state.graph.get_node(node_id), IfInvocation)and self._is_if_condition_ready(node_id)or not isinstance(self._state.graph.get_node(node_id), IfInvocation))+ and not self._should_defer_shared_collect_if(node_id, iterator_ancestry)+ and not (+ isinstance(self._state.graph.get_node(node_id), IfInvocation)+ and graph_if_runtime._has_unresolved_if_frame_axes(self._state, node_id, iterator_ancestry)+ and not self._has_completed_empty_nested_if_branch(node_id)+ )and self._has_admitted_source_mapping(node_id, g, iterator_ancestry)and not self._should_defer_sibling_if_collect_iterate(node_id)and (@@ -2464,12 +3661,244 @@ class _ExecutionNodeBuilder:new_node_ids: list[str] = []if isinstance(next_node, CollectInvocation):- iteration_mapping_groups = self._get_collect_iteration_mapping_groups(- self._state.graph._get_input_edges(next_node_id)- )- for iteration_path, iteration_mappings in iteration_mapping_groups:- create_results = self.create_execution_node(next_node_id, iteration_mappings, iteration_path)- new_node_ids.extend(create_results)+ collect_inputs = self._state.graph._get_input_edges(next_node_id)+ nested_literal_sources = [+ edge.source.node_id+ for edge in collect_inputs+ if edge.destination.field == ITEM_FIELD+ and isinstance(self._state.graph.get_node(edge.source.node_id), IfInvocation)+ and not self._state.graph._get_input_edges(edge.source.node_id, "condition")+ and any(+ isinstance(self._state.graph.get_node(branch_edge.source.node_id), IfInvocation)+ for branch in ("true_input", "false_input")+ for branch_edge in self._state.graph._get_input_edges(edge.source.node_id, branch)+ )+ ]+ prepared_nested_ids = [+ prepared_id+ for source_id in dict.fromkeys(nested_literal_sources)+ for prepared_id in self._get_ordered_prepared_nodes_for_source(source_id)+ ]+ nested_literal_source_ids = set(nested_literal_sources)+ iterator_ancestry = self._get_iterator_ancestry(self.iterator_graph())+ prepared_ids_by_edge: dict[tuple[str, str, str, str], list[str]] = {}+ prepared_paths_by_edge: dict[tuple[str, str, str, str], dict[str, tuple[int, ...]]] = {}+ selected_parent_axes_by_source: dict[str, tuple[str, ...]] = {}+ selected_source_axes_by_source: dict[str, tuple[str, ...]] = {}+ static_source_axes_by_source: dict[str, tuple[str, ...]] = {}+ root_item_by_edge: dict[tuple[str, str, str, str], bool] = {}++ def input_edge_key(edge: Edge) -> tuple[str, str, str, str]:+ return (+ edge.source.node_id,+ edge.source.field,+ edge.destination.node_id,+ edge.destination.field,+ )++ def get_prepared_ids(edge: Edge) -> list[str]:+ key = input_edge_key(edge)+ if key not in prepared_ids_by_edge:+ prepared_ids_by_edge[key] = self._get_ordered_prepared_nodes_for_edge(edge)+ return prepared_ids_by_edge[key]++ def get_prepared_path(edge: Edge, prepared_id: str) -> tuple[int, ...]:+ key = input_edge_key(edge)+ paths = prepared_paths_by_edge.setdefault(key, {})+ if prepared_id not in paths:+ paths[prepared_id] = self._get_prepared_edge_iteration_path(edge, prepared_id)+ return paths[prepared_id]++ def get_selected_parent_axes(source_id: str) -> tuple[str, ...]:+ if source_id not in selected_parent_axes_by_source:+ selected_parent_axes_by_source[source_id] = self._get_selected_for_final_parent_axes(+ source_id, iterator_ancestry+ )+ return selected_parent_axes_by_source[source_id]++ def get_static_source_axes(source_id: str) -> tuple[str, ...]:+ if source_id not in static_source_axes_by_source:+ static_source_axes_by_source[source_id] = tuple(self._get_collect_source_iterator_ids(source_id))+ return static_source_axes_by_source[source_id]++ def get_selected_source_axes(source_id: str) -> tuple[str, ...]:+ if source_id not in selected_source_axes_by_source:+ selected_axes = (+ get_selected_parent_axes(source_id)+ if isinstance(self._state.graph.get_node(source_id), IfInvocation)+ else ()+ )+ selected_source_axes_by_source[source_id] = selected_axes or get_static_source_axes(source_id)+ return selected_source_axes_by_source[source_id]++ def is_root_item_source(edge: Edge) -> bool:+ key = input_edge_key(edge)+ if key not in root_item_by_edge:+ prepared_ids = get_prepared_ids(edge)+ root_item_by_edge[key] = (+ edge.destination.field == ITEM_FIELD+ and not get_static_source_axes(edge.source.node_id)+ and bool(prepared_ids)+ and all(not get_prepared_path(edge, prepared_id) for prepared_id in prepared_ids)+ )+ return root_item_by_edge[key]++ item_edges = [edge for edge in collect_inputs if edge.destination.field == ITEM_FIELD]+ selected_axis_prefixes = {+ axes[:prefix_depth]+ for source_id in (edge.source.node_id for edge in item_edges)+ for axes in (get_selected_parent_axes(source_id),)+ for prefix_depth in range(len(axes))+ }++ prepared_item_groups: set[tuple[tuple[str, ...], tuple[int, ...]]] = set()+ for input_edge in item_edges:+ source_id = input_edge.source.node_id+ if is_root_item_source(input_edge):+ continue+ source_axes = get_selected_source_axes(source_id)+ if source_id in nested_literal_source_ids:+ selected_for_axes = get_selected_parent_axes(source_id)+ enclosing_selected_for_axes = source_axes in selected_axis_prefixes+ group_axes = selected_for_axes or (+ source_axes if source_axes and enclosing_selected_for_axes else source_axes[:-1]+ )+ prepared_item_groups.update(+ (group_axes[: len(path)], path[: len(group_axes)])+ for candidate_id in get_prepared_ids(input_edge)+ if len(path := get_prepared_path(input_edge, candidate_id)) <= len(source_axes)+ )+ else:+ prepared_item_groups.update(+ (group_axes, path)+ for group_axes, path, _ in self._get_collect_iteration_mapping_groups([input_edge])+ )+ prepared_item_groups = self._remove_collect_group_prefixes(prepared_item_groups)+ if (+ self._collect_has_selected_for_final_input(next_node_id)+ and len(prepared_nested_ids) > 1+ and len(prepared_item_groups) > 1+ ):+ group_keys_by_depths: dict[tuple[int, int], set[tuple[tuple[str, ...], tuple[int, ...]]]] = defaultdict(+ set+ )+ for group_key in prepared_item_groups:+ group_keys_by_depths[(len(group_key[0]), len(group_key[1]))].add(group_key)+ groups_by_candidate_prefix: dict[+ tuple[int, int],+ dict[tuple[tuple[str, ...], tuple[int, ...]], list[tuple[tuple[str, ...], tuple[int, ...]]]],+ ] = {}++ def get_candidate_ancestor_groups(+ candidate_axes: tuple[str, ...], candidate_path: tuple[int, ...]+ ) -> list[tuple[tuple[str, ...], tuple[int, ...]]]:+ prefix_depths = (len(candidate_axes), len(candidate_path))+ index = groups_by_candidate_prefix.get(prefix_depths)+ if index is None:+ index = defaultdict(list)+ for group_axes, group_path in prepared_item_groups:+ if len(group_axes) >= prefix_depths[0] and len(group_path) >= prefix_depths[1]:+ index[(group_axes[: prefix_depths[0]], group_path[: prefix_depths[1]])].append(+ (group_axes, group_path)+ )+ groups_by_candidate_prefix[prefix_depths] = index+ return index.get((candidate_axes, candidate_path), [])++ grouped_item_mappings: list[+ Optional[dict[tuple[tuple[str, ...], tuple[int, ...]], list[tuple[str, str]]]]+ ] = []+ special_item_candidates_by_edge: dict[+ tuple[str, str, str, str], dict[tuple[tuple[str, ...], tuple[int, ...]], list[str]]+ ] = {}+ for input_edge in collect_inputs:+ source_id = input_edge.source.node_id+ is_root_item = is_root_item_source(input_edge)+ if (+ input_edge.destination.field != ITEM_FIELD+ or source_id in nested_literal_source_ids+ or is_root_item+ ):+ grouped_item_mappings.append(None)+ source_axes = get_selected_source_axes(source_id)+ candidates_by_group: dict[tuple[tuple[str, ...], tuple[int, ...]], list[str]] = defaultdict(+ list+ )+ for candidate_id in get_prepared_ids(input_edge):+ candidate_path = get_prepared_path(input_edge, candidate_id)+ candidate_axes = source_axes[: len(candidate_path)]+ candidate_groups = set(get_candidate_ancestor_groups(candidate_axes, candidate_path))+ for group_depths, groups_at_depth in group_keys_by_depths.items():+ group_axes_depth, group_path_depth = group_depths+ if group_axes_depth < len(candidate_axes) and group_path_depth <= len(candidate_path):+ group_key = (candidate_axes[:group_axes_depth], candidate_path[:group_path_depth])+ if group_key in groups_at_depth:+ candidate_groups.add(group_key)+ for group_axes, iteration_path in candidate_groups:+ candidate_is_ancestor = (+ len(candidate_axes) <= len(group_axes)+ and group_axes[: len(candidate_axes)] == candidate_axes+ and iteration_path[: len(candidate_path)] == candidate_path+ )+ candidate_is_descendant = (+ len(candidate_axes) > len(group_axes)+ and candidate_axes[: len(group_axes)] == group_axes+ and candidate_path[: len(iteration_path)] == iteration_path+ )+ if candidate_is_ancestor or (+ input_edge.destination.field == ITEM_FIELD and candidate_is_descendant+ ):+ candidates_by_group[(group_axes, iteration_path)].append(candidate_id)+ special_item_candidates_by_edge[input_edge_key(input_edge)] = candidates_by_group+ continue+ grouped_item_mappings.append(+ {+ (candidate_axes, iteration_path): iteration_mappings+ for candidate_axes, iteration_path, iteration_mappings in (+ self._get_collect_iteration_mapping_groups([input_edge])+ )+ }+ )+ has_nonroot_prepared_group = any(axes for axes, _ in prepared_item_groups)+ for group_axes, iteration_path in sorted(prepared_item_groups):+ iteration_mapping: list[tuple[str, str]] = []+ for input_edge, item_mappings in zip(collect_inputs, grouped_item_mappings, strict=True):+ source_id = input_edge.source.node_id+ if item_mappings is not None:+ iteration_mapping.extend(item_mappings.get((group_axes, iteration_path), ()))+ continue++ source_axes = get_selected_source_axes(source_id)+ is_root_item = is_root_item_source(input_edge)+ if is_root_item and not group_axes and has_nonroot_prepared_group:+ continue+ # A selected nested branch stays out of a separate root item group.+ if (+ input_edge.destination.field == ITEM_FIELD+ and not group_axes+ and get_selected_parent_axes(source_id)+ ):+ continue+ iteration_mapping.extend(+ (source_id, candidate_id)+ for candidate_id in special_item_candidates_by_edge.get(input_edge_key(input_edge), {}).get(+ (group_axes, iteration_path), ()+ )+ )+ new_node_ids.extend(+ self.create_execution_node(+ next_node_id,+ iteration_mapping,+ iteration_path,+ iteration_axes=group_axes,+ )+ )+ else:+ iteration_mapping_groups = self._get_collect_iteration_mapping_groups(collect_inputs)+ for group_axes, iteration_path, iteration_mappings in iteration_mapping_groups:+ create_results = self.create_execution_node(+ next_node_id, iteration_mappings, iteration_path, iteration_axes=group_axes+ )+ new_node_ids.extend(create_results)elif isinstance(next_node, IfInvocation):condition_paths = graph_if_runtime._get_if_iteration_paths_with_ancestry(self._state,@@ -2483,30 +3912,143 @@ class _ExecutionNodeBuilder:if condition_edges:iteration_mappings = list(self._get_if_condition_iteration_mappings(next_node_id, g))if condition_paths:- for iteration_path in condition_paths:- matching_mappings = [- iteration_mapping- for iteration_mapping in iteration_mappings- if (- (- condition_path := self._get_known_iteration_path(- -1, iteration_mapping, condition_edges- )- or ()- )[: len(iteration_path)]- == iteration_path- or iteration_path[: len(condition_path or ())] == (condition_path or ())+ condition_axes = tuple(+ self._get_ordered_iterator_axes_for_edges(condition_edges, self.iterator_graph(g))+ )+ branch_edges = [+ edge+ for branch in ("true_input", "false_input")+ for edge in self._state.graph._get_input_edges(next_node_id, branch)+ ]+ branch_axes = [+ tuple(self._get_collect_source_iterator_ids(edge.source.node_id)) for edge in branch_edges+ ]+ condition_frames_are_exact = (+ bool(condition_axes)+ and any(axes == condition_axes for axes in branch_axes)+ and all(not axes or axes == condition_axes for axes in branch_axes)+ )+ if condition_frames_are_exact:+ for iteration_mapping in iteration_mappings:+ condition_exec_id = dict(iteration_mapping).get(condition_edges[0].source.node_id)+ if condition_exec_id is None:+ continue+ condition_path = self._get_prepared_edge_iteration_path(+ condition_edges[0], condition_exec_id+ )+ axes = self._state._prepared_registry().get_iteration_axes(condition_exec_id)+ if axes is None:+ axes = self._get_prepared_edge_iteration_axes(condition_edges[0], condition_exec_id)+ new_node_ids.extend(+ self.create_execution_node(+ next_node_id,+ iteration_mapping,+ condition_path,+ input_fields={"condition"},+ iteration_axes=axes,+ ))- ]- for iteration_mapping in matching_mappings:- create_results = self.create_execution_node(- next_node_id,- iteration_mapping,- iteration_path,- input_fields={"condition"},+ else:+ root_frame_counts_by_field: dict[+ str,+ tuple[+ dict[tuple[int, ...], int],+ Optional[_ProjectedRootIfFrames],+ ],+ ] = {}+ if not condition_axes:+ for iteration_mapping in iteration_mappings:+ condition_exec_id = dict(iteration_mapping).get(condition_edges[0].source.node_id)+ if condition_exec_id not in self._state.results:+ continue+ selected_field = (+ "true_input"+ if getattr(self._state.results[condition_exec_id], condition_edges[0].source.field)+ else "false_input"+ )+ if selected_field not in root_frame_counts_by_field:+ root_frame_counts_by_field[selected_field] = (+ self._get_root_if_projected_sibling_frame_counts(+ next_node_id,+ selected_field,+ self.iterator_graph(g),+ iterator_ancestry,+ condition_paths,+ )+ )+ for iteration_path in condition_paths:+ matching_mappings = [+ iteration_mapping+ for iteration_mapping in iteration_mappings+ if (+ (+ condition_path := self._get_known_iteration_path(+ -1, iteration_mapping, condition_edges+ )+ or ()+ )[: len(iteration_path)]+ == iteration_path+ or iteration_path[: len(condition_path or ())] == (condition_path or ())+ )+ ]+ condition_exec_ids = self._state.source_prepared_mapping.get(+ condition_edges[0].source.node_id, ())- new_node_ids.extend(create_results)- elif not self.get_node_iterators(next_node_id):+ condition_exec_id = next(iter(condition_exec_ids), None)+ has_unresolved_nested_if = False+ if condition_exec_id in self._state.results:+ selected_field = (+ "true_input"+ if getattr(self._state.results[condition_exec_id], condition_edges[0].source.field)+ else "false_input"+ )+ has_unresolved_nested_if = any(+ isinstance(self._state.graph.get_node(edge.source.node_id), IfInvocation)+ and self._state.graph._get_input_edges(edge.source.node_id, "condition")+ and not self._state.source_prepared_mapping.get(edge.source.node_id)+ for edge in self._state.graph._get_input_edges(next_node_id, selected_field)+ )+ if not matching_mappings and not iteration_path and not has_unresolved_nested_if:+ matching_mappings = list(+ self._get_parent_iteration_mappings(+ next_node_id, g, input_edges=condition_edges, iterator_node_ids=[]+ )+ )+ for iteration_mapping in matching_mappings:+ condition_exec_id = dict(iteration_mapping).get(condition_edges[0].source.node_id)+ selected_field = (+ "true_input"+ if condition_exec_id in self._state.results+ and getattr(self._state.results[condition_exec_id], condition_edges[0].source.field)+ else "false_input"+ )+ frame_counts, projected_frames = root_frame_counts_by_field.get(+ selected_field, ({}, None)+ )+ if projected_frames is None:+ for _ in range(frame_counts.get(iteration_path, 1)):+ create_results = self.create_execution_node(+ next_node_id,+ iteration_mapping,+ iteration_path,+ input_fields={"condition"},+ )+ new_node_ids.extend(create_results)+ else:+ for frame_path, frame_axes in projected_frames[iteration_path]:+ create_results = self.create_execution_node(+ next_node_id,+ iteration_mapping,+ frame_path,+ input_fields={"condition"},+ iteration_axes=frame_axes,+ )+ new_node_ids.extend(create_results)+ elif not self.get_node_iterators(+ next_node_id+ ) and not graph_if_runtime._has_empty_selected_for_final_frame(+ self._state, iterator_ancestry, next_node_id+ ):# Root-frame If nodes may be prepared from their condition while branch sources# are still being materialized; branch inputs attach after the gate resolves.for iteration_mapping in iteration_mappings:@@ -2517,9 +4059,70 @@ class _ExecutionNodeBuilder:)new_node_ids.extend(create_results)else:- for iteration_path in condition_paths:- create_results = self.create_execution_node(next_node_id, [], iteration_path)+ selected_field = "true_input" if next_node.condition else "false_input"+ selected_edges = self._state.graph._get_input_edges(next_node_id, selected_field)+ selected_empty_nested = bool(selected_edges) and all(+ isinstance(self._state.graph.get_node(edge.source.node_id), IfInvocation)+ and edge.source.node_id in self._state.executed+ and not self._state.source_prepared_mapping.get(edge.source.node_id)+ for edge in selected_edges+ )+ if selected_empty_nested:+ create_results = self.create_execution_node(next_node_id, [], ())new_node_ids.extend(create_results)+ else:+ frame_iterators = tuple(iterator_ancestry.get_frame_iterators(next_node_id))+ reiterated_axes = graph_if_runtime._get_sibling_collect_iterate_axes_to_project(+ self._state, iterator_ancestry, frame_iterators+ )+ prepared_path_axes: dict[tuple[int, ...], tuple[str, ...]] = {}+ if reiterated_axes:+ frame_axes = tuple(axis_id for axis_id in frame_iterators if axis_id not in reiterated_axes)+ else:+ selected_edges = self._state.graph._get_input_edges(next_node_id, selected_field)+ frame_axes = tuple(+ self._get_ordered_iterator_axes_for_edges(selected_edges, self.iterator_graph(g))+ )+ prepared_frames: list[tuple[tuple[int, ...], tuple[str, ...]]] = []+ for edge in selected_edges:+ for prepared_id in self._get_prepared_nodes_for_source(edge.source.node_id):+ prepared_frames.append(+ (+ self._get_prepared_edge_iteration_path(edge, prepared_id),+ self._get_prepared_edge_iteration_axes(edge, prepared_id),+ )+ )+ projected_paths = graph_if_runtime._project_prepared_iteration_paths(prepared_frames, set())+ if projected_paths is not None:+ condition_path_set = set(condition_paths)+ for path, axes in prepared_frames:+ if path in condition_path_set:+ prepared_path_axes.setdefault(path, axes)+ root_frame_counts, projected_frames = self._get_root_if_projected_sibling_frame_counts(+ next_node_id, selected_field, iterator_graph, iterator_ancestry, condition_paths+ )+ for iteration_path in condition_paths:+ iteration_axes = prepared_path_axes.get(iteration_path)+ if iteration_axes is None and len(frame_axes) >= len(iteration_path):+ iteration_axes = frame_axes[: len(iteration_path)]+ if projected_frames is None:+ for _ in range(root_frame_counts[iteration_path]):+ create_results = self.create_execution_node(+ next_node_id,+ [],+ iteration_path,+ iteration_axes=iteration_axes,+ )+ new_node_ids.extend(create_results)+ else:+ for frame_path, frame_axes in projected_frames[iteration_path]:+ create_results = self.create_execution_node(+ next_node_id,+ [],+ frame_path,+ iteration_axes=frame_axes,+ )+ new_node_ids.extend(create_results)else:parent_iterator_nodes = self.get_node_iterators(next_node_id)iteration_mappings_iter = (diff --git a/invokeai/app/services/shared/graph_runtime_records.py b/invokeai/app/services/shared/graph_runtime_records.pyindex e2739b50de..e549b801dd 100644--- a/invokeai/app/services/shared/graph_runtime_records.py+++ b/invokeai/app/services/shared/graph_runtime_records.py@@ -1,6 +1,6 @@import sysfrom dataclasses import dataclass-from typing import TYPE_CHECKING, Any, Callable, Optional+from typing import TYPE_CHECKING, Any, Callable, Iterable, Optionalfrom invokeai.app.services.shared.graph_models import PreparedExecState@@ -38,6 +38,7 @@ class _PreparedExecNodeMetadata:source_node_id: striteration_path: Optional[tuple[int, ...]] = None+ iteration_axes: Optional[tuple[str, ...]] = Nonestate: PreparedExecState = "pending"@@ -58,26 +59,77 @@ class _PreparedExecRegistry:metadata: dict[str, _PreparedExecNodeMetadata],on_iteration_path_change: Callable[[str], None] | None = None,state: Optional["GraphExecutionState"] = None,+ prepared_iteration_axes: Optional[dict[str, tuple[str, ...]]] = None,) -> None:self._prepared_source_mapping = prepared_source_mappingself._source_prepared_mapping = source_prepared_mappingself._prepared_iteration_paths = prepared_iteration_paths+ self._prepared_iteration_axes = prepared_iteration_axes if prepared_iteration_axes is not None else {}self._metadata = metadataself._on_iteration_path_change = on_iteration_path_changeself._state = state- self._prepared_ids_by_source_and_path: dict[str, dict[tuple[int, ...], set[str]]] = {}-- def _invalidate_source_path_index(self, source_node_id: str) -> None:- previous = self._prepared_ids_by_source_and_path.pop(source_node_id, None)- if self._state is not None and self._state._apply_transaction is not None:- self._state._tx_record_once(- ("prepared_path_index", id(self), source_node_id),- lambda: (- self._prepared_ids_by_source_and_path.__setitem__(source_node_id, previous)- if previous is not None- else self._prepared_ids_by_source_and_path.pop(source_node_id, None)- ),- )+ self._prepared_ids_by_source_and_path: dict[+ str, tuple[dict[tuple[int, ...], set[str]], dict[tuple[int, ...], set[str]]]+ ] = {}++ def _record_index_undo(self, undo: Callable[[], None]) -> None:+ if self._state is not None:+ self._state._tx_record(undo)++ @staticmethod+ def _change_path_index(+ index: tuple[dict[tuple[int, ...], set[str]], dict[tuple[int, ...], set[str]]],+ exec_node_id: str,+ iteration_path: tuple[int, ...],+ add: bool,+ ) -> None:+ ids_by_path, ids_by_prefix = index+ if add:+ ids_by_path.setdefault(iteration_path, set()).add(exec_node_id)+ for prefix_length in range(len(iteration_path) + 1):+ ids_by_prefix.setdefault(iteration_path[:prefix_length], set()).add(exec_node_id)+ return+ path_ids = ids_by_path.get(iteration_path)+ if path_ids is not None:+ path_ids.discard(exec_node_id)+ if not path_ids:+ del ids_by_path[iteration_path]+ for prefix_length in range(len(iteration_path) + 1):+ prefix = iteration_path[:prefix_length]+ prefix_ids = ids_by_prefix.get(prefix)+ if prefix_ids is not None:+ prefix_ids.discard(exec_node_id)+ if not prefix_ids:+ del ids_by_prefix[prefix]++ def _get_source_path_index(+ self, source_node_id: str+ ) -> tuple[dict[tuple[int, ...], set[str]], dict[tuple[int, ...], set[str]]]:+ index = self._prepared_ids_by_source_and_path.get(source_node_id)+ if index is None:+ ids_by_path: dict[tuple[int, ...], set[str]] = {}+ ids_by_prefix: dict[tuple[int, ...], set[str]] = {}+ index = (ids_by_path, ids_by_prefix)+ self._prepared_ids_by_source_and_path[source_node_id] = index+ if self._state is not None:+ self._state._tx_record_once(+ ("prepared_path_index", id(self), source_node_id),+ lambda: self._prepared_ids_by_source_and_path.pop(source_node_id, None),+ )+ for exec_node_id in self.get_prepared_ids(source_node_id):+ path = self.get_iteration_path(exec_node_id)+ if path is not None:+ self._change_path_index(index, exec_node_id, path, True)+ return index++ def _update_source_path_index(+ self, source_node_id: str, exec_node_id: str, iteration_path: tuple[int, ...], add: bool+ ) -> None:+ index = self._prepared_ids_by_source_and_path.get(source_node_id)+ if index is None:+ return+ self._change_path_index(index, exec_node_id, iteration_path, add)+ self._record_index_undo(lambda: self._change_path_index(index, exec_node_id, iteration_path, not add))def _set_mapping(self, mapping: dict[Any, Any], key: Any, value: Any) -> None:if self._state is not None:@@ -98,9 +150,13 @@ class _PreparedExecRegistry:setattr(obj, name, value)def register(self, exec_node_id: str, source_node_id: str) -> None:- self._invalidate_source_path_index(source_node_id)+ previous_source = self._prepared_source_mapping.get(exec_node_id)+ previous_path = self.get_iteration_path(exec_node_id)+ if previous_source is not None and previous_path is not None:+ self._update_source_path_index(previous_source, exec_node_id, previous_path, False)self._set_mapping(self._prepared_source_mapping, exec_node_id, source_node_id)self._pop_mapping(self._prepared_iteration_paths, exec_node_id)+ self._pop_mapping(self._prepared_iteration_axes, exec_node_id)self._set_mapping(self._metadata, exec_node_id, _new_prepared_exec_node_metadata(source_node_id))if source_node_id not in self._source_prepared_mapping:self._set_mapping(self._source_prepared_mapping, source_node_id, set())@@ -127,24 +183,27 @@ class _PreparedExecRegistry:def get_prepared_id_at_path(self, source_node_id: str, iteration_path: tuple[int, ...]) -> str | None:"""Return the only prepared execution for a source/path without rescanning siblings."""- paths = self._prepared_ids_by_source_and_path.get(source_node_id)- if paths is None:- paths = {}- for exec_node_id in self.get_prepared_ids(source_node_id):- path = self.get_iteration_path(exec_node_id)- if path is not None:- paths.setdefault(path, set()).add(exec_node_id)- self._prepared_ids_by_source_and_path[source_node_id] = paths- if self._state is not None and self._state._apply_transaction is not None:- self._state._tx_record_once(- ("prepared_path_index", id(self), source_node_id),- lambda: self._prepared_ids_by_source_and_path.pop(source_node_id, None),- )+ paths, _ = self._get_source_path_index(source_node_id)matches = paths.get(iteration_path, set())if len(matches) > 1:raise RuntimeError(f"Multiple prepared nested nodes exist for {source_node_id} at {iteration_path}")return next(iter(matches), None)+ def get_prepared_ids_with_overlapping_path(+ self, source_node_id: str, iteration_path: tuple[int, ...]+ ) -> Iterable[str]:+ """Yield prepared IDs whose paths are ancestors or descendants of ``iteration_path``."""+ ids_by_path, ids_by_prefix = self._get_source_path_index(source_node_id)+ seen: set[str] = set()+ for prefix_length in range(len(iteration_path) + 1):+ for exec_node_id in ids_by_path.get(iteration_path[:prefix_length], ()):+ if exec_node_id not in seen:+ seen.add(exec_node_id)+ yield exec_node_id+ for exec_node_id in ids_by_prefix.get(iteration_path, ()):+ if exec_node_id not in seen:+ yield exec_node_id+def set_state(self, exec_node_id: str, state: PreparedExecState) -> None:self._set_attr(self.get_metadata(exec_node_id), "state", state)@@ -158,8 +217,25 @@ class _PreparedExecRegistry:return iteration_pathdef set_iteration_path(self, exec_node_id: str, iteration_path: tuple[int, ...]) -> None:- self._invalidate_source_path_index(self.get_source_node_id(exec_node_id))+ source_node_id = self.get_source_node_id(exec_node_id)+ previous_path = self.get_iteration_path(exec_node_id)+ if previous_path is not None:+ self._update_source_path_index(source_node_id, exec_node_id, previous_path, False)self._set_mapping(self._prepared_iteration_paths, exec_node_id, iteration_path)self._set_attr(self.get_metadata(exec_node_id), "iteration_path", iteration_path)+ self._update_source_path_index(source_node_id, exec_node_id, iteration_path, True)if self._on_iteration_path_change is not None:self._on_iteration_path_change(exec_node_id)++ def get_iteration_axes(self, exec_node_id: str) -> Optional[tuple[str, ...]]:+ metadata = self._metadata.get(exec_node_id)+ if metadata is not None and metadata.iteration_axes is not None:+ return metadata.iteration_axes+ iteration_axes = self._prepared_iteration_axes.get(exec_node_id)+ if iteration_axes is not None:+ self._set_attr(self.get_metadata(exec_node_id), "iteration_axes", iteration_axes)+ return iteration_axes++ def set_iteration_axes(self, exec_node_id: str, iteration_axes: tuple[str, ...]) -> None:+ self._set_mapping(self._prepared_iteration_axes, exec_node_id, iteration_axes)+ self._set_attr(self.get_metadata(exec_node_id), "iteration_axes", iteration_axes)diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex e339645c55..8ccab66993 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -49413,6 +49413,17 @@"title": "Prepared Iteration Paths","description": "The iteration coordinates of each prepared execution node"},+ "prepared_iteration_axes": {+ "additionalProperties": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "type": "object",+ "title": "Prepared Iteration Axes",+ "description": "The named iteration axes of each prepared execution node"+ },"ready_order": {"items": {"type": "string"diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex dac5f08cc5..80ad813fe6 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -19397,6 +19397,13 @@ export type components = {prepared_iteration_paths?: {[key: string]: number[];};+ /**+ * Prepared Iteration Axes+ * @description The named iteration axes of each prepared execution node+ */+ prepared_iteration_axes?: {+ [key: string]: string[];+ };/** Ready Order */ready_order?: string[];/**diff --git a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.jsonindex 1eac063e72..f2e790544f 100644--- a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json+++ b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json@@ -47,7 +47,7 @@{"s":"users-guide/workflows/face-tools","t":"Face Tools Nodes","c":1,"h":[["faceidentifier","FaceIdentifier"],["inputs","Inputs"],["outputs","Outputs"],["facemask","FaceMask"],["inputs-1","Inputs"],["outputs-1","Outputs"],["faceoff","FaceOff"],["inputs-2","Inputs"],["outputs-2","Outputs"],["tips","Tips"]]},{"s":"users-guide/workflows/image-adjustments","t":"Image Detail and Contrast Nodes","d":"Use Clarity, Texture, and Contrast Dehaze in workflows, with their controls and image-format limits.","c":1,"h":[["choose-a-node","Choose a node"],["image-formats-and-alpha","Image formats and alpha"],["contrast-dehaze-limits","Contrast Dehaze limits"]]},{"s":"users-guide/workflows/introduction","t":"Automating with Workflows","d":"Why and when to use workflows, how nodes and connections work, a tour of the workflow editor, and a walkthrough that generates a subject with SDXL, composites it onto a background, and builds a simple form for it.","c":1,"h":[["nodes-and-connections","Nodes and connections"],["a-tour-of-the-workflow-editor","A tour of the workflow editor"],["the-essentials","The essentials"],["walkthrough-put-a-generated-subject-on-a-background","Walkthrough: put a generated subject on a background"],["1-start-from-the-sdxl-text-to-image-workflow","1. Start from the SDXL text-to-image workflow"],["2-add-the-image-compositor","2. Add the Image Compositor"],["3-run-it","3. Run it"],["4-build-a-form-for-the-workflow","4. Build a form for the workflow"],["5-save-and-share-it","5. Save and share it"],["learn-more","Learn more"]]},-{"s":"users-guide/workflows/loop-nodes","t":"Loop Nodes","d":"Repeat workflow steps over a collection and optionally carry values from one iteration to the next.","c":1,"h":[["the-basic-pattern","The Basic Pattern"],["a-simple-example","A Simple Example"],["what-the-for-outputs-mean","What The For Outputs Mean"],["returning-results","Returning Results"],["carrying-values-with-state","Carrying Values With State"],["making-collections-for-a-loop","Making Collections For A Loop"],["range-nodes","Range Nodes"],["combining-collections","Combining Collections"],["for-and-iterate","For And Iterate"],["nested-for-loops","Nested For Loops"],["empty-collections-and-early-stop","Empty Collections And Early Stop"],["collection-type-checks","Collection Type Checks"],["common-wiring-mistakes","Common Wiring Mistakes"]]},+{"s":"users-guide/workflows/loop-nodes","t":"Loop Nodes","d":"Repeat workflow steps over a collection and optionally carry values from one iteration to the next.","c":1,"h":[["the-basic-pattern","The Basic Pattern"],["a-simple-example","A Simple Example"],["what-the-for-outputs-mean","What The For Outputs Mean"],["returning-results","Returning Results"],["carrying-values-with-state","Carrying Values With State"],["making-collections-for-a-loop","Making Collections For A Loop"],["range-nodes","Range Nodes"],["combining-collections","Combining Collections"],["for-and-iterate","For And Iterate"],["nested-for-loops","Nested For Loops"],["empty-collections-and-early-stop","Empty Collections And Early Stop"],["if-branch-execution","If Branch Execution"],["collection-type-checks","Collection Type Checks"],["common-wiring-mistakes","Common Wiring Mistakes"]]},{"s":"users-guide/models/external-models/alibabacloud","t":"Alibaba Cloud DashScope","c":2,"h":[["getting-an-api-key","Getting an API Key"],["configuration","Configuration"],["available-models","Available Models"],["tips","Tips"]]},{"s":"users-guide/models/external-models/gemini","t":"Google Gemini","c":2,"h":[["getting-an-api-key","Getting an API Key"],["configuration","Configuration"],["available-models","Available Models"],["provider-specific-options","Provider-Specific Options"],["canvas","Canvas"],["tips","Tips"]]},{"s":"users-guide/models/external-models/introduction","t":"Using external models","c":2,"h":[["supported-providers","Supported Providers"],["configuring-api-keys","Configuring API Keys"],["installing-external-models","Installing External Models"],["capabilities-and-settings-visibility","Capabilities and Settings Visibility"],["costs-and-rate-limits","Costs and Rate Limits"]]},diff --git a/pyproject.toml b/pyproject.tomlindex 9cd288e776..20fc565867 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -639,9 +639,10 @@ version = { attr = "invokeai.version.__version__" }# fixtures are set up once per file instead of in every worker that received part of it.# It is not isolation: a worker process runs many files, in an order that depends on the# worker count and on which file finished first, so a file must still set up its own-# process-global state. It costs nothing -- per-test distribution measured the same wall-# clock on the full suite -- and it lives here rather than in the CI command so that it-# also holds when `-n` is passed by hand. Coverage is opt-in via `--cov`.+# process-global state. For maximum local parallelism, pass `-n <cpus> --dist load`;+# this overrides `loadfile` and can split a single file across workers, repeating+# module-scoped fixture setup. This config default also applies when `-n` is passed by hand.+# Coverage is opt-in via `--cov`.addopts = "--strict-markers --dist loadfile -m \"not slow\""markers = ["slow: Marks tests as slow. Disabled by default. To run all tests, use -m \"\". To run only slow tests, use -m \"slow\".",diff --git a/tests/AGENTS.md b/tests/AGENTS.mdindex 99627c6273..fac5fe63b6 100644--- a/tests/AGENTS.md+++ b/tests/AGENTS.md@@ -7,6 +7,7 @@- Cover affected rollback, revisions, cross-user isolation, retries, cancellation, bounds, cleanup. IndexedDB, Web Locks, focus, rendering belong in webv2 browser tests.- Use root pytest commands. CI runs one xdist worker per vCPU; windows-ffmpeg runs two. `--dist loadfile` in `addopts` keeps each file on one worker; file assignment and order are arbitrary. Each file sets up its own process-global state (e.g. JWT secret) and passes alone. Verify new files on their own.- Full CI: `uv run --no-sync pytest -n logical`, which fits CI runners that own the machine. Dev box: cap workers (`-n 4`, or plain `pytest`). Set `OMP_NUM_THREADS` when a run must stay light.+- For maximum local parallelism, use `-n <cpus> --dist load` (replace `<cpus>` with the desired worker count, e.g. `-n 8`). This overrides the configured `loadfile` mode and can distribute tests from one file across workers; module-scoped fixtures may be set up once per worker.- `uv run --no-sync mypy scripts/invokeai-web.py` uses current exclusions. Optional diagnostic only: not a CI gate, not full type coverage.- Default tests assert behavior, not throughput or latency under runner contention. Generous hang ceilings fine. CPU time tolerates contention better than wall time. Hardware or quiet-machine measurements: mark `slow` (excluded by default and in CI). Dev machines: `-m slow` for that lane, `-m ""` for everything.- Keep a test's run time to the work it checks: idle seconds add up, and windows-ffmpeg runs the ffmpeg tests on two workers. Check new files with `--durations=10` (splits setup, call, teardown).diff --git a/tests/app/services/session_processor/test_if_processor_sqlite.py b/tests/app/services/session_processor/test_if_processor_sqlite.pyindex 8353409530..841290a310 100644--- a/tests/app/services/session_processor/test_if_processor_sqlite.py+++ b/tests/app/services/session_processor/test_if_processor_sqlite.py@@ -1,4 +1,5 @@import asyncio+import jsonimport uuidfrom contextlib import contextmanagerfrom threading import Condition, Event@@ -19,6 +20,7 @@ from invokeai.app.services.session_processor.session_processor_default import ()from invokeai.app.services.session_queue.session_queue_default import SessionQueuefrom invokeai.app.services.shared.database.database import Database+from invokeai.app.services.shared.execution_state_migration import dump_execution_statefrom invokeai.app.services.shared.graph import Graph, GraphExecutionStatefrom tests.fixtures.sqlite_database import sqlite_cursor_offrom tests.test_nodes import create_edge@@ -89,7 +91,7 @@ def _insert_session(queue: SessionQueue, graph: Graph) -> int:""",("default",- session.model_dump_json(warnings=False, exclude_none=True),+ json.dumps(dump_execution_state(session)),session.id,str(uuid.uuid4()),None,@@ -185,15 +187,18 @@ def test_if_cancellation_preserves_activation_and_never_resumes_unselected_branc)try:processor.start(mock_invoker)- assert registered_event_bus.wait_for_status(item_id, "canceled", timeout=_PROCESSOR_TIMEOUT)+ assert registered_event_bus.wait_for_status(item_id, "canceled", timeout=_PROCESSOR_TIMEOUT), completed_sourcesassert session_persisted.wait(timeout=_PROCESSOR_TIMEOUT)queue_item = queue.get_queue_item(item_id)assert queue_item.status == "canceled"assert queue.get_current("default") is None- assert completed_sources == ["condition", selected_branch, "if"]- assert _completed_source_ids(queue_item.session) == completed_sources+ assert set(completed_sources) == {"condition", selected_branch, "if"}+ if_index = completed_sources.index("if")+ assert completed_sources.index("condition") < if_index+ assert completed_sources.index(selected_branch) < if_indexassert unselected_branch not in completed_sources+ assert _completed_source_ids(queue_item.session) == completed_sourcesassert "sink" not in completed_sourcesassert not queue_item.session.is_complete()_assert_if_activation_token(queue_item.session, expected_field=selected_field)@@ -277,7 +282,10 @@ def test_if_retry_starts_fresh_and_preserves_selected_output_without_stale_activassert completed_item.status == "completed"assert completed_item.session.is_complete()completed_sources = _completed_source_ids(completed_item.session)- assert completed_sources == ["condition", selected_branch, "if", "sink"]+ assert set(completed_sources) == {"condition", selected_branch, "if", "sink"}+ if_index = completed_sources.index("if")+ assert completed_sources.index("condition") < if_index+ assert completed_sources.index(selected_branch) < if_indexassert unselected_branch not in completed_sources[sink_execution_id] = completed_item.session.source_prepared_mapping["sink"]assert completed_item.session.results[sink_execution_id].value == sink_value@@ -333,9 +341,11 @@ def test_if_early_cancellation_before_resolution_does_not_run_any_branch_continucanceled_item = queue.get_queue_item(item_id)assert canceled_item.status == "canceled"assert queue.get_current("default") is None- assert completed_sources == ["condition", selected_branch]- assert _completed_source_ids(canceled_item.session) == completed_sources+ assert completed_sources[0] == "condition"+ assert completed_sources[-1] == selected_branchassert unselected_branch not in completed_sources+ assert _completed_source_ids(canceled_item.session) == completed_sources+ assert selected_branch in completed_sourcesassert "if" not in completed_sourcesassert "sink" not in completed_sourcesassert "if" not in _completed_source_ids(canceled_item.session)diff --git a/tests/app/services/shared/test_collect_frame_regressions.py b/tests/app/services/shared/test_collect_frame_regressions.pynew file mode 100644index 0000000000..25cbce517e--- /dev/null+++ b/tests/app/services/shared/test_collect_frame_regressions.py@@ -0,0 +1,2124 @@+"""Collect grouping must follow the iteration frame of its inputs, whatever depth or wrapper each input arrives through.++Each Collect execution is read separately: several executions at one iteration path is itself the failure, and a dict+keyed by path would hide it. Order across different sources in one Collect is unspecified, so items are compared sorted.+"""++import json+import re+from collections.abc import Callable+from typing import Any as AnyValue+from unittest.mock import Mock++import pytest++from invokeai.app.invocations.baseinvocation import BaseInvocation+from invokeai.app.invocations.collections import CollectionConcatInvocation as Concat+from invokeai.app.invocations.logic import IfInvocation as If+from invokeai.app.invocations.loops import ForInvocation as For+from invokeai.app.invocations.loops import ForReturnInvocation as ForReturn+from invokeai.app.invocations.primitives import BooleanInvocation+from invokeai.app.services.shared import graph_if_runtime+from invokeai.app.services.shared.execution_state_migration import dump_execution_state, load_execution_state+from invokeai.app.services.shared.graph import CollectInvocation as Collect+from invokeai.app.services.shared.graph import (+ Graph,+ GraphExecutionState,+ _ExecutionScheduler,+ _GenericGraphSchedulerAdapter,+)+from invokeai.app.services.shared.graph import IterateInvocation as Iterate+from invokeai.app.services.shared.graph_if_runtime import (+ _get_sibling_collect_iterate_axes_to_project,+ _is_sibling_collect_iterate_axis,+ _project_prepared_iteration_paths,+)+from invokeai.app.services.shared.graph_iterator_ancestry import _IteratorAncestry+from invokeai.app.services.shared.graph_materializer import _ExecutionMaterializer+from tests.test_nodes import AnyTypeTestInvocation as Value+from tests.test_nodes import FixedCollectionTestInvocation as Truthy+from tests.test_nodes import MarkedAnyTypeTestInvocation as Marked+from tests.test_nodes import create_edge, create_loop_linkage++pytestmark = pytest.mark.platform_independent++Runs = list[tuple[tuple[int, ...], list[AnyValue]]]++[email protected](params=[False, True], ids=["generic-adapter", "compatibility-scheduler"])+def compatibility_scheduler(request: pytest.FixtureRequest) -> bool:+ return request.param+++def _graph(src: list[AnyValue], levels: int, nodes: list[BaseInvocation], edges: str) -> Graph:+ """Build `src -> it0 -> cc0 -> it1 -> ... -> it{levels - 1}` plus `nodes` and "a.field -> b.field" `edges` lines."""+ graph = Graph()+ spine: list[BaseInvocation] = [Concat(id="src", first=src), Iterate(id="it0")]+ links = ["src.collection -> it0.collection"]+ for level in range(1, levels):+ spine += [Concat(id=f"cc{level - 1}"), Iterate(id=f"it{level}")]+ links += [f"it{level - 1}.item -> cc{level - 1}.first", f"cc{level - 1}.collection -> it{level}.collection"]+ for node in spine + nodes:+ graph.add_node(node)+ # Edges out of a Collect validate against its `item` inputs, so those go in first.+ parsed = [re.split(r"\s*->\s*|\.", line.strip()) for line in links + edges.splitlines() if line.strip()]+ for source, source_field, target, target_field in sorted(parsed, key=lambda edge: edge[3] != "item"):+ if source_field == "loop_linkage":+ graph.add_edge(create_loop_linkage(source, target))+ else:+ graph.add_edge(create_edge(source, source_field, target, target_field))+ graph.validate_self()+ return graph+++def _sorted_items(items: list[AnyValue]) -> list[AnyValue]:+ return sorted(items, key=repr)+++def _collect_runs(graph: Graph, compatibility: bool, *sinks: str) -> dict[str, Runs]:+ """Execute `graph` to completion and return each sink's executions, normalized."""+ state = GraphExecutionState(graph=graph)+ state._execution_scheduler = _ExecutionScheduler(state) if compatibility else _GenericGraphSchedulerAdapter(state)+ expected_scheduler = _ExecutionScheduler if compatibility else _GenericGraphSchedulerAdapter+ assert isinstance(state._execution_scheduler, expected_scheduler)+ for _ in range(5000):+ node = state.next()+ if node is None:+ break+ state.complete(node.id, node.invoke(Mock()))+ assert state.is_complete() and not state.has_error()+ return {+ name: _sorted_runs(+ [+ (state._get_iteration_path(execution), state.results[execution].collection)+ for execution in state._prepared_registry().get_prepared_ids(name)+ if execution in state.results+ ]+ )+ for name in sinks or ("out",)+ }+++def _sorted_runs(runs: Runs) -> Runs:+ return sorted(((path, _sorted_items(items)) for path, items in runs), key=repr)+++def test_plain_iterate_collect_prepared_path_lookups_are_bounded(monkeypatch: pytest.MonkeyPatch) -> None:+ graph = Graph()+ graph.add_node(Concat(id="src", first=list(range(1000))))+ graph.add_node(Iterate(id="it0"))+ graph.add_node(Collect(id="out"))+ graph.add_edge(create_edge("src", "collection", "it0", "collection"))+ graph.add_edge(create_edge("it0", "item", "out", "item"))+ graph.validate_self()+ path_lookups = 0+ get_path = _ExecutionMaterializer._get_prepared_edge_iteration_path++ def counted_get_path(self: _ExecutionMaterializer, edge: AnyValue, prepared_id: str) -> tuple[int, ...]:+ nonlocal path_lookups+ path_lookups += 1+ return get_path(self, edge, prepared_id)++ monkeypatch.setattr(_ExecutionMaterializer, "_get_prepared_edge_iteration_path", counted_get_path)+ state = GraphExecutionState(graph=graph)+ for _ in range(5000):+ node = state.next()+ if node is None:+ break+ state.complete(node.id, node.invoke(Mock()))++ assert state.is_complete() and not state.has_error()+ assert path_lookups <= 9_000+++# Flaw: collapsing an all-empty frame must keep the parent frames, not index past the known iterator axes.+ "src, levels, expected",+ [+ pytest.param([[[], []]], 3, [((0, 0), []), ((0, 1), [])], id="one-outer-two-empty"),+ pytest.param([[[]], [[]]], 3, [((0, 0), []), ((1, 0), [])], id="two-outer-one-empty-each"),+ pytest.param([[], [[]]], 3, [((0,), []), ((1, 0), [])], id="empty-at-two-depths"),+ pytest.param([[[[], []]]], 4, [((0, 0, 0), []), ((0, 0, 1), [])], id="one-level-deeper"),+ ],+)+def test_all_empty_frames_produce_one_empty_run_per_frame(+ compatibility_scheduler: bool, src: list[AnyValue], levels: int, expected: Runs+) -> None:+ graph = _graph(+ src,+ levels,+ [+ Marked(id="m", marker="m"),+ Collect(id="col"),+ Iterate(id="rit"),+ Marked(id="rm", marker="r"),+ Collect(id="out"),+ ],+ f"""+ it{levels - 1}.item -> m.value+ m.value -> col.item+ col.collection -> rit.collection+ rit.item -> rm.value+ rm.value -> out.item+ """,+ )++ assert _collect_runs(graph, compatibility_scheduler)["out"] == _sorted_runs(expected)+++_MIXED_DEPTH_SRC = [[[["c", "a"]], [["c"]]], [[["b"], ["a"]]], []]+_SHALLOW_COLLECT_RUNS = [+ ((0,), ["T:[\"x[['c', 'a']]\", \"x[['c']]\"]", "S:[\"x['c', 'a']\"]", "S:[\"x['c']\"]"]),+ ((1,), ["T:[\"x[['b'], ['a']]\"]", "S:[\"x['b']\", \"x['a']\"]"]),+ ((2,), ["T:[]", "S:[]"]),+]+++def _mixed_depth(shallow_nodes: list[BaseInvocation], shallow_edges: str) -> Graph:+ """A shallow T input and a Collect-per-it1-frame S input join `out`; `shallow_edges` must reach out.item."""+ return _graph(+ _MIXED_DEPTH_SRC,+ 3,+ [+ *shallow_nodes,+ Marked(id="cm2", marker="x"),+ Collect(id="c2"),+ Marked(id="S", marker="S:"),+ Collect(id="out"),+ ],+ f"""+ {shallow_edges}+ it2.item -> cm2.value+ cm2.value -> c2.item+ c2.collection -> S.value+ S.value -> out.item+ """,+ )+++def _collected_shallow_input(literal_ifs: int) -> Graph:+ nodes: list[BaseInvocation] = [Marked(id="cm1", marker="x"), Collect(id="c1"), Marked(id="T", marker="T:")]+ edges = ["it1.item -> cm1.value", "cm1.value -> c1.item", "c1.collection -> T.value"]+ previous = "T"+ for index in range(literal_ifs):+ nodes.append(If(id=f"if{index}", condition=True))+ edges.append(f"{previous}.value -> if{index}.true_input")+ previous = f"if{index}"+ edges.append(f"{previous}.value -> out.item")+ return _mixed_depth(nodes, "\n".join(edges))+++def _iterated_shallow_input() -> Graph:+ return _mixed_depth([Marked(id="T", marker="T:")], "it0.item -> T.value\nT.value -> out.item")+++def _collects_through_literal_if() -> Graph: # fuzz-1259+ return _graph(+ [[[["c", "a", "c"]], [["c"]], [["c", ""], ["a", "b"]]], [[["", "b"], ["a", "a"]]], []],+ 3,+ [+ Marked(id="cm1", marker="x"),+ Collect(id="col2"),+ Marked(id="p3", marker="T:"),+ Marked(id="cm4", marker="x"),+ Collect(id="col5"),+ Marked(id="p6", marker="F:"),+ If(id="if", condition=True),+ Collect(id="out"),+ Marked(id="cm7", marker="x"),+ Collect(id="col8"),+ Marked(id="p9", marker="S:"),+ ],+ """+ cm1.value -> col2.item+ cm4.value -> col5.item+ if.value -> out.item+ cm7.value -> col8.item+ p9.value -> out.item+ it1.item -> cm1.value+ col2.collection -> p3.value+ it1.item -> cm4.value+ col5.collection -> p6.value+ p3.value -> if.true_input+ p6.value -> if.false_input+ it2.item -> cm7.value+ col8.collection -> p9.value+ """,+ )+++def _shallow_input_behind_two_literal_ifs_with_outer_collect() -> Graph: # fuzz-2338+ return _graph(+ [[[["b"], ["a", "", "b"]], [["b", "b", "b"], []], []], [[["c"], []], [["c"], ["b"]]]],+ 3,+ [+ Value(id="root2", value="aT:"),+ Marked(id="cm3", marker="x"),+ Collect(id="col4"),+ Marked(id="p5", marker="bT:"),+ If(id="iif1", condition=False),+ Marked(id="p6", marker="T:"),+ Marked(id="m7", marker="F:"),+ If(id="if", condition=False),+ Collect(id="out"),+ Marked(id="cm8", marker="x"),+ Collect(id="col9"),+ Marked(id="p10", marker="S:"),+ Collect(id="out2"),+ ],+ """+ cm3.value -> col4.item+ if.value -> out.item+ cm8.value -> col9.item+ p10.value -> out.item+ out.collection -> out2.item+ it2.item -> cm3.value+ col4.collection -> p5.value+ root2.value -> iif1.true_input+ p5.value -> iif1.false_input+ iif1.value -> p6.value+ it0.item -> m7.value+ p6.value -> if.true_input+ m7.value -> if.false_input+ it2.item -> cm8.value+ col9.collection -> p10.value+ """,+ )+++# Flaw: inputs reaching one Collect from different depths must still land in one run per shared outer frame.+ "build, expected",+ [+ pytest.param(lambda: _collected_shallow_input(0), {"out": _SHALLOW_COLLECT_RUNS}, id="shallow-collect"),+ pytest.param(lambda: _collected_shallow_input(1), {"out": _SHALLOW_COLLECT_RUNS}, id="shallow-collect-one-if"),+ pytest.param(lambda: _collected_shallow_input(2), {"out": _SHALLOW_COLLECT_RUNS}, id="shallow-collect-two-ifs"),+ pytest.param(+ _iterated_shallow_input,+ {+ "out": [+ ((0,), ["T:[[['c', 'a']], [['c']]]", "S:[\"x['c', 'a']\"]", "S:[\"x['c']\"]"]),+ ((1,), ["T:[[['b'], ['a']]]", "S:[\"x['b']\", \"x['a']\"]"]),+ ((2,), ["T:[]", "S:[]"]),+ ]+ },+ id="shallow-item",+ ),+ pytest.param(+ _collects_through_literal_if,+ {+ "out": [+ (+ (0,),+ [+ "T:[\"x[['c', 'a', 'c']]\", \"x[['c']]\", \"x[['c', ''], ['a', 'b']]\"]",+ "S:[\"x['c', 'a', 'c']\"]",+ "S:[\"x['c']\"]",+ "S:[\"x['c', '']\", \"x['a', 'b']\"]",+ ],+ ),+ ((1,), ["T:[\"x[['', 'b'], ['a', 'a']]\"]", "S:[\"x['', 'b']\", \"x['a', 'a']\"]"]),+ ((2,), ["T:[]", "S:[]"]),+ ]+ },+ id="fuzz-1259-collects-through-if",+ ),+ pytest.param(+ _shallow_input_behind_two_literal_ifs_with_outer_collect,+ {+ "out": [+ (+ (0,),+ [+ "F:[[['b'], ['a', '', 'b']], [['b', 'b', 'b'], []], []]",+ "S:[\"x['b']\", \"x['a', '', 'b']\"]",+ "S:[\"x['b', 'b', 'b']\", 'x[]']",+ "S:[]",+ ],+ ),+ ((1,), ["F:[[['c'], []], [['c'], ['b']]]", "S:[\"x['c']\", 'x[]']", "S:[\"x['c']\", \"x['b']\"]"]),+ ],+ "out2": [+ (+ (),+ [+ [+ "F:[[['b'], ['a', '', 'b']], [['b', 'b', 'b'], []], []]",+ "S:[\"x['b']\", \"x['a', '', 'b']\"]",+ "S:[\"x['b', 'b', 'b']\", 'x[]']",+ "S:[]",+ ],+ ["F:[[['c'], []], [['c'], ['b']]]", "S:[\"x['c']\", 'x[]']", "S:[\"x['c']\", \"x['b']\"]"],+ ],+ )+ ],+ },+ id="fuzz-2338-nested-ifs-outer-collect",+ ),+ ],+)+def test_inputs_at_different_depths_share_one_run_per_outer_frame(+ compatibility_scheduler: bool, build, expected: dict[str, Runs]+) -> None:+ runs = _collect_runs(build(), compatibility_scheduler, *expected)++ assert runs == {sink: _sorted_runs(sink_runs) for sink, sink_runs in expected.items()}+++_FOR_SRC = [[], [["a", "b"]]]+_FOR_RUNS = {+ "out": [((0,), []), ((1,), ["S:['Fa', 'Fb']", "T:['a', 'b']"])],+ "out2": [((0,), []), ((1,), ["rS:['Fa', 'Fb']", "rT:['a', 'b']"])],+}+++def _for_final_with_sibling(sibling_nodes: list[BaseInvocation], sibling_edges: str) -> Graph:+ """`sibling_edges` carry `it1.item` to out.item beside a For final; out.collection is re-iterated into out2."""+ return _graph(+ _FOR_SRC,+ 2,+ [+ Marked(id="mT", marker="T:"),+ *sibling_nodes,+ For(id="for"),+ Marked(id="fb", marker="F"),+ ForReturn(id="ret"),+ Marked(id="Sx", marker="S:"),+ Collect(id="out"),+ Iterate(id="rit"),+ Marked(id="rm", marker="r"),+ Collect(id="out2"),+ ],+ f"""+ it1.item -> mT.value+ {sibling_edges}+ it1.item -> for.collection+ for.item -> fb.value+ fb.value -> ret.output+ for.loop_linkage -> ret.loop_linkage+ for.output_collection -> Sx.value+ Sx.value -> out.item+ out.collection -> rit.collection+ rit.item -> rm.value+ rm.value -> out2.item+ """,+ )+++def _for_sibling_direct() -> Graph:+ return _for_final_with_sibling([], "mT.value -> out.item")+++def _for_sibling_through_item_if() -> Graph:+ return _for_final_with_sibling(+ [If(id="if"), Truthy(id="fc"), Value(id="R", value="R")],+ """+ it1.item -> fc.value+ fc.condition -> if.condition+ mT.value -> if.true_input+ R.value -> if.false_input+ if.value -> out.item+ """,+ )+++def _for_sibling_through_literal_if() -> Graph:+ return _for_final_with_sibling(+ [If(id="if", condition=True)],+ """+ mT.value -> if.true_input+ if.value -> out.item+ """,+ )+++def _unselected_for_behind_item_if_with_reiterate() -> Graph: # fuzz-1681+ return _graph(+ [[], [["a", "b"]]],+ 2,+ [+ Marked(id="m1", marker="T:"),+ For(id="for2", collection=["u"]),+ Marked(id="fb3", marker="F"),+ ForReturn(id="ret4"),+ If(id="if"),+ Truthy(id="cond"),+ Collect(id="out"),+ For(id="for5"),+ Marked(id="fb6", marker="F"),+ ForReturn(id="ret7"),+ Marked(id="p8", marker="S:"),+ Iterate(id="rit"),+ Marked(id="rm", marker="r"),+ Value(id="rr", value="RR"),+ If(id="rif"),+ Collect(id="out2"),+ Truthy(id="rc"),+ ],+ """+ if.value -> out.item+ p8.value -> out.item+ rif.value -> out2.item+ it1.item -> m1.value+ for2.item -> fb3.value+ fb3.value -> ret4.output+ for2.loop_linkage -> ret4.loop_linkage+ m1.value -> if.true_input+ for2.output_collection -> if.false_input+ it1.item -> cond.value+ cond.condition -> if.condition+ it1.item -> for5.collection+ for5.item -> fb6.value+ fb6.value -> ret7.output+ for5.loop_linkage -> ret7.loop_linkage+ for5.output_collection -> p8.value+ out.collection -> rit.collection+ rit.item -> rm.value+ rm.value -> rif.true_input+ rr.value -> rif.false_input+ rit.item -> rc.value+ rc.condition -> rif.condition+ """,+ )+++def _root_for_through_literal_if_beside_empty_iterator() -> Graph: # fuzz-2236+ return _graph(+ [[["", "b", "a"]], [[], ["b", "b"]]],+ 2,+ [+ For(id="for1", collection=["u", "v"]),+ Marked(id="fb2", marker="F"),+ ForReturn(id="ret3"),+ Marked(id="m4", marker="F:"),+ If(id="if", condition=True),+ Collect(id="out"),+ Concat(id="sbs"),+ Iterate(id="itb"),+ Marked(id="sx", marker="n"),+ Collect(id="out2"),+ ],+ """+ if.value -> out.item+ sx.value -> out.item+ out.collection -> out2.item+ for1.item -> fb2.value+ fb2.value -> ret3.output+ for1.loop_linkage -> ret3.loop_linkage+ it1.item -> m4.value+ for1.output_collection -> if.true_input+ m4.value -> if.false_input+ sbs.collection -> itb.collection+ itb.item -> sx.value+ """,+ )+++def _nested_for_ifs_beside_per_item_for_with_reiterate() -> Graph: # fuzz-2600+ return _graph(+ [[[]], [[[], ["b"], [""]], [["a", ""]], [["a"], ["", "a"]]]],+ 3,+ [+ Value(id="root2", value="aT:"),+ Value(id="root3", value="bT:"),+ If(id="iif1", condition=False),+ Marked(id="p4", marker="T:"),+ For(id="for6", collection=["u", "v"]),+ Marked(id="fb7", marker="F"),+ ForReturn(id="ret8"),+ For(id="for9", collection=["u"]),+ Marked(id="fb10", marker="F"),+ ForReturn(id="ret11"),+ If(id="iif5"),+ BooleanInvocation(id="ic12", value=False),+ Marked(id="p13", marker="F:"),+ If(id="if", condition=False),+ Collect(id="out"),+ For(id="for14"),+ Marked(id="fb15", marker="F"),+ ForReturn(id="ret16"),+ Iterate(id="rit"),+ Marked(id="rm", marker="r"),+ Value(id="rr", value="RR"),+ If(id="rif", condition=True),+ Collect(id="out2"),+ ],+ """+ if.value -> out.item+ for14.output_collection -> out.item+ rif.value -> out2.item+ root2.value -> iif1.true_input+ root3.value -> iif1.false_input+ iif1.value -> p4.value+ for6.item -> fb7.value+ fb7.value -> ret8.output+ for6.loop_linkage -> ret8.loop_linkage+ for9.item -> fb10.value+ fb10.value -> ret11.output+ for9.loop_linkage -> ret11.loop_linkage+ for6.output_collection -> iif5.true_input+ for9.output_collection -> iif5.false_input+ ic12.value -> iif5.condition+ iif5.value -> p13.value+ p4.value -> if.true_input+ p13.value -> if.false_input+ it2.item -> for14.collection+ for14.item -> fb15.value+ fb15.value -> ret16.output+ for14.loop_linkage -> ret16.loop_linkage+ out.collection -> rit.collection+ rit.item -> rm.value+ rm.value -> rif.true_input+ rr.value -> rif.false_input+ """,+ )+++# Flaw: a For final beside a passthrough must join the passthrough's run, keeping both values in one frame.+ "build, expected",+ [+ pytest.param(_for_sibling_direct, _FOR_RUNS, id="direct"),+ pytest.param(_for_sibling_through_item_if, _FOR_RUNS, id="through-per-item-if"),+ pytest.param(_for_sibling_through_literal_if, _FOR_RUNS, id="through-literal-if"),+ pytest.param(+ _unselected_for_behind_item_if_with_reiterate,+ {+ "out": [((0,), []), ((1,), ["T:['a', 'b']", "S:['Fa', 'Fb']"])],+ "out2": [((0,), []), ((1,), ["rT:['a', 'b']", "rS:['Fa', 'Fb']"])],+ },+ id="fuzz-1681-for-behind-per-item-if",+ ),+ pytest.param(+ _root_for_through_literal_if_beside_empty_iterator,+ {+ "out": [((0,), [["Fu", "Fv"]]), ((1,), [["Fu", "Fv"], ["Fu", "Fv"]])],+ "out2": [((), [[["Fu", "Fv"]], [["Fu", "Fv"], ["Fu", "Fv"]]])],+ },+ id="fuzz-2236-root-for-beside-empty-iterator",+ ),+ pytest.param(+ _nested_for_ifs_beside_per_item_for_with_reiterate,+ {+ "out": [+ ((0, 0), ["F:['Fu']"]),+ ((1, 0, 0), ["F:['Fu']", []]),+ ((1, 0, 1), ["F:['Fu']", ["Fb"]]),+ ((1, 0, 2), ["F:['Fu']", ["F"]]),+ ((1, 1, 0), ["F:['Fu']", ["Fa", "F"]]),+ ((1, 2, 0), ["F:['Fu']", ["Fa"]]),+ ((1, 2, 1), ["F:['Fu']", ["F", "Fa"]]),+ ],+ "out2": [+ ((0, 0, 0), ["rF:['Fu']"]),+ ((1, 0, 0), ["rF:['Fu']", "r[]"]),+ ((1, 0, 1), ["rF:['Fu']", "r['Fb']"]),+ ((1, 0, 2), ["rF:['Fu']", "r['F']"]),+ ((1, 1, 0), ["rF:['Fu']", "r['Fa', 'F']"]),+ ((1, 2, 0), ["rF:['Fu']", "r['Fa']"]),+ ((1, 2, 1), ["rF:['Fu']", "r['F', 'Fa']"]),+ ],+ },+ id="fuzz-2600-nested-for-ifs",+ ),+ ],+)+def test_for_final_beside_passthrough_stays_in_one_run_per_frame(+ compatibility_scheduler: bool, build, expected: dict[str, Runs]+) -> None:+ runs = _collect_runs(build(), compatibility_scheduler, *expected)++ assert runs == {sink: _sorted_runs(sink_runs) for sink, sink_runs in expected.items()}+++# Flaw: a per-item If that is never selected contributes no items, so it must not add runs of its own.+# Which runs the O: values group into is undecided, so only the absence of empty runs and of lost values is pinned.+ "src, expected_values",+ [+ pytest.param(+ [[[["c"]], [[""]]], [[["b"], ["d"]]]],+ {"O:[[['c']], [['']]]", "O:[[['b'], ['d']]]"},+ id="reduced",+ ),+ pytest.param(+ [[[["c", "a", "a"]], [[""]]], [[["b"], ["c", "c"], ["c"]]], [[["a", "c", "b"], ["a", "a"]]]],+ {+ "O:[[['c', 'a', 'a']], [['']]]",+ "O:[[['b'], ['c', 'c'], ['c']]]",+ "O:[[['a', 'c', 'b'], ['a', 'a']]]",+ },+ id="fuzz-1292",+ ),+ ],+)+def test_unselected_per_item_if_adds_no_empty_runs(+ compatibility_scheduler: bool, src: list[AnyValue], expected_values: set[str]+) -> None:+ graph = _graph(+ src,+ 3,+ [+ Marked(id="cm1", marker="x"),+ Collect(id="col"),+ Marked(id="p3", marker="T:"),+ Marked(id="p4", marker="F:"),+ If(id="if"),+ Truthy(id="fc"),+ Marked(id="m5", marker="O:"),+ If(id="if2", condition=False),+ Collect(id="out"),+ ],+ """+ it0.item -> cm1.value+ cm1.value -> col.item+ col.collection -> p3.value+ col.collection -> p4.value+ p3.value -> if.true_input+ p4.value -> if.false_input+ it2.item -> fc.value+ fc.condition -> if.condition+ it0.item -> m5.value+ m5.value -> if2.false_input+ if.value -> if2.true_input+ if2.value -> out.item+ """,+ )++ runs = _collect_runs(graph, compatibility_scheduler)["out"]++ assert all(items for _, items in runs), runs+ assert expected_values <= {item for _, items in runs for item in items}, runs+++def test_root_conditioned_if_waits_for_a_nested_for_final(compatibility_scheduler: bool) -> None:+ graph = _graph(+ [[[["a"]]]],+ 1,+ [+ Marked(id="m2", marker="aT:"),+ For(id="for3", collection=["u", "v"]),+ Marked(id="fb4", marker="F"),+ ForReturn(id="ret5"),+ If(id="iif1", condition=False),+ BooleanInvocation(id="ic6", value=True),+ For(id="for8"),+ Marked(id="fb9", marker="F"),+ ForReturn(id="ret10"),+ Marked(id="p11", marker="aF:"),+ If(id="iif7", condition=True),+ Marked(id="p13", marker="F:"),+ If(id="if", condition=False),+ BooleanInvocation(id="cond", value=True),+ ],+ """+ it0.item -> m2.value+ for3.item -> fb4.value+ fb4.value -> ret5.output+ for3.loop_linkage -> ret5.loop_linkage+ m2.value -> iif1.true_input+ ic6.value -> iif1.condition+ it0.item -> for8.collection+ for8.item -> fb9.value+ fb9.value -> ret10.output+ for8.loop_linkage -> ret10.loop_linkage+ for8.output_collection -> p11.value+ p11.value -> iif7.true_input+ iif7.value -> p13.value+ iif1.value -> if.true_input+ p13.value -> if.false_input+ cond.value -> if.condition+ """,+ )+ state = GraphExecutionState(graph=graph)+ state._execution_scheduler = (+ _ExecutionScheduler(state) if compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )+ trace = []+ for _ in range(200):+ node = state.next()+ if node is None:+ break+ source_id = state.prepared_source_mapping[node.id]+ trace.append((source_id, state._get_iteration_path(node.id)))+ state.complete(node.id, node.invoke(Mock()))++ assert state.is_complete(), f"execution stalled; trace={trace}"+ assert not state.has_error(), trace+ observed = {+ node_id: [+ (state._get_iteration_path(exec_id), getattr(state.results[exec_id], "value", None))+ for exec_id in state._prepared_registry().get_prepared_ids(node_id)+ if exec_id in state.results+ ]+ for node_id in ("m2", "iif1", "if")+ }+ assert observed == {+ "m2": [((0,), "aT:[[['a']]]")],+ "iif1": [((0,), "aT:[[['a']]]")],+ "if": [((0,), "aT:[[['a']]]")],+ }+++ "true_branch_edges",+ [+ pytest.param(+ """+ it1.item -> t.value+ t.value -> c1.item+ c1.collection -> c2.item+ c2.collection -> if.true_input+ """,+ id="collect-of-collect-fuzz-2037",+ ),+ pytest.param(+ """+ it0.item -> t.value+ t.value -> c2.item+ c2.collection -> if.true_input+ """,+ id="collect-closing-outer-axis-fuzz-460",+ ),+ ],+)[email protected]("computed_condition", [False, True], ids=["literal-condition", "computed-condition"])+def test_root_condition_selecting_per_frame_collect_closes_downstream_collect(+ true_branch_edges: str, computed_condition: bool, compatibility_scheduler: bool+) -> None:+ nodes: list[BaseInvocation] = [+ Marked(id="x", marker="x"),+ Collect(id="col"),+ Marked(id="f", marker="F:"),+ Marked(id="t", marker="x"),+ Collect(id="c2"),+ If(id="if", condition=False),+ Collect(id="out"),+ ]+ if "c1" in true_branch_edges:+ nodes.append(Collect(id="c1"))+ edges = f"""+ it1.item -> x.value+ x.value -> col.item+ col.collection -> f.value+ f.value -> if.false_input+ {true_branch_edges}+ if.value -> out.item+ """+ if computed_condition:+ nodes.append(BooleanInvocation(id="cond", value=False))+ edges += "cond.value -> if.condition\n"+ graph = _graph([["a", "b"], ["c"]], 2, nodes, edges)++ assert _collect_runs(graph, compatibility_scheduler)["out"] == [((), ["F:['xa', 'xb']", "F:['xc']"])]++[email protected]("computed_condition", [False, True], ids=["literal-condition", "computed-condition"])[email protected]("resume", [False, True], ids=["fresh", "resume-after-parent-collect"])+def test_reiterating_collect_keeps_root_if_value_in_parent_frames(+ compatibility_scheduler: bool, computed_condition: bool, resume: bool, monkeypatch: pytest.MonkeyPatch+) -> None:+ nodes: list[BaseInvocation] = [+ Marked(id="m", marker="T:"),+ Collect(id="out"),+ Iterate(id="rit"),+ Marked(id="rm", marker="r"),+ If(id="rif") if computed_condition else If(id="rif", condition=False),+ Value(id="rr", value="RR"),+ Collect(id="out2"),+ ]+ edges = """+ it1.item -> m.value+ m.value -> out.item+ out.collection -> rit.collection+ rit.item -> rm.value+ rm.value -> rif.true_input+ rr.value -> rif.false_input+ rif.value -> out2.item+ """+ if computed_condition:+ nodes.append(BooleanInvocation(id="cond", value=False))+ edges += "cond.value -> rif.condition\n"+ graph = _graph([[], [["a"]], [["b"], ["c"]]], 2, nodes, edges)++ state = GraphExecutionState(graph=graph)+ state._execution_scheduler = (+ _ExecutionScheduler(state) if compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )+ checkpointed = not resume+ for _ in range(5000):+ out_exec_ids = state.source_prepared_mapping.get("out", set())+ rit_exec_ids = state.source_prepared_mapping.get("rit", set())+ if (+ resume+ and not checkpointed+ and out_exec_ids+ and all(exec_id in state.results for exec_id in out_exec_ids)+ and not any(exec_id in state.results for exec_id in rit_exec_ids)+ ):+ state = load_execution_state(json.loads(json.dumps(dump_execution_state(state))))+ state._execution_scheduler = (+ _ExecutionScheduler(state) if compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )+ checkpointed = True+ node = state.next()+ if node is None:+ break+ state.complete(node.id, node.invoke(Mock()))++ assert checkpointed+ assert state.is_complete() and not state.has_error()+ materializer = _ExecutionMaterializer(state)+ registry = state._prepared_registry()+ root_value_edge = graph._get_input_edges("out2", "item")[0]+ from invokeai.app.services.shared.graph_if_runtime import _get_if_iteration_paths_with_ancestry++ iterator_ancestry = materializer._get_iterator_ancestry(materializer.iterator_graph())+ assert _get_if_iteration_paths_with_ancestry(+ state,+ "rif",+ set(),+ materializer._get_prepared_nodes_for_source,+ materializer._get_prepared_edge_iteration_path,+ iterator_ancestry,+ ) == [(1, 0), (2, 0), (2, 1)]+ static_axis_derivations = 0+ get_static_collect_group_axes = materializer._get_static_collect_group_axes++ def count_static_axis_derivations(edge: AnyValue) -> tuple[str, ...]:+ nonlocal static_axis_derivations+ static_axis_derivations += 1+ return get_static_collect_group_axes(edge)++ monkeypatch.setattr(materializer, "_get_static_collect_group_axes", count_static_axis_derivations)+ rif_exec_ids = registry.get_prepared_ids("rif")+ for exec_id in rif_exec_ids:+ assert materializer._get_prepared_edge_iteration_axes(root_value_edge, exec_id) == ("it0", "rit")+ parent_item_edges = graph._get_input_edges("out", "item")+ assert static_axis_derivations == len(parent_item_edges)++ empty_out_exec_id = registry.get_prepared_id_at_path("out", (0,))+ assert empty_out_exec_id is not None+ collection_edge = graph._get_input_edges("rit", "collection")[0]+ assert materializer._get_prepared_edge_iteration_axes(collection_edge, empty_out_exec_id) == ("it0",)++ execution_graph_reads = 0+ get_execution_graph_flat = state._get_execution_graph_flat++ def count_execution_graph_reads() -> AnyValue:+ nonlocal execution_graph_reads+ execution_graph_reads += 1+ return get_execution_graph_flat()++ monkeypatch.setattr(state, "_get_execution_graph_flat", count_execution_graph_reads)+ for exec_id in rif_exec_ids:+ assert materializer._get_prepared_edge_iteration_axes(root_value_edge, exec_id) == ("it0", "rit")+ assert execution_graph_reads == 0++ observed = _sorted_runs(+ [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state.source_prepared_mapping.get("out2", ())+ if exec_id in state.results+ ]+ )+ assert observed == [((0,), []), ((1,), ["RR"]), ((2,), ["RR", "RR"])]++ state.add_node(Marked(id="unrelated", marker="x"))+ assert materializer._get_prepared_edge_iteration_axes(root_value_edge, next(iter(rif_exec_ids))) == (+ "it0",+ "rit",+ )+ assert static_axis_derivations == len(parent_item_edges) * 2+++def test_reiterated_collect_parent_path_index_is_stable_while_children_expand(+ compatibility_scheduler: bool, monkeypatch: pytest.MonkeyPatch+) -> None:+ child_count = 24+ nodes: list[BaseInvocation] = [+ Marked(id="m", marker="T:"),+ Collect(id="out"),+ Iterate(id="rit"),+ Marked(id="rm", marker="r"),+ If(id="rif", condition=False),+ Value(id="rr", value="RR"),+ Collect(id="out2"),+ ]+ graph = _graph(+ [[[f"v{i}"]] for i in range(child_count)],+ 2,+ nodes,+ """+ it1.item -> m.value+ m.value -> out.item+ out.collection -> rit.collection+ rit.item -> rm.value+ rm.value -> rif.true_input+ rr.value -> rif.false_input+ rif.value -> out2.item+ """,+ )+ state = GraphExecutionState(graph=graph)+ state._execution_scheduler = (+ _ExecutionScheduler(state) if compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )+ registry = state._prepared_registry()+ original_lookup = registry.get_prepared_id_at_path+ original_get_iteration_path = registry.get_iteration_path+ original_register = registry.register+ out_index_builds = 0+ out_index_source_visits = 0+ out_lookups = 0+ late_out_registrations = 0+ building_out_index = False++ def track_iteration_path(exec_id: str) -> tuple[int, ...] | None:+ nonlocal out_index_source_visits+ if building_out_index:+ out_index_source_visits += 1+ return original_get_iteration_path(exec_id)++ def track_lookup(source_node_id: str, iteration_path: tuple[int, ...]) -> str | None:+ nonlocal building_out_index, out_index_builds, out_lookups+ if source_node_id != "out":+ return original_lookup(source_node_id, iteration_path)+ out_lookups += 1+ building_out_index = source_node_id not in registry._prepared_ids_by_source_and_path+ if building_out_index:+ out_index_builds += 1+ try:+ return original_lookup(source_node_id, iteration_path)+ finally:+ building_out_index = False++ def track_register(exec_id: str, source_node_id: str) -> None:+ nonlocal late_out_registrations+ if source_node_id == "out" and out_index_builds:+ late_out_registrations += 1+ original_register(exec_id, source_node_id)++ monkeypatch.setattr(registry, "get_prepared_id_at_path", track_lookup)+ monkeypatch.setattr(registry, "get_iteration_path", track_iteration_path)+ monkeypatch.setattr(registry, "register", track_register)++ for _ in range(10000):+ node = state.next()+ if node is None:+ break+ state.complete(node.id, node.invoke(Mock()))++ assert state.is_complete() and not state.has_error()+ assert len(registry.get_prepared_ids("out")) == child_count+ assert len(registry.get_prepared_ids("rif")) == child_count+ assert _sorted_runs(+ [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in registry.get_prepared_ids("out2")+ ]+ ) == _sorted_runs([((index,), ["RR"]) for index in range(child_count)])+ assert out_index_builds == 1+ assert out_index_source_visits == child_count+ assert late_out_registrations == 0+ assert out_lookups >= child_count++[email protected]("resume", [False, True], ids=["fresh", "checkpoint-after-parent-collect"])[email protected]("empty_parent_run", [False, True], ids=["non-empty-parent-runs", "empty-parent-run"])+def test_reiterating_collect_consumes_each_sibling_group_independently(+ compatibility_scheduler: bool, resume: bool, empty_parent_run: bool+) -> None:+ graph = _graph(+ ([[], ["a"], ["b", "c"]] if empty_parent_run else [["a"], ["b", "c"]]),+ 2,+ [+ Marked(id="m", marker="T:"),+ Concat(id="sib_src", first=["q", "p", "r"]),+ Iterate(id="itb"),+ Marked(id="n", marker="n"),+ Collect(id="out"),+ Iterate(id="rit"),+ Marked(id="rm", marker="r"),+ Collect(id="out2"),+ ],+ """+ it1.item -> m.value+ m.value -> out.item+ sib_src.collection -> itb.collection+ itb.item -> n.value+ n.value -> out.item+ out.collection -> rit.collection+ rit.item -> rm.value+ rm.value -> out2.item+ """,+ )+ state = GraphExecutionState(graph=graph)+ state._execution_scheduler = (+ _ExecutionScheduler(state) if compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )+ checkpointed = not resume+ for _ in range(5000):+ out_exec_ids = state.source_prepared_mapping.get("out", set())+ rit_exec_ids = state.source_prepared_mapping.get("rit", set())+ if (+ resume+ and not checkpointed+ and out_exec_ids+ and all(exec_id in state.results for exec_id in out_exec_ids)+ and not any(exec_id in state.results for exec_id in rit_exec_ids)+ ):+ state = load_execution_state(json.loads(json.dumps(dump_execution_state(state))))+ state._execution_scheduler = (+ _ExecutionScheduler(state) if compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )+ checkpointed = True+ node = state.next()+ if node is None:+ break+ state.complete(node.id, node.invoke(Mock()))++ assert checkpointed+ assert state.is_complete() and not state.has_error()+ root_sibling_runs = [+ state.results[exec_id].collection+ for exec_id in state.source_prepared_mapping.get("out2", ())+ if exec_id in state.results and state._get_iteration_path(exec_id) == ()+ ]+ assert root_sibling_runs == [["rnq", "rnp", "rnr"]]+ expected = (+ [+ ((), ["rnp", "rnq", "rnr"]),+ ((0,), []),+ ((1,), ["rT:a"]),+ ((2,), ["rT:b", "rT:c"]),+ ]+ if empty_parent_run+ else [+ ((), ["rnp", "rnq", "rnr"]),+ ((0,), ["rT:a"]),+ ((1,), ["rT:b", "rT:c"]),+ ]+ )+ assert (+ _sorted_runs(+ [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state.source_prepared_mapping.get("out2", ())+ if exec_id in state.results+ ]+ )+ == expected+ )++[email protected]("checkpoint_after_out", [False, True], ids=["fresh", "checkpoint-after-out"])+def test_downstream_if_keeps_sibling_collect_parent_frames(+ compatibility_scheduler: bool, checkpoint_after_out: bool+) -> None:+ graph = _graph(+ [["a"], ["b", "c"]],+ 2,+ [+ Marked(id="m", marker="T:"),+ Truthy(id="cond"),+ If(id="if"),+ Concat(id="sib_src", first=["p", "q", "r"]),+ Iterate(id="itb"),+ Marked(id="n", marker="n"),+ Collect(id="out"),+ Iterate(id="rit"),+ Marked(id="rm", marker="r"),+ Truthy(id="rc"),+ Value(id="rr", value="RR"),+ If(id="rif"),+ Collect(id="out2"),+ ],+ """+ it1.item -> m.value+ m.value -> if.true_input+ it1.item -> cond.value+ cond.condition -> if.condition+ if.value -> out.item+ sib_src.collection -> itb.collection+ itb.item -> n.value+ n.value -> out.item+ out.collection -> rit.collection+ rit.item -> rm.value+ rm.value -> rif.true_input+ rr.value -> rif.false_input+ rit.item -> rc.value+ rc.condition -> rif.condition+ rif.value -> out2.item+ """,+ )+ state = GraphExecutionState(graph=graph)+ state._execution_scheduler = (+ _ExecutionScheduler(state) if compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )+ checkpointed = not checkpoint_after_out+ for _ in range(5000):+ out_ids = state._prepared_registry().get_prepared_ids("out")+ rit_ids = state._prepared_registry().get_prepared_ids("rit")+ if (+ checkpoint_after_out+ and not checkpointed+ and len(out_ids) == 3+ and all(exec_id in state.results for exec_id in out_ids)+ and not any(exec_id in state.results for exec_id in rit_ids)+ ):+ state = load_execution_state(json.loads(json.dumps(dump_execution_state(state))))+ state._execution_scheduler = (+ _ExecutionScheduler(state) if compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )+ checkpointed = True+ node = state.next()+ if node is None:+ break+ state.complete(node.id, node.invoke(Mock()))++ assert checkpointed+ assert state.is_complete() and not state.has_error()+ observed_out = _sorted_runs(+ [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state._prepared_registry().get_prepared_ids("out")+ if exec_id in state.results+ ]+ )+ observed_out2 = _sorted_runs(+ [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state._prepared_registry().get_prepared_ids("out2")+ if exec_id in state.results+ ]+ )+ assert observed_out == [((), ["np", "nq", "nr"]), ((0,), ["T:a"]), ((1,), ["T:b", "T:c"])]+ assert observed_out2 == [+ ((), ["rnp", "rnq", "rnr"]),+ ((0,), ["rT:a"]),+ ((1,), ["rT:b", "rT:c"]),+ ]+++def test_sibling_collect_classification_is_cached_per_source_graph(+ compatibility_scheduler: bool, monkeypatch: pytest.MonkeyPatch+) -> None:+ downstream_count = 12+ parent_sources = {"m", "n"}+ graph = _graph(+ ["a", "b"],+ 1,+ [+ Marked(id="m", marker="T:"),+ Concat(id="sib_src", first=["p", "q"]),+ Iterate(id="itb"),+ Marked(id="n", marker="n"),+ Collect(id="out"),+ Iterate(id="rit"),+ *[Marked(id=f"rm{index}", marker="r") for index in range(downstream_count)],+ *[Collect(id=f"sink{index}") for index in range(downstream_count)],+ ],+ "\n".join(+ [+ "it0.item -> m.value",+ "m.value -> out.item",+ "sib_src.collection -> itb.collection",+ "itb.item -> n.value",+ "n.value -> out.item",+ "out.collection -> rit.collection",+ *[+ f"rit.item -> rm{index}.value\nrm{index}.value -> sink{index}.item"+ for index in range(downstream_count)+ ],+ ]+ ),+ )+ state = GraphExecutionState(graph=graph)+ state._execution_scheduler = (+ _ExecutionScheduler(state) if compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )+ materializer = _ExecutionMaterializer(state)+ original_get_source_axes = materializer._get_collect_source_iterator_ids+ classifications = dict.fromkeys(parent_sources, 0)++ def count_parent_item_classification(source_node_id: str) -> tuple[str, ...]:+ if source_node_id in parent_sources:+ classifications[source_node_id] += 1+ return original_get_source_axes(source_node_id)++ monkeypatch.setattr(materializer, "_get_collect_source_iterator_ids", count_parent_item_classification)+ for index in range(downstream_count):+ assert materializer._is_sibling_collect_reiteration(f"rm{index}")++ assert classifications == dict.fromkeys(parent_sources, 1)++ state.add_node(Marked(id="unrelated", marker="x"))+ assert materializer._is_sibling_collect_reiteration("rm0")+ assert classifications == dict.fromkeys(parent_sources, 2)+++def _run_reiteration_graph(+ graph: Graph, compatibility_scheduler: bool, checkpoint_after_out: bool+) -> GraphExecutionState:+ state = GraphExecutionState(graph=graph)+ state._execution_scheduler = (+ _ExecutionScheduler(state) if compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )+ if checkpoint_after_out:+ for _ in range(5000):+ out_ids = state._prepared_registry().get_prepared_ids("out")+ if len(out_ids) == 2 and all(exec_id in state.results for exec_id in out_ids):+ break+ node = state.next()+ assert node is not None, "graph stalled before upstream Collect completed"+ state.complete(node.id, node.invoke(Mock()))+ else:+ pytest.fail("upstream Collect did not produce both executions")++ assert not any(exec_id in state.results for exec_id in state._prepared_registry().get_prepared_ids("rit"))+ state = load_execution_state(json.loads(json.dumps(dump_execution_state(state))))+ state._execution_scheduler = (+ _ExecutionScheduler(state) if compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )++ for _ in range(5000):+ node = state.next()+ if node is None:+ break+ state.complete(node.id, node.invoke(Mock()))+ assert state.is_complete() and not state.has_error()+ return state+++def _lstein_reiterate_graph(with_for: bool) -> Graph:+ nodes: list[BaseInvocation] = [+ Marked(id="cm", marker="C:"),+ Truthy(id="condition"),+ If(id="if"),+ Collect(id="out"),+ Iterate(id="rit"),+ Marked(id="rm", marker="r"),+ Value(id="RR", value="RR"),+ Truthy(id="rcondition"),+ If(id="rif"),+ Collect(id="out2"),+ ]+ if with_for:+ nodes.extend([For(id="for", collection=["u"]), Marked(id="fb", marker="F"), ForReturn(id="ret")])+ true_branch = """+ for.item -> fb.value+ fb.value -> ret.output+ for.loop_linkage -> ret.loop_linkage+ for.output_collection -> if.true_input+ """+ else:+ nodes.append(Value(id="for_value", value=["Fu"]))+ true_branch = "for_value.value -> if.true_input"++ return _graph(+ [[["c"], ["c", ""]], []],+ 2,+ nodes,+ f"""+ it1.item -> cm.value+ cm.value -> if.false_input+ it1.item -> condition.value+ condition.condition -> if.condition+ {true_branch}+ if.value -> out.item+ out.collection -> rit.collection+ rit.item -> rm.value+ rm.value -> rif.true_input+ RR.value -> rif.false_input+ rit.item -> rcondition.value+ rcondition.condition -> rif.condition+ rif.value -> out2.item+ """,+ )++[email protected]("with_for", [False, True], ids=["root-value", "for-final"])[email protected]("checkpoint_after_out", [False, True], ids=["fresh", "checkpoint-after-out"])+def test_reiterated_root_condition_keeps_lstein_empty_frames(+ compatibility_scheduler: bool, with_for: bool, checkpoint_after_out: bool+) -> None:+ state = _run_reiteration_graph(_lstein_reiterate_graph(with_for), compatibility_scheduler, checkpoint_after_out)+ out_runs = [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state._prepared_registry().get_prepared_ids("out")+ if exec_id in state.results+ ]+ out2_runs = [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state._prepared_registry().get_prepared_ids("out2")+ if exec_id in state.results+ ]+ assert _sorted_runs(out_runs) == [((0,), [["Fu"], ["Fu"]]), ((1,), [])]+ assert _sorted_runs(out2_runs) == [((0,), ["r['Fu']", "r['Fu']"]), ((1,), [])]+++def _seed_1234_reiteration_graph() -> Graph:+ return _graph(+ [[], [[[], [], ["b"]], [], []]],+ 3,+ [+ Marked(id="m1", marker="T:"),+ Marked(id="m2", marker="F:"),+ If(id="if", condition=False),+ Truthy(id="cond"),+ Marked(id="cm3", marker="x"),+ Collect(id="col4"),+ Marked(id="p5", marker="O:"),+ If(id="if2", condition=False),+ Collect(id="out"),+ Iterate(id="rit"),+ Marked(id="rm", marker="r"),+ Value(id="rr", value="RR"),+ If(id="rif"),+ Collect(id="out2"),+ BooleanInvocation(id="rc", value=True),+ ],+ """+ it0.item -> m1.value+ it0.item -> m2.value+ m1.value -> if.true_input+ m2.value -> if.false_input+ it1.item -> cond.value+ cond.condition -> if.condition+ it0.item -> cm3.value+ cm3.value -> col4.item+ col4.collection -> p5.value+ if.value -> if2.true_input+ p5.value -> if2.false_input+ if2.value -> out.item+ out.collection -> rit.collection+ rit.item -> rm.value+ rm.value -> rif.true_input+ rr.value -> rif.false_input+ rc.value -> rif.condition+ rif.value -> out2.item+ """,+ )++[email protected]("checkpoint_after_out", [False, True], ids=["fresh", "checkpoint-after-out"])+def test_seed_1234_reiteration_keeps_empty_outer_frame(+ compatibility_scheduler: bool, checkpoint_after_out: bool+) -> None:+ state = _run_reiteration_graph(_seed_1234_reiteration_graph(), compatibility_scheduler, checkpoint_after_out)+ collected_value = "O:['x[]', \"x[[[], [], ['b']], [], []]\"]"+ reiterated_value = f"r{collected_value}"+ out_runs = [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state._prepared_registry().get_prepared_ids("out")+ if exec_id in state.results+ ]+ out2_runs = [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state._prepared_registry().get_prepared_ids("out2")+ if exec_id in state.results+ ]+ assert _sorted_runs(out_runs) == [((0,), []), ((1,), [collected_value] * 3)]+ assert _sorted_runs(out2_runs) == [((0,), []), ((1,), [reiterated_value] * 3)]+++def _root_for_final_selected_in_every_frame(items: int, for_items: int) -> Graph:+ """A per-item If feeds one branch of a literal-False If whose other branch is a root For final."""+ return _graph(+ [["c"]] * items,+ 1,+ [+ Truthy(id="cond"),+ Value(id="t", value="T"),+ Value(id="f", value="F"),+ If(id="inner"),+ For(id="for", collection=[f"u{index}" for index in range(for_items)]),+ Marked(id="body", marker="B"),+ ForReturn(id="ret"),+ If(id="outer", condition=False),+ Collect(id="out"),+ ],+ """+ it0.item -> cond.value+ cond.condition -> inner.condition+ t.value -> inner.true_input+ f.value -> inner.false_input+ for.item -> body.value+ body.value -> ret.output+ for.loop_linkage -> ret.loop_linkage+ inner.value -> outer.true_input+ for.output_collection -> outer.false_input+ outer.value -> out.item+ """,+ )+++ ("items", "for_items"),+ [+ pytest.param(2, 1, id="2-frames-1-for-item"),+ pytest.param(3, 2, id="3-frames-2-for-items"),+ pytest.param(5, 3, id="5-frames-3-for-items"),+ pytest.param(3, 3, id="3-frames-3-for-items"),+ pytest.param(3, 0, id="3-frames-empty-for"),+ ],+)+def test_root_for_final_reaches_every_item_frame(items: int, for_items: int, compatibility_scheduler: bool) -> None:+ """Every frame gets the For final, whether or not its index is also a For iteration index."""+ final = [f"Bu{index}" for index in range(for_items)]++ runs = _collect_runs(_root_for_final_selected_in_every_frame(items, for_items), compatibility_scheduler)["out"]++ assert runs == [((), [final] * items)]+++def _run_with_reload(graph: Graph, compatibility: bool, reload_after: int, *sinks: str) -> dict[str, Runs]:+ """Like `_collect_runs`, but dump and reload the state after `reload_after` invocations."""++ def use_scheduler(state: GraphExecutionState) -> GraphExecutionState:+ state._execution_scheduler = (+ _ExecutionScheduler(state) if compatibility else _GenericGraphSchedulerAdapter(state)+ )+ return state++ state = use_scheduler(GraphExecutionState(graph=graph))+ for step in range(5000):+ if step == reload_after:+ snapshot = json.loads(json.dumps(dump_execution_state(state)))+ state = use_scheduler(load_execution_state(snapshot))+ node = state.next()+ if node is None:+ break+ state.complete(node.id, node.invoke(Mock()))+ assert step > reload_after, "the graph finished before the reload point"+ assert state.is_complete() and not state.has_error()+ return {+ name: _sorted_runs(+ [+ (state._get_iteration_path(execution), state.results[execution].collection)+ for execution in state._prepared_registry().get_prepared_ids(name)+ if execution in state.results+ ]+ )+ for name in sinks or ("out",)+ }+++def _per_item_if_selecting_root_for_final() -> Graph: # fuzz-6+ return _graph(+ [["a"], []],+ 1,+ [+ For(id="for1"),+ Marked(id="fb2", marker="F"),+ ForReturn(id="ret3"),+ Marked(id="p4", marker="T:"),+ For(id="for5", collection=["u", "v"]),+ Marked(id="fb6", marker="F"),+ ForReturn(id="ret7"),+ If(id="if"),+ Truthy(id="cond"),+ Collect(id="out"),+ ],+ """+ it0.item -> for1.collection+ for1.item -> fb2.value+ fb2.value -> ret3.output+ for1.loop_linkage -> ret3.loop_linkage+ for1.output_collection -> p4.value+ for5.item -> fb6.value+ fb6.value -> ret7.output+ for5.loop_linkage -> ret7.loop_linkage+ p4.value -> if.true_input+ for5.output_collection -> if.false_input+ it0.item -> cond.value+ cond.condition -> if.condition+ if.value -> out.item+ """,+ )+++def _nested_for_ifs_under_literal_if() -> Graph: # fuzz-125+ return _graph(+ [[["b"], ["b"]]],+ 2,+ [+ For(id="for2"),+ Marked(id="fb3", marker="F"),+ ForReturn(id="ret4"),+ Value(id="root5", value="bT:"),+ If(id="iif1"),+ Truthy(id="ic6"),+ For(id="for8"),+ Marked(id="fb9", marker="F"),+ ForReturn(id="ret10"),+ Marked(id="p11", marker="aF:"),+ For(id="for12"),+ Marked(id="fb13", marker="F"),+ ForReturn(id="ret14"),+ If(id="iif7"),+ Truthy(id="ic15"),+ If(id="if", condition=True),+ Collect(id="out"),+ Collect(id="out2"),+ ],+ """+ it0.item -> for2.collection+ for2.item -> fb3.value+ fb3.value -> ret4.output+ for2.loop_linkage -> ret4.loop_linkage+ for2.output_collection -> iif1.true_input+ root5.value -> iif1.false_input+ it1.item -> ic6.value+ ic6.condition -> iif1.condition+ it0.item -> for8.collection+ for8.item -> fb9.value+ fb9.value -> ret10.output+ for8.loop_linkage -> ret10.loop_linkage+ for8.output_collection -> p11.value+ for12.item -> fb13.value+ fb13.value -> ret14.output+ for12.loop_linkage -> ret14.loop_linkage+ p11.value -> iif7.true_input+ for12.output_collection -> iif7.false_input+ it0.item -> ic15.value+ ic15.condition -> iif7.condition+ iif1.value -> if.true_input+ iif7.value -> if.false_input+ if.value -> out.item+ out.collection -> out2.item+ """,+ )+++def _chained_per_item_ifs_over_root_fors() -> Graph: # fuzz-763+ return _graph(+ [[], []],+ 1,+ [+ For(id="for2", collection=["u"]),+ Marked(id="fb3", marker="F"),+ ForReturn(id="ret4"),+ For(id="for5"),+ Marked(id="fb6", marker="F"),+ ForReturn(id="ret7"),+ Marked(id="p8", marker="bT:"),+ If(id="iif1"),+ Truthy(id="ic9"),+ For(id="for10", collection=["u", "v"]),+ Marked(id="fb11", marker="F"),+ ForReturn(id="ret12"),+ If(id="if"),+ Truthy(id="cond"),+ Value(id="root13", value="O:"),+ If(id="if2", condition=True),+ Collect(id="out"),+ Collect(id="out2"),+ ],+ """+ for2.item -> fb3.value+ fb3.value -> ret4.output+ for2.loop_linkage -> ret4.loop_linkage+ it0.item -> for5.collection+ for5.item -> fb6.value+ fb6.value -> ret7.output+ for5.loop_linkage -> ret7.loop_linkage+ for5.output_collection -> p8.value+ for2.output_collection -> iif1.true_input+ p8.value -> iif1.false_input+ it0.item -> ic9.value+ ic9.condition -> iif1.condition+ for10.item -> fb11.value+ fb11.value -> ret12.output+ for10.loop_linkage -> ret12.loop_linkage+ iif1.value -> if.true_input+ for10.output_collection -> if.false_input+ it0.item -> cond.value+ cond.condition -> if.condition+ if.value -> if2.true_input+ root13.value -> if2.false_input+ if2.value -> out.item+ out.collection -> out2.item+ """,+ )+++_FOR_FINAL_BOTH = [["Fu", "Fv"], ["Fu", "Fv"]]+_NESTED_FINALS = [["F['b']", "F['b']"], ["F['b']", "F['b']"]]+++ ("build", "expected"),+ [+ pytest.param(+ _per_item_if_selecting_root_for_final,+ {"out": [((0,), ["T:['Fa']"]), ((1,), [["Fu", "Fv"]])]},+ id="fuzz-6",+ ),+ pytest.param(+ _nested_for_ifs_under_literal_if,+ {"out": [((0,), _NESTED_FINALS)], "out2": [((), [_NESTED_FINALS])]},+ id="fuzz-125",+ ),+ pytest.param(+ _chained_per_item_ifs_over_root_fors,+ {"out": [((), _FOR_FINAL_BOTH)], "out2": [((), [_FOR_FINAL_BOTH])]},+ id="fuzz-763",+ ),+ ],+)[email protected]("reload_after", [3, 6, 10])+def test_mid_run_reload_keeps_root_for_finals(+ build: Callable[[], Graph], expected: dict[str, Runs], reload_after: int, compatibility_scheduler: bool+) -> None:+ """A dumped and reloaded state finishes with the same runs as an uninterrupted one."""+ assert _collect_runs(build(), compatibility_scheduler, *expected) == expected++ assert _run_with_reload(build(), compatibility_scheduler, reload_after, *expected) == expected+++def _nested_for_final_through_literal_if() -> Graph: # fuzz-304+ """A literal-False If selects a For final from the `(it0, it1)` frame; its other branch is in the `it0` frame."""+ return _graph(+ [[["c", "a"], [""]]],+ 2,+ [+ For(id="for"),+ Marked(id="body", marker="F"),+ ForReturn(id="ret"),+ Marked(id="t", marker="T:"),+ If(id="if", condition=False),+ Collect(id="out"),+ ],+ """+ it1.item -> for.collection+ for.item -> body.value+ body.value -> ret.output+ for.loop_linkage -> ret.loop_linkage+ it0.item -> t.value+ t.value -> if.true_input+ for.output_collection -> if.false_input+ if.value -> out.item+ """,+ )+++def test_if_selecting_nested_for_final_gets_each_frames_final(compatibility_scheduler: bool) -> None:+ runs = _collect_runs(_nested_for_final_through_literal_if(), compatibility_scheduler)["out"]++ assert runs == [((0, 0), [["Fc", "Fa"]]), ((0, 1), [["F"]])]++[email protected]("reload_after", [4, 9])+def test_if_selecting_nested_for_final_survives_reload(reload_after: int, compatibility_scheduler: bool) -> None:+ expected = {"out": [((0, 0), [["Fc", "Fa"]]), ((0, 1), [["F"]])]}++ assert (+ _run_with_reload(_nested_for_final_through_literal_if(), compatibility_scheduler, reload_after, "out")+ == expected+ )+++def _sibling_reiterate_into_if(+ computed_condition: bool, src: list[AnyValue] | None = None, levels: int = 2, condition: bool = True+) -> Graph: # fuzz3-117+ """`out` holds a nested per-item value and a sibling root value; an If after re-iterating it selects each item+ (`condition=True`) or the root `RR` value (`condition=False`)."""+ condition_node: list[BaseInvocation] = [BooleanInvocation(id="cond", value=condition)] if computed_condition else []+ return _graph(+ [[["c"]]] if src is None else src,+ levels,+ [+ Marked(id="item", marker="a:"),+ Concat(id="sibling_src", first=["p"]),+ Iterate(id="sibling"),+ Marked(id="sibling_value", marker="n"),+ Collect(id="out"),+ Iterate(id="rit"),+ Marked(id="re", marker="r"),+ Value(id="other", value="RR"),+ If(id="if", condition=condition),+ Collect(id="out2"),+ *condition_node,+ ],+ f"it{levels - 1}.item -> item.value"+ + """+ item.value -> out.item+ sibling_src.collection -> sibling.collection+ sibling.item -> sibling_value.value+ sibling_value.value -> out.item+ out.collection -> rit.collection+ rit.item -> re.value+ re.value -> if.true_input+ other.value -> if.false_input+ if.value -> out2.item+ """+ + ("cond.value -> if.condition" if computed_condition else ""),+ )+++def test_sibling_reiterate_projection_keeps_distinct_axes_at_same_path(monkeypatch: pytest.MonkeyPatch) -> None:+ state = GraphExecutionState(graph=_sibling_reiterate_into_if(computed_condition=False))+ iterator_ancestry = _IteratorAncestry(state)+ final_axis_checks = 0+ get_final_axes = graph_if_runtime._get_if_final_axes_for_edge++ def count_final_axis_checks(*args: AnyValue) -> AnyValue:+ nonlocal final_axis_checks+ final_axis_checks += 1+ return get_final_axes(*args)++ monkeypatch.setattr(graph_if_runtime, "_get_if_final_axes_for_edge", count_final_axis_checks)+ assert _is_sibling_collect_iterate_axis(state, iterator_ancestry, "rit")+ first_check_count = final_axis_checks+ assert first_check_count > 0+ assert _is_sibling_collect_iterate_axis(state, iterator_ancestry, "rit")+ assert final_axis_checks == first_check_count++ registry = state._prepared_registry()+ registry_type = type(registry)+ frame_metadata_reads = 0+ get_iteration_path = registry_type.get_iteration_path+ get_iteration_axes = registry_type.get_iteration_axes++ def count_iteration_path_reads(self: AnyValue, exec_id: str) -> AnyValue:+ nonlocal frame_metadata_reads+ frame_metadata_reads += 1+ return get_iteration_path(self, exec_id)++ def count_iteration_axes_reads(self: AnyValue, exec_id: str) -> AnyValue:+ nonlocal frame_metadata_reads+ frame_metadata_reads += 1+ return get_iteration_axes(self, exec_id)++ monkeypatch.setattr(registry_type, "get_iteration_path", count_iteration_path_reads)+ monkeypatch.setattr(registry_type, "get_iteration_axes", count_iteration_axes_reads)+ registry.register("frame-a", "rit")+ registry.set_iteration_path("frame-a", (0, 0))+ registry.set_iteration_axes("frame-a", ("it0", "rit"))+ assert _get_sibling_collect_iterate_axes_to_project(state, iterator_ancestry, ("it0", "rit")) == {"rit"}+ first_frame_scan_count = frame_metadata_reads+ assert first_frame_scan_count > 0+ assert _get_sibling_collect_iterate_axes_to_project(state, iterator_ancestry, ("it0", "rit")) == {"rit"}+ assert frame_metadata_reads == first_frame_scan_count++ registry.register("parent-frame", "it0")+ registry.set_iteration_path("parent-frame", (0,))+ registry.set_iteration_axes("parent-frame", ("it0",))+ assert _get_sibling_collect_iterate_axes_to_project(state, iterator_ancestry, ("it0", "rit")) == {"rit"}+ assert frame_metadata_reads > first_frame_scan_count+ first_frame_scan_count = frame_metadata_reads+ state.source_prepared_mapping["it0"] = set(state.source_prepared_mapping["it0"])+ assert _get_sibling_collect_iterate_axes_to_project(state, iterator_ancestry, ("it0", "rit")) == {"rit"}+ assert frame_metadata_reads > first_frame_scan_count+ first_frame_scan_count = frame_metadata_reads++ registry.register("frame-b", "rit")+ registry.set_iteration_path("frame-b", (0, 1))+ registry.set_iteration_axes("frame-b", ("it0", "rit"))+ assert _get_sibling_collect_iterate_axes_to_project(state, iterator_ancestry, ("it0", "rit")) == {"rit"}+ assert frame_metadata_reads > first_frame_scan_count++ registry.register("frame-c", "rit")+ registry.set_iteration_path("frame-c", (0, 1))+ registry.set_iteration_axes("frame-c", ("sibling", "rit"))++ assert not _is_sibling_collect_iterate_axis(state, iterator_ancestry, "rit")+ assert not _is_sibling_collect_iterate_axis(state, iterator_ancestry, "rit")+++def test_combined_sibling_reiterate_projection_rejects_ambiguous_axes() -> None:+ prepared_frames = [+ ((0, 0, 0, 1), ("it0", "rit_a", "keep_a", "rit_b")),+ ((0, 1, 0, 0), ("it0", "rit_a", "keep_b", "rit_b")),+ ]++ assert _project_prepared_iteration_paths(prepared_frames, {"rit_a"}) is not None+ assert _project_prepared_iteration_paths(prepared_frames, {"rit_b"}) is not None+ assert _project_prepared_iteration_paths(prepared_frames, {"rit_a", "rit_b"}) is None+ assert _project_prepared_iteration_paths([*prepared_frames, ((1, 0), ("rit_a",))], {"rit_a"}) is None++[email protected]("computed_condition", [False, True], ids=["literal-condition", "computed-condition"])+def test_if_after_reiterate_keeps_sibling_root_value(computed_condition: bool, compatibility_scheduler: bool) -> None:+ """Without the If, out2 gets `(): ['rnp']` and `(0,): ["ra:['c']"]`; the If must not change that."""+ runs = _collect_runs(_sibling_reiterate_into_if(computed_condition), compatibility_scheduler, "out2")["out2"]++ assert runs == [((), ["rnp"]), ((0,), ["ra:['c']"])]++[email protected]("computed_condition", [False, True], ids=["literal-condition", "computed-condition"])+def test_if_after_reiterate_keeps_sibling_root_value_after_reload(+ computed_condition: bool, compatibility_scheduler: bool+) -> None:+ expected = {"out2": [((), ["rnp"]), ((0,), ["ra:['c']"])]}++ assert (+ _run_with_reload(_sibling_reiterate_into_if(computed_condition), compatibility_scheduler, 12, "out2")+ == expected+ )++[email protected]("computed_condition", [False, True], ids=["literal-condition", "computed-condition"])+def test_if_after_sibling_reiterate_selects_root_value_once_per_item(+ computed_condition: bool, compatibility_scheduler: bool+) -> None:+ """`out` holds `a:a`, `a:b` and `np`; an If that selects the root `RR` runs once per re-iterated item."""+ graph = _sibling_reiterate_into_if(computed_condition, src=["a", "b"], levels=1, condition=False)++ runs = _collect_runs(graph, compatibility_scheduler, "out2")["out2"]++ assert runs == [((), ["RR", "RR", "RR"])]++[email protected]("computed_condition", [False, True], ids=["literal-condition", "computed-condition"])+def test_if_after_three_level_sibling_reiterate_keeps_sibling_value_once(+ computed_condition: bool, compatibility_scheduler: bool+) -> None:+ """One more Iterate level than the fuzz3-117 graph; the sibling value must not be read twice."""+ graph = _sibling_reiterate_into_if(computed_condition, src=[[[["c"]]]], levels=3)++ runs = _collect_runs(graph, compatibility_scheduler, "out2")["out2"]++ assert runs == [((), ["rnp"]), ((0, 0), ["ra:['c']"])]+++def _values(runs: Runs) -> list[AnyValue]:+ return _sorted_items([value for _, items in runs for value in items])+++def _sibling_reiterate_through_second_iterate(src: list[AnyValue], condition: str) -> Graph:+ """`out` holds each `src` list plus the sibling's `["p"]`; it is re-iterated twice (`rit`, then `rit2` over each+ list) and passed through an If whose condition is literal True or truthy per `rit2` item. (A root Boolean+ condition is rejected here: the false branch has no `rit2` axis.)"""+ per_item = condition == "per-item"+ condition_nodes: list[BaseInvocation] = [Truthy(id="cond")] if per_item else []+ condition_edges = "rit2.item -> cond.value\ncond.condition -> if.condition" if per_item else ""+ return _graph(+ src,+ 1,+ [+ Value(id="item"),+ Concat(id="sibling_src", first=[["p"]]),+ Iterate(id="sibling"),+ Value(id="sibling_value"),+ Collect(id="out"),+ Iterate(id="rit"),+ Concat(id="rcc"),+ Iterate(id="rit2"),+ Marked(id="re", marker="r"),+ Value(id="other", value="RR"),+ If(id="if", condition=True),+ Collect(id="out2"),+ *condition_nodes,+ ],+ """+ it0.item -> item.value+ item.value -> out.item+ sibling_src.collection -> sibling.collection+ sibling.item -> sibling_value.value+ sibling_value.value -> out.item+ out.collection -> rit.collection+ rit.item -> rcc.first+ rcc.collection -> rit2.collection+ rit2.item -> re.value+ re.value -> if.true_input+ other.value -> if.false_input+ if.value -> out2.item+ """+ + condition_edges,+ )+++ ("src", "expected"),+ [([["a", "b"], ["c"]], ["ra", "rb", "rc", "rp"]), ([[], ["c"]], ["rc", "rp"])],+ ids=["filled-lists", "empty-list"],+)[email protected]("condition", ["literal", "per-item"])+def test_if_after_sibling_reiterate_through_second_iterate_keeps_every_item(+ src: list[AnyValue], expected: list[AnyValue], condition: str, compatibility_scheduler: bool+) -> None:+ """The If always selects `rit2`'s item, so out2 holds what it would without the If. The empty-list case stalled or+ emptied every frame in some runs only (it depends on generated node ids), so it runs several times."""+ for _ in range(10):+ runs = _collect_runs(+ _sibling_reiterate_through_second_iterate(src, condition), compatibility_scheduler, "out2"+ )["out2"]++ assert _values(runs) == expected+++ ("src", "expected"),+ [([["a", "b"], ["c"]], ["ra", "rb", "rc", "rp"]), ([[], ["c"]], ["rc", "rp"])],+ ids=["filled-lists", "empty-list"],+)[email protected]("condition", ["literal", "per-item"])+def test_if_after_sibling_reiterate_through_second_iterate_keeps_every_item_after_reload(+ src: list[AnyValue], expected: list[AnyValue], condition: str, compatibility_scheduler: bool+) -> None:+ runs = _run_with_reload(+ _sibling_reiterate_through_second_iterate(src, condition), compatibility_scheduler, 12, "out2"+ )["out2"]++ assert _values(runs) == expected+++def _outer_and_nested_frames_into_root_if(computed_condition: bool) -> Graph:+ """`out` collects `it0`'s item and each nested `it1` item per `it0` frame (3 values, then 2); an If after+ re-iterating it selects the root `RR` value."""+ condition_node: list[BaseInvocation] = [BooleanInvocation(id="cond", value=False)] if computed_condition else []+ return _graph(+ [["x", "y"], ["z"]],+ 2,+ [+ Marked(id="outer", marker="o:"),+ Marked(id="inner", marker="i:"),+ Collect(id="out"),+ Iterate(id="rit"),+ Marked(id="re", marker="r"),+ Value(id="other", value="RR"),+ If(id="if", condition=False),+ Collect(id="out2"),+ *condition_node,+ ],+ """+ it0.item -> outer.value+ outer.value -> out.item+ it1.item -> inner.value+ inner.value -> out.item+ out.collection -> rit.collection+ rit.item -> re.value+ re.value -> if.true_input+ other.value -> if.false_input+ if.value -> out2.item+ """+ + ("cond.value -> if.condition" if computed_condition else ""),+ )+++def _root_if_through_passthrough(computed_condition: bool, nested: bool) -> Graph:+ graph = (+ _outer_and_nested_frames_into_root_if(computed_condition)+ if nested+ else _sibling_reiterate_into_if(computed_condition, src=["a", "b"], levels=1, condition=False)+ )+ graph.delete_edge(create_edge("if", "value", "out2", "item"))+ graph.add_node(Marked(id="middle", marker="P:"))+ graph.add_edge(create_edge("if", "value", "middle", "value"))+ graph.add_edge(create_edge("middle", "value", "out2", "item"))+ graph.validate_self()+ return graph++[email protected]("computed_condition", [False, True], ids=["literal-condition", "computed-condition"])[email protected](("nested", "expected_count"), [(False, 3), (True, 5)], ids=["flat", "nested"])[email protected]("reload", [False, True], ids=["fresh", "reload"])+def test_root_if_passthrough_preserves_reiterated_values(+ computed_condition: bool,+ nested: bool,+ expected_count: int,+ reload: bool,+ compatibility_scheduler: bool,+) -> None:+ graph = _root_if_through_passthrough(computed_condition, nested)+ runs = (+ _run_with_reload(graph, compatibility_scheduler, 12, "out2")+ if reload+ else _collect_runs(graph, compatibility_scheduler, "out2")+ )++ assert _values(runs["out2"]) == ["P:RR"] * expected_count++[email protected]("computed_condition", [False, True], ids=["literal-condition", "computed-condition"])+def test_root_if_after_reiterating_outer_and_nested_frames_runs_once_per_item(+ computed_condition: bool, compatibility_scheduler: bool+) -> None:+ """`rit` yields 5 items in all, so the If selects `RR` exactly 5 times."""+ runs = _collect_runs(_outer_and_nested_frames_into_root_if(computed_condition), compatibility_scheduler, "out2")[+ "out2"+ ]++ assert _values(runs) == ["RR"] * 5++[email protected]("computed_condition", [False, True], ids=["literal-condition", "computed-condition"])+def test_root_if_after_reiterating_outer_and_nested_frames_runs_once_per_item_after_reload(+ computed_condition: bool, compatibility_scheduler: bool+) -> None:+ runs = _run_with_reload(+ _outer_and_nested_frames_into_root_if(computed_condition), compatibility_scheduler, 12, "out2"+ )["out2"]++ assert _values(runs) == ["RR"] * 5+++def _root_sibling_in_second_reiterate_into_root_if(computed_condition: bool) -> Graph:+ """`rit` re-iterates `out` (2 frames). Inside each, `ita` items and a root-level `sibling` value feed `inner`, which+ `rit2` re-iterates: 4 items in all (`aa`, `ab`, `ac`, `sq`). An If after `rit2` selects the root `RR` value."""+ condition_node: list[BaseInvocation] = [BooleanInvocation(id="cond", value=False)] if computed_condition else []+ return _graph(+ [["a", "b"], ["c"]],+ 1,+ [+ Value(id="item"),+ Collect(id="out"),+ Iterate(id="rit"),+ Concat(id="rcc"),+ Iterate(id="ita"),+ Marked(id="nested", marker="a"),+ Concat(id="sibling_src", first=["q"]),+ Iterate(id="sibling"),+ Marked(id="sibling_value", marker="s"),+ Collect(id="inner"),+ Iterate(id="rit2"),+ Marked(id="re", marker="r"),+ Value(id="other", value="RR"),+ If(id="if", condition=False),+ Collect(id="out2"),+ *condition_node,+ ],+ """+ it0.item -> item.value+ item.value -> out.item+ out.collection -> rit.collection+ rit.item -> rcc.first+ rcc.collection -> ita.collection+ ita.item -> nested.value+ nested.value -> inner.item+ sibling_src.collection -> sibling.collection+ sibling.item -> sibling_value.value+ sibling_value.value -> inner.item+ inner.collection -> rit2.collection+ rit2.item -> re.value+ re.value -> if.true_input+ other.value -> if.false_input+ if.value -> out2.item+ """+ + ("cond.value -> if.condition" if computed_condition else ""),+ )++[email protected]("computed_condition", [False, True], ids=["literal-condition", "computed-condition"])+def test_root_if_after_root_sibling_in_second_reiterate_runs_once_per_item(+ computed_condition: bool, compatibility_scheduler: bool+) -> None:+ """`rit2` yields 4 items across frames at two depths, so the If selects `RR` exactly 4 times."""+ runs = _collect_runs(+ _root_sibling_in_second_reiterate_into_root_if(computed_condition), compatibility_scheduler, "out2"+ )["out2"]++ assert _values(runs) == ["RR"] * 4++[email protected]("computed_condition", [False, True], ids=["literal-condition", "computed-condition"])+def test_root_if_after_root_sibling_in_second_reiterate_runs_once_per_item_after_reload(+ computed_condition: bool, compatibility_scheduler: bool+) -> None:+ runs = _run_with_reload(+ _root_sibling_in_second_reiterate_into_root_if(computed_condition), compatibility_scheduler, 12, "out2"+ )["out2"]++ assert _values(runs) == ["RR"] * 4diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.pyindex 38a42f86ed..bde2123ad5 100644--- a/tests/app/services/shared/test_execution_engine_differential.py+++ b/tests/app/services/shared/test_execution_engine_differential.py@@ -6,6 +6,7 @@ import itertoolsimport jsonimport randomimport sys+from collections import Counterfrom itertools import productfrom pathlib import Pathfrom typing import Any, Callable@@ -43,6 +44,7 @@ from invokeai.app.services.shared.graph import (_ExecutionScheduler,_GenericGraphSchedulerAdapter,)+from invokeai.app.services.shared.graph_iterator_ancestry import _IteratorAncestryfrom invokeai.app.services.shared.graph_materializer import UnsupportedSharedIfCollectBranchesErrorfrom invokeai.app.services.shared.graph_nested_iterate_planner import get_nested_iterate_sequence_depthfrom invokeai.app.services.shared.invocation_context import InvocationContextData, build_invocation_context@@ -1494,6 +1496,17 @@ def _state_projection(state: GraphExecutionState) -> tuple[Any, ...]:)+def _assert_state_projection_matches_ignoring_execution_order(+ actual: GraphExecutionState,+ expected: GraphExecutionState,+) -> None:+ actual_projection = _state_projection(actual)+ expected_projection = _state_projection(expected)+ assert actual_projection[:3] == expected_projection[:3]+ assert Counter(actual_projection[3]) == Counter(expected_projection[3])+ assert actual_projection[4:] == expected_projection[4:]++def _activation_projection(state: GraphExecutionState) -> tuple[tuple[str, str, Any, tuple[int, ...]], ...]:"""Normalize activation tokens to source IDs and frame paths."""return tuple(@@ -1878,17 +1891,17 @@ def _expected_edge_projection("""Project the live execution graph for either scheduler adapter."""del force_compatibility_schedulerlive_edges = {("outer_condition", "value", "outer_if", "condition", "default")}- if outer_condition:- live_edges.add(("inner_condition", "value", "inner_if", "condition", "default"))- live_edges.add(- (- "inner_true" if inner_condition else "inner_false",- "value",- "inner_if",- "true_input" if inner_condition else "false_input",- "default",- )+ live_edges.add(("inner_condition", "value", "inner_if", "condition", "default"))+ live_edges.add(+ (+ "inner_true" if inner_condition else "inner_false",+ "value",+ "inner_if",+ "true_input" if inner_condition else "false_input",+ "default",)+ )+ if outer_condition:live_edges.add(("inner_if", "value", "outer_if", "true_input", "default"))else:live_edges.add(("outer_false", "value", "outer_if", "false_input", "default"))@@ -2034,25 +2047,61 @@ def test_static_dag_fresh_execution_has_matching_source_trace() -> None:(True,True,- {"outer_condition", "inner_condition", "inner_true", "inner_if", "outer_if", "sink"},+ {+ "outer_condition",+ "inner_condition",+ "inner_true",+ "inner_false",+ "inner_if",+ "outer_false",+ "outer_if",+ "sink",+ },5,),(True,False,- {"outer_condition", "inner_condition", "inner_false", "inner_if", "outer_if", "sink"},+ {+ "outer_condition",+ "inner_condition",+ "inner_true",+ "inner_false",+ "inner_if",+ "outer_false",+ "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,),],@@ -2096,8 +2145,7 @@ def test_nested_if_fresh_execution_matches_compatibility_scheduler(expected_activations = [("outer_if", "true_input" if outer_condition else "false_input"),]- if outer_condition:- expected_activations.append(("inner_if", "true_input" if inner_condition else "false_input"))+ expected_activations.append(("inner_if", "true_input" if inner_condition else "false_input"))expected_activation_projection = tuple(sorted((*activation, activation[1], ()) for activation in expected_activations))@@ -3329,19 +3377,19 @@ def _for_output_iterate_branch_graph(condition: bool) -> Graph:[_collected_iterate_branch_graph, _doubly_collected_nested_iterate_branch_graph, _for_output_iterate_branch_graph],ids=["one-collect", "two-collects", "for-output"],)-def test_literal_if_rejecting_closed_iterate_branch_completes(build_graph: Callable[[bool], Graph]) -> None:- """A literal If does not wait for an Iterate that closes on its rejected branch, which never runs (#9484)."""+def test_literal_if_eagerly_runs_closed_iterate_branch_and_completes(build_graph: Callable[[bool], Graph]) -> None:+ """A non-candidate If runs both branches after its condition gate, including a closed Iterate branch."""graph = build_graph(False)graph.validate_self()trace, state = _run(GraphExecutionState(graph=graph))- # This shape is outside the generic scheduler's supported set.+ # This shape is outside both lazy candidates, so the closed branch is admitted eagerly.assert isinstance(state._execution_scheduler, _ExecutionScheduler)assert state.is_complete(), f"execution stalled after {trace}"sink_exec_ids = state._prepared_registry().get_prepared_ids("sink")assert [state.results[exec_id].value for exec_id in sink_exec_ids] == [["fallback"]]- assert not {"for", "return", "iterate", "body", "collect"} & set(trace)+ assert {"for", "return", "iterate", "body", "collect"} & set(trace)def _per_item_for_output_collect_branch_graph() -> Graph:@@ -3384,9 +3432,131 @@ def test_literal_if_selecting_collect_of_for_output_runs_per_outer_item() -> Non} == {(0,): [["a", "b"]], (1,): [["c"]]}[email protected]("condition", [True, False], ids=["true", "false"])[email protected]("passthrough", [False, True], ids=["direct", "passthrough"])[email protected]("condition_passthrough", [False, True], ids=["direct-condition", "boolean-condition"])[email protected]("force_compatibility_scheduler", [False, True], ids=["default", "compatibility"])+def test_root_condition_selects_between_nested_for_final_branches(+ condition: bool, passthrough: bool, condition_passthrough: bool, force_compatibility_scheduler: bool+) -> None:+ nodes: list[Any] = [+ CollectionConcatInvocation(id="source", first=[[["a", "b"], ["c"]], [["d"]]]),+ IterateInvocation(id="outer"),+ CollectionConcatInvocation(id="inner_source", first=[]),+ IterateInvocation(id="inner"),+ FixedCollectionTestInvocation(id="condition", value=condition),+ IfInvocation(id="if"),+ CollectInvocation(id="inner_collect"),+ CollectInvocation(id="outer_collect"),+ ]+ edges: list[Any] = [+ ("source", "collection", "outer", "collection"),+ ("outer", "item", "inner_source", "first"),+ ("inner_source", "collection", "inner", "collection"),+ ("if", "value", "inner_collect", "item"),+ ("inner_collect", "collection", "outer_collect", "item"),+ ]+ if condition_passthrough:+ nodes.append(BooleanInvocation(id="condition_passthrough"))+ edges += [+ ("condition", "condition", "condition_passthrough", "value"),+ ("condition_passthrough", "value", "if", "condition"),+ ]+ else:+ edges.append(("condition", "condition", "if", "condition"))+ for prefix, branch in (("yes", "true_input"), ("no", "false_input")):+ nodes += [+ ForInvocation(id=f"{prefix}_for"),+ MarkedAnyTypeTestInvocation(id=f"{prefix}_body", marker=f"{prefix}:"),+ ForReturnInvocation(id=f"{prefix}_return"),+ ]+ edges += [+ ("inner", "item", f"{prefix}_for", "collection"),+ (f"{prefix}_for", "item", f"{prefix}_body", "value"),+ (f"{prefix}_body", "value", f"{prefix}_return", "output"),+ create_loop_linkage(f"{prefix}_for", f"{prefix}_return"),+ ]+ if passthrough:+ nodes.append(AnyTypeTestInvocation(id=f"{prefix}_pass"))+ edges += [+ (f"{prefix}_for", "output_collection", f"{prefix}_pass", "value"),+ (f"{prefix}_pass", "value", "if", branch),+ ]+ else:+ edges.append((f"{prefix}_for", "output_collection", "if", branch))+ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )++ assert not state.has_error(), state.errors+ assert state.is_complete(), f"graph stalled after {trace}"+ marker = "yes:" if condition else "no:"+ assert _source_values(state, "outer_collect") == {+ (): [[[f"{marker}a", f"{marker}b"], [f"{marker}c"]], [[f"{marker}d"]]]+ }+ selected, rejected = ("yes", "no") if condition else ("no", "yes")+ assert f"{selected}_for" in trace+ assert f"{rejected}_for" in trace++[email protected]("condition_passthrough", [False, True], ids=["direct-condition", "boolean-condition"])[email protected]("force_compatibility_scheduler", [False, True], ids=["default", "compatibility"])+def test_for_final_collect_closes_inner_axis_beyond_condition_frame(+ condition_passthrough: bool, force_compatibility_scheduler: bool+) -> None:+ nodes: list[Any] = [+ CollectionConcatInvocation(id="source", first=[[["a", "b"], ["c"]], [["d"]]]),+ IterateInvocation(id="outer"),+ FixedCollectionTestInvocation(id="condition_source"),+ CollectionConcatInvocation(id="inner_source"),+ IterateInvocation(id="inner"),+ IfInvocation(id="if"),+ CollectInvocation(id="inner_collect"),+ CollectInvocation(id="outer_collect"),+ ]+ edges: list[Any] = [+ ("source", "collection", "outer", "collection"),+ ("outer", "item", "condition_source", "value"),+ ("outer", "item", "inner_source", "first"),+ ("inner_source", "collection", "inner", "collection"),+ ("condition_source", "condition", "if", "condition"),+ ("if", "value", "inner_collect", "item"),+ ("inner_collect", "collection", "outer_collect", "item"),+ ]+ if condition_passthrough:+ nodes.append(BooleanInvocation(id="condition"))+ edges.remove(("condition_source", "condition", "if", "condition"))+ edges += [+ ("condition_source", "condition", "condition", "value"),+ ("condition", "value", "if", "condition"),+ ]+ for prefix, branch in (("yes", "true_input"), ("no", "false_input")):+ nodes += [+ ForInvocation(id=f"{prefix}_for"),+ MarkedAnyTypeTestInvocation(id=f"{prefix}_body", marker=f"{prefix}:"),+ ForReturnInvocation(id=f"{prefix}_return"),+ ]+ edges += [+ ("inner", "item", f"{prefix}_for", "collection"),+ (f"{prefix}_for", "item", f"{prefix}_body", "value"),+ (f"{prefix}_body", "value", f"{prefix}_return", "output"),+ create_loop_linkage(f"{prefix}_for", f"{prefix}_return"),+ (f"{prefix}_for", "output_collection", "if", branch),+ ]+ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )++ assert state.is_complete(), trace+ assert not state.has_error(), state.errors+ assert _source_values(state, "outer_collect") == {(): [[["yes:a", "yes:b"], ["yes:c"]], [["yes:d"]]]}++@pytest.mark.parametrize("fail_unselected", [False, True], ids=["succeeds", "unselected-fails"])-def test_per_item_if_does_not_run_for_output_branch_for_unselected_item(fail_unselected: bool) -> None:- """A For whose final output is collected into one If branch runs, with its body, only for selecting items."""+def test_per_item_if_eagerly_runs_for_output_branch_for_every_item(fail_unselected: bool) -> None:+ """A loop-containing If is eager, so failure in an unselected item branch fails the execution."""graph = Graph()graph.add_node(CollectionConcatInvocation(id="outer_source", first=["", "x"]))graph.add_node(IterateInvocation(id="outer_iterate"))@@ -3423,11 +3593,16 @@ def test_per_item_if_does_not_run_for_output_branch_for_unselected_item(fail_unscontinuestate.complete(node.id, node.invoke(Mock()))- # This shape is outside the generic scheduler's supported set.+ # This shape is outside both lazy candidates.assert isinstance(state._execution_scheduler, _ExecutionScheduler)+ assert any(entry[0] in unselected_sources and entry[1][:1] == (0,) for entry in trace)+ if fail_unselected:+ assert state.has_error(), state.errors+ assert state.is_complete()+ assert any("ran for an unselected item" in error for error in state.errors.values())+ returnassert not state.has_error(), state.errorsassert state.is_complete(), f"execution stalled after {trace}"- assert not [entry for entry in trace if entry[0] in unselected_sources and entry[1][:1] == (0,)]assert {source_id for source_id, path in trace if path[:1] == (1,)} >= {"for", "body", "collect"}assert {state._get_iteration_path(exec_id): state.results[exec_id].value@@ -3500,16 +3675,21 @@ def test_if_in_for_body_rejecting_nested_for_branch_completes(computed_condition@pytest.mark.parametrize(- ("condition", "computed_condition"),- [(True, True), (False, False), (False, True)],- ids=["computed-True", "literal-False", "computed-False"],+ ("condition", "computed_condition", "source_data"),+ [+ (True, True, [["a", "b"], ["c"]]),+ (False, False, [["a", "b"], ["c"]]),+ (False, True, [["a", "b"], ["c"]]),+ (False, True, []),+ ],+ ids=["computed-True", "literal-False", "computed-False", "computed-False-empty-source"],)def test_root_condition_if_with_for_output_branch_under_iterate_completes(- condition: bool, computed_condition: bool+ condition: bool, computed_condition: bool, source_data: list[list[str]]) -> None:- """The Iterate a branch For runs under is not gated by the If, and the rejected For never runs."""+ """Both branch producers run when a frame exists; empty Iterates leave no frame to admit."""nodes = [- CollectionConcatInvocation(id="src", first=[["a", "b"], ["c"]]),+ CollectionConcatInvocation(id="src", first=source_data),IterateInvocation(id="iterate"),ForInvocation(id="for"),MarkedAnyTypeTestInvocation(id="body", marker="b:"),@@ -3536,920 +3716,2105 @@ def test_root_condition_if_with_for_output_branch_under_iterate_completes(trace, state = _run_to_completion(_graph_from(nodes, edges))- # Selecting the root value keeps main's single root-frame If; selected-branch cardinality is decided separately.expected = [["b:a", "b:b"], ["b:c"]] if condition else ["fb"]assert _source_values(state, "collect") == {(): expected}- if not condition:+ if source_data:+ assert {"for", "body", "ret", "mid"} <= set(trace)+ else:assert not {"for", "body", "ret", "mid"} & set(trace)[email protected]("condition", [True, False])-def test_literal_if_with_empty_nested_iterate_on_a_branch_has_no_frames(condition: bool) -> None:- """An open Iterate with no items gives the If no frame, whichever branch the literal condition selects."""+def test_computed_root_if_selecting_root_value_over_unselected_for_emits_one_result() -> None:graph = _graph_from([- CollectionConcatInvocation(id="src", first=[[], []]),- IterateInvocation(id="outer"),- CollectionConcatInvocation(id="inner_src", first=[]),- IterateInvocation(id="inner"),- MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),- MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),- IfInvocation(id="if", condition=condition),- CollectInvocation(id="collect"),- ],- [- ("src", "collection", "outer", "collection"),- ("outer", "item", "inner_src", "first"),- ("inner_src", "collection", "inner", "collection"),- ("inner", "item", "true_value", "value"),- ("true_value", "value", "if", "true_input"),- ("outer", "item", "false_value", "value"),- ("false_value", "value", "if", "false_input"),- ("if", "value", "collect", "item"),- ],- )-- trace, state = _run_to_completion(graph)-- assert _source_values(state, "collect") == {(0,): [], (1,): []}- assert "if" not in trace---def _unrelated_open_branches_graph(condition: bool, computed_condition: bool) -> Graph:- nodes = [- CollectionConcatInvocation(id="true_src", first=[1, 2]),- IterateInvocation(id="true_iterate"),- CollectionConcatInvocation(id="false_src", first=[10, 20, 30]),- IterateInvocation(id="false_iterate"),- IfInvocation(id="if", condition=condition),- CollectInvocation(id="collect"),- ]- edges = [- ("true_src", "collection", "true_iterate", "collection"),- ("false_src", "collection", "false_iterate", "collection"),- ("true_iterate", "item", "if", "true_input"),- ("false_iterate", "item", "if", "false_input"),- ("if", "value", "collect", "item"),- ]- if computed_condition:- nodes.append(FixedCollectionTestInvocation(id="condition", value=condition))- edges.append(("condition", "condition", "if", "condition"))- return _graph_from(nodes, edges)---def _root_condition_with_deeper_axis_on_one_branch_graph(outer_values: list[list[str]]) -> Graph:- return _graph_from(- [- CollectionConcatInvocation(id="src", first=outer_values),- IterateInvocation(id="outer"),- CollectionConcatInvocation(id="inner_src", first=[]),- IterateInvocation(id="inner"),- MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),- MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),- FixedCollectionTestInvocation(id="condition", value=False),+ CollectionConcatInvocation(id="src", first=[["c"], ["d"], ["e"]]),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ MarkedAnyTypeTestInvocation(id="body", marker="F"),+ ForReturnInvocation(id="ret"),+ AnyTypeTestInvocation(id="root", value="R"),+ BooleanInvocation(id="condition", value=True),IfInvocation(id="if"),CollectInvocation(id="collect"),],[- ("src", "collection", "outer", "collection"),- ("outer", "item", "inner_src", "first"),- ("inner_src", "collection", "inner", "collection"),- ("inner", "item", "true_value", "value"),- ("true_value", "value", "if", "true_input"),- ("outer", "item", "false_value", "value"),- ("false_value", "value", "if", "false_input"),- ("condition", "condition", "if", "condition"),+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("root", "value", "if", "true_input"),+ ("for", "output_collection", "if", "false_input"),+ ("condition", "value", "if", "condition"),("if", "value", "collect", "item"),],)+ trace, state = _run_graph(GraphExecutionState(graph=graph), force_compatibility_scheduler=True)-def _per_item_condition_with_deeper_collect_branch_graph() -> Graph:- return _graph_from(- [- CollectionConcatInvocation(id="src", first=["x", "y"]),- IterateInvocation(id="outer"),- FixedCollectionTestInvocation(id="middle_src"),- IterateInvocation(id="middle"),- FixedCollectionTestInvocation(id="inner_src"),- IterateInvocation(id="inner"),- MarkedAnyTypeTestInvocation(id="body", marker="b:"),- CollectInvocation(id="branch_collect"),- AnyTypeTestInvocation(id="fallback", value="fb"),- FixedCollectionTestInvocation(id="condition"),- IfInvocation(id="if"),- CollectInvocation(id="collect"),- ],- [- ("src", "collection", "outer", "collection"),- ("outer", "item", "middle_src", "value"),- ("middle_src", "collection", "middle", "collection"),- ("middle", "item", "inner_src", "value"),- ("inner_src", "collection", "inner", "collection"),- ("inner", "item", "body", "value"),- ("body", "value", "branch_collect", "item"),- ("branch_collect", "collection", "if", "true_input"),- ("outer", "item", "fallback", "value"),- ("fallback", "value", "if", "false_input"),- ("outer", "item", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("if", "value", "collect", "item"),- ],- )+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {(): ["R"]}+ assert trace.count("if") == 1+ assert {"for", "body", "ret"} <= set(trace)-def _per_item_condition_with_deeper_for_output_collect_branch_graph() -> Graph:- return _graph_from(+def test_computed_root_if_selecting_root_value_over_empty_unselected_for_emits_one_result() -> None:+ graph = _graph_from([- CollectionConcatInvocation(id="src", first=["", "x"]),- IterateInvocation(id="outer"),- FixedCollectionTestInvocation(id="condition"),- FixedCollectionTestInvocation(id="inner_src"),- IterateInvocation(id="inner"),- FixedCollectionTestInvocation(id="items"),+ CollectionConcatInvocation(id="src", first=[]),+ IterateInvocation(id="iterate"),ForInvocation(id="for"),- MarkedAnyTypeTestInvocation(id="body", marker="b:"),+ MarkedAnyTypeTestInvocation(id="body", marker="F"),ForReturnInvocation(id="ret"),- CollectInvocation(id="branch_collect"),- MarkedAnyTypeTestInvocation(id="fallback", marker="f:"),+ AnyTypeTestInvocation(id="root", value="R"),+ BooleanInvocation(id="condition", value=True),IfInvocation(id="if"),CollectInvocation(id="collect"),],[- ("src", "collection", "outer", "collection"),- ("outer", "item", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("outer", "item", "inner_src", "value"),- ("inner_src", "collection", "inner", "collection"),- ("inner", "item", "items", "value"),- ("items", "collection", "for", "collection"),+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),("for", "item", "body", "value"),("body", "value", "ret", "output"),create_loop_linkage("for", "ret"),- ("for", "output_collection", "branch_collect", "item"),- ("branch_collect", "collection", "if", "true_input"),- ("outer", "item", "fallback", "value"),- ("fallback", "value", "if", "false_input"),+ ("root", "value", "if", "true_input"),+ ("for", "output_collection", "if", "false_input"),+ ("condition", "value", "if", "condition"),("if", "value", "collect", "item"),],)+ trace, state = _run_graph(GraphExecutionState(graph=graph), force_compatibility_scheduler=True)-def _cross_product_branch_graph(condition: bool, condition_from_branch: bool = False) -> Graph:- nodes = [- CollectionConcatInvocation(id="left_src", first=[1, 2]),- IterateInvocation(id="left"),- CollectionConcatInvocation(id="right_src", first=[10, 20, 30]),- IterateInvocation(id="right"),- AddInvocation(id="add"),- AnyTypeTestInvocation(id="fallback", value=0),- IfInvocation(id="if", condition=condition),+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {(): ["R"]}+ assert trace.count("if") == 1+ assert not {"for", "body", "ret"} & set(trace)+++def test_literal_nested_if_collect_preserves_sibling_collection_input() -> None:+ nodes = [+ CollectionConcatInvocation(id="src", first=[["a"], ["b"]]),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="body"),+ ForReturnInvocation(id="ret"),+ BooleanInvocation(id="inner_condition", value=True),+ IfInvocation(id="inner"),+ AnyTypeTestInvocation(id="inner_fallback", value="inner"),+ IfInvocation(id="outer", condition=True),+ AnyTypeTestInvocation(id="outer_fallback", value="outer"),+ CollectionConcatInvocation(id="sibling_collection", first=["sibling"]),CollectInvocation(id="collect"),]edges = [- ("left_src", "collection", "left", "collection"),- ("right_src", "collection", "right", "collection"),- ("left", "item", "add", "a"),- ("right", "item", "add", "b"),- ("add", "value", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "collect", "item"),+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "inner", "true_input"),+ ("inner_fallback", "value", "inner", "false_input"),+ ("inner_condition", "value", "inner", "condition"),+ ("inner", "value", "outer", "true_input"),+ ("outer_fallback", "value", "outer", "false_input"),+ ("outer", "value", "collect", "item"),+ ("sibling_collection", "collection", "collect", "collection"),]- if condition_from_branch:- nodes.append(FixedCollectionTestInvocation(id="condition"))- edges += [("add", "value", "condition", "value"), ("condition", "condition", "if", "condition")]- return _graph_from(nodes, edges)+ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=True,+ )+ assert not state.has_error(), trace+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {+ (0,): ["sibling", ["a"]],+ (1,): ["sibling", ["b"]],+ }-def _collect_then_reopen_graph(- condition: bool, extra_items: tuple[str, ...] = (), appended_items: tuple[str, ...] = ()-) -> Graph:+[email protected]("computed_outer_condition", [False, True], ids=["literal-outer", "computed-outer"])+def test_empty_literal_nested_if_collect_with_sibling_collection_completes(+ computed_outer_condition: bool,+) -> None:nodes = [- CollectionConcatInvocation(id="src", first=["a1", "a2"]),- IterateInvocation(id="first"),- MarkedAnyTypeTestInvocation(id="body", marker="b:"),- CollectInvocation(id="closing_collect"),- IterateInvocation(id="second"),- MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),- MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),- IfInvocation(id="if", condition=condition),+ CollectionConcatInvocation(id="src", first=[]),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="body"),+ ForReturnInvocation(id="ret"),+ BooleanInvocation(id="inner_condition", value=True),+ IfInvocation(id="inner"),+ AnyTypeTestInvocation(id="inner_fallback", value="inner"),+ IfInvocation(id="outer", condition=True),+ AnyTypeTestInvocation(id="outer_fallback", value="outer"),+ CollectionConcatInvocation(id="sibling_collection", first=["sibling"]),CollectInvocation(id="collect"),]+ if computed_outer_condition:+ nodes.insert(-4, BooleanInvocation(id="outer_condition", value=True))edges = [- ("src", "collection", "first", "collection"),- ("first", "item", "body", "value"),- ("body", "value", "closing_collect", "item"),- ]- if appended_items:- nodes.append(CollectionConcatInvocation(id="appended", first=list(appended_items)))- edges.append(("appended", "collection", "closing_collect", "collection"))- if extra_items:- nodes.append(CollectionConcatInvocation(id="extend", second=list(extra_items)))- edges += [- ("closing_collect", "collection", "extend", "first"),- ("extend", "collection", "second", "collection"),- ]- else:- edges.append(("closing_collect", "collection", "second", "collection"))- edges += [- ("second", "item", "true_value", "value"),- ("true_value", "value", "if", "true_input"),- ("first", "item", "false_value", "value"),- ("false_value", "value", "if", "false_input"),- ("if", "value", "collect", "item"),+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "inner", "true_input"),+ ("inner_fallback", "value", "inner", "false_input"),+ ("inner_condition", "value", "inner", "condition"),+ ("inner", "value", "outer", "true_input"),+ ("outer_fallback", "value", "outer", "false_input"),+ ("outer", "value", "collect", "item"),+ ("sibling_collection", "collection", "collect", "collection"),]- return _graph_from(nodes, edges)+ if computed_outer_condition:+ edges.insert(-3, ("outer_condition", "value", "outer", "condition"))+ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=True,+ )+ assert not state.has_error(), trace+ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.source_prepared_mapping.get("outer")+ assert _source_values(state, "collect") == {(): ["sibling"]}-def _collect_with_literal_items_then_reopen_graph() -> Graph:- graph = _collect_then_reopen_graph(True)- graph.get_node("closing_collect").collection = ["x"]- return graph+def test_literal_nested_if_collect_preserves_all_sibling_iterate_items() -> None:+ nodes = [+ CollectionConcatInvocation(id="src", first=[["a", "b"], ["c", "d"]]),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="body"),+ ForReturnInvocation(id="ret"),+ BooleanInvocation(id="inner_condition", value=True),+ IfInvocation(id="inner"),+ AnyTypeTestInvocation(id="inner_fallback", value="inner"),+ IfInvocation(id="outer", condition=True),+ AnyTypeTestInvocation(id="outer_fallback", value="outer"),+ IterateInvocation(id="sibling_iterate"),+ AnyTypeTestInvocation(id="sibling_value"),+ CollectInvocation(id="collect"),+ ]+ edges = [+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "inner", "true_input"),+ ("inner_fallback", "value", "inner", "false_input"),+ ("inner_condition", "value", "inner", "condition"),+ ("inner", "value", "outer", "true_input"),+ ("outer_fallback", "value", "outer", "false_input"),+ ("outer", "value", "collect", "item"),+ ("for", "output_collection", "sibling_iterate", "collection"),+ ("sibling_iterate", "item", "sibling_value", "value"),+ ("sibling_value", "value", "collect", "item"),+ ]+ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=True,+ )++ assert not state.has_error(), trace+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {+ (0,): [["a", "b"], "a", "b"],+ (1,): [["c", "d"], "c", "d"],+ }-def _collect_of_collect_reopen_graph(- groups: list[list[str]], unselected_axis: str, extra_collect: bool = False, append_unrelated_axis: bool = False-) -> Graph:- """An Iterate reopens a Collect of per-group Collects, so its frames are the groups of the outer axis."""- nodes: list[Any] = [- CollectionConcatInvocation(id="groups_src", first=groups),- IterateInvocation(id="group"),- CollectionConcatInvocation(id="members_src"),- IterateInvocation(id="member"),- MarkedAnyTypeTestInvocation(id="body", marker="b:"),- CollectInvocation(id="group_collect"),- CollectInvocation(id="closing_collect"),- IterateInvocation(id="reopened"),- MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),- MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),- IfInvocation(id="if", condition=True),+[email protected]("reverse_collect_items", [False, True], ids=["first-narrow", "first-wide"])+def test_nested_literal_if_collect_uses_union_of_item_frame_paths(reverse_collect_items: bool) -> None:+ nodes = [+ CollectionConcatInvocation(id="src", first=[[], ["a"]]),+ IterateInvocation(id="outer_iterate"),+ PolymorphicStringTestInvocation(id="inner_collection"),+ IterateInvocation(id="inner_iterate"),+ FixedCollectionTestInvocation(id="for_collection"),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="body", value="for"),+ ForReturnInvocation(id="ret"),+ IfInvocation(id="first_inner", condition=True),+ AnyTypeTestInvocation(id="first_inner_fallback", value="first-inner-fallback"),+ IfInvocation(id="first_outer", condition=True),+ AnyTypeTestInvocation(id="first_outer_fallback", value="first-outer-fallback"),+ IfInvocation(id="second_inner", condition=True),+ AnyTypeTestInvocation(id="second_inner_fallback", value="second-inner-fallback"),+ IfInvocation(id="second_outer", condition=True),+ AnyTypeTestInvocation(id="second_outer_fallback", value="second-outer-fallback"),CollectInvocation(id="collect"),]- edges: list[Any] = [- ("groups_src", "collection", "group", "collection"),- ("group", "item", "members_src", "first"),- ("members_src", "collection", "member", "collection"),- ("member", "item", "body", "value"),- ("body", "value", "group_collect", "item"),- ("group_collect", "collection", "closing_collect", "item"),+ edges = [+ ("src", "collection", "outer_iterate", "collection"),+ ("outer_iterate", "item", "inner_collection", "value"),+ ("inner_collection", "collection", "inner_iterate", "collection"),+ ("inner_iterate", "item", "for_collection", "value"),+ ("for_collection", "collection", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "first_inner", "true_input"),+ ("first_inner_fallback", "value", "first_inner", "false_input"),+ ("first_inner", "value", "first_outer", "true_input"),+ ("first_outer_fallback", "value", "first_outer", "false_input"),+ ("outer_iterate", "item", "second_inner", "true_input"),+ ("second_inner_fallback", "value", "second_inner", "false_input"),+ ("second_inner", "value", "second_outer", "true_input"),+ ("second_outer_fallback", "value", "second_outer", "false_input"),]- if append_unrelated_axis:- nodes += [- CollectionConcatInvocation(id="appended_src", first=[["v1"], ["v2"], ["v3"]]),- IterateInvocation(id="appended"),- CollectionConcatInvocation(id="appended_items"),- ]- edges += [- ("appended_src", "collection", "appended", "collection"),- ("appended", "item", "appended_items", "first"),- ("appended_items", "collection", "group_collect", "collection"),- ]- if extra_collect:- nodes.append(CollectInvocation(id="outer_collect"))- edges += [- ("closing_collect", "collection", "outer_collect", "item"),- ("outer_collect", "collection", "reopened", "collection"),- ]- else:- edges.append(("closing_collect", "collection", "reopened", "collection"))- edges += [- ("reopened", "item", "true_value", "value"),- ("true_value", "value", "if", "true_input"),- (unselected_axis, "item", "false_value", "value"),- ("false_value", "value", "if", "false_input"),- ("if", "value", "collect", "item"),+ collect_item_edges = [+ ("first_outer", "value", "collect", "item"),+ ("second_outer", "value", "collect", "item"),]- return _graph_from(nodes, edges)+ if reverse_collect_items:+ collect_item_edges.reverse()+ edges.extend(collect_item_edges)+ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=True,+ )+ assert not state.has_error(), trace+ assert state.is_complete(), f"graph stalled after {trace}"+ assert len(state.source_prepared_mapping["collect"]) == 2+ assert set(_source_values(state, "collect")) == {(0,), (1, 0)}+ assert _source_values(state, "collect") == {+ (0,): [[]],+ (1, 0): [["a"], [0, 1]],+ }-def _per_item_condition_with_collect_of_collects_branch_graph() -> Graph:- """A per-item condition on the outer axis chooses between a Collect over a deeper axis and a Collect of one."""- nodes: list[Any] = [- CollectionConcatInvocation(id="src", first=[[[["a"], ["b"]], [["c"]]], [[["x"]], []], [[["d", "e"]]]]),- ]- edges: list[Any] = []- previous = ("src", "collection")- for axis_id in ("outer", "middle", "deep", "inner"):- nodes.append(IterateInvocation(id=axis_id))- edges.append((*previous, axis_id, "collection"))- if axis_id != "inner":- nodes.append(CollectionConcatInvocation(id=f"{axis_id}_items"))- edges.append((axis_id, "item", f"{axis_id}_items", "first"))- previous = (f"{axis_id}_items", "collection")- nodes += [- MarkedAnyTypeTestInvocation(id="inner_body", marker="b:"),- CollectInvocation(id="inner_collect"),- CollectInvocation(id="deep_collect"),- MarkedAnyTypeTestInvocation(id="deep_body", marker="n:"),- CollectInvocation(id="deep_item_collect"),- FixedCollectionTestInvocation(id="condition"),- IfInvocation(id="if"),+[email protected]("computed_inner_condition", [False, True], ids=["literal-inner", "computed-inner"])[email protected]("inner_condition", [False, True], ids=["inner-false", "inner-true"])[email protected]("source_data", [[], [["a"], ["b"]]], ids=["empty", "nonempty"])+def test_nested_root_if_preserves_output_with_empty_unselected_for_branch(+ computed_inner_condition: bool,+ inner_condition: bool,+ source_data: list[list[str]],+) -> None:+ """Nested selected-branch cardinality is outside the README's direct root-If promise."""+ nodes = [+ CollectionConcatInvocation(id="src", first=source_data),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="body"),+ ForReturnInvocation(id="ret"),+ AnyTypeTestInvocation(id="inner_fallback", value="inner"),+ IfInvocation(id="inner", condition=inner_condition),+ AnyTypeTestInvocation(id="outer_fallback", value="outer"),+ BooleanInvocation(id="outer_condition", value=True),+ IfInvocation(id="outer"),CollectInvocation(id="collect"),]- edges += [- ("inner", "item", "inner_body", "value"),- ("inner_body", "value", "inner_collect", "item"),- ("inner_collect", "collection", "deep_collect", "item"),- ("deep", "item", "deep_body", "value"),- ("deep_body", "value", "deep_item_collect", "item"),- ("outer", "index", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("deep_item_collect", "collection", "if", "true_input"),- ("deep_collect", "collection", "if", "false_input"),- ("if", "value", "collect", "item"),+ edges = [+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "inner", "true_input"),+ ("inner_fallback", "value", "inner", "false_input"),+ ("inner", "value", "outer", "true_input"),+ ("outer_fallback", "value", "outer", "false_input"),+ ("outer_condition", "value", "outer", "condition"),+ ("outer", "value", "collect", "item"),]- return _graph_from(nodes, edges)+ if computed_inner_condition:+ nodes.append(BooleanInvocation(id="inner_condition", value=inner_condition))+ edges.append(("inner_condition", "value", "inner", "condition"))--def _reopen_of_a_cross_product_graph(swap_add_inputs: bool, condition: bool = False) -> Graph:- """A literal If chooses between an Iterate reopening a Collect over two crossed axes and the crossed inner axis."""- first_axis, second_axis = ("right", "left") if swap_add_inputs else ("left", "right")- return _graph_from(- [- CollectionConcatInvocation(id="left_src", first=[1, 2]),- IterateInvocation(id="left"),- CollectionConcatInvocation(id="right_src", first=[10, 20, 30]),- IterateInvocation(id="right"),- AddInvocation(id="add"),- CollectInvocation(id="closing_collect"),- IterateInvocation(id="reopened"),- MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),- MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),- IfInvocation(id="if", condition=condition),- CollectInvocation(id="collect"),- ],- [- ("left_src", "collection", "left", "collection"),- ("right_src", "collection", "right", "collection"),- (first_axis, "item", "add", "a"),- (second_axis, "item", "add", "b"),- ("add", "value", "closing_collect", "item"),- ("closing_collect", "collection", "reopened", "collection"),- ("reopened", "item", "true_value", "value"),- ("true_value", "value", "if", "true_input"),- (second_axis, "item", "false_value", "value"),- ("false_value", "value", "if", "false_input"),- ("if", "value", "collect", "item"),- ],+ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=True,)--def _reopen_of_a_different_closed_axis_graph() -> Graph:- return _graph_from(+ assert not state.has_error(), trace+ assert state.is_complete(), f"graph stalled after {trace}"+ if source_data:+ assert {"for", "body", "ret"} <= set(trace)+ assert all(state.source_prepared_mapping.get(node_id) for node_id in ("for", "body", "ret"))+ assert state.source_prepared_mapping.get("outer")+ else:+ assert not {"for", "body", "ret"} & set(trace)+ assert all(not state.source_prepared_mapping.get(node_id) for node_id in ("for", "body", "ret"))+ expected = (+ {(): []}+ if inner_condition and not source_data+ else {(0,): [["a"]], (1,): [["b"]]}+ if inner_condition and computed_inner_condition+ else {(): [["a"], ["b"]]}+ if inner_condition+ else {(): ["inner"]}+ )+ assert _source_values(state, "collect") == expected+ if inner_condition and source_data:+ for node_id in ("inner", "outer"):+ assert sorted(state._get_iteration_path(exec_id) for exec_id in state.source_prepared_mapping[node_id]) == (+ [(0,), (1,)]+ )++[email protected]("outer_computed", [False, True], ids=["literal-outer", "computed-outer"])[email protected]("source_data", [[], [["a"], ["b"]]], ids=["empty", "nonempty"])+def test_literal_and_computed_outer_if_match_empty_nested_selection(+ outer_computed: bool,+ source_data: list[list[str]],+) -> None:+ nodes = [+ CollectionConcatInvocation(id="src", first=source_data),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="body"),+ ForReturnInvocation(id="ret"),+ BooleanInvocation(id="inner_condition", value=True),+ IfInvocation(id="inner"),+ AnyTypeTestInvocation(id="inner_fallback", value="inner"),+ IfInvocation(id="outer", condition=True),+ AnyTypeTestInvocation(id="outer_fallback", value="outer"),+ CollectInvocation(id="collect"),+ ]+ edges = [+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "inner", "true_input"),+ ("inner_fallback", "value", "inner", "false_input"),+ ("inner_condition", "value", "inner", "condition"),+ ("inner", "value", "outer", "true_input"),+ ("outer_fallback", "value", "outer", "false_input"),+ ("outer", "value", "collect", "item"),+ ]+ if outer_computed:+ nodes.append(BooleanInvocation(id="outer_condition", value=True))+ edges.append(("outer_condition", "value", "outer", "condition"))++ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=True,+ )++ assert not state.has_error(), trace+ assert state.is_complete(), (+ f"graph stalled after {trace}; executed={state.executed}; mappings={state.source_prepared_mapping}"+ )+ if not source_data:+ assert not state.source_prepared_mapping.get("outer")+ assert _source_values(state, "collect") == ({(): []} if not source_data else {(0,): [["a"]], (1,): [["b"]]})++[email protected]("source_data", [[], [["a"], ["b"]]], ids=["empty", "nonempty"])+def test_three_level_computed_if_chain_preserves_for_frames(+ source_data: list[list[str]],+) -> None:+ """Compatibility fallback guard; this nested selected-branch shape is outside direct root-If cardinality guarantees."""+ nodes = [+ CollectionConcatInvocation(id="src", first=source_data),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="body"),+ ForReturnInvocation(id="ret"),+ BooleanInvocation(id="deep_condition", value=True),+ IfInvocation(id="deep"),+ BooleanInvocation(id="middle_condition", value=True),+ IfInvocation(id="middle"),+ BooleanInvocation(id="outer_condition", value=True),+ IfInvocation(id="outer"),+ AnyTypeTestInvocation(id="deep_fallback", value="deep"),+ AnyTypeTestInvocation(id="middle_fallback", value="middle"),+ AnyTypeTestInvocation(id="outer_fallback", value="outer"),+ CollectInvocation(id="collect"),+ ]+ edges = [+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "deep", "true_input"),+ ("deep_fallback", "value", "deep", "false_input"),+ ("deep_condition", "value", "deep", "condition"),+ ("deep", "value", "middle", "true_input"),+ ("middle_fallback", "value", "middle", "false_input"),+ ("middle_condition", "value", "middle", "condition"),+ ("middle", "value", "outer", "true_input"),+ ("outer_fallback", "value", "outer", "false_input"),+ ("outer_condition", "value", "outer", "condition"),+ ("outer", "value", "collect", "item"),+ ]+ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=True,+ )+ assert not state.has_error(), trace+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == ({(): []} if not source_data else {(0,): [["a"]], (1,): [["b"]]})+ if source_data:+ for node_id in ("deep", "middle", "outer"):+ assert sorted(state._get_iteration_path(exec_id) for exec_id in state.source_prepared_mapping[node_id]) == [+ (0,),+ (1,),+ ]++[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("for_field", ["true_input", "false_input"], ids=["true-for", "false-for"])+def test_literal_if_skips_direct_unselected_for_final(force_compatibility_scheduler: bool, for_field: str) -> None:+ selected_field = "false_input" if for_field == "true_input" else "true_input"+ graph = _graph_from([- CollectionConcatInvocation(id="closed_src", first=["z1", "z2", "z3"]),- IterateInvocation(id="closed"),- CollectInvocation(id="closing_collect"),- IterateInvocation(id="reopened"),- MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),- CollectionConcatInvocation(id="other_src", first=["u1", "u2"]),- IterateInvocation(id="other"),- MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),- IfInvocation(id="if", condition=True),+ CollectionConcatInvocation(id="src", first=[["a"], ["b"]]),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ MarkedAnyTypeTestInvocation(id="body", marker="F"),+ ForReturnInvocation(id="ret"),+ AnyTypeTestInvocation(id="fallback", value="fb"),+ IfInvocation(id="if", condition=selected_field == "true_input"),CollectInvocation(id="collect"),],[- ("closed_src", "collection", "closed", "collection"),- ("closed", "item", "closing_collect", "item"),- ("closing_collect", "collection", "reopened", "collection"),- ("reopened", "item", "true_value", "value"),- ("true_value", "value", "if", "true_input"),- ("other_src", "collection", "other", "collection"),- ("other", "item", "false_value", "value"),- ("false_value", "value", "if", "false_input"),+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "if", for_field),+ ("fallback", "value", "if", selected_field),("if", "value", "collect", "item"),],)+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )-def _for_output_connected_to_selected_axis_graph(selected_is_downstream: bool) -> Graph:- """A For's final output on the unselected branch, under an axis connected to the selected one by a reopen."""- upstream_ids = ("upstream_src", "upstream")- downstream_ids = ("downstream_src", "downstream")- for_parent = upstream_ids[1] if selected_is_downstream else downstream_ids[1]- selected_axis = downstream_ids[1] if selected_is_downstream else upstream_ids[1]- return _graph_from(+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {(): ["fb"]}+ assert {"for", "body", "ret"} <= set(trace)++[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_nested_literal_if_under_wired_root_if_keeps_parent_iterate_frames(+ force_compatibility_scheduler: bool,+) -> None:+ graph = _graph_from([- CollectionConcatInvocation(id="upstream_src", first=[["a0", "a1"], ["a2"]]),- IterateInvocation(id="upstream"),- MarkedAnyTypeTestInvocation(id="body", marker="b:"),- CollectInvocation(id="closing_collect"),- CollectionConcatInvocation(id="downstream_src", second=[["x"]]),- IterateInvocation(id="downstream"),- FixedCollectionTestInvocation(id="for_items"),- ForInvocation(id="for"),- ForReturnInvocation(id="return"),- MarkedAnyTypeTestInvocation(id="selected_value", marker="s:"),- IfInvocation(id="if", condition=True),+ CollectionConcatInvocation(id="src", first=[["a", "c"], ["c", "b"]]),+ IterateInvocation(id="iterate"),+ ForInvocation(id="left_for"),+ MarkedAnyTypeTestInvocation(id="left_body", marker="F"),+ ForReturnInvocation(id="left_ret"),+ ForInvocation(id="right_for"),+ MarkedAnyTypeTestInvocation(id="right_body", marker="F"),+ ForReturnInvocation(id="right_ret"),+ IfInvocation(id="inner_if", condition=True),+ MarkedAnyTypeTestInvocation(id="passthrough", marker="p:"),+ AnyTypeTestInvocation(id="root", value="R"),+ BooleanInvocation(id="condition", value=True),+ IfInvocation(id="outer_if"),CollectInvocation(id="collect"),],[- ("upstream_src", "collection", "upstream", "collection"),- ("upstream", "item", "body", "value"),- ("body", "value", "closing_collect", "item"),- ("closing_collect", "collection", "downstream_src", "first"),- ("downstream_src", "collection", "downstream", "collection"),- (for_parent, "item", "for_items", "value"),- ("for_items", "collection", "for", "collection"),- ("for", "item", "return", "output"),- create_loop_linkage("for", "return"),- ("for", "output_collection", "if", "false_input"),- (selected_axis, "item", "selected_value", "value"),- ("selected_value", "value", "if", "true_input"),- ("if", "value", "collect", "item"),+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "left_for", "collection"),+ ("left_for", "item", "left_body", "value"),+ ("left_body", "value", "left_ret", "output"),+ create_loop_linkage("left_for", "left_ret"),+ ("iterate", "item", "right_for", "collection"),+ ("right_for", "item", "right_body", "value"),+ ("right_body", "value", "right_ret", "output"),+ create_loop_linkage("right_for", "right_ret"),+ ("left_for", "output_collection", "inner_if", "true_input"),+ ("right_for", "output_collection", "inner_if", "false_input"),+ ("inner_if", "value", "passthrough", "value"),+ ("passthrough", "value", "outer_if", "true_input"),+ ("root", "value", "outer_if", "false_input"),+ ("condition", "value", "outer_if", "condition"),+ ("outer_if", "value", "collect", "item"),],)+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )- ("selected_is_downstream", "expected"),- [- (True, ["s:b:['a0', 'a1']", "s:b:['a2']", "s:['x']"]),- (False, ["s:['a0', 'a1']", "s:['a2']"]),- ],- ids=["selects-reopened-axis", "selects-closed-axis"],-)-def test_literal_if_ignores_unselected_for_output_under_an_axis_connected_to_the_selected_one(- selected_is_downstream: bool, expected: list[str]-) -> None:- """An unselected For final output adds no frames even when its axis feeds, or is fed by, the selected axis."""- _trace, state = _run_to_completion(_for_output_connected_to_selected_axis_graph(selected_is_downstream))+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {(): ["p:['Fa', 'Fc']", "p:['Fc', 'Fb']"]}+ assert trace.count("inner_if") == 2+ assert trace.count("outer_if") == 2- assert _source_values(state, "collect") == {(): expected}[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_literal_if_after_final_iterate_checkpoint_completes_with_eager_unselected_for(+ force_compatibility_scheduler: bool,+) -> None:+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="src", first=[["a", "b"], ["c"], ["d"]]),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ MarkedAnyTypeTestInvocation(id="body", marker="F"),+ ForReturnInvocation(id="ret"),+ AnyTypeTestInvocation(id="root", value="R"),+ IfInvocation(id="if", condition=False),+ CollectInvocation(id="collect"),+ ],+ [+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "if", "true_input"),+ ("root", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ],+ )+ trace, partial = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler, stop_after=5+ )+ assert trace[-1] == "iterate"[email protected]("condition_from_branch", [False, True], ids=["literal", "condition-from-branch"])-def test_if_over_cross_product_carried_by_its_deciding_input_completes(condition_from_branch: bool) -> None:- """Unrelated axes combined by one input are that input's own frames, so the If keeps the cross product."""- _trace, state = _run_to_completion(_cross_product_branch_graph(True, condition_from_branch))+ resumed_trace, state = _run_graph(+ load_execution_state(dump_execution_state(partial)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )- assert _source_values(state, "collect") == {(0,): [11, 21, 31], (1,): [12, 22, 32]}+ assert state.is_complete(), f"graph stalled after {trace + resumed_trace}"+ assert _source_values(state, "collect") == {(): ["R"]}+ assert {"for", "body", "ret"} <= set(trace + resumed_trace)-def test_literal_if_selecting_axis_reopened_directly_from_a_collect_pairs_frames() -> None:- """An Iterate fed straight from the Collect that closed the other axis has its length, so frames pair by index."""- _trace, state = _run_to_completion(_collect_then_reopen_graph(True))[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_empty_nested_iterates_and_collects_complete_through_unselected_for(+ force_compatibility_scheduler: bool,+) -> None:+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="src", first=[[], [[[]], [["c", "a", "c"]]]]),+ IterateInvocation(id="it0"),+ CollectionConcatInvocation(id="concat1"),+ IterateInvocation(id="it1"),+ CollectionConcatInvocation(id="concat2"),+ IterateInvocation(id="it2"),+ MarkedAnyTypeTestInvocation(id="x", marker="x"),+ CollectInvocation(id="branch_collect"),+ MarkedAnyTypeTestInvocation(id="passthrough", marker="F:"),+ CollectionConcatInvocation(id="empty_src", first=[]),+ IterateInvocation(id="empty_iterate"),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="for_body"),+ ForReturnInvocation(id="for_ret"),+ BooleanInvocation(id="condition", value=False),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ],+ [+ ("src", "collection", "it0", "collection"),+ ("it0", "item", "concat1", "first"),+ ("concat1", "collection", "it1", "collection"),+ ("it1", "item", "concat2", "first"),+ ("concat2", "collection", "it2", "collection"),+ ("it1", "item", "x", "value"),+ ("x", "value", "branch_collect", "item"),+ ("branch_collect", "collection", "passthrough", "value"),+ ("empty_src", "collection", "empty_iterate", "collection"),+ ("empty_iterate", "item", "for", "collection"),+ ("for", "item", "for_body", "value"),+ ("for_body", "value", "for_ret", "output"),+ create_loop_linkage("for", "for_ret"),+ ("for", "output_collection", "if", "true_input"),+ ("passthrough", "value", "if", "false_input"),+ ("condition", "value", "if", "condition"),+ ("if", "value", "collect", "item"),+ ],+ )- assert _source_values(state, "collect") == {(0,): ["t:b:a1"], (1,): ["t:b:a2"]}+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {(): ["F:[]", "F:['x[[]]', \"x[['c', 'a', 'c']]\"]"]}+ assert "for" not in trace and "for_body" not in trace-def test_literal_if_selecting_axis_reopened_through_two_collects_pairs_frames() -> None:- """A chain of direct reopens keeps the first axis's length, so the last reopened axis pairs with it."""++def test_literal_root_condition_runs_unselected_for_output_branch_under_iterate() -> None:graph = _graph_from([- CollectionConcatInvocation(id="src", first=["a1", "a2", "a3"]),- IterateInvocation(id="first"),- MarkedAnyTypeTestInvocation(id="first_body", marker="b:"),- CollectInvocation(id="first_collect"),- IterateInvocation(id="middle"),- MarkedAnyTypeTestInvocation(id="middle_body", marker="c:"),- CollectInvocation(id="middle_collect"),- IterateInvocation(id="last"),- MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),- MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),- IfInvocation(id="if", condition=True),+ CollectionConcatInvocation(id="src", first=[["a", "b"], ["c"]]),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ MarkedAnyTypeTestInvocation(id="body", marker="b:"),+ ForReturnInvocation(id="ret"),+ AnyTypeTestInvocation(id="mid"),+ AnyTypeTestInvocation(id="fallback", value="fb"),+ IfInvocation(id="if", condition=False),CollectInvocation(id="collect"),],[- ("src", "collection", "first", "collection"),- ("first", "item", "first_body", "value"),- ("first_body", "value", "first_collect", "item"),- ("first_collect", "collection", "middle", "collection"),- ("middle", "item", "middle_body", "value"),- ("middle_body", "value", "middle_collect", "item"),- ("middle_collect", "collection", "last", "collection"),- ("last", "item", "true_value", "value"),- ("true_value", "value", "if", "true_input"),- ("first", "item", "false_value", "value"),- ("false_value", "value", "if", "false_input"),+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "mid", "value"),+ ("mid", "value", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),("if", "value", "collect", "item"),],)- _trace, state = _run_to_completion(graph)-- assert _source_values(state, "collect") == {(0,): ["t:c:b:a1"], (1,): ["t:c:b:a2"], (2,): ["t:c:b:a3"]}+ trace, state = _run_to_completion(graph)+ assert _source_values(state, "collect") == {(): ["fb"]}+ assert {"for", "body", "ret", "mid"} <= set(trace)-def test_literal_if_selecting_axis_reopened_from_nested_collects_pairs_with_the_outer_axis() -> None:- """Each Collect in a chain closes one more axis, so the last one gathers one item per outermost frame."""[email protected]("condition", [True, False])+def test_literal_if_with_empty_nested_iterate_on_a_branch_has_no_frames(condition: bool) -> None:+ """An open Iterate with no items gives the If no frame, whichever branch the literal condition selects."""graph = _graph_from([- CollectionConcatInvocation(id="outer_src", first=[[["a"], ["b"]], [["c", "d"]]]),+ CollectionConcatInvocation(id="src", first=[[], []]),IterateInvocation(id="outer"),- CollectionConcatInvocation(id="middle_src"),- IterateInvocation(id="middle"),- CollectionConcatInvocation(id="inner_src"),+ CollectionConcatInvocation(id="inner_src", first=[]),IterateInvocation(id="inner"),- MarkedAnyTypeTestInvocation(id="body", marker="b:"),- CollectInvocation(id="inner_collect"),- CollectInvocation(id="middle_collect"),- CollectInvocation(id="outer_collect"),- IterateInvocation(id="reopened"),MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),- IfInvocation(id="if", condition=True),+ IfInvocation(id="if", condition=condition),CollectInvocation(id="collect"),],[- ("outer_src", "collection", "outer", "collection"),- ("outer", "item", "middle_src", "first"),- ("middle_src", "collection", "middle", "collection"),- ("middle", "item", "inner_src", "first"),+ ("src", "collection", "outer", "collection"),+ ("outer", "item", "inner_src", "first"),("inner_src", "collection", "inner", "collection"),- ("inner", "item", "body", "value"),- ("body", "value", "inner_collect", "item"),- ("inner_collect", "collection", "middle_collect", "item"),- ("middle_collect", "collection", "outer_collect", "item"),- ("outer_collect", "collection", "reopened", "collection"),- ("reopened", "item", "true_value", "value"),+ ("inner", "item", "true_value", "value"),("true_value", "value", "if", "true_input"),("outer", "item", "false_value", "value"),("false_value", "value", "if", "false_input"),("if", "value", "collect", "item"),],)- _trace, state = _run_to_completion(graph)- assert _source_values(state, "collect") == {- (0,): ["t:[['b:a'], ['b:b']]"],- (1,): ["t:[['b:c', 'b:d']]"],- }+ trace, state = _run_to_completion(graph)++ assert _source_values(state, "collect") == {(0,): [], (1,): []}+ assert "if" not in trace-def test_literal_if_selecting_axis_nested_under_a_reopened_axis_pairs_frames() -> None:- """An Iterate nested under a direct reopen runs in the reopened frames, which pair with the closed axis."""[email protected]("force_compatibility_scheduler", [False, True], ids=["default", "forced-compatibility"])+def test_wired_root_condition_with_empty_for_parent_frame_completes(+ force_compatibility_scheduler: bool,+) -> None:graph = _graph_from([- CollectionConcatInvocation(id="src", first=[["x1", "x2"], ["y1"]]),- IterateInvocation(id="first"),- AnyTypeTestInvocation(id="body"),- CollectInvocation(id="closing_collect"),- IterateInvocation(id="reopened"),- CollectionConcatInvocation(id="nested_src"),- IterateInvocation(id="nested"),- MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),- MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),- IfInvocation(id="if", condition=True),+ CollectionConcatInvocation(id="src", first=[]),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ ForReturnInvocation(id="ret"),+ FixedCollectionTestInvocation(id="condition", value=True),+ AnyTypeTestInvocation(id="fallback", value="fb"),+ IfInvocation(id="if"),CollectInvocation(id="collect"),],[- ("src", "collection", "first", "collection"),- ("first", "item", "body", "value"),- ("body", "value", "closing_collect", "item"),- ("closing_collect", "collection", "reopened", "collection"),- ("reopened", "item", "nested_src", "first"),- ("nested_src", "collection", "nested", "collection"),- ("nested", "item", "true_value", "value"),- ("true_value", "value", "if", "true_input"),- ("first", "item", "false_value", "value"),- ("false_value", "value", "if", "false_input"),+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "if", "true_input"),+ ("condition", "condition", "if", "condition"),+ ("fallback", "value", "if", "false_input"),("if", "value", "collect", "item"),],)- _trace, state = _run_to_completion(graph)+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)- assert _source_values(state, "collect") == {(0, 0): ["t:x1"], (0, 1): ["t:x2"], (1, 0): ["t:y1"]}+ trace: list[str] = []+ while (node := state.next()) is not None:+ source_id = state.prepared_source_mapping[node.id]+ trace.append(source_id)+ state.complete(node.id, node.invoke(Mock()))++ assert not state.has_error(), state.errors+ assert state.is_complete(), f"trace={trace}; executed={state.executed}; prepared={state.source_prepared_mapping}"+ assert _source_values(state, "collect") == {(): []}+ assert not {"if", "for", "ret", "fallback"} & set(trace)-def test_literal_if_selecting_axis_reopened_within_kept_outer_frames_pairs_both_axes() -> None:- """A Collect closing an inner axis keeps the outer one; its reopening pairs with the inner axis per outer frame."""[email protected]("force_compatibility_scheduler", [False, True], ids=["default", "compatibility"])+def test_wired_root_condition_with_empty_for_output_through_any_node_completes(+ force_compatibility_scheduler: bool,+) -> None:graph = _graph_from([- CollectionConcatInvocation(id="outer_src", first=[["a1", "a2"], ["b1"]]),- IterateInvocation(id="outer"),- CollectionConcatInvocation(id="inner_src"),- IterateInvocation(id="inner"),- MarkedAnyTypeTestInvocation(id="body", marker="b:"),- CollectInvocation(id="closing_collect"),- IterateInvocation(id="reopened"),- MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),- MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),- IfInvocation(id="if", condition=True),+ CollectionConcatInvocation(id="src", first=[]),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="for_output"),+ ForReturnInvocation(id="ret"),+ FixedCollectionTestInvocation(id="condition", value=True),+ AnyTypeTestInvocation(id="fallback", value="fb"),+ IfInvocation(id="if"),CollectInvocation(id="collect"),],[- ("outer_src", "collection", "outer", "collection"),- ("outer", "item", "inner_src", "first"),- ("inner_src", "collection", "inner", "collection"),- ("inner", "item", "body", "value"),- ("body", "value", "closing_collect", "item"),- ("closing_collect", "collection", "reopened", "collection"),- ("reopened", "item", "true_value", "value"),- ("true_value", "value", "if", "true_input"),- ("inner", "item", "false_value", "value"),- ("false_value", "value", "if", "false_input"),+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "output_collection", "for_output", "value"),+ ("for_output", "value", "if", "true_input"),+ ("for", "item", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("condition", "condition", "if", "condition"),+ ("fallback", "value", "if", "false_input"),("if", "value", "collect", "item"),],)- _trace, state = _run_to_completion(graph)+ state = GraphExecutionState(graph=graph)+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- assert _source_values(state, "collect") == {(0, 0): ["t:b:a1"], (0, 1): ["t:b:a2"], (1, 0): ["t:b:b1"]}+ assert not state.has_error(), state.errors+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {(): []}+ assert not {"if", "for", "for_output", "ret", "fallback"} & set(trace)- ("condition", "expected"),- [(False, [["a0", "a1"], ["a2"]]), (True, [["b0"], ["b1"], ["b2"]])],- ids=["selects-a", "selects-b"],-)-def test_literal_if_ignores_independent_axis_reaching_it_through_unselected_for_output(- condition: bool, expected: list[list[str]][email protected]("force_compatibility_scheduler", [False, True], ids=["default", "compatibility"])+def test_wired_per_item_condition_with_empty_for_output_completes(+ force_compatibility_scheduler: bool,) -> None:- """An unselected For final output adds no frames, so the If runs once per item of the selected branch's axis."""- nodes: list[Any] = [IfInvocation(id="if", condition=condition), CollectInvocation(id="collect")]- edges: list[Any] = [("if", "value", "collect", "item")]- for prefix, values, branch in (- ("a", [["a0", "a1"], ["a2"]], "false_input"),- ("b", [["b0"], ["b1"], ["b2"]], "true_input"),- ):- nodes += [- CollectionConcatInvocation(id=f"{prefix}_src", first=values),- IterateInvocation(id=f"{prefix}_iter"),- ForInvocation(id=f"{prefix}_for"),- ForReturnInvocation(id=f"{prefix}_return"),- ]- edges += [- (f"{prefix}_src", "collection", f"{prefix}_iter", "collection"),- (f"{prefix}_iter", "item", f"{prefix}_for", "collection"),- (f"{prefix}_for", "item", f"{prefix}_return", "output"),- create_loop_linkage(f"{prefix}_for", f"{prefix}_return"),- (f"{prefix}_for", "output_collection", "if", branch),- ]- _trace, state = _run_to_completion(_graph_from(nodes, edges))-- assert _source_values(state, "collect") == {(): expected}--[email protected]("condition", [True, False])-def test_root_condition_if_broadcasts_over_nested_axes_both_branches_share(condition: bool) -> None:- """A root-frame condition selects between branches that run in the same nested frames, once per inner item."""graph = _graph_from([- CollectionConcatInvocation(id="src", first=[["p", "q"], ["r"]]),- IterateInvocation(id="outer"),- CollectionConcatInvocation(id="inner_src", first=[]),- IterateInvocation(id="inner"),- MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),- MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),- FixedCollectionTestInvocation(id="condition", value=condition),+ CollectionConcatInvocation(id="src", first=[]),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="for_output"),+ ForReturnInvocation(id="ret"),+ FixedCollectionTestInvocation(id="condition"),+ AnyTypeTestInvocation(id="fallback", value="fb"),IfInvocation(id="if"),CollectInvocation(id="collect"),],[- ("src", "collection", "outer", "collection"),- ("outer", "item", "inner_src", "first"),- ("inner_src", "collection", "inner", "collection"),- ("inner", "item", "true_value", "value"),- ("inner", "item", "false_value", "value"),- ("true_value", "value", "if", "true_input"),- ("false_value", "value", "if", "false_input"),+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "output_collection", "for_output", "value"),+ ("for_output", "value", "if", "true_input"),+ ("for", "item", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("iterate", "item", "condition", "value"),("condition", "condition", "if", "condition"),+ ("fallback", "value", "if", "false_input"),("if", "value", "collect", "item"),],)+ state = GraphExecutionState(graph=graph)+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- _trace, state = _run_to_completion(graph)-- marker = "t:" if condition else "f:"- assert _source_values(state, "collect") == {(0,): [f"{marker}p", f"{marker}q"], (1,): [f"{marker}r"]}---def _shared_nested_axes_graph(data: list[Any], levels: int, condition_on_outer: bool) -> Graph:- """Both branches read the innermost of ``levels`` nested Iterates; the condition is root or per outer item."""- axis_ids = ["outer", "middle", "inner"] if levels == 3 else ["outer", "inner"]- nodes: list[Any] = [CollectionConcatInvocation(id="src", first=data), IterateInvocation(id=axis_ids[0])]- edges: list[Any] = [("src", "collection", axis_ids[0], "collection")]- for parent_id, axis_id in itertools.pairwise(axis_ids):- nodes += [CollectionConcatInvocation(id=f"{axis_id}_src", first=[]), IterateInvocation(id=axis_id)]- edges += [- (parent_id, "item", f"{axis_id}_src", "first"),- (f"{axis_id}_src", "collection", axis_id, "collection"),- ]- nodes += [- MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),- MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),- FixedCollectionTestInvocation(id="condition", value=True),- IfInvocation(id="if"),- ]- edges += [- (axis_ids[-1], "item", "true_value", "value"),- (axis_ids[-1], "item", "false_value", "value"),- ("true_value", "value", "if", "true_input"),- ("false_value", "value", "if", "false_input"),- ("condition", "condition", "if", "condition"),- ]- if condition_on_outer:- edges.append((axis_ids[0], "item", "condition", "value"))- previous = ("if", "value")- for index in range(levels):- nodes.append(CollectInvocation(id=f"collect{index}"))- edges.append((*previous, f"collect{index}", "item"))- previous = (f"collect{index}", "collection")- return _graph_from(nodes, edges)---def test_per_item_condition_if_over_three_shared_nested_axes_completes() -> None:- """A per-outer-item condition broadcasts over two deeper shared axes, and no Collect closes before the If runs."""- graph = _shared_nested_axes_graph([[["p", "q"], ["r"]], [["s"]]], levels=3, condition_on_outer=True)-- trace, state = _run_to_completion(graph)-- assert _source_values(state, "collect2") == {(): [[["t:p", "t:q"], ["t:r"]], [["t:s"]]]}- assert trace.index("collect0") > max(index for index, source_id in enumerate(trace) if source_id == "if")+ assert not state.has_error(), state.errors+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {(): []}+ assert trace[0] == "src"+ assert not {"condition", "if", "for", "for_output", "ret", "fallback"} & set(trace)@pytest.mark.parametrize(- ("data", "levels", "expected"),- [- pytest.param([[], []], 2, {(): [[], []]}, id="two-levels"),- pytest.param([[[], []], [[]]], 3, {(): [[[], []], [[]]]}, id="three-levels"),- ],+ "force_compatibility_scheduler", [False, True], ids=["default-route", "forced-compatibility-route"])-def test_root_condition_if_over_shared_nested_axes_with_empty_innermost_iterate_has_no_frames(- data: list[Any], levels: int, expected: dict[tuple[int, ...], Any]+def test_per_item_if_runs_direct_for_output_in_rejected_frames(+ force_compatibility_scheduler: bool,) -> None:- """An innermost shared Iterate empty in every frame leaves a root-conditioned If no frames, as a literal one has."""- trace, state = _run_to_completion(_shared_nested_axes_graph(data, levels=levels, condition_on_outer=False))-- assert _source_values(state, f"collect{levels - 1}") == expected- assert "if" not in trace---def test_literal_if_selecting_for_output_under_empty_iterate_has_no_frames() -> None:- """An Iterate with no items that a selected branch For runs under leaves the If no executions."""graph = _graph_from([- CollectionConcatInvocation(id="src", first=[]),+ CollectionConcatInvocation(id="src", first=["", "x"]),IterateInvocation(id="iterate"),+ FixedCollectionTestInvocation(id="condition"),ForInvocation(id="for"),- MarkedAnyTypeTestInvocation(id="body", marker="b:"),+ AnyTypeTestInvocation(id="body"),ForReturnInvocation(id="ret"),- AnyTypeTestInvocation(id="mid"),AnyTypeTestInvocation(id="fallback", value="fb"),- IfInvocation(id="if", condition=True),+ IfInvocation(id="if"),CollectInvocation(id="collect"),],[("src", "collection", "iterate", "collection"),- ("iterate", "item", "for", "collection"),+ ("iterate", "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("condition", "collection", "for", "collection"),("for", "item", "body", "value"),("body", "value", "ret", "output"),create_loop_linkage("for", "ret"),- ("for", "output_collection", "mid", "value"),- ("mid", "value", "if", "true_input"),+ ("for", "output_collection", "if", "true_input"),("fallback", "value", "if", "false_input"),("if", "value", "collect", "item"),],)+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)+ trace: list[tuple[str, tuple[int, ...]]] = []+ while (node := state.next()) is not None:+ source_id = state.prepared_source_mapping[node.id]+ iteration_path = state._get_iteration_path(node.id)+ trace.append((source_id, iteration_path))+ state.complete(node.id, node.invoke(Mock()))- trace, state = _run_to_completion(graph)+ assert not state.has_error(), state.errors+ assert state.is_complete(), f"execution stalled after {trace}"+ assert _source_values(state, "if") == {(0,): "fb", (1,): [0, 1]}+ # The fallback and selected For final retain their distinct parent Iterate frames.+ assert _source_values(state, "collect") == {(0,): ["fb"], (1,): [[0, 1]]}+ assert [path for source_id, path in trace if source_id == "if"] == [(0,), (1,)]+ assert [path for source_id, path in trace if source_id == "for"] == [(0, 0), (1, 0), (0, 1), (1, 1)]+ assert [path for source_id, path in trace if source_id == "body"] == [(0, 0), (1, 0), (0, 1), (1, 1)]+ assert [path for source_id, path in trace if source_id == "ret"] == [(0, 0), (1, 0), (0, 1), (1, 1)]- assert _source_values(state, "collect") == {(): []}- assert "if" not in trace and "fallback" not in trace++def _unrelated_open_branches_graph(condition: bool, computed_condition: bool) -> Graph:+ nodes = [+ CollectionConcatInvocation(id="true_src", first=[1, 2]),+ IterateInvocation(id="true_iterate"),+ CollectionConcatInvocation(id="false_src", first=[10, 20, 30]),+ IterateInvocation(id="false_iterate"),+ IfInvocation(id="if", condition=condition),+ CollectInvocation(id="collect"),+ ]+ edges = [+ ("true_src", "collection", "true_iterate", "collection"),+ ("false_src", "collection", "false_iterate", "collection"),+ ("true_iterate", "item", "if", "true_input"),+ ("false_iterate", "item", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ]+ if computed_condition:+ nodes.append(FixedCollectionTestInvocation(id="condition", value=condition))+ edges.append(("condition", "condition", "if", "condition"))+ return _graph_from(nodes, edges)[email protected]("fail_unselected", [False, True], ids=["succeeds", "unselected-fails"])-def test_per_item_if_gates_branch_for_together_with_the_for_nested_in_its_body(fail_unselected: bool) -> None:- """A gated For brings the For nested in its body along, so a false item runs neither loop."""- graph = _graph_from(+def _root_condition_with_deeper_axis_on_one_branch_graph(outer_values: list[list[str]]) -> Graph:+ return _graph_from([- CollectionConcatInvocation(id="outer_source", first=["", "x"]),- IterateInvocation(id="outer_iterate"),+ CollectionConcatInvocation(id="src", first=outer_values),+ IterateInvocation(id="outer"),+ CollectionConcatInvocation(id="inner_src", first=[]),+ IterateInvocation(id="inner"),+ MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),+ MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),+ FixedCollectionTestInvocation(id="condition", value=False),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ],+ [+ ("src", "collection", "outer", "collection"),+ ("outer", "item", "inner_src", "first"),+ ("inner_src", "collection", "inner", "collection"),+ ("inner", "item", "true_value", "value"),+ ("true_value", "value", "if", "true_input"),+ ("outer", "item", "false_value", "value"),+ ("false_value", "value", "if", "false_input"),+ ("condition", "condition", "if", "condition"),+ ("if", "value", "collect", "item"),+ ],+ )+++def _per_item_condition_with_deeper_collect_branch_graph() -> Graph:+ return _graph_from(+ [+ CollectionConcatInvocation(id="src", first=["x", "y"]),+ IterateInvocation(id="outer"),+ FixedCollectionTestInvocation(id="middle_src"),+ IterateInvocation(id="middle"),+ FixedCollectionTestInvocation(id="inner_src"),+ IterateInvocation(id="inner"),+ MarkedAnyTypeTestInvocation(id="body", marker="b:"),+ CollectInvocation(id="branch_collect"),+ AnyTypeTestInvocation(id="fallback", value="fb"),+ FixedCollectionTestInvocation(id="condition"),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ],+ [+ ("src", "collection", "outer", "collection"),+ ("outer", "item", "middle_src", "value"),+ ("middle_src", "collection", "middle", "collection"),+ ("middle", "item", "inner_src", "value"),+ ("inner_src", "collection", "inner", "collection"),+ ("inner", "item", "body", "value"),+ ("body", "value", "branch_collect", "item"),+ ("branch_collect", "collection", "if", "true_input"),+ ("outer", "item", "fallback", "value"),+ ("fallback", "value", "if", "false_input"),+ ("outer", "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("if", "value", "collect", "item"),+ ],+ )+++def _per_item_condition_with_deeper_for_output_collect_branch_graph() -> Graph:+ return _graph_from(+ [+ CollectionConcatInvocation(id="src", first=["", "x"]),+ IterateInvocation(id="outer"),+ FixedCollectionTestInvocation(id="condition"),+ FixedCollectionTestInvocation(id="inner_src"),+ IterateInvocation(id="inner"),FixedCollectionTestInvocation(id="items"),ForInvocation(id="for"),- FixedCollectionTestInvocation(id="mk"),- ForInvocation(id="ifor"),- AnyTypeTestInvocation(id="ibody"),- ForReturnInvocation(id="ireturn"),- ForReturnInvocation(id="return"),+ MarkedAnyTypeTestInvocation(id="body", marker="b:"),+ ForReturnInvocation(id="ret"),CollectInvocation(id="branch_collect"),- AnyTypeTestInvocation(id="fallback", value="fallback"),+ MarkedAnyTypeTestInvocation(id="fallback", marker="f:"),IfInvocation(id="if"),- AnyTypeTestInvocation(id="sink"),+ CollectInvocation(id="collect"),],[- ("outer_source", "collection", "outer_iterate", "collection"),- ("outer_iterate", "item", "items", "value"),- ("items", "condition", "if", "condition"),+ ("src", "collection", "outer", "collection"),+ ("outer", "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("outer", "item", "inner_src", "value"),+ ("inner_src", "collection", "inner", "collection"),+ ("inner", "item", "items", "value"),("items", "collection", "for", "collection"),- ("for", "item", "mk", "value"),- ("mk", "collection", "ifor", "collection"),- ("ifor", "item", "ibody", "value"),- ("ibody", "value", "ireturn", "output"),- create_loop_linkage("ifor", "ireturn"),- ("ifor", "output_collection", "return", "output"),- create_loop_linkage("for", "return"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),("for", "output_collection", "branch_collect", "item"),("branch_collect", "collection", "if", "true_input"),+ ("outer", "item", "fallback", "value"),("fallback", "value", "if", "false_input"),- ("if", "value", "sink", "value"),+ ("if", "value", "collect", "item"),],)- gated_sources = {"for", "mk", "ifor", "ibody", "ireturn", "return", "branch_collect"}- state = GraphExecutionState(graph=graph)- trace: list[tuple[str, tuple[int, ...]]] = []- while (node := state.next()) is not None:- source_id = state.prepared_source_mapping[node.id]- iteration_path = state._get_iteration_path(node.id)- trace.append((source_id, iteration_path))- if fail_unselected and source_id in gated_sources and iteration_path[:1] == (0,):- state.set_node_error(node.id, f"{source_id} ran for an unselected item")- continue- state.complete(node.id, node.invoke(Mock()))- assert not state.has_error(), state.errors- assert state.is_complete(), f"execution stalled after {trace}"- assert not [entry for entry in trace if entry[0] in gated_sources and entry[1][:1] == (0,)]- assert _source_values(state, "sink") == {(0,): "fallback", (1,): [[[0, 1], [0, 1]]]}+def _cross_product_branch_graph(condition: bool, condition_from_branch: bool = False) -> Graph:+ nodes = [+ CollectionConcatInvocation(id="left_src", first=[1, 2]),+ IterateInvocation(id="left"),+ CollectionConcatInvocation(id="right_src", first=[10, 20, 30]),+ IterateInvocation(id="right"),+ AddInvocation(id="add"),+ AnyTypeTestInvocation(id="fallback", value=0),+ IfInvocation(id="if", condition=condition),+ CollectInvocation(id="collect"),+ ]+ edges = [+ ("left_src", "collection", "left", "collection"),+ ("right_src", "collection", "right", "collection"),+ ("left", "item", "add", "a"),+ ("right", "item", "add", "b"),+ ("add", "value", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ]+ if condition_from_branch:+ nodes.append(FixedCollectionTestInvocation(id="condition"))+ edges += [("add", "value", "condition", "value"), ("condition", "condition", "if", "condition")]+ return _graph_from(nodes, edges)- ("build_graph", "message"),- [- pytest.param(- lambda: _unrelated_open_branches_graph(True, False),- "unrelated open iterator axes",- id="unrelated-literal-T",- ),- pytest.param(- lambda: _unrelated_open_branches_graph(False, False),- "unrelated open iterator axes",- id="unrelated-literal-F",- ),- pytest.param(- lambda: _unrelated_open_branches_graph(True, True),- "unrelated open iterator axes",- id="unrelated-computed-T",- ),- pytest.param(- lambda: _unrelated_open_branches_graph(False, True),- "unrelated open iterator axes",- id="unrelated-computed-F",- ),- pytest.param(- lambda: _root_condition_with_deeper_axis_on_one_branch_graph([[], ["p", "q"]]),- "different deeper open iterator axes",- id="root-condition-partly-empty-deeper-axis",- ),- pytest.param(- lambda: _root_condition_with_deeper_axis_on_one_branch_graph([["p"], ["q", "r"]]),- "different deeper open iterator axes",- id="root-condition-deeper-axis",- ),- pytest.param(- _per_item_condition_with_deeper_collect_branch_graph,- "deeper open iterator axes kept by a Collect",- id="per-item-condition-deeper-collect",- ),- pytest.param(- _per_item_condition_with_deeper_for_output_collect_branch_graph,- "deeper open iterator axes kept by a Collect",- id="per-item-condition-deeper-for-output-collect",- ),- pytest.param(- lambda: _cross_product_branch_graph(condition=False),- "unrelated open iterator axes",- id="literal-root-value-over-cross-product",- ),- pytest.param(- _per_item_condition_with_collect_of_collects_branch_graph,- "deeper open iterator axes kept by a Collect",- id="per-item-condition-deeper-collect-beside-collect-of-collects",- ),- pytest.param(- lambda: _collect_then_reopen_graph(condition=False, extra_items=("x",)),- "unrelated open iterator axes",- id="literal-selects-axis-a-collect-closed-before-the-other",- ),- pytest.param(- lambda: _collect_then_reopen_graph(condition=True, extra_items=("x",)),- "unrelated open iterator axes",- id="literal-selects-axis-reopened-through-a-node-after-the-collect",- ),- pytest.param(- lambda: _collect_then_reopen_graph(condition=True, appended_items=("x",)),- "unrelated open iterator axes",- id="literal-selects-axis-reopened-from-a-collect-that-appends-items",- ),- pytest.param(- _collect_with_literal_items_then_reopen_graph,- "unrelated open iterator axes",- id="literal-selects-axis-reopened-from-a-collect-with-literal-items",- ),- pytest.param(- lambda: _collect_then_reopen_graph(condition=False),- "unrelated open iterator axes",- id="literal-selects-axis-an-iterate-reopens",- ),- pytest.param(- lambda: _reopen_of_a_cross_product_graph(swap_add_inputs=False),- "unrelated open iterator axes",- id="literal-selects-closed-axis-of-a-reopened-cross-product",- ),- pytest.param(- lambda: _reopen_of_a_cross_product_graph(swap_add_inputs=True),- "unrelated open iterator axes",- id="literal-selects-closed-axis-of-a-reopened-swapped-cross-product",+def _collect_then_reopen_graph(+ condition: bool, extra_items: tuple[str, ...] = (), appended_items: tuple[str, ...] = ()+) -> Graph:+ nodes = [+ CollectionConcatInvocation(id="src", first=["a1", "a2"]),+ IterateInvocation(id="first"),+ MarkedAnyTypeTestInvocation(id="body", marker="b:"),+ CollectInvocation(id="closing_collect"),+ IterateInvocation(id="second"),+ MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),+ MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),+ IfInvocation(id="if", condition=condition),+ CollectInvocation(id="collect"),+ ]+ edges = [+ ("src", "collection", "first", "collection"),+ ("first", "item", "body", "value"),+ ("body", "value", "closing_collect", "item"),+ ]+ if appended_items:+ nodes.append(CollectionConcatInvocation(id="appended", first=list(appended_items)))+ edges.append(("appended", "collection", "closing_collect", "collection"))+ if extra_items:+ nodes.append(CollectionConcatInvocation(id="extend", second=list(extra_items)))+ edges += [+ ("closing_collect", "collection", "extend", "first"),+ ("extend", "collection", "second", "collection"),+ ]+ else:+ edges.append(("closing_collect", "collection", "second", "collection"))+ edges += [+ ("second", "item", "true_value", "value"),+ ("true_value", "value", "if", "true_input"),+ ("first", "item", "false_value", "value"),+ ("false_value", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ]+ return _graph_from(nodes, edges)+++def _collect_with_literal_items_then_reopen_graph() -> Graph:+ graph = _collect_then_reopen_graph(True)+ graph.get_node("closing_collect").collection = ["x"]+ return graph+++def _collect_of_collect_reopen_graph(+ groups: list[list[str]], unselected_axis: str, extra_collect: bool = False, append_unrelated_axis: bool = False+) -> Graph:+ """An Iterate reopens a Collect of per-group Collects, so its frames are the groups of the outer axis."""+ nodes: list[Any] = [+ CollectionConcatInvocation(id="groups_src", first=groups),+ IterateInvocation(id="group"),+ CollectionConcatInvocation(id="members_src"),+ IterateInvocation(id="member"),+ MarkedAnyTypeTestInvocation(id="body", marker="b:"),+ CollectInvocation(id="group_collect"),+ CollectInvocation(id="closing_collect"),+ IterateInvocation(id="reopened"),+ MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),+ MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),+ IfInvocation(id="if", condition=True),+ CollectInvocation(id="collect"),+ ]+ edges: list[Any] = [+ ("groups_src", "collection", "group", "collection"),+ ("group", "item", "members_src", "first"),+ ("members_src", "collection", "member", "collection"),+ ("member", "item", "body", "value"),+ ("body", "value", "group_collect", "item"),+ ("group_collect", "collection", "closing_collect", "item"),+ ]+ if append_unrelated_axis:+ nodes += [+ CollectionConcatInvocation(id="appended_src", first=[["v1"], ["v2"], ["v3"]]),+ IterateInvocation(id="appended"),+ CollectionConcatInvocation(id="appended_items"),+ ]+ edges += [+ ("appended_src", "collection", "appended", "collection"),+ ("appended", "item", "appended_items", "first"),+ ("appended_items", "collection", "group_collect", "collection"),+ ]+ if extra_collect:+ nodes.append(CollectInvocation(id="outer_collect"))+ edges += [+ ("closing_collect", "collection", "outer_collect", "item"),+ ("outer_collect", "collection", "reopened", "collection"),+ ]+ else:+ edges.append(("closing_collect", "collection", "reopened", "collection"))+ edges += [+ ("reopened", "item", "true_value", "value"),+ ("true_value", "value", "if", "true_input"),+ (unselected_axis, "item", "false_value", "value"),+ ("false_value", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ]+ return _graph_from(nodes, edges)+++def _per_item_condition_with_collect_of_collects_branch_graph() -> Graph:+ """A per-item condition on the outer axis chooses between a Collect over a deeper axis and a Collect of one."""+ nodes: list[Any] = [+ CollectionConcatInvocation(id="src", first=[[[["a"], ["b"]], [["c"]]], [[["x"]], []], [[["d", "e"]]]]),+ ]+ edges: list[Any] = []+ previous = ("src", "collection")+ for axis_id in ("outer", "middle", "deep", "inner"):+ nodes.append(IterateInvocation(id=axis_id))+ edges.append((*previous, axis_id, "collection"))+ if axis_id != "inner":+ nodes.append(CollectionConcatInvocation(id=f"{axis_id}_items"))+ edges.append((axis_id, "item", f"{axis_id}_items", "first"))+ previous = (f"{axis_id}_items", "collection")+ nodes += [+ MarkedAnyTypeTestInvocation(id="inner_body", marker="b:"),+ CollectInvocation(id="inner_collect"),+ CollectInvocation(id="deep_collect"),+ MarkedAnyTypeTestInvocation(id="deep_body", marker="n:"),+ CollectInvocation(id="deep_item_collect"),+ FixedCollectionTestInvocation(id="condition"),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ]+ edges += [+ ("inner", "item", "inner_body", "value"),+ ("inner_body", "value", "inner_collect", "item"),+ ("inner_collect", "collection", "deep_collect", "item"),+ ("deep", "item", "deep_body", "value"),+ ("deep_body", "value", "deep_item_collect", "item"),+ ("outer", "index", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("deep_item_collect", "collection", "if", "true_input"),+ ("deep_collect", "collection", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ]+ return _graph_from(nodes, edges)+++def _outer_condition_with_two_collects_graph(+ *,+ share_branch_axes: bool,+ passthrough_between_collects: bool = False,+ source_values: list[Any] | None = None,+) -> Graph:+ nodes: list[Any] = [+ CollectionConcatInvocation(+ id="source",+ first=source_values if source_values is not None else [[[["a"], ["b"]], [["c"]]], [], [[["d", "e"]]]],+ ),+ ]+ edges: list[Any] = []+ previous = ("source", "collection")+ for axis_id in ("outer", "middle", "deep", "inner"):+ nodes.append(IterateInvocation(id=axis_id))+ edges.append((*previous, axis_id, "collection"))+ if axis_id != "inner":+ concat_id = f"{axis_id}_items"+ nodes.append(CollectionConcatInvocation(id=concat_id))+ edges.append((axis_id, "item", concat_id, "first"))+ previous = (concat_id, "collection")+ nodes += [+ MarkedAnyTypeTestInvocation(id="body", marker="b:"),+ CollectInvocation(id="inner_collect"),+ CollectInvocation(id="middle_collect"),+ FixedCollectionTestInvocation(id="condition"),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ]+ edges += [+ ("inner", "item", "body", "value"),+ ("body", "value", "inner_collect", "item"),+ ("outer", "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("if", "value", "collect", "item"),+ ]+ if passthrough_between_collects:+ nodes.append(AnyTypeTestInvocation(id="collect_passthrough"))+ edges.append(("inner_collect", "collection", "collect_passthrough", "value"))+ edges.append(("collect_passthrough", "value", "middle_collect", "item"))+ else:+ edges.append(("inner_collect", "collection", "middle_collect", "item"))+ edges.append(("middle_collect", "collection", "if", "true_input"))+ if share_branch_axes:+ nodes.append(MarkedAnyTypeTestInvocation(id="false_copy", marker="f:"))+ edges += [+ ("middle_collect", "collection", "false_copy", "value"),+ ("false_copy", "value", "if", "false_input"),+ ]+ else:+ nodes.append(AnyTypeTestInvocation(id="fallback", value="root"))+ edges.append(("fallback", "value", "if", "false_input"))+ return _graph_from(nodes, edges)+++def _separate_collect_branches_graph(+ *, shape: str, unrelated_root_collect: bool, unrelated_root_collect_branch: str | None = None+) -> Graph:+ nodes: list[Any] = [+ CollectionConcatInvocation(id="source", first=[[["a", "b"], ["c"]], [["d"]]]),+ IterateInvocation(id="outer"),+ CollectionConcatInvocation(id="middle_source"),+ IterateInvocation(id="middle"),+ CollectionConcatInvocation(id="deep_source"),+ IterateInvocation(id="deep"),+ FixedCollectionTestInvocation(id="condition", value=True),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ]+ edges: list[Any] = [+ ("source", "collection", "outer", "collection"),+ ("outer", "item", "middle_source", "first"),+ ("middle_source", "collection", "middle", "collection"),+ ("middle", "item", "deep_source", "first"),+ ("deep_source", "collection", "deep", "collection"),+ ("outer", "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("if", "value", "collect", "item"),+ ]+ nodes += [MarkedAnyTypeTestInvocation(id="true_body", marker="true:"), CollectInvocation(id="true_collect")]+ edges += [+ ("deep", "item", "true_body", "value"),+ ("true_body", "value", "true_collect", "item"),+ ]+ if not unrelated_root_collect and unrelated_root_collect_branch != "true_input":+ edges.append(("true_collect", "collection", "if", "true_input"))+ if shape == "distinct-inner-axis":+ nodes += [+ CollectionConcatInvocation(id="middle2_source"),+ IterateInvocation(id="middle2"),+ CollectionConcatInvocation(id="deep2_source"),+ IterateInvocation(id="deep2"),+ MarkedAnyTypeTestInvocation(id="false_body", marker="false:"),+ CollectInvocation(id="false_collect"),+ ]+ edges += [+ ("outer", "item", "middle2_source", "first"),+ ("middle2_source", "collection", "middle2", "collection"),+ ("middle2", "item", "deep2_source", "first"),+ ("deep2_source", "collection", "deep2", "collection"),+ ("deep2", "item", "false_body", "value"),+ ("false_body", "value", "false_collect", "item"),+ ]+ false_source = "false_collect"+ if not unrelated_root_collect and unrelated_root_collect_branch != "false_input":+ edges.append((false_source, "collection", "if", "false_input"))+ else:+ nodes += [MarkedAnyTypeTestInvocation(id="false_body", marker="false:"), CollectInvocation(id="false_collect")]+ edges += [+ ("deep", "item", "false_body", "value"),+ ("false_body", "value", "false_collect", "item"),+ ]+ if shape == "asymmetric":+ nodes.append(CollectInvocation(id="false_outer_collect"))+ edges += [+ ("false_collect", "collection", "false_outer_collect", "item"),+ ]+ false_source = "false_outer_collect"+ else:+ false_source = "false_collect"+ if not unrelated_root_collect and unrelated_root_collect_branch != "false_input":+ edges.append((false_source, "collection", "if", "false_input"))+ if unrelated_root_collect or unrelated_root_collect_branch:+ nodes += [+ CollectionConcatInvocation(id="unrelated_source", first=[]),+ IterateInvocation(id="unrelated_iterate"),+ AnyTypeTestInvocation(id="unrelated_body"),+ CollectInvocation(id="unrelated_collect"),+ ]+ edges += [+ ("unrelated_source", "collection", "unrelated_iterate", "collection"),+ ("unrelated_iterate", "item", "unrelated_body", "value"),+ ("unrelated_body", "value", "unrelated_collect", "item"),+ ]+ append_fields = (+ {"true_input", "false_input"}+ if unrelated_root_collect+ else {unrelated_root_collect_branch}+ if unrelated_root_collect_branch+ else set()+ )+ for branch_field, branch_source in (("true_input", "true_collect"), ("false_input", false_source)):+ if branch_field in append_fields:+ append_id = f"{branch_field}_append"+ nodes.append(CollectionConcatInvocation(id=append_id))+ edges += [+ (branch_source, "collection", append_id, "first"),+ ("unrelated_collect", "collection", append_id, "second"),+ (append_id, "collection", "if", branch_field),+ ]+ return _graph_from(nodes, edges)++[email protected]("unrelated_root_collect", [False, True], ids=["plain", "unrelated-collect"])[email protected]("force_compatibility_scheduler", [False, True], ids=["default", "compatibility"])+def test_if_accepts_separate_collects_retaining_matching_axes(+ unrelated_root_collect: bool, force_compatibility_scheduler: bool+) -> None:+ state = GraphExecutionState(+ graph=_separate_collect_branches_graph(shape="matching", unrelated_root_collect=unrelated_root_collect)+ )+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert not state.has_error(), state.errors+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {+ (0,): [["true:a", "true:b"], ["true:c"]],+ (1,): [["true:d"]],+ }+ assert trace.count("if") == 3+ assert any(source_id == "false_body" for source_id in trace)++[email protected]("unrelated_root_collect_branch", ["true_input", "false_input"])[email protected]("force_compatibility_scheduler", [False, True], ids=["default", "compatibility"])+def test_if_accepts_matching_collect_axes_with_one_sided_unrelated_root_collect(+ unrelated_root_collect_branch: str, force_compatibility_scheduler: bool+) -> None:+ state = GraphExecutionState(+ graph=_separate_collect_branches_graph(+ shape="matching", unrelated_root_collect=False, unrelated_root_collect_branch=unrelated_root_collect_branch+ )+ )+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert not state.has_error(), state.errors+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {+ (0,): [["true:a", "true:b"], ["true:c"]],+ (1,): [["true:d"]],+ }+ assert trace.count("if") == 3+ assert "unrelated_body" not in trace++[email protected]("shape", ["asymmetric", "distinct-inner-axis"], ids=["O-M-vs-O", "O-M-vs-O-M2"])[email protected]("unrelated_root_collect", [False, True], ids=["plain", "unrelated-collect"])[email protected]("force_compatibility_scheduler", [False, True], ids=["default", "compatibility"])+def test_if_rejects_separate_collects_with_different_axes_before_invocation(+ shape: str, unrelated_root_collect: bool, force_compatibility_scheduler: bool+) -> None:+ state = GraphExecutionState(+ graph=_separate_collect_branches_graph(shape=shape, unrelated_root_collect=unrelated_root_collect)+ )+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)++ with pytest.raises(graph_if_runtime.UnsupportedIfIterationAxesError):+ state.next()+ assert state.executed_history == []++[email protected]("force_compatibility_scheduler", [False, True], ids=["default", "compatibility"])+ ("source_values", "expected", "if_count"),+ [([[]], {(0,): []}, 0), ([[], []], {(0,): [], (1,): []}, 0), ([[[]], [[]]], {(0,): [[[]]], (1,): [[[]]]}, 2)],+ ids=["empty-outer", "empty-outer-frames", "empty-deep-groups"],+)+def test_shared_collect_chain_completes_empty_groups(+ force_compatibility_scheduler: bool, source_values: list[Any], expected: dict[tuple[int, ...], Any], if_count: int+) -> None:+ state = GraphExecutionState(+ graph=_outer_condition_with_two_collects_graph(share_branch_axes=True, source_values=source_values)+ )+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert not state.has_error(), state.errors+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == expected+ assert trace.count("if") == if_count+ assert trace.count("false_copy") == if_count++[email protected]("force_compatibility_scheduler", [False, True], ids=["default", "compatibility"])+def test_if_branch_frame_axes_handles_long_passthrough_chain(force_compatibility_scheduler: bool) -> None:+ nodes: list[Any] = [CollectionConcatInvocation(id="source", first=["x"]), IterateInvocation(id="iterate")]+ edges: list[Any] = [("source", "collection", "iterate", "collection")]+ previous = ("iterate", "item")+ for index in range(1000):+ node_id = f"pass{index}"+ nodes.append(AnyTypeTestInvocation(id=node_id))+ edges.append((*previous, node_id, "value"))+ previous = (node_id, "value")+ nodes += [+ FixedCollectionTestInvocation(id="condition", value=True),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ]+ edges += [+ ("iterate", "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ (*previous, "if", "true_input"),+ ("if", "value", "collect", "item"),+ ]+ state = GraphExecutionState(graph=_graph_from(nodes, edges))+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert not state.has_error(), state.errors+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {(): ["x"]}++[email protected]("force_compatibility_scheduler", [False, True], ids=["default", "compatibility"])+def test_per_item_if_rejects_asymmetric_collect_chain_before_invocation(+ force_compatibility_scheduler: bool,+) -> None:+ state = GraphExecutionState(graph=_outer_condition_with_two_collects_graph(share_branch_axes=False))+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)++ with pytest.raises(graph_if_runtime.UnsupportedIfIterationAxesError, match="deeper open iterator axes"):+ state.next()+ assert state.executed_history == []++[email protected]("force_compatibility_scheduler", [False, True], ids=["default", "compatibility"])+def test_per_item_if_accepts_shared_collect_chain_axes_and_completes(+ force_compatibility_scheduler: bool,+) -> None:+ state = GraphExecutionState(graph=_outer_condition_with_two_collects_graph(share_branch_axes=True))+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert not state.has_error(), state.errors+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {+ (0,): [[["b:a"], ["b:b"]], [["b:c"]]],+ (1,): [],+ (2,): [[["b:d", "b:e"]]],+ }+ assert trace.count("if") == 3+ assert trace.count("false_copy") == 4++[email protected]("force_compatibility_scheduler", [False, True], ids=["default", "compatibility"])+def test_per_item_if_preserves_collect_axes_through_passthrough_and_completes(+ force_compatibility_scheduler: bool,+) -> None:+ state = GraphExecutionState(+ graph=_outer_condition_with_two_collects_graph(share_branch_axes=True, passthrough_between_collects=True)+ )+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert not state.has_error(), state.errors+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {+ (0,): [[["b:a"], ["b:b"]], [["b:c"]]],+ (1,): [],+ (2,): [[["b:d", "b:e"]]],+ }+ assert trace.count("if") == 3+ assert trace.count("false_copy") == 4+++def _reopen_of_a_cross_product_graph(swap_add_inputs: bool, condition: bool = False) -> Graph:+ """A literal If chooses between an Iterate reopening a Collect over two crossed axes and the crossed inner axis."""+ first_axis, second_axis = ("right", "left") if swap_add_inputs else ("left", "right")+ return _graph_from(+ [+ CollectionConcatInvocation(id="left_src", first=[1, 2]),+ IterateInvocation(id="left"),+ CollectionConcatInvocation(id="right_src", first=[10, 20, 30]),+ IterateInvocation(id="right"),+ AddInvocation(id="add"),+ CollectInvocation(id="closing_collect"),+ IterateInvocation(id="reopened"),+ MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),+ MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),+ IfInvocation(id="if", condition=condition),+ CollectInvocation(id="collect"),+ ],+ [+ ("left_src", "collection", "left", "collection"),+ ("right_src", "collection", "right", "collection"),+ (first_axis, "item", "add", "a"),+ (second_axis, "item", "add", "b"),+ ("add", "value", "closing_collect", "item"),+ ("closing_collect", "collection", "reopened", "collection"),+ ("reopened", "item", "true_value", "value"),+ ("true_value", "value", "if", "true_input"),+ (second_axis, "item", "false_value", "value"),+ ("false_value", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ],+ )+++def _reopen_of_a_different_closed_axis_graph() -> Graph:+ return _graph_from(+ [+ CollectionConcatInvocation(id="closed_src", first=["z1", "z2", "z3"]),+ IterateInvocation(id="closed"),+ CollectInvocation(id="closing_collect"),+ IterateInvocation(id="reopened"),+ MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),+ CollectionConcatInvocation(id="other_src", first=["u1", "u2"]),+ IterateInvocation(id="other"),+ MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),+ IfInvocation(id="if", condition=True),+ CollectInvocation(id="collect"),+ ],+ [+ ("closed_src", "collection", "closed", "collection"),+ ("closed", "item", "closing_collect", "item"),+ ("closing_collect", "collection", "reopened", "collection"),+ ("reopened", "item", "true_value", "value"),+ ("true_value", "value", "if", "true_input"),+ ("other_src", "collection", "other", "collection"),+ ("other", "item", "false_value", "value"),+ ("false_value", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ],+ )+++def _for_output_connected_to_selected_axis_graph(selected_is_downstream: bool) -> Graph:+ """A For's final output on the unselected branch, under an axis connected to the selected one by a reopen."""+ upstream_ids = ("upstream_src", "upstream")+ downstream_ids = ("downstream_src", "downstream")+ for_parent = upstream_ids[1] if selected_is_downstream else downstream_ids[1]+ selected_axis = downstream_ids[1] if selected_is_downstream else upstream_ids[1]+ return _graph_from(+ [+ CollectionConcatInvocation(id="upstream_src", first=[["a0", "a1"], ["a2"]]),+ IterateInvocation(id="upstream"),+ MarkedAnyTypeTestInvocation(id="body", marker="b:"),+ CollectInvocation(id="closing_collect"),+ CollectionConcatInvocation(id="downstream_src", second=[["x"]]),+ IterateInvocation(id="downstream"),+ FixedCollectionTestInvocation(id="for_items"),+ ForInvocation(id="for"),+ ForReturnInvocation(id="return"),+ MarkedAnyTypeTestInvocation(id="selected_value", marker="s:"),+ IfInvocation(id="if", condition=True),+ CollectInvocation(id="collect"),+ ],+ [+ ("upstream_src", "collection", "upstream", "collection"),+ ("upstream", "item", "body", "value"),+ ("body", "value", "closing_collect", "item"),+ ("closing_collect", "collection", "downstream_src", "first"),+ ("downstream_src", "collection", "downstream", "collection"),+ (for_parent, "item", "for_items", "value"),+ ("for_items", "collection", "for", "collection"),+ ("for", "item", "return", "output"),+ create_loop_linkage("for", "return"),+ ("for", "output_collection", "if", "false_input"),+ (selected_axis, "item", "selected_value", "value"),+ ("selected_value", "value", "if", "true_input"),+ ("if", "value", "collect", "item"),+ ],+ )+++ ("selected_is_downstream", "expected"),+ [+ (True, ["s:b:['a0', 'a1']", "s:b:['a2']", "s:['x']"]),+ (False, ["s:['a0', 'a1']", "s:['a2']"]),+ ],+ ids=["selects-reopened-axis", "selects-closed-axis"],+)+def test_literal_if_ignores_unselected_for_output_under_an_axis_connected_to_the_selected_one(+ selected_is_downstream: bool, expected: list[str]+) -> None:+ """An unselected For final output adds no frames even when its axis feeds, or is fed by, the selected axis."""+ _trace, state = _run_to_completion(_for_output_connected_to_selected_axis_graph(selected_is_downstream))++ assert _source_values(state, "collect") == {(): expected}++[email protected]("condition_from_branch", [False, True], ids=["literal", "condition-from-branch"])+def test_if_over_cross_product_carried_by_its_deciding_input_completes(condition_from_branch: bool) -> None:+ """Unrelated axes combined by one input are that input's own frames, so the If keeps the cross product."""+ _trace, state = _run_to_completion(_cross_product_branch_graph(True, condition_from_branch))++ assert _source_values(state, "collect") == {(0,): [11, 21, 31], (1,): [12, 22, 32]}+++def test_literal_if_selecting_axis_reopened_directly_from_a_collect_pairs_frames() -> None:+ """An Iterate fed straight from the Collect that closed the other axis has its length, so frames pair by index."""+ _trace, state = _run_to_completion(_collect_then_reopen_graph(True))++ assert _source_values(state, "collect") == {(0,): ["t:b:a1"], (1,): ["t:b:a2"]}+++def test_literal_if_selecting_axis_reopened_through_two_collects_pairs_frames() -> None:+ """A chain of direct reopens keeps the first axis's length, so the last reopened axis pairs with it."""+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="src", first=["a1", "a2", "a3"]),+ IterateInvocation(id="first"),+ MarkedAnyTypeTestInvocation(id="first_body", marker="b:"),+ CollectInvocation(id="first_collect"),+ IterateInvocation(id="middle"),+ MarkedAnyTypeTestInvocation(id="middle_body", marker="c:"),+ CollectInvocation(id="middle_collect"),+ IterateInvocation(id="last"),+ MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),+ MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),+ IfInvocation(id="if", condition=True),+ CollectInvocation(id="collect"),+ ],+ [+ ("src", "collection", "first", "collection"),+ ("first", "item", "first_body", "value"),+ ("first_body", "value", "first_collect", "item"),+ ("first_collect", "collection", "middle", "collection"),+ ("middle", "item", "middle_body", "value"),+ ("middle_body", "value", "middle_collect", "item"),+ ("middle_collect", "collection", "last", "collection"),+ ("last", "item", "true_value", "value"),+ ("true_value", "value", "if", "true_input"),+ ("first", "item", "false_value", "value"),+ ("false_value", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ],+ )+ _trace, state = _run_to_completion(graph)++ assert _source_values(state, "collect") == {(0,): ["t:c:b:a1"], (1,): ["t:c:b:a2"], (2,): ["t:c:b:a3"]}+++def test_literal_if_selecting_axis_reopened_from_nested_collects_pairs_with_the_outer_axis() -> None:+ """Each Collect in a chain closes one more axis, so the last one gathers one item per outermost frame."""+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="outer_src", first=[[["a"], ["b"]], [["c", "d"]]]),+ IterateInvocation(id="outer"),+ CollectionConcatInvocation(id="middle_src"),+ IterateInvocation(id="middle"),+ CollectionConcatInvocation(id="inner_src"),+ IterateInvocation(id="inner"),+ MarkedAnyTypeTestInvocation(id="body", marker="b:"),+ CollectInvocation(id="inner_collect"),+ CollectInvocation(id="middle_collect"),+ CollectInvocation(id="outer_collect"),+ IterateInvocation(id="reopened"),+ MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),+ MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),+ IfInvocation(id="if", condition=True),+ CollectInvocation(id="collect"),+ ],+ [+ ("outer_src", "collection", "outer", "collection"),+ ("outer", "item", "middle_src", "first"),+ ("middle_src", "collection", "middle", "collection"),+ ("middle", "item", "inner_src", "first"),+ ("inner_src", "collection", "inner", "collection"),+ ("inner", "item", "body", "value"),+ ("body", "value", "inner_collect", "item"),+ ("inner_collect", "collection", "middle_collect", "item"),+ ("middle_collect", "collection", "outer_collect", "item"),+ ("outer_collect", "collection", "reopened", "collection"),+ ("reopened", "item", "true_value", "value"),+ ("true_value", "value", "if", "true_input"),+ ("outer", "item", "false_value", "value"),+ ("false_value", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ],+ )+ _trace, state = _run_to_completion(graph)++ assert _source_values(state, "collect") == {+ (0,): ["t:[['b:a'], ['b:b']]"],+ (1,): ["t:[['b:c', 'b:d']]"],+ }+++def test_literal_if_selecting_axis_nested_under_a_reopened_axis_pairs_frames() -> None:+ """An Iterate nested under a direct reopen runs in the reopened frames, which pair with the closed axis."""+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="src", first=[["x1", "x2"], ["y1"]]),+ IterateInvocation(id="first"),+ AnyTypeTestInvocation(id="body"),+ CollectInvocation(id="closing_collect"),+ IterateInvocation(id="reopened"),+ CollectionConcatInvocation(id="nested_src"),+ IterateInvocation(id="nested"),+ MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),+ MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),+ IfInvocation(id="if", condition=True),+ CollectInvocation(id="collect"),+ ],+ [+ ("src", "collection", "first", "collection"),+ ("first", "item", "body", "value"),+ ("body", "value", "closing_collect", "item"),+ ("closing_collect", "collection", "reopened", "collection"),+ ("reopened", "item", "nested_src", "first"),+ ("nested_src", "collection", "nested", "collection"),+ ("nested", "item", "true_value", "value"),+ ("true_value", "value", "if", "true_input"),+ ("first", "item", "false_value", "value"),+ ("false_value", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ],+ )+ _trace, state = _run_to_completion(graph)++ assert _source_values(state, "collect") == {(0, 0): ["t:x1"], (0, 1): ["t:x2"], (1, 0): ["t:y1"]}+++def test_literal_if_selecting_axis_reopened_within_kept_outer_frames_pairs_both_axes() -> None:+ """A Collect closing an inner axis keeps the outer one; its reopening pairs with the inner axis per outer frame."""+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="outer_src", first=[["a1", "a2"], ["b1"]]),+ IterateInvocation(id="outer"),+ CollectionConcatInvocation(id="inner_src"),+ IterateInvocation(id="inner"),+ MarkedAnyTypeTestInvocation(id="body", marker="b:"),+ CollectInvocation(id="closing_collect"),+ IterateInvocation(id="reopened"),+ MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),+ MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),+ IfInvocation(id="if", condition=True),+ CollectInvocation(id="collect"),+ ],+ [+ ("outer_src", "collection", "outer", "collection"),+ ("outer", "item", "inner_src", "first"),+ ("inner_src", "collection", "inner", "collection"),+ ("inner", "item", "body", "value"),+ ("body", "value", "closing_collect", "item"),+ ("closing_collect", "collection", "reopened", "collection"),+ ("reopened", "item", "true_value", "value"),+ ("true_value", "value", "if", "true_input"),+ ("inner", "item", "false_value", "value"),+ ("false_value", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ],+ )+ _trace, state = _run_to_completion(graph)++ assert _source_values(state, "collect") == {(0, 0): ["t:b:a1"], (0, 1): ["t:b:a2"], (1, 0): ["t:b:b1"]}+++ ("condition", "expected"),+ [+ (False, {(0,): [["a0", "a1"]], (1,): [["a2"]]}),+ (True, {(0,): [["b0"]], (1,): [["b1"]], (2,): [["b2"]]}),+ ],+ ids=["selects-a", "selects-b"],+)+def test_literal_if_collect_groups_selected_for_final_by_parent_frame(+ condition: bool, expected: dict[tuple[int, ...], list[list[str]]]+) -> None:+ """The selected For final closes its own axis while the parent Iterate frame stays open."""+ nodes: list[Any] = [IfInvocation(id="if", condition=condition), CollectInvocation(id="collect")]+ edges: list[Any] = [("if", "value", "collect", "item")]+ for prefix, values, branch in (+ ("a", [["a0", "a1"], ["a2"]], "false_input"),+ ("b", [["b0"], ["b1"], ["b2"]], "true_input"),+ ):+ nodes += [+ CollectionConcatInvocation(id=f"{prefix}_src", first=values),+ IterateInvocation(id=f"{prefix}_iter"),+ ForInvocation(id=f"{prefix}_for"),+ ForReturnInvocation(id=f"{prefix}_return"),+ ]+ edges += [+ (f"{prefix}_src", "collection", f"{prefix}_iter", "collection"),+ (f"{prefix}_iter", "item", f"{prefix}_for", "collection"),+ (f"{prefix}_for", "item", f"{prefix}_return", "output"),+ create_loop_linkage(f"{prefix}_for", f"{prefix}_return"),+ (f"{prefix}_for", "output_collection", "if", branch),+ ]+ _trace, state = _run_to_completion(_graph_from(nodes, edges))++ assert _source_values(state, "collect") == expected++[email protected]("condition_source", ["literal", "computed"], ids=["literal", "computed"])[email protected]("condition", [True, False], ids=["true", "false"])[email protected]("unselected_values", [[], [["u", "v"]]], ids=["empty-unselected", "non-empty-unselected"])[email protected]("force_compatibility_scheduler", [False, True], ids=["default", "compatibility"])+def test_root_if_selection_runs_unselected_for_when_axis_has_items(+ condition_source: str, condition: bool, unselected_values: list[Any], force_compatibility_scheduler: bool+) -> None:+ root_branch, for_branch = ("true_input", "false_input") if condition else ("false_input", "true_input")+ nodes: list[Any] = [+ CollectionConcatInvocation(id="source", first=unselected_values),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ ForReturnInvocation(id="return"),+ AnyTypeTestInvocation(id="root", value="root"),+ IfInvocation(id="if", **({"condition": condition} if condition_source == "literal" else {})),+ CollectInvocation(id="collect"),+ ]+ edges: list[Any] = [+ ("source", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "return", "output"),+ create_loop_linkage("for", "return"),+ ("root", "value", "if", root_branch),+ ("for", "output_collection", "if", for_branch),+ ("if", "value", "collect", "item"),+ ]+ if condition_source == "computed":+ nodes.append(FixedCollectionTestInvocation(id="condition", value=condition))+ edges.append(("condition", "condition", "if", "condition"))+ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )++ assert not state.has_error(), state.errors+ assert state.is_complete(), f"graph stalled after {trace}"+ assert _source_values(state, "collect") == {(): ["root"]}+ assert trace.count("if") == 1+ if unselected_values:+ assert {"for", "return"} <= set(trace)+ else:+ assert not {"for", "return"} & set(trace)++[email protected]("condition", [True, False])+def test_root_condition_if_broadcasts_over_nested_axes_both_branches_share(condition: bool) -> None:+ """A root-frame condition selects between branches that run in the same nested frames, once per inner item."""+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="src", first=[["p", "q"], ["r"]]),+ IterateInvocation(id="outer"),+ CollectionConcatInvocation(id="inner_src", first=[]),+ IterateInvocation(id="inner"),+ MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),+ MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),+ FixedCollectionTestInvocation(id="condition", value=condition),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ],+ [+ ("src", "collection", "outer", "collection"),+ ("outer", "item", "inner_src", "first"),+ ("inner_src", "collection", "inner", "collection"),+ ("inner", "item", "true_value", "value"),+ ("inner", "item", "false_value", "value"),+ ("true_value", "value", "if", "true_input"),+ ("false_value", "value", "if", "false_input"),+ ("condition", "condition", "if", "condition"),+ ("if", "value", "collect", "item"),+ ],+ )++ _trace, state = _run_to_completion(graph)++ marker = "t:" if condition else "f:"+ assert _source_values(state, "collect") == {(0,): [f"{marker}p", f"{marker}q"], (1,): [f"{marker}r"]}+++def _shared_nested_axes_graph(data: list[Any], levels: int, condition_on_outer: bool) -> Graph:+ """Both branches read the innermost of ``levels`` nested Iterates; the condition is root or per outer item."""+ axis_ids = ["outer", "middle", "inner"] if levels == 3 else ["outer", "inner"]+ nodes: list[Any] = [CollectionConcatInvocation(id="src", first=data), IterateInvocation(id=axis_ids[0])]+ edges: list[Any] = [("src", "collection", axis_ids[0], "collection")]+ for parent_id, axis_id in itertools.pairwise(axis_ids):+ nodes += [CollectionConcatInvocation(id=f"{axis_id}_src", first=[]), IterateInvocation(id=axis_id)]+ edges += [+ (parent_id, "item", f"{axis_id}_src", "first"),+ (f"{axis_id}_src", "collection", axis_id, "collection"),+ ]+ nodes += [+ MarkedAnyTypeTestInvocation(id="true_value", marker="t:"),+ MarkedAnyTypeTestInvocation(id="false_value", marker="f:"),+ FixedCollectionTestInvocation(id="condition", value=True),+ IfInvocation(id="if"),+ ]+ edges += [+ (axis_ids[-1], "item", "true_value", "value"),+ (axis_ids[-1], "item", "false_value", "value"),+ ("true_value", "value", "if", "true_input"),+ ("false_value", "value", "if", "false_input"),+ ("condition", "condition", "if", "condition"),+ ]+ if condition_on_outer:+ edges.append((axis_ids[0], "item", "condition", "value"))+ previous = ("if", "value")+ for index in range(levels):+ nodes.append(CollectInvocation(id=f"collect{index}"))+ edges.append((*previous, f"collect{index}", "item"))+ previous = (f"collect{index}", "collection")+ return _graph_from(nodes, edges)+++def test_per_item_condition_if_over_three_shared_nested_axes_completes() -> None:+ """A per-outer-item condition broadcasts over two deeper shared axes, and no Collect closes before the If runs."""+ graph = _shared_nested_axes_graph([[["p", "q"], ["r"]], [["s"]]], levels=3, condition_on_outer=True)++ trace, state = _run_to_completion(graph)++ assert _source_values(state, "collect2") == {(): [[["t:p", "t:q"], ["t:r"]], [["t:s"]]]}+ assert trace.index("collect0") > max(index for index, source_id in enumerate(trace) if source_id == "if")+++ ("data", "levels", "expected"),+ [+ pytest.param([[], []], 2, {(): [[], []]}, id="two-levels"),+ pytest.param([[[], []], [[]]], 3, {(): [[[], []], [[]]]}, id="three-levels"),+ ],+)+def test_root_condition_if_over_shared_nested_axes_with_empty_innermost_iterate_has_no_frames(+ data: list[Any], levels: int, expected: dict[tuple[int, ...], Any]+) -> None:+ """An innermost shared Iterate empty in every frame leaves a root-conditioned If no frames, as a literal one has."""+ trace, state = _run_to_completion(_shared_nested_axes_graph(data, levels=levels, condition_on_outer=False))++ assert _source_values(state, f"collect{levels - 1}") == expected+ assert "if" not in trace+++def test_literal_if_selecting_for_output_under_empty_iterate_has_no_frames() -> None:+ """An Iterate with no items that a selected branch For runs under leaves the If no executions."""+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="src", first=[]),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ MarkedAnyTypeTestInvocation(id="body", marker="b:"),+ ForReturnInvocation(id="ret"),+ AnyTypeTestInvocation(id="mid"),+ AnyTypeTestInvocation(id="fallback", value="fb"),+ IfInvocation(id="if", condition=True),+ CollectInvocation(id="collect"),+ ],+ [+ ("src", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "mid", "value"),+ ("mid", "value", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ],+ )++ trace, state = _run_to_completion(graph)++ assert _source_values(state, "collect") == {(): []}+ assert "if" not in trace and "fallback" not in trace++[email protected]("fail_unselected", [False, True], ids=["succeeds", "unselected-fails"])+def test_per_item_if_gates_branch_for_together_with_the_for_nested_in_its_body(fail_unselected: bool) -> None:+ """Eager branch execution brings a nested For along after its frame-local condition resolves."""+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="outer_source", first=["", "x"]),+ IterateInvocation(id="outer_iterate"),+ FixedCollectionTestInvocation(id="items"),+ ForInvocation(id="for"),+ FixedCollectionTestInvocation(id="mk"),+ ForInvocation(id="ifor"),+ AnyTypeTestInvocation(id="ibody"),+ ForReturnInvocation(id="ireturn"),+ ForReturnInvocation(id="return"),+ CollectInvocation(id="branch_collect"),+ AnyTypeTestInvocation(id="fallback", value="fallback"),+ IfInvocation(id="if"),+ AnyTypeTestInvocation(id="sink"),+ ],+ [+ ("outer_source", "collection", "outer_iterate", "collection"),+ ("outer_iterate", "item", "items", "value"),+ ("items", "condition", "if", "condition"),+ ("items", "collection", "for", "collection"),+ ("for", "item", "mk", "value"),+ ("mk", "collection", "ifor", "collection"),+ ("ifor", "item", "ibody", "value"),+ ("ibody", "value", "ireturn", "output"),+ create_loop_linkage("ifor", "ireturn"),+ ("ifor", "output_collection", "return", "output"),+ create_loop_linkage("for", "return"),+ ("for", "output_collection", "branch_collect", "item"),+ ("branch_collect", "collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "sink", "value"),+ ],+ )+ gated_sources = {"for", "mk", "ifor", "ibody", "ireturn", "return", "branch_collect"}++ state = GraphExecutionState(graph=graph)+ trace: list[tuple[str, tuple[int, ...]]] = []+ while (node := state.next()) is not None:+ source_id = state.prepared_source_mapping[node.id]+ iteration_path = state._get_iteration_path(node.id)+ trace.append((source_id, iteration_path))+ if fail_unselected and source_id in gated_sources and iteration_path[:1] == (0,):+ state.set_node_error(node.id, f"{source_id} ran for an unselected item")+ continue+ state.complete(node.id, node.invoke(Mock()))++ if fail_unselected:+ assert state.has_error(), state.errors+ assert any("ran for an unselected item" in error for error in state.errors.values())+ return+ assert not state.has_error(), state.errors+ assert state.is_complete(), f"execution stalled after {trace}"+ assert [entry for entry in trace if entry[0] in gated_sources and entry[1][:1] == (0,)]+ assert _source_values(state, "sink") == {(0,): "fallback", (1,): [[[0, 1], [0, 1]]]}+++ ("build_graph", "message"),+ [+ pytest.param(+ lambda: _unrelated_open_branches_graph(True, False),+ "unrelated open iterator axes",+ id="unrelated-literal-T",+ ),+ pytest.param(+ lambda: _unrelated_open_branches_graph(False, False),+ "unrelated open iterator axes",+ id="unrelated-literal-F",+ ),+ pytest.param(+ lambda: _unrelated_open_branches_graph(True, True),+ "unrelated open iterator axes",+ id="unrelated-computed-T",+ ),+ pytest.param(+ lambda: _unrelated_open_branches_graph(False, True),+ "unrelated open iterator axes",+ id="unrelated-computed-F",+ ),+ pytest.param(+ lambda: _root_condition_with_deeper_axis_on_one_branch_graph([[], ["p", "q"]]),+ "different deeper open iterator axes",+ id="root-condition-partly-empty-deeper-axis",+ ),+ pytest.param(+ lambda: _root_condition_with_deeper_axis_on_one_branch_graph([["p"], ["q", "r"]]),+ "different deeper open iterator axes",+ id="root-condition-deeper-axis",+ ),+ pytest.param(+ _per_item_condition_with_deeper_collect_branch_graph,+ "deeper open iterator axes kept by a Collect",+ id="per-item-condition-deeper-collect",+ ),+ pytest.param(+ _per_item_condition_with_deeper_for_output_collect_branch_graph,+ "deeper open iterator axes kept by a Collect",+ id="per-item-condition-deeper-for-output-collect",+ ),+ pytest.param(+ lambda: _cross_product_branch_graph(condition=False),+ "unrelated open iterator axes",+ id="literal-root-value-over-cross-product",+ ),+ pytest.param(+ _per_item_condition_with_collect_of_collects_branch_graph,+ "deeper open iterator axes kept by a Collect",+ id="per-item-condition-deeper-collect-beside-collect-of-collects",+ ),+ pytest.param(+ lambda: _collect_then_reopen_graph(condition=False, extra_items=("x",)),+ "unrelated open iterator axes",+ id="literal-selects-axis-a-collect-closed-before-the-other",+ ),+ pytest.param(+ lambda: _collect_then_reopen_graph(condition=True, extra_items=("x",)),+ "unrelated open iterator axes",+ id="literal-selects-axis-reopened-through-a-node-after-the-collect",+ ),+ pytest.param(+ lambda: _collect_then_reopen_graph(condition=True, appended_items=("x",)),+ "unrelated open iterator axes",+ id="literal-selects-axis-reopened-from-a-collect-that-appends-items",+ ),+ pytest.param(+ _collect_with_literal_items_then_reopen_graph,+ "unrelated open iterator axes",+ id="literal-selects-axis-reopened-from-a-collect-with-literal-items",+ ),+ pytest.param(+ lambda: _collect_then_reopen_graph(condition=False),+ "unrelated open iterator axes",+ id="literal-selects-axis-an-iterate-reopens",+ ),+ pytest.param(+ lambda: _reopen_of_a_cross_product_graph(swap_add_inputs=False),+ "unrelated open iterator axes",+ id="literal-selects-closed-axis-of-a-reopened-cross-product",+ ),+ pytest.param(+ lambda: _reopen_of_a_cross_product_graph(swap_add_inputs=True),+ "unrelated open iterator axes",+ id="literal-selects-closed-axis-of-a-reopened-swapped-cross-product",),pytest.param(lambda: _reopen_of_a_cross_product_graph(swap_add_inputs=True, condition=True),@@ -4483,343 +5848,852 @@ def test_per_item_if_gates_branch_for_together_with_the_for_nested_in_its_body(f),],)-def test_if_without_one_nested_chain_of_frames_is_rejected_before_any_node_runs(- build_graph: Callable[[], Graph], message: str+def test_if_without_one_nested_chain_of_frames_is_rejected_before_any_node_runs(+ build_graph: Callable[[], Graph], message: str+) -> None:+ """An If runs once per frame of a single chain of nested open axes; other frame sets fail before running."""+ state = GraphExecutionState(graph=build_graph())++ with pytest.raises(graph_if_runtime.UnsupportedIfIterationAxesError, match=message):+ _run(state)+ assert state.executed_history == []++[email protected]("fail_unselected", [False, True], ids=["succeeds", "unselected-fails"])+def test_per_item_if_keeps_shared_for_running_but_gates_its_branch_collect(fail_unselected: bool) -> None:+ """A shared For and its branch Collect both run after each frame-local gate resolves."""+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="outer_source", first=["", "x"]),+ IterateInvocation(id="outer_iterate"),+ FixedCollectionTestInvocation(id="items"),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="body"),+ ForReturnInvocation(id="return"),+ CollectInvocation(id="collect"),+ CollectInvocation(id="other_collect"),+ AnyTypeTestInvocation(id="side_sink"),+ AnyTypeTestInvocation(id="fallback", value="fallback"),+ IfInvocation(id="if"),+ AnyTypeTestInvocation(id="sink"),+ ],+ [+ ("outer_source", "collection", "outer_iterate", "collection"),+ ("outer_iterate", "item", "items", "value"),+ ("items", "condition", "if", "condition"),+ ("items", "collection", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "return", "output"),+ create_loop_linkage("for", "return"),+ ("for", "output_collection", "collect", "item"),+ ("collect", "collection", "if", "true_input"),+ ("for", "output_collection", "other_collect", "item"),+ ("other_collect", "collection", "side_sink", "value"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "sink", "value"),+ ],+ )++ state = GraphExecutionState(graph=graph)+ trace: list[tuple[str, tuple[int, ...]]] = []+ while (node := state.next()) is not None:+ source_id = state.prepared_source_mapping[node.id]+ iteration_path = state._get_iteration_path(node.id)+ trace.append((source_id, iteration_path))+ if fail_unselected and source_id == "collect" and iteration_path[:1] == (0,):+ state.set_node_error(node.id, "collect ran for an unselected item")+ continue+ state.complete(node.id, node.invoke(Mock()))++ if fail_unselected:+ assert state.has_error(), state.errors+ assert any("collect ran for an unselected item" in error for error in state.errors.values())+ return+ assert not state.has_error(), state.errors+ assert state.is_complete(), f"execution stalled after {trace}"+ assert ("collect", (0,)) in trace+ assert _source_values(state, "sink") == {(0,): "fallback", (1,): [[0, 1]]}+ assert _source_values(state, "side_sink") == {(0,): [[0, 1]], (1,): [[0, 1]]}+++def _shared_outer_iterate_branch_graph(condition: bool) -> Graph:+ """The outer frame reaches the If only through the deferred branch, so the If cannot see it yet."""+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="outer_source", first=["x", "y"]))+ graph.add_node(IterateInvocation(id="outer_iterate"))+ graph.add_node(AnyTypeTestInvocation(id="side"))+ graph.add_node(FixedCollectionTestInvocation(id="inner_source"))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(AnyTypeTestInvocation(id="body"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_node(AnyTypeTestInvocation(id="fallback", value=["fallback"]))+ graph.add_node(IfInvocation(id="if", condition=condition))+ graph.add_node(AnyTypeTestInvocation(id="sink"))+ graph.add_edge(create_edge("outer_source", "collection", "outer_iterate", "collection"))+ graph.add_edge(create_edge("outer_iterate", "item", "side", "value"))+ graph.add_edge(create_edge("outer_iterate", "item", "inner_source", "value"))+ graph.add_edge(create_edge("inner_source", "collection", "iterate", "collection"))+ graph.add_edge(create_edge("iterate", "item", "body", "value"))+ graph.add_edge(create_edge("body", "value", "collect", "item"))+ graph.add_edge(create_edge("collect", "collection", "if", "true_input"))+ graph.add_edge(create_edge("fallback", "value", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "sink", "value"))+ return graph+++def _sibling_iterates_branch_graph(condition: bool) -> Graph:+ """The Collect closes only one of two sibling frames, so the If inherits the other."""+ graph = Graph()+ graph.add_node(FixedCollectionTestInvocation(id="left_source"))+ graph.add_node(FixedCollectionTestInvocation(id="right_source"))+ graph.add_node(IterateInvocation(id="left_iterate"))+ graph.add_node(IterateInvocation(id="right_iterate"))+ graph.add_node(AddInvocation(id="body"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_node(AnyTypeTestInvocation(id="fallback", value=["fallback"]))+ graph.add_node(IfInvocation(id="if", condition=condition))+ graph.add_node(AnyTypeTestInvocation(id="sink"))+ graph.add_edge(create_edge("left_source", "collection", "left_iterate", "collection"))+ graph.add_edge(create_edge("right_source", "collection", "right_iterate", "collection"))+ graph.add_edge(create_edge("left_iterate", "item", "body", "a"))+ graph.add_edge(create_edge("right_iterate", "item", "body", "b"))+ graph.add_edge(create_edge("body", "value", "collect", "item"))+ graph.add_edge(create_edge("collect", "collection", "if", "true_input"))+ graph.add_edge(create_edge("fallback", "value", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "sink", "value"))+ return graph+++ "build_graph",+ [_shared_outer_iterate_branch_graph, _sibling_iterates_branch_graph],+ ids=["outer-frame-through-branch", "sibling-frame-left-open"],+)+def test_literal_if_rejecting_collect_branch_that_keeps_a_frame_open_runs_once(+ build_graph: Callable[[bool], Graph],+) -> None:+ """Eagerly admitting a private rejected Collect branch still preserves the selected root result."""+ graph = build_graph(False)+ graph.validate_self()++ trace, state = _run(GraphExecutionState(graph=graph))++ # This shape is outside the generic scheduler's supported set.+ assert isinstance(state._execution_scheduler, _ExecutionScheduler)+ assert state.is_complete(), f"execution stalled after {trace}"+ assert [+ (state._get_iteration_path(exec_id), state.results[exec_id].value)+ for exec_id in state._prepared_registry().get_prepared_ids("sink")+ ] == [((), ["fallback"])]+ assert "body" in trace+++ ("condition", "expected_paths", "expected_values"),+ [+ pytest.param(True, {(0,), (1,)}, [0, 1], id="selects-item-branch"),+ pytest.param(False, {(0,), (1,)}, ["root-value", "root-value"], id="selects-root-branch"),+ ],+)+def test_root_condition_if_keeps_branch_iterate_cardinality(+ condition: bool, expected_paths: set[tuple[int, ...]], expected_values: list[int | str]+) -> None:+ """A root-frame condition is read by one If execution per item of the Iterate open on a branch."""+ graph = Graph()+ graph.add_node(FixedCollectionTestInvocation(id="source", value=True))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(FixedCollectionTestInvocation(id="condition", value=condition))+ graph.add_node(AnyTypeTestInvocation(id="root_branch", value="root-value"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("source", "collection", "iterate", "collection"))+ graph.add_edge(create_edge("condition", "condition", "if", "condition"))+ graph.add_edge(create_edge("iterate", "item", "if", "true_input"))+ graph.add_edge(create_edge("root_branch", "value", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "collect", "item"))+ graph.validate_self()++ trace, state = _run_graph(GraphExecutionState(graph=graph))++ # This shape is outside the generic scheduler's supported set.+ assert isinstance(state._execution_scheduler, _ExecutionScheduler)+ assert state.is_complete(), f"execution stalled after {trace}"+ if_paths = {state._get_iteration_path(exec_id) for exec_id in state._prepared_registry().get_prepared_ids("if")}+ assert if_paths == expected_paths+ collect_id = next(iter(state._prepared_registry().get_prepared_ids("collect")))+ assert state.results[collect_id].collection == expected_values+++def test_literal_if_selecting_empty_iterate_branch_produces_no_values() -> None:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="source", first=[]))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(AnyTypeTestInvocation(id="root_branch", value="root-value"))+ graph.add_node(IfInvocation(id="if", condition=True))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("source", "collection", "iterate", "collection"))+ graph.add_edge(create_edge("iterate", "item", "if", "true_input"))+ graph.add_edge(create_edge("root_branch", "value", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "collect", "item"))+ graph.validate_self()++ trace, state = _run_graph(GraphExecutionState(graph=graph))++ # This shape is outside the generic scheduler's supported set.+ assert isinstance(state._execution_scheduler, _ExecutionScheduler)+ assert state.is_complete(), f"execution stalled after {trace}"+ assert "root_branch" not in trace+ assert not state._prepared_registry().get_prepared_ids("if")+ collect_id = next(iter(state._prepared_registry().get_prepared_ids("collect")))+ assert state.results[collect_id].collection == []+++def test_node_after_literal_if_selecting_root_branch_keeps_iterate_cardinality() -> None:+ """A literal If selecting a root value still runs once per item of the Iterate open on its other branch."""+ graph = Graph()+ graph.add_node(FixedCollectionTestInvocation(id="source", value=True))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(AnyTypeTestInvocation(id="root_branch", value="root-value"))+ graph.add_node(IfInvocation(id="if", condition=False))+ graph.add_node(AnyTypeTestInvocation(id="sink"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("source", "collection", "iterate", "collection"))+ graph.add_edge(create_edge("iterate", "item", "if", "true_input"))+ graph.add_edge(create_edge("root_branch", "value", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "sink", "value"))+ graph.add_edge(create_edge("sink", "value", "collect", "item"))+ graph.validate_self()++ trace, state = _run_graph(GraphExecutionState(graph=graph))++ # This shape is outside the generic scheduler's supported set.+ assert isinstance(state._execution_scheduler, _ExecutionScheduler)+ assert state.is_complete(), f"execution stalled after {trace}"+ collect_id = next(iter(state._prepared_registry().get_prepared_ids("collect")))+ assert state.results[collect_id].collection == ["root-value", "root-value"]+++def test_computed_condition_selecting_empty_iterate_branch_produces_no_values() -> None:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="source", first=[]))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(FixedCollectionTestInvocation(id="condition", value=True))+ graph.add_node(AnyTypeTestInvocation(id="root_branch", value="root-value"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("source", "collection", "iterate", "collection"))+ graph.add_edge(create_edge("condition", "condition", "if", "condition"))+ graph.add_edge(create_edge("iterate", "item", "if", "true_input"))+ graph.add_edge(create_edge("root_branch", "value", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "collect", "item"))+ graph.validate_self()++ trace, state = _run_graph(GraphExecutionState(graph=graph))++ # This shape is outside the generic scheduler's supported set.+ assert isinstance(state._execution_scheduler, _ExecutionScheduler)+ assert state.is_complete(), f"execution stalled after {trace}"+ assert "root_branch" not in trace+ collect_id = next(iter(state._prepared_registry().get_prepared_ids("collect")))+ assert state.results[collect_id].collection == []++[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("checkpoint", [False, True], ids=["fresh", "checkpoint"])+def test_empty_iterate_for_output_to_computed_if_closes_collect(+ force_compatibility_scheduler: bool, checkpoint: bool+) -> None:+ graph = Graph()+ for node in (+ CollectionConcatInvocation(id="source", first=[]),+ IterateInvocation(id="iterate"),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="body"),+ ForReturnInvocation(id="return"),+ AnyTypeTestInvocation(id="passthrough"),+ FixedCollectionTestInvocation(id="condition", value=True),+ BooleanInvocation(id="fallback", value=False),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ):+ graph.add_node(node)+ for source, source_field, destination, destination_field in (+ ("source", "collection", "iterate", "collection"),+ ("iterate", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "return", "output"),+ ("for", "output_collection", "passthrough", "value"),+ ("passthrough", "value", "if", "true_input"),+ ("condition", "condition", "if", "condition"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))+ graph.add_edge(create_loop_linkage("for", "return"))++ fresh_trace, fresh_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )+ if checkpoint:+ partial_trace, partial_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after_source="condition",+ )+ assert not partial_state.is_complete()+ resumed_trace, state = _run_graph_with_effects(+ load_execution_state(dump_execution_state(partial_state)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ trace = partial_trace + resumed_trace+ assert trace == fresh_trace+ else:+ state = fresh_state+ trace = fresh_trace++ assert state.is_complete(), (+ f"execution stalled after {trace}; history={state.executed_history}; "+ f"prepared={state.prepared_source_mapping}; pending_if={state._pending_if_exec_nodes}; "+ f"indegree={state.indegree}"+ )+ assert not state.has_error(), state.errors+ assert not {"for", "body", "passthrough", "if", "fallback"} & set(trace)+ collect_results = {+ state._get_iteration_path(exec_id): state.results[exec_id].collection+ for exec_id in state.source_prepared_mapping["collect"]+ }+ assert collect_results == {(): []}+ if checkpoint:+ assert _state_projection(state) == _state_projection(fresh_state)+++ ("conditions", "expected_values"),+ [+ pytest.param([True, False], ["inner:True", "outer-false"], id="first-nested"),+ pytest.param([False, True], ["outer-false", "inner:True"], id="second-nested"),+ ],+)+def test_per_item_if_selecting_per_item_nested_if_keeps_every_item(+ conditions: list[bool], expected_values: list[str]+) -> None:+ """The outer If runs in every item frame even when an item selects a nested If that is not materialized yet."""+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="conditions", first=conditions))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(FixedCollectionTestInvocation(id="inner_condition"))+ graph.add_node(MarkedAnyTypeTestInvocation(id="inner_true", marker="inner:"))+ graph.add_node(AnyTypeTestInvocation(id="inner_false", value="inner-false"))+ graph.add_node(IfInvocation(id="inner_if"))+ graph.add_node(AnyTypeTestInvocation(id="outer_false", value="outer-false"))+ graph.add_node(IfInvocation(id="outer_if"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("conditions", "collection", "iterate", "collection"))+ graph.add_edge(create_edge("iterate", "item", "outer_if", "condition"))+ graph.add_edge(create_edge("iterate", "item", "inner_condition", "value"))+ graph.add_edge(create_edge("inner_condition", "condition", "inner_if", "condition"))+ graph.add_edge(create_edge("iterate", "item", "inner_true", "value"))+ graph.add_edge(create_edge("inner_true", "value", "inner_if", "true_input"))+ graph.add_edge(create_edge("inner_false", "value", "inner_if", "false_input"))+ graph.add_edge(create_edge("inner_if", "value", "outer_if", "true_input"))+ graph.add_edge(create_edge("outer_false", "value", "outer_if", "false_input"))+ graph.add_edge(create_edge("outer_if", "value", "collect", "item"))+ graph.validate_self()++ trace, state = _run_graph(GraphExecutionState(graph=graph))++ # This shape is outside the generic scheduler's supported set.+ assert isinstance(state._execution_scheduler, _ExecutionScheduler)+ assert state.is_complete(), f"execution stalled after {trace}"+ collect_id = next(iter(state._prepared_registry().get_prepared_ids("collect")))+ assert state.results[collect_id].collection == expected_values++[email protected]("force_compatibility_scheduler", [False, True])+def test_if_collect_collection_inner_iterate_keeps_values_in_outer_frame(+ force_compatibility_scheduler: bool,+) -> None:+ graph = _iterate_if_collect_inner_iterate_graph()+ graph.validate_self()++ trace, state = _run(GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler)++ assert trace.count("sink") == 2+ sinks_by_outer_path = {+ state._get_iteration_path(exec_id): state.results[exec_id].value+ for exec_id in state._prepared_registry().get_prepared_ids("sink")+ }+ assert sinks_by_outer_path == {(0,): [1, 2], (1,): [2, 3]}+ assert state.is_complete()++[email protected]("force_compatibility_scheduler", [False, True])+def test_chained_sibling_iterates_keep_each_outer_and_inner_frame(+ force_compatibility_scheduler: bool,) -> None:- """An If runs once per frame of a single chain of nested open axes; other frame sets fail before running."""- state = GraphExecutionState(graph=build_graph())+ graph = _chained_sibling_iterates_with_unrelated_if_graph()+ graph.validate_self()- with pytest.raises(graph_if_runtime.UnsupportedIfIterationAxesError, match=message):- _run(state)- assert state.executed_history == []+ trace, state = _run(GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler)+ sinks_by_iteration_path = {+ state._get_iteration_path(exec_id): state.results[exec_id].value+ for exec_id in state._prepared_registry().get_prepared_ids("sink")+ }+ assert sinks_by_iteration_path == {+ (0, 0): [1, 2],+ (0, 1): [2, 3],+ (1, 0): [2, 3],+ (1, 1): [3, 4],+ }+ assert state.is_complete()[email protected]("fail_unselected", [False, True], ids=["succeeds", "unselected-fails"])-def test_per_item_if_keeps_shared_for_running_but_gates_its_branch_collect(fail_unselected: bool) -> None:- """A For whose final output also feeds a node outside the If runs for every item; its branch Collect does not."""- graph = _graph_from(- [- CollectionConcatInvocation(id="outer_source", first=["", "x"]),- IterateInvocation(id="outer_iterate"),- FixedCollectionTestInvocation(id="items"),- ForInvocation(id="for"),- AnyTypeTestInvocation(id="body"),- ForReturnInvocation(id="return"),- CollectInvocation(id="collect"),- CollectInvocation(id="other_collect"),- AnyTypeTestInvocation(id="side_sink"),- AnyTypeTestInvocation(id="fallback", value="fallback"),- IfInvocation(id="if"),- AnyTypeTestInvocation(id="sink"),- ],- [- ("outer_source", "collection", "outer_iterate", "collection"),- ("outer_iterate", "item", "items", "value"),- ("items", "condition", "if", "condition"),- ("items", "collection", "for", "collection"),- ("for", "item", "body", "value"),- ("body", "value", "return", "output"),- create_loop_linkage("for", "return"),- ("for", "output_collection", "collect", "item"),- ("collect", "collection", "if", "true_input"),- ("for", "output_collection", "other_collect", "item"),- ("other_collect", "collection", "side_sink", "value"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "sink", "value"),- ],++def test_nested_iterate_chain_closes_empty_inner_frame() -> None:+ graph = _nested_iterate_chain_graph(outer_collection=[[], ["c"]])+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("nested Iterate chain used compatibility materializer"),+ ):+ generic_trace, generic_state = _run(GraphExecutionState(graph=graph))+ compatibility_trace, compatibility_state = _run(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,)- state = GraphExecutionState(graph=graph)- trace: list[tuple[str, tuple[int, ...]]] = []- while (node := state.next()) is not None:- source_id = state.prepared_source_mapping[node.id]- iteration_path = state._get_iteration_path(node.id)- trace.append((source_id, iteration_path))- if fail_unselected and source_id == "collect" and iteration_path[:1] == (0,):- state.set_node_error(node.id, "collect ran for an unselected item")- continue- state.complete(node.id, node.invoke(Mock()))+ assert generic_trace == compatibility_trace+ assert generic_trace == [+ "outer_source",+ "outer_iterate",+ "outer_iterate",+ "inner_collection",+ "inner_collection",+ "inner_iterate",+ "body",+ ]+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert (+ generic_state._generic_runtime().streams[generic_state._iteration_stream_id("inner_iterate", (0,))].values == ()+ )- assert not state.has_error(), state.errors- assert state.is_complete(), f"execution stalled after {trace}"- assert ("collect", (0,)) not in trace- assert _source_values(state, "sink") == {(0,): "fallback", (1,): [[0, 1]]}- assert _source_values(state, "side_sink") == {(0,): [[0, 1]], (1,): [[0, 1]]}+def test_nested_iterate_chain_completes_when_all_collections_are_empty() -> None:+ graph = _nested_iterate_chain_graph(outer_collection=[[], []])+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("nested Iterate chain used compatibility materializer"),+ ):+ generic_trace, generic_state = _run(GraphExecutionState(graph=graph))+ compatibility_trace, compatibility_state = _run(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ )-def _shared_outer_iterate_branch_graph(condition: bool) -> Graph:- """The outer frame reaches the If only through the deferred branch, so the If cannot see it yet."""- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="outer_source", first=["x", "y"]))- graph.add_node(IterateInvocation(id="outer_iterate"))- graph.add_node(AnyTypeTestInvocation(id="side"))- graph.add_node(FixedCollectionTestInvocation(id="inner_source"))- graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(AnyTypeTestInvocation(id="body"))- graph.add_node(CollectInvocation(id="collect"))- graph.add_node(AnyTypeTestInvocation(id="fallback", value=["fallback"]))- graph.add_node(IfInvocation(id="if", condition=condition))- graph.add_node(AnyTypeTestInvocation(id="sink"))- graph.add_edge(create_edge("outer_source", "collection", "outer_iterate", "collection"))- graph.add_edge(create_edge("outer_iterate", "item", "side", "value"))- graph.add_edge(create_edge("outer_iterate", "item", "inner_source", "value"))- graph.add_edge(create_edge("inner_source", "collection", "iterate", "collection"))- graph.add_edge(create_edge("iterate", "item", "body", "value"))- graph.add_edge(create_edge("body", "value", "collect", "item"))- graph.add_edge(create_edge("collect", "collection", "if", "true_input"))- graph.add_edge(create_edge("fallback", "value", "if", "false_input"))- graph.add_edge(create_edge("if", "value", "sink", "value"))- return graph+ assert generic_trace == compatibility_trace+ assert generic_trace == [+ "outer_source",+ "outer_iterate",+ "outer_iterate",+ "inner_collection",+ "inner_collection",+ ]+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+++def test_nested_iterate_chain_rehydrates_without_replay() -> None:+ graph = _nested_iterate_chain_graph()+ expected_trace, expected_state = _run(GraphExecutionState(graph=graph))+ partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=5)++ resumed_trace, resumed_state = _run(load_execution_state(dump_execution_state(partial_state)))++ assert partial_trace + resumed_trace == expected_trace+ assert resumed_state.is_complete()+ assert _state_projection(resumed_state) == _state_projection(expected_state)+++def test_nested_iterate_chain_failure_does_not_release_later_frames() -> None:+ graph = _nested_iterate_chain_graph()+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("nested Iterate chain used compatibility materializer"),+ ):+ generic_trace, generic_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ fail_source_id="body",+ )+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ fail_source_id="body",+ )++ assert generic_trace == compatibility_trace+ assert generic_state.has_error() and compatibility_state.has_error()+ assert generic_state.is_complete() and compatibility_state.is_complete()+ assert "body" in generic_trace+ assert generic_trace.count("body") == 1+++def test_three_level_nested_iterate_matches_compatibility() -> None:+ graph = _three_level_nested_iterate_chain_graph()+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("three-level nested Iterate used compatibility materializer"),+ ):+ generic_trace, generic_state = _run(GraphExecutionState(graph=graph))+ compatibility_trace, compatibility_state = _run(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ )++ assert generic_trace == compatibility_trace+ assert generic_trace == [+ "outer_source",+ "outer_iterate",+ "outer_iterate",+ "middle_collection",+ "middle_collection",+ "middle_iterate",+ "middle_iterate",+ "middle_iterate",+ "inner_collection",+ "inner_collection",+ "inner_collection",+ "inner_iterate",+ "inner_iterate",+ "inner_iterate",+ "inner_iterate",+ "body",+ "body",+ "body",+ "body",+ ]+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(+ compatibility_state+ )+ assert sorted(+ generic_state._get_iteration_path(exec_id)+ for exec_id in generic_state._prepared_registry().get_prepared_ids("body")+ ) == [(0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 0, 0)]+++ ("outer_collection", "expected_body_paths"),+ [+ ([], []),+ ([[], [["c"]]], [(1, 0, 0)]),+ ([[[], []]], []),+ ],+ ids=["outer-empty", "mixed-empty", "all-empty"],+)+def test_three_level_nested_iterate_closes_empty_frames(+ outer_collection: list[list[list[str]]], expected_body_paths: list[tuple[int, ...]]+) -> None:+ graph = _three_level_nested_iterate_chain_graph(outer_collection=outer_collection)+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("three-level nested Iterate used compatibility materializer"),+ ):+ generic_trace, generic_state = _run(GraphExecutionState(graph=graph))+ compatibility_trace, compatibility_state = _run(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ )++ assert generic_trace == compatibility_trace+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert (+ sorted(+ generic_state._get_iteration_path(exec_id)+ for exec_id in generic_state._prepared_registry().get_prepared_ids("body")+ )+ == expected_body_paths+ )-def _sibling_iterates_branch_graph(condition: bool) -> Graph:- """The Collect closes only one of two sibling frames, so the If inherits the other."""- graph = Graph()- graph.add_node(FixedCollectionTestInvocation(id="left_source"))- graph.add_node(FixedCollectionTestInvocation(id="right_source"))- graph.add_node(IterateInvocation(id="left_iterate"))- graph.add_node(IterateInvocation(id="right_iterate"))- graph.add_node(AddInvocation(id="body"))- graph.add_node(CollectInvocation(id="collect"))- graph.add_node(AnyTypeTestInvocation(id="fallback", value=["fallback"]))- graph.add_node(IfInvocation(id="if", condition=condition))- graph.add_node(AnyTypeTestInvocation(id="sink"))- graph.add_edge(create_edge("left_source", "collection", "left_iterate", "collection"))- graph.add_edge(create_edge("right_source", "collection", "right_iterate", "collection"))- graph.add_edge(create_edge("left_iterate", "item", "body", "a"))- graph.add_edge(create_edge("right_iterate", "item", "body", "b"))- graph.add_edge(create_edge("body", "value", "collect", "item"))- graph.add_edge(create_edge("collect", "collection", "if", "true_input"))- graph.add_edge(create_edge("fallback", "value", "if", "false_input"))- graph.add_edge(create_edge("if", "value", "sink", "value"))- return graph+def test_three_level_nested_iterate_rehydrates_without_replay() -> None:+ graph = _three_level_nested_iterate_chain_graph()+ expected_trace, expected_state = _run(GraphExecutionState(graph=graph))+ partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=8)+ resumed_trace, resumed_state = _run(load_execution_state(dump_execution_state(partial_state)))- "build_graph",- [_shared_outer_iterate_branch_graph, _sibling_iterates_branch_graph],- ids=["outer-frame-through-branch", "sibling-frame-left-open"],-)-def test_literal_if_rejecting_collect_branch_that_keeps_a_frame_open_runs_once(- build_graph: Callable[[bool], Graph],-) -> None:- """A rejected Collect branch never runs, so the frame it would leave open gives the If no executions.+ assert partial_trace + resumed_trace == expected_trace+ assert resumed_state.is_complete()+ assert _state_projection(resumed_state) == _state_projection(expected_state)+ _assert_retained_iterate_streams_match_expected(resumed_state, expected_state)- The If does not wait for the Iterate inside that branch and runs once in the root frame.- """- graph = build_graph(False)- graph.validate_self()- trace, state = _run(GraphExecutionState(graph=graph))+def test_three_level_nested_iterate_failure_matches_compatibility() -> None:+ graph = _three_level_nested_iterate_chain_graph()+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("three-level nested Iterate used compatibility materializer"),+ ):+ generic_trace, generic_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ fail_source_id="body",+ )+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ fail_source_id="body",+ )- # This shape is outside the generic scheduler's supported set.- assert isinstance(state._execution_scheduler, _ExecutionScheduler)- assert state.is_complete(), f"execution stalled after {trace}"- assert [- (state._get_iteration_path(exec_id), state.results[exec_id].value)- for exec_id in state._prepared_registry().get_prepared_ids("sink")- ] == [((), ["fallback"])]- assert "body" not in trace+ assert generic_trace == compatibility_trace+ assert generic_state.has_error() and compatibility_state.has_error()+ assert generic_state.is_complete() and compatibility_state.is_complete()+ assert generic_trace.count("body") == 1+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+++def test_four_level_nested_iterate_matches_compatibility() -> None:+ graph = _four_level_nested_iterate_chain_graph()+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("four-level nested Iterate used compatibility materializer"),+ ):+ generic_trace, generic_state = _run(GraphExecutionState(graph=graph))+ compatibility_trace, compatibility_state = _run(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ )++ assert generic_trace == compatibility_trace+ assert generic_trace == (+ ["outer_source"]+ + ["outer_iterate"] * 2+ + ["level1_collection"] * 2+ + ["level1_iterate"] * 3+ + ["level2_collection"] * 3+ + ["level2_iterate"] * 4+ + ["level3_collection"] * 4+ + ["level3_iterate"] * 5+ + ["body"] * 5+ )+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(+ compatibility_state+ )+ assert sorted(+ generic_state._get_iteration_path(exec_id)+ for exec_id in generic_state._prepared_registry().get_prepared_ids("body")+ ) == [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 1, 0, 0), (1, 0, 0, 0)]@pytest.mark.parametrize(- ("condition", "expected_paths", "expected_values"),+ ("outer_collection", "expected_body_paths"),[- pytest.param(True, {(0,), (1,)}, [0, 1], id="selects-item-branch"),- pytest.param(False, {(0,), (1,)}, ["root-value", "root-value"], id="selects-root-branch"),+ ([], []),+ (+ [+ [],+ [+ [+ [+ "c",+ ]+ ]+ ],+ ],+ [(1, 0, 0, 0)],+ ),+ ([[[]]], []),+ ([[[], []]], []),],+ ids=["outer-empty", "mixed-empty", "deepest-empty", "all-empty"],)-def test_root_condition_if_keeps_branch_iterate_cardinality(- condition: bool, expected_paths: set[tuple[int, ...]], expected_values: list[int | str]+def test_four_level_nested_iterate_closes_empty_frames(+ outer_collection: list[list[list[list[str]]]], expected_body_paths: list[tuple[int, ...]]) -> None:- """A root-frame condition is read by one If execution per item of the Iterate open on a branch."""- graph = Graph()- graph.add_node(FixedCollectionTestInvocation(id="source", value=True))- graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(FixedCollectionTestInvocation(id="condition", value=condition))- graph.add_node(AnyTypeTestInvocation(id="root_branch", value="root-value"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="collect"))- graph.add_edge(create_edge("source", "collection", "iterate", "collection"))- graph.add_edge(create_edge("condition", "condition", "if", "condition"))- graph.add_edge(create_edge("iterate", "item", "if", "true_input"))- graph.add_edge(create_edge("root_branch", "value", "if", "false_input"))- graph.add_edge(create_edge("if", "value", "collect", "item"))- graph.validate_self()-- trace, state = _run_graph(GraphExecutionState(graph=graph))-- # This shape is outside the generic scheduler's supported set.- assert isinstance(state._execution_scheduler, _ExecutionScheduler)- assert state.is_complete(), f"execution stalled after {trace}"- if_paths = {state._get_iteration_path(exec_id) for exec_id in state._prepared_registry().get_prepared_ids("if")}- assert if_paths == expected_paths- collect_id = next(iter(state._prepared_registry().get_prepared_ids("collect")))- assert state.results[collect_id].collection == expected_values-+ graph = _four_level_nested_iterate_chain_graph(outer_collection=outer_collection)+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("four-level nested Iterate used compatibility materializer"),+ ):+ generic_trace, generic_state = _run(GraphExecutionState(graph=graph))+ compatibility_trace, compatibility_state = _run(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ )-def test_literal_if_selecting_empty_iterate_branch_produces_no_values() -> None:- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="source", first=[]))- graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(AnyTypeTestInvocation(id="root_branch", value="root-value"))- graph.add_node(IfInvocation(id="if", condition=True))- graph.add_node(CollectInvocation(id="collect"))- graph.add_edge(create_edge("source", "collection", "iterate", "collection"))- graph.add_edge(create_edge("iterate", "item", "if", "true_input"))- graph.add_edge(create_edge("root_branch", "value", "if", "false_input"))- graph.add_edge(create_edge("if", "value", "collect", "item"))- graph.validate_self()+ assert generic_trace == compatibility_trace+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert (+ sorted(+ generic_state._get_iteration_path(exec_id)+ for exec_id in generic_state._prepared_registry().get_prepared_ids("body")+ )+ == expected_body_paths+ )- trace, state = _run_graph(GraphExecutionState(graph=graph))- # This shape is outside the generic scheduler's supported set.- assert isinstance(state._execution_scheduler, _ExecutionScheduler)- assert state.is_complete(), f"execution stalled after {trace}"- assert "root_branch" not in trace- assert not state._prepared_registry().get_prepared_ids("if")- collect_id = next(iter(state._prepared_registry().get_prepared_ids("collect")))- assert state.results[collect_id].collection == []+def test_four_level_nested_iterate_rehydrates_without_replay() -> None:+ graph = _four_level_nested_iterate_chain_graph()+ expected_trace, expected_state = _run(GraphExecutionState(graph=graph))+ partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=12)+ resumed_trace, resumed_state = _run(load_execution_state(dump_execution_state(partial_state)))-def test_node_after_literal_if_selecting_root_branch_keeps_iterate_cardinality() -> None:- """A literal If selecting a root value still runs once per item of the Iterate open on its other branch."""- graph = Graph()- graph.add_node(FixedCollectionTestInvocation(id="source", value=True))- graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(AnyTypeTestInvocation(id="root_branch", value="root-value"))- graph.add_node(IfInvocation(id="if", condition=False))- graph.add_node(AnyTypeTestInvocation(id="sink"))- graph.add_node(CollectInvocation(id="collect"))- graph.add_edge(create_edge("source", "collection", "iterate", "collection"))- graph.add_edge(create_edge("iterate", "item", "if", "true_input"))- graph.add_edge(create_edge("root_branch", "value", "if", "false_input"))- graph.add_edge(create_edge("if", "value", "sink", "value"))- graph.add_edge(create_edge("sink", "value", "collect", "item"))- graph.validate_self()+ assert partial_trace + resumed_trace == expected_trace+ assert resumed_state.is_complete()+ assert _state_projection(resumed_state) == _state_projection(expected_state)+ _assert_retained_iterate_streams_match_expected(resumed_state, expected_state)- trace, state = _run_graph(GraphExecutionState(graph=graph))- # This shape is outside the generic scheduler's supported set.- assert isinstance(state._execution_scheduler, _ExecutionScheduler)- assert state.is_complete(), f"execution stalled after {trace}"- collect_id = next(iter(state._prepared_registry().get_prepared_ids("collect")))- assert state.results[collect_id].collection == ["root-value", "root-value"]+def test_four_level_nested_iterate_failure_matches_compatibility() -> None:+ graph = _four_level_nested_iterate_chain_graph()+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("four-level nested Iterate used compatibility materializer"),+ ):+ generic_trace, generic_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ fail_source_id="body",+ )+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ fail_source_id="body",+ )+ assert generic_trace == compatibility_trace+ assert generic_state.has_error() and compatibility_state.has_error()+ assert generic_state.is_complete() and compatibility_state.is_complete()+ assert generic_trace.count("body") == 1+ assert _state_projection(generic_state) == _state_projection(compatibility_state)-def test_computed_condition_selecting_empty_iterate_branch_produces_no_values() -> None:- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="source", first=[]))- graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(FixedCollectionTestInvocation(id="condition", value=True))- graph.add_node(AnyTypeTestInvocation(id="root_branch", value="root-value"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="collect"))- graph.add_edge(create_edge("source", "collection", "iterate", "collection"))- graph.add_edge(create_edge("condition", "condition", "if", "condition"))- graph.add_edge(create_edge("iterate", "item", "if", "true_input"))- graph.add_edge(create_edge("root_branch", "value", "if", "false_input"))- graph.add_edge(create_edge("if", "value", "collect", "item"))- graph.validate_self()- trace, state = _run_graph(GraphExecutionState(graph=graph))+def test_five_level_nested_iterate_matches_compatibility() -> None:+ graph = _five_level_nested_iterate_chain_graph()+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("five-level nested Iterate used compatibility materializer"),+ ):+ generic_trace, generic_state = _run(GraphExecutionState(graph=graph))+ compatibility_trace, compatibility_state = _run(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ )- # This shape is outside the generic scheduler's supported set.- assert isinstance(state._execution_scheduler, _ExecutionScheduler)- assert state.is_complete(), f"execution stalled after {trace}"- assert "root_branch" not in trace- collect_id = next(iter(state._prepared_registry().get_prepared_ids("collect")))- assert state.results[collect_id].collection == []+ assert generic_trace == compatibility_trace+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(+ compatibility_state+ )+ assert sorted(+ generic_state._get_iteration_path(exec_id)+ for exec_id in generic_state._prepared_registry().get_prepared_ids("body")+ ) == [+ (0, 0, 0, 0, 0),+ (0, 0, 0, 0, 1),+ (0, 0, 1, 0, 0),+ (0, 1, 0, 0, 0),+ (1, 0, 0, 0, 0),+ ]@pytest.mark.parametrize(- ("conditions", "expected_values"),+ ("outer_collection", "expected_body_paths"),[- pytest.param([True, False], ["inner:True", "outer-false"], id="first-nested"),- pytest.param([False, True], ["outer-false", "inner:True"], id="second-nested"),+ ([], []),+ ([[], [[[["c"]]]]], [(1, 0, 0, 0, 0)]),+ ([[[[]]]], []),+ ([[[[], []]]], []),],+ ids=["outer-empty", "mixed-empty", "deepest-empty", "all-empty"],)-def test_per_item_if_selecting_per_item_nested_if_keeps_every_item(- conditions: list[bool], expected_values: list[str]+def test_five_level_nested_iterate_closes_empty_frames(+ outer_collection: list[list[list[list[list[str]]]]], expected_body_paths: list[tuple[int, ...]]) -> None:- """The outer If runs in every item frame even when an item selects a nested If that is not materialized yet."""- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="conditions", first=conditions))- graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(FixedCollectionTestInvocation(id="inner_condition"))- graph.add_node(MarkedAnyTypeTestInvocation(id="inner_true", marker="inner:"))- graph.add_node(AnyTypeTestInvocation(id="inner_false", value="inner-false"))- graph.add_node(IfInvocation(id="inner_if"))- graph.add_node(AnyTypeTestInvocation(id="outer_false", value="outer-false"))- graph.add_node(IfInvocation(id="outer_if"))- graph.add_node(CollectInvocation(id="collect"))- graph.add_edge(create_edge("conditions", "collection", "iterate", "collection"))- graph.add_edge(create_edge("iterate", "item", "outer_if", "condition"))- graph.add_edge(create_edge("iterate", "item", "inner_condition", "value"))- graph.add_edge(create_edge("inner_condition", "condition", "inner_if", "condition"))- graph.add_edge(create_edge("iterate", "item", "inner_true", "value"))- graph.add_edge(create_edge("inner_true", "value", "inner_if", "true_input"))- graph.add_edge(create_edge("inner_false", "value", "inner_if", "false_input"))- graph.add_edge(create_edge("inner_if", "value", "outer_if", "true_input"))- graph.add_edge(create_edge("outer_false", "value", "outer_if", "false_input"))- graph.add_edge(create_edge("outer_if", "value", "collect", "item"))- graph.validate_self()-- trace, state = _run_graph(GraphExecutionState(graph=graph))-- # This shape is outside the generic scheduler's supported set.- assert isinstance(state._execution_scheduler, _ExecutionScheduler)- assert state.is_complete(), f"execution stalled after {trace}"- collect_id = next(iter(state._prepared_registry().get_prepared_ids("collect")))- assert state.results[collect_id].collection == expected_values+ graph = _five_level_nested_iterate_chain_graph(outer_collection=outer_collection)+ generic_trace, generic_state = _run(GraphExecutionState(graph=graph))+ compatibility_trace, compatibility_state = _run(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ )+ assert generic_trace == compatibility_trace+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert (+ sorted(+ generic_state._get_iteration_path(exec_id)+ for exec_id in generic_state._prepared_registry().get_prepared_ids("body")+ )+ == expected_body_paths+ )[email protected]("force_compatibility_scheduler", [False, True])-def test_if_collect_collection_inner_iterate_keeps_values_in_outer_frame(- force_compatibility_scheduler: bool,-) -> None:- graph = _iterate_if_collect_inner_iterate_graph()- graph.validate_self()- trace, state = _run(GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler)+def test_five_level_nested_iterate_rehydrates_without_replay() -> None:+ graph = _five_level_nested_iterate_chain_graph()+ expected_trace, expected_state = _run(GraphExecutionState(graph=graph))+ partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=15)- assert trace.count("sink") == 2- sinks_by_outer_path = {- state._get_iteration_path(exec_id): state.results[exec_id].value- for exec_id in state._prepared_registry().get_prepared_ids("sink")- }- assert sinks_by_outer_path == {(0,): [1, 2], (1,): [2, 3]}- assert state.is_complete()+ resumed_trace, resumed_state = _run(load_execution_state(dump_execution_state(partial_state)))+ assert partial_trace + resumed_trace == expected_trace+ assert resumed_state.is_complete()+ assert _state_projection(resumed_state) == _state_projection(expected_state)+ _assert_retained_iterate_streams_match_expected(resumed_state, expected_state)[email protected]("force_compatibility_scheduler", [False, True])-def test_chained_sibling_iterates_keep_each_outer_and_inner_frame(- force_compatibility_scheduler: bool,-) -> None:- graph = _chained_sibling_iterates_with_unrelated_if_graph()- graph.validate_self()- trace, state = _run(GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler)+def test_five_level_nested_iterate_failure_matches_compatibility() -> None:+ graph = _five_level_nested_iterate_chain_graph()+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("five-level nested Iterate used compatibility materializer"),+ ):+ generic_trace, generic_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ fail_source_id="body",+ )+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ fail_source_id="body",+ )- sinks_by_iteration_path = {- state._get_iteration_path(exec_id): state.results[exec_id].value- for exec_id in state._prepared_registry().get_prepared_ids("sink")- }- assert sinks_by_iteration_path == {- (0, 0): [1, 2],- (0, 1): [2, 3],- (1, 0): [2, 3],- (1, 1): [3, 4],- }- assert state.is_complete()+ assert generic_trace == compatibility_trace+ assert generic_state.has_error() and compatibility_state.has_error()+ assert generic_state.is_complete() and compatibility_state.is_complete()+ assert generic_trace.count("body") == 1+ assert _state_projection(generic_state) == _state_projection(compatibility_state)-def test_nested_iterate_chain_closes_empty_inner_frame() -> None:- graph = _nested_iterate_chain_graph(outer_collection=[[], ["c"]])+def test_six_level_nested_iterate_matches_compatibility() -> None:+ graph = _six_level_nested_iterate_chain_graph()with patch.object(graph_module._ExecutionMaterializer,"prepare",- side_effect=AssertionError("nested Iterate chain used compatibility materializer"),+ side_effect=AssertionError("six-level nested Iterate used compatibility materializer"),):generic_trace, generic_state = _run(GraphExecutionState(graph=graph))compatibility_trace, compatibility_state = _run(@@ -4828,28 +6702,46 @@ def test_nested_iterate_chain_closes_empty_inner_frame() -> None:)assert generic_trace == compatibility_trace- assert generic_trace == [- "outer_source",- "outer_iterate",- "outer_iterate",- "inner_collection",- "inner_collection",- "inner_iterate",- "body",- ]assert generic_state.is_complete()assert compatibility_state.is_complete()- assert (- generic_state._generic_runtime().streams[generic_state._iteration_stream_id("inner_iterate", (0,))].values == ()- )+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert sorted(+ generic_state._get_iteration_path(exec_id)+ for exec_id in generic_state._prepared_registry().get_prepared_ids("body")+ ) == [+ (0, 0, 0, 0, 0, 0),+ (0, 0, 0, 0, 0, 1),+ (0, 0, 0, 1, 0, 0),+ (0, 0, 1, 0, 0, 0),+ (1, 0, 0, 0, 0, 0),+ ]-def test_nested_iterate_chain_completes_when_all_collections_are_empty() -> None:- graph = _nested_iterate_chain_graph(outer_collection=[[], []])+def _nested_collection(value: Any, depth: int) -> list[Any]:+ collection: Any = [value]+ for _ in range(depth - 1):+ collection = [collection]+ return collection+++ ("outer_collection", "expected_body_paths"),+ [+ ([], []),+ ([[], _nested_collection("c", 5)], [(1, 0, 0, 0, 0, 0)]),+ ([_nested_collection([], 4)], []),+ ([_nested_collection([], 3)], []),+ ],+ ids=["outer-empty", "mixed-empty", "deepest-empty", "intermediate-empty"],+)+def test_six_level_nested_iterate_closes_empty_frames(+ outer_collection: list[Any], expected_body_paths: list[tuple[int, ...]]+) -> None:+ graph = _six_level_nested_iterate_chain_graph(outer_collection=outer_collection)with patch.object(graph_module._ExecutionMaterializer,"prepare",- side_effect=AssertionError("nested Iterate chain used compatibility materializer"),+ side_effect=AssertionError("six-level nested Iterate used compatibility materializer"),):generic_trace, generic_state = _run(GraphExecutionState(graph=graph))compatibility_trace, compatibility_state = _run(@@ -4858,22 +6750,22 @@ def test_nested_iterate_chain_completes_when_all_collections_are_empty() -> None)assert generic_trace == compatibility_trace- assert generic_trace == [- "outer_source",- "outer_iterate",- "outer_iterate",- "inner_collection",- "inner_collection",- ]assert generic_state.is_complete()assert compatibility_state.is_complete()assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert (+ sorted(+ generic_state._get_iteration_path(exec_id)+ for exec_id in generic_state._prepared_registry().get_prepared_ids("body")+ )+ == expected_body_paths+ )-def test_nested_iterate_chain_rehydrates_without_replay() -> None:- graph = _nested_iterate_chain_graph()+def test_six_level_nested_iterate_rehydrates_without_replay() -> None:+ graph = _six_level_nested_iterate_chain_graph()expected_trace, expected_state = _run(GraphExecutionState(graph=graph))- partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=5)+ partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=8)resumed_trace, resumed_state = _run(load_execution_state(dump_execution_state(partial_state)))@@ -4882,12 +6774,12 @@ def test_nested_iterate_chain_rehydrates_without_replay() -> None:assert _state_projection(resumed_state) == _state_projection(expected_state)-def test_nested_iterate_chain_failure_does_not_release_later_frames() -> None:- graph = _nested_iterate_chain_graph()+def test_six_level_nested_iterate_failure_matches_compatibility() -> None:+ graph = _six_level_nested_iterate_chain_graph()with patch.object(graph_module._ExecutionMaterializer,"prepare",- side_effect=AssertionError("nested Iterate chain used compatibility materializer"),+ side_effect=AssertionError("six-level nested Iterate used compatibility materializer"),):generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph),@@ -4902,16 +6794,15 @@ def test_nested_iterate_chain_failure_does_not_release_later_frames() -> None:assert generic_trace == compatibility_traceassert generic_state.has_error() and compatibility_state.has_error()assert generic_state.is_complete() and compatibility_state.is_complete()- assert "body" in generic_traceassert generic_trace.count("body") == 1-def test_three_level_nested_iterate_matches_compatibility() -> None:- graph = _three_level_nested_iterate_chain_graph()+def test_seven_level_nested_iterate_matches_compatibility() -> None:+ graph = _serial_nested_iterate_chain_graph_at_depth(7)with patch.object(graph_module._ExecutionMaterializer,"prepare",- side_effect=AssertionError("three-level nested Iterate used compatibility materializer"),+ side_effect=AssertionError("seven-level nested Iterate used compatibility materializer"),):generic_trace, generic_state = _run(GraphExecutionState(graph=graph))compatibility_trace, compatibility_state = _run(@@ -4920,56 +6811,33 @@ def test_three_level_nested_iterate_matches_compatibility() -> None:)assert generic_trace == compatibility_trace- assert generic_trace == [- "outer_source",- "outer_iterate",- "outer_iterate",- "middle_collection",- "middle_collection",- "middle_iterate",- "middle_iterate",- "middle_iterate",- "inner_collection",- "inner_collection",- "inner_collection",- "inner_iterate",- "inner_iterate",- "inner_iterate",- "inner_iterate",- "body",- "body",- "body",- "body",- ]assert generic_state.is_complete()assert compatibility_state.is_complete()assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(- compatibility_state- )assert sorted(generic_state._get_iteration_path(exec_id)for exec_id in generic_state._prepared_registry().get_prepared_ids("body")- ) == [(0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 0, 0)]+ ) == [(0, 0, 0, 0, 0, 0, 0)]@pytest.mark.parametrize(("outer_collection", "expected_body_paths"),[([], []),- ([[], [["c"]]], [(1, 0, 0)]),- ([[[], []]], []),+ ([[], _nested_collection("c", 6)], [(1, 0, 0, 0, 0, 0, 0)]),+ ([_nested_collection([], 5)], []),],- ids=["outer-empty", "mixed-empty", "all-empty"],+ ids=["outer-empty", "mixed-empty", "deepest-empty"],)-def test_three_level_nested_iterate_closes_empty_frames(- outer_collection: list[list[list[str]]], expected_body_paths: list[tuple[int, ...]]+def test_seven_level_nested_iterate_closes_empty_frames(+ outer_collection: list[Any], expected_body_paths: list[tuple[int, ...]]) -> None:- graph = _three_level_nested_iterate_chain_graph(outer_collection=outer_collection)+ graph = _serial_nested_iterate_chain_graph_at_depth(7)+ graph.get_node("source").first = outer_collectionwith patch.object(graph_module._ExecutionMaterializer,"prepare",- side_effect=AssertionError("three-level nested Iterate used compatibility materializer"),+ side_effect=AssertionError("seven-level nested Iterate used compatibility materializer"),):generic_trace, generic_state = _run(GraphExecutionState(graph=graph))compatibility_trace, compatibility_state = _run(@@ -4990,8 +6858,8 @@ def test_three_level_nested_iterate_closes_empty_frames()-def test_three_level_nested_iterate_rehydrates_without_replay() -> None:- graph = _three_level_nested_iterate_chain_graph()+def test_seven_level_nested_iterate_rehydrates_without_replay() -> None:+ graph = _serial_nested_iterate_chain_graph_at_depth(7)expected_trace, expected_state = _run(GraphExecutionState(graph=graph))partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=8)@@ -5000,15 +6868,14 @@ def test_three_level_nested_iterate_rehydrates_without_replay() -> None:assert partial_trace + resumed_trace == expected_traceassert resumed_state.is_complete()assert _state_projection(resumed_state) == _state_projection(expected_state)- _assert_retained_iterate_streams_match_expected(resumed_state, expected_state)-def test_three_level_nested_iterate_failure_matches_compatibility() -> None:- graph = _three_level_nested_iterate_chain_graph()+def test_seven_level_nested_iterate_failure_matches_compatibility() -> None:+ graph = _serial_nested_iterate_chain_graph_at_depth(7)with patch.object(graph_module._ExecutionMaterializer,"prepare",- side_effect=AssertionError("three-level nested Iterate used compatibility materializer"),+ side_effect=AssertionError("seven-level nested Iterate used compatibility materializer"),):generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph),@@ -5024,15 +6891,14 @@ def test_three_level_nested_iterate_failure_matches_compatibility() -> None:assert generic_state.has_error() and compatibility_state.has_error()assert generic_state.is_complete() and compatibility_state.is_complete()assert generic_trace.count("body") == 1- assert _state_projection(generic_state) == _state_projection(compatibility_state)-def test_four_level_nested_iterate_matches_compatibility() -> None:- graph = _four_level_nested_iterate_chain_graph()+def test_eight_level_nested_iterate_matches_compatibility() -> None:+ graph = _serial_nested_iterate_chain_graph_at_depth(8)with patch.object(graph_module._ExecutionMaterializer,"prepare",- side_effect=AssertionError("four-level nested Iterate used compatibility materializer"),+ side_effect=AssertionError("eight-level nested Iterate used compatibility materializer"),):generic_trace, generic_state = _run(GraphExecutionState(graph=graph))compatibility_trace, compatibility_state = _run(@@ -5041,59 +6907,33 @@ def test_four_level_nested_iterate_matches_compatibility() -> None:)assert generic_trace == compatibility_trace- assert generic_trace == (- ["outer_source"]- + ["outer_iterate"] * 2- + ["level1_collection"] * 2- + ["level1_iterate"] * 3- + ["level2_collection"] * 3- + ["level2_iterate"] * 4- + ["level3_collection"] * 4- + ["level3_iterate"] * 5- + ["body"] * 5- )assert generic_state.is_complete()assert compatibility_state.is_complete()assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(- compatibility_state- )assert sorted(generic_state._get_iteration_path(exec_id)for exec_id in generic_state._prepared_registry().get_prepared_ids("body")- ) == [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 1, 0, 0), (1, 0, 0, 0)]+ ) == [(0, 0, 0, 0, 0, 0, 0, 0)]@pytest.mark.parametrize(("outer_collection", "expected_body_paths"),[([], []),- (- [- [],- [- [- [- "c",- ]- ]- ],- ],- [(1, 0, 0, 0)],- ),- ([[[]]], []),- ([[[], []]], []),+ ([[], _nested_collection("c", 7)], [(1, 0, 0, 0, 0, 0, 0, 0)]),+ ([_nested_collection([], 6)], []),],- ids=["outer-empty", "mixed-empty", "deepest-empty", "all-empty"],+ ids=["outer-empty", "mixed-empty", "deepest-empty"],)-def test_four_level_nested_iterate_closes_empty_frames(- outer_collection: list[list[list[list[str]]]], expected_body_paths: list[tuple[int, ...]]+def test_eight_level_nested_iterate_closes_empty_frames(+ outer_collection: list[Any], expected_body_paths: list[tuple[int, ...]]) -> None:- graph = _four_level_nested_iterate_chain_graph(outer_collection=outer_collection)+ graph = _serial_nested_iterate_chain_graph_at_depth(8)+ graph.get_node("source").first = outer_collectionwith patch.object(graph_module._ExecutionMaterializer,"prepare",- side_effect=AssertionError("four-level nested Iterate used compatibility materializer"),+ side_effect=AssertionError("eight-level nested Iterate used compatibility materializer"),):generic_trace, generic_state = _run(GraphExecutionState(graph=graph))compatibility_trace, compatibility_state = _run(@@ -5114,25 +6954,24 @@ def test_four_level_nested_iterate_closes_empty_frames()-def test_four_level_nested_iterate_rehydrates_without_replay() -> None:- graph = _four_level_nested_iterate_chain_graph()+def test_eight_level_nested_iterate_rehydrates_without_replay() -> None:+ graph = _serial_nested_iterate_chain_graph_at_depth(8)expected_trace, expected_state = _run(GraphExecutionState(graph=graph))- partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=12)+ partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=8)resumed_trace, resumed_state = _run(load_execution_state(dump_execution_state(partial_state)))assert partial_trace + resumed_trace == expected_traceassert resumed_state.is_complete()assert _state_projection(resumed_state) == _state_projection(expected_state)- _assert_retained_iterate_streams_match_expected(resumed_state, expected_state)-def test_four_level_nested_iterate_failure_matches_compatibility() -> None:- graph = _four_level_nested_iterate_chain_graph()+def test_eight_level_nested_iterate_failure_matches_compatibility() -> None:+ graph = _serial_nested_iterate_chain_graph_at_depth(8)with patch.object(graph_module._ExecutionMaterializer,"prepare",- side_effect=AssertionError("four-level nested Iterate used compatibility materializer"),+ side_effect=AssertionError("eight-level nested Iterate used compatibility materializer"),):generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph),@@ -5148,686 +6987,811 @@ def test_four_level_nested_iterate_failure_matches_compatibility() -> None:assert generic_state.has_error() and compatibility_state.has_error()assert generic_state.is_complete() and compatibility_state.is_complete()assert generic_trace.count("body") == 1- assert _state_projection(generic_state) == _state_projection(compatibility_state)-def test_five_level_nested_iterate_matches_compatibility() -> None:- graph = _five_level_nested_iterate_chain_graph()- with patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("five-level nested Iterate used compatibility materializer"),- ):- generic_trace, generic_state = _run(GraphExecutionState(graph=graph))+def test_nine_level_nested_iterate_remains_on_compatibility_fallback() -> None:+ state = GraphExecutionState(graph=_serial_nested_iterate_chain_graph_at_depth(9))+ materializer = state._materializer()+ with patch.object(materializer, "prepare", wraps=materializer.prepare) as prepare:+ trace, state = _run(state)++ assert trace.count("body") == 1+ assert state.is_complete()+ assert prepare.call_count > 0++[email protected]("depth", range(2, 9))+def test_nested_iterate_sequence_depth_matcher_matches_supported_inventory(depth: int) -> None:+ state = GraphExecutionState(graph=_serial_nested_iterate_chain_graph_at_depth(depth))++ assert get_nested_iterate_sequence_depth(state) == depth++[email protected]("depth", [1, 9])+def test_nested_iterate_sequence_depth_matcher_rejects_unsupported_depth(depth: int) -> None:+ state = GraphExecutionState(graph=_serial_nested_iterate_chain_graph_at_depth(depth))++ assert get_nested_iterate_sequence_depth(state) is None++[email protected]("values", [[1, None, 1], []], ids=["ordered-duplicates-and-none", "empty"])+def test_input_driven_iterate_collect_uses_generic_stream_ownership(values: list[Any]) -> None:+ compatibility_state = GraphExecutionState(graph=_input_driven_iterate_body_collect_graph(values))compatibility_trace, compatibility_state = _run(- GraphExecutionState(graph=graph),+ compatibility_state,force_compatibility_scheduler=True,)+ generic_state = GraphExecutionState(graph=_input_driven_iterate_body_collect_graph(values))+ with patch.object(+ generic_state._materializer(),+ "prepare",+ side_effect=AssertionError("input-driven Iterate/Collect must not use materializer.prepare"),+ ):+ generic_trace, generic_state = _run(generic_state)+assert generic_trace == compatibility_traceassert generic_state.is_complete()assert compatibility_state.is_complete()+ assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(- compatibility_state+ assert _source_output(generic_state, "after").value == values+++def test_input_driven_iterate_collect_partial_dump_load_preserves_generic_streams() -> None:+ graph = _input_driven_iterate_body_collect_graph(["first", None, "last"])+ expected_trace, expected_state = _run_graph(GraphExecutionState(graph=graph))+ partial_trace, partial_state = _run_graph(GraphExecutionState(graph=graph), stop_after=3)++ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("input-driven checkpoint must not use materializer.prepare"),+ ):+ resumed_trace, resumed_state = _run_graph(load_execution_state(dump_execution_state(partial_state)))++ assert partial_trace + resumed_trace == expected_trace+ assert _source_output(resumed_state, "after").value == ["first", None, "last"]+ assert _state_projection(resumed_state) == _state_projection(expected_state)+++def test_input_driven_iterate_collect_failure_matches_compatibility() -> None:+ graph = _input_driven_iterate_body_collect_graph(["first", "last"])+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph), fail_source_id="body")+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=True, fail_source_id="body")- assert sorted(- generic_state._get_iteration_path(exec_id)- for exec_id in generic_state._prepared_registry().get_prepared_ids("body")- ) == [- (0, 0, 0, 0, 0),- (0, 0, 0, 0, 1),- (0, 0, 1, 0, 0),- (0, 1, 0, 0, 0),- (1, 0, 0, 0, 0),- ]+ assert generic_trace == compatibility_trace+ assert generic_state.has_error() == compatibility_state.has_error()+ assert generic_state.is_complete() == compatibility_state.is_complete()+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert generic_state.next() is None- ("outer_collection", "expected_body_paths"),- [- ([], []),- ([[], [[[["c"]]]]], [(1, 0, 0, 0, 0)]),- ([[[[]]]], []),- ([[[[], []]]], []),- ],- ids=["outer-empty", "mixed-empty", "deepest-empty", "all-empty"],-)-def test_five_level_nested_iterate_closes_empty_frames(- outer_collection: list[list[list[list[list[str]]]]], expected_body_paths: list[tuple[int, ...]]++def test_input_driven_iterate_collect_planner_rolls_back_partial_expansion(+ monkeypatch: pytest.MonkeyPatch,) -> None:- graph = _five_level_nested_iterate_chain_graph(outer_collection=outer_collection)- generic_trace, generic_state = _run(GraphExecutionState(graph=graph))- compatibility_trace, compatibility_state = _run(+ state = GraphExecutionState(graph=_input_driven_iterate_body_collect_graph(["first", "last"]))+ for _ in range(2):+ node = state.next()+ assert node is not None+ state.complete(node.id, node.invoke(Mock()))++ original_create = GraphExecutionState._create_direct_execution_node_copy++ def fail_at_body(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):+ node = original_create(self, source_node_id, *args, **kwargs)+ if source_node_id == "body":+ raise RuntimeError("injected input-driven planner failure")+ return node++ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_body)+ with pytest.raises(RuntimeError, match="injected input-driven planner failure"):+ state.next()++ assert set(state.source_prepared_mapping) == {"producer", "source"}+ assert len(state.execution_graph.nodes) == 2+ assert len(state.execution_graph.edges) == 1++ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)+ trace, state = _run_graph(state)+ assert trace == ["iterate", "iterate", "body", "body", "collect", "after"]+ assert _source_output(state, "after").value == ["first", "last"]+ assert state.is_complete()+++def test_input_driven_iterate_collect_retry_after_input_boundary_isolated() -> None:+ graph = _input_driven_iterate_body_collect_graph(["first", None, "last"])+ canceled_trace, canceled_state = _run_until_source(GraphExecutionState(graph=graph),- force_compatibility_scheduler=True,+ "source",)+ retry_trace, retry_state = _run_graph(GraphExecutionState(graph=graph.model_copy(deep=True)))- assert generic_trace == compatibility_trace- assert generic_state.is_complete()- assert compatibility_state.is_complete()- assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert (- sorted(- generic_state._get_iteration_path(exec_id)- for exec_id in generic_state._prepared_registry().get_prepared_ids("body")- )- == expected_body_paths- )+ assert canceled_trace == ["producer", "source"]+ assert not canceled_state.is_complete()+ assert retry_trace == [+ "producer",+ "source",+ "iterate",+ "iterate",+ "iterate",+ "body",+ "body",+ "body",+ "collect",+ "after",+ ]+ assert retry_state.id != canceled_state.id+ assert _source_output(retry_state, "after").value == ["first", None, "last"]+ assert retry_state.is_complete()-def test_five_level_nested_iterate_rehydrates_without_replay() -> None:- graph = _five_level_nested_iterate_chain_graph()- expected_trace, expected_state = _run(GraphExecutionState(graph=graph))- partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=15)+def test_direct_iterate_body_collect_fresh_execution_preserves_order_and_none() -> None:+ collection = ["first", None, "last"]+ state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection))- resumed_trace, resumed_state = _run(load_execution_state(dump_execution_state(partial_state)))+ with (+ patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("canonical Iterate -> body -> Collect must not use materializer.prepare"),+ ) as prepare,+ patch.object(+ graph_module._ExecutionMaterializer,+ "_get_collect_iteration_mapping_groups",+ side_effect=AssertionError("canonical Iterate -> body -> Collect must not group collector inputs"),+ ) as group_collector_inputs,+ ):+ trace, state = _run_graph(state)- assert partial_trace + resumed_trace == expected_trace- assert resumed_state.is_complete()- assert _state_projection(resumed_state) == _state_projection(expected_state)- _assert_retained_iterate_streams_match_expected(resumed_state, expected_state)+ assert trace.count("iterate") == len(collection)+ assert trace.count("body") == len(collection)+ assert trace.count("collect") == 1+ assert _source_output(state, "collect").collection == collection+ assert state.is_complete()+ assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)+ prepare.assert_not_called()+ group_collector_inputs.assert_not_called()-def test_five_level_nested_iterate_failure_matches_compatibility() -> None:- graph = _five_level_nested_iterate_chain_graph()+def test_direct_iterate_body_collect_fresh_construction_and_execution_do_not_instantiate_materializer() -> None:+ collection = ["first", None, "last"]with patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("five-level nested Iterate used compatibility materializer"),- ):- generic_trace, generic_state = _run_graph_with_effects(- GraphExecutionState(graph=graph),- fail_source_id="body",- )- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=graph),- force_compatibility_scheduler=True,- fail_source_id="body",- )+ graph_module,+ "_ExecutionMaterializer",+ side_effect=AssertionError("fresh direct Iterate/Collect must not instantiate materializer"),+ ) as materializer:+ trace, state = _run_graph(GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)))- assert generic_trace == compatibility_trace- assert generic_state.has_error() and compatibility_state.has_error()- assert generic_state.is_complete() and compatibility_state.is_complete()- assert generic_trace.count("body") == 1- assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert trace == ["source", "iterate", "iterate", "iterate", "body", "body", "body", "collect"]+ assert _source_output(state, "collect").collection == collection+ assert state.is_complete()+ materializer.assert_not_called()-def test_six_level_nested_iterate_matches_compatibility() -> None:- graph = _six_level_nested_iterate_chain_graph()+def test_direct_iterate_body_collect_checkpoint_rehydration_does_not_instantiate_materializer() -> None:+ collection = ["first", None, "last"]+ partial_trace, partial_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)), stop_after=2+ )+with patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("six-level nested Iterate used compatibility materializer"),- ):- generic_trace, generic_state = _run(GraphExecutionState(graph=graph))- compatibility_trace, compatibility_state = _run(- GraphExecutionState(graph=graph),- force_compatibility_scheduler=True,+ graph_module,+ "_ExecutionMaterializer",+ side_effect=AssertionError("direct Iterate/Collect checkpoint must not instantiate materializer"),+ ) as materializer:+ resumed_trace, resumed_state = _run_graph(load_execution_state(dump_execution_state(partial_state)))++ assert partial_trace + resumed_trace == [+ "source",+ "iterate",+ "iterate",+ "iterate",+ "body",+ "body",+ "body",+ "collect",+ ]+ assert _source_output(resumed_state, "collect").collection == collection+ assert resumed_state.is_complete()+ materializer.assert_not_called()+++def test_legacy_direct_iterate_body_collect_snapshot_uses_compatibility_materializer() -> None:+ collection = ["first", None, "last"]+ partial_trace, partial_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)), stop_after=1)+ snapshot = dump_execution_state(partial_state)+ snapshot.pop("execution_state_version")+ snapshot.pop("execution_effects")+ materializer_type = graph_module._ExecutionMaterializer- assert generic_trace == compatibility_trace- assert generic_state.is_complete()- assert compatibility_state.is_complete()- assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert sorted(- generic_state._get_iteration_path(exec_id)- for exec_id in generic_state._prepared_registry().get_prepared_ids("body")- ) == [- (0, 0, 0, 0, 0, 0),- (0, 0, 0, 0, 0, 1),- (0, 0, 0, 1, 0, 0),- (0, 0, 1, 0, 0, 0),- (1, 0, 0, 0, 0, 0),+ with patch.object(graph_module, "_ExecutionMaterializer", wraps=materializer_type) as materializer:+ restored = load_execution_state(snapshot)+ assert restored._legacy_snapshot_loaded+ assert isinstance(restored._scheduler(), _GenericGraphSchedulerAdapter)+ resumed_trace, restored = _run_graph(restored)++ assert materializer.call_count == 1+ assert partial_trace + resumed_trace == [+ "source",+ "iterate",+ "iterate",+ "iterate",+ "body",+ "body",+ "body",+ "collect",]+ assert _source_output(restored, "collect").collection == collection+ assert restored.is_complete()-def _nested_collection(value: Any, depth: int) -> list[Any]:- collection: Any = [value]- for _ in range(depth - 1):- collection = [collection]- return collection+def test_direct_iterate_fan_in_fresh_execution_owns_two_stream_expansion() -> None:+ state = GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=[None, "left-last"], right=["right-first"]))++ with (+ patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("fresh direct fan-in must not use materializer.prepare"),+ ) as prepare,+ patch.object(+ graph_module._ExecutionMaterializer,+ "_get_collect_iteration_mapping_groups",+ side_effect=AssertionError("fresh direct fan-in must not group collector inputs"),+ ) as group_collector_inputs,+ ):+ trace, state = _run_graph(state)++ assert trace.count("collect") == 1+ assert trace == ["left_source", "right_source", "left_iterate", "right_iterate", "left_iterate", "collect"]+ assert _source_output(state, "collect").collection == [None, "left-last", "right-first"]+ streams = {+ stream.owner_id: stream+ for stream in state._generic_runtime().streams.values()+ if stream.owner_id in {"left_iterate", "right_iterate"}+ }+ assert {owner_id: (stream.values, stream.closed) for owner_id, stream in streams.items()} == {+ "left_iterate": ((None, "left-last"), True),+ "right_iterate": (("right-first",), True),+ }+ assert state.is_complete()+ prepare.assert_not_called()+ group_collector_inputs.assert_not_called()@pytest.mark.parametrize(- ("outer_collection", "expected_body_paths"),+ ("left", "right", "expected"),[- ([], []),- ([[], _nested_collection("c", 5)], [(1, 0, 0, 0, 0, 0)]),- ([_nested_collection([], 4)], []),- ([_nested_collection([], 3)], []),+ ([], ["right", None], ["right", None]),+ (["left", None], [], ["left", None]),+ ([], [], []),],- ids=["outer-empty", "mixed-empty", "deepest-empty", "intermediate-empty"],+ ids=["left-empty", "right-empty", "both-empty"],)-def test_six_level_nested_iterate_closes_empty_frames(- outer_collection: list[Any], expected_body_paths: list[tuple[int, ...]]+def test_direct_iterate_fan_in_fresh_execution_closes_empty_streams(+ left: list[Any], right: list[Any], expected: list[Any]) -> None:- graph = _six_level_nested_iterate_chain_graph(outer_collection=outer_collection)- with patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("six-level nested Iterate used compatibility materializer"),- ):- generic_trace, generic_state = _run(GraphExecutionState(graph=graph))- compatibility_trace, compatibility_state = _run(- GraphExecutionState(graph=graph),- force_compatibility_scheduler=True,- )+ trace, state = _run_graph(GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=left, right=right)))- assert generic_trace == compatibility_trace- assert generic_state.is_complete()- assert compatibility_state.is_complete()- assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert (- sorted(- generic_state._get_iteration_path(exec_id)- for exec_id in generic_state._prepared_registry().get_prepared_ids("body")- )- == expected_body_paths- )+ assert trace.count("collect") == 1+ assert _source_output(state, "collect").collection == expected+ streams = {+ stream.owner_id: stream+ for stream in state._generic_runtime().streams.values()+ if stream.owner_id in {"left_iterate", "right_iterate"}+ }+ assert set(streams) == {"left_iterate", "right_iterate"}+ assert all(stream.closed for stream in streams.values())+ assert state.is_complete()-def test_six_level_nested_iterate_rehydrates_without_replay() -> None:- graph = _six_level_nested_iterate_chain_graph()- expected_trace, expected_state = _run(GraphExecutionState(graph=graph))- partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=8)+def test_direct_iterate_fan_in_gates_collect_until_both_streams_close_and_rehydrates() -> None:+ graph = _direct_iterate_fan_in_graph(left=["left-0", "left-1"], right=["right-0", "right-1"])+ expected_trace, expected_state = _run_graph_with_effects(GraphExecutionState(graph=graph))+ partial_trace, partial_state = _run_graph_with_effects(GraphExecutionState(graph=graph), stop_after=3)- resumed_trace, resumed_state = _run(load_execution_state(dump_execution_state(partial_state)))+ assert partial_trace == ["left_source", "right_source", "left_iterate"]+ assert "collect" not in partial_trace+ collect_exec_ids = partial_state.source_prepared_mapping["collect"]+ assert len(collect_exec_ids) == 1+ collect_exec_id = next(iter(collect_exec_ids))+ assert collect_exec_id not in partial_state.executed+ assert not partial_state._generic_runtime().streams[partial_state._iteration_stream_id("left_iterate", ())].closed++ restored = load_execution_state(dump_execution_state(partial_state))+ assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)+ assert _direct_iterate_fan_in_execution_ref_projection(+ restored, execution_ids=set(partial_state.execution_refs)+ ) == _direct_iterate_fan_in_execution_ref_projection(partial_state)+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)+ resumed_trace, resumed_state = _run_graph_with_effects(restored)assert partial_trace + resumed_trace == expected_trace- assert resumed_state.is_complete()+ assert _source_output(resumed_state, "collect").collection == ["left-0", "left-1", "right-0", "right-1"]assert _state_projection(resumed_state) == _state_projection(expected_state)---def test_six_level_nested_iterate_failure_matches_compatibility() -> None:- graph = _six_level_nested_iterate_chain_graph()- with patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("six-level nested Iterate used compatibility materializer"),- ):- generic_trace, generic_state = _run_graph_with_effects(- GraphExecutionState(graph=graph),- fail_source_id="body",- )- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=graph),- force_compatibility_scheduler=True,- fail_source_id="body",+ assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(+ expected_state)-- assert generic_trace == compatibility_trace- assert generic_state.has_error() and compatibility_state.has_error()- assert generic_state.is_complete() and compatibility_state.is_complete()- assert generic_trace.count("body") == 1+ assert _direct_iterate_fan_in_execution_ref_projection(+ resumed_state+ ) == _direct_iterate_fan_in_execution_ref_projection(expected_state)+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)+ assert collect_exec_id in resumed_state.executed+ assert resumed_state.is_complete()-def test_seven_level_nested_iterate_matches_compatibility() -> None:- graph = _serial_nested_iterate_chain_graph_at_depth(7)- with patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("seven-level nested Iterate used compatibility materializer"),- ):- generic_trace, generic_state = _run(GraphExecutionState(graph=graph))- compatibility_trace, compatibility_state = _run(- GraphExecutionState(graph=graph),+def _assert_direct_iterate_fan_in_matches_forced_compatibility_scheduler(left: list[Any], right: list[Any]) -> None:+ generic_trace, generic_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=left, right=right))+ )+ compatibility_trace, compatibility_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=left, right=right)),force_compatibility_scheduler=True,)assert generic_trace == compatibility_trace+ assert (+ _source_output(generic_state, "collect").collection == _source_output(compatibility_state, "collect").collection+ )+ assert _state_projection(generic_state) == _state_projection(compatibility_state)assert generic_state.is_complete()assert compatibility_state.is_complete()- assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert sorted(- generic_state._get_iteration_path(exec_id)- for exec_id in generic_state._prepared_registry().get_prepared_ids("body")- ) == [(0, 0, 0, 0, 0, 0, 0)]@pytest.mark.parametrize(- ("outer_collection", "expected_body_paths"),- [- ([], []),- ([[], _nested_collection("c", 6)], [(1, 0, 0, 0, 0, 0, 0)]),- ([_nested_collection([], 5)], []),- ],- ids=["outer-empty", "mixed-empty", "deepest-empty"],+ ("left", "right"),+ [(["left", None], ["right"]), ([], ["right", None]), ([], [])],+ ids=["ordered-none", "mixed-empty", "both-empty"],)-def test_seven_level_nested_iterate_closes_empty_frames(- outer_collection: list[Any], expected_body_paths: list[tuple[int, ...]]+def test_direct_iterate_fan_in_parity_cases(left: list[Any], right: list[Any]) -> None:+ _assert_direct_iterate_fan_in_matches_forced_compatibility_scheduler(left, right)++[email protected]("force_compatibility_scheduler", [False, True])+def test_direct_iterate_fan_in_partial_dump_load_parity(+ force_compatibility_scheduler: bool,) -> None:- graph = _serial_nested_iterate_chain_graph_at_depth(7)- graph.get_node("source").first = outer_collection- with patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("seven-level nested Iterate used compatibility materializer"),- ):- generic_trace, generic_state = _run(GraphExecutionState(graph=graph))- compatibility_trace, compatibility_state = _run(+ graph = _direct_iterate_fan_in_graph(left=["left-0", "left-1"], right=["right-0", "right-1"])+ expected_trace, expected_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )+ partial_trace, partial_state = _run_graph_with_effects(GraphExecutionState(graph=graph),- force_compatibility_scheduler=True,+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after=3,)- assert generic_trace == compatibility_trace- assert generic_state.is_complete()- assert compatibility_state.is_complete()- assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert (- sorted(- generic_state._get_iteration_path(exec_id)- for exec_id in generic_state._prepared_registry().get_prepared_ids("body")- )- == expected_body_paths+ restored = load_execution_state(dump_execution_state(partial_state))+ assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)+ assert _direct_iterate_fan_in_execution_ref_projection(+ restored, execution_ids=set(partial_state.execution_refs)+ ) == _direct_iterate_fan_in_execution_ref_projection(partial_state)+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(restored)+ resumed_trace, resumed_state = _run_graph_with_effects(+ restored, force_compatibility_scheduler=force_compatibility_scheduler)--def test_seven_level_nested_iterate_rehydrates_without_replay() -> None:- graph = _serial_nested_iterate_chain_graph_at_depth(7)- expected_trace, expected_state = _run(GraphExecutionState(graph=graph))- partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=8)-- resumed_trace, resumed_state = _run(load_execution_state(dump_execution_state(partial_state)))-assert partial_trace + resumed_trace == expected_trace- assert resumed_state.is_complete()+ assert _source_output(resumed_state, "collect").collection == ["left-0", "left-1", "right-0", "right-1"]assert _state_projection(resumed_state) == _state_projection(expected_state)---def test_seven_level_nested_iterate_failure_matches_compatibility() -> None:- graph = _serial_nested_iterate_chain_graph_at_depth(7)- with patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("seven-level nested Iterate used compatibility materializer"),- ):- generic_trace, generic_state = _run_graph_with_effects(- GraphExecutionState(graph=graph),- fail_source_id="body",- )- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=graph),- force_compatibility_scheduler=True,- fail_source_id="body",+ assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(+ expected_state)-- assert generic_trace == compatibility_trace- assert generic_state.has_error() and compatibility_state.has_error()- assert generic_state.is_complete() and compatibility_state.is_complete()- assert generic_trace.count("body") == 1+ assert _direct_iterate_fan_in_execution_ref_projection(+ resumed_state+ ) == _direct_iterate_fan_in_execution_ref_projection(expected_state)+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)+ assert resumed_state.is_complete()-def test_eight_level_nested_iterate_matches_compatibility() -> None:- graph = _serial_nested_iterate_chain_graph_at_depth(8)- with patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("eight-level nested Iterate used compatibility materializer"),- ):- generic_trace, generic_state = _run(GraphExecutionState(graph=graph))- compatibility_trace, compatibility_state = _run(- GraphExecutionState(graph=graph),- force_compatibility_scheduler=True,[email protected]("force_compatibility_scheduler", [False, True])+def test_direct_iterate_fan_in_failure_does_not_execute_collect(+ force_compatibility_scheduler: bool,+) -> None:+ trace, state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=["left"], right=["right"])),+ force_compatibility_scheduler=force_compatibility_scheduler,+ fail_source_id="right_iterate",)- assert generic_trace == compatibility_trace- assert generic_state.is_complete()- assert compatibility_state.is_complete()- assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert sorted(- generic_state._get_iteration_path(exec_id)- for exec_id in generic_state._prepared_registry().get_prepared_ids("body")- ) == [(0, 0, 0, 0, 0, 0, 0, 0)]+ assert trace[-1] == "right_iterate"+ assert "collect" not in trace+ assert state.has_error()+ assert state.is_complete()+ restored = load_execution_state(dump_execution_state(state))+ assert restored.has_error()+ assert restored.is_complete()@pytest.mark.parametrize(- ("outer_collection", "expected_body_paths"),+ ("fail_source_id", "expected_trace"),[- ([], []),- ([[], _nested_collection("c", 7)], [(1, 0, 0, 0, 0, 0, 0, 0)]),- ([_nested_collection([], 6)], []),+ ("right_source", ["left_source", "right_source"]),+ ("right_iterate", ["left_source", "right_source", "left_iterate", "right_iterate"]),],- ids=["outer-empty", "mixed-empty", "deepest-empty"],+ ids=["source-failure", "iterator-failure"],)-def test_eight_level_nested_iterate_closes_empty_frames(- outer_collection: list[Any], expected_body_paths: list[tuple[int, ...]]+def test_direct_iterate_fan_in_apply_failure_matches_compatibility_scheduler(+ fail_source_id: str, expected_trace: list[str]) -> None:- graph = _serial_nested_iterate_chain_graph_at_depth(8)- graph.get_node("source").first = outer_collection- with patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("eight-level nested Iterate used compatibility materializer"),- ):- generic_trace, generic_state = _run(GraphExecutionState(graph=graph))- compatibility_trace, compatibility_state = _run(- GraphExecutionState(graph=graph),- force_compatibility_scheduler=True,+ generic_trace, generic_state = _run_graph_with_effects(+ GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=["left"], right=["right"])),+ fail_source_id=fail_source_id,)-- assert generic_trace == compatibility_trace- assert generic_state.is_complete()- assert compatibility_state.is_complete()- assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert (- sorted(- generic_state._get_iteration_path(exec_id)- for exec_id in generic_state._prepared_registry().get_prepared_ids("body")- )- == expected_body_paths+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=["left"], right=["right"])),+ force_compatibility_scheduler=True,+ fail_source_id=fail_source_id,)+ assert generic_trace == compatibility_trace == expected_trace+ for state in (generic_state, compatibility_state):+ assert state.next() is None+ assert {+ state.prepared_source_mapping.get(node_id, node_id): message for node_id, message in state.errors.items()+ } == {fail_source_id: "injected failure"}+ assert "collect" not in {+ state.prepared_source_mapping.get(execution_id, execution_id) for execution_id in state.executed+ }+ assert state.is_complete()+ restored = load_execution_state(dump_execution_state(state))+ assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(state)+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(state)+ assert restored.next() is None+ assert restored.is_complete()-def test_eight_level_nested_iterate_rehydrates_without_replay() -> None:- graph = _serial_nested_iterate_chain_graph_at_depth(8)- expected_trace, expected_state = _run(GraphExecutionState(graph=graph))- partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=8)+ assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(+ compatibility_state+ )- resumed_trace, resumed_state = _run(load_execution_state(dump_execution_state(partial_state)))- assert partial_trace + resumed_trace == expected_trace- assert resumed_state.is_complete()- assert _state_projection(resumed_state) == _state_projection(expected_state)+def test_direct_iterate_fan_in_rolls_back_partial_expansion(monkeypatch: pytest.MonkeyPatch) -> None:+ state = GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=["left"], right=["right"]))+ _partial_trace, state = _run_graph(state, stop_after=2)+ original_create = GraphExecutionState._create_direct_execution_node_copy-def test_eight_level_nested_iterate_failure_matches_compatibility() -> None:- graph = _serial_nested_iterate_chain_graph_at_depth(8)- with patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("eight-level nested Iterate used compatibility materializer"),- ):- generic_trace, generic_state = _run_graph_with_effects(- GraphExecutionState(graph=graph),- fail_source_id="body",- )- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=graph),- force_compatibility_scheduler=True,- fail_source_id="body",- )+ def fail_at_right_iterate(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):+ if source_node_id == "right_iterate":+ raise RuntimeError("injected fan-in planner failure")+ return original_create(self, source_node_id, *args, **kwargs)- assert generic_trace == compatibility_trace- assert generic_state.has_error() and compatibility_state.has_error()- assert generic_state.is_complete() and compatibility_state.is_complete()- assert generic_trace.count("body") == 1+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_right_iterate)+ with pytest.raises(RuntimeError, match="injected fan-in planner failure"):+ state.next()+ assert set(state.source_prepared_mapping) == {"left_source", "right_source"}+ assert len(state.execution_graph.nodes) == 2+ assert not state.execution_graph.edges+ assert not state._generic_runtime().streams-def test_nine_level_nested_iterate_remains_on_compatibility_fallback() -> None:- state = GraphExecutionState(graph=_serial_nested_iterate_chain_graph_at_depth(9))- materializer = state._materializer()- with patch.object(materializer, "prepare", wraps=materializer.prepare) as prepare:- trace, state = _run(state)+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)+ trace, state = _run_graph(state)- assert trace.count("body") == 1+ assert trace == ["left_iterate", "right_iterate", "collect"]+ assert _source_output(state, "collect").collection == ["left", "right"]assert state.is_complete()- assert prepare.call_count > 0--[email protected]("depth", range(2, 9))-def test_nested_iterate_sequence_depth_matcher_matches_supported_inventory(depth: int) -> None:- state = GraphExecutionState(graph=_serial_nested_iterate_chain_graph_at_depth(depth))- assert get_nested_iterate_sequence_depth(state) == depth+def test_direct_iterate_three_fan_in_fresh_execution_owns_sorted_stream_expansion() -> None:+ graph = _direct_iterate_three_fan_in_graph(a=["dup", None, "dup"], m=["middle"], z=[None, "dup"], unsorted=True)+ assert tuple(graph.nodes) == (+ "collect",+ "z_source",+ "z_iterate",+ "a_source",+ "a_iterate",+ "m_source",+ "m_iterate",+ )+ state = GraphExecutionState(graph=graph)+ fan_in = state._get_direct_iterate_collect_nodes()+ assert isinstance(fan_in, graph_module._DirectIterateCollectFanIn)+ assert fan_in.branches == (+ ("a_source", "a_iterate"),+ ("m_source", "m_iterate"),+ ("z_source", "z_iterate"),+ )[email protected]("depth", [1, 9])-def test_nested_iterate_sequence_depth_matcher_rejects_unsupported_depth(depth: int) -> None:- state = GraphExecutionState(graph=_serial_nested_iterate_chain_graph_at_depth(depth))+ with (+ patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("fresh three-branch fan-in must not use materializer.prepare"),+ ) as prepare,+ patch.object(+ graph_module._ExecutionMaterializer,+ "_get_collect_iteration_mapping_groups",+ side_effect=AssertionError("fresh three-branch fan-in must not group collector inputs"),+ ) as group_collector_inputs,+ ):+ trace, state = _run_graph(state)- assert get_nested_iterate_sequence_depth(state) is None+ assert trace == [+ "a_source",+ "m_source",+ "z_source",+ "a_iterate",+ "m_iterate",+ "z_iterate",+ "a_iterate",+ "z_iterate",+ "a_iterate",+ "collect",+ ]+ assert _source_output(state, "collect").collection == ["dup", None, "dup", "middle", None, "dup"]+ streams = {+ stream.owner_id: stream+ for stream in state._generic_runtime().streams.values()+ if stream.owner_id in {"a_iterate", "m_iterate", "z_iterate"}+ }+ assert {owner_id: (stream.values, stream.closed) for owner_id, stream in streams.items()} == {+ "a_iterate": (("dup", None, "dup"), True),+ "m_iterate": (("middle",), True),+ "z_iterate": ((None, "dup"), True),+ }+ assert state.is_complete()+ prepare.assert_not_called()+ group_collector_inputs.assert_not_called()[email protected]("values", [[1, None, 1], []], ids=["ordered-duplicates-and-none", "empty"])-def test_input_driven_iterate_collect_uses_generic_stream_ownership(values: list[Any]) -> None:- compatibility_state = GraphExecutionState(graph=_input_driven_iterate_body_collect_graph(values))- compatibility_trace, compatibility_state = _run(- compatibility_state,- force_compatibility_scheduler=True,- )+ ("a", "m", "z"),+ [+ ([], [], []),+ (["a"], [], []),+ ([], ["m"], []),+ ([], [], ["z"]),+ (["a"], ["m"], []),+ (["a"], [], ["z"]),+ ([], ["m"], ["z"]),+ ],+ ids=["all-empty", "a-only", "m-only", "z-only", "a-m", "a-z", "m-z"],+)+def test_direct_iterate_three_fan_in_closes_every_empty_stream(a: list[Any], m: list[Any], z: list[Any]) -> None:+ trace, state = _run_graph(GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=a, m=m, z=z)))- generic_state = GraphExecutionState(graph=_input_driven_iterate_body_collect_graph(values))- with patch.object(- generic_state._materializer(),- "prepare",- side_effect=AssertionError("input-driven Iterate/Collect must not use materializer.prepare"),- ):- generic_trace, generic_state = _run(generic_state)+ assert trace.count("collect") == 1+ assert _source_output(state, "collect").collection == a + m + z+ streams = {+ stream.owner_id: stream+ for stream in state._generic_runtime().streams.values()+ if stream.owner_id in {"a_iterate", "m_iterate", "z_iterate"}+ }+ assert set(streams) == {"a_iterate", "m_iterate", "z_iterate"}+ assert all(stream.closed for stream in streams.values())+ assert state.is_complete()- assert generic_trace == compatibility_trace- assert generic_state.is_complete()- assert compatibility_state.is_complete()- assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)- assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)- assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert _source_output(generic_state, "after").value == values+def test_direct_iterate_three_fan_in_partial_dump_load_resumes_without_duplicate_work() -> None:+ graph = _direct_iterate_three_fan_in_graph(a=["a-0", "a-1"], m=["m-0", "m-1"], z=["z-0", "z-1"])+ expected_trace, expected_state = _run_graph_with_effects(GraphExecutionState(graph=graph))+ partial_trace, partial_state = _run_graph_with_effects(GraphExecutionState(graph=graph), stop_after=5)-def test_input_driven_iterate_collect_partial_dump_load_preserves_generic_streams() -> None:- graph = _input_driven_iterate_body_collect_graph(["first", None, "last"])- expected_trace, expected_state = _run_graph(GraphExecutionState(graph=graph))- partial_trace, partial_state = _run_graph(GraphExecutionState(graph=graph), stop_after=3)+ assert partial_trace == ["a_source", "m_source", "z_source", "a_iterate", "m_iterate"]+ assert "collect" not in partial_trace+ collect_exec_ids = partial_state.source_prepared_mapping["collect"]+ assert len(collect_exec_ids) == 1+ collect_exec_id = next(iter(collect_exec_ids))+ assert collect_exec_id not in partial_state.executed- with patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("input-driven checkpoint must not use materializer.prepare"),- ):- resumed_trace, resumed_state = _run_graph(load_execution_state(dump_execution_state(partial_state)))+ restored = load_execution_state(dump_execution_state(partial_state))+ assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)+ assert _direct_iterate_fan_in_execution_ref_projection(+ restored, execution_ids=set(partial_state.execution_refs)+ ) == _direct_iterate_fan_in_execution_ref_projection(partial_state)+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)+ resumed_trace, resumed_state = _run_graph_with_effects(restored)assert partial_trace + resumed_trace == expected_trace- assert _source_output(resumed_state, "after").value == ["first", None, "last"]+ assert _source_output(resumed_state, "collect").collection == ["a-0", "a-1", "m-0", "m-1", "z-0", "z-1"]assert _state_projection(resumed_state) == _state_projection(expected_state)+ assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(+ expected_state+ )+ assert _direct_iterate_fan_in_execution_ref_projection(+ resumed_state+ ) == _direct_iterate_fan_in_execution_ref_projection(expected_state)+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)+ assert collect_exec_id in resumed_state.executed+ assert resumed_state.is_complete()+++ ("a", "m", "z"),+ [+ (["a", None, "a"], ["m"], ["z", None]),+ ([], ["m", "m"], []),+ ([], [], []),+ ],+ ids=["ordered-none-duplicates", "mixed-empty-duplicates", "all-empty"],+)+def test_direct_iterate_three_fan_in_matches_forced_compatibility_scheduler(+ a: list[Any], m: list[Any], z: list[Any]+) -> None:+ generic_trace, generic_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=a, m=m, z=z))+ )+ compatibility_trace, compatibility_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=a, m=m, z=z)),+ force_compatibility_scheduler=True,+ )++ assert generic_trace == compatibility_trace+ assert (+ _source_output(generic_state, "collect").collection == _source_output(compatibility_state, "collect").collection+ )+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()-def test_input_driven_iterate_collect_failure_matches_compatibility() -> None:- graph = _input_driven_iterate_body_collect_graph(["first", "last"])- generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph), fail_source_id="body")+ ("fail_source_id", "expected_trace"),+ [+ ("m_source", ["a_source", "m_source"]),+ (+ "m_iterate",+ ["a_source", "m_source", "z_source", "a_iterate", "m_iterate"],+ ),+ ],+ ids=["source-failure", "iterator-failure"],+)+def test_direct_iterate_three_fan_in_failure_matches_compatibility_and_blocks_collect(+ fail_source_id: str, expected_trace: list[str]+) -> None:+ generic_trace, generic_state = _run_graph_with_effects(+ GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=["a"], m=["m"], z=["z"])),+ fail_source_id=fail_source_id,+ )compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=graph), force_compatibility_scheduler=True, fail_source_id="body"+ GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=["a"], m=["m"], z=["z"])),+ force_compatibility_scheduler=True,+ fail_source_id=fail_source_id,)- assert generic_trace == compatibility_trace- assert generic_state.has_error() == compatibility_state.has_error()- assert generic_state.is_complete() == compatibility_state.is_complete()- assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert generic_state.next() is None+ assert generic_trace == compatibility_trace == expected_trace+ for state in (generic_state, compatibility_state):+ assert state.next() is None+ assert state.has_error()+ assert "collect" not in {+ state.prepared_source_mapping.get(execution_id, execution_id) for execution_id in state.executed+ }+ assert state.is_complete()+ restored = load_execution_state(dump_execution_state(state))+ assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(state)+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(state)+ assert restored.next() is None+ assert restored.is_complete()++ assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(+ compatibility_state+ )-def test_input_driven_iterate_collect_planner_rolls_back_partial_expansion(- monkeypatch: pytest.MonkeyPatch,-) -> None:- state = GraphExecutionState(graph=_input_driven_iterate_body_collect_graph(["first", "last"]))- for _ in range(2):- node = state.next()- assert node is not None- state.complete(node.id, node.invoke(Mock()))+def test_direct_iterate_three_fan_in_rolls_back_partial_expansion(monkeypatch: pytest.MonkeyPatch) -> None:+ state = GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=["a"], m=["m"], z=["z"]))+ _partial_trace, state = _run_graph(state, stop_after=3)original_create = GraphExecutionState._create_direct_execution_node_copy- def fail_at_body(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):- node = original_create(self, source_node_id, *args, **kwargs)- if source_node_id == "body":- raise RuntimeError("injected input-driven planner failure")- return node+ def fail_at_m_iterate(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):+ if source_node_id == "m_iterate":+ raise RuntimeError("injected three-branch fan-in planner failure")+ return original_create(self, source_node_id, *args, **kwargs)- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_body)- with pytest.raises(RuntimeError, match="injected input-driven planner failure"):+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_m_iterate)+ with pytest.raises(RuntimeError, match="injected three-branch fan-in planner failure"):state.next()- assert set(state.source_prepared_mapping) == {"producer", "source"}- assert len(state.execution_graph.nodes) == 2- assert len(state.execution_graph.edges) == 1+ assert set(state.source_prepared_mapping) == {"a_source", "m_source", "z_source"}+ assert len(state.execution_graph.nodes) == 3+ assert not state.execution_graph.edges+ assert not state._generic_runtime().streamsmonkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)trace, state = _run_graph(state)- assert trace == ["iterate", "iterate", "body", "body", "collect", "after"]- assert _source_output(state, "after").value == ["first", "last"]++ assert trace == ["a_iterate", "m_iterate", "z_iterate", "collect"]+ assert _source_output(state, "collect").collection == ["a", "m", "z"]assert state.is_complete()-def test_input_driven_iterate_collect_retry_after_input_boundary_isolated() -> None:- graph = _input_driven_iterate_body_collect_graph(["first", None, "last"])- canceled_trace, canceled_state = _run_until_source(- GraphExecutionState(graph=graph),- "source",+def test_direct_iterate_four_fan_in_stays_on_compatibility_fallback() -> None:+ graph = _direct_iterate_fan_in_graph_with_branches(+ branches=(+ ("a_source", "a_iterate", ["a"]),+ ("m_source", "m_iterate", ["m"]),+ ("z_source", "z_iterate", ["z"]),+ ("q_source", "q_iterate", ["q"]),+ ))- retry_trace, retry_state = _run_graph(GraphExecutionState(graph=graph.model_copy(deep=True)))+ state = GraphExecutionState(graph=graph)+ assert state._get_direct_iterate_collect_nodes() is None- assert canceled_trace == ["producer", "source"]- assert not canceled_state.is_complete()- assert retry_trace == [- "producer",- "source",- "iterate",- "iterate",- "iterate",- "body",- "body",- "body",- "collect",- "after",- ]- assert retry_state.id != canceled_state.id- assert _source_output(retry_state, "after").value == ["first", None, "last"]- assert retry_state.is_complete()+ compatibility_trace, compatibility_state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=True+ )++ assert compatibility_trace+ assert sorted(_source_output(compatibility_state, "collect").collection) == ["a", "m", "q", "z"]+ assert compatibility_state.is_complete()-def test_direct_iterate_body_collect_fresh_execution_preserves_order_and_none() -> None:- collection = ["first", None, "last"]- state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection))+def test_body_iterate_fan_in_fresh_execution_owns_exact_two_branch_shape() -> None:+ graph = _body_iterate_fan_in_graph(+ branches=(+ ("z_source", "z_iterate", "z_body", ["z", None, "z"]),+ ("a_source", "a_iterate", "a_body", ["a", None, "a"]),+ )+ )+ assert len(graph.nodes) == 7+ assert len(graph.edges) == 6+ state = GraphExecutionState(graph=graph)+ fan_in = state._get_direct_iterate_collect_nodes()+ assert isinstance(fan_in, graph_module._BodyIterateCollectFanIn)+ assert fan_in.branches == (+ ("a_source", "a_iterate", "a_body"),+ ("z_source", "z_iterate", "z_body"),+ )with (patch.object(graph_module._ExecutionMaterializer,"prepare",- side_effect=AssertionError("canonical Iterate -> body -> Collect must not use materializer.prepare"),+ side_effect=AssertionError("body fan-in must not use materializer.prepare"),) as prepare,patch.object(graph_module._ExecutionMaterializer,"_get_collect_iteration_mapping_groups",- side_effect=AssertionError("canonical Iterate -> body -> Collect must not group collector inputs"),+ side_effect=AssertionError("body fan-in must not group collector inputs"),) as group_collector_inputs,):trace, state = _run_graph(state)- assert trace.count("iterate") == len(collection)- assert trace.count("body") == len(collection)+ assert trace.count("a_source") == trace.count("z_source") == 1+ assert trace.count("a_iterate") == 3+ assert trace.count("z_iterate") == 3+ assert trace.count("a_body") == 3+ assert trace.count("z_body") == 3assert trace.count("collect") == 1- assert _source_output(state, "collect").collection == collection+ assert _source_output(state, "collect").collection == ["a", None, "a", "z", None, "z"]assert state.is_complete()assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)prepare.assert_not_called()group_collector_inputs.assert_not_called()-def test_direct_iterate_body_collect_fresh_construction_and_execution_do_not_instantiate_materializer() -> None:- collection = ["first", None, "last"]- with patch.object(- graph_module,- "_ExecutionMaterializer",- side_effect=AssertionError("fresh direct Iterate/Collect must not instantiate materializer"),- ) as materializer:- trace, state = _run_graph(GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)))-- assert trace == ["source", "iterate", "iterate", "iterate", "body", "body", "body", "collect"]- assert _source_output(state, "collect").collection == collection- assert state.is_complete()- materializer.assert_not_called()---def test_direct_iterate_body_collect_checkpoint_rehydration_does_not_instantiate_materializer() -> None:- collection = ["first", None, "last"]- partial_trace, partial_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)), stop_after=2+def test_body_iterate_fan_in_orders_by_source_id_not_body_id() -> None:+ graph = _body_iterate_fan_in_graph(+ branches=(+ ("z_source", "z_iterate", "a_body", ["z-0", "z-1"]),+ ("a_source", "a_iterate", "z_body", ["a-0", "a-1"]),+ ))-- with patch.object(- graph_module,- "_ExecutionMaterializer",- side_effect=AssertionError("direct Iterate/Collect checkpoint must not instantiate materializer"),- ) as materializer:- resumed_trace, resumed_state = _run_graph(load_execution_state(dump_execution_state(partial_state)))-- assert partial_trace + resumed_trace == [- "source",- "iterate",- "iterate",- "iterate",- "body",- "body",- "body",- "collect",- ]- assert _source_output(resumed_state, "collect").collection == collection- assert resumed_state.is_complete()- materializer.assert_not_called()---def test_legacy_direct_iterate_body_collect_snapshot_uses_compatibility_materializer() -> None:- collection = ["first", None, "last"]- partial_trace, partial_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)), stop_after=1+ state = GraphExecutionState(graph=graph)+ fan_in = state._get_direct_iterate_collect_nodes()+ assert isinstance(fan_in, graph_module._BodyIterateCollectFanIn)+ assert fan_in.branches == (+ ("a_source", "a_iterate", "z_body"),+ ("z_source", "z_iterate", "a_body"),)- snapshot = dump_execution_state(partial_state)- snapshot.pop("execution_state_version")- snapshot.pop("execution_effects")- materializer_type = graph_module._ExecutionMaterializer-- with patch.object(graph_module, "_ExecutionMaterializer", wraps=materializer_type) as materializer:- restored = load_execution_state(snapshot)- assert restored._legacy_snapshot_loaded- assert isinstance(restored._scheduler(), _GenericGraphSchedulerAdapter)- resumed_trace, restored = _run_graph(restored)-- assert materializer.call_count == 1- assert partial_trace + resumed_trace == [- "source",- "iterate",- "iterate",- "iterate",- "body",- "body",- "body",- "collect",- ]- assert _source_output(restored, "collect").collection == collection- assert restored.is_complete()--def test_direct_iterate_fan_in_fresh_execution_owns_two_stream_expansion() -> None:- state = GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=[None, "left-last"], right=["right-first"]))-- with (- patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("fresh direct fan-in must not use materializer.prepare"),- ) as prepare,- patch.object(- graph_module._ExecutionMaterializer,- "_get_collect_iteration_mapping_groups",- side_effect=AssertionError("fresh direct fan-in must not group collector inputs"),- ) as group_collector_inputs,- ):- trace, state = _run_graph(state)+ trace, state = _run_graph_with_effects(state)- assert trace.count("collect") == 1- assert trace == ["left_source", "right_source", "left_iterate", "right_iterate", "left_iterate", "collect"]- assert _source_output(state, "collect").collection == [None, "left-last", "right-first"]- streams = {- stream.owner_id: stream- for stream in state._generic_runtime().streams.values()- if stream.owner_id in {"left_iterate", "right_iterate"}- }- assert {owner_id: (stream.values, stream.closed) for owner_id, stream in streams.items()} == {- "left_iterate": ((None, "left-last"), True),- "right_iterate": (("right-first",), True),- }+ assert trace[-1] == "collect"+ assert _source_output(state, "collect").collection == ["a-0", "a-1", "z-0", "z-1"]assert state.is_complete()- prepare.assert_not_called()- group_collector_inputs.assert_not_called()@pytest.mark.parametrize(@@ -5839,10 +7803,14 @@ def test_direct_iterate_fan_in_fresh_execution_owns_two_stream_expansion() -> No],ids=["left-empty", "right-empty", "both-empty"],)-def test_direct_iterate_fan_in_fresh_execution_closes_empty_streams(- left: list[Any], right: list[Any], expected: list[Any]-) -> None:- trace, state = _run_graph(GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=left, right=right)))+def test_body_iterate_fan_in_closes_empty_branches(left: list[Any], right: list[Any], expected: list[Any]) -> None:+ graph = _body_iterate_fan_in_graph(+ branches=(+ ("right_source", "right_iterate", "right_body", right),+ ("left_source", "left_iterate", "left_body", left),+ )+ )+ trace, state = _run_graph(GraphExecutionState(graph=graph))assert trace.count("collect") == 1assert _source_output(state, "collect").collection == expected@@ -5856,29 +7824,49 @@ def test_direct_iterate_fan_in_fresh_execution_closes_empty_streams(assert state.is_complete()-def test_direct_iterate_fan_in_gates_collect_until_both_streams_close_and_rehydrates() -> None:- graph = _direct_iterate_fan_in_graph(left=["left-0", "left-1"], right=["right-0", "right-1"])- expected_trace, expected_state = _run_graph_with_effects(GraphExecutionState(graph=graph))- partial_trace, partial_state = _run_graph_with_effects(GraphExecutionState(graph=graph), stop_after=3)[email protected]("force_compatibility_scheduler", [False, True])+def test_body_iterate_fan_in_partial_dump_load_preserves_streams_and_effects(+ force_compatibility_scheduler: bool,+) -> None:+ graph = _body_iterate_fan_in_graph(+ branches=(+ ("right_source", "right_iterate", "right_body", ["right-0", "right-1"]),+ ("left_source", "left_iterate", "left_body", ["left-0", "left-1"]),+ )+ )+ expected_trace, expected_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )+ partial_trace, partial_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after=3,+ )- assert partial_trace == ["left_source", "right_source", "left_iterate"]assert "collect" not in partial_trace- collect_exec_ids = partial_state.source_prepared_mapping["collect"]- assert len(collect_exec_ids) == 1- collect_exec_id = next(iter(collect_exec_ids))- assert collect_exec_id not in partial_state.executed- assert not partial_state._generic_runtime().streams[partial_state._iteration_stream_id("left_iterate", ())].closed-+ if not force_compatibility_scheduler:+ assert (+ not partial_state._generic_runtime().streams[partial_state._iteration_stream_id("left_iterate", ())].closed+ )restored = load_execution_state(dump_execution_state(partial_state))assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)assert _direct_iterate_fan_in_execution_ref_projection(restored, execution_ids=set(partial_state.execution_refs)) == _direct_iterate_fan_in_execution_ref_projection(partial_state)assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)- resumed_trace, resumed_state = _run_graph_with_effects(restored)+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(restored)+ resumed_trace, resumed_state = _run_graph_with_effects(+ restored, force_compatibility_scheduler=force_compatibility_scheduler+ )assert partial_trace + resumed_trace == expected_trace- assert _source_output(resumed_state, "collect").collection == ["left-0", "left-1", "right-0", "right-1"]+ assert _source_output(resumed_state, "collect").collection == [+ "left-0",+ "left-1",+ "right-0",+ "right-1",+ ]assert _state_projection(resumed_state) == _state_projection(expected_state)assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(expected_state@@ -5887,65 +7875,50 @@ def test_direct_iterate_fan_in_gates_collect_until_both_streams_close_and_rehydrresumed_state) == _direct_iterate_fan_in_execution_ref_projection(expected_state)assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)- assert collect_exec_id in resumed_state.executedassert resumed_state.is_complete()-def _assert_direct_iterate_fan_in_matches_forced_compatibility_scheduler(left: list[Any], right: list[Any]) -> None:- generic_trace, generic_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=left, right=right))- )- compatibility_trace, compatibility_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=left, right=right)),- force_compatibility_scheduler=True,- )-- assert generic_trace == compatibility_trace- assert (- _source_output(generic_state, "collect").collection == _source_output(compatibility_state, "collect").collection- )- assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert generic_state.is_complete()- assert compatibility_state.is_complete()--- ("left", "right"),- [(["left", None], ["right"]), ([], ["right", None]), ([], [])],- ids=["ordered-none", "mixed-empty", "both-empty"],-)-def test_direct_iterate_fan_in_parity_cases(left: list[Any], right: list[Any]) -> None:- _assert_direct_iterate_fan_in_matches_forced_compatibility_scheduler(left, right)--@pytest.mark.parametrize("force_compatibility_scheduler", [False, True])-def test_direct_iterate_fan_in_partial_dump_load_parity(+def test_body_iterate_fan_in_source_prepared_dump_load_resumes(force_compatibility_scheduler: bool,) -> None:- graph = _direct_iterate_fan_in_graph(left=["left-0", "left-1"], right=["right-0", "right-1"])+ graph = _body_iterate_fan_in_graph(+ branches=(+ ("right_source", "right_iterate", "right_body", ["right-0", "right-1"]),+ ("left_source", "left_iterate", "left_body", ["left-0", "left-1"]),+ )+ )expected_trace, expected_state = _run_graph_with_effects(GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler)partial_trace, partial_state = _run_graph_with_effects(GraphExecutionState(graph=graph),force_compatibility_scheduler=force_compatibility_scheduler,- stop_after=3,+ stop_after=2,)- restored = load_execution_state(dump_execution_state(partial_state))+ assert partial_trace == expected_trace[:2]+ assert set(partial_trace) == {"left_source", "right_source"}+ assert set(partial_state.source_prepared_mapping) == {"left_source", "right_source"}+ assert "collect" not in partial_state.source_prepared_mapping+ assert not partial_state._generic_runtime().streams+ checkpoint = dump_execution_state(partial_state)+ restored = load_execution_state(checkpoint)+ assert _state_projection(restored) == _state_projection(partial_state)assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)assert _direct_iterate_fan_in_execution_ref_projection(restored, execution_ids=set(partial_state.execution_refs)) == _direct_iterate_fan_in_execution_ref_projection(partial_state)+ assert _execution_token_projection(restored) == _execution_token_projection(partial_state)assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)if force_compatibility_scheduler:_restore_compatibility_scheduler(restored)+resumed_trace, resumed_state = _run_graph_with_effects(restored, force_compatibility_scheduler=force_compatibility_scheduler)assert partial_trace + resumed_trace == expected_trace- assert _source_output(resumed_state, "collect").collection == ["left-0", "left-1", "right-0", "right-1"]assert _state_projection(resumed_state) == _state_projection(expected_state)assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(expected_state@@ -5953,2508 +7926,3357 @@ def test_direct_iterate_fan_in_partial_dump_load_parity(assert _direct_iterate_fan_in_execution_ref_projection(resumed_state) == _direct_iterate_fan_in_execution_ref_projection(expected_state)+ assert _execution_token_projection(resumed_state) == _execution_token_projection(expected_state)+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)+ assert resumed_state.is_complete()+++def test_body_iterate_fan_in_partial_dump_load_after_one_stream_closes() -> None:+ graph = _body_iterate_fan_in_graph(+ branches=(+ ("right_source", "right_iterate", "right_body", ["right-0", "right-1"]),+ ("left_source", "left_iterate", "left_body", ["left-0"]),+ )+ )+ expected_trace, expected_state = _run_graph_with_effects(GraphExecutionState(graph=graph))+ partial_trace, partial_state = _run_graph_with_effects(GraphExecutionState(graph=graph), stop_after=3)++ assert partial_trace == ["left_source", "right_source", "left_iterate"]+ streams = partial_state._generic_runtime().streams+ assert streams[partial_state._iteration_stream_id("left_iterate", ())].closed+ right_stream = streams.get(partial_state._iteration_stream_id("right_iterate", ()))+ assert right_stream is None or not right_stream.closed+ assert "collect" not in partial_trace++ restored = load_execution_state(dump_execution_state(partial_state))+ assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)+ resumed_trace, resumed_state = _run_graph_with_effects(restored)++ assert partial_trace + resumed_trace == expected_trace+ assert _source_output(resumed_state, "collect").collection == ["left-0", "right-0", "right-1"]+ assert _state_projection(resumed_state) == _state_projection(expected_state)+ assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(+ expected_state+ )assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)assert resumed_state.is_complete()+ ("left", "right", "expected"),+ [+ (["left", None, "left"], ["right", None], ["left", None, "left", "right", None]),+ ([], ["right", None], ["right", None]),+ ([], [], []),+ ],+ ids=["ordered-none-duplicates", "mixed-empty", "all-empty"],+)+def test_body_iterate_fan_in_matches_forced_compatibility_scheduler(+ left: list[Any], right: list[Any], expected: list[Any]+) -> None:+ graph = _body_iterate_fan_in_graph(+ branches=(+ ("left_source", "left_iterate", "left_body", left),+ ("right_source", "right_iterate", "right_body", right),+ )+ )+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph))+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=True+ )++ assert generic_trace == compatibility_trace+ assert _source_output(generic_state, "collect").collection == expected+ assert (+ _source_output(generic_state, "collect").collection == _source_output(compatibility_state, "collect").collection+ )+ if left or right:+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(+ compatibility_state+ )+ assert _direct_iterate_fan_in_execution_ref_projection(+ generic_state+ ) == _direct_iterate_fan_in_execution_ref_projection(compatibility_state)+ assert _execution_token_projection(generic_state) == _execution_token_projection(compatibility_state)+ assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)+ assert _execution_edge_projection(generic_state) == _execution_edge_projection(compatibility_state)+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()++@pytest.mark.parametrize("force_compatibility_scheduler", [False, True])-def test_direct_iterate_fan_in_failure_does_not_execute_collect(- force_compatibility_scheduler: bool,[email protected]("fail_source_id", ["right_source", "right_iterate", "right_body"])+def test_body_iterate_fan_in_failure_blocks_collect_and_persists(+ force_compatibility_scheduler: bool, fail_source_id: str) -> None:- trace, state = _run_graph(- GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=["left"], right=["right"])),+ graph = _body_iterate_fan_in_graph(+ branches=(+ ("left_source", "left_iterate", "left_body", ["left"]),+ ("right_source", "right_iterate", "right_body", ["right"]),+ )+ )+ trace, state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),force_compatibility_scheduler=force_compatibility_scheduler,- fail_source_id="right_iterate",+ fail_source_id=fail_source_id,)- assert trace[-1] == "right_iterate"+ assert trace[-1] == fail_source_idassert "collect" not in traceassert state.has_error()assert state.is_complete()+ assert state.next() is None+ assert tuple(+ sorted(+ (state.prepared_source_mapping.get(execution_id, execution_id), message)+ for execution_id, message in state.errors.items()+ )+ ) == ((fail_source_id, "injected failure"),)restored = load_execution_state(dump_execution_state(state))+ assert _state_projection(restored) == _state_projection(state)+ assert _execution_edge_projection(restored) == _execution_edge_projection(state)+ assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(state)+ assert _direct_iterate_fan_in_execution_ref_projection(+ restored, execution_ids=set(state.execution_refs)+ ) == _direct_iterate_fan_in_execution_ref_projection(state)+ assert _execution_token_projection(restored) == _execution_token_projection(state)+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(state)assert restored.has_error()+ assert tuple(+ sorted(+ (restored.prepared_source_mapping.get(execution_id, execution_id), message)+ for execution_id, message in restored.errors.items()+ )+ ) == ((fail_source_id, "injected failure"),)+ assert restored.next() is Noneassert restored.is_complete()- ("fail_source_id", "expected_trace"),- [- ("right_source", ["left_source", "right_source"]),- ("right_iterate", ["left_source", "right_source", "left_iterate", "right_iterate"]),- ],- ids=["source-failure", "iterator-failure"],-)-def test_direct_iterate_fan_in_apply_failure_matches_compatibility_scheduler(- fail_source_id: str, expected_trace: list[str]-) -> None:[email protected]("fail_source_id", ["right_source", "right_iterate", "right_body"])+def test_body_iterate_fan_in_failure_matches_forced_compatibility_scheduler(fail_source_id: str) -> None:+ graph = _body_iterate_fan_in_graph(+ branches=(+ ("left_source", "left_iterate", "left_body", ["left"]),+ ("right_source", "right_iterate", "right_body", ["right"]),+ )+ )generic_trace, generic_state = _run_graph_with_effects(- GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=["left"], right=["right"])),- fail_source_id=fail_source_id,+ GraphExecutionState(graph=graph), fail_source_id=fail_source_id)compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=["left"], right=["right"])),+ GraphExecutionState(graph=graph),force_compatibility_scheduler=True,fail_source_id=fail_source_id,)- assert generic_trace == compatibility_trace == expected_trace+ assert generic_trace == compatibility_trace+ assert generic_state.has_error() == compatibility_state.has_error()+ assert generic_state.is_complete() == compatibility_state.is_complete()+ assert {+ generic_state.prepared_source_mapping.get(execution_id, execution_id): message+ for execution_id, message in generic_state.errors.items()+ } == {+ compatibility_state.prepared_source_mapping.get(execution_id, execution_id): message+ for execution_id, message in compatibility_state.errors.items()+ }+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(+ compatibility_state+ )+ assert _direct_iterate_fan_in_execution_ref_projection(+ generic_state+ ) == _direct_iterate_fan_in_execution_ref_projection(compatibility_state)+ assert _execution_token_projection(generic_state) == _execution_token_projection(compatibility_state)+ assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)for state in (generic_state, compatibility_state):- assert state.next() is None- assert {- state.prepared_source_mapping.get(node_id, node_id): message for node_id, message in state.errors.items()- } == {fail_source_id: "injected failure"}+ assert state.has_error()assert "collect" not in {state.prepared_source_mapping.get(execution_id, execution_id) for execution_id in state.executed}assert state.is_complete()- restored = load_execution_state(dump_execution_state(state))- assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(state)- assert _effect_ledger_projection(restored) == _effect_ledger_projection(state)- assert restored.next() is None- assert restored.is_complete()- assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)- assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(- compatibility_state- )--def test_direct_iterate_fan_in_rolls_back_partial_expansion(monkeypatch: pytest.MonkeyPatch) -> None:- state = GraphExecutionState(graph=_direct_iterate_fan_in_graph(left=["left"], right=["right"]))- _partial_trace, state = _run_graph(state, stop_after=2)+def test_body_iterate_fan_in_rolls_back_mid_expansion_and_retries(monkeypatch: pytest.MonkeyPatch) -> None:+ graph = _body_iterate_fan_in_graph(+ branches=(+ ("left_source", "left_iterate", "left_body", ["left"]),+ ("right_source", "right_iterate", "right_body", ["right"]),+ )+ )+ state = GraphExecutionState(graph=graph)+ _partial_trace, state = _run_graph_with_effects(state, stop_after=2)+ before_failure_durable = _body_fan_in_durable_projection(state)+ before_failure_runtime = _body_fan_in_runtime_projection(state)original_create = GraphExecutionState._create_direct_execution_node_copy- def fail_at_right_iterate(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):- if source_node_id == "right_iterate":- raise RuntimeError("injected fan-in planner failure")+ def fail_at_right_body(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):+ if source_node_id == "right_body":+ raise RuntimeError("injected body fan-in planner failure")return original_create(self, source_node_id, *args, **kwargs)- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_right_iterate)- with pytest.raises(RuntimeError, match="injected fan-in planner failure"):+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_right_body)+ with pytest.raises(RuntimeError, match="injected body fan-in planner failure"):state.next()- assert set(state.source_prepared_mapping) == {"left_source", "right_source"}- assert len(state.execution_graph.nodes) == 2- assert not state.execution_graph.edges- assert not state._generic_runtime().streams+ assert _body_fan_in_durable_projection(state) == before_failure_durable+ assert _body_fan_in_runtime_projection(state) == before_failure_runtimemonkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)- trace, state = _run_graph(state)+ trace, state = _run_graph_with_effects(state)+ expected_trace, expected_state = _run_graph_with_effects(+ GraphExecutionState(+ graph=_body_iterate_fan_in_graph(+ branches=(+ ("left_source", "left_iterate", "left_body", ["left"]),+ ("right_source", "right_iterate", "right_body", ["right"]),+ )+ )+ )+ )- assert trace == ["left_iterate", "right_iterate", "collect"]+ assert _partial_trace + trace == expected_trace+ assert trace == ["left_iterate", "right_iterate", "left_body", "right_body", "collect"]assert _source_output(state, "collect").collection == ["left", "right"]+ assert _state_projection(state) == _state_projection(expected_state)+ assert _direct_iterate_fan_in_stream_projection(state) == _direct_iterate_fan_in_stream_projection(expected_state)+ assert _direct_iterate_fan_in_execution_ref_projection(state) == _direct_iterate_fan_in_execution_ref_projection(+ expected_state+ )+ assert _execution_token_projection(state) == _execution_token_projection(expected_state)+ assert _effect_ledger_projection(state) == _effect_ledger_projection(expected_state)assert state.is_complete()-def test_direct_iterate_three_fan_in_fresh_execution_owns_sorted_stream_expansion() -> None:- graph = _direct_iterate_three_fan_in_graph(a=["dup", None, "dup"], m=["middle"], z=[None, "dup"], unsorted=True)- assert tuple(graph.nodes) == (- "collect",- "z_source",- "z_iterate",- "a_source",- "a_iterate",- "m_source",- "m_iterate",+def test_body_iterate_fan_in_unsupported_topology_uses_compatibility_fallback() -> None:+ graph = _body_iterate_fan_in_graph(+ branches=(+ ("m_source", "m_iterate", "m_body", ["m"]),+ ("z_source", "z_iterate", "z_body", ["z"]),+ ("a_source", "a_iterate", "a_body", ["a"]),+ ))- state = GraphExecutionState(graph=graph)- fan_in = state._get_direct_iterate_collect_nodes()- assert isinstance(fan_in, graph_module._DirectIterateCollectFanIn)- assert fan_in.branches == (- ("a_source", "a_iterate"),- ("m_source", "m_iterate"),- ("z_source", "z_iterate"),+ assert GraphExecutionState(graph=graph)._get_direct_iterate_collect_nodes() is None++ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph))+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=True+ )++ assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter) and isinstance(+ compatibility_state._execution_scheduler, _ExecutionScheduler+ )+ assert generic_trace == compatibility_trace+ generic_collection = _source_output(generic_state, "collect").collection+ compatibility_collection = _source_output(compatibility_state, "collect").collection+ # Unsupported body-mediated fan-in stays on the legacy materializer. Its item ordering+ # is not part of this bounded planner's contract, but values (including duplicates) must+ # be retained; only the admitted two-branch planner promises lexical source ordering.+ assert sorted(generic_collection) == sorted(compatibility_collection) == ["a", "m", "z"]+ assert _execution_edge_projection(generic_state) == _execution_edge_projection(compatibility_state)+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(+ compatibility_state+ )+ assert _direct_iterate_fan_in_execution_ref_projection(+ generic_state+ ) == _direct_iterate_fan_in_execution_ref_projection(compatibility_state)+ assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+++def test_body_iterate_fan_in_downstream_topology_stays_on_compatibility_fallback() -> None:+ graph = _body_iterate_fan_in_graph(+ branches=(+ ("right_source", "right_iterate", "right_body", ["right"]),+ ("left_source", "left_iterate", "left_body", ["left"]),+ )+ )+ graph.add_node(AnyTypeTestInvocation(id="after"))+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="collect", field="collection"),+ destination=EdgeConnection(node_id="after", field="value"),+ )+ )++ assert GraphExecutionState(graph=graph)._get_direct_iterate_collect_nodes() is None++ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph))+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=True+ )++ assert generic_trace == compatibility_trace+ assert generic_trace[-2:] == ["collect", "after"]+ generic_collection = _source_output(generic_state, "collect").collection+ compatibility_collection = _source_output(compatibility_state, "collect").collection+ assert sorted(generic_collection) == sorted(compatibility_collection) == ["left", "right"]+ assert _source_output(generic_state, "after").value == generic_collection+ assert _source_output(compatibility_state, "after").value == compatibility_collection+ assert _execution_edge_projection(generic_state) == _execution_edge_projection(compatibility_state)+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(+ compatibility_state)+ assert _direct_iterate_fan_in_execution_ref_projection(+ generic_state+ ) == _direct_iterate_fan_in_execution_ref_projection(compatibility_state)+ assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()++def test_direct_iterate_body_collect_fresh_execution_handles_empty_input() -> None:+ state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=[]))with (patch.object(graph_module._ExecutionMaterializer,"prepare",- side_effect=AssertionError("fresh three-branch fan-in must not use materializer.prepare"),+ side_effect=AssertionError("canonical empty Iterate -> body -> Collect must not use materializer.prepare"),) as prepare,patch.object(graph_module._ExecutionMaterializer,"_get_collect_iteration_mapping_groups",- side_effect=AssertionError("fresh three-branch fan-in must not group collector inputs"),+ side_effect=AssertionError("canonical empty Iterate -> body -> Collect must not group collector inputs"),) as group_collector_inputs,):trace, state = _run_graph(state)- assert trace == [- "a_source",- "m_source",- "z_source",- "a_iterate",- "m_iterate",- "z_iterate",- "a_iterate",- "z_iterate",- "a_iterate",- "collect",- ]- assert _source_output(state, "collect").collection == ["dup", None, "dup", "middle", None, "dup"]- streams = {- stream.owner_id: stream- for stream in state._generic_runtime().streams.values()- if stream.owner_id in {"a_iterate", "m_iterate", "z_iterate"}- }- assert {owner_id: (stream.values, stream.closed) for owner_id, stream in streams.items()} == {- "a_iterate": (("dup", None, "dup"), True),- "m_iterate": (("middle",), True),- "z_iterate": ((None, "dup"), True),- }+ assert "iterate" not in trace+ assert "body" not in trace+ assert trace[-1] == "collect"+ assert _source_output(state, "collect").collection == []+ assert state.is_complete()+ prepare.assert_not_called()+ group_collector_inputs.assert_not_called()+++def test_direct_iterate_body_collect_planner_rolls_back_partial_expansion(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["first", "last"]))+ source_node = state.next()+ assert source_node is not None+ state.complete(source_node.id, source_node.invoke(Mock()))++ original_create = GraphExecutionState._create_direct_execution_node_copy+ failed = False++ def fail_after_body(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):+ nonlocal failed+ node = original_create(self, source_node_id, *args, **kwargs)+ if source_node_id == "body" and not failed:+ failed = True+ raise RuntimeError("injected direct planner failure")+ return node++ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_after_body)+ with pytest.raises(RuntimeError, match="injected direct planner failure"):+ state.next()++ assert set(state.source_prepared_mapping) == {"source"}+ assert len(state.execution_graph.nodes) == 1+ assert not state.execution_graph.edges++ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)+ trace, state = _run(state)++ assert trace == ["iterate", "iterate", "body", "body", "collect"]+ assert _source_output(state, "collect").collection == ["first", "last"]assert state.is_complete()- prepare.assert_not_called()- group_collector_inputs.assert_not_called()- ("a", "m", "z"),- [- ([], [], []),- (["a"], [], []),- ([], ["m"], []),- ([], [], ["z"]),- (["a"], ["m"], []),- (["a"], [], ["z"]),- ([], ["m"], ["z"]),- ],- ids=["all-empty", "a-only", "m-only", "z-only", "a-m", "a-z", "m-z"],-)-def test_direct_iterate_three_fan_in_closes_every_empty_stream(a: list[Any], m: list[Any], z: list[Any]) -> None:- trace, state = _run_graph(GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=a, m=m, z=z)))+def test_direct_iterate_body_collect_downstream_planner_rolls_back_partial_expansion(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["first", "last"], with_after=True))+ source_node = state.next()+ assert source_node is not None+ state.complete(source_node.id, source_node.invoke(Mock()))- assert trace.count("collect") == 1- assert _source_output(state, "collect").collection == a + m + z- streams = {- stream.owner_id: stream- for stream in state._generic_runtime().streams.values()- if stream.owner_id in {"a_iterate", "m_iterate", "z_iterate"}- }- assert set(streams) == {"a_iterate", "m_iterate", "z_iterate"}- assert all(stream.closed for stream in streams.values())- assert state.is_complete()+ original_create = GraphExecutionState._create_direct_execution_node_copy+ def fail_at_downstream(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):+ if source_node_id == "after":+ raise RuntimeError("injected downstream planner failure")+ return original_create(self, source_node_id, *args, **kwargs)-def test_direct_iterate_three_fan_in_partial_dump_load_resumes_without_duplicate_work() -> None:- graph = _direct_iterate_three_fan_in_graph(a=["a-0", "a-1"], m=["m-0", "m-1"], z=["z-0", "z-1"])- expected_trace, expected_state = _run_graph_with_effects(GraphExecutionState(graph=graph))- partial_trace, partial_state = _run_graph_with_effects(GraphExecutionState(graph=graph), stop_after=5)+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_downstream)+ with pytest.raises(RuntimeError, match="injected downstream planner failure"):+ state.next()- assert partial_trace == ["a_source", "m_source", "z_source", "a_iterate", "m_iterate"]- assert "collect" not in partial_trace- collect_exec_ids = partial_state.source_prepared_mapping["collect"]- assert len(collect_exec_ids) == 1- collect_exec_id = next(iter(collect_exec_ids))- assert collect_exec_id not in partial_state.executed+ assert set(state.source_prepared_mapping) == {"source"}+ assert len(state.execution_graph.nodes) == 1+ assert not state.execution_graph.edges- restored = load_execution_state(dump_execution_state(partial_state))- assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)- assert _direct_iterate_fan_in_execution_ref_projection(- restored, execution_ids=set(partial_state.execution_refs)- ) == _direct_iterate_fan_in_execution_ref_projection(partial_state)- assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)- resumed_trace, resumed_state = _run_graph_with_effects(restored)+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)+ trace, state = _run_graph(state)- assert partial_trace + resumed_trace == expected_trace- assert _source_output(resumed_state, "collect").collection == ["a-0", "a-1", "m-0", "m-1", "z-0", "z-1"]- assert _state_projection(resumed_state) == _state_projection(expected_state)- assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(- expected_state- )- assert _direct_iterate_fan_in_execution_ref_projection(- resumed_state- ) == _direct_iterate_fan_in_execution_ref_projection(expected_state)- assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)- assert collect_exec_id in resumed_state.executed- assert resumed_state.is_complete()+ assert trace == ["iterate", "iterate", "body", "body", "collect", "after"]+ assert _source_output(state, "after").value == ["first", "last"]+ assert state.is_complete()@pytest.mark.parametrize(- ("a", "m", "z"),+ "collection",[- (["a", None, "a"], ["m"], ["z", None]),- ([], ["m", "m"], []),- ([], [], []),+ ["first", None, "last"],+ [],],- ids=["ordered-none-duplicates", "mixed-empty-duplicates", "all-empty"],+ ids=["ordered-values-including-none", "empty"],)-def test_direct_iterate_three_fan_in_matches_forced_compatibility_scheduler(- a: list[Any], m: list[Any], z: list[Any]-) -> None:+def test_direct_iterate_body_collect_matches_forced_compatibility_scheduler(collection: list[Any]) -> None:generic_trace, generic_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=a, m=m, z=z))+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)))compatibility_trace, compatibility_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=a, m=m, z=z)),+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)),force_compatibility_scheduler=True,)assert generic_trace == compatibility_trace- assert (- _source_output(generic_state, "collect").collection == _source_output(compatibility_state, "collect").collection- )- assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert _source_output(generic_state, "collect").collection == collection+ assert _source_output(compatibility_state, "collect").collection == collectionassert generic_state.is_complete()assert compatibility_state.is_complete()+ assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)+ assert _state_projection(generic_state) == _state_projection(compatibility_state)- ("fail_source_id", "expected_trace"),- [- ("m_source", ["a_source", "m_source"]),- (- "m_iterate",- ["a_source", "m_source", "z_source", "a_iterate", "m_iterate"],- ),- ],- ids=["source-failure", "iterator-failure"],-)-def test_direct_iterate_three_fan_in_failure_matches_compatibility_and_blocks_collect(- fail_source_id: str, expected_trace: list[str][email protected]("force_compatibility_scheduler", [False, True])+def test_direct_iterate_body_collect_partial_dump_load_resume_matches_fresh_execution(+ force_compatibility_scheduler: bool,) -> None:- generic_trace, generic_state = _run_graph_with_effects(- GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=["a"], m=["m"], z=["z"])),- fail_source_id=fail_source_id,+ collection = ["first", None, "last"]+ expected_trace, expected_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)),+ force_compatibility_scheduler=force_compatibility_scheduler,)- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=["a"], m=["m"], z=["z"])),- force_compatibility_scheduler=True,- fail_source_id=fail_source_id,+ partial_trace, partial_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after=2,)- assert generic_trace == compatibility_trace == expected_trace- for state in (generic_state, compatibility_state):- assert state.next() is None- assert state.has_error()- assert "collect" not in {- state.prepared_source_mapping.get(execution_id, execution_id) for execution_id in state.executed- }- assert state.is_complete()- restored = load_execution_state(dump_execution_state(state))- assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(state)- assert _effect_ledger_projection(restored) == _effect_ledger_projection(state)- assert restored.next() is None- assert restored.is_complete()+ restored = load_execution_state(dump_execution_state(partial_state))+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(restored)+ resumed_trace, resumed_state = _run_graph(+ restored,+ force_compatibility_scheduler=force_compatibility_scheduler,+ )- assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)- assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(- compatibility_state+ assert partial_trace + resumed_trace == expected_trace+ assert _source_output(resumed_state, "collect").collection == collection+ assert resumed_state.is_complete()+ assert _state_projection(resumed_state) == _state_projection(expected_state)+ if force_compatibility_scheduler:+ assert isinstance(resumed_state._execution_scheduler, _ExecutionScheduler)+ else:+ assert isinstance(resumed_state._execution_scheduler, _GenericGraphSchedulerAdapter)+++def test_direct_iterate_body_collect_empty_checkpoint_rehydrates_without_materializer() -> None:+ _partial_trace, partial_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=[])), stop_after=1+ )+ with (+ patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("empty canonical checkpoint must not use materializer.prepare"),+ ) as prepare,+ patch.object(+ graph_module._ExecutionMaterializer,+ "_get_collect_iteration_mapping_groups",+ side_effect=AssertionError("empty canonical checkpoint must not group collector inputs"),+ ) as group_collector_inputs,+ ):+ resumed_trace, resumed_state = _run_graph(load_execution_state(dump_execution_state(partial_state)))++ assert resumed_trace == ["collect"]+ assert _source_output(resumed_state, "collect").collection == []+ assert resumed_state.is_complete()+ prepare.assert_not_called()+ group_collector_inputs.assert_not_called()+++def test_direct_iterate_body_collect_failure_rehydrates_pending_state_without_replanning() -> None:+ trace, failed_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["first", "last"])),+ fail_source_id="body",)+ assert trace[0] == "source"+ assert trace.count("iterate") == 2+ assert trace[-1] == "body"+ assert failed_state.has_error()+ restored = load_execution_state(dump_execution_state(failed_state))+ assert restored.has_error()+ assert restored.source_prepared_mapping.get("collect")+ assert restored.is_complete()-def test_direct_iterate_three_fan_in_rolls_back_partial_expansion(monkeypatch: pytest.MonkeyPatch) -> None:- state = GraphExecutionState(graph=_direct_iterate_three_fan_in_graph(a=["a"], m=["m"], z=["z"]))- _partial_trace, state = _run_graph(state, stop_after=3)- original_create = GraphExecutionState._create_direct_execution_node_copy+def test_direct_iterate_body_collect_with_downstream_consumer_uses_private_planner() -> None:+ with (+ patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("direct Iterate -> body -> Collect -> after must not use materializer.prepare"),+ ) as prepare,+ patch.object(+ graph_module._ExecutionMaterializer,+ "_get_collect_iteration_mapping_groups",+ side_effect=AssertionError("direct downstream Collect must not group collector inputs"),+ ) as group_collector_inputs,+ ):+ trace, state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["value"], with_after=True))+ )- def fail_at_m_iterate(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):- if source_node_id == "m_iterate":- raise RuntimeError("injected three-branch fan-in planner failure")- return original_create(self, source_node_id, *args, **kwargs)+ assert trace[-1] == "after"+ assert _source_output(state, "after").value == ["value"]+ assert state.is_complete()+ prepare.assert_not_called()+ group_collector_inputs.assert_not_called()+++def test_direct_iterate_body_collect_two_downstream_consumers_admits_exact_shape() -> None:+ state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["value"], downstream_count=2))++ assert len(state.graph.nodes) == 6+ assert len(state.graph.edges) == 5+ assert state._get_direct_iterate_collect_nodes() == (+ "source",+ "iterate",+ "body",+ "collect",+ ("after_1", "after_2"),+ )+ assert state._can_use_direct_iterate_collect_planner()- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_m_iterate)- with pytest.raises(RuntimeError, match="injected three-branch fan-in planner failure"):- state.next()- assert set(state.source_prepared_mapping) == {"a_source", "m_source", "z_source"}- assert len(state.execution_graph.nodes) == 3- assert not state.execution_graph.edges- assert not state._generic_runtime().streams+def test_direct_iterate_body_collect_three_downstream_consumers_uses_private_planner() -> None:+ state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["value"], downstream_count=3))+ assert state._get_direct_iterate_collect_nodes() == (+ "source",+ "iterate",+ "body",+ "collect",+ ("after_1", "after_2", "after_3"),+ )+ assert state._can_use_direct_iterate_collect_planner()- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)- trace, state = _run_graph(state)+ with (+ patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("three direct downstream consumers must not use materializer.prepare"),+ ) as prepare,+ patch.object(+ graph_module._ExecutionMaterializer,+ "_get_collect_iteration_mapping_groups",+ side_effect=AssertionError("three direct downstream consumers must not group collector inputs"),+ ) as group_collector_inputs,+ ):+ trace, state = _run_graph(state)- assert trace == ["a_iterate", "m_iterate", "z_iterate", "collect"]- assert _source_output(state, "collect").collection == ["a", "m", "z"]+ assert trace == ["source", "iterate", "body", "collect", "after_1", "after_2", "after_3"]+ for downstream_id in ("after_1", "after_2", "after_3"):+ assert _source_output(state, downstream_id).value == ["value"]assert state.is_complete()+ prepare.assert_not_called()+ group_collector_inputs.assert_not_called()-def test_direct_iterate_four_fan_in_stays_on_compatibility_fallback() -> None:- graph = _direct_iterate_fan_in_graph_with_branches(- branches=(- ("a_source", "a_iterate", ["a"]),- ("m_source", "m_iterate", ["m"]),- ("z_source", "z_iterate", ["z"]),- ("q_source", "q_iterate", ["q"]),- )[email protected]("collection", [["first", None, "last"], []], ids=["ordered-none", "empty"])+def test_direct_iterate_body_collect_three_downstream_consumers_matches_compatibility(+ collection: list[Any],+) -> None:+ generic_trace, generic_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=3)))- state = GraphExecutionState(graph=graph)- assert state._get_direct_iterate_collect_nodes() is None-compatibility_trace, compatibility_state = _run_graph(- GraphExecutionState(graph=graph), force_compatibility_scheduler=True+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=3)),+ force_compatibility_scheduler=True,)- assert compatibility_trace- assert sorted(_source_output(compatibility_state, "collect").collection) == ["a", "m", "q", "z"]- assert compatibility_state.is_complete()-+ expected_trace = ["source"] + ["iterate"] * len(collection) + ["body"] * len(collection)+ expected_trace += ["collect", "after_1", "after_2", "after_3"]+ assert generic_trace == expected_trace+ assert generic_trace[:-3] == compatibility_trace[:-3]+ assert sorted(generic_trace[-3:]) == sorted(compatibility_trace[-3:]) == ["after_1", "after_2", "after_3"]+ for state in (generic_state, compatibility_state):+ assert _source_output(state, "collect").collection == collection+ for downstream_id in ("after_1", "after_2", "after_3"):+ assert _source_output(state, downstream_id).value == collection+ assert state.is_complete()-def test_body_iterate_fan_in_fresh_execution_owns_exact_two_branch_shape() -> None:- graph = _body_iterate_fan_in_graph(- branches=(- ("z_source", "z_iterate", "z_body", ["z", None, "z"]),- ("a_source", "a_iterate", "a_body", ["a", None, "a"]),- )- )- assert len(graph.nodes) == 7- assert len(graph.edges) == 6- state = GraphExecutionState(graph=graph)- fan_in = state._get_direct_iterate_collect_nodes()- assert isinstance(fan_in, graph_module._BodyIterateCollectFanIn)- assert fan_in.branches == (- ("a_source", "a_iterate", "a_body"),- ("z_source", "z_iterate", "z_body"),- )+def test_direct_iterate_body_collect_two_downstream_consumers_uses_private_planner() -> None:with (patch.object(graph_module._ExecutionMaterializer,"prepare",- side_effect=AssertionError("body fan-in must not use materializer.prepare"),+ side_effect=AssertionError("two direct downstream consumers must not use materializer.prepare"),) as prepare,patch.object(graph_module._ExecutionMaterializer,"_get_collect_iteration_mapping_groups",- side_effect=AssertionError("body fan-in must not group collector inputs"),+ side_effect=AssertionError("two direct downstream consumers must not group collector inputs"),) as group_collector_inputs,):- trace, state = _run_graph(state)+ trace, state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["value"], downstream_count=2))+ )- assert trace.count("a_source") == trace.count("z_source") == 1- assert trace.count("a_iterate") == 3- assert trace.count("z_iterate") == 3- assert trace.count("a_body") == 3- assert trace.count("z_body") == 3- assert trace.count("collect") == 1- assert _source_output(state, "collect").collection == ["a", None, "a", "z", None, "z"]+ assert trace == ["source", "iterate", "body", "collect", "after_1", "after_2"]+ assert _source_output(state, "after_1").value == ["value"]+ assert _source_output(state, "after_2").value == ["value"]assert state.is_complete()- assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)prepare.assert_not_called()group_collector_inputs.assert_not_called()-def test_body_iterate_fan_in_orders_by_source_id_not_body_id() -> None:- graph = _body_iterate_fan_in_graph(- branches=(- ("z_source", "z_iterate", "a_body", ["z-0", "z-1"]),- ("a_source", "a_iterate", "z_body", ["a-0", "a-1"]),- )[email protected]("collection", [["first", None, "last"], []], ids=["ordered-none", "empty"])+def test_direct_iterate_body_collect_two_downstream_consumers_matches_compatibility(+ collection: list[Any],+) -> None:+ generic_trace, generic_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=2)))- state = GraphExecutionState(graph=graph)- fan_in = state._get_direct_iterate_collect_nodes()- assert isinstance(fan_in, graph_module._BodyIterateCollectFanIn)- assert fan_in.branches == (- ("a_source", "a_iterate", "z_body"),- ("z_source", "z_iterate", "a_body"),+ compatibility_trace, compatibility_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=2)),+ force_compatibility_scheduler=True,)- trace, state = _run_graph_with_effects(state)-- assert trace[-1] == "collect"- assert _source_output(state, "collect").collection == ["a-0", "a-1", "z-0", "z-1"]- assert state.is_complete()+ expected_trace = ["source"] + ["iterate"] * len(collection) + ["body"] * len(collection)+ expected_trace += ["collect", "after_1", "after_2"]+ assert generic_trace == expected_trace+ assert generic_trace[:-2] == compatibility_trace[:-2]+ assert sorted(generic_trace[-2:]) == sorted(compatibility_trace[-2:]) == ["after_1", "after_2"]+ for state in (generic_state, compatibility_state):+ assert _source_output(state, "collect").collection == collection+ assert _source_output(state, "after_1").value == collection+ assert _source_output(state, "after_2").value == collection+ assert state.is_complete()- ("left", "right", "expected"),- [- ([], ["right", None], ["right", None]),- (["left", None], [], ["left", None]),- ([], [], []),- ],- ids=["left-empty", "right-empty", "both-empty"],-)-def test_body_iterate_fan_in_closes_empty_branches(left: list[Any], right: list[Any], expected: list[Any]) -> None:- graph = _body_iterate_fan_in_graph(- branches=(- ("right_source", "right_iterate", "right_body", right),- ("left_source", "left_iterate", "left_body", left),- )+def test_direct_iterate_body_collect_two_downstream_consumers_rolls_back_partial_expansion(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = GraphExecutionState(+ graph=_direct_iterate_body_collect_graph(collection=["first", "last"], downstream_count=2))- trace, state = _run_graph(GraphExecutionState(graph=graph))+ source_node = state.next()+ assert source_node is not None+ state.complete(source_node.id, source_node.invoke(Mock()))- assert trace.count("collect") == 1- assert _source_output(state, "collect").collection == expected- streams = {- stream.owner_id: stream- for stream in state._generic_runtime().streams.values()- if stream.owner_id in {"left_iterate", "right_iterate"}- }- assert set(streams) == {"left_iterate", "right_iterate"}- assert all(stream.closed for stream in streams.values())+ original_create = GraphExecutionState._create_direct_execution_node_copy++ def fail_at_second_downstream(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):+ if source_node_id == "after_2":+ raise RuntimeError("injected second downstream planner failure")+ return original_create(self, source_node_id, *args, **kwargs)++ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_second_downstream)+ with pytest.raises(RuntimeError, match="injected second downstream planner failure"):+ state.next()++ assert set(state.source_prepared_mapping) == {"source"}+ assert len(state.execution_graph.nodes) == 1+ assert not state.execution_graph.edges++ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)+ trace, state = _run_graph(state)++ assert trace == ["iterate", "iterate", "body", "body", "collect", "after_1", "after_2"]+ assert _source_output(state, "after_1").value == ["first", "last"]+ assert _source_output(state, "after_2").value == ["first", "last"]assert state.is_complete()[email protected]("force_compatibility_scheduler", [False, True])-def test_body_iterate_fan_in_partial_dump_load_preserves_streams_and_effects(- force_compatibility_scheduler: bool,+def test_direct_iterate_body_collect_three_downstream_consumers_rolls_back_partial_expansion(+ monkeypatch: pytest.MonkeyPatch,) -> None:- graph = _body_iterate_fan_in_graph(- branches=(- ("right_source", "right_iterate", "right_body", ["right-0", "right-1"]),- ("left_source", "left_iterate", "left_body", ["left-0", "left-1"]),- )- )- expected_trace, expected_state = _run_graph_with_effects(- GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler- )- partial_trace, partial_state = _run_graph_with_effects(- GraphExecutionState(graph=graph),- force_compatibility_scheduler=force_compatibility_scheduler,- stop_after=3,+ state = GraphExecutionState(+ graph=_direct_iterate_body_collect_graph(collection=["first", "last"], downstream_count=3))+ source_node = state.next()+ assert source_node is not None+ state.complete(source_node.id, source_node.invoke(Mock()))- assert "collect" not in partial_trace- if not force_compatibility_scheduler:- assert (- not partial_state._generic_runtime().streams[partial_state._iteration_stream_id("left_iterate", ())].closed- )- restored = load_execution_state(dump_execution_state(partial_state))- assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)- assert _direct_iterate_fan_in_execution_ref_projection(- restored, execution_ids=set(partial_state.execution_refs)- ) == _direct_iterate_fan_in_execution_ref_projection(partial_state)- assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)- if force_compatibility_scheduler:- _restore_compatibility_scheduler(restored)- resumed_trace, resumed_state = _run_graph_with_effects(- restored, force_compatibility_scheduler=force_compatibility_scheduler- )+ original_create = GraphExecutionState._create_direct_execution_node_copy- assert partial_trace + resumed_trace == expected_trace- assert _source_output(resumed_state, "collect").collection == [- "left-0",- "left-1",- "right-0",- "right-1",- ]- assert _state_projection(resumed_state) == _state_projection(expected_state)- assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(- expected_state- )- assert _direct_iterate_fan_in_execution_ref_projection(- resumed_state- ) == _direct_iterate_fan_in_execution_ref_projection(expected_state)- assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)- assert resumed_state.is_complete()+ def fail_at_third_downstream(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):+ if source_node_id == "after_3":+ raise RuntimeError("injected third downstream planner failure")+ return original_create(self, source_node_id, *args, **kwargs)+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_third_downstream)+ with pytest.raises(RuntimeError, match="injected third downstream planner failure"):+ state.next()[email protected]("force_compatibility_scheduler", [False, True])-def test_body_iterate_fan_in_source_prepared_dump_load_resumes(- force_compatibility_scheduler: bool,-) -> None:- graph = _body_iterate_fan_in_graph(- branches=(- ("right_source", "right_iterate", "right_body", ["right-0", "right-1"]),- ("left_source", "left_iterate", "left_body", ["left-0", "left-1"]),- )- )- expected_trace, expected_state = _run_graph_with_effects(- GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler- )- partial_trace, partial_state = _run_graph_with_effects(- GraphExecutionState(graph=graph),- force_compatibility_scheduler=force_compatibility_scheduler,- stop_after=2,- )+ assert set(state.source_prepared_mapping) == {"source"}+ assert len(state.execution_graph.nodes) == 1+ assert not state.execution_graph.edges- assert partial_trace == expected_trace[:2]- assert set(partial_trace) == {"left_source", "right_source"}- assert set(partial_state.source_prepared_mapping) == {"left_source", "right_source"}- assert "collect" not in partial_state.source_prepared_mapping- assert not partial_state._generic_runtime().streams- checkpoint = dump_execution_state(partial_state)- restored = load_execution_state(checkpoint)- assert _state_projection(restored) == _state_projection(partial_state)- assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)- assert _direct_iterate_fan_in_execution_ref_projection(- restored, execution_ids=set(partial_state.execution_refs)- ) == _direct_iterate_fan_in_execution_ref_projection(partial_state)- assert _execution_token_projection(restored) == _execution_token_projection(partial_state)- assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)- if force_compatibility_scheduler:- _restore_compatibility_scheduler(restored)+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)+ trace, state = _run_graph(state)- resumed_trace, resumed_state = _run_graph_with_effects(- restored, force_compatibility_scheduler=force_compatibility_scheduler+ assert trace == ["iterate", "iterate", "body", "body", "collect", "after_1", "after_2", "after_3"]+ for downstream_id in ("after_1", "after_2", "after_3"):+ assert _source_output(state, downstream_id).value == ["first", "last"]+ assert state.is_complete()+++def test_direct_iterate_body_collect_two_downstream_consumers_checkpoint_rehydrates() -> None:+ collection = ["first", None, "last"]+ expected_trace, expected_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=2))+ )+ partial_trace, partial_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=2)),+ stop_after=3,)+ resumed_trace, resumed_state = _run_graph(load_execution_state(dump_execution_state(partial_state)))+assert partial_trace + resumed_trace == expected_trace- assert _state_projection(resumed_state) == _state_projection(expected_state)- assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(- expected_state- )- assert _direct_iterate_fan_in_execution_ref_projection(- resumed_state- ) == _direct_iterate_fan_in_execution_ref_projection(expected_state)- assert _execution_token_projection(resumed_state) == _execution_token_projection(expected_state)- assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)+ assert _source_output(resumed_state, "collect").collection == collection+ assert _source_output(resumed_state, "after_1").value == collection+ assert _source_output(resumed_state, "after_2").value == collectionassert resumed_state.is_complete()+ assert _state_projection(resumed_state) == _state_projection(expected_state)-def test_body_iterate_fan_in_partial_dump_load_after_one_stream_closes() -> None:- graph = _body_iterate_fan_in_graph(- branches=(- ("right_source", "right_iterate", "right_body", ["right-0", "right-1"]),- ("left_source", "left_iterate", "left_body", ["left-0"]),- )+def test_direct_iterate_body_collect_three_downstream_consumers_checkpoint_rehydrates() -> None:+ collection = ["first", None, "last"]+ expected_trace, expected_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=3))+ )+ partial_trace, partial_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=3)),+ stop_after=3,)- expected_trace, expected_state = _run_graph_with_effects(GraphExecutionState(graph=graph))- partial_trace, partial_state = _run_graph_with_effects(GraphExecutionState(graph=graph), stop_after=3)-- assert partial_trace == ["left_source", "right_source", "left_iterate"]- streams = partial_state._generic_runtime().streams- assert streams[partial_state._iteration_stream_id("left_iterate", ())].closed- right_stream = streams.get(partial_state._iteration_stream_id("right_iterate", ()))- assert right_stream is None or not right_stream.closed- assert "collect" not in partial_trace- restored = load_execution_state(dump_execution_state(partial_state))- assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)- assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)- resumed_trace, resumed_state = _run_graph_with_effects(restored)+ resumed_trace, resumed_state = _run_graph(load_execution_state(dump_execution_state(partial_state)))assert partial_trace + resumed_trace == expected_trace- assert _source_output(resumed_state, "collect").collection == ["left-0", "right-0", "right-1"]- assert _state_projection(resumed_state) == _state_projection(expected_state)- assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(- expected_state- )- assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)+ assert _source_output(resumed_state, "collect").collection == collection+ for downstream_id in ("after_1", "after_2", "after_3"):+ assert _source_output(resumed_state, downstream_id).value == collectionassert resumed_state.is_complete()+ assert _state_projection(resumed_state) == _state_projection(expected_state)- ("left", "right", "expected"),- [- (["left", None, "left"], ["right", None], ["left", None, "left", "right", None]),- ([], ["right", None], ["right", None]),- ([], [], []),- ],- ids=["ordered-none-duplicates", "mixed-empty", "all-empty"],-)-def test_body_iterate_fan_in_matches_forced_compatibility_scheduler(- left: list[Any], right: list[Any], expected: list[Any]-) -> None:- graph = _body_iterate_fan_in_graph(- branches=(- ("left_source", "left_iterate", "left_body", left),- ("right_source", "right_iterate", "right_body", right),+def test_direct_iterate_body_collect_with_downstream_consumer_matches_forced_compatibility_scheduler() -> None:+ generic_trace, generic_state = _run_graph(+ GraphExecutionState(+ graph=_direct_iterate_body_collect_graph(collection=["first", None, "last"], with_after=True)))- generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph))- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=graph), force_compatibility_scheduler=True+ compatibility_trace, compatibility_state = _run_graph(+ GraphExecutionState(+ graph=_direct_iterate_body_collect_graph(collection=["first", None, "last"], with_after=True)+ ),+ force_compatibility_scheduler=True,)assert generic_trace == compatibility_trace- assert _source_output(generic_state, "collect").collection == expected- assert (- _source_output(generic_state, "collect").collection == _source_output(compatibility_state, "collect").collection- )- if left or right:- assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(- compatibility_state- )- assert _direct_iterate_fan_in_execution_ref_projection(- generic_state- ) == _direct_iterate_fan_in_execution_ref_projection(compatibility_state)- assert _execution_token_projection(generic_state) == _execution_token_projection(compatibility_state)- assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)- assert _execution_edge_projection(generic_state) == _execution_edge_projection(compatibility_state)+ assert generic_trace[-2:] == ["collect", "after"]+ assert _source_output(generic_state, "after").value == ["first", None, "last"]+ assert _source_output(compatibility_state, "after").value == ["first", None, "last"]assert generic_state.is_complete()assert compatibility_state.is_complete()+ assert _state_projection(generic_state) == _state_projection(compatibility_state)[email protected]("force_compatibility_scheduler", [False, True])[email protected]("fail_source_id", ["right_source", "right_iterate", "right_body"])-def test_body_iterate_fan_in_failure_blocks_collect_and_persists(- force_compatibility_scheduler: bool, fail_source_id: str-) -> None:- graph = _body_iterate_fan_in_graph(- branches=(- ("left_source", "left_iterate", "left_body", ["left"]),- ("right_source", "right_iterate", "right_body", ["right"]),- )+def test_direct_iterate_body_collect_downstream_checkpoint_after_none_item_rehydrates() -> None:+ collection = ["first", None, "last"]+ expected_trace, expected_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, with_after=True)))- trace, state = _run_graph_with_effects(- GraphExecutionState(graph=graph),- force_compatibility_scheduler=force_compatibility_scheduler,- fail_source_id=fail_source_id,+ partial_trace, partial_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, with_after=True)),+ stop_after=3,)- assert trace[-1] == fail_source_id- assert "collect" not in trace- assert state.has_error()- assert state.is_complete()- assert state.next() is None- assert tuple(- sorted(- (state.prepared_source_mapping.get(execution_id, execution_id), message)- for execution_id, message in state.errors.items()- )- ) == ((fail_source_id, "injected failure"),)- restored = load_execution_state(dump_execution_state(state))- assert _state_projection(restored) == _state_projection(state)- assert _execution_edge_projection(restored) == _execution_edge_projection(state)- assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(state)- assert _direct_iterate_fan_in_execution_ref_projection(- restored, execution_ids=set(state.execution_refs)- ) == _direct_iterate_fan_in_execution_ref_projection(state)- assert _execution_token_projection(restored) == _execution_token_projection(state)- assert _effect_ledger_projection(restored) == _effect_ledger_projection(state)- assert restored.has_error()- assert tuple(- sorted(- (restored.prepared_source_mapping.get(execution_id, execution_id), message)- for execution_id, message in restored.errors.items()- )- ) == ((fail_source_id, "injected failure"),)- assert restored.next() is None+ assert partial_trace == ["source", "iterate", "iterate"]+ iterate_exec_id = next(+ exec_node_id+ for exec_node_id, source_node_id in partial_state.prepared_source_mapping.items()+ if source_node_id == "iterate"+ and exec_node_id in partial_state.results+ and partial_state.results[exec_node_id].index == 1 # type: ignore[union-attr]+ )+ snapshot = dump_execution_state(partial_state)+ assert snapshot["results"][iterate_exec_id]["item"] is None++ resumed_trace, resumed_state = _run_graph(load_execution_state(snapshot))++ assert partial_trace + resumed_trace == expected_trace+ assert _source_output(resumed_state, "collect").collection == collection+ assert _source_output(resumed_state, "after").value == collection+ assert resumed_state.is_complete()+ assert _state_projection(resumed_state) == _state_projection(expected_state)+++def test_direct_flat_for_completion_persists_continuations_and_result_outputs() -> None:+ trace, state = _run(GraphExecutionState(graph=_flat_for_graph()))++ assert trace == ["for", "body", "return", "for", "body", "return"]+ snapshot = dump_execution_state(state)+ restored = load_execution_state(snapshot)+ final_for_id = max(+ state.source_prepared_mapping["for"],+ key=lambda exec_node_id: state.execution_graph.get_node(exec_node_id).index,+ )+ final_output = state.results[final_for_id]++ assert snapshot["execution_effects"]+ assert final_output.output_collection == [11, 12]+ assert snapshot["execution_refs"] == {}+ assert restored.execution_tokens == {}+ assert restored.execution_refs+ assert restored.results[final_for_id].output_collection == [11, 12]+ assert restored.results[final_for_id].final_state == final_output.final_state+ assert sorted(+ (effect.operation, effect.continuation_kind)+ for effects in state.execution_effects.values()+ for effect in effects+ if effect.kind == "continuation"+ ) == [("complete", "for"), ("complete", "for"), ("start", "for"), ("start", "for")]+ assert restored.is_complete()+++def test_legacy_flat_for_snapshot_uses_compatibility_scheduler() -> None:+ _trace, partial_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph()),+ stop_after=1,+ )+ snapshot = dump_execution_state(partial_state)+ snapshot.pop("execution_state_version")+ snapshot.pop("execution_effects")++ restored = load_execution_state(snapshot)+ migrated = load_execution_state(dump_execution_state(restored))++ assert isinstance(restored._scheduler(), _ExecutionScheduler)+ remaining_trace, restored = _run(restored)+ migrated_trace, migrated = _run(migrated)+ assert remaining_trace == ["body", "return", "for", "body", "return"]+ assert migrated_trace == remaining_traceassert restored.is_complete()+ assert migrated.is_complete()+ assert _final_for_output(restored).output_collection == [11, 12]+ assert _final_for_output(migrated).output_collection == [11, 12][email protected]("fail_source_id", ["right_source", "right_iterate", "right_body"])-def test_body_iterate_fan_in_failure_matches_forced_compatibility_scheduler(fail_source_id: str) -> None:- graph = _body_iterate_fan_in_graph(- branches=(- ("left_source", "left_iterate", "left_body", ["left"]),- ("right_source", "right_iterate", "right_body", ["right"]),- )- )+def test_terminal_legacy_flat_for_snapshot_can_be_resaved_and_reloaded() -> None:+ _trace, state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph()))+ snapshot = dump_execution_state(state)+ snapshot.pop("execution_state_version")+ snapshot.pop("execution_effects")++ restored = load_execution_state(snapshot)+ migrated = load_execution_state(dump_execution_state(restored))++ assert restored.execution_effects == {}+ assert migrated.is_complete()+ assert _final_for_output(migrated).output_collection == [11, 12]+++def test_failed_direct_completion_does_not_persist_a_reference() -> None:+ graph = Graph()+ graph.add_node(AddInvocation(id="add", a=1, b=2))+ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert isinstance(node, AddInvocation)+ before = dump_execution_state(state)++ with pytest.raises(TypeError, match="does not belong to execution node"):+ state.complete(node.id, BooleanOutput(value=True))++ assert dump_execution_state(state) == before+++def test_flat_for_fresh_execution_releases_after_loop_consumer() -> None:generic_trace, generic_state = _run_graph_with_effects(- GraphExecutionState(graph=graph), fail_source_id=fail_source_id+ GraphExecutionState(graph=_flat_for_graph(with_after=True)),)compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=graph),+ GraphExecutionState(graph=_flat_for_graph(with_after=True)),force_compatibility_scheduler=True,- fail_source_id=fail_source_id,)- assert generic_trace == compatibility_trace- assert generic_state.has_error() == compatibility_state.has_error()- assert generic_state.is_complete() == compatibility_state.is_complete()- assert {- generic_state.prepared_source_mapping.get(execution_id, execution_id): message- for execution_id, message in generic_state.errors.items()- } == {- compatibility_state.prepared_source_mapping.get(execution_id, execution_id): message- for execution_id, message in compatibility_state.errors.items()- }- assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(- compatibility_state+ assert generic_trace == compatibility_trace == ["for", "body", "return", "for", "body", "return", "after"]+ after_id = next(+ exec_node_id+ for exec_node_id, source_node_id in generic_state.prepared_source_mapping.items()+ if source_node_id == "after")- assert _direct_iterate_fan_in_execution_ref_projection(- generic_state- ) == _direct_iterate_fan_in_execution_ref_projection(compatibility_state)- assert _execution_token_projection(generic_state) == _execution_token_projection(compatibility_state)- assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)- for state in (generic_state, compatibility_state):- assert state.has_error()- assert "collect" not in {- state.prepared_source_mapping.get(execution_id, execution_id) for execution_id in state.executed- }- assert state.is_complete()+ assert generic_state.results[after_id].value == [11, 12]+ assert compatibility_state.results[+ next(+ exec_node_id+ for exec_node_id, source_node_id in compatibility_state.prepared_source_mapping.items()+ if source_node_id == "after"+ )+ ].value == [11, 12]+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)-def test_body_iterate_fan_in_rolls_back_mid_expansion_and_retries(monkeypatch: pytest.MonkeyPatch) -> None:- graph = _body_iterate_fan_in_graph(- branches=(- ("left_source", "left_iterate", "left_body", ["left"]),- ("right_source", "right_iterate", "right_body", ["right"]),- )+def test_flat_for_none_output_matches_compatibility_scheduler() -> None:+ graph = _flat_for_graph(collection=[None, None], body_returns_none=True)+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph.model_copy(deep=True)))+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=True,)- state = GraphExecutionState(graph=graph)- _partial_trace, state = _run_graph_with_effects(state, stop_after=2)- before_failure_durable = _body_fan_in_durable_projection(state)- before_failure_runtime = _body_fan_in_runtime_projection(state)- original_create = GraphExecutionState._create_direct_execution_node_copy+ assert generic_trace == compatibility_trace == ["for", "body", "return", "for", "body", "return"]+ assert _final_for_output(generic_state).output_collection == [None, None]+ assert _final_for_output(compatibility_state).output_collection == [None, None]+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert _execution_identity_projection(generic_state) == _execution_identity_projection(compatibility_state)+ _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)- def fail_at_right_body(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):- if source_node_id == "right_body":- raise RuntimeError("injected body fan-in planner failure")- return original_create(self, source_node_id, *args, **kwargs)- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_right_body)- with pytest.raises(RuntimeError, match="injected body fan-in planner failure"):- state.next()+def test_flat_for_apply_path_matches_compatibility_scheduler() -> None:+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph(with_after=True)))+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph(with_after=True)),+ force_compatibility_scheduler=True,+ )- assert _body_fan_in_durable_projection(state) == before_failure_durable- assert _body_fan_in_runtime_projection(state) == before_failure_runtime+ assert generic_trace == compatibility_trace == ["for", "body", "return", "for", "body", "return", "after"]+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)+ _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)+ for state in (generic_state, compatibility_state):+ after_id = next(+ execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "after"+ )+ assert state.results[after_id].value == [11, 12]+ assert _final_for_output(state).output_collection == [11, 12]- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)- trace, state = _run_graph_with_effects(state)- expected_trace, expected_state = _run_graph_with_effects(- GraphExecutionState(- graph=_body_iterate_fan_in_graph(- branches=(- ("left_source", "left_iterate", "left_body", ["left"]),- ("right_source", "right_iterate", "right_body", ["right"]),- )+ continuations = sorted(+ state._generic_runtime().continuations.values(), key=lambda continuation: continuation.frame.iteration_path+ )+ assert [+ (+ state.prepared_source_mapping[continuation.owner_id],+ continuation.kind,+ continuation.status,+ tuple(continuation.frame.iteration_path),+ continuation.frame.state_id,+ continuation.frame.workflow_call_depth,+ )+ for continuation in continuations+ ] == [+ ("for", "for", "completed", (0,), state.id, 0),+ ("for", "for", "completed", (1,), state.id, 0),+ ]+ continuation_effects = sorted(+ (+ state.prepared_source_mapping[effect.execution_ref.node_id],+ effect.operation,+ effect.continuation_kind,+ tuple(effect.execution_ref.frame),)+ for effects in state.execution_effects.values()+ for effect in effects+ if effect.kind == "continuation")- )+ assert continuation_effects == [+ ("for", "start", "for", (0,)),+ ("for", "start", "for", (1,)),+ ("return", "complete", "for", (0,)),+ ("return", "complete", "for", (1,)),+ ]- assert _partial_trace + trace == expected_trace- assert trace == ["left_iterate", "right_iterate", "left_body", "right_body", "collect"]- assert _source_output(state, "collect").collection == ["left", "right"]- assert _state_projection(state) == _state_projection(expected_state)- assert _direct_iterate_fan_in_stream_projection(state) == _direct_iterate_fan_in_stream_projection(expected_state)- assert _direct_iterate_fan_in_execution_ref_projection(state) == _direct_iterate_fan_in_execution_ref_projection(- expected_state- )- assert _execution_token_projection(state) == _execution_token_projection(expected_state)- assert _effect_ledger_projection(state) == _effect_ledger_projection(expected_state)- assert state.is_complete()+def test_flat_for_apply_partial_rehydration_preserves_continuation_runtime() -> None:+ graph = _flat_for_graph(with_after=True, collection=[None, None], body_returns_none=True)+ resumed_projections: list[tuple[Any, ...]] = []-def test_body_iterate_fan_in_unsupported_topology_uses_compatibility_fallback() -> None:- graph = _body_iterate_fan_in_graph(- branches=(- ("m_source", "m_iterate", "m_body", ["m"]),- ("z_source", "z_iterate", "z_body", ["z"]),- ("a_source", "a_iterate", "a_body", ["a"]),+ for force_compatibility_scheduler in (False, True):+ expected_trace, expected_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=force_compatibility_scheduler,)- )- assert GraphExecutionState(graph=graph)._get_direct_iterate_collect_nodes() is None-- generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph))- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=graph), force_compatibility_scheduler=True- )-- assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter) and isinstance(- compatibility_state._execution_scheduler, _ExecutionScheduler- )- assert generic_trace == compatibility_trace- generic_collection = _source_output(generic_state, "collect").collection- compatibility_collection = _source_output(compatibility_state, "collect").collection- # Unsupported body-mediated fan-in stays on the legacy materializer. Its item ordering- # is not part of this bounded planner's contract, but values (including duplicates) must- # be retained; only the admitted two-branch planner promises lexical source ordering.- assert sorted(generic_collection) == sorted(compatibility_collection) == ["a", "m", "z"]- assert _execution_edge_projection(generic_state) == _execution_edge_projection(compatibility_state)- assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(- compatibility_state- )- assert _direct_iterate_fan_in_execution_ref_projection(- generic_state- ) == _direct_iterate_fan_in_execution_ref_projection(compatibility_state)- assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)- assert generic_state.is_complete()- assert compatibility_state.is_complete()+ partial_trace, partial_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after_source="return",+ )+ restored = load_execution_state(dump_execution_state(partial_state))+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(restored)+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)+ # Rehydration reconstructs references for all prepared nodes, while the partial in-memory+ # state only has references for nodes reached so far. Compare the durable token/effect projection.+ assert _execution_token_projection(restored) == _execution_token_projection(partial_state)+ _assert_execution_identity_consistent(restored)+ assert any(+ (effect.get("kind") if isinstance(effect, dict) else effect.kind) == "continuation"+ and (effect.get("operation") if isinstance(effect, dict) else effect.operation) == "complete"+ and (effect.get("payload") if isinstance(effect, dict) else effect.payload)+ == {"output": None, "state": None, "continue_condition": True}+ for effects in restored.execution_effects.values()+ for effect in effects+ )-def test_body_iterate_fan_in_downstream_topology_stays_on_compatibility_fallback() -> None:- graph = _body_iterate_fan_in_graph(- branches=(- ("right_source", "right_iterate", "right_body", ["right"]),- ("left_source", "left_iterate", "left_body", ["left"]),+ remaining_trace, resumed_state = _run_graph_with_effects(+ restored,+ force_compatibility_scheduler=force_compatibility_scheduler,)- )- graph.add_node(AnyTypeTestInvocation(id="after"))- graph.add_edge(- Edge(- source=EdgeConnection(node_id="collect", field="collection"),- destination=EdgeConnection(node_id="after", field="value"),++ assert partial_trace + remaining_trace == expected_trace+ assert _state_projection(resumed_state) == _state_projection(expected_state)+ assert _continuation_projection(resumed_state) == _continuation_projection(expected_state)+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)+ assert _execution_token_projection(resumed_state) == _execution_token_projection(expected_state)+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)+ assert _final_for_output(resumed_state).output_collection == [None, None]+ _assert_execution_identity_consistent(resumed_state)+ if force_compatibility_scheduler:+ assert isinstance(resumed_state._execution_scheduler, _ExecutionScheduler)+ else:+ assert isinstance(resumed_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ resumed_projections.append(+ (+ _state_projection(resumed_state),+ _continuation_projection(resumed_state),+ _effect_ledger_projection(resumed_state),+ _execution_identity_projection(resumed_state),+ ))- )- assert GraphExecutionState(graph=graph)._get_direct_iterate_collect_nodes() is None+ assert resumed_projections[0] == resumed_projections[1]- generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph))++ ("fail_source_id", "expected_trace"),+ [+ ("body", ["for", "body"]),+ ("return", ["for", "body", "return"]),+ ],+)+def test_flat_for_failure_matches_compatibility_scheduler(fail_source_id: str, expected_trace: list[str]) -> None:+ generic_trace, generic_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph()),+ fail_source_id=fail_source_id,+ )compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=graph), force_compatibility_scheduler=True+ GraphExecutionState(graph=_flat_for_graph()),+ force_compatibility_scheduler=True,+ fail_source_id=fail_source_id,)- assert generic_trace == compatibility_trace- assert generic_trace[-2:] == ["collect", "after"]- generic_collection = _source_output(generic_state, "collect").collection- compatibility_collection = _source_output(compatibility_state, "collect").collection- assert sorted(generic_collection) == sorted(compatibility_collection) == ["left", "right"]- assert _source_output(generic_state, "after").value == generic_collection- assert _source_output(compatibility_state, "after").value == compatibility_collection- assert _execution_edge_projection(generic_state) == _execution_edge_projection(compatibility_state)- assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(- compatibility_state- )- assert _direct_iterate_fan_in_execution_ref_projection(- generic_state- ) == _direct_iterate_fan_in_execution_ref_projection(compatibility_state)- assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)- assert generic_state.is_complete()- assert compatibility_state.is_complete()+ assert generic_trace == compatibility_trace == expected_trace+ for state in (generic_state, compatibility_state):+ assert state.next() is None+ assert {+ state.prepared_source_mapping.get(node_id, node_id): message for node_id, message in state.errors.items()+ } == {fail_source_id: "injected failure"}+ assert state.is_complete()+ assert sum(len(effects) for effects in state.execution_effects.values()) == 1+ assert all(item.status == "running" for item in state._generic_runtime().continuations.values())+ _assert_execution_identity_consistent(state)+ restored = load_execution_state(dump_execution_state(state))+ if isinstance(state._execution_scheduler, _ExecutionScheduler):+ _restore_compatibility_scheduler(restored)+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(state)+ assert _continuation_projection(restored) == _continuation_projection(state)+ _assert_execution_identity_consistent(restored)+ assert {+ state.prepared_source_mapping.get(node_id, node_id): message for node_id, message in restored.errors.items()+ } == {fail_source_id: "injected failure"}+ assert restored.next() is None+ assert restored.is_complete()+ if isinstance(state._execution_scheduler, _ExecutionScheduler):+ assert isinstance(restored._execution_scheduler, _ExecutionScheduler)+ else:+ assert restored._execution_scheduler is None+ assert _state_projection(generic_state) == _state_projection(compatibility_state)-def test_direct_iterate_body_collect_fresh_execution_handles_empty_input() -> None:- state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=[]))- with (- patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("canonical empty Iterate -> body -> Collect must not use materializer.prepare"),- ) as prepare,- patch.object(- graph_module._ExecutionMaterializer,- "_get_collect_iteration_mapping_groups",- side_effect=AssertionError("canonical empty Iterate -> body -> Collect must not group collector inputs"),- ) as group_collector_inputs,- ):- trace, state = _run_graph(state)[email protected]("stop_after_source", ["for", "body"])+def test_flat_for_partial_rehydration_matches_compatibility_scheduler(stop_after_source: str) -> None:+ graph = _flat_for_graph()+ expected_trace, expected_state = _run_graph_with_effects(GraphExecutionState(graph=graph.model_copy(deep=True)))+ resumed_projections: list[tuple[Any, ...]] = []- assert "iterate" not in trace- assert "body" not in trace- assert trace[-1] == "collect"- assert _source_output(state, "collect").collection == []- assert state.is_complete()- prepare.assert_not_called()- group_collector_inputs.assert_not_called()+ for force_compatibility_scheduler in (False, True):+ partial_trace, partial_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ stop_after_source=stop_after_source,+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ snapshot = dump_execution_state(partial_state)+ restored = load_execution_state(snapshot)+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(restored)+ remaining_trace, resumed_state = _run_graph_with_effects(+ restored,+ force_compatibility_scheduler=force_compatibility_scheduler,+ )-def test_direct_iterate_body_collect_planner_rolls_back_partial_expansion(- monkeypatch: pytest.MonkeyPatch,-) -> None:- state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["first", "last"]))- source_node = state.next()- assert source_node is not None- state.complete(source_node.id, source_node.invoke(Mock()))+ assert partial_trace + remaining_trace == expected_trace+ assert _state_projection(resumed_state) == _state_projection(expected_state)+ # Rehydration reconstructs durable execution references for all prepared nodes; a fresh+ # in-memory run does not retain those references after terminal cleanup. Compare durable+ # token/effect state and continuation records instead.+ assert _execution_token_projection(resumed_state) == _execution_token_projection(expected_state)+ assert _continuation_projection(resumed_state) == _continuation_projection(expected_state)+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)+ _assert_execution_identity_consistent(resumed_state)+ if force_compatibility_scheduler:+ assert isinstance(resumed_state._execution_scheduler, _ExecutionScheduler)+ else:+ assert isinstance(resumed_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ resumed_projections.append(+ (+ _state_projection(resumed_state),+ _continuation_projection(resumed_state),+ _effect_ledger_projection(resumed_state),+ )+ )- original_create = GraphExecutionState._create_direct_execution_node_copy- failed = False+ assert resumed_projections[0] == resumed_projections[1]- def fail_after_body(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):- nonlocal failed- node = original_create(self, source_node_id, *args, **kwargs)- if source_node_id == "body" and not failed:- failed = True- raise RuntimeError("injected direct planner failure")- return node- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_after_body)- with pytest.raises(RuntimeError, match="injected direct planner failure"):- state.next()+def test_flat_for_frame_and_continuation_identity_matches_compatibility_scheduler() -> None:+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph()), stop_after=4)+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph()),+ force_compatibility_scheduler=True,+ stop_after=4,+ )- assert set(state.source_prepared_mapping) == {"source"}- assert len(state.execution_graph.nodes) == 1- assert not state.execution_graph.edges+ assert generic_trace == compatibility_trace == ["for", "body", "return", "for"]+ assert _execution_identity_projection(generic_state) == _execution_identity_projection(compatibility_state)+ assert _continuation_projection(generic_state) == _continuation_projection(compatibility_state)+ _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)+ for state in (generic_state, compatibility_state):+ continuations = sorted(+ state._generic_runtime().continuations.values(), key=lambda item: item.frame.iteration_path+ )+ assert len(continuations) == 2+ assert [tuple(item.frame.iteration_path) for item in continuations] == [(0,), (1,)]+ assert {state.prepared_source_mapping[item.owner_id] for item in continuations} == {"for"}+ assert {item.frame.state_id for item in continuations} == {state.id}+ assert {item.frame.workflow_call_depth for item in continuations} == {0}+ frame_ids = [item.frame.frame_id for item in continuations]+ assert all(frame_ids)+ assert len(set(frame_ids)) == len(frame_ids)+ assert all(+ item.frame.model_dump(mode="json")+ == state._expected_execution_ref(item.owner_id).frame.model_dump(mode="json")+ for item in continuations+ )+ assert [item.status for item in continuations] == ["completed", "running"]+ _assert_execution_identity_consistent(state)- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)- trace, state = _run(state)+ generic_frames = {item.frame.frame_id for item in generic_state._generic_runtime().continuations.values()}+ compatibility_frames = {+ item.frame.frame_id for item in compatibility_state._generic_runtime().continuations.values()+ }+ assert generic_frames.isdisjoint(compatibility_frames)- assert trace == ["iterate", "iterate", "body", "body", "collect"]- assert _source_output(state, "collect").collection == ["first", "last"]- assert state.is_complete()+ other_trace, other_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph()), stop_after=4)+ assert other_trace == generic_trace+ other_frames = {item.frame.frame_id for item in other_state._generic_runtime().continuations.values()}+ generic_frames = {item.frame.frame_id for item in generic_state._generic_runtime().continuations.values()}+ assert other_frames.isdisjoint(generic_frames)-def test_direct_iterate_body_collect_downstream_planner_rolls_back_partial_expansion(- monkeypatch: pytest.MonkeyPatch,-) -> None:- state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["first", "last"], with_after=True))- source_node = state.next()- assert source_node is not None- state.complete(source_node.id, source_node.invoke(Mock()))+def test_empty_literal_flat_for_uses_generic_scheduler() -> None:+ state = GraphExecutionState(graph=_flat_for_graph(collection=[]))- original_create = GraphExecutionState._create_direct_execution_node_copy+ assert state._can_use_generic_scheduler()+ assert isinstance(state._scheduler(), _GenericGraphSchedulerAdapter)- def fail_at_downstream(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):- if source_node_id == "after":- raise RuntimeError("injected downstream planner failure")- return original_create(self, source_node_id, *args, **kwargs)- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_downstream)- with pytest.raises(RuntimeError, match="injected downstream planner failure"):- state.next()+def test_empty_literal_flat_for_matches_compatibility_scheduler() -> None:+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph(collection=[])))+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph(collection=[])),+ force_compatibility_scheduler=True,+ )++ assert generic_trace == compatibility_trace == []+ assert _final_for_output(generic_state).output_collection == []+ assert _final_for_output(compatibility_state).output_collection == []+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)+ assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert set(state.source_prepared_mapping) == {"source"}- assert len(state.execution_graph.nodes) == 1- assert not state.execution_graph.edges- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)- trace, state = _run_graph(state)+def test_input_driven_empty_flat_for_uses_generic_scheduler_and_exact_terminal_semantics() -> None:+ state = GraphExecutionState(graph=_flat_for_graph(input_collection=[]))- assert trace == ["iterate", "iterate", "body", "body", "collect", "after"]- assert _source_output(state, "after").value == ["first", "last"]+ assert state._can_use_generic_scheduler()+ trace, state = _run_graph_with_effects(state)++ assert trace == ["collection"]+ assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)+ final_output = _final_for_output(state)+ assert final_output.item is None+ assert final_output.index == -1+ assert final_output.total == 0+ assert final_output.state == LoopState()+ assert final_output.output_collection == []+ assert final_output.final_state == LoopState()+ assert "body" not in state.source_prepared_mapping+ assert "return" not in state.source_prepared_mappingassert state.is_complete()+ assert list(state._generic_runtime().continuations.values()) == []+ _assert_execution_identity_consistent(state)- "collection",- [- ["first", None, "last"],- [],- ],- ids=["ordered-values-including-none", "empty"],-)-def test_direct_iterate_body_collect_matches_forced_compatibility_scheduler(collection: list[Any]) -> None:- generic_trace, generic_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection))+def test_input_driven_empty_flat_for_matches_compatibility_scheduler() -> None:+ generic_trace, generic_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph(input_collection=[])))- compatibility_trace, compatibility_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)),+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph(input_collection=[])),force_compatibility_scheduler=True,)- assert generic_trace == compatibility_trace- assert _source_output(generic_state, "collect").collection == collection- assert _source_output(compatibility_state, "collect").collection == collection- assert generic_state.is_complete()- assert compatibility_state.is_complete()+ assert generic_trace == compatibility_trace == ["collection"]assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)assert _state_projection(generic_state) == _state_projection(compatibility_state)+ _assert_execution_identity_consistent(generic_state)+ _assert_execution_identity_consistent(compatibility_state)[email protected]("force_compatibility_scheduler", [False, True])-def test_direct_iterate_body_collect_partial_dump_load_resume_matches_fresh_execution(- force_compatibility_scheduler: bool,-) -> None:- collection = ["first", None, "last"]- expected_trace, expected_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)),- force_compatibility_scheduler=force_compatibility_scheduler,+def test_input_driven_empty_flat_for_checkpoint_after_producer_does_not_replay() -> None:+ expected_trace, expected_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph(input_collection=[])))- partial_trace, partial_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)),- force_compatibility_scheduler=force_compatibility_scheduler,- stop_after=2,+ partial_trace, partial_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph(input_collection=[])),+ stop_after_source="collection",)restored = load_execution_state(dump_execution_state(partial_state))- if force_compatibility_scheduler:- _restore_compatibility_scheduler(restored)- resumed_trace, resumed_state = _run_graph(- restored,- force_compatibility_scheduler=force_compatibility_scheduler,- )+ resumed_trace, restored = _run_graph_with_effects(restored)+ terminal_reload = load_execution_state(dump_execution_state(restored))- assert partial_trace + resumed_trace == expected_trace- assert _source_output(resumed_state, "collect").collection == collection- assert resumed_state.is_complete()- assert _state_projection(resumed_state) == _state_projection(expected_state)- if force_compatibility_scheduler:- assert isinstance(resumed_state._execution_scheduler, _ExecutionScheduler)- else:- assert isinstance(resumed_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert expected_trace == partial_trace == ["collection"]+ assert resumed_trace == []+ assert isinstance(restored._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert _state_projection(restored) == _state_projection(expected_state)+ assert terminal_reload.is_complete()+ assert _state_projection(terminal_reload) == _state_projection(restored)+ assert _final_for_output(terminal_reload).output_collection == []+ _assert_execution_identity_consistent(restored)+ _assert_execution_identity_consistent(terminal_reload)-def test_direct_iterate_body_collect_empty_checkpoint_rehydrates_without_materializer() -> None:- _partial_trace, partial_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=[])), stop_after=1- )- with (- patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("empty canonical checkpoint must not use materializer.prepare"),- ) as prepare,- patch.object(- graph_module._ExecutionMaterializer,- "_get_collect_iteration_mapping_groups",- side_effect=AssertionError("empty canonical checkpoint must not group collector inputs"),- ) as group_collector_inputs,- ):- resumed_trace, resumed_state = _run_graph(load_execution_state(dump_execution_state(partial_state)))+def test_input_driven_empty_flat_for_with_downstream_remains_compatibility_owned() -> None:+ state = GraphExecutionState(graph=_flat_for_graph(input_collection=[], with_after=True))- assert resumed_trace == ["collect"]- assert _source_output(resumed_state, "collect").collection == []- assert resumed_state.is_complete()- prepare.assert_not_called()- group_collector_inputs.assert_not_called()+ assert state._can_use_generic_scheduler() is False+ assert isinstance(state._scheduler(), _ExecutionScheduler)-def test_direct_iterate_body_collect_failure_rehydrates_pending_state_without_replanning() -> None:- trace, failed_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["first", "last"])),- fail_source_id="body",- )- assert trace[0] == "source"- assert trace.count("iterate") == 2- assert trace[-1] == "body"- assert failed_state.has_error()+def test_input_driven_empty_flat_for_with_index_body_edge_remains_compatibility_owned() -> None:+ graph = _flat_for_graph(input_collection=[])+ body_edge = next(edge for edge in graph.edges if edge.destination.node_id == "body")+ graph.delete_edge(body_edge)+ graph.add_edge(create_edge("for", "index", "body", body_edge.destination.field))- restored = load_execution_state(dump_execution_state(failed_state))- assert restored.has_error()- assert restored.source_prepared_mapping.get("collect")- assert restored.is_complete()+ state = GraphExecutionState(graph=graph)+ assert state._can_use_generic_scheduler() is False-def test_direct_iterate_body_collect_with_downstream_consumer_uses_private_planner() -> None:- with (- patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("direct Iterate -> body -> Collect -> after must not use materializer.prepare"),- ) as prepare,- patch.object(- graph_module._ExecutionMaterializer,- "_get_collect_iteration_mapping_groups",- side_effect=AssertionError("direct downstream Collect must not group collector inputs"),- ) as group_collector_inputs,- ):- trace, state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["value"], with_after=True))- )- assert trace[-1] == "after"- assert _source_output(state, "after").value == ["value"]- assert state.is_complete()- prepare.assert_not_called()- group_collector_inputs.assert_not_called()+def test_input_driven_empty_flat_for_with_wrong_return_edge_remains_compatibility_owned() -> None:+ graph = _flat_for_graph(input_collection=[])+ graph.delete_node("body")+ graph.add_node(StateSetInvocation(id="body"))+ graph.add_edge(create_edge("for", "item", "body", "value"))+ graph.add_edge(create_edge("body", "state", "return", "state"))+ state = GraphExecutionState(graph=graph)-def test_direct_iterate_body_collect_two_downstream_consumers_admits_exact_shape() -> None:- state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["value"], downstream_count=2))+ assert state._can_use_generic_scheduler() is False- assert len(state.graph.nodes) == 6- assert len(state.graph.edges) == 5- assert state._get_direct_iterate_collect_nodes() == (- "source",- "iterate",- "body",- "collect",- ("after_1", "after_2"),++def test_input_driven_flat_for_uses_generic_scheduler() -> None:+ state = GraphExecutionState(graph=_flat_for_graph(input_collection=[3, 7]))++ assert state._can_use_generic_scheduler()+ assert isinstance(state._scheduler(), _GenericGraphSchedulerAdapter)+++def test_input_driven_flat_for_matches_compatibility_scheduler() -> None:+ generic_trace, generic_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph(input_collection=[3, 7]))+ )+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph(input_collection=[3, 7])),+ force_compatibility_scheduler=True,+ )++ assert (+ generic_trace+ == compatibility_trace+ == [+ "collection",+ "for",+ "body",+ "return",+ "for",+ "body",+ "return",+ ]+ )+ assert _final_for_output(generic_state).output_collection == [13, 17]+ assert _final_for_output(compatibility_state).output_collection == [13, 17]+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)+ assert _state_projection(generic_state) == _state_projection(compatibility_state)++ restored_generic = load_execution_state(dump_execution_state(generic_state))+ restored_compatibility = load_execution_state(dump_execution_state(compatibility_state))+ _restore_compatibility_scheduler(restored_compatibility)+ assert isinstance(restored_generic._scheduler(), _GenericGraphSchedulerAdapter)+ assert isinstance(restored_compatibility._execution_scheduler, _ExecutionScheduler)+ assert _state_projection(restored_generic) == _state_projection(generic_state)+ assert _state_projection(restored_compatibility) == _state_projection(compatibility_state)+ _assert_execution_identity_consistent(restored_generic)+ _assert_execution_identity_consistent(restored_compatibility)+++ ("continue_condition", "expected_trace", "expected_collection", "expected_state"),+ [+ (True, ["for", "body", "return"] * 3, [1, 2, 3], {"count": 3}),+ (False, ["for", "body", "return"], [1], {"count": 1}),+ ],+)+def test_flat_for_fresh_execution_matches_state_and_break_semantics(+ continue_condition: bool,+ expected_trace: list[str],+ expected_collection: list[int],+ expected_state: dict[str, int],+) -> None:+ generic_trace, generic_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_state_graph(continue_condition)),+ )+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_state_graph(continue_condition)),+ force_compatibility_scheduler=True,)- assert state._can_use_direct_iterate_collect_planner()--def test_direct_iterate_body_collect_three_downstream_consumers_uses_private_planner() -> None:- state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["value"], downstream_count=3))- assert state._get_direct_iterate_collect_nodes() == (- "source",- "iterate",- "body",- "collect",- ("after_1", "after_2", "after_3"),+ assert generic_trace == compatibility_trace == expected_trace+ final_for_id = max(+ (+ exec_node_id+ for exec_node_id, source_node_id in generic_state.prepared_source_mapping.items()+ if source_node_id == "for"+ ),+ key=lambda exec_node_id: generic_state.execution_graph.get_node(exec_node_id).index,)- assert state._can_use_direct_iterate_collect_planner()+ final_for_output = generic_state.results[final_for_id]+ assert final_for_output.output_collection == expected_collection+ assert final_for_output.final_state == LoopState(values=expected_state)+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)- with (- patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("three direct downstream consumers must not use materializer.prepare"),- ) as prepare,- patch.object(- graph_module._ExecutionMaterializer,- "_get_collect_iteration_mapping_groups",- side_effect=AssertionError("three direct downstream consumers must not group collector inputs"),- ) as group_collector_inputs,- ):- trace, state = _run_graph(state)- assert trace == ["source", "iterate", "body", "collect", "after_1", "after_2", "after_3"]- for downstream_id in ("after_1", "after_2", "after_3"):- assert _source_output(state, downstream_id).value == ["value"]- assert state.is_complete()- prepare.assert_not_called()- group_collector_inputs.assert_not_called()+def test_nested_if_checkpoint_restore_matches_compatibility_scheduler() -> None:+ graph = _nested_if_graph()+ expected_trace, expected_state = _run_graph(GraphExecutionState(graph=graph.model_copy(deep=True)))+ for force_compatibility_scheduler in (False, True):+ checkpoint_trace, checkpoint_state = _run_graph(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after=4,+ )+ restored = load_execution_state(dump_execution_state(checkpoint_state))+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(restored)+ remaining_trace, restored_state = _run_graph(+ restored,+ force_compatibility_scheduler=force_compatibility_scheduler,+ )++ assert checkpoint_trace + remaining_trace == expected_trace+ assert _state_projection(restored_state) == _state_projection(expected_state)+ assert _activation_projection(restored_state) == _activation_projection(expected_state)+ assert restored_state.is_complete()+++def test_nested_if_failure_round_trip_matches_compatibility_scheduler() -> None:+ expected_trace = ["outer_condition", "inner_condition", "outer_false", "inner_true", "inner_false"]+ expected_errors = {"inner_false": "injected failure"}[email protected]("collection", [["first", None, "last"], []], ids=["ordered-none", "empty"])-def test_direct_iterate_body_collect_three_downstream_consumers_matches_compatibility(- collection: list[Any],-) -> None:generic_trace, generic_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=3))+ GraphExecutionState(graph=_nested_if_graph()),+ fail_source_id="inner_false",)compatibility_trace, compatibility_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=3)),+ GraphExecutionState(graph=_nested_if_graph()),force_compatibility_scheduler=True,+ fail_source_id="inner_false",)- expected_trace = ["source"] + ["iterate"] * len(collection) + ["body"] * len(collection)- expected_trace += ["collect", "after_1", "after_2", "after_3"]- assert generic_trace == expected_trace- assert generic_trace[:-3] == compatibility_trace[:-3]- assert sorted(generic_trace[-3:]) == sorted(compatibility_trace[-3:]) == ["after_1", "after_2", "after_3"]+ assert generic_trace == compatibility_trace == expected_trace+ assert generic_state.next() is None+ assert compatibility_state.next() is Nonefor state in (generic_state, compatibility_state):- assert _source_output(state, "collect").collection == collection- for downstream_id in ("after_1", "after_2", "after_3"):- assert _source_output(state, downstream_id).value == collection- assert state.is_complete()+ assert {+ state.prepared_source_mapping.get(execution_id, execution_id): message+ for execution_id, message in state.errors.items()+ } == expected_errors+ result_sources = {state.prepared_source_mapping[execution_id] for execution_id in state.results}+ assert "inner_if" not in result_sources+ assert "outer_if" not in result_sources+ assert "sink" not in result_sources+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ restored_generic = load_execution_state(dump_execution_state(generic_state))+ restored_compatibility = load_execution_state(dump_execution_state(compatibility_state))+ _restore_compatibility_scheduler(restored_compatibility)+ assert restored_generic.next() is None+ assert restored_compatibility.next() is None+ assert _state_projection(restored_generic) == _state_projection(restored_compatibility)-def test_direct_iterate_body_collect_two_downstream_consumers_uses_private_planner() -> None:- with (- patch.object(- graph_module._ExecutionMaterializer,- "prepare",- side_effect=AssertionError("two direct downstream consumers must not use materializer.prepare"),- ) as prepare,- patch.object(- graph_module._ExecutionMaterializer,- "_get_collect_iteration_mapping_groups",- side_effect=AssertionError("two direct downstream consumers must not group collector inputs"),- ) as group_collector_inputs,- ):- trace, state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["value"], downstream_count=2))++def test_static_dag_checkpoint_restore_has_matching_remaining_trace() -> None:+ expected_trace, expected_state = _run(_load_fixture())++ for force_compatibility_scheduler in (False, True):+ checkpoint_trace, checkpoint_state = _run(+ _load_fixture(),+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after=1,+ )+ restored = load_execution_state(dump_execution_state(checkpoint_state))+ remaining_trace, restored_state = _run(+ restored,+ force_compatibility_scheduler=force_compatibility_scheduler,)- assert trace == ["source", "iterate", "body", "collect", "after_1", "after_2"]- assert _source_output(state, "after_1").value == ["value"]- assert _source_output(state, "after_2").value == ["value"]- assert state.is_complete()- prepare.assert_not_called()- group_collector_inputs.assert_not_called()+ assert checkpoint_trace + remaining_trace == expected_trace+ assert restored_state.is_complete()+ assert _state_projection(restored_state) == _state_projection(expected_state)[email protected]("collection", [["first", None, "last"], []], ids=["ordered-none", "empty"])-def test_direct_iterate_body_collect_two_downstream_consumers_matches_compatibility(- collection: list[Any],-) -> None:- generic_trace, generic_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=2))- )- compatibility_trace, compatibility_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=2)),- force_compatibility_scheduler=True,- )[email protected]("force_compatibility_scheduler", [False, True])+def test_inflight_checkpoint_replays_claimed_work_after_rehydrate(force_compatibility_scheduler: bool) -> None:+ state = _load_fixture()+ if force_compatibility_scheduler:+ object.__setattr__(state, "_execution_scheduler", _ExecutionScheduler(state))- expected_trace = ["source"] + ["iterate"] * len(collection) + ["body"] * len(collection)- expected_trace += ["collect", "after_1", "after_2"]- assert generic_trace == expected_trace- assert generic_trace[:-2] == compatibility_trace[:-2]- assert sorted(generic_trace[-2:]) == sorted(compatibility_trace[-2:]) == ["after_1", "after_2"]- for state in (generic_state, compatibility_state):- assert _source_output(state, "collect").collection == collection- assert _source_output(state, "after_1").value == collection- assert _source_output(state, "after_2").value == collection- assert state.is_complete()+ claimed = state.next()+ assert claimed is not None+ snapshot = dump_execution_state(state)+ restored = load_execution_state(snapshot)+ if force_compatibility_scheduler:+ object.__setattr__(restored, "_execution_scheduler", _ExecutionScheduler(restored))+ replayed = restored.next()+ assert replayed is not None+ assert state.prepared_source_mapping[claimed.id] == "left"+ assert restored.prepared_source_mapping[replayed.id] == "left"+ assert restored.executed == set()-def test_direct_iterate_body_collect_two_downstream_consumers_rolls_back_partial_expansion(- monkeypatch: pytest.MonkeyPatch,-) -> None:- state = GraphExecutionState(- graph=_direct_iterate_body_collect_graph(collection=["first", "last"], downstream_count=2)- )- source_node = state.next()- assert source_node is not None- state.complete(source_node.id, source_node.invoke(Mock()))- original_create = GraphExecutionState._create_direct_execution_node_copy+def test_injected_failure_stops_both_schedulers_without_further_scheduling() -> None:+ for trace, state in _run_both(fail_source_id="right"):+ assert trace == ["left", "right"]+ assert {+ state.prepared_source_mapping.get(node_id, node_id): message for node_id, message in state.errors.items()+ } == {"right": "injected failure"}+ assert state.next() is None+ assert "join" not in state.results- def fail_at_second_downstream(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):- if source_node_id == "after_2":- raise RuntimeError("injected second downstream planner failure")- return original_create(self, source_node_id, *args, **kwargs)- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_second_downstream)- with pytest.raises(RuntimeError, match="injected second downstream planner failure"):- state.next()+def test_injected_failure_round_trip_preserves_both_scheduler_terminal_state() -> None:+ generic, compatibility = _run_both(fail_source_id="right")+ restored_generic = load_execution_state(dump_execution_state(generic[1]))+ restored_compatibility = load_execution_state(dump_execution_state(compatibility[1]))+ _restore_compatibility_scheduler(restored_compatibility)- assert set(state.source_prepared_mapping) == {"source"}- assert len(state.execution_graph.nodes) == 1- assert not state.execution_graph.edges+ assert restored_generic.next() is None+ assert restored_compatibility.next() is None+ assert restored_generic.is_complete()+ assert restored_compatibility.is_complete()+ assert _state_projection(restored_generic) == _state_projection(restored_compatibility)- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)- trace, state = _run_graph(state)- assert trace == ["iterate", "iterate", "body", "body", "collect", "after_1", "after_2"]- assert _source_output(state, "after_1").value == ["first", "last"]- assert _source_output(state, "after_2").value == ["first", "last"]- assert state.is_complete()+def test_real_invocation_failure_round_trip_preserves_both_scheduler_terminal_state() -> None:+ expected_error = "This invocation is supposed to fail"+ terminal_states: list[tuple[str, bool, bool]] = []+ for force_compatibility_scheduler in (False, True):+ graph = Graph()+ graph.add_node(ErrorInvocation(id="error"))+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)-def test_direct_iterate_body_collect_three_downstream_consumers_rolls_back_partial_expansion(- monkeypatch: pytest.MonkeyPatch,-) -> None:- state = GraphExecutionState(- graph=_direct_iterate_body_collect_graph(collection=["first", "last"], downstream_count=3)- )- source_node = state.next()- assert source_node is not None- state.complete(source_node.id, source_node.invoke(Mock()))+ node = state.next()+ assert node is not None+ with pytest.raises(Exception) as invocation_error:+ node.invoke(Mock())+ assert str(invocation_error.value) == expected_error+ state.set_node_error(node.id, str(invocation_error.value))++ assert state.next() is None+ assert state.is_complete()+ assert {+ state.prepared_source_mapping.get(node_id, node_id): message for node_id, message in state.errors.items()+ } == {"error": expected_error}- original_create = GraphExecutionState._create_direct_execution_node_copy+ restored = load_execution_state(dump_execution_state(state))+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(restored)- def fail_at_third_downstream(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):- if source_node_id == "after_3":- raise RuntimeError("injected third downstream planner failure")- return original_create(self, source_node_id, *args, **kwargs)+ assert restored.errors == state.errors+ assert restored.next() is None+ assert restored.is_complete()+ terminal_states.append((str(next(iter(restored.errors.values()))), True, restored.is_complete()))- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_third_downstream)- with pytest.raises(RuntimeError, match="injected third downstream planner failure"):- state.next()+ assert terminal_states == [(expected_error, True, True), (expected_error, True, True)]- assert set(state.source_prepared_mapping) == {"source"}- assert len(state.execution_graph.nodes) == 1- assert not state.execution_graph.edges- monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)- trace, state = _run_graph(state)[email protected]("fixture_name", ["static_dag_partial_v1.json", "static_dag_failed_v1.json"])+def test_durable_snapshot_corpus_round_trips_without_losing_terminal_state(fixture_name: str) -> None:+ state = _load_fixture(fixture_name)+ restored = load_execution_state(dump_execution_state(state))- assert trace == ["iterate", "iterate", "body", "body", "collect", "after_1", "after_2", "after_3"]- for downstream_id in ("after_1", "after_2", "after_3"):- assert _source_output(state, downstream_id).value == ["first", "last"]- assert state.is_complete()+ assert restored.id == state.id+ assert restored.executed == state.executed+ assert restored.executed_history == state.executed_history+ assert restored.errors == state.errors+ assert restored.indegree == state.indegree+ if state.errors:+ for force_compatibility_scheduler in (False, True):+ candidate = load_execution_state(dump_execution_state(state))+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(candidate)+ assert candidate.next() is None+ assert candidate.is_complete()+ generic = load_execution_state(dump_execution_state(state))+ compatibility = load_execution_state(dump_execution_state(state))+ _restore_compatibility_scheduler(compatibility)+ assert _state_projection(generic) == _state_projection(compatibility)+ else:+ generic_trace, generic_state = _run(restored)+ compatibility_trace, compatibility_state = _run(+ load_execution_state(dump_execution_state(state)),+ force_compatibility_scheduler=True,+ )+ assert generic_trace == compatibility_trace == ["right", "join"]+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()-def test_direct_iterate_body_collect_two_downstream_consumers_checkpoint_rehydrates() -> None:- collection = ["first", None, "last"]- expected_trace, expected_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=2))- )- partial_trace, partial_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=2)),- stop_after=3,- )- resumed_trace, resumed_state = _run_graph(load_execution_state(dump_execution_state(partial_state)))+def test_fixture_is_versioned_and_future_versions_are_explicitly_rejected() -> None:+ with FIXTURE_PATH.open(encoding="utf-8") as fixture:+ snapshot = json.load(fixture)- assert partial_trace + resumed_trace == expected_trace- assert _source_output(resumed_state, "collect").collection == collection- assert _source_output(resumed_state, "after_1").value == collection- assert _source_output(resumed_state, "after_2").value == collection- assert resumed_state.is_complete()- assert _state_projection(resumed_state) == _state_projection(expected_state)+ assert snapshot["execution_state_version"] == 1+ restored = load_execution_state(snapshot)+ assert restored.id == "fixture-state"+ assert dump_execution_state(restored)["execution_state_version"] == CURRENT_EXECUTION_STATE_VERSION+ future_snapshot = dict(snapshot)+ future_snapshot["execution_state_version"] = CURRENT_EXECUTION_STATE_VERSION + 1+ with pytest.raises(UnsupportedExecutionStateVersionError, match="newer than supported"):+ load_execution_state(future_snapshot)-def test_direct_iterate_body_collect_three_downstream_consumers_checkpoint_rehydrates() -> None:- collection = ["first", None, "last"]- expected_trace, expected_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=3))- )- partial_trace, partial_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=3)),- stop_after=3,- )- resumed_trace, resumed_state = _run_graph(load_execution_state(dump_execution_state(partial_state)))+def test_generic_legacy_shaped_if_does_not_prune_or_skip_during_resolution(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ graph = _nested_if_graph()+ state = GraphExecutionState(graph=graph)+ deleted_edges: list[Edge] = []- assert partial_trace + resumed_trace == expected_trace- assert _source_output(resumed_state, "collect").collection == collection- for downstream_id in ("after_1", "after_2", "after_3"):- assert _source_output(resumed_state, downstream_id).value == collection- assert resumed_state.is_complete()- assert _state_projection(resumed_state) == _state_projection(expected_state)+ def record_deleted_edge(self: GraphExecutionState, edge: Edge) -> None:+ deleted_edges.append(edge)+ monkeypatch.setattr(GraphExecutionState, "_tx_delete_execution_edge", record_deleted_edge)-def test_direct_iterate_body_collect_with_downstream_consumer_matches_forced_compatibility_scheduler() -> None:- generic_trace, generic_state = _run_graph(- GraphExecutionState(- graph=_direct_iterate_body_collect_graph(collection=["first", None, "last"], with_after=True)- )- )- compatibility_trace, compatibility_state = _run_graph(- GraphExecutionState(- graph=_direct_iterate_body_collect_graph(collection=["first", None, "last"], with_after=True)- ),- force_compatibility_scheduler=True,- )+ trace, state = _run_graph(state)- assert generic_trace == compatibility_trace- assert generic_trace[-2:] == ["collect", "after"]- assert _source_output(generic_state, "after").value == ["first", None, "last"]- assert _source_output(compatibility_state, "after").value == ["first", None, "last"]- assert generic_state.is_complete()- assert compatibility_state.is_complete()- assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert trace == [+ "outer_condition",+ "inner_condition",+ "outer_false",+ "inner_true",+ "inner_false",+ "inner_if",+ "outer_if",+ "sink",+ ]+ sink_id = next(iter(state.source_prepared_mapping["sink"]))+ assert state.results[sink_id].value == 7+ assert state.is_complete()+ assert deleted_edges == []-def test_direct_iterate_body_collect_downstream_checkpoint_after_none_item_rehydrates() -> None:- collection = ["first", None, "last"]- expected_trace, expected_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, with_after=True))- )- partial_trace, partial_state = _run_graph(- GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, with_after=True)),- stop_after=3,- )[email protected]("force_compatibility_scheduler", [False, True])+def test_if_readiness_preserves_both_schedulers(+ force_compatibility_scheduler: bool,+) -> None:+ graph = _nested_if_graph()- assert partial_trace == ["source", "iterate", "iterate"]- iterate_exec_id = next(- exec_node_id- for exec_node_id, source_node_id in partial_state.prepared_source_mapping.items()- if source_node_id == "iterate"- and exec_node_id in partial_state.results- and partial_state.results[exec_node_id].index == 1 # type: ignore[union-attr]+ trace, state = _run_graph(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=force_compatibility_scheduler,)- snapshot = dump_execution_state(partial_state)- assert snapshot["results"][iterate_exec_id]["item"] is None-- resumed_trace, resumed_state = _run_graph(load_execution_state(snapshot))-- assert partial_trace + resumed_trace == expected_trace- assert _source_output(resumed_state, "collect").collection == collection- assert _source_output(resumed_state, "after").value == collection- assert resumed_state.is_complete()- assert _state_projection(resumed_state) == _state_projection(expected_state)+ assert trace == [+ "outer_condition",+ "inner_condition",+ "outer_false",+ "inner_true",+ "inner_false",+ "inner_if",+ "outer_if",+ "sink",+ ]+ assert state.is_complete()-def test_direct_flat_for_completion_persists_continuations_and_result_outputs() -> None:- trace, state = _run(GraphExecutionState(graph=_flat_for_graph()))- assert trace == ["for", "body", "return", "for", "body", "return"]- snapshot = dump_execution_state(state)- restored = load_execution_state(snapshot)- final_for_id = max(- state.source_prepared_mapping["for"],- key=lambda exec_node_id: state.execution_graph.get_node(exec_node_id).index,[email protected]("force_compatibility_scheduler", [False, True])+def test_private_flat_if_runs_selected_branch_and_records_authoritative_token(+ force_compatibility_scheduler: bool,+) -> None:+ trace, state = _run_graph(+ GraphExecutionState(graph=_flat_if_graph()),+ force_compatibility_scheduler=force_compatibility_scheduler,)- final_output = state.results[final_for_id]- assert snapshot["execution_effects"]- assert final_output.output_collection == [11, 12]- assert snapshot["execution_refs"] == {}- assert restored.execution_tokens == {}- assert restored.execution_refs- assert restored.results[final_for_id].output_collection == [11, 12]- assert restored.results[final_for_id].final_state == final_output.final_state- assert sorted(- (effect.operation, effect.continuation_kind)- for effects in state.execution_effects.values()- for effect in effects- if effect.kind == "continuation"- ) == [("complete", "for"), ("complete", "for"), ("start", "for"), ("start", "for")]- assert restored.is_complete()+ assert trace == ["condition", "true_branch", "if", "sink"]+ assert set(state.source_prepared_mapping) == {"condition", "true_branch", "false_branch", "if", "sink"}+ assert "false_branch" not in trace+ assert not any(state.prepared_source_mapping[execution_id] == "false_branch" for execution_id in state.results)+ activation_tokens = [token for token in state.execution_tokens.values() if token.token_kind == "activation"]+ assert len(activation_tokens) == 1+ assert activation_tokens[0].port == "true_input"+ sink_id = next(iter(state.source_prepared_mapping["sink"]))+ assert state.results[sink_id].value == 6+ assert state.is_complete()-def test_legacy_flat_for_snapshot_uses_compatibility_scheduler() -> None:- _trace, partial_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph()),- stop_after=1,- )- snapshot = dump_execution_state(partial_state)- snapshot.pop("execution_state_version")- snapshot.pop("execution_effects")[email protected]("force_compatibility_scheduler", [False, True])+def test_fresh_flat_if_records_dependencies_without_author_graph_branch_analysis(+ force_compatibility_scheduler: bool,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh flat If used controller-owned branch analysis")- restored = load_execution_state(snapshot)- migrated = load_execution_state(dump_execution_state(restored))+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)- assert isinstance(restored._scheduler(), _ExecutionScheduler)- remaining_trace, restored = _run(restored)- migrated_trace, migrated = _run(migrated)- assert remaining_trace == ["body", "return", "for", "body", "return"]- assert migrated_trace == remaining_trace- assert restored.is_complete()- assert migrated.is_complete()- assert _final_for_output(restored).output_collection == [11, 12]- assert _final_for_output(migrated).output_collection == [11, 12]+ trace, state = _run_graph(+ GraphExecutionState(graph=_flat_if_graph()),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ assert trace == ["condition", "true_branch", "if", "sink"]+ true_branch_id = next(+ execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "true_branch"+ )+ assert [+ (dependency.owner_id, dependency.branch, dependency.frame)+ for dependency in state._if_activation_dependencies_by_exec[true_branch_id]+ ] == [("if", "true_input", ())]+ assert state.is_complete()-def test_terminal_legacy_flat_for_snapshot_can_be_resaved_and_reloaded() -> None:- _trace, state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph()))- snapshot = dump_execution_state(state)- snapshot.pop("execution_state_version")- snapshot.pop("execution_effects")- restored = load_execution_state(snapshot)- migrated = load_execution_state(dump_execution_state(restored))+ ("first_condition", "second_condition"),+ [(True, True), (True, False), (False, True), (False, False)],+)+def test_fresh_sibling_ifs_preserve_owner_local_selection_and_scheduler_parity(+ first_condition: bool,+ second_condition: bool,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh sibling If used controller-owned branch analysis")- assert restored.execution_effects == {}- assert migrated.is_complete()- assert _final_for_output(migrated).output_collection == [11, 12]+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ runs: list[tuple[list[str], GraphExecutionState]] = []+ for force_compatibility_scheduler in (False, True):+ state = GraphExecutionState(+ graph=_sibling_if_graph(first_condition=first_condition, second_condition=second_condition)+ )+ assert state._can_use_fresh_flat_if_activation()+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ runs.append((trace, state))-def test_failed_direct_completion_does_not_persist_a_reference() -> None:- graph = Graph()- graph.add_node(AddInvocation(id="add", a=1, b=2))- state = GraphExecutionState(graph=graph)- node = state.next()- assert isinstance(node, AddInvocation)- before = dump_execution_state(state)+ expected_sources = {+ "first_condition",+ "second_condition",+ "first_if",+ "second_if",+ "first_sink",+ "second_sink",+ }+ expected_sources.add("first_true" if first_condition else "first_false")+ expected_sources.add("second_true" if second_condition else "second_false")+ expected_sources.update({"first_true", "first_false", "second_true", "second_false"})+ assert set(state.source_prepared_mapping) == expected_sources+ assert {"first_true", "first_false", "second_true", "second_false"} <= set(trace)+ first_sink_id = next(iter(state.source_prepared_mapping["first_sink"]))+ second_sink_id = next(iter(state.source_prepared_mapping["second_sink"]))+ assert state.results[first_sink_id].value == (103 if first_condition else 111)+ assert state.results[second_sink_id].value == (204 if second_condition else 221)- with pytest.raises(TypeError, match="does not belong to execution node"):- state.complete(node.id, BooleanOutput(value=True))+ dependencies_by_source = {+ source_id: {+ (dependency.owner_id, dependency.branch, dependency.frame)+ for execution_id, source_id_value in state.prepared_source_mapping.items()+ if source_id_value == source_id+ for dependency in state._if_activation_dependencies_by_exec.get(execution_id, ())+ }+ for source_id in ("first_true", "first_false", "second_true", "second_false")+ }+ assert dependencies_by_source == {+ "first_true": {("first_if", "true_input", ())},+ "first_false": {("first_if", "false_input", ())},+ "second_true": {("second_if", "true_input", ())},+ "second_false": {("second_if", "false_input", ())},+ }+ assert state.is_complete()- assert dump_execution_state(state) == before+ assert runs[0][0] == runs[1][0]+ assert _state_projection(runs[0][1]) == _state_projection(runs[1][1])-def test_flat_for_fresh_execution_releases_after_loop_consumer() -> None:- generic_trace, generic_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph(with_after=True)),[email protected]("force_compatibility_scheduler", [False, True])+ ("first_condition", "second_condition"),+ [(True, True), (True, False), (False, True), (False, False)],+)[email protected]("stop_after", range(1, 8))+def test_fresh_sibling_ifs_checkpoint_resume_matches_fresh_execution(+ force_compatibility_scheduler: bool,+ first_condition: bool,+ second_condition: bool,+ stop_after: int,+) -> None:+ graph = _sibling_if_graph(first_condition=first_condition, second_condition=second_condition)+ expected_trace, expected_state = _run_graph(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=force_compatibility_scheduler,)- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph(with_after=True)),- force_compatibility_scheduler=True,+ checkpoint_trace, checkpoint_state = _run_graph(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after=stop_after,)- assert generic_trace == compatibility_trace == ["for", "body", "return", "for", "body", "return", "after"]- after_id = next(- exec_node_id- for exec_node_id, source_node_id in generic_state.prepared_source_mapping.items()- if source_node_id == "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 generic_state.results[after_id].value == [11, 12]- assert compatibility_state.results[- next(- exec_node_id- for exec_node_id, source_node_id in compatibility_state.prepared_source_mapping.items()- if source_node_id == "after"- )- ].value == [11, 12]- assert _state_projection(generic_state) == _state_projection(compatibility_state)- _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)++ assert Counter(checkpoint_trace + resumed_trace) == Counter(expected_trace)+ _assert_state_projection_matches_ignoring_execution_order(resumed_state, expected_state)+ assert _activation_projection(resumed_state) == _activation_projection(expected_state)+ assert resumed_state.is_complete()-def test_flat_for_none_output_matches_compatibility_scheduler() -> None:- graph = _flat_for_graph(collection=[None, None], body_returns_none=True)- generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph.model_copy(deep=True)))- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=graph.model_copy(deep=True)),- force_compatibility_scheduler=True,+ ("first_condition", "second_condition"),+ [(True, True), (True, False), (False, True), (False, False)],+)+def test_fresh_sibling_ifs_shared_ancestor_executes_once(+ first_condition: bool,+ second_condition: bool,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh sibling If used controller-owned branch analysis")++ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ trace, state = _run_graph(+ GraphExecutionState(+ graph=_sibling_if_graph(+ first_condition=first_condition,+ second_condition=second_condition,+ with_shared_ancestor=True,+ )+ ))- assert generic_trace == compatibility_trace == ["for", "body", "return", "for", "body", "return"]- assert _final_for_output(generic_state).output_collection == [None, None]- assert _final_for_output(compatibility_state).output_collection == [None, None]- assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert _execution_identity_projection(generic_state) == _execution_identity_projection(compatibility_state)- _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)+ assert trace.count("shared") == 1+ assert state.is_complete()-def test_flat_for_apply_path_matches_compatibility_scheduler() -> None:- generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph(with_after=True)))- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph(with_after=True)),- force_compatibility_scheduler=True,- )+ ("first_condition", "second_condition", "third_condition"),+ [+ (True, True, True),+ (True, True, False),+ (True, False, True),+ (True, False, False),+ (False, True, True),+ (False, True, False),+ (False, False, True),+ (False, False, False),+ ],+)+def test_fresh_three_sibling_ifs_run_owner_local_branches_and_match_compatibility(+ first_condition: bool,+ second_condition: bool,+ third_condition: bool,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh three-sibling If used controller-owned branch analysis")- assert generic_trace == compatibility_trace == ["for", "body", "return", "for", "body", "return", "after"]- assert _state_projection(generic_state) == _state_projection(compatibility_state)- assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)- _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)- for state in (generic_state, compatibility_state):- after_id = next(- execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "after"- )- assert state.results[after_id].value == [11, 12]- assert _final_for_output(state).output_collection == [11, 12]+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ runs: list[tuple[list[str], GraphExecutionState]] = []- continuations = sorted(- state._generic_runtime().continuations.values(), key=lambda continuation: continuation.frame.iteration_path- )- assert [- (- state.prepared_source_mapping[continuation.owner_id],- continuation.kind,- continuation.status,- tuple(continuation.frame.iteration_path),- continuation.frame.state_id,- continuation.frame.workflow_call_depth,- )- for continuation in continuations- ] == [- ("for", "for", "completed", (0,), state.id, 0),- ("for", "for", "completed", (1,), state.id, 0),- ]- continuation_effects = sorted(- (- state.prepared_source_mapping[effect.execution_ref.node_id],- effect.operation,- effect.continuation_kind,- tuple(effect.execution_ref.frame),+ for force_compatibility_scheduler in (False, True):+ state = GraphExecutionState(+ graph=_three_sibling_if_graph(+ first_condition=first_condition,+ second_condition=second_condition,+ third_condition=third_condition,)- for effects in state.execution_effects.values()- for effect in effects- if effect.kind == "continuation")- assert continuation_effects == [- ("for", "start", "for", (0,)),- ("for", "start", "for", (1,)),- ("return", "complete", "for", (0,)),- ("return", "complete", "for", (1,)),- ]+ assert state._can_use_fresh_flat_if_activation()+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ runs.append((trace, state))++ branch_sources = {"first_true", "first_false", "second_true", "second_false", "third_true", "third_false"}+ expected_sources = {+ "first_condition",+ "second_condition",+ "third_condition",+ "first_if",+ "second_if",+ "third_if",+ "first_sink",+ "second_sink",+ "third_sink",+ *branch_sources,+ }+ assert set(state.source_prepared_mapping) == expected_sources+ assert branch_sources <= set(trace)++ dependencies_by_source = {+ source_id: {+ (dependency.owner_id, dependency.branch, dependency.frame)+ for execution_id, source_id_value in state.prepared_source_mapping.items()+ if source_id_value == source_id+ for dependency in state._if_activation_dependencies_by_exec.get(execution_id, ())+ }+ for source_id in branch_sources+ }+ assert dependencies_by_source == {+ "first_true": {("first_if", "true_input", ())},+ "first_false": {("first_if", "false_input", ())},+ "second_true": {("second_if", "true_input", ())},+ "second_false": {("second_if", "false_input", ())},+ "third_true": {("third_if", "true_input", ())},+ "third_false": {("third_if", "false_input", ())},+ }+ first_sink_id = next(iter(state.source_prepared_mapping["first_sink"]))+ second_sink_id = next(iter(state.source_prepared_mapping["second_sink"]))+ third_sink_id = next(iter(state.source_prepared_mapping["third_sink"]))+ assert state.results[first_sink_id].value == (103 if first_condition else 111)+ assert state.results[second_sink_id].value == (204 if second_condition else 221)+ assert state.results[third_sink_id].value == (305 if third_condition else 331)+ 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])-def test_flat_for_apply_partial_rehydration_preserves_continuation_runtime() -> None:- graph = _flat_for_graph(with_after=True, collection=[None, None], body_returns_none=True)- resumed_projections: list[tuple[Any, ...]] = []- for force_compatibility_scheduler in (False, True):- expected_trace, expected_state = _run_graph_with_effects(- GraphExecutionState(graph=graph.model_copy(deep=True)),- force_compatibility_scheduler=force_compatibility_scheduler,- )- partial_trace, partial_state = _run_graph_with_effects(- GraphExecutionState(graph=graph.model_copy(deep=True)),- force_compatibility_scheduler=force_compatibility_scheduler,- stop_after_source="return",- )- restored = load_execution_state(dump_execution_state(partial_state))- if force_compatibility_scheduler:- _restore_compatibility_scheduler(restored)+def test_fresh_three_sibling_ifs_shared_ancestor_executes_once_without_cross_owner_dependencies(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh three-sibling If used controller-owned branch analysis")- assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)- # Rehydration reconstructs references for all prepared nodes, while the partial in-memory- # state only has references for nodes reached so far. Compare the durable token/effect projection.- assert _execution_token_projection(restored) == _execution_token_projection(partial_state)- _assert_execution_identity_consistent(restored)- assert any(- (effect.get("kind") if isinstance(effect, dict) else effect.kind) == "continuation"- and (effect.get("operation") if isinstance(effect, dict) else effect.operation) == "complete"- and (effect.get("payload") if isinstance(effect, dict) else effect.payload)- == {"output": None, "state": None, "continue_condition": True}- for effects in restored.execution_effects.values()- for effect in effects- )+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ runs: list[tuple[list[str], GraphExecutionState]] = []- remaining_trace, resumed_state = _run_graph_with_effects(- restored,- force_compatibility_scheduler=force_compatibility_scheduler,- )+ for force_compatibility_scheduler in (False, True):+ state = GraphExecutionState(graph=_three_sibling_if_graph(with_shared_ancestor=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 partial_trace + remaining_trace == expected_trace- assert _state_projection(resumed_state) == _state_projection(expected_state)- assert _continuation_projection(resumed_state) == _continuation_projection(expected_state)- assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)- assert _execution_token_projection(resumed_state) == _execution_token_projection(expected_state)- assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)- assert _final_for_output(resumed_state).output_collection == [None, None]- _assert_execution_identity_consistent(resumed_state)- if force_compatibility_scheduler:- assert isinstance(resumed_state._execution_scheduler, _ExecutionScheduler)- else:- assert isinstance(resumed_state._execution_scheduler, _GenericGraphSchedulerAdapter)- resumed_projections.append(- (- _state_projection(resumed_state),- _continuation_projection(resumed_state),- _effect_ledger_projection(resumed_state),- _execution_identity_projection(resumed_state),+ assert trace.count("shared") == 1+ assert state.results[next(iter(state.source_prepared_mapping["first_sink"]))].value == 105+ assert state.results[next(iter(state.source_prepared_mapping["second_sink"]))].value == 206+ assert state.results[next(iter(state.source_prepared_mapping["third_sink"]))].value == 307+ assert state.is_complete()++ for source_id, if_id, branch in (+ ("first_true", "first_if", "true_input"),+ ("second_true", "second_if", "true_input"),+ ("third_true", "third_if", "true_input"),+ ):+ execution_id = next(+ execution_id+ for execution_id, prepared_source_id in state.prepared_source_mapping.items()+ if prepared_source_id == source_id)- )+ assert {+ (dependency.owner_id, dependency.branch, dependency.frame)+ for dependency in state._if_activation_dependencies_by_exec[execution_id]+ } == {(if_id, branch, ())}- assert resumed_projections[0] == resumed_projections[1]+ _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])- ("fail_source_id", "expected_trace"),- [- ("body", ["for", "body"]),- ("return", ["for", "body", "return"]),- ],-)-def test_flat_for_failure_matches_compatibility_scheduler(fail_source_id: str, expected_trace: list[str]) -> None:- generic_trace, generic_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph()),- fail_source_id=fail_source_id,- )- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph()),- force_compatibility_scheduler=True,- fail_source_id=fail_source_id,- )[email protected]("first_condition", [False, True])[email protected]("second_condition", [False, True])[email protected]("third_condition", [False, True])[email protected]("fourth_condition", [False, True])+def test_fresh_four_sibling_ifs_match_compatibility_for_all_polarities(+ first_condition: bool,+ second_condition: bool,+ third_condition: bool,+ fourth_condition: bool,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh four-sibling If used controller-owned branch analysis")- assert generic_trace == compatibility_trace == expected_trace- for state in (generic_state, compatibility_state):- assert state.next() is None- assert {- state.prepared_source_mapping.get(node_id, node_id): message for node_id, message in state.errors.items()- } == {fail_source_id: "injected failure"}+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ graph = _four_sibling_if_graph(+ first_condition=first_condition,+ second_condition=second_condition,+ third_condition=third_condition,+ fourth_condition=fourth_condition,+ )+ 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))+ branch_sources = {+ "first_true",+ "first_false",+ "second_true",+ "second_false",+ "third_true",+ "third_false",+ "fourth_true",+ "fourth_false",+ }assert state.is_complete()- assert sum(len(effects) for effects in state.execution_effects.values()) == 1- assert all(item.status == "running" for item in state._generic_runtime().continuations.values())- _assert_execution_identity_consistent(state)- restored = load_execution_state(dump_execution_state(state))- if isinstance(state._execution_scheduler, _ExecutionScheduler):- _restore_compatibility_scheduler(restored)- assert _effect_ledger_projection(restored) == _effect_ledger_projection(state)- assert _continuation_projection(restored) == _continuation_projection(state)- _assert_execution_identity_consistent(restored)- assert {- state.prepared_source_mapping.get(node_id, node_id): message for node_id, message in restored.errors.items()- } == {fail_source_id: "injected failure"}- assert restored.next() is None- assert restored.is_complete()- if isinstance(state._execution_scheduler, _ExecutionScheduler):- assert isinstance(restored._execution_scheduler, _ExecutionScheduler)- else:- assert restored._execution_scheduler is None- assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert branch_sources <= set(trace)+ for sink_id, expected in (+ ("first_sink", 103 if first_condition else 111),+ ("second_sink", 204 if second_condition else 221),+ ("third_sink", 305 if third_condition else 331),+ ("fourth_sink", 406 if fourth_condition else 441),+ ):+ sink_exec_id = next(iter(state.source_prepared_mapping[sink_id]))+ assert state.results[sink_exec_id].value == expected+ _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]("stop_after_source", ["for", "body"])-def test_flat_for_partial_rehydration_matches_compatibility_scheduler(stop_after_source: str) -> None:- graph = _flat_for_graph()- expected_trace, expected_state = _run_graph_with_effects(GraphExecutionState(graph=graph.model_copy(deep=True)))- resumed_projections: list[tuple[Any, ...]] = []- for force_compatibility_scheduler in (False, True):- partial_trace, partial_state = _run_graph_with_effects(- GraphExecutionState(graph=graph.model_copy(deep=True)),- stop_after_source=stop_after_source,- force_compatibility_scheduler=force_compatibility_scheduler,- )- snapshot = dump_execution_state(partial_state)- restored = load_execution_state(snapshot)- if force_compatibility_scheduler:- _restore_compatibility_scheduler(restored)[email protected]("force_compatibility_scheduler", [False, True])[email protected]("stop_after", [1, 4, 5, 8, 9, 12])+def test_fresh_four_sibling_ifs_checkpoint_resume_matches_fresh_execution(+ force_compatibility_scheduler: bool,+ stop_after: int,+) -> None:+ graph = _four_sibling_if_graph(+ first_condition=True,+ second_condition=False,+ third_condition=True,+ fourth_condition=False,+ )+ expected_trace, expected_state = _run_graph(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ checkpoint_trace, checkpoint_state = _run_graph(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after=stop_after,+ )- remaining_trace, resumed_state = _run_graph_with_effects(- restored,- force_compatibility_scheduler=force_compatibility_scheduler,- )+ 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 partial_trace + remaining_trace == expected_trace- assert _state_projection(resumed_state) == _state_projection(expected_state)- # Rehydration reconstructs durable execution references for all prepared nodes; a fresh- # in-memory run does not retain those references after terminal cleanup. Compare durable- # token/effect state and continuation records instead.- assert _execution_token_projection(resumed_state) == _execution_token_projection(expected_state)- assert _continuation_projection(resumed_state) == _continuation_projection(expected_state)- assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)- _assert_execution_identity_consistent(resumed_state)- if force_compatibility_scheduler:- assert isinstance(resumed_state._execution_scheduler, _ExecutionScheduler)- else:- assert isinstance(resumed_state._execution_scheduler, _GenericGraphSchedulerAdapter)- resumed_projections.append(- (- _state_projection(resumed_state),- _continuation_projection(resumed_state),- _effect_ledger_projection(resumed_state),- )- )+ assert Counter(checkpoint_trace + resumed_trace) == Counter(expected_trace)+ _assert_state_projection_matches_ignoring_execution_order(resumed_state, expected_state)+ assert _activation_projection(resumed_state) == _activation_projection(expected_state)+ assert resumed_state.is_complete()+++def test_fresh_four_sibling_ifs_shared_ancestor_executes_once_without_cross_owner_dependencies(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh four-sibling If used controller-owned branch analysis")++ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ graph = _four_sibling_if_graph(with_shared_ancestor=True)+ 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.count("shared") == 1+ assert state.is_complete()- assert resumed_projections[0] == resumed_projections[1]+ _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])-def test_flat_for_frame_and_continuation_identity_matches_compatibility_scheduler() -> None:- generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph()), stop_after=4)- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph()),- force_compatibility_scheduler=True,- stop_after=4,- )+def test_fresh_mixed_iterate_if_collect_uses_selected_branches_in_both_scheduler_routes() -> None:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="source", first=[True, False, True, False]))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(AnyTypeTestInvocation(id="true_branch"))+ graph.add_node(AnyTypeTestInvocation(id="false_branch"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("source", "collection", "iterate", "collection"))+ graph.add_edge(create_edge("iterate", "item", "if", "condition"))+ graph.add_edge(create_edge("iterate", "item", "true_branch", "value"))+ graph.add_edge(create_edge("iterate", "item", "false_branch", "value"))+ graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))+ graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "collect", "item"))- assert generic_trace == compatibility_trace == ["for", "body", "return", "for"]- assert _execution_identity_projection(generic_state) == _execution_identity_projection(compatibility_state)- assert _continuation_projection(generic_state) == _continuation_projection(compatibility_state)- _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)- for state in (generic_state, compatibility_state):- continuations = sorted(- state._generic_runtime().continuations.values(), key=lambda item: item.frame.iteration_path- )- assert len(continuations) == 2- assert [tuple(item.frame.iteration_path) for item in continuations] == [(0,), (1,)]- assert {state.prepared_source_mapping[item.owner_id] for item in continuations} == {"for"}- assert {item.frame.state_id for item in continuations} == {state.id}- assert {item.frame.workflow_call_depth for item in continuations} == {0}- frame_ids = [item.frame.frame_id for item in continuations]- assert all(frame_ids)- assert len(set(frame_ids)) == len(frame_ids)- assert all(- item.frame.model_dump(mode="json")- == state._expected_execution_ref(item.owner_id).frame.model_dump(mode="json")- for item in continuations+ runs: list[tuple[list[str], GraphExecutionState]] = []+ for force_compatibility_scheduler in (False, True):+ state = GraphExecutionState(graph=graph.model_copy(deep=True))+ assert state._is_fresh_lazy_if_candidate("if")+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ runs.append((trace, state))++ assert trace[0] == "source"+ assert trace[-1] == "collect"+ assert trace.count("iterate") == 4+ assert trace.count("true_branch") == 2+ assert trace.count("false_branch") == 2+ assert trace.count("if") == 4+ assert state.executed_history[-1] == "collect"+ assert set(state.executed_history) == {"source", "iterate", "true_branch", "false_branch", "if", "collect"}+ assert state.results[next(iter(state.source_prepared_mapping["collect"]))].collection == [+ True,+ False,+ True,+ False,+ ]+ activation_tokens = sorted(+ (token for token in state.execution_tokens.values() if token.token_kind == "activation"),+ key=lambda token: token.frame.iteration_path,)- assert [item.status for item in continuations] == ["completed", "running"]- _assert_execution_identity_consistent(state)+ assert [token.port for token in activation_tokens] == [+ "true_input",+ "false_input",+ "true_input",+ "false_input",+ ]+ assert state.is_complete()- generic_frames = {item.frame.frame_id for item in generic_state._generic_runtime().continuations.values()}- compatibility_frames = {- item.frame.frame_id for item in compatibility_state._generic_runtime().continuations.values()- }- assert generic_frames.isdisjoint(compatibility_frames)+ assert runs[0][0] == runs[1][0]+ assert _state_projection(runs[0][1]) == _state_projection(runs[1][1])- other_trace, other_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph()), stop_after=4)- assert other_trace == generic_trace- other_frames = {item.frame.frame_id for item in other_state._generic_runtime().continuations.values()}- generic_frames = {item.frame.frame_id for item in generic_state._generic_runtime().continuations.values()}- assert other_frames.isdisjoint(generic_frames)[email protected](("condition", "branch"), [(True, "true:"), (False, "false:")])+def test_constant_if_inside_iterate_routes_each_loop_item(condition: bool, branch: str) -> None:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="source", first=[1, 2]))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(IfInvocation(id="if", condition=condition))+ graph.add_node(MarkedAnyTypeTestInvocation(id="true_branch", marker="true:"))+ graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="false:"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("source", "collection", "iterate", "collection"))+ graph.add_edge(create_edge("iterate", "item", "true_branch", "value"))+ graph.add_edge(create_edge("iterate", "item", "false_branch", "value"))+ graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))+ graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "collect", "item"))-def test_empty_literal_flat_for_uses_generic_scheduler() -> None:- state = GraphExecutionState(graph=_flat_for_graph(collection=[]))+ trace, state = _run_graph(GraphExecutionState(graph=graph))- assert state._can_use_generic_scheduler()- assert isinstance(state._scheduler(), _GenericGraphSchedulerAdapter)+ selected_source = "true_branch" if condition else "false_branch"+ unselected_source = "false_branch" if condition else "true_branch"+ assert trace[0] == "source"+ assert trace[-1] == "collect"+ assert trace.count("iterate") == 2+ assert trace.count(selected_source) == 2+ assert trace.count("if") == 2+ assert trace.count(unselected_source) == 2+ collect_id = next(iter(state.source_prepared_mapping["collect"]))+ assert state.results[collect_id].collection == [f"{branch}1", f"{branch}2"]+ assert state.is_complete()+ assert state.next() is None+ assert not state._ready_node_ids+ assert all(not queue for queue in state._ready_queues.values())-def test_empty_literal_flat_for_matches_compatibility_scheduler() -> None:- generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph(collection=[])))- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph(collection=[])),- force_compatibility_scheduler=True,- )[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_selected_if_frame_cache_tracks_branch_resolution_and_restore(force_compatibility_scheduler: bool) -> None:+ graph = Graph()+ for node in (+ CollectionConcatInvocation(id="source", first=[2, 1]),+ IterateInvocation(id="items"),+ AddInvocation(id="condition_value", b=-1),+ FixedCollectionTestInvocation(id="condition"),+ AnyTypeTestInvocation(id="true_value", value="T"),+ AnyTypeTestInvocation(id="false_value", value="F"),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ):+ graph.add_node(node)+ for source, source_field, destination, destination_field in (+ ("source", "collection", "items", "collection"),+ ("items", "item", "condition_value", "a"),+ ("condition_value", "value", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("true_value", "value", "if", "true_input"),+ ("false_value", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- assert generic_trace == compatibility_trace == []- assert _final_for_output(generic_state).output_collection == []- assert _final_for_output(compatibility_state).output_collection == []- assert generic_state.is_complete()- assert compatibility_state.is_complete()- assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)- assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)- assert _state_projection(generic_state) == _state_projection(compatibility_state)+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)++ trace: list[str] = []+ selected_true_frames: set[tuple[int, ...]] = set()+ if_frames_seen = 0+ while (node := state.next()) is not None:+ source_id = state.prepared_source_mapping[node.id]+ trace.append(source_id)+ if source_id == "condition":+ assert set(graph_if_runtime._get_selected_if_frames_for_preparation(state, "if", "true_input")) == (+ selected_true_frames+ )+ elif source_id == "if":+ if_frames_seen += 1+ iteration_path = state._get_iteration_path(node.id)+ expected_selected_frames = selected_true_frames | ({iteration_path} if node.condition else set())+ assert set(graph_if_runtime._get_selected_if_frames_for_preparation(state, "if", "true_input")) == (+ expected_selected_frames+ )+ output = node.invoke(Mock())+ state.complete(node.id, output)+ if source_id == "condition":+ assert set(graph_if_runtime._get_selected_if_frames_for_preparation(state, "if", "true_input")) == (+ selected_true_frames+ )+ elif source_id == "if" and node.condition:+ selected_true_frames.add(iteration_path)+ assert state.is_complete(), f"graph stalled after {trace}"+ assert if_frames_seen == 2+ assert state.results[next(iter(state.source_prepared_mapping["collect"]))].collection == ["T", "F"]-def test_input_driven_empty_flat_for_uses_generic_scheduler_and_exact_terminal_semantics() -> None:- state = GraphExecutionState(graph=_flat_for_graph(input_collection=[]))+ restored = load_execution_state(dump_execution_state(state))+ assert (+ set(graph_if_runtime._get_selected_if_frames_for_preparation(restored, "if", "true_input"))+ == selected_true_frames+ )- assert state._can_use_generic_scheduler()- trace, state = _run_graph_with_effects(state)- assert trace == ["collection"]- assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)- final_output = _final_for_output(state)- assert final_output.item is None- assert final_output.index == -1- assert final_output.total == 0- assert final_output.state == LoopState()- assert final_output.output_collection == []- assert final_output.final_state == LoopState()- assert "body" not in state.source_prepared_mapping- assert "return" not in state.source_prepared_mapping- assert state.is_complete()- assert list(state._generic_runtime().continuations.values()) == []- _assert_execution_identity_consistent(state)[email protected](("condition", "branch"), [(True, "true:"), (False, "false:")])+def test_constant_if_inside_for_routes_each_loop_item(condition: bool, branch: str) -> None:+ graph = Graph()+ graph.add_node(ForInvocation(id="for", collection=[1, 2]))+ graph.add_node(IfInvocation(id="if", condition=condition))+ graph.add_node(MarkedAnyTypeTestInvocation(id="true_branch", marker="true:"))+ graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="false:"))+ graph.add_node(ForReturnInvocation(id="return"))+ graph.add_edge(create_edge("for", "item", "true_branch", "value"))+ graph.add_edge(create_edge("for", "item", "false_branch", "value"))+ graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))+ graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "return", "output"))+ graph.add_edge(create_loop_linkage("for", "return"))+ trace, state = _run_graph(GraphExecutionState(graph=graph))-def test_input_driven_empty_flat_for_matches_compatibility_scheduler() -> None:- generic_trace, generic_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph(input_collection=[]))- )- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph(input_collection=[])),- force_compatibility_scheduler=True,+ selected_source = "true_branch" if condition else "false_branch"+ unselected_source = "false_branch" if condition else "true_branch"+ assert trace.count("for") == 2+ assert trace.count(selected_source) == 2+ assert trace.count("if") == 2+ assert trace.count("return") == 2+ assert trace.count(unselected_source) == 2+ assert sorted(state._get_iteration_path(exec_node_id) for exec_node_id in state.source_prepared_mapping["if"]) == [+ (0,),+ (1,),+ ]+ final_for_id = max(+ state.source_prepared_mapping["for"],+ key=lambda exec_node_id: state.execution_graph.get_node(exec_node_id).index,)-- assert generic_trace == compatibility_trace == ["collection"]- assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)- assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)- assert _state_projection(generic_state) == _state_projection(compatibility_state)- _assert_execution_identity_consistent(generic_state)- _assert_execution_identity_consistent(compatibility_state)+ assert state.results[final_for_id].output_collection == [f"{branch}1", f"{branch}2"]+ assert state.is_complete()+ assert state.next() is None+ assert not state._ready_node_ids+ assert all(not queue for queue in state._ready_queues.values())-def test_input_driven_empty_flat_for_checkpoint_after_producer_does_not_replay() -> None:- expected_trace, expected_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph(input_collection=[]))- )- partial_trace, partial_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph(input_collection=[])),- stop_after_source="collection",- )[email protected](("condition", "branch"), [(True, "true:"), (False, "false:")])+def test_external_condition_if_inside_iterate_routes_each_loop_item(condition: bool, branch: str) -> None:+ graph = Graph()+ graph.add_node(BooleanInvocation(id="condition", value=condition))+ graph.add_node(CollectionConcatInvocation(id="source", first=[1, 2]))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(MarkedAnyTypeTestInvocation(id="true_branch", marker="true:"))+ graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="false:"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("condition", "value", "if", "condition"))+ graph.add_edge(create_edge("source", "collection", "iterate", "collection"))+ graph.add_edge(create_edge("iterate", "item", "true_branch", "value"))+ graph.add_edge(create_edge("iterate", "item", "false_branch", "value"))+ graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))+ graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "collect", "item"))- restored = load_execution_state(dump_execution_state(partial_state))- resumed_trace, restored = _run_graph_with_effects(restored)- terminal_reload = load_execution_state(dump_execution_state(restored))+ trace, state = _run_graph(GraphExecutionState(graph=graph))- assert expected_trace == partial_trace == ["collection"]- assert resumed_trace == []- assert isinstance(restored._execution_scheduler, _GenericGraphSchedulerAdapter)- assert _state_projection(restored) == _state_projection(expected_state)- assert terminal_reload.is_complete()- assert _state_projection(terminal_reload) == _state_projection(restored)- assert _final_for_output(terminal_reload).output_collection == []- _assert_execution_identity_consistent(restored)- _assert_execution_identity_consistent(terminal_reload)+ selected_source = "true_branch" if condition else "false_branch"+ unselected_source = "false_branch" if condition else "true_branch"+ assert trace.count("condition") == 1+ assert trace.count("source") == 1+ assert trace.count("iterate") == 2+ assert trace.count(selected_source) == 2+ assert trace.count("if") == 2+ assert trace.count("collect") == 1+ assert trace.count(unselected_source) == 2+ assert sorted(state._get_iteration_path(exec_node_id) for exec_node_id in state.source_prepared_mapping["if"]) == [+ (0,),+ (1,),+ ]+ collect_id = next(iter(state.source_prepared_mapping["collect"]))+ assert state.results[collect_id].collection == [f"{branch}1", f"{branch}2"]+ assert state.is_complete()+ assert state.next() is None+ assert not state._pending_if_exec_nodes+ assert not state._ready_node_ids+ assert all(not queue for queue in state._ready_queues.values())-def test_input_driven_empty_flat_for_with_downstream_remains_compatibility_owned() -> None:- state = GraphExecutionState(graph=_flat_for_graph(input_collection=[], with_after=True))[email protected](("condition", "branch"), [(True, "true:"), (False, "false:")])+def test_external_condition_if_inside_for_routes_each_loop_item(condition: bool, branch: str) -> None:+ graph = Graph()+ graph.add_node(BooleanInvocation(id="condition", value=condition))+ graph.add_node(ForInvocation(id="for", collection=[1, 2]))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(MarkedAnyTypeTestInvocation(id="true_branch", marker="true:"))+ graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="false:"))+ graph.add_node(ForReturnInvocation(id="return"))+ graph.add_edge(create_edge("condition", "value", "if", "condition"))+ graph.add_edge(create_edge("for", "item", "true_branch", "value"))+ graph.add_edge(create_edge("for", "item", "false_branch", "value"))+ graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))+ graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "return", "output"))+ graph.add_edge(create_loop_linkage("for", "return"))- assert state._can_use_generic_scheduler() is False- assert isinstance(state._scheduler(), _ExecutionScheduler)+ trace, state = _run_graph(GraphExecutionState(graph=graph))+ selected_source = "true_branch" if condition else "false_branch"+ unselected_source = "false_branch" if condition else "true_branch"+ assert trace.count("condition") == 1+ assert trace.count("for") == 2+ assert trace.count(selected_source) == 2+ assert trace.count("if") == 2+ assert trace.count("return") == 2+ assert trace.count(unselected_source) == 2+ assert sorted(state._get_iteration_path(exec_node_id) for exec_node_id in state.source_prepared_mapping["if"]) == [+ (0,),+ (1,),+ ]+ final_for_id = max(+ state.source_prepared_mapping["for"],+ key=lambda exec_node_id: state.execution_graph.get_node(exec_node_id).index,+ )+ assert state.results[final_for_id].output_collection == [f"{branch}1", f"{branch}2"]+ assert state.is_complete()+ assert state.next() is None+ assert not state._pending_if_exec_nodes+ assert not state._ready_node_ids+ assert all(not queue for queue in state._ready_queues.values())-def test_input_driven_empty_flat_for_with_index_body_edge_remains_compatibility_owned() -> None:- graph = _flat_for_graph(input_collection=[])- body_edge = next(edge for edge in graph.edges if edge.destination.node_id == "body")- graph.delete_edge(body_edge)- graph.add_edge(create_edge("for", "index", "body", body_edge.destination.field))- state = GraphExecutionState(graph=graph)[email protected]("force_compatibility_scheduler", [False, True])+ ("first_condition", "second_condition", "third_condition"),+ [+ (True, True, True),+ (True, True, False),+ (True, False, True),+ (True, False, False),+ (False, True, True),+ (False, True, False),+ (False, False, True),+ (False, False, False),+ ],+)[email protected]("stop_after", range(1, 12))+def test_fresh_three_sibling_ifs_checkpoint_resume_matches_fresh_execution(+ force_compatibility_scheduler: bool,+ first_condition: bool,+ second_condition: bool,+ third_condition: bool,+ stop_after: int,+) -> None:+ graph = _three_sibling_if_graph(+ first_condition=first_condition,+ second_condition=second_condition,+ third_condition=third_condition,+ )+ expected_trace, expected_state = _run_graph(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ checkpoint_trace, checkpoint_state = _run_graph(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after=stop_after,+ )- assert state._can_use_generic_scheduler() is False+ 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 Counter(checkpoint_trace + resumed_trace) == Counter(expected_trace)+ _assert_state_projection_matches_ignoring_execution_order(resumed_state, expected_state)+ assert _activation_projection(resumed_state) == _activation_projection(expected_state)+ assert resumed_state.is_complete()-def test_input_driven_empty_flat_for_with_wrong_return_edge_remains_compatibility_owned() -> None:- graph = _flat_for_graph(input_collection=[])- graph.delete_node("body")- graph.add_node(StateSetInvocation(id="body"))- graph.add_edge(create_edge("for", "item", "body", "value"))- graph.add_edge(create_edge("body", "state", "return", "state"))+def test_sibling_if_unsupported_saved_workflow_keeps_controller_fallback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ graph = _sibling_if_graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call", workflow_id="saved-workflow"))state = GraphExecutionState(graph=graph)+ branch_analysis_calls: list[tuple[str, str]] = []+ original_branch_sources = graph_module._IfActivationController._branch_sources- assert state._can_use_generic_scheduler() is False+ 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)-def test_input_driven_flat_for_uses_generic_scheduler() -> None:- state = GraphExecutionState(graph=_flat_for_graph(input_collection=[3, 7]))+ assert not state._can_use_fresh_flat_if_activation()+ dependencies = state._get_source_activation_dependencies("first_true", (7,))+ assert {dependency.owner_id for dependency in dependencies} == {"first_if"}+ assert branch_analysis_calls- assert state._can_use_generic_scheduler()- assert isinstance(state._scheduler(), _GenericGraphSchedulerAdapter)+def test_indirectly_connected_sibling_ifs_eagerly_run_private_branch_sources() -> None:+ runs: list[GraphExecutionState] = []+ for force_compatibility_scheduler in (False, True):+ trace, state = _run_graph(+ GraphExecutionState(graph=_indirectly_connected_sibling_if_graph()),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ assert {"first_true", "first_false", "bridge", "second_false"}.issubset(trace)+ assert state.is_complete()+ assert state.results[next(iter(state.source_prepared_mapping["second_sink"]))].value == 208+ runs.append(state)-def test_input_driven_flat_for_matches_compatibility_scheduler() -> None:- generic_trace, generic_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph(input_collection=[3, 7]))- )- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_graph(input_collection=[3, 7])),- force_compatibility_scheduler=True,- )+ _assert_state_projection_matches_ignoring_execution_order(runs[0], runs[1])- assert (- generic_trace- == compatibility_trace- == [- "collection",- "for",- "body",- "return",- "for",- "body",- "return",- ]+[email protected]("force_compatibility_scheduler", [False, True])+ ("outer_condition", "inner_condition", "expected_trace"),+ [+ (+ True,+ True,+ ["outer_condition", "inner_condition", "inner_true", "inner_if", "outer_if", "sink"],+ ),+ (+ True,+ False,+ ["outer_condition", "inner_condition", "inner_false", "inner_if", "outer_if", "sink"],+ ),+ (False, True, ["outer_condition", "outer_false", "outer_if", "sink"]),+ (False, False, ["outer_condition", "outer_false", "outer_if", "sink"]),+ ],+)+def test_fresh_nested_if_records_graph_state_dependencies_without_controller_analysis(+ force_compatibility_scheduler: bool,+ outer_condition: bool,+ inner_condition: bool,+ expected_trace: list[str],+) -> None:+ graph = _nested_if_graph()+ graph.get_node("outer_condition").value = outer_condition+ graph.get_node("inner_condition").value = inner_condition+ state = GraphExecutionState(graph=graph)+ dependencies_by_source = {+ source_id: {+ (dependency.owner_id, dependency.branch, dependency.frame)+ for dependency in state._get_source_activation_dependencies(source_id)+ }+ for source_id in {"inner_condition", "inner_true", "inner_false", "inner_if"}+ }++ trace, state = _run_graph(+ state,+ force_compatibility_scheduler=force_compatibility_scheduler,)- assert _final_for_output(generic_state).output_collection == [13, 17]- assert _final_for_output(compatibility_state).output_collection == [13, 17]- assert generic_state.is_complete()- assert compatibility_state.is_complete()- assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)- assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)- assert _state_projection(generic_state) == _state_projection(compatibility_state)- restored_generic = load_execution_state(dump_execution_state(generic_state))- restored_compatibility = load_execution_state(dump_execution_state(compatibility_state))- _restore_compatibility_scheduler(restored_compatibility)- assert isinstance(restored_generic._scheduler(), _GenericGraphSchedulerAdapter)- assert isinstance(restored_compatibility._execution_scheduler, _ExecutionScheduler)- assert _state_projection(restored_generic) == _state_projection(generic_state)- assert _state_projection(restored_compatibility) == _state_projection(compatibility_state)- _assert_execution_identity_consistent(restored_generic)- _assert_execution_identity_consistent(restored_compatibility)+ branch_sources = {+ edge.source.node_id+ for edge in graph.edges+ if edge.destination.node_id in {"inner_if", "outer_if"}+ and edge.destination.field in {"true_input", "false_input"}+ }+ assert set(expected_trace).issubset(trace)+ assert branch_sources.issubset(trace)+ assert state.results[next(iter(state.source_prepared_mapping["sink"]))].value == (+ 11 if not outer_condition else (5 if inner_condition else 7)+ )+ assert dependencies_by_source == {+ "inner_condition": {("outer_if", "true_input", ())},+ "inner_true": {("inner_if", "true_input", ())},+ "inner_false": {("inner_if", "false_input", ())},+ "inner_if": {("outer_if", "true_input", ())},+ }+ assert state.is_complete()@pytest.mark.parametrize(- ("continue_condition", "expected_trace", "expected_collection", "expected_state"),+ ("outer_condition", "middle_condition", "inner_condition", "selected", "expected_value", "expected_trace"),[- (True, ["for", "body", "return"] * 3, [1, 2, 3], {"count": 3}),- (False, ["for", "body", "return"], [1], {"count": 1}),+ (+ True,+ True,+ True,+ "inner_true",+ 5,+ [+ "outer_condition",+ "middle_condition",+ "inner_condition",+ "inner_true",+ "inner_if",+ "middle_if",+ "outer_if",+ "sink",+ ],+ ),+ (+ True,+ True,+ False,+ "inner_false",+ 7,+ [+ "outer_condition",+ "middle_condition",+ "inner_condition",+ "inner_false",+ "inner_if",+ "middle_if",+ "outer_if",+ "sink",+ ],+ ),+ (+ True,+ False,+ True,+ "middle_false",+ 11,+ ["outer_condition", "middle_condition", "middle_false", "middle_if", "outer_if", "sink"],+ ),+ (+ True,+ False,+ False,+ "middle_false",+ 11,+ ["outer_condition", "middle_condition", "middle_false", "middle_if", "outer_if", "sink"],+ ),+ (False, True, True, "outer_false", 21, ["outer_condition", "outer_false", "outer_if", "sink"]),+ (False, True, False, "outer_false", 21, ["outer_condition", "outer_false", "outer_if", "sink"]),+ (False, False, True, "outer_false", 21, ["outer_condition", "outer_false", "outer_if", "sink"]),+ (False, False, False, "outer_false", 21, ["outer_condition", "outer_false", "outer_if", "sink"]),],)-def test_flat_for_fresh_execution_matches_state_and_break_semantics(- continue_condition: bool,+def test_fresh_three_nested_ifs_select_only_branches_and_match_compatibility(+ outer_condition: bool,+ middle_condition: bool,+ inner_condition: bool,+ selected: str,+ expected_value: int,expected_trace: list[str],- expected_collection: list[int],- expected_state: dict[str, int],+ monkeypatch: pytest.MonkeyPatch,) -> None:- generic_trace, generic_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_state_graph(continue_condition)),- )- compatibility_trace, compatibility_state = _run_graph_with_effects(- GraphExecutionState(graph=_flat_for_state_graph(continue_condition)),- force_compatibility_scheduler=True,- )-- assert generic_trace == compatibility_trace == expected_trace- final_for_id = max(- (- exec_node_id- for exec_node_id, source_node_id in generic_state.prepared_source_mapping.items()- if source_node_id == "for"- ),- key=lambda exec_node_id: generic_state.execution_graph.get_node(exec_node_id).index,- )- final_for_output = generic_state.results[final_for_id]- assert final_for_output.output_collection == expected_collection- assert final_for_output.final_state == LoopState(values=expected_state)- assert _state_projection(generic_state) == _state_projection(compatibility_state)- _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)---def test_nested_if_checkpoint_restore_matches_compatibility_scheduler() -> None:- graph = _nested_if_graph()- expected_trace, expected_state = _run_graph(GraphExecutionState(graph=graph.model_copy(deep=True)))+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh three-nested If used controller-owned branch analysis")+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ runs: list[tuple[list[str], GraphExecutionState]] = []for force_compatibility_scheduler in (False, True):- checkpoint_trace, checkpoint_state = _run_graph(- GraphExecutionState(graph=graph.model_copy(deep=True)),- force_compatibility_scheduler=force_compatibility_scheduler,- stop_after=4,- )- restored = load_execution_state(dump_execution_state(checkpoint_state))- if force_compatibility_scheduler:- _restore_compatibility_scheduler(restored)- remaining_trace, restored_state = _run_graph(- restored,- force_compatibility_scheduler=force_compatibility_scheduler,+ state = GraphExecutionState(+ graph=_three_nested_if_graph(+ outer_condition=outer_condition,+ middle_condition=middle_condition,+ inner_condition=inner_condition,+ ))+ assert state._can_use_fresh_flat_if_activation()+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ runs.append((trace, state))- assert checkpoint_trace + remaining_trace == expected_trace- assert _state_projection(restored_state) == _state_projection(expected_state)- assert _activation_projection(restored_state) == _activation_projection(expected_state)- assert restored_state.is_complete()---def test_nested_if_failure_round_trip_matches_compatibility_scheduler() -> None:- expected_trace = ["outer_condition", "inner_condition", "inner_false"]- expected_errors = {"inner_false": "injected failure"}-- generic_trace, generic_state = _run_graph(- GraphExecutionState(graph=_nested_if_graph()),- fail_source_id="inner_false",- )- compatibility_trace, compatibility_state = _run_graph(- GraphExecutionState(graph=_nested_if_graph()),- force_compatibility_scheduler=True,- fail_source_id="inner_false",- )+ branch_producers = set(state.graph.nodes) & {+ "inner_true",+ "inner_false",+ "middle_true",+ "middle_false",+ "outer_true",+ "outer_false",+ }+ assert set(expected_trace).issubset(trace)+ assert branch_producers.issubset(trace)+ assert selected in trace+ sink_id = next(iter(state.source_prepared_mapping["sink"]))+ assert state.results[sink_id].value == expected_value+ assert state.is_complete()- assert generic_trace == compatibility_trace == expected_trace- assert generic_state.next() is None- assert compatibility_state.next() is None- for state in (generic_state, compatibility_state):- assert {- state.prepared_source_mapping.get(execution_id, execution_id): message- for execution_id, message in state.errors.items()- } == expected_errors- result_sources = {state.prepared_source_mapping[execution_id] for execution_id in state.results}- assert "inner_if" not in result_sources- assert "outer_if" not in result_sources- assert "sink" not in result_sources- assert _state_projection(generic_state) == _state_projection(compatibility_state)+ _assert_generic_and_compatibility_schedulers(runs[0][1], runs[1][1])+ assert Counter(runs[0][0]) == Counter(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])- restored_generic = load_execution_state(dump_execution_state(generic_state))- restored_compatibility = load_execution_state(dump_execution_state(compatibility_state))- _restore_compatibility_scheduler(restored_compatibility)- assert restored_generic.next() is None- assert restored_compatibility.next() is None- assert _state_projection(restored_generic) == _state_projection(restored_compatibility)[email protected]("middle_branch", ["true_input", "false_input"])[email protected]("outer_branch", ["true_input", "false_input"])+def test_fresh_three_nested_ifs_support_direct_false_parent_branch_edges(+ middle_branch: str,+ outer_branch: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh three-nested If used controller-owned branch analysis")-def test_static_dag_checkpoint_restore_has_matching_remaining_trace() -> None:- expected_trace, expected_state = _run(_load_fixture())+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ graph = _three_nested_if_graph(+ outer_condition=outer_branch == "true_input",+ middle_condition=middle_branch == "true_input",+ middle_branch=middle_branch,+ outer_branch=outer_branch,+ )+ runs: list[tuple[list[str], GraphExecutionState]] = []for force_compatibility_scheduler in (False, True):- checkpoint_trace, checkpoint_state = _run(- _load_fixture(),- force_compatibility_scheduler=force_compatibility_scheduler,- stop_after=1,- )- restored = load_execution_state(dump_execution_state(checkpoint_state))- remaining_trace, restored_state = _run(- restored,+ trace, state = _run_graph(+ GraphExecutionState(graph=graph.model_copy(deep=True)),force_compatibility_scheduler=force_compatibility_scheduler,)+ runs.append((trace, state))- assert checkpoint_trace + remaining_trace == expected_trace- assert restored_state.is_complete()- assert _state_projection(restored_state) == _state_projection(expected_state)--[email protected]("force_compatibility_scheduler", [False, True])-def test_inflight_checkpoint_replays_claimed_work_after_rehydrate(force_compatibility_scheduler: bool) -> None:- state = _load_fixture()- if force_compatibility_scheduler:- object.__setattr__(state, "_execution_scheduler", _ExecutionScheduler(state))-- claimed = state.next()- assert claimed is not None- snapshot = dump_execution_state(state)- restored = load_execution_state(snapshot)- if force_compatibility_scheduler:- object.__setattr__(restored, "_execution_scheduler", _ExecutionScheduler(restored))-- replayed = restored.next()- assert replayed is not None- assert state.prepared_source_mapping[claimed.id] == "left"- assert restored.prepared_source_mapping[replayed.id] == "left"- assert restored.executed == set()+ branch_sources = {+ edge.source.node_id+ for edge in graph.edges+ if edge.destination.node_id in {"inner_if", "middle_if", "outer_if"}+ and edge.destination.field in {"true_input", "false_input"}+ }+ assert {+ "outer_condition",+ "middle_condition",+ "inner_condition",+ "inner_if",+ "middle_if",+ "outer_if",+ "sink",+ }.issubset(trace)+ assert branch_sources.issubset(trace)+ assert state.results[next(iter(state.source_prepared_mapping["sink"]))].value == 5+ assert state.is_complete()+ _assert_generic_and_compatibility_schedulers(runs[0][1], runs[1][1])+ assert Counter(runs[0][0]) == Counter(runs[1][0])+ assert _state_projection(runs[0][1]) == _state_projection(runs[1][1])-def test_injected_failure_stops_both_schedulers_without_further_scheduling() -> None:- for trace, state in _run_both(fail_source_id="right"):- assert trace == ["left", "right"]- assert {- state.prepared_source_mapping.get(node_id, node_id): message for node_id, message in state.errors.items()- } == {"right": "injected failure"}- assert state.next() is None- assert "join" not in state.results[email protected]("force_compatibility_scheduler", [False, True])[email protected]("stop_after", range(1, 10))+def test_fresh_three_nested_ifs_shared_ancestor_isolated_and_checkpoint_resumes(+ force_compatibility_scheduler: bool,+ stop_after: int,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh three-nested If used controller-owned branch analysis")-def test_injected_failure_round_trip_preserves_both_scheduler_terminal_state() -> None:- generic, compatibility = _run_both(fail_source_id="right")- restored_generic = load_execution_state(dump_execution_state(generic[1]))- restored_compatibility = load_execution_state(dump_execution_state(compatibility[1]))- _restore_compatibility_scheduler(restored_compatibility)+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ graph = _three_nested_if_graph_with_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 restored_generic.next() is None- assert restored_compatibility.next() is None- assert restored_generic.is_complete()- assert restored_compatibility.is_complete()- assert _state_projection(restored_generic) == _state_projection(restored_compatibility)+ combined_trace = checkpoint_trace + resumed_trace+ assert Counter(combined_trace) == Counter(expected_trace)+ assert Counter(resumed_state.executed_history) == Counter(expected_state.executed_history)+ assert resumed_state.results[next(iter(resumed_state.source_prepared_mapping["sink"]))].value == 6+ assert resumed_state.is_complete()+ assert resumed_state.executed_history.count("shared") == 1+ _assert_state_projection_matches_ignoring_execution_order(resumed_state, expected_state)+ assert _activation_projection(resumed_state) == _activation_projection(expected_state)-def test_real_invocation_failure_round_trip_preserves_both_scheduler_terminal_state() -> None:- expected_error = "This invocation is supposed to fail"- terminal_states: list[tuple[str, bool, bool]] = [][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")- for force_compatibility_scheduler in (False, True):- graph = Graph()- graph.add_node(ErrorInvocation(id="error"))- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)+ 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)- node = state.next()- assert node is not None- with pytest.raises(Exception) as invocation_error:- node.invoke(Mock())- assert str(invocation_error.value) == expected_error- state.set_node_error(node.id, str(invocation_error.value))+ assert state._can_use_fresh_flat_if_activation()+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- assert state.next() is None- assert state.is_complete()- assert {- state.prepared_source_mapping.get(node_id, node_id): message for node_id, message in state.errors.items()- } == {"error": expected_error}+ expected_events = set(expected_trace) | (+ set(graph.nodes) & {"inner_true", "inner_false", "middle_true", "middle_false", "outer_true", "outer_false"}+ )+ assert expected_events.issubset(trace)+ assert state.results[next(iter(state.source_prepared_mapping["sink"]))].value == expected_value+ side_consumer_id = next(iter(state.source_prepared_mapping["middle_side_consumer"]))+ middle_value = (4 if inner_condition else 6) if middle_condition else 10+ assert state.results[side_consumer_id].value == middle_value + 1+ assert state.is_complete()- restored = load_execution_state(dump_execution_state(state))- if force_compatibility_scheduler:- _restore_compatibility_scheduler(restored)- assert restored.errors == state.errors- assert restored.next() is None- assert restored.is_complete()- terminal_states.append((str(next(iter(restored.errors.values()))), True, restored.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")- assert terminal_states == [(expected_error, True, True), (expected_error, True, True)]+ 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_events = {+ "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))+ branch_sources = {+ edge.source.node_id+ for edge in graph.edges+ if edge.destination.node_id in {"inner_if", "middle_if", "outer_if"}+ and edge.destination.field in {"true_input", "false_input"}+ }+ assert expected_events.issubset(trace)+ assert branch_sources.issubset(trace)+ assert state.is_complete()+ assert Counter(runs[0][0]) == Counter(runs[1][0])+ assert _state_projection(runs[0][1]) == _state_projection(runs[1][1])[email protected]("fixture_name", ["static_dag_partial_v1.json", "static_dag_failed_v1.json"])-def test_durable_snapshot_corpus_round_trips_without_losing_terminal_state(fixture_name: str) -> None:- state = _load_fixture(fixture_name)- restored = load_execution_state(dump_execution_state(state))- assert restored.id == state.id- assert restored.executed == state.executed- assert restored.executed_history == state.executed_history- assert restored.errors == state.errors- assert restored.indegree == state.indegree[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")- if state.errors:- for force_compatibility_scheduler in (False, True):- candidate = load_execution_state(dump_execution_state(state))- if force_compatibility_scheduler:- _restore_compatibility_scheduler(candidate)- assert candidate.next() is None- assert candidate.is_complete()- generic = load_execution_state(dump_execution_state(state))- compatibility = load_execution_state(dump_execution_state(state))- _restore_compatibility_scheduler(compatibility)- assert _state_projection(generic) == _state_projection(compatibility)- else:- generic_trace, generic_state = _run(restored)- compatibility_trace, compatibility_state = _run(- load_execution_state(dump_execution_state(state)),- force_compatibility_scheduler=True,- )- assert generic_trace == compatibility_trace == ["right", "join"]- assert generic_state.is_complete()- assert compatibility_state.is_complete()+ 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 Counter(checkpoint_trace + resumed_trace) == Counter(expected_trace)+ assert Counter(resumed_state.executed_history) == Counter(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_matches_ignoring_execution_order(resumed_state, expected_state)+ assert _activation_projection(resumed_state) == _activation_projection(expected_state)+ assert resumed_state.is_complete()-def test_fixture_is_versioned_and_future_versions_are_explicitly_rejected() -> None:- with FIXTURE_PATH.open(encoding="utf-8") as fixture:- snapshot = json.load(fixture)- assert snapshot["execution_state_version"] == 1- restored = load_execution_state(snapshot)- assert restored.id == "fixture-state"- assert dump_execution_state(restored)["execution_state_version"] == CURRENT_EXECUTION_STATE_VERSION+ "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,+) -> None:+ graph = graph_factory()+ state = GraphExecutionState(graph=graph)+ if_nodes = {"inner_if", "middle_if", "outer_if"}- future_snapshot = dict(snapshot)- future_snapshot["execution_state_version"] = CURRENT_EXECUTION_STATE_VERSION + 1- with pytest.raises(UnsupportedExecutionStateVersionError, match="newer than supported"):- load_execution_state(future_snapshot)+ assert all(not state._is_fresh_lazy_if_candidate(if_id) for if_id in if_nodes)+ trace, state = _run_graph(state)+ branch_sources = {+ edge.source.node_id+ for edge in graph.edges+ if edge.destination.node_id in if_nodes and edge.destination.field in {"true_input", "false_input"}+ }+ assert branch_sources.issubset(trace)+ assert state.results[next(iter(state.source_prepared_mapping["sink"]))].value == 5+ assert state.is_complete()-def test_generic_legacy_shaped_if_does_not_prune_or_skip_during_resolution(+ ("outer_condition", "inner_condition", "expected_value"),+ [(True, True, 5), (True, False, 6), (False, True, 11), (False, False, 11)],+)+def test_fresh_nested_if_preserves_shared_ancestor_isolation(+ outer_condition: bool,+ inner_condition: bool,+ expected_value: int,monkeypatch: pytest.MonkeyPatch,) -> None:- graph = _nested_if_graph()- state = GraphExecutionState(graph=graph)- deleted_edges: list[Edge] = []-- def record_deleted_edge(self: GraphExecutionState, edge: Edge) -> None:- deleted_edges.append(edge)+ def fail_branch_analysis(*_: object, **__: object) -> set[str]:+ raise AssertionError("fresh nested If used controller-owned branch analysis")- monkeypatch.setattr(GraphExecutionState, "_tx_delete_execution_edge", record_deleted_edge)+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ graph = _nested_if_graph_with_shared_ancestor()+ graph.get_node("outer_condition").value = outer_condition+ graph.get_node("inner_condition").value = inner_condition- trace, state = _run_graph(state)+ trace, state = _run_graph(GraphExecutionState(graph=graph))- assert trace == ["outer_condition", "inner_condition", "inner_false", "inner_if", "outer_if", "sink"]+ assert trace.count("shared") == 1+ assert "inner_true" in trace+ assert "inner_false" in trace+ assert trace.count("outer_false") == 1sink_id = next(iter(state.source_prepared_mapping["sink"]))- assert state.results[sink_id].value == 7+ assert state.results[sink_id].value == expected_valueassert state.is_complete()- assert deleted_edges == [][email protected]("force_compatibility_scheduler", [False, True])-def test_if_readiness_preserves_both_schedulers(- force_compatibility_scheduler: bool,-) -> None:- graph = _nested_if_graph()+def test_noncanonical_private_root_if_runs_only_the_selected_branch() -> None:+ state = GraphExecutionState(graph=_noncanonical_flat_if_graph())+ assert state._is_fresh_lazy_if_candidate("if")- trace, state = _run_graph(- GraphExecutionState(graph=graph),- force_compatibility_scheduler=force_compatibility_scheduler,- )+ trace, state = _run_graph(state)- assert trace == ["outer_condition", "inner_condition", "inner_false", "inner_if", "outer_if", "sink"]+ assert trace == ["condition", "true_source", "true_branch", "if", "sink"]+ assert state.results[next(iter(state.source_prepared_mapping["sink"]))].value == 10assert state.is_complete()@pytest.mark.parametrize("force_compatibility_scheduler", [False, True])-def test_flat_if_admission_is_demand_driven_and_token_authoritative(+def test_fresh_if_dependency_cache_refreshes_after_branch_source_graph_edit(force_compatibility_scheduler: bool,) -> None:- trace, state = _run_graph(- GraphExecutionState(graph=_flat_if_graph()),- force_compatibility_scheduler=force_compatibility_scheduler,- )+ state = GraphExecutionState(graph=_flat_if_graph(condition=False))- assert trace == ["condition", "true_branch", "if", "sink"]- assert set(state.source_prepared_mapping) == {"condition", "true_branch", "false_branch", "if", "sink"}- assert state.source_prepared_mapping["false_branch"] == set()- assert [source_id for source_id in state.executed_history if source_id != "false_branch"] == trace- assert state.executed_history.count("false_branch") == 1- assert all(- state._get_prepared_exec_metadata(exec_node_id).state != "skipped"- for exec_node_id in state.prepared_source_mapping+ assert state._get_source_activation_dependencies("true_branch") == (+ graph_module.ActivationDependency(owner_id="if", branch="true_input", frame=()),)- activation_tokens = [token for token in state.execution_tokens.values() if token.token_kind == "activation"]- assert len(activation_tokens) == 1- assert activation_tokens[0].port == "true_input"- sink_id = next(iter(state.source_prepared_mapping["sink"]))- assert state.results[sink_id].value == 6++ state.add_node(AddInvocation(id="true_consumer", b=1))+ state.add_edge(create_edge("true_branch", "value", "true_consumer", "a"))++ assert state._get_source_activation_dependencies("true_branch") == ()+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert trace == ["true_branch", "true_consumer", "condition", "false_branch", "if", "sink"]+ assert state.results[next(iter(state.source_prepared_mapping["true_consumer"]))].value == 6+ assert state.results[next(iter(state.source_prepared_mapping["sink"]))].value == 31assert state.is_complete()[email protected]("force_compatibility_scheduler", [False, True])-def test_fresh_flat_if_records_dependencies_without_author_graph_branch_analysis(- force_compatibility_scheduler: bool,+def test_fresh_flat_if_with_saved_workflow_uses_controller_fallback(monkeypatch: pytest.MonkeyPatch,) -> None:- def fail_branch_analysis(*_: object, **__: object) -> set[str]:- raise AssertionError("fresh flat If used controller-owned branch analysis")+ graph = _flat_if_graph()+ graph.delete_node("sink")+ graph.add_node(CallSavedWorkflowInvocation(id="call", workflow_id="saved-workflow"))+ graph.add_edge(create_edge("if", "value", "call", "saved_workflow_input::input::value"))+ state = GraphExecutionState(graph=graph)+ branch_analysis_calls: list[tuple[str, str]] = []+ original_branch_sources = graph_module._IfActivationController._branch_sources- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ 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)- trace, state = _run_graph(- GraphExecutionState(graph=_flat_if_graph()),- force_compatibility_scheduler=force_compatibility_scheduler,- )+ monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", record_branch_analysis)- assert trace == ["condition", "true_branch", "if", "sink"]- true_branch_id = next(- execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "true_branch"+ assert not state._can_use_fresh_flat_if_activation()+ assert state._get_source_activation_dependencies("true_branch") == (+ graph_module.ActivationDependency(owner_id="if", branch="true_input", frame=()),)- assert [- (dependency.owner_id, dependency.branch, dependency.frame)- for dependency in state._if_activation_dependencies_by_exec[true_branch_id]- ] == [("if", "true_input", ())]- assert state.is_complete()+ assert branch_analysis_calls@pytest.mark.parametrize(- ("first_condition", "second_condition"),- [(True, True), (True, False), (False, True), (False, False)],+ ("outer_condition", "inner_condition", "expected_value"),+ [+ (+ True,+ True,+ 5,+ ),+ (+ True,+ False,+ 7,+ ),+ (+ False,+ True,+ 11,+ ),+ (+ False,+ False,+ 11,+ ),+ ],)-def test_fresh_sibling_ifs_preserve_owner_local_selection_and_scheduler_parity(- first_condition: bool,- second_condition: bool,+def test_fresh_generic_nested_if_preserves_state_without_legacy_branch_projection(+ outer_condition: bool,+ inner_condition: bool,+ expected_value: int,monkeypatch: pytest.MonkeyPatch,) -> None:- def fail_branch_analysis(*_: object, **__: object) -> set[str]:- raise AssertionError("fresh sibling If used controller-owned branch analysis")+ graph = _nested_if_graph()+ graph.get_node("outer_condition").value = outer_condition+ graph.get_node("inner_condition").value = inner_condition- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)- runs: list[tuple[list[str], GraphExecutionState]] = []+ def fail_edge_deletion(*_: object, **__: object) -> None:+ raise AssertionError("fresh generic If execution deleted an execution edge")++ monkeypatch.setattr(GraphExecutionState, "_tx_delete_execution_edge", fail_edge_deletion)++ trace, state = _run_graph(GraphExecutionState(graph=graph))++ assert {+ "outer_condition",+ "outer_false",+ "inner_condition",+ "inner_true",+ "inner_false",+ "inner_if",+ "outer_if",+ "sink",+ }.issubset(trace)+ assert Counter(state.executed_history) == Counter(trace)+ 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) == _expected_edge_projection(+ graph,+ force_compatibility_scheduler=False,+ outer_condition=outer_condition,+ inner_condition=inner_condition,+ )++[email protected]("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]] = []++ for force_compatibility_scheduler in (False, True):+ partial_trace, canceled_state = _run_until_source(+ GraphExecutionState(graph=_nested_if_graph()),+ stop_after_source,+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ assert partial_trace[-1] == stop_after_source+ 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", ()),+ )+ partial_snapshot = dump_execution_state(canceled_state)+ restored_canceled = load_execution_state(partial_snapshot)+ restored_expected = load_execution_state(partial_snapshot)+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(restored_canceled)+ assert _state_projection(restored_canceled) == _state_projection(canceled_state)+ assert _activation_projection(restored_canceled) == _activation_projection(canceled_state)+ assert dump_execution_state(restored_canceled)["execution_tokens"] == partial_snapshot["execution_tokens"]+ 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))+ )- for force_compatibility_scheduler in (False, True):- state = GraphExecutionState(- graph=_sibling_if_graph(first_condition=first_condition, second_condition=second_condition)+ remaining_trace, resumed_state = _run_graph(+ restored_canceled,+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ assert Counter(partial_trace + remaining_trace) == Counter(expected_trace)+ assert Counter(resumed_state.executed_history) == Counter(expected_state.executed_history)+ _assert_state_projection_matches_ignoring_execution_order(resumed_state, 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,)- assert state._can_use_fresh_flat_if_activation()- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- runs.append((trace, state))- expected_sources = {- "first_condition",- "second_condition",- "first_if",- "second_if",- "first_sink",- "second_sink",- }- expected_sources.add("first_true" if first_condition else "first_false")- expected_sources.add("second_true" if second_condition else "second_false")- unselected = {- "first_false" if first_condition else "first_true",- "second_false" if second_condition else "second_true",- }- expected_sources.update(unselected)- assert set(state.source_prepared_mapping) == expected_sources- assert all(state.source_prepared_mapping[source_id] == set() for source_id in unselected)- assert ("first_true" in trace) is first_condition- assert ("first_false" in trace) is not first_condition- assert ("second_true" in trace) is second_condition- assert ("second_false" in trace) is not second_condition- first_sink_id = next(iter(state.source_prepared_mapping["first_sink"]))- second_sink_id = next(iter(state.source_prepared_mapping["second_sink"]))- assert state.results[first_sink_id].value == (103 if first_condition else 111)- assert state.results[second_sink_id].value == (204 if second_condition else 221)+ retried_state = GraphExecutionState(graph=canceled_state.graph.model_copy(deep=True))+ assert retried_state.id != canceled_state.id+ assert retried_state.results == {}+ assert retried_state.execution_refs == {}+ assert retried_state.execution_tokens == {}- selected_first = "first_true" if first_condition else "first_false"- selected_second = "second_true" if second_condition else "second_false"- dependencies_by_source = {- source_id: {- (dependency.owner_id, dependency.branch, dependency.frame)- for execution_id, source_id_value in state.prepared_source_mapping.items()- if source_id_value == source_id- for dependency in state._if_activation_dependencies_by_exec.get(execution_id, ())- }- for source_id in (selected_first, selected_second)- }- assert dependencies_by_source == {- selected_first: {("first_if", "true_input" if first_condition else "false_input", ())},- selected_second: {("second_if", "true_input" if second_condition else "false_input", ())},- }- assert state.is_complete()+ retried_trace, retried_state = _run_graph(+ retried_state,+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ projections.append((retried_trace, retried_state))- assert runs[0][0] == runs[1][0]- assert _state_projection(runs[0][1]) == _state_projection(runs[1][1])+ assert partial_projections[0] == partial_projections[1]+ expected_events = [+ "outer_condition",+ "outer_false",+ "inner_condition",+ "inner_true",+ "inner_false",+ "inner_if",+ "outer_if",+ "sink",+ ]+ assert Counter(projections[0][0]) == Counter(projections[1][0]) == Counter(expected_events)+ _assert_state_projection_matches_ignoring_execution_order(projections[0][1], projections[1][1])+ assert _activation_projection(projections[0][1]) == _activation_projection(projections[1][1])+ assert _execution_identity_projection(projections[0][1]) == _execution_identity_projection(projections[1][1])+ _assert_execution_identity_consistent(projections[0][1])+ _assert_execution_identity_consistent(projections[1][1])+ assert projections[0][1].results[next(iter(projections[0][1].source_prepared_mapping["sink"]))].value == 7[email protected]("force_compatibility_scheduler", [False, True])@pytest.mark.parametrize(- ("first_condition", "second_condition"),- [(True, True), (True, False), (False, True), (False, False)],+ "tampered_field",+ [+ "token_id",+ "owner_node_id",+ "reference_id",+ "frame_id",+ "state_id",+ "iteration_path",+ "workflow_call_depth",+ "blank_owner_node_id",+ "blank_frame_id",+ "blank_state_id",+ "mapping_key",+ "both_ids",+ ],)[email protected]("stop_after", range(1, 8))-def test_fresh_sibling_ifs_checkpoint_resume_matches_fresh_execution(- force_compatibility_scheduler: bool,- first_condition: bool,- second_condition: bool,- stop_after: int,-) -> None:- graph = _sibling_if_graph(first_condition=first_condition, second_condition=second_condition)- expected_trace, expected_state = _run_graph(- GraphExecutionState(graph=graph.model_copy(deep=True)),- force_compatibility_scheduler=force_compatibility_scheduler,- )- checkpoint_trace, checkpoint_state = _run_graph(- GraphExecutionState(graph=graph.model_copy(deep=True)),- force_compatibility_scheduler=force_compatibility_scheduler,- stop_after=stop_after,+def test_rehydrated_if_rejects_tampered_activation_identity(tampered_field: str) -> None:+ """A persisted activation token with stale identity or frame data is rejected."""+ _, partial_state = _run_until_source(GraphExecutionState(graph=_nested_if_graph()), "outer_if")+ snapshot = dump_execution_state(partial_state)+ token_id, token = next(+ (token_id, token)+ for token_id, token in snapshot["execution_tokens"].items()+ if token["token_kind"] == "activation")+ source_if_id = partial_state.prepared_source_mapping[token["owner_node_id"]]- 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,+ valid_restored = load_execution_state(snapshot)+ valid_plan = valid_restored._scheduler()._scheduler.plan+ dependency = next(+ dependency+ for plan_node in valid_plan.nodes.values()+ for dependency in plan_node.activation_dependencies+ if dependency.owner_id == source_if_id)+ assert valid_restored._is_activation_dependency_satisfied(dependency)+ restored_token = valid_restored.execution_tokens[token_id]+ expected_ref = valid_restored.execution_refs[restored_token.owner_node_id]+ assert restored_token.token_id == token_id == f"{expected_ref.reference_id}:activation:{restored_token.port}"+ assert restored_token.reference_id == expected_ref.reference_id+ assert restored_token.owner_node_id == expected_ref.exec_node_id+ assert restored_token.frame == expected_ref.frame- assert checkpoint_trace + resumed_trace == expected_trace- assert _state_projection(resumed_state) == _state_projection(expected_state)- assert _activation_projection(resumed_state) == _activation_projection(expected_state)- assert resumed_state.is_complete()-+ stale_snapshot = json.loads(json.dumps(snapshot))+ stale_token = stale_snapshot["execution_tokens"][token_id]+ if tampered_field == "token_id":+ stale_token["token_id"] = "stale-token"+ elif tampered_field == "owner_node_id":+ stale_token["owner_node_id"] = "stale-owner"+ elif tampered_field == "reference_id":+ stale_token["reference_id"] = "stale-reference"+ elif tampered_field == "frame_id":+ stale_token["frame"]["frame_id"] = "stale-frame"+ elif tampered_field == "state_id":+ stale_token["frame"]["state_id"] = "stale-state"+ elif tampered_field == "iteration_path":+ stale_token["frame"]["iteration_path"] = [1]+ elif tampered_field == "workflow_call_depth":+ stale_token["frame"]["workflow_call_depth"] = 1+ elif tampered_field == "blank_owner_node_id":+ stale_token["owner_node_id"] = ""+ elif tampered_field == "blank_frame_id":+ stale_token["frame"]["frame_id"] = ""+ elif tampered_field == "blank_state_id":+ stale_token["frame"]["state_id"] = ""+ elif tampered_field == "mapping_key":+ stale_snapshot["execution_tokens"]["stale-key"] = stale_snapshot["execution_tokens"].pop(token_id)+ else:+ stale_snapshot["execution_tokens"]["stale-key"] = stale_snapshot["execution_tokens"].pop(token_id)+ stale_snapshot["execution_tokens"]["stale-key"]["token_id"] = "stale-key"+ with pytest.raises(ValidationError, match="Activation token|Execution token"):+ load_execution_state(stale_snapshot)- ("first_condition", "second_condition"),- [(True, True), (True, False), (False, True), (False, False)],-)-def test_fresh_sibling_ifs_shared_ancestor_executes_once(- first_condition: bool,- second_condition: bool,- monkeypatch: pytest.MonkeyPatch,-) -> None:- def fail_branch_analysis(*_: object, **__: object) -> set[str]:- raise AssertionError("fresh sibling If used controller-owned branch analysis")- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)- trace, state = _run_graph(- GraphExecutionState(- graph=_sibling_if_graph(- first_condition=first_condition,- second_condition=second_condition,- with_shared_ancestor=True,- )- )+def test_rehydrated_if_rejects_activation_token_with_ghost_owner_and_reference() -> None:+ _, partial_state = _run_until_source(GraphExecutionState(graph=_nested_if_graph()), "outer_if")+ snapshot = dump_execution_state(partial_state)+ token_id, token = next(+ (token_id, token)+ for token_id, token in snapshot["execution_tokens"].items()+ if token["token_kind"] == "activation")+ expected_ref = partial_state._expected_execution_ref(token["owner_node_id"]).model_dump(mode="json")+ ghost_ref = {**expected_ref, "exec_node_id": "ghost", "reference_id": f"{snapshot['id']}:ghost"}+ snapshot["execution_refs"]["ghost"] = ghost_ref+ ghost_token_id = f"{ghost_ref['reference_id']}:activation:{token['port']}"+ ghost_token = {+ **token,+ "token_id": ghost_token_id,+ "reference_id": ghost_ref["reference_id"],+ "owner_node_id": "ghost",+ }+ snapshot["execution_tokens"].pop(token_id)+ snapshot["execution_tokens"][ghost_token_id] = ghost_token- assert trace.count("shared") == 1- assert state.is_complete()+ with pytest.raises(ValidationError, match="Activation token|Execution token"):+ load_execution_state(snapshot)- ("first_condition", "second_condition", "third_condition"),- [- (True, True, True),- (True, True, False),- (True, False, True),- (True, False, False),- (False, True, True),- (False, True, False),- (False, False, True),- (False, False, False),- ],-)-def test_fresh_three_sibling_ifs_select_only_owner_local_branches_and_match_compatibility(- first_condition: bool,- second_condition: bool,- third_condition: bool,- monkeypatch: pytest.MonkeyPatch,-) -> None:- def fail_branch_analysis(*_: object, **__: object) -> set[str]:- raise AssertionError("fresh three-sibling If used controller-owned branch analysis")+def test_rehydrated_if_rejects_activation_token_on_invocation_without_declared_field() -> None:+ _, partial_state = _run_until_source(GraphExecutionState(graph=_nested_if_graph()), "outer_if")+ snapshot = dump_execution_state(partial_state)+ ordinary_exec_id = next(+ execution_id+ for execution_id, source_id in partial_state.prepared_source_mapping.items()+ if source_id == "inner_false"+ )+ reference = partial_state._expected_execution_ref(ordinary_exec_id).model_dump(mode="json")+ token_id = f"{reference['reference_id']}:activation:value"+ snapshot["execution_tokens"][token_id] = {+ "token_id": token_id,+ "reference_id": reference["reference_id"],+ "owner_node_id": ordinary_exec_id,+ "port": "value",+ "frame": reference["frame"],+ "value": "value",+ "token_kind": "activation",+ }++ with pytest.raises(ValidationError, match="Activation token|Execution token"):+ load_execution_state(snapshot)- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)- runs: list[tuple[list[str], GraphExecutionState]] = []- for force_compatibility_scheduler in (False, True):- state = GraphExecutionState(- graph=_three_sibling_if_graph(- first_condition=first_condition,- second_condition=second_condition,- third_condition=third_condition,- )- )- assert state._can_use_fresh_flat_if_activation()- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- runs.append((trace, state))+def test_rehydrated_activation_token_allows_unknown_frame_metadata() -> None:+ _, partial_state = _run_until_source(GraphExecutionState(graph=_nested_if_graph()), "outer_if")+ snapshot = dump_execution_state(partial_state)+ token_id, token = next(+ (token_id, token)+ for token_id, token in snapshot["execution_tokens"].items()+ if token["token_kind"] == "activation"+ )+ snapshot["execution_tokens"][token_id]["frame"]["future_frame_metadata"] = "preserved"- selected = {- "first_true" if first_condition else "first_false",- "second_true" if second_condition else "second_false",- "third_true" if third_condition else "third_false",- }- expected_sources = {- "first_condition",- "second_condition",- "third_condition",- "first_if",- "second_if",- "third_if",- "first_sink",- "second_sink",- "third_sink",- *selected,- }- unselected = {- "first_false" if first_condition else "first_true",- "second_false" if second_condition else "second_true",- "third_false" if third_condition else "third_true",- }- expected_sources.update(unselected)- assert set(state.source_prepared_mapping) == expected_sources- assert set(trace) == expected_sources - unselected- assert all(state.source_prepared_mapping[source_id] == set() for source_id in unselected)- assert not unselected.intersection(trace)+ restored = load_execution_state(snapshot)+ assert restored.execution_tokens[token_id].frame.model_extra["future_frame_metadata"] == "preserved"- dependencies_by_source = {- source_id: {- (dependency.owner_id, dependency.branch, dependency.frame)- for execution_id, source_id_value in state.prepared_source_mapping.items()- if source_id_value == source_id- for dependency in state._if_activation_dependencies_by_exec.get(execution_id, ())- }- for source_id in selected- }- assert dependencies_by_source == {- "first_true" if first_condition else "first_false": {- ("first_if", "true_input" if first_condition else "false_input", ())- },- "second_true" if second_condition else "second_false": {- ("second_if", "true_input" if second_condition else "false_input", ())- },- "third_true" if third_condition else "third_false": {- ("third_if", "true_input" if third_condition else "false_input", ())- },- }- first_sink_id = next(iter(state.source_prepared_mapping["first_sink"]))- second_sink_id = next(iter(state.source_prepared_mapping["second_sink"]))- third_sink_id = next(iter(state.source_prepared_mapping["third_sink"]))- assert state.results[first_sink_id].value == (103 if first_condition else 111)- assert state.results[second_sink_id].value == (204 if second_condition else 221)- assert state.results[third_sink_id].value == (305 if third_condition else 331)- 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])+def _expected_four_nested_if_value(conditions: tuple[bool, bool, bool, bool]) -> int:+ root_condition, outer_condition, middle_condition, inner_condition = conditions+ if not root_condition:+ return 31+ if not outer_condition:+ return 21+ if not middle_condition:+ return 11+ return 5 if inner_condition else 7-def test_fresh_three_sibling_ifs_shared_ancestor_executes_once_without_cross_owner_dependencies([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 three-sibling If used controller-owned branch analysis")+ 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_value = _expected_four_nested_if_value(conditions)runs: list[tuple[list[str], GraphExecutionState]] = []-for force_compatibility_scheduler in (False, True):- state = GraphExecutionState(graph=_three_sibling_if_graph(with_shared_ancestor=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.count("shared") == 1- assert state.results[next(iter(state.source_prepared_mapping["first_sink"]))].value == 105- assert state.results[next(iter(state.source_prepared_mapping["second_sink"]))].value == 206- assert state.results[next(iter(state.source_prepared_mapping["third_sink"]))].value == 307+ assert set(trace) == set(state.graph.nodes)+ assert all(trace.count(source_id) == 1 for source_id in state.graph.nodes)+ assert state.results[next(iter(state.source_prepared_mapping["sink"]))].value == expected_valueassert state.is_complete()- for source_id, if_id, branch in (- ("first_true", "first_if", "true_input"),- ("second_true", "second_if", "true_input"),- ("third_true", "third_if", "true_input"),- ):- execution_id = next(- execution_id- for execution_id, prepared_source_id in state.prepared_source_mapping.items()- if prepared_source_id == source_id- )- assert {- (dependency.owner_id, dependency.branch, dependency.frame)- for dependency in state._if_activation_dependencies_by_exec[execution_id]- } == {(if_id, 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])+ assert _execution_token_projection(runs[0][1]) == _execution_token_projection(runs[1][1])[email protected]("first_condition", [False, True])[email protected]("second_condition", [False, True])[email protected]("third_condition", [False, True])[email protected]("fourth_condition", [False, True])-def test_fresh_four_sibling_ifs_match_compatibility_for_all_polarities(- first_condition: bool,- second_condition: bool,- third_condition: bool,- fourth_condition: bool,[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-sibling If used controller-owned branch analysis")+ raise AssertionError("fresh four-nested If used controller-owned branch analysis")monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)- graph = _four_sibling_if_graph(- first_condition=first_condition,- second_condition=second_condition,- third_condition=third_condition,- fourth_condition=fourth_condition,+ 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",)runs: list[tuple[list[str], GraphExecutionState]] = []for force_compatibility_scheduler in (False, True):@@ -8462,22 +11284,14 @@ def test_fresh_four_sibling_ifs_match_compatibility_for_all_polarities(assert state._can_use_fresh_flat_if_activation()trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)runs.append((trace, state))- selected = {- "first_true" if first_condition else "first_false",- "second_true" if second_condition else "second_false",- "third_true" if third_condition else "third_false",- "fourth_true" if fourth_condition else "fourth_false",- }- unselected = {- "first_false" if first_condition else "first_true",- "second_false" if second_condition else "second_true",- "third_false" if third_condition else "third_true",- "fourth_false" if fourth_condition else "fourth_true",- }++ assert set(trace) == set(state.graph.nodes)+ assert state.results[next(iter(state.source_prepared_mapping["sink"]))].value == 5assert state.is_complete()- assert selected.issubset(trace)- assert not unselected.intersection(trace)- assert not unselected.intersection(state.prepared_source_mapping.values())+ assert {+ (dependency.owner_id, dependency.branch, dependency.frame)+ for dependency in state._get_source_activation_dependencies("inner_true")+ } == {("inner_if", "true_input", ())}_assert_generic_and_compatibility_schedulers(runs[0][1], runs[1][1])assert runs[0][0] == runs[1][0]@@ -8486,229 +11300,215 @@ def test_fresh_four_sibling_ifs_match_compatibility_for_all_polarities(@pytest.mark.parametrize("force_compatibility_scheduler", [False, True])[email protected]("stop_after", [1, 4, 5, 8, 9, 12])-def test_fresh_four_sibling_ifs_checkpoint_resume_matches_fresh_execution([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:- graph = _four_sibling_if_graph(- first_condition=True,- second_condition=False,- third_condition=True,- fourth_condition=False,- )- expected_trace, expected_state = _run_graph(- GraphExecutionState(graph=graph.model_copy(deep=True)),- force_compatibility_scheduler=force_compatibility_scheduler,+ 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_run, expected_state = _run_graph(GraphExecutionState(graph=graph.model_copy(deep=True)))+ assert set(expected_trace_run) == set(graph.nodes)+ assert expected_trace_run.count("shared") == 1checkpoint_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,- )+ resumed_trace, resumed_state = _run_graph(restored, force_compatibility_scheduler=force_compatibility_scheduler)- assert checkpoint_trace + resumed_trace == expected_trace- assert _state_projection(resumed_state) == _state_projection(expected_state)+ assert Counter(checkpoint_trace + resumed_trace) == Counter(expected_trace_run)+ assert Counter(resumed_state.executed_history) == Counter(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_matches_ignoring_execution_order(resumed_state, 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()-def test_fresh_four_sibling_ifs_shared_ancestor_executes_once_without_cross_owner_dependencies(- monkeypatch: pytest.MonkeyPatch,-) -> None:- def fail_branch_analysis(*_: object, **__: object) -> set[str]:- raise AssertionError("fresh four-sibling If used controller-owned branch analysis")-- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)- graph = _four_sibling_if_graph(with_shared_ancestor=True)- 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.count("shared") == 1- 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])--[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])@pytest.mark.parametrize(- "graph_factory",+ ("collection", "expected"),[- pytest.param(_flat_if_graph, id="flat"),- pytest.param(_noncanonical_flat_if_graph, id="noncanonical-flat"),- pytest.param(_nested_if_graph, id="nested"),- pytest.param(_three_nested_if_graph, id="three-nested"),- pytest.param(_three_nested_if_graph_with_middle_leaf_fanout, id="middle-leaf-fanout"),- pytest.param(_four_sibling_if_graph, id="four-siblings"),+ ([False, True], ["false-root", "true-root"]),+ ([True, True], ["true-root", "true-root"]),+ ([False, False], ["false-root", "false-root"]),],+ ids=["mixed", "all-true", "all-false"],)[email protected]("force_compatibility_scheduler", [False, True])-def test_supported_fresh_if_shapes_do_not_use_controller_or_skip_projection(- graph_factory: Any,- force_compatibility_scheduler: bool,- monkeypatch: pytest.MonkeyPatch,+def test_for_condition_if_reads_root_frame_sources_and_runs_both_roots(+ force_compatibility_scheduler: bool, collection: list[bool], expected: list[str]) -> None:- """Fresh supported shapes use graph-state dependencies in both scheduler routes."""-- def fail_controller(*_: object, **__: object) -> Any:- raise AssertionError("fresh supported If shape used compatibility controller")-- def fail_generic_retirement(*_: object, **__: object) -> None:- raise AssertionError("fresh supported If shape used generic skip projection")-- monkeypatch.setattr(GraphExecutionState, "_if_activation_controller", fail_controller)- monkeypatch.setattr(_GenericGraphSchedulerAdapter, "_retire_unselected_node", fail_generic_retirement)+ graph = Graph()+ graph.add_node(ForInvocation(id="for", collection=collection))+ graph.add_node(AnyTypeTestInvocation(id="root_true", value="true-root"))+ graph.add_node(AnyTypeTestInvocation(id="root_false", value="false-root"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(ForReturnInvocation(id="return"))+ graph.add_node(AnyTypeTestInvocation(id="after"))+ graph.add_edge(create_edge("for", "item", "if", "condition"))+ graph.add_edge(create_edge("root_true", "value", "if", "true_input"))+ graph.add_edge(create_edge("root_false", "value", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "return", "output"))+ graph.add_edge(create_loop_linkage("for", "return"))+ graph.add_edge(create_edge("for", "output_collection", "after", "value"))- state = GraphExecutionState(graph=graph_factory())- assert state._can_use_fresh_flat_if_activation()- trace, state = _run(state, force_compatibility_scheduler=force_compatibility_scheduler)+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )- assert trace- assert state.is_complete()- assert all(- state._get_prepared_exec_metadata(exec_node_id).state != "skipped"- for exec_node_id in state.prepared_source_mapping+ assert state.is_complete(), (+ f"graph stalled after {trace}; history={state.executed_history}; "+ f"sources={state.source_prepared_mapping}; pending_if={state._pending_if_exec_nodes}; "+ f"resolved={state._resolved_if_exec_branches}; indegree={state.indegree}")+ assert _source_output(state, "after").value == expected+ assert trace.count("root_true") == 1+ assert trace.count("root_false") == 1-def test_fresh_mixed_iterate_if_collect_uses_selected_branches_in_both_scheduler_routes(- monkeypatch: pytest.MonkeyPatch,[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+ ("conditions", "expected"),+ [+ ([False, True], ["false-root", "true-root"]),+ ([True, True], ["true-root", "true-root"]),+ ([False, False], ["false-root", "false-root"]),+ ],+ ids=["mixed", "all-true", "all-false"],+)+def test_iterate_condition_if_reads_root_frame_sources_and_runs_both_roots(+ force_compatibility_scheduler: bool, conditions: list[bool], expected: list[str]) -> None:graph = Graph()- graph.add_node(CollectionConcatInvocation(id="source", first=[True, False, True, False]))+ graph.add_node(CollectionConcatInvocation(id="conditions", first=conditions))graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(AnyTypeTestInvocation(id="root_true", value="true-root"))+ graph.add_node(AnyTypeTestInvocation(id="root_false", value="false-root"))graph.add_node(IfInvocation(id="if"))- graph.add_node(AnyTypeTestInvocation(id="true_branch"))- graph.add_node(AnyTypeTestInvocation(id="false_branch"))- graph.add_node(CollectInvocation(id="collect"))- graph.add_edge(create_edge("source", "collection", "iterate", "collection"))+ graph.add_node(CollectInvocation(id="output"))+ graph.add_edge(create_edge("conditions", "collection", "iterate", "collection"))graph.add_edge(create_edge("iterate", "item", "if", "condition"))- graph.add_edge(create_edge("iterate", "item", "true_branch", "value"))- graph.add_edge(create_edge("iterate", "item", "false_branch", "value"))- graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))- graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))- graph.add_edge(create_edge("if", "value", "collect", "item"))-- def fail_controller(*_: object, **__: object) -> Any:- raise AssertionError("fresh mixed If used compatibility controller")-- def fail_generic_retirement(*_: object, **__: object) -> None:- raise AssertionError("fresh mixed If used generic skip projection")-- monkeypatch.setattr(GraphExecutionState, "_if_activation_controller", fail_controller)- monkeypatch.setattr(_GenericGraphSchedulerAdapter, "_retire_unselected_node", fail_generic_retirement)-- 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_mixed_if_iterate_collect()- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- runs.append((trace, state))+ graph.add_edge(create_edge("root_true", "value", "if", "true_input"))+ graph.add_edge(create_edge("root_false", "value", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "output", "item"))- assert trace[0] == "source"- assert trace[-1] == "collect"- assert trace.count("iterate") == 4- assert trace.count("true_branch") == 2- assert trace.count("false_branch") == 2- assert trace.count("if") == 4- assert state.executed_history[-1] == "collect"- assert set(state.executed_history) == {"source", "iterate", "true_branch", "false_branch", "if", "collect"}- assert list(state.prepared_source_mapping.values()).count("true_branch") == 2- assert list(state.prepared_source_mapping.values()).count("false_branch") == 2- assert state.results[next(iter(state.source_prepared_mapping["collect"]))].collection == [- True,- False,- True,- False,- ]- activation_tokens = sorted(- (token for token in state.execution_tokens.values() if token.token_kind == "activation"),- key=lambda token: token.frame.iteration_path,- )- assert [token.port for token in activation_tokens] == [- "true_input",- "false_input",- "true_input",- "false_input",- ]- assert all(- state._get_prepared_exec_metadata(exec_node_id).state != "skipped"- for exec_node_id in state.prepared_source_mapping- )- assert state.is_complete()+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )- assert runs[0][0] == runs[1][0]- assert _state_projection(runs[0][1]) == _state_projection(runs[1][1])+ assert state.is_complete(), f"graph stalled after {trace}; history={state.executed_history}"+ assert _source_output(state, "output").collection == expected+ assert trace.count("root_true") == 1+ assert trace.count("root_false") == 1[email protected](("condition", "branch"), [(True, "true:"), (False, "false:")])-def test_constant_if_inside_iterate_routes_each_loop_item(condition: bool, branch: str) -> None:[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_iterate_for_collect_preserves_empty_inner_collection(force_compatibility_scheduler: bool) -> None:graph = Graph()- graph.add_node(CollectionConcatInvocation(id="source", first=[1, 2]))+ graph.add_node(CollectionConcatInvocation(id="source", first=[[1, 2], []]))graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(IfInvocation(id="if", condition=condition))- graph.add_node(MarkedAnyTypeTestInvocation(id="true_branch", marker="true:"))- graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="false:"))+ graph.add_node(ForInvocation(id="for"))+ graph.add_node(AddInvocation(id="add", b=10))+ graph.add_node(ForReturnInvocation(id="return"))graph.add_node(CollectInvocation(id="collect"))+ graph.add_node(AnyTypeTestInvocation(id="after"))graph.add_edge(create_edge("source", "collection", "iterate", "collection"))- graph.add_edge(create_edge("iterate", "item", "true_branch", "value"))- graph.add_edge(create_edge("iterate", "item", "false_branch", "value"))- graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))- graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))- graph.add_edge(create_edge("if", "value", "collect", "item"))+ graph.add_edge(create_edge("iterate", "item", "for", "collection"))+ graph.add_edge(create_edge("for", "item", "add", "a"))+ graph.add_edge(create_edge("add", "value", "return", "output"))+ graph.add_edge(create_loop_linkage("for", "return"))+ graph.add_edge(create_edge("for", "output_collection", "collect", "item"))+ graph.add_edge(create_edge("collect", "collection", "after", "value"))- trace, state = _run_graph(GraphExecutionState(graph=graph))+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)+ trace, state = _run_graph(state)- selected_source = "true_branch" if condition else "false_branch"- unselected_source = "false_branch" if condition else "true_branch"- assert trace[0] == "source"- assert trace[-1] == "collect"- assert trace.count("iterate") == 2- assert trace.count(selected_source) == 2- assert trace.count("if") == 2- assert unselected_source not in trace- collect_id = next(iter(state.source_prepared_mapping["collect"]))- assert state.results[collect_id].collection == [f"{branch}1", f"{branch}2"]+ after_exec_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)+ assert trace.count("add") == 2+ assert trace.count("after") == 2+ assert [state._get_iteration_path(exec_id) for exec_id in after_exec_ids] == [(0,), (1,)]+ assert [state.results[exec_id].value for exec_id in after_exec_ids] == [[[11, 12]], [[]]]assert state.is_complete()- assert state.next() is None- assert not state._ready_node_ids- assert all(not queue for queue in state._ready_queues.values())@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_selected_if_frame_cache_tracks_branch_resolution_and_restore(force_compatibility_scheduler: bool) -> None:+ ("left_values", "expected"),+ [([1, 2], ["fallback", [12, 22]]), ([1, 1], ["fallback", "fallback"])],+ ids=["mixed", "branch-never-selected"],+)+ "node_order",+ [+ tuple(order)+ for order in (+ random.Random(seed).sample(+ (+ "left_source",+ "right_source",+ "left",+ "right",+ "body",+ "branch_collect",+ "minus_one",+ "condition",+ "fallback",+ "if",+ "collect",+ ),+ 11,+ )+ for seed in range(20)+ )+ ],+)+def test_sibling_iterates_collect_through_if_branch_without_unsupported_frames(+ left_values, expected, node_order, force_compatibility_scheduler+):graph = Graph()- for node in (- CollectionConcatInvocation(id="source", first=[2, 1]),- IterateInvocation(id="items"),- AddInvocation(id="condition_value", b=-1),- FixedCollectionTestInvocation(id="condition"),- AnyTypeTestInvocation(id="true_value", value="T"),- AnyTypeTestInvocation(id="false_value", value="F"),- IfInvocation(id="if"),- CollectInvocation(id="collect"),- ):- graph.add_node(node)+ nodes = {+ "left_source": CollectionConcatInvocation(id="left_source", first=left_values),+ "right_source": CollectionConcatInvocation(id="right_source", first=[10, 20]),+ "left": IterateInvocation(id="left"),+ "right": IterateInvocation(id="right"),+ "body": AddInvocation(id="body"),+ "branch_collect": CollectInvocation(id="branch_collect"),+ "minus_one": AddInvocation(id="minus_one", b=-1),+ "condition": FixedCollectionTestInvocation(id="condition"),+ "fallback": AnyTypeTestInvocation(id="fallback", value="fallback"),+ "if": IfInvocation(id="if"),+ "collect": CollectInvocation(id="collect"),+ }+ for node_id in node_order:+ graph.add_node(nodes[node_id])for source, source_field, destination, destination_field in (- ("source", "collection", "items", "collection"),- ("items", "item", "condition_value", "a"),- ("condition_value", "value", "condition", "value"),+ ("left_source", "collection", "left", "collection"),+ ("right_source", "collection", "right", "collection"),+ ("left", "item", "body", "a"),+ ("right", "item", "body", "b"),+ ("body", "value", "branch_collect", "item"),+ ("left", "item", "minus_one", "a"),+ ("minus_one", "value", "condition", "value"),("condition", "condition", "if", "condition"),- ("true_value", "value", "if", "true_input"),- ("false_value", "value", "if", "false_input"),+ ("branch_collect", "collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),("if", "value", "collect", "item"),):graph.add_edge(create_edge(source, source_field, destination, destination_field))@@ -8716,3544 +11516,3643 @@ def test_selected_if_frame_cache_tracks_branch_resolution_and_restore(force_compstate = GraphExecutionState(graph=graph)if force_compatibility_scheduler:state._execution_scheduler = _ExecutionScheduler(state)+ trace, state = _run_graph(state)- trace: list[str] = []- selected_true_frames: set[tuple[int, ...]] = set()- if_frames_seen = 0- while (node := state.next()) is not None:- source_id = state.prepared_source_mapping[node.id]- trace.append(source_id)- if source_id == "condition":- assert set(graph_if_runtime._get_selected_if_frames_for_preparation(state, "if", "true_input")) == (- selected_true_frames- )- elif source_id == "if":- if_frames_seen += 1- iteration_path = state._get_iteration_path(node.id)- expected_selected_frames = selected_true_frames | ({iteration_path} if node.condition else set())- assert set(graph_if_runtime._get_selected_if_frames_for_preparation(state, "if", "true_input")) == (- expected_selected_frames- )- output = node.invoke(Mock())- state.complete(node.id, output)- if source_id == "condition":- assert set(graph_if_runtime._get_selected_if_frames_for_preparation(state, "if", "true_input")) == (- selected_true_frames- )- elif source_id == "if" and node.condition:- selected_true_frames.add(iteration_path)-- assert state.is_complete(), f"graph stalled after {trace}"- assert if_frames_seen == 2- assert state.results[next(iter(state.source_prepared_mapping["collect"]))].collection == ["T", "F"]-- restored = load_execution_state(dump_execution_state(state))- assert (- set(graph_if_runtime._get_selected_if_frames_for_preparation(restored, "if", "true_input"))- == selected_true_frames- )--[email protected](("condition", "branch"), [(True, "true:"), (False, "false:")])-def test_constant_if_inside_for_routes_each_loop_item(condition: bool, branch: str) -> None:- graph = Graph()- graph.add_node(ForInvocation(id="for", collection=[1, 2]))- graph.add_node(IfInvocation(id="if", condition=condition))- graph.add_node(MarkedAnyTypeTestInvocation(id="true_branch", marker="true:"))- graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="false:"))- graph.add_node(ForReturnInvocation(id="return"))- graph.add_edge(create_edge("for", "item", "true_branch", "value"))- graph.add_edge(create_edge("for", "item", "false_branch", "value"))- graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))- graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))- graph.add_edge(create_edge("if", "value", "return", "output"))- graph.add_edge(create_loop_linkage("for", "return"))-- trace, state = _run_graph(GraphExecutionState(graph=graph))-- selected_source = "true_branch" if condition else "false_branch"- unselected_source = "false_branch" if condition else "true_branch"- assert trace.count("for") == 2- assert trace.count(selected_source) == 2- assert trace.count("if") == 2- assert trace.count("return") == 2- assert unselected_source not in trace- assert sorted(state._get_iteration_path(exec_node_id) for exec_node_id in state.source_prepared_mapping["if"]) == [- (0,),- (1,),- ]- final_for_id = max(- state.source_prepared_mapping["for"],- key=lambda exec_node_id: state.execution_graph.get_node(exec_node_id).index,- )- assert state.results[final_for_id].output_collection == [f"{branch}1", f"{branch}2"]assert state.is_complete()- assert state.next() is None- assert not state._ready_node_ids- assert all(not queue for queue in state._ready_queues.values())+ assert state.results[next(iter(state.source_prepared_mapping["collect"]))].collection == expected+ if left_values == [1, 1]:+ assert "right" not in trace+ assert "body" not in trace[email protected](("condition", "branch"), [(True, "true:"), (False, "false:")])-def test_external_condition_if_inside_iterate_routes_each_loop_item(condition: bool, branch: str) -> None:+def test_sibling_collect_shared_by_distinct_if_owners_remains_unsupported() -> None:graph = Graph()- graph.add_node(BooleanInvocation(id="condition", value=condition))- graph.add_node(CollectionConcatInvocation(id="source", first=[1, 2]))- graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(MarkedAnyTypeTestInvocation(id="true_branch", marker="true:"))- graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="false:"))- graph.add_node(CollectInvocation(id="collect"))- graph.add_edge(create_edge("condition", "value", "if", "condition"))- graph.add_edge(create_edge("source", "collection", "iterate", "collection"))- graph.add_edge(create_edge("iterate", "item", "true_branch", "value"))- graph.add_edge(create_edge("iterate", "item", "false_branch", "value"))- graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))- graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))- graph.add_edge(create_edge("if", "value", "collect", "item"))+ for node in (+ CollectionConcatInvocation(id="left_source", first=[1, 2]),+ IterateInvocation(id="left"),+ CollectionConcatInvocation(id="right_source", first=[10, 20]),+ IterateInvocation(id="right"),+ AddInvocation(id="body"),+ CollectInvocation(id="branch_collect"),+ FixedCollectionTestInvocation(id="condition"),+ AnyTypeTestInvocation(id="fallback_a", value=0),+ AnyTypeTestInvocation(id="fallback_b", value=0),+ IfInvocation(id="if_a"),+ IfInvocation(id="if_b"),+ ):+ graph.add_node(node)+ for source, source_field, destination, destination_field in (+ ("left_source", "collection", "left", "collection"),+ ("right_source", "collection", "right", "collection"),+ ("left", "item", "body", "a"),+ ("right", "item", "body", "b"),+ ("body", "value", "branch_collect", "item"),+ ("left", "item", "condition", "value"),+ ("condition", "condition", "if_a", "condition"),+ ("condition", "condition", "if_b", "condition"),+ ("branch_collect", "collection", "if_a", "true_input"),+ ("branch_collect", "collection", "if_b", "true_input"),+ ("fallback_a", "value", "if_a", "false_input"),+ ("fallback_b", "value", "if_b", "false_input"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- trace, state = _run_graph(GraphExecutionState(graph=graph))+ state = GraphExecutionState(graph=graph)- selected_source = "true_branch" if condition else "false_branch"- unselected_source = "false_branch" if condition else "true_branch"- assert trace.count("condition") == 1- assert trace.count("source") == 1- assert trace.count("iterate") == 2- assert trace.count(selected_source) == 2- assert trace.count("if") == 2- assert trace.count("collect") == 1- assert unselected_source not in trace- assert sorted(state._get_iteration_path(exec_node_id) for exec_node_id in state.source_prepared_mapping["if"]) == [- (0,),- (1,),- ]- collect_id = next(iter(state.source_prepared_mapping["collect"]))- assert state.results[collect_id].collection == [f"{branch}1", f"{branch}2"]- assert state.is_complete()- assert state.next() is None- assert not state._pending_if_exec_nodes- assert not state._ready_node_ids- assert all(not queue for queue in state._ready_queues.values())+ with pytest.raises(UnsupportedSharedIfCollectBranchesError, match="multiple If nodes"):+ state.next()[email protected](("condition", "branch"), [(True, "true:"), (False, "false:")])-def test_external_condition_if_inside_for_routes_each_loop_item(condition: bool, branch: str) -> None:+def test_nested_iterate_collected_in_if_branch_is_not_misclassified_as_sibling():graph = Graph()- graph.add_node(BooleanInvocation(id="condition", value=condition))- graph.add_node(ForInvocation(id="for", collection=[1, 2]))+ graph.add_node(CollectionConcatInvocation(id="outer_source", first=[["a", "b"], ["c"]]))+ graph.add_node(IterateInvocation(id="outer"))+ graph.add_node(PolymorphicStringTestInvocation(id="inner_collection"))+ graph.add_node(IterateInvocation(id="inner"))+ graph.add_node(AnyTypeTestInvocation(id="body"))+ graph.add_node(CollectInvocation(id="branch_collect"))+ graph.add_node(FixedCollectionTestInvocation(id="condition"))+ graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))graph.add_node(IfInvocation(id="if"))- graph.add_node(MarkedAnyTypeTestInvocation(id="true_branch", marker="true:"))- graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="false:"))- graph.add_node(ForReturnInvocation(id="return"))- graph.add_edge(create_edge("condition", "value", "if", "condition"))- graph.add_edge(create_edge("for", "item", "true_branch", "value"))- graph.add_edge(create_edge("for", "item", "false_branch", "value"))- graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))- graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))- graph.add_edge(create_edge("if", "value", "return", "output"))- graph.add_edge(create_loop_linkage("for", "return"))+ graph.add_node(CollectInvocation(id="result_collect"))+ for source, source_field, destination, destination_field in (+ ("outer_source", "collection", "outer", "collection"),+ ("outer", "item", "inner_collection", "value"),+ ("inner_collection", "collection", "inner", "collection"),+ ("inner", "item", "body", "value"),+ ("body", "value", "branch_collect", "item"),+ ("outer", "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("branch_collect", "collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "result_collect", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- trace, state = _run_graph(GraphExecutionState(graph=graph))+ state = GraphExecutionState(graph=graph)++ trace, state = _run_graph(state)- selected_source = "true_branch" if condition else "false_branch"- unselected_source = "false_branch" if condition else "true_branch"- assert trace.count("condition") == 1- assert trace.count("for") == 2- assert trace.count(selected_source) == 2- assert trace.count("if") == 2- assert trace.count("return") == 2- assert unselected_source not in trace- assert sorted(state._get_iteration_path(exec_node_id) for exec_node_id in state.source_prepared_mapping["if"]) == [- (0,),- (1,),- ]- final_for_id = max(- state.source_prepared_mapping["for"],- key=lambda exec_node_id: state.execution_graph.get_node(exec_node_id).index,- )- assert state.results[final_for_id].output_collection == [f"{branch}1", f"{branch}2"]assert state.is_complete()- assert state.next() is None- assert not state._pending_if_exec_nodes- assert not state._ready_node_ids- assert all(not queue for queue in state._ready_queues.values())+ assert state.results[next(iter(state.source_prepared_mapping["result_collect"]))].collection == [+ ["a", "b"],+ ["c"],+ ][email protected]("force_compatibility_scheduler", [False, True])- ("first_condition", "second_condition", "third_condition"),- [- (True, True, True),- (True, True, False),- (True, False, True),- (True, False, False),- (False, True, True),- (False, True, False),- (False, False, True),- (False, False, False),- ],-)[email protected]("stop_after", range(1, 12))-def test_fresh_three_sibling_ifs_checkpoint_resume_matches_fresh_execution([email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_nested_collect_preserves_condition_frame_when_classifying_branch_iterate(force_compatibility_scheduler: bool,- first_condition: bool,- second_condition: bool,- third_condition: bool,- stop_after: int,) -> None:- graph = _three_sibling_if_graph(- first_condition=first_condition,- second_condition=second_condition,- third_condition=third_condition,- )- expected_trace, expected_state = _run_graph(- GraphExecutionState(graph=graph.model_copy(deep=True)),- force_compatibility_scheduler=force_compatibility_scheduler,- )- checkpoint_trace, checkpoint_state = _run_graph(- GraphExecutionState(graph=graph.model_copy(deep=True)),- force_compatibility_scheduler=force_compatibility_scheduler,- stop_after=stop_after,- )+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="outer_source", first=[1, 2]))+ graph.add_node(IterateInvocation(id="outer"))+ graph.add_node(RangeOfSizeInvocation(id="middle_range", size=1))+ graph.add_node(IterateInvocation(id="middle"))+ graph.add_node(CollectInvocation(id="middle_collect"))+ graph.add_node(CollectInvocation(id="middle_collect_2"))+ graph.add_node(IterateInvocation(id="inner"))+ graph.add_node(AddInvocation(id="body"))+ graph.add_node(CollectInvocation(id="branch_collect"))+ graph.add_node(FixedCollectionTestInvocation(id="condition"))+ graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(CollectInvocation(id="result_collect"))+ for source, source_field, destination, destination_field in (+ ("outer_source", "collection", "outer", "collection"),+ ("outer", "item", "middle_range", "start"),+ ("middle_range", "collection", "middle", "collection"),+ ("middle", "item", "middle_collect", "item"),+ ("middle_collect", "collection", "middle_collect_2", "collection"),+ ("middle_collect_2", "collection", "inner", "collection"),+ ("outer", "item", "body", "a"),+ ("inner", "item", "body", "b"),+ ("body", "value", "branch_collect", "item"),+ ("outer", "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("branch_collect", "collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "result_collect", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- restored = load_execution_state(dump_execution_state(checkpoint_state))+ state = GraphExecutionState(graph=graph)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 _state_projection(resumed_state) == _state_projection(expected_state)- assert _activation_projection(resumed_state) == _activation_projection(expected_state)- assert resumed_state.is_complete()-+ state._execution_scheduler = _ExecutionScheduler(state)-def test_sibling_if_unsupported_saved_workflow_keeps_controller_fallback(- monkeypatch: pytest.MonkeyPatch,-) -> None:- graph = _sibling_if_graph()- graph.add_node(CallSavedWorkflowInvocation(id="call", workflow_id="saved-workflow"))- state = GraphExecutionState(graph=graph)- branch_analysis_calls: list[tuple[str, str]] = []- original_branch_sources = graph_module._IfActivationController._branch_sources+ trace, state = _run_graph(state)- 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)+ assert state.is_complete(), (+ f"graph stalled after {trace}; pending={state._pending_if_exec_nodes}; "+ f"prepared={state.source_prepared_mapping}; indegree={state.indegree}; "+ f"resolved={state._resolved_if_exec_branches}; "+ f"unindexed={set(state.prepared_source_mapping) - state._if_activation_dependents_indexed_exec_ids}; "+ f"middle_axes={state._materializer().get_node_iterators('middle_body', state._get_source_graph_flat())}; "+ f"middle_mappings={list(state._materializer()._get_parent_iteration_mappings('middle_body', state._get_source_graph_flat()))}; "+ f"middle_dependencies={state._get_source_activation_dependencies('middle_body', (0,))}; "+ f"middle_admitted={state._is_source_activation_admitted('middle_body', (0,))}; "+ f"iterator_sources_executed={[(source_id, source_id in state.executed) for source_id in ('left', 'right')]}"+ )+ middle_collect_exec_ids = sorted(state.source_prepared_mapping["middle_collect"], key=state._get_iteration_path)+ assert [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection) for exec_id in middle_collect_exec_ids+ ] == [((0,), [1]), ((1,), [2])]+ middle_collect_2_exec_ids = sorted(state.source_prepared_mapping["middle_collect_2"], key=state._get_iteration_path)+ assert [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection) for exec_id in middle_collect_2_exec_ids+ ] == [((0,), [1]), ((1,), [2])]+ inner_exec_ids = sorted(state.source_prepared_mapping["inner"], key=state._get_iteration_path)+ assert [state._get_iteration_path(exec_id) for exec_id in inner_exec_ids] == [(0, 0), (1, 0)]+ branch_collect_exec_ids = sorted(state.source_prepared_mapping["branch_collect"], key=state._get_iteration_path)+ assert [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection) for exec_id in branch_collect_exec_ids+ ] == [((0,), [2]), ((1,), [4])]+ assert state.results[next(iter(state.source_prepared_mapping["result_collect"]))].collection == [[2], [4]]- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", record_branch_analysis)- assert not state._can_use_fresh_flat_if_activation()- dependencies = state._get_source_activation_dependencies("first_true", (7,))- assert {dependency.owner_id for dependency in dependencies} == {"first_if"}- assert branch_analysis_calls[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_direct_collect_collapses_condition_frame_for_branch_iterate(+ force_compatibility_scheduler: bool,+) -> None:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="outer_source", first=[1, 2]))+ graph.add_node(IterateInvocation(id="outer"))+ graph.add_node(CollectInvocation(id="middle_collect"))+ graph.add_node(IterateInvocation(id="inner"))+ graph.add_node(AddInvocation(id="body"))+ graph.add_node(CollectInvocation(id="branch_collect"))+ graph.add_node(FixedCollectionTestInvocation(id="condition"))+ graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(CollectInvocation(id="result_collect"))+ for source, source_field, destination, destination_field in (+ ("outer_source", "collection", "outer", "collection"),+ ("outer", "item", "middle_collect", "item"),+ ("middle_collect", "collection", "inner", "collection"),+ ("outer", "item", "body", "a"),+ ("inner", "item", "body", "b"),+ ("body", "value", "branch_collect", "item"),+ ("outer", "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("branch_collect", "collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "result_collect", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)-def test_indirectly_connected_sibling_ifs_match_controller_fallback() -> None:- expected_trace, expected_state = _run_graph(- GraphExecutionState(graph=_indirectly_connected_sibling_if_graph()),- force_compatibility_scheduler=True,- )- state = GraphExecutionState(graph=_indirectly_connected_sibling_if_graph())- assert not state._can_use_fresh_flat_if_activation()- assert not state._can_use_generic_scheduler()trace, state = _run_graph(state)- assert trace == expected_trace- assert _state_projection(state) == _state_projection(expected_state)assert state.is_complete()+ middle_collect_id = next(iter(state.source_prepared_mapping["middle_collect"]))+ assert state._get_iteration_path(middle_collect_id) == ()+ assert state.results[middle_collect_id].collection == [1, 2]+ inner_exec_ids = sorted(state.source_prepared_mapping["inner"], key=state._get_iteration_path)+ assert [state._get_iteration_path(exec_id) for exec_id in inner_exec_ids] == [+ (0, 0),+ (0, 1),+ (1, 0),+ (1, 1),+ ]+ assert state.results[next(iter(state.source_prepared_mapping["result_collect"]))].collection == [[2, 3], [3, 4]][email protected]("force_compatibility_scheduler", [False, True])- ("outer_condition", "inner_condition", "expected_trace"),- [- (- True,- True,- ["outer_condition", "inner_condition", "inner_true", "inner_if", "outer_if", "sink"],- ),- (- True,- False,- ["outer_condition", "inner_condition", "inner_false", "inner_if", "outer_if", "sink"],- ),- (False, True, ["outer_condition", "outer_false", "outer_if", "sink"]),- (False, False, ["outer_condition", "outer_false", "outer_if", "sink"]),- ],-)-def test_fresh_nested_if_records_graph_state_dependencies_without_controller_analysis([email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("node_order", ["original", "reverse", "seed7", "renamed", "renamed_producers"])+def test_independent_iterator_collect_preserves_ordered_parent_axis_for_branch_iterate(force_compatibility_scheduler: bool,- outer_condition: bool,- inner_condition: bool,- expected_trace: list[str],- monkeypatch: pytest.MonkeyPatch,+ node_order: str,) -> None:- def fail_branch_analysis(*_: object, **__: object) -> set[str]:- raise AssertionError("fresh nested If used controller-owned branch analysis")-- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)-- graph = _nested_if_graph()- graph.get_node("outer_condition").value = outer_condition- graph.get_node("inner_condition").value = inner_condition- state = GraphExecutionState(graph=graph)- dependencies_by_source = {- source_id: {- (dependency.owner_id, dependency.branch, dependency.frame)- for dependency in state._get_source_activation_dependencies(source_id)- }- for source_id in {"inner_condition", "inner_true", "inner_false", "inner_if"}- }-- trace, state = _run_graph(- state,- force_compatibility_scheduler=force_compatibility_scheduler,+ graph = Graph()+ condition_axis_id, other_axis_id = ("z_condition", "a_other") if node_order == "renamed" else ("left", "right")+ condition_source_id, other_source_id = (+ ("z_condition_source", "a_other_source")+ if node_order == "renamed_producers"+ else ("left_source", "right_source"))-- assert trace == expected_trace- assert dependencies_by_source == {- "inner_condition": {("outer_if", "true_input", ())},- "inner_true": {("outer_if", "true_input", ()), ("inner_if", "true_input", ())},- "inner_false": {("outer_if", "true_input", ()), ("inner_if", "false_input", ())},- "inner_if": {("outer_if", "true_input", ())},+ nodes = {+ condition_source_id: CollectionConcatInvocation(id=condition_source_id, first=[1, 2]),+ condition_axis_id: IterateInvocation(id=condition_axis_id),+ other_source_id: CollectionConcatInvocation(id=other_source_id, first=[10, 20]),+ other_axis_id: IterateInvocation(id=other_axis_id),+ "middle_body": AddInvocation(id="middle_body"),+ "middle_collect": CollectInvocation(id="middle_collect"),+ "candidate": IterateInvocation(id="candidate"),+ "body": AddInvocation(id="body"),+ "branch_collect": CollectInvocation(id="branch_collect"),+ "condition": FixedCollectionTestInvocation(id="condition"),+ "fallback": AnyTypeTestInvocation(id="fallback", value="fallback"),+ "if": IfInvocation(id="if"),+ "result_collect": CollectInvocation(id="result_collect"),}- assert state.is_complete()--- ("outer_condition", "middle_condition", "inner_condition", "selected", "expected_value", "expected_trace"),- [- (- True,- True,- True,- "inner_true",- 5,- [- "outer_condition",- "middle_condition",- "inner_condition",- "inner_true",- "inner_if",- "middle_if",- "outer_if",- "sink",- ],- ),- (- True,- True,- False,- "inner_false",- 7,- [- "outer_condition",- "middle_condition",- "inner_condition",- "inner_false",- "inner_if",- "middle_if",- "outer_if",- "sink",- ],- ),- (- True,- False,- True,- "middle_false",- 11,- ["outer_condition", "middle_condition", "middle_false", "middle_if", "outer_if", "sink"],- ),- (- True,- False,- False,- "middle_false",- 11,- ["outer_condition", "middle_condition", "middle_false", "middle_if", "outer_if", "sink"],- ),- (False, True, True, "outer_false", 21, ["outer_condition", "outer_false", "outer_if", "sink"]),- (False, True, False, "outer_false", 21, ["outer_condition", "outer_false", "outer_if", "sink"]),- (False, False, True, "outer_false", 21, ["outer_condition", "outer_false", "outer_if", "sink"]),- (False, False, False, "outer_false", 21, ["outer_condition", "outer_false", "outer_if", "sink"]),- ],-)-def test_fresh_three_nested_ifs_select_only_branches_and_match_compatibility(- outer_condition: bool,- middle_condition: bool,- inner_condition: bool,- selected: str,- expected_value: int,- expected_trace: list[str],- monkeypatch: pytest.MonkeyPatch,-) -> None:- def fail_branch_analysis(*_: object, **__: object) -> set[str]:- raise AssertionError("fresh three-nested If used controller-owned branch analysis")+ ordered_node_ids = list(nodes)+ if node_order == "reverse":+ ordered_node_ids.reverse()+ elif node_order == "seed7":+ ordered_node_ids = random.Random(7).sample(ordered_node_ids, len(ordered_node_ids))+ for node_id in ordered_node_ids:+ graph.add_node(nodes[node_id])+ for source, source_field, destination, destination_field in (+ (condition_source_id, "collection", condition_axis_id, "collection"),+ (other_source_id, "collection", other_axis_id, "collection"),+ (condition_axis_id, "item", "middle_body", "a"),+ (other_axis_id, "item", "middle_body", "b"),+ ("middle_body", "value", "middle_collect", "item"),+ ("middle_collect", "collection", "candidate", "collection"),+ (condition_axis_id, "item", "body", "a"),+ ("candidate", "item", "body", "b"),+ ("body", "value", "branch_collect", "item"),+ (condition_axis_id, "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("branch_collect", "collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "result_collect", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)- runs: list[tuple[list[str], GraphExecutionState]] = []- for force_compatibility_scheduler in (False, True):- state = GraphExecutionState(- graph=_three_nested_if_graph(- outer_condition=outer_condition,- middle_condition=middle_condition,- inner_condition=inner_condition,- )- )- assert state._can_use_fresh_flat_if_activation()- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- runs.append((trace, state))+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)- assert trace == expected_trace- expected_source_ids = set(expected_trace)- assert expected_source_ids.issubset(state.source_prepared_mapping)- assert all(- not execution_ids- for source_id, execution_ids in state.source_prepared_mapping.items()- if source_id not in expected_source_ids- )- assert selected in trace- sink_id = next(iter(state.source_prepared_mapping["sink"]))- assert state.results[sink_id].value == expected_value- assert state.is_complete()+ trace, state = _run_graph(state)- _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 state.is_complete(), f"graph stalled after {trace}"+ middle_collect_exec_ids = sorted(state.source_prepared_mapping["middle_collect"], key=state._get_iteration_path)+ assert [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection) for exec_id in middle_collect_exec_ids+ ] == [((0,), [11, 21]), ((1,), [12, 22])]+ candidate_exec_ids = sorted(state.source_prepared_mapping["candidate"], key=state._get_iteration_path)+ assert [state._get_iteration_path(exec_id) for exec_id in candidate_exec_ids] == [+ (0, 0),+ (0, 1),+ (1, 0),+ (1, 1),+ ]+ assert state.results[next(iter(state.source_prepared_mapping["result_collect"]))].collection == [+ [12, 22],+ [14, 24],+ ][email protected]("middle_branch", ["true_input", "false_input"])[email protected]("outer_branch", ["true_input", "false_input"])-def test_fresh_three_nested_ifs_support_direct_false_parent_branch_edges(- middle_branch: str,- outer_branch: str,- monkeypatch: pytest.MonkeyPatch,[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+ ("xs", "expected"),+ [+ ([], []),+ ([True], ["T"]),+ ],+ ids=["empty-condition", "non-empty-condition"],+)+def test_iterate_if_condition_completes_after_invoking_both_branches(+ force_compatibility_scheduler: bool,+ xs: list[bool],+ expected: list[str],) -> None:- def fail_branch_analysis(*_: object, **__: object) -> set[str]:- raise AssertionError("fresh three-nested If used controller-owned branch analysis")-- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)- graph = _three_nested_if_graph(- outer_condition=outer_branch == "true_input",- middle_condition=middle_branch == "true_input",- middle_branch=middle_branch,- outer_branch=outer_branch,- )+ graph = Graph()+ for node in (+ CollectionConcatInvocation(id="xs", first=xs),+ IterateInvocation(id="iterate"),+ AnyTypeTestInvocation(id="true_value", value="T"),+ AnyTypeTestInvocation(id="false_value", value="F"),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ):+ graph.add_node(node)+ for source, source_field, destination, destination_field in (+ ("xs", "collection", "iterate", "collection"),+ ("iterate", "item", "if", "condition"),+ ("true_value", "value", "if", "true_input"),+ ("false_value", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- 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))+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)+ trace, state = _run_graph(state)- assert trace == [- "outer_condition",- "middle_condition",- "inner_condition",- "inner_true",- "inner_if",- "middle_if",- "outer_if",- "sink",- ]- expected_source_ids = set(trace)- assert expected_source_ids.issubset(state.source_prepared_mapping)- assert all(- not execution_ids- for source_id, execution_ids in state.source_prepared_mapping.items()- if source_id not in expected_source_ids- )- assert state.results[next(iter(state.source_prepared_mapping["sink"]))].value == 5- assert state.is_complete()+ if xs:+ assert trace[:2] == ["xs", "iterate"]+ assert trace[-2:] == ["if", "collect"]+ assert trace.count("true_value") == trace.count("false_value") == 1+ assert trace.index("true_value") < trace.index("if")+ assert trace.index("false_value") < trace.index("if")+ else:+ assert trace == ["xs", "collect"]+ collect_exec_id = next(iter(state.source_prepared_mapping["collect"]))+ assert state.results[collect_exec_id].collection == expected+ assert not state.has_error()+ assert state.is_complete(), f"graph stalled after {trace}"+ if xs:+ assert state.executed_history.index("true_value") < state.executed_history.index("if")+ assert state.executed_history.index("false_value") < state.executed_history.index("if")+ if not xs:+ assert state.source_prepared_mapping["true_value"] == set()+ assert state.source_prepared_mapping["false_value"] == set()+ else:+ assert state.source_prepared_mapping["true_value"]+ assert state.source_prepared_mapping["false_value"]- _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])+ restored = load_execution_state(dump_execution_state(state))+ assert restored.is_complete()+ assert restored.executed_history == state.executed_history+ restored_collect_exec_id = next(iter(restored.source_prepared_mapping["collect"]))+ assert restored.results[restored_collect_exec_id].collection == expected[email protected]("force_compatibility_scheduler", [False, True])[email protected]("stop_after", range(1, 10))-def test_fresh_three_nested_ifs_shared_ancestor_isolated_and_checkpoint_resumes(- force_compatibility_scheduler: bool,- stop_after: int,- monkeypatch: pytest.MonkeyPatch,-) -> None:- def fail_branch_analysis(*_: object, **__: object) -> set[str]:- raise AssertionError("fresh three-nested If used controller-owned branch analysis")[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_if_allows_shared_condition_and_branch_iterator_axis(force_compatibility_scheduler: bool) -> None:+ graph = Graph()+ for node in (+ CollectionConcatInvocation(id="source", first=[1, 0]),+ IterateInvocation(id="iterate"),+ FixedCollectionTestInvocation(id="condition"),+ AnyTypeTestInvocation(id="branch"),+ AnyTypeTestInvocation(id="fallback", value="fallback"),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ):+ graph.add_node(node)+ for source, source_field, destination, destination_field in (+ ("source", "collection", "iterate", "collection"),+ ("iterate", "item", "condition", "value"),+ ("iterate", "item", "branch", "value"),+ ("condition", "condition", "if", "condition"),+ ("branch", "value", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)- graph = _three_nested_if_graph_with_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,+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler)- 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)- combined_trace = checkpoint_trace + resumed_trace- assert combined_trace == expected_trace- assert resumed_state.executed_history == expected_state.executed_history- assert resumed_state.results[next(iter(resumed_state.source_prepared_mapping["sink"]))].value == 6- assert resumed_state.is_complete()- assert resumed_state.executed_history.count("shared") == 1- assert _state_projection(resumed_state) == _state_projection(expected_state)- assert _activation_projection(resumed_state) == _activation_projection(expected_state)+ assert state.is_complete(), f"graph stalled after {trace}"+ result_exec_id = next(iter(state.source_prepared_mapping["collect"]))+ assert state.results[result_exec_id].collection == [1, "fallback"][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")+def test_if_iteration_axis_validation_cache_invalidates_after_graph_edit() -> None:+ graph = Graph()+ for node in (+ CollectionConcatInvocation(id="branch_source", first=[10, 20]),+ IterateInvocation(id="branch_iterate"),+ AnyTypeTestInvocation(id="branch_value"),+ CollectionConcatInvocation(id="condition_source", first=[1]),+ IterateInvocation(id="condition_iterate"),+ FixedCollectionTestInvocation(id="condition"),+ IfInvocation(id="if"),+ ):+ graph.add_node(node)+ for source, source_field, destination, destination_field in (+ ("branch_source", "collection", "branch_iterate", "collection"),+ ("branch_iterate", "item", "branch_value", "value"),+ ("condition_source", "collection", "condition_iterate", "collection"),+ ("condition_iterate", "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- 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.next() is not None+ state.add_edge(create_edge("branch_value", "value", "if", "true_input"))- assert state._can_use_fresh_flat_if_activation()- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)-- assert trace == expected_trace- expected_source_ids = set(expected_trace)- assert expected_source_ids.issubset(state.source_prepared_mapping)- assert all(- not execution_ids- for source_id, execution_ids in state.source_prepared_mapping.items()- if source_id not in expected_source_ids- )- 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 state.source_prepared_mapping.get("middle_side_consumer", set()) == set()- assert state.is_complete()-+ with pytest.raises(+ graph_if_runtime.UnsupportedIfIterationAxesError,+ match=(+ r"If node 'if' cannot select branch input 'true_input' from unrelated open iterator axes: "+ r"condition \['condition_iterate'\], branch \['branch_iterate'\]"+ ),+ ):+ state.next()[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()[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_if_rejects_sibling_inner_iterator_axes_with_shared_outer_axis(force_compatibility_scheduler: bool) -> None:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="outer_source", first=["truth"]))+ graph.add_node(IterateInvocation(id="outer"))+ graph.add_node(PolymorphicStringTestInvocation(id="left_source"))+ graph.add_node(IterateInvocation(id="left"))+ graph.add_node(FixedCollectionTestInvocation(id="right_source"))+ graph.add_node(IterateInvocation(id="right"))+ graph.add_node(FixedCollectionTestInvocation(id="condition"))+ graph.add_node(AnyTypeTestInvocation(id="branch"))+ graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(CollectInvocation(id="collect"))+ for source, source_field, destination, destination_field in (+ ("outer_source", "collection", "outer", "collection"),+ ("outer", "item", "left_source", "value"),+ ("left_source", "collection", "left", "collection"),+ ("outer", "item", "right_source", "value"),+ ("right_source", "collection", "right", "collection"),+ ("left", "item", "condition", "value"),+ ("right", "item", "branch", "value"),+ ("condition", "condition", "if", "condition"),+ ("branch", "value", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- assert runs[0][0] == runs[1][0]- assert _state_projection(runs[0][1]) == _state_projection(runs[1][1])+ graph.validate_self()+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)+ with pytest.raises(+ graph_if_runtime.UnsupportedIfIterationAxesError,+ match="cannot select branch input 'true_input' from unrelated open iterator axes",+ ):+ _run_graph(state)[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")[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_sibling_collect_cannot_feed_multiple_if_branches(force_compatibility_scheduler: bool) -> None:+ graph = Graph()+ for node in (+ CollectionConcatInvocation(id="left_source", first=[0, 1]),+ CollectionConcatInvocation(id="right_source", first=[10, 20]),+ IterateInvocation(id="left"),+ IterateInvocation(id="right"),+ AddInvocation(id="body"),+ CollectInvocation(id="branch_collect"),+ FixedCollectionTestInvocation(id="left_condition"),+ AddInvocation(id="right_minus_one", b=-1),+ FixedCollectionTestInvocation(id="right_condition"),+ AnyTypeTestInvocation(id="fallback", value="fallback"),+ IfInvocation(id="left_if"),+ IfInvocation(id="right_if"),+ CollectInvocation(id="left_result"),+ CollectInvocation(id="right_result"),+ ):+ graph.add_node(node)+ for source, source_field, destination, destination_field in (+ ("left_source", "collection", "left", "collection"),+ ("right_source", "collection", "right", "collection"),+ ("left", "item", "body", "a"),+ ("right", "item", "body", "b"),+ ("body", "value", "branch_collect", "item"),+ ("left", "item", "left_condition", "value"),+ ("left", "item", "right_minus_one", "a"),+ ("right_minus_one", "value", "right_condition", "value"),+ ("left_condition", "condition", "left_if", "condition"),+ ("right_condition", "condition", "right_if", "condition"),+ ("branch_collect", "collection", "left_if", "true_input"),+ ("branch_collect", "collection", "right_if", "true_input"),+ ("fallback", "value", "left_if", "false_input"),+ ("fallback", "value", "right_if", "false_input"),+ ("left_if", "value", "left_result", "item"),+ ("right_if", "value", "right_result", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- 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))+ graph.validate_self()+ state = GraphExecutionState(graph=graph)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()+ state._execution_scheduler = _ExecutionScheduler(state)+ with pytest.raises(ValueError, match="cannot supply Collect-backed inputs to multiple If nodes"):+ _run_graph(state)- "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 test_1000_node_any_chain_inside_iterate_if_completes_with_eager_branches() -> None:+ chain_length = 1_000+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="source", first=[True, False]))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="f"))+ for index in range(chain_length):+ graph.add_node(AnyTypeTestInvocation(id=f"chain_{index}"))+ graph.add_edge(create_edge("source", "collection", "iterate", "collection"))+ graph.add_edge(create_edge("iterate", "item", "if", "condition"))+ graph.add_edge(create_edge("iterate", "item", "chain_0", "value"))+ graph.add_edge(create_edge("iterate", "item", "false_branch", "value"))+ graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))+ for index in range(chain_length - 1):+ graph.add_edge(create_edge(f"chain_{index}", "value", f"chain_{index + 1}", "value"))+ graph.add_edge(create_edge(f"chain_{chain_length - 1}", "value", "if", "true_input"))+ graph.add_edge(create_edge("if", "value", "collect", "item"))- 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)+ state = GraphExecutionState(graph=graph)+ original_recursion_limit = sys.getrecursionlimit()+ try:+ sys.setrecursionlimit(len(inspect.stack()) + 250)+ trace, state = _run_graph(state)+ finally:+ sys.setrecursionlimit(original_recursion_limit)- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", record_branch_analysis)- state = GraphExecutionState(graph=graph_factory())+ collect_exec_id = next(iter(state.source_prepared_mapping["collect"]))+ assert state.results[collect_exec_id].collection == [True, "fFalse"]+ assert all(trace.count(f"chain_{index}") == 2 for index in range(chain_length))+ assert trace.count("false_branch") == 2+ assert state.is_complete(), f"graph stalled after {trace[-8:]}"- assert not state._can_use_fresh_flat_if_activation()- state._get_source_activation_dependencies("inner_true")- assert branch_analysis_calls+def test_execution_materializer_cache_refreshes_after_sibling_iterate_edge_addition() -> None:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="left_source", first=[2, 2]))+ graph.add_node(CollectionConcatInvocation(id="right_source", first=[10, 20]))+ graph.add_node(IterateInvocation(id="left"))+ graph.add_node(IterateInvocation(id="right"))+ graph.add_node(AddInvocation(id="body"))+ graph.add_node(CollectInvocation(id="branch_collect"))+ graph.add_node(AddInvocation(id="minus_one", b=-1))+ graph.add_node(FixedCollectionTestInvocation(id="condition"))+ graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(CollectInvocation(id="collect"))+ for source, source_field, destination, destination_field in (+ ("left_source", "collection", "left", "collection"),+ ("right_source", "collection", "right", "collection"),+ ("left", "item", "body", "a"),+ ("body", "value", "branch_collect", "item"),+ ("left", "item", "minus_one", "a"),+ ("minus_one", "value", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("branch_collect", "collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- ("outer_condition", "inner_condition", "expected_value"),- [(True, True, 5), (True, False, 6), (False, True, 11), (False, False, 11)],-)-def test_fresh_nested_if_preserves_shared_ancestor_isolation(- outer_condition: bool,- inner_condition: bool,- expected_value: int,- monkeypatch: pytest.MonkeyPatch,-) -> None:- def fail_branch_analysis(*_: object, **__: object) -> set[str]:- raise AssertionError("fresh nested If used controller-owned branch analysis")+ state = GraphExecutionState(graph=graph)+ first_node = state.next()+ assert first_node is not None+ first_source = state.prepared_source_mapping[first_node.id]+ state.complete(first_node.id, first_node.invoke(Mock()))- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)- graph = _nested_if_graph_with_shared_ancestor()- graph.get_node("outer_condition").value = outer_condition- graph.get_node("inner_condition").value = inner_condition+ state.add_edge(create_edge("right", "item", "body", "b"))- trace, state = _run_graph(GraphExecutionState(graph=graph))+ trace, state = _run_graph(state)- assert trace.count("shared") == int(outer_condition)- assert ("inner_true" in trace) is (outer_condition and inner_condition)- assert ("inner_false" in trace) is (outer_condition and not inner_condition)- assert trace.count("outer_false") == int(not outer_condition)- sink_id = next(iter(state.source_prepared_mapping["sink"]))- assert state.results[sink_id].value == expected_value+ collect_exec_id = next(iter(state.source_prepared_mapping["collect"]))+ assert state.results[collect_exec_id].collection == [[12, 22], [12, 22]]+ assert "right" in trace or first_source == "right"+ assert "body" in traceassert state.is_complete()[email protected]("force_compatibility_scheduler", [False, True])-def test_fresh_noncanonical_if_compiles_branch_membership_without_controller_analysis(- force_compatibility_scheduler: bool,- monkeypatch: pytest.MonkeyPatch,[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_if_diamond_branch_traversal_scales_with_graph_size(+ force_compatibility_scheduler: bool, monkeypatch: pytest.MonkeyPatch) -> None:- def fail_branch_analysis(*_: object, **__: object) -> set[str]:- raise AssertionError("fresh noncanonical If used controller-owned branch analysis")+ diamond_count = 16+ graph = Graph()+ graph.add_node(AnyTypeTestInvocation(id="source", value=1))+ graph.add_node(IfInvocation(id="if", condition=True))+ graph.add_node(AnyTypeTestInvocation(id="result"))+ previous_node_id = "source"+ for index in range(diamond_count):+ left_id = f"left_{index}"+ right_id = f"right_{index}"+ merge_id = f"merge_{index}"+ graph.add_node(AnyTypeTestInvocation(id=left_id))+ graph.add_node(AnyTypeTestInvocation(id=right_id))+ graph.add_node(AddInvocation(id=merge_id))+ graph.add_edge(create_edge(previous_node_id, "value", left_id, "value"))+ graph.add_edge(create_edge(previous_node_id, "value", right_id, "value"))+ graph.add_edge(create_edge(left_id, "value", merge_id, "a"))+ graph.add_edge(create_edge(right_id, "value", merge_id, "b"))+ previous_node_id = merge_id+ graph.add_edge(create_edge(previous_node_id, "value", "if", "true_input"))+ graph.add_edge(create_edge("if", "value", "result", "value"))- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", fail_branch_analysis)+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)- trace, state = _run_graph(- GraphExecutionState(graph=_noncanonical_flat_if_graph()),- force_compatibility_scheduler=force_compatibility_scheduler,- )+ original_get_node = Graph.get_node+ original_if_paths = graph_if_runtime._get_if_iteration_paths_with_ancestry+ if_path_node_visits = 0+ if_path_depth = 0- assert trace == ["condition", "true_source", "true_branch", "if", "sink"]- dependencies_by_source = {- source_id: {- (dependency.owner_id, dependency.branch, dependency.frame)- for execution_id, source_id in state.prepared_source_mapping.items()- for dependency in state._if_activation_dependencies_by_exec.get(execution_id, ())- }- for source_id in {"true_source", "true_branch"}- }- assert dependencies_by_source == {- "true_source": {("if", "true_input", ())},- "true_branch": {("if", "true_input", ())},- }- assert state.is_complete()+ def count_node_visits(self: Graph, node_id: str):+ nonlocal if_path_node_visits+ if if_path_depth:+ if_path_node_visits += 1+ return original_get_node(self, node_id)+ def count_if_path_work(*args: Any, **kwargs: Any):+ nonlocal if_path_depth+ if_path_depth += 1+ try:+ return original_if_paths(*args, **kwargs)+ finally:+ if_path_depth -= 1[email protected]("force_compatibility_scheduler", [False, True])-def test_fresh_if_dependency_cache_refreshes_after_branch_source_graph_edit(- force_compatibility_scheduler: bool,-) -> None:- state = GraphExecutionState(graph=_flat_if_graph(condition=False))+ monkeypatch.setattr(Graph, "get_node", count_node_visits)+ monkeypatch.setattr(graph_if_runtime, "_get_if_iteration_paths_with_ancestry", count_if_path_work)+ trace, state = _run_graph(state)- assert state._get_source_activation_dependencies("true_branch") == (- graph_module.ActivationDependency(owner_id="if", branch="true_input", frame=()),+ result_exec_id = next(iter(state.source_prepared_mapping["result"]))+ assert state.results[result_exec_id].value == 2**diamond_count+ assert state.is_complete(), f"graph stalled after {trace}"+ assert if_path_node_visits < 100 * len(graph.nodes), (+ f"If path inference visited {if_path_node_visits} graph nodes for {len(graph.nodes)} nodes")- state.add_node(AddInvocation(id="true_consumer", b=1))- state.add_edge(create_edge("true_branch", "value", "true_consumer", "a"))- assert state._get_source_activation_dependencies("true_branch") == ()- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+ ("xs", "ys", "expected"),+ [+ ([1, 1, 0], [10, 20, 30], [[10, 20, 30], [10, 20, 30], "fb"]),+ ([1, 0], [10, 20], [[10, 20], "fb"]),+ ([0, 1], [10, 20], ["fb", [10, 20]]),+ ],+ ids=["false-last", "false-last-short", "false-first"],+)+def test_per_item_if_preserves_unrelated_root_collect_frames(+ force_compatibility_scheduler: bool,+ xs: list[int],+ ys: list[int],+ expected: list[Any],+) -> None:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="xs", first=xs))+ graph.add_node(IterateInvocation(id="x"))+ graph.add_node(CollectionConcatInvocation(id="ys", first=ys))+ graph.add_node(IterateInvocation(id="y"))+ graph.add_node(AnyTypeTestInvocation(id="yv"))+ graph.add_node(CollectInvocation(id="branch_collect"))+ graph.add_node(AnyTypeTestInvocation(id="fallback", value="fb"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(CollectInvocation(id="output"))+ for source, source_field, destination, destination_field in (+ ("xs", "collection", "x", "collection"),+ ("x", "item", "if", "condition"),+ ("ys", "collection", "y", "collection"),+ ("y", "item", "yv", "value"),+ ("yv", "value", "branch_collect", "item"),+ ("branch_collect", "collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "output", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- assert trace == ["true_branch", "true_consumer", "condition", "false_branch", "if", "sink"]- assert state.results[next(iter(state.source_prepared_mapping["true_consumer"]))].value == 6- assert state.results[next(iter(state.source_prepared_mapping["sink"]))].value == 31- assert state.is_complete()+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)+ trace, state = _run_graph(state)+ assert state.is_complete(), f"graph stalled after {trace}"+ output_exec_id = next(iter(state.source_prepared_mapping["output"]))+ assert state.results[output_exec_id].collection == expected-def test_fresh_flat_if_with_saved_workflow_uses_controller_fallback(- monkeypatch: pytest.MonkeyPatch,-) -> None:- graph = _flat_if_graph()- graph.delete_node("sink")- graph.add_node(CallSavedWorkflowInvocation(id="call", workflow_id="saved-workflow"))- graph.add_edge(create_edge("if", "value", "call", "saved_workflow_input::input::value"))- state = GraphExecutionState(graph=graph)- 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)[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+ ("conditions", "expected"),+ [+ pytest.param([False, True, True], ["fb", [5, 6], [5, 6]], id="mixed-conditions"),+ pytest.param([True, True], [[5, 6], [5, 6]], id="all-true"),+ pytest.param([False, False, False], ["fb", "fb", "fb"], id="all-false"),+ ],+)+def test_per_item_if_keeps_closed_for_output_collection(+ force_compatibility_scheduler: bool,+ conditions: list[bool],+ expected: list[Any],+) -> None:+ """Root For item paths are distinct from condition frames; no selected frame means no For work."""+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="conditions", first=conditions))+ graph.add_node(IterateInvocation(id="condition_iterate"))+ graph.add_node(ForInvocation(id="for", collection=[5, 6], state=LoopState(values={"count": 0})))+ graph.add_node(AnyTypeTestInvocation(id="body"))+ graph.add_node(ForReturnInvocation(id="for_return"))+ graph.add_node(AnyTypeTestInvocation(id="fallback", value="fb"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(CollectInvocation(id="output"))+ for source, source_field, destination, destination_field in (+ ("conditions", "collection", "condition_iterate", "collection"),+ ("condition_iterate", "item", "if", "condition"),+ ("for", "item", "body", "value"),+ ("body", "value", "for_return", "output"),+ ("for", "output_collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "output", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))+ graph.add_edge(create_loop_linkage("for", "for_return"))- monkeypatch.setattr(graph_module._IfActivationController, "_branch_sources", record_branch_analysis)+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)+ trace, state = _run_graph(state)- assert not state._can_use_fresh_flat_if_activation()- assert state._get_source_activation_dependencies("true_branch") == (- graph_module.ActivationDependency(owner_id="if", branch="true_input", frame=()),- )- assert branch_analysis_calls+ assert state.is_complete(), f"graph stalled after {trace}"+ output_exec_id = next(iter(state.source_prepared_mapping["output"]))+ assert state.results[output_exec_id].collection == expected+ if any(conditions):+ final_for_exec_id = max(+ state.source_prepared_mapping["for"],+ key=lambda exec_node_id: state.execution_graph.get_node(exec_node_id).index,+ )+ assert state.results[final_for_exec_id].output_collection == [5, 6]+ else:+ assert {"for", "body", "for_return"} <= set(trace)[email protected]("unsupported_shape", ["extra_if", "mixed_iterate", "inner_fanout"])-def test_nested_if_unsupported_shapes_use_controller_fallback(- unsupported_shape: str,- monkeypatch: pytest.MonkeyPatch,[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("extra_source", ["right", "branch_collect"])+def test_deferred_sibling_iterate_does_not_starve_ready_consumers(+ force_compatibility_scheduler: bool,+ extra_source: str,) -> None:- graph = _nested_if_graph()- if unsupported_shape == "extra_if":- graph.add_node(IfInvocation(id="extra_if"))- elif unsupported_shape == "mixed_iterate":- graph.add_node(RangeInvocation(id="extra_range", start=0, stop=1, step=1))- graph.add_node(IterateInvocation(id="extra_iterate"))- graph.add_edge(create_edge("extra_range", "collection", "extra_iterate", "collection"))- else:- graph.add_node(AddInvocation(id="inner_side_consumer", b=1))- graph.add_edge(create_edge("inner_if", "value", "inner_side_consumer", "a"))+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="left_source", first=[1, 2]))+ graph.add_node(CollectionConcatInvocation(id="right_source", first=[10, 20]))+ graph.add_node(IterateInvocation(id="left"))+ graph.add_node(IterateInvocation(id="right"))+ graph.add_node(AddInvocation(id="body"))+ graph.add_node(CollectInvocation(id="branch_collect"))+ graph.add_node(AddInvocation(id="minus_one", b=-1))+ graph.add_node(FixedCollectionTestInvocation(id="condition"))+ graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(CollectInvocation(id="output"))+ graph.add_node(AnyTypeTestInvocation(id="extra"))+ for source, source_field, destination, destination_field in (+ ("left_source", "collection", "left", "collection"),+ ("right_source", "collection", "right", "collection"),+ ("left", "item", "body", "a"),+ ("right", "item", "body", "b"),+ ("body", "value", "branch_collect", "item"),+ ("left", "item", "minus_one", "a"),+ ("minus_one", "value", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("branch_collect", "collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "output", "item"),+ (extra_source, "item" if extra_source == "right" else "collection", "extra", "value"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))state = GraphExecutionState(graph=graph)- 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)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)+ trace, state = _run_graph(state)- assert not state._can_use_fresh_flat_if_activation()- dependencies = state._get_source_activation_dependencies("inner_true")- assert {dependency.owner_id for dependency in dependencies} >= {"inner_if"}- assert branch_analysis_calls+ assert state.is_complete(), f"graph stalled after {trace}"+ output_exec_id = next(iter(state.source_prepared_mapping["output"]))+ assert state.results[output_exec_id].collection == ["fallback", [12, 22]]+ assert "extra" in trace[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("reverse_node_insertion", [False, True], ids=["forward-insertion", "reverse-insertion"])@pytest.mark.parametrize(- ("outer_condition", "inner_condition", "expected_trace", "expected_history", "expected_value"),+ ("source_a", "iterate_a", "source_b", "iterate_b"),[- (- 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,- ),+ ("zz_source", "zz_iterate", "aa_source", "aa_iterate"),+ ("p_source", "q_iterate", "x_source", "y_iterate"),],+ ids=["reverse-lexical-ids", "alternate-ids"],)-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,+def test_independent_iterate_axes_follow_add_input_order(+ force_compatibility_scheduler: bool,+ reverse_node_insertion: bool,+ source_a: str,+ iterate_a: str,+ source_b: str,+ iterate_b: str,) -> None:- graph = _nested_if_graph()- graph.get_node("outer_condition").value = outer_condition- graph.get_node("inner_condition").value = inner_condition+ nodes = [+ CollectionConcatInvocation(id=source_a, first=[10, 20]),+ IterateInvocation(id=iterate_a),+ CollectionConcatInvocation(id=source_b, first=[1, 2, 3]),+ IterateInvocation(id=iterate_b),+ AddInvocation(id="sum"),+ CollectInvocation(id="output"),+ ]+ if reverse_node_insertion:+ nodes.reverse()+ graph = Graph(nodes={node.id: node for node in nodes})+ for source, source_field, destination, destination_field in (+ (source_a, "collection", iterate_a, "collection"),+ (source_b, "collection", iterate_b, "collection"),+ (iterate_a, "item", "sum", "a"),+ (iterate_b, "item", "sum", "b"),+ ("sum", "value", "output", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- def fail_edge_deletion(*_: object, **__: object) -> None:- raise AssertionError("fresh generic If execution deleted an execution edge")+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)+ _, state = _run_graph(state)- generic_retired_nodes: list[str] = []- original_discard = _GenericGraphSchedulerAdapter._retire_unselected_node+ output_exec_ids = sorted(state.source_prepared_mapping["output"], key=state._get_iteration_path)+ actual = [(state._get_iteration_path(exec_id), state.results[exec_id].collection) for exec_id in output_exec_ids]+ assert actual == [((0,), [11, 12, 13]), ((1,), [21, 22, 23])]+ assert state.is_complete()- 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(_GenericGraphSchedulerAdapter, "_retire_unselected_node", record_generic_discard)- monkeypatch.setattr(GraphExecutionState, "_tx_delete_execution_edge", fail_edge_deletion)[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+ ("condition", "wire_opposite_root"),+ [(True, True), (False, True), (False, False)],+ ids=["true-with-root-false", "false-with-root-true", "false-without-true-input"],+)+def test_literal_if_inside_iterate_uses_selected_branch_frame(+ force_compatibility_scheduler: bool,+ condition: bool,+ wire_opposite_root: bool,+) -> None:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="source", first=[1, 2]))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(IfInvocation(id="if", condition=condition))+ graph.add_node(CollectInvocation(id="output"))+ graph.add_edge(create_edge("source", "collection", "iterate", "collection"))+ selected_branch = "true_input" if condition else "false_input"+ selected_source = "true_branch" if condition else "false_branch"+ opposite_branch = "false_input" if condition else "true_input"+ graph.add_node(MarkedAnyTypeTestInvocation(id=selected_source, marker=f"{selected_branch}:"))+ graph.add_edge(create_edge("iterate", "item", selected_source, "value"))+ graph.add_edge(create_edge(selected_source, "value", "if", selected_branch))+ if wire_opposite_root:+ graph.add_node(AnyTypeTestInvocation(id="root_opposite", value="root"))+ graph.add_edge(create_edge("root_opposite", "value", "if", opposite_branch))+ graph.add_edge(create_edge("if", "value", "output", "item"))- trace, state = _run_graph(GraphExecutionState(graph=graph))+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)+ trace, state = _run_graph(state)- 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) == _expected_edge_projection(- graph,- force_compatibility_scheduler=False,- outer_condition=outer_condition,- inner_condition=inner_condition,+ assert state.is_complete(), (+ f"graph stalled after {trace}; prepared_paths={[(source_id, [state._get_iteration_path(exec_id) for exec_id in exec_ids]) for source_id, exec_ids in state.source_prepared_mapping.items()]}; "+ f"indegree={state.indegree}; pending_if={state._pending_if_exec_nodes}; resolved={state._resolved_if_exec_branches}")- assert generic_retired_nodes == []+ output_exec_id = next(iter(state.source_prepared_mapping["output"]))+ marker = f"{selected_branch}:"+ assert state.results[output_exec_id].collection == [f"{marker}1", f"{marker}2"]+ assert trace.count("if") == 2+ assert trace.count(selected_source) == 2+ assert trace.count("root_opposite") == (1 if wire_opposite_root else 0)+ assert state.is_complete(), f"graph stalled after {trace}"+ assert state.next() is None+ assert not state._ready_node_ids+ assert all(not queue for queue in state._ready_queues.values())[email protected]("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,[email protected]("round_trip_after", [None, 6], ids=["fresh", "restored"])[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_literal_if_branch_feeds_per_item_if_without_stranding_unselected_root(+ force_compatibility_scheduler: bool,+ round_trip_after: int | None,) -> 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]] = []-- for force_compatibility_scheduler in (False, True):- partial_trace, canceled_state = _run_until_source(- GraphExecutionState(graph=_nested_if_graph()),- stop_after_source,- force_compatibility_scheduler=force_compatibility_scheduler,- )- expected_partial_trace = ["outer_condition", "inner_condition"]- if stop_after_source == "inner_false":- expected_partial_trace.append("inner_false")- else:- expected_partial_trace.extend(["inner_false", "inner_if", "outer_if"])- assert partial_trace == expected_partial_trace- assert "inner_true" not in {- canceled_state.prepared_source_mapping[execution_id] for execution_id in canceled_state.results- }- assert "outer_false" not in {- 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", ()),- )- partial_snapshot = dump_execution_state(canceled_state)- restored_canceled = load_execution_state(partial_snapshot)- restored_expected = load_execution_state(partial_snapshot)- if force_compatibility_scheduler:- _restore_compatibility_scheduler(restored_canceled)- assert _state_projection(restored_canceled) == _state_projection(canceled_state)- assert _activation_projection(restored_canceled) == _activation_projection(canceled_state)- assert dump_execution_state(restored_canceled)["execution_tokens"] == partial_snapshot["execution_tokens"]- 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))- )+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="conditions", first=[True, True]))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(AnyTypeTestInvocation(id="literal_selected", value="literal"))+ graph.add_node(AnyTypeTestInvocation(id="literal_unselected", value="literal-unselected"))+ graph.add_node(IfInvocation(id="literal_if", condition=True))+ graph.add_node(AnyTypeTestInvocation(id="per_item_unselected", value="per-item-unselected"))+ graph.add_node(IfInvocation(id="per_item_if"))+ graph.add_node(CollectInvocation(id="output"))+ for source, source_field, destination, destination_field in (+ ("conditions", "collection", "iterate", "collection"),+ ("literal_selected", "value", "literal_if", "true_input"),+ ("literal_unselected", "value", "literal_if", "false_input"),+ ("iterate", "item", "per_item_if", "condition"),+ ("literal_if", "value", "per_item_if", "true_input"),+ ("per_item_unselected", "value", "per_item_if", "false_input"),+ ("per_item_if", "value", "output", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- 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,+ state = GraphExecutionState(graph=graph)+ if round_trip_after is None:+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ else:+ checkpoint_trace, partial_state = _run_graph(+ state,force_compatibility_scheduler=force_compatibility_scheduler,- outer_condition=True,- inner_condition=False,+ stop_after=round_trip_after,)+ assert "literal_unselected" in checkpoint_trace+ assert "output" not in checkpoint_trace+ restored = load_execution_state(dump_execution_state(partial_state))+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(restored)+ resumed_trace, state = _run_graph(restored, force_compatibility_scheduler=force_compatibility_scheduler)+ trace = checkpoint_trace + resumed_trace- retried_state = GraphExecutionState(graph=canceled_state.graph.model_copy(deep=True))- assert retried_state.id != canceled_state.id- assert retried_state.results == {}- assert retried_state.execution_refs == {}- assert retried_state.execution_tokens == {}-- retried_trace, retried_state = _run_graph(- retried_state,- force_compatibility_scheduler=force_compatibility_scheduler,- )- projections.append((retried_trace, retried_state))+ assert state.is_complete(), f"graph stalled after {trace}; pending={state._pending_if_exec_nodes}"+ output_exec_id = next(iter(state.source_prepared_mapping["output"]))+ assert state.results[output_exec_id].collection == ["literal", "literal"]+ assert trace.count("literal_if") == 1+ assert trace.count("per_item_if") == 2+ assert state.source_prepared_mapping["literal_unselected"]+ assert state.source_prepared_mapping["per_item_unselected"]+ assert trace.count("literal_unselected") == 1+ assert trace.count("per_item_unselected") == 1- assert partial_projections[0] == partial_projections[1]- assert (- projections[0][0]- == projections[1][0]- == [- "outer_condition",- "inner_condition",- "inner_false",- "inner_if",- "outer_if",- "sink",- ]- )- assert _state_projection(projections[0][1]) == _state_projection(projections[1][1])- assert _activation_projection(projections[0][1]) == _activation_projection(projections[1][1])- assert _execution_identity_projection(projections[0][1]) == _execution_identity_projection(projections[1][1])- _assert_execution_identity_consistent(projections[0][1])- _assert_execution_identity_consistent(projections[1][1])- assert projections[0][1].results[next(iter(projections[0][1].source_prepared_mapping["sink"]))].value == 7+def test_per_item_if_condition_from_iterate_index_selects_literal_values() -> None:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="source", first=[10, 20]))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(FixedCollectionTestInvocation(id="condition"))+ graph.add_node(AnyTypeTestInvocation(id="false_value", value="no"))+ graph.add_node(AnyTypeTestInvocation(id="true_value", value="yes"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(CollectInvocation(id="output"))+ for source, source_field, destination, destination_field in (+ ("source", "collection", "iterate", "collection"),+ ("iterate", "index", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("false_value", "value", "if", "false_input"),+ ("true_value", "value", "if", "true_input"),+ ("if", "value", "output", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))- "tampered_field",- [- "token_id",- "owner_node_id",- "reference_id",- "frame_id",- "state_id",- "iteration_path",- "workflow_call_depth",- "blank_owner_node_id",- "blank_frame_id",- "blank_state_id",- "mapping_key",- "both_ids",- ],-)-def test_rehydrated_if_rejects_tampered_activation_identity(tampered_field: str) -> None:- """A persisted activation token with stale identity or frame data is rejected."""- _, partial_state = _run_until_source(GraphExecutionState(graph=_nested_if_graph()), "outer_if")- snapshot = dump_execution_state(partial_state)- token_id, token = next(- (token_id, token)- for token_id, token in snapshot["execution_tokens"].items()- if token["token_kind"] == "activation"- )- source_if_id = partial_state.prepared_source_mapping[token["owner_node_id"]]+ trace, state = _run_graph(GraphExecutionState(graph=graph))- valid_restored = load_execution_state(snapshot)- valid_plan = valid_restored._scheduler()._scheduler.plan- dependency = next(- dependency- for plan_node in valid_plan.nodes.values()- for dependency in plan_node.activation_dependencies- if dependency.owner_id == source_if_id- )- assert valid_restored._is_activation_dependency_satisfied(dependency)- restored_token = valid_restored.execution_tokens[token_id]- expected_ref = valid_restored.execution_refs[restored_token.owner_node_id]- assert restored_token.token_id == token_id == f"{expected_ref.reference_id}:activation:{restored_token.port}"- assert restored_token.reference_id == expected_ref.reference_id- assert restored_token.owner_node_id == expected_ref.exec_node_id- assert restored_token.frame == expected_ref.frame+ assert state.is_complete(), f"graph stalled after {trace}"+ output_exec_id = next(iter(state.source_prepared_mapping["output"]))+ assert state.results[output_exec_id].collection == ["no", "yes"]+ assert trace.count("if") == 2- stale_snapshot = json.loads(json.dumps(snapshot))- stale_token = stale_snapshot["execution_tokens"][token_id]- if tampered_field == "token_id":- stale_token["token_id"] = "stale-token"- elif tampered_field == "owner_node_id":- stale_token["owner_node_id"] = "stale-owner"- elif tampered_field == "reference_id":- stale_token["reference_id"] = "stale-reference"- elif tampered_field == "frame_id":- stale_token["frame"]["frame_id"] = "stale-frame"- elif tampered_field == "state_id":- stale_token["frame"]["state_id"] = "stale-state"- elif tampered_field == "iteration_path":- stale_token["frame"]["iteration_path"] = [1]- elif tampered_field == "workflow_call_depth":- stale_token["frame"]["workflow_call_depth"] = 1- elif tampered_field == "blank_owner_node_id":- stale_token["owner_node_id"] = ""- elif tampered_field == "blank_frame_id":- stale_token["frame"]["frame_id"] = ""- elif tampered_field == "blank_state_id":- stale_token["frame"]["state_id"] = ""- elif tampered_field == "mapping_key":- stale_snapshot["execution_tokens"]["stale-key"] = stale_snapshot["execution_tokens"].pop(token_id)- else:- stale_snapshot["execution_tokens"]["stale-key"] = stale_snapshot["execution_tokens"].pop(token_id)- stale_snapshot["execution_tokens"]["stale-key"]["token_id"] = "stale-key"- with pytest.raises(ValidationError, match="Activation token|Execution token"):- load_execution_state(stale_snapshot)[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_deep_branch_root_false_with_two_outer_frames_and_nested_collect(+ force_compatibility_scheduler: bool,+) -> None:+ graph = Graph()+ for node in (+ CollectionConcatInvocation(id="outer_source", first=[0, 2]),+ IterateInvocation(id="outer"),+ AddInvocation(id="inner_size", b=1),+ RangeOfSizeInvocation(id="inner_source", start=100),+ IterateInvocation(id="inner"),+ AnyTypeTestInvocation(id="body"),+ CollectInvocation(id="branch_collect"),+ FixedCollectionTestInvocation(id="condition"),+ AnyTypeTestInvocation(id="fallback", value="F"),+ IfInvocation(id="if"),+ CollectInvocation(id="output"),+ ):+ graph.add_node(node)+ for source, source_field, destination, destination_field in (+ ("outer_source", "collection", "outer", "collection"),+ ("outer", "item", "inner_size", "a"),+ ("inner_size", "value", "inner_source", "size"),+ ("inner_source", "collection", "inner", "collection"),+ ("inner", "item", "body", "value"),+ ("body", "value", "branch_collect", "item"),+ ("outer", "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("branch_collect", "collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "output", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))-def test_rehydrated_if_rejects_activation_token_with_ghost_owner_and_reference() -> None:- _, partial_state = _run_until_source(GraphExecutionState(graph=_nested_if_graph()), "outer_if")- snapshot = dump_execution_state(partial_state)- token_id, token = next(- (token_id, token)- for token_id, token in snapshot["execution_tokens"].items()- if token["token_kind"] == "activation"+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler)- expected_ref = partial_state._expected_execution_ref(token["owner_node_id"]).model_dump(mode="json")- ghost_ref = {**expected_ref, "exec_node_id": "ghost", "reference_id": f"{snapshot['id']}:ghost"}- snapshot["execution_refs"]["ghost"] = ghost_ref- ghost_token_id = f"{ghost_ref['reference_id']}:activation:{token['port']}"- ghost_token = {- **token,- "token_id": ghost_token_id,- "reference_id": ghost_ref["reference_id"],- "owner_node_id": "ghost",- }- snapshot["execution_tokens"].pop(token_id)- snapshot["execution_tokens"][ghost_token_id] = ghost_token-- with pytest.raises(ValidationError, match="Activation token|Execution token"):- load_execution_state(snapshot)+ assert state.is_complete(), f"graph stalled after {trace}; history={state.executed_history}"+ assert _source_output(state, "output").collection == ["F", [100, 101, 102]]+ assert trace.count("if") == 2+ assert trace.count("branch_collect") == 2+ assert trace.count("fallback") == 1+ assert trace.count("output") == 1-def test_rehydrated_if_rejects_activation_token_on_invocation_without_declared_field() -> None:- _, partial_state = _run_until_source(GraphExecutionState(graph=_nested_if_graph()), "outer_if")- snapshot = dump_execution_state(partial_state)- ordinary_exec_id = next(- execution_id- for execution_id, source_id in partial_state.prepared_source_mapping.items()- if source_id == "inner_false"- )- reference = partial_state._expected_execution_ref(ordinary_exec_id).model_dump(mode="json")- token_id = f"{reference['reference_id']}:activation:value"- snapshot["execution_tokens"][token_id] = {- "token_id": token_id,- "reference_id": reference["reference_id"],- "owner_node_id": ordinary_exec_id,- "port": "value",- "frame": reference["frame"],- "value": "value",- "token_kind": "activation",- }- with pytest.raises(ValidationError, match="Activation token|Execution token"):- load_execution_state(snapshot)[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("extra_inner_consumer", [False, True], ids=["no-extra-consumer", "extra-inner-consumer"])+def test_nested_if_collect_branch_with_all_outer_frames_false_completes(+ force_compatibility_scheduler: bool,+ extra_inner_consumer: bool,+) -> None:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="outer_source", first=["", ""]))+ graph.add_node(IterateInvocation(id="outer"))+ graph.add_node(PolymorphicStringTestInvocation(id="inner_collection"))+ graph.add_node(IterateInvocation(id="inner"))+ graph.add_node(AnyTypeTestInvocation(id="body"))+ graph.add_node(CollectInvocation(id="branch_collect"))+ graph.add_node(FixedCollectionTestInvocation(id="condition"))+ graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(CollectInvocation(id="output"))+ for source, source_field, destination, destination_field in (+ ("outer_source", "collection", "outer", "collection"),+ ("outer", "item", "inner_collection", "value"),+ ("inner_collection", "collection", "inner", "collection"),+ ("inner", "item", "body", "value"),+ ("body", "value", "branch_collect", "item"),+ ("outer", "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("branch_collect", "collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "output", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))+ if extra_inner_consumer:+ graph.add_node(AnyTypeTestInvocation(id="extra"))+ graph.add_edge(create_edge("inner", "item", "extra", "value"))+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)+ trace, state = _run_graph(state)-def test_rehydrated_activation_token_allows_unknown_frame_metadata() -> None:- _, partial_state = _run_until_source(GraphExecutionState(graph=_nested_if_graph()), "outer_if")- snapshot = dump_execution_state(partial_state)- token_id, token = next(- (token_id, token)- for token_id, token in snapshot["execution_tokens"].items()- if token["token_kind"] == "activation"+ assert state.is_complete(), (+ f"graph stalled after {trace}; prepared={state.source_prepared_mapping}; pending_if={state._pending_if_exec_nodes}; "+ f"inactive_inner={state._is_source_inactive('inner')}; "+ f"inner_dependencies={state._get_source_activation_dependencies('inner')}")- snapshot["execution_tokens"][token_id]["frame"]["future_frame_metadata"] = "preserved"-- 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+ output_exec_id = next(iter(state.source_prepared_mapping["output"]))+ assert state.results[output_exec_id].collection == ["fallback", "fallback"]+ assert trace.count("branch_collect") == 2+ assert trace.count("body") == 2+ assert "inner" in trace+ assert ("extra" in trace) is extra_inner_consumer+ assert state.is_complete(), f"graph stalled after {trace}"+ assert state.next() is None+ assert not state._ready_node_ids+ assert all(not queue for queue in state._ready_queues.values())[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 _sibling_collect_if_graph(+ *,+ left: list[int],+ right: list[int],+ condition_axis: str = "left",+ collect_field: str = "true_input",+ same_if_both_fields: bool = False,+) -> Graph:+ """Build the #9820 shape: a Collect over a left x right product feeds one branch of a per-item If."""+ graph = Graph()+ for node in (+ CollectionConcatInvocation(id="left_source", first=left),+ CollectionConcatInvocation(id="right_source", first=right),+ IterateInvocation(id="left"),+ IterateInvocation(id="right"),+ AddInvocation(id="body"),+ CollectInvocation(id="branch_collect"),+ AddInvocation(id="minus_one", b=-1),+ FixedCollectionTestInvocation(id="condition"),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ):+ graph.add_node(node)+ other_field = "false_input" if collect_field == "true_input" else "true_input"+ edges = [+ ("left_source", "collection", "left", "collection"),+ ("right_source", "collection", "right", "collection"),+ ("left", "item", "body", "a"),+ ("right", "item", "body", "b"),+ ("body", "value", "branch_collect", "item"),+ (condition_axis, "item", "minus_one", "a"),+ ("minus_one", "value", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("branch_collect", "collection", "if", collect_field),+ ("if", "value", "collect", "item"),+ ]+ if same_if_both_fields:+ edges.append(("branch_collect", "collection", "if", other_field))+ else:+ graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))+ edges.append(("fallback", "value", "if", other_field))+ for source, source_field, destination, destination_field in edges:+ graph.add_edge(create_edge(source, source_field, destination, destination_field))+ return graph- 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))+def _collect_output(state: GraphExecutionState, source_id: str = "collect") -> list[Any]:+ return state.results[next(iter(state.source_prepared_mapping[source_id]))].collection- assert trace == expected_trace- expected_source_ids = set(expected_trace)- assert expected_source_ids.issubset(state.source_prepared_mapping)- assert all(- not execution_ids- for source_id, execution_ids in state.source_prepared_mapping.items()- if source_id not in expected_source_ids- )- 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])+def _zip_collect_branch_with_root_condition_graph(condition_value: int) -> Graph:+ graph = Graph()+ for node in (+ CollectionConcatInvocation(id="left_source", first=[1, 2]),+ CollectionConcatInvocation(id="right_source", first=[10, 20]),+ IterateInvocation(id="left"),+ IterateInvocation(id="right"),+ AddInvocation(id="body"),+ CollectInvocation(id="branch_collect"),+ FixedCollectionTestInvocation(id="condition", value=condition_value),+ AnyTypeTestInvocation(id="fallback", value="fallback"),+ IfInvocation(id="if"),+ AnyTypeTestInvocation(id="after"),+ ):+ graph.add_node(node)+ for source, source_field, destination, destination_field in (+ ("left_source", "collection", "left", "collection"),+ ("right_source", "collection", "right", "collection"),+ ("left", "item", "body", "a"),+ ("right", "item", "body", "b"),+ ("body", "value", "branch_collect", "item"),+ ("condition", "condition", "if", "condition"),+ ("branch_collect", "collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "after", "value"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))+ return graph[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")+def _zip_collect_then_after_graph() -> Graph:+ graph = _zip_collect_branch_with_root_condition_graph(1)+ graph.delete_node("if")+ graph.delete_node("fallback")+ graph.add_edge(create_edge("branch_collect", "collection", "after", "value"))+ return graph- 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, ()),- }+def _zip_collect_branch_with_after2_graph() -> Graph:+ graph = _zip_collect_branch_with_root_condition_graph(condition_value=1)+ graph.add_node(AnyTypeTestInvocation(id="after2"))+ graph.add_edge(create_edge("after", "value", "after2", "value"))+ return graph- _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])+def _zip_collect_branch_with_after_collect_graph() -> Graph:+ graph = _zip_collect_branch_with_root_condition_graph(condition_value=1)+ graph.add_node(CollectInvocation(id="after_collect"))+ graph.add_edge(create_edge("after", "value", "after_collect", "item"))+ return graph[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,[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_zip_collect_then_after_completes_without_if(force_compatibility_scheduler: bool) -> None:+ state = GraphExecutionState(graph=_zip_collect_then_after_graph())+ state._execution_scheduler = (+ _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state))- 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()+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error()+ after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)+ assert [state._get_iteration_path(node_id) for node_id in after_ids] == [(0,), (1,)]+ assert [state.results[node_id].value for node_id in after_ids] == [[11, 21], [12, 22]]+ assert trace.count("body") == 4+ assert trace.count("branch_collect") == 2@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])- ("collection", "expected"),- [- ([False, True], ["false-root", "true-root"]),- ([True, True], ["true-root", "true-root"]),- ([False, False], ["false-root", "false-root"]),- ],- ids=["mixed", "all-true", "all-false"],-)-def test_for_condition_if_reads_root_frame_sources_and_skips_unselected_root(- force_compatibility_scheduler: bool, collection: list[bool], expected: list[str]+def test_zip_collect_then_after_with_empty_right_completes_without_if(+ force_compatibility_scheduler: bool,) -> None:- graph = Graph()- graph.add_node(ForInvocation(id="for", collection=collection))- graph.add_node(AnyTypeTestInvocation(id="root_true", value="true-root"))- graph.add_node(AnyTypeTestInvocation(id="root_false", value="false-root"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(ForReturnInvocation(id="return"))- graph.add_node(AnyTypeTestInvocation(id="after"))- graph.add_edge(create_edge("for", "item", "if", "condition"))- graph.add_edge(create_edge("root_true", "value", "if", "true_input"))- graph.add_edge(create_edge("root_false", "value", "if", "false_input"))- graph.add_edge(create_edge("if", "value", "return", "output"))- graph.add_edge(create_loop_linkage("for", "return"))- graph.add_edge(create_edge("for", "output_collection", "after", "value"))-- trace, state = _run_graph(- GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ graph = _zip_collect_then_after_graph()+ graph.update_node("right_source", CollectionConcatInvocation(id="right_source", first=[]))+ state = GraphExecutionState(graph=graph)+ state._execution_scheduler = (+ _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state))- assert state.is_complete(), (- f"graph stalled after {trace}; history={state.executed_history}; "- f"sources={state.source_prepared_mapping}; pending_if={state._pending_if_exec_nodes}; "- f"resolved={state._resolved_if_exec_branches}; indegree={state.indegree}"- )- assert _source_output(state, "after").value == expected- assert trace.count("root_true") == (1 if True in collection else 0)- assert trace.count("root_false") == (1 if False in collection else 0)+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error()+ after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)+ assert [state._get_iteration_path(node_id) for node_id in after_ids] == [(0,), (1,)]+ assert [state.results[node_id].value for node_id in after_ids] == [[], []]+ assert trace.count("body") == 0+ assert trace.count("branch_collect") == 2@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])@pytest.mark.parametrize(- ("conditions", "expected"),- [- ([False, True], ["false-root", "true-root"]),- ([True, True], ["true-root", "true-root"]),- ([False, False], ["false-root", "false-root"]),- ],- ids=["mixed", "all-true", "all-false"],+ ("condition_value", "expected"), [(1, [[11, 21], [12, 22]]), (0, "fallback")], ids=["true", "false"])-def test_iterate_condition_if_reads_root_frame_sources_and_skips_unselected_root(- force_compatibility_scheduler: bool, conditions: list[bool], expected: list[str]+def test_zip_collect_branch_with_root_condition_completes(+ force_compatibility_scheduler: bool, condition_value: int, expected: Any) -> None:- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="conditions", first=conditions))- graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(AnyTypeTestInvocation(id="root_true", value="true-root"))- graph.add_node(AnyTypeTestInvocation(id="root_false", value="false-root"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="output"))- graph.add_edge(create_edge("conditions", "collection", "iterate", "collection"))- graph.add_edge(create_edge("iterate", "item", "if", "condition"))- graph.add_edge(create_edge("root_true", "value", "if", "true_input"))- graph.add_edge(create_edge("root_false", "value", "if", "false_input"))- graph.add_edge(create_edge("if", "value", "output", "item"))-- trace, state = _run_graph(- GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ state = GraphExecutionState(graph=_zip_collect_branch_with_root_condition_graph(condition_value))+ state._execution_scheduler = (+ _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state))- assert state.is_complete(), f"graph stalled after {trace}; history={state.executed_history}"- assert _source_output(state, "output").collection == expected- assert trace.count("root_true") == (1 if True in conditions else 0)- assert trace.count("root_false") == (1 if False in conditions else 0)+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error()+ after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)+ if_ids = set(state.source_prepared_mapping["if"])+ activation_tokens = sorted(+ (+ token+ for token in state.execution_tokens.values()+ if token.token_kind == "activation" and token.owner_node_id in if_ids+ ),+ key=lambda token: token.frame.iteration_path,+ )+ if condition_value:+ assert [state._get_iteration_path(node_id) for node_id in after_ids] == [(0,), (1,)]+ assert [state.results[node_id].value for node_id in after_ids] == expected+ assert trace.count("body") == 4+ assert trace.count("branch_collect") == 2+ assert trace.count("if") == 2+ assert [(token.port, token.frame.iteration_path) for token in activation_tokens] == [+ ("true_input", (0,)),+ ("true_input", (1,)),+ ]+ restored = load_execution_state(dump_execution_state(state))+ assert restored.is_complete()+ assert not restored.has_error()+ restored_after_ids = sorted(restored.source_prepared_mapping["after"], key=restored._get_iteration_path)+ assert [restored.results[node_id].value for node_id in restored_after_ids] == expected+ else:+ assert [state._get_iteration_path(node_id) for node_id in after_ids] == [()]+ assert [state.results[node_id].value for node_id in after_ids] == [expected]+ assert trace.count("body") == 4+ assert trace.count("branch_collect") == 2+ assert trace.count("if") == 1+ assert [(token.port, token.frame.iteration_path) for token in activation_tokens] == [("false_input", ())]@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_iterate_for_collect_preserves_empty_inner_collection(force_compatibility_scheduler: bool) -> None:- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="source", first=[[1, 2], []]))- graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(ForInvocation(id="for"))- graph.add_node(AddInvocation(id="add", b=10))- graph.add_node(ForReturnInvocation(id="return"))- graph.add_node(CollectInvocation(id="collect"))- graph.add_node(AnyTypeTestInvocation(id="after"))- graph.add_edge(create_edge("source", "collection", "iterate", "collection"))- graph.add_edge(create_edge("iterate", "item", "for", "collection"))- graph.add_edge(create_edge("for", "item", "add", "a"))- graph.add_edge(create_edge("add", "value", "return", "output"))- graph.add_edge(create_loop_linkage("for", "return"))- graph.add_edge(create_edge("for", "output_collection", "collect", "item"))- graph.add_edge(create_edge("collect", "collection", "after", "value"))+def test_zip_collect_root_condition_preserves_frames_through_ordinary_descendants(+ force_compatibility_scheduler: bool,+) -> None:+ state = GraphExecutionState(graph=_zip_collect_branch_with_after2_graph())+ state._execution_scheduler = (+ _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)- trace, state = _run_graph(state)+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- after_exec_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)- assert trace.count("add") == 2- assert trace.count("after") == 2- assert [state._get_iteration_path(exec_id) for exec_id in after_exec_ids] == [(0,), (1,)]- assert [state.results[exec_id].value for exec_id in after_exec_ids] == [[[11, 12]], [[]]]- assert state.is_complete()+ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error()+ after2_ids = sorted(state.source_prepared_mapping["after2"], key=state._get_iteration_path)+ assert [state._get_iteration_path(node_id) for node_id in after2_ids] == [(0,), (1,)]+ assert [state.results[node_id].value for node_id in after2_ids] == [[11, 21], [12, 22]]+ assert trace.count("after2") == 2@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])- ("left_values", "expected"),- [([1, 2], ["fallback", [12, 22]]), ([1, 1], ["fallback", "fallback"])],- ids=["mixed", "branch-never-selected"],-)- "node_order",- [- tuple(order)- for order in (- random.Random(seed).sample(- (- "left_source",- "right_source",- "left",- "right",- "body",- "branch_collect",- "minus_one",- "condition",- "fallback",- "if",- "collect",- ),- 11,- )- for seed in range(20)- )- ],-)-def test_sibling_iterates_collect_through_if_branch_without_unsupported_frames(- left_values, expected, node_order, force_compatibility_scheduler-):- graph = Graph()- nodes = {- "left_source": CollectionConcatInvocation(id="left_source", first=left_values),- "right_source": CollectionConcatInvocation(id="right_source", first=[10, 20]),- "left": IterateInvocation(id="left"),- "right": IterateInvocation(id="right"),- "body": AddInvocation(id="body"),- "branch_collect": CollectInvocation(id="branch_collect"),- "minus_one": AddInvocation(id="minus_one", b=-1),- "condition": FixedCollectionTestInvocation(id="condition"),- "fallback": AnyTypeTestInvocation(id="fallback", value="fallback"),- "if": IfInvocation(id="if"),- "collect": CollectInvocation(id="collect"),- }- for node_id in node_order:- graph.add_node(nodes[node_id])- for source, source_field, destination, destination_field in (- ("left_source", "collection", "left", "collection"),- ("right_source", "collection", "right", "collection"),- ("left", "item", "body", "a"),- ("right", "item", "body", "b"),- ("body", "value", "branch_collect", "item"),- ("left", "item", "minus_one", "a"),- ("minus_one", "value", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("branch_collect", "collection", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "collect", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))+def test_zip_collect_root_condition_preserves_groups_in_downstream_collect(+ force_compatibility_scheduler: bool,+) -> None:+ state = GraphExecutionState(graph=_zip_collect_branch_with_after_collect_graph())+ state._execution_scheduler = (+ _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)- trace, state = _run_graph(state)+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error()+ collect_ids = sorted(state.source_prepared_mapping["after_collect"], key=state._get_iteration_path)+ assert len(collect_ids) == 1+ assert state._get_iteration_path(collect_ids[0]) == ()+ assert state.results[collect_ids[0]].collection == [[11, 21], [12, 22]]+ assert trace.count("after_collect") == 1- assert state.is_complete()- assert state.results[next(iter(state.source_prepared_mapping["collect"]))].collection == expected- if left_values == [1, 1]:- assert "right" not in trace- assert "body" not in trace[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_zip_collect_root_condition_expansion_rolls_back_after_if_initialization_failure(+ monkeypatch: pytest.MonkeyPatch, force_compatibility_scheduler: bool+) -> None:+ state = GraphExecutionState(graph=_zip_collect_branch_with_root_condition_graph(condition_value=1))+ state._execution_scheduler = (+ _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )-def test_sibling_collect_shared_by_distinct_if_owners_remains_unsupported() -> None:- graph = Graph()- for node in (- CollectionConcatInvocation(id="left_source", first=[1, 2]),- IterateInvocation(id="left"),- CollectionConcatInvocation(id="right_source", first=[10, 20]),- IterateInvocation(id="right"),- AddInvocation(id="body"),- CollectInvocation(id="branch_collect"),- FixedCollectionTestInvocation(id="condition"),- AnyTypeTestInvocation(id="fallback_a", value=0),- AnyTypeTestInvocation(id="fallback_b", value=0),- IfInvocation(id="if_a"),- IfInvocation(id="if_b"),- ):- graph.add_node(node)- for source, source_field, destination, destination_field in (- ("left_source", "collection", "left", "collection"),- ("right_source", "collection", "right", "collection"),- ("left", "item", "body", "a"),- ("right", "item", "body", "b"),- ("body", "value", "branch_collect", "item"),- ("left", "item", "condition", "value"),- ("condition", "condition", "if_a", "condition"),- ("condition", "condition", "if_b", "condition"),- ("branch_collect", "collection", "if_a", "true_input"),- ("branch_collect", "collection", "if_b", "true_input"),- ("fallback_a", "value", "if_a", "false_input"),- ("fallback_b", "value", "if_b", "false_input"),+ while (+ len(+ [exec_id for exec_id in state.source_prepared_mapping.get("branch_collect", ()) if exec_id in state.results]+ )+ < 2):- graph.add_edge(create_edge(source, source_field, destination, destination_field))-- state = GraphExecutionState(graph=graph)+ node = state.next()+ assert node is not None+ state.complete(node.id, node.invoke(Mock()))- with pytest.raises(UnsupportedSharedIfCollectBranchesError, match="multiple If nodes"):- state.next()+ root_if_ids = [+ exec_id for exec_id in state.source_prepared_mapping["if"] if state._get_iteration_path(exec_id) == ()+ ]+ assert len(root_if_ids) == 1+ root_if_id = root_if_ids[0]+ assert root_if_id not in state.executed+ before_nodes = set(state.execution_graph.nodes)+ before_edges = tuple(state.execution_graph.edges)+ before_prepared_sources = dict(state.prepared_source_mapping)+ before_source_prepared = {source_id: set(exec_ids) for source_id, exec_ids in state.source_prepared_mapping.items()}+ before_paths = dict(state.prepared_iteration_paths)+ before_indegree = dict(state.indegree)+ before_tokens = state.execution_tokens.copy()+ before_gates = copy.deepcopy(state._generic_runtime().gates)+ materializer = state._materializer()+ initialize_execution_node = materializer._initialize_execution_node-def test_nested_iterate_collected_in_if_branch_is_not_misclassified_as_sibling():- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="outer_source", first=[["a", "b"], ["c"]]))- graph.add_node(IterateInvocation(id="outer"))- graph.add_node(PolymorphicStringTestInvocation(id="inner_collection"))- graph.add_node(IterateInvocation(id="inner"))- graph.add_node(AnyTypeTestInvocation(id="body"))- graph.add_node(CollectInvocation(id="branch_collect"))- graph.add_node(FixedCollectionTestInvocation(id="condition"))- graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="result_collect"))- for source, source_field, destination, destination_field in (- ("outer_source", "collection", "outer", "collection"),- ("outer", "item", "inner_collection", "value"),- ("inner_collection", "collection", "inner", "collection"),- ("inner", "item", "body", "value"),- ("body", "value", "branch_collect", "item"),- ("outer", "item", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("branch_collect", "collection", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "result_collect", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))+ def fail_after_if_initialization(exec_node_id: str, input_edges: Any = None) -> None:+ initialize_execution_node(exec_node_id, input_edges)+ if state.prepared_source_mapping.get(exec_node_id) == "if" and state._get_iteration_path(exec_node_id) == (1,):+ raise RuntimeError("injected If-copy initialization failure")- state = GraphExecutionState(graph=graph)+ monkeypatch.setattr(materializer, "_initialize_execution_node", fail_after_if_initialization)+ with pytest.raises(RuntimeError, match="injected If-copy initialization failure"):+ while (node := state.next()) is not None:+ state.complete(node.id, node.invoke(Mock()))- trace, state = _run_graph(state)+ assert set(state.execution_graph.nodes) == before_nodes+ assert tuple(state.execution_graph.edges) == before_edges+ assert state.prepared_source_mapping == before_prepared_sources+ assert state.source_prepared_mapping == before_source_prepared+ assert state.prepared_iteration_paths == before_paths+ assert state.indegree == before_indegree+ assert state.execution_tokens == before_tokens+ assert state._generic_runtime().gates == before_gates+ assert state._get_iteration_path(root_if_id) == ()- assert state.is_complete()- assert state.results[next(iter(state.source_prepared_mapping["result_collect"]))].collection == [- ["a", "b"],- ["c"],- ]+ monkeypatch.undo()+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ assert state.is_complete(), f"graph stalled after retry: {trace}"+ assert not state.has_error()+ after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)+ assert [state.results[node_id].value for node_id in after_ids] == [[11, 21], [12, 22]]@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_nested_collect_preserves_condition_frame_when_classifying_branch_iterate(- force_compatibility_scheduler: bool,+def test_zip_collect_root_condition_deferred_consumer_failure_rolls_back_and_retries(+ monkeypatch: pytest.MonkeyPatch, force_compatibility_scheduler: bool) -> None:- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="outer_source", first=[1, 2]))- graph.add_node(IterateInvocation(id="outer"))- graph.add_node(RangeOfSizeInvocation(id="middle_range", size=1))- graph.add_node(IterateInvocation(id="middle"))- graph.add_node(CollectInvocation(id="middle_collect"))- graph.add_node(CollectInvocation(id="middle_collect_2"))- graph.add_node(IterateInvocation(id="inner"))- graph.add_node(AddInvocation(id="body"))- graph.add_node(CollectInvocation(id="branch_collect"))- graph.add_node(FixedCollectionTestInvocation(id="condition"))- graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="result_collect"))- for source, source_field, destination, destination_field in (- ("outer_source", "collection", "outer", "collection"),- ("outer", "item", "middle_range", "start"),- ("middle_range", "collection", "middle", "collection"),- ("middle", "item", "middle_collect", "item"),- ("middle_collect", "collection", "middle_collect_2", "collection"),- ("middle_collect_2", "collection", "inner", "collection"),- ("outer", "item", "body", "a"),- ("inner", "item", "body", "b"),- ("body", "value", "branch_collect", "item"),- ("outer", "item", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("branch_collect", "collection", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "result_collect", "item"),+ state = GraphExecutionState(graph=_zip_collect_branch_with_root_condition_graph(condition_value=1))+ state._execution_scheduler = (+ _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )++ while (+ len(+ [exec_id for exec_id in state.source_prepared_mapping.get("branch_collect", ()) if exec_id in state.results]+ )+ < 2):- graph.add_edge(create_edge(source, source_field, destination, destination_field))+ node = state.next()+ assert node is not None+ state.complete(node.id, node.invoke(Mock()))- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)+ root_if_exec_ids = [+ exec_id for exec_id in state.source_prepared_mapping["if"] if state._get_iteration_path(exec_id) == ()+ ]+ assert len(root_if_exec_ids) == 1+ state._materializer().create_execution_node("after", [("if", root_if_exec_ids[0])], iteration_path=())+ assert len(state.source_prepared_mapping["after"]) == 1- trace, state = _run_graph(state)+ materializer_type = graph_module._ExecutionMaterializer+ initialize_execution_node = materializer_type._initialize_execution_node+ run_materialization_transaction = state._run_materialization_transaction+ failed_transaction_snapshot: dict[str, Any] | None = None- assert state.is_complete(), (- f"graph stalled after {trace}; pending={state._pending_if_exec_nodes}; "- f"prepared={state.source_prepared_mapping}; indegree={state.indegree}; "- f"resolved={state._resolved_if_exec_branches}; "- f"unindexed={set(state.prepared_source_mapping) - state._if_activation_dependents_indexed_exec_ids}; "- f"middle_axes={state._materializer().get_node_iterators('middle_body', state._get_source_graph_flat())}; "- f"middle_mappings={list(state._materializer()._get_parent_iteration_mappings('middle_body', state._get_source_graph_flat()))}; "- f"middle_dependencies={state._get_source_activation_dependencies('middle_body', (0,))}; "- f"middle_admitted={state._is_source_activation_admitted('middle_body', (0,))}; "- f"iterator_sources_executed={[(source_id, source_id in state.executed) for source_id in ('left', 'right')]}"- )- middle_collect_exec_ids = sorted(state.source_prepared_mapping["middle_collect"], key=state._get_iteration_path)- assert [- (state._get_iteration_path(exec_id), state.results[exec_id].collection) for exec_id in middle_collect_exec_ids- ] == [((0,), [1]), ((1,), [2])]- middle_collect_2_exec_ids = sorted(state.source_prepared_mapping["middle_collect_2"], key=state._get_iteration_path)- assert [- (state._get_iteration_path(exec_id), state.results[exec_id].collection) for exec_id in middle_collect_2_exec_ids- ] == [((0,), [1]), ((1,), [2])]- inner_exec_ids = sorted(state.source_prepared_mapping["inner"], key=state._get_iteration_path)- assert [state._get_iteration_path(exec_id) for exec_id in inner_exec_ids] == [(0, 0), (1, 0)]- branch_collect_exec_ids = sorted(state.source_prepared_mapping["branch_collect"], key=state._get_iteration_path)- assert [- (state._get_iteration_path(exec_id), state.results[exec_id].collection) for exec_id in branch_collect_exec_ids- ] == [((0,), [2]), ((1,), [4])]- assert state.results[next(iter(state.source_prepared_mapping["result_collect"]))].collection == [[2], [4]]+ def snapshot_state() -> dict[str, Any]:+ return {+ "nodes": {+ node_id: copy.deepcopy(state.execution_graph.get_node(node_id))+ for node_id in state.execution_graph.nodes+ },+ "edges": copy.deepcopy(tuple(state.execution_graph.edges)),+ "prepared_source_mapping": copy.deepcopy(state.prepared_source_mapping),+ "source_prepared_mapping": copy.deepcopy(state.source_prepared_mapping),+ "prepared_iteration_paths": copy.deepcopy(state.prepared_iteration_paths),+ "indegree": copy.deepcopy(state.indegree),+ "execution_tokens": copy.deepcopy(state.execution_tokens),+ "gates": copy.deepcopy(state._generic_runtime().gates),+ }++ def capture_failed_transaction(operation: Any) -> Any:+ nonlocal failed_transaction_snapshot+ transaction_snapshot = snapshot_state() if state._apply_transaction is None else None+ try:+ return run_materialization_transaction(operation)+ except RuntimeError as error:+ if transaction_snapshot is not None and str(error) == "injected deferred consumer initialization failure":+ failed_transaction_snapshot = transaction_snapshot+ raise++ def fail_after_second_frame(materializer: Any, exec_node_id: str, input_edges: Any = None) -> None:+ initialize_execution_node(materializer, exec_node_id, input_edges)+ if (+ materializer._state is state+ and state.prepared_source_mapping.get(exec_node_id) == "after"+ and state._get_iteration_path(exec_node_id) == (1,)+ ):+ raise RuntimeError("injected deferred consumer initialization failure")++ monkeypatch.setattr(materializer_type, "_initialize_execution_node", fail_after_second_frame)+ monkeypatch.setattr(state, "_run_materialization_transaction", capture_failed_transaction)+ with pytest.raises(RuntimeError, match="injected deferred consumer initialization failure"):+ while (node := state.next()) is not None:+ state.complete(node.id, node.invoke(Mock()))++ assert failed_transaction_snapshot is not None, "injected failure did not occur in a materialization transaction"+ assert snapshot_state() == failed_transaction_snapshot+ monkeypatch.undo()+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ assert state.is_complete(), f"graph stalled after retry: {trace}"+ assert not state.has_error()+ after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)+ assert [state.results[node_id].value for node_id in after_ids] == [[11, 21], [12, 22]][email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_direct_collect_collapses_condition_frame_for_branch_iterate(- force_compatibility_scheduler: bool,-) -> None:- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="outer_source", first=[1, 2]))- graph.add_node(IterateInvocation(id="outer"))- graph.add_node(CollectInvocation(id="middle_collect"))- graph.add_node(IterateInvocation(id="inner"))- graph.add_node(AddInvocation(id="body"))- graph.add_node(CollectInvocation(id="branch_collect"))- graph.add_node(FixedCollectionTestInvocation(id="condition"))- graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="result_collect"))- for source, source_field, destination, destination_field in (- ("outer_source", "collection", "outer", "collection"),- ("outer", "item", "middle_collect", "item"),- ("middle_collect", "collection", "inner", "collection"),- ("outer", "item", "body", "a"),- ("inner", "item", "body", "b"),- ("body", "value", "branch_collect", "item"),- ("outer", "item", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("branch_collect", "collection", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "result_collect", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_zip_collect_branch_with_empty_selected_collect_completes(force_compatibility_scheduler: bool) -> None:+ graph = _zip_collect_branch_with_root_condition_graph(condition_value=1)+ graph.update_node("left_source", CollectionConcatInvocation(id="left_source", first=[]))state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)+ state._execution_scheduler = (+ _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ )- trace, state = _run_graph(state)+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- assert state.is_complete()- middle_collect_id = next(iter(state.source_prepared_mapping["middle_collect"]))- assert state._get_iteration_path(middle_collect_id) == ()- assert state.results[middle_collect_id].collection == [1, 2]- inner_exec_ids = sorted(state.source_prepared_mapping["inner"], key=state._get_iteration_path)- assert [state._get_iteration_path(exec_id) for exec_id in inner_exec_ids] == [- (0, 0),- (0, 1),- (1, 0),- (1, 1),- ]- assert state.results[next(iter(state.source_prepared_mapping["result_collect"]))].collection == [[2, 3], [3, 4]]+ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error()+ after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)+ collect_ids = sorted(state.source_prepared_mapping["branch_collect"], key=state._get_iteration_path)+ assert len(after_ids) == 1+ assert state._get_iteration_path(after_ids[0]) == ()+ assert state.results[after_ids[0]].value == []+ assert len(collect_ids) == 1+ assert state.results[collect_ids[0]].collection == []+ assert trace.count("right") == 2+ assert trace.count("body") == 0+ assert trace.count("branch_collect") == 1+ assert trace.count("if") == 1+ activation_tokens = [token for token in state.execution_tokens.values() if token.token_kind == "activation"]+ assert [(token.port, token.frame.iteration_path) for token in activation_tokens] == [("true_input", ())]@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("node_order", ["original", "reverse", "seed7", "renamed", "renamed_producers"])-def test_independent_iterator_collect_preserves_ordered_parent_axis_for_branch_iterate(- force_compatibility_scheduler: bool,- node_order: str,-) -> None:- graph = Graph()- condition_axis_id, other_axis_id = ("z_condition", "a_other") if node_order == "renamed" else ("left", "right")- condition_source_id, other_source_id = (- ("z_condition_source", "a_other_source")- if node_order == "renamed_producers"- else ("left_source", "right_source")+def test_zip_collect_branch_with_empty_right_preserves_left_frames(force_compatibility_scheduler: bool) -> None:+ graph = _zip_collect_branch_with_root_condition_graph(condition_value=1)+ graph.update_node("right_source", CollectionConcatInvocation(id="right_source", first=[]))+ state = GraphExecutionState(graph=graph)+ state._execution_scheduler = (+ _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state))- nodes = {- condition_source_id: CollectionConcatInvocation(id=condition_source_id, first=[1, 2]),- condition_axis_id: IterateInvocation(id=condition_axis_id),- other_source_id: CollectionConcatInvocation(id=other_source_id, first=[10, 20]),- other_axis_id: IterateInvocation(id=other_axis_id),- "middle_body": AddInvocation(id="middle_body"),- "middle_collect": CollectInvocation(id="middle_collect"),- "candidate": IterateInvocation(id="candidate"),- "body": AddInvocation(id="body"),- "branch_collect": CollectInvocation(id="branch_collect"),- "condition": FixedCollectionTestInvocation(id="condition"),- "fallback": AnyTypeTestInvocation(id="fallback", value="fallback"),- "if": IfInvocation(id="if"),- "result_collect": CollectInvocation(id="result_collect"),- }- ordered_node_ids = list(nodes)- if node_order == "reverse":- ordered_node_ids.reverse()- elif node_order == "seed7":- ordered_node_ids = random.Random(7).sample(ordered_node_ids, len(ordered_node_ids))- for node_id in ordered_node_ids:- graph.add_node(nodes[node_id])- for source, source_field, destination, destination_field in (- (condition_source_id, "collection", condition_axis_id, "collection"),- (other_source_id, "collection", other_axis_id, "collection"),- (condition_axis_id, "item", "middle_body", "a"),- (other_axis_id, "item", "middle_body", "b"),- ("middle_body", "value", "middle_collect", "item"),- ("middle_collect", "collection", "candidate", "collection"),- (condition_axis_id, "item", "body", "a"),- ("candidate", "item", "body", "b"),- ("body", "value", "branch_collect", "item"),- (condition_axis_id, "item", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("branch_collect", "collection", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "result_collect", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))- state = GraphExecutionState(graph=graph)+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error()+ after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)+ assert [state._get_iteration_path(node_id) for node_id in after_ids] == [(0,), (1,)]+ assert [state.results[node_id].value for node_id in after_ids] == [[], []]+ assert trace.count("body") == 0+ assert trace.count("branch_collect") == 2+ assert trace.count("if") == 2+ tokens = sorted(+ (token for token in state.execution_tokens.values() if token.token_kind == "activation"),+ key=lambda token: token.frame.iteration_path,+ )+ assert [(token.port, token.frame.iteration_path) for token in tokens] == [+ ("true_input", (0,)),+ ("true_input", (1,)),+ ]++[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_zip_collect_branch_activation_frames_resume_after_round_trip(force_compatibility_scheduler: bool) -> None:+ state = GraphExecutionState(graph=_zip_collect_branch_with_root_condition_graph(condition_value=1))if force_compatibility_scheduler:state._execution_scheduler = _ExecutionScheduler(state)- trace, state = _run_graph(state)+ partial_trace, state = _run_graph(+ state,+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after=15,+ )+ assert partial_trace[-1] == "if"+ assert partial_trace.count("if") == 1+ assert not state.is_complete()+ assert not state.has_error()+ partial_if_ids = sorted(state.source_prepared_mapping["if"], key=state._get_iteration_path)+ assert [state._get_iteration_path(node_id) for node_id in partial_if_ids] == [(0,), (1,)]+ assert sum(node_id in state.results for node_id in partial_if_ids) == 1+ assert sum(node_id not in state.results for node_id in partial_if_ids) == 1- assert state.is_complete(), f"graph stalled after {trace}"- middle_collect_exec_ids = sorted(state.source_prepared_mapping["middle_collect"], key=state._get_iteration_path)- assert [- (state._get_iteration_path(exec_id), state.results[exec_id].collection) for exec_id in middle_collect_exec_ids- ] == [((0,), [11, 21]), ((1,), [12, 22])]- candidate_exec_ids = sorted(state.source_prepared_mapping["candidate"], key=state._get_iteration_path)- assert [state._get_iteration_path(exec_id) for exec_id in candidate_exec_ids] == [- (0, 0),- (0, 1),- (1, 0),- (1, 1),- ]- assert state.results[next(iter(state.source_prepared_mapping["result_collect"]))].collection == [- [12, 22],- [14, 24],- ]+ state = load_execution_state(dump_execution_state(state))+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(state)+ remaining_trace, state = _run_graph(state)++ assert state.is_complete(), f"resume stalled after {remaining_trace}"+ assert not state.has_error()+ assert not state._pending_if_exec_nodes+ assert not state._has_pending_lifecycle_execution()+ after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)+ assert [state.results[node_id].value for node_id in after_ids] == [[11, 21], [12, 22]]@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])@pytest.mark.parametrize(- ("xs", "expected", "expected_trace", "expected_history"),+ ("left", "right", "expected"),[- ([], [], ["xs", "collect"], ["xs", "iterate", "true_value", "false_value", "if", "collect"]),- (- [True],- ["T"],- ["xs", "iterate", "true_value", "if", "collect"],- ["xs", "iterate", "false_value", "true_value", "if", "collect"],- ),+ ([5, 6, 7, 8], [10], [[15, 16, 17, 18]]),+ ([1, 2, 3], [10, 20], [[11, 12, 13], [21, 22, 23]]),],- ids=["empty-condition", "non-empty-condition"],+ ids=["one-right-item", "two-right-items"],)-def test_iterate_if_condition_completes_without_invoking_unselected_branches(- force_compatibility_scheduler: bool,- xs: list[bool],- expected: list[str],- expected_trace: list[str],- expected_history: list[str],+def test_sibling_collect_branch_keeps_every_item_when_condition_comes_from_the_other_axis(+ force_compatibility_scheduler: bool, left: list[int], right: list[int], expected: list[list[int]]) -> None:- graph = Graph()- for node in (- CollectionConcatInvocation(id="xs", first=xs),- IterateInvocation(id="iterate"),- AnyTypeTestInvocation(id="true_value", value="T"),- AnyTypeTestInvocation(id="false_value", value="F"),- IfInvocation(id="if"),- CollectInvocation(id="collect"),- ):- graph.add_node(node)- for source, source_field, destination, destination_field in (- ("xs", "collection", "iterate", "collection"),- ("iterate", "item", "if", "condition"),- ("true_value", "value", "if", "true_input"),- ("false_value", "value", "if", "false_input"),- ("if", "value", "collect", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))+ state = GraphExecutionState(graph=_sibling_collect_if_graph(left=left, right=right, condition_axis="right"))- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)- trace, state = _run_graph(state)+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- assert trace == expected_trace- collect_exec_id = next(iter(state.source_prepared_mapping["collect"]))- assert state.results[collect_exec_id].collection == expected- assert not state.has_error()assert state.is_complete(), f"graph stalled after {trace}"- assert state.executed_history == expected_history- if not xs:- assert state.source_prepared_mapping["true_value"] == set()- assert state.source_prepared_mapping["false_value"] == set()- else:- assert state.source_prepared_mapping["true_value"]- assert state.source_prepared_mapping["false_value"] == set()+ assert _collect_output(state) == expected+ assert trace.count("body") == len(left) * len(right)++[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+ ("left", "collect_field", "expected"),+ [+ ([1, 2], "true_input", ["fallback", []]),+ ([2, 2], "true_input", [[], []]),+ ([2], "true_input", [[]]),+ ([1, 2], "false_input", [[], "fallback"]),+ ],+ ids=["mixed", "all-selected", "single-selected", "false-branch"],+)+def test_sibling_collect_branch_with_empty_right_collection_completes(+ force_compatibility_scheduler: bool, left: list[int], collect_field: str, expected: list[Any]+) -> None:+ state = GraphExecutionState(graph=_sibling_collect_if_graph(left=left, right=[], collect_field=collect_field))- restored = load_execution_state(dump_execution_state(state))- assert restored.is_complete()- assert restored.executed_history == expected_history- restored_collect_exec_id = next(iter(restored.source_prepared_mapping["collect"]))- assert restored.results[restored_collect_exec_id].collection == expected+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert state.is_complete(), f"graph stalled after {trace}"+ assert _collect_output(state) == expected+ assert "body" not in trace@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_if_allows_shared_condition_and_branch_iterator_axis(force_compatibility_scheduler: bool) -> None:- graph = Graph()- for node in (- CollectionConcatInvocation(id="source", first=[1, 0]),- IterateInvocation(id="iterate"),- FixedCollectionTestInvocation(id="condition"),- AnyTypeTestInvocation(id="branch"),- AnyTypeTestInvocation(id="fallback", value="fallback"),- IfInvocation(id="if"),- CollectInvocation(id="collect"),- ):- graph.add_node(node)- for source, source_field, destination, destination_field in (- ("source", "collection", "iterate", "collection"),- ("iterate", "item", "condition", "value"),- ("iterate", "item", "branch", "value"),- ("condition", "condition", "if", "condition"),- ("branch", "value", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "collect", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))+def test_one_collect_may_feed_both_branches_of_the_same_if(force_compatibility_scheduler: bool) -> None:+ state = GraphExecutionState(graph=_sibling_collect_if_graph(left=[1, 2], right=[10, 20], same_if_both_fields=True))- trace, state = _run_graph(- GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler- )+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)assert state.is_complete(), f"graph stalled after {trace}"- result_exec_id = next(iter(state.source_prepared_mapping["collect"]))- assert state.results[result_exec_id].collection == [1, "fallback"]+ assert _collect_output(state) == [[11, 21], [12, 22]]-def test_if_iteration_axis_validation_cache_invalidates_after_graph_edit() -> None:+def _nested_collect_branch_graph(*, outer_values: list[int], extra_consumer_of: str) -> Graph:+ """Per-outer If whose true branch collects an inner Iterate; another node also consumes the inner axis."""graph = Graph()for node in (- CollectionConcatInvocation(id="branch_source", first=[10, 20]),- IterateInvocation(id="branch_iterate"),- AnyTypeTestInvocation(id="branch_value"),- CollectionConcatInvocation(id="condition_source", first=[1]),- IterateInvocation(id="condition_iterate"),+ CollectionConcatInvocation(id="outer_source", first=outer_values),+ IterateInvocation(id="outer"),+ RangeInvocation(id="range", start=0, step=1),+ IterateInvocation(id="inner"),+ AddInvocation(id="body", b=100),+ CollectInvocation(id="inner_collect"),+ AnyTypeTestInvocation(id="root_false", value="F"),+ AddInvocation(id="minus_one", b=-1),FixedCollectionTestInvocation(id="condition"),IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ AnyTypeTestInvocation(id="extra"),+ CollectInvocation(id="extra_collect"),):graph.add_node(node)+ extra_field = "item" if extra_consumer_of == "inner" else "value"for source, source_field, destination, destination_field in (- ("branch_source", "collection", "branch_iterate", "collection"),- ("branch_iterate", "item", "branch_value", "value"),- ("condition_source", "collection", "condition_iterate", "collection"),- ("condition_iterate", "item", "condition", "value"),+ ("outer_source", "collection", "outer", "collection"),+ ("outer", "item", "range", "stop"),+ ("range", "collection", "inner", "collection"),+ ("inner", "item", "body", "a"),+ ("body", "value", "inner_collect", "item"),+ ("outer", "item", "minus_one", "a"),+ ("minus_one", "value", "condition", "value"),("condition", "condition", "if", "condition"),+ ("inner_collect", "collection", "if", "true_input"),+ ("root_false", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ (extra_consumer_of, extra_field, "extra", "value"),+ ("extra", "value", "extra_collect", "item"),):graph.add_edge(create_edge(source, source_field, destination, destination_field))+ return graph- state = GraphExecutionState(graph=graph)- assert state.next() is not None- state.add_edge(create_edge("branch_value", "value", "if", "true_input"))- with pytest.raises(- graph_if_runtime.UnsupportedIfIterationAxesError,- match=(- r"If node 'if' cannot select branch input 'true_input' from unrelated open iterator axes: "- r"condition \['condition_iterate'\], branch \['branch_iterate'\]"- ),- ):- state.next()[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("extra_consumer_of", ["inner", "body"])+ ("outer_values", "expected"),+ [([2], [[100, 101]]), ([3, 1, 2], [[100, 101, 102], "F", [100, 101]])],+ ids=["single-outer", "mixed-outer"],+)+def test_nested_collect_branch_with_extra_inner_consumer_runs_if_once_per_outer_item(+ force_compatibility_scheduler: bool, extra_consumer_of: str, outer_values: list[int], expected: list[Any]+) -> None:+ state = GraphExecutionState(+ graph=_nested_collect_branch_graph(outer_values=outer_values, extra_consumer_of=extra_consumer_of)+ )++ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)++ assert state.is_complete(), f"graph stalled after {trace}"+ assert _collect_output(state) == expected+ assert trace.count("if") == len(outer_values)@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_if_rejects_sibling_inner_iterator_axes_with_shared_outer_axis(force_compatibility_scheduler: bool) -> None:+ "conditions",+ [[True], [False], [True, False], [False, False]],+ ids=["selected", "never-selected", "mixed", "all-unselected"],+)+def test_if_with_unrelated_branch_axis_is_rejected_before_any_node_runs(+ force_compatibility_scheduler: bool, conditions: list[bool]+) -> None:+ """The axis mismatch is topological, so it must not depend on condition values or run upstream work first."""graph = Graph()- graph.add_node(CollectionConcatInvocation(id="outer_source", first=["truth"]))- graph.add_node(IterateInvocation(id="outer"))- graph.add_node(PolymorphicStringTestInvocation(id="left_source"))- graph.add_node(IterateInvocation(id="left"))- graph.add_node(FixedCollectionTestInvocation(id="right_source"))- graph.add_node(IterateInvocation(id="right"))+ graph.add_node(CollectionConcatInvocation(id="branch_source", first=[1, 2]))+ graph.add_node(IterateInvocation(id="branch_iterate"))+ graph.add_node(AnyTypeTestInvocation(id="branch_value"))+ graph.add_node(CollectionConcatInvocation(id="condition_source", first=conditions))+ graph.add_node(IterateInvocation(id="condition_iterate"))graph.add_node(FixedCollectionTestInvocation(id="condition"))- graph.add_node(AnyTypeTestInvocation(id="branch"))graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))graph.add_node(IfInvocation(id="if"))graph.add_node(CollectInvocation(id="collect"))for source, source_field, destination, destination_field in (- ("outer_source", "collection", "outer", "collection"),- ("outer", "item", "left_source", "value"),- ("left_source", "collection", "left", "collection"),- ("outer", "item", "right_source", "value"),- ("right_source", "collection", "right", "collection"),- ("left", "item", "condition", "value"),- ("right", "item", "branch", "value"),+ ("branch_source", "collection", "branch_iterate", "collection"),+ ("branch_iterate", "item", "branch_value", "value"),+ ("condition_source", "collection", "condition_iterate", "collection"),+ ("condition_iterate", "item", "condition", "value"),("condition", "condition", "if", "condition"),- ("branch", "value", "if", "true_input"),+ ("branch_value", "value", "if", "true_input"),("fallback", "value", "if", "false_input"),("if", "value", "collect", "item"),):graph.add_edge(create_edge(source, source_field, destination, destination_field))- graph.validate_self()- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)- with pytest.raises(- graph_if_runtime.UnsupportedIfIterationAxesError,- match="cannot select branch input 'true_input' from unrelated open iterator axes",- ):- _run_graph(state)+ executed: list[str] = []+ with pytest.raises(graph_if_runtime.UnsupportedIfIterationAxesError):+ graph.validate_self()+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)+ while (node := state.next()) is not None:+ executed.append(state.prepared_source_mapping[node.id])+ state.complete(node.id, node.invoke(Mock()))+ assert executed == [][email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_sibling_collect_cannot_feed_multiple_if_branches(force_compatibility_scheduler: bool) -> None:+def _product_branch_deeper_than_condition_graph() -> Graph:graph = Graph()for node in (- CollectionConcatInvocation(id="left_source", first=[0, 1]),+ CollectionConcatInvocation(id="left_source", first=[1, 2]),CollectionConcatInvocation(id="right_source", first=[10, 20]),IterateInvocation(id="left"),IterateInvocation(id="right"),AddInvocation(id="body"),- CollectInvocation(id="branch_collect"),- FixedCollectionTestInvocation(id="left_condition"),- AddInvocation(id="right_minus_one", b=-1),- FixedCollectionTestInvocation(id="right_condition"),- AnyTypeTestInvocation(id="fallback", value="fallback"),- IfInvocation(id="left_if"),- IfInvocation(id="right_if"),- CollectInvocation(id="left_result"),- CollectInvocation(id="right_result"),- ):- graph.add_node(node)- for source, source_field, destination, destination_field in (- ("left_source", "collection", "left", "collection"),- ("right_source", "collection", "right", "collection"),- ("left", "item", "body", "a"),- ("right", "item", "body", "b"),- ("body", "value", "branch_collect", "item"),- ("left", "item", "left_condition", "value"),- ("left", "item", "right_minus_one", "a"),- ("right_minus_one", "value", "right_condition", "value"),- ("left_condition", "condition", "left_if", "condition"),- ("right_condition", "condition", "right_if", "condition"),- ("branch_collect", "collection", "left_if", "true_input"),- ("branch_collect", "collection", "right_if", "true_input"),- ("fallback", "value", "left_if", "false_input"),- ("fallback", "value", "right_if", "false_input"),- ("left_if", "value", "left_result", "item"),- ("right_if", "value", "right_result", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))-- graph.validate_self()- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)- with pytest.raises(ValueError, match="cannot supply Collect-backed inputs to multiple If nodes"):- _run_graph(state)---def test_1000_node_any_chain_inside_iterate_if_completes() -> None:- chain_length = 1_000- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="source", first=[True, False]))- graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="collect"))- graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="f"))- for index in range(chain_length):- graph.add_node(AnyTypeTestInvocation(id=f"chain_{index}"))- graph.add_edge(create_edge("source", "collection", "iterate", "collection"))- graph.add_edge(create_edge("iterate", "item", "if", "condition"))- graph.add_edge(create_edge("iterate", "item", "chain_0", "value"))- graph.add_edge(create_edge("iterate", "item", "false_branch", "value"))- graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))- for index in range(chain_length - 1):- graph.add_edge(create_edge(f"chain_{index}", "value", f"chain_{index + 1}", "value"))- graph.add_edge(create_edge(f"chain_{chain_length - 1}", "value", "if", "true_input"))- graph.add_edge(create_edge("if", "value", "collect", "item"))-- state = GraphExecutionState(graph=graph)- original_recursion_limit = sys.getrecursionlimit()- try:- sys.setrecursionlimit(len(inspect.stack()) + 250)- trace, state = _run_graph(state)- finally:- sys.setrecursionlimit(original_recursion_limit)-- collect_exec_id = next(iter(state.source_prepared_mapping["collect"]))- assert state.results[collect_exec_id].collection == [True, "fFalse"]- assert all(trace.count(f"chain_{index}") == 1 for index in range(chain_length))- assert trace.count("false_branch") == 1- assert state.is_complete(), f"graph stalled after {trace[-8:]}"---def test_execution_materializer_cache_refreshes_after_sibling_iterate_edge_addition() -> None:- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="left_source", first=[2, 2]))- graph.add_node(CollectionConcatInvocation(id="right_source", first=[10, 20]))- graph.add_node(IterateInvocation(id="left"))- graph.add_node(IterateInvocation(id="right"))- graph.add_node(AddInvocation(id="body"))- graph.add_node(CollectInvocation(id="branch_collect"))- graph.add_node(AddInvocation(id="minus_one", b=-1))- graph.add_node(FixedCollectionTestInvocation(id="condition"))- graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="collect"))+ AddInvocation(id="minus_one", b=-1),+ FixedCollectionTestInvocation(id="condition"),+ AnyTypeTestInvocation(id="fallback", value="fallback"),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ):+ graph.add_node(node)for source, source_field, destination, destination_field in (("left_source", "collection", "left", "collection"),("right_source", "collection", "right", "collection"),("left", "item", "body", "a"),- ("body", "value", "branch_collect", "item"),+ ("right", "item", "body", "b"),("left", "item", "minus_one", "a"),("minus_one", "value", "condition", "value"),("condition", "condition", "if", "condition"),- ("branch_collect", "collection", "if", "true_input"),+ ("body", "value", "if", "true_input"),("fallback", "value", "if", "false_input"),("if", "value", "collect", "item"),):graph.add_edge(create_edge(source, source_field, destination, destination_field))-- state = GraphExecutionState(graph=graph)- first_node = state.next()- assert first_node is not None- first_source = state.prepared_source_mapping[first_node.id]- state.complete(first_node.id, first_node.invoke(Mock()))-- state.add_edge(create_edge("right", "item", "body", "b"))-- trace, state = _run_graph(state)-- collect_exec_id = next(iter(state.source_prepared_mapping["collect"]))- assert state.results[collect_exec_id].collection == [[12, 22], [12, 22]]- assert "right" in trace or first_source == "right"- assert "body" in trace- assert state.is_complete()+ return graph[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_if_diamond_branch_traversal_scales_with_graph_size(- force_compatibility_scheduler: bool, monkeypatch: pytest.MonkeyPatch-) -> None:- diamond_count = 16+def _nested_branch_deeper_than_condition_graph() -> Graph:+ """Condition per outer item; true branch per inner item, false branch per outer item."""graph = Graph()- graph.add_node(AnyTypeTestInvocation(id="source", value=1))- graph.add_node(IfInvocation(id="if", condition=True))- graph.add_node(AnyTypeTestInvocation(id="result"))- previous_node_id = "source"- for index in range(diamond_count):- left_id = f"left_{index}"- right_id = f"right_{index}"- merge_id = f"merge_{index}"- graph.add_node(AnyTypeTestInvocation(id=left_id))- graph.add_node(AnyTypeTestInvocation(id=right_id))- graph.add_node(AddInvocation(id=merge_id))- graph.add_edge(create_edge(previous_node_id, "value", left_id, "value"))- graph.add_edge(create_edge(previous_node_id, "value", right_id, "value"))- graph.add_edge(create_edge(left_id, "value", merge_id, "a"))- graph.add_edge(create_edge(right_id, "value", merge_id, "b"))- previous_node_id = merge_id- graph.add_edge(create_edge(previous_node_id, "value", "if", "true_input"))- graph.add_edge(create_edge("if", "value", "result", "value"))-- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)-- original_get_node = Graph.get_node- original_if_paths = graph_if_runtime._get_if_iteration_paths_with_ancestry- if_path_node_visits = 0- if_path_depth = 0-- def count_node_visits(self: Graph, node_id: str):- nonlocal if_path_node_visits- if if_path_depth:- if_path_node_visits += 1- return original_get_node(self, node_id)-- def count_if_path_work(*args: Any, **kwargs: Any):- nonlocal if_path_depth- if_path_depth += 1- try:- return original_if_paths(*args, **kwargs)- finally:- if_path_depth -= 1-- monkeypatch.setattr(Graph, "get_node", count_node_visits)- monkeypatch.setattr(graph_if_runtime, "_get_if_iteration_paths_with_ancestry", count_if_path_work)- trace, state = _run_graph(state)-- result_exec_id = next(iter(state.source_prepared_mapping["result"]))- assert state.results[result_exec_id].value == 2**diamond_count- assert state.is_complete(), f"graph stalled after {trace}"- assert if_path_node_visits < 100 * len(graph.nodes), (- f"If path inference visited {if_path_node_visits} graph nodes for {len(graph.nodes)} nodes"- )+ for node in (+ CollectionConcatInvocation(id="outer_source", first=[1, 2]),+ IterateInvocation(id="outer"),+ RangeInvocation(id="range", start=0, step=1),+ IterateInvocation(id="inner"),+ AddInvocation(id="minus_one", b=-1),+ FixedCollectionTestInvocation(id="condition"),+ MarkedAnyTypeTestInvocation(id="true_branch", marker="t"),+ MarkedAnyTypeTestInvocation(id="false_branch", marker="f"),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ):+ graph.add_node(node)+ for source, source_field, destination, destination_field in (+ ("outer_source", "collection", "outer", "collection"),+ ("outer", "item", "range", "stop"),+ ("range", "collection", "inner", "collection"),+ ("outer", "item", "minus_one", "a"),+ ("minus_one", "value", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("inner", "item", "true_branch", "value"),+ ("outer", "item", "false_branch", "value"),+ ("true_branch", "value", "if", "true_input"),+ ("false_branch", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ):+ graph.add_edge(create_edge(source, source_field, destination, destination_field))+ return graph[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])- ("xs", "ys", "expected"),- [- ([1, 1, 0], [10, 20, 30], [[10, 20, 30], [10, 20, 30], "fb"]),- ([1, 0], [10, 20], [[10, 20], "fb"]),- ([0, 1], [10, 20], ["fb", [10, 20]]),- ],- ids=["false-last", "false-last-short", "false-first"],-)-def test_per_item_if_preserves_unrelated_root_collect_frames(- force_compatibility_scheduler: bool,- xs: list[int],- ys: list[int],- expected: list[Any],-) -> None:+def _nested_branch_with_root_false_graph() -> Graph:+ """Condition per outer item; true branch per inner item, false branch at root."""graph = Graph()- graph.add_node(CollectionConcatInvocation(id="xs", first=xs))- graph.add_node(IterateInvocation(id="x"))- graph.add_node(CollectionConcatInvocation(id="ys", first=ys))- graph.add_node(IterateInvocation(id="y"))- graph.add_node(AnyTypeTestInvocation(id="yv"))- graph.add_node(CollectInvocation(id="branch_collect"))- graph.add_node(AnyTypeTestInvocation(id="fallback", value="fb"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="output"))+ for node in (+ CollectionConcatInvocation(id="outer_source", first=[3, 2]),+ IterateInvocation(id="outer"),+ RangeInvocation(id="range", start=0, step=1),+ IterateInvocation(id="inner"),+ AddInvocation(id="body", b=100),+ AddInvocation(id="minus_two", b=-2),+ FixedCollectionTestInvocation(id="condition"),+ AnyTypeTestInvocation(id="root_false", value="F"),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ):+ graph.add_node(node)for source, source_field, destination, destination_field in (- ("xs", "collection", "x", "collection"),- ("x", "item", "if", "condition"),- ("ys", "collection", "y", "collection"),- ("y", "item", "yv", "value"),- ("yv", "value", "branch_collect", "item"),- ("branch_collect", "collection", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "output", "item"),+ ("outer_source", "collection", "outer", "collection"),+ ("outer", "item", "range", "stop"),+ ("range", "collection", "inner", "collection"),+ ("inner", "item", "body", "a"),+ ("outer", "item", "minus_two", "a"),+ ("minus_two", "value", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ("body", "value", "if", "true_input"),+ ("root_false", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),):graph.add_edge(create_edge(source, source_field, destination, destination_field))-- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)- trace, state = _run_graph(state)-- assert state.is_complete(), f"graph stalled after {trace}"- output_exec_id = next(iter(state.source_prepared_mapping["output"]))- assert state.results[output_exec_id].collection == expected+ return graph@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])@pytest.mark.parametrize(- ("conditions", "expected"),+ "build_graph",[- ([False, True, True], ["fb", [5, 6], [5, 6]]),- ([True, True], [[5, 6], [5, 6]]),+ _product_branch_deeper_than_condition_graph,+ _nested_branch_deeper_than_condition_graph,+ _nested_branch_with_root_false_graph,],- ids=["mixed-conditions", "all-true"],+ ids=["product-branch", "nested-true-branch", "nested-branch-root-false"],)-def test_per_item_if_keeps_closed_for_output_collection(- force_compatibility_scheduler: bool,- conditions: list[bool],- expected: list[Any],+def test_if_branch_deeper_than_its_condition_completes_or_is_rejected(+ force_compatibility_scheduler: bool, build_graph: Callable[[], Graph]) -> None:- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="conditions", first=conditions))- graph.add_node(IterateInvocation(id="condition_iterate"))- graph.add_node(ForInvocation(id="for", collection=[5, 6], state=LoopState(values={"count": 0})))- graph.add_node(AnyTypeTestInvocation(id="body"))- graph.add_node(ForReturnInvocation(id="for_return"))- graph.add_node(AnyTypeTestInvocation(id="fallback", value="fb"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="output"))- for source, source_field, destination, destination_field in (- ("conditions", "collection", "condition_iterate", "collection"),- ("condition_iterate", "item", "if", "condition"),- ("for", "item", "body", "value"),- ("body", "value", "for_return", "output"),- ("for", "output_collection", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "output", "item"),+ """Deeper open branch axes are explicitly rejected before any node executes."""+ state = GraphExecutionState(graph=build_graph())+ with pytest.raises(+ graph_if_runtime.UnsupportedIfIterationAxesError,+ match=(+ r"If node 'if' cannot select branch input 'true_input' from deeper open iterator axes "+ r"without a Collect boundary"+ ),):- graph.add_edge(create_edge(source, source_field, destination, destination_field))- graph.add_edge(create_loop_linkage("for", "for_return"))-- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)- trace, state = _run_graph(state)-- assert state.is_complete(), f"graph stalled after {trace}"- output_exec_id = next(iter(state.source_prepared_mapping["output"]))- assert state.results[output_exec_id].collection == expected- final_for_exec_id = max(- state.source_prepared_mapping["for"],- key=lambda exec_node_id: state.execution_graph.get_node(exec_node_id).index,- )- assert state.results[final_for_exec_id].output_collection == [5, 6]+ _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ assert state.executed_history == [][email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("extra_source", ["right", "branch_collect"])-def test_deferred_sibling_iterate_does_not_starve_ready_consumers(- force_compatibility_scheduler: bool,- extra_source: str,-) -> None:- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="left_source", first=[1, 2]))- graph.add_node(CollectionConcatInvocation(id="right_source", first=[10, 20]))- graph.add_node(IterateInvocation(id="left"))- graph.add_node(IterateInvocation(id="right"))- graph.add_node(AddInvocation(id="body"))- graph.add_node(CollectInvocation(id="branch_collect"))- graph.add_node(AddInvocation(id="minus_one", b=-1))- graph.add_node(FixedCollectionTestInvocation(id="condition"))- graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="output"))- graph.add_node(AnyTypeTestInvocation(id="extra"))+def _broadcast_deeper_if_graph(*, selected: bool) -> Graph:+ """An outer condition selects one of two complete inner-Iterate branches."""+ graph = Graph()+ for node in (+ CollectionConcatInvocation(id="outer_source", first=[2, 0] if selected else [0, 2]),+ IterateInvocation(id="outer"),+ AddInvocation(id="range_stop", b=1),+ RangeInvocation(id="range", start=0, step=1),+ IterateInvocation(id="inner"),+ FixedCollectionTestInvocation(id="condition"),+ AddInvocation(id="true_value", b=10),+ AddInvocation(id="false_value", b=100),+ IfInvocation(id="if"),+ CollectInvocation(id="collect"),+ ):+ graph.add_node(node)for source, source_field, destination, destination_field in (- ("left_source", "collection", "left", "collection"),- ("right_source", "collection", "right", "collection"),- ("left", "item", "body", "a"),- ("right", "item", "body", "b"),- ("body", "value", "branch_collect", "item"),- ("left", "item", "minus_one", "a"),- ("minus_one", "value", "condition", "value"),+ ("outer_source", "collection", "outer", "collection"),+ ("outer", "item", "condition", "value"),("condition", "condition", "if", "condition"),- ("branch_collect", "collection", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "output", "item"),- (extra_source, "item" if extra_source == "right" else "collection", "extra", "value"),+ ("outer", "item", "range_stop", "a"),+ ("range_stop", "value", "range", "stop"),+ ("range", "collection", "inner", "collection"),+ ("inner", "item", "true_value", "a"),+ ("inner", "item", "false_value", "a"),+ ("true_value", "value", "if", "true_input"),+ ("false_value", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),):graph.add_edge(create_edge(source, source_field, destination, destination_field))+ return graph- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)- trace, state = _run_graph(state)+[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("selected", [True, False], ids=["true-branch", "false-branch"])+def test_if_broadcasts_a_deeper_iterate_branch_across_each_outer_condition_frame(+ force_compatibility_scheduler: bool, selected: bool+) -> None:+ state = GraphExecutionState(graph=_broadcast_deeper_if_graph(selected=selected))++ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)assert state.is_complete(), f"graph stalled after {trace}"- output_exec_id = next(iter(state.source_prepared_mapping["output"]))- assert state.results[output_exec_id].collection == ["fallback", [12, 22]]- assert "extra" in trace+ assert not state.has_error()+ expected = [[10, 11, 12], [100]] if selected else [[100], [10, 11, 12]]+ collect_nodes = sorted(state.source_prepared_mapping["collect"], key=state._get_iteration_path)+ collected = [state.results[node_id].collection for node_id in collect_nodes]+ assert collected == expected, f"{trace=}"+ assert trace.count("if") == 4+ assert trace.count("true_value") == 4+ assert trace.count("false_value") == 4+ assert len(collect_nodes) == 2@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("reverse_node_insertion", [False, True], ids=["forward-insertion", "reverse-insertion"])- ("source_a", "iterate_a", "source_b", "iterate_b"),- [- ("zz_source", "zz_iterate", "aa_source", "aa_iterate"),- ("p_source", "q_iterate", "x_source", "y_iterate"),- ],- ids=["reverse-lexical-ids", "alternate-ids"],-)-def test_independent_iterate_axes_follow_add_input_order(+def test_if_broadcast_deeper_iterate_frames_resume_after_dump_load(force_compatibility_scheduler: bool,- reverse_node_insertion: bool,- source_a: str,- iterate_a: str,- source_b: str,- iterate_b: str,) -> None:- nodes = [- CollectionConcatInvocation(id=source_a, first=[10, 20]),- IterateInvocation(id=iterate_a),- CollectionConcatInvocation(id=source_b, first=[1, 2, 3]),- IterateInvocation(id=iterate_b),- AddInvocation(id="sum"),- CollectInvocation(id="output"),- ]- if reverse_node_insertion:- nodes.reverse()- graph = Graph(nodes={node.id: node for node in nodes})- for source, source_field, destination, destination_field in (- (source_a, "collection", iterate_a, "collection"),- (source_b, "collection", iterate_b, "collection"),- (iterate_a, "item", "sum", "a"),- (iterate_b, "item", "sum", "b"),- ("sum", "value", "output", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))+ state = GraphExecutionState(graph=_broadcast_deeper_if_graph(selected=True))+ _, partial = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler, stop_after=7)+ restored = load_execution_state(dump_execution_state(partial))- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)- _, state = _run_graph(state)+ trace, restored = _run_graph(restored, force_compatibility_scheduler=force_compatibility_scheduler)- output_exec_ids = sorted(state.source_prepared_mapping["output"], key=state._get_iteration_path)- actual = [(state._get_iteration_path(exec_id), state.results[exec_id].collection) for exec_id in output_exec_ids]- assert actual == [((0,), [11, 12, 13]), ((1,), [21, 22, 23])]- assert state.is_complete()+ assert restored.is_complete(), f"graph stalled after resume: {trace}"+ collect_nodes = sorted(restored.source_prepared_mapping["collect"], key=restored._get_iteration_path)+ assert [restored.results[node_id].collection for node_id in collect_nodes] == [[10, 11, 12], [100]]@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])@pytest.mark.parametrize(- ("condition", "wire_opposite_root"),- [(True, True), (False, True), (False, False)],- ids=["true-with-root-false", "false-with-root-true", "false-without-true-input"],+ ("condition", "per_item_field", "root_field", "expected_value"),+ [+ (True, "false_input", "true_input", "root"),+ (False, "true_input", "false_input", "root"),+ (False, "true_input", None, None),+ ],+ ids=["true-selects-root", "false-selects-root", "false-selects-unwired"],)-def test_literal_if_inside_iterate_uses_selected_branch_frame(+def test_literal_if_selecting_a_root_branch_runs_both_branches_eagerly(force_compatibility_scheduler: bool,condition: bool,- wire_opposite_root: bool,+ per_item_field: str,+ root_field: str | None,+ expected_value: str | None,) -> None:graph = Graph()graph.add_node(CollectionConcatInvocation(id="source", first=[1, 2]))graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(AddInvocation(id="per_item", b=10))graph.add_node(IfInvocation(id="if", condition=condition))- graph.add_node(CollectInvocation(id="output"))+ graph.add_node(CollectInvocation(id="collect"))graph.add_edge(create_edge("source", "collection", "iterate", "collection"))- selected_branch = "true_input" if condition else "false_input"- selected_source = "true_branch" if condition else "false_branch"- opposite_branch = "false_input" if condition else "true_input"- graph.add_node(MarkedAnyTypeTestInvocation(id=selected_source, marker=f"{selected_branch}:"))- graph.add_edge(create_edge("iterate", "item", selected_source, "value"))- graph.add_edge(create_edge(selected_source, "value", "if", selected_branch))- if wire_opposite_root:- graph.add_node(AnyTypeTestInvocation(id="root_opposite", value="root"))- graph.add_edge(create_edge("root_opposite", "value", "if", opposite_branch))- graph.add_edge(create_edge("if", "value", "output", "item"))-+ graph.add_edge(create_edge("iterate", "item", "per_item", "a"))+ graph.add_edge(create_edge("per_item", "value", "if", per_item_field))+ graph.add_edge(create_edge("if", "value", "collect", "item"))+ if root_field is not None:+ graph.add_node(AnyTypeTestInvocation(id="root", value="root"))+ graph.add_edge(create_edge("root", "value", "if", root_field))state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)- trace, state = _run_graph(state)-- assert state.is_complete(), (- f"graph stalled after {trace}; prepared_paths={[(source_id, [state._get_iteration_path(exec_id) for exec_id in exec_ids]) for source_id, exec_ids in state.source_prepared_mapping.items()]}; "- f"indegree={state.indegree}; pending_if={state._pending_if_exec_nodes}; resolved={state._resolved_if_exec_branches}"- )- output_exec_id = next(iter(state.source_prepared_mapping["output"]))- marker = f"{selected_branch}:"- assert state.results[output_exec_id].collection == [f"{marker}1", f"{marker}2"]- assert trace.count("if") == 2- assert trace.count(selected_source) == 2- assert "root_opposite" not in trace- assert state.is_complete(), f"graph stalled after {trace}"- assert state.next() is None- assert not state._ready_node_ids- assert all(not queue for queue in state._ready_queues.values())--[email protected]("round_trip_after", [None, 6], ids=["fresh", "restored"])[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_literal_if_branch_feeds_per_item_if_without_stranding_unselected_root(- force_compatibility_scheduler: bool,- round_trip_after: int | None,-) -> None:- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="conditions", first=[True, True]))- graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(AnyTypeTestInvocation(id="literal_selected", value="literal"))- graph.add_node(AnyTypeTestInvocation(id="literal_unselected", value="literal-unselected"))- graph.add_node(IfInvocation(id="literal_if", condition=True))- graph.add_node(AnyTypeTestInvocation(id="per_item_unselected", value="per-item-unselected"))- graph.add_node(IfInvocation(id="per_item_if"))- graph.add_node(CollectInvocation(id="output"))- for source, source_field, destination, destination_field in (- ("conditions", "collection", "iterate", "collection"),- ("literal_selected", "value", "literal_if", "true_input"),- ("literal_unselected", "value", "literal_if", "false_input"),- ("iterate", "item", "per_item_if", "condition"),- ("literal_if", "value", "per_item_if", "true_input"),- ("per_item_unselected", "value", "per_item_if", "false_input"),- ("per_item_if", "value", "output", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))- state = GraphExecutionState(graph=graph)- if round_trip_after is None:- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- else:- checkpoint_trace, partial_state = _run_graph(- state,- force_compatibility_scheduler=force_compatibility_scheduler,- stop_after=round_trip_after,- )- assert "per_item_if" in checkpoint_trace- restored = load_execution_state(dump_execution_state(partial_state))- if force_compatibility_scheduler:- _restore_compatibility_scheduler(restored)- resumed_trace, state = _run_graph(restored, force_compatibility_scheduler=force_compatibility_scheduler)- trace = checkpoint_trace + resumed_trace+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- assert state.is_complete(), f"graph stalled after {trace}; pending={state._pending_if_exec_nodes}"- output_exec_id = next(iter(state.source_prepared_mapping["output"]))- assert state.results[output_exec_id].collection == ["literal", "literal"]- assert trace.count("literal_if") == 1- assert trace.count("per_item_if") == 2- assert state.source_prepared_mapping["literal_unselected"] == set()- assert state.source_prepared_mapping["per_item_unselected"] == set()- assert "literal_unselected" not in trace- assert "per_item_unselected" not in trace+ assert state.is_complete(), f"graph stalled after {trace}"+ assert trace.count("per_item") == 2+ collected = _collect_output(state)+ assert collected == [expected_value, expected_value]+ assert trace.count("if") == 2-def test_per_item_if_condition_from_iterate_index_selects_literal_values() -> None:+def test_deep_if_branch_chain_does_not_need_recursion_per_chain_node() -> None:+ """Guard #9821 cheaply: a recursive traversal exceeds this limit long before the issue's 1,000-node repro does."""+ chain_length = 150graph = Graph()- graph.add_node(CollectionConcatInvocation(id="source", first=[10, 20]))+ graph.add_node(CollectionConcatInvocation(id="source", first=[True, False]))graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(FixedCollectionTestInvocation(id="condition"))- graph.add_node(AnyTypeTestInvocation(id="false_value", value="no"))- graph.add_node(AnyTypeTestInvocation(id="true_value", value="yes"))graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="output"))- for source, source_field, destination, destination_field in (- ("source", "collection", "iterate", "collection"),- ("iterate", "index", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("false_value", "value", "if", "false_input"),- ("true_value", "value", "if", "true_input"),- ("if", "value", "output", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))-- trace, state = _run_graph(GraphExecutionState(graph=graph))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="f"))+ for index in range(chain_length):+ graph.add_node(AnyTypeTestInvocation(id=f"chain_{index}"))+ graph.add_edge(create_edge("source", "collection", "iterate", "collection"))+ graph.add_edge(create_edge("iterate", "item", "if", "condition"))+ graph.add_edge(create_edge("iterate", "item", "chain_0", "value"))+ graph.add_edge(create_edge("iterate", "item", "false_branch", "value"))+ graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))+ for index in range(chain_length - 1):+ graph.add_edge(create_edge(f"chain_{index}", "value", f"chain_{index + 1}", "value"))+ graph.add_edge(create_edge(f"chain_{chain_length - 1}", "value", "if", "true_input"))+ graph.add_edge(create_edge("if", "value", "collect", "item"))+ state = GraphExecutionState(graph=graph)- assert state.is_complete(), f"graph stalled after {trace}"- output_exec_id = next(iter(state.source_prepared_mapping["output"]))- assert state.results[output_exec_id].collection == ["no", "yes"]- assert trace.count("if") == 2+ previous_limit = sys.getrecursionlimit()+ sys.setrecursionlimit(len(inspect.stack()) + 250)+ try:+ _, state = _run_graph(state)+ finally:+ sys.setrecursionlimit(previous_limit)+ assert state.is_complete()+ assert _collect_output(state) == [True, "fFalse"][email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_deep_branch_root_false_with_two_outer_frames_and_nested_collect(- force_compatibility_scheduler: bool,-) -> None:- graph = Graph()- for node in (- CollectionConcatInvocation(id="outer_source", first=[0, 2]),- IterateInvocation(id="outer"),- RangeOfSizeInvocation(id="inner_source", start=100),- IterateInvocation(id="inner"),- AnyTypeTestInvocation(id="body"),- CollectInvocation(id="branch_collect"),- FixedCollectionTestInvocation(id="condition"),- AnyTypeTestInvocation(id="fallback", value="F"),- IfInvocation(id="if"),- CollectInvocation(id="output"),- ):- graph.add_node(node)- for source, source_field, destination, destination_field in (- ("outer_source", "collection", "outer", "collection"),- ("outer", "item", "inner_source", "size"),- ("inner_source", "collection", "inner", "collection"),- ("inner", "item", "body", "value"),- ("body", "value", "branch_collect", "item"),- ("outer", "item", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("branch_collect", "collection", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "output", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))[email protected]("force_compatibility_scheduler", [False, True])+def test_root_if_waits_for_reopened_collect_axis(force_compatibility_scheduler: bool) -> None:+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="src", first=["a", "b"]),+ IterateInvocation(id="it"),+ AnyTypeTestInvocation(id="m"),+ CollectInvocation(id="first"),+ IterateInvocation(id="rit"),+ AnyTypeTestInvocation(id="rm"),+ IfInvocation(id="if"),+ BooleanInvocation(id="cond", value=True),+ AnyTypeTestInvocation(id="root", value="RR"),+ CollectInvocation(id="collect"),+ ],+ [+ ("src", "collection", "it", "collection"),+ ("it", "item", "m", "value"),+ ("m", "value", "first", "item"),+ ("first", "collection", "rit", "collection"),+ ("rit", "item", "rm", "value"),+ ("rm", "value", "if", "true_input"),+ ("root", "value", "if", "false_input"),+ ("cond", "value", "if", "condition"),+ ("if", "value", "collect", "item"),+ ],+ )trace, state = _run_graph(GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler)+ assert state.is_complete(), trace+ assert _source_values(state, "collect") == {(): ["a", "b"]}- assert state.is_complete(), f"graph stalled after {trace}; history={state.executed_history}"- assert _source_output(state, "output").collection == ["F", [100, 101]]- assert trace.count("if") == 2- assert trace.count("branch_collect") == 1- assert trace.count("fallback") == 1- assert trace.count("output") == 1[email protected]("force_compatibility_scheduler", [False, True])[email protected]("sibling", [False, True])[email protected]("reverse_items", [False, True])+def test_plain_literal_if_chain_preserves_collect_items(+ force_compatibility_scheduler: bool, sibling: bool, reverse_items: bool+) -> None:+ nodes = [+ CollectionConcatInvocation(id="src", first=["x", "y"]),+ IterateInvocation(id="it"),+ MarkedAnyTypeTestInvocation(id="m", marker="m"),+ IfInvocation(id="if0", condition=True),+ IfInvocation(id="if1", condition=True),+ AnyTypeTestInvocation(id="fb0", value="R0"),+ AnyTypeTestInvocation(id="fb1", value="R1"),+ CollectInvocation(id="collect"),+ ]+ edges = [+ ("src", "collection", "it", "collection"),+ ("it", "item", "m", "value"),+ ("m", "value", "if0", "true_input"),+ ("fb0", "value", "if0", "false_input"),+ ("if0", "value", "if1", "true_input"),+ ("fb1", "value", "if1", "false_input"),+ ]+ items = [("if1", "value", "collect", "item")]+ if sibling:+ nodes += [+ CollectionConcatInvocation(id="srcb", first=["p", "q", "r"]),+ IterateInvocation(id="itb"),+ MarkedAnyTypeTestInvocation(id="n", marker="n"),+ ]+ edges += [("srcb", "collection", "itb", "collection"), ("itb", "item", "n", "value")]+ items += [("n", "value", "collect", "item")]+ edges += list(reversed(items)) if reverse_items else items+ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ assert state.is_complete(), trace+ values = _source_values(state, "collect")+ assert set(values) == {()}+ if sibling:+ assert set(values[()][:2]) == {"mx", "np"}+ assert set(values[()][2:4]) == {"my", "nq"}+ assert values[()][4:] == ["nr"]+ else:+ assert values[()] == ["mx", "my"][email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("extra_inner_consumer", [False, True], ids=["no-extra-consumer", "extra-inner-consumer"])-def test_nested_if_collect_branch_with_all_outer_frames_false_completes(- force_compatibility_scheduler: bool,- extra_inner_consumer: bool,+[email protected]("force_compatibility_scheduler", [False, True])[email protected]("inner_condition", [False, True])[email protected]("wired", [False, True])[email protected]("collect", [False, True])+def test_rejected_nested_if_with_shared_direct_and_for_axis_completes(+ force_compatibility_scheduler: bool, inner_condition: bool, wired: bool, collect: bool) -> None:- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="outer_source", first=["", ""]))- graph.add_node(IterateInvocation(id="outer"))- graph.add_node(PolymorphicStringTestInvocation(id="inner_collection"))- graph.add_node(IterateInvocation(id="inner"))- graph.add_node(AnyTypeTestInvocation(id="body"))- graph.add_node(CollectInvocation(id="branch_collect"))- graph.add_node(FixedCollectionTestInvocation(id="condition"))- graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="output"))- for source, source_field, destination, destination_field in (- ("outer_source", "collection", "outer", "collection"),- ("outer", "item", "inner_collection", "value"),- ("inner_collection", "collection", "inner", "collection"),- ("inner", "item", "body", "value"),- ("body", "value", "branch_collect", "item"),- ("outer", "item", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("branch_collect", "collection", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "output", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))- if extra_inner_consumer:- graph.add_node(AnyTypeTestInvocation(id="extra"))- graph.add_edge(create_edge("inner", "item", "extra", "value"))+ nodes = [+ CollectionConcatInvocation(id="src", first=[["a"]]),+ IterateInvocation(id="it"),+ AnyTypeTestInvocation(id="cm"),+ CollectInvocation(id="col"),+ AnyTypeTestInvocation(id="p3"),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="fb"),+ ForReturnInvocation(id="ret"),+ AnyTypeTestInvocation(id="p8"),+ AnyTypeTestInvocation(id="m9"),+ IfInvocation(id="inner", condition=inner_condition),+ IfInvocation(id="outer"),+ BooleanInvocation(id="cond", value=True),+ ]+ edges = [+ ("src", "collection", "it", "collection"),+ ("it", "item", "cm", "value"),+ ("cm", "value", "col", "item"),+ ("col", "collection", "p3", "value"),+ ("p3", "value", "outer", "true_input"),+ ("it", "item", "for", "collection"),+ ("for", "item", "fb", "value"),+ ("fb", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "p8", "value"),+ ("p8", "value", "inner", "true_input"),+ ("it", "item", "m9", "value"),+ ("m9", "value", "inner", "false_input"),+ ("inner", "value", "outer", "false_input"),+ ("cond", "value", "outer", "condition"),+ ]+ if wired:+ nodes += [BooleanInvocation(id="inner_cond", value=inner_condition)]+ edges += [("inner_cond", "value", "inner", "condition")]+ if collect:+ nodes += [CollectInvocation(id="collect")]+ edges += [("outer", "value", "collect", "item")]+ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ assert state.is_complete(), trace+ assert _source_values(state, "outer") == {(0,): [["a"]]}+ if collect:+ assert _source_values(state, "collect") == {(): [[["a"]]]}- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)- trace, state = _run_graph(state)- assert state.is_complete(), (- f"graph stalled after {trace}; prepared={state.source_prepared_mapping}; pending_if={state._pending_if_exec_nodes}; "- f"inactive_inner={state._is_source_inactive('inner')}; "- f"inner_dependencies={state._get_source_activation_dependencies('inner')}"[email protected]("force_compatibility_scheduler", [False, True])[email protected]("inner_condition", [False, True])+def test_nested_literal_branch_validation_preserves_shared_frames(+ force_compatibility_scheduler: bool, inner_condition: bool+) -> None:+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="src", first=[["a", "b"], ["", ""]]),+ IterateInvocation(id="it0"),+ CollectionConcatInvocation(id="cc"),+ IterateInvocation(id="it1"),+ MarkedAnyTypeTestInvocation(id="m1", marker="T:"),+ MarkedAnyTypeTestInvocation(id="m4", marker="U:"),+ AnyTypeTestInvocation(id="root", value="R"),+ IfInvocation(id="inner", condition=inner_condition),+ FixedCollectionTestInvocation(id="cond"),+ IfInvocation(id="outer"),+ CollectInvocation(id="collect"),+ ],+ [+ ("src", "collection", "it0", "collection"),+ ("it0", "item", "cc", "first"),+ ("cc", "collection", "it1", "collection"),+ ("it1", "item", "m1", "value"),+ ("m1", "value", "outer", "true_input"),+ ("it1", "item", "m4", "value"),+ ("m4", "value", "inner", "false_input"),+ ("root", "value", "inner", "true_input"),+ ("inner", "value", "outer", "false_input"),+ ("it0", "item", "cond", "value"),+ ("cond", "condition", "outer", "condition"),+ ("outer", "value", "collect", "item"),+ ],)- output_exec_id = next(iter(state.source_prepared_mapping["output"]))- assert state.results[output_exec_id].collection == ["fallback", "fallback"]- assert "branch_collect" not in trace- assert "body" not in trace- assert ("inner" in trace) is extra_inner_consumer- assert ("extra" in trace) is extra_inner_consumer- assert state.is_complete(), f"graph stalled after {trace}"- assert state.next() is None- assert not state._ready_node_ids- assert all(not queue for queue in state._ready_queues.values())+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )+ assert state.is_complete(), trace+ assert _source_values(state, "collect") == {(0,): ["T:a", "T:b"], (1,): ["T:", "T:"]}-def _sibling_collect_if_graph(- *,- left: list[int],- right: list[int],- condition_axis: str = "left",- collect_field: str = "true_input",- same_if_both_fields: bool = False,-) -> Graph:- """Build the #9820 shape: a Collect over a left x right product feeds one branch of a per-item If."""- graph = Graph()- for node in (- CollectionConcatInvocation(id="left_source", first=left),- CollectionConcatInvocation(id="right_source", first=right),- IterateInvocation(id="left"),- IterateInvocation(id="right"),- AddInvocation(id="body"),- CollectInvocation(id="branch_collect"),- AddInvocation(id="minus_one", b=-1),- FixedCollectionTestInvocation(id="condition"),- IfInvocation(id="if"),[email protected]("force_compatibility_scheduler", [False, True])+def test_per_item_if_with_deep_literal_chain_completes(force_compatibility_scheduler: bool) -> None:+ nodes = [+ CollectionConcatInvocation(id="src", first=[True]),+ IterateInvocation(id="it"),+ AnyTypeTestInvocation(id="m"),+ AnyTypeTestInvocation(id="root", value="R"),+ IfInvocation(id="outer"),CollectInvocation(id="collect"),- ):- graph.add_node(node)- other_field = "false_input" if collect_field == "true_input" else "true_input"+ ]edges = [- ("left_source", "collection", "left", "collection"),- ("right_source", "collection", "right", "collection"),- ("left", "item", "body", "a"),- ("right", "item", "body", "b"),- ("body", "value", "branch_collect", "item"),- (condition_axis, "item", "minus_one", "a"),- ("minus_one", "value", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("branch_collect", "collection", "if", collect_field),- ("if", "value", "collect", "item"),+ ("src", "collection", "it", "collection"),+ ("it", "item", "m", "value"),+ ("it", "item", "outer", "condition"),+ ("root", "value", "outer", "false_input"),+ ("outer", "value", "collect", "item"),]- if same_if_both_fields:- edges.append(("branch_collect", "collection", "if", other_field))- else:- graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))- edges.append(("fallback", "value", "if", other_field))- for source, source_field, destination, destination_field in edges:- graph.add_edge(create_edge(source, source_field, destination, destination_field))+ previous = "m"+ for index in range(600):+ node_id = f"literal{index}"+ nodes.append(IfInvocation(id=node_id, condition=True))+ edges += [(previous, "value", node_id, "true_input"), ("m", "value", node_id, "false_input")]+ previous = node_id+ edges += [(previous, "value", "outer", "true_input")]+ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ assert state.is_complete(), trace+ assert _source_values(state, "collect") == {(): [True]}+++def _review_b1_nested_literal_if_collect_graph(*, inner_condition: bool | None = None) -> Graph:+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="src", first=[[["a"], ["b", "c"]], [["d"]]]),+ IterateInvocation(id="it0"),+ CollectionConcatInvocation(id="cc0"),+ IterateInvocation(id="it1"),+ CollectionConcatInvocation(id="cc1"),+ IterateInvocation(id="it2"),+ MarkedAnyTypeTestInvocation(id="t", marker="T:"),+ FixedCollectionTestInvocation(id="cond"),+ AnyTypeTestInvocation(id="root", value="R"),+ IfInvocation(id="inner", condition=True),+ CollectInvocation(id="col"),+ MarkedAnyTypeTestInvocation(id="u", marker="U:"),+ IfInvocation(id="outer"),+ CollectInvocation(id="out"),+ ],+ [+ ("src", "collection", "it0", "collection"),+ ("it0", "item", "cc0", "first"),+ ("cc0", "collection", "it1", "collection"),+ ("it1", "item", "cc1", "first"),+ ("cc1", "collection", "it2", "collection"),+ ("it0", "item", "t", "value"),+ ("t", "value", "outer", "true_input"),+ ("it0", "item", "cond", "value"),+ ("cond", "condition", "outer", "condition"),+ ("root", "value", "inner", "true_input"),+ ("it2", "item", "col", "item"),+ ("col", "collection", "u", "value"),+ ("u", "value", "inner", "false_input"),+ ("inner", "value", "outer", "false_input"),+ ("outer", "value", "out", "item"),+ ],+ )+ if inner_condition is not None:+ graph.update_node("inner", IfInvocation(id="inner"))+ graph.add_node(BooleanInvocation(id="inner_condition", value=inner_condition))+ graph.add_edge(create_edge("inner_condition", "value", "inner", "condition"))return graph-def _collect_output(state: GraphExecutionState, source_id: str = "collect") -> list[Any]:- return state.results[next(iter(state.source_prepared_mapping[source_id]))].collection[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("inner_condition", [None, True], ids=["literal", "wired-root"])+def test_nested_literal_if_collect_preserves_selected_outer_frames(+ force_compatibility_scheduler: bool, inner_condition: bool | None+) -> None:+ state = GraphExecutionState(graph=_review_b1_nested_literal_if_collect_graph(inner_condition=inner_condition))+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)-def _zip_collect_branch_with_root_condition_graph(condition_value: int) -> Graph:- graph = Graph()- for node in (- CollectionConcatInvocation(id="left_source", first=[1, 2]),- CollectionConcatInvocation(id="right_source", first=[10, 20]),- IterateInvocation(id="left"),- IterateInvocation(id="right"),- AddInvocation(id="body"),- CollectInvocation(id="branch_collect"),- FixedCollectionTestInvocation(id="condition", value=condition_value),- AnyTypeTestInvocation(id="fallback", value="fallback"),- IfInvocation(id="if"),- AnyTypeTestInvocation(id="after"),- ):- graph.add_node(node)- for source, source_field, destination, destination_field in (- ("left_source", "collection", "left", "collection"),- ("right_source", "collection", "right", "collection"),- ("left", "item", "body", "a"),- ("right", "item", "body", "b"),- ("body", "value", "branch_collect", "item"),- ("condition", "condition", "if", "condition"),- ("branch_collect", "collection", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "after", "value"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))- return graph+ assert state.is_complete(), trace+ assert _source_values(state, "out") == {(): ["T:[['a'], ['b', 'c']]", "T:[['d']]"]}-def _zip_collect_then_after_graph() -> Graph:- graph = _zip_collect_branch_with_root_condition_graph(1)- graph.delete_node("if")- graph.delete_node("fallback")- graph.add_edge(create_edge("branch_collect", "collection", "after", "value"))- return graph+def _review_b2_root_condition_for_final_nested_if_graph() -> Graph:+ return _graph_from(+ [+ CollectionConcatInvocation(id="empty", first=[]),+ IterateInvocation(id="it0"),+ MarkedAnyTypeTestInvocation(id="m10", marker="bF:"),+ ForInvocation(id="for", collection=["u", "v"]),+ MarkedAnyTypeTestInvocation(id="fb8", marker="F"),+ ForReturnInvocation(id="ret9"),+ IfInvocation(id="iif6"),+ BooleanInvocation(id="cond", value=False),+ MarkedAnyTypeTestInvocation(id="p12", marker="F:"),+ IfInvocation(id="outer", condition=False),+ AnyTypeTestInvocation(id="root", value="R"),+ CollectInvocation(id="out"),+ ],+ [+ ("empty", "collection", "it0", "collection"),+ ("it0", "item", "m10", "value"),+ ("m10", "value", "iif6", "false_input"),+ ("for", "item", "fb8", "value"),+ ("fb8", "value", "ret9", "output"),+ create_loop_linkage("for", "ret9"),+ ("for", "output_collection", "iif6", "true_input"),+ ("cond", "value", "iif6", "condition"),+ ("iif6", "value", "p12", "value"),+ ("p12", "value", "outer", "false_input"),+ ("root", "value", "outer", "true_input"),+ ("outer", "value", "out", "item"),+ ],+ )+++def test_static_if_frame_analysis_is_independent_of_runtime_cache_order() -> None:+ def analyze(*, prime_runtime_selection: bool) -> Any:+ state = GraphExecutionState(graph=_review_b2_root_condition_for_final_nested_if_graph())+ ancestry = _IteratorAncestry(state)+ if prime_runtime_selection:+ state.source_prepared_mapping["iif6"] = {"iif6-exec"}+ state._resolved_if_exec_branches["iif6-exec"] = "true_input"+ graph_if_runtime._get_if_runtime_branch_frame_axes(state, ancestry, "iif6")+ return graph_if_runtime._get_if_static_frame_analysis(state, ancestry, "outer")++ assert analyze(prime_runtime_selection=False) == analyze(prime_runtime_selection=True)++[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("stop_after", [1, 2], ids=["dump-step-1", "dump-step-2"])+def test_root_condition_for_final_nested_if_restores_cold(force_compatibility_scheduler: bool, stop_after: int) -> None:+ graph = _review_b2_root_condition_for_final_nested_if_graph()+ _, expected = _run_graph(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ _, partial = _run_graph(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after=stop_after,+ )+ restored = load_execution_state(dump_execution_state(partial))++ trace, restored = _run_graph(restored, force_compatibility_scheduler=force_compatibility_scheduler)++ assert restored.is_complete(), trace+ assert _source_values(restored, "out") == _source_values(expected, "out") == {(): []}+++def _review_b3_nested_collect_selected_a_graph() -> Graph:+ return _graph_from(+ [+ CollectionConcatInvocation(id="src", first=[[["a"], ["b", "c"]], [[""]]]),+ IterateInvocation(id="it0"),+ CollectionConcatInvocation(id="cc0"),+ IterateInvocation(id="it1"),+ CollectionConcatInvocation(id="cc1"),+ IterateInvocation(id="it2"),+ FixedCollectionTestInvocation(id="cond"),+ AnyTypeTestInvocation(id="a", value="A"),+ AnyTypeTestInvocation(id="b", value="B"),+ IfInvocation(id="if"),+ IfInvocation(id="if2", condition=True),+ MarkedAnyTypeTestInvocation(id="cm", marker="x"),+ CollectInvocation(id="col"),+ MarkedAnyTypeTestInvocation(id="u", marker="U:"),+ CollectInvocation(id="out"),+ ],+ [+ ("src", "collection", "it0", "collection"),+ ("it0", "item", "cc0", "first"),+ ("cc0", "collection", "it1", "collection"),+ ("it1", "item", "cc1", "first"),+ ("cc1", "collection", "it2", "collection"),+ ("it0", "item", "cond", "value"),+ ("cond", "condition", "if", "condition"),+ ("a", "value", "if", "true_input"),+ ("b", "value", "if", "false_input"),+ ("if", "value", "if2", "true_input"),+ ("it2", "item", "cm", "value"),+ ("cm", "value", "col", "item"),+ ("col", "collection", "u", "value"),+ ("u", "value", "if2", "false_input"),+ ("if2", "value", "out", "item"),+ ],+ )-def _zip_collect_branch_with_after2_graph() -> Graph:- graph = _zip_collect_branch_with_root_condition_graph(condition_value=1)- graph.add_node(AnyTypeTestInvocation(id="after2"))- graph.add_edge(create_edge("after", "value", "after2", "value"))- return graph[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("stop_after", [2, 5, 8], ids=["dump-step-2", "dump-step-5", "dump-step-8"])+def test_nested_collect_selected_a_survives_dump_load(force_compatibility_scheduler: bool, stop_after: int) -> None:+ state = GraphExecutionState(graph=_review_b3_nested_collect_selected_a_graph())+ _, partial = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler, stop_after=stop_after)+ restored = load_execution_state(dump_execution_state(partial))+ trace, restored = _run_graph(restored, force_compatibility_scheduler=force_compatibility_scheduler)-def _zip_collect_branch_with_after_collect_graph() -> Graph:- graph = _zip_collect_branch_with_root_condition_graph(condition_value=1)- graph.add_node(CollectInvocation(id="after_collect"))- graph.add_edge(create_edge("after", "value", "after_collect", "item"))- return graph+ assert restored.is_complete(), trace+ assert _source_values(restored, "out") == {(): ["A", "A"]}+++def _review_b4_empty_for_if_chain_graph(chain_length: int, *, empty_collect: bool = False) -> Graph:+ nodes: list[Any] = [IterateInvocation(id="rit"), MarkedAnyTypeTestInvocation(id="rm", marker="r")]+ edges: list[Any] = []+ if empty_collect:+ nodes += [+ CollectionConcatInvocation(id="empty_source", first=[]),+ IterateInvocation(id="empty_iterate"),+ CollectInvocation(id="empty_collect"),+ ]+ edges += [+ ("empty_source", "collection", "empty_iterate", "collection"),+ ("empty_iterate", "item", "empty_collect", "item"),+ ("empty_collect", "collection", "rit", "collection"),+ ]+ else:+ nodes += [+ ForInvocation(id="for", collection=[]),+ MarkedAnyTypeTestInvocation(id="fb", marker="f"),+ ForReturnInvocation(id="ret"),+ ]+ edges += [+ ("for", "output_collection", "rit", "collection"),+ ("for", "item", "fb", "value"),+ ("fb", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ]+ edges.append(("rit", "item", "rm", "value"))+ nodes.append(CollectInvocation(id="out"))+ previous = "rm"+ for index in range(chain_length):+ if_node = f"rif{index}"+ fallback = f"rr{index}"+ nodes += [+ IfInvocation(id=if_node),+ BooleanInvocation(id=f"cond{index}", value=True),+ AnyTypeTestInvocation(id=fallback, value=f"RR{index}"),+ ]+ edges += [+ (f"cond{index}", "value", if_node, "condition"),+ (previous, "value", if_node, "true_input"),+ (fallback, "value", if_node, "false_input"),+ ]+ previous = if_node+ edges.append((previous, "value", "out", "item"))+ return _graph_from(nodes, edges)@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_zip_collect_then_after_completes_without_if(force_compatibility_scheduler: bool) -> None:- state = GraphExecutionState(graph=_zip_collect_then_after_graph())- state._execution_scheduler = (- _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)- )[email protected]("chain_length", [1, 2, 4], ids=["one-if", "two-if", "four-if"])[email protected]("empty_collect", [False, True], ids=["empty-for", "empty-collect-iterate"])+def test_empty_iterator_root_if_chain_completes_empty(+ force_compatibility_scheduler: bool, chain_length: int, empty_collect: bool+) -> None:+ state = GraphExecutionState(graph=_review_b4_empty_for_if_chain_graph(chain_length, empty_collect=empty_collect))trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- assert state.is_complete(), f"graph stalled after {trace}"- assert not state.has_error()- after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)- assert [state._get_iteration_path(node_id) for node_id in after_ids] == [(0,), (1,)]- assert [state.results[node_id].value for node_id in after_ids] == [[11, 21], [12, 22]]- assert trace.count("body") == 4- assert trace.count("branch_collect") == 2+ assert state.is_complete(), trace+ assert _source_values(state, "out") == {(): []}+++def _empty_collected_iterate_into_if_graph(+ *, wired_condition: bool, shared_upstream: bool = False, upstream_chain_length: int = 1+) -> Graph:+ assert upstream_chain_length > 0+ nodes: list[Any] = [+ CollectionConcatInvocation(id="empty_source", first=[]),+ IterateInvocation(id="iterate"),+ MarkedAnyTypeTestInvocation(id="body", marker="body:"),+ CollectInvocation(id="collected"),+ IterateInvocation(id="re_iterate"),+ MarkedAnyTypeTestInvocation(id="re_body", marker="re:"),+ AnyTypeTestInvocation(id="rr"),+ IfInvocation(id="if") if wired_condition else IfInvocation(id="if", condition=False),+ CollectInvocation(id="out"),+ ]+ edges: list[Any] = [+ ("empty_source", "collection", "iterate", "collection"),+ ("iterate", "item", "body", "value"),+ ("body", "value", "collected", "item"),+ ("collected", "collection", "re_iterate", "collection"),+ ("re_iterate", "item", "re_body", "value"),+ ("re_body", "value", "if", "true_input"),+ ("rr", "value", "if", "false_input"),+ ("if", "value", "out", "item"),+ ]+ upstream_ids = ["upstream", *(f"upstream_{index}" for index in range(1, upstream_chain_length))]+ nodes.extend(+ AnyTypeTestInvocation(id=node_id, **({"value": "RR"} if index == 0 else {}))+ for index, node_id in enumerate(upstream_ids)+ )+ edges.extend(+ [+ (upstream_ids[index - 1], "value", node_id, "value")+ for index, node_id in enumerate(upstream_ids)+ if index > 0+ ]+ )+ edges.append((upstream_ids[-1], "value", "rr", "value"))+ if shared_upstream:+ nodes.append(AnyTypeTestInvocation(id="upstream_sink"))+ edges.append(("upstream", "value", "upstream_sink", "value"))+ if wired_condition:+ nodes.append(BooleanInvocation(id="condition", value=False))+ edges.append(("condition", "value", "if", "condition"))+ return _graph_from(nodes, edges)@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_zip_collect_then_after_with_empty_right_completes_without_if([email protected]("wired_condition", [False, True], ids=["literal-false", "wired-false"])[email protected]("upstream_chain_length", [1, 3], ids=["one-ancestor", "three-ancestors"])+ "checkpoint", [None, "collected", "condition"], ids=["fresh", "after-collect", "after-condition"]+)+def test_empty_collected_iterate_into_rejected_if_branch_completes(force_compatibility_scheduler: bool,+ wired_condition: bool,+ upstream_chain_length: int,+ checkpoint: str | None,) -> None:- graph = _zip_collect_then_after_graph()- graph.update_node("right_source", CollectionConcatInvocation(id="right_source", first=[]))- state = GraphExecutionState(graph=graph)- state._execution_scheduler = (- _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ state = GraphExecutionState(+ graph=_empty_collected_iterate_into_if_graph(+ wired_condition=wired_condition, upstream_chain_length=upstream_chain_length+ ))+ if checkpoint is not None:+ _, state = _run_until_source(+ state,+ checkpoint,+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ state = load_execution_state(dump_execution_state(state))trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- assert state.is_complete(), f"graph stalled after {trace}"- assert not state.has_error()- after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)- assert [state._get_iteration_path(node_id) for node_id in after_ids] == [(0,), (1,)]- assert [state.results[node_id].value for node_id in after_ids] == [[], []]- assert trace.count("body") == 0- assert trace.count("branch_collect") == 2+ assert state.is_complete(), trace+ assert not state.has_error(), state.errors+ assert _source_values(state, "out") == {(): []}+ assert "re_body" not in trace+ assert not any(source_id.startswith("upstream") for source_id in trace)+ assert "rr" not in trace@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])- ("condition_value", "expected"), [(1, [[11, 21], [12, 22]]), (0, "fallback")], ids=["true", "false"]-)-def test_zip_collect_branch_with_root_condition_completes(- force_compatibility_scheduler: bool, condition_value: int, expected: Any[email protected]("wired_condition", [False, True], ids=["literal-false", "wired-false"])+def test_empty_collect_rejects_branch_local_upstream_but_keeps_shared_source(+ force_compatibility_scheduler: bool,+ wired_condition: bool,) -> None:- state = GraphExecutionState(graph=_zip_collect_branch_with_root_condition_graph(condition_value))- state._execution_scheduler = (- _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ state = GraphExecutionState(+ graph=_empty_collected_iterate_into_if_graph(wired_condition=wired_condition, shared_upstream=True))trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- assert state.is_complete(), f"graph stalled after {trace}"- assert not state.has_error()- after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)- if_ids = set(state.source_prepared_mapping["if"])- activation_tokens = sorted(- (- token- for token in state.execution_tokens.values()- if token.token_kind == "activation" and token.owner_node_id in if_ids- ),- key=lambda token: token.frame.iteration_path,+ assert state.is_complete(), trace+ assert not state.has_error(), state.errors+ assert _source_values(state, "out") == {(): []}+ assert "upstream" in trace+ assert "upstream_sink" in trace+ assert "re_body" not in trace+ assert "rr" not in trace+++def test_empty_collect_iterate_owner_cache_rebuilds_after_graph_edit() -> None:+ state = GraphExecutionState(graph=_empty_collected_iterate_into_if_graph(wired_condition=False))++ dependencies = graph_if_runtime._get_static_selected_collect_iterate_dependencies(state, "upstream", ())+ assert {(dependency.owner_id, dependency.branch) for dependency in dependencies} == {("if", "false_input")}+ original_runtime = state._runtime()++ state.add_node(AnyTypeTestInvocation(id="upstream_sink"))+ state.add_edge(create_edge("upstream", "value", "upstream_sink", "value"))++ assert state._runtime() is not original_runtime+ assert graph_if_runtime._get_static_selected_collect_iterate_dependencies(state, "upstream", ()) == ()+++def test_empty_collect_iterate_ancestor_keeps_all_selected_if_dependencies() -> None:+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="empty_source", first=[]),+ IterateInvocation(id="iterate"),+ MarkedAnyTypeTestInvocation(id="body", marker="body:"),+ CollectInvocation(id="collected"),+ IterateInvocation(id="inner_re_iterate"),+ MarkedAnyTypeTestInvocation(id="inner_re_body", marker="inner:"),+ AnyTypeTestInvocation(id="upstream", value="RR"),+ AnyTypeTestInvocation(id="rr"),+ IfInvocation(id="inner_if", condition=False),+ IterateInvocation(id="outer_re_iterate"),+ MarkedAnyTypeTestInvocation(id="outer_re_body", marker="outer:"),+ IfInvocation(id="outer_if", condition=False),+ CollectInvocation(id="out"),+ ],+ [+ ("empty_source", "collection", "iterate", "collection"),+ ("iterate", "item", "body", "value"),+ ("body", "value", "collected", "item"),+ ("collected", "collection", "inner_re_iterate", "collection"),+ ("inner_re_iterate", "item", "inner_re_body", "value"),+ ("inner_re_body", "value", "inner_if", "true_input"),+ ("upstream", "value", "rr", "value"),+ ("rr", "value", "inner_if", "false_input"),+ ("inner_if", "value", "outer_if", "false_input"),+ ("collected", "collection", "outer_re_iterate", "collection"),+ ("outer_re_iterate", "item", "outer_re_body", "value"),+ ("outer_re_body", "value", "outer_if", "true_input"),+ ("outer_if", "value", "out", "item"),+ ],)- if condition_value:- assert [state._get_iteration_path(node_id) for node_id in after_ids] == [(0,), (1,)]- assert [state.results[node_id].value for node_id in after_ids] == expected- assert trace.count("body") == 4- assert trace.count("branch_collect") == 2- assert trace.count("if") == 2- assert [(token.port, token.frame.iteration_path) for token in activation_tokens] == [- ("true_input", (0,)),- ("true_input", (1,)),- ]- restored = load_execution_state(dump_execution_state(state))- assert restored.is_complete()- assert not restored.has_error()- restored_after_ids = sorted(restored.source_prepared_mapping["after"], key=restored._get_iteration_path)- assert [restored.results[node_id].value for node_id in restored_after_ids] == expected- else:- assert [state._get_iteration_path(node_id) for node_id in after_ids] == [()]- assert [state.results[node_id].value for node_id in after_ids] == [expected]- assert trace.count("body") == 0- assert trace.count("branch_collect") == 0- assert trace.count("if") == 1- assert [(token.port, token.frame.iteration_path) for token in activation_tokens] == [("false_input", ())]+ state = GraphExecutionState(graph=graph)++ dependencies = graph_if_runtime._get_static_selected_collect_iterate_dependencies(state, "upstream", ())++ assert {(dependency.owner_id, dependency.branch) for dependency in dependencies} == {+ ("inner_if", "false_input"),+ ("outer_if", "false_input"),+ }@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_zip_collect_root_condition_preserves_frames_through_ordinary_descendants(- force_compatibility_scheduler: bool,[email protected]("chain_length", [0, 1, 2, 3])+def test_for_final_through_literal_if_chain_groups_by_parent_frame(+ force_compatibility_scheduler: bool, chain_length: int) -> None:- state = GraphExecutionState(graph=_zip_collect_branch_with_after2_graph())- state._execution_scheduler = (- _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)- )+ nodes: list[Any] = [+ CollectionConcatInvocation(id="src", first=[["a"], ["b"]]),+ IterateInvocation(id="it"),+ ForInvocation(id="for"),+ ForReturnInvocation(id="ret"),+ CollectInvocation(id="out"),+ ]+ edges: list[Any] = [+ ("src", "collection", "it", "collection"),+ ("it", "item", "for", "collection"),+ ("for", "item", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ]+ previous = "for"+ previous_field = "output_collection"+ for index in range(chain_length):+ if_node = f"if{index}"+ nodes += [+ IfInvocation(id=if_node, condition=True),+ AnyTypeTestInvocation(id=f"fallback{index}", value="fallback"),+ ]+ edges += [+ (previous, previous_field, if_node, "true_input"),+ (f"fallback{index}", "value", if_node, "false_input"),+ ]+ previous, previous_field = if_node, "value"+ edges.append((previous, previous_field, "out", "item"))+ graph = _graph_from(nodes, edges)- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )- assert state.is_complete(), f"graph stalled after {trace}"- assert not state.has_error()- after2_ids = sorted(state.source_prepared_mapping["after2"], key=state._get_iteration_path)- assert [state._get_iteration_path(node_id) for node_id in after2_ids] == [(0,), (1,)]- assert [state.results[node_id].value for node_id in after2_ids] == [[11, 21], [12, 22]]- assert trace.count("after2") == 2+ assert state.is_complete(), trace+ assert _source_values(state, "out") == {(0,): [["a"]], (1,): [["b"]]}@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_zip_collect_root_condition_preserves_groups_in_downstream_collect(+def test_long_literal_true_if_chain_feeding_collect_completes(force_compatibility_scheduler: bool,) -> None:- state = GraphExecutionState(graph=_zip_collect_branch_with_after_collect_graph())- state._execution_scheduler = (- _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)- )+ chain_length = 1000+ nodes: list[Any] = [+ CollectionConcatInvocation(id="source", first=["preserved"]),+ IterateInvocation(id="iterate"),+ AnyTypeTestInvocation(id="m"),+ CollectInvocation(id="out"),+ ]+ edges: list[Any] = [("source", "collection", "iterate", "collection"), ("iterate", "item", "m", "value")]+ previous = "m"+ for index in range(chain_length):+ if_node = f"if{index}"+ nodes.append(IfInvocation(id=if_node, condition=True))+ edges.extend(+ [+ (previous, "value", if_node, "true_input"),+ ("m", "value", if_node, "false_input"),+ ]+ )+ previous = if_node+ edges.append((previous, "value", "out", "item"))- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ trace, state = _run_graph(+ GraphExecutionState(graph=_graph_from(nodes, edges)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )- assert state.is_complete(), f"graph stalled after {trace}"- assert not state.has_error()- collect_ids = sorted(state.source_prepared_mapping["after_collect"], key=state._get_iteration_path)- assert len(collect_ids) == 1- assert state._get_iteration_path(collect_ids[0]) == ()- assert state.results[collect_ids[0]].collection == [[11, 21], [12, 22]]- assert trace.count("after_collect") == 1+ assert state.is_complete(), trace+ assert not state.has_error(), state.errors+ assert _source_values(state, "out") == {(): ["preserved"]}@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_zip_collect_root_condition_expansion_rolls_back_after_if_initialization_failure(- monkeypatch: pytest.MonkeyPatch, force_compatibility_scheduler: bool+def test_if_with_dynamic_boolean_invocation_condition_groups_for_final_by_parent_frame(+ force_compatibility_scheduler: bool,) -> None:- state = GraphExecutionState(graph=_zip_collect_branch_with_root_condition_graph(condition_value=1))- state._execution_scheduler = (- _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="src", first=[["a"], []]),+ IterateInvocation(id="it"),+ FixedCollectionTestInvocation(id="condition_source"),+ BooleanInvocation(id="condition", value=True),+ ForInvocation(id="for"),+ ForReturnInvocation(id="ret"),+ AnyTypeTestInvocation(id="fallback", value="fallback"),+ IfInvocation(id="if"),+ CollectInvocation(id="out"),+ ],+ [+ ("src", "collection", "it", "collection"),+ ("it", "item", "condition_source", "value"),+ ("condition_source", "condition", "condition", "value"),+ ("condition", "value", "if", "condition"),+ ("it", "item", "for", "collection"),+ ("for", "item", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "out", "item"),+ ],)- while (- len(- [exec_id for exec_id in state.source_prepared_mapping.get("branch_collect", ()) if exec_id in state.results]- )- < 2- ):- node = state.next()- assert node is not None- state.complete(node.id, node.invoke(Mock()))+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )- root_if_ids = [- exec_id for exec_id in state.source_prepared_mapping["if"] if state._get_iteration_path(exec_id) == ()- ]- assert len(root_if_ids) == 1- root_if_id = root_if_ids[0]- assert root_if_id not in state.executed+ assert state.is_complete(), trace+ assert _source_values(state, "out") == {(0,): [["a"]], (1,): ["fallback"]}- before_nodes = set(state.execution_graph.nodes)- before_edges = tuple(state.execution_graph.edges)- before_prepared_sources = dict(state.prepared_source_mapping)- before_source_prepared = {source_id: set(exec_ids) for source_id, exec_ids in state.source_prepared_mapping.items()}- before_paths = dict(state.prepared_iteration_paths)- before_indegree = dict(state.indegree)- before_tokens = state.execution_tokens.copy()- before_gates = copy.deepcopy(state._generic_runtime().gates)- materializer = state._materializer()- initialize_execution_node = materializer._initialize_execution_node- def fail_after_if_initialization(exec_node_id: str, input_edges: Any = None) -> None:- initialize_execution_node(exec_node_id, input_edges)- if state.prepared_source_mapping.get(exec_node_id) == "if" and state._get_iteration_path(exec_node_id) == (1,):- raise RuntimeError("injected If-copy initialization failure")[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_literal_if_after_wired_if_preserves_parent_for_final_frames(+ force_compatibility_scheduler: bool,+) -> None:+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="src", first=[[], ["b"]]),+ IterateInvocation(id="it"),+ FixedCollectionTestInvocation(id="condition_source"),+ BooleanInvocation(id="condition", value=True),+ ForInvocation(id="for"),+ AnyTypeTestInvocation(id="body"),+ ForReturnInvocation(id="ret"),+ AnyTypeTestInvocation(id="inner_fallback", value="inner"),+ IfInvocation(id="inner"),+ AnyTypeTestInvocation(id="outer_fallback", value="outer"),+ IfInvocation(id="outer", condition=True),+ CollectInvocation(id="out"),+ ],+ [+ ("src", "collection", "it", "collection"),+ ("it", "item", "condition_source", "value"),+ ("condition_source", "condition", "condition", "value"),+ ("condition", "value", "inner", "condition"),+ ("it", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "inner", "true_input"),+ ("inner_fallback", "value", "inner", "false_input"),+ ("inner", "value", "outer", "true_input"),+ ("outer_fallback", "value", "outer", "false_input"),+ ("outer", "value", "out", "item"),+ ],+ )- monkeypatch.setattr(materializer, "_initialize_execution_node", fail_after_if_initialization)- with pytest.raises(RuntimeError, match="injected If-copy initialization failure"):- while (node := state.next()) is not None:- state.complete(node.id, node.invoke(Mock()))+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )- assert set(state.execution_graph.nodes) == before_nodes- assert tuple(state.execution_graph.edges) == before_edges- assert state.prepared_source_mapping == before_prepared_sources- assert state.source_prepared_mapping == before_source_prepared- assert state.prepared_iteration_paths == before_paths- assert state.indegree == before_indegree- assert state.execution_tokens == before_tokens- assert state._generic_runtime().gates == before_gates- assert state._get_iteration_path(root_if_id) == ()+ assert state.is_complete(), trace+ assert _source_values(state, "out") == {(0,): ["inner"], (1,): [["b"]]}- monkeypatch.undo()- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- assert state.is_complete(), f"graph stalled after retry: {trace}"- assert not state.has_error()- after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)- assert [state.results[node_id].value for node_id in after_ids] == [[11, 21], [12, 22]]++def _root_for_final_through_iterate_if_graph(*, wrapper_count: int, wired_condition: bool) -> Graph:+ nodes: list[Any] = [+ ForInvocation(id="for", collection=["a", "b"]),+ MarkedAnyTypeTestInvocation(id="for_body", marker="f"),+ ForReturnInvocation(id="for_return"),+ IterateInvocation(id="rit"),+ MarkedAnyTypeTestInvocation(id="rm", marker="r"),+ AnyTypeTestInvocation(id="fallback", value="R"),+ CollectInvocation(id="out"),+ ]+ edges: list[Any] = [+ ("for", "item", "for_body", "value"),+ ("for_body", "value", "for_return", "output"),+ create_loop_linkage("for", "for_return"),+ ("for", "output_collection", "rit", "collection"),+ ("rit", "item", "rm", "value"),+ ]+ previous_id = "rm"+ previous_field = "value"+ for index in range(wrapper_count):+ if_id = f"if_{index}"+ nodes.append(IfInvocation(id=if_id) if wired_condition else IfInvocation(id=if_id, condition=True))+ edges.extend(+ [+ (previous_id, previous_field, if_id, "true_input"),+ ("fallback", "value", if_id, "false_input"),+ ]+ )+ if wired_condition:+ condition_id = f"condition_{index}"+ nodes.append(BooleanInvocation(id=condition_id, value=True))+ edges.append((condition_id, "value", if_id, "condition"))+ previous_id, previous_field = if_id, "value"+ edges.append((previous_id, previous_field, "out", "item"))+ return _graph_from(nodes, edges)@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_zip_collect_root_condition_deferred_consumer_failure_rolls_back_and_retries(- monkeypatch: pytest.MonkeyPatch, force_compatibility_scheduler: bool[email protected]("checkpoint", [None, "rit"], ids=["fresh", "after-iterate"])+ ("wrapper_count", "wired_condition"),+ [(0, False), (1, False), (1, True), (2, False), (2, True)],+ ids=["no-wrapper", "one-literal", "one-wired", "two-literal", "two-wired"],+)+def test_root_for_final_through_iterate_if_wrappers_stays_in_root_group(+ force_compatibility_scheduler: bool,+ checkpoint: str | None,+ wrapper_count: int,+ wired_condition: bool,) -> None:- state = GraphExecutionState(graph=_zip_collect_branch_with_root_condition_graph(condition_value=1))- state._execution_scheduler = (- _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ graph = _root_for_final_through_iterate_if_graph(+ wrapper_count=wrapper_count,+ wired_condition=wired_condition,)-- while (- len(- [exec_id for exec_id in state.source_prepared_mapping.get("branch_collect", ()) if exec_id in state.results]+ state = GraphExecutionState(graph=graph)+ if not force_compatibility_scheduler:+ state._execution_scheduler = _GenericGraphSchedulerAdapter(state)+ if checkpoint is not None:+ _, state = _run_until_source(+ state,+ checkpoint,+ force_compatibility_scheduler=force_compatibility_scheduler,)- < 2- ):- node = state.next()- assert node is not None- state.complete(node.id, node.invoke(Mock()))-- root_if_exec_ids = [- exec_id for exec_id in state.source_prepared_mapping["if"] if state._get_iteration_path(exec_id) == ()- ]- assert len(root_if_exec_ids) == 1- state._materializer().create_execution_node("after", [("if", root_if_exec_ids[0])], iteration_path=())- assert len(state.source_prepared_mapping["after"]) == 1+ state = load_execution_state(dump_execution_state(state))+ if not force_compatibility_scheduler:+ state._execution_scheduler = _GenericGraphSchedulerAdapter(state)- materializer_type = graph_module._ExecutionMaterializer- initialize_execution_node = materializer_type._initialize_execution_node- run_materialization_transaction = state._run_materialization_transaction- failed_transaction_snapshot: dict[str, Any] | None = None+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- def snapshot_state() -> dict[str, Any]:- return {- "nodes": {- node_id: copy.deepcopy(state.execution_graph.get_node(node_id))- for node_id in state.execution_graph.nodes- },- "edges": copy.deepcopy(tuple(state.execution_graph.edges)),- "prepared_source_mapping": copy.deepcopy(state.prepared_source_mapping),- "source_prepared_mapping": copy.deepcopy(state.source_prepared_mapping),- "prepared_iteration_paths": copy.deepcopy(state.prepared_iteration_paths),- "indegree": copy.deepcopy(state.indegree),- "execution_tokens": copy.deepcopy(state.execution_tokens),- "gates": copy.deepcopy(state._generic_runtime().gates),- }+ assert state.is_complete(), trace+ assert not state.has_error(), state.errors+ if force_compatibility_scheduler:+ assert isinstance(state._execution_scheduler, _ExecutionScheduler)+ else:+ assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert _source_values(state, "out") == {(): ["rfa", "rfb"]}- def capture_failed_transaction(operation: Any) -> Any:- nonlocal failed_transaction_snapshot- transaction_snapshot = snapshot_state() if state._apply_transaction is None else None- try:- return run_materialization_transaction(operation)- except RuntimeError as error:- if transaction_snapshot is not None and str(error) == "injected deferred consumer initialization failure":- failed_transaction_snapshot = transaction_snapshot- raise- def fail_after_second_frame(materializer: Any, exec_node_id: str, input_edges: Any = None) -> None:- initialize_execution_node(materializer, exec_node_id, input_edges)- if (- materializer._state is state- and state.prepared_source_mapping.get(exec_node_id) == "after"- and state._get_iteration_path(exec_node_id) == (1,)- ):- raise RuntimeError("injected deferred consumer initialization failure")+def _for_final_if_with_iteration_condition_graph(+ *,+ pass_condition: bool,+ collection: list[list[str]] | None = None,+ reverse_nodes: bool = False,+ reverse_edges: bool = False,+) -> Graph:+ nodes: list[Any] = [+ CollectionConcatInvocation(id="src", first=[["a"], ["b", "c"]] if collection is None else collection),+ IterateInvocation(id="it"),+ ForInvocation(id="for"),+ MarkedAnyTypeTestInvocation(id="body", marker="F"),+ ForReturnInvocation(id="ret"),+ FixedCollectionTestInvocation(id="fc"),+ IfInvocation(id="if"),+ AnyTypeTestInvocation(id="fallback", value="R"),+ CollectInvocation(id="out"),+ ]+ edges: list[Any] = [+ ("src", "collection", "it", "collection"),+ ("it", "item", "for", "collection"),+ ("for", "item", "body", "value"),+ ("body", "value", "ret", "output"),+ create_loop_linkage("for", "ret"),+ ("for", "output_collection", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("it", "item", "fc", "value"),+ ("if", "value", "out", "item"),+ ]+ if pass_condition:+ nodes.append(BooleanInvocation(id="condition"))+ edges += [+ ("fc", "condition", "condition", "value"),+ ("condition", "value", "if", "condition"),+ ]+ else:+ edges.append(("fc", "condition", "if", "condition"))+ if reverse_nodes:+ nodes.reverse()+ if reverse_edges:+ edges = [edges[0], *reversed(edges[1:])]+ return _graph_from(nodes, edges)- monkeypatch.setattr(materializer_type, "_initialize_execution_node", fail_after_second_frame)- monkeypatch.setattr(state, "_run_materialization_transaction", capture_failed_transaction)- with pytest.raises(RuntimeError, match="injected deferred consumer initialization failure"):- while (node := state.next()) is not None:- state.complete(node.id, node.invoke(Mock()))- assert failed_transaction_snapshot is not None, "injected failure did not occur in a materialization transaction"- assert snapshot_state() == failed_transaction_snapshot[email protected]("pass_condition", [False, True], ids=["direct-condition", "boolean-pass-through"])+ ("checkpoint", "reverse_edges", "reverse_nodes"),+ [(None, False, False), (None, True, True), (3, False, True), (5, True, False)],+ ids=["fresh-forward", "fresh-reverse", "after-step-3", "after-step-5-reverse-edges"],+)[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_for_final_if_iteration_condition_keeps_parent_groups(+ pass_condition: bool,+ checkpoint: int | None,+ reverse_edges: bool,+ reverse_nodes: bool,+ force_compatibility_scheduler: bool,+) -> None:+ graph = _for_final_if_with_iteration_condition_graph(+ pass_condition=pass_condition,+ reverse_nodes=reverse_nodes,+ reverse_edges=reverse_edges,+ )+ state = GraphExecutionState(graph=graph)+ if not force_compatibility_scheduler:+ state._execution_scheduler = _GenericGraphSchedulerAdapter(state)+ if checkpoint is not None:+ _, state = _run_graph(+ state,+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after=checkpoint,+ )+ state = load_execution_state(dump_execution_state(state))+ if not force_compatibility_scheduler:+ state._execution_scheduler = _GenericGraphSchedulerAdapter(state)- monkeypatch.undo()trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- assert state.is_complete(), f"graph stalled after retry: {trace}"- assert not state.has_error()- after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)- assert [state.results[node_id].value for node_id in after_ids] == [[11, 21], [12, 22]]++ assert state.is_complete(), trace+ assert not state.has_error(), state.errors+ if force_compatibility_scheduler:+ assert isinstance(state._execution_scheduler, _ExecutionScheduler)+ else:+ assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert _source_values(state, "out") == {(0,): [["Fa"]], (1,): [["Fb", "Fc"]]}[email protected]("pass_condition", [False, True], ids=["direct-condition", "boolean-pass-through"])@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_zip_collect_branch_with_empty_selected_collect_completes(force_compatibility_scheduler: bool) -> None:- graph = _zip_collect_branch_with_root_condition_graph(condition_value=1)- graph.update_node("left_source", CollectionConcatInvocation(id="left_source", first=[]))- state = GraphExecutionState(graph=graph)- state._execution_scheduler = (- _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+def test_for_final_if_iteration_condition_keeps_mixed_fallback_and_for_groups(+ pass_condition: bool,+ force_compatibility_scheduler: bool,+) -> None:+ graph = _for_final_if_with_iteration_condition_graph(+ pass_condition=pass_condition,+ collection=[[], ["b", "c"]],)+ state = GraphExecutionState(graph=graph)+ if not force_compatibility_scheduler:+ state._execution_scheduler = _GenericGraphSchedulerAdapter(state)trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- assert state.is_complete(), f"graph stalled after {trace}"- assert not state.has_error()- after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)- collect_ids = sorted(state.source_prepared_mapping["branch_collect"], key=state._get_iteration_path)- assert len(after_ids) == 1- assert state._get_iteration_path(after_ids[0]) == ()- assert state.results[after_ids[0]].value == []- assert len(collect_ids) == 1- assert state.results[collect_ids[0]].collection == []- assert trace.count("right") == 2- assert trace.count("body") == 0- assert trace.count("branch_collect") == 1- assert trace.count("if") == 1- activation_tokens = [token for token in state.execution_tokens.values() if token.token_kind == "activation"]- assert [(token.port, token.frame.iteration_path) for token in activation_tokens] == [("true_input", ())]+ assert state.is_complete(), trace+ assert not state.has_error(), state.errors+ if force_compatibility_scheduler:+ assert isinstance(state._execution_scheduler, _ExecutionScheduler)+ else:+ assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert _source_values(state, "out") == {(0,): ["R"], (1,): [["Fb", "Fc"]]}+++def _unselected_for_collect_with_sibling_graph(*, pass_condition: bool, reverse_nodes: bool = False) -> Graph:+ nodes: list[Any] = [+ CollectionConcatInvocation(id="source", first=[["b"], ["a"]]),+ IterateInvocation(id="it"),+ MarkedAnyTypeTestInvocation(id="selected", marker="T:"),+ ForInvocation(id="for"),+ MarkedAnyTypeTestInvocation(id="for_body", marker="F:"),+ ForReturnInvocation(id="for_return"),+ FixedCollectionTestInvocation(id="condition"),+ IfInvocation(id="if"),+ AnyTypeTestInvocation(id="root", value="S"),+ CollectionConcatInvocation(id="sibling_source", first=["s0", "s1", "s2"]),+ IterateInvocation(id="sibling"),+ CollectInvocation(id="out"),+ AnyTypeTestInvocation(id="downstream"),+ ]+ edges: list[Any] = [+ ("source", "collection", "it", "collection"),+ ("it", "item", "selected", "value"),+ ("selected", "value", "if", "true_input"),+ ("it", "item", "for", "collection"),+ ("for", "item", "for_body", "value"),+ ("for_body", "value", "for_return", "output"),+ create_loop_linkage("for", "for_return"),+ ("for", "output_collection", "if", "false_input"),+ ("it", "item", "condition", "value"),+ ("if", "value", "out", "item"),+ ("root", "value", "out", "item"),+ ("sibling_source", "collection", "sibling", "collection"),+ ("sibling", "item", "out", "item"),+ ("out", "collection", "downstream", "value"),+ ]+ if pass_condition:+ nodes.append(BooleanInvocation(id="condition_passthrough"))+ edges += [+ ("condition", "condition", "condition_passthrough", "value"),+ ("condition_passthrough", "value", "if", "condition"),+ ]+ else:+ edges.append(("condition", "condition", "if", "condition"))+ if reverse_nodes:+ nodes.reverse()+ return _graph_from(nodes, edges)@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_zip_collect_branch_with_empty_right_preserves_left_frames(force_compatibility_scheduler: bool) -> None:- graph = _zip_collect_branch_with_root_condition_graph(condition_value=1)- graph.update_node("right_source", CollectionConcatInvocation(id="right_source", first=[]))- state = GraphExecutionState(graph=graph)- state._execution_scheduler = (- _ExecutionScheduler(state) if force_compatibility_scheduler else _GenericGraphSchedulerAdapter(state)+ ("pass_condition", "reverse_nodes"),+ [(False, False), (True, False), (False, True)],+ ids=["direct-condition", "boolean-pass-through", "reverse-node-insertion"],+)+def test_unselected_for_does_not_split_root_collect_or_copy_sibling_items(+ force_compatibility_scheduler: bool,+ pass_condition: bool,+ reverse_nodes: bool,+) -> None:+ state = GraphExecutionState(+ graph=_unselected_for_collect_with_sibling_graph(+ pass_condition=pass_condition,+ reverse_nodes=reverse_nodes,+ ))-trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)assert state.is_complete(), f"graph stalled after {trace}"- assert not state.has_error()- after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)- assert [state._get_iteration_path(node_id) for node_id in after_ids] == [(0,), (1,)]- assert [state.results[node_id].value for node_id in after_ids] == [[], []]- assert trace.count("body") == 0- assert trace.count("branch_collect") == 2- assert trace.count("if") == 2- tokens = sorted(- (token for token in state.execution_tokens.values() if token.token_kind == "activation"),- key=lambda token: token.frame.iteration_path,- )- assert [(token.port, token.frame.iteration_path) for token in tokens] == [- ("true_input", (0,)),- ("true_input", (1,)),- ]+ assert not state.has_error(), state.errors+ outputs = _source_values(state, "out")+ assert set(outputs) == {()}+ assert sorted(outputs[()]) == sorted(["S", "T:['b']", "T:['a']", "s0", "s1", "s2"])+ assert [value for value in outputs[()] if value.startswith("T:")] == ["T:['b']", "T:['a']"]+ assert [value for value in outputs[()] if value in {"s0", "s1", "s2"}] == ["s0", "s1", "s2"]+ assert trace.count("downstream") == 1+ assert {"for", "for_body", "for_return"} <= set(trace)@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_zip_collect_branch_activation_frames_resume_after_round_trip(force_compatibility_scheduler: bool) -> None:- state = GraphExecutionState(graph=_zip_collect_branch_with_root_condition_graph(condition_value=1))- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)-+def test_unselected_for_collect_grouping_survives_dump_load(+ force_compatibility_scheduler: bool,+) -> None:+ state = GraphExecutionState(graph=_unselected_for_collect_with_sibling_graph(pass_condition=False))partial_trace, state = _run_graph(state,force_compatibility_scheduler=force_compatibility_scheduler,- stop_after=14,+ stop_after=16,)- assert partial_trace[-1] == "if"- assert partial_trace.count("if") == 1- assert not state.is_complete()- assert not state.has_error()- partial_if_ids = sorted(state.source_prepared_mapping["if"], key=state._get_iteration_path)- assert [state._get_iteration_path(node_id) for node_id in partial_if_ids] == [(0,), (1,)]- assert sum(node_id in state.results for node_id in partial_if_ids) == 1- assert sum(node_id not in state.results for node_id in partial_if_ids) == 1+ assert partial_trace.count("if") == 2+ assert "out" not in partial_trace- state = load_execution_state(dump_execution_state(state))- if force_compatibility_scheduler:- _restore_compatibility_scheduler(state)- remaining_trace, state = _run_graph(state)+ restored = load_execution_state(dump_execution_state(state))+ trace, restored = _run_graph(restored, force_compatibility_scheduler=force_compatibility_scheduler)- assert state.is_complete(), f"resume stalled after {remaining_trace}"- assert not state.has_error()- assert not state._pending_if_exec_nodes- assert not state._has_pending_lifecycle_execution()- after_ids = sorted(state.source_prepared_mapping["after"], key=state._get_iteration_path)- assert [state.results[node_id].value for node_id in after_ids] == [[11, 21], [12, 22]]+ assert restored.is_complete(), trace+ assert not restored.has_error(), restored.errors+ outputs = _source_values(restored, "out")+ assert set(outputs) == {()}+ assert sorted(outputs[()]) == sorted(["S", "T:['b']", "T:['a']", "s0", "s1", "s2"])+ assert [value for value in outputs[()] if value.startswith("T:")] == ["T:['b']", "T:['a']"]+ assert [value for value in outputs[()] if value in {"s0", "s1", "s2"}] == ["s0", "s1", "s2"]+ assert trace.count("downstream") == 1[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])- ("left", "right", "expected"),- [- ([5, 6, 7, 8], [10], [[15, 16, 17, 18]]),- ([1, 2, 3], [10, 20], [[11, 12, 13], [21, 22, 23]]),- ],- ids=["one-right-item", "two-right-items"],-)-def test_sibling_collect_branch_keeps_every_item_when_condition_comes_from_the_other_axis(- force_compatibility_scheduler: bool, left: list[int], right: list[int], expected: list[list[int]]+def _seed52_if_collect_graph() -> Graph:+ return _graph_from(+ [+ CollectionConcatInvocation(id="empty", first=[]),+ IterateInvocation(id="it0"),+ MarkedAnyTypeTestInvocation(id="m", marker="bF:"),+ AnyTypeTestInvocation(id="c", value="c"),+ CollectInvocation(id="col"),+ MarkedAnyTypeTestInvocation(id="p", marker="aF:"),+ IfInvocation(id="iif", condition=False),+ AnyTypeTestInvocation(id="T", value="T"),+ IfInvocation(id="outer", condition=True),+ CollectInvocation(id="out"),+ ],+ [+ ("empty", "collection", "it0", "collection"),+ ("it0", "item", "m", "value"),+ ("m", "value", "iif", "false_input"),+ ("c", "value", "col", "item"),+ ("col", "collection", "p", "value"),+ ("p", "value", "iif", "true_input"),+ ("iif", "value", "outer", "false_input"),+ ("T", "value", "outer", "true_input"),+ ("outer", "value", "out", "item"),+ ],+ )++[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("checkpoint", [None, 2], ids=["fresh", "after-empty-source"])+def test_empty_unselected_inner_if_retires_while_outer_selects_root_value(+ force_compatibility_scheduler: bool,+ checkpoint: int | None,) -> None:- state = GraphExecutionState(graph=_sibling_collect_if_graph(left=left, right=right, condition_axis="right"))+ state = GraphExecutionState(graph=_seed52_if_collect_graph())+ if checkpoint is not None:+ partial_trace, state = _run_graph(+ state,+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after=checkpoint,+ )+ assert set(partial_trace) == {"T", "empty"}+ assert not state.is_complete()+ assert not state.has_error(), state.errors+ state = load_execution_state(dump_execution_state(state))trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)assert state.is_complete(), f"graph stalled after {trace}"- assert _collect_output(state) == expected- assert trace.count("body") == len(left) * len(right)+ assert not state.has_error(), state.errors+ assert _source_values(state, "out") == {(): []}+ assert _source_values(state, "outer") == {}+++def _asymmetric_collect_chain_seed_graph(source: list[Any]) -> Graph:+ return _graph_from(+ [+ CollectionConcatInvocation(id="src", first=source),+ IterateInvocation(id="it0"),+ CollectionConcatInvocation(id="cc0"),+ IterateInvocation(id="it1"),+ CollectionConcatInvocation(id="cc1"),+ IterateInvocation(id="it2"),+ MarkedAnyTypeTestInvocation(id="cm", marker="x"),+ CollectInvocation(id="col"),+ MarkedAnyTypeTestInvocation(id="p", marker="F:"),+ FixedCollectionTestInvocation(id="condition"),+ IfInvocation(id="if"),+ ],+ [+ ("src", "collection", "it0", "collection"),+ ("it0", "item", "cc0", "first"),+ ("cc0", "collection", "it1", "collection"),+ ("it1", "item", "cc1", "first"),+ ("cc1", "collection", "it2", "collection"),+ ("it2", "item", "cm", "value"),+ ("cm", "value", "col", "item"),+ ("col", "collection", "p", "value"),+ ("p", "value", "if", "false_input"),+ ("it0", "item", "condition", "value"),+ ("condition", "condition", "if", "condition"),+ ],+ )@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])@pytest.mark.parametrize(- ("left", "collect_field", "expected"),+ "source",[- ([1, 2], "true_input", ["fallback", []]),- ([2, 2], "true_input", [[], []]),- ([2], "true_input", [[]]),- ([1, 2], "false_input", [[], "fallback"]),+ pytest.param([[[]]], id="seed-157"),+ pytest.param([[[[""]], [["b"]]], [[[], ["b", "b"]]]], id="seed-795"),],- ids=["mixed", "all-selected", "single-selected", "false-branch"],)-def test_sibling_collect_branch_with_empty_right_collection_completes(- force_compatibility_scheduler: bool, left: list[int], collect_field: str, expected: list[Any]+def test_seeded_unwired_if_branch_rejects_asymmetric_collect_chain_before_invocation(+ force_compatibility_scheduler: bool,+ source: list[Any],) -> None:- state = GraphExecutionState(graph=_sibling_collect_if_graph(left=left, right=[], collect_field=collect_field))-- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)-- assert state.is_complete(), f"graph stalled after {trace}"- assert _collect_output(state) == expected- assert "body" not in trace--[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_one_collect_may_feed_both_branches_of_the_same_if(force_compatibility_scheduler: bool) -> None:- state = GraphExecutionState(graph=_sibling_collect_if_graph(left=[1, 2], right=[10, 20], same_if_both_fields=True))-- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ state = GraphExecutionState(graph=_asymmetric_collect_chain_seed_graph(source))+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)- assert state.is_complete(), f"graph stalled after {trace}"- assert _collect_output(state) == [[11, 21], [12, 22]]+ with pytest.raises(graph_if_runtime.UnsupportedIfIterationAxesError, match="deeper open iterator axes"):+ state.next()+ assert state.executed_history == []-def _nested_collect_branch_graph(*, outer_values: list[int], extra_consumer_of: str) -> Graph:- """Per-outer If whose true branch collects an inner Iterate; another node also consumes the inner axis."""- graph = Graph()- for node in (- CollectionConcatInvocation(id="outer_source", first=outer_values),- IterateInvocation(id="outer"),- RangeInvocation(id="range", start=0, step=1),- IterateInvocation(id="inner"),- AddInvocation(id="body", b=100),- CollectInvocation(id="inner_collect"),- AnyTypeTestInvocation(id="root_false", value="F"),- AddInvocation(id="minus_one", b=-1),- FixedCollectionTestInvocation(id="condition"),- IfInvocation(id="if"),- CollectInvocation(id="collect"),- AnyTypeTestInvocation(id="extra"),- CollectInvocation(id="extra_collect"),- ):- graph.add_node(node)- extra_field = "item" if extra_consumer_of == "inner" else "value"- for source, source_field, destination, destination_field in (- ("outer_source", "collection", "outer", "collection"),- ("outer", "item", "range", "stop"),- ("range", "collection", "inner", "collection"),- ("inner", "item", "body", "a"),- ("body", "value", "inner_collect", "item"),- ("outer", "item", "minus_one", "a"),- ("minus_one", "value", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("inner_collect", "collection", "if", "true_input"),- ("root_false", "value", "if", "false_input"),- ("if", "value", "collect", "item"),- (extra_consumer_of, extra_field, "extra", "value"),- ("extra", "value", "extra_collect", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))+def _for_final_if_with_unrelated_sibling_graph(collection: list[list[str]]) -> Graph:+ graph = _for_final_if_with_iteration_condition_graph(pass_condition=False, collection=collection)+ graph.add_node(CollectionConcatInvocation(id="sibling_source", first=["s0", "s1", "s2"]))+ graph.add_node(IterateInvocation(id="sibling"))+ graph.add_edge(create_edge("sibling_source", "collection", "sibling", "collection"))+ graph.add_edge(create_edge("sibling", "item", "out", "item"))return graph@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("extra_consumer_of", ["inner", "body"])@pytest.mark.parametrize(- ("outer_values", "expected"),- [([2], [[100, 101]]), ([3, 1, 2], [[100, 101, 102], "F", [100, 101]])],- ids=["single-outer", "mixed-outer"],+ ("collection", "expected_by_frame"),+ [+ pytest.param([["a"], ["b", "c"]], {(0,): ["Fa"], (1,): ["Fb", "Fc"]}, id="all-for-frames"),+ pytest.param([["a"], []], {(0,): ["Fa"], (1,): "R"}, id="mixed-for-and-fallback"),+ ],)-def test_nested_collect_branch_with_extra_inner_consumer_runs_if_once_per_outer_item(- force_compatibility_scheduler: bool, extra_consumer_of: str, outer_values: list[int], expected: list[Any]+def test_selected_for_final_does_not_duplicate_unrelated_sibling_items(+ force_compatibility_scheduler: bool,+ collection: list[list[str]],+ expected_by_frame: dict[tuple[int, ...], Any],) -> None:- state = GraphExecutionState(- graph=_nested_collect_branch_graph(outer_values=outer_values, extra_consumer_of=extra_consumer_of)+ trace, state = _run_graph(+ GraphExecutionState(graph=_for_final_if_with_unrelated_sibling_graph(collection)),+ force_compatibility_scheduler=force_compatibility_scheduler,)- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)-assert state.is_complete(), f"graph stalled after {trace}"- assert _collect_output(state) == expected- assert trace.count("if") == len(outer_values)+ assert not state.has_error(), state.errors+ outputs = _source_values(state, "out")+ for frame, expected in expected_by_frame.items():+ assert expected in outputs[frame]+ assert all(expected not in values for other_frame, values in outputs.items() if other_frame != frame)+ sibling_values = [+ value+ for _, values in sorted(outputs.items())+ for value in values+ if isinstance(value, str) and value in {"s0", "s1", "s2"}+ ]+ assert sibling_values == ["s0", "s1", "s2"]+ assert sum(map(len, outputs.values())) == 5@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])- "conditions",- [[True], [False], [True, False], [False, False]],- ids=["selected", "never-selected", "mixed", "all-unselected"],-)-def test_if_with_unrelated_branch_axis_is_rejected_before_any_node_runs(- force_compatibility_scheduler: bool, conditions: list[bool]+def test_root_item_broadcasts_into_selected_for_groups_and_keeps_sibling_group(+ force_compatibility_scheduler: bool,) -> None:- """The axis mismatch is topological, so it must not depend on condition values or run upstream work first."""- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="branch_source", first=[1, 2]))- graph.add_node(IterateInvocation(id="branch_iterate"))- graph.add_node(AnyTypeTestInvocation(id="branch_value"))- graph.add_node(CollectionConcatInvocation(id="condition_source", first=conditions))- graph.add_node(IterateInvocation(id="condition_iterate"))- graph.add_node(FixedCollectionTestInvocation(id="condition"))- graph.add_node(AnyTypeTestInvocation(id="fallback", value="fallback"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="collect"))- for source, source_field, destination, destination_field in (- ("branch_source", "collection", "branch_iterate", "collection"),- ("branch_iterate", "item", "branch_value", "value"),- ("condition_source", "collection", "condition_iterate", "collection"),- ("condition_iterate", "item", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("branch_value", "value", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "collect", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))+ graph = _for_final_if_with_unrelated_sibling_graph([["a"], ["b", "c"]])+ graph.delete_edge(next(edge for edge in graph._get_input_edges("out", "item") if edge.source.node_id == "if"))+ graph.add_node(IfInvocation(id="outer", condition=True))+ graph.add_node(AnyTypeTestInvocation(id="root", value="ROOT"))+ graph.add_edge(create_edge("if", "value", "outer", "true_input"))+ graph.add_edge(create_edge("outer", "value", "out", "item"))+ graph.add_edge(create_edge("root", "value", "out", "item"))- executed: list[str] = []- with pytest.raises(graph_if_runtime.UnsupportedIfIterationAxesError):- graph.validate_self()- state = GraphExecutionState(graph=graph)- if force_compatibility_scheduler:- state._execution_scheduler = _ExecutionScheduler(state)- while (node := state.next()) is not None:- executed.append(state.prepared_source_mapping[node.id])- state.complete(node.id, node.invoke(Mock()))- assert executed == []+ trace, state = _run_graph(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error(), state.errors+ outputs = _source_values(state, "out")+ assert set(outputs) == {(), (0,), (1,)}+ assert len(outputs[(0,)]) == 2+ assert "ROOT" in outputs[(0,)] and ["Fa"] in outputs[(0,)]+ assert len(outputs[(1,)]) == 2+ assert "ROOT" in outputs[(1,)] and ["Fb", "Fc"] in outputs[(1,)]+ assert outputs[()] == ["s0", "s1", "s2"]+ assert [value for value in outputs[()] if value in {"s0", "s1", "s2"}] == ["s0", "s1", "s2"]-def _product_branch_deeper_than_condition_graph() -> Graph:- graph = Graph()- for node in (- CollectionConcatInvocation(id="left_source", first=[1, 2]),- CollectionConcatInvocation(id="right_source", first=[10, 20]),- IterateInvocation(id="left"),- IterateInvocation(id="right"),- AddInvocation(id="body"),- AddInvocation(id="minus_one", b=-1),- FixedCollectionTestInvocation(id="condition"),- AnyTypeTestInvocation(id="fallback", value="fallback"),- IfInvocation(id="if"),- CollectInvocation(id="collect"),- ):- graph.add_node(node)- for source, source_field, destination, destination_field in (- ("left_source", "collection", "left", "collection"),- ("right_source", "collection", "right", "collection"),- ("left", "item", "body", "a"),- ("right", "item", "body", "b"),- ("left", "item", "minus_one", "a"),- ("minus_one", "value", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("body", "value", "if", "true_input"),- ("fallback", "value", "if", "false_input"),- ("if", "value", "collect", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))- return graph[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_root_item_broadcast_into_nested_literal_if_for_groups_has_no_empty_root_group(+ force_compatibility_scheduler: bool,+) -> None:+ graph = _for_final_if_with_iteration_condition_graph(pass_condition=False)+ graph.delete_edge(next(edge for edge in graph._get_input_edges("if", "condition")))+ graph.update_node("if", IfInvocation(id="if", condition=True))+ graph.delete_edge(next(edge for edge in graph._get_input_edges("out", "item")))+ graph.add_node(IfInvocation(id="outer", condition=True))+ graph.add_node(AnyTypeTestInvocation(id="root", value="ROOT"))+ graph.add_edge(create_edge("if", "value", "outer", "true_input"))+ graph.add_edge(create_edge("outer", "value", "out", "item"))+ graph.add_edge(create_edge("root", "value", "out", "item"))-def _nested_branch_deeper_than_condition_graph() -> Graph:- """Condition per outer item; true branch per inner item, false branch per outer item."""- graph = Graph()- for node in (- CollectionConcatInvocation(id="outer_source", first=[1, 2]),- IterateInvocation(id="outer"),- RangeInvocation(id="range", start=0, step=1),- IterateInvocation(id="inner"),- AddInvocation(id="minus_one", b=-1),- FixedCollectionTestInvocation(id="condition"),- MarkedAnyTypeTestInvocation(id="true_branch", marker="t"),- MarkedAnyTypeTestInvocation(id="false_branch", marker="f"),- IfInvocation(id="if"),- CollectInvocation(id="collect"),- ):- graph.add_node(node)- for source, source_field, destination, destination_field in (- ("outer_source", "collection", "outer", "collection"),- ("outer", "item", "range", "stop"),- ("range", "collection", "inner", "collection"),- ("outer", "item", "minus_one", "a"),- ("minus_one", "value", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("inner", "item", "true_branch", "value"),- ("outer", "item", "false_branch", "value"),- ("true_branch", "value", "if", "true_input"),- ("false_branch", "value", "if", "false_input"),- ("if", "value", "collect", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))- return graph+ trace, state = _run_graph(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )++ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error(), state.errors+ outputs = _source_values(state, "out")+ assert set(outputs) == {(0,), (1,)}+ assert len(outputs[(0,)]) == 2+ assert "ROOT" in outputs[(0,)] and ["Fa"] in outputs[(0,)]+ assert len(outputs[(1,)]) == 2+ assert "ROOT" in outputs[(1,)] and ["Fb", "Fc"] in outputs[(1,)]-def _nested_branch_with_root_false_graph() -> Graph:- """Condition per outer item; true branch per inner item, false branch at root."""- graph = Graph()- for node in (- CollectionConcatInvocation(id="outer_source", first=[3, 2]),- IterateInvocation(id="outer"),- RangeInvocation(id="range", start=0, step=1),- IterateInvocation(id="inner"),- AddInvocation(id="body", b=100),- AddInvocation(id="minus_two", b=-2),- FixedCollectionTestInvocation(id="condition"),- AnyTypeTestInvocation(id="root_false", value="F"),- IfInvocation(id="if"),- CollectInvocation(id="collect"),- ):- graph.add_node(node)- for source, source_field, destination, destination_field in (- ("outer_source", "collection", "outer", "collection"),- ("outer", "item", "range", "stop"),- ("range", "collection", "inner", "collection"),- ("inner", "item", "body", "a"),- ("outer", "item", "minus_two", "a"),- ("minus_two", "value", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("body", "value", "if", "true_input"),- ("root_false", "value", "if", "false_input"),- ("if", "value", "collect", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))- return graph[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_root_collect_collection_broadcasts_to_sibling_and_selected_for_groups(+ force_compatibility_scheduler: bool,+) -> None:+ graph = _for_final_if_with_unrelated_sibling_graph([["a"], ["b", "c"]])+ graph.add_node(CollectionConcatInvocation(id="root_collection", first=["ROOT"]))+ graph.add_edge(create_edge("root_collection", "collection", "out", "collection"))++ trace, state = _run_graph(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )++ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error(), state.errors+ outputs = _source_values(state, "out")+ assert set(outputs) == {(), (0,), (1,)}+ assert len(outputs[()]) == 4+ assert outputs[()].count("ROOT") == 1+ assert [value for value in outputs[()] if value in {"s0", "s1", "s2"}] == ["s0", "s1", "s2"]+ assert len(outputs[(0,)]) == 2+ assert "ROOT" in outputs[(0,)] and ["Fa"] in outputs[(0,)]+ assert len(outputs[(1,)]) == 2+ assert "ROOT" in outputs[(1,)] and ["Fb", "Fc"] in outputs[(1,)]++[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_root_collect_item_broadcasts_into_nested_iterator_groups(force_compatibility_scheduler: bool) -> None:+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="source", first=[0, 10]),+ IterateInvocation(id="outer"),+ RangeOfSizeInvocation(id="inner_source", size=2),+ IterateInvocation(id="inner"),+ AnyTypeTestInvocation(id="inner_item"),+ AnyTypeTestInvocation(id="root_item", value=100),+ CollectInvocation(id="collect"),+ ],+ [+ ("source", "collection", "outer", "collection"),+ ("outer", "item", "inner_source", "start"),+ ("inner_source", "collection", "inner", "collection"),+ ("inner", "item", "inner_item", "value"),+ ("inner_item", "value", "collect", "item"),+ ("root_item", "value", "collect", "item"),+ ],+ )+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )++ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error(), state.errors+ assert _source_values(state, "collect") == {(0,): [100, 0, 1], (1,): [100, 10, 11]}@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])@pytest.mark.parametrize(- "build_graph",+ ("collection", "expected"),[- _product_branch_deeper_than_condition_graph,- _nested_branch_deeper_than_condition_graph,- _nested_branch_with_root_false_graph,+ pytest.param([["a"]], {(0,): ["a"]}, id="single-nested"),+ pytest.param([[], [["s"]]], {(0,): [], (1,): [["s"]]}, id="empty-before-nonempty"),+ pytest.param([[], []], {(0,): [], (1,): []}, id="all-empty"),+ pytest.param([[["a"]], [], [["b"]]], {(0,): [["a"]], (1,): [], (2,): [["b"]]}, id="ragged-empty-middle"),],- ids=["product-branch", "nested-true-branch", "nested-branch-root-false"],)-def test_if_branch_deeper_than_its_condition_completes_or_is_rejected(- force_compatibility_scheduler: bool, build_graph: Callable[[], Graph]+def test_collect_preserves_empty_and_ragged_nested_iterator_paths(+ force_compatibility_scheduler: bool,+ collection: list[Any],+ expected: dict[tuple[int, ...], Any],) -> None:- """Deeper open branch axes are explicitly rejected before any node executes."""- state = GraphExecutionState(graph=build_graph())- with pytest.raises(- graph_if_runtime.UnsupportedIfIterationAxesError,- match=(- r"If node 'if' cannot select branch input 'true_input' from deeper open iterator axes "- r"without a Collect boundary"- ),- ):- _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- assert state.executed_history == []-+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="source", first=collection),+ IterateInvocation(id="outer"),+ CollectionConcatInvocation(id="inner_source"),+ IterateInvocation(id="inner"),+ AnyTypeTestInvocation(id="item"),+ CollectInvocation(id="collect"),+ ],+ [+ ("source", "collection", "outer", "collection"),+ ("outer", "item", "inner_source", "first"),+ ("inner_source", "collection", "inner", "collection"),+ ("inner", "item", "item", "value"),+ ("item", "value", "collect", "item"),+ ],+ )+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )-def _broadcast_deeper_if_graph(*, selected: bool) -> Graph:- """An outer condition selects one of two complete inner-Iterate branches."""- graph = Graph()- for node in (- CollectionConcatInvocation(id="outer_source", first=[2, 0] if selected else [0, 2]),- IterateInvocation(id="outer"),- AddInvocation(id="range_stop", b=1),- RangeInvocation(id="range", start=0, step=1),- IterateInvocation(id="inner"),- FixedCollectionTestInvocation(id="condition"),- AddInvocation(id="true_value", b=10),- AddInvocation(id="false_value", b=100),- IfInvocation(id="if"),- CollectInvocation(id="collect"),- ):- graph.add_node(node)- for source, source_field, destination, destination_field in (- ("outer_source", "collection", "outer", "collection"),- ("outer", "item", "condition", "value"),- ("condition", "condition", "if", "condition"),- ("outer", "item", "range_stop", "a"),- ("range_stop", "value", "range", "stop"),- ("range", "collection", "inner", "collection"),- ("inner", "item", "true_value", "a"),- ("inner", "item", "false_value", "a"),- ("true_value", "value", "if", "true_input"),- ("false_value", "value", "if", "false_input"),- ("if", "value", "collect", "item"),- ):- graph.add_edge(create_edge(source, source_field, destination, destination_field))- return graph+ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error(), state.errors+ assert _source_values(state, "collect") == expected@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("selected", [True, False], ids=["true-branch", "false-branch"])-def test_if_broadcasts_a_deeper_iterate_branch_across_each_outer_condition_frame(- force_compatibility_scheduler: bool, selected: bool+def test_two_literal_if_sibling_wrappers_share_one_group_with_selected_for(+ force_compatibility_scheduler: bool,) -> None:- state = GraphExecutionState(graph=_broadcast_deeper_if_graph(selected=selected))-- trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ graph = _for_final_if_with_unrelated_sibling_graph([["a"], ["b"]])+ graph.delete_edge(next(edge for edge in graph._get_input_edges("out", "item") if edge.source.node_id == "if"))+ graph.delete_edge(next(edge for edge in graph._get_input_edges("out", "item") if edge.source.node_id == "sibling"))+ graph.add_node(IfInvocation(id="selected_if_outer", condition=True))+ graph.add_edge(create_edge("if", "value", "selected_if_outer", "true_input"))+ graph.add_edge(create_edge("selected_if_outer", "value", "out", "item"))+ graph.add_node(IfInvocation(id="sibling_if", condition=True))+ graph.add_node(IfInvocation(id="sibling_if_outer", condition=True))+ graph.add_edge(create_edge("sibling", "item", "sibling_if", "true_input"))+ graph.add_edge(create_edge("sibling_if", "value", "sibling_if_outer", "true_input"))+ graph.add_edge(create_edge("sibling_if_outer", "value", "out", "item"))+ trace, state = _run_graph(+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler+ )assert state.is_complete(), f"graph stalled after {trace}"- assert not state.has_error()- expected = [[10, 11, 12], [100]] if selected else [[100], [10, 11, 12]]- collect_nodes = sorted(state.source_prepared_mapping["collect"], key=state._get_iteration_path)- collected = [state.results[node_id].collection for node_id in collect_nodes]- assert collected == expected, f"{trace=}"- assert trace.count("if") == 4- assert trace.count("true_value") == 3- assert trace.count("false_value") == 1- assert len(collect_nodes) == 2+ assert not state.has_error(), state.errors+ outputs = _source_values(state, "out")+ assert set(outputs) == {(), (0,), (1,)}+ assert outputs[(0,)] == [["Fa"]]+ assert outputs[(1,)] == [["Fb"]]+ root_values = outputs[()]+ assert len(root_values) == 3+ assert root_values == ["s0", "s1", "s2"]@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])-def test_if_broadcast_deeper_iterate_frames_resume_after_dump_load(- force_compatibility_scheduler: bool,[email protected]("with_literal_if", [False, True], ids=["plain", "literal-if"])+def test_parallel_root_iterates_collect_each_pair_with_both_values_from_third_iterate(+ force_compatibility_scheduler: bool, with_literal_if: bool) -> None:- state = GraphExecutionState(graph=_broadcast_deeper_if_graph(selected=True))- _, partial = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler, stop_after=7)- restored = load_execution_state(dump_execution_state(partial))-- trace, restored = _run_graph(restored, force_compatibility_scheduler=force_compatibility_scheduler)+ nodes: list[Any] = [+ CollectionConcatInvocation(id="a_source", first=[0, 1]),+ IterateInvocation(id="a"),+ CollectionConcatInvocation(id="b_source", first=[10, 20, 30]),+ IterateInvocation(id="b"),+ CollectionConcatInvocation(id="c_source", first=[100, 200]),+ IterateInvocation(id="c"),+ AddInvocation(id="pair"),+ AddInvocation(id="consumer"),+ CollectInvocation(id="collect"),+ AnyTypeTestInvocation(id="downstream"),+ ]+ edges: list[Any] = [+ ("a_source", "collection", "a", "collection"),+ ("b_source", "collection", "b", "collection"),+ ("c_source", "collection", "c", "collection"),+ ("a", "item", "pair", "a"),+ ("b", "item", "pair", "b"),+ ("pair", "value", "consumer", "a"),+ ("c", "item", "consumer", "b"),+ ]+ if with_literal_if:+ nodes.append(IfInvocation(id="literal_if", condition=True))+ edges.extend([("consumer", "value", "literal_if", "true_input"), ("literal_if", "value", "collect", "item")])+ else:+ edges.append(("consumer", "value", "collect", "item"))+ edges.append(("collect", "collection", "downstream", "value"))+ graph = _graph_from(+ nodes,+ edges,+ )+ state = GraphExecutionState(graph=graph)+ if not force_compatibility_scheduler:+ state._execution_scheduler = _GenericGraphSchedulerAdapter(state)+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)- assert restored.is_complete(), f"graph stalled after resume: {trace}"- collect_nodes = sorted(restored.source_prepared_mapping["collect"], key=restored._get_iteration_path)- assert [restored.results[node_id].collection for node_id in collect_nodes] == [[10, 11, 12], [100]]+ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error(), state.errors+ if not force_compatibility_scheduler:+ assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)+ collect_runs = [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state._prepared_registry().get_prepared_ids("collect")+ ]+ assert sorted(collect_runs) == [+ ((a_index, b_index), [a + b + 100, a + b + 200])+ for a_index, a in enumerate((0, 1))+ for b_index, b in enumerate((10, 20, 30))+ ]+ assert len(state._prepared_registry().get_prepared_ids("pair")) == 6+ assert len(state._prepared_registry().get_prepared_ids("consumer")) == 12+ assert len(state._prepared_registry().get_prepared_ids("downstream")) == 6+ assert all(path != (2,) for path, _ in collect_runs)@pytest.mark.parametrize("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])@pytest.mark.parametrize(- ("condition", "per_item_field", "root_field", "expected_value"),+ ("source", "expected_col1", "expected_col2"),[- (True, "false_input", "true_input", "root"),- (False, "true_input", "false_input", "root"),- (False, "true_input", None, None),+ ([[["a"], []]], [((0,), [["t:a"], []])], [((), [[["t:a"], []]])]),+ (+ [[["a", "c"]], []],+ [((0,), [["t:a", "t:c"]]), ((1,), [[]])],+ [((), [[["t:a", "t:c"]], [[]]])],+ ),+ (+ [[["a"]], [], [["b"]]],+ [((0,), [["t:a"]]), ((1,), [[]]), ((2,), [["t:b"]])],+ [((), [[["t:a"]], [[]], [["t:b"]]])],+ ),],- ids=["true-selects-root", "false-selects-root", "false-selects-unwired"],)-def test_literal_if_selecting_a_root_branch_skips_the_per_item_branch(+def test_three_nested_iterates_collect_chains_preserve_every_ordered_execution(force_compatibility_scheduler: bool,- condition: bool,- per_item_field: str,- root_field: str | None,- expected_value: str | None,+ source: list[Any],+ expected_col1: list[tuple[tuple[int, ...], Any]],+ expected_col2: list[tuple[tuple[int, ...], Any]],) -> None:- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="source", first=[1, 2]))- graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(AddInvocation(id="per_item", b=10))- graph.add_node(IfInvocation(id="if", condition=condition))- graph.add_node(CollectInvocation(id="collect"))- graph.add_edge(create_edge("source", "collection", "iterate", "collection"))- graph.add_edge(create_edge("iterate", "item", "per_item", "a"))- graph.add_edge(create_edge("per_item", "value", "if", per_item_field))- graph.add_edge(create_edge("if", "value", "collect", "item"))- if root_field is not None:- graph.add_node(AnyTypeTestInvocation(id="root", value="root"))- graph.add_edge(create_edge("root", "value", "if", root_field))+ graph = _graph_from(+ [+ CollectionConcatInvocation(id="source", first=source),+ IterateInvocation(id="it0"),+ CollectionConcatInvocation(id="c0"),+ IterateInvocation(id="it1"),+ CollectionConcatInvocation(id="c1"),+ IterateInvocation(id="it2"),+ MarkedAnyTypeTestInvocation(id="mark", marker="t:"),+ CollectInvocation(id="col0"),+ CollectInvocation(id="col1"),+ CollectInvocation(id="col2"),+ ],+ [+ ("source", "collection", "it0", "collection"),+ ("it0", "item", "c0", "first"),+ ("c0", "collection", "it1", "collection"),+ ("it1", "item", "c1", "first"),+ ("c1", "collection", "it2", "collection"),+ ("it2", "item", "mark", "value"),+ ("mark", "value", "col0", "item"),+ ("col0", "collection", "col1", "item"),+ ("col1", "collection", "col2", "item"),+ ],+ )state = GraphExecutionState(graph=graph)-+ if not force_compatibility_scheduler:+ state._execution_scheduler = _GenericGraphSchedulerAdapter(state)trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)-assert state.is_complete(), f"graph stalled after {trace}"- assert "per_item" not in trace- collected = _collect_output(state)- assert collected == [expected_value, expected_value]- assert trace.count("if") == 2+ assert not state.has_error(), state.errors+ if not force_compatibility_scheduler:+ assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)+ def records(node: str) -> list[tuple[tuple[int, ...], Any]]:+ return [+ (state._get_iteration_path(exec_id), getattr(state.results[exec_id], "collection", None))+ for exec_id in state._prepared_registry().get_prepared_ids(node)+ ]-def test_deep_if_branch_chain_does_not_need_recursion_per_chain_node() -> None:- """Guard #9821 cheaply: a recursive traversal exceeds this limit long before the issue's 1,000-node repro does."""- chain_length = 150- graph = Graph()- graph.add_node(CollectionConcatInvocation(id="source", first=[True, False]))- graph.add_node(IterateInvocation(id="iterate"))- graph.add_node(IfInvocation(id="if"))- graph.add_node(CollectInvocation(id="collect"))- graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="f"))- for index in range(chain_length):- graph.add_node(AnyTypeTestInvocation(id=f"chain_{index}"))- graph.add_edge(create_edge("source", "collection", "iterate", "collection"))- graph.add_edge(create_edge("iterate", "item", "if", "condition"))- graph.add_edge(create_edge("iterate", "item", "chain_0", "value"))- graph.add_edge(create_edge("iterate", "item", "false_branch", "value"))- graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))- for index in range(chain_length - 1):- graph.add_edge(create_edge(f"chain_{index}", "value", f"chain_{index + 1}", "value"))- graph.add_edge(create_edge(f"chain_{chain_length - 1}", "value", "if", "true_input"))- graph.add_edge(create_edge("if", "value", "collect", "item"))+ assert len(records("col1")) == len(expected_col1)+ assert sorted(records("col1"), key=lambda record: (record[0], repr(record[1]))) == sorted(+ expected_col1, key=lambda record: (record[0], repr(record[1]))+ )+ assert len(records("col2")) == 1+ assert records("col2") == expected_col2++[email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])[email protected]("if_variant", ["plain", "literal", "wired"], ids=["plain", "literal-if", "wired-if"])[email protected]("with_root_item", [False, True], ids=["no-root-S", "root-S"])+def test_root_item_and_nested_collect_iterate_out2_keep_exact_groups(+ force_compatibility_scheduler: bool, if_variant: str, with_root_item: bool+) -> None:+ nodes: list[Any] = [+ CollectionConcatInvocation(id="source", first=[[], [["b", ""]]]),+ IterateInvocation(id="it0"),+ CollectionConcatInvocation(id="concat"),+ IterateInvocation(id="it1"),+ MarkedAnyTypeTestInvocation(id="m1", marker="T:"),+ CollectInvocation(id="out"),+ IterateInvocation(id="rit"),+ MarkedAnyTypeTestInvocation(id="rm", marker="r:"),+ CollectInvocation(id="out2"),+ ]+ edges: list[Any] = [+ ("source", "collection", "it0", "collection"),+ ("it0", "item", "concat", "first"),+ ("concat", "collection", "it1", "collection"),+ ("it1", "item", "m1", "value"),+ ("m1", "value", "out", "item"),+ ("out", "collection", "rit", "collection"),+ ("rit", "item", "rm", "value"),+ ]+ if with_root_item:+ nodes.append(AnyTypeTestInvocation(id="root", value="S"))+ edges.append(("root", "value", "out", "item"))+ if if_variant != "plain":+ nodes.append(IfInvocation(id="if", condition=True))+ edges.append(("rm", "value", "if", "true_input"))+ if if_variant == "wired":+ nodes.append(BooleanInvocation(id="condition", value=True))+ edges.append(("condition", "value", "if", "condition"))+ edges.append(("if", "value", "out2", "item"))+ else:+ edges.append(("rm", "value", "out2", "item"))+ graph = _graph_from(+ nodes,+ edges,+ )state = GraphExecutionState(graph=graph)+ if not force_compatibility_scheduler:+ state._execution_scheduler = _GenericGraphSchedulerAdapter(state)+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error(), state.errors+ if not force_compatibility_scheduler:+ assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)+ expected_out = {(0,): ["S"], (1,): ["S", "T:['b', '']"]} if with_root_item else {(0,): [], (1,): ["T:['b', '']"]}+ expected_out2 = (+ {(0,): ["r:S"], (1,): ["r:S", "r:T:['b', '']"]} if with_root_item else {(0,): [], (1,): ["r:T:['b', '']"]}+ )+ out_records = [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state._prepared_registry().get_prepared_ids("out")+ ]+ out2_records = [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state._prepared_registry().get_prepared_ids("out2")+ ]+ assert len(out_records) == len(expected_out)+ assert dict(out_records) == expected_out+ assert len(out2_records) == len(expected_out2)+ assert dict(out2_records) == expected_out2+ if with_root_item:+ assert sorted(out_records, key=lambda record: (record[0], repr(record[1]))) == sorted(+ expected_out.items(), key=lambda record: (record[0], repr(record[1]))+ )+ assert sorted(out2_records, key=lambda record: (record[0], repr(record[1]))) == sorted(+ expected_out2.items(), key=lambda record: (record[0], repr(record[1]))+ )+ assert [path for path, _ in out2_records].count((1,)) == 1- previous_limit = sys.getrecursionlimit()- sys.setrecursionlimit(len(inspect.stack()) + 250)- try:- _, state = _run_graph(state)- finally:- sys.setrecursionlimit(previous_limit)- assert state.is_complete()- assert _collect_output(state) == [True, "fFalse"][email protected]("force_compatibility_scheduler", [False, True], ids=["generic", "compatibility"])+def test_literal_false_if_after_collect_chain_keeps_selected_values_and_no_phantom_collect(+ force_compatibility_scheduler: bool,+) -> None:+ graph = _graph_from(+ [+ CollectionConcatInvocation(+ id="source", first=[[[["b"], ["b", "c"]], [["a"], ["c", "b"], ["b", "a", ""]], []], []]+ ),+ IterateInvocation(id="it0"),+ CollectionConcatInvocation(id="concat0"),+ IterateInvocation(id="it1"),+ CollectionConcatInvocation(id="concat1"),+ IterateInvocation(id="it2"),+ MarkedAnyTypeTestInvocation(id="cm", marker="x"),+ CollectInvocation(id="col3"),+ CollectInvocation(id="col4"),+ MarkedAnyTypeTestInvocation(id="m1", marker="T:"),+ IfInvocation(id="if", condition=False),+ CollectionConcatInvocation(id="root", first=["S"]),+ CollectInvocation(id="out"),+ ],+ [+ ("source", "collection", "it0", "collection"),+ ("it0", "item", "concat0", "first"),+ ("concat0", "collection", "it1", "collection"),+ ("it1", "item", "concat1", "first"),+ ("concat1", "collection", "it2", "collection"),+ ("it2", "item", "cm", "value"),+ ("cm", "value", "col3", "item"),+ ("col3", "collection", "col4", "item"),+ ("it1", "item", "m1", "value"),+ ("m1", "value", "if", "true_input"),+ ("col4", "collection", "if", "false_input"),+ ("if", "value", "out", "item"),+ ("root", "collection", "out", "collection"),+ ],+ )+ state = GraphExecutionState(graph=graph)+ if not force_compatibility_scheduler:+ state._execution_scheduler = _GenericGraphSchedulerAdapter(state)+ trace, state = _run_graph(state, force_compatibility_scheduler=force_compatibility_scheduler)+ assert state.is_complete(), f"graph stalled after {trace}"+ assert not state.has_error(), state.errors+ if not force_compatibility_scheduler:+ assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)+ out_runs = [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state._prepared_registry().get_prepared_ids("out")+ ]+ aggregate = [+ ["x['b']", "x['b', 'c']"],+ ["x['a']", "x['c', 'b']", "x['b', 'a', '']"],+ [],+ ]+ assert sorted(out_runs, key=lambda record: (record[0], repr(record[1]))) == sorted(+ [+ ((0,), ["S", aggregate, aggregate, aggregate]),+ ((1,), ["S"]),+ ],+ key=lambda record: (record[0], repr(record[1])),+ )+ if_runs = [+ (state._get_iteration_path(exec_id), state.results[exec_id].value)+ for exec_id in state._prepared_registry().get_prepared_ids("if")+ ]+ assert sorted(if_runs, key=lambda record: (record[0], repr(record[1]))) == [+ ((0, 0), aggregate),+ ((0, 1), aggregate),+ ((0, 2), aggregate),+ ]+ assert all(path != () for path, _ in out_runs)+ empty_col4_paths = [+ state._get_iteration_path(exec_id)+ for exec_id in state._prepared_registry().get_prepared_ids("col4")+ if state.results[exec_id].collection == [[]]+ ]+ assert empty_col4_paths == [(1,)]diff --git a/tests/app/services/shared/test_execution_engine_fuzz.py b/tests/app/services/shared/test_execution_engine_fuzz.pynew file mode 100644index 0000000000..bd6c059368--- /dev/null+++ b/tests/app/services/shared/test_execution_engine_fuzz.py@@ -0,0 +1,718 @@+"""Execution-engine fuzzer.++Run serially with ``uv run --no-sync pytest tests/app/services/shared/test_execution_engine_fuzz.py -m slow --durations=10``.+For local parallel execution across seeds, add ``-n <cpus> --dist load``; replace ``<cpus>`` with a worker count.+The configured ``loadfile`` distribution otherwise keeps this single file on one worker.+"""++from __future__ import annotations++import json+import random+from collections import Counter, defaultdict+from typing import Any+from unittest.mock import Mock++import pytest++from invokeai.app.invocations.collections import CollectionConcatInvocation+from invokeai.app.invocations.logic import IfInvocation+from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation+from invokeai.app.invocations.primitives import BooleanInvocation+from invokeai.app.services.shared.execution_state_migration import dump_execution_state, load_execution_state+from invokeai.app.services.shared.graph import (+ CollectInvocation,+ Graph,+ GraphExecutionState,+ IterateInvocation,+ _ExecutionScheduler,+ _GenericGraphSchedulerAdapter,+)+from invokeai.app.services.shared.graph_if_runtime import UnsupportedIfIterationAxesError+from tests.test_nodes import (+ AnyTypeTestInvocation,+ FixedCollectionTestInvocation,+ MarkedAnyTypeTestInvocation,+ create_edge,+ create_loop_linkage,+)+++def G(nodes, edges):+ graph = Graph()+ for node in nodes:+ graph.add_node(node)+ for edge in sorted(+ edges, key=lambda edge: 0 if (edge[3] if isinstance(edge, tuple) else edge.destination.field) == "item" else 1+ ):+ graph.add_edge(create_edge(*edge) if isinstance(edge, tuple) else edge)+ graph.validate_self()+ return graph+++LEAVES = ["a", "b", "", "c"]+++def data(r, depth):+ if depth == 0:+ return r.choice(LEAVES)+ n = r.choice([0, 1, 1, 2, 2, 3])+ return [data(r, depth - 1) for _ in range(n)]+++def build(seed):+ r = random.Random(seed)+ L = r.choice([1, 2, 2, 3])+ depth = L + 1 # leaves under deepest iterate are lists of strings+ src = data(r, depth)+ if not src and r.random() < 0.7:++ def nonempty(level):+ return "a" if level == 0 else [nonempty(level - 1)]++ src = data(r, depth) or [nonempty(depth - 1)]+ nodes = [CollectionConcatInvocation(id="src", first=src)]+ edges = []+ prev = ("src", "collection")+ for k in range(L):+ nodes.append(IterateInvocation(id=f"it{k}"))+ edges.append((*prev, f"it{k}", "collection"))+ prev = (f"it{k}", "item")+ if k < L - 1:+ nodes.append(CollectionConcatInvocation(id=f"cc{k}"))+ edges.append((f"it{k}", "item", f"cc{k}", "first"))+ prev = (f"cc{k}", "collection")+ ctr = [0]++ def new(prefix):+ ctr[0] += 1+ return f"{prefix}{ctr[0]}"++ shared_cache = {}+ used = []++ def branch(kind, marker):+ t = kind[0]+ used.append(kind[0])+ if t == "root":+ n = new("root")+ nodes.append(AnyTypeTestInvocation(id=n, value=marker))+ return (n, "value")+ if t == "iter":+ n = new("m")+ nodes.append(MarkedAnyTypeTestInvocation(id=n, marker=marker))+ edges.append((f"it{kind[1]}", "item", n, "value"))+ return (n, "value")+ if t in ("collect", "shared"):+ k = kind[1]+ key = ("c", k)+ if t == "shared" and key in shared_cache:+ c = shared_cache[key]+ else:+ m = new("cm")+ nodes.append(MarkedAnyTypeTestInvocation(id=m, marker="x"))+ edges.append((f"it{k}", "item", m, "value"))+ c = new("col")+ nodes.append(CollectInvocation(id=c))+ edges.append((m, "value", c, "item"))+ if t == "shared":+ shared_cache[key] = c+ n = new("p")+ nodes.append(MarkedAnyTypeTestInvocation(id=n, marker=marker))+ edges.append((c, "collection", n, "value"))+ return (n, "value")+ if t == "collect2":+ k = kind[1]+ m = new("cm")+ nodes.append(MarkedAnyTypeTestInvocation(id=m, marker="x"))+ edges.append((f"it{k}", "item", m, "value"))+ c = new("col")+ nodes.append(CollectInvocation(id=c))+ edges.append((m, "value", c, "item"))+ c2 = new("col")+ nodes.append(CollectInvocation(id=c2))+ edges.append((c, "collection", c2, "item"))+ return (c2, "collection")+ if t == "if":+ ik = r.choice(["litT", "litF", "rootT", "rootF", "item"])+ il = r.randrange(L)+ n = new("iif")+ kw = {"condition": ik == "litT"} if ik in ("litT", "litF") else {}+ a = branch(base(), "a" + marker)+ b = branch(base(), "b" + marker)+ nodes.append(IfInvocation(id=n, **kw))+ edges.extend([(*a, n, "true_input"), (*b, n, "false_input")])+ if ik in ("rootT", "rootF"):+ c = new("ic")+ nodes.append(BooleanInvocation(id=c, value=ik == "rootT"))+ edges.append((c, "value", n, "condition"))+ elif ik == "item":+ c = new("ic")+ nodes.append(FixedCollectionTestInvocation(id=c))+ edges.extend([(f"it{il}", "item", c, "value"), (c, "condition", n, "condition")])+ if r.random() < 0.5:+ return (n, "value")+ p = new("p")+ nodes.append(MarkedAnyTypeTestInvocation(id=p, marker=marker))+ edges.append((n, "value", p, "value"))+ return (p, "value")+ if t == "forE":+ f = new("for")+ b = new("fb")+ rt = new("ret")+ ei = new("eit")+ es = new("es")+ nodes.extend(+ [+ CollectionConcatInvocation(id=es, first=[]),+ IterateInvocation(id=ei),+ ForInvocation(id=f),+ MarkedAnyTypeTestInvocation(id=b, marker="F"),+ ForReturnInvocation(id=rt),+ ]+ )+ edges.extend(+ [+ (es, "collection", ei, "collection"),+ (ei, "item", f, "collection"),+ (f, "item", b, "value"),+ (b, "value", rt, "output"),+ create_loop_linkage(f, rt),+ ]+ )+ return (f, "output_collection")+ if t == "forR":+ f = new("for")+ b = new("fb")+ rt = new("ret")+ nodes.extend(+ [+ ForInvocation(id=f, collection=r.choice([[], ["u"], ["u", "v"]])),+ MarkedAnyTypeTestInvocation(id=b, marker="F"),+ ForReturnInvocation(id=rt),+ ]+ )+ edges.extend([(f, "item", b, "value"), (b, "value", rt, "output"), create_loop_linkage(f, rt)])+ return (f, "output_collection")+ if t == "for":+ k = kind[1]+ direct = kind[2]+ f = new("for")+ b = new("fb")+ rt = new("ret")+ nodes.extend(+ [ForInvocation(id=f), MarkedAnyTypeTestInvocation(id=b, marker="F"), ForReturnInvocation(id=rt)]+ )+ edges.extend(+ [+ (f"it{k}", "item", f, "collection"),+ (f, "item", b, "value"),+ (b, "value", rt, "output"),+ create_loop_linkage(f, rt),+ ]+ )+ if direct:+ return (f, "output_collection")+ n = new("p")+ nodes.append(MarkedAnyTypeTestInvocation(id=n, marker=marker))+ edges.append((f, "output_collection", n, "value"))+ return (n, "value")++ def base():+ opts = [+ ("root",),+ ("iter", r.randrange(L)),+ ("collect", r.randrange(L)),+ ("for", r.randrange(L), r.random() < 0.5),+ ("forR",),+ ]+ return r.choice(opts)++ def rkind():+ opts = [("root",), ("iter", r.randrange(L)), ("collect", r.randrange(L)), ("shared", r.randrange(L))]+ if L >= 2:+ opts.append(("collect2", r.randrange(1, L)))+ opts.append(("for", r.randrange(L), r.random() < 0.5))+ opts += [("if",), ("if",), ("forE",), ("forR",)]+ return r.choice(opts)++ tk, fk = rkind(), rkind()+ if r.random() < 0.3:+ fk = tk if tk[0] != "for" else fk+ ckind = r.choice(["litT", "litF", "rootT", "rootF", "item", "item"])+ clevel = r.randrange(L)+ tsrc = branch(tk, "T:")+ fsrc = branch(fk, "F:")+ ifkw = {"condition": True} if ckind == "litT" else ({"condition": False} if ckind == "litF" else {})+ nodes.append(IfInvocation(id="if", **ifkw))+ edges.extend([(*tsrc, "if", "true_input"), (*fsrc, "if", "false_input")])+ if ckind in ("rootT", "rootF"):+ nodes.append(BooleanInvocation(id="cond", value=ckind == "rootT"))+ edges.append(("cond", "value", "if", "condition"))+ elif ckind == "item":+ nodes.append(FixedCollectionTestInvocation(id="cond"))+ edges.extend([(f"it{clevel}", "item", "cond", "value"), ("cond", "condition", "if", "condition")])+ outsrc = ("if", "value")+ if r.random() < 0.3:+ o = branch(base(), "O:")+ nodes.append(IfInvocation(id="if2", condition=r.random() < 0.5))+ edges.extend([("if", "value", "if2", "true_input"), (*o, "if2", "false_input")])+ outsrc = ("if2", "value")+ nodes.append(CollectInvocation(id="out"))+ edges.append((*outsrc, "out", "item"))+ extra = r.choice(["none", "sibroot", "sibiter", "sibcoll", "sibchain", "sibsame"])+ if extra == "sibroot":+ nodes.append(AnyTypeTestInvocation(id="sx", value="S"))+ edges.append(("sx", "value", "out", "item"))+ elif extra == "sibcoll":+ nodes.append(CollectionConcatInvocation(id="sx", first=["S"]))+ edges.append(("sx", "collection", "out", "collection"))+ elif extra in ("sibiter", "sibchain"):+ nodes += [+ CollectionConcatInvocation(id="sbs", first=r.choice([[], ["p"], ["p", "q", "r"]])),+ IterateInvocation(id="itb"),+ MarkedAnyTypeTestInvocation(id="sx", marker="n"),+ ]+ edges += [("sbs", "collection", "itb", "collection"), ("itb", "item", "sx", "value")]+ last = ("sx", "value")+ if extra == "sibchain":+ nodes += [+ IfInvocation(id="sj0", condition=True),+ AnyTypeTestInvocation(id="sjr", value="J"),+ IfInvocation(id="sj1", condition=r.random() < 0.5),+ ]+ edges += [+ ("sx", "value", "sj0", "true_input"),+ ("sjr", "value", "sj0", "false_input"),+ ("sj0", "value", "sj1", "true_input"),+ ("sj0", "value", "sj1", "false_input"),+ ]+ last = ("sj1", "value")+ edges.append((*last, "out", "item"))+ elif extra == "sibsame":+ b = branch(base(), "S:")+ edges.append((*b, "out", "item"))+ tail = r.choice(["none", "out2", "reif"])+ if tail == "out2":+ nodes.append(CollectInvocation(id="out2"))+ edges.append(("out", "collection", "out2", "item"))+ elif tail == "reif":+ # If -> Collect -> Iterate -> If -> Collect+ rk = r.choice(["lit", "root", "item"])+ nodes += [+ IterateInvocation(id="rit"),+ MarkedAnyTypeTestInvocation(id="rm", marker="r"),+ AnyTypeTestInvocation(id="rr", value="RR"),+ IfInvocation(id="rif", **({"condition": r.random() < 0.5} if rk == "lit" else {})),+ CollectInvocation(id="out2"),+ ]+ edges += [+ ("out", "collection", "rit", "collection"),+ ("rit", "item", "rm", "value"),+ ("rm", "value", "rif", "true_input"),+ ("rr", "value", "rif", "false_input"),+ ("rif", "value", "out2", "item"),+ ]+ if rk == "root":+ nodes.append(BooleanInvocation(id="rc", value=r.random() < 0.5))+ edges.append(("rc", "value", "rif", "condition"))+ if rk == "item":+ nodes.append(FixedCollectionTestInvocation(id="rc"))+ edges += [("rit", "item", "rc", "value"), ("rc", "condition", "rif", "condition")]+ used.append(extra)+ used.append(tail)+ desc = f"used={used} if2={'if2' in [n.id for n in nodes]} L={L} src={src} T={tk} F={fk} cond={ckind}@{clevel}"+ return desc, (lambda: G(list(nodes), list(edges)))+++_KNOWN_VALID_SEEDS = frozenset(+ {+ 3,+ 52,+ 233,+ 333,+ 573,+ 630,+ 880,+ 887,+ 992,+ 1300,+ 1331,+ 1593,+ 1728,+ 1836,+ 1906,+ 1940,+ 1970,+ 2047,+ 2057,+ 2355,+ 2382,+ 2394,+ 2575,+ 2667,+ 2775,+ 2829,+ }+)++[email protected]("seed", [52, 887, 1593, 2667], ids=lambda seed: f"seed{seed}")+def test_empty_nested_if_frames_retire_branch_descendants(seed: int) -> None:+ desc, graph_factory = build(seed)+ graph_factory().validate_self()+ results = {+ (forced, checkpoint): _run(seed, forced_compatibility=forced, roundtrip_at=checkpoint)+ for forced in (False, True)+ for checkpoint in (None, 3, 4, 5)+ }+ assert all(result == results[(False, None)] for result in results.values()), f"seed={seed} graph={desc}"+++def _canonical_result(graph: Graph, node_id: str, value: Any) -> Any:+ if not isinstance(value, list):+ return value+ node = graph.get_node(node_id)+ if isinstance(node, CollectInvocation):+ edges = graph._get_input_edges(node_id, "item")+ if len(edges) == 1 and isinstance(graph.get_node(edges[0].source.node_id), CollectInvocation):+ value = [_canonical_result(graph, edges[0].source.node_id, item) for item in value]+ # Collect aggregates independent sources, so only its outer item order is unspecified.+ return tuple(sorted(value, key=repr))+ if isinstance(node, IfInvocation):+ branch_edges = graph._get_input_edges(node_id, "true_input") + graph._get_input_edges(node_id, "false_input")+ if any(isinstance(graph.get_node(edge.source.node_id), CollectInvocation) for edge in branch_edges):+ return tuple(sorted(value, key=repr))+ return value+++def _normalize_collect_fed_iterate_permutations(+ graph: Graph,+ state: GraphExecutionState,+ outputs: dict[str, list[tuple[tuple[int, ...], Any]]],+ execution_ids: dict[str, list[str]],+) -> dict[str, list[tuple[tuple[int, ...], Any]]]:+ """Normalize only frame-to-value assignments on axes fed by Collect item order."""+ collect_fed_iterators = {+ edge.destination.node_id+ for edge in graph.edges+ if edge.destination.field == "collection"+ and isinstance(graph.get_node(edge.source.node_id), CollectInvocation)+ and isinstance(graph.get_node(edge.destination.node_id), IterateInvocation)+ }+ if not collect_fed_iterators:+ return outputs++ execution_graph = state._get_execution_graph_flat()+ for node_id, executions in outputs.items():+ grouped_positions: dict[tuple[int, tuple[int, ...], tuple[int, ...]], list[int]] = {}+ for position, (path, _) in enumerate(executions):+ execution_id = execution_ids[node_id][position]+ matching_axis_indices: set[int] = set()+ for iterator_id in sorted(collect_fed_iterators):+ pending = list(execution_graph.predecessors(execution_id))+ visited: set[str] = set()+ while pending:+ candidate_id = pending.pop()+ if candidate_id in visited:+ continue+ visited.add(candidate_id)+ candidate_node = state.execution_graph.get_node(candidate_id)+ if (+ state.prepared_source_mapping.get(candidate_id) == iterator_id+ and isinstance(candidate_node, IterateInvocation)+ and candidate_node.index >= 0+ ):+ iteration_path = state._get_iteration_path(candidate_id)+ if len(iteration_path) <= len(path) and path[: len(iteration_path)] == iteration_path:+ matching_axis_indices.add(len(iteration_path) - 1)+ pending.extend(execution_graph.predecessors(candidate_id))++ for axis_index in matching_axis_indices:+ frame_without_axis = path[:axis_index], path[axis_index + 1 :]+ grouped_positions.setdefault((axis_index, *frame_without_axis), []).append(position)++ if grouped_positions:+ normalized_executions = list(executions)+ for (axis_index, _, _), positions in grouped_positions.items():+ ordered_positions = sorted(+ positions, key=lambda position: (executions[position][0][axis_index], position)+ )+ ordered_values = sorted((executions[position][1] for position in positions), key=repr)+ for position, value in zip(ordered_positions, ordered_values, strict=True):+ normalized_executions[position] = (executions[position][0], value)+ executions[:] = normalized_executions++ return outputs+++_ReloadObservation = tuple[str, tuple[int, ...], tuple[str, ...] | None, Any]+_RawOutputObservation = tuple[str, tuple[int, ...], Any]+++def _get_reload_observations(state: GraphExecutionState, graph: Graph) -> tuple[_ReloadObservation, ...]:+ registry = state._prepared_registry()+ observations = []+ for exec_id, source_id in state.prepared_source_mapping.items():+ result = state.results.get(exec_id)+ value = None+ if result is not None and isinstance(graph.get_node(source_id), (CollectInvocation, IfInvocation)):+ value = getattr(result, "collection", getattr(result, "value", getattr(result, "item", None)))+ value = _canonical_result(graph, source_id, value)+ observations.append(+ (source_id, state._get_iteration_path(exec_id), registry.get_iteration_axes(exec_id), value)+ )+ return tuple(sorted(observations, key=repr))+++def _assert_v2_reload_observations_preserve_known_axes(+ intact: tuple[_ReloadObservation, ...], reconstructed: tuple[_ReloadObservation, ...]+) -> None:+ def signatures(observations: tuple[_ReloadObservation, ...]):+ rows: Counter[tuple[str, tuple[int, ...], str]] = Counter()+ axes_by_row: dict[tuple[str, tuple[int, ...], str], Counter[tuple[str, ...]]] = defaultdict(Counter)+ for source_id, path, axes, result in observations:+ row = (source_id, path, repr(result))+ rows[row] += 1+ if axes is not None:+ axes_by_row[row][axes] += 1+ return rows, axes_by_row++ intact_rows, intact_axes = signatures(intact)+ reconstructed_rows, reconstructed_axes = signatures(reconstructed)+ assert intact_rows == reconstructed_rows+ for row, axes in intact_axes.items():+ assert not axes - reconstructed_axes[row], f"known axes changed for {row}: {axes} -> {reconstructed_axes[row]}"+++def _run(+ seed: int,+ *,+ forced_compatibility: bool,+ roundtrip_at: int | None,+ omit_prepared_iteration_axes: bool = False,+ capture_reload_observations: bool = False,+) -> (+ dict[str, list[tuple[tuple[int, ...], Any]]]+ | tuple[+ tuple[_ReloadObservation, ...],+ tuple[_RawOutputObservation, ...],+ dict[str, list[tuple[tuple[int, ...], Any]]],+ ]+):+ desc, graph_factory = build(seed)+ graph = graph_factory()+ state = GraphExecutionState(graph=graph)+ if forced_compatibility:+ state._execution_scheduler = _ExecutionScheduler(state)+ selected_route = state._scheduler()+ route_type = type(selected_route)+ trace: list[tuple[str, tuple[int, ...]]] = []+ completed_before_reload: set[str] = set()+ reloaded = False+ reload_observations: tuple[_ReloadObservation, ...] = ()+ try:+ for step in range(2000):+ if roundtrip_at == step:+ completed_before_reload = set(state.results)+ reloaded = True+ snapshot = json.loads(json.dumps(dump_execution_state(state)))+ if omit_prepared_iteration_axes:+ snapshot.pop("prepared_iteration_axes", None)+ snapshot["execution_state_version"] = 2+ state = load_execution_state(snapshot)+ if omit_prepared_iteration_axes:+ assert dump_execution_state(state)["execution_state_version"] == 3+ if capture_reload_observations:+ reload_observations = _get_reload_observations(state, graph)+ state._execution_scheduler = (+ _ExecutionScheduler(state)+ if route_type is _ExecutionScheduler+ else _GenericGraphSchedulerAdapter(state)+ )+ assert type(state._scheduler()) is route_type+ node = state.next()+ if reloaded:+ assert node is None or node.id not in completed_before_reload, (+ f"seed={seed} graph={desc} route={route_type.__name__} checkpoint={roundtrip_at} "+ f"replayed completed execution {node.id if node else None}"+ )+ if node is None:+ break+ sid = state.prepared_source_mapping[node.id]+ trace.append((sid, state._get_iteration_path(node.id)))+ state.complete(node.id, node.invoke(Mock()))+ else:+ pytest.fail(+ f"seed={seed} graph={desc} route={route_type.__name__} checkpoint={roundtrip_at} exceeded 2000 steps; trace={trace[-30:]}"+ )+ except UnsupportedIfIterationAxesError:+ if trace:+ pytest.fail(+ f"seed={seed} graph={desc} route={route_type.__name__} checkpoint={roundtrip_at} axis rejection after invocation; trace={trace[-30:]}"+ )+ raise+ except Exception as error:+ pytest.fail(+ f"seed={seed} graph={desc} route={route_type.__name__} checkpoint={roundtrip_at} "+ f"raised {type(error).__name__}: {error}; trace={trace[-30:]}"+ )++ assert state.is_complete(), (+ f"seed={seed} graph={desc} route={route_type.__name__} checkpoint={roundtrip_at} stalled; trace={trace[-30:]}"+ )+ assert not state.has_error(), (+ f"seed={seed} graph={desc} route={route_type.__name__} checkpoint={roundtrip_at} ended with execution errors"+ )+ outputs: dict[str, list[tuple[tuple[int, ...], Any]]] = {}+ output_execution_ids: dict[str, list[str]] = {}+ for node_id, node in graph.nodes.items():+ if not isinstance(node, (CollectInvocation, IfInvocation)):+ continue+ executions = []+ for exec_id in state._prepared_registry().get_prepared_ids(node_id):+ if exec_id in state.results:+ result = state.results[exec_id]+ value = getattr(result, "collection", getattr(result, "value", None))+ executions.append(+ (tuple(state._get_iteration_path(exec_id)), _canonical_result(graph, node_id, value), exec_id)+ )+ # Prepared IDs come from a set, so same-path tie order is unspecified.+ executions.sort(key=lambda item: (item[0], repr(item[1])))+ outputs[node_id] = [(path, value) for path, value, _ in executions]+ output_execution_ids[node_id] = [exec_id for _, _, exec_id in executions]+ if capture_reload_observations:+ raw_observations = tuple(+ sorted(+ [(node_id, path, value) for node_id, executions in outputs.items() for path, value in executions],+ key=repr,+ )+ )+ normalized_outputs = _normalize_collect_fed_iterate_permutations(graph, state, outputs, output_execution_ids)+ return reload_observations, raw_observations, normalized_outputs+ return _normalize_collect_fed_iterate_permutations(graph, state, outputs, output_execution_ids)+++ ("seed", "checkpoint"),+ [(1717, 5), (1717, 6), (1717, 10), (2447, 5), (2447, 10), (2704, 5), (2704, 10)],+)[email protected]("forced_compatibility", [False, True], ids=["generic", "compatibility"])+def test_v2_snapshot_without_prepared_iteration_axes_matches_uninterrupted(+ seed: int, checkpoint: int, forced_compatibility: bool+) -> None:+ uninterrupted = _run(seed, forced_compatibility=forced_compatibility, roundtrip_at=None)+ intact_snapshot_observations = _run(+ seed,+ forced_compatibility=forced_compatibility,+ roundtrip_at=checkpoint,+ capture_reload_observations=True,+ )+ missing_axes_snapshot_observations = _run(+ seed,+ forced_compatibility=forced_compatibility,+ roundtrip_at=checkpoint,+ omit_prepared_iteration_axes=True,+ capture_reload_observations=True,+ )++ assert isinstance(intact_snapshot_observations, tuple)+ assert isinstance(missing_axes_snapshot_observations, tuple)+ intact_reload, _, intact_snapshot = intact_snapshot_observations+ missing_axes_reload, _, missing_axes_snapshot = missing_axes_snapshot_observations++ assert intact_snapshot == uninterrupted+ assert missing_axes_snapshot == uninterrupted+ _assert_v2_reload_observations_preserve_known_axes(intact_reload, missing_axes_reload)+++def test_v2_reload_axis_oracle_rejects_named_axis_reordering() -> None:+ intact = (("for1", (0, 0), ("it0", "it1"), None),)+ reordered = (("for1", (0, 0), ("it1", "it0"), None),)+ with pytest.raises(AssertionError, match="known axes changed"):+ _assert_v2_reload_observations_preserve_known_axes(intact, reordered)++[email protected]("forced_compatibility", [False, True], ids=["generic", "compatibility"])+def test_v2_sibling_reiterate_snapshot_preserves_raw_frames_and_axis_metadata(+ forced_compatibility: bool,+) -> None:+ observations = _run(+ 2704,+ forced_compatibility=forced_compatibility,+ roundtrip_at=10,+ omit_prepared_iteration_axes=True,+ capture_reload_observations=True,+ )+ assert isinstance(observations, tuple)+ reload_observations, raw_outputs, _ = observations++ assert reload_observations == (+ ("if", (0,), ("it0",), "F:['c', 'a']"),+ ("it0", (0,), ("it0",), None),+ ("itb", (0,), ("itb",), None),+ ("m1", (0,), ("it0",), None),+ ("m2", (0,), ("it0",), None),+ ("out", (), (), ("F:['c', 'a']", "np")),+ ("rit", (0,), ("rit",), None),+ ("rit", (1,), ("rit",), None),+ ("sbs", (), (), None),+ ("src", (), (), None),+ ("sx", (0,), ("itb",), None),+ )+ assert raw_outputs == (+ ("if", (0,), "F:['c', 'a']"),+ ("out", (), ("F:['c', 'a']", "np")),+ ("out2", (), ("RR", "RR")),+ ("rif", (0,), "RR"),+ ("rif", (1,), "RR"),+ )++[email protected]("seed", range(3000), ids=lambda seed: f"seed{seed}")+def test_execution_engine_fuzz_routes_and_snapshots(seed: int) -> None:+ try:+ desc, graph_factory = build(seed)+ graph_factory().validate_self()+ except UnsupportedIfIterationAxesError as error:+ if seed in _KNOWN_VALID_SEEDS:+ pytest.fail(f"seed={seed} graph={desc}: known-valid seed rejected before invocation: {error}")+ pytest.skip(f"seed={seed} graph={desc}: expected pre-invocation axis rejection: {error}")++ results = {}+ for forced in (False, True):+ for checkpoint in (None, 3, 4, 5):+ route_name = "compat" if forced else "auto"+ try:+ results[(route_name, checkpoint)] = _run(seed, forced_compatibility=forced, roundtrip_at=checkpoint)+ except UnsupportedIfIterationAxesError as error:+ if seed in _KNOWN_VALID_SEEDS:+ pytest.fail(+ f"seed={seed} graph={desc} route={route_name} checkpoint={checkpoint}: "+ f"known-valid seed rejected before invocation: {error}"+ )+ pytest.skip(+ f"seed={seed} graph={desc} route={route_name} checkpoint={checkpoint}: "+ f"expected pre-invocation axis rejection: {error}"+ )++ reference = results[("auto", None)]+ if seed == 1681:+ expected = {+ "out": [((0,), ()), ((1,), ("S:['Fa', 'Fb']", "T:['a', 'b']"))],+ "out2": [((0,), ()), ((1,), ("rS:['Fa', 'Fb']", "rT:['a', 'b']"))],+ "if": [((1, 0), "T:['a', 'b']")],+ }+ canary = {node_id: reference[node_id] for node_id in expected}+ assert canary == expected, (+ f"seed=1681 graph={desc}: expected duplicate-sensitive per-execution result {expected}, got {canary}"+ )++ for key, result in results.items():+ assert result == reference, f"seed={seed} graph={desc} route={key}: expected {reference}, got {result}"+++def test_seed_2220_rejects_unsupported_axes_before_invocation() -> None:+ with pytest.raises(UnsupportedIfIterationAxesError):+ _run(2220, forced_compatibility=False, roundtrip_at=None)diff --git a/tests/app/services/shared/test_execution_engine_scheduler.py b/tests/app/services/shared/test_execution_engine_scheduler.pyindex 8fae0ab8fd..4ad2195f66 100644--- a/tests/app/services/shared/test_execution_engine_scheduler.py+++ b/tests/app/services/shared/test_execution_engine_scheduler.py@@ -4,6 +4,7 @@ from unittest.mock import Mockimport pytest+from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocationfrom invokeai.app.invocations.collections import CollectionConcatInvocationfrom invokeai.app.invocations.logic import IfInvocationfrom invokeai.app.invocations.math import AddInvocation, MultiplyInvocation@@ -19,6 +20,7 @@ from invokeai.app.services.shared.graph import (Edge,EdgeConnection,Graph,+ GraphExecutionStalledError,GraphExecutionState,IterateInvocation,_ExecutionScheduler,@@ -159,6 +161,36 @@ def test_generic_plan_rejects_malformed_activation_dependency_snapshot() -> NoneExecutionPlan.from_snapshot(snapshot)+def test_graph_state_next_returns_none_while_generic_invocation_is_claimed() -> None:+ graph = Graph()+ graph.add_node(BooleanInvocation(id="only", value=True))+ state = GraphExecutionState(graph=graph)++ node = state.next()+ assert node is not None+ assert isinstance(state._scheduler(), _GenericGraphSchedulerAdapter)+ assert state.next() is None+ assert not state.is_complete()++ state.complete(node.id, node.invoke(Mock()))++ assert state.is_complete()+ assert state.next() is None+++def test_graph_state_next_returns_none_while_waiting_on_workflow_call() -> None:+ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call", workflow_id="workflow"))+ state = GraphExecutionState(graph=graph)++ call = state.next()+ assert isinstance(call, CallSavedWorkflowInvocation)+ state.begin_waiting_on_workflow_call(state.build_workflow_call_frame(call.id, call.workflow_id))++ assert state.next() is None+ assert not state.is_complete()++def test_graph_state_generic_if_readiness_uses_activation_dependency_records(monkeypatch: pytest.MonkeyPatch) -> None:graph = Graph()graph.add_node(BooleanInvocation(id="condition", value=True))@@ -189,12 +221,16 @@ def test_graph_state_generic_if_readiness_uses_activation_dependency_records(monassert condition is not Nonestate.complete(condition.id, condition.invoke(Mock()))- while "true_value" not in state.source_prepared_mapping:+ while not {"true_value", "false_value"}.issubset(state.source_prepared_mapping):assert state._materializer().prepare(state._get_source_graph_flat()) is not Nonetrue_exec_id = next(iter(state.source_prepared_mapping["true_value"]))plan_node = state._generic_graph_scheduler._scheduler.plan.nodes[true_exec_id]assert plan_node.activation_dependencies == (ActivationDependency(owner_id="if", branch="true_input", frame=()),)- assert state.source_prepared_mapping["false_value"] == set()+ false_exec_id = next(iter(state.source_prepared_mapping["false_value"]))+ false_plan_node = state._generic_graph_scheduler._scheduler.plan.nodes[false_exec_id]+ assert false_plan_node.activation_dependencies == (+ ActivationDependency(owner_id="if", branch="false_input", frame=()),+ )if_exec_id = next(execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "if"@@ -225,7 +261,8 @@ def test_graph_state_generic_if_readiness_uses_activation_dependency_records(monmonkeypatch.setattr(GraphExecutionState, "_is_deferred_by_unresolved_if", fail_if_topology_is_consulted)state._generic_graph_scheduler._scheduler.rebuild_ready()- assert state.next() is None+ with pytest.raises(GraphExecutionStalledError, match="no invocation is ready or in flight"):+ state.next()stale_token = activation_token.model_copy(update={"reference_id": "stale-reference"})state.execution_tokens[activation_token_id] = stale_token@@ -294,8 +331,8 @@ def test_graph_state_rehydrates_legacy_if_without_activation_token() -> None:def test_graph_state_loads_legacy_if_with_prepared_skipped_branch() -> None:graph = Graph()graph.add_node(BooleanInvocation(id="condition", value=False))- graph.add_node(AddInvocation(id="true_value", a=2, b=2))graph.add_node(AddInvocation(id="false_value", a=3, b=3))+ graph.add_node(AddInvocation(id="true_value", a=2, b=2))graph.add_node(IfInvocation(id="if"))graph.add_edge(Edge(@@ -317,8 +354,10 @@ def test_graph_state_loads_legacy_if_with_prepared_skipped_branch() -> None:)state = GraphExecutionState(graph=graph)+ state.set_ready_order([BooleanInvocation])condition = state.next()assert condition is not None+ assert state.prepared_source_mapping[condition.id] == "condition"state.complete(condition.id, condition.invoke(Mock()))selected_branch = state.next()assert selected_branch is not None@@ -326,10 +365,13 @@ def test_graph_state_loads_legacy_if_with_prepared_skipped_branch() -> None:assert state.prepared_source_mapping[selected_branch_exec_id] == "false_value"# Recreate the prepared/skipped branch projection written by the legacy If scheduler.- skipped_exec_id = state._materializer().create_execution_node(- "true_value", [], iteration_path=(), enforce_admission=False- )[0]+ [skipped_exec_id] = state.source_prepared_mapping["true_value"]+ # Fresh If execution eagerly prepares both branches; recreate the old snapshot metadata explicitly.+ state._set_prepared_exec_state(skipped_exec_id, "skipped")assert state._get_prepared_exec_metadata(skipped_exec_id).state == "skipped"+ if_exec_id = next(iter(state.source_prepared_mapping.get("if", ())), None)+ if if_exec_id is None:+ [if_exec_id] = state._materializer().create_execution_node("if", [], iteration_path=(), enforce_admission=False)snapshot = dump_execution_state(state)snapshot.pop("execution_state_version")@@ -343,6 +385,16 @@ def test_graph_state_loads_legacy_if_with_prepared_skipped_branch() -> None:destination=EdgeConnection(node_id=if_exec_id, field="true_input"),).model_dump(mode="json"))+ snapshot["execution_graph"]["edges"].extend(+ Edge(+ source=EdgeConnection(node_id=source_exec_id, field=source_field),+ destination=EdgeConnection(node_id=if_exec_id, field=destination_field),+ ).model_dump(mode="json")+ for source_exec_id, source_field, destination_field in (+ (next(iter(state.source_prepared_mapping["condition"])), "value", "condition"),+ (selected_branch_exec_id, "value", "false_input"),+ )+ )restored = load_execution_state(snapshot)@@ -357,6 +409,17 @@ def test_graph_state_loads_legacy_if_with_prepared_skipped_branch() -> None:assert next_node.id == selected_branch_exec_idassert restored.prepared_source_mapping[next_node.id] == "false_value"+ resumed_sources = [restored.prepared_source_mapping[next_node.id]]+ restored.complete(next_node.id, next_node.invoke(Mock()))+ while (next_node := restored.next()) is not None:+ resumed_sources.append(restored.prepared_source_mapping[next_node.id])+ restored.complete(next_node.id, next_node.invoke(Mock()))++ assert resumed_sources == ["false_value", "if"]+ if_exec_id = next(iter(restored.source_prepared_mapping["if"]))+ assert restored.results[if_exec_id].value == 6+ assert restored.is_complete()+def test_generic_scheduler_discarded_claim_is_not_requeued() -> None:plan = ExecutionPlan()@@ -720,11 +783,8 @@ def test_graph_state_if_uses_generic_activation_routing() -> None:completed_sources = {source_id for exec_node_id, source_id in state.prepared_source_mapping.items() if exec_node_id in state.results}- assert completed_sources == {- "condition",- "true_value",- "if",- }+ assert completed_sources == {"condition", "true_value", "if"}+ assert "false_value" not in completed_sources@pytest.mark.parametrize("condition", [False, True])@@ -769,8 +829,12 @@ def test_graph_state_compatibility_if_uses_opaque_activation_routing(trace.append(state.prepared_source_mapping[node.id])state.complete(node.id, node.invoke(Mock()))- selected_value = "true_value" if condition else "false_value"- assert trace == ["condition", selected_value, "if"]+ assert trace[0] == "condition"+ selected_branch = "true_value" if condition else "false_value"+ unselected_branch = "false_value" if condition else "true_value"+ assert set(trace) == {"condition", selected_branch, "if"}+ assert trace.index(selected_branch) < trace.index("if")+ assert unselected_branch not in traceassert state.is_complete()assert deleted_edges == []@@ -822,7 +886,7 @@ def test_graph_state_if_generic_and_legacy_paths_have_matching_completion() -> Nassert generic_completed == legacy_completed == {"condition", "false_value", "if"}-def test_graph_state_if_rehydrates_discarded_unselected_branch() -> None:+def test_graph_state_if_rehydrates_selected_branch() -> None:graph = Graph()graph.add_node(BooleanInvocation(id="condition", value=False))graph.add_node(AddInvocation(id="true_value", a=2, b=2))@@ -853,17 +917,17 @@ def test_graph_state_if_rehydrates_discarded_unselected_branch() -> None:assert state.prepared_source_mapping[condition.id] == "condition"state.complete(condition.id, condition.invoke(Mock()))- selected_branch = state.next()- assert selected_branch is not None- selected_branch_exec_id = selected_branch.id- assert state.prepared_source_mapping[selected_branch_exec_id] == "false_value"- assert state.source_prepared_mapping["true_value"] == set()+ first_branch = state.next()+ assert first_branch is not None+ first_branch_exec_id = first_branch.id+ assert state.prepared_source_mapping[first_branch_exec_id] == "false_value"+ assert not any(exec_id in state.results for exec_id in state.source_prepared_mapping.get("true_value", ()))restored = GraphExecutionState.model_validate(state.model_dump(mode="python"), strict=False)next_node = restored.next()assert next_node is not None- assert next_node.id == selected_branch_exec_id+ assert next_node.id == first_branch_exec_idassert restored.prepared_source_mapping[next_node.id] == "false_value"diff --git a/tests/app/services/shared/test_execution_engine_stall_regressions.py b/tests/app/services/shared/test_execution_engine_stall_regressions.pynew file mode 100644index 0000000000..fc2c4304e1--- /dev/null+++ b/tests/app/services/shared/test_execution_engine_stall_regressions.py@@ -0,0 +1,291 @@+"""Small semantic regressions distilled from the execution-engine fuzzer stalls."""++from __future__ import annotations++import json+from collections.abc import Callable+from typing import Any+from unittest.mock import Mock++import pytest++from invokeai.app.services.shared.execution_state_migration import dump_execution_state, load_execution_state+from invokeai.app.services.shared.graph import (+ GraphExecutionState,+ _ExecutionScheduler,+ _GenericGraphSchedulerAdapter,+)+from tests.app.services.shared.test_execution_engine_fuzz import build+++def _run_seed(+ seed: int,+ *,+ compatibility: bool,+ checkpoint: int | None,+ checkpoint_when: Callable[[GraphExecutionState], bool] | None = None,+ checkpoint_observer: Callable[[GraphExecutionState], None] | None = None,+ completion_observer: Callable[[GraphExecutionState], None] | None = None,+) -> dict[str, list[tuple[tuple[int, ...], Any]]]:+ _, graph_factory = build(seed)+ state = GraphExecutionState(graph=graph_factory())+ if compatibility:+ state._execution_scheduler = _ExecutionScheduler(state)+ route_type = type(state._scheduler())++ checkpointed = False+ for step in range(500):+ if not checkpointed and (checkpoint == step or (checkpoint_when is not None and checkpoint_when(state))):+ checkpointed = True+ state = load_execution_state(json.loads(json.dumps(dump_execution_state(state))))+ state._execution_scheduler = (+ _ExecutionScheduler(state)+ if route_type is _ExecutionScheduler+ else _GenericGraphSchedulerAdapter(state)+ )+ if checkpoint_observer is not None:+ checkpoint_observer(state)+ node = state.next()+ if node is None:+ break+ state.complete(node.id, node.invoke(Mock()))++ assert checkpoint_when is None or checkpointed, "semantic checkpoint was never reached"+ assert state.is_complete(), f"seed={seed} route={route_type.__name__} stopped before source completion"+ if completion_observer is not None:+ completion_observer(state)+ outputs: dict[str, list[tuple[tuple[int, ...], Any]]] = {}+ for source_id in ("if", "out", "out2"):+ executions = []+ for exec_id, prepared_source_id in state.prepared_source_mapping.items():+ if prepared_source_id != source_id or exec_id not in state.results:+ continue+ result = state.results[exec_id]+ value = getattr(result, "collection", getattr(result, "value", None))+ executions.append((state._get_iteration_path(exec_id), value))+ outputs[source_id] = sorted(executions)+ return outputs+++_ROOT_IF_BRANCH_ITEMS: dict[int, list[tuple[tuple[int, ...], list[list[str]]]]] = {+ # These are the values collected by the selected nested branch for each root If frame.+ 2394: [((0, 0), [["c"], [], ["b", "c"]]), ((0, 1), [["c", "b"]])],+ 1728: [((0, 0), []), ((0, 1), [["", "a"]]), ((0, 2), [[]])],+ 2775: [+ ((0, 0), [[""]]),+ ((0, 1), [["c"], ["", "a", "a"], ["c"]]),+ ((1,), []),+ ((2, 0), [["c"], ["b"]]),+ ((2, 1), [["a"]]),+ ],+}+_ROOT_IF_OTHER_COLLECT_VALUES: dict[int, Any] = {2394: "S", 1728: ["Fu"], 2775: "S"}+++def _expected_root_if_outputs(seed: int) -> list[tuple[tuple[int, ...], str]]:+ _, graph_factory = build(seed)+ graph = graph_factory()+ condition_edge = graph._get_input_edges("if", "condition")[0]+ condition = graph.get_node(condition_edge.source.node_id).value+ selected_field = "true_input" if condition else "false_input"+ selected_branch_edge = graph._get_input_edges("if", selected_field)[0]+ marker = graph.get_node(selected_branch_edge.source.node_id).marker+ return [+ (path, f"{marker}{[f'x{item}' for item in branch_items]}") for path, branch_items in _ROOT_IF_BRANCH_ITEMS[seed]+ ]+++def _assert_out_collect_uses_matching_if_frames(+ state: GraphExecutionState, expected_paths: list[tuple[int, ...]]+) -> None:+ if_exec_ids_by_path: dict[tuple[int, ...], list[str]] = {}+ for exec_id in state.source_prepared_mapping["if"]:+ if_exec_ids_by_path.setdefault(state._get_iteration_path(exec_id), []).append(exec_id)+ assert set(if_exec_ids_by_path) == set(expected_paths)+ assert all(len(exec_ids) == 1 for exec_ids in if_exec_ids_by_path.values())++ out_exec_ids = state.source_prepared_mapping["out"]+ assert sorted(state._get_iteration_path(exec_id) for exec_id in out_exec_ids) == sorted(expected_paths)+ for out_exec_id in out_exec_ids:+ out_path = state._get_iteration_path(out_exec_id)+ if_edges = [+ edge+ for edge in state.execution_graph._get_input_edges(out_exec_id)+ if edge.destination.field == "item" and state.prepared_source_mapping.get(edge.source.node_id) == "if"+ ]+ assert len(if_edges) == 1+ assert if_edges[0].source.node_id == if_exec_ids_by_path[out_path][0]++[email protected]("compatibility", [False, True], ids=["auto", "compatibility"])[email protected]("resume", [False, True], ids=["fresh", "partial-expansion-checkpoint"])[email protected]("seed", [2394, 1728, 2775], ids=lambda seed: f"seed-{seed}")+def test_root_if_expansion_preserves_collect_groups(compatibility: bool, resume: bool, seed: int) -> None:+ expected_if = _expected_root_if_outputs(seed)+ expected_paths = [path for path, _ in expected_if]++ def has_partial_expansion(state: GraphExecutionState) -> bool:+ prepared_if_ids = state.source_prepared_mapping.get("if", ())+ prepared_paths = {state._get_iteration_path(exec_id) for exec_id in prepared_if_ids}+ completed_count = sum(exec_id in state.results for exec_id in prepared_if_ids)+ return prepared_paths == set(expected_paths) and 0 < completed_count < len(expected_paths)++ def check_partial_expansion(state: GraphExecutionState) -> None:+ assert has_partial_expansion(state)+ if state.source_prepared_mapping.get("out"):+ _assert_out_collect_uses_matching_if_frames(state, expected_paths)++ outputs = _run_seed(+ seed,+ compatibility=compatibility,+ checkpoint=None,+ checkpoint_when=has_partial_expansion if resume else None,+ checkpoint_observer=check_partial_expansion if resume else None,+ completion_observer=lambda state: _assert_out_collect_uses_matching_if_frames(state, expected_paths),+ )++ assert outputs["if"] == expected_if+ expected_out_value = _ROOT_IF_OTHER_COLLECT_VALUES[seed]+ assert outputs["out"] == [(path, [expected_out_value, value]) for path, value in expected_if]++[email protected]("compatibility", [False, True], ids=["auto", "compatibility"])[email protected]("checkpoint", [None, 5], ids=["fresh", "resume-after-iteration-preparation"])+def test_root_condition_selects_each_collected_frame(compatibility: bool, checkpoint: int | None) -> None:+ outputs = _run_seed(3, compatibility=compatibility, checkpoint=checkpoint)++ assert outputs["if"] == [+ ((0,), "T:[\"x['']\", \"x['c', 'a']\"]"),+ ((1,), "T:['x[]', \"x['', 'b']\"]"),+ ]++[email protected]("compatibility", [False, True], ids=["auto", "compatibility"])[email protected]("checkpoint", [3, 5], ids=["before-empty-parent-input", "after-empty-parent-input"])+def test_per_item_if_broadcasts_eager_collected_branches(compatibility: bool, checkpoint: int | None) -> None:+ def check_empty_parent_anchor(state: GraphExecutionState) -> None:+ results = [+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state.source_prepared_mapping["cc0"]+ if exec_id in state.results+ ]+ assert sorted(results) == [((0,), [["b", "a"]]), ((1,), [])]++ outputs = _run_seed(+ 233,+ compatibility=compatibility,+ checkpoint=checkpoint,+ checkpoint_observer=check_empty_parent_anchor if checkpoint == 5 else None,+ )++ true_items = ["x[['b', 'a']]", "x[]"]+ true_value = f"T:{true_items}"+ false_value = [["x['b', 'a']"], []]+ assert outputs["if"] == [((0,), true_value), ((1,), false_value)]+ expected_items = ["S:[\"x['b', 'a']\"]", true_value, "S:[]", false_value]+ assert len(outputs["out"]) == 1 and outputs["out"][0][0] == ()+ assert sorted(outputs["out"][0][1], key=repr) == sorted(expected_items, key=repr)+ assert outputs["out2"] == [((), [outputs["out"][0][1]])]++[email protected]("compatibility", [False, True], ids=["auto", "compatibility"])[email protected]("checkpoint", ["fresh", "resumed", "after-parent-collections"])+def test_nested_per_item_if_broadcasts_eager_collect_results_and_resumes(compatibility: bool, checkpoint: str) -> None:+ def parent_inputs_completed(state: GraphExecutionState) -> bool:+ return all(+ source_id in state.executed+ and state.source_prepared_mapping.get(source_id)+ and all(exec_id in state.results for exec_id in state.source_prepared_mapping[source_id])+ for source_id in ("cc1", "sx")+ )++ def check_parent_inputs(state: GraphExecutionState) -> None:+ assert sorted(+ (state._get_iteration_path(exec_id), state.results[exec_id].collection)+ for exec_id in state.source_prepared_mapping["cc1"]+ ) == [((0, 0), []), ((0, 1), [["a"], ["c", "b"], []])]+ assert [+ (state._get_iteration_path(exec_id), state.results[exec_id].value)+ for exec_id in state.source_prepared_mapping["sx"]+ ] == [((0,), "np")]++ outputs = _run_seed(+ 2057,+ compatibility=compatibility,+ checkpoint=5 if checkpoint == "resumed" else None,+ checkpoint_when=parent_inputs_completed if checkpoint == "after-parent-collections" else None,+ checkpoint_observer=check_parent_inputs if checkpoint == "after-parent-collections" else None,+ )++ branch_value = [[], ["x['a']", "x['c', 'b']", "x[]"]]+ assert outputs["if"] == [((0, 0), branch_value), ((0, 1), branch_value)]+ assert outputs["out"][0] == ((), ["np"])+ expected_nested_items = [branch_value, branch_value]+ assert outputs["out"][1][0] == (0,)+ assert sorted(outputs["out"][1][1], key=repr) == sorted(expected_nested_items, key=repr)+ assert outputs["out2"][0][0] == ()+ assert sorted(outputs["out2"][0][1], key=repr) == sorted([["np"], outputs["out"][1][1]], key=repr)++[email protected]("compatibility", [False, True], ids=["auto", "compatibility"])[email protected]("checkpoint", [None, 5], ids=["fresh", "resumed"])+def test_empty_if_frames_retire_and_finish_downstream_collects(compatibility: bool, checkpoint: int | None) -> None:+ outputs = _run_seed(2575, compatibility=compatibility, checkpoint=checkpoint)++ assert outputs["out"] == [((), ["np"]), ((0,), []), ((1,), [])]+++ ("seed", "expected"),+ [+ (880, [((), ["S:[]"])]),+ (992, [((0,), [["Fu"]])]),+ ],+ ids=["empty-iterate-branch", "empty-iterate-nested-collect"],+)[email protected]("compatibility", [False, True], ids=["auto", "compatibility"])[email protected]("checkpoint", [None, 5], ids=["fresh", "resumed"])+def test_empty_iterate_frames_retire_before_downstream_collect(+ seed: int,+ expected: list[tuple[tuple[int, ...], Any]],+ compatibility: bool,+ checkpoint: int | None,+) -> None:+ outputs = _run_seed(seed, compatibility=compatibility, checkpoint=checkpoint)++ assert outputs["out"] == expected++[email protected]("compatibility", [False, True], ids=["auto", "compatibility"])+def test_nested_if_branch_completion_reaches_downstream_collect(compatibility: bool) -> None:+ outputs = _run_seed(573, compatibility=compatibility, checkpoint=4)++ # The selected true branch comes from an empty Iterate; the J input is unselected.+ assert outputs["if"] == []+ assert outputs["out"] == [((), [])]++[email protected]("compatibility", [False, True], ids=["auto", "compatibility"])[email protected]("checkpoint", [None, 5], ids=["fresh", "resumed"])+def test_root_condition_expands_partial_frames_from_completed_branch(+ compatibility: bool, checkpoint: int | None+) -> None:+ outputs = _run_seed(1331, compatibility=compatibility, checkpoint=checkpoint)++ assert outputs["if"] == [+ ((0, 0), "T:bT:[\"x['c']\", \"x['', 'c']\"]"),+ ((1, 0), "T:bT:[\"x['a', 'a']\", \"x['b', 'a', 'c']\", \"x['b']\"]"),+ ]++[email protected]("compatibility", [False, True], ids=["auto", "compatibility"])[email protected]("checkpoint", [None, 15], ids=["fresh", "blocked-frame-resume"])+def test_nested_if_activation_uses_matching_axis_frame(compatibility: bool, checkpoint: int | None) -> None:+ outputs = _run_seed(1836, compatibility=compatibility, checkpoint=checkpoint)+ selected_value = "bT:[\"F['c']\"]"++ assert outputs == {+ "if": [((0, 0), selected_value)],+ "out": [((0,), ["S", selected_value]), ((1,), ["S"])],+ "out2": [((), [["S", selected_value], ["S"]])],+ }diff --git a/tests/app/services/shared/test_for_scheduler_performance.py b/tests/app/services/shared/test_for_scheduler_performance.pyindex a5ccc3a12f..c7f010be2b 100644--- a/tests/app/services/shared/test_for_scheduler_performance.py+++ b/tests/app/services/shared/test_for_scheduler_performance.py@@ -5,6 +5,7 @@ Optional absolute-time benchmarks remain marked `slow`."""import gc+import sysimport timefrom collections.abc import Callablefrom unittest.mock import Mock@@ -12,7 +13,7 @@ from unittest.mock import Mockimport networkx as nximport pytest-from invokeai.app.invocations.collections import RangeInvocation+from invokeai.app.invocations.collections import CollectionConcatInvocation, RangeInvocationfrom invokeai.app.invocations.logic import IfInvocationfrom invokeai.app.invocations.loops import ForInvocation, ForReturnInvocationfrom invokeai.app.invocations.primitives import BooleanInvocation@@ -26,6 +27,8 @@ from invokeai.app.services.shared.graph import (_GenericGraphSchedulerAdapter,)from invokeai.app.services.shared.graph_loop_topology import LoopTopology+from invokeai.app.services.shared.graph_materializer import _ExecutionNodeBuilder+from invokeai.app.services.shared.graph_runtime_records import _PreparedExecRegistryfrom tests.test_nodes import (AnyTypeTestInvocation,FixedCollectionTestInvocation,@@ -101,6 +104,20 @@ class _CountingSet(set[str]):yield value+class _CountingTuple(tuple):+ def __new__(cls, values, slices: list[int]):+ instance = super().__new__(cls, values)+ instance.slices = slices+ return instance++ def __getitem__(self, key):+ value = super().__getitem__(key)+ if isinstance(key, slice):+ self.slices[0] += 1+ return _CountingTuple(value, self.slices)+ return value++def _run_trivial_loop(loop_type: str,count: int,@@ -512,6 +529,179 @@ def test_loop_scheduler_mapping_visits_scale_linearly()[email protected]_independent+def test_collect_reiteration_grouping_slices_scale_linearly(monkeypatch: pytest.MonkeyPatch) -> None:+ slices_by_count: dict[int, int] = {}+ group_input_checks_by_count: dict[int, int] = {}+ original_path = _ExecutionNodeBuilder._get_prepared_edge_iteration_path+ original_axes = _ExecutionNodeBuilder._get_prepared_edge_iteration_axes++ for count in (24, 48):+ slices = [0]++ def counted_path(self, edge, prepared_id, slices=slices):+ return _CountingTuple(original_path(self, edge, prepared_id), slices)++ def counted_axes(self, edge, prepared_id, slices=slices):+ return _CountingTuple(original_axes(self, edge, prepared_id), slices)++ monkeypatch.setattr(_ExecutionNodeBuilder, "_get_prepared_edge_iteration_path", counted_path)+ monkeypatch.setattr(_ExecutionNodeBuilder, "_get_prepared_edge_iteration_axes", counted_axes)++ graph = Graph()+ graph.add_node(RangeInvocation(id="range", start=0, stop=count))+ graph.add_node(IterateInvocation(id="outer"))+ graph.add_node(FixedCollectionTestInvocation(id="inner_source"))+ graph.add_node(IterateInvocation(id="inner"))+ graph.add_node(CollectInvocation(id="parent_collect"))+ graph.add_node(IterateInvocation(id="reiterate"))+ graph.add_node(CollectInvocation(id="final_collect"))+ graph.add_node(AnyTypeTestInvocation(id="sink"))+ graph.add_edge(create_edge("range", "collection", "outer", "collection"))+ graph.add_edge(create_edge("outer", "item", "inner_source", "value"))+ graph.add_edge(create_edge("inner_source", "collection", "inner", "collection"))+ graph.add_edge(create_edge("inner", "item", "parent_collect", "item"))+ graph.add_edge(create_edge("parent_collect", "collection", "reiterate", "collection"))+ graph.add_edge(create_edge("reiterate", "item", "final_collect", "item"))+ graph.add_edge(create_edge("final_collect", "collection", "sink", "value"))+ state = GraphExecutionState(graph=graph)+ group_input_checks = [0]++ def count_group_input_checks(frame, event, arg, group_input_checks=group_input_checks):+ if event == "call" and frame.f_code.co_name == "matches_group":+ group_input_checks[0] += 1++ prior_profile = sys.getprofile()+ sys.setprofile(count_group_input_checks)+ try:+ while (node := state.next()) is not None:+ state.complete(node.id, node.invoke(Mock()))+ finally:+ sys.setprofile(prior_profile)++ assert state.is_complete()+ assert not state.has_error()+ results = [+ state.results[node_id].value+ for node_id in sorted(state.source_prepared_mapping["sink"], key=state._get_iteration_path)+ ]+ assert results == [[0, 1] for _ in range(count)]+ slices_by_count[count] = slices[0]+ group_input_checks_by_count[count] = group_input_checks[0]++ assert slices_by_count[48] < slices_by_count[24] * 3, slices_by_count+ assert group_input_checks_by_count[48] < group_input_checks_by_count[24] * 3, group_input_checks_by_count++[email protected]_independent[email protected]("force_compatibility_scheduler", [False, True])+def test_nested_literal_for_collect_grouping_slices_scale_linearly(+ monkeypatch: pytest.MonkeyPatch, force_compatibility_scheduler: bool+) -> None:+ work_by_count: dict[int, dict[str, int]] = {}+ original_path = _ExecutionNodeBuilder._get_prepared_edge_iteration_path+ original_axes = _ExecutionNodeBuilder._get_prepared_edge_iteration_axes+ original_grouping = _ExecutionNodeBuilder._get_collect_iteration_mapping_groups+ original_overlap = _PreparedExecRegistry.get_prepared_ids_with_overlapping_path+ original_create = _ExecutionNodeBuilder.create_execution_node++ for count in (24, 48):+ slices = [0]+ work = {+ "grouping_calls": 0,+ "grouping_results": 0,+ "overlap_candidates": 0,+ "collect_mapping_calls": 0,+ "collect_mapping_entries": 0,+ }++ def counted_path(self, edge, prepared_id, slices=slices):+ return _CountingTuple(original_path(self, edge, prepared_id), slices)++ def counted_axes(self, edge, prepared_id, slices=slices):+ return _CountingTuple(original_axes(self, edge, prepared_id), slices)++ def counted_grouping(self, input_edges, work=work):+ work["grouping_calls"] += 1+ result = original_grouping(self, input_edges)+ work["grouping_results"] += len(result)+ return result++ def counted_overlap(self, source_node_id, iteration_path, work=work):+ for prepared_id in original_overlap(self, source_node_id, iteration_path):+ work["overlap_candidates"] += 1+ yield prepared_id++ def counted_create(self, node_id, iteration_node_map, *args, work=work, **kwargs):+ if node_id == "collect":+ work["collect_mapping_calls"] += 1+ work["collect_mapping_entries"] += len(iteration_node_map)+ return original_create(self, node_id, iteration_node_map, *args, **kwargs)++ monkeypatch.setattr(_ExecutionNodeBuilder, "_get_prepared_edge_iteration_path", counted_path)+ monkeypatch.setattr(_ExecutionNodeBuilder, "_get_prepared_edge_iteration_axes", counted_axes)+ monkeypatch.setattr(_ExecutionNodeBuilder, "_get_collect_iteration_mapping_groups", counted_grouping)+ monkeypatch.setattr(_PreparedExecRegistry, "get_prepared_ids_with_overlapping_path", counted_overlap)+ monkeypatch.setattr(_ExecutionNodeBuilder, "create_execution_node", counted_create)++ graph = Graph()+ graph.add_node(+ CollectionConcatInvocation(id="source", first=[[f"{index}a", f"{index}b"] for index in range(count)])+ )+ graph.add_node(IterateInvocation(id="outer"))+ graph.add_node(ForInvocation(id="for"))+ graph.add_node(AnyTypeTestInvocation(id="body"))+ graph.add_node(ForReturnInvocation(id="return"))+ graph.add_node(IfInvocation(id="inner_if", condition=True))+ graph.add_node(AnyTypeTestInvocation(id="inner_fallback", value="inner"))+ graph.add_node(IfInvocation(id="outer_if", condition=True))+ graph.add_node(AnyTypeTestInvocation(id="outer_fallback", value="outer"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("source", "collection", "outer", "collection"))+ graph.add_edge(create_edge("outer", "item", "for", "collection"))+ graph.add_edge(create_edge("for", "item", "body", "value"))+ graph.add_edge(create_edge("body", "value", "return", "output"))+ graph.add_edge(create_loop_linkage("for", "return"))+ graph.add_edge(create_edge("for", "output_collection", "inner_if", "true_input"))+ graph.add_edge(create_edge("inner_fallback", "value", "inner_if", "false_input"))+ graph.add_edge(create_edge("inner_if", "value", "outer_if", "true_input"))+ graph.add_edge(create_edge("outer_fallback", "value", "outer_if", "false_input"))+ graph.add_edge(create_edge("outer_if", "value", "collect", "item"))+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)+ while (node := state.next()) is not None:+ state.complete(node.id, node.invoke(Mock()))++ assert state.is_complete()+ assert not state.has_error()+ results = {+ state._get_iteration_path(node_id): state.results[node_id].collection+ for node_id in state.source_prepared_mapping["collect"]+ }+ assert results == {(index,): [[f"{index}a", f"{index}b"]] for index in range(count)}+ work["prepared_for_frames"] = len(state.source_prepared_mapping["for"])+ work["collect_groups"] = len(state.source_prepared_mapping["collect"])+ work["path_axis_slices"] = slices[0]+ work_by_count[count] = work++ assert work_by_count[48]["overlap_candidates"] < work_by_count[24]["overlap_candidates"] * 3, work_by_count+ assert work_by_count[48]["collect_mapping_entries"] < work_by_count[24]["collect_mapping_entries"] * 3, (+ work_by_count+ )+ assert work_by_count[24]["prepared_for_frames"] == 48+ assert work_by_count[48]["prepared_for_frames"] == 96+ assert work_by_count[24]["overlap_candidates"] <= 24 * 4+ assert work_by_count[48]["overlap_candidates"] <= 48 * 4+ assert work_by_count[24]["grouping_calls"] == work_by_count[48]["grouping_calls"] == 3+ assert work_by_count[24]["grouping_results"] == work_by_count[48]["grouping_results"] == 3+ assert work_by_count[24]["collect_groups"] == 24+ assert work_by_count[48]["collect_groups"] == 48+ assert work_by_count[24]["collect_mapping_entries"] == 24+ assert work_by_count[48]["collect_mapping_entries"] == 48+ assert work_by_count[48]["path_axis_slices"] < work_by_count[24]["path_axis_slices"] * 3, work_by_count++def test_prepared_execution_count_scans_each_source_once() -> None:counter = _MappingTraversalCounter()state = GraphExecutionState(graph=Graph())@@ -668,7 +858,7 @@ def _measure_pending_if_attachment(assert state.is_complete()assert not state.has_error()assert trace.count("true_body") == count- assert "false_body" not in trace+ assert trace.count("false_body") == countassert trace.count("if") == countcollect_exec_ids = state.source_prepared_mapping["collect"]assert len(collect_exec_ids) == 1@@ -750,50 +940,6 @@ def test_completion_cache_preserves_completed_sources_after_restore() -> None:assert restored_state.is_complete()-def test_prepare_retirement_checks_only_activation_dependent_sources() -> None:- graph = Graph()- graph.add_node(BooleanInvocation(id="condition", value=True))- graph.add_node(AnyTypeTestInvocation(id="selected", value=1))- graph.add_node(AnyTypeTestInvocation(id="unselected", value=2))- graph.add_node(IfInvocation(id="if"))- graph.add_edge(create_edge("condition", "value", "if", "condition"))- graph.add_edge(create_edge("selected", "value", "if", "true_input"))- graph.add_edge(create_edge("unselected", "value", "if", "false_input"))- unrelated_source_ids = {f"independent_{index}" for index in range(120)}- for source_id in unrelated_source_ids:- graph.add_node(AnyTypeTestInvocation(id=source_id, value=source_id))-- state = GraphExecutionState(graph=graph)- materializer = state._materializer()- original_candidates = materializer._get_activation_candidate_source_ids- candidate_sources: set[str] = set()- candidate_visits = 0- prepare_scans = 0-- def counted_candidates(source_graph: object) -> tuple[str, ...]:- nonlocal candidate_visits, prepare_scans- candidates = original_candidates(source_graph) # type: ignore[arg-type]- candidate_sources.update(candidates)- candidate_visits += len(candidates)- prepare_scans += 1- return candidates-- materializer._get_activation_candidate_source_ids = counted_candidates # type: ignore[method-assign]- context = Mock()- while (node := state.next()) is not None:- state.complete(node.id, node.invoke(context))-- assert state.is_complete()- assert not state.has_error()- assert state.results[next(iter(state.source_prepared_mapping["if"]))].value == 1- assert "unselected" in state.executed- assert not unrelated_source_ids.intersection(candidate_sources), (- f"retirement candidates included unrelated sources: {unrelated_source_ids.intersection(candidate_sources)}"- )- assert candidate_sources == {"unselected"}- assert candidate_visits <= 2 * prepare_scans--def _measure_if_chain_retirement_candidates(length: int) -> tuple[int, int, int, list[str]]:graph = Graph()graph.add_node(BooleanInvocation(id="condition", value=True))diff --git a/tests/app/services/shared/test_graph_execution_state.py b/tests/app/services/shared/test_graph_execution_state.pynew file mode 100644index 0000000000..7a23790d07--- /dev/null+++ b/tests/app/services/shared/test_graph_execution_state.py@@ -0,0 +1,442 @@+from unittest.mock import Mock++import pytest++from invokeai.app.invocations.logic import IfInvocation+from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation+from invokeai.app.invocations.math import AddInvocation+from invokeai.app.invocations.primitives import BooleanCollectionInvocation, BooleanInvocation+from invokeai.app.services.shared.graph import (+ CollectInvocation,+ Edge,+ EdgeConnection,+ Graph,+ GraphExecutionState,+ InvalidEdgeError,+ IterateInvocation,+)+from tests.test_nodes import AnyTypeTestInvocation, ErrorInvocation, PromptTestInvocation, create_loop_linkage++[email protected]("condition", [False, True])[email protected]("connected_condition", [False, True])+def test_if_executes_both_connected_branches_before_resolving_and_preserves_fanout(+ condition: bool, connected_condition: bool+) -> None:+ graph = Graph()+ graph.add_node(AddInvocation(id="shared", a=2, b=3))+ graph.add_node(AddInvocation(id="true_branch", b=10))+ graph.add_node(AddInvocation(id="false_branch", b=20))+ graph.add_node(IfInvocation(id="if", condition=condition if not connected_condition else False))+ graph.add_node(AddInvocation(id="consumer"))+ if connected_condition:+ graph.add_node(BooleanInvocation(id="condition", value=condition))+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="condition", field="value"),+ destination=EdgeConnection(node_id="if", field="condition"),+ )+ )+ for branch_id, branch_port in (("true_branch", "true_input"), ("false_branch", "false_input")):+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="shared", field="value"),+ destination=EdgeConnection(node_id=branch_id, field="a"),+ )+ )+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id=branch_id, field="value"),+ destination=EdgeConnection(node_id="if", field=branch_port),+ )+ )+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="true_branch", field="value"),+ destination=EdgeConnection(node_id="consumer", field="a"),+ )+ )+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="if", field="value"),+ destination=EdgeConnection(node_id="consumer", field="b"),+ )+ )++ state = GraphExecutionState(graph=graph)+ execution_order: list[str] = []+ while (node := state.next()) is not None:+ source_id = state.prepared_source_mapping[node.id]+ execution_order.append(source_id)+ if source_id == "if":+ assert node.true_input == (15 if condition else None)+ assert node.false_input == (25 if not condition else None)+ state.complete(node.id, node.invoke(Mock()))++ if_index = execution_order.index("if")+ assert execution_order.index("true_branch") < if_index+ assert execution_order.index("false_branch") < if_index+ assert execution_order.count("shared") == 1++ result_by_source = {+ source_id: state.results[execution_id]+ for source_id, execution_ids in state.source_prepared_mapping.items()+ for execution_id in execution_ids+ }+ assert result_by_source["if"].value == (15 if condition else 25)+ assert result_by_source["consumer"].value == (30 if condition else 40)+ assert state.is_complete()++[email protected]("condition", [False, True])+def test_if_resolves_literal_branch_inputs(condition: bool) -> None:+ graph = Graph(nodes={"if": IfInvocation(id="if", condition=condition, true_input=11, false_input=22)})++ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert node is not None+ state.complete(node.id, node.invoke(Mock()))++ assert state.results[node.id].value == (11 if condition else 22)+ assert state.is_complete()+++def test_failure_in_unselected_if_branch_fails_execution() -> None:+ graph = Graph()+ graph.add_node(IfInvocation(id="if", condition=False))+ graph.add_node(ErrorInvocation(id="unselected_failure"))+ graph.add_node(AddInvocation(id="selected", a=4, b=5))+ graph.add_node(PromptTestInvocation(id="external_consumer"))+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="unselected_failure", field="prompt"),+ destination=EdgeConnection(node_id="if", field="true_input"),+ )+ )+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="selected", field="value"),+ destination=EdgeConnection(node_id="if", field="false_input"),+ )+ )+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="unselected_failure", field="prompt"),+ destination=EdgeConnection(node_id="external_consumer", field="prompt"),+ )+ )++ state = GraphExecutionState(graph=graph)+ with pytest.raises(Exception, match="supposed to fail"):+ while (node := state.next()) is not None:+ state.complete(node.id, node.invoke(Mock()))++[email protected](("condition", "expected"), [(True, 17), (False, 27)])+def test_root_if_executes_only_the_selected_private_branch_and_shared_ancestor_once(+ condition: bool, expected: int+) -> None:+ graph = Graph()+ graph.add_node(BooleanInvocation(id="condition", value=condition))+ graph.add_node(AddInvocation(id="shared", a=3, b=4))+ graph.add_node(AddInvocation(id="true_branch", b=10))+ graph.add_node(AddInvocation(id="false_branch", b=20))+ graph.add_node(IfInvocation(id="if"))+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="condition", field="value"),+ destination=EdgeConnection(node_id="if", field="condition"),+ )+ )+ for branch_id, branch_field in (("true_branch", "true_input"), ("false_branch", "false_input")):+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="shared", field="value"),+ destination=EdgeConnection(node_id=branch_id, field="a"),+ )+ )+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id=branch_id, field="value"),+ destination=EdgeConnection(node_id="if", field=branch_field),+ )+ )++ state = GraphExecutionState(graph=graph)+ executed: list[str] = []+ while (node := state.next()) is not None:+ source_id = state.prepared_source_mapping[node.id]+ executed.append(source_id)+ state.complete(node.id, node.invoke(Mock()))++ assert executed.count("shared") == 1+ selected_branch = "true_branch" if condition else "false_branch"+ unselected_branch = "false_branch" if condition else "true_branch"+ assert selected_branch in executed+ assert executed.index("condition") < executed.index(selected_branch)+ assert unselected_branch not in executed+ if_exec_id = next(iter(state.source_prepared_mapping["if"]))+ assert state.results[if_exec_id].value == expected+ assert state.is_complete()+++def test_single_iterate_if_collect_executes_only_selected_branch_per_frame_in_order() -> None:+ graph = Graph()+ graph.add_node(BooleanCollectionInvocation(id="conditions", collection=[True, False, True]))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(BooleanInvocation(id="true_branch"))+ graph.add_node(BooleanInvocation(id="false_branch"))+ graph.add_node(CollectInvocation(id="collect"))+ for source, source_field, destination, destination_field in (+ ("conditions", "collection", "iterate", "collection"),+ ("iterate", "item", "if", "condition"),+ ("iterate", "item", "true_branch", "value"),+ ("true_branch", "value", "if", "true_input"),+ ("iterate", "item", "false_branch", "value"),+ ("false_branch", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ):+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id=source, field=source_field),+ destination=EdgeConnection(node_id=destination, field=destination_field),+ )+ )++ state = GraphExecutionState(graph=graph)+ executed: list[str] = []+ while (node := state.next()) is not None:+ source_id = state.prepared_source_mapping[node.id]+ executed.append(source_id)+ state.complete(node.id, node.invoke(Mock()))++ assert executed.count("conditions") == 1+ assert executed.count("iterate") == 3+ assert executed.count("true_branch") == 2+ assert executed.count("false_branch") == 1+ collect_exec_id = next(iter(state.source_prepared_mapping["collect"]))+ assert state.results[collect_exec_id].collection == [True, False, True]+ assert state.is_complete()+++def test_iterate_if_with_second_collect_consumer_remains_eager() -> None:+ graph = Graph()+ graph.add_node(BooleanCollectionInvocation(id="conditions", collection=[True, False, True]))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(BooleanInvocation(id="true_branch"))+ graph.add_node(BooleanInvocation(id="false_branch"))+ graph.add_node(CollectInvocation(id="collect_a"))+ graph.add_node(CollectInvocation(id="collect_b"))+ for source, source_field, destination, destination_field in (+ ("conditions", "collection", "iterate", "collection"),+ ("iterate", "item", "if", "condition"),+ ("iterate", "item", "true_branch", "value"),+ ("true_branch", "value", "if", "true_input"),+ ("iterate", "item", "false_branch", "value"),+ ("false_branch", "value", "if", "false_input"),+ ("if", "value", "collect_a", "item"),+ ("if", "value", "collect_b", "item"),+ ):+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id=source, field=source_field),+ destination=EdgeConnection(node_id=destination, field=destination_field),+ )+ )++ state = GraphExecutionState(graph=graph)+ executed: list[str] = []+ while (node := state.next()) is not None:+ source_id = state.prepared_source_mapping[node.id]+ executed.append(source_id)+ state.complete(node.id, node.invoke(Mock()))++ assert executed.count("true_branch") == 3+ assert executed.count("false_branch") == 3+ for collect_id in ("collect_a", "collect_b"):+ collect_exec_id = next(iter(state.source_prepared_mapping[collect_id]))+ assert state.results[collect_exec_id].collection == [True, False, True]+ assert state.is_complete()+++def test_nested_ifs_remain_eager() -> None:+ graph = Graph()+ graph.add_node(BooleanInvocation(id="outer_condition", value=True))+ graph.add_node(BooleanInvocation(id="inner_condition", value=False))+ graph.add_node(BooleanInvocation(id="inner_true", value=True))+ graph.add_node(BooleanInvocation(id="inner_false", value=False))+ graph.add_node(BooleanInvocation(id="outer_false", value=False))+ graph.add_node(IfInvocation(id="inner_if"))+ graph.add_node(IfInvocation(id="outer_if"))+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="inner_condition", field="value"),+ destination=EdgeConnection(node_id="inner_if", field="condition"),+ )+ )+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="inner_true", field="value"),+ destination=EdgeConnection(node_id="inner_if", field="true_input"),+ )+ )+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="inner_false", field="value"),+ destination=EdgeConnection(node_id="inner_if", field="false_input"),+ )+ )+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="outer_condition", field="value"),+ destination=EdgeConnection(node_id="outer_if", field="condition"),+ )+ )+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="inner_if", field="value"),+ destination=EdgeConnection(node_id="outer_if", field="true_input"),+ )+ )+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="outer_false", field="value"),+ destination=EdgeConnection(node_id="outer_if", field="false_input"),+ )+ )++ state = GraphExecutionState(graph=graph)+ executed: list[str] = []+ while (node := state.next()) is not None:+ executed.append(state.prepared_source_mapping[node.id])+ state.complete(node.id, node.invoke(Mock()))++ assert {"inner_true", "inner_false", "outer_false"}.issubset(executed)+ assert state.is_complete()+++def test_sibling_ifs_remain_eager() -> None:+ graph = Graph()+ for node_id, value in (+ ("condition_a", True),+ ("condition_b", False),+ ("true_a", True),+ ("false_a", False),+ ("true_b", True),+ ("false_b", False),+ ):+ graph.add_node(BooleanInvocation(id=node_id, value=value))+ graph.add_node(IfInvocation(id="if_a"))+ graph.add_node(IfInvocation(id="if_b"))+ graph.add_node(CollectInvocation(id="collect"))+ for condition, if_id, true_id, false_id in (+ ("condition_a", "if_a", "true_a", "false_a"),+ ("condition_b", "if_b", "true_b", "false_b"),+ ):+ for source_id, source_field, destination_id, destination_field in (+ (condition, "value", if_id, "condition"),+ (true_id, "value", if_id, "true_input"),+ (false_id, "value", if_id, "false_input"),+ (if_id, "value", "collect", "item"),+ ):+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id=source_id, field=source_field),+ destination=EdgeConnection(node_id=destination_id, field=destination_field),+ )+ )++ state = GraphExecutionState(graph=graph)+ executed: list[str] = []+ while (node := state.next()) is not None:+ executed.append(state.prepared_source_mapping[node.id])+ state.complete(node.id, node.invoke(Mock()))++ assert {"true_a", "false_a", "true_b", "false_b"}.issubset(executed)+ collect_exec_id = next(iter(state.source_prepared_mapping["collect"]))+ assert sorted(state.results[collect_exec_id].collection) == [False, True]+ assert state.is_complete()+++def test_if_with_for_axis_remains_eager() -> None:+ graph = Graph()+ graph.add_node(ForInvocation(id="for", collection=[True, False]))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(AnyTypeTestInvocation(id="true_branch"))+ graph.add_node(AnyTypeTestInvocation(id="false_branch"))+ graph.add_node(ForReturnInvocation(id="return"))+ for source_id, source_field, destination_id, destination_field in (+ ("for", "item", "if", "condition"),+ ("for", "item", "true_branch", "value"),+ ("true_branch", "value", "if", "true_input"),+ ("for", "item", "false_branch", "value"),+ ("false_branch", "value", "if", "false_input"),+ ("if", "value", "return", "output"),+ ):+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id=source_id, field=source_field),+ destination=EdgeConnection(node_id=destination_id, field=destination_field),+ )+ )+ graph.add_edge(create_loop_linkage("for", "return"))++ state = GraphExecutionState(graph=graph)+ executed: list[str] = []+ while (node := state.next()) is not None:+ executed.append(state.prepared_source_mapping[node.id])+ state.complete(node.id, node.invoke(Mock()))++ assert executed.count("true_branch") == 2+ assert executed.count("false_branch") == 2+ assert state.is_complete()+++def test_iterate_if_with_unscoped_branch_inputs_remains_eager() -> None:+ graph = Graph()+ graph.add_node(BooleanCollectionInvocation(id="conditions", collection=[True, False]))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(BooleanInvocation(id="true_branch", value=True))+ graph.add_node(BooleanInvocation(id="false_branch", value=False))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(CollectInvocation(id="collect"))+ for source_id, source_field, destination_id, destination_field in (+ ("conditions", "collection", "iterate", "collection"),+ ("iterate", "item", "if", "condition"),+ ("true_branch", "value", "if", "true_input"),+ ("false_branch", "value", "if", "false_input"),+ ("if", "value", "collect", "item"),+ ):+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id=source_id, field=source_field),+ destination=EdgeConnection(node_id=destination_id, field=destination_field),+ )+ )++ state = GraphExecutionState(graph=graph)+ executed: list[str] = []+ while (node := state.next()) is not None:+ executed.append(state.prepared_source_mapping[node.id])+ state.complete(node.id, node.invoke(Mock()))++ assert executed.count("true_branch") == 1+ assert executed.count("false_branch") == 1+ collect_exec_id = next(iter(state.source_prepared_mapping["collect"]))+ assert state.results[collect_exec_id].collection == [True, False]+ assert state.is_complete()+++def test_invalid_edge_still_fails_graph_validation() -> None:+ graph = Graph()+ graph.add_node(BooleanInvocation(id="condition", value=True))+ graph.add_node(IfInvocation(id="if"))+ with pytest.raises(InvalidEdgeError, match="Field types are incompatible"):+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="condition", field="not_an_output"),+ destination=EdgeConnection(node_id="if", field="condition"),+ )+ )diff --git a/tests/app/services/shared/test_graph_if_activation.py b/tests/app/services/shared/test_graph_if_activation.pyindex 150bc985b9..2c3d4ea38f 100644--- a/tests/app/services/shared/test_graph_if_activation.py+++ b/tests/app/services/shared/test_graph_if_activation.py@@ -46,35 +46,13 @@ class _Graph:return self._output_edges.get(node_id, [])-class _Registry:- def get_source_node_id(self, exec_node_id: str) -> str:- return exec_node_id-- def get_prepared_ids(self, source_node_id: str) -> list[str]:- return [source_node_id] if source_node_id == "if" else []--class _State:def __init__(self) -> None:self.graph = _Graph()- self.admitted: set[ActivationDependency] = set()- self.rejected: set[ActivationDependency] = set()-- def _prepared_registry(self) -> _Registry:- return _Registry()-- def _get_iteration_path(self, _: str) -> tuple[int, ...]:- return ()def _get_source_graph_flat(self) -> object:return object()- def _is_activation_dependency_satisfied(self, dependency: ActivationDependency) -> bool:- return dependency in self.admitted-- def _is_activation_dependency_rejected(self, dependency: ActivationDependency) -> bool:- return dependency in self.rejected-@pytest.mark.platform_independentdef test_standalone_import_does_not_import_graph() -> None:@@ -101,7 +79,7 @@ def test_graph_nx_patch_seam_and_branch_cache(monkeypatch: pytest.MonkeyPatch) -assert calls == ["true"]-def test_controller_dependencies_admission_rejection_and_inactive(monkeypatch: pytest.MonkeyPatch) -> None:+def test_controller_gets_source_dependencies(monkeypatch: pytest.MonkeyPatch) -> None:class _NetworkX:def ancestors(self, _graph: object, _node_id: str) -> set[str]:return set()@@ -115,17 +93,6 @@ def test_controller_dependencies_admission_rejection_and_inactive(monkeypatch: passert controller.get_source_dependencies("true") == (true_dependency,)assert controller.get_source_dependencies("false") == (false_dependency,)assert controller.get_source_dependencies("outside") == ()- assert not controller.is_source_admitted("true")- assert not controller.is_source_rejected("true")- assert not controller.is_source_inactive("true")-- state.admitted.add(true_dependency)- assert controller.is_source_admitted("true")-- state.rejected.add(true_dependency)- assert controller.is_source_rejected("true")- state.rejected.add(ActivationDependency(owner_id="if", branch="true_input", frame=(1,)))- assert controller.is_source_inactive("true", (1,))@pytest.mark.parametrize(@@ -135,7 +102,7 @@ def test_controller_dependencies_admission_rejection_and_inactive(monkeypatch: p(False, "false", "true", "true_input"),],)-def test_controller_admits_only_source_level_selected_branch(+def test_controller_selects_source_dependencies_for_source_level_branch(monkeypatch: pytest.MonkeyPatch,condition: bool,selected_source: str,@@ -152,8 +119,6 @@ def test_controller_admits_only_source_level_selected_branch(controller = _IfActivationController(state)assert controller.get_source_dependencies(selected_source) == ()- assert controller.is_source_admitted(selected_source)- assert not controller.is_source_inactive(selected_source)assert controller.get_source_dependencies(unselected_source) == (ActivationDependency(owner_id="if", branch=unselected_field, frame=()),)diff --git a/tests/app/services/shared/test_graph_if_dependencies.py b/tests/app/services/shared/test_graph_if_dependencies.pyindex a1004553b3..479e301af8 100644--- a/tests/app/services/shared/test_graph_if_dependencies.py+++ b/tests/app/services/shared/test_graph_if_dependencies.py@@ -147,62 +147,6 @@ 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))- graph.add_edge(_edge("middle_if", "value", "middle_side_consumer", "a"))- 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))@@ -301,7 +245,10 @@ def test_replacing_graph_invalidates_source_graph_and_if_eligibility_caches() ->copied_state = state.model_copy(update={"graph": _indirectly_connected_if_graph()})- assert not copied_state._can_use_fresh_flat_if_activation()+ assert copied_state._can_use_fresh_flat_if_activation()+ assert copied_state._get_source_activation_dependencies("first_true") == (+ ActivationDependency(owner_id="first_if", branch="true_input", frame=()),+ )def test_flat_and_nested_dependencies_preserve_values_and_order() -> None:@@ -316,11 +263,36 @@ def test_flat_and_nested_dependencies_preserve_values_and_order() -> None:nested_state = GraphExecutionState(graph=_nested_if_graph())assert nested_state._get_source_activation_dependencies("inner_true") == (ActivationDependency(owner_id="inner_if", branch="true_input", frame=()),- ActivationDependency(owner_id="outer_if", branch="true_input", frame=()),)assert nested_state._get_source_activation_dependencies("inner_false", (4,)) == (ActivationDependency(owner_id="inner_if", branch="false_input", frame=(4,)),- ActivationDependency(owner_id="outer_if", branch="true_input", frame=(4,)),+ )+++def test_gate_frontier_keeps_incomparable_owner_and_branch() -> None:+ owners = (+ ("inner_if", "true_input"),+ ("sibling_if", "false_input"),+ ("outer_if", "true_input"),+ )+ outer_bit = 1 << 2+ masks = {"source": (1 << 0) | (1 << 1) | outer_bit}++ graph_if_dependencies._reduce_activation_owner_masks_to_frontier(+ masks,+ owners,+ {"inner_if": outer_bit},+ )++ assert masks == {"source": (1 << 0) | (1 << 1)}+ retained = tuple(+ ActivationDependency(owner_id=owners[index][0], branch=owners[index][1], frame=())+ for index in range(len(owners))+ if masks["source"] & (1 << index)+ )+ assert retained == (+ ActivationDependency(owner_id="inner_if", branch="true_input", frame=()),+ ActivationDependency(owner_id="sibling_if", branch="false_input", frame=()),)@@ -440,41 +412,6 @@ def test_four_independent_sibling_ifs_admit_owner_local_frame_local_dependenciesassert state._get_source_activation_dependencies("shared") == ()- ("graph_factory", "source_node_id"),- [- 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(_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"),- ],-)-def test_unsupported_if_shapes_use_controller_fallback(- monkeypatch: pytest.MonkeyPatch,- graph_factory: Any,- source_node_id: str,-) -> None:- expected = (ActivationDependency(owner_id="fallback", branch="true_input", frame=(9,)),)- calls: list[tuple[str, tuple[int, ...]]] = []-- def get_source_dependencies(- _controller: Any, actual_source_node_id: str, iteration_path: tuple[int, ...]- ) -> tuple[ActivationDependency, ...]:- calls.append((actual_source_node_id, iteration_path))- return expected-- monkeypatch.setattr(graph_module._IfActivationController, "get_source_dependencies", get_source_dependencies)- state = GraphExecutionState(graph=graph_factory())-- assert not state._can_use_fresh_flat_if_activation()- assert state._get_source_activation_dependencies(source_node_id, (9,)) == expected- assert calls == [(source_node_id, (9,))]--@pytest.mark.parametrize("outer_condition", [False, True])@pytest.mark.parametrize("middle_condition", [False, True])@pytest.mark.parametrize("inner_condition", [False, True])@@ -490,35 +427,30 @@ def test_three_nested_ifs_admit_owner_and_frame_dependencies(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("inner_false", (2,)) == (ActivationDependency(owner_id="inner_if", branch="false_input", frame=(2,)),- ActivationDependency(owner_id="middle_if", branch="true_input", frame=(2,)),- ActivationDependency(owner_id="outer_if", branch="true_input", frame=(2,)),)assert state._get_source_activation_dependencies("middle_false", (3,)) == (ActivationDependency(owner_id="middle_if", branch="false_input", frame=(3,)),- ActivationDependency(owner_id="outer_if", branch="true_input", frame=(3,)),)assert state._get_source_activation_dependencies("outer_false", (4,)) == (ActivationDependency(owner_id="outer_if", branch="false_input", frame=(4,)),)-def test_three_nested_ifs_with_one_middle_leaf_fanout_admit_exact_dependencies() -> None:- state = GraphExecutionState(graph=_three_nested_if_fanout_graph())+def test_three_nested_ifs_middle_leaf_fanout_keeps_only_outer_dependency() -> None:+ graph = _three_nested_if_graph()+ graph.add_node(AddInvocation(id="middle_side_consumer", b=1))+ graph.add_edge(_edge("middle_if", "value", "middle_side_consumer", "a"))+ state = GraphExecutionState(graph=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,)),@@ -534,13 +466,9 @@ def test_four_nested_ifs_admit_owner_and_frame_dependencies() -> None: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,)),@@ -568,24 +496,12 @@ def test_three_nested_ifs_with_one_middle_leaf_fanout_preserve_parent_branch_por)-def test_indirectly_connected_ifs_retain_controller_fallback(monkeypatch: pytest.MonkeyPatch) -> None:+def test_indirectly_connected_ifs_compile_dependencies() -> None:state = GraphExecutionState(graph=_indirectly_connected_if_graph())- 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]:- 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)-- assert not state._can_use_fresh_flat_if_activation()- assert state._get_source_activation_dependencies("first_true", (7,)) == (- ActivationDependency(owner_id="first_if", branch="true_input", frame=(7,)),+ assert state._can_use_fresh_flat_if_activation()+ assert state._get_source_activation_dependencies("first_true") == (+ ActivationDependency(owner_id="first_if", branch="true_input", frame=()),+ )+ assert state._get_source_activation_dependencies("bridge") == (+ ActivationDependency(owner_id="second_if", branch="true_input", frame=()),)- assert ("first_if", "true_input") in callsdiff --git a/tests/app/services/shared/test_graph_if_runtime.py b/tests/app/services/shared/test_graph_if_runtime.pyindex 47ae5d400e..455d14097f 100644--- a/tests/app/services/shared/test_graph_if_runtime.py+++ b/tests/app/services/shared/test_graph_if_runtime.py@@ -1,6 +1,10 @@+from types import SimpleNamespace+import pytest+from invokeai.app.invocations.collections import CollectionConcatInvocationfrom invokeai.app.invocations.logic import BooleanLogicInvocation, IfInvocation+from invokeai.app.invocations.loops import ForInvocationfrom invokeai.app.invocations.math import AddInvocationfrom invokeai.app.invocations.primitives import BooleanOutputfrom invokeai.app.services.shared import graph_if_runtime@@ -8,8 +12,9 @@ from invokeai.app.services.shared.execution_engine.scheduler import ActivationDefrom invokeai.app.services.shared.graph import Edge, EdgeConnection, Graph, GraphExecutionStatefrom invokeai.app.services.shared.graph_iterator_ancestry import _IteratorAncestryfrom invokeai.app.services.shared.graph_runtime_records import _ApplyTransaction-from invokeai.app.services.shared.graph_validation import IterateInvocation+from invokeai.app.services.shared.graph_validation import CollectInvocation, IterateInvocationfrom tests.app.services.shared.import_test_utils import assert_module_imports_without_graph+from tests.test_nodes import AnyTypeTestInvocation@pytest.fixture@@ -26,6 +31,45 @@ def test_runtime_import_without_graph() -> None:assert_module_imports_without_graph("invokeai.app.services.shared.graph_if_runtime")+def test_empty_if_frame_analysis_reuses_static_branch_axes(monkeypatch: pytest.MonkeyPatch) -> None:+ state = GraphExecutionState(graph=Graph(nodes={"if": IfInvocation(id="if")}))+ original = graph_if_runtime._get_if_branch_frame_axes+ analysis_count = 0++ def count_analysis(*args: object, **kwargs: object) -> dict[str, tuple[str, ...]]:+ nonlocal analysis_count+ analysis_count += 1+ return original(*args, **kwargs) # type: ignore[arg-type]++ monkeypatch.setattr(graph_if_runtime, "_get_if_branch_frame_axes", count_analysis)++ assert [graph_if_runtime._has_empty_if_frame(state, "if") for _ in range(20)] == [False] * 20+ assert analysis_count == 1+++ ("source_kind", "source_field", "axes", "expected"),+ [+ ("regular", "value", ("outer", "inner"), ("outer",)),+ ("regular", "value", (), ()),+ ("for_final", "output_collection", ("outer",), ("outer",)),+ ],+)+def test_collect_item_axis_closure_handles_empty_axes_and_for_final_output(+ source_kind: str, source_field: str, axes: tuple[str, ...], expected: tuple[str, ...]+) -> None:+ source = IfInvocation(id="source", condition=True) if source_kind == "regular" else ForInvocation(id="source")+ graph = Graph()+ graph.nodes.update({"source": source, "collect": CollectInvocation(id="collect")})+ state = SimpleNamespace(graph=graph)+ edge = Edge(+ source=EdgeConnection(node_id="source", field=source_field),+ destination=EdgeConnection(node_id="collect", field="item"),+ )++ assert graph_if_runtime._without_closed_axis(state, edge, axes) == expected++@pytest.mark.parametrize("field,value",[("state_id", "foreign"), ("frame_id", "foreign"), ("iteration_path", (3,)), ("workflow_call_depth", 1)],@@ -182,7 +226,7 @@ def test_nested_if_iteration_paths_use_supplied_source_graph_recursively() -> Nodef test_unresolved_nested_literal_if_chain_has_no_condition_path() -> None:nodes = {"iterator": IterateInvocation(id="iterator"), "guarded": IfInvocation(id="guarded")}- nodes.update({f"if-{i}": IfInvocation(id=f"if-{i}", condition=True) for i in range(24)})+ nodes.update({f"if-{i}": IfInvocation(id=f"if-{i}", condition=True) for i in range(600)})edges = [Edge(source=EdgeConnection(node_id="iterator", field="item"),@@ -190,7 +234,7 @@ def test_unresolved_nested_literal_if_chain_has_no_condition_path() -> None:)]previous = "guarded"- for i in range(24):+ for i in range(600):edges.append(Edge(source=EdgeConnection(node_id=previous, field="value"),@@ -215,6 +259,239 @@ def test_resolved_literal_if_uses_root_frame_path() -> None:) == [()]+def test_if_branch_frame_axes_deduplicates_stably_with_linear_comparisons(monkeypatch: pytest.MonkeyPatch) -> None:+ comparisons = 0++ class Axis(str):+ def __eq__(self, other: object) -> bool:+ nonlocal comparisons+ comparisons += 1+ return super().__eq__(other)++ __hash__ = str.__hash__++ axes = [Axis(f"axis-{index}") for index in range(1000)]+ graph = Graph(nodes={"if": IfInvocation(id="if")})+ for index in range(2):+ source_id = f"source{index}"+ graph.add_node(AddInvocation(id=source_id))+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id=source_id, field="value"),+ destination=EdgeConnection(node_id="if", field="true_input" if index == 0 else "false_input"),+ )+ )+ state = SimpleNamespace(graph=graph)+ axis_tuple = tuple(axes)+ monkeypatch.setattr(graph_if_runtime, "_get_edge_frame_axes", lambda _state, _ancestry, edge, _cache: axis_tuple)++ result = graph_if_runtime._get_if_branch_frame_axes(+ state, _IteratorAncestry(GraphExecutionState(graph=Graph())), "if", {}+ )++ assert tuple(result["true_input"]) == tuple(f"axis-{index}" for index in range(1000))+ assert result["true_input"] == result["false_input"]+ assert comparisons < 10_000+++def test_edge_frame_axis_traversal_visits_long_passthrough_chain_linearly(monkeypatch: pytest.MonkeyPatch) -> None:+ chain_length = 1000+ graph = Graph()+ graph.nodes["source"] = CollectionConcatInvocation(id="source", first=["x"])+ graph.nodes["iterate"] = IterateInvocation(id="iterate")+ graph.nodes["if"] = IfInvocation(id="if")+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="source", field="collection"),+ destination=EdgeConnection(node_id="iterate", field="collection"),+ )+ )+ previous = ("iterate", "item")+ for index in range(chain_length):+ node_id = f"pass{index}"+ graph.nodes[node_id] = AnyTypeTestInvocation(id=node_id)+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id=previous[0], field=previous[1]),+ destination=EdgeConnection(node_id=node_id, field="value"),+ )+ )+ previous = (node_id, "value")+ edge = Edge(+ source=EdgeConnection(node_id=previous[0], field=previous[1]),+ destination=EdgeConnection(node_id="if", field="true_input"),+ )+ graph.add_edge(edge)+ state = GraphExecutionState(graph=graph)+ get_input_edges = graph._get_input_edges+ visits = 0++ def counted_get_input_edges(node_id: str, *args: object, **kwargs: object) -> list[Edge]:+ nonlocal visits+ visits += 1+ return get_input_edges(node_id, *args, **kwargs)++ monkeypatch.setattr(graph, "_get_input_edges", counted_get_input_edges)++ axes = graph_if_runtime._get_edge_frame_axes(state, _IteratorAncestry(state), edge, {})++ assert axes == ("iterate",)+ assert visits < chain_length * 3+++def test_edge_frame_axis_traversal_caches_shared_nested_ifs(monkeypatch: pytest.MonkeyPatch) -> None:+ chain_length = 12+ graph = Graph()+ graph.nodes["source"] = AddInvocation(id="source")+ previous_id = "source"+ for index in range(chain_length):+ node_id = f"if-{index}"+ graph.nodes[node_id] = IfInvocation(id=node_id, condition=True)+ for branch in ("true_input", "false_input"):+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id=previous_id, field="value"),+ destination=EdgeConnection(node_id=node_id, field=branch),+ )+ )+ previous_id = node_id+ graph.nodes["sink"] = AddInvocation(id="sink")+ edge = Edge(+ source=EdgeConnection(node_id=previous_id, field="value"),+ destination=EdgeConnection(node_id="sink", field="a"),+ )+ graph.add_edge(edge)+ state = GraphExecutionState(graph=graph)+ original = graph_if_runtime._get_if_branch_frame_axes+ branch_lookups = 0++ def count_branch_lookups(*args: object, **kwargs: object) -> dict[str, tuple[str, ...]]:+ nonlocal branch_lookups+ branch_lookups += 1+ return original(*args, **kwargs) # type: ignore[arg-type]++ monkeypatch.setattr(graph_if_runtime, "_get_if_branch_frame_axes", count_branch_lookups)++ assert graph_if_runtime._get_edge_frame_axes(state, _IteratorAncestry(state), edge, {}) == ()+ assert branch_lookups <= chain_length + 1+++def test_nested_if_frame_axes_do_not_depend_on_runtime_branch_selection(monkeypatch: pytest.MonkeyPatch) -> None:+ graph = Graph(+ nodes={+ "condition": BooleanLogicInvocation(id="condition"),+ "if": IfInvocation(id="if"),+ "true": AddInvocation(id="true"),+ "false": AddInvocation(id="false"),+ "sink": AddInvocation(id="sink"),+ }+ )+ edge = Edge(+ source=EdgeConnection(node_id="if", field="value"),+ destination=EdgeConnection(node_id="sink", field="a"),+ )+ graph.edges.extend(+ [+ Edge(+ source=EdgeConnection(node_id="condition", field="value"),+ destination=EdgeConnection(node_id="if", field="condition"),+ ),+ Edge(+ source=EdgeConnection(node_id="true", field="value"),+ destination=EdgeConnection(node_id="if", field="true_input"),+ ),+ Edge(+ source=EdgeConnection(node_id="false", field="value"),+ destination=EdgeConnection(node_id="if", field="false_input"),+ ),+ edge,+ ]+ )+ state = GraphExecutionState(graph=graph)+ state.source_prepared_mapping["if"] = {"if-exec"}+ state._resolved_if_exec_branches["if-exec"] = "true_input"+ iterator_ancestry = _IteratorAncestry(state)++ assert graph_if_runtime._get_if_static_frame_analysis(state, iterator_ancestry, "if")[0] == {+ "true_input": (),+ "false_input": (),+ }+ state._resolved_if_exec_branches["if-exec"] = "false_input"+ assert graph_if_runtime._get_if_static_frame_analysis(state, iterator_ancestry, "if")[0] == {+ "true_input": (),+ "false_input": (),+ }+++def test_static_if_analysis_is_independent_of_runtime_branch_selection(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ graph = Graph(+ nodes={+ "condition": BooleanLogicInvocation(id="condition"),+ "inner": IfInvocation(id="inner"),+ "outer-condition": BooleanLogicInvocation(id="outer-condition"),+ "outer": IfInvocation(id="outer"),+ "true": AddInvocation(id="true"),+ "false": AddInvocation(id="false"),+ "outer-false": AddInvocation(id="outer-false"),+ }+ )+ graph.edges.extend(+ [+ Edge(+ source=EdgeConnection(node_id="condition", field="value"),+ destination=EdgeConnection(node_id="inner", field="condition"),+ ),+ Edge(+ source=EdgeConnection(node_id="true", field="value"),+ destination=EdgeConnection(node_id="inner", field="true_input"),+ ),+ Edge(+ source=EdgeConnection(node_id="false", field="value"),+ destination=EdgeConnection(node_id="inner", field="false_input"),+ ),+ Edge(+ source=EdgeConnection(node_id="outer-condition", field="value"),+ destination=EdgeConnection(node_id="outer", field="condition"),+ ),+ Edge(+ source=EdgeConnection(node_id="inner", field="value"),+ destination=EdgeConnection(node_id="outer", field="true_input"),+ ),+ Edge(+ source=EdgeConnection(node_id="outer-false", field="value"),+ destination=EdgeConnection(node_id="outer", field="false_input"),+ ),+ ]+ )+ state = GraphExecutionState(graph=graph)+ state.source_prepared_mapping["inner"] = {"inner-exec"}+ iterator_ancestry = _IteratorAncestry(state)++ def branch_axes(_current_state: GraphExecutionState, _ancestry: object, node_id: str, _cache: dict) -> dict:+ if node_id == "outer":+ return {"true_input": (), "false_input": ()}+ return {"true_input": (), "false_input": ()}++ monkeypatch.setattr(graph_if_runtime, "_get_if_branch_frame_axes", branch_axes)++ assert graph_if_runtime._get_if_static_frame_analysis(state, iterator_ancestry, "outer")[0] == {+ "true_input": (),+ "false_input": (),+ }+ state._resolved_if_exec_branches["inner-exec"] = "true_input"+ assert graph_if_runtime._get_if_static_frame_analysis(state, iterator_ancestry, "outer")[0] == {+ "true_input": (),+ "false_input": (),+ }+ state._resolved_if_exec_branches.clear()+ assert graph_if_runtime._get_if_static_frame_analysis(state, iterator_ancestry, "outer")[0] == {+ "true_input": (),+ "false_input": (),+ }++@pytest.mark.parametrize("executed", [False, True])def test_prepared_selected_source_preserves_paths_without_ancestry(executed: bool) -> None:state = GraphExecutionState(@@ -238,3 +515,54 @@ def test_prepared_selected_source_preserves_paths_without_ancestry(executed: boolambda *_: (2,),_IteratorAncestry(state),) == ([] if executed else [(2,)])+++def test_collect_empty_path_fallback_reuses_input_edge_axes(monkeypatch: pytest.MonkeyPatch) -> None:+ graph = Graph(+ nodes={+ "outer": AddInvocation(id="outer"),+ "source": AddInvocation(id="source"),+ "collect": CollectInvocation(id="collect"),+ }+ )+ graph.edges.append(+ Edge(+ source=EdgeConnection(node_id="outer", field="item"),+ destination=EdgeConnection(node_id="source", field="a"),+ )+ )+ input_edge = Edge(+ source=EdgeConnection(node_id="source", field="output_collection"),+ destination=EdgeConnection(node_id="collect", field="item"),+ )+ graph.edges.append(input_edge)+ graph.edges.append(+ Edge(+ source=EdgeConnection(node_id="outer", field="item"),+ destination=EdgeConnection(node_id="consumer", field="value"),+ )+ )+ graph._invalidate_edge_indexes()+ state = SimpleNamespace(graph=graph, source_prepared_mapping={"outer"})+ axis_lookups = 0++ def get_edge_frame_axes(_state: object, _ancestry: object, edge: Edge, _cache: dict) -> tuple[str, ...]:+ nonlocal axis_lookups+ assert edge == input_edge+ axis_lookups += 1+ return ("outer", "inner")++ monkeypatch.setattr(graph_if_runtime, "_get_edge_frame_axes", get_edge_frame_axes)++ assert graph_if_runtime._get_effective_iteration_paths_for_edge(+ state,+ Edge(+ source=EdgeConnection(node_id="collect", field="collection"),+ destination=EdgeConnection(node_id="consumer", field="value"),+ ),+ {"source"},+ lambda _source_id: {"outer-exec"},+ lambda _edge, _prepared_id: (),+ _IteratorAncestry(GraphExecutionState(graph=Graph())),+ ) == {()}+ assert axis_lookups == 1diff --git a/tests/app/services/shared/test_graph_materializer.py b/tests/app/services/shared/test_graph_materializer.pyindex 886ac490a7..2a78d6764e 100644--- a/tests/app/services/shared/test_graph_materializer.py+++ b/tests/app/services/shared/test_graph_materializer.py@@ -71,7 +71,7 @@ def test_materializer_preserves_execution_edges_and_source_nodes() -> None:assert state.is_complete()-def test_prepare_admits_only_selected_frame_after_unresolved_conditions() -> None:+def test_prepare_waits_for_both_branches_with_unresolved_conditions() -> None:from invokeai.app.invocations.logic import IfInvocationfrom invokeai.app.services.shared.graph_validation import IterateInvocation, nx@@ -106,8 +106,11 @@ def test_prepare_admits_only_selected_frame_after_unresolved_conditions() -> Non# Keep condition sources outside this preparation view; their If nodes stay unresolved.preparation_graph = nx.subgraph_view(graph, filter_node=lambda node_id: not node_id.startswith("condition-"))prepared_id = state._materializer().prepare(preparation_graph)- assert prepared_id in state.source_prepared_mapping["selected"]- assert len(state.source_prepared_mapping["selected"]) == 1+ assert prepared_id is not None+ assert state.prepared_source_mapping[prepared_id] == "selected"+ assert state._is_pending_if(prepared_id)+ assert state._resolved_if_exec_branches[prepared_id] == "true_input"+ assert set(state.source_prepared_mapping) == {"selected"}assert "blocked-a" not in state.source_prepared_mappingassert "blocked-b" not in state.source_prepared_mappingassert "inner-a" not in state.source_prepared_mappingdiff --git a/tests/app/services/shared/test_graph_runtime_records.py b/tests/app/services/shared/test_graph_runtime_records.pyindex 689018af72..0dfd035185 100644--- a/tests/app/services/shared/test_graph_runtime_records.py+++ b/tests/app/services/shared/test_graph_runtime_records.py@@ -82,6 +82,70 @@ def test_standalone_registry_lifecycle_and_lazy_metadata() -> None:assert "new-exec-node" not in prepared_iteration_paths+def test_prepared_path_overlap_index_tracks_registration_and_path_changes() -> None:+ prepared_source_mapping = {"first": "source"}+ source_prepared_mapping = {"source": {"first"}}+ prepared_iteration_paths = {"first": (2, 3)}+ registry = graph_runtime_records._PreparedExecRegistry(+ prepared_source_mapping,+ source_prepared_mapping,+ prepared_iteration_paths,+ {},+ )++ assert set(registry.get_prepared_ids_with_overlapping_path("source", (2,))) == {"first"}+ assert set(registry.get_prepared_ids_with_overlapping_path("source", (2, 3, 4))) == {"first"}+ assert set(registry.get_prepared_ids_with_overlapping_path("source", (1,))) == set()++ registry.register("second", "source")+ registry.set_iteration_path("second", (4,))+ assert set(registry.get_prepared_ids_with_overlapping_path("source", (4, 5))) == {"second"}++ registry.set_iteration_path("first", (5,))+ assert set(registry.get_prepared_ids_with_overlapping_path("source", (2,))) == set()+ assert set(registry.get_prepared_ids_with_overlapping_path("source", (5, 6))) == {"first"}+++def test_prepared_path_overlap_index_rolls_back_with_registration_and_path() -> None:+ state = graph_facade.GraphExecutionState(graph=graph_facade.Graph())+ registry = state._prepared_registry()++ def add_then_fail() -> None:+ registry.register("exec-node", "source-node")+ registry.set_iteration_path("exec-node", (2, 3))+ assert set(registry.get_prepared_ids_with_overlapping_path("source-node", (2,))) == {"exec-node"}+ raise RuntimeError("rollback test")++ with pytest.raises(RuntimeError, match="rollback test"):+ state._run_materialization_transaction(add_then_fail)++ assert registry.get_prepared_ids("source-node") == set()+ assert set(registry.get_prepared_ids_with_overlapping_path("source-node", (2,))) == set()+++def test_prepared_path_overlap_index_incremental_updates_roll_back() -> None:+ state = graph_facade.GraphExecutionState(graph=graph_facade.Graph())+ registry = state._prepared_registry()+ registry.register("existing", "source-node")+ registry.set_iteration_path("existing", (1, 2))+ assert set(registry.get_prepared_ids_with_overlapping_path("source-node", (1,))) == {"existing"}++ def mutate_then_fail() -> None:+ registry.register("new", "source-node")+ registry.set_iteration_path("new", (2,))+ registry.set_iteration_path("existing", (3, 4))+ assert set(registry.get_prepared_ids_with_overlapping_path("source-node", (3,))) == {"existing"}+ raise RuntimeError("rollback cached index")++ with pytest.raises(RuntimeError, match="rollback cached index"):+ state._run_materialization_transaction(mutate_then_fail)++ assert registry.get_prepared_ids("source-node") == {"existing"}+ assert set(registry.get_prepared_ids_with_overlapping_path("source-node", (1,))) == {"existing"}+ assert set(registry.get_prepared_ids_with_overlapping_path("source-node", (2,))) == set()+ assert set(registry.get_prepared_ids_with_overlapping_path("source-node", (3,))) == set()++def test_apply_transaction_record_once_rolls_back_in_reverse_order() -> None:transaction = graph_runtime_records._ApplyTransaction()undone: list[str] = []diff --git a/tests/app/services/shared/test_if_analysis_performance.py b/tests/app/services/shared/test_if_analysis_performance.pynew file mode 100644index 0000000000..5aa15cbdd0--- /dev/null+++ b/tests/app/services/shared/test_if_analysis_performance.py@@ -0,0 +1,416 @@+from __future__ import annotations++from collections.abc import Iterator+from typing import Any+from unittest.mock import Mock++import networkx as nx+import pytest++from invokeai.app.invocations.collections import CollectionConcatInvocation+from invokeai.app.invocations.logic import IfInvocation+from invokeai.app.invocations.primitives import BooleanInvocation+from invokeai.app.services.shared import graph_if_dependencies, graph_if_runtime+from invokeai.app.services.shared.execution_engine import ActivationDependency+from invokeai.app.services.shared.graph import Graph, GraphExecutionState, IterateInvocation, _ExecutionScheduler+from invokeai.app.services.shared.graph_validation import _EdgeList+from tests.test_nodes import AnyTypeTestInvocation, FixedCollectionTestInvocation, create_edge+++class _CountingNodes(dict[str, Any]):+ def __init__(self, nodes: dict[str, Any], counts: dict[str, int]) -> None:+ super().__init__(nodes)+ self.counts = counts++ def values(self) -> Iterator[Any]:+ for value in super().values():+ self.counts["nodes"] += 1+ yield value++ def items(self) -> Iterator[tuple[str, Any]]:+ for item in super().items():+ self.counts["nodes"] += 1+ yield item++ def __iter__(self) -> Iterator[str]:+ for node_id in super().__iter__():+ self.counts["nodes"] += 1+ yield node_id+++class _CountingEdgeList:+ def __init__(self, edges: list[Any] | tuple[Any, ...], counts: dict[str, int]) -> None:+ self.edges = edges+ self.counts = counts++ def __iter__(self) -> Iterator[Any]:+ for edge in self.edges:+ self.counts["adjacency_edges"] += 1+ yield edge++ def __len__(self) -> int:+ return len(self.edges)+++class _CountingAdjacency(dict[str, list[Any]]):+ def __init__(self, edges: dict[str, list[Any]], counts: dict[str, int]) -> None:+ super().__init__(edges)+ self.counts = counts++ def get(self, node_id: str, default: Any = None) -> Any:+ edges = super().get(node_id, default)+ return _CountingEdgeList(edges, self.counts) if isinstance(edges, list) else edges+++class _CountingNodeOrder(tuple[str, ...]):+ def __new__(cls, nodes: tuple[str, ...], counts: dict[str, int]):+ instance = super().__new__(cls, nodes)+ instance.counts = counts+ return instance++ def __iter__(self) -> Iterator[str]:+ for node_id in super().__iter__():+ self.counts["traversal_nodes"] += 1+ yield node_id++ def __reversed__(self) -> Iterator[str]:+ for index in range(len(self) - 1, -1, -1):+ self.counts["traversal_nodes"] += 1+ yield tuple.__getitem__(self, index)+++class _CountingIterationPaths(list[tuple[int, ...]]):+ def __init__(self, paths: list[tuple[int, ...]]) -> None:+ super().__init__(paths)+ self.work = 0++ def __iter__(self) -> Iterator[tuple[int, ...]]:+ for path in list.__iter__(self):+ self.work += 1+ yield path++ def __contains__(self, item: object) -> bool:+ for path in list.__iter__(self):+ self.work += 1+ if path == item:+ return True+ return False+++def _add_if(graph: Graph, if_id: str, true_source: str, false_source: str) -> None:+ graph.add_node(IfInvocation(id=if_id))+ graph.add_edge(create_edge("condition", "value", if_id, "condition"))+ graph.add_edge(create_edge(true_source, "value", if_id, "true_input"))+ graph.add_edge(create_edge(false_source, "value", if_id, "false_input"))+++def _make_graph(if_count: int) -> Graph:+ graph = Graph()+ graph.add_node(BooleanInvocation(id="condition", value=True))+ previous = "condition"+ for index in range(80):+ node_id = f"chain_{index}"+ graph.add_node(AnyTypeTestInvocation(id=node_id))+ graph.add_edge(create_edge(previous, "value", node_id, "value"))+ previous = node_id++ for index in range(if_count):+ true_source = f"true_{index}"+ false_source = f"false_{index}"+ graph.add_node(AnyTypeTestInvocation(id=true_source))+ graph.add_node(AnyTypeTestInvocation(id=false_source))+ graph.add_edge(create_edge(previous, "value", true_source, "value"))+ graph.add_edge(create_edge(previous, "value", false_source, "value"))+ _add_if(graph, f"if_{index}", true_source, false_source)+ return graph+++def _make_nested_if_graph(if_count: int) -> Graph:+ graph = Graph()+ graph.add_node(AnyTypeTestInvocation(id="true_leaf"))+ previous = "true_leaf"+ for index in range(if_count):+ if_id = f"if_{index}"+ condition_id = f"condition_{index}"+ false_source_id = f"false_{index}"+ graph.add_node(BooleanInvocation(id=condition_id, value=True))+ graph.add_node(AnyTypeTestInvocation(id=false_source_id))+ graph.add_node(IfInvocation(id=if_id))+ graph.add_edge(create_edge(condition_id, "value", if_id, "condition"))+ graph.add_edge(create_edge(previous, "value", if_id, "true_input"))+ graph.add_edge(create_edge(false_source_id, "value", if_id, "false_input"))+ previous = if_id++ graph.add_node(AnyTypeTestInvocation(id="sink"))+ graph.add_edge(create_edge(previous, "value", "sink", "value"))+ return graph+++def _instrument(state: GraphExecutionState, monkeypatch: pytest.MonkeyPatch) -> dict[str, int]:+ counts = {+ "nodes": 0,+ "edges": 0,+ "ancestor_nodes": 0,+ "adjacency_edges": 0,+ "traversal_nodes": 0,+ "traversal_edges": 0,+ "owner_mask_entries": 0,+ "owner_relations": 0,+ }+ object.__setattr__(state.graph, "nodes", _CountingNodes(state.graph.nodes, counts))++ original_edge_iter = _EdgeList.__iter__++ def count_edges(edges: _EdgeList):+ for edge in original_edge_iter(edges):+ counts["edges"] += 1+ yield edge++ original_ancestors = nx.ancestors++ def count_ancestors(graph: Any, node_id: Any) -> set[Any]:+ ancestors = original_ancestors(graph, node_id)+ counts["ancestor_nodes"] += len(ancestors) + 1+ return ancestors++ original_topological_sort = nx.topological_sort++ def count_topological_sort(graph: Any) -> Iterator[Any]:+ nodes = tuple(original_topological_sort(graph))+ counts["traversal_nodes"] += len(nodes)+ counts["traversal_edges"] += graph.number_of_edges()+ return iter(nodes)++ original_get_owner_masks = graph_if_dependencies._get_flat_activation_owner_masks_by_source++ def count_owner_analysis(state: GraphExecutionState, analysis: Any) -> dict[str, int]:+ is_new_analysis = analysis.activation_owner_masks_by_source is None+ if is_new_analysis:+ analysis.input_edges = _CountingAdjacency(analysis.input_edges, counts)+ analysis.output_edges = _CountingAdjacency(analysis.output_edges, counts)+ owners_by_source = original_get_owner_masks(state, analysis)+ if is_new_analysis:+ counts["owner_mask_entries"] += len(owners_by_source)+ return owners_by_source++ original_get_dependencies = graph_if_dependencies._get_source_activation_dependencies++ def count_dependencies(+ state: GraphExecutionState, source_node_id: str, iteration_path: tuple[int, ...] = ()+ ) -> tuple[ActivationDependency, ...]:+ dependencies = original_get_dependencies(state, source_node_id, iteration_path)+ counts["owner_relations"] += len(dependencies)+ return dependencies++ original_topological_order = graph_if_dependencies._get_if_topological_order++ def count_topological_order(analysis: Any) -> tuple[str, ...] | None:+ order = original_topological_order(analysis)+ if order is None:+ return None+ if not isinstance(order, _CountingNodeOrder):+ order = _CountingNodeOrder(order, counts)+ analysis.topological_order = order+ return order++ monkeypatch.setattr(_EdgeList, "__iter__", count_edges)+ monkeypatch.setattr(nx, "ancestors", count_ancestors)+ monkeypatch.setattr(nx, "topological_sort", count_topological_sort)+ monkeypatch.setattr(graph_if_dependencies, "_get_flat_activation_owner_masks_by_source", count_owner_analysis)+ monkeypatch.setattr(graph_if_dependencies, "_get_source_activation_dependencies", count_dependencies)+ monkeypatch.setattr(graph_if_dependencies, "_get_if_topological_order", count_topological_order)+ return counts+++def _work(counts: dict[str, int]) -> int:+ return sum(counts.values())+++def test_if_analysis_graph_traversal_work_is_bounded_and_invalidated_by_graph_edits(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ graph = _make_graph(4)+ state = GraphExecutionState(graph=graph)+ counts = _instrument(state, monkeypatch)++ assert state._can_use_fresh_flat_if_activation()+ for index in range(4, 32):+ true_source = f"true_{index}"+ false_source = f"false_{index}"+ if_id = f"if_{index}"+ state.add_node(AnyTypeTestInvocation(id=true_source))+ state.add_node(AnyTypeTestInvocation(id=false_source))+ state.add_node(IfInvocation(id=if_id))+ for source, destination, field in (+ ("chain_79", true_source, "value"),+ ("chain_79", false_source, "value"),+ ("condition", if_id, "condition"),+ (true_source, if_id, "true_input"),+ (false_source, if_id, "false_input"),+ ):+ state.add_edge(create_edge(source, "value", destination, field))++ # The edit APIs must invalidate ownership analysis. Count its rebuild and all dependency lookups.+ counts.update(dict.fromkeys(counts, 0))+ for index in range(32):+ assert state._get_source_activation_dependencies(f"true_{index}", (index,)) == (+ ActivationDependency(owner_id=f"if_{index}", branch="true_input", frame=(index,)),+ )+ assert state._get_source_activation_dependencies(f"false_{index}", (index + 32,)) == (+ ActivationDependency(owner_id=f"if_{index}", branch="false_input", frame=(index + 32,)),+ )+ graph_size = len(graph.nodes) + len(graph.edges)+ graph_traversal_work = _work(counts)+ assert graph_traversal_work <= 8 * graph_size, (+ f"If ownership visited {graph_traversal_work} graph items for {graph_size} nodes and edges"+ )+++def test_nested_if_analysis_materializes_gate_frontiers_and_bounds_mask_payload() -> None:+ measurements = []+ for depth in (16, 32, 64, 128):+ graph = _make_nested_if_graph(depth)+ state = GraphExecutionState(graph=graph)+ dependencies = {+ source_id: state._get_source_activation_dependencies(source_id, (7,)) for source_id in graph.nodes+ }+ relation_count = sum(map(len, dependencies.values()))++ analysis = state._if_graph_analysis+ assert analysis is not None+ owner_masks_by_source = analysis.activation_owner_masks_by_source+ assert owner_masks_by_source is not None+ # shortcut: packed masks bound materialized frontier relations, but bit payload remains+ # O(V·I/w); revisit a sparse representation if profiling on real workflows shows it matters.+ mask_payload_bits = sum(mask.bit_length() for mask in owner_masks_by_source.values())+ frontier_iterations = sum(mask.bit_count() for mask in owner_masks_by_source.values())++ assert dependencies["true_leaf"] == (ActivationDependency(owner_id="if_0", branch="true_input", frame=(7,)),)+ assert relation_count <= 3 * depth + 1+ # The reducer performs one loop iteration per retained frontier owner bit.+ assert frontier_iterations == relation_count+ assert len(owner_masks_by_source) <= len(graph.nodes)+ assert all(isinstance(mask, int) for mask in owner_masks_by_source.values())+ # A compact integer bitset still stores through its highest owner bit; that payload grows with+ # graph size × owner count even though only the frontier relations are materialized.+ assert mask_payload_bits <= 2 * len(owner_masks_by_source) * (2 * depth)+ measurements.append((depth, relation_count, mask_payload_bits))++ assert measurements[-1][1] <= 9 * measurements[0][1]+++def _count_prepared_if_frame_visits(item_count: int, force_compatibility: bool) -> tuple[int, int]:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="src", first=list(range(item_count))))+ graph.add_node(IterateInvocation(id="it"))+ graph.add_node(FixedCollectionTestInvocation(id="cond"))+ graph.add_node(AnyTypeTestInvocation(id="branch", value="B"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_node(AnyTypeTestInvocation(id="fallback", value="F"))+ graph.add_node(AnyTypeTestInvocation(id="after"))+ for edge in (+ ("src", "collection", "it", "collection"),+ ("it", "item", "cond", "value"),+ ("it", "item", "branch", "value"),+ ("cond", "condition", "if", "condition"),+ ("branch", "value", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "after", "value"),+ ):+ graph.add_edge(create_edge(*edge))++ state = GraphExecutionState(graph=graph)+ if force_compatibility:+ state._execution_scheduler = _ExecutionScheduler(state)+ original_register = state._register_prepared_exec_node+ original_get_frames = state._prepared_if_exec_frames+ frame_visits = 0+ owner_id_visits = 0++ class _CountingPreparedIds(set[str]):+ def __iter__(self) -> Iterator[str]:+ nonlocal owner_id_visits+ owner_id_visits += len(self)+ return super().__iter__()++ def count_prepared_id_iterations() -> None:+ # Count actual scans of the If owner-ID set, including scans hidden inside index builders.+ prepared_ids = state.source_prepared_mapping.get("if")+ if prepared_ids is not None and not isinstance(prepared_ids, _CountingPreparedIds):+ state.source_prepared_mapping["if"] = _CountingPreparedIds(prepared_ids)++ def register_prepared_exec_node(execution_node_id: str, source_node_id: str) -> Any:+ result = original_register(execution_node_id, source_node_id)+ count_prepared_id_iterations()+ return result++ def count_frame_visits(source_node_id: str) -> tuple[tuple[int, ...], ...]:+ nonlocal frame_visits+ frames = original_get_frames(source_node_id)+ frame_visits += len(frames)+ return frames++ state._prepared_if_exec_frames = count_frame_visits # type: ignore[method-assign]+ state._register_prepared_exec_node = register_prepared_exec_node # type: ignore[method-assign]+ while (node := state.next()) is not None:+ state.complete(node.id, node.invoke(Mock()))+ assert state.is_complete()+ return frame_visits, owner_id_visits++[email protected]_independent[email protected]("force_compatibility", [False, True], ids=["generic", "compatibility"])+def test_if_dependency_frame_visits_scale_linearly(force_compatibility: bool) -> None:+ visits = {+ item_count: _count_prepared_if_frame_visits(item_count, force_compatibility) for item_count in (8, 16, 32)+ }+ frame_visits = {item_count: counts[0] for item_count, counts in visits.items()}+ owner_id_visits = {item_count: counts[1] for item_count, counts in visits.items()}+ assert frame_visits[16] <= max(1, frame_visits[8]) * 3, f"candidate frame visits: {frame_visits}"+ assert frame_visits[32] <= max(1, frame_visits[16]) * 3, f"candidate frame visits: {frame_visits}"+ assert owner_id_visits[16] <= max(1, owner_id_visits[8]) * 3, f"owner execution visits: {owner_id_visits}"+ assert owner_id_visits[32] <= max(1, owner_id_visits[16]) * 3, f"owner execution visits: {owner_id_visits}"+ assert owner_id_visits[32] <= 20 * 32, f"owner execution visits exceeded linear work: {owner_id_visits}"++[email protected]_independent+def test_literal_root_if_preparation_path_membership_scales_linearly(monkeypatch: pytest.MonkeyPatch) -> None:+ original_get_paths = graph_if_runtime._get_if_iteration_paths_with_ancestry+ counted_path_lists: list[_CountingIterationPaths] = []++ def count_if_paths(state: GraphExecutionState, node_id: str, *args: Any, **kwargs: Any) -> list[tuple[int, ...]]:+ paths = original_get_paths(state, node_id, *args, **kwargs)+ if node_id == "if":+ paths = _CountingIterationPaths(paths)+ counted_path_lists.append(paths)+ return paths++ monkeypatch.setattr(graph_if_runtime, "_get_if_iteration_paths_with_ancestry", count_if_paths)+ work_by_item_count: dict[int, int] = {}+ for item_count in (100, 200, 400):+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="src", first=list(range(item_count))))+ graph.add_node(IterateInvocation(id="it"))+ graph.add_node(AnyTypeTestInvocation(id="selected"))+ graph.add_node(AnyTypeTestInvocation(id="fallback", value="F"))+ graph.add_node(IfInvocation(id="if", condition=True))+ graph.add_node(AnyTypeTestInvocation(id="sink"))+ for edge in (+ ("src", "collection", "it", "collection"),+ ("it", "item", "selected", "value"),+ ("selected", "value", "if", "true_input"),+ ("fallback", "value", "if", "false_input"),+ ("if", "value", "sink", "value"),+ ):+ graph.add_edge(create_edge(*edge))+ graph.validate_self()++ counted_path_lists.clear()+ state = GraphExecutionState(graph=graph)+ while (node := state.next()) is not None:+ state.complete(node.id, node.invoke(Mock()))+ assert state.is_complete()+ work_by_item_count[item_count] = sum(paths.work for paths in counted_path_lists)++ assert work_by_item_count[200] <= 3 * work_by_item_count[100], work_by_item_count+ assert work_by_item_count[400] <= 3 * work_by_item_count[200], work_by_item_countdiff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.pyindex 5c9293a7de..c06dea1c18 100644--- a/tests/test_graph_execution_state.py+++ b/tests/test_graph_execution_state.py@@ -3059,8 +3059,6 @@ def test_nested_if_literal_condition_activates_selected_branch():graph.add_edge(create_edge("outer_if", "value", "sink", "a"))state = GraphExecutionState(graph=graph)- assert not state._can_use_fresh_flat_if_activation()-executed_source_ids = execute_all_nodes(state)assert state.is_complete(), (@@ -5015,6 +5013,31 @@ def test_graph_collector_reuses_outer_collection_input_for_each_nested_iterator_assert collect_results == [[100, 0, 1], [100, 10, 11]]+def test_graph_collector_broadcasts_root_item_into_each_nested_iterator_group():+ graph = Graph()+ graph.add_node(RangeInvocation(id="outer_range", start=0, stop=2, step=1))+ graph.add_node(IterateInvocation(id="outer_iter"))+ graph.add_node(IntegerCollectionFromItemTestInvocation(id="inner_collection"))+ graph.add_node(IterateInvocation(id="inner_iter"))+ graph.add_node(AddInvocation(id="inner_item", b=0))+ graph.add_node(AddInvocation(id="root_item", a=100, b=0))+ graph.add_node(CollectInvocation(id="collect"))++ graph.add_edge(create_edge("outer_range", "collection", "outer_iter", "collection"))+ graph.add_edge(create_edge("outer_iter", "item", "inner_collection", "value"))+ graph.add_edge(create_edge("inner_collection", "collection", "inner_iter", "collection"))+ graph.add_edge(create_edge("inner_iter", "item", "inner_item", "a"))+ graph.add_edge(create_edge("inner_item", "value", "collect", "item"))+ graph.add_edge(create_edge("root_item", "value", "collect", "item"))++ state = GraphExecutionState(graph=graph)+ execute_all_nodes(state)++ collect_ids = state.source_prepared_mapping["collect"]+ assert len(collect_ids) == 2+ assert sorted(state.results[node_id].collection for node_id in collect_ids) == [[100, 0, 1], [100, 10, 11]]++def test_graph_collector_nested_under_three_iterators_preserves_outer_iteration_paths():graph = Graph()@@ -5214,7 +5237,7 @@ def test_if_invocation_output_connects_to_downstream_input():(False, "false_values", "true_values", ["false-a"]),],)-def test_if_output_iterates_only_selected_collection_branch(+def test_if_output_iterates_selected_collection_with_eager_branch_producers(condition: bool, selected_node_id: str, unselected_node_id: str, expected_values: list[str]):graph = Graph()@@ -5235,7 +5258,7 @@ def test_if_output_iterates_only_selected_collection_branch(assert len(collect_exec_ids) == 1assert state.results[next(iter(collect_exec_ids))].collection == expected_valuesassert selected_node_id in executed_node_ids- assert unselected_node_id not in executed_node_ids+ assert unselected_node_id in executed_node_ids@pytest.mark.xfail(strict=True, reason="Legacy eager If-node execution should no longer occur")@@ -5505,7 +5528,7 @@ def test_if_graph_optimized_behavior_skips_unselected_branch_but_keeps_shared_anassert "false_leaf" not in executed_source_ids-def test_if_graph_optimized_behavior_skips_distant_unselected_ancestors_only_when_exclusive():+def test_if_graph_external_branch_consumer_makes_if_eager():graph = Graph()graph.add_node(BooleanInvocation(id="condition", value=False))graph.add_node(PromptTestInvocation(id="shared_root", prompt="shared value"))@@ -5534,13 +5557,15 @@ def test_if_graph_optimized_behavior_skips_distant_unselected_ancestors_only_whe"condition","shared_root","true_shared_mid",+ "true_exclusive_leaf","false_mid","false_leaf","shared_observer","if","selected_output",}- assert "true_exclusive_leaf" not in executed_source_ids+ selected_output_id = next(iter(g.source_prepared_mapping["selected_output"]))+ assert g.results[selected_output_id].prompt == "shared value"def test_if_graph_optimized_behavior_allows_selected_missing_branch_input():@@ -5563,7 +5588,7 @@ def test_if_graph_optimized_behavior_allows_selected_missing_branch_input():assert "true_value" not in executed_source_ids-def test_if_graph_optimized_behavior_does_not_cross_defer_independent_ifs():+def test_independent_ifs_eagerly_run_both_branches():graph = Graph()graph.add_node(BooleanInvocation(id="condition_a", value=True))graph.add_node(BooleanInvocation(id="condition_b", value=False))@@ -5593,16 +5618,16 @@ def test_if_graph_optimized_behavior_does_not_cross_defer_independent_ifs():"condition_a","condition_b","true_a",+ "false_a",+ "true_b","false_b","if_a","if_b","collect",}- assert "false_a" not in executed_source_ids- assert "true_b" not in executed_source_ids-def test_if_graph_optimized_behavior_supports_nested_ifs():+def test_nested_ifs_eagerly_run_both_branches():graph = Graph()graph.add_node(BooleanInvocation(id="outer_condition", value=True))graph.add_node(BooleanInvocation(id="inner_condition", value=False))@@ -5629,13 +5654,13 @@ def test_if_graph_optimized_behavior_supports_nested_ifs():assert set(executed_source_ids) == {"outer_condition","inner_condition",+ "inner_true","inner_false",+ "outer_false","inner_if","outer_if","selected_output",}- assert "inner_true" not in executed_source_ids- assert "outer_false" not in executed_source_idsdef test_if_graph_optimized_behavior_prunes_branches_per_iteration():@@ -5695,7 +5720,7 @@ def test_if_graph_optimized_behavior_handles_empty_iteration():assert g.is_complete()-def test_if_graph_optimized_behavior_keeps_shared_live_consumers_per_iteration():+def test_if_external_branch_consumer_makes_all_iteration_branches_eager():graph = Graph()graph.add_node(BooleanCollectionInvocation(id="conditions", collection=[True, False, False]))graph.add_node(IterateInvocation(id="condition_iter"))@@ -5729,8 +5754,8 @@ def test_if_graph_optimized_behavior_keeps_shared_live_consumers_per_iteration()assert executed_source_ids.count("condition_iter") == 3assert executed_source_ids.count("shared_branch") == 3assert executed_source_ids.count("observer") == 3- assert executed_source_ids.count("true_leaf") == 1- assert executed_source_ids.count("false_branch") == 2+ assert executed_source_ids.count("true_leaf") == 3+ assert executed_source_ids.count("false_branch") == 3assert g.is_complete()@@ -5754,12 +5779,12 @@ def test_if_graph_optimized_behavior_keeps_shared_live_consumers_per_iteration()pytest.param(False,["shared"],- {"condition", "shared_item", "shared_collect", "if", "selected_output"},+ {"condition", "shared_item", "true_item", "shared_collect", "true_collect", "if", "selected_output"},id="false-branch",),],)-def test_if_graph_optimized_behavior_handles_selected_branch_with_shared_ancestor(+def test_if_collect_branches_eagerly_evaluate_shared_ancestor(condition: bool, expected_value: list[str], expected_source_ids: set[str]):graph = Graph()@@ -5834,7 +5859,7 @@ def test_get_collect_iteration_mapping_groups_ignores_skipped_prepared_exec_nodemappings = g._materializer()._get_collect_iteration_mapping_groups(graph._get_input_edges("collect"))- assert mappings == [((), [("parent", active_exec_id)])]+ assert mappings == [((), (), [("parent", active_exec_id)])]def test_get_iteration_node_ignores_skipped_prepared_exec_nodes():