apache-hamilton 1.90.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. apache_hamilton-1.90.0.dev0.dist-info/METADATA +407 -0
  2. apache_hamilton-1.90.0.dev0.dist-info/RECORD +151 -0
  3. apache_hamilton-1.90.0.dev0.dist-info/WHEEL +4 -0
  4. apache_hamilton-1.90.0.dev0.dist-info/entry_points.txt +9 -0
  5. apache_hamilton-1.90.0.dev0.dist-info/licenses/DISCLAIMER +10 -0
  6. apache_hamilton-1.90.0.dev0.dist-info/licenses/LICENSE +228 -0
  7. apache_hamilton-1.90.0.dev0.dist-info/licenses/NOTICE +5 -0
  8. hamilton/__init__.py +24 -0
  9. hamilton/ad_hoc_utils.py +132 -0
  10. hamilton/async_driver.py +465 -0
  11. hamilton/base.py +466 -0
  12. hamilton/caching/__init__.py +16 -0
  13. hamilton/caching/adapter.py +1475 -0
  14. hamilton/caching/cache_key.py +70 -0
  15. hamilton/caching/fingerprinting.py +287 -0
  16. hamilton/caching/stores/__init__.py +16 -0
  17. hamilton/caching/stores/base.py +242 -0
  18. hamilton/caching/stores/file.py +140 -0
  19. hamilton/caching/stores/memory.py +297 -0
  20. hamilton/caching/stores/sqlite.py +282 -0
  21. hamilton/caching/stores/utils.py +40 -0
  22. hamilton/cli/__init__.py +16 -0
  23. hamilton/cli/__main__.py +328 -0
  24. hamilton/cli/commands.py +126 -0
  25. hamilton/cli/logic.py +338 -0
  26. hamilton/common/__init__.py +76 -0
  27. hamilton/contrib/__init__.py +41 -0
  28. hamilton/data_quality/__init__.py +16 -0
  29. hamilton/data_quality/base.py +198 -0
  30. hamilton/data_quality/default_validators.py +560 -0
  31. hamilton/data_quality/pandera_validators.py +121 -0
  32. hamilton/dataflows/__init__.py +726 -0
  33. hamilton/dataflows/template/README.md +25 -0
  34. hamilton/dataflows/template/__init__.py +54 -0
  35. hamilton/dataflows/template/author.md +28 -0
  36. hamilton/dataflows/template/requirements.txt +0 -0
  37. hamilton/dataflows/template/tags.json +7 -0
  38. hamilton/dataflows/template/valid_configs.jsonl +1 -0
  39. hamilton/dev_utils/__init__.py +16 -0
  40. hamilton/dev_utils/deprecation.py +204 -0
  41. hamilton/driver.py +2112 -0
  42. hamilton/execution/__init__.py +16 -0
  43. hamilton/execution/debugging_utils.py +56 -0
  44. hamilton/execution/executors.py +502 -0
  45. hamilton/execution/graph_functions.py +421 -0
  46. hamilton/execution/grouping.py +430 -0
  47. hamilton/execution/state.py +539 -0
  48. hamilton/experimental/__init__.py +27 -0
  49. hamilton/experimental/databackend.py +61 -0
  50. hamilton/experimental/decorators/__init__.py +16 -0
  51. hamilton/experimental/decorators/parameterize_frame.py +233 -0
  52. hamilton/experimental/h_async.py +29 -0
  53. hamilton/experimental/h_cache.py +413 -0
  54. hamilton/experimental/h_dask.py +28 -0
  55. hamilton/experimental/h_databackends.py +174 -0
  56. hamilton/experimental/h_ray.py +28 -0
  57. hamilton/experimental/h_spark.py +32 -0
  58. hamilton/function_modifiers/README +40 -0
  59. hamilton/function_modifiers/__init__.py +121 -0
  60. hamilton/function_modifiers/adapters.py +900 -0
  61. hamilton/function_modifiers/base.py +859 -0
  62. hamilton/function_modifiers/configuration.py +310 -0
  63. hamilton/function_modifiers/delayed.py +202 -0
  64. hamilton/function_modifiers/dependencies.py +246 -0
  65. hamilton/function_modifiers/expanders.py +1230 -0
  66. hamilton/function_modifiers/macros.py +1634 -0
  67. hamilton/function_modifiers/metadata.py +434 -0
  68. hamilton/function_modifiers/recursive.py +908 -0
  69. hamilton/function_modifiers/validation.py +289 -0
  70. hamilton/function_modifiers_base.py +31 -0
  71. hamilton/graph.py +1153 -0
  72. hamilton/graph_types.py +264 -0
  73. hamilton/graph_utils.py +41 -0
  74. hamilton/htypes.py +450 -0
  75. hamilton/io/__init__.py +32 -0
  76. hamilton/io/data_adapters.py +216 -0
  77. hamilton/io/default_data_loaders.py +224 -0
  78. hamilton/io/materialization.py +500 -0
  79. hamilton/io/utils.py +158 -0
  80. hamilton/lifecycle/__init__.py +67 -0
  81. hamilton/lifecycle/api.py +833 -0
  82. hamilton/lifecycle/base.py +1130 -0
  83. hamilton/lifecycle/default.py +802 -0
  84. hamilton/log_setup.py +47 -0
  85. hamilton/models.py +92 -0
  86. hamilton/node.py +449 -0
  87. hamilton/plugins/README.md +48 -0
  88. hamilton/plugins/__init__.py +16 -0
  89. hamilton/plugins/dask_extensions.py +47 -0
  90. hamilton/plugins/dlt_extensions.py +161 -0
  91. hamilton/plugins/geopandas_extensions.py +49 -0
  92. hamilton/plugins/h_dask.py +331 -0
  93. hamilton/plugins/h_ddog.py +522 -0
  94. hamilton/plugins/h_diskcache.py +163 -0
  95. hamilton/plugins/h_experiments/__init__.py +22 -0
  96. hamilton/plugins/h_experiments/__main__.py +62 -0
  97. hamilton/plugins/h_experiments/cache.py +39 -0
  98. hamilton/plugins/h_experiments/data_model.py +68 -0
  99. hamilton/plugins/h_experiments/hook.py +219 -0
  100. hamilton/plugins/h_experiments/server.py +375 -0
  101. hamilton/plugins/h_kedro.py +152 -0
  102. hamilton/plugins/h_logging.py +454 -0
  103. hamilton/plugins/h_mcp/__init__.py +28 -0
  104. hamilton/plugins/h_mcp/__main__.py +33 -0
  105. hamilton/plugins/h_mcp/_helpers.py +129 -0
  106. hamilton/plugins/h_mcp/_templates.py +417 -0
  107. hamilton/plugins/h_mcp/server.py +328 -0
  108. hamilton/plugins/h_mlflow.py +335 -0
  109. hamilton/plugins/h_narwhals.py +134 -0
  110. hamilton/plugins/h_openlineage.py +400 -0
  111. hamilton/plugins/h_opentelemetry.py +167 -0
  112. hamilton/plugins/h_pandas.py +257 -0
  113. hamilton/plugins/h_pandera.py +117 -0
  114. hamilton/plugins/h_polars.py +304 -0
  115. hamilton/plugins/h_polars_lazyframe.py +282 -0
  116. hamilton/plugins/h_pyarrow.py +56 -0
  117. hamilton/plugins/h_pydantic.py +127 -0
  118. hamilton/plugins/h_ray.py +242 -0
  119. hamilton/plugins/h_rich.py +142 -0
  120. hamilton/plugins/h_schema.py +493 -0
  121. hamilton/plugins/h_slack.py +100 -0
  122. hamilton/plugins/h_spark.py +1380 -0
  123. hamilton/plugins/h_threadpool.py +125 -0
  124. hamilton/plugins/h_tqdm.py +122 -0
  125. hamilton/plugins/h_vaex.py +129 -0
  126. hamilton/plugins/huggingface_extensions.py +236 -0
  127. hamilton/plugins/ibis_extensions.py +93 -0
  128. hamilton/plugins/jupyter_magic.py +622 -0
  129. hamilton/plugins/kedro_extensions.py +117 -0
  130. hamilton/plugins/lightgbm_extensions.py +99 -0
  131. hamilton/plugins/matplotlib_extensions.py +108 -0
  132. hamilton/plugins/mlflow_extensions.py +216 -0
  133. hamilton/plugins/numpy_extensions.py +105 -0
  134. hamilton/plugins/pandas_extensions.py +1763 -0
  135. hamilton/plugins/plotly_extensions.py +150 -0
  136. hamilton/plugins/polars_extensions.py +71 -0
  137. hamilton/plugins/polars_implementations.py +25 -0
  138. hamilton/plugins/polars_lazyframe_extensions.py +302 -0
  139. hamilton/plugins/polars_post_1_0_0_extensions.py +877 -0
  140. hamilton/plugins/polars_pre_1_0_0_extension.py +836 -0
  141. hamilton/plugins/pydantic_extensions.py +98 -0
  142. hamilton/plugins/pyspark_pandas_extensions.py +47 -0
  143. hamilton/plugins/sklearn_plot_extensions.py +129 -0
  144. hamilton/plugins/spark_extensions.py +105 -0
  145. hamilton/plugins/vaex_extensions.py +51 -0
  146. hamilton/plugins/xgboost_extensions.py +91 -0
  147. hamilton/plugins/yaml_extensions.py +89 -0
  148. hamilton/registry.py +254 -0
  149. hamilton/settings.py +18 -0
  150. hamilton/telemetry.py +50 -0
  151. hamilton/version.py +18 -0
@@ -0,0 +1,859 @@
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ import abc
19
+ import collections
20
+ import functools
21
+ import itertools
22
+ import logging
23
+ from abc import ABC
24
+
25
+ try:
26
+ from types import EllipsisType
27
+ except ImportError:
28
+ # python3.10 and above
29
+ EllipsisType = type(...)
30
+ from collections.abc import Callable, Collection
31
+ from typing import Any, Union
32
+
33
+ from hamilton import node, registry, settings
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ if not registry.INITIALIZED:
38
+ # Trigger load of extensions here because decorators are the only thing that use the registry
39
+ # right now. Side note: ray serializes things weirdly, so we need to do this here rather than in
40
+ # in the other choice of hamilton/base.py.
41
+ registry.initialize()
42
+
43
+
44
+ def sanitize_function_name(name: str) -> str:
45
+ """Sanitizes the function name to use.
46
+ Note that this is a slightly leaky abstraction, but this is really just a single case in which we want to strip out
47
+ dunderscores. This will likely change over time, but for now we need a way for a decorator to know about the true
48
+ function name without having to rely on the decorator order. So, if you want the function name of the function you're
49
+ decorating, call this first.
50
+
51
+ :param name: Function name
52
+ :return: Sanitized version.
53
+ """
54
+ last_dunder_index = name.rfind("__")
55
+ return name[:last_dunder_index] if last_dunder_index != -1 else name
56
+
57
+
58
+ DECORATOR_COUNTER = collections.defaultdict(int)
59
+
60
+
61
+ def track_decorator_usage(call_fn: Callable) -> Callable:
62
+ """Decorator to wrap the __call__ to count decorator usage.
63
+
64
+ :param call_fn: the `__call__` function.
65
+ :return: the wrapped call function.
66
+ """
67
+
68
+ @functools.wraps(call_fn)
69
+ def replace__call__(self, fn):
70
+ global DECORATOR_COUNTER
71
+ if self.__module__.startswith("hamilton.function_modifiers"):
72
+ # only capture counts for hamilton decorators
73
+ DECORATOR_COUNTER[self.__class__.__name__] = (
74
+ DECORATOR_COUNTER[self.__class__.__name__] + 1
75
+ )
76
+ else:
77
+ DECORATOR_COUNTER["custom_decorator"] = DECORATOR_COUNTER["custom_decorator"] + 1
78
+ return call_fn(self, fn)
79
+
80
+ return replace__call__
81
+
82
+
83
+ class NodeTransformLifecycle(abc.ABC):
84
+ """Base class to represent the decorator lifecycle. Common among all node decorators."""
85
+
86
+ @classmethod
87
+ @abc.abstractmethod
88
+ def get_lifecycle_name(cls) -> str:
89
+ """Gives the lifecycle name of the node decorator. Unique to the class, will likely not be overwritten by subclasses.
90
+ Note that this is coupled with the resolve_node() function below.
91
+ """
92
+ pass
93
+
94
+ @classmethod
95
+ @abc.abstractmethod
96
+ def allows_multiple(cls) -> bool:
97
+ """Whether or not multiple of these decorators are allowed.
98
+
99
+ :return: True if multiple decorators are allowed else False
100
+ """
101
+ pass
102
+
103
+ @abc.abstractmethod
104
+ def validate(self, fn: Callable):
105
+ """Validates the decorator against the function
106
+
107
+ :param fn: Function to validate against
108
+ :return: Nothing, raises exception if not valid.
109
+ """
110
+ pass
111
+
112
+ @track_decorator_usage
113
+ def __call__(self, fn: Callable):
114
+ """Calls the decorator by adding attributes using the get_lifecycle_name string.
115
+ These attributes are the pointer to the decorator object itself, and used later in resolve_nodes below.
116
+
117
+ :param fn: Function to decorate
118
+ :return: The function again, with the desired properties.
119
+ """
120
+ self.validate(fn)
121
+ lifecycle_name = self.__class__.get_lifecycle_name()
122
+ if hasattr(fn, self.get_lifecycle_name()):
123
+ if not self.allows_multiple():
124
+ raise ValueError(
125
+ f"Got multiple decorators for decorator @{self.__class__}. Only one allowed."
126
+ )
127
+ curr_value = getattr(fn, lifecycle_name)
128
+ setattr(fn, lifecycle_name, curr_value + [self])
129
+ else:
130
+ setattr(fn, lifecycle_name, [self])
131
+ return fn
132
+
133
+ def required_config(self) -> list[str] | None:
134
+ """Declares the required configuration keys for this decorator.
135
+ Note that these configuration keys will be filtered and passed to the `configuration`
136
+ parameter of the functions that this decorator uses.
137
+
138
+ Note that this currently allows for a "escape hatch".
139
+ That is, returning None from this function.
140
+
141
+ :return: A list of the required configuration keys.
142
+ """
143
+ return []
144
+
145
+ def optional_config(self) -> dict[str, Any] | None:
146
+ """Declares the optional configuration keys for this decorator.
147
+ These are configuration keys that can be used by the decorator, but are not required.
148
+ Along with these we have *defaults*, which we will use to pass to the config.
149
+
150
+ :return: The optional configuration keys with defaults. Note that this will return None
151
+ if we have no idea what they are, which bypasses the configuration filtering we use entirely.
152
+ This is mainly for the legacy API.
153
+ """
154
+ return {}
155
+
156
+ @property
157
+ def name(self) -> str:
158
+ """Name of the decorator.
159
+
160
+ :return: The name of the decorator
161
+ """
162
+ return self.__class__.__name__
163
+
164
+
165
+ class NodeResolver(NodeTransformLifecycle):
166
+ """Decorator to resolve a nodes function. Can modify anything about the function and is run at DAG creation time."""
167
+
168
+ @abc.abstractmethod
169
+ def resolve(self, fn: Callable, config: dict[str, Any]) -> Callable | None:
170
+ """Determines what a function resolves to. Returns None if it should not be included in the DAG.
171
+
172
+ :param fn: Function to resolve
173
+ :param config: DAG config
174
+ :return: A name if it should resolve to something. Otherwise None.
175
+ """
176
+ pass
177
+
178
+ @abc.abstractmethod
179
+ def validate(self, fn):
180
+ """Validates that the function can work with the function resolver.
181
+
182
+ :param fn: Function to validate
183
+ :return: nothing
184
+ :raises InvalidDecoratorException: if the function is not valid for this decorator
185
+ """
186
+ pass
187
+
188
+ @classmethod
189
+ def get_lifecycle_name(cls) -> str:
190
+ return "resolve"
191
+
192
+ @classmethod
193
+ def allows_multiple(cls) -> bool:
194
+ return True
195
+
196
+
197
+ class NodeCreator(NodeTransformLifecycle, abc.ABC):
198
+ """Abstract class for nodes that "expand" functions into other nodes."""
199
+
200
+ @abc.abstractmethod
201
+ def generate_nodes(self, fn: Callable, config: dict[str, Any]) -> list[node.Node]:
202
+ """Given a function, converts it to a series of nodes that it produces.
203
+
204
+ :param config:
205
+ :param fn: A function to convert.
206
+ :return: A collection of nodes.
207
+ """
208
+ pass
209
+
210
+ @abc.abstractmethod
211
+ def validate(self, fn: Callable):
212
+ """Validates that a function will work with this expander
213
+
214
+ :param fn: Function to validate.
215
+ :raises InvalidDecoratorException if this is not a valid function for the annotator
216
+ """
217
+ pass
218
+
219
+ @classmethod
220
+ def get_lifecycle_name(cls) -> str:
221
+ return "generate"
222
+
223
+ @classmethod
224
+ def allows_multiple(cls) -> bool:
225
+ return False
226
+
227
+
228
+ class SubDAGModifier(NodeTransformLifecycle, abc.ABC):
229
+ @abc.abstractmethod
230
+ def transform_dag(
231
+ self, nodes: Collection[node.Node], config: dict[str, Any], fn: Callable
232
+ ) -> Collection[node.Node]:
233
+ """Modifies a DAG consisting of a set of nodes. Note that this is to support the following two base classes.
234
+
235
+ :param nodes: Collection of nodes (not necessarily connected) to modify
236
+ :param config: Configuration in case any is needed
237
+ :return: the new DAG of nodes
238
+ """
239
+ pass
240
+
241
+
242
+ class NodeInjector(SubDAGModifier, abc.ABC):
243
+ """Injects a value as a source node in the DAG. This is a special case of the SubDAGModifier,
244
+ which gets all the upstream (required) nodes from the subdag and gives the decorator a chance
245
+ to inject values into them.
246
+
247
+ This is used when you want to feed in, say, some parameter to a function. For instance:
248
+
249
+ def processed_data(data: pd.DataFrame) -> pd.DataFrame:
250
+ ...
251
+
252
+ on its own would produce the "user-defined" node data, which the user is expected to pass in.
253
+ The NodeInjector know sthat this is a parameter of the DAG and has the chance to provide a value
254
+ for "data".
255
+ """
256
+
257
+ @staticmethod
258
+ def find_injectable_params(nodes: Collection[node.Node]) -> dict[str, type[type]]:
259
+ """Identifies required nodes of this subDAG (nodes produced by this function)
260
+ that aren't satisfied by the nodes inside it. These are "injectable",
261
+ meaning that we can add more nodes that feed into them.
262
+
263
+ Note that these would be "user-defined" if nothing satisfied them --
264
+ in this case we're finding them to give this class a chance to feed them values.
265
+
266
+ :param nodes: Subdag to consider
267
+ :return: All dependencies that are not satisfied by the subdag.
268
+ """
269
+ output_deps = {}
270
+ node_names = {node_.name for node_ in nodes}
271
+ for node_ in nodes:
272
+ for param_name, (type_, _) in node_.input_types.items():
273
+ if param_name not in node_names:
274
+ output_deps[param_name] = type_
275
+ return output_deps
276
+
277
+ def transform_dag(
278
+ self, nodes: Collection[node.Node], config: dict[str, Any], fn: Callable
279
+ ) -> Collection[node.Node]:
280
+ """Transforms the subDAG by getting the injectable parameters (anything not
281
+ produced by nodes inside it), then calling the inject_nodes function on it.
282
+
283
+ :param nodes:
284
+ :param config:
285
+ :param fn:
286
+ :return:
287
+ """
288
+ injectable_params = NodeInjector.find_injectable_params(nodes)
289
+ nodes_to_inject, rename_map = self.inject_nodes(injectable_params, config, fn)
290
+ out = []
291
+ for node_ in nodes:
292
+ # if there's an intersection then we want to rename the input
293
+ if set(node_.input_types.keys()) & set(rename_map.keys()):
294
+ out.append(node_.reassign_inputs(input_names=rename_map))
295
+ else:
296
+ out.append(node_)
297
+ out.extend(nodes_to_inject)
298
+ return out
299
+
300
+ @abc.abstractmethod
301
+ def inject_nodes(
302
+ self, params: dict[str, type[type]], config: dict[str, Any], fn: Callable
303
+ ) -> tuple[list[node.Node], dict[str, str]]:
304
+ """Adds a set of nodes to inject into the DAG. These get injected into the specified param name,
305
+ meaning that exactly one of the output nodes will have that name. Note that this also allows
306
+ input renaming, meaning that the injector can rename the input to something else (to avoid
307
+ name-clashes).
308
+
309
+ :param params: Dictionary of all the type names one wants to inject
310
+ :param config: Configuration with which the DAG was constructed.
311
+ :param fn: original function we're decorating. This is useful largely for debugging.
312
+ :return: A list of nodes to add. Empty if you wish to inject nothing, as well as a dictionary,
313
+ allowing the injector to rename the inputs (e.g. if you want the name to be
314
+ namespaced to avoid clashes)
315
+ """
316
+
317
+ pass
318
+
319
+ @classmethod
320
+ def get_lifecycle_name(cls) -> str:
321
+ return "inject"
322
+
323
+ @classmethod
324
+ def allows_multiple(cls) -> bool:
325
+ return True
326
+
327
+ @abc.abstractmethod
328
+ def validate(self, fn: Callable):
329
+ pass
330
+
331
+
332
+ class NodeExpander(SubDAGModifier):
333
+ """Expands a node into multiple nodes. This is a special case of the SubDAGModifier,
334
+ which allows modification of some portion of the DAG. This just modifies a single node.
335
+ """
336
+
337
+ EXPAND_NODES = "expand_nodes"
338
+
339
+ def transform_dag(
340
+ self, nodes: Collection[node.Node], config: dict[str, Any], fn: Callable
341
+ ) -> Collection[node.Node]:
342
+ if len(nodes) != 1:
343
+ raise ValueError(
344
+ f"Cannot call NodeExpander: {self.__class__} on more than one node. This must be "
345
+ f"called first in the DAG. Called with {nodes} "
346
+ )
347
+ (node_,) = nodes
348
+ return self.expand_node(node_, config, fn)
349
+
350
+ @abc.abstractmethod
351
+ def expand_node(
352
+ self, node_: node.Node, config: dict[str, Any], fn: Callable
353
+ ) -> Collection[node.Node]:
354
+ """Given a single node, expands into multiple nodes. Note that this node list includes:
355
+ 1. Each "output" node (think sink in a DAG)
356
+ 2. All intermediate steps
357
+ So in essence, this forms a miniature DAG
358
+
359
+ :param node: The node to expand
360
+ :return: A collection of nodes to add to the DAG
361
+ """
362
+ pass
363
+
364
+ @abc.abstractmethod
365
+ def validate(self, fn: Callable):
366
+ pass
367
+
368
+ @classmethod
369
+ def get_lifecycle_name(cls) -> str:
370
+ return "expand"
371
+
372
+ @classmethod
373
+ def allows_multiple(cls) -> bool:
374
+ return False
375
+
376
+
377
+ TargetType = Union[str, Collection[str], None, EllipsisType]
378
+
379
+
380
+ class NodeTransformer(SubDAGModifier):
381
+ NON_FINAL_TAG = "hamilton.non_final_node"
382
+
383
+ @classmethod
384
+ def _early_validate_target(cls, target: TargetType, allow_multiple: bool):
385
+ """Determines whether the target is valid, given that we may or may not
386
+ want to allow multiple nodes to be transformed.
387
+
388
+ If the target type is a single string then we're good.
389
+ If the target type is a collection of strings, then it has to be a collection of size one.
390
+ If the target type is None, then we delay checking until later (as there might be just
391
+ one node transformed in the DAG).
392
+ If the target type is ellipsis, then we delay checking until later (as there might be
393
+ just one node transformed in the DAG)
394
+
395
+ :param target: How to appply this node. See docs below.
396
+ :param allow_multiple: Whether or not this can operate on multiple nodes.
397
+ :raises InvalidDecoratorException: if the target is invalid given the value of allow_multiple.
398
+ """
399
+ if isinstance(target, str):
400
+ # We're good -- regardless of the value of allow_multiple we'll pass
401
+ return
402
+ elif isinstance(target, Collection) and all(isinstance(x, str) for x in target):
403
+ if len(target) > 1 and not allow_multiple:
404
+ raise InvalidDecoratorException(f"Cannot have multiple targets for . Got {target}")
405
+ return
406
+ elif target is None or target is Ellipsis:
407
+ return
408
+ else:
409
+ raise InvalidDecoratorException(f"Invalid target type for NodeTransformer: {target}")
410
+
411
+ def __init__(self, target: TargetType):
412
+ """Target determines to which node(s) this applies. This represents selection from a subDAG.
413
+ For the options, consider at the following graph:
414
+ A -> B -> C
415
+ \\_> D -> E
416
+
417
+ 1. If it is `None`, it defaults to the "old" behavior. That is, is applies to all "final" DAG
418
+ nodes. In the subdag. That is, all nodes with out-degree zero/sinks. In the case
419
+ above, *just* C and E will be transformed.
420
+
421
+ 2. If it is a string, it will be interpreted as a node name. In the above case, if it is A, it
422
+ will transform A, B will transform B, etc...
423
+
424
+ 3. If it is a collection of strings, it will be interpreted as a collection of node names.
425
+ That is, it will apply to all nodes that are referenced in that collection. In the above case,
426
+ if it is ["A", "B"], it will transform to A and B.
427
+
428
+ 4. If it is Ellipsis, it will apply to all nodes in the subDAG. In the above case, it will
429
+ transform A, B, C, D, and E.
430
+
431
+ :param target: Which node(s)/node spec to run transforms on top of. These nodes will get
432
+ replaced by a list of nodes.
433
+ """
434
+ self.target = target
435
+
436
+ @staticmethod
437
+ def _extract_final_nodes(
438
+ nodes: Collection[node.Node],
439
+ ) -> Collection[node.Node]:
440
+ """Separates out final nodes (sinks) from the nodes.
441
+
442
+ :param nodes: Nodes to separate out
443
+ :return: A tuple consisting of [internal, final] node sets
444
+ """
445
+ non_final_nodes = set()
446
+ for node_ in nodes:
447
+ for dep in node_.input_types:
448
+ non_final_nodes.add(dep)
449
+ return [
450
+ node_
451
+ for node_ in nodes
452
+ if node_.name not in non_final_nodes
453
+ and not node_.tags.get(NodeTransformer.NON_FINAL_TAG)
454
+ ]
455
+
456
+ @staticmethod
457
+ def select_nodes(target: TargetType, nodes: Collection[node.Node]) -> Collection[node.Node]:
458
+ """Resolves all nodes to match the target. This does a resolution on the rules
459
+ specified in the constructor above, giving a set of nodes that match a target.
460
+ We then can split them from the remainder of nodes, and just transform them.
461
+
462
+ :param target: The target to use to resolve nodes
463
+ :param nodes: SubDAG to resolve.
464
+ :return: The set of nodes matching this target
465
+ """
466
+ if target is None:
467
+ return NodeTransformer._extract_final_nodes(nodes)
468
+ elif target is Ellipsis:
469
+ return nodes
470
+ elif isinstance(target, str):
471
+ out = [node_ for node_ in nodes if node_.name == target]
472
+ if len(out) == 0:
473
+ raise InvalidDecoratorException(f"Could not find node {target} in {nodes}")
474
+ return out
475
+ elif isinstance(target, Collection):
476
+ out = [node_ for node_ in nodes if node_.name in target]
477
+ if len(out) != len(target):
478
+ raise InvalidDecoratorException(
479
+ f"Could not find all nodes {target} in {nodes}. "
480
+ f"Missing ({set(target) - set([node_.name for node_ in out])})"
481
+ )
482
+ return out
483
+ else:
484
+ raise ValueError(f"Invalid target: {target}")
485
+
486
+ @staticmethod
487
+ def compliment(
488
+ all_nodes: Collection[node.Node], nodes_to_transform: Collection[node.Node]
489
+ ) -> Collection[node.Node]:
490
+ """Given a set of nodes, and a set of nodes to transform, returns the set of nodes that
491
+ are not in the set of nodes to transform.
492
+
493
+ :param all_nodes: All nodes in the subdag
494
+ :param nodes_to_transform: All nodes to transform
495
+ :return: A collection of nodes that are not in the set of nodes to transform but are in the
496
+ subdag
497
+ """
498
+ return [node_ for node_ in all_nodes if node_ not in nodes_to_transform]
499
+
500
+ def transform_targets(
501
+ self, targets: Collection[node.Node], config: dict[str, Any], fn: Callable
502
+ ) -> Collection[node.Node]:
503
+ """Transforms a set of target nodes. Note that this is just a loop,
504
+ but abstracting t away gives subclasses control over how this is done,
505
+ allowing them to validate beforehand. While we *could* just have this
506
+ as a `validate`, or `transforms_multiple` function, this is a pretty clean/
507
+ readable way to do it.
508
+
509
+ :param targets: Node Targets to transform
510
+ :param config: Configuration to use to
511
+ :param fn: Function being decorated
512
+ :return: Results of transformations
513
+ """
514
+ out = []
515
+ for node_to_transform in targets:
516
+ out += list(self.transform_node(node_to_transform, config, fn))
517
+ return out
518
+
519
+ def transform_dag(
520
+ self, nodes: Collection[node.Node], config: dict[str, Any], fn: Callable
521
+ ) -> Collection[node.Node]:
522
+ """Finds the sources and sinks and runs the transformer on each sink.
523
+ Then returns the result of the entire set of sinks. Note that each sink has to have a unique name.
524
+
525
+ :param config: The original function we're messing with
526
+ :param nodes: Subdag to modify
527
+ :param fn: Original function that we're utilizing/modifying
528
+ :return: The DAG of nodes in this node
529
+ """
530
+ nodes_to_transform = self.select_nodes(self.target, nodes)
531
+ nodes_to_keep = self.compliment(nodes, nodes_to_transform)
532
+ out = list(nodes_to_keep)
533
+ out += self.transform_targets(nodes_to_transform, config, fn)
534
+ return out
535
+
536
+ @abc.abstractmethod
537
+ def transform_node(
538
+ self, node_: node.Node, config: dict[str, Any], fn: Callable
539
+ ) -> Collection[node.Node]:
540
+ pass
541
+
542
+ @abc.abstractmethod
543
+ def validate(self, fn: Callable):
544
+ pass
545
+
546
+ @classmethod
547
+ def get_lifecycle_name(cls) -> str:
548
+ return "transform"
549
+
550
+ @classmethod
551
+ def allows_multiple(cls) -> bool:
552
+ return True
553
+
554
+
555
+ class SingleNodeNodeTransformer(NodeTransformer, ABC):
556
+ """A node transformer that only allows a single node to be transformed.
557
+ Specifically, this must be applied to a decorator operation that returns
558
+ a single node (E.G. @subdag). Note that if you have multiple node transformations,
559
+ the order *does* matter.
560
+
561
+ This should end up killing NodeExpander, as it has the same impact, and the same API.
562
+ """
563
+
564
+ def __init__(self):
565
+ """Initializes the node transformer to only allow a single node to be transformed.
566
+ Note this passes target=None to the superclass, which means that it will only
567
+ apply to the 'sink' nodes produced."""
568
+ super().__init__(target=None)
569
+
570
+ def transform_targets(
571
+ self, targets: Collection[node.Node], config: dict[str, Any], fn: Callable
572
+ ) -> Collection[node.Node]:
573
+ """Transforms the target set of nodes. Exists to validate the target set.
574
+
575
+ :param targets: Targets to transform -- this has to be an array of 1.
576
+ :param config: Configuration passed into the DAG.
577
+ :param fn: Function that was decorated.
578
+ :return: The resulting nodes.
579
+ """
580
+ if len(targets) != 1:
581
+ raise InvalidDecoratorException(
582
+ f"Expected a single node to transform, but got {len(targets)}. {self.__class__} "
583
+ f" can only operate on a single node, but multiple nodes were created by {fn.__qualname__}"
584
+ )
585
+ return super().transform_targets(targets, config, fn)
586
+
587
+
588
+ class NodeDecorator(NodeTransformer, abc.ABC):
589
+ DECORATE_NODES = "decorate_nodes"
590
+
591
+ def __init__(self, target: TargetType):
592
+ """Initializes a NodeDecorator with a target, to determine *which* nodes to decorate.
593
+ See documentation in NodeTransformer for more details on what to decorate.
594
+
595
+ :param target: Target parameter to resolve set of nodes to transform.
596
+ """
597
+ super().__init__(target=target)
598
+
599
+ def validate_node(self, node_: node.Node):
600
+ """Validates that a node is valid for this decorator. This is
601
+ not the same as validation on the function, as this is done
602
+ during node-resolution.
603
+
604
+ :param node_: Node to validate
605
+ :raises InvalidDecoratorException: if the node is not valid for this decorator
606
+ """
607
+ pass
608
+
609
+ def transform_node(
610
+ self, node_: node.Node, config: dict[str, Any], fn: Callable
611
+ ) -> Collection[node.Node]:
612
+ """Transforms the node. Delegates to decorate_node
613
+
614
+ :param node_: Node to transform
615
+ :param config: Config in case its needed
616
+ :param fn: Function we're decorating
617
+ :return: The nodes produced by the transformation
618
+ """
619
+ self.validate_node(node_)
620
+ return [self.decorate_node(node_)]
621
+
622
+ @classmethod
623
+ def get_lifecycle_name(cls) -> str:
624
+ return NodeDecorator.DECORATE_NODES
625
+
626
+ @classmethod
627
+ def allows_multiple(cls) -> bool:
628
+ return True
629
+
630
+ def validate(self, fn: Callable):
631
+ pass
632
+
633
+ @abc.abstractmethod
634
+ def decorate_node(self, node_: node.Node) -> node.Node:
635
+ """Decorates the node -- copies and embellishes in some way.
636
+
637
+ :param node_: Node to decorate.
638
+ :return: A copy of the node.
639
+ """
640
+ pass
641
+
642
+
643
+ class DefaultNodeCreator(NodeCreator):
644
+ def generate_nodes(self, fn: Callable, config: dict[str, Any]) -> list[node.Node]:
645
+ return [node.Node.from_fn(fn)]
646
+
647
+ def validate(self, fn: Callable):
648
+ pass
649
+
650
+
651
+ class DefaultNodeResolver(NodeResolver):
652
+ def resolve(self, fn: Callable, config: dict[str, Any]) -> Callable:
653
+ return fn
654
+
655
+ def validate(self, fn):
656
+ pass
657
+
658
+
659
+ class DefaultNodeDecorator(NodeDecorator):
660
+ def __init__(self):
661
+ super().__init__(target=...)
662
+
663
+ def decorate_node(self, node_: node.Node) -> node.Node:
664
+ return node_
665
+
666
+
667
+ def resolve_config(
668
+ name_for_error: str,
669
+ config: dict[str, Any],
670
+ config_required: list[str] | None,
671
+ config_optional_with_defaults: dict[str, Any],
672
+ ) -> dict[str, Any]:
673
+ """Resolves the configuration that a decorator utilizes
674
+
675
+ :param name_for_error:
676
+ :param config:
677
+ :param config_required:
678
+ :param config_optional_with_defaults:
679
+ :return:
680
+ """
681
+ if config_required is None:
682
+ # This is an out to allow for backwards compatibility for the config.resolve decorator
683
+ # Note this is an internal API, but we made the config with the `resolve` parameter public
684
+ return config
685
+ # Validate that all required parameters are present, so we fake the optional parameters for now
686
+ config_optional_with_global_defaults_applied = (
687
+ config_optional_with_defaults.copy() if config_optional_with_defaults is not None else {}
688
+ )
689
+ config_optional_with_global_defaults_applied[settings.ENABLE_POWER_USER_MODE] = (
690
+ config_optional_with_global_defaults_applied.get(settings.ENABLE_POWER_USER_MODE, False)
691
+ )
692
+ missing_keys = (
693
+ set(config_required)
694
+ - set(config.keys())
695
+ - set(config_optional_with_global_defaults_applied.keys())
696
+ )
697
+ if len(missing_keys) > 0:
698
+ raise MissingConfigParametersException(
699
+ f"The following configurations are required by {name_for_error}: {missing_keys}"
700
+ )
701
+ config_out = {key: config[key] for key in config_required}
702
+ for key in config_optional_with_global_defaults_applied:
703
+ config_out[key] = config.get(key, config_optional_with_global_defaults_applied[key])
704
+ return config_out
705
+
706
+
707
+ class DynamicResolver(NodeTransformLifecycle):
708
+ @classmethod
709
+ def get_lifecycle_name(cls) -> str:
710
+ return "dynamic"
711
+
712
+ @classmethod
713
+ def allows_multiple(cls) -> bool:
714
+ return True
715
+
716
+ def validate(self, fn: Callable):
717
+ pass
718
+
719
+
720
+ def filter_config(config: dict[str, Any], decorator: NodeTransformLifecycle) -> dict[str, Any]:
721
+ """Filters the config to only include the keys in config_required
722
+ :param config: The config to filter
723
+ :param config_required: The keys to include
724
+ :param decorator: The decorator that is utilizing the configuration
725
+ :return: The filtered config
726
+ """
727
+ config_required = decorator.required_config()
728
+ config_optional_with_defaults = decorator.optional_config()
729
+ return resolve_config(decorator.name, config, config_required, config_optional_with_defaults)
730
+
731
+
732
+ def get_node_decorators(
733
+ fn: Callable, config: dict[str, Any]
734
+ ) -> dict[str, list[NodeTransformLifecycle]]:
735
+ """Gets the decorators for a function. Contract is this will have one entry
736
+ for every step of the decorator lifecycle that can always be run (currently everything except NodeExpander)
737
+
738
+ :param fn:
739
+ :return:
740
+ """
741
+ defaults = {
742
+ NodeResolver.get_lifecycle_name(): [DefaultNodeResolver()],
743
+ NodeCreator.get_lifecycle_name(): [DefaultNodeCreator()],
744
+ NodeExpander.get_lifecycle_name(): [],
745
+ NodeTransformer.get_lifecycle_name(): [],
746
+ NodeInjector.get_lifecycle_name(): [],
747
+ NodeDecorator.get_lifecycle_name(): [DefaultNodeDecorator()],
748
+ }
749
+ dynamic_decorators = []
750
+ for dynamic_resolver in getattr(fn, DynamicResolver.get_lifecycle_name(), []):
751
+ dynamic_decorators.append(dynamic_resolver.resolve(config, fn))
752
+ all_decorators = list(
753
+ itertools.chain(
754
+ *[getattr(fn, lifecycle_step, []) for lifecycle_step in defaults],
755
+ dynamic_decorators,
756
+ )
757
+ )
758
+ grouped_by_lifecycle_step = collections.defaultdict(list)
759
+ for decorator in all_decorators:
760
+ grouped_by_lifecycle_step[decorator.get_lifecycle_name()].append(decorator)
761
+ defaults.update(grouped_by_lifecycle_step)
762
+ return defaults
763
+
764
+
765
+ def _add_original_function_to_nodes(fn: Callable, nodes: list[node.Node]) -> list[node.Node]:
766
+ """Adds the original function to the nodes. We do this so that we can have appropriate metadata
767
+ on the function -- this is valuable to see if/how the function changes over time to manage node
768
+ versions, etc...
769
+
770
+ Note that this will add it so the "external" function is always last. They *should* correspond
771
+ to namespaces, but this is not
772
+
773
+ This is not mutating them, rather
774
+ copying them with the original function. If it gets slow we *can* mutate them, but
775
+ this is just another O(n) operation so I'm not concerned.
776
+
777
+
778
+ :param fn: The function to add
779
+ :param nodes: The nodes to add it to
780
+ :return: The nodes with the function added
781
+ """
782
+ out = []
783
+ for node_ in nodes:
784
+ current_originating_functions = node_.originating_functions
785
+ new_originating_functions = (
786
+ current_originating_functions if current_originating_functions is not None else ()
787
+ ) + (fn,)
788
+ out.append(node_.copy_with(originating_functions=new_originating_functions))
789
+ return out
790
+
791
+
792
+ def _resolve_nodes_error(fn: Callable) -> str:
793
+ return f"Exception occurred while compiling function: {fn.__name__} to nodes"
794
+
795
+
796
+ def resolve_nodes(fn: Callable, config: dict[str, Any]) -> Collection[node.Node]:
797
+ """Gets a list of nodes from a function. This is meant to be an abstraction between the node
798
+ and the function that it implements. This will end up coordinating with the decorators we build
799
+ to modify nodes.
800
+
801
+ Algorithm is as follows:
802
+ 1. If there is a list of function resolvers, apply them one
803
+ after the other. Otherwise, apply the default function resolver
804
+ which will always return just the function. This determines whether to
805
+ proceed -- if any function resolver is none, short circuit and return
806
+ an empty list of nodes.
807
+
808
+ 2. If there is a list of node creators, that list must be of length 1
809
+ -- this is determined in the node creator class. Apply that to get
810
+ the initial node.
811
+
812
+ 3. If there is a list of node expanders, apply them. Otherwise apply the default
813
+ node expander This must be a list of length one. This gives out a list of nodes.
814
+
815
+ 4. If there is a node transformer, apply that. Note that the node transformer
816
+ gets applied individually to just the sink nodes in the subdag. It subclasses
817
+ "DagTransformer" to do so.
818
+
819
+ 5. Return the final list of nodes.
820
+
821
+ :param fn: Function to input.
822
+ :param config: Configuration to use -- this can be used by decorators to specify
823
+ which configuration they need.
824
+ :return: A list of nodes into which this function transforms.
825
+ """
826
+ try:
827
+ function_decorators = get_node_decorators(fn, config)
828
+ node_resolvers = function_decorators[NodeResolver.get_lifecycle_name()]
829
+ for resolver in node_resolvers:
830
+ fn = resolver.resolve(fn, config=filter_config(config, resolver))
831
+ if fn is None:
832
+ return []
833
+ (node_creator,) = function_decorators[NodeCreator.get_lifecycle_name()]
834
+ nodes = node_creator.generate_nodes(fn, filter_config(config, node_creator))
835
+ node_injectors = function_decorators[NodeInjector.get_lifecycle_name()]
836
+ for node_injector in node_injectors:
837
+ nodes = node_injector.transform_dag(nodes, filter_config(config, node_injector), fn)
838
+ node_expanders = function_decorators[NodeExpander.get_lifecycle_name()]
839
+ if len(node_expanders) > 0:
840
+ (node_expander,) = node_expanders
841
+ nodes = node_expander.transform_dag(nodes, filter_config(config, node_expander), fn)
842
+ node_transformers = function_decorators[NodeTransformer.get_lifecycle_name()]
843
+ for dag_modifier in node_transformers:
844
+ nodes = dag_modifier.transform_dag(nodes, filter_config(config, dag_modifier), fn)
845
+ function_decorators = function_decorators[NodeDecorator.get_lifecycle_name()]
846
+ for node_decorator in function_decorators:
847
+ nodes = node_decorator.transform_dag(nodes, filter_config(config, node_decorator), fn)
848
+ return _add_original_function_to_nodes(fn, nodes)
849
+ except Exception as e:
850
+ logger.exception(_resolve_nodes_error(fn))
851
+ raise e
852
+
853
+
854
+ class InvalidDecoratorException(Exception):
855
+ pass
856
+
857
+
858
+ class MissingConfigParametersException(Exception):
859
+ pass