forked from invoke-ai/InvokeAI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.py
More file actions
2017 lines (1626 loc) · 85 KB
/
graph.py
File metadata and controls
2017 lines (1626 loc) · 85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2022 Kyle Schouviller (https://github.com/kyle0654)
import copy
import itertools
from collections import deque
from dataclasses import dataclass
from typing import Any, Deque, Iterable, Literal, Optional, Type, TypeVar, Union, get_args, get_origin
import networkx as nx
from pydantic import (
BaseModel,
ConfigDict,
GetCoreSchemaHandler,
GetJsonSchemaHandler,
PrivateAttr,
ValidationError,
field_validator,
)
from pydantic.fields import Field
from pydantic.json_schema import JsonSchemaValue
from pydantic_core import core_schema
# Importing * is bad karma but needed here for node detection
from invokeai.app.invocations import * # noqa: F401 F403
from invokeai.app.invocations.baseinvocation import (
BaseInvocation,
BaseInvocationOutput,
InvocationRegistry,
invocation,
invocation_output,
)
from invokeai.app.invocations.fields import Input, InputField, OutputField, UIType
from invokeai.app.invocations.logic import IfInvocation
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.app.util.misc import uuid_string
# in 3.10 this would be "from types import NoneType"
NoneType = type(None)
# Port name constants
ITEM_FIELD = "item"
COLLECTION_FIELD = "collection"
class EdgeConnection(BaseModel):
node_id: str = Field(description="The id of the node for this edge connection")
field: str = Field(description="The field for this connection")
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and getattr(other, "node_id", None) == self.node_id
and getattr(other, "field", None) == self.field
)
def __hash__(self):
return hash(f"{self.node_id}.{self.field}")
class Edge(BaseModel):
source: EdgeConnection = Field(description="The connection for the edge's from node and field")
destination: EdgeConnection = Field(description="The connection for the edge's to node and field")
def __str__(self):
return f"{self.source.node_id}.{self.source.field} -> {self.destination.node_id}.{self.destination.field}"
PreparedExecState = Literal["pending", "ready", "executed", "skipped"]
@dataclass
class _PreparedExecNodeMetadata:
"""Cached metadata for a materialized execution node."""
source_node_id: str
iteration_path: Optional[tuple[int, ...]] = None
state: PreparedExecState = "pending"
class _PreparedExecRegistry:
"""Tracks prepared execution nodes and their relationship to source graph nodes."""
def __init__(
self,
prepared_source_mapping: dict[str, str],
source_prepared_mapping: dict[str, set[str]],
metadata: dict[str, _PreparedExecNodeMetadata],
) -> None:
self._prepared_source_mapping = prepared_source_mapping
self._source_prepared_mapping = source_prepared_mapping
self._metadata = metadata
def register(self, exec_node_id: str, source_node_id: str) -> None:
self._prepared_source_mapping[exec_node_id] = source_node_id
self._metadata[exec_node_id] = _PreparedExecNodeMetadata(source_node_id=source_node_id)
if source_node_id not in self._source_prepared_mapping:
self._source_prepared_mapping[source_node_id] = set()
self._source_prepared_mapping[source_node_id].add(exec_node_id)
def get_metadata(self, exec_node_id: str) -> _PreparedExecNodeMetadata:
metadata = self._metadata.get(exec_node_id)
if metadata is None:
metadata = _PreparedExecNodeMetadata(source_node_id=self._prepared_source_mapping[exec_node_id])
self._metadata[exec_node_id] = metadata
return metadata
def get_source_node_id(self, exec_node_id: str) -> str:
metadata = self._metadata.get(exec_node_id)
if metadata is not None:
return metadata.source_node_id
return self._prepared_source_mapping[exec_node_id]
def get_prepared_ids(self, source_node_id: str) -> set[str]:
return self._source_prepared_mapping.get(source_node_id, set())
def set_state(self, exec_node_id: str, state: PreparedExecState) -> None:
self.get_metadata(exec_node_id).state = state
def get_iteration_path(self, exec_node_id: str) -> Optional[tuple[int, ...]]:
metadata = self._metadata.get(exec_node_id)
return metadata.iteration_path if metadata is not None else None
def set_iteration_path(self, exec_node_id: str, iteration_path: tuple[int, ...]) -> None:
self.get_metadata(exec_node_id).iteration_path = iteration_path
class _IfBranchScheduler:
"""Applies lazy `If` semantics by deferring, releasing, and skipping branch-local exec nodes."""
def __init__(self, state: "GraphExecutionState") -> None:
self._state = state
def _get_branch_input_sources(self, if_node_id: str, branch_field: str) -> set[str]:
return {e.source.node_id for e in self._state.graph._get_input_edges(if_node_id, branch_field)}
def _expand_with_ancestors(self, node_ids: set[str]) -> set[str]:
expanded = set(node_ids)
source_graph = self._state.graph.nx_graph_flat()
for node_id in list(expanded):
expanded.update(nx.ancestors(source_graph, node_id))
return expanded
def _node_outputs_stay_in_branch(
self, node_id: str, if_node_id: str, branch_field: str, branch_nodes: set[str]
) -> bool:
output_edges = self._state.graph._get_output_edges(node_id)
return all(
edge.destination.node_id in branch_nodes
or (edge.destination.node_id == if_node_id and edge.destination.field == branch_field)
for edge in output_edges
)
def _prune_nonexclusive_branch_nodes(
self, if_node_id: str, branch_field: str, candidate_nodes: set[str]
) -> set[str]:
exclusive_nodes = set(candidate_nodes)
changed = True
while changed:
changed = False
for node_id in list(exclusive_nodes):
if self._node_outputs_stay_in_branch(node_id, if_node_id, branch_field, exclusive_nodes):
continue
exclusive_nodes.remove(node_id)
changed = True
return exclusive_nodes
def _get_matching_prepared_if_ids(self, if_node_id: str, iteration_path: tuple[int, ...]) -> list[str]:
prepared_if_ids = self._state._prepared_registry().get_prepared_ids(if_node_id)
return [pid for pid in prepared_if_ids if self._state._get_iteration_path(pid) == iteration_path]
def _has_unresolved_matching_if(self, if_node_id: str, iteration_path: tuple[int, ...]) -> bool:
matching_prepared_if_ids = self._get_matching_prepared_if_ids(if_node_id, iteration_path)
if not matching_prepared_if_ids:
return True
return not all(pid in self._state._resolved_if_exec_branches for pid in matching_prepared_if_ids)
def _apply_condition_inputs(self, exec_node_id: str, node: IfInvocation) -> bool:
condition_edges = self._state.execution_graph._get_input_edges(exec_node_id, "condition")
if any(edge.source.node_id not in self._state.executed for edge in condition_edges):
return False
for edge in condition_edges:
setattr(
node,
edge.destination.field,
copydeep(getattr(self._state.results[edge.source.node_id], edge.source.field)),
)
return True
def _get_selected_branch_fields(self, node: IfInvocation) -> tuple[str, str]:
selected_field = "true_input" if node.condition else "false_input"
unselected_field = "false_input" if node.condition else "true_input"
return selected_field, unselected_field
def _prune_unselected_if_inputs(self, exec_node_id: str, unselected_field: str) -> None:
for edge in self._state.execution_graph._get_input_edges(exec_node_id, unselected_field):
if edge.source.node_id in self._state.executed:
continue
if self._state.indegree[exec_node_id] == 0:
raise RuntimeError(f"indegree underflow for {exec_node_id} when pruning {unselected_field}")
self._state.indegree[exec_node_id] -= 1
def _apply_branch_resolution(
self,
exec_node_id: str,
iteration_path: tuple[int, ...],
exclusive_sources: dict[str, set[str]],
selected_field: str,
unselected_field: str,
) -> None:
# This iterates over the stable prepared-source mapping while mutating per-exec runtime state such as ready
# queues, execution state, and prepared metadata. Branch resolution never adds or removes prepared exec nodes.
for prepared_id, prepared_source in self._state.prepared_source_mapping.items():
if prepared_id in self._state.executed:
continue
if self._state._get_iteration_path(prepared_id) != iteration_path:
continue
if prepared_source in exclusive_sources[selected_field]:
self._state._enqueue_if_ready(prepared_id)
elif prepared_source in exclusive_sources[unselected_field]:
self.mark_exec_node_skipped(prepared_id)
def get_branch_exclusive_sources(self, if_node_id: str) -> dict[str, set[str]]:
cached = self._state._if_branch_exclusive_sources.get(if_node_id)
if cached is not None:
return cached
branch_sources: dict[str, set[str]] = {}
for branch_field in ("true_input", "false_input"):
direct_inputs = self._get_branch_input_sources(if_node_id, branch_field)
candidate_nodes = self._expand_with_ancestors(direct_inputs)
branch_sources[branch_field] = self._prune_nonexclusive_branch_nodes(
if_node_id, branch_field, candidate_nodes
)
self._state._if_branch_exclusive_sources[if_node_id] = branch_sources
return branch_sources
def is_deferred_by_unresolved_if(self, exec_node_id: str) -> bool:
source_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
iteration_path = self._state._get_iteration_path(exec_node_id)
for source_if_id, source_if_node in self._state.graph.nodes.items():
if not isinstance(source_if_node, IfInvocation):
continue
branches = self.get_branch_exclusive_sources(source_if_id)
if source_node_id not in branches["true_input"] and source_node_id not in branches["false_input"]:
continue
if self._has_unresolved_matching_if(source_if_id, iteration_path):
return True
return False
def mark_exec_node_skipped(self, exec_node_id: str) -> None:
self._state._remove_from_ready_queues(exec_node_id)
self._state._set_prepared_exec_state(exec_node_id, "skipped")
self._state.executed.add(exec_node_id)
registry = self._state._prepared_registry()
source_node_id = registry.get_source_node_id(exec_node_id)
prepared_nodes = registry.get_prepared_ids(source_node_id)
if all(n in self._state.executed for n in prepared_nodes):
if source_node_id not in self._state.executed:
self._state.executed.add(source_node_id)
self._state.executed_history.append(source_node_id)
def try_resolve_if_node(self, exec_node_id: str) -> None:
if exec_node_id in self._state._resolved_if_exec_branches:
return
node = self._state.execution_graph.get_node(exec_node_id)
if not isinstance(node, IfInvocation):
return
if not self._apply_condition_inputs(exec_node_id, node):
return
selected_field, unselected_field = self._get_selected_branch_fields(node)
self._state._resolved_if_exec_branches[exec_node_id] = selected_field
source_if_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
exclusive_sources = self.get_branch_exclusive_sources(source_if_node_id)
iteration_path = self._state._get_iteration_path(exec_node_id)
self._prune_unselected_if_inputs(exec_node_id, unselected_field)
self._apply_branch_resolution(exec_node_id, iteration_path, exclusive_sources, selected_field, unselected_field)
self._state._enqueue_if_ready(exec_node_id)
class _ExecutionMaterializer:
"""Expands source-graph nodes into concrete execution-graph nodes for the current runtime state.
`GraphExecutionState.next()` calls into this helper when no prepared exec node is ready. The materializer chooses
the next source node that can be expanded, creates the corresponding exec nodes in the execution graph, wires their
inputs, and initializes their scheduler state.
"""
def __init__(self, state: "GraphExecutionState") -> None:
self._state = state
def _get_iterator_iteration_count(self, node_id: str, iteration_node_map: list[tuple[str, str]]) -> int:
input_collection_edge = next(iter(self._state.graph._get_input_edges(node_id, COLLECTION_FIELD)))
input_collection_prepared_node_id = next(
prepared_id
for source_id, prepared_id in iteration_node_map
if source_id == input_collection_edge.source.node_id
)
input_collection_output = self._state.results[input_collection_prepared_node_id]
input_collection = getattr(input_collection_output, input_collection_edge.source.field)
return len(input_collection)
def _get_new_node_iterations(
self, node: BaseInvocation, node_id: str, iteration_node_map: list[tuple[str, str]]
) -> list[int]:
if not isinstance(node, IterateInvocation):
return [-1]
iteration_count = self._get_iterator_iteration_count(node_id, iteration_node_map)
if iteration_count == 0:
return []
return list(range(iteration_count))
def _build_execution_edges(self, node_id: str, iteration_node_map: list[tuple[str, str]]) -> list[Edge]:
input_edges = self._state.graph._get_input_edges(node_id)
new_edges: list[Edge] = []
for edge in input_edges:
matching_inputs = [
prepared_id for source_id, prepared_id in iteration_node_map if source_id == edge.source.node_id
]
for input_node_id in matching_inputs:
new_edges.append(
Edge(
source=EdgeConnection(node_id=input_node_id, field=edge.source.field),
destination=EdgeConnection(node_id="", field=edge.destination.field),
)
)
return new_edges
def _create_execution_node_copy(self, node: BaseInvocation, node_id: str, iteration_index: int) -> BaseInvocation:
new_node = node.model_copy(deep=True)
new_node.id = uuid_string()
if isinstance(new_node, IterateInvocation):
new_node.index = iteration_index
self._state.execution_graph.add_node(new_node)
self._state._register_prepared_exec_node(new_node.id, node_id)
return new_node
def _attach_execution_edges(self, exec_node_id: str, new_edges: list[Edge]) -> None:
for edge in new_edges:
self._state.execution_graph.add_edge(
Edge(
source=edge.source,
destination=EdgeConnection(node_id=exec_node_id, field=edge.destination.field),
)
)
def _initialize_execution_node(self, exec_node_id: str) -> None:
inputs = self._state.execution_graph._get_input_edges(exec_node_id)
unmet = sum(1 for edge in inputs if edge.source.node_id not in self._state.executed)
self._state.indegree[exec_node_id] = unmet
self._state._try_resolve_if_node(exec_node_id)
self._state._enqueue_if_ready(exec_node_id)
def _get_collect_iteration_mappings(self, parent_node_ids: list[str]) -> list[tuple[str, str]]:
all_iteration_mappings: list[tuple[str, str]] = []
for source_node_id in parent_node_ids:
prepared_nodes = self._state.source_prepared_mapping[source_node_id]
all_iteration_mappings.extend((source_node_id, prepared_id) for prepared_id in prepared_nodes)
return all_iteration_mappings
def _get_parent_iteration_mappings(self, next_node_id: str, graph: nx.DiGraph) -> list[list[tuple[str, str]]]:
parent_node_ids = [source_id for source_id, _ in graph.in_edges(next_node_id)]
iterator_graph = self.iterator_graph(graph)
iterator_nodes = self.get_node_iterators(next_node_id, iterator_graph)
iterator_nodes_prepared = [list(self._state.source_prepared_mapping[node_id]) for node_id in iterator_nodes]
iterator_node_prepared_combinations = list(itertools.product(*iterator_nodes_prepared))
execution_graph = self._state.execution_graph.nx_graph_flat()
prepared_parent_mappings = [
[
(node_id, self.get_iteration_node(node_id, graph, execution_graph, prepared_iterators))
for node_id in parent_node_ids
]
for prepared_iterators in iterator_node_prepared_combinations
]
return [
mapping
for mapping in prepared_parent_mappings
if all(prepared_id is not None for _, prepared_id in mapping)
]
def create_execution_node(self, node_id: str, iteration_node_map: list[tuple[str, str]]) -> list[str]:
"""Prepares an iteration node and connects all edges, returning the new node id"""
node = self._state.graph.get_node(node_id)
iteration_indexes = self._get_new_node_iterations(node, node_id, iteration_node_map)
if not iteration_indexes:
return []
new_edges = self._build_execution_edges(node_id, iteration_node_map)
new_nodes: list[str] = []
for iteration_index in iteration_indexes:
new_node = self._create_execution_node_copy(node, node_id, iteration_index)
self._attach_execution_edges(new_node.id, new_edges)
self._initialize_execution_node(new_node.id)
new_nodes.append(new_node.id)
return new_nodes
def iterator_graph(self, base: Optional[nx.DiGraph] = None) -> nx.DiGraph:
"""Gets a DiGraph with edges to collectors removed so an ancestor search produces all active iterators for any node"""
g = base.copy() if base is not None else self._state.graph.nx_graph_flat()
collectors = (
n for n in self._state.graph.nodes if isinstance(self._state.graph.get_node(n), CollectInvocation)
)
for c in collectors:
g.remove_edges_from(list(g.in_edges(c)))
return g
def get_node_iterators(self, node_id: str, it_graph: Optional[nx.DiGraph] = None) -> list[str]:
g = it_graph or self.iterator_graph()
return [n for n in nx.ancestors(g, node_id) if isinstance(self._state.graph.get_node(n), IterateInvocation)]
def _get_prepared_nodes_for_source(self, source_node_id: str) -> set[str]:
return self._state.source_prepared_mapping[source_node_id]
def _get_parent_iterator_exec_nodes(
self, source_node_id: str, graph: nx.DiGraph, prepared_iterator_nodes: list[str]
) -> list[tuple[str, str]]:
iterator_source_node_mapping = [
(prepared_exec_node_id, self._state.prepared_source_mapping[prepared_exec_node_id])
for prepared_exec_node_id in prepared_iterator_nodes
]
return [
iterator_mapping
for iterator_mapping in iterator_source_node_mapping
if nx.has_path(graph, iterator_mapping[1], source_node_id)
]
def _matches_parent_iterators(
self, candidate_exec_node_id: str, parent_iterators: list[tuple[str, str]], execution_graph: nx.DiGraph
) -> bool:
return all(
nx.has_path(execution_graph, parent_iterator_exec_id, candidate_exec_node_id)
for parent_iterator_exec_id, _ in parent_iterators
)
def _get_direct_prepared_iterator_match(
self,
prepared_nodes: set[str],
prepared_iterator_nodes: list[str],
parent_iterators: list[tuple[str, str]],
execution_graph: nx.DiGraph,
) -> Optional[str]:
prepared_iterator = next((node_id for node_id in prepared_nodes if node_id in prepared_iterator_nodes), None)
if prepared_iterator is None:
return None
if self._matches_parent_iterators(prepared_iterator, parent_iterators, execution_graph):
return prepared_iterator
return None
def _find_prepared_node_matching_iterators(
self, prepared_nodes: set[str], parent_iterators: list[tuple[str, str]], execution_graph: nx.DiGraph
) -> Optional[str]:
return next(
(
node_id
for node_id in prepared_nodes
if self._matches_parent_iterators(node_id, parent_iterators, execution_graph)
),
None,
)
def get_iteration_node(
self,
source_node_id: str,
graph: nx.DiGraph,
execution_graph: nx.DiGraph,
prepared_iterator_nodes: list[str],
) -> Optional[str]:
prepared_nodes = self._get_prepared_nodes_for_source(source_node_id)
if len(prepared_nodes) == 1:
return next(iter(prepared_nodes))
parent_iterators = self._get_parent_iterator_exec_nodes(source_node_id, graph, prepared_iterator_nodes)
direct_iterator_match = self._get_direct_prepared_iterator_match(
prepared_nodes, prepared_iterator_nodes, parent_iterators, execution_graph
)
if direct_iterator_match is not None:
return direct_iterator_match
return self._find_prepared_node_matching_iterators(prepared_nodes, parent_iterators, execution_graph)
def prepare(self, base_g: Optional[nx.DiGraph] = None) -> Optional[str]:
g = base_g or self._state.graph.nx_graph_flat()
next_node_id = next(
(
node_id
for node_id in nx.topological_sort(g)
if node_id not in self._state.source_prepared_mapping
and (
not isinstance(self._state.graph.get_node(node_id), IterateInvocation)
or all(source_id in self._state.executed for source_id, _ in g.in_edges(node_id))
)
and not any(
isinstance(self._state.graph.get_node(ancestor_id), IterateInvocation)
and ancestor_id not in self._state.executed
for ancestor_id in nx.ancestors(g, node_id)
)
),
None,
)
if next_node_id is None:
return None
next_node = self._state.graph.get_node(next_node_id)
new_node_ids: list[str] = []
if isinstance(next_node, CollectInvocation):
next_node_parents = [source_id for source_id, _ in g.in_edges(next_node_id)]
create_results = self.create_execution_node(
next_node_id, self._get_collect_iteration_mappings(next_node_parents)
)
if create_results is not None:
new_node_ids.extend(create_results)
else:
for iteration_mappings in self._get_parent_iteration_mappings(next_node_id, g):
create_results = self.create_execution_node(next_node_id, iteration_mappings)
if create_results is not None:
new_node_ids.extend(create_results)
return next(iter(new_node_ids), None)
class _ExecutionScheduler:
"""Owns ready-queue ordering and indegree-driven execution transitions."""
def __init__(self, state: "GraphExecutionState") -> None:
self._state = state
def _validate_exec_node_ready_state(self, exec_node_id: str) -> None:
if exec_node_id not in self._state.execution_graph.nodes:
raise KeyError(f"exec node {exec_node_id} missing from execution_graph")
if exec_node_id not in self._state.indegree:
raise KeyError(f"indegree missing for exec node {exec_node_id}")
def _should_skip_ready_enqueue(self, exec_node_id: str) -> bool:
return (
self._state.indegree[exec_node_id] != 0
or exec_node_id in self._state.executed
or self._state._is_deferred_by_unresolved_if(exec_node_id)
)
def _get_ready_queue(self, exec_node_id: str) -> Deque[str]:
node_obj = self._state.execution_graph.nodes[exec_node_id]
return self.queue_for(self._state._type_key(node_obj))
def _insert_ready_node(self, queue: Deque[str], exec_node_id: str) -> None:
exec_node_path = self._state._get_iteration_path(exec_node_id)
for i, existing in enumerate(queue):
if self._state._get_iteration_path(existing) > exec_node_path:
queue.insert(i, exec_node_id)
return
queue.append(exec_node_id)
def _record_completed_node(self, exec_node_id: str, output: BaseInvocationOutput) -> None:
self._state._set_prepared_exec_state(exec_node_id, "executed")
self._state.executed.add(exec_node_id)
self._state.results[exec_node_id] = output
def _mark_source_node_complete(self, exec_node_id: str) -> None:
registry = self._state._prepared_registry()
source_node_id = registry.get_source_node_id(exec_node_id)
prepared_nodes = registry.get_prepared_ids(source_node_id)
if all(node_id in self._state.executed for node_id in prepared_nodes):
self._state.executed.add(source_node_id)
self._state.executed_history.append(source_node_id)
def _decrement_child_indegree(self, child_exec_node_id: str, parent_exec_node_id: str) -> None:
if child_exec_node_id not in self._state.indegree:
raise KeyError(f"indegree missing for exec node {child_exec_node_id}")
if self._state.indegree[child_exec_node_id] == 0:
raise RuntimeError(f"indegree underflow for {child_exec_node_id} from parent {parent_exec_node_id}")
self._state.indegree[child_exec_node_id] -= 1
def _release_downstream_nodes(self, exec_node_id: str) -> None:
for edge in self._state.execution_graph._get_output_edges(exec_node_id):
child = edge.destination.node_id
self._decrement_child_indegree(child, exec_node_id)
self._state._try_resolve_if_node(child)
if self._state.indegree[child] == 0:
self.enqueue_if_ready(child)
def queue_for(self, cls_name: str) -> Deque[str]:
q = self._state._ready_queues.get(cls_name)
if q is None:
q = deque()
self._state._ready_queues[cls_name] = q
return q
def remove_from_ready_queues(self, exec_node_id: str) -> None:
for q in self._state._ready_queues.values():
try:
q.remove(exec_node_id)
except ValueError:
continue
def enqueue_if_ready(self, exec_node_id: str) -> None:
"""Push exec_node_id to its class queue if unmet inputs == 0."""
self._validate_exec_node_ready_state(exec_node_id)
if self._should_skip_ready_enqueue(exec_node_id):
return
queue = self._get_ready_queue(exec_node_id)
if exec_node_id in queue:
return
self._state._set_prepared_exec_state(exec_node_id, "ready")
self._insert_ready_node(queue, exec_node_id)
def get_next_node(self) -> Optional[BaseInvocation]:
"""Gets the next ready node: FIFO within class, drain class before switching."""
while True:
if self._state._active_class:
q = self._state._ready_queues.get(self._state._active_class)
while q:
exec_node_id = q.popleft()
if exec_node_id not in self._state.executed:
return self._state.execution_graph.nodes[exec_node_id]
self._state._active_class = None
continue
seen = set(self._state.ready_order)
next_class = next(
(cls_name for cls_name in self._state.ready_order if self._state._ready_queues.get(cls_name)),
None,
)
if next_class is None:
next_class = next(
(
cls_name
for cls_name in sorted(k for k in self._state._ready_queues.keys() if k not in seen)
if self._state._ready_queues[cls_name]
),
None,
)
if next_class is None:
return None
self._state._active_class = next_class
def complete(self, exec_node_id: str, output: BaseInvocationOutput) -> None:
if exec_node_id not in self._state.execution_graph.nodes:
return
self._record_completed_node(exec_node_id, output)
self._mark_source_node_complete(exec_node_id)
self._release_downstream_nodes(exec_node_id)
class _ExecutionRuntime:
"""Provides runtime-only helpers such as iteration-path lookup and input hydration."""
def __init__(self, state: "GraphExecutionState") -> None:
self._state = state
def _get_cached_iteration_path(self, exec_node_id: str) -> Optional[tuple[int, ...]]:
registry = self._state._prepared_registry()
metadata_iteration_path = registry.get_iteration_path(exec_node_id)
if metadata_iteration_path is not None:
return metadata_iteration_path
return self._state._iteration_path_cache.get(exec_node_id)
def _get_iteration_source_node_id(self, exec_node_id: str) -> Optional[str]:
if exec_node_id not in self._state.prepared_source_mapping:
return None
return self._state._prepared_registry().get_source_node_id(exec_node_id)
def _get_ordered_iterator_sources(self, source_node_id: str) -> list[str]:
iterator_graph = self._state._iterator_graph(self._state.graph.nx_graph())
iterator_sources = [
node_id
for node_id in nx.ancestors(iterator_graph, source_node_id)
if isinstance(self._state.graph.get_node(node_id), IterateInvocation)
]
topo = list(nx.topological_sort(iterator_graph))
topo_index = {node_id: i for i, node_id in enumerate(topo)}
iterator_sources.sort(key=lambda node_id: topo_index.get(node_id, 0))
return iterator_sources
def _get_iterator_exec_id(
self, iterator_source_id: str, exec_node_id: str, execution_graph: nx.DiGraph
) -> Optional[str]:
prepared = self._state.source_prepared_mapping.get(iterator_source_id)
if not prepared:
return None
return next((pid for pid in prepared if nx.has_path(execution_graph, pid, exec_node_id)), None)
def _build_iteration_path(self, exec_node_id: str, source_node_id: str) -> tuple[int, ...]:
iterator_sources = self._get_ordered_iterator_sources(source_node_id)
execution_graph = self._state.execution_graph.nx_graph()
path: list[int] = []
for iterator_source_id in iterator_sources:
iterator_exec_id = self._get_iterator_exec_id(iterator_source_id, exec_node_id, execution_graph)
if iterator_exec_id is None:
continue
iterator_node = self._state.execution_graph.nodes.get(iterator_exec_id)
if isinstance(iterator_node, IterateInvocation):
path.append(iterator_node.index)
node_obj = self._state.execution_graph.nodes.get(exec_node_id)
if isinstance(node_obj, IterateInvocation):
path.append(node_obj.index)
return tuple(path)
def _cache_iteration_path(self, exec_node_id: str, iteration_path: tuple[int, ...]) -> tuple[int, ...]:
self._state._iteration_path_cache[exec_node_id] = iteration_path
self._state._prepared_registry().set_iteration_path(exec_node_id, iteration_path)
return iteration_path
def get_iteration_path(self, exec_node_id: str) -> tuple[int, ...]:
"""Best-effort outer->inner iteration indices for an execution node, stopping at collectors."""
cached = self._get_cached_iteration_path(exec_node_id)
if cached is not None:
return cached
source_node_id = self._get_iteration_source_node_id(exec_node_id)
if source_node_id is None:
return self._cache_iteration_path(exec_node_id, ())
return self._cache_iteration_path(exec_node_id, self._build_iteration_path(exec_node_id, source_node_id))
def _sort_collect_input_edges(self, input_edges: list[Edge], field_name: str) -> list[Edge]:
matching_edges = [edge for edge in input_edges if edge.destination.field == field_name]
matching_edges.sort(key=lambda edge: (self.get_iteration_path(edge.source.node_id), edge.source.node_id))
return matching_edges
def _get_copied_result_value(self, edge: Edge) -> Any:
return copydeep(getattr(self._state.results[edge.source.node_id], edge.source.field))
def _build_collect_collection(self, input_edges: list[Edge]) -> list[Any]:
item_edges = self._sort_collect_input_edges(input_edges, ITEM_FIELD)
collection_edges = self._sort_collect_input_edges(input_edges, COLLECTION_FIELD)
output_collection = []
for edge in collection_edges:
source_value = self._get_copied_result_value(edge)
if isinstance(source_value, list):
output_collection.extend(source_value)
else:
output_collection.append(source_value)
output_collection.extend(self._get_copied_result_value(edge) for edge in item_edges)
return output_collection
def _set_node_inputs(
self, node: BaseInvocation, input_edges: list[Edge], allowed_fields: Optional[set[str]] = None
) -> None:
for edge in input_edges:
if allowed_fields is not None and edge.destination.field not in allowed_fields:
continue
setattr(node, edge.destination.field, self._get_copied_result_value(edge))
def _prepare_collect_inputs(self, node: "CollectInvocation", input_edges: list[Edge]) -> None:
node.collection = self._build_collect_collection(input_edges)
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"}
self._set_node_inputs(node, input_edges, allowed_fields)
def _prepare_default_inputs(self, node: BaseInvocation, input_edges: list[Edge]) -> None:
self._set_node_inputs(node, input_edges)
def prepare_inputs(self, node: BaseInvocation) -> None:
input_edges = self._state.execution_graph._get_input_edges(node.id)
if isinstance(node, CollectInvocation):
self._prepare_collect_inputs(node, input_edges)
return
if isinstance(node, IfInvocation):
self._prepare_if_inputs(node, input_edges)
return
self._prepare_default_inputs(node, input_edges)
def get_output_field_type(node: BaseInvocation, field: str) -> Any:
# TODO(psyche): This is awkward - if field_info is None, it means the field is not defined in the output, which
# really should raise. The consumers of this utility expect it to never raise, and return None instead. Fixing this
# would require some fairly significant changes and I don't want risk breaking anything.
try:
invocation_class = type(node)
invocation_output_class = invocation_class.get_output_annotation()
field_info = invocation_output_class.model_fields.get(field)
assert field_info is not None, f"Output field '{field}' not found in {invocation_output_class.get_type()}"
output_field_type = field_info.annotation
return output_field_type
except Exception:
return None
def get_input_field_type(node: BaseInvocation, field: str) -> Any:
# TODO(psyche): This is awkward - if field_info is None, it means the field is not defined in the output, which
# really should raise. The consumers of this utility expect it to never raise, and return None instead. Fixing this
# would require some fairly significant changes and I don't want risk breaking anything.
try:
invocation_class = type(node)
field_info = invocation_class.model_fields.get(field)
assert field_info is not None, f"Input field '{field}' not found in {invocation_class.get_type()}"
input_field_type = field_info.annotation
return input_field_type
except Exception:
return None
def is_union_subtype(t1, t2):
t1_args = get_args(t1)
t2_args = get_args(t2)
if not t1_args:
# t1 is a single type
return t1 in t2_args
else:
# t1 is a Union, check that all of its types are in t2_args
return all(arg in t2_args for arg in t1_args)
def is_list_or_contains_list(t):
t_args = get_args(t)
# If the type is a List
if get_origin(t) is list:
return True
# If the type is a Union
elif t_args:
# Check if any of the types in the Union is a List
for arg in t_args:
if get_origin(arg) is list:
return True
return False
def is_any(t: Any) -> bool:
return t == Any or Any in get_args(t)
def extract_collection_item_types(t: Any) -> set[Any]:
"""Extracts list item types from a collection annotation, including unions containing list branches."""
if is_any(t):
return {Any}
if get_origin(t) is list:
return {arg for arg in get_args(t) if arg != NoneType}
item_types: set[Any] = set()
for arg in get_args(t):
if is_any(arg):
item_types.add(Any)
elif get_origin(arg) is list:
item_types.update(item_arg for item_arg in get_args(arg) if item_arg != NoneType)
return item_types
def are_connection_types_compatible(from_type: Any, to_type: Any) -> bool:
if not from_type or not to_type:
return False
# Ports are compatible
if from_type == to_type or is_any(from_type) or is_any(to_type):
return True
if from_type in get_args(to_type):
return True
if to_type in get_args(from_type):
return True
# allow int -> float, pydantic will cast for us
if from_type is int and to_type is float:
return True
# allow int|float -> str, pydantic will cast for us
if (from_type is int or from_type is float) and to_type is str:
return True
# Prefer issubclass when both are real classes
try:
if isinstance(from_type, type) and isinstance(to_type, type):
return issubclass(from_type, to_type)
except TypeError:
pass
# Union-to-Union (or Union-to-non-Union) handling
return is_union_subtype(from_type, to_type)
def are_connections_compatible(
from_node: BaseInvocation, from_field: str, to_node: BaseInvocation, to_field: str
) -> bool:
"""Determines if a connection between fields of two nodes is compatible."""
# TODO: handle iterators and collectors
from_type = get_output_field_type(from_node, from_field)
to_type = get_input_field_type(to_node, to_field)
return are_connection_types_compatible(from_type, to_type)
T = TypeVar("T")
def copydeep(obj: T) -> T:
"""Deep-copies an object. If it is a pydantic model, use the model's copy method."""
if isinstance(obj, BaseModel):
return obj.model_copy(deep=True)
return copy.deepcopy(obj)
class NodeAlreadyInGraphError(ValueError):
pass
class InvalidEdgeError(ValueError):
pass
class NodeNotFoundError(ValueError):
pass
class NodeAlreadyExecutedError(ValueError):
pass
class DuplicateNodeIdError(ValueError):
pass
class NodeFieldNotFoundError(ValueError):
pass
class NodeIdMismatchError(ValueError):
pass
class CyclicalGraphError(ValueError):
pass
class UnknownGraphValidationError(ValueError):
pass
class NodeInputError(ValueError):
"""Raised when a node fails preparation. This occurs when a node's inputs are being set from its incomers, but an
input fails validation.
Attributes:
node: The node that failed preparation. Note: only successfully set fields will be accurate. Review the error to
determine which field caused the failure.
"""
def __init__(self, node: BaseInvocation, e: ValidationError):
self.original_error = e
self.node = node
# When preparing a node, we set each input one-at-a-time. We may thus safely assume that the first error
# represents the first input that failed.
self.failed_input = loc_to_dot_sep(e.errors()[0]["loc"])
super().__init__(f"Node {node.id} has invalid incoming input for {self.failed_input}")
def loc_to_dot_sep(loc: tuple[Union[str, int], ...]) -> str:
"""Helper to pretty-print pydantic error locations as dot-separated strings.
Taken from https://docs.pydantic.dev/latest/errors/errors/#customize-error-messages
"""
path = ""
for i, x in enumerate(loc):
if isinstance(x, str):
if i > 0:
path += "."
path += x
else:
path += f"[{x}]"
return path
@invocation_output("iterate_output")
class IterateInvocationOutput(BaseInvocationOutput):
"""Used to connect iteration outputs. Will be expanded to a specific output."""
item: Any = OutputField(
description="The item being iterated over", title="Collection Item", ui_type=UIType._CollectionItem
)