flyte 2.0.0b32__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.

Potentially problematic release.


This version of flyte might be problematic. Click here for more details.

Files changed (204) hide show
  1. flyte/__init__.py +108 -0
  2. flyte/_bin/__init__.py +0 -0
  3. flyte/_bin/debug.py +38 -0
  4. flyte/_bin/runtime.py +195 -0
  5. flyte/_bin/serve.py +178 -0
  6. flyte/_build.py +26 -0
  7. flyte/_cache/__init__.py +12 -0
  8. flyte/_cache/cache.py +147 -0
  9. flyte/_cache/defaults.py +9 -0
  10. flyte/_cache/local_cache.py +216 -0
  11. flyte/_cache/policy_function_body.py +42 -0
  12. flyte/_code_bundle/__init__.py +8 -0
  13. flyte/_code_bundle/_ignore.py +121 -0
  14. flyte/_code_bundle/_packaging.py +218 -0
  15. flyte/_code_bundle/_utils.py +347 -0
  16. flyte/_code_bundle/bundle.py +266 -0
  17. flyte/_constants.py +1 -0
  18. flyte/_context.py +155 -0
  19. flyte/_custom_context.py +73 -0
  20. flyte/_debug/__init__.py +0 -0
  21. flyte/_debug/constants.py +38 -0
  22. flyte/_debug/utils.py +17 -0
  23. flyte/_debug/vscode.py +307 -0
  24. flyte/_deploy.py +408 -0
  25. flyte/_deployer.py +109 -0
  26. flyte/_doc.py +29 -0
  27. flyte/_docstring.py +32 -0
  28. flyte/_environment.py +122 -0
  29. flyte/_excepthook.py +37 -0
  30. flyte/_group.py +32 -0
  31. flyte/_hash.py +8 -0
  32. flyte/_image.py +1055 -0
  33. flyte/_initialize.py +628 -0
  34. flyte/_interface.py +119 -0
  35. flyte/_internal/__init__.py +3 -0
  36. flyte/_internal/controllers/__init__.py +129 -0
  37. flyte/_internal/controllers/_local_controller.py +239 -0
  38. flyte/_internal/controllers/_trace.py +48 -0
  39. flyte/_internal/controllers/remote/__init__.py +58 -0
  40. flyte/_internal/controllers/remote/_action.py +211 -0
  41. flyte/_internal/controllers/remote/_client.py +47 -0
  42. flyte/_internal/controllers/remote/_controller.py +583 -0
  43. flyte/_internal/controllers/remote/_core.py +465 -0
  44. flyte/_internal/controllers/remote/_informer.py +381 -0
  45. flyte/_internal/controllers/remote/_service_protocol.py +50 -0
  46. flyte/_internal/imagebuild/__init__.py +3 -0
  47. flyte/_internal/imagebuild/docker_builder.py +706 -0
  48. flyte/_internal/imagebuild/image_builder.py +277 -0
  49. flyte/_internal/imagebuild/remote_builder.py +386 -0
  50. flyte/_internal/imagebuild/utils.py +78 -0
  51. flyte/_internal/resolvers/__init__.py +0 -0
  52. flyte/_internal/resolvers/_task_module.py +21 -0
  53. flyte/_internal/resolvers/common.py +31 -0
  54. flyte/_internal/resolvers/default.py +28 -0
  55. flyte/_internal/runtime/__init__.py +0 -0
  56. flyte/_internal/runtime/convert.py +486 -0
  57. flyte/_internal/runtime/entrypoints.py +204 -0
  58. flyte/_internal/runtime/io.py +188 -0
  59. flyte/_internal/runtime/resources_serde.py +152 -0
  60. flyte/_internal/runtime/reuse.py +125 -0
  61. flyte/_internal/runtime/rusty.py +193 -0
  62. flyte/_internal/runtime/task_serde.py +362 -0
  63. flyte/_internal/runtime/taskrunner.py +209 -0
  64. flyte/_internal/runtime/trigger_serde.py +160 -0
  65. flyte/_internal/runtime/types_serde.py +54 -0
  66. flyte/_keyring/__init__.py +0 -0
  67. flyte/_keyring/file.py +115 -0
  68. flyte/_logging.py +300 -0
  69. flyte/_map.py +312 -0
  70. flyte/_module.py +72 -0
  71. flyte/_pod.py +30 -0
  72. flyte/_resources.py +473 -0
  73. flyte/_retry.py +32 -0
  74. flyte/_reusable_environment.py +102 -0
  75. flyte/_run.py +724 -0
  76. flyte/_secret.py +96 -0
  77. flyte/_task.py +550 -0
  78. flyte/_task_environment.py +316 -0
  79. flyte/_task_plugins.py +47 -0
  80. flyte/_timeout.py +47 -0
  81. flyte/_tools.py +27 -0
  82. flyte/_trace.py +119 -0
  83. flyte/_trigger.py +1000 -0
  84. flyte/_utils/__init__.py +30 -0
  85. flyte/_utils/asyn.py +121 -0
  86. flyte/_utils/async_cache.py +139 -0
  87. flyte/_utils/coro_management.py +27 -0
  88. flyte/_utils/docker_credentials.py +173 -0
  89. flyte/_utils/file_handling.py +72 -0
  90. flyte/_utils/helpers.py +134 -0
  91. flyte/_utils/lazy_module.py +54 -0
  92. flyte/_utils/module_loader.py +104 -0
  93. flyte/_utils/org_discovery.py +57 -0
  94. flyte/_utils/uv_script_parser.py +49 -0
  95. flyte/_version.py +34 -0
  96. flyte/app/__init__.py +22 -0
  97. flyte/app/_app_environment.py +157 -0
  98. flyte/app/_deploy.py +125 -0
  99. flyte/app/_input.py +160 -0
  100. flyte/app/_runtime/__init__.py +3 -0
  101. flyte/app/_runtime/app_serde.py +347 -0
  102. flyte/app/_types.py +101 -0
  103. flyte/app/extras/__init__.py +3 -0
  104. flyte/app/extras/_fastapi.py +151 -0
  105. flyte/cli/__init__.py +12 -0
  106. flyte/cli/_abort.py +28 -0
  107. flyte/cli/_build.py +114 -0
  108. flyte/cli/_common.py +468 -0
  109. flyte/cli/_create.py +371 -0
  110. flyte/cli/_delete.py +45 -0
  111. flyte/cli/_deploy.py +293 -0
  112. flyte/cli/_gen.py +176 -0
  113. flyte/cli/_get.py +370 -0
  114. flyte/cli/_option.py +33 -0
  115. flyte/cli/_params.py +554 -0
  116. flyte/cli/_plugins.py +209 -0
  117. flyte/cli/_run.py +597 -0
  118. flyte/cli/_serve.py +64 -0
  119. flyte/cli/_update.py +37 -0
  120. flyte/cli/_user.py +17 -0
  121. flyte/cli/main.py +221 -0
  122. flyte/config/__init__.py +3 -0
  123. flyte/config/_config.py +248 -0
  124. flyte/config/_internal.py +73 -0
  125. flyte/config/_reader.py +225 -0
  126. flyte/connectors/__init__.py +11 -0
  127. flyte/connectors/_connector.py +270 -0
  128. flyte/connectors/_server.py +197 -0
  129. flyte/connectors/utils.py +135 -0
  130. flyte/errors.py +243 -0
  131. flyte/extend.py +19 -0
  132. flyte/extras/__init__.py +5 -0
  133. flyte/extras/_container.py +286 -0
  134. flyte/git/__init__.py +3 -0
  135. flyte/git/_config.py +21 -0
  136. flyte/io/__init__.py +29 -0
  137. flyte/io/_dataframe/__init__.py +131 -0
  138. flyte/io/_dataframe/basic_dfs.py +223 -0
  139. flyte/io/_dataframe/dataframe.py +1026 -0
  140. flyte/io/_dir.py +910 -0
  141. flyte/io/_file.py +914 -0
  142. flyte/io/_hashing_io.py +342 -0
  143. flyte/models.py +479 -0
  144. flyte/py.typed +0 -0
  145. flyte/remote/__init__.py +35 -0
  146. flyte/remote/_action.py +738 -0
  147. flyte/remote/_app.py +57 -0
  148. flyte/remote/_client/__init__.py +0 -0
  149. flyte/remote/_client/_protocols.py +189 -0
  150. flyte/remote/_client/auth/__init__.py +12 -0
  151. flyte/remote/_client/auth/_auth_utils.py +14 -0
  152. flyte/remote/_client/auth/_authenticators/__init__.py +0 -0
  153. flyte/remote/_client/auth/_authenticators/base.py +403 -0
  154. flyte/remote/_client/auth/_authenticators/client_credentials.py +73 -0
  155. flyte/remote/_client/auth/_authenticators/device_code.py +117 -0
  156. flyte/remote/_client/auth/_authenticators/external_command.py +79 -0
  157. flyte/remote/_client/auth/_authenticators/factory.py +200 -0
  158. flyte/remote/_client/auth/_authenticators/pkce.py +516 -0
  159. flyte/remote/_client/auth/_channel.py +213 -0
  160. flyte/remote/_client/auth/_client_config.py +85 -0
  161. flyte/remote/_client/auth/_default_html.py +32 -0
  162. flyte/remote/_client/auth/_grpc_utils/__init__.py +0 -0
  163. flyte/remote/_client/auth/_grpc_utils/auth_interceptor.py +288 -0
  164. flyte/remote/_client/auth/_grpc_utils/default_metadata_interceptor.py +151 -0
  165. flyte/remote/_client/auth/_keyring.py +152 -0
  166. flyte/remote/_client/auth/_token_client.py +260 -0
  167. flyte/remote/_client/auth/errors.py +16 -0
  168. flyte/remote/_client/controlplane.py +128 -0
  169. flyte/remote/_common.py +30 -0
  170. flyte/remote/_console.py +19 -0
  171. flyte/remote/_data.py +161 -0
  172. flyte/remote/_logs.py +185 -0
  173. flyte/remote/_project.py +88 -0
  174. flyte/remote/_run.py +386 -0
  175. flyte/remote/_secret.py +142 -0
  176. flyte/remote/_task.py +527 -0
  177. flyte/remote/_trigger.py +306 -0
  178. flyte/remote/_user.py +33 -0
  179. flyte/report/__init__.py +3 -0
  180. flyte/report/_report.py +182 -0
  181. flyte/report/_template.html +124 -0
  182. flyte/storage/__init__.py +36 -0
  183. flyte/storage/_config.py +237 -0
  184. flyte/storage/_parallel_reader.py +274 -0
  185. flyte/storage/_remote_fs.py +34 -0
  186. flyte/storage/_storage.py +456 -0
  187. flyte/storage/_utils.py +5 -0
  188. flyte/syncify/__init__.py +56 -0
  189. flyte/syncify/_api.py +375 -0
  190. flyte/types/__init__.py +52 -0
  191. flyte/types/_interface.py +40 -0
  192. flyte/types/_pickle.py +145 -0
  193. flyte/types/_renderer.py +162 -0
  194. flyte/types/_string_literals.py +119 -0
  195. flyte/types/_type_engine.py +2254 -0
  196. flyte/types/_utils.py +80 -0
  197. flyte-2.0.0b32.data/scripts/debug.py +38 -0
  198. flyte-2.0.0b32.data/scripts/runtime.py +195 -0
  199. flyte-2.0.0b32.dist-info/METADATA +351 -0
  200. flyte-2.0.0b32.dist-info/RECORD +204 -0
  201. flyte-2.0.0b32.dist-info/WHEEL +5 -0
  202. flyte-2.0.0b32.dist-info/entry_points.txt +7 -0
  203. flyte-2.0.0b32.dist-info/licenses/LICENSE +201 -0
  204. flyte-2.0.0b32.dist-info/top_level.txt +1 -0
@@ -0,0 +1,465 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import os
5
+ import sys
6
+ import threading
7
+ from asyncio import Event
8
+ from typing import Awaitable, Coroutine, Optional
9
+
10
+ import grpc.aio
11
+ from aiolimiter import AsyncLimiter
12
+ from flyteidl2.common import identifier_pb2
13
+ from flyteidl2.task import task_definition_pb2
14
+ from flyteidl2.workflow import queue_service_pb2, run_definition_pb2
15
+ from google.protobuf.wrappers_pb2 import StringValue
16
+
17
+ import flyte.errors
18
+ from flyte._logging import log, logger
19
+
20
+ from ._action import Action
21
+ from ._informer import InformerCache
22
+ from ._service_protocol import ClientSet, QueueService, StateService
23
+
24
+
25
+ class Controller:
26
+ """
27
+ Generic controller with high-level submit API running in a dedicated thread with its own event loop.
28
+ All methods that begin with _bg_ are run in the controller's event loop, and will need to use
29
+ _run_coroutine_in_controller_thread to run them in the controller's event loop.
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ client_coro: Awaitable[ClientSet],
35
+ workers: int = 20,
36
+ max_system_retries: int = 10,
37
+ resource_log_interval_sec: float = 10.0,
38
+ min_backoff_on_err_sec: float = 0.5,
39
+ thread_wait_timeout_sec: float = 5.0,
40
+ enqueue_timeout_sec: float = 5.0,
41
+ ):
42
+ """
43
+ Create a new controller instance.
44
+ :param workers: Number of worker threads.
45
+ :param max_system_retries: Maximum number of system retries.
46
+ :param resource_log_interval_sec: Interval for logging resource stats.
47
+ :param min_backoff_on_err_sec: Minimum backoff time on error.
48
+ :param thread_wait_timeout_sec: Timeout for waiting for the controller thread to start.
49
+ :param
50
+ """
51
+ self._informers = InformerCache()
52
+ self._shared_queue: asyncio.Queue[Action] = asyncio.Queue(maxsize=10000)
53
+ self._running = False
54
+ self._resource_log_task = None
55
+ self._workers = workers
56
+ self._max_retries = int(os.getenv("_F_MAX_RETRIES", max_system_retries))
57
+ self._resource_log_interval = resource_log_interval_sec
58
+ self._min_backoff_on_err = min_backoff_on_err_sec
59
+ self._max_backoff_on_err = float(os.getenv("_F_MAX_BFF_ON_ERR", "10.0"))
60
+ self._thread_wait_timeout = thread_wait_timeout_sec
61
+ self._client_coro = client_coro
62
+ self._failure_event: Event | None = None
63
+ self._enqueue_timeout = enqueue_timeout_sec
64
+ self._informer_start_wait_timeout = thread_wait_timeout_sec
65
+ max_qps = int(os.getenv("_F_MAX_QPS", "100"))
66
+ self._rate_limiter = AsyncLimiter(max_qps, 1.0)
67
+
68
+ # Thread management
69
+ self._thread = None
70
+ self._loop = None
71
+ self._thread_ready = threading.Event()
72
+ self._thread_exception: Optional[BaseException] = None
73
+ self._thread_com_lock = threading.Lock()
74
+ self._start()
75
+
76
+ # ---------------- Public sync methods, we can add more sync methods if needed
77
+ @log
78
+ def submit_action_sync(self, action: Action) -> Action:
79
+ """Synchronous version of submit that runs in the controller's event loop"""
80
+ fut = self._run_coroutine_in_controller_thread(self._bg_submit_action(action))
81
+ return fut.result()
82
+
83
+ # --------------- Public async methods
84
+ @log
85
+ async def submit_action(self, action: Action) -> Action:
86
+ """Public API to submit a resource and wait for completion"""
87
+ return await self._run_coroutine_in_controller_thread(self._bg_submit_action(action))
88
+
89
+ async def get_action(self, action_id: identifier_pb2.ActionIdentifier, parent_action_name: str) -> Optional[Action]:
90
+ """Get the action from the informer"""
91
+ return await self._run_coroutine_in_controller_thread(self._bg_get_action(action_id, parent_action_name))
92
+
93
+ @log
94
+ async def cancel_action(self, action: Action):
95
+ return await self._run_coroutine_in_controller_thread(self._bg_cancel_action(action))
96
+
97
+ async def _finalize_parent_action(
98
+ self,
99
+ run_id: identifier_pb2.RunIdentifier,
100
+ parent_action_name: str,
101
+ timeout: Optional[float] = None,
102
+ ):
103
+ """Finalize the parent run"""
104
+ await self._run_coroutine_in_controller_thread(
105
+ self._bg_finalize_informer(run_id=run_id, parent_action_name=parent_action_name, timeout=timeout)
106
+ )
107
+
108
+ def _bg_handle_informer_error(self, task: asyncio.Task):
109
+ """Handle errors in the informer task"""
110
+ try:
111
+ exc = task.exception()
112
+ if exc:
113
+ logger.error("Informer task failed with exception", exc_info=exc)
114
+ self._set_exception(exc)
115
+ if self._failure_event is None:
116
+ raise RuntimeError("Failure event not initialized")
117
+ self._failure_event.set()
118
+ except asyncio.CancelledError:
119
+ raise
120
+
121
+ async def _bg_watch_for_errors(self):
122
+ if self._failure_event is None:
123
+ raise RuntimeError("Failure event not initialized")
124
+ await self._failure_event.wait()
125
+ logger.warning(f"Failure event received: {self._failure_event}, cleaning up informers and exiting.")
126
+ self._running = False
127
+
128
+ async def watch_for_errors(self):
129
+ """Watch for errors in the background thread"""
130
+ await self._run_coroutine_in_controller_thread(self._bg_watch_for_errors())
131
+ raise flyte.errors.RuntimeSystemError(
132
+ code="InformerWatchFailure",
133
+ message=f"Controller thread failed with exception: {self._get_exception()}",
134
+ )
135
+
136
+ @log
137
+ async def stop(self):
138
+ """Stop the controller"""
139
+ return await self._run_coroutine_in_controller_thread(self._bg_stop())
140
+
141
+ # ------------- Background thread management methods
142
+ def _set_exception(self, exc: Optional[BaseException]):
143
+ """Set exception in the thread lock"""
144
+ with self._thread_com_lock:
145
+ self._thread_exception = exc
146
+
147
+ def _get_exception(self) -> Optional[BaseException]:
148
+ """Get exception in the thread lock"""
149
+ with self._thread_com_lock:
150
+ return self._thread_exception
151
+
152
+ @log
153
+ def _start(self):
154
+ """Start the controller in a separate thread"""
155
+ if self._thread and self._thread.is_alive():
156
+ logger.warning("Controller thread is already running")
157
+ return
158
+
159
+ self._thread_ready.clear()
160
+ self._set_exception(None)
161
+ self._thread = threading.Thread(target=self._bg_thread_target, daemon=True, name="ControllerThread")
162
+ self._thread.start()
163
+
164
+ # Wait for the thread to be ready
165
+ if not self._thread_ready.wait(timeout=self._thread_wait_timeout):
166
+ logger.warning("Controller thread did not finish within timeout")
167
+ raise TimeoutError("Controller thread failed to start in time")
168
+
169
+ if self._get_exception():
170
+ raise flyte.errors.RuntimeSystemError(
171
+ type(self._get_exception()).__name__,
172
+ f"Controller thread startup failed: {self._get_exception()}",
173
+ )
174
+
175
+ logger.info(f"Controller started in thread: {self._thread.name}")
176
+
177
+ def _run_coroutine_in_controller_thread(self, coro: Coroutine) -> asyncio.Future:
178
+ """Run a coroutine in the controller's event loop and return the result"""
179
+ with self._thread_com_lock:
180
+ loop = self._loop
181
+ if not self._loop or not self._thread or not self._thread.is_alive():
182
+ raise RuntimeError("Controller thread is not running")
183
+
184
+ assert self._thread.name != threading.current_thread().name, "Cannot run coroutine in the same thread"
185
+
186
+ future = asyncio.run_coroutine_threadsafe(coro, loop)
187
+ return asyncio.wrap_future(future)
188
+
189
+ # ------------- Private methods that run on the background thread
190
+ async def _bg_worker_pool(self):
191
+ logger.debug("Starting controller worker pool")
192
+ self._running = True
193
+ logger.debug("Waiting for Service Client to be ready")
194
+ client_set = await self._client_coro
195
+ self._state_service: StateService = client_set.state_service
196
+ self._queue_service: QueueService = client_set.queue_service
197
+ self._resource_log_task = asyncio.create_task(self._bg_log_stats())
198
+ # We will wait for this to signal that the thread is ready
199
+ # Signal the main thread that we're ready
200
+ logger.debug("Background thread initialization complete")
201
+ if sys.version_info >= (3, 11):
202
+ async with asyncio.TaskGroup() as tg:
203
+ for i in range(self._workers):
204
+ tg.create_task(self._bg_run(f"worker-{i}"))
205
+ self._thread_ready.set()
206
+ else:
207
+ tasks = []
208
+ for i in range(self._workers):
209
+ tasks.append(asyncio.create_task(self._bg_run(f"worker-{i}")))
210
+ self._thread_ready.set()
211
+ await asyncio.gather(*tasks)
212
+
213
+ def _bg_thread_target(self):
214
+ """Target function for the controller thread that creates and manages its own event loop"""
215
+ try:
216
+ # Create a new event loop for this thread
217
+ self._loop = asyncio.new_event_loop()
218
+ asyncio.set_event_loop(self._loop)
219
+ self._loop.set_exception_handler(flyte.errors.silence_grpc_polling_error)
220
+ logger.debug(f"Controller thread started with new event loop: {threading.current_thread().name}")
221
+
222
+ # Create an event to signal the errors were observed in the thread's loop
223
+ self._failure_event = Event()
224
+
225
+ self._loop.run_until_complete(self._bg_worker_pool())
226
+ except Exception as e:
227
+ logger.error(f"Controller thread encountered an exception: {e}")
228
+ self._set_exception(e)
229
+ self._failure_event.set()
230
+ finally:
231
+ if self._loop and self._loop.is_running():
232
+ self._loop.close()
233
+ logger.debug(f"Controller thread exiting: {threading.current_thread().name}")
234
+
235
+ async def _bg_get_action(
236
+ self, action_id: identifier_pb2.ActionIdentifier, parent_action_name: str
237
+ ) -> Optional[Action]:
238
+ """Get the action from the informer"""
239
+ # Ensure the informer is created and wait for it to be ready
240
+ informer = await self._informers.get_or_create(
241
+ action_id.run,
242
+ parent_action_name,
243
+ self._shared_queue,
244
+ self._state_service,
245
+ fn=self._bg_handle_informer_error,
246
+ timeout=self._informer_start_wait_timeout,
247
+ )
248
+ if informer:
249
+ return await informer.get(action_id.name)
250
+ return None
251
+
252
+ async def _bg_finalize_informer(
253
+ self,
254
+ run_id: identifier_pb2.RunIdentifier,
255
+ parent_action_name: str,
256
+ timeout: Optional[float] = None,
257
+ ):
258
+ informer = await self._informers.remove(run_name=run_id.name, parent_action_name=parent_action_name)
259
+ if informer:
260
+ await informer.stop()
261
+
262
+ @log
263
+ async def _bg_submit_action(self, action: Action) -> Action:
264
+ """Submit a resource and await its completion, returning the final state"""
265
+ logger.debug(f"{threading.current_thread().name} Submitting action {action.name}")
266
+ informer = await self._informers.get_or_create(
267
+ action.action_id.run,
268
+ action.parent_action_name,
269
+ self._shared_queue,
270
+ self._state_service,
271
+ fn=self._bg_handle_informer_error,
272
+ timeout=self._informer_start_wait_timeout,
273
+ )
274
+ await informer.submit(action)
275
+
276
+ logger.debug(f"{threading.current_thread().name} Waiting for completion of {action.name}")
277
+ # Wait for completion
278
+ await informer.wait_for_action_completion(action.name)
279
+ logger.info(f"{threading.current_thread().name} Action {action.name} completed")
280
+
281
+ # Get final resource state and clean up
282
+ final_resource = await informer.get(action.name)
283
+ if final_resource is None:
284
+ raise ValueError(f"Action {action.name} not found")
285
+ logger.debug(f"{threading.current_thread().name} Removed completion event for action {action.name}")
286
+ await informer.remove(action.name) # TODO we should not remove maybe, we should keep a record of completed?
287
+ logger.debug(f"{threading.current_thread().name} Removed action {action.name}, final={final_resource}")
288
+ return final_resource
289
+
290
+ async def _bg_cancel_action(self, action: Action):
291
+ """
292
+ Cancel an action.
293
+ """
294
+ if action.is_terminal():
295
+ logger.info(f"Action {action.name} is already terminal, no need to cancel.")
296
+ return
297
+
298
+ started = action.is_started()
299
+ action.mark_cancelled()
300
+ if started:
301
+ async with self._rate_limiter:
302
+ logger.info(f"Cancelling action: {action.name}")
303
+ try:
304
+ await self._queue_service.AbortQueuedAction(
305
+ queue_service_pb2.AbortQueuedActionRequest(action_id=action.action_id),
306
+ wait_for_ready=True,
307
+ )
308
+ logger.info(f"Successfully cancelled action: {action.name}")
309
+ except grpc.aio.AioRpcError as e:
310
+ if e.code() in [
311
+ grpc.StatusCode.NOT_FOUND,
312
+ grpc.StatusCode.FAILED_PRECONDITION,
313
+ ]:
314
+ logger.info(f"Action {action.name} not found, assumed completed or cancelled.")
315
+ return
316
+ else:
317
+ # If the action is not started, we have to ensure it does not get launched
318
+ logger.info(f"Action {action.name} is not started, no need to cancel.")
319
+
320
+ informer = await self._informers.get(run_name=action.run_name, parent_action_name=action.parent_action_name)
321
+ if informer:
322
+ await informer.fire_completion_event(action.name)
323
+
324
+ async def _bg_launch(self, action: Action):
325
+ """
326
+ Attempt to launch an action.
327
+ """
328
+ if not action.is_started():
329
+ async with self._rate_limiter:
330
+ task: run_definition_pb2.TaskAction | None = None
331
+ trace: run_definition_pb2.TraceAction | None = None
332
+ if action.type == "task":
333
+ if action.task is None:
334
+ raise flyte.errors.RuntimeSystemError(
335
+ "NoTaskSpec", "Task Spec not found, cannot launch Task Action."
336
+ )
337
+ cache_key = None
338
+ logger.info(f"Action {action.name} has cache version {action.cache_key}")
339
+ if action.cache_key:
340
+ cache_key = StringValue(value=action.cache_key)
341
+
342
+ task = run_definition_pb2.TaskAction(
343
+ id=task_definition_pb2.TaskIdentifier(
344
+ version=action.task.task_template.id.version,
345
+ org=action.task.task_template.id.org,
346
+ project=action.task.task_template.id.project,
347
+ domain=action.task.task_template.id.domain,
348
+ name=action.task.task_template.id.name,
349
+ ),
350
+ spec=action.task,
351
+ cache_key=cache_key,
352
+ cluster=action.queue,
353
+ )
354
+ elif action.type == "trace":
355
+ trace = action.trace
356
+
357
+ logger.debug(f"Attempting to launch action: {action.name}")
358
+ try:
359
+ await self._queue_service.EnqueueAction(
360
+ queue_service_pb2.EnqueueActionRequest(
361
+ action_id=action.action_id,
362
+ parent_action_name=action.parent_action_name,
363
+ task=task,
364
+ trace=trace,
365
+ input_uri=action.inputs_uri,
366
+ run_output_base=action.run_output_base,
367
+ group=action.group.name if action.group else None,
368
+ # Subject is not used in the current implementation
369
+ ),
370
+ wait_for_ready=True,
371
+ timeout=self._enqueue_timeout,
372
+ )
373
+ logger.info(f"Successfully launched action: {action.name}")
374
+ except grpc.aio.AioRpcError as e:
375
+ if e.code() == grpc.StatusCode.ALREADY_EXISTS:
376
+ logger.info(f"Action {action.name} already exists, continuing to monitor.")
377
+ return
378
+ if e.code() in [
379
+ grpc.StatusCode.FAILED_PRECONDITION,
380
+ grpc.StatusCode.INVALID_ARGUMENT,
381
+ grpc.StatusCode.NOT_FOUND,
382
+ ]:
383
+ raise flyte.errors.RuntimeSystemError(
384
+ e.code().name, f"Precondition failed: {e.details()}"
385
+ ) from e
386
+ # For all other errors, we will retry with backoff
387
+ logger.exception(
388
+ f"Failed to launch action: {action.name}, Code: {e.code()}, "
389
+ f"Details {e.details()} backing off..."
390
+ )
391
+ logger.debug(f"Action details: {action}")
392
+ raise flyte.errors.SlowDownError(f"Failed to launch action: {e.details()}") from e
393
+
394
+ @log
395
+ async def _bg_process(self, action: Action):
396
+ """Process resource updates"""
397
+ logger.debug(f"Processing action: name={action.name}, started={action.is_started()}")
398
+
399
+ if not action.is_started():
400
+ await self._bg_launch(action)
401
+ elif action.is_terminal():
402
+ informer = await self._informers.get(run_name=action.run_name, parent_action_name=action.parent_action_name)
403
+ if informer:
404
+ await informer.fire_completion_event(action.name)
405
+ else:
406
+ logger.debug(f"Resource {action.name} still in progress...")
407
+
408
+ async def _bg_log_stats(self):
409
+ """Periodically log resource stats if debug is enabled"""
410
+ while self._running:
411
+ async for (
412
+ started,
413
+ pending,
414
+ terminal,
415
+ ) in self._informers.count_started_pending_terminal_actions():
416
+ logger.info(f"Resource stats: Started={started}, Pending={pending}, Terminal={terminal}")
417
+ await asyncio.sleep(self._resource_log_interval)
418
+
419
+ @log
420
+ async def _bg_run(self, worker_id: str):
421
+ """Run loop with resource status logging"""
422
+ logger.info(f"Worker {worker_id} started")
423
+ while self._running:
424
+ logger.debug(f"{threading.current_thread().name} Waiting for resource")
425
+ action = await self._shared_queue.get()
426
+ logger.debug(f"{threading.current_thread().name} Got resource {action.name}")
427
+ try:
428
+ await self._bg_process(action)
429
+ except flyte.errors.SlowDownError as e:
430
+ action.retries += 1
431
+ if action.retries > self._max_retries:
432
+ raise
433
+ backoff = min(self._min_backoff_on_err * (2 ** (action.retries - 1)), self._max_backoff_on_err)
434
+ logger.warning(
435
+ f"[{worker_id}] Backing off for {backoff} [retry {action.retries}/{self._max_retries}] "
436
+ f"on action {action.name} due to error: {e}"
437
+ )
438
+ await asyncio.sleep(backoff)
439
+ logger.warning(f"[{worker_id}] Retrying action {action.name} after backoff")
440
+ await self._shared_queue.put(action)
441
+ except Exception as e:
442
+ logger.error(f"[{worker_id}] Error in controller loop for {action.name}: {e}")
443
+ err = flyte.errors.RuntimeSystemError(
444
+ code=type(e).__name__,
445
+ message=f"Controller failed, system retries {action.retries} / {self._max_retries} "
446
+ f"crossed threshold, for action {action.name}: {e}",
447
+ worker=worker_id,
448
+ )
449
+ err.__cause__ = e
450
+ action.set_client_error(err)
451
+ informer = await self._informers.get(
452
+ run_name=action.run_name,
453
+ parent_action_name=action.parent_action_name,
454
+ )
455
+ if informer:
456
+ await informer.fire_completion_event(action.name)
457
+ finally:
458
+ self._shared_queue.task_done()
459
+
460
+ @log
461
+ async def _bg_stop(self):
462
+ """Stop the controller"""
463
+ self._running = False
464
+ self._resource_log_task.cancel()
465
+ await self._informers.remove_and_stop_all()