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