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
flyte/models.py ADDED
@@ -0,0 +1,479 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import os
5
+ import pathlib
6
+ import typing
7
+ from dataclasses import dataclass, field, replace
8
+ from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Literal, Optional, Tuple, Type
9
+
10
+ import rich.repr
11
+
12
+ from flyte._docstring import Docstring
13
+ from flyte._interface import extract_return_annotation, literal_to_enum
14
+ from flyte._logging import logger
15
+
16
+ if TYPE_CHECKING:
17
+ from flyteidl2.core import literals_pb2
18
+
19
+ from flyte._internal.imagebuild.image_builder import ImageCache
20
+ from flyte.report import Report
21
+
22
+ # --- Constants ----
23
+ MAX_INLINE_IO_BYTES = 10 * 1024 * 1024 # 100 MB
24
+
25
+
26
+ def generate_random_name() -> str:
27
+ """
28
+ Generate a random name for the task. This is used to create unique names for tasks.
29
+ TODO we can use unique-namer in the future, for now its just guids
30
+ """
31
+ from uuid import uuid4
32
+
33
+ return str(uuid4()) # Placeholder for actual random name generation logic
34
+
35
+
36
+ @rich.repr.auto
37
+ @dataclass(frozen=True, kw_only=True)
38
+ class ActionID:
39
+ """
40
+ A class representing the ID of an Action, nested within a Run. This is used to identify a specific action on a task.
41
+ """
42
+
43
+ name: str
44
+ run_name: str | None = None
45
+ project: str | None = None
46
+ domain: str | None = None
47
+ org: str | None = None
48
+
49
+ def __post_init__(self):
50
+ if self.run_name is None:
51
+ object.__setattr__(self, "run_name", self.name)
52
+
53
+ @classmethod
54
+ def create_random(cls):
55
+ name = generate_random_name()
56
+ return cls(name=name, run_name=name)
57
+
58
+ def new_sub_action(self, name: str | None = None) -> ActionID:
59
+ """
60
+ Create a new sub-run with the given name. If name is None, a random name will be generated.
61
+ """
62
+ if name is None:
63
+ name = generate_random_name()
64
+ return replace(self, name=name)
65
+
66
+ def new_sub_action_from(self, task_call_seq: int, task_hash: str, input_hash: str, group: str | None) -> ActionID:
67
+ """Make a deterministic name"""
68
+ import hashlib
69
+
70
+ from flyte._utils.helpers import base36_encode
71
+
72
+ components = f"{self.name}-{input_hash}-{task_hash}-{task_call_seq}" + (f"-{group}" if group else "")
73
+ logger.debug(f"----- Generating sub-action ID from components: {components}")
74
+ # has the components into something deterministic
75
+ bytes_digest = hashlib.md5(components.encode()).digest()
76
+ new_name = base36_encode(bytes_digest)
77
+ return self.new_sub_action(new_name)
78
+
79
+
80
+ @rich.repr.auto
81
+ @dataclass
82
+ class PathRewrite:
83
+ """
84
+ Configuration for rewriting paths during input loading.
85
+ """
86
+
87
+ # If set, rewrites any path starting with this prefix to the new prefix.
88
+ old_prefix: str
89
+ new_prefix: str
90
+
91
+ def __post_init__(self):
92
+ if not self.old_prefix or not self.new_prefix:
93
+ raise ValueError("Both old_prefix and new_prefix must be non-empty strings.")
94
+ if self.old_prefix == self.new_prefix:
95
+ raise ValueError("old_prefix and new_prefix must be different.")
96
+
97
+ @classmethod
98
+ def from_str(cls, pattern: str) -> PathRewrite:
99
+ """
100
+ Create a PathRewrite from a string pattern of the form `old_prefix->new_prefix`.
101
+ """
102
+ parts = pattern.split("->")
103
+ if len(parts) != 2:
104
+ raise ValueError(f"Invalid path rewrite pattern: {pattern}. Expected format 'old_prefix->new_prefix'.")
105
+ return cls(old_prefix=parts[0], new_prefix=parts[1])
106
+
107
+ def __repr__(self) -> str:
108
+ return f"{self.old_prefix}->{self.new_prefix}"
109
+
110
+
111
+ @rich.repr.auto
112
+ @dataclass(frozen=True, kw_only=True)
113
+ class RawDataPath:
114
+ """
115
+ A class representing the raw data path for a task. This is used to store the raw data for the task execution and
116
+ also get mutations on the path.
117
+ """
118
+
119
+ path: str
120
+ path_rewrite: Optional[PathRewrite] = None
121
+
122
+ @classmethod
123
+ def from_local_folder(cls, local_folder: str | pathlib.Path | None = None) -> RawDataPath:
124
+ """
125
+ Create a new context attribute object, with local path given. Will be created if it doesn't exist.
126
+ :return: Path to the temporary directory
127
+ """
128
+ import tempfile
129
+
130
+ match local_folder:
131
+ case pathlib.Path():
132
+ local_folder.mkdir(parents=True, exist_ok=True)
133
+ return RawDataPath(path=str(local_folder))
134
+ case None:
135
+ # Create a temporary directory for data storage
136
+ p = tempfile.mkdtemp()
137
+ logger.debug(f"Creating temporary directory for data storage: {p}")
138
+ pathlib.Path(p).mkdir(parents=True, exist_ok=True)
139
+ return RawDataPath(path=p)
140
+ case str():
141
+ return RawDataPath(path=local_folder)
142
+ case _:
143
+ raise ValueError(f"Invalid local path {local_folder}")
144
+
145
+ def get_random_remote_path(self, file_name: Optional[str] = None) -> str:
146
+ """
147
+ Returns a random path for uploading a file/directory to. This file/folder will not be created, it's just a path.
148
+
149
+ :param file_name: If given, will be joined after a randomly generated portion.
150
+ :return:
151
+ """
152
+ import random
153
+ from uuid import UUID
154
+
155
+ import fsspec
156
+ from fsspec.utils import get_protocol
157
+
158
+ random_string = UUID(int=random.getrandbits(128)).hex
159
+ file_prefix = self.path
160
+
161
+ protocol = get_protocol(file_prefix)
162
+ if "file" in protocol:
163
+ parent_folder = pathlib.Path(file_prefix)
164
+ parent_folder.mkdir(exist_ok=True, parents=True)
165
+ if file_name:
166
+ random_folder = parent_folder / random_string
167
+ random_folder.mkdir()
168
+ local_path = random_folder / file_name
169
+ else:
170
+ local_path = parent_folder / random_string
171
+ return str(local_path.absolute())
172
+
173
+ fs = fsspec.filesystem(protocol)
174
+ if file_prefix.endswith(fs.sep):
175
+ file_prefix = file_prefix[:-1]
176
+ remote_path = fs.sep.join([file_prefix, random_string])
177
+ if file_name:
178
+ remote_path = fs.sep.join([remote_path, file_name])
179
+ return remote_path
180
+
181
+
182
+ @rich.repr.auto
183
+ @dataclass(frozen=True)
184
+ class GroupData:
185
+ name: str
186
+
187
+
188
+ @rich.repr.auto
189
+ @dataclass(frozen=True, kw_only=True)
190
+ class TaskContext:
191
+ """
192
+ A context class to hold the current task executions context.
193
+ This can be used to access various contextual parameters in the task execution by the user.
194
+
195
+ :param action: The action ID of the current execution. This is always set, within a run.
196
+ :param version: The version of the executed task. This is set when the task is executed by an action and will be
197
+ set on all sub-actions.
198
+ :param custom_context: Context metadata for the action. If an action receives context, it'll automatically pass it
199
+ to any actions it spawns. Context will not be used for cache key computation.
200
+ """
201
+
202
+ action: ActionID
203
+ version: str
204
+ raw_data_path: RawDataPath
205
+ input_path: str | None = None
206
+ output_path: str
207
+ run_base_dir: str
208
+ report: Report
209
+ group_data: GroupData | None = None
210
+ checkpoints: Checkpoints | None = None
211
+ code_bundle: CodeBundle | None = None
212
+ compiled_image_cache: ImageCache | None = None
213
+ data: Dict[str, Any] = field(default_factory=dict)
214
+ mode: Literal["local", "remote", "hybrid"] = "remote"
215
+ interactive_mode: bool = False
216
+ custom_context: Dict[str, str] = field(default_factory=dict)
217
+
218
+ def replace(self, **kwargs) -> TaskContext:
219
+ if "data" in kwargs:
220
+ rec_data = kwargs.pop("data")
221
+ if rec_data is None:
222
+ return replace(self, **kwargs)
223
+ data = {}
224
+ if self.data is not None:
225
+ data = self.data.copy()
226
+ data.update(rec_data)
227
+ kwargs.update({"data": data})
228
+ return replace(self, **kwargs)
229
+
230
+ def __getitem__(self, key: str) -> Optional[Any]:
231
+ return self.data.get(key)
232
+
233
+ def is_in_cluster(self):
234
+ """
235
+ Check if the task is running in a cluster.
236
+ :return: bool
237
+ """
238
+ return self.mode == "remote"
239
+
240
+
241
+ @rich.repr.auto
242
+ @dataclass(frozen=True, kw_only=True)
243
+ class CodeBundle:
244
+ """
245
+ A class representing a code bundle for a task. This is used to package the code and the inflation path.
246
+ The code bundle computes the version of the code using the hash of the code.
247
+
248
+ :param computed_version: The version of the code bundle. This is the hash of the code.
249
+ :param destination: The destination path for the code bundle to be inflated to.
250
+ :param tgz: Optional path to the tgz file.
251
+ :param pkl: Optional path to the pkl file.
252
+ :param downloaded_path: The path to the downloaded code bundle. This is only available during runtime, when
253
+ the code bundle has been downloaded and inflated.
254
+ """
255
+
256
+ computed_version: str
257
+ destination: str = "."
258
+ tgz: str | None = None
259
+ pkl: str | None = None
260
+ downloaded_path: pathlib.Path | None = None
261
+
262
+ # runtime_dependencies: Tuple[str, ...] = field(default_factory=tuple) In the future if we want we could add this
263
+ # but this messes up actors, spark etc
264
+
265
+ def __post_init__(self):
266
+ if self.tgz is None and self.pkl is None:
267
+ raise ValueError("Either tgz or pkl must be provided")
268
+
269
+ def with_downloaded_path(self, path: pathlib.Path) -> CodeBundle:
270
+ """
271
+ Create a new CodeBundle with the given downloaded path.
272
+ """
273
+ return replace(self, downloaded_path=path)
274
+
275
+
276
+ @rich.repr.auto
277
+ @dataclass(frozen=True)
278
+ class Checkpoints:
279
+ """
280
+ A class representing the checkpoints for a task. This is used to store the checkpoints for the task execution.
281
+ """
282
+
283
+ prev_checkpoint_path: str | None
284
+ checkpoint_path: str | None
285
+
286
+
287
+ class _has_default:
288
+ """
289
+ A marker class to indicate that a specific input has a default value or not.
290
+ This is used to determine if the input is required or not.
291
+ """
292
+
293
+
294
+ @dataclass(frozen=True)
295
+ class NativeInterface:
296
+ """
297
+ A class representing the native interface for a task. This is used to interact with the task and its execution
298
+ context.
299
+ """
300
+
301
+ inputs: Dict[str, Tuple[Type, Any]]
302
+ outputs: Dict[str, Type]
303
+ docstring: Optional[Docstring] = None
304
+
305
+ # This field is used to indicate that the task has a default value for the input, but already in the
306
+ # remote form.
307
+ _remote_defaults: Optional[Dict[str, literals_pb2.Literal]] = field(default=None, repr=False)
308
+
309
+ has_default: ClassVar[Type[_has_default]] = _has_default # This can be used to indicate if a specific input
310
+
311
+ # has a default value or not, in the case when the default value is not known. An example would be remote tasks.
312
+
313
+ def has_outputs(self) -> bool:
314
+ """
315
+ Check if the task has outputs. This is used to determine if the task has outputs or not.
316
+ """
317
+ return self.outputs is not None and len(self.outputs) > 0
318
+
319
+ def required_inputs(self) -> List[str]:
320
+ """
321
+ Get the names of the required inputs for the task. This is used to determine which inputs are required for the
322
+ task execution.
323
+ :return: A list of required input names.
324
+ """
325
+ return [k for k, v in self.inputs.items() if v[1] is inspect.Parameter.empty]
326
+
327
+ def num_required_inputs(self) -> int:
328
+ """
329
+ Get the number of required inputs for the task. This is used to determine how many inputs are required for the
330
+ task execution.
331
+ """
332
+ return sum(1 for t in self.inputs.values() if t[1] is inspect.Parameter.empty)
333
+
334
+ @classmethod
335
+ def from_types(
336
+ cls,
337
+ inputs: Dict[str, Tuple[Type, Type[_has_default] | Type[inspect._empty]]],
338
+ outputs: Dict[str, Type],
339
+ default_inputs: Optional[Dict[str, literals_pb2.Literal]] = None,
340
+ ) -> NativeInterface:
341
+ """
342
+ Create a new NativeInterface from the given types. This is used to create a native interface for the task.
343
+ :param inputs: A dictionary of input names and their types and a value indicating if they have a default value.
344
+ :param outputs: A dictionary of output names and their types.
345
+ :param default_inputs: Optional dictionary of default inputs for remote tasks.
346
+ :return: A NativeInterface object with the given inputs and outputs.
347
+ """
348
+ for k, v in inputs.items():
349
+ if v[1] is cls.has_default and (default_inputs is None or k not in default_inputs):
350
+ raise ValueError(f"Input {k} has a default value but no default input provided for remote task.")
351
+ return cls(inputs=inputs, outputs=outputs, _remote_defaults=default_inputs)
352
+
353
+ @classmethod
354
+ def from_callable(cls, func: Callable) -> NativeInterface:
355
+ """
356
+ Extract the native interface from the given function. This is used to create a native interface for the task.
357
+ """
358
+ # Get function parameters, defaults, varargs info (POSITIONAL_ONLY, VAR_POSITIONAL, KEYWORD_ONLY, etc.).
359
+ sig = inspect.signature(func)
360
+
361
+ # Extract parameter details (name, type, default value)
362
+ param_info = {}
363
+ try:
364
+ # Get fully evaluated, real Python types for type checking.
365
+ hints = typing.get_type_hints(func, include_extras=True)
366
+ except Exception as e:
367
+ logger.warning(f"Could not get type hints for function {func.__name__}: {e}")
368
+ raise
369
+
370
+ for name, param in sig.parameters.items():
371
+ if param.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD):
372
+ raise ValueError(f"Function {func.__name__} cannot have variable positional or keyword arguments.")
373
+ if param.annotation is inspect.Parameter.empty:
374
+ logger.warning(
375
+ f"Function {func.__name__} has parameter {name} without type annotation. Data will be pickled."
376
+ )
377
+ arg_type = hints.get(name, param.annotation)
378
+ if typing.get_origin(arg_type) is Literal:
379
+ param_info[name] = (literal_to_enum(arg_type), param.default)
380
+ else:
381
+ param_info[name] = (arg_type, param.default)
382
+
383
+ # Get return type
384
+ outputs = extract_return_annotation(hints.get("return", sig.return_annotation))
385
+ return cls(inputs=param_info, outputs=outputs)
386
+
387
+ def convert_to_kwargs(self, *args, **kwargs) -> Dict[str, Any]:
388
+ """
389
+ Convert the given arguments to keyword arguments based on the native interface. This is used to convert the
390
+ arguments to the correct types for the task execution.
391
+ """
392
+ # Convert positional arguments to keyword arguments
393
+ if len(args) > len(self.inputs):
394
+ raise ValueError(
395
+ f"Too many positional arguments provided, expected inputs {self.inputs.keys()}, args {len(args)}"
396
+ )
397
+ for arg, input_name in zip(args, self.inputs.keys()):
398
+ kwargs[input_name] = arg
399
+ if len(kwargs) > len(self.inputs):
400
+ raise ValueError(
401
+ f"Too many keyword arguments provided, expected inputs {self.inputs.keys()}, args {kwargs.keys()}"
402
+ )
403
+ return kwargs
404
+
405
+ def get_input_types(self) -> Dict[str, Type]:
406
+ """
407
+ Get the input types for the task. This is used to get the types of the inputs for the task execution.
408
+ """
409
+ return {k: v[0] for k, v in self.inputs.items()}
410
+
411
+ def __repr__(self):
412
+ """
413
+ Returns a string representation of the task interface.
414
+ """
415
+ i = "("
416
+ if self.inputs:
417
+ initial = True
418
+ for key, tpe in self.inputs.items():
419
+ if not initial:
420
+ i += ", "
421
+ initial = False
422
+ tp = tpe[0] if isinstance(tpe[0], str) else getattr(tpe[0], "__name__", str(tpe[0]))
423
+ i += f"{key}: {tp}"
424
+ if tpe[1] is not inspect.Parameter.empty:
425
+ if tpe[1] is self.has_default:
426
+ i += " = ..."
427
+ else:
428
+ i += f" = {tpe[1]}"
429
+ i += ")"
430
+ if self.outputs:
431
+ initial = True
432
+ multi = len(self.outputs) > 1
433
+ i += " -> "
434
+ if multi:
435
+ i += "("
436
+ for key, tpe in self.outputs.items():
437
+ if not initial:
438
+ i += ", "
439
+ initial = False
440
+ tp = tpe.__name__ if isinstance(tpe, type) else tpe
441
+ i += f"{key}: {tp}"
442
+ if multi:
443
+ i += ")"
444
+ return i + ":"
445
+
446
+
447
+ @dataclass
448
+ class SerializationContext:
449
+ """
450
+ This object holds serialization time contextual information, that can be used when serializing the task and
451
+ various parameters of a tasktemplate. This is only available when the task is being serialized and can be
452
+ during a deployment or runtime.
453
+
454
+ :param version: The version of the task
455
+ :param code_bundle: The code bundle for the task. This is used to package the code and the inflation path.
456
+ :param input_path: The path to the inputs for the task. This is used to determine where the inputs will be located
457
+ :param output_path: The path to the outputs for the task. This is used to determine where the outputs will be
458
+ located
459
+ """
460
+
461
+ version: str
462
+ project: str | None = None
463
+ domain: str | None = None
464
+ org: str | None = None
465
+ code_bundle: Optional[CodeBundle] = None
466
+ input_path: str = "{{.input}}"
467
+ output_path: str = "{{.outputPrefix}}"
468
+ interpreter_path: str = "/opt/venv/bin/python"
469
+ image_cache: ImageCache | None = None
470
+ root_dir: Optional[pathlib.Path] = None
471
+
472
+ def get_entrypoint_path(self, interpreter_path: Optional[str] = None) -> str:
473
+ """
474
+ Get the entrypoint path for the task. This is used to determine the entrypoint for the task execution.
475
+ :param interpreter_path: The path to the interpreter (python)
476
+ """
477
+ if interpreter_path is None:
478
+ interpreter_path = self.interpreter_path
479
+ return os.path.join(os.path.dirname(interpreter_path), "runtime.py")
flyte/py.typed ADDED
File without changes
@@ -0,0 +1,35 @@
1
+ """
2
+ Remote Entities that are accessible from the Union Server once deployed or created.
3
+ """
4
+
5
+ __all__ = [
6
+ "Action",
7
+ "ActionDetails",
8
+ "ActionInputs",
9
+ "ActionOutputs",
10
+ "App",
11
+ "Phase",
12
+ "Project",
13
+ "Run",
14
+ "RunDetails",
15
+ "Secret",
16
+ "SecretTypes",
17
+ "Task",
18
+ "TaskDetails",
19
+ "Trigger",
20
+ "User",
21
+ "create_channel",
22
+ "upload_dir",
23
+ "upload_file",
24
+ ]
25
+
26
+ from ._action import Action, ActionDetails, ActionInputs, ActionOutputs
27
+ from ._app import App
28
+ from ._client.auth import create_channel
29
+ from ._data import upload_dir, upload_file
30
+ from ._project import Project
31
+ from ._run import Phase, Run, RunDetails
32
+ from ._secret import Secret, SecretTypes
33
+ from ._task import Task, TaskDetails
34
+ from ._trigger import Trigger
35
+ from ._user import User