runnable 0.1.0__py3-none-any.whl → 0.2.0__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 (71) hide show
  1. runnable/__init__.py +34 -0
  2. runnable/catalog.py +141 -0
  3. runnable/cli.py +272 -0
  4. runnable/context.py +34 -0
  5. runnable/datastore.py +686 -0
  6. runnable/defaults.py +179 -0
  7. runnable/entrypoints.py +484 -0
  8. runnable/exceptions.py +94 -0
  9. runnable/executor.py +431 -0
  10. runnable/experiment_tracker.py +139 -0
  11. runnable/extensions/catalog/__init__.py +21 -0
  12. runnable/extensions/catalog/file_system/__init__.py +0 -0
  13. runnable/extensions/catalog/file_system/implementation.py +226 -0
  14. runnable/extensions/catalog/k8s_pvc/__init__.py +0 -0
  15. runnable/extensions/catalog/k8s_pvc/implementation.py +16 -0
  16. runnable/extensions/catalog/k8s_pvc/integration.py +59 -0
  17. runnable/extensions/executor/__init__.py +714 -0
  18. runnable/extensions/executor/argo/__init__.py +0 -0
  19. runnable/extensions/executor/argo/implementation.py +1182 -0
  20. runnable/extensions/executor/argo/specification.yaml +51 -0
  21. runnable/extensions/executor/k8s_job/__init__.py +0 -0
  22. runnable/extensions/executor/k8s_job/implementation_FF.py +259 -0
  23. runnable/extensions/executor/k8s_job/integration_FF.py +69 -0
  24. runnable/extensions/executor/local/__init__.py +0 -0
  25. runnable/extensions/executor/local/implementation.py +69 -0
  26. runnable/extensions/executor/local_container/__init__.py +0 -0
  27. runnable/extensions/executor/local_container/implementation.py +367 -0
  28. runnable/extensions/executor/mocked/__init__.py +0 -0
  29. runnable/extensions/executor/mocked/implementation.py +220 -0
  30. runnable/extensions/experiment_tracker/__init__.py +0 -0
  31. runnable/extensions/experiment_tracker/mlflow/__init__.py +0 -0
  32. runnable/extensions/experiment_tracker/mlflow/implementation.py +94 -0
  33. runnable/extensions/nodes.py +675 -0
  34. runnable/extensions/run_log_store/__init__.py +0 -0
  35. runnable/extensions/run_log_store/chunked_file_system/__init__.py +0 -0
  36. runnable/extensions/run_log_store/chunked_file_system/implementation.py +106 -0
  37. runnable/extensions/run_log_store/chunked_k8s_pvc/__init__.py +0 -0
  38. runnable/extensions/run_log_store/chunked_k8s_pvc/implementation.py +21 -0
  39. runnable/extensions/run_log_store/chunked_k8s_pvc/integration.py +61 -0
  40. runnable/extensions/run_log_store/db/implementation_FF.py +157 -0
  41. runnable/extensions/run_log_store/db/integration_FF.py +0 -0
  42. runnable/extensions/run_log_store/file_system/__init__.py +0 -0
  43. runnable/extensions/run_log_store/file_system/implementation.py +136 -0
  44. runnable/extensions/run_log_store/generic_chunked.py +541 -0
  45. runnable/extensions/run_log_store/k8s_pvc/__init__.py +0 -0
  46. runnable/extensions/run_log_store/k8s_pvc/implementation.py +21 -0
  47. runnable/extensions/run_log_store/k8s_pvc/integration.py +56 -0
  48. runnable/extensions/secrets/__init__.py +0 -0
  49. runnable/extensions/secrets/dotenv/__init__.py +0 -0
  50. runnable/extensions/secrets/dotenv/implementation.py +100 -0
  51. runnable/extensions/secrets/env_secrets/__init__.py +0 -0
  52. runnable/extensions/secrets/env_secrets/implementation.py +42 -0
  53. runnable/graph.py +464 -0
  54. runnable/integration.py +205 -0
  55. runnable/interaction.py +399 -0
  56. runnable/names.py +546 -0
  57. runnable/nodes.py +489 -0
  58. runnable/parameters.py +183 -0
  59. runnable/pickler.py +102 -0
  60. runnable/sdk.py +470 -0
  61. runnable/secrets.py +95 -0
  62. runnable/tasks.py +392 -0
  63. runnable/utils.py +630 -0
  64. runnable-0.2.0.dist-info/METADATA +437 -0
  65. runnable-0.2.0.dist-info/RECORD +69 -0
  66. runnable-0.2.0.dist-info/entry_points.txt +44 -0
  67. runnable-0.1.0.dist-info/METADATA +0 -16
  68. runnable-0.1.0.dist-info/RECORD +0 -6
  69. /runnable/{.gitkeep → extensions/__init__.py} +0 -0
  70. {runnable-0.1.0.dist-info → runnable-0.2.0.dist-info}/LICENSE +0 -0
  71. {runnable-0.1.0.dist-info → runnable-0.2.0.dist-info}/WHEEL +0 -0
@@ -0,0 +1,714 @@
1
+ import copy
2
+ import json
3
+ import logging
4
+ import os
5
+ from abc import abstractmethod
6
+ from typing import Any, Dict, List, Optional, cast
7
+
8
+ from rich import print
9
+
10
+ from runnable import context, defaults, exceptions, integration, parameters, utils
11
+ from runnable.datastore import DataCatalog, RunLog, StepLog
12
+ from runnable.defaults import TypeMapVariable
13
+ from runnable.executor import BaseExecutor
14
+ from runnable.experiment_tracker import get_tracked_data
15
+ from runnable.extensions.nodes import TaskNode
16
+ from runnable.graph import Graph
17
+ from runnable.nodes import BaseNode
18
+
19
+ logger = logging.getLogger(defaults.LOGGER_NAME)
20
+
21
+
22
+ class GenericExecutor(BaseExecutor):
23
+ """
24
+ The skeleton of an executor class.
25
+ Any implementation of an executor should inherit this class and over-ride accordingly.
26
+
27
+ This is a loaded base class which has a lot of methods already implemented for "typical" executions.
28
+ Look at the function docs to understand how to use them appropriately.
29
+
30
+ For any implementation:
31
+ 1). Who/when should the run log be set up?
32
+ 2). Who/When should the step log be set up?
33
+
34
+ """
35
+
36
+ service_name: str = ""
37
+ service_type: str = "executor"
38
+
39
+ @property
40
+ def _context(self):
41
+ return context.run_context
42
+
43
+ @property
44
+ def step_decorator_run_id(self):
45
+ """
46
+ TODO: Experimental feature, design is not mature yet.
47
+
48
+ This function is used by the decorator function.
49
+ The design idea is we can over-ride this method in different implementations to retrieve the run_id.
50
+ But is it really intrusive to ask to set the environmental variable MAGNUS_RUN_ID?
51
+
52
+ Returns:
53
+ _type_: _description_
54
+ """
55
+ return os.environ.get("MAGNUS_RUN_ID", None)
56
+
57
+ def _get_parameters(self) -> Dict[str, Any]:
58
+ """
59
+ Consolidate the parameters from the environment variables
60
+ and the parameters file.
61
+
62
+ The parameters defined in the environment variables take precedence over the parameters file.
63
+
64
+ Returns:
65
+ _type_: _description_
66
+ """
67
+ params: Dict[str, Any] = {}
68
+ if self._context.parameters_file:
69
+ params.update(utils.load_yaml(self._context.parameters_file))
70
+
71
+ # Update these with some from the environment variables
72
+ params.update(parameters.get_user_set_parameters())
73
+ return params
74
+
75
+ def _set_up_for_re_run(self, parameters: Dict[str, Any]) -> None:
76
+ try:
77
+ attempt_run_log = self._context.run_log_store.get_run_log_by_id(
78
+ run_id=self._context.original_run_id, full=False
79
+ )
80
+ except exceptions.RunLogNotFoundError as e:
81
+ msg = (
82
+ f"Expected a run log with id: {self._context.original_run_id} "
83
+ "but it does not exist in the run log store. "
84
+ "If the original execution was in a different environment, ensure that it is available in the current "
85
+ "environment."
86
+ )
87
+ logger.exception(msg)
88
+ raise Exception(msg) from e
89
+
90
+ # Sync the previous run log catalog to this one.
91
+ self._context.catalog_handler.sync_between_runs(
92
+ previous_run_id=self._context.original_run_id, run_id=self._context.run_id
93
+ )
94
+
95
+ parameters.update(cast(RunLog, attempt_run_log).parameters)
96
+
97
+ def _set_up_run_log(self, exists_ok=False):
98
+ """
99
+ Create a run log and put that in the run log store
100
+
101
+ If exists_ok, we allow the run log to be already present in the run log store.
102
+ """
103
+ try:
104
+ attempt_run_log = self._context.run_log_store.get_run_log_by_id(run_id=self._context.run_id, full=False)
105
+
106
+ logger.warning(f"The run log by id: {self._context.run_id} already exists")
107
+ raise exceptions.RunLogExistsError(
108
+ f"The run log by id: {self._context.run_id} already exists and is {attempt_run_log.status}"
109
+ )
110
+ except exceptions.RunLogNotFoundError:
111
+ pass
112
+ except exceptions.RunLogExistsError:
113
+ if exists_ok:
114
+ return
115
+ raise
116
+
117
+ # Consolidate and get the parameters
118
+ parameters = self._get_parameters()
119
+
120
+ if self._context.use_cached:
121
+ self._set_up_for_re_run(parameters=parameters)
122
+
123
+ self._context.run_log_store.create_run_log(
124
+ run_id=self._context.run_id,
125
+ tag=self._context.tag,
126
+ status=defaults.PROCESSING,
127
+ dag_hash=self._context.dag_hash,
128
+ use_cached=self._context.use_cached,
129
+ original_run_id=self._context.original_run_id,
130
+ )
131
+ # Any interaction with run log store attributes should happen via API if available.
132
+ self._context.run_log_store.set_parameters(run_id=self._context.run_id, parameters=parameters)
133
+
134
+ # Update run_config
135
+ run_config = utils.get_run_config()
136
+ self._context.run_log_store.set_run_config(run_id=self._context.run_id, run_config=run_config)
137
+
138
+ def prepare_for_graph_execution(self):
139
+ """
140
+ This method should be called prior to calling execute_graph.
141
+ Perform any steps required before doing the graph execution.
142
+
143
+ The most common implementation is to prepare a run log for the run if the run uses local interactive compute.
144
+
145
+ But in cases of actual rendering the job specs (eg: AWS step functions, K8's) we check if the services are OK.
146
+ We do not set up a run log as its not relevant.
147
+ """
148
+
149
+ integration.validate(self, self._context.run_log_store)
150
+ integration.configure_for_traversal(self, self._context.run_log_store)
151
+
152
+ integration.validate(self, self._context.catalog_handler)
153
+ integration.configure_for_traversal(self, self._context.catalog_handler)
154
+
155
+ integration.validate(self, self._context.secrets_handler)
156
+ integration.configure_for_traversal(self, self._context.secrets_handler)
157
+
158
+ integration.validate(self, self._context.experiment_tracker)
159
+ integration.configure_for_traversal(self, self._context.experiment_tracker)
160
+
161
+ self._set_up_run_log()
162
+
163
+ def prepare_for_node_execution(self):
164
+ """
165
+ Perform any modifications to the services prior to execution of the node.
166
+
167
+ Args:
168
+ node (Node): [description]
169
+ map_variable (dict, optional): [description]. Defaults to None.
170
+ """
171
+ integration.validate(self, self._context.run_log_store)
172
+ integration.configure_for_execution(self, self._context.run_log_store)
173
+
174
+ integration.validate(self, self._context.catalog_handler)
175
+ integration.configure_for_execution(self, self._context.catalog_handler)
176
+
177
+ integration.validate(self, self._context.secrets_handler)
178
+ integration.configure_for_execution(self, self._context.secrets_handler)
179
+
180
+ integration.validate(self, self._context.experiment_tracker)
181
+ integration.configure_for_execution(self, self._context.experiment_tracker)
182
+
183
+ def _sync_catalog(self, step_log: StepLog, stage: str, synced_catalogs=None) -> Optional[List[DataCatalog]]:
184
+ """
185
+ 1). Identify the catalog settings by over-riding node settings with the global settings.
186
+ 2). For stage = get:
187
+ Identify the catalog items that are being asked to get from the catalog
188
+ And copy them to the local compute data folder
189
+ 3). For stage = put:
190
+ Identify the catalog items that are being asked to put into the catalog
191
+ Copy the items from local compute folder to the catalog
192
+ 4). Add the items onto the step log according to the stage
193
+
194
+ Args:
195
+ node (Node): The current node being processed
196
+ step_log (StepLog): The step log corresponding to that node
197
+ stage (str): One of get or put
198
+
199
+ Raises:
200
+ Exception: If the stage is not in one of get/put
201
+
202
+ """
203
+ if stage not in ["get", "put"]:
204
+ msg = (
205
+ "Catalog service only accepts get/put possible actions as part of node execution."
206
+ f"Sync catalog of the executor: {self.service_name} asks for {stage} which is not accepted"
207
+ )
208
+ raise Exception(msg)
209
+
210
+ try:
211
+ node_catalog_settings = self._context_node._get_catalog_settings()
212
+ except exceptions.TerminalNodeError:
213
+ return None
214
+
215
+ if not (node_catalog_settings and stage in node_catalog_settings):
216
+ logger.info("No catalog settings found for stage: %s", stage)
217
+ # Nothing to get/put from the catalog
218
+ return None
219
+
220
+ compute_data_folder = self.get_effective_compute_data_folder()
221
+
222
+ data_catalogs = []
223
+ for name_pattern in node_catalog_settings.get(stage) or []:
224
+ if stage == "get":
225
+ data_catalog = self._context.catalog_handler.get(
226
+ name=name_pattern, run_id=self._context.run_id, compute_data_folder=compute_data_folder
227
+ )
228
+ elif stage == "put":
229
+ data_catalog = self._context.catalog_handler.put(
230
+ name=name_pattern,
231
+ run_id=self._context.run_id,
232
+ compute_data_folder=compute_data_folder,
233
+ synced_catalogs=synced_catalogs,
234
+ )
235
+ else:
236
+ raise Exception(f"Invalid stage: {stage}")
237
+ logger.info(f"Added data catalog: {data_catalog} to step log")
238
+ data_catalogs.extend(data_catalog)
239
+
240
+ if data_catalogs:
241
+ step_log.add_data_catalogs(data_catalogs)
242
+
243
+ return data_catalogs
244
+
245
+ def get_effective_compute_data_folder(self) -> str:
246
+ """
247
+ Get the effective compute data folder for the given stage.
248
+ If there is nothing to catalog, we return None.
249
+
250
+ The default is the compute data folder of the catalog but this can be over-ridden by the node.
251
+
252
+ Args:
253
+ stage (str): The stage we are in the process of cataloging
254
+
255
+
256
+ Returns:
257
+ str: The compute data folder as defined by the node defaulting to catalog handler
258
+ """
259
+ compute_data_folder = self._context.catalog_handler.compute_data_folder
260
+
261
+ catalog_settings = self._context_node._get_catalog_settings()
262
+ effective_compute_data_folder = catalog_settings.get("compute_data_folder", "") or compute_data_folder
263
+
264
+ return effective_compute_data_folder
265
+
266
+ @property
267
+ def step_attempt_number(self) -> int:
268
+ """
269
+ The attempt number of the current step.
270
+ Orchestrators should use this step to submit multiple attempts of the job.
271
+
272
+ Returns:
273
+ int: The attempt number of the current step. Defaults to 1.
274
+ """
275
+ return int(os.environ.get(defaults.ATTEMPT_NUMBER, 1))
276
+
277
+ def _execute_node(self, node: BaseNode, map_variable: TypeMapVariable = None, **kwargs):
278
+ """
279
+ This is the entry point when we do the actual execution of the function.
280
+ DO NOT Over-ride this function.
281
+
282
+ While in interactive execution, we just compute, in 3rd party interactive execution, we need to reach
283
+ this function.
284
+
285
+ In most cases,
286
+ * We get the corresponding step_log of the node and the parameters.
287
+ * We sync the catalog to GET any data sets that are in the catalog
288
+ * We call the execute method of the node for the actual compute and retry it as many times as asked.
289
+ * If the node succeeds, we get any of the user defined metrics provided by the user.
290
+ * We sync the catalog to PUT any data sets that are in the catalog.
291
+
292
+ Args:
293
+ node (Node): The node to execute
294
+ map_variable (dict, optional): If the node is of a map state, map_variable is the value of the iterable.
295
+ Defaults to None.
296
+ """
297
+ step_log = self._context.run_log_store.get_step_log(node._get_step_log_name(map_variable), self._context.run_id)
298
+ """
299
+ By now, all the parameters are part of the run log as a dictionary.
300
+ We set them as environment variables, serialized as json strings.
301
+ """
302
+ params = self._context.run_log_store.get_parameters(run_id=self._context.run_id)
303
+ parameters.set_user_defined_params_as_environment_variables(params)
304
+
305
+ attempt = self.step_attempt_number
306
+ logger.info(f"Trying to execute node: {node.internal_name}, attempt : {attempt}")
307
+
308
+ attempt_log = self._context.run_log_store.create_attempt_log()
309
+ self._context_step_log = step_log
310
+ self._context_node = node
311
+
312
+ data_catalogs_get: Optional[List[DataCatalog]] = self._sync_catalog(step_log, stage="get")
313
+ try:
314
+ attempt_log = node.execute(executor=self, mock=step_log.mock, map_variable=map_variable, **kwargs)
315
+ except Exception as e:
316
+ # Any exception here is a magnus exception as node suppresses exceptions.
317
+ msg = "This is clearly magnus fault, please report a bug and the logs"
318
+ logger.exception(msg)
319
+ raise Exception(msg) from e
320
+ finally:
321
+ attempt_log.attempt_number = attempt
322
+ attempt_log.parameters = params.copy()
323
+ step_log.attempts.append(attempt_log)
324
+
325
+ tracked_data = get_tracked_data()
326
+
327
+ self._context.experiment_tracker.publish_data(tracked_data)
328
+ # By this point, the updated parameters are deserialized as json strings.
329
+ parameters_out = parameters.get_user_set_parameters(remove=True)
330
+
331
+ if attempt_log.status == defaults.FAIL:
332
+ logger.exception(f"Node: {node} failed")
333
+ step_log.status = defaults.FAIL
334
+ else:
335
+ # Mock is always set to False, bad design??
336
+ # TODO: Stub nodes should not sync back data
337
+ # TODO: Errors in catalog syncing should point to Fail step
338
+ # TODO: Even for a failed execution, the catalog can happen
339
+ step_log.status = defaults.SUCCESS
340
+ self._sync_catalog(step_log, stage="put", synced_catalogs=data_catalogs_get)
341
+ step_log.user_defined_metrics = tracked_data
342
+ diff_parameters = utils.diff_dict(params, parameters_out)
343
+ self._context.run_log_store.set_parameters(self._context.run_id, diff_parameters)
344
+
345
+ # Remove the step context
346
+ self._context_step_log = None
347
+ self._context_node = None # type: ignore
348
+ self._context_metrics = {} # type: ignore
349
+
350
+ self._context.run_log_store.add_step_log(step_log, self._context.run_id)
351
+
352
+ def add_code_identities(self, node: BaseNode, step_log: StepLog, **kwargs):
353
+ """
354
+ Add code identities specific to the implementation.
355
+
356
+ The Base class has an implementation of adding git code identities.
357
+
358
+ Args:
359
+ step_log (object): The step log object
360
+ node (BaseNode): The node we are adding the step log for
361
+ """
362
+ step_log.code_identities.append(utils.get_git_code_identity())
363
+
364
+ def execute_from_graph(self, node: BaseNode, map_variable: TypeMapVariable = None, **kwargs):
365
+ """
366
+ This is the entry point to from the graph execution.
367
+
368
+ While the self.execute_graph is responsible for traversing the graph, this function is responsible for
369
+ actual execution of the node.
370
+
371
+ If the node type is:
372
+ * task : We can delegate to _execute_node after checking the eligibility for re-run in cases of a re-run
373
+ * success: We can delegate to _execute_node
374
+ * fail: We can delegate to _execute_node
375
+
376
+ For nodes that are internally graphs:
377
+ * parallel: Delegate the responsibility of execution to the node.execute_as_graph()
378
+ * dag: Delegate the responsibility of execution to the node.execute_as_graph()
379
+ * map: Delegate the responsibility of execution to the node.execute_as_graph()
380
+
381
+ Transpilers will NEVER use this method and will NEVER call ths method.
382
+ This method should only be used by interactive executors.
383
+
384
+ Args:
385
+ node (Node): The node to execute
386
+ map_variable (dict, optional): If the node if of a map state, this corresponds to the value of iterable.
387
+ Defaults to None.
388
+ """
389
+ step_log = self._context.run_log_store.create_step_log(node.name, node._get_step_log_name(map_variable))
390
+
391
+ self.add_code_identities(node=node, step_log=step_log)
392
+
393
+ step_log.step_type = node.node_type
394
+ step_log.status = defaults.PROCESSING
395
+
396
+ # Add the step log to the database as per the situation.
397
+ # If its a terminal node, complete it now
398
+ if node.node_type in ["success", "fail"]:
399
+ self._context.run_log_store.add_step_log(step_log, self._context.run_id)
400
+ self._execute_node(node, map_variable=map_variable, **kwargs)
401
+ return
402
+
403
+ # In single step
404
+ if (self._single_step and not node.name == self._single_step) or not self._is_step_eligible_for_rerun(
405
+ node, map_variable=map_variable
406
+ ):
407
+ # If the node name does not match, we move on to the next node.
408
+ # If previous run was successful, move on to the next step
409
+ step_log.mock = True
410
+ step_log.status = defaults.SUCCESS
411
+ self._context.run_log_store.add_step_log(step_log, self._context.run_id)
412
+ return
413
+ # We call an internal function to iterate the sub graphs and execute them
414
+ if node.is_composite:
415
+ self._context.run_log_store.add_step_log(step_log, self._context.run_id)
416
+ node.execute_as_graph(map_variable=map_variable, **kwargs)
417
+ return
418
+
419
+ # Executor specific way to trigger a job
420
+ self._context.run_log_store.add_step_log(step_log, self._context.run_id)
421
+ self.trigger_job(node=node, map_variable=map_variable, **kwargs)
422
+
423
+ def trigger_job(self, node: BaseNode, map_variable: TypeMapVariable = None, **kwargs):
424
+ """
425
+ Call this method only if we are responsible for traversing the graph via
426
+ execute_from_graph().
427
+
428
+ We are not prepared to execute node as of now.
429
+
430
+ Args:
431
+ node (BaseNode): The node to execute
432
+ map_variable (str, optional): If the node if of a map state, this corresponds to the value of iterable.
433
+ Defaults to ''.
434
+
435
+ NOTE: We do not raise an exception as this method is not required by many extensions
436
+ """
437
+ pass
438
+
439
+ def _get_status_and_next_node_name(self, current_node: BaseNode, dag: Graph, map_variable: TypeMapVariable = None):
440
+ """
441
+ Given the current node and the graph, returns the name of the next node to execute.
442
+
443
+ The name is always relative the graph that the node resides in.
444
+
445
+ If the current node succeeded, we return the next node as per the graph.
446
+ If the current node failed, we return the on failure node of the node (if provided) or the global one.
447
+
448
+ This method is only used by interactive executors i.e local and local-container
449
+
450
+ Args:
451
+ current_node (BaseNode): The current node.
452
+ dag (Graph): The dag we are traversing.
453
+ map_variable (dict): If the node belongs to a map branch.
454
+
455
+ """
456
+
457
+ step_log = self._context.run_log_store.get_step_log(
458
+ current_node._get_step_log_name(map_variable), self._context.run_id
459
+ )
460
+ logger.info(f"Finished executing the node {current_node} with status {step_log.status}")
461
+
462
+ try:
463
+ next_node_name = current_node._get_next_node()
464
+ except exceptions.TerminalNodeError:
465
+ next_node_name = ""
466
+
467
+ if step_log.status == defaults.FAIL:
468
+ next_node_name = dag.get_fail_node().name
469
+ if current_node._get_on_failure_node():
470
+ next_node_name = current_node._get_on_failure_node()
471
+
472
+ return step_log.status, next_node_name
473
+
474
+ def execute_graph(self, dag: Graph, map_variable: TypeMapVariable = None, **kwargs):
475
+ """
476
+ The parallelization is controlled by the nodes and not by this function.
477
+
478
+ Transpilers should over ride this method to do the translation of dag to the platform specific way.
479
+ Interactive methods should use this to traverse and execute the dag.
480
+ - Use execute_from_graph to handle sub-graphs
481
+
482
+ Logically the method should:
483
+ * Start at the dag.start_at of the dag.
484
+ * Call the self.execute_from_graph(node)
485
+ * depending upon the status of the execution, either move to the success node or failure node.
486
+
487
+ Args:
488
+ dag (Graph): The directed acyclic graph to traverse and execute.
489
+ map_variable (dict, optional): If the node if of a map state, this corresponds to the value of the iterable.
490
+ Defaults to None.
491
+ """
492
+ current_node = dag.start_at
493
+ previous_node = None
494
+ logger.info(f"Running the execution with {current_node}")
495
+
496
+ while True:
497
+ working_on = dag.get_node_by_name(current_node)
498
+
499
+ if previous_node == current_node:
500
+ raise Exception("Potentially running in a infinite loop")
501
+
502
+ previous_node = current_node
503
+
504
+ logger.info(f"Creating execution log for {working_on}")
505
+ self.execute_from_graph(working_on, map_variable=map_variable, **kwargs)
506
+
507
+ status, next_node_name = self._get_status_and_next_node_name(
508
+ current_node=working_on, dag=dag, map_variable=map_variable
509
+ )
510
+
511
+ if status == defaults.TRIGGERED:
512
+ # Some nodes go into triggered state and self traverse
513
+ logger.info(f"Triggered the job to execute the node {current_node}")
514
+ break
515
+
516
+ if working_on.node_type in ["success", "fail"]:
517
+ break
518
+
519
+ current_node = next_node_name
520
+
521
+ run_log = self._context.run_log_store.get_branch_log(
522
+ working_on._get_branch_log_name(map_variable), self._context.run_id
523
+ )
524
+
525
+ branch = "graph"
526
+ if working_on.internal_branch_name:
527
+ branch = working_on.internal_branch_name
528
+
529
+ logger.info(f"Finished execution of the {branch} with status {run_log.status}")
530
+
531
+ # get the final run log
532
+ if branch == "graph":
533
+ run_log = self._context.run_log_store.get_run_log_by_id(run_id=self._context.run_id, full=True)
534
+ print(json.dumps(run_log.model_dump(), indent=4))
535
+
536
+ def _is_step_eligible_for_rerun(self, node: BaseNode, map_variable: TypeMapVariable = None):
537
+ """
538
+ In case of a re-run, this method checks to see if the previous run step status to determine if a re-run is
539
+ necessary.
540
+ * True: If its not a re-run.
541
+ * True: If its a re-run and we failed in the last run or the corresponding logs do not exist.
542
+ * False: If its a re-run and we succeeded in the last run.
543
+
544
+ Most cases, this logic need not be touched
545
+
546
+ Args:
547
+ node (Node): The node to check against re-run
548
+ map_variable (dict, optional): If the node if of a map state, this corresponds to the value of iterable..
549
+ Defaults to None.
550
+
551
+ Returns:
552
+ bool: Eligibility for re-run. True means re-run, False means skip to the next step.
553
+ """
554
+ if self._context.use_cached:
555
+ node_step_log_name = node._get_step_log_name(map_variable=map_variable)
556
+ logger.info(f"Scanning previous run logs for node logs of: {node_step_log_name}")
557
+
558
+ try:
559
+ previous_node_log = self._context.run_log_store.get_step_log(
560
+ internal_name=node_step_log_name, run_id=self._context.original_run_id
561
+ )
562
+ except exceptions.StepLogNotFoundError:
563
+ logger.warning(f"Did not find the node {node.name} in previous run log")
564
+ return True # We should re-run the node.
565
+
566
+ logger.info(f"The original step status: {previous_node_log.status}")
567
+
568
+ if previous_node_log.status == defaults.SUCCESS:
569
+ return False # We need not run the node
570
+
571
+ logger.info(f"The new execution should start executing graph from this node {node.name}")
572
+ return True
573
+
574
+ return True
575
+
576
+ def send_return_code(self, stage="traversal"):
577
+ """
578
+ Convenience function used by pipeline to send return code to the caller of the cli
579
+
580
+ Raises:
581
+ Exception: If the pipeline execution failed
582
+ """
583
+ run_id = self._context.run_id
584
+
585
+ run_log = self._context.run_log_store.get_run_log_by_id(run_id=run_id, full=False)
586
+ if run_log.status == defaults.FAIL:
587
+ raise exceptions.ExecutionFailedError(run_id=run_id)
588
+
589
+ def _resolve_executor_config(self, node: BaseNode):
590
+ """
591
+ The overrides section can contain specific over-rides to an global executor config.
592
+ To avoid too much clutter in the dag definition, we allow the configuration file to have overrides block.
593
+ The nodes can over-ride the global config by referring to key in the overrides.
594
+
595
+ This function also applies variables to the effective node config.
596
+
597
+ For example:
598
+ # configuration.yaml
599
+ execution:
600
+ type: cloud-implementation
601
+ config:
602
+ k1: v1
603
+ k3: v3
604
+ overrides:
605
+ custom_config:
606
+ k1: v11
607
+ k2: v2 # Could be a mapping internally.
608
+
609
+ # in pipeline definition.yaml
610
+ dag:
611
+ steps:
612
+ step1:
613
+ overrides:
614
+ cloud-implementation: custom_config
615
+
616
+ This method should resolve the node_config to {'k1': 'v11', 'k2': 'v2', 'k3': 'v3'}
617
+
618
+ Args:
619
+ node (BaseNode): The current node being processed.
620
+
621
+ """
622
+ effective_node_config = copy.deepcopy(self.model_dump())
623
+ try:
624
+ ctx_node_config = node._get_executor_config(self.service_name)
625
+ except exceptions.TerminalNodeError:
626
+ # Some modes request for effective node config even for success or fail nodes
627
+ return utils.apply_variables(effective_node_config, self._context.variables)
628
+
629
+ if ctx_node_config:
630
+ if ctx_node_config not in self.overrides:
631
+ raise Exception(f"No override of key: {ctx_node_config} found in the overrides section")
632
+
633
+ effective_node_config.update(self.overrides[ctx_node_config])
634
+
635
+ effective_node_config = utils.apply_variables(effective_node_config, self._context.variables)
636
+ logger.debug(f"Effective node config: {effective_node_config}")
637
+
638
+ return effective_node_config
639
+
640
+ @abstractmethod
641
+ def execute_job(self, node: TaskNode):
642
+ """
643
+ Executor specific way of executing a job (python function or a notebook).
644
+
645
+ Interactive executors should execute the job.
646
+ Transpilers should write the instructions.
647
+
648
+ Args:
649
+ node (BaseNode): The job node to execute
650
+
651
+ Raises:
652
+ NotImplementedError: Executors should choose to extend this functionality or not.
653
+ """
654
+ raise NotImplementedError
655
+
656
+ def fan_out(self, node: BaseNode, map_variable: TypeMapVariable = None):
657
+ """
658
+ This method is used to appropriately fan-out the execution of a composite node.
659
+ This is only useful when we want to execute a composite node during 3rd party orchestrators.
660
+
661
+ Reason: Transpilers typically try to run the leaf nodes but do not have any capacity to do anything for the
662
+ step which is composite. By calling this fan-out before calling the leaf nodes, we have an opportunity to
663
+ do the right set up (creating the step log, exposing the parameters, etc.) for the composite step.
664
+
665
+ All 3rd party orchestrators should use this method to fan-out the execution of a composite node.
666
+ This ensures:
667
+ - The dot path notation is preserved, this method should create the step and call the node's fan out to
668
+ create the branch logs and let the 3rd party do the actual step execution.
669
+ - Gives 3rd party orchestrators an opportunity to set out the required for running a composite node.
670
+
671
+ Args:
672
+ node (BaseNode): The node to fan-out
673
+ map_variable (dict, optional): If the node if of a map state,.Defaults to None.
674
+
675
+ """
676
+ step_log = self._context.run_log_store.create_step_log(
677
+ node.name, node._get_step_log_name(map_variable=map_variable)
678
+ )
679
+
680
+ self.add_code_identities(node=node, step_log=step_log)
681
+
682
+ step_log.step_type = node.node_type
683
+ step_log.status = defaults.PROCESSING
684
+ self._context.run_log_store.add_step_log(step_log, self._context.run_id)
685
+
686
+ node.fan_out(executor=self, map_variable=map_variable)
687
+
688
+ def fan_in(self, node: BaseNode, map_variable: TypeMapVariable = None):
689
+ """
690
+ This method is used to appropriately fan-in after the execution of a composite node.
691
+ This is only useful when we want to execute a composite node during 3rd party orchestrators.
692
+
693
+ Reason: Transpilers typically try to run the leaf nodes but do not have any capacity to do anything for the
694
+ step which is composite. By calling this fan-in after calling the leaf nodes, we have an opportunity to
695
+ act depending upon the status of the individual branches.
696
+
697
+ All 3rd party orchestrators should use this method to fan-in the execution of a composite node.
698
+ This ensures:
699
+ - Gives the renderer's the control on where to go depending upon the state of the composite node.
700
+ - The status of the step and its underlying branches are correctly updated.
701
+
702
+ Args:
703
+ node (BaseNode): The node to fan-in
704
+ map_variable (dict, optional): If the node if of a map state,.Defaults to None.
705
+
706
+ """
707
+ node.fan_in(executor=self, map_variable=map_variable)
708
+
709
+ step_log = self._context.run_log_store.get_step_log(
710
+ node._get_step_log_name(map_variable=map_variable), self._context.run_id
711
+ )
712
+
713
+ if step_log.status == defaults.FAIL:
714
+ raise Exception(f"Step {node.name} failed")