codecraftai-agent-kit 1.3.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 (230) hide show
  1. ccai/agentkit/__init__.py +304 -0
  2. ccai/agentkit/addressresolver.py +177 -0
  3. ccai/agentkit/agent.py +2945 -0
  4. ccai/agentkit/agentaddress.py +187 -0
  5. ccai/agentkit/agentconfiguration.py +581 -0
  6. ccai/agentkit/agentidentity.py +152 -0
  7. ccai/agentkit/agentregistry.py +221 -0
  8. ccai/agentkit/agentstatemachine.py +134 -0
  9. ccai/agentkit/alternateproviderstrategy.py +36 -0
  10. ccai/agentkit/approvalgate.py +238 -0
  11. ccai/agentkit/approvalrequest.py +250 -0
  12. ccai/agentkit/asyncagent.py +187 -0
  13. ccai/agentkit/breakpoint.py +150 -0
  14. ccai/agentkit/builtinagentmetrics.py +114 -0
  15. ccai/agentkit/builtins/__init__.py +11 -0
  16. ccai/agentkit/builtins/filereadtool.py +90 -0
  17. ccai/agentkit/builtins/filewritetool.py +93 -0
  18. ccai/agentkit/builtins/httprequesttool.py +169 -0
  19. ccai/agentkit/builtins/shellcommandtool.py +190 -0
  20. ccai/agentkit/cachedresultstrategy.py +43 -0
  21. ccai/agentkit/checkpointmanager.py +219 -0
  22. ccai/agentkit/circuitbreaker.py +230 -0
  23. ccai/agentkit/circuitbreakerconfiguration.py +158 -0
  24. ccai/agentkit/circuitbreakerevent.py +158 -0
  25. ccai/agentkit/circuitbreakerhealthcheck.py +32 -0
  26. ccai/agentkit/circuitbreakerregistry.py +116 -0
  27. ccai/agentkit/circuitbreakerstate.py +44 -0
  28. ccai/agentkit/clearcacheaction.py +46 -0
  29. ccai/agentkit/concurrencybridge.py +143 -0
  30. ccai/agentkit/concurrencymodel.py +19 -0
  31. ccai/agentkit/conditionevaluator.py +594 -0
  32. ccai/agentkit/configurationchangeevent.py +179 -0
  33. ccai/agentkit/configurationerrors.py +152 -0
  34. ccai/agentkit/configurationlayer.py +160 -0
  35. ccai/agentkit/configurationlayersource.py +46 -0
  36. ccai/agentkit/configurationmanager.py +680 -0
  37. ccai/agentkit/configurationschema.py +224 -0
  38. ccai/agentkit/configurationschemafield.py +217 -0
  39. ccai/agentkit/configurationserializer.py +163 -0
  40. ccai/agentkit/configurationvalidationresult.py +118 -0
  41. ccai/agentkit/contextsummarizer.py +170 -0
  42. ccai/agentkit/contextwindow.py +264 -0
  43. ccai/agentkit/contextwindowstrategy.py +57 -0
  44. ccai/agentkit/correlationcontext.py +156 -0
  45. ccai/agentkit/costestimate.py +139 -0
  46. ccai/agentkit/costtracker.py +121 -0
  47. ccai/agentkit/deadletterentry.py +134 -0
  48. ccai/agentkit/deadletterquery.py +119 -0
  49. ccai/agentkit/deadletterqueue.py +123 -0
  50. ccai/agentkit/deadletterstore.py +86 -0
  51. ccai/agentkit/debuginspector.py +211 -0
  52. ccai/agentkit/debugsession.py +223 -0
  53. ccai/agentkit/defaultvaluestrategy.py +43 -0
  54. ccai/agentkit/degradationchangeevent.py +120 -0
  55. ccai/agentkit/degradationlevel.py +44 -0
  56. ccai/agentkit/degradationmanager.py +212 -0
  57. ccai/agentkit/degradationpolicy.py +130 -0
  58. ccai/agentkit/degradationstrategy.py +66 -0
  59. ccai/agentkit/embeddingprovider.py +106 -0
  60. ccai/agentkit/errors.py +95 -0
  61. ccai/agentkit/executionrecord.py +213 -0
  62. ccai/agentkit/executionrecorder.py +180 -0
  63. ccai/agentkit/executionrecording.py +230 -0
  64. ccai/agentkit/executionreplayer.py +187 -0
  65. ccai/agentkit/expirationpolicy.py +116 -0
  66. ccai/agentkit/fallbackchain.py +82 -0
  67. ccai/agentkit/featureflag.py +154 -0
  68. ccai/agentkit/featureflagevaluator.py +109 -0
  69. ccai/agentkit/featureflagregistry.py +258 -0
  70. ccai/agentkit/filedeadletterstore.py +112 -0
  71. ccai/agentkit/filememorystore.py +291 -0
  72. ccai/agentkit/healthcheck.py +46 -0
  73. ccai/agentkit/healthcheckregistry.py +51 -0
  74. ccai/agentkit/healthmonitor.py +258 -0
  75. ccai/agentkit/healthstatus.py +105 -0
  76. ccai/agentkit/hotreloadmonitor.py +214 -0
  77. ccai/agentkit/hotreloadpolicy.py +160 -0
  78. ccai/agentkit/inmemorydeadletterstore.py +61 -0
  79. ccai/agentkit/inmemorystore.py +173 -0
  80. ccai/agentkit/jsonmessageserializer.py +89 -0
  81. ccai/agentkit/jsonoutputparser.py +50 -0
  82. ccai/agentkit/lifecyclestate.py +22 -0
  83. ccai/agentkit/llmconversation.py +153 -0
  84. ccai/agentkit/llmerrors.py +193 -0
  85. ccai/agentkit/llmmessage.py +158 -0
  86. ccai/agentkit/llmprovider.py +158 -0
  87. ccai/agentkit/llmproviderregistry.py +200 -0
  88. ccai/agentkit/llmresponse.py +190 -0
  89. ccai/agentkit/llmstreamchunk.py +65 -0
  90. ccai/agentkit/llmstreamhandler.py +48 -0
  91. ccai/agentkit/llmtoolbridge.py +154 -0
  92. ccai/agentkit/logexporter.py +316 -0
  93. ccai/agentkit/logformatter.py +169 -0
  94. ccai/agentkit/memoryconfiguration.py +243 -0
  95. ccai/agentkit/memoryentry.py +254 -0
  96. ccai/agentkit/memoryerrors.py +135 -0
  97. ccai/agentkit/memoryindex.py +213 -0
  98. ccai/agentkit/memoryquery.py +248 -0
  99. ccai/agentkit/memoryqueryresult.py +86 -0
  100. ccai/agentkit/memoryscope.py +54 -0
  101. ccai/agentkit/memorystore.py +260 -0
  102. ccai/agentkit/memorystorehealthcheck.py +33 -0
  103. ccai/agentkit/memorystoreregistry.py +106 -0
  104. ccai/agentkit/message.py +310 -0
  105. ccai/agentkit/messageenvelope.py +144 -0
  106. ccai/agentkit/messagepattern.py +50 -0
  107. ccai/agentkit/messagerouter.py +290 -0
  108. ccai/agentkit/messageserializer.py +106 -0
  109. ccai/agentkit/messageserializerregistry.py +163 -0
  110. ccai/agentkit/messagingconfiguration.py +397 -0
  111. ccai/agentkit/messagingerrors.py +338 -0
  112. ccai/agentkit/metricdefinition.py +164 -0
  113. ccai/agentkit/metricmeasurement.py +178 -0
  114. ccai/agentkit/metricscollector.py +258 -0
  115. ccai/agentkit/metricsexporter.py +303 -0
  116. ccai/agentkit/metricsregistry.py +130 -0
  117. ccai/agentkit/metricssnapshot.py +155 -0
  118. ccai/agentkit/metrictype.py +51 -0
  119. ccai/agentkit/msgpackmessageserializer.py +97 -0
  120. ccai/agentkit/observabilityconfiguration.py +546 -0
  121. ccai/agentkit/observabilityerror.py +67 -0
  122. ccai/agentkit/observabilitypipeline.py +252 -0
  123. ccai/agentkit/outputparser.py +82 -0
  124. ccai/agentkit/outputschema.py +142 -0
  125. ccai/agentkit/parallelbranch.py +87 -0
  126. ccai/agentkit/platform/__init__.py +43 -0
  127. ccai/agentkit/platform/adapters/__init__.py +18 -0
  128. ccai/agentkit/platform/adapters/awsplatformadapter.py +1272 -0
  129. ccai/agentkit/platform/adapters/azureplatformadapter.py +1227 -0
  130. ccai/agentkit/platform/adapters/gcpplatformadapter.py +1257 -0
  131. ccai/agentkit/platform/adapters/localplatformadapter.py +956 -0
  132. ccai/agentkit/platform/adapters/platformadapter.py +139 -0
  133. ccai/agentkit/platform/deployment/__init__.py +15 -0
  134. ccai/agentkit/platform/deployment/deploymentdescriptor.py +234 -0
  135. ccai/agentkit/platform/deployment/deploymentdescriptorparser.py +178 -0
  136. ccai/agentkit/platform/deployment/deploymentdescriptorprinter.py +97 -0
  137. ccai/agentkit/platform/errors.py +224 -0
  138. ccai/agentkit/platform/platformconfiguration.py +412 -0
  139. ccai/agentkit/platform/platformdetector.py +125 -0
  140. ccai/agentkit/platform/platformruntime.py +331 -0
  141. ccai/agentkit/platform/platformserviceregistry.py +149 -0
  142. ccai/agentkit/platform/platformtype.py +60 -0
  143. ccai/agentkit/platform/services/__init__.py +19 -0
  144. ccai/agentkit/platform/services/computeservice.py +112 -0
  145. ccai/agentkit/platform/services/invocationresult.py +173 -0
  146. ccai/agentkit/platform/services/messagingservice.py +135 -0
  147. ccai/agentkit/platform/services/platformservice.py +111 -0
  148. ccai/agentkit/platform/services/queuemessage.py +193 -0
  149. ccai/agentkit/platform/services/storageobject.py +195 -0
  150. ccai/agentkit/platform/services/storageservice.py +159 -0
  151. ccai/agentkit/pluginconfiguration.py +241 -0
  152. ccai/agentkit/plugindependency.py +129 -0
  153. ccai/agentkit/plugindescriptor.py +225 -0
  154. ccai/agentkit/pluginlifecyclehook.py +41 -0
  155. ccai/agentkit/pluginmanager.py +360 -0
  156. ccai/agentkit/pluginstatus.py +47 -0
  157. ccai/agentkit/pooledagent.py +116 -0
  158. ccai/agentkit/prompttemplate.py +221 -0
  159. ccai/agentkit/prompttemplateregistry.py +145 -0
  160. ccai/agentkit/protobufmessageserializer.py +144 -0
  161. ccai/agentkit/pubsubbroker.py +311 -0
  162. ccai/agentkit/py.typed +0 -0
  163. ccai/agentkit/reconnecttransportaction.py +47 -0
  164. ccai/agentkit/regexoutputparser.py +68 -0
  165. ccai/agentkit/requestresponsehandler.py +274 -0
  166. ccai/agentkit/resetcircuitbreakeraction.py +48 -0
  167. ccai/agentkit/resilienceconfiguration.py +191 -0
  168. ccai/agentkit/resilienceerrors.py +103 -0
  169. ccai/agentkit/resiliencepipeline.py +201 -0
  170. ccai/agentkit/retryattempt.py +158 -0
  171. ccai/agentkit/retryexecutor.py +157 -0
  172. ccai/agentkit/retrypolicy.py +195 -0
  173. ccai/agentkit/retryresult.py +186 -0
  174. ccai/agentkit/selfhealingaction.py +42 -0
  175. ccai/agentkit/selfhealingpolicy.py +67 -0
  176. ccai/agentkit/selfhealingresult.py +130 -0
  177. ccai/agentkit/stepexecutionstatus.py +52 -0
  178. ccai/agentkit/stepresult.py +198 -0
  179. ccai/agentkit/steps/__init__.py +9 -0
  180. ccai/agentkit/steps/agentstep.py +247 -0
  181. ccai/agentkit/steps/approvalstep.py +276 -0
  182. ccai/agentkit/steps/llmstep.py +403 -0
  183. ccai/agentkit/steps/subworkflowstep.py +270 -0
  184. ccai/agentkit/steps/toolstep.py +265 -0
  185. ccai/agentkit/structuredlogentry.py +222 -0
  186. ccai/agentkit/structuredlogger.py +189 -0
  187. ccai/agentkit/subscription.py +141 -0
  188. ccai/agentkit/threadedagent.py +94 -0
  189. ccai/agentkit/tokenusage.py +136 -0
  190. ccai/agentkit/tool.py +203 -0
  191. ccai/agentkit/toolchain.py +268 -0
  192. ccai/agentkit/toolchainexecutor.py +134 -0
  193. ccai/agentkit/toolchainresult.py +166 -0
  194. ccai/agentkit/tooldescriptor.py +203 -0
  195. ccai/agentkit/toolerrors.py +160 -0
  196. ccai/agentkit/toolexecutor.py +168 -0
  197. ccai/agentkit/toolfactory.py +60 -0
  198. ccai/agentkit/toolregistry.py +184 -0
  199. ccai/agentkit/toolresult.py +142 -0
  200. ccai/agentkit/toolschema.py +197 -0
  201. ccai/agentkit/tracecontext.py +294 -0
  202. ccai/agentkit/traceevent.py +166 -0
  203. ccai/agentkit/traceexporter.py +305 -0
  204. ccai/agentkit/tracer.py +234 -0
  205. ccai/agentkit/tracespan.py +349 -0
  206. ccai/agentkit/transitionrecord.py +84 -0
  207. ccai/agentkit/transport.py +334 -0
  208. ccai/agentkit/transportconfiguration.py +436 -0
  209. ccai/agentkit/transporthealthcheck.py +36 -0
  210. ccai/agentkit/transportregistry.py +224 -0
  211. ccai/agentkit/transports/__init__.py +28 -0
  212. ccai/agentkit/transports/grpctransport.py +410 -0
  213. ccai/agentkit/transports/httptransport.py +423 -0
  214. ccai/agentkit/transports/messagequeuetransport.py +489 -0
  215. ccai/agentkit/transports/websockettransport.py +473 -0
  216. ccai/agentkit/workflowcheckpoint.py +208 -0
  217. ccai/agentkit/workflowconfiguration.py +295 -0
  218. ccai/agentkit/workflowcontext.py +249 -0
  219. ccai/agentkit/workflowdefinition.py +790 -0
  220. ccai/agentkit/workflowedge.py +128 -0
  221. ccai/agentkit/workflowerrors.py +295 -0
  222. ccai/agentkit/workflowexecutionstatus.py +48 -0
  223. ccai/agentkit/workflowexecutor.py +1121 -0
  224. ccai/agentkit/workflowregistry.py +185 -0
  225. ccai/agentkit/workflowresult.py +250 -0
  226. ccai/agentkit/workflowstep.py +195 -0
  227. codecraftai_agent_kit-1.3.0.dist-info/METADATA +99 -0
  228. codecraftai_agent_kit-1.3.0.dist-info/RECORD +230 -0
  229. codecraftai_agent_kit-1.3.0.dist-info/WHEEL +4 -0
  230. codecraftai_agent_kit-1.3.0.dist-info/licenses/LICENSE.md +204 -0
@@ -0,0 +1,1121 @@
1
+ """
2
+ Defines the WorkflowExecutor class responsible for executing a
3
+ WorkflowDefinition by traversing the DAG, evaluating edge
4
+ conditions, executing steps, managing parallel branches, and
5
+ producing a WorkflowResult.
6
+
7
+ The WorkflowExecutor coordinates with the ConditionEvaluator for
8
+ conditional branching, the CheckpointManager for fault-tolerant
9
+ execution with resumption, and uses concurrent.futures for
10
+ parallel branch execution.
11
+
12
+ Requirements: 4.1-4.13, 8.6-8.9, 9.6-9.7, 10.1-10.6,
13
+ 22.1-22.15, 23.21, 23.22
14
+
15
+ .. module:: ccai.agentkit.workflowexecutor
16
+ :platform: Darwin, Linux, Unix, Windows
17
+ :synopsis: DAG traversal and step execution engine.
18
+ """
19
+
20
+ import logging
21
+ import os
22
+ import time
23
+ import uuid
24
+
25
+ from collections import deque
26
+ from concurrent.futures import ThreadPoolExecutor, as_completed
27
+ from typing import List
28
+ from typing import Optional
29
+ from typing import Set
30
+ from typing import Tuple
31
+
32
+ from ccai.agentkit.checkpointmanager import CheckpointManager
33
+ from ccai.agentkit.conditionevaluator import ConditionEvaluator
34
+ from ccai.agentkit.stepexecutionstatus import StepExecutionStatus
35
+ from ccai.agentkit.stepresult import StepResult
36
+ from ccai.agentkit.workflowconfiguration import WorkflowConfiguration
37
+ from ccai.agentkit.workflowcontext import WorkflowContext
38
+ from ccai.agentkit.workflowdefinition import WorkflowDefinition
39
+ from ccai.agentkit.workflowedge import WorkflowEdge
40
+ from ccai.agentkit.workflowerrors import WorkflowCheckpointError
41
+ from ccai.agentkit.workflowerrors import WorkflowDefinitionError
42
+ from ccai.agentkit.workflowerrors import WorkflowExecutionError
43
+ from ccai.agentkit.workflowexecutionstatus import WorkflowExecutionStatus
44
+ from ccai.agentkit.workflowresult import WorkflowResult
45
+
46
+
47
+ # The key used to track a traversed edge: (source_step_id, target_step_id).
48
+ EdgeKey = Tuple[str, str]
49
+
50
+
51
+ class WorkflowExecutor:
52
+ """
53
+ Executes a WorkflowDefinition by traversing the DAG,
54
+ evaluating edge conditions, executing steps, managing
55
+ parallel branches, and producing a WorkflowResult.
56
+
57
+ The executor creates a WorkflowContext from the provided
58
+ inputs, computes a topological execution order from the
59
+ DAG, and executes each step in order. For unconditional
60
+ edges with parallel branches, branches are executed
61
+ concurrently using a ThreadPoolExecutor bounded by the
62
+ configured max_parallel_workers.
63
+
64
+ When a step completes, its outgoing edges decide which
65
+ successors are traversed:
66
+
67
+ * An edge without a condition is unconditional and is always
68
+ traversed.
69
+ * The conditional edges are evaluated by the
70
+ ConditionEvaluator in ascending priority order and only the
71
+ first edge whose condition is True is traversed. The
72
+ conditions after the first match are not evaluated.
73
+ * When no conditional edge matches, none of the conditional
74
+ targets is traversed from that step and the workflow
75
+ continues with the edges that were traversed. It is not an
76
+ error.
77
+ * A default (else) branch is declared as a conditional edge
78
+ with the condition ``"True"`` and the largest priority value,
79
+ so it is evaluated last and taken only when no other
80
+ condition matched.
81
+
82
+ A step runs once every step before it in topological order
83
+ has been decided and at least one of its incoming edges was
84
+ traversed, so a merge step after a conditional branch runs
85
+ when any branch reaches it. A step with incoming edges, none
86
+ of which was traversed, is recorded with a SKIPPED StepResult
87
+ and its outgoing edges are not traversed, so the skip
88
+ propagates down the untaken path.
89
+
90
+ Checkpoints are saved via the CheckpointManager at the
91
+ configured interval. Failed steps are retried according
92
+ to their RetryPolicy when configured.
93
+
94
+ :param configuration: An optional WorkflowConfiguration
95
+ for execution settings. Defaults to a
96
+ WorkflowConfiguration with default values.
97
+ :param checkpoint_manager: An optional CheckpointManager
98
+ for saving and loading checkpoints.
99
+ """
100
+
101
+ def __init__(self, configuration: Optional[WorkflowConfiguration] = None,
102
+ checkpoint_manager: Optional[CheckpointManager] = None) -> None:
103
+ self._configuration = configuration or WorkflowConfiguration()
104
+ self._checkpoint_manager = checkpoint_manager
105
+ self._condition_evaluator = ConditionEvaluator()
106
+ self._logger = logging.getLogger("ccai.agentkit.workflow.executor")
107
+ return
108
+
109
+ def execute(self, workflow: WorkflowDefinition, inputs: dict,
110
+ agent=None) -> WorkflowResult:
111
+ """
112
+ Executes a workflow from the start step.
113
+
114
+ Creates a WorkflowContext from the provided inputs,
115
+ generates a unique execution identifier, computes the
116
+ topological execution order from the DAG, and executes
117
+ each step in order. Conditional edges are evaluated in
118
+ ascending priority order and the first true edge is
119
+ traversed; steps on paths that are not traversed are
120
+ reported as SKIPPED. Parallel branches declared in the
121
+ workflow definition are executed concurrently.
122
+
123
+ :param workflow: The WorkflowDefinition to execute.
124
+ :param inputs: The initial input dictionary.
125
+ :param agent: The executing Agent instance.
126
+
127
+ :returns: A WorkflowResult with the execution outcome.
128
+
129
+ :raises WorkflowDefinitionError: When an edge condition
130
+ expression is invalid.
131
+ :raises WorkflowExecutionError: When an edge condition
132
+ references a step that has not been executed.
133
+ """
134
+ execution_id = str(uuid.uuid4())
135
+ context = WorkflowContext(inputs=inputs, agent=agent)
136
+ context.set_metadata("workflow_name", workflow.name)
137
+ context.set_metadata("execution_id", execution_id)
138
+
139
+ agent_id = getattr(agent, "identifier", None) if agent is not None else None
140
+
141
+ self._logger.info(
142
+ "Workflow execution begins: workflow='%s', "
143
+ "execution_id='%s', agent_id='%s'.",
144
+ workflow.name, execution_id, agent_id
145
+ )
146
+
147
+ start_time = time.monotonic()
148
+ step_results = []
149
+ completed_step_ids = set()
150
+ steps_since_checkpoint = 0
151
+
152
+ result = self._execute_steps(
153
+ workflow=workflow,
154
+ context=context,
155
+ execution_id=execution_id,
156
+ step_results=step_results,
157
+ completed_step_ids=completed_step_ids,
158
+ steps_since_checkpoint=steps_since_checkpoint,
159
+ start_time=start_time
160
+ )
161
+
162
+ return result
163
+
164
+ def resume(self, execution_id: str, workflow: WorkflowDefinition,
165
+ agent=None) -> WorkflowResult:
166
+ """
167
+ Resumes a workflow from the last checkpoint.
168
+
169
+ Loads the most recent checkpoint for the execution
170
+ identifier, restores the WorkflowContext from the
171
+ checkpoint state, skips completed steps, and continues
172
+ execution from the next step. The edges traversed from
173
+ the completed steps are re-derived by evaluating their
174
+ conditions against the restored context, so the resumed
175
+ execution follows the same conditional branches.
176
+
177
+ :param execution_id: The workflow execution identifier.
178
+ :param workflow: The WorkflowDefinition to resume.
179
+ :param agent: The executing Agent instance.
180
+
181
+ :returns: A WorkflowResult with the execution outcome.
182
+
183
+ :raises WorkflowCheckpointError: When no checkpoint is
184
+ found for the execution identifier.
185
+ """
186
+ if self._checkpoint_manager is None:
187
+ raise WorkflowCheckpointError(
188
+ execution_id=execution_id,
189
+ operation="load",
190
+ cause=ValueError("No checkpoint manager configured.")
191
+ )
192
+
193
+ checkpoint = self._checkpoint_manager.load_checkpoint(execution_id)
194
+
195
+ if checkpoint is None:
196
+ raise WorkflowCheckpointError(
197
+ execution_id=execution_id,
198
+ operation="load",
199
+ cause=ValueError(
200
+ "No checkpoint found for execution '{}'.".format(
201
+ execution_id
202
+ )
203
+ )
204
+ )
205
+
206
+ context = WorkflowContext.from_dict(
207
+ checkpoint.context_state, agent=agent
208
+ )
209
+ context.set_metadata("workflow_name", workflow.name)
210
+ context.set_metadata("execution_id", execution_id)
211
+
212
+ completed_step_ids = set(checkpoint.completed_step_ids)
213
+
214
+ self._logger.info(
215
+ "Workflow resumed: workflow='%s', execution_id='%s', "
216
+ "previously_completed_steps=%d.",
217
+ workflow.name, execution_id, len(completed_step_ids)
218
+ )
219
+
220
+ # Build StepResults for previously completed steps from
221
+ # the checkpoint context state.
222
+ step_results = []
223
+ for step_id in completed_step_ids:
224
+ step = workflow.get_step(step_id)
225
+ step_name = step.name if step is not None else step_id
226
+ output = context.get_step_output(step_id) or {}
227
+ prior_result = StepResult(
228
+ step_id=step_id,
229
+ step_name=step_name,
230
+ status=StepExecutionStatus.COMPLETED,
231
+ output=output
232
+ )
233
+ step_results.append(prior_result)
234
+
235
+ start_time = time.monotonic()
236
+ steps_since_checkpoint = 0
237
+
238
+ result = self._execute_steps(
239
+ workflow=workflow,
240
+ context=context,
241
+ execution_id=execution_id,
242
+ step_results=step_results,
243
+ completed_step_ids=completed_step_ids,
244
+ steps_since_checkpoint=steps_since_checkpoint,
245
+ start_time=start_time
246
+ )
247
+
248
+ return result
249
+
250
+ def _execute_steps(self, workflow: WorkflowDefinition,
251
+ context: WorkflowContext,
252
+ execution_id: str,
253
+ step_results: list,
254
+ completed_step_ids: set,
255
+ steps_since_checkpoint: int,
256
+ start_time: float) -> WorkflowResult:
257
+ """
258
+ Core execution loop that traverses the DAG in
259
+ topological order and executes each step.
260
+
261
+ :param workflow: The WorkflowDefinition being executed.
262
+ :param context: The WorkflowContext for this execution.
263
+ :param execution_id: The unique execution identifier.
264
+ :param step_results: The list of StepResult objects
265
+ accumulated so far.
266
+ :param completed_step_ids: The set of step identifiers
267
+ that have already completed.
268
+ :param steps_since_checkpoint: Counter of steps executed
269
+ since the last checkpoint.
270
+ :param start_time: The monotonic start time for duration
271
+ calculation.
272
+
273
+ :returns: A WorkflowResult with the execution outcome.
274
+
275
+ :raises WorkflowDefinitionError: When an edge condition
276
+ expression is invalid.
277
+ :raises WorkflowExecutionError: When an edge condition
278
+ references a step that has not been executed.
279
+ """
280
+ topo_order = self._compute_topological_order(workflow)
281
+
282
+ # Build a set of fork step IDs for parallel branch detection.
283
+ parallel_fork_map = {}
284
+ for branch in workflow.parallel_branches:
285
+ parallel_fork_map[branch.fork_step_id] = branch
286
+
287
+ # The keys of the edges that have been traversed so far and the
288
+ # identifiers of the steps that were skipped because none of
289
+ # their incoming edges was traversed.
290
+ traversed_edges: Set[EdgeKey] = set()
291
+ skipped_step_ids: Set[str] = set()
292
+
293
+ # When resuming, the steps completed before the checkpoint are not
294
+ # executed again. Re-derive the edges they traversed from the
295
+ # restored context, in the same topological order in which the
296
+ # conditions were originally evaluated.
297
+ for step_id in topo_order:
298
+ if step_id in completed_step_ids:
299
+ resumed_edges = self._select_traversed_edges(
300
+ workflow, step_id, context
301
+ )
302
+ traversed_edges.update(resumed_edges)
303
+
304
+ for step_id in topo_order:
305
+ if step_id in completed_step_ids:
306
+ continue
307
+
308
+ if step_id in skipped_step_ids:
309
+ continue
310
+
311
+ step = workflow.get_step(step_id)
312
+
313
+ # Every step before this one in topological order has been
314
+ # decided, so the step runs when one of its incoming edges was
315
+ # traversed and is skipped otherwise.
316
+ should_execute = self._should_execute_step(
317
+ step_id, workflow, traversed_edges
318
+ )
319
+
320
+ if should_execute is not True:
321
+ skipped_result = self._build_skipped_result(workflow, step)
322
+ step_results.append(skipped_result)
323
+ skipped_step_ids.add(step_id)
324
+ continue
325
+
326
+ # Check if this is a fork step for a parallel branch.
327
+ if step_id in parallel_fork_map:
328
+ branch = parallel_fork_map[step_id]
329
+
330
+ # Execute the fork step itself first.
331
+ fork_result = self._execute_single_step(
332
+ workflow, step, context, execution_id
333
+ )
334
+ step_results.append(fork_result)
335
+ completed_step_ids.add(step_id)
336
+ steps_since_checkpoint += 1
337
+
338
+ if not fork_result.is_success:
339
+ return self._build_failed_result(
340
+ workflow, step_results, start_time,
341
+ step_id, fork_result.error, execution_id
342
+ )
343
+
344
+ # Decide which branch starts are traversed from the fork.
345
+ fork_edges = self._select_traversed_edges(
346
+ workflow, step_id, context
347
+ )
348
+ traversed_edges.update(fork_edges)
349
+
350
+ # Execute parallel branches. _execute_parallel_branches appends
351
+ # each branch step result to step_results, so the count of newly
352
+ # added branch steps is the growth in the list length.
353
+ step_count_before_branches = len(step_results)
354
+
355
+ branch_result = self._execute_parallel_branches(
356
+ workflow=workflow,
357
+ branch=branch,
358
+ context=context,
359
+ execution_id=execution_id,
360
+ step_results=step_results,
361
+ completed_step_ids=completed_step_ids,
362
+ traversed_edges=traversed_edges,
363
+ skipped_step_ids=skipped_step_ids,
364
+ topo_order=topo_order
365
+ )
366
+
367
+ if not branch_result:
368
+ return self._build_failed_result(
369
+ workflow, step_results, start_time,
370
+ step_id, "Parallel branch execution failed.",
371
+ execution_id
372
+ )
373
+
374
+ branch_steps_added = len(step_results) - step_count_before_branches
375
+ steps_since_checkpoint += branch_steps_added
376
+
377
+ # Save checkpoint if interval reached.
378
+ steps_since_checkpoint = self._maybe_save_checkpoint(
379
+ workflow, context, execution_id,
380
+ completed_step_ids, step_id,
381
+ steps_since_checkpoint
382
+ )
383
+
384
+ continue
385
+
386
+ # Execute the step.
387
+ step_result = self._execute_single_step(
388
+ workflow, step, context, execution_id
389
+ )
390
+ step_results.append(step_result)
391
+ completed_step_ids.add(step_id)
392
+ steps_since_checkpoint += 1
393
+
394
+ if not step_result.is_success:
395
+ return self._build_failed_result(
396
+ workflow, step_results, start_time,
397
+ step_id, step_result.error, execution_id
398
+ )
399
+
400
+ # Save checkpoint if interval reached.
401
+ steps_since_checkpoint = self._maybe_save_checkpoint(
402
+ workflow, context, execution_id,
403
+ completed_step_ids, step_id,
404
+ steps_since_checkpoint
405
+ )
406
+
407
+ # Determine which outgoing edges are traversed from this step.
408
+ selected_edges = self._select_traversed_edges(
409
+ workflow, step_id, context
410
+ )
411
+ traversed_edges.update(selected_edges)
412
+
413
+ # Build successful result.
414
+ duration = time.monotonic() - start_time
415
+ terminal_steps = workflow.get_terminal_steps()
416
+ final_output = {}
417
+ for tid in terminal_steps:
418
+ output = context.get_step_output(tid)
419
+ if output is not None:
420
+ final_output.update(output)
421
+
422
+ self._logger.info(
423
+ "Workflow execution completes: workflow='%s', "
424
+ "execution_id='%s', status='COMPLETED', "
425
+ "duration=%.3fs.",
426
+ workflow.name, execution_id, duration
427
+ )
428
+
429
+ result = WorkflowResult(
430
+ workflow_name=workflow.name,
431
+ status=WorkflowExecutionStatus.COMPLETED,
432
+ step_results=step_results,
433
+ final_output=final_output,
434
+ duration=duration
435
+ )
436
+ return result
437
+
438
+ def _should_execute_step(self, step_id: str,
439
+ workflow: WorkflowDefinition,
440
+ traversed_edges: Set[EdgeKey]) -> bool:
441
+ """
442
+ Determines whether a step should be executed once every
443
+ step before it in topological order has been decided.
444
+
445
+ A step without incoming edges (the start step) is always
446
+ executed. Any other step is executed when at least one of
447
+ its incoming edges was traversed. A step whose incoming
448
+ edges were all left untraversed, because their source
449
+ steps were skipped or their conditions did not match, is
450
+ not executed.
451
+
452
+ :param step_id: The step identifier to check.
453
+ :param workflow: The WorkflowDefinition.
454
+ :param traversed_edges: The keys of the edges traversed so
455
+ far, as (source_step_id, target_step_id) tuples.
456
+
457
+ :returns: True if the step should be executed, False if it
458
+ should be skipped.
459
+ """
460
+ incoming_edges = workflow.get_incoming_edges(step_id)
461
+
462
+ if len(incoming_edges) == 0:
463
+ return True
464
+
465
+ for edge in incoming_edges:
466
+ edge_key = (edge.source_step_id, edge.target_step_id)
467
+ if edge_key in traversed_edges:
468
+ return True
469
+
470
+ return False
471
+
472
+ def _select_traversed_edges(self, workflow: WorkflowDefinition,
473
+ step_id: str,
474
+ context: WorkflowContext) -> List[EdgeKey]:
475
+ """
476
+ Decides which outgoing edges of a completed step are
477
+ traversed.
478
+
479
+ Unconditional edges are always traversed. The conditional
480
+ edges are evaluated in ascending priority order and only
481
+ the first edge whose condition is True is traversed; the
482
+ conditions after the first match are not evaluated. When
483
+ no conditional edge matches, none of the conditional
484
+ targets is traversed from this step.
485
+
486
+ :param workflow: The WorkflowDefinition being executed.
487
+ :param step_id: The identifier of the completed step.
488
+ :param context: The WorkflowContext the conditions are
489
+ evaluated against.
490
+
491
+ :returns: The keys of the traversed edges, as
492
+ (source_step_id, target_step_id) tuples.
493
+
494
+ :raises WorkflowDefinitionError: When an edge condition
495
+ expression is invalid.
496
+ :raises WorkflowExecutionError: When an edge condition
497
+ references a step that has not been executed.
498
+ """
499
+ # get_outgoing_edges returns the edges sorted by ascending priority.
500
+ outgoing_edges = workflow.get_outgoing_edges(step_id)
501
+
502
+ selected_edges = []
503
+ matched_edge = None
504
+ conditional_edge_count = 0
505
+
506
+ for edge in outgoing_edges:
507
+ edge_key = (edge.source_step_id, edge.target_step_id)
508
+
509
+ if edge.condition is None:
510
+ selected_edges.append(edge_key)
511
+ continue
512
+
513
+ conditional_edge_count += 1
514
+
515
+ if matched_edge is not None:
516
+ self._logger.debug(
517
+ "Edge condition not evaluated: workflow='%s', "
518
+ "source_step_id='%s', target_step_id='%s', "
519
+ "priority=%d, reason='edge to %s with priority %d "
520
+ "already matched'.",
521
+ workflow.name, edge.source_step_id,
522
+ edge.target_step_id, edge.priority,
523
+ matched_edge.target_step_id, matched_edge.priority
524
+ )
525
+ continue
526
+
527
+ condition_met = self._evaluate_edge_condition(
528
+ workflow, edge, context
529
+ )
530
+
531
+ if condition_met is True:
532
+ matched_edge = edge
533
+ selected_edges.append(edge_key)
534
+
535
+ if conditional_edge_count > 0 and matched_edge is None:
536
+ self._logger.info(
537
+ "No conditional edge matched: workflow='%s', "
538
+ "step_id='%s', conditional_edge_count=%d.",
539
+ workflow.name, step_id, conditional_edge_count
540
+ )
541
+
542
+ return selected_edges
543
+
544
+ def _evaluate_edge_condition(self, workflow: WorkflowDefinition,
545
+ edge: WorkflowEdge,
546
+ context: WorkflowContext) -> bool:
547
+ """
548
+ Evaluates the condition of a conditional edge against the
549
+ workflow context using the ConditionEvaluator.
550
+
551
+ Errors raised by the ConditionEvaluator are re-raised with
552
+ the workflow name and the edge that carries the condition,
553
+ which the evaluator itself does not know.
554
+
555
+ :param workflow: The WorkflowDefinition being executed.
556
+ :param edge: The conditional WorkflowEdge to evaluate.
557
+ :param context: The WorkflowContext to evaluate against.
558
+
559
+ :returns: True when the condition is satisfied, False
560
+ otherwise.
561
+
562
+ :raises WorkflowDefinitionError: When the condition
563
+ expression is invalid.
564
+ :raises WorkflowExecutionError: When the condition
565
+ references a step that has not been executed.
566
+ """
567
+ try:
568
+ condition_met = self._condition_evaluator.evaluate(
569
+ edge.condition, context
570
+ )
571
+ except WorkflowDefinitionError as def_err:
572
+ errmsg_lines = [
573
+ "The condition on edge '{}' -> '{}' is invalid.".format(
574
+ edge.source_step_id, edge.target_step_id
575
+ ),
576
+ " CONDITION: {}".format(edge.condition),
577
+ " PRIORITY: {}".format(edge.priority),
578
+ " DETAIL: {}".format(def_err.detail),
579
+ ]
580
+ detail = os.linesep.join(errmsg_lines)
581
+ raise WorkflowDefinitionError(
582
+ workflow_name=workflow.name, detail=detail
583
+ ) from def_err
584
+ except WorkflowExecutionError as exec_err:
585
+ raise WorkflowExecutionError(
586
+ workflow_name=workflow.name,
587
+ step_id=edge.source_step_id,
588
+ cause=exec_err
589
+ ) from exec_err
590
+
591
+ self._logger.info(
592
+ "Edge condition evaluated: workflow='%s', "
593
+ "source_step_id='%s', target_step_id='%s', priority=%d, "
594
+ "condition='%s', result=%s.",
595
+ workflow.name, edge.source_step_id, edge.target_step_id,
596
+ edge.priority, edge.condition, condition_met
597
+ )
598
+
599
+ return condition_met
600
+
601
+ def _build_skipped_result(self, workflow: WorkflowDefinition,
602
+ step) -> StepResult:
603
+ """
604
+ Builds the SKIPPED StepResult for a step that is not
605
+ executed because none of its incoming edges was traversed.
606
+
607
+ :param workflow: The WorkflowDefinition being executed.
608
+ :param step: The WorkflowStep being skipped.
609
+
610
+ :returns: A StepResult with SKIPPED status.
611
+ """
612
+ self._logger.info(
613
+ "Step skipped: workflow='%s', step_id='%s', "
614
+ "step_name='%s', reason='no incoming edge was traversed'.",
615
+ workflow.name, step.step_id, step.name
616
+ )
617
+
618
+ skipped_result = StepResult(
619
+ step_id=step.step_id,
620
+ step_name=step.name,
621
+ status=StepExecutionStatus.SKIPPED
622
+ )
623
+ return skipped_result
624
+
625
+ def _execute_single_step(self, workflow: WorkflowDefinition,
626
+ step, context: WorkflowContext,
627
+ execution_id: str) -> StepResult:
628
+ """
629
+ Executes a single workflow step with retry support.
630
+
631
+ Logs step execution start and completion. If the step
632
+ has a retry policy configured, retries the step on
633
+ failure according to the policy. Stores the step output
634
+ in the context on success.
635
+
636
+ :param workflow: The WorkflowDefinition being executed.
637
+ :param step: The WorkflowStep to execute.
638
+ :param context: The WorkflowContext.
639
+ :param execution_id: The execution identifier.
640
+
641
+ :returns: A StepResult with the execution outcome.
642
+ """
643
+ self._logger.info(
644
+ "Step execution begins: workflow='%s', step_id='%s', "
645
+ "step_name='%s'.",
646
+ workflow.name, step.step_id, step.name
647
+ )
648
+
649
+ step_start = time.monotonic()
650
+ retry_policy = step.retry_policy
651
+ max_attempts = 1
652
+
653
+ if retry_policy is not None:
654
+ max_attempts = 1 + retry_policy.max_retries
655
+
656
+ last_result = None
657
+
658
+ for attempt in range(max_attempts):
659
+ try:
660
+ result = step.execute(context)
661
+ except Exception as ex:
662
+ step_duration = time.monotonic() - step_start
663
+ self._logger.warning(
664
+ "Step execution fails: workflow='%s', "
665
+ "step_id='%s', error='%s'.",
666
+ workflow.name, step.step_id, str(ex)
667
+ )
668
+ result = StepResult(
669
+ step_id=step.step_id,
670
+ step_name=step.name,
671
+ status=StepExecutionStatus.FAILED,
672
+ duration=step_duration,
673
+ error=str(ex)
674
+ )
675
+
676
+ last_result = result
677
+
678
+ if result.is_success:
679
+ break
680
+
681
+ # Check if we should retry.
682
+ if retry_policy is not None and attempt < max_attempts - 1:
683
+ # Create a synthetic exception for the retry policy
684
+ # check.
685
+ synthetic_error = Exception(result.error or "Step failed")
686
+ if retry_policy.should_retry(synthetic_error, attempt):
687
+ delay = retry_policy.get_delay(attempt)
688
+ time.sleep(delay)
689
+ step_start = time.monotonic()
690
+ continue
691
+
692
+ break
693
+
694
+ step_duration = time.monotonic() - step_start
695
+ if last_result.is_success:
696
+ # Rebuild result with accurate duration.
697
+ last_result = StepResult(
698
+ step_id=step.step_id,
699
+ step_name=step.name,
700
+ status=last_result.status,
701
+ output=last_result.output,
702
+ duration=step_duration,
703
+ error=last_result.error
704
+ )
705
+
706
+ context.set_step_output(step.step_id, last_result.output)
707
+
708
+ self._logger.info(
709
+ "Step execution completes: workflow='%s', "
710
+ "step_id='%s', status='%s', duration=%.3fs.",
711
+ workflow.name, step.step_id,
712
+ last_result.status.value, step_duration
713
+ )
714
+ else:
715
+ self._logger.warning(
716
+ "Step execution fails: workflow='%s', "
717
+ "step_id='%s', error='%s'.",
718
+ workflow.name, step.step_id,
719
+ last_result.error
720
+ )
721
+
722
+ return last_result
723
+
724
+ def _execute_parallel_branches(self, workflow: WorkflowDefinition,
725
+ branch, context: WorkflowContext,
726
+ execution_id: str,
727
+ step_results: list,
728
+ completed_step_ids: set,
729
+ traversed_edges: Set[EdgeKey],
730
+ skipped_step_ids: Set[str],
731
+ topo_order: List[str]) -> bool:
732
+ """
733
+ Executes parallel branches concurrently from a fork step
734
+ to a join step.
735
+
736
+ Identifies all branch paths from the fork step, executes
737
+ them concurrently using a ThreadPoolExecutor, and merges
738
+ results into the context. Each branch honours the edge
739
+ conditions in the same way as the main execution loop, so
740
+ a branch whose start edge from the fork was not traversed
741
+ is reported as SKIPPED. If any branch fails, remaining
742
+ branches are cancelled.
743
+
744
+ :param workflow: The WorkflowDefinition being executed.
745
+ :param branch: The ParallelBranch declaration.
746
+ :param context: The WorkflowContext.
747
+ :param execution_id: The execution identifier.
748
+ :param step_results: The accumulated step results list.
749
+ :param completed_step_ids: The set of completed step IDs.
750
+ :param traversed_edges: The keys of the edges traversed so
751
+ far, including the edges traversed from the fork step.
752
+ The edges traversed inside the branches are added to it.
753
+ :param skipped_step_ids: The set of skipped step IDs. The
754
+ branch steps that are skipped are added to it.
755
+ :param topo_order: The topological order of the workflow
756
+ steps, used to order the steps inside each branch.
757
+
758
+ :returns: True if all branches completed successfully,
759
+ False if any branch failed.
760
+
761
+ :raises WorkflowDefinitionError: When an edge condition
762
+ inside a branch is invalid.
763
+ :raises WorkflowExecutionError: When an edge condition
764
+ inside a branch references a step that has not been
765
+ executed.
766
+ """
767
+ fork_id = branch.fork_step_id
768
+ join_id = branch.join_step_id
769
+
770
+ # Find all immediate successors of the fork step as branch
771
+ # starting points.
772
+ outgoing_edges = workflow.get_outgoing_edges(fork_id)
773
+ branch_starts = [edge.target_step_id for edge in outgoing_edges]
774
+
775
+ self._logger.info(
776
+ "Parallel branches forked: workflow='%s', "
777
+ "fork_step_id='%s', branch_count=%d.",
778
+ workflow.name, fork_id, len(branch_starts)
779
+ )
780
+
781
+ max_workers = self._configuration.max_parallel_workers
782
+
783
+ topo_index = {}
784
+ for index, topo_step_id in enumerate(topo_order):
785
+ topo_index[topo_step_id] = index
786
+
787
+ # Collect steps for each branch path (from branch start to
788
+ # just before the join step), in topological order so each step
789
+ # is decided after the steps it depends on.
790
+ branch_step_lists = []
791
+ for branch_start_id in branch_starts:
792
+ branch_steps = self._collect_branch_steps(
793
+ workflow, branch_start_id, join_id
794
+ )
795
+ ordered_branch_steps = sorted(
796
+ branch_steps, key=topo_index.get
797
+ )
798
+ branch_step_lists.append(ordered_branch_steps)
799
+
800
+ # Each branch starts from an immutable snapshot of the edges traversed
801
+ # so far, because the main thread merges the edges traversed by the
802
+ # branches that finish into traversed_edges while others still run.
803
+ traversed_snapshot = frozenset(traversed_edges)
804
+
805
+ all_success = True
806
+
807
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
808
+ futures = {}
809
+
810
+ for branch_steps in branch_step_lists:
811
+ future = executor.submit(
812
+ self._execute_branch,
813
+ workflow, branch_steps, context, execution_id,
814
+ traversed_snapshot
815
+ )
816
+ futures[future] = branch_steps
817
+
818
+ for future in as_completed(futures):
819
+ try:
820
+ branch_results, branch_traversed_edges = future.result()
821
+ except (WorkflowDefinitionError, WorkflowExecutionError):
822
+ # An edge condition inside the branch could not be
823
+ # evaluated. That is a problem with the workflow
824
+ # definition, not a step failure, so let it propagate as
825
+ # it does from the main execution loop.
826
+ for other_future in futures:
827
+ if other_future is not future:
828
+ other_future.cancel()
829
+ raise
830
+ except Exception as ex:
831
+ all_success = False
832
+ self._logger.warning(
833
+ "Parallel branch failed: workflow='%s', "
834
+ "error='%s'.",
835
+ workflow.name, str(ex)
836
+ )
837
+ # Cancel remaining futures.
838
+ for other_future in futures:
839
+ if other_future is not future:
840
+ other_future.cancel()
841
+ break
842
+
843
+ traversed_edges.update(branch_traversed_edges)
844
+
845
+ for br in branch_results:
846
+ step_results.append(br)
847
+
848
+ if br.status == StepExecutionStatus.SKIPPED:
849
+ skipped_step_ids.add(br.step_id)
850
+ continue
851
+
852
+ completed_step_ids.add(br.step_id)
853
+
854
+ if not br.is_success:
855
+ all_success = False
856
+ # Cancel remaining futures.
857
+ for other_future in futures:
858
+ if other_future is not future:
859
+ other_future.cancel()
860
+ break
861
+
862
+ if not all_success:
863
+ break
864
+
865
+ if all_success:
866
+ self._logger.info(
867
+ "Parallel branches joined: workflow='%s', "
868
+ "join_step_id='%s', completed_branch_count=%d.",
869
+ workflow.name, join_id, len(branch_starts)
870
+ )
871
+
872
+ return all_success
873
+
874
+ def _collect_branch_steps(self, workflow: WorkflowDefinition,
875
+ start_id: str, join_id: str) -> list:
876
+ """
877
+ Collects the ordered list of step IDs in a branch path
878
+ from start_id up to (but not including) join_id.
879
+
880
+ Uses BFS to traverse the branch path.
881
+
882
+ :param workflow: The WorkflowDefinition.
883
+ :param start_id: The starting step ID of the branch.
884
+ :param join_id: The join step ID (not included).
885
+
886
+ :returns: An ordered list of step IDs in the branch.
887
+ """
888
+ steps = []
889
+ queue = deque()
890
+ queue.append(start_id)
891
+ visited = set()
892
+
893
+ while len(queue) > 0:
894
+ current = queue.popleft()
895
+
896
+ if current == join_id:
897
+ continue
898
+
899
+ if current in visited:
900
+ continue
901
+
902
+ visited.add(current)
903
+ steps.append(current)
904
+
905
+ outgoing = workflow.get_outgoing_edges(current)
906
+ for edge in outgoing:
907
+ if edge.target_step_id not in visited:
908
+ queue.append(edge.target_step_id)
909
+
910
+ return steps
911
+
912
+ def _execute_branch(self, workflow: WorkflowDefinition,
913
+ branch_steps: list,
914
+ context: WorkflowContext,
915
+ execution_id: str,
916
+ traversed_snapshot: frozenset) -> Tuple[list, Set[EdgeKey]]:
917
+ """
918
+ Executes a sequence of steps in a single branch.
919
+
920
+ Each step is executed when one of its incoming edges was
921
+ traversed and is reported as SKIPPED otherwise. After a
922
+ step completes, its outgoing edges are selected in the same
923
+ way as in the main execution loop.
924
+
925
+ :param workflow: The WorkflowDefinition.
926
+ :param branch_steps: The list of step IDs to execute, in
927
+ topological order.
928
+ :param context: The WorkflowContext (shared across
929
+ branches).
930
+ :param execution_id: The execution identifier.
931
+ :param traversed_snapshot: The keys of the edges traversed
932
+ before the branches were started.
933
+
934
+ :returns: A tuple of the list of StepResult objects for the
935
+ branch and the set of edge keys traversed so far,
936
+ including the edges traversed inside this branch.
937
+
938
+ :raises WorkflowDefinitionError: When an edge condition
939
+ inside the branch is invalid.
940
+ :raises WorkflowExecutionError: When an edge condition
941
+ inside the branch references a step that has not been
942
+ executed.
943
+ """
944
+ results = []
945
+ branch_traversed_edges = set(traversed_snapshot)
946
+
947
+ for step_id in branch_steps:
948
+ step = workflow.get_step(step_id)
949
+
950
+ should_execute = self._should_execute_step(
951
+ step_id, workflow, branch_traversed_edges
952
+ )
953
+
954
+ if should_execute is not True:
955
+ skipped_result = self._build_skipped_result(workflow, step)
956
+ results.append(skipped_result)
957
+ continue
958
+
959
+ result = self._execute_single_step(
960
+ workflow, step, context, execution_id
961
+ )
962
+ results.append(result)
963
+
964
+ if not result.is_success:
965
+ break
966
+
967
+ selected_edges = self._select_traversed_edges(
968
+ workflow, step_id, context
969
+ )
970
+ branch_traversed_edges.update(selected_edges)
971
+
972
+ return results, branch_traversed_edges
973
+
974
+ def _compute_topological_order(self, workflow: WorkflowDefinition) -> list:
975
+ """
976
+ Computes a topological ordering of the workflow steps
977
+ using Kahn's algorithm (BFS-based).
978
+
979
+ The ordering ensures that for every edge (A -> B), step
980
+ A appears before step B in the result.
981
+
982
+ :param workflow: The WorkflowDefinition to compute the
983
+ order for.
984
+
985
+ :returns: A list of step identifiers in topological
986
+ order.
987
+ """
988
+ # Build adjacency list and in-degree map.
989
+ in_degree = {}
990
+ adjacency = {}
991
+
992
+ for step_id in workflow.steps:
993
+ in_degree[step_id] = 0
994
+ adjacency[step_id] = []
995
+
996
+ for edge in workflow.edges:
997
+ adjacency[edge.source_step_id].append(edge.target_step_id)
998
+ in_degree[edge.target_step_id] += 1
999
+
1000
+ # Initialize queue with all steps that have in-degree 0.
1001
+ queue = deque()
1002
+ for step_id in workflow.steps:
1003
+ if in_degree[step_id] == 0:
1004
+ queue.append(step_id)
1005
+
1006
+ topo_order = []
1007
+
1008
+ while len(queue) > 0:
1009
+ current = queue.popleft()
1010
+ topo_order.append(current)
1011
+
1012
+ for neighbor in adjacency[current]:
1013
+ in_degree[neighbor] -= 1
1014
+ if in_degree[neighbor] == 0:
1015
+ queue.append(neighbor)
1016
+
1017
+ return topo_order
1018
+
1019
+ def _maybe_save_checkpoint(self, workflow: WorkflowDefinition,
1020
+ context: WorkflowContext,
1021
+ execution_id: str,
1022
+ completed_step_ids: set,
1023
+ current_step_id: str,
1024
+ steps_since_checkpoint: int) -> int:
1025
+ """
1026
+ Saves a checkpoint if the checkpoint interval has been
1027
+ reached and a checkpoint manager is configured.
1028
+
1029
+ :param workflow: The WorkflowDefinition.
1030
+ :param context: The WorkflowContext.
1031
+ :param execution_id: The execution identifier.
1032
+ :param completed_step_ids: The set of completed step IDs.
1033
+ :param current_step_id: The current step ID.
1034
+ :param steps_since_checkpoint: Steps executed since last
1035
+ checkpoint.
1036
+
1037
+ :returns: The updated steps_since_checkpoint counter
1038
+ (reset to 0 after saving).
1039
+ """
1040
+ if self._checkpoint_manager is None:
1041
+ return steps_since_checkpoint
1042
+
1043
+ checkpoint_interval = self._configuration.checkpoint_interval
1044
+
1045
+ if steps_since_checkpoint >= checkpoint_interval:
1046
+ self._checkpoint_manager.save_checkpoint(
1047
+ execution_id=execution_id,
1048
+ context=context,
1049
+ completed_step_ids=completed_step_ids,
1050
+ current_step_id=current_step_id
1051
+ )
1052
+
1053
+ self._logger.info(
1054
+ "Checkpoint saved: workflow='%s', "
1055
+ "execution_id='%s', completed_step_count=%d.",
1056
+ workflow.name, execution_id,
1057
+ len(completed_step_ids)
1058
+ )
1059
+
1060
+ return 0
1061
+
1062
+ return steps_since_checkpoint
1063
+
1064
+ def _build_failed_result(self, workflow: WorkflowDefinition,
1065
+ step_results: list,
1066
+ start_time: float,
1067
+ failed_step_id: str,
1068
+ error: str,
1069
+ execution_id: str) -> WorkflowResult:
1070
+ """
1071
+ Builds a WorkflowResult with FAILED status.
1072
+
1073
+ :param workflow: The WorkflowDefinition.
1074
+ :param step_results: The accumulated step results.
1075
+ :param start_time: The monotonic start time.
1076
+ :param failed_step_id: The ID of the failed step.
1077
+ :param error: The error message.
1078
+ :param execution_id: The execution identifier.
1079
+
1080
+ :returns: A WorkflowResult with FAILED status.
1081
+ """
1082
+ duration = time.monotonic() - start_time
1083
+
1084
+ self._logger.warning(
1085
+ "Workflow execution fails: workflow='%s', "
1086
+ "execution_id='%s', failed_step_id='%s', "
1087
+ "error='%s'.",
1088
+ workflow.name, execution_id, failed_step_id, error
1089
+ )
1090
+
1091
+ result = WorkflowResult(
1092
+ workflow_name=workflow.name,
1093
+ status=WorkflowExecutionStatus.FAILED,
1094
+ step_results=step_results,
1095
+ duration=duration,
1096
+ error=error
1097
+ )
1098
+ return result
1099
+
1100
+ def __repr__(self) -> str:
1101
+ """
1102
+ Returns a detailed string representation including the
1103
+ class name and the configuration.
1104
+
1105
+ :returns: A repr string for debugging.
1106
+ """
1107
+ repr_str = "{}(configuration={!r})".format(
1108
+ self.__class__.__name__, self._configuration
1109
+ )
1110
+ return repr_str
1111
+
1112
+ def __str__(self) -> str:
1113
+ """
1114
+ Returns a human-readable summary including the
1115
+ configuration details.
1116
+
1117
+ :returns: A human-readable string describing the
1118
+ executor.
1119
+ """
1120
+ str_val = "WorkflowExecutor: {}".format(self._configuration)
1121
+ return str_val