-
Notifications
You must be signed in to change notification settings - Fork 204
Expand file tree
/
Copy pathtest_graph.py
More file actions
1691 lines (1412 loc) · 63.2 KB
/
Copy pathtest_graph.py
File metadata and controls
1691 lines (1412 loc) · 63.2 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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import inspect
import pathlib
import sys
import uuid
from itertools import permutations
from types import ModuleType
import pandas as pd
import pytest
import hamilton.graph_utils
import hamilton.htypes
from hamilton import ad_hoc_utils, base, graph, node
from hamilton import function_modifiers as fm
from hamilton.execution import graph_functions
from hamilton.function_modifiers import schema
from hamilton.lifecycle import base as lifecycle_base
from hamilton.node import NodeType
import tests.resources.bad_functions
import tests.resources.compatible_input_types
import tests.resources.config_modifier
import tests.resources.cyclic_functions
import tests.resources.display_name_functions
import tests.resources.display_name_list_functions
import tests.resources.dummy_functions
import tests.resources.dummy_functions_module_override
import tests.resources.extract_column_nodes
import tests.resources.extract_columns_execution_count
import tests.resources.functions_with_generics
import tests.resources.incompatible_input_types
import tests.resources.layered_decorators
import tests.resources.multiple_decorators_together
import tests.resources.optional_dependencies
import tests.resources.parametrized_inputs
import tests.resources.parametrized_nodes
import tests.resources.test_default_args
import tests.resources.typing_vs_not_typing
@pytest.mark.parametrize(
("child_name", "parent_name", "expected"),
[
("foo", "foo", True), # same module
("foo.bar", "foo", True), # direct child
("foo.bar.baz", "foo", True), # nested child
("foo.bar.baz", "foo.bar", True), # nested child of subpackage
("foobar", "foo", False), # not a submodule, just a prefix without dot separator
("hamilton.function_modifiers", "modifiers", False), # substring match, not a submodule
("hamilton.function_modifiers.dependencies", "modifiers", False), # substring deeper
("x.foo.y", "foo", False), # parent name in the middle, not a prefix
("bar", "foo", False), # completely unrelated
],
ids=[
"same_module",
"direct_child",
"nested_child",
"nested_child_of_subpackage",
"prefix_without_dot",
"substring_not_submodule",
"substring_deeper",
"parent_in_middle",
"unrelated",
],
)
def test_is_submodule(child_name, parent_name, expected):
"""Tests that is_submodule correctly checks module hierarchy using prefix matching."""
child = ModuleType(child_name)
parent = ModuleType(parent_name)
assert hamilton.graph_utils.is_submodule(child, parent) == expected
def test_find_functions():
"""Tests that we filter out _ functions when passed a module and don't pull in anything from the imports."""
expected = [
("A", tests.resources.dummy_functions.A),
("B", tests.resources.dummy_functions.B),
("C", tests.resources.dummy_functions.C),
]
actual = hamilton.graph_utils.find_functions(tests.resources.dummy_functions)
assert len(actual) == len(expected)
assert actual == expected
def test_find_functions_excludes_imports_with_substring_module_name():
"""Regression test: imported functions should not be included when the user module's
name is a substring of the imported function's module path.
Previously, is_submodule used `parent.__name__ in child.__name__` (substring match),
which caused e.g. a module named 'modifiers' to pull in functions from
'hamilton.function_modifiers'.
"""
# Create a fake module named "modifiers" with one real function and two imports
mod = ModuleType("modifiers")
def my_func(x: int) -> int:
return x * 2
# Assign the function to the module so inspect.getmodule can resolve it
my_func.__module__ = "modifiers"
mod.my_func = my_func
mod.source = fm.source
mod.value = fm.value
# Register in sys.modules so inspect.getmodule can find it
sys.modules["modifiers"] = mod
try:
actual = hamilton.graph_utils.find_functions(mod)
actual_names = [name for name, _ in actual]
assert actual_names == ["my_func"], (
f"Expected only ['my_func'] but got {actual_names}. "
"Imported functions from hamilton.function_modifiers should not be included."
)
finally:
del sys.modules["modifiers"]
def test_find_functions_from_temporary_function_module():
"""Tests that we handle the TemporaryFunctionModule object correctly."""
expected = [
("A", tests.resources.dummy_functions.A),
("B", tests.resources.dummy_functions.B),
("C", tests.resources.dummy_functions.C),
]
func_module = ad_hoc_utils.create_temporary_module(
tests.resources.dummy_functions.A,
tests.resources.dummy_functions.B,
tests.resources.dummy_functions.C,
)
actual = hamilton.graph_utils.find_functions(func_module)
assert len(actual) == len(expected)
assert [node_name for node_name, _ in actual] == [node_name for node_name, _ in expected]
assert [fn.__code__ for _, fn in actual] == [
fn.__code__ for _, fn in expected
] # easy way to say they're the same
def test_add_dependency_missing_param_type():
"""Tests case that we error if types are missing from a parameter."""
with pytest.raises(ValueError):
a_sig = inspect.signature(tests.resources.bad_functions.A)
node.Node(
"A", a_sig.return_annotation, "A doc", tests.resources.bad_functions.A
) # should error out
def test_add_dependency_missing_function_type():
"""Tests case that we error if types are missing from a function."""
with pytest.raises(ValueError):
b_sig = inspect.signature(tests.resources.bad_functions.B)
node.Node(
"B", b_sig.return_annotation, "B doc", tests.resources.bad_functions.B
) # should error out
def test_add_dependency_strict_node_dependencies():
"""Tests that we add node dependencies between functions correctly.
Setup here is: B depends on A. So A is depended on by B. B is not depended on by anyone.
"""
b_sig = inspect.signature(tests.resources.dummy_functions.B)
func_node = node.Node("B", b_sig.return_annotation, "B doc", tests.resources.dummy_functions.B)
func_name = "B"
nodes = {
"A": node.Node(
"A",
inspect.signature(tests.resources.dummy_functions.A).return_annotation,
"A doc",
tests.resources.dummy_functions.A,
)
}
param_name = "A"
param_type = b_sig.parameters["A"].annotation
graph.add_dependency(
func_node,
func_name,
nodes,
param_name,
param_type,
lifecycle_base.LifecycleAdapterSet(),
)
assert nodes["A"] == func_node.dependencies[0]
assert func_node.depended_on_by == []
def test_add_dependency_input_nodes_mismatch_on_types():
"""Tests that if two functions request an input that has incompatible types, we error out."""
b_sig = inspect.signature(tests.resources.incompatible_input_types.b)
c_sig = inspect.signature(tests.resources.incompatible_input_types.c)
nodes = {
"b": node.Node.from_fn(tests.resources.incompatible_input_types.b),
"c": node.Node.from_fn(tests.resources.incompatible_input_types.c),
}
nodes["b"]._originating_functions = (tests.resources.incompatible_input_types.b,)
nodes["c"]._originating_functions = (tests.resources.incompatible_input_types.c,)
param_name = "a"
# this adds 'a' to nodes
graph.add_dependency(
nodes["b"],
"b",
nodes,
param_name,
b_sig.parameters[param_name].annotation,
lifecycle_base.LifecycleAdapterSet(),
)
assert "a" in nodes
# adding dependency of c on a should fail because the types are incompatible
with pytest.raises(ValueError):
graph.add_dependency(
nodes["c"],
"c",
nodes,
param_name,
c_sig.parameters[param_name].annotation,
lifecycle_base.LifecycleAdapterSet(),
)
def test_add_dependency_input_nodes_mismatch_on_types_complex():
"""Tests a more complex scenario we don't support right now with input types."""
e_sig = inspect.signature(tests.resources.incompatible_input_types.e)
f_sig = inspect.signature(tests.resources.incompatible_input_types.f)
nodes = {
"e": node.Node.from_fn(tests.resources.incompatible_input_types.e),
"f": node.Node.from_fn(tests.resources.incompatible_input_types.f),
}
nodes["e"]._originating_functions = (tests.resources.incompatible_input_types.e,)
nodes["f"]._originating_functions = (tests.resources.incompatible_input_types.f,)
param_name = "d"
# this adds 'a' to nodes
graph.add_dependency(
nodes["e"],
"e",
nodes,
param_name,
e_sig.parameters[param_name].annotation,
lifecycle_base.LifecycleAdapterSet(),
)
assert "d" in nodes
# adding dependency of c on a should fail because the types are incompatible
with pytest.raises(ValueError):
graph.add_dependency(
nodes["e"],
"e",
nodes,
param_name,
f_sig.parameters[param_name].annotation,
lifecycle_base.LifecycleAdapterSet(),
)
def test_add_dependency_input_nodes_compatible_types():
"""Tests that if functions request an input that we correctly accept compatible types."""
b_sig = inspect.signature(tests.resources.compatible_input_types.b)
c_sig = inspect.signature(tests.resources.compatible_input_types.c)
d_sig = inspect.signature(tests.resources.compatible_input_types.d)
nodes = {
"b": node.Node.from_fn(tests.resources.compatible_input_types.b),
"c": node.Node.from_fn(tests.resources.compatible_input_types.c),
"d": node.Node.from_fn(tests.resources.compatible_input_types.d),
}
nodes["b"]._originating_functions = (tests.resources.compatible_input_types.b,)
nodes["c"]._originating_functions = (tests.resources.compatible_input_types.c,)
nodes["d"]._originating_functions = (tests.resources.compatible_input_types.d,)
# what we want to add
param_name = "a"
# this adds 'a' to nodes
graph.add_dependency(
nodes["b"],
"b",
nodes,
param_name,
b_sig.parameters[param_name].annotation,
lifecycle_base.LifecycleAdapterSet(),
)
assert "a" in nodes
# this adds 'a' to 'c' as well.
graph.add_dependency(
nodes["c"],
"c",
nodes,
param_name,
c_sig.parameters[param_name].annotation,
lifecycle_base.LifecycleAdapterSet(),
)
# test that we shrink the type to the tighter type
assert nodes["a"].type == str
graph.add_dependency(
nodes["d"],
"d",
nodes,
param_name,
d_sig.parameters[param_name].annotation,
lifecycle_base.LifecycleAdapterSet(),
)
def test_add_dependency_input_nodes_compatible_types_order_check():
"""Tests that if functions request an input that we correctly accept compatible types independent of order.
This just reorders test_add_dependency_input_nodes_compatible_types to ensure the outcome does not change.
"""
b_sig = inspect.signature(tests.resources.compatible_input_types.b)
c_sig = inspect.signature(tests.resources.compatible_input_types.c)
d_sig = inspect.signature(tests.resources.compatible_input_types.d)
nodes = {
"b": node.Node.from_fn(tests.resources.compatible_input_types.b),
"c": node.Node.from_fn(tests.resources.compatible_input_types.c),
"d": node.Node.from_fn(tests.resources.compatible_input_types.d),
}
nodes["b"]._originating_functions = (tests.resources.compatible_input_types.b,)
nodes["c"]._originating_functions = (tests.resources.compatible_input_types.c,)
nodes["d"]._originating_functions = (tests.resources.compatible_input_types.d,)
# what we want to add
param_name = "a"
# this adds 'a' to nodes
graph.add_dependency(
nodes["c"],
"c",
nodes,
param_name,
c_sig.parameters[param_name].annotation,
lifecycle_base.LifecycleAdapterSet(),
)
assert "a" in nodes
assert nodes["a"].type == str
# this adds 'a' to 'c' as well.
graph.add_dependency(
nodes["b"],
"b",
nodes,
param_name,
b_sig.parameters[param_name].annotation,
lifecycle_base.LifecycleAdapterSet(),
)
# test that type didn't change
assert nodes["a"].type == str
graph.add_dependency(
nodes["d"],
"d",
nodes,
param_name,
d_sig.parameters[param_name].annotation,
lifecycle_base.LifecycleAdapterSet(),
)
def test_typing_to_primitive_conversion():
"""Tests that we can mix function output being typing type, and dependent function using primitive type."""
b_sig = inspect.signature(tests.resources.typing_vs_not_typing.B)
func_node = node.Node(
"B", b_sig.return_annotation, "B doc", tests.resources.typing_vs_not_typing.B
)
func_name = "B"
nodes = {
"A": node.Node(
"A",
inspect.signature(tests.resources.typing_vs_not_typing.A).return_annotation,
"A doc",
tests.resources.typing_vs_not_typing.A,
)
}
param_name = "A"
param_type = b_sig.parameters["A"].annotation
graph.add_dependency(
func_node,
func_name,
nodes,
param_name,
param_type,
lifecycle_base.LifecycleAdapterSet(),
)
assert nodes["A"] == func_node.dependencies[0]
assert func_node.depended_on_by == []
def test_primitive_to_typing_conversion():
"""Tests that we can mix function output being a primitive type, and dependent function using typing type."""
b_sig = inspect.signature(tests.resources.typing_vs_not_typing.B2)
func_node = node.Node(
"B2", b_sig.return_annotation, "B2 doc", tests.resources.typing_vs_not_typing.B2
)
func_name = "B2"
nodes = {
"A2": node.Node(
"A2",
inspect.signature(tests.resources.typing_vs_not_typing.A2).return_annotation,
"A2 doc",
tests.resources.typing_vs_not_typing.A2,
)
}
param_name = "A2"
param_type = b_sig.parameters["A2"].annotation
graph.add_dependency(
func_node,
func_name,
nodes,
param_name,
param_type,
lifecycle_base.LifecycleAdapterSet(),
)
assert nodes["A2"] == func_node.dependencies[0]
assert func_node.depended_on_by == []
def test_throwing_error_on_incompatible_types():
"""Tests we error on incompatible types."""
d_sig = inspect.signature(tests.resources.bad_functions.D)
func_node = node.Node("D", d_sig.return_annotation, "D doc", tests.resources.bad_functions.D)
func_name = "D"
nodes = {
"C": node.Node(
"C",
inspect.signature(tests.resources.bad_functions.C).return_annotation,
"C doc",
tests.resources.bad_functions.C,
)
}
param_name = "C"
param_type = d_sig.parameters["C"].annotation
with pytest.raises(ValueError):
graph.add_dependency(
func_node,
func_name,
nodes,
param_name,
param_type,
lifecycle_base.LifecycleAdapterSet(),
)
def test_add_dependency_user_nodes():
"""Tests that we add node user defined dependencies correctly.
Setup here is: A depends on b and c. But we're only doing one call. So expecting A having 'b' as a dependency,
and 'b' is depended on by A.
"""
a_sig = inspect.signature(tests.resources.dummy_functions.A)
func_node = node.Node("A", a_sig.return_annotation, "A doc", tests.resources.dummy_functions.A)
func_name = "A"
nodes = {}
param_name = "b"
param_type = a_sig.parameters["b"].annotation
graph.add_dependency(
func_node,
func_name,
nodes,
param_name,
param_type,
lifecycle_base.LifecycleAdapterSet(),
)
# user node is created and added to nodes.
assert nodes["b"] == func_node.dependencies[0]
assert nodes["b"].depended_on_by[0] == func_node
assert func_node.depended_on_by == []
def create_testing_nodes():
"""Helper function for creating the nodes represented in dummy_functions.py."""
nodes = {
"A": node.Node.from_fn(fn=tests.resources.dummy_functions.A, name="A"),
"B": node.Node.from_fn(fn=tests.resources.dummy_functions.B, name="B"),
"C": node.Node.from_fn(fn=tests.resources.dummy_functions.C, name="C"),
"b": node.Node(
"b",
inspect.signature(tests.resources.dummy_functions.A).parameters["b"].annotation,
node_source=NodeType.EXTERNAL,
),
"c": node.Node(
"c",
inspect.signature(tests.resources.dummy_functions.A).parameters["c"].annotation,
node_source=NodeType.EXTERNAL,
),
}
nodes["A"].dependencies.append(nodes["b"])
nodes["A"].dependencies.append(nodes["c"])
nodes["A"].depended_on_by.append(nodes["B"])
nodes["A"].depended_on_by.append(nodes["C"])
nodes["b"].depended_on_by.append(nodes["A"])
nodes["c"].depended_on_by.append(nodes["A"])
nodes["B"].dependencies.append(nodes["A"])
nodes["C"].dependencies.append(nodes["A"])
return nodes
def create_testing_nodes_override_B():
"""Helper function for creating the nodes represented in dummy_functions.py
with node B overridden by dummy_functions_module_override.py."""
nodes = {
"A": node.Node.from_fn(fn=tests.resources.dummy_functions.A, name="A"),
"B": node.Node.from_fn(fn=tests.resources.dummy_functions_module_override.B, name="B"),
"C": node.Node.from_fn(fn=tests.resources.dummy_functions.C, name="C"),
"b": node.Node(
"b",
inspect.signature(tests.resources.dummy_functions.A).parameters["b"].annotation,
node_source=NodeType.EXTERNAL,
),
"c": node.Node(
"c",
inspect.signature(tests.resources.dummy_functions.A).parameters["c"].annotation,
node_source=NodeType.EXTERNAL,
),
}
nodes["A"].dependencies.append(nodes["b"])
nodes["A"].dependencies.append(nodes["c"])
nodes["A"].depended_on_by.append(nodes["B"])
nodes["A"].depended_on_by.append(nodes["C"])
nodes["b"].depended_on_by.append(nodes["A"])
nodes["c"].depended_on_by.append(nodes["A"])
nodes["B"].dependencies.append(nodes["A"])
nodes["C"].dependencies.append(nodes["A"])
return nodes
def test_create_function_graph_simple():
"""Tests that we create a simple function graph."""
expected = create_testing_nodes()
actual = graph.create_function_graph(tests.resources.dummy_functions, config={})
assert actual == expected
def test_create_function_graph_with_override():
"""Tests that we can override nodes from later modules in function graph."""
override_expected = create_testing_nodes_override_B()
override_actual = graph.create_function_graph(
tests.resources.dummy_functions,
tests.resources.dummy_functions_module_override,
config={},
allow_module_overrides=True,
)
assert override_expected == override_actual
def test_execute():
"""Tests graph execution along with basic memoization since A is depended on by two functions."""
nodes = create_testing_nodes()
inputs = {"b": 2, "c": 5}
expected = {"A": 7, "B": 49, "C": 14, "b": 2, "c": 5}
actual = graph_functions.execute_subdag(nodes=nodes.values(), inputs=inputs)
assert actual == expected
actual = graph_functions.execute_subdag(nodes=nodes.values(), inputs=inputs, overrides={"A": 8})
assert actual["A"] == 8
def test_get_required_functions():
"""Exercises getting the subset of the graph for computation on the toy example we have constructed."""
nodes = create_testing_nodes()
final_vars = ["A", "B"]
expected_user_nodes = {nodes["b"], nodes["c"]}
expected_nodes = {nodes["A"], nodes["B"], nodes["b"], nodes["c"]} # we skip 'C'
fg = graph.FunctionGraph.from_modules(tests.resources.dummy_functions, config={})
actual_nodes, actual_ud_nodes = fg.get_upstream_nodes(final_vars)
assert actual_nodes == expected_nodes
assert actual_ud_nodes == expected_user_nodes
def test_get_downstream_nodes():
"""Exercises getting the downstream subset of the graph for computation on the toy example we have constructed."""
nodes = create_testing_nodes()
var_changes = ["A"]
expected_nodes = {nodes["B"], nodes["C"], nodes["A"]}
# expected_nodes = {nodes['A'], nodes['B'], nodes['b'], nodes['c']} # we skip 'C'
fg = graph.FunctionGraph.from_modules(tests.resources.dummy_functions, config={})
actual_nodes = fg.get_downstream_nodes(var_changes)
assert actual_nodes == expected_nodes
def test_get_upstream_nodes_large_chain_no_recursion_error():
"""Regression test: get_upstream_nodes with only final_node on a large chain DAG.
A recursive DFS would exceed Python's recursion limit (~1000) when traversing
a long dependency chain from a single final node. This test verifies that
the iterative DFS in directional_dfs_traverse handles large DAGs correctly.
Chain size is chosen to exceed recursion limit: 1200 nodes > 1000.
"""
def step(prev: float) -> float:
"""Single step in a linear chain."""
return prev + 1.0
# Build a linear chain: node_0 -> node_1 -> ... -> node_N
chain_size = sys.getrecursionlimit() + 200 # Exceeds recursion limit
config = {}
for i in range(chain_size):
prev = f"node_{i - 1}" if i > 0 else 0.0
config[f"node_{i}"] = {
"prev": fm.source(prev) if i > 0 else fm.value(0.0),
}
decorated = fm.parameterize(**config)(step)
module = ad_hoc_utils.create_temporary_module(decorated, module_name="large_chain")
fg = graph.FunctionGraph.from_modules(module, config={})
final_node = f"node_{chain_size - 1}"
# This would raise RecursionError with recursive DFS
nodes, user_nodes = fg.get_upstream_nodes([final_node])
assert len(nodes) == chain_size
assert len(user_nodes) == 0
assert all(fg.nodes[f"node_{i}"] in nodes for i in range(chain_size))
def test_get_upstream_nodes_diamond_dag():
"""Tests that diamond-shaped DAGs don't produce duplicate visits.
DAG shape:
x, y (inputs)
|
left right (both depend on x and y)
\\ /
bottom (depends on left and right)
The shared inputs x and y are reachable via both left and right.
With a naive iterative DFS (mark-on-pop), x and y could be pushed
onto the stack multiple times. This verifies they appear exactly once.
"""
def left(x: int, y: int) -> int:
return x + y
def right(x: int, y: int) -> int:
return x * y
def bottom(left: int, right: int) -> int:
return left + right
module = ad_hoc_utils.create_temporary_module(left, right, bottom)
fg = graph.FunctionGraph.from_modules(module, config={})
nodes, user_nodes = fg.get_upstream_nodes(["bottom"])
assert len(nodes) == 5 # x, y, left, right, bottom
assert {n.name for n in nodes} == {"x", "y", "left", "right", "bottom"}
# x and y are external inputs
assert {n.name for n in user_nodes} == {"x", "y"}
def test_get_upstream_nodes_single_node():
"""Tests traversal of a single node with no dependencies."""
def solo() -> int:
return 42
module = ad_hoc_utils.create_temporary_module(solo)
fg = graph.FunctionGraph.from_modules(module, config={})
nodes, user_nodes = fg.get_upstream_nodes(["solo"])
assert len(nodes) == 1
assert {n.name for n in nodes} == {"solo"}
assert len(user_nodes) == 0
def test_get_upstream_nodes_overlapping_starting_nodes():
"""Tests that overlapping subgraphs from multiple starting nodes are handled correctly.
DAG shape:
shared (input)
/ \\
a b (both depend on shared)
Requesting both a and b as starting nodes means 'shared' is reachable
from both traversals. It should still appear exactly once in the result.
"""
def a(shared: int) -> int:
return shared + 1
def b(shared: int) -> int:
return shared + 2
module = ad_hoc_utils.create_temporary_module(a, b)
fg = graph.FunctionGraph.from_modules(module, config={})
nodes, user_nodes = fg.get_upstream_nodes(["a", "b"])
assert len(nodes) == 3 # shared, a, b
assert {n.name for n in nodes} == {"shared", "a", "b"}
assert {n.name for n in user_nodes} == {"shared"}
def test_function_graph_from_multiple_sources():
fg = graph.FunctionGraph.from_modules(
tests.resources.dummy_functions, tests.resources.parametrized_nodes, config={}
)
assert len(fg.get_nodes()) == 8 # we take the union of all of them, and want to test that
def test_end_to_end_with_parametrized_nodes():
"""Tests that a simple function graph with parametrized nodes works end-to-end"""
fg = graph.FunctionGraph.from_modules(tests.resources.parametrized_nodes, config={})
results = fg.execute(fg.get_nodes(), {})
assert results == {"parametrized_1": 1, "parametrized_2": 2, "parametrized_3": 3}
def test_end_to_end_with_parametrized_inputs():
fg = graph.FunctionGraph.from_modules(
tests.resources.parametrized_inputs, config={"static_value": 3}
)
results = fg.execute(fg.get_nodes())
assert results == {
"input_1": 1,
"input_2": 2,
"input_3": 3,
"output_1": 1 + 3,
"output_2": 2 + 3,
"output_12": 1 + 2 + 3,
"output_123": 1 + 2 + 3 + 3,
"static_value": 3,
}
def test_get_required_functions_askfor_config():
"""Tests that a simple function graph with parametrized nodes works end-to-end"""
fg = graph.FunctionGraph.from_modules(tests.resources.parametrized_nodes, config={"a": 1})
nodes, user_nodes = fg.get_upstream_nodes(["a", "parametrized_1"])
(n,) = user_nodes
assert n.name == "a"
results = fg.execute(user_nodes)
assert results == {"a": 1}
def test_end_to_end_with_column_extractor_nodes():
"""Tests that a simple function graph with nodes that extract columns works end-to-end"""
fg = graph.FunctionGraph.from_modules(tests.resources.extract_column_nodes, config={})
nodes = fg.get_nodes()
results = fg.execute(nodes, {}, {})
df_expected = tests.resources.extract_column_nodes.generate_df()
pd.testing.assert_series_equal(results["col_1"], df_expected["col_1"])
pd.testing.assert_series_equal(results["col_2"], df_expected["col_2"])
pd.testing.assert_frame_equal(results["generate_df"], df_expected)
assert (
nodes[0].documentation == "Function that should be parametrized to form multiple functions"
)
def test_end_to_end_with_multiple_decorators():
"""Tests that a simple function graph with multiple decorators on a function works end-to-end"""
fg = graph.FunctionGraph.from_modules(
tests.resources.multiple_decorators_together,
config={"param0": 3, "param1": 1, "in_value1": 42, "in_value2": "string_value"},
)
nodes = fg.get_nodes()
# To help debug issues:
# nodez, user_nodes = fg.get_upstream_nodes([n.name for n in nodes],
# {"param0": 3, "param1": 1,
# "in_value1": 42, "in_value2": "string_value"})
# fg.display(
# nodez,
# user_nodes,
# "all_multiple_decorators",
# render_kwargs=None,
# graphviz_kwargs=None,
# )
results = fg.execute(nodes, {}, {})
df_expected = tests.resources.multiple_decorators_together._sum_multiply(3, 1, 2)
dict_expected = tests.resources.multiple_decorators_together._sum(3, 1, 2)
pd.testing.assert_series_equal(results["param1b"], df_expected["param1b"])
pd.testing.assert_frame_equal(results["to_modify"], df_expected)
assert results["total"] == dict_expected["total"]
assert results["to_modify_2"] == dict_expected
node_dict = {n.name: n for n in nodes}
print(sorted(list(node_dict.keys())))
assert (
node_dict["to_modify"].documentation
== "This is a dummy function showing extract_columns with does."
)
assert (
node_dict["to_modify_2"].documentation
== "This is a dummy function showing extract_fields with does."
)
# tag only applies right now to outer most node layer
assert node_dict["uber_decorated_function"].tags == {
"module": "tests.resources.multiple_decorators_together"
} # tags are not propagated
assert node_dict["out_value1"].tags == {
"module": "tests.resources.multiple_decorators_together",
"test_key": "test-value",
}
assert node_dict["out_value2"].tags == {
"module": "tests.resources.multiple_decorators_together",
"test_key": "test-value",
}
def test_end_to_end_with_config_modifier():
config = {
"fn_1_version": 1,
}
fg = graph.FunctionGraph.from_modules(tests.resources.config_modifier, config=config)
results = fg.execute(fg.get_nodes(), {}, {})
assert results["fn"] == "version_1"
config = {
"fn_1_version": 2,
}
fg = graph.FunctionGraph.from_modules(tests.resources.config_modifier, config=config)
results = fg.execute(fg.get_nodes(), {}, {})
assert results["fn"] == "version_2"
config = {
"fn_1_version": 3,
}
fg = graph.FunctionGraph.from_modules(tests.resources.config_modifier, config=config)
results = fg.execute(fg.get_nodes(), {}, {})
assert results["fn"] == "version_3"
def test_non_required_nodes():
fg = graph.FunctionGraph.from_modules(
tests.resources.test_default_args, config={"required": 10}
)
results = fg.execute(
# D is not on the execution path, so it should not break things
[n for n in fg.get_nodes() if n.node_role == NodeType.STANDARD and n.name != "D"],
{},
{},
)
assert results["A"] == 10
fg = graph.FunctionGraph.from_modules(
tests.resources.test_default_args, config={"required": 10, "defaults_to_zero": 1}
)
results = fg.execute(
[n for n in fg.get_nodes() if n.node_role == NodeType.STANDARD],
{},
{},
)
assert results["A"] == 11
assert results["D"] == 2
def test_config_can_override():
config = {"new_param": "new_value"}
fg = graph.FunctionGraph.from_modules(tests.resources.config_modifier, config=config)
out = fg.execute([n for n in fg.get_nodes()])
assert out["new_param"] == "new_value"
def test_function_graph_has_cycles_true():
"""Tests whether we catch a graph with cycles -- and expected behaviors"""
fg = graph.FunctionGraph.from_modules(tests.resources.cyclic_functions, config={"b": 2, "c": 1})
all_nodes = fg.get_nodes()
nodes = [n for n in all_nodes if not n.user_defined]
user_nodes = [n for n in all_nodes if n.user_defined]
assert fg.has_cycles(nodes, user_nodes) is True
required_nodes, required_user_nodes = fg.get_upstream_nodes(["A", "B", "C"])
assert required_nodes == set(nodes + user_nodes)
assert required_user_nodes == set(user_nodes)
# We don't want to support this behavior officially -- but this works:
# result = fg.execute([n for n in nodes if n.name == 'B'], overrides={'A': 1, 'D': 2})
# assert len(result) == 3
# assert result['B'] == 3
with pytest.raises(
RecursionError
): # throw recursion error when we don't have a way to short circuit
fg.execute([n for n in nodes if n.name == "B"])
def test_function_graph_has_cycles_false():
"""Tests whether we catch a graph with cycles"""
fg = graph.FunctionGraph.from_modules(tests.resources.dummy_functions, config={"b": 1, "c": 2})
all_nodes = fg.get_nodes()
# checks it two ways
nodes = [n for n in all_nodes if not n.user_defined]
user_nodes = [n for n in all_nodes if n.user_defined]
assert fg.has_cycles(nodes, user_nodes) is False
# this is called by the driver
nodes, user_nodes = fg.get_upstream_nodes(["A", "B", "C"])
assert fg.has_cycles(nodes, user_nodes) is False
def test_function_graph_display_content(tmp_path: pathlib.Path):
"""Tests that display saves a file"""
dot_file_path = tmp_path / "dag"
config = {"b": 1, "c": 2}
fg = graph.FunctionGraph.from_modules(tests.resources.dummy_functions, config=config)
node_modifiers = {"B": {graph.VisualizationNodeModifiers.IS_OUTPUT}}
all_nodes = set()
for n in fg.get_nodes():
if n.user_defined:
node_modifiers[n.name] = {graph.VisualizationNodeModifiers.IS_USER_INPUT}
all_nodes.add(n)
# hack of a test -- but it works... sort the lines and match them up.
# why? because for some reason given the same graph, the output file isn't deterministic.
# for the same reason, order of input nodes are non-deterministic
expected_set = set(
[
'\t\tfunction [fillcolor="#b4d8e4" fontname=Helvetica margin=0.15 shape=rectangle style="rounded,filled"]\n',
'\t\tgraph [fillcolor="#ffffff" fontname=helvetica label=Legend rank=same]\n',
'\t\tinput [fontname=Helvetica margin=0.15 shape=rectangle style="filled,dashed"]\n',
'\t\toutput [fillcolor="#FFC857" fontname=Helvetica margin=0.15 shape=rectangle style="rounded,filled"]\n',
"\tA -> B\n",
"\tA -> C\n",
'\tA [label=<<b>A</b><br /><br /><i>int</i>> fillcolor="#b4d8e4" fontname=Helvetica margin=0.15 shape=rectangle style="rounded,filled"]\n',
'\tB [label=<<b>B</b><br /><br /><i>int</i>> fillcolor="#FFC857" fontname=Helvetica margin=0.15 shape=rectangle style="rounded,filled"]\n',
'\tC [label=<<b>C</b><br /><br /><i>int</i>> fillcolor="#b4d8e4" fontname=Helvetica margin=0.15 shape=rectangle style="rounded,filled"]\n',
"\tb [label=<<b>b</b><br /><br /><i>1</i>> fontname=Helvetica shape=note style=filled]\n",
"\tc [label=<<b>c</b><br /><br /><i>2</i>> fontname=Helvetica shape=note style=filled]\n",
"\t_A_inputs -> A\n",
# commenting out input node: '\t_A_inputs [label=<<table border="0"><tr><td>c</td><td>int</td></tr><tr><td>b</td><td>int</td></tr></table>> fontname=Helvetica margin=0.15 shape=rectangle style=dashed]\n',
"\tgraph [compound=true concentrate=true rankdir=LR ranksep=0.4 style=filled]\n",
'\tnode [fillcolor="#ffffff"]\n',
"\tsubgraph cluster__legend {\n",
"\t}\n",
"// Dependency Graph\n",
"digraph {\n",
"}\n",
]
)
fg.display(
all_nodes,
output_file_path=str(dot_file_path),
node_modifiers=node_modifiers,
config=config,
keep_dot=True,
)
dot_file = dot_file_path.open("r").readlines()
dot_set = set(dot_file)
assert dot_set.issuperset(expected_set) and len(dot_set.difference(expected_set)) == 1
@pytest.mark.parametrize(
("filename", "keep_dot"), [("dag", False), ("dag.png", False), ("dag", True), ("dag.png", True)]
)
def test_function_graph_display_output_filename(
tmp_path: pathlib.Path, filename: str, keep_dot: bool
):
"""Handle file generation with `graph.Digraph` `.render()` and `.pipe()`"""
output_file_path = f"{tmp_path}/{filename}"
config = {"b": 1, "c": 2}
fg = graph.FunctionGraph.from_modules(tests.resources.dummy_functions, config=config)
fg.display(
set(fg.get_nodes()),
output_file_path=output_file_path,
config=config,
keep_dot=keep_dot,
)
assert pathlib.Path(tmp_path, "dag.png").exists()
assert pathlib.Path(tmp_path, "dag").exists() == keep_dot
def test_function_graph_display_no_dot_output(tmp_path: pathlib.Path):
dot_file_path = tmp_path / "dag"
config = {"b": 1, "c": 2}
fg = graph.FunctionGraph.from_modules(tests.resources.dummy_functions, config=config)
fg.display(set(fg.get_nodes()), output_file_path=None, config=config)
assert not dot_file_path.exists()
def test_function_graph_display_custom_style_node():
def _styling_function(*, node, node_class):
return dict(fill_color="aquamarine"), None, "legend_key"
config = {"b": 1, "c": 2}
fg = graph.FunctionGraph.from_modules(tests.resources.dummy_functions, config=config)
digraph = fg.display(