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,2254 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import collections
5
+ import copy
6
+ import dataclasses
7
+ import datetime
8
+ import enum
9
+ import inspect
10
+ import json
11
+ import os
12
+ import sys
13
+ import textwrap
14
+ import threading
15
+ import typing
16
+ from abc import ABC, abstractmethod
17
+ from collections import OrderedDict
18
+ from functools import lru_cache
19
+ from types import GenericAlias, NoneType
20
+ from typing import Any, Dict, NamedTuple, Optional, Type, cast
21
+
22
+ import msgpack
23
+ from flyteidl2.core import interface_pb2, literals_pb2, types_pb2
24
+ from flyteidl2.core.literals_pb2 import Binary, Literal, LiteralCollection, LiteralMap, Primitive, Scalar, Union, Void
25
+ from flyteidl2.core.types_pb2 import LiteralType, SimpleType, TypeAnnotation, TypeStructure, UnionType
26
+ from fsspec.asyn import _run_coros_in_chunks # pylint: disable=W0212
27
+ from google.protobuf import json_format as _json_format
28
+ from google.protobuf import struct_pb2
29
+ from google.protobuf.json_format import MessageToDict as _MessageToDict
30
+ from google.protobuf.json_format import ParseDict as _ParseDict
31
+ from google.protobuf.message import Message
32
+ from mashumaro.codecs.json import JSONDecoder, JSONEncoder
33
+ from mashumaro.codecs.msgpack import MessagePackDecoder, MessagePackEncoder
34
+ from mashumaro.jsonschema.models import Context, JSONSchema
35
+ from mashumaro.jsonschema.plugins import BasePlugin
36
+ from mashumaro.jsonschema.schema import Instance
37
+ from mashumaro.mixins.json import DataClassJSONMixin
38
+ from pydantic import BaseModel
39
+ from typing_extensions import Annotated, get_args, get_origin
40
+
41
+ import flyte.storage as storage
42
+ from flyte._logging import logger
43
+ from flyte._utils.helpers import load_proto_from_file
44
+ from flyte.models import NativeInterface
45
+
46
+ from ._utils import literal_types_match
47
+
48
+ T = typing.TypeVar("T")
49
+
50
+ MESSAGEPACK = "msgpack"
51
+ CACHE_KEY_METADATA = "cache-key-metadata"
52
+ SERIALIZATION_FORMAT = "serialization-format"
53
+
54
+ DEFINITIONS = "definitions"
55
+ TITLE = "title"
56
+
57
+ _TYPE_ENGINE_COROS_BATCH_SIZE = int(os.environ.get("_F_TE_MAX_COROS", "10"))
58
+
59
+
60
+ # In Mashumaro, the default encoder uses strict_map_key=False, while the default decoder uses strict_map_key=True.
61
+ # This is relevant for cases like Dict[int, str]. If strict_map_key=False is not used,
62
+ # the decoder will raise an error when trying to decode keys that are not strictly typed.
63
+ def _default_msgpack_decoder(data: bytes) -> Any:
64
+ return msgpack.unpackb(data, strict_map_key=False)
65
+
66
+
67
+ def modify_literal_uris(lit: Literal):
68
+ """
69
+ Modifies the literal object recursively to replace the URIs with the native paths in case they are of
70
+ type "flyte://"
71
+ """
72
+ from flyte.storage._remote_fs import RemoteFSPathResolver
73
+
74
+ if lit.HasField("collection"):
75
+ for literal in lit.collection.literals:
76
+ modify_literal_uris(literal)
77
+ elif lit.HasField("map"):
78
+ for k, v in lit.map.literals.items():
79
+ modify_literal_uris(v)
80
+ elif lit.HasField("scalar"):
81
+ if (
82
+ lit.scalar.HasField("blob")
83
+ and lit.scalar.blob.uri
84
+ and lit.scalar.blob.uri.startswith(RemoteFSPathResolver.protocol)
85
+ ):
86
+ lit.scalar.blob.uri = RemoteFSPathResolver.resolve_remote_path(lit.scalar.blob.uri)
87
+ elif lit.scalar.HasField("union"):
88
+ modify_literal_uris(lit.scalar.union.value)
89
+ elif (
90
+ lit.scalar.HasField("structured_dataset")
91
+ and lit.scalar.structured_dataset.uri
92
+ and lit.scalar.structured_dataset.uri.startswith(RemoteFSPathResolver.protocol)
93
+ ):
94
+ lit.scalar.structured_dataset.uri = RemoteFSPathResolver.resolve_remote_path(
95
+ lit.scalar.structured_dataset.uri
96
+ )
97
+
98
+
99
+ class TypeTransformerFailedError(TypeError, AssertionError, ValueError): ...
100
+
101
+
102
+ class TypeTransformer(typing.Generic[T]):
103
+ """
104
+ Base transformer type that should be implemented for every python native type that can be handled by flytekit
105
+ """
106
+
107
+ def __init__(self, name: str, t: Type[T], enable_type_assertions: bool = True):
108
+ self._t = t
109
+ self._name = name
110
+ self._type_assertions_enabled = enable_type_assertions
111
+ self._msgpack_encoder: Dict[Type, MessagePackEncoder] = {}
112
+ self._msgpack_decoder: Dict[Type, MessagePackDecoder] = {}
113
+
114
+ @property
115
+ def name(self):
116
+ return self._name
117
+
118
+ @property
119
+ def python_type(self) -> Type[T]:
120
+ """
121
+ This returns the python type
122
+ """
123
+ return self._t
124
+
125
+ @property
126
+ def type_assertions_enabled(self) -> bool:
127
+ """
128
+ Indicates if the transformer wants type assertions to be enabled at the core type engine layer
129
+ """
130
+ return self._type_assertions_enabled
131
+
132
+ def isinstance_generic(self, obj, generic_alias):
133
+ origin = get_origin(generic_alias) # list from list[int])
134
+
135
+ if not isinstance(obj, origin):
136
+ raise TypeTransformerFailedError(f"Value '{obj}' is not of container type {origin}")
137
+
138
+ def assert_type(self, t: Type[T], v: T):
139
+ if sys.version_info >= (3, 10):
140
+ import types
141
+
142
+ if isinstance(t, types.GenericAlias):
143
+ return self.isinstance_generic(v, t)
144
+
145
+ if not hasattr(t, "__origin__") and not isinstance(v, t):
146
+ raise TypeTransformerFailedError(f"Expected value of type {t} but got '{v}' of type {type(v)}")
147
+
148
+ @abstractmethod
149
+ def get_literal_type(self, t: Type[T]) -> LiteralType:
150
+ """
151
+ Converts the python type to a Flyte LiteralType
152
+ """
153
+ raise NotImplementedError("Conversion to LiteralType should be implemented")
154
+
155
+ def guess_python_type(self, literal_type: LiteralType) -> Type[T]:
156
+ """
157
+ Converts the Flyte LiteralType to a python object type.
158
+ """
159
+ raise ValueError("By default, transformers do not translate from Flyte types back to Python types")
160
+
161
+ @abstractmethod
162
+ async def to_literal(self, python_val: T, python_type: Type[T], expected: LiteralType) -> Literal:
163
+ """
164
+ Converts a given python_val to a Flyte Literal, assuming the given python_val matches the declared python_type.
165
+ Implementers should refrain from using type(python_val) instead rely on the passed in python_type. If these
166
+ do not match (or are not allowed) the Transformer implementer should raise an AssertionError, clearly stating
167
+ what was the mismatch
168
+ :param python_val: The actual value to be transformed
169
+ :param python_type: The assumed type of the value (this matches the declared type on the function)
170
+ :param expected: Expected Literal Type
171
+ """
172
+ raise NotImplementedError(f"Conversion to Literal for python type {python_type} not implemented")
173
+
174
+ @abstractmethod
175
+ async def to_python_value(self, lv: Literal, expected_python_type: Type[T]) -> Optional[T]:
176
+ """
177
+ Converts the given Literal to a Python Type. If the conversion cannot be done an AssertionError should be raised
178
+ :param lv: The received literal Value
179
+ :param expected_python_type: Expected native python type that should be returned
180
+ """
181
+ raise NotImplementedError(
182
+ f"Conversion to python value expected type {expected_python_type} from literal not implemented"
183
+ )
184
+
185
+ def from_binary_idl(self, binary_idl_object: Binary, expected_python_type: Type[T]) -> Optional[T]:
186
+ """
187
+ This function primarily handles deserialization for untyped dicts, dataclasses, Pydantic BaseModels, and
188
+ attribute access.
189
+
190
+ For untyped dict, dataclass, and pydantic basemodel:
191
+ Life Cycle (Untyped Dict as example):
192
+ python val -> msgpack bytes -> binary literal scalar -> msgpack bytes -> python val
193
+ (to_literal) (from_binary_idl)
194
+
195
+ For attribute access:
196
+ Life Cycle:
197
+ python val -> msgpack bytes -> binary literal scalar -> resolved golang value -> binary literal scalar
198
+ -> msgpack bytes -> python val
199
+ (to_literal) (propeller attribute access) (from_binary_idl)
200
+ """
201
+ if binary_idl_object.tag == MESSAGEPACK:
202
+ try:
203
+ decoder = self._msgpack_decoder[expected_python_type]
204
+ except KeyError:
205
+ decoder = MessagePackDecoder(expected_python_type, pre_decoder_func=_default_msgpack_decoder)
206
+ self._msgpack_decoder[expected_python_type] = decoder
207
+ python_val = decoder.decode(binary_idl_object.value)
208
+
209
+ return python_val
210
+ else:
211
+ raise TypeTransformerFailedError(f"Unsupported binary format `{binary_idl_object.tag}`")
212
+
213
+ def to_html(self, python_val: T, expected_python_type: Type[T]) -> str:
214
+ """
215
+ Converts any python val (dataframe, int, float) to a html string, and it will be wrapped in the HTML div
216
+ """
217
+ return str(python_val)
218
+
219
+ def __repr__(self):
220
+ return f"{self._name} Transforms ({self._t}) to Flyte native"
221
+
222
+ def __str__(self):
223
+ return str(self.__repr__())
224
+
225
+
226
+ class SimpleTransformer(TypeTransformer[T]):
227
+ """
228
+ A Simple implementation of a type transformer that uses simple lambdas to transform and reduces boilerplate
229
+ """
230
+
231
+ def __init__(
232
+ self,
233
+ name: str,
234
+ t: Type[T],
235
+ lt: types_pb2.LiteralType,
236
+ to_literal_transformer: typing.Callable[[T], Literal],
237
+ from_literal_transformer: typing.Callable[[Literal], Optional[T]],
238
+ ):
239
+ super().__init__(name, t)
240
+ self._type = t
241
+ self._lt = lt
242
+ self._to_literal_transformer = to_literal_transformer
243
+ self._from_literal_transformer = from_literal_transformer
244
+
245
+ @property
246
+ def base_type(self) -> Type:
247
+ return self._type
248
+
249
+ def get_literal_type(self, t: Optional[Type[T]] = None) -> types_pb2.LiteralType:
250
+ return self._lt
251
+
252
+ async def to_literal(self, python_val: T, python_type: Type[T], expected: Optional[LiteralType] = None) -> Literal:
253
+ if type(python_val) is not self._type:
254
+ raise TypeTransformerFailedError(
255
+ f"Expected value of type {self._type} but got '{python_val}' of type {type(python_val)}"
256
+ )
257
+ return self._to_literal_transformer(python_val)
258
+
259
+ def from_binary_idl(self, binary_idl_object: Binary, expected_python_type: Type[T]) -> Optional[T]:
260
+ if binary_idl_object.tag == MESSAGEPACK:
261
+ if expected_python_type in [datetime.date, datetime.datetime, datetime.timedelta]:
262
+ """
263
+ MessagePack doesn't support datetime, date, and timedelta.
264
+ However, mashumaro's MessagePackEncoder and MessagePackDecoder can convert them to str and vice versa.
265
+ That's why we need to use mashumaro's MessagePackDecoder here.
266
+ """
267
+ try:
268
+ decoder = self._msgpack_decoder[expected_python_type]
269
+ except KeyError:
270
+ decoder = MessagePackDecoder(expected_python_type, pre_decoder_func=_default_msgpack_decoder)
271
+ self._msgpack_decoder[expected_python_type] = decoder
272
+ python_val = decoder.decode(binary_idl_object.value)
273
+ else:
274
+ python_val = msgpack.loads(binary_idl_object.value)
275
+ r"""
276
+ In the case below, when using Union Transformer + Simple Transformer, then `a`
277
+ can be converted to int, bool, str and float if we use MessagePackDecoder[expected_python_type].
278
+
279
+ Life Cycle:
280
+ 1 -> msgpack bytes -> (1, true, "1", 1.0)
281
+
282
+ Example Code:
283
+ @dataclass
284
+ class DC:
285
+ a: Union[int, bool, str, float]
286
+ b: Union[int, bool, str, float]
287
+
288
+ @task(container_image=custom_image)
289
+ def add(a: Union[int, bool, str, float],
290
+ b: Union[int, bool, str, float]) -> Union[int, bool, str, float]:
291
+ return a + b
292
+
293
+ @workflow
294
+ def wf(dc: DC) -> Union[int, bool, str, float]:
295
+ return add(dc.a, dc.b)
296
+
297
+ wf(DC(1, 1))
298
+ """
299
+ assert isinstance(python_val, expected_python_type)
300
+
301
+ return python_val
302
+ else:
303
+ raise TypeTransformerFailedError(f"Unsupported binary format `{binary_idl_object.tag}`")
304
+
305
+ async def to_python_value(self, lv: Literal, expected_python_type: Type[T]) -> T:
306
+ expected_python_type = get_underlying_type(expected_python_type)
307
+
308
+ if expected_python_type is not self._type:
309
+ if expected_python_type is None and issubclass(self._type, NoneType):
310
+ # If the expected type is NoneType, we can return None
311
+ return None
312
+ raise TypeTransformerFailedError(
313
+ f"Cannot convert to type {expected_python_type}, only {self._type} is supported"
314
+ )
315
+
316
+ if lv.HasField("scalar") and lv.scalar.HasField("binary"):
317
+ return self.from_binary_idl(lv.scalar.binary, expected_python_type) # type: ignore
318
+
319
+ try:
320
+ res = self._from_literal_transformer(lv)
321
+ if type(res) is not self._type:
322
+ raise TypeTransformerFailedError(f"Cannot convert literal {lv} to {self._type}")
323
+ return res
324
+ except AttributeError:
325
+ # Assume that this is because a property on `lv` was None
326
+ raise TypeTransformerFailedError(f"Cannot convert literal {lv} to {self._type}")
327
+
328
+ def guess_python_type(self, literal_type: types_pb2.LiteralType) -> Type[T]:
329
+ if literal_type.HasField("simple") and literal_type.simple == self._lt.simple:
330
+ return self.python_type
331
+ raise ValueError(f"Transformer {self} cannot reverse {literal_type}")
332
+
333
+
334
+ class RestrictedTypeError(Exception):
335
+ pass
336
+
337
+
338
+ class RestrictedTypeTransformer(TypeTransformer[T], ABC):
339
+ """
340
+ Types registered with the RestrictedTypeTransformer are not allowed to be converted to and from literals.
341
+ In other words,
342
+ Restricted types are not allowed to be used as inputs or outputs of tasks and workflows.
343
+ """
344
+
345
+ def __init__(self, name: str, t: Type[T]):
346
+ super().__init__(name, t)
347
+
348
+ def get_literal_type(self, t: Optional[Type[T]] = None) -> LiteralType:
349
+ raise RestrictedTypeError(f"Transformer for type {self.python_type} is restricted currently")
350
+
351
+ async def to_literal(self, python_val: T, python_type: Type[T], expected: LiteralType) -> Literal:
352
+ raise RestrictedTypeError(f"Transformer for type {self.python_type} is restricted currently")
353
+
354
+ async def to_python_value(self, lv: Literal, expected_python_type: Type[T]) -> T:
355
+ raise RestrictedTypeError(f"Transformer for type {self.python_type} is restricted currently")
356
+
357
+
358
+ class PydanticTransformer(TypeTransformer[BaseModel]):
359
+ def __init__(self):
360
+ super().__init__("Pydantic Transformer", BaseModel, enable_type_assertions=False)
361
+
362
+ def get_literal_type(self, t: Type[BaseModel]) -> LiteralType:
363
+ schema = t.model_json_schema()
364
+
365
+ meta_struct = struct_pb2.Struct()
366
+ meta_struct.update(
367
+ {
368
+ CACHE_KEY_METADATA: {
369
+ SERIALIZATION_FORMAT: MESSAGEPACK,
370
+ }
371
+ }
372
+ )
373
+
374
+ # The type engine used to publish a type structure for attribute access. As of v2, this is no longer needed.
375
+ return LiteralType(
376
+ simple=SimpleType.STRUCT,
377
+ metadata=schema,
378
+ annotation=TypeAnnotation(annotations=meta_struct),
379
+ )
380
+
381
+ async def to_literal(
382
+ self,
383
+ python_val: BaseModel,
384
+ python_type: Type[BaseModel],
385
+ expected: LiteralType,
386
+ ) -> Literal:
387
+ json_str = python_val.model_dump_json()
388
+ dict_obj = json.loads(json_str)
389
+ msgpack_bytes = msgpack.dumps(dict_obj)
390
+ return Literal(scalar=Scalar(binary=Binary(value=msgpack_bytes, tag=MESSAGEPACK)))
391
+
392
+ def from_binary_idl(self, binary_idl_object: Binary, expected_python_type: Type[BaseModel]) -> BaseModel:
393
+ if binary_idl_object.tag == MESSAGEPACK:
394
+ dict_obj = msgpack.loads(binary_idl_object.value, strict_map_key=False)
395
+ json_str = json.dumps(dict_obj)
396
+ python_val = expected_python_type.model_validate_json(
397
+ json_data=json_str, strict=False, context={"deserialize": True}
398
+ )
399
+ return python_val
400
+ else:
401
+ raise TypeTransformerFailedError(f"Unsupported binary format: `{binary_idl_object.tag}`")
402
+
403
+ async def to_python_value(self, lv: Literal, expected_python_type: Type[BaseModel]) -> BaseModel:
404
+ """
405
+ There are two kinds of literal values to handle:
406
+ 1. Protobuf Structs (from the UI)
407
+ 2. Binary scalars (from other sources)
408
+ We need to account for both cases accordingly.
409
+ """
410
+ if lv and lv.HasField("scalar") and lv.scalar.HasField("binary"):
411
+ return self.from_binary_idl(lv.scalar.binary, expected_python_type) # type: ignore
412
+
413
+ json_str = _json_format.MessageToJson(lv.scalar.generic)
414
+ python_val = expected_python_type.model_validate_json(json_str, strict=False, context={"deserialize": True})
415
+ return python_val
416
+
417
+
418
+ class PydanticSchemaPlugin(BasePlugin):
419
+ """This allows us to generate proper schemas for Pydantic models."""
420
+
421
+ def get_schema(
422
+ self,
423
+ instance: Instance,
424
+ ctx: Context,
425
+ schema: JSONSchema | None = None,
426
+ ) -> JSONSchema | None:
427
+ from pydantic import BaseModel
428
+
429
+ try:
430
+ if issubclass(instance.type, BaseModel):
431
+ pydantic_schema = instance.type.model_json_schema()
432
+ return JSONSchema.from_dict(pydantic_schema)
433
+ except TypeError:
434
+ return None
435
+ return None
436
+
437
+
438
+ class DataclassTransformer(TypeTransformer[object]):
439
+ """
440
+ The Dataclass Transformer provides a type transformer for dataclasses.
441
+
442
+ The dataclass is converted to and from MessagePack Bytes by the mashumaro library
443
+ and is transported between tasks using the Binary IDL representation.
444
+ Also, the type declaration will try to extract the JSON Schema for the
445
+ object, if possible, and pass it with the definition.
446
+
447
+ The lifecycle of the dataclass in the Flyte type system is as follows:
448
+
449
+ 1. Serialization: The dataclass transformer converts the dataclass to MessagePack Bytes.
450
+ (1) Handle dataclass attributes to make them serializable with mashumaro.
451
+ (2) Use the mashumaro API to serialize the dataclass to MessagePack Bytes.
452
+ (3) Use MessagePack Bytes to create a Flyte Literal.
453
+ (4) Serialize the Flyte Literal to a Binary IDL Object.
454
+
455
+ 2. Deserialization: The dataclass transformer converts the MessagePack Bytes back to a dataclass.
456
+ (1) Convert MessagePack Bytes to a dataclass using mashumaro.
457
+ (2) Handle dataclass attributes to ensure they are of the correct types.
458
+ """
459
+
460
+ def __init__(self) -> None:
461
+ super().__init__("Object-Dataclass-Transformer", object)
462
+ self._json_encoder: Dict[Type, JSONEncoder] = {}
463
+ self._json_decoder: Dict[Type, JSONDecoder] = {}
464
+
465
+ def assert_type(self, expected_type: Type, v: T):
466
+ # Skip iterating all attributes in the dataclass if the type of v already matches the expected_type
467
+ expected_type = get_underlying_type(expected_type)
468
+ if type(v) is expected_type or issubclass(type(v), expected_type):
469
+ return
470
+
471
+ # @dataclass
472
+ # class Foo:
473
+ # a: int = 0
474
+ #
475
+ # @task
476
+ # def t1(a: Foo):
477
+ # ...
478
+ #
479
+ # In above example, the type of v may not equal to the expected_type in some cases
480
+ # For example,
481
+ # 1. The input of t1 is another dataclass (bar), then we should raise an error
482
+ # 2. when using flyte remote to execute the above task, the expected_type is guess_python_type (FooSchema)
483
+ # by default.
484
+ # However, FooSchema is created by flytekit and it's not equal to the user-defined dataclass (Foo).
485
+ # Therefore, we should iterate all attributes in the dataclass and check the type of value in dataclass
486
+ # matches the expected_type.
487
+ expected_fields_dict = {}
488
+
489
+ for f in dataclasses.fields(expected_type):
490
+ expected_fields_dict[f.name] = cast(type, f.type)
491
+
492
+ if isinstance(v, dict):
493
+ original_dict = v
494
+
495
+ # Find the Optional keys in expected_fields_dict
496
+ optional_keys = {k for k, t in expected_fields_dict.items() if UnionTransformer.is_optional_type(t)}
497
+
498
+ # Remove the Optional keys from the keys of original_dict
499
+ original_key = set(original_dict.keys()) - optional_keys
500
+ expected_key = set(expected_fields_dict.keys()) - optional_keys
501
+
502
+ # Check if original_key is missing any keys from expected_key
503
+ missing_keys = expected_key - original_key
504
+ if missing_keys:
505
+ raise TypeTransformerFailedError(
506
+ f"The original fields are missing the following keys from the dataclass fields: "
507
+ f"{list(missing_keys)}"
508
+ )
509
+
510
+ # Check if original_key has any extra keys that are not in expected_key
511
+ extra_keys = original_key - expected_key
512
+ if extra_keys:
513
+ raise TypeTransformerFailedError(
514
+ f"The original fields have the following extra keys that are not in dataclass fields:"
515
+ f" {list(extra_keys)}"
516
+ )
517
+
518
+ for k, v in original_dict.items():
519
+ if k in expected_fields_dict:
520
+ if isinstance(v, dict):
521
+ self.assert_type(expected_fields_dict[k], v)
522
+ else:
523
+ expected_type = expected_fields_dict[k]
524
+ original_type = type(v)
525
+ if UnionTransformer.is_optional_type(expected_type):
526
+ expected_type = UnionTransformer.get_sub_type_in_optional(expected_type)
527
+ if original_type != expected_type:
528
+ raise TypeTransformerFailedError(
529
+ f"Type of Val '{original_type}' is not an instance of {expected_type}"
530
+ )
531
+
532
+ else:
533
+ for f in dataclasses.fields(type(v)): # type: ignore
534
+ original_type = cast(type, f.type)
535
+ if f.name not in expected_fields_dict:
536
+ raise TypeTransformerFailedError(
537
+ f"Field '{f.name}' is not present in the expected dataclass fields {expected_type.__name__}"
538
+ )
539
+ expected_type = expected_fields_dict[f.name]
540
+
541
+ if UnionTransformer.is_optional_type(original_type):
542
+ original_type = UnionTransformer.get_sub_type_in_optional(original_type)
543
+ if UnionTransformer.is_optional_type(expected_type):
544
+ expected_type = UnionTransformer.get_sub_type_in_optional(expected_type)
545
+
546
+ val = v.__getattribute__(f.name)
547
+ if dataclasses.is_dataclass(val):
548
+ self.assert_type(expected_type, val)
549
+ elif original_type != expected_type:
550
+ raise TypeTransformerFailedError(
551
+ f"Type of Val '{original_type}' is not an instance of {expected_type}"
552
+ )
553
+
554
+ def get_literal_type(self, t: Type[T]) -> LiteralType:
555
+ """
556
+ Extracts the Literal type definition for a Dataclass and returns a type Struct.
557
+ If possible also extracts the JSONSchema for the dataclass.
558
+ """
559
+
560
+ if is_annotated(t):
561
+ args = get_args(t)
562
+ logger.info(f"These annotations will be skipped for dataclasses = {args[1:]}")
563
+ # Drop all annotations and handle only the dataclass type passed in.
564
+ t = args[0]
565
+
566
+ schema = None
567
+ try:
568
+ # This produce JSON SCHEMA draft 2020-12
569
+ from mashumaro.jsonschema import build_json_schema
570
+
571
+ schema = build_json_schema(
572
+ self._get_origin_type_in_annotation(t), plugins=[PydanticSchemaPlugin()]
573
+ ).to_dict()
574
+ except Exception as e:
575
+ logger.error(
576
+ f"Failed to extract schema for object {t}, error: {e}\n"
577
+ f"Possibly remove `DataClassJsonMixin` and `dataclass_json` decorator from dataclass declaration"
578
+ )
579
+
580
+ meta_struct = struct_pb2.Struct()
581
+ meta_struct.update(
582
+ {
583
+ CACHE_KEY_METADATA: {
584
+ SERIALIZATION_FORMAT: MESSAGEPACK,
585
+ }
586
+ }
587
+ )
588
+
589
+ # The type engine used to publish the type `structure` for attribute access. As of v2, this is no longer needed.
590
+ return types_pb2.LiteralType(
591
+ simple=types_pb2.SimpleType.STRUCT,
592
+ metadata=schema,
593
+ annotation=TypeAnnotation(annotations=meta_struct),
594
+ )
595
+
596
+ async def to_literal(self, python_val: T, python_type: Type[T], expected: LiteralType) -> Literal:
597
+ if isinstance(python_val, dict):
598
+ msgpack_bytes = msgpack.dumps(python_val)
599
+ return Literal(scalar=Scalar(binary=Binary(value=msgpack_bytes, tag=MESSAGEPACK)))
600
+
601
+ if not dataclasses.is_dataclass(python_val):
602
+ raise TypeTransformerFailedError(
603
+ f"{type(python_val)} is not of type @dataclass, only Dataclasses are supported for "
604
+ f"user defined datatypes in Flytekit"
605
+ )
606
+
607
+ # The function looks up or creates a MessagePackEncoder specifically designed for the object's type.
608
+ # This encoder is then used to convert a data class into MessagePack Bytes.
609
+ try:
610
+ encoder = self._msgpack_encoder[python_type]
611
+ except KeyError:
612
+ encoder = MessagePackEncoder(python_type)
613
+ self._msgpack_encoder[python_type] = encoder
614
+
615
+ try:
616
+ msgpack_bytes = encoder.encode(python_val)
617
+ except NotImplementedError:
618
+ # you can refer FlyteFile, FlyteDirectory and StructuredDataset to see how flyte types can be implemented.
619
+ raise NotImplementedError(
620
+ f"{python_type} should inherit from mashumaro.types.SerializableType"
621
+ f" and implement _serialize and _deserialize methods."
622
+ )
623
+
624
+ return Literal(scalar=Scalar(binary=Binary(value=msgpack_bytes, tag=MESSAGEPACK)))
625
+
626
+ def _get_origin_type_in_annotation(self, python_type: Type[T]) -> Type[T]:
627
+ # dataclass will try to hash a python type when calling dataclass.schema(), but some types in the annotation are
628
+ # not hashable, such as Annotated[StructuredDataset, kwtypes(...)]. Therefore, we should just extract the origin
629
+ # type from annotated.
630
+ if get_origin(python_type) is list:
631
+ return typing.List[self._get_origin_type_in_annotation(get_args(python_type)[0])] # type: ignore
632
+ elif get_origin(python_type) is dict:
633
+ return typing.Dict[ # type: ignore
634
+ self._get_origin_type_in_annotation(get_args(python_type)[0]),
635
+ self._get_origin_type_in_annotation(get_args(python_type)[1]),
636
+ ]
637
+ elif is_annotated(python_type):
638
+ return get_args(python_type)[0]
639
+ elif dataclasses.is_dataclass(python_type):
640
+ for field in dataclasses.fields(copy.deepcopy(python_type)):
641
+ field.type = self._get_origin_type_in_annotation(cast(type, field.type))
642
+ return python_type
643
+
644
+ def from_binary_idl(self, binary_idl_object: Binary, expected_python_type: Type[T]) -> T:
645
+ if binary_idl_object.tag == MESSAGEPACK:
646
+ if issubclass(expected_python_type, DataClassJSONMixin):
647
+ dict_obj = msgpack.loads(binary_idl_object.value, strict_map_key=False)
648
+ json_str = json.dumps(dict_obj)
649
+ dc = expected_python_type.from_json(json_str) # type: ignore
650
+ else:
651
+ try:
652
+ decoder = self._msgpack_decoder[expected_python_type]
653
+ except KeyError:
654
+ decoder = MessagePackDecoder(expected_python_type, pre_decoder_func=_default_msgpack_decoder)
655
+ self._msgpack_decoder[expected_python_type] = decoder
656
+ dc = decoder.decode(binary_idl_object.value)
657
+
658
+ return cast(T, dc)
659
+ else:
660
+ raise TypeTransformerFailedError(f"Unsupported binary format: `{binary_idl_object.tag}`")
661
+
662
+ async def to_python_value(self, lv: Literal, expected_python_type: Type[T]) -> T:
663
+ if not dataclasses.is_dataclass(expected_python_type):
664
+ raise TypeTransformerFailedError(
665
+ f"{expected_python_type} is not of type @dataclass, only Dataclasses are supported for "
666
+ "user defined datatypes in Flytekit"
667
+ )
668
+
669
+ if lv.HasField("scalar") and lv.scalar.HasField("binary"):
670
+ return self.from_binary_idl(lv.scalar.binary, expected_python_type) # type: ignore
671
+
672
+ # todo: revisit this, it should always be a binary in v2.
673
+ json_str = _json_format.MessageToJson(lv.scalar.generic)
674
+
675
+ # The `from_json` function is provided from mashumaro's `DataClassJSONMixin`.
676
+ # It deserializes a JSON string into a data class, and supports additional functionality over JSONDecoder
677
+ # We can't use hasattr(expected_python_type, "from_json") here because we rely on mashumaro's API to
678
+ # customize the deserialization behavior for Flyte types.
679
+ if issubclass(expected_python_type, DataClassJSONMixin):
680
+ dc = expected_python_type.from_json(json_str) # type: ignore
681
+ else:
682
+ # The function looks up or creates a JSONDecoder specifically designed for the object's type.
683
+ # This decoder is then used to convert a JSON string into a data class.
684
+ try:
685
+ decoder = self._json_decoder[expected_python_type]
686
+ except KeyError:
687
+ decoder = JSONDecoder(expected_python_type)
688
+ self._json_decoder[expected_python_type] = decoder
689
+
690
+ dc = decoder.decode(json_str)
691
+
692
+ return cast(T, dc)
693
+
694
+ # This ensures that calls with the same literal type returns the same dataclass. For example, `pyflyte run``
695
+ # command needs to call guess_python_type to get the TypeEngine-derived dataclass. Without caching here, separate
696
+ # calls to guess_python_type would result in a logically equivalent (but new) dataclass, which
697
+ # TypeEngine.assert_type would not be happy about.
698
+ def guess_python_type(self, literal_type: LiteralType) -> Type[T]: # type: ignore
699
+ if literal_type.simple == SimpleType.STRUCT:
700
+ if literal_type.HasField("metadata"):
701
+ from google.protobuf import json_format
702
+
703
+ metadata = json_format.MessageToDict(literal_type.metadata)
704
+ if TITLE in metadata:
705
+ schema_name = metadata[TITLE]
706
+ return convert_mashumaro_json_schema_to_python_class(metadata, schema_name)
707
+ raise ValueError(f"Dataclass transformer cannot reverse {literal_type}")
708
+
709
+
710
+ class ProtobufTransformer(TypeTransformer[Message]):
711
+ PB_FIELD_KEY = "pb_type"
712
+
713
+ def __init__(self):
714
+ super().__init__("Protobuf-Transformer", Message)
715
+
716
+ @staticmethod
717
+ def tag(expected_python_type: Type[T]) -> str:
718
+ return f"{expected_python_type.__module__}.{expected_python_type.__name__}"
719
+
720
+ def get_literal_type(self, t: Type[T]) -> LiteralType:
721
+ return LiteralType(simple=SimpleType.STRUCT, metadata={ProtobufTransformer.PB_FIELD_KEY: self.tag(t)})
722
+
723
+ async def to_literal(self, python_val: T, python_type: Type[T], expected: LiteralType) -> Literal:
724
+ """
725
+ Convert the protobuf struct to literal.
726
+
727
+ This conversion supports two types of python_val:
728
+ 1. google.protobuf.struct_pb2.Struct: A dictionary-like message
729
+ 2. google.protobuf.struct_pb2.ListValue: An ordered collection of values
730
+
731
+ For details, please refer to the following issue:
732
+ https://github.com/flyteorg/flyte/issues/5959
733
+
734
+ Because the remote handling works without errors, we implement conversion with the logic as below:
735
+ https://github.com/flyteorg/flyte/blob/a87585ab7cbb6a047c76d994b3f127c4210070fd/flytepropeller/pkg/controller/nodes/attr_path_resolver.go#L72-L106
736
+ """
737
+ try:
738
+ if type(python_val) is struct_pb2.ListValue:
739
+ literals = []
740
+ for v in python_val:
741
+ literal_type = TypeEngine.to_literal_type(type(v))
742
+ # Recursively convert python native values to literals
743
+ literal = await TypeEngine.to_literal(v, type(v), literal_type)
744
+ literals.append(literal)
745
+ return Literal(collection=LiteralCollection(literals=literals))
746
+ else:
747
+ struct = struct_pb2.Struct()
748
+ struct.update(_MessageToDict(cast(Message, python_val)))
749
+ return Literal(scalar=Scalar(generic=struct))
750
+ except Exception:
751
+ raise TypeTransformerFailedError("Failed to convert to generic protobuf struct")
752
+
753
+ async def to_python_value(self, lv: Literal, expected_python_type: Type[T]) -> T:
754
+ if not (lv and lv.HasField("scalar") and lv.scalar.HasField("generic")):
755
+ raise TypeTransformerFailedError("Can only convert a generic literal to a Protobuf")
756
+
757
+ pb_obj = expected_python_type()
758
+ dictionary = _MessageToDict(lv.scalar.generic)
759
+ pb_obj = _ParseDict(dictionary, pb_obj) # type: ignore
760
+ return pb_obj
761
+
762
+ def guess_python_type(self, literal_type: LiteralType) -> Type[T]:
763
+ # avoid loading
764
+ raise ValueError(f"Transformer {self} cannot reverse {literal_type}")
765
+
766
+
767
+ class EnumTransformer(TypeTransformer[enum.Enum]):
768
+ """
769
+ Enables converting a python type enum.Enum to LiteralType.EnumType
770
+ """
771
+
772
+ def __init__(self):
773
+ super().__init__(name="DefaultEnumTransformer", t=enum.Enum)
774
+
775
+ def get_literal_type(self, t: Type[T]) -> LiteralType:
776
+ if is_annotated(t):
777
+ raise ValueError(
778
+ f"Flytekit does not currently have support \
779
+ for FlyteAnnotations applied to enums. {t} cannot be \
780
+ parsed."
781
+ )
782
+
783
+ values = [v.value for v in t] # type: ignore
784
+ if not isinstance(values[0], str):
785
+ raise TypeTransformerFailedError("Only EnumTypes with value of string are supported")
786
+ return LiteralType(enum_type=types_pb2.EnumType(values=values))
787
+
788
+ async def to_literal(self, python_val: enum.Enum, python_type: Type[T], expected: LiteralType) -> Literal:
789
+ if isinstance(python_val, str):
790
+ # this is the case when python Literals are used as enums
791
+ if python_val not in expected.enum_type.values:
792
+ raise TypeTransformerFailedError(
793
+ f"Value {python_val} is not valid value, expected - {expected.enum_type.values}"
794
+ )
795
+ return Literal(scalar=Scalar(primitive=Primitive(string_value=python_val))) # type: ignore
796
+ if type(python_val).__class__ != enum.EnumMeta:
797
+ raise TypeTransformerFailedError("Expected an enum")
798
+ if type(python_val.value) is not str:
799
+ raise TypeTransformerFailedError("Only string-valued enums are supported")
800
+
801
+ return Literal(scalar=Scalar(primitive=Primitive(string_value=python_val.value))) # type: ignore
802
+
803
+ async def to_python_value(self, lv: Literal, expected_python_type: Type[T]) -> T:
804
+ if lv.HasField("scalar") and lv.scalar.HasField("binary"):
805
+ return self.from_binary_idl(lv.scalar.binary, expected_python_type) # type: ignore
806
+ from flyte._interface import LITERAL_ENUM
807
+
808
+ if expected_python_type.__name__ is LITERAL_ENUM:
809
+ # This is the case when python Literal types are used as enums. The class name is always LiteralEnum an
810
+ # hardcoded in flyte.models
811
+ return lv.scalar.primitive.string_value
812
+ return expected_python_type(lv.scalar.primitive.string_value) # type: ignore
813
+
814
+ def guess_python_type(self, literal_type: LiteralType) -> Type[enum.Enum]:
815
+ if literal_type.HasField("enum_type"):
816
+ return enum.Enum("DynamicEnum", {f"{i}": i for i in literal_type.enum_type.values}) # type: ignore
817
+ raise ValueError(f"Enum transformer cannot reverse {literal_type}")
818
+
819
+ def assert_type(self, t: Type[enum.Enum], v: T):
820
+ val = v.value if isinstance(v, enum.Enum) else v
821
+ if val not in [t_item.value for t_item in t]:
822
+ raise TypeTransformerFailedError(f"Value {v} is not in Enum {t}")
823
+
824
+
825
+ def generate_attribute_list_from_dataclass_json_mixin(schema: dict, schema_name: typing.Any):
826
+ from flyte.io._dir import Dir
827
+ from flyte.io._file import File
828
+
829
+ attribute_list: typing.List[typing.Tuple[Any, Any]] = []
830
+ for property_key, property_val in schema["properties"].items():
831
+ if property_val.get("anyOf"):
832
+ property_type = property_val["anyOf"][0]["type"]
833
+ elif property_val.get("enum"):
834
+ property_type = "enum"
835
+ else:
836
+ property_type = property_val["type"]
837
+ # Handle list
838
+ if property_type == "array":
839
+ attribute_list.append((property_key, typing.List[_get_element_type(property_val["items"])])) # type: ignore
840
+ # Handle dataclass and dict
841
+ elif property_type == "object":
842
+ if property_val.get("anyOf"):
843
+ # For optional with dataclass
844
+ sub_schemea = property_val["anyOf"][0]
845
+ sub_schemea_name = sub_schemea["title"]
846
+ if File.schema_match(property_val):
847
+ attribute_list.append(
848
+ (
849
+ property_key,
850
+ typing.cast(
851
+ GenericAlias,
852
+ File,
853
+ ),
854
+ )
855
+ )
856
+ continue
857
+ elif Dir.schema_match(property_val):
858
+ attribute_list.append(
859
+ (
860
+ property_key,
861
+ typing.cast(
862
+ GenericAlias,
863
+ Dir,
864
+ ),
865
+ )
866
+ )
867
+ continue
868
+ attribute_list.append(
869
+ (
870
+ property_key,
871
+ typing.cast(
872
+ GenericAlias, convert_mashumaro_json_schema_to_python_class(sub_schemea, sub_schemea_name)
873
+ ),
874
+ )
875
+ )
876
+ elif property_val.get("additionalProperties"):
877
+ # For typing.Dict type
878
+ elem_type = _get_element_type(property_val["additionalProperties"])
879
+ attribute_list.append((property_key, typing.Dict[str, elem_type])) # type: ignore
880
+ elif property_val.get("title"):
881
+ # For nested dataclass
882
+ sub_schemea_name = property_val["title"]
883
+ # Check Flyte offloaded types
884
+ if File.schema_match(property_val):
885
+ attribute_list.append(
886
+ (
887
+ property_key,
888
+ typing.cast(
889
+ GenericAlias,
890
+ File,
891
+ ),
892
+ )
893
+ )
894
+ continue
895
+ elif Dir.schema_match(property_val):
896
+ attribute_list.append(
897
+ (
898
+ property_key,
899
+ typing.cast(
900
+ GenericAlias,
901
+ Dir,
902
+ ),
903
+ )
904
+ )
905
+ continue
906
+ attribute_list.append(
907
+ (
908
+ property_key,
909
+ typing.cast(
910
+ GenericAlias, convert_mashumaro_json_schema_to_python_class(property_val, sub_schemea_name)
911
+ ),
912
+ )
913
+ )
914
+ else:
915
+ # For untyped dict
916
+ attribute_list.append((property_key, dict)) # type: ignore
917
+ elif property_type == "enum":
918
+ attribute_list.append([property_key, str]) # type: ignore
919
+ # Handle int, float, bool or str
920
+ else:
921
+ attribute_list.append([property_key, _get_element_type(property_val)]) # type: ignore
922
+ return attribute_list
923
+
924
+
925
+ class TypeEngine(typing.Generic[T]):
926
+ """
927
+ Core Extensible TypeEngine of Flytekit. This should be used to extend the capabilities of FlyteKits type system.
928
+ Users can implement their own TypeTransformers and register them with the TypeEngine. This will allow special
929
+ handling
930
+ of user objects
931
+ """
932
+
933
+ _REGISTRY: typing.ClassVar[typing.Dict[type, TypeTransformer]] = {}
934
+ _RESTRICTED_TYPES: typing.ClassVar[typing.List[type]] = []
935
+ _DATACLASS_TRANSFORMER: typing.ClassVar[TypeTransformer] = DataclassTransformer()
936
+ _ENUM_TRANSFORMER: typing.ClassVar[TypeTransformer] = EnumTransformer()
937
+ lazy_import_lock: typing.ClassVar[threading.Lock] = threading.Lock()
938
+
939
+ @classmethod
940
+ def register(
941
+ cls,
942
+ transformer: TypeTransformer,
943
+ additional_types: Optional[typing.List[Type]] = None,
944
+ ):
945
+ """
946
+ This should be used for all types that respond with the right type annotation when you use type(...) function
947
+ """
948
+ types = [transformer.python_type, *(additional_types or [])]
949
+ for t in types:
950
+ if t in cls._REGISTRY:
951
+ existing = cls._REGISTRY[t]
952
+ raise ValueError(
953
+ f"Transformer {existing.name} for type {t} is already registered."
954
+ f" Cannot override with {transformer.name}"
955
+ )
956
+ cls._REGISTRY[t] = transformer
957
+
958
+ @classmethod
959
+ def register_restricted_type(
960
+ cls,
961
+ name: str,
962
+ type: Type[T],
963
+ ):
964
+ cls._RESTRICTED_TYPES.append(type)
965
+ cls.register(RestrictedTypeTransformer(name, type)) # type: ignore
966
+
967
+ @classmethod
968
+ def register_additional_type(cls, transformer: TypeTransformer[T], additional_type: Type[T], override=False):
969
+ if additional_type not in cls._REGISTRY or override:
970
+ cls._REGISTRY[additional_type] = transformer
971
+
972
+ @classmethod
973
+ def _get_transformer(cls, python_type: Type) -> Optional[TypeTransformer[T]]:
974
+ cls.lazy_import_transformers()
975
+ if is_annotated(python_type):
976
+ args = get_args(python_type)
977
+ for annotation in args:
978
+ if isinstance(annotation, TypeTransformer):
979
+ return annotation
980
+ return cls.get_transformer(args[0])
981
+
982
+ if inspect.isclass(python_type) and issubclass(python_type, enum.Enum):
983
+ # Special case: prevent that for a type `FooEnum(str, Enum)`, the str transformer is used.
984
+ return cls._ENUM_TRANSFORMER
985
+
986
+ if hasattr(python_type, "__origin__"):
987
+ # If the type is a generic type, we should check the origin type. But consider the case like Iterator[JSON]
988
+ # or List[int] has been specifically registered; we should check for the entire type.
989
+ # The challenge is for StructuredDataset, example List[StructuredDataset] the column names is an OrderedDict
990
+ # are not hashable, thus looking up this type is not possible.
991
+ # In such as case, we will have to skip the "type" lookup and use the origin type only
992
+ try:
993
+ if python_type in cls._REGISTRY:
994
+ return cls._REGISTRY[python_type]
995
+ except TypeError:
996
+ pass
997
+ if python_type.__origin__ in cls._REGISTRY:
998
+ return cls._REGISTRY[python_type.__origin__]
999
+
1000
+ # Handling UnionType specially - PEP 604
1001
+ import types
1002
+
1003
+ if isinstance(python_type, types.UnionType):
1004
+ return cls._REGISTRY[types.UnionType]
1005
+
1006
+ if python_type in cls._REGISTRY:
1007
+ return cls._REGISTRY[python_type]
1008
+
1009
+ return None
1010
+
1011
+ @classmethod
1012
+ def get_transformer(cls, python_type: Type) -> TypeTransformer:
1013
+ """
1014
+ Implements a recursive search for the transformer.
1015
+ """
1016
+ v = cls._get_transformer(python_type)
1017
+ if v is not None:
1018
+ return v
1019
+
1020
+ if hasattr(python_type, "__mro__"):
1021
+ class_tree = inspect.getmro(python_type)
1022
+ for t in class_tree:
1023
+ v = cls._get_transformer(t)
1024
+ if v is not None:
1025
+ return v
1026
+
1027
+ # dataclass type transformer is left for last to give users a chance to register a type transformer
1028
+ # to handle dataclass-like objects as part of the mro evaluation.
1029
+ #
1030
+ # NB: keep in mind that there are no compatibility guarantees between these user-defined dataclass transformers
1031
+ # and the flytekit one. This incompatibility is *not* a new behavior introduced by the recent type engine
1032
+ # refactor (https://github.com/flyteorg/flytekit/pull/2815), but it is worth calling out explicitly as a known
1033
+ # limitation nonetheless.
1034
+ if dataclasses.is_dataclass(python_type):
1035
+ return cls._DATACLASS_TRANSFORMER
1036
+
1037
+ display_pickle_warning(str(python_type))
1038
+ from flyte.types._pickle import FlytePickleTransformer
1039
+
1040
+ return FlytePickleTransformer()
1041
+
1042
+ @classmethod
1043
+ def lazy_import_transformers(cls):
1044
+ """
1045
+ Only load the transformers if needed.
1046
+ """
1047
+ with cls.lazy_import_lock:
1048
+ # Avoid a race condition where concurrent threads may exit lazy_import_transformers before the transformers
1049
+ # have been imported. This could be implemented without a lock if you assume python assignments are atomic
1050
+ # and re-registering transformers is acceptable, but I decided to play it safe.
1051
+ from flyte.io import lazy_import_dataframe_handler
1052
+
1053
+ # todo: bring in extras transformers (pytorch, etc.)
1054
+ lazy_import_dataframe_handler()
1055
+
1056
+ @classmethod
1057
+ def to_literal_type(cls, python_type: Type[T]) -> LiteralType:
1058
+ """
1059
+ Converts a python type into a flyte specific ``LiteralType``
1060
+ """
1061
+ transformer = cls.get_transformer(python_type)
1062
+ res = transformer.get_literal_type(python_type)
1063
+ return res
1064
+
1065
+ @classmethod
1066
+ def to_literal_checks(cls, python_val: typing.Any, python_type: Type[T], expected: LiteralType):
1067
+ if isinstance(python_val, tuple):
1068
+ raise AssertionError(
1069
+ "Tuples are not a supported type for individual values in Flyte - got a tuple -"
1070
+ f" {python_val}. If using named tuple in an inner task, please, de-reference the"
1071
+ "actual attribute that you want to use. For example, in NamedTuple('OP', x=int) then"
1072
+ "return v.x, instead of v, even if this has a single element"
1073
+ )
1074
+ if (
1075
+ (python_val is None and python_type is not type(None))
1076
+ and expected
1077
+ and expected.union_type is None
1078
+ and python_type is not Any
1079
+ ):
1080
+ raise TypeTransformerFailedError(f"Python value cannot be None, expected {python_type}/{expected}")
1081
+
1082
+ @classmethod
1083
+ async def to_literal(
1084
+ cls, python_val: typing.Any, python_type: Type[T], expected: types_pb2.LiteralType
1085
+ ) -> literals_pb2.Literal:
1086
+ transformer = cls.get_transformer(python_type)
1087
+
1088
+ if transformer.type_assertions_enabled:
1089
+ transformer.assert_type(python_type, python_val)
1090
+
1091
+ lv = await transformer.to_literal(python_val, python_type, expected)
1092
+
1093
+ modify_literal_uris(lv)
1094
+ return lv
1095
+
1096
+ @classmethod
1097
+ async def unwrap_offloaded_literal(cls, lv: literals_pb2.Literal) -> literals_pb2.Literal:
1098
+ if not lv.HasField("offloaded_metadata"):
1099
+ return lv
1100
+
1101
+ literal_local_file = storage.get_random_local_path()
1102
+ assert lv.offloaded_metadata.uri, "missing offloaded uri"
1103
+ await storage.get(lv.offloaded_metadata.uri, str(literal_local_file))
1104
+ input_proto = load_proto_from_file(literals_pb2.Literal, literal_local_file)
1105
+ return input_proto
1106
+
1107
+ @classmethod
1108
+ async def to_python_value(cls, lv: Literal, expected_python_type: Type) -> typing.Any:
1109
+ """
1110
+ Converts a Literal value with an expected python type into a python value.
1111
+ """
1112
+ # Initiate the process of loading the offloaded literal if offloaded_metadata is set
1113
+ if lv.HasField("offloaded_metadata"):
1114
+ lv = await cls.unwrap_offloaded_literal(lv)
1115
+
1116
+ transformer = cls.get_transformer(expected_python_type)
1117
+ res = await transformer.to_python_value(lv, expected_python_type)
1118
+ return res
1119
+
1120
+ @classmethod
1121
+ def to_html(cls, python_val: typing.Any, expected_python_type: Type[typing.Any]) -> str:
1122
+ transformer = cls.get_transformer(expected_python_type)
1123
+ if is_annotated(expected_python_type):
1124
+ expected_python_type, *annotate_args = get_args(expected_python_type)
1125
+ from flyte.types._renderer import Renderable
1126
+
1127
+ for arg in annotate_args:
1128
+ if isinstance(arg, Renderable):
1129
+ return arg.to_html(python_val)
1130
+ return transformer.to_html(python_val, expected_python_type)
1131
+
1132
+ @classmethod
1133
+ def named_tuple_to_variable_map(cls, t: typing.NamedTuple) -> interface_pb2.VariableMap:
1134
+ """
1135
+ Converts a python-native ``NamedTuple`` to a flyte-specific VariableMap of named literals.
1136
+ """
1137
+ variables = {}
1138
+ for idx, (var_name, var_type) in enumerate(t.__annotations__.items()):
1139
+ literal_type = cls.to_literal_type(var_type)
1140
+ variables[var_name] = interface_pb2.Variable(type=literal_type, description=f"{idx}")
1141
+ return interface_pb2.VariableMap(variables=variables)
1142
+
1143
+ @classmethod
1144
+ async def literal_map_to_kwargs(
1145
+ cls,
1146
+ lm: LiteralMap,
1147
+ python_types: typing.Optional[typing.Dict[str, type]] = None,
1148
+ literal_types: typing.Optional[typing.Dict[str, interface_pb2.Variable]] = None,
1149
+ ) -> typing.Dict[str, typing.Any]:
1150
+ """
1151
+ Given a ``LiteralMap`` (usually an input into a task - intermediate), convert to kwargs for the task
1152
+ """
1153
+ if python_types is None and literal_types is None:
1154
+ raise ValueError("At least one of python_types or literal_types must be provided")
1155
+
1156
+ if literal_types:
1157
+ python_interface_inputs: dict[str, Type[T]] = {
1158
+ name: TypeEngine.guess_python_type(lt.type) for name, lt in literal_types.items()
1159
+ }
1160
+ else:
1161
+ python_interface_inputs = python_types # type: ignore
1162
+
1163
+ if not python_interface_inputs or len(python_interface_inputs) == 0:
1164
+ return {}
1165
+
1166
+ if len(lm.literals) > len(python_interface_inputs):
1167
+ raise ValueError(
1168
+ f"Received more input values {len(lm.literals)}"
1169
+ f" than allowed by the input spec {len(python_interface_inputs)}"
1170
+ )
1171
+ # Create tasks for converting each kwarg
1172
+ tasks = {}
1173
+ for k in lm.literals:
1174
+ tasks[k] = asyncio.create_task(TypeEngine.to_python_value(lm.literals[k], python_interface_inputs[k]))
1175
+
1176
+ # Gather all tasks, returning exceptions instead of raising them
1177
+ results = await asyncio.gather(*tasks.values(), return_exceptions=True)
1178
+
1179
+ # Check for exceptions and raise with specific kwarg name
1180
+ kwargs = {}
1181
+ for (key, task), result in zip(tasks.items(), results):
1182
+ if isinstance(result, Exception):
1183
+ raise TypeTransformerFailedError(
1184
+ f"Error converting input '{key}':\n"
1185
+ f"Literal value: {lm.literals[key]}\n"
1186
+ f"Expected Python type: {python_interface_inputs[key]}\n"
1187
+ f"Exception: {result}"
1188
+ ) from result
1189
+ kwargs[key] = result
1190
+
1191
+ return kwargs
1192
+
1193
+ @classmethod
1194
+ async def dict_to_literal_map(
1195
+ cls,
1196
+ d: typing.Dict[str, typing.Any],
1197
+ type_hints: Optional[typing.Dict[str, type]] = None,
1198
+ ) -> LiteralMap:
1199
+ """
1200
+ Given a dictionary mapping string keys to python values and a dictionary containing guessed types for such
1201
+ string keys,
1202
+ convert to a LiteralMap.
1203
+ """
1204
+ type_hints = type_hints or {}
1205
+ literal_map = {}
1206
+ for k, v in d.items():
1207
+ # The guessed type takes precedence over the type returned by the python runtime. This is needed
1208
+ # to account for the type erasure that happens in the case of built-in collection containers, such as
1209
+ # `list` and `dict`.
1210
+ python_type = type_hints.get(k, type(v))
1211
+ literal_map[k] = asyncio.create_task(
1212
+ TypeEngine.to_literal(
1213
+ python_val=v,
1214
+ python_type=python_type,
1215
+ expected=TypeEngine.to_literal_type(python_type),
1216
+ )
1217
+ )
1218
+ await asyncio.gather(*literal_map.values(), return_exceptions=True)
1219
+ for idx, (k, v) in enumerate(literal_map.items()):
1220
+ if literal_map[k].exception() is not None:
1221
+ python_type = type_hints.get(k, type(d[k]))
1222
+ e: BaseException = literal_map[k].exception() # type: ignore
1223
+ if isinstance(e, TypeError):
1224
+ raise TypeError(
1225
+ f"Error converting: Var:{k}, type:{type(d[k])}, into:{python_type}, received_value {d[k]}"
1226
+ )
1227
+ else:
1228
+ raise e
1229
+ literal_map[k] = v.result()
1230
+
1231
+ return LiteralMap(literals=literal_map)
1232
+
1233
+ @classmethod
1234
+ def get_available_transformers(cls) -> typing.KeysView[Type]:
1235
+ """
1236
+ Returns all python types for which transformers are available
1237
+ """
1238
+ return cls._REGISTRY.keys()
1239
+
1240
+ @classmethod
1241
+ def guess_python_types(
1242
+ cls, flyte_variable_dict: typing.Dict[str, interface_pb2.Variable]
1243
+ ) -> typing.Dict[str, Type[Any]]:
1244
+ """
1245
+ Transforms a dictionary of flyte-specific ``Variable`` objects to a dictionary of regular python values.
1246
+ """
1247
+ python_types = {}
1248
+ for k, v in flyte_variable_dict.items():
1249
+ python_types[k] = cls.guess_python_type(v.type)
1250
+ return python_types
1251
+
1252
+ @classmethod
1253
+ def guess_python_type(cls, flyte_type: LiteralType) -> Type[T]:
1254
+ """
1255
+ Transforms a flyte-specific ``LiteralType`` to a regular python value.
1256
+ """
1257
+ for _, transformer in cls._REGISTRY.items():
1258
+ try:
1259
+ return transformer.guess_python_type(flyte_type)
1260
+ except ValueError:
1261
+ # Skipping transformer
1262
+ continue
1263
+
1264
+ # Because the dataclass transformer is handled explicitly in the get_transformer code, we have to handle it
1265
+ # separately here too.
1266
+ try:
1267
+ return cls._DATACLASS_TRANSFORMER.guess_python_type(literal_type=flyte_type)
1268
+ except ValueError:
1269
+ logger.debug(f"Skipping transformer {cls._DATACLASS_TRANSFORMER.name} for {flyte_type}")
1270
+ raise ValueError(f"No transformers could reverse Flyte literal type {flyte_type}")
1271
+
1272
+
1273
+ class ListTransformer(TypeTransformer[T]):
1274
+ """
1275
+ Transformer that handles a univariate typing.List[T]
1276
+ """
1277
+
1278
+ def __init__(self):
1279
+ super().__init__("Typed List", list)
1280
+
1281
+ @staticmethod
1282
+ def get_sub_type(t: Type[T]) -> Type[T]:
1283
+ """
1284
+ Return the generic Type T of the List
1285
+ """
1286
+ if (sub_type := ListTransformer.get_sub_type_or_none(t)) is not None:
1287
+ return sub_type
1288
+
1289
+ raise ValueError("Only generic univariate typing.List[T] type is supported.")
1290
+
1291
+ @staticmethod
1292
+ def get_sub_type_or_none(t: Type[T]) -> Optional[Type[T]]:
1293
+ """
1294
+ Return the generic Type T of the List, or None if the generic type cannot be inferred
1295
+ """
1296
+ if hasattr(t, "__origin__"):
1297
+ # Handle annotation on list generic, eg:
1298
+ # Annotated[typing.List[int], 'foo']
1299
+ if is_annotated(t):
1300
+ return ListTransformer.get_sub_type(get_args(t)[0])
1301
+
1302
+ if getattr(t, "__origin__") is list and hasattr(t, "__args__"):
1303
+ return getattr(t, "__args__")[0]
1304
+
1305
+ return None
1306
+
1307
+ def get_literal_type(self, t: Type[T]) -> Optional[types_pb2.LiteralType]:
1308
+ """
1309
+ Only univariate Lists are supported in Flyte
1310
+ """
1311
+ try:
1312
+ sub_type = TypeEngine.to_literal_type(self.get_sub_type(t))
1313
+ return types_pb2.LiteralType(collection_type=sub_type)
1314
+ except Exception as e:
1315
+ raise ValueError(f"Type of Generic List type is not supported, {e}")
1316
+
1317
+ async def to_literal(self, python_val: T, python_type: Type[T], expected: LiteralType) -> Literal:
1318
+ if type(python_val) is not list:
1319
+ raise TypeTransformerFailedError("Expected a list")
1320
+
1321
+ t = self.get_sub_type(python_type)
1322
+ lit_list = [TypeEngine.to_literal(x, t, expected.collection_type) for x in python_val]
1323
+
1324
+ lit_list = await _run_coros_in_chunks(lit_list, batch_size=_TYPE_ENGINE_COROS_BATCH_SIZE)
1325
+
1326
+ return Literal(collection=LiteralCollection(literals=lit_list))
1327
+
1328
+ async def to_python_value( # type: ignore
1329
+ self, lv: Literal, expected_python_type: Type[T]
1330
+ ) -> typing.Optional[typing.List[T]]:
1331
+ if lv and lv.HasField("scalar") and lv.scalar.HasField("binary"):
1332
+ return self.from_binary_idl(lv.scalar.binary, expected_python_type) # type: ignore
1333
+
1334
+ try:
1335
+ lits = lv.collection.literals
1336
+ except AttributeError:
1337
+ raise TypeTransformerFailedError(
1338
+ (
1339
+ f"The expected python type is '{expected_python_type}' but the received Flyte literal value "
1340
+ f"is not a collection (Flyte's representation of Python lists)."
1341
+ )
1342
+ )
1343
+
1344
+ st = self.get_sub_type(expected_python_type)
1345
+ result = [TypeEngine.to_python_value(x, st) for x in lits]
1346
+ result = await _run_coros_in_chunks(result, batch_size=_TYPE_ENGINE_COROS_BATCH_SIZE)
1347
+ return result # type: ignore # should be a list, thinks its a tuple
1348
+
1349
+ def guess_python_type(self, literal_type: types_pb2.LiteralType) -> list: # type: ignore
1350
+ if literal_type.HasField("collection_type"):
1351
+ ct: Type = TypeEngine.guess_python_type(literal_type.collection_type)
1352
+ return typing.List[ct] # type: ignore
1353
+ raise ValueError(f"List transformer cannot reverse {literal_type}")
1354
+
1355
+
1356
+ @lru_cache
1357
+ def display_pickle_warning(python_type: str):
1358
+ # This is a warning that is only displayed once per python type
1359
+ logger.warning(
1360
+ f"Unsupported Type {python_type} found, Flyte will default to use PickleFile as the transport. "
1361
+ f"Pickle can only be used to send objects between the exact same version of Python, "
1362
+ f"and we strongly recommend to use python type that flyte support."
1363
+ )
1364
+
1365
+
1366
+ def _add_tag_to_type(x: types_pb2.LiteralType, tag: str) -> types_pb2.LiteralType:
1367
+ replica = types_pb2.LiteralType()
1368
+ replica.CopyFrom(x)
1369
+ replica.structure.CopyFrom(TypeStructure(tag=tag))
1370
+ return replica
1371
+
1372
+
1373
+ def _type_essence(x: types_pb2.LiteralType) -> types_pb2.LiteralType:
1374
+ if x.HasField("metadata") or x.HasField("structure") or x.HasField("annotation"):
1375
+ x2 = types_pb2.LiteralType()
1376
+ x2.CopyFrom(x)
1377
+ x2.ClearField("metadata")
1378
+ x2.ClearField("structure")
1379
+ x2.ClearField("annotation")
1380
+ return x2
1381
+ return x
1382
+
1383
+
1384
+ def _are_types_castable(upstream: types_pb2.LiteralType, downstream: types_pb2.LiteralType) -> bool:
1385
+ if upstream.union_type is not None:
1386
+ # for each upstream variant, there must be a compatible type downstream
1387
+ for v in upstream.union_type.variants:
1388
+ if not _are_types_castable(v, downstream):
1389
+ return False
1390
+ return True
1391
+
1392
+ if downstream.union_type is not None:
1393
+ # there must be a compatible downstream type
1394
+ for v in downstream.union_type.variants:
1395
+ if _are_types_castable(upstream, v):
1396
+ return True
1397
+
1398
+ if upstream.HasField("collection_type"):
1399
+ if not downstream.HasField("collection_type"):
1400
+ return False
1401
+
1402
+ return _are_types_castable(upstream.collection_type, downstream.collection_type)
1403
+
1404
+ if upstream.HasField("map_value_type"):
1405
+ if not downstream.HasField("map_value_type"):
1406
+ return False
1407
+
1408
+ return _are_types_castable(upstream.map_value_type, downstream.map_value_type)
1409
+
1410
+ # TODO: Structured dataset type matching requires that downstream structured datasets
1411
+ # are a strict sub-set of the upstream structured dataset.
1412
+ if upstream.HasField("structured_dataset_type"):
1413
+ if not downstream.HasField("structured_dataset_type"):
1414
+ return False
1415
+
1416
+ usdt = upstream.structured_dataset_type
1417
+ dsdt = downstream.structured_dataset_type
1418
+
1419
+ if usdt.format != dsdt.format:
1420
+ return False
1421
+
1422
+ if usdt.external_schema_type != dsdt.external_schema_type:
1423
+ return False
1424
+
1425
+ if usdt.external_schema_bytes != dsdt.external_schema_bytes:
1426
+ return False
1427
+
1428
+ ucols = usdt.columns
1429
+ dcols = dsdt.columns
1430
+
1431
+ if len(ucols) != len(dcols):
1432
+ return False
1433
+
1434
+ for u, d in zip(ucols, dcols):
1435
+ if u.name != d.name:
1436
+ return False
1437
+
1438
+ if not _are_types_castable(u.literal_type, d.literal_type):
1439
+ return False
1440
+
1441
+ return True
1442
+
1443
+ if upstream.HasField("union_type") and upstream.union_type is not None:
1444
+ # for each upstream variant, there must be a compatible type downstream
1445
+ for v in upstream.union_type.variants:
1446
+ if not _are_types_castable(v, downstream):
1447
+ return False
1448
+ return True
1449
+
1450
+ if downstream.HasField("union_type"):
1451
+ # there must be a compatible downstream type
1452
+ for v in downstream.union_type.variants:
1453
+ if _are_types_castable(upstream, v):
1454
+ return True
1455
+
1456
+ if upstream.HasField("enum_type"):
1457
+ # enums are castable to string
1458
+ if downstream.simple == SimpleType.STRING:
1459
+ return True
1460
+
1461
+ if _type_essence(upstream) == _type_essence(downstream):
1462
+ return True
1463
+
1464
+ return False
1465
+
1466
+
1467
+ def _is_union_type(t):
1468
+ """Returns True if t is a Union type."""
1469
+
1470
+ if sys.version_info >= (3, 10):
1471
+ import types
1472
+
1473
+ UnionType = types.UnionType
1474
+ else:
1475
+ UnionType = None
1476
+
1477
+ return t is typing.Union or get_origin(t) is typing.Union or (UnionType and isinstance(t, UnionType))
1478
+
1479
+
1480
+ class UnionTransformer(TypeTransformer[T]):
1481
+ """
1482
+ Transformer that handles a typing.Union[T1, T2, ...]
1483
+ """
1484
+
1485
+ def __init__(self):
1486
+ super().__init__("Typed Union", typing.Union)
1487
+
1488
+ @staticmethod
1489
+ def is_optional_type(t: Type[Any]) -> bool:
1490
+ return _is_union_type(t) and type(None) in get_args(t)
1491
+
1492
+ @staticmethod
1493
+ def get_sub_type_in_optional(t: Type[T]) -> Type[T]:
1494
+ """
1495
+ Return the generic Type T of the Optional type
1496
+ """
1497
+ return get_args(t)[0]
1498
+
1499
+ def assert_type(self, t: Type[T], v: T):
1500
+ python_type = get_underlying_type(t)
1501
+ if _is_union_type(python_type):
1502
+ for sub_type in get_args(python_type):
1503
+ if sub_type == typing.Any:
1504
+ # this is an edge case
1505
+ return
1506
+ try:
1507
+ sub_trans: TypeTransformer = TypeEngine.get_transformer(sub_type)
1508
+ if sub_trans.type_assertions_enabled:
1509
+ sub_trans.assert_type(sub_type, v)
1510
+ return
1511
+ else:
1512
+ return
1513
+ except TypeTransformerFailedError:
1514
+ continue
1515
+ except TypeError:
1516
+ continue
1517
+ raise TypeTransformerFailedError(f"Value {v} is not of type {t}")
1518
+
1519
+ def get_literal_type(self, t: Type[T]) -> Optional[types_pb2.LiteralType]:
1520
+ t = get_underlying_type(t)
1521
+
1522
+ try:
1523
+ trans: typing.List[typing.Tuple[TypeTransformer, typing.Any]] = [
1524
+ (TypeEngine.get_transformer(x), x) for x in get_args(t)
1525
+ ]
1526
+ # must go through TypeEngine.to_literal_type instead of trans.get_literal_type
1527
+ # to handle Annotated
1528
+ variants = [_add_tag_to_type(TypeEngine.to_literal_type(x), t.name) for (t, x) in trans]
1529
+ return types_pb2.LiteralType(union_type=UnionType(variants=variants))
1530
+ except Exception as e:
1531
+ raise ValueError(f"Type of Generic Union type is not supported, {e}")
1532
+
1533
+ async def to_literal(
1534
+ self, python_val: T, python_type: Type[T], expected: types_pb2.LiteralType
1535
+ ) -> literals_pb2.Literal:
1536
+ python_type = get_underlying_type(python_type)
1537
+ inferred_type = type(python_val)
1538
+ subtypes = get_args(python_type)
1539
+
1540
+ if inferred_type in subtypes:
1541
+ # If the Python value's type matches one of the types in the Union,
1542
+ # always use the transformer associated with that specific type.
1543
+ transformer = TypeEngine.get_transformer(inferred_type)
1544
+ res = await transformer.to_literal(
1545
+ python_val, inferred_type, expected.union_type.variants[subtypes.index(inferred_type)]
1546
+ )
1547
+ res_type = _add_tag_to_type(transformer.get_literal_type(inferred_type), transformer.name)
1548
+ return Literal(scalar=Scalar(union=Union(value=res, type=res_type)))
1549
+
1550
+ potential_types = []
1551
+ found_res = False
1552
+ is_ambiguous = False
1553
+ res = None
1554
+ res_type = None
1555
+ t = None
1556
+ for i in range(len(subtypes)):
1557
+ try:
1558
+ t = subtypes[i]
1559
+ trans: TypeTransformer[T] = TypeEngine.get_transformer(t)
1560
+ attempt = trans.to_literal(python_val, t, expected.union_type.variants[i])
1561
+ res = await attempt
1562
+ if found_res:
1563
+ logger.debug(f"Current type {subtypes[i]} old res {res_type}")
1564
+ is_ambiguous = True
1565
+ res_type = _add_tag_to_type(trans.get_literal_type(t), trans.name)
1566
+ found_res = True
1567
+ potential_types.append(t)
1568
+ except Exception as e:
1569
+ logger.debug(
1570
+ f"UnionTransformer failed attempt to convert from {python_val} to {t} error: {e}",
1571
+ )
1572
+ continue
1573
+
1574
+ if is_ambiguous:
1575
+ raise TypeError(
1576
+ f"Ambiguous choice of variant for union type.\n"
1577
+ f"Potential types: {potential_types}\n"
1578
+ "These types are structurally the same, because it's attributes have the same names and associated"
1579
+ " types."
1580
+ )
1581
+
1582
+ if found_res:
1583
+ return Literal(scalar=Scalar(union=Union(value=res, type=res_type)))
1584
+
1585
+ raise TypeTransformerFailedError(f"Cannot convert from {python_val} to {python_type}")
1586
+
1587
+ async def to_python_value(self, lv: Literal, expected_python_type: Type[T]) -> Optional[typing.Any]:
1588
+ expected_python_type = get_underlying_type(expected_python_type)
1589
+
1590
+ union_tag = None
1591
+ union_type = None
1592
+ if lv.HasField("scalar") and lv.scalar.HasField("union"):
1593
+ union_type = lv.scalar.union.type
1594
+ if union_type.HasField("structure"):
1595
+ union_tag = union_type.structure.tag
1596
+
1597
+ found_res = False
1598
+ is_ambiguous = False
1599
+ cur_transformer = ""
1600
+ res = None
1601
+ res_tag = None
1602
+ # This is serial, not actually async, but should be okay since it's more reasonable for Unions.
1603
+ for v in get_args(expected_python_type):
1604
+ try:
1605
+ trans: TypeTransformer[T] = TypeEngine.get_transformer(v)
1606
+ if union_tag is not None:
1607
+ if trans.name != union_tag:
1608
+ continue
1609
+
1610
+ expected_literal_type = TypeEngine.to_literal_type(v)
1611
+ if not _are_types_castable(union_type, expected_literal_type):
1612
+ continue
1613
+
1614
+ assert lv.scalar.HasField("union"), f"Literal {lv} is not a union" # type checker
1615
+
1616
+ if lv.scalar.HasField("binary"):
1617
+ res = await trans.to_python_value(lv, v)
1618
+ else:
1619
+ res = await trans.to_python_value(lv.scalar.union.value, v)
1620
+
1621
+ if found_res:
1622
+ is_ambiguous = True
1623
+ cur_transformer = trans.name
1624
+ break
1625
+ else:
1626
+ res = await trans.to_python_value(lv, v)
1627
+ if found_res:
1628
+ is_ambiguous = True
1629
+ cur_transformer = trans.name
1630
+ break
1631
+ res_tag = trans.name
1632
+ found_res = True
1633
+ except Exception as e:
1634
+ logger.debug(f"Failed to convert from {lv} to {v} with error: {e}")
1635
+
1636
+ if is_ambiguous:
1637
+ raise TypeError(
1638
+ f"Ambiguous choice of variant for union type. Both {res_tag} and {cur_transformer} transformers match"
1639
+ )
1640
+
1641
+ if found_res:
1642
+ return res
1643
+
1644
+ raise TypeError(f"Cannot convert from {lv} to {expected_python_type} (using tag {union_tag})")
1645
+
1646
+ def guess_python_type(self, literal_type: LiteralType) -> type:
1647
+ if literal_type.HasField("union_type"):
1648
+ return typing.Union[tuple(TypeEngine.guess_python_type(v) for v in literal_type.union_type.variants)] # type: ignore
1649
+
1650
+ raise ValueError(f"Union transformer cannot reverse {literal_type}")
1651
+
1652
+
1653
+ class DictTransformer(TypeTransformer[dict]):
1654
+ """
1655
+ Transformer that transforms an univariate dictionary Dict[str, T] to a Literal Map or
1656
+ transforms an untyped dictionary to a Binary Scalar Literal with a Struct Literal Type.
1657
+ """
1658
+
1659
+ def __init__(self):
1660
+ super().__init__("Typed Dict", dict)
1661
+
1662
+ @staticmethod
1663
+ def extract_types(t: Optional[Type[dict]]) -> typing.Tuple:
1664
+ if t is None:
1665
+ return None, None
1666
+
1667
+ # Get the origin and type arguments.
1668
+ _origin = get_origin(t)
1669
+ _args = get_args(t)
1670
+
1671
+ # If not annotated or dict, return None, None.
1672
+ if _origin is None:
1673
+ return None, None
1674
+
1675
+ # If this is something like Annotated[dict[int, str], FlyteAnnotation("abc")],
1676
+ # we need to check if there's a FlyteAnnotation in the metadata.
1677
+ if _origin is Annotated:
1678
+ # This case should never happen since Python's typing system requires at least two arguments
1679
+ # for Annotated[...] - a type and an annotation. Including this check for completeness.
1680
+ if not _args:
1681
+ return None, None
1682
+
1683
+ first_arg = _args[0]
1684
+ # Recursively process the first argument if it's Annotated (or dict).
1685
+ return DictTransformer.extract_types(first_arg)
1686
+
1687
+ # If the origin is dict, return the type arguments if they exist.
1688
+ if _origin is dict:
1689
+ # _args can be ().
1690
+ if _args is not None:
1691
+ return _args # type: ignore
1692
+
1693
+ # Otherwise, we do not support this type in extract_types.
1694
+ raise ValueError(f"Trying to extract dictionary type information from a non-dict type {t}")
1695
+
1696
+ @staticmethod
1697
+ async def dict_to_binary_literal(v: dict, python_type: Type[dict], allow_pickle: bool) -> Literal:
1698
+ """
1699
+ Converts a Python dictionary to a Flyte-specific ``Literal`` using MessagePack encoding.
1700
+ Falls back to Pickle if encoding fails and `allow_pickle` is True.
1701
+ """
1702
+ from flyte.types._pickle import FlytePickle
1703
+
1704
+ try:
1705
+ # Handle dictionaries with non-string keys (e.g., Dict[int, Type])
1706
+ encoder = MessagePackEncoder(python_type)
1707
+ msgpack_bytes = encoder.encode(v)
1708
+ return Literal(scalar=Scalar(binary=Binary(value=msgpack_bytes, tag=MESSAGEPACK)))
1709
+ except TypeError as e:
1710
+ if allow_pickle:
1711
+ remote_path = await FlytePickle.to_pickle(v)
1712
+ return Literal(
1713
+ scalar=Scalar(
1714
+ generic=_json_format.Parse(json.dumps({"pickle_file": remote_path}), struct_pb2.Struct())
1715
+ ),
1716
+ metadata={"format": "pickle"},
1717
+ )
1718
+ raise TypeTransformerFailedError(f"Cannot convert `{v}` to Flyte Literal.\nError Message: {e}")
1719
+
1720
+ @staticmethod
1721
+ def is_pickle(python_type: Type[dict]) -> bool:
1722
+ _origin = get_origin(python_type)
1723
+ metadata: typing.Tuple = ()
1724
+ if _origin is Annotated:
1725
+ metadata = get_args(python_type)[1:]
1726
+
1727
+ for each_metadata in metadata:
1728
+ if isinstance(each_metadata, OrderedDict):
1729
+ allow_pickle = each_metadata.get("allow_pickle", False)
1730
+ return allow_pickle
1731
+
1732
+ return False
1733
+
1734
+ def get_literal_type(self, t: Type[dict]) -> LiteralType:
1735
+ """
1736
+ Transforms a native python dictionary to a flyte-specific ``LiteralType``
1737
+ """
1738
+ tp = DictTransformer.extract_types(t)
1739
+
1740
+ if tp:
1741
+ if tp[0] is str:
1742
+ try:
1743
+ sub_type = TypeEngine.to_literal_type(cast(type, tp[1]))
1744
+ return types_pb2.LiteralType(map_value_type=sub_type)
1745
+ except Exception as e:
1746
+ raise ValueError(f"Type of Generic List type is not supported, {e}")
1747
+ return types_pb2.LiteralType(
1748
+ simple=types_pb2.SimpleType.STRUCT,
1749
+ annotation=TypeAnnotation(annotations={CACHE_KEY_METADATA: {SERIALIZATION_FORMAT: MESSAGEPACK}}),
1750
+ )
1751
+
1752
+ async def to_literal(self, python_val: typing.Any, python_type: Type[dict], expected: LiteralType) -> Literal:
1753
+ if type(python_val) is not dict:
1754
+ raise TypeTransformerFailedError("Expected a dict")
1755
+
1756
+ allow_pickle = False
1757
+
1758
+ if get_origin(python_type) is Annotated:
1759
+ allow_pickle = DictTransformer.is_pickle(python_type)
1760
+
1761
+ if expected and expected.HasField("simple") and expected.simple == SimpleType.STRUCT:
1762
+ return await self.dict_to_binary_literal(python_val, python_type, allow_pickle)
1763
+
1764
+ lit_map = {}
1765
+ for k, v in python_val.items():
1766
+ if type(k) is not str:
1767
+ raise ValueError("Flyte MapType expects all keys to be strings")
1768
+
1769
+ _, v_type = self.extract_types(python_type)
1770
+ lit_map[k] = TypeEngine.to_literal(v, cast(type, v_type), expected.map_value_type)
1771
+ vals = await _run_coros_in_chunks(list(lit_map.values()), batch_size=_TYPE_ENGINE_COROS_BATCH_SIZE)
1772
+ for idx, k in zip(range(len(vals)), lit_map.keys()):
1773
+ lit_map[k] = vals[idx]
1774
+
1775
+ return Literal(map=LiteralMap(literals=lit_map))
1776
+
1777
+ async def to_python_value(self, lv: Literal, expected_python_type: Type[dict]) -> dict:
1778
+ if lv and lv.HasField("scalar") and lv.scalar.HasField("binary"):
1779
+ return self.from_binary_idl(lv.scalar.binary, expected_python_type) # type: ignore
1780
+
1781
+ if lv and lv.HasField("map"):
1782
+ tp = DictTransformer.extract_types(expected_python_type)
1783
+
1784
+ if tp is None or len(tp) == 0 or tp[0] is None:
1785
+ raise TypeError(
1786
+ "TypeMismatch: Cannot convert to python dictionary from Flyte Literal Dictionary as the given "
1787
+ "dictionary does not have sub-type hints or they do not match with the originating dictionary "
1788
+ "source. Flytekit does not currently support implicit conversions"
1789
+ )
1790
+ if tp[0] is not str:
1791
+ raise TypeError("TypeMismatch. Destination dictionary does not accept 'str' key")
1792
+ py_map = {}
1793
+ for k, v in lv.map.literals.items():
1794
+ py_map[k] = TypeEngine.to_python_value(v, cast(Type, tp[1]))
1795
+
1796
+ vals = await _run_coros_in_chunks(list(py_map.values()), batch_size=_TYPE_ENGINE_COROS_BATCH_SIZE)
1797
+ for idx, k in zip(range(len(vals)), py_map.keys()):
1798
+ py_map[k] = vals[idx]
1799
+
1800
+ return py_map
1801
+
1802
+ # for empty generic we have to explicitly test for lv.scalar.generic is not None as empty dict
1803
+ # evaluates to false
1804
+ # pr: han-ru is this part still necessary?
1805
+ if lv and lv.HasField("scalar") and lv.scalar.HasField("generic"):
1806
+ if lv.metadata and lv.metadata.get("format", None) == "pickle":
1807
+ from flyte.types._pickle import FlytePickle
1808
+
1809
+ uri = json.loads(_json_format.MessageToJson(lv.scalar.generic)).get("pickle_file")
1810
+ return await FlytePickle.from_pickle(uri)
1811
+
1812
+ try:
1813
+ """
1814
+ Handles the case where Flyte Console provides input as a protobuf struct.
1815
+ When resolving an attribute like 'dc.dict_int_ff', FlytePropeller retrieves a dictionary.
1816
+ Mashumaro's decoder can convert this dictionary to the expected Python object if the correct type
1817
+ is provided.
1818
+ Since Flyte Types handle their own deserialization, the dictionary is automatically converted to
1819
+ the expected Python object.
1820
+
1821
+ Example Code:
1822
+ @dataclass
1823
+ class DC:
1824
+ dict_int_ff: Dict[int, FlyteFile]
1825
+
1826
+ @workflow
1827
+ def wf(dc: DC):
1828
+ t_ff(dc.dict_int_ff)
1829
+
1830
+ Life Cycle:
1831
+ json str -> protobuf struct -> resolved protobuf struct -> dictionary
1832
+ -> expected Python object
1833
+ (console user input) (console output) (propeller)
1834
+ (flytekit dict transformer) (mashumaro decoder)
1835
+
1836
+ Related PR:
1837
+ - Title: Override Dataclass Serialization/Deserialization Behavior for FlyteTypes via Mashumaro
1838
+ - Link: https://github.com/flyteorg/flytekit/pull/2554
1839
+ - Title: Binary IDL With MessagePack
1840
+ - Link: https://github.com/flyteorg/flytekit/pull/2760
1841
+ """
1842
+
1843
+ dict_obj = json.loads(_json_format.MessageToJson(lv.scalar.generic))
1844
+ msgpack_bytes = msgpack.dumps(dict_obj)
1845
+
1846
+ try:
1847
+ decoder = self._msgpack_decoder[expected_python_type]
1848
+ except KeyError:
1849
+ decoder = MessagePackDecoder(expected_python_type, pre_decoder_func=_default_msgpack_decoder)
1850
+ self._msgpack_decoder[expected_python_type] = decoder
1851
+
1852
+ return decoder.decode(msgpack_bytes)
1853
+ except TypeError:
1854
+ raise TypeTransformerFailedError(f"Cannot convert from {lv} to {expected_python_type}")
1855
+
1856
+ raise TypeTransformerFailedError(f"Cannot convert from {lv} to {expected_python_type}")
1857
+
1858
+ def guess_python_type(self, literal_type: LiteralType) -> Union[Type[dict], typing.Dict[Type, Type]]:
1859
+ if literal_type.HasField("map_value_type"):
1860
+ mt: typing.Type = TypeEngine.guess_python_type(literal_type.map_value_type)
1861
+ return typing.Dict[str, mt] # type: ignore
1862
+
1863
+ if literal_type.simple == SimpleType.STRUCT:
1864
+ if not literal_type.HasField("metadata"):
1865
+ return dict # type: ignore
1866
+
1867
+ raise ValueError(f"Dictionary transformer cannot reverse {literal_type}")
1868
+
1869
+
1870
+ def convert_mashumaro_json_schema_to_python_class(schema: dict, schema_name: typing.Any) -> Type[T]:
1871
+ """
1872
+ Generate a model class based on the provided JSON Schema
1873
+ :param schema: dict representing valid JSON schema
1874
+ :param schema_name: dataclass name of return type
1875
+ """
1876
+
1877
+ attribute_list = generate_attribute_list_from_dataclass_json_mixin(schema, schema_name)
1878
+ return dataclasses.make_dataclass(schema_name, attribute_list)
1879
+
1880
+
1881
+ def _get_element_type(element_property: typing.Dict[str, str]) -> Type:
1882
+ from flyte.io._dir import Dir
1883
+ from flyte.io._file import File
1884
+
1885
+ if File.schema_match(element_property):
1886
+ return File
1887
+ elif Dir.schema_match(element_property):
1888
+ return Dir
1889
+ element_type = (
1890
+ [e_property["type"] for e_property in element_property["anyOf"]] # type: ignore
1891
+ if element_property.get("anyOf")
1892
+ else element_property["type"]
1893
+ )
1894
+ element_format = element_property["format"] if "format" in element_property else None
1895
+
1896
+ if isinstance(element_type, list):
1897
+ # Element type of Optional[int] is [integer, None]
1898
+ return typing.Optional[_get_element_type({"type": element_type[0]})] # type: ignore
1899
+
1900
+ if element_type == "string":
1901
+ return str
1902
+ elif element_type == "integer":
1903
+ return int
1904
+ elif element_type == "boolean":
1905
+ return bool
1906
+ elif element_type == "number":
1907
+ if element_format == "integer":
1908
+ return int
1909
+ else:
1910
+ return float
1911
+ return str
1912
+
1913
+
1914
+ def dataclass_from_dict(cls: type, src: typing.Dict[str, typing.Any]) -> typing.Any:
1915
+ """
1916
+ Utility function to construct a dataclass object from dict
1917
+ """
1918
+ field_types_lookup = {field.name: field.type for field in dataclasses.fields(cls)}
1919
+
1920
+ constructor_inputs = {}
1921
+ for field_name, value in src.items():
1922
+ if dataclasses.is_dataclass(field_types_lookup[field_name]):
1923
+ constructor_inputs[field_name] = dataclass_from_dict(cast(type, field_types_lookup[field_name]), value)
1924
+ else:
1925
+ constructor_inputs[field_name] = value
1926
+
1927
+ return cls(**constructor_inputs)
1928
+
1929
+
1930
+ def strict_type_hint_matching(input_val: typing.Any, target_literal_type: LiteralType) -> typing.Type:
1931
+ """
1932
+ Try to be smarter about guessing the type of the input (and hence the transformer).
1933
+ If the literal type from the transformer for type(v), matches the literal type of the interface, then we
1934
+ can use type(). Otherwise, fall back to guess python type from the literal type.
1935
+ Raises ValueError, like in case of [1,2,3] type() will just give `list`, which won't work.
1936
+ Raises ValueError also if the transformer found for the raw type doesn't have a literal type match.
1937
+ """
1938
+ native_type = type(input_val)
1939
+ transformer: TypeTransformer = TypeEngine.get_transformer(native_type)
1940
+ inferred_literal_type = transformer.get_literal_type(native_type)
1941
+ # note: if no good match, transformer will be the pickle transformer, but type will not match unless it's the
1942
+ # pickle type so will fall back to normal guessing
1943
+ if literal_types_match(inferred_literal_type, target_literal_type):
1944
+ return type(input_val)
1945
+
1946
+ raise ValueError(
1947
+ f"Transformer for {native_type} returned literal type {inferred_literal_type} "
1948
+ f"which doesn't match {target_literal_type}"
1949
+ )
1950
+
1951
+
1952
+ def _check_and_covert_float(lv: literals_pb2.Literal) -> float:
1953
+ if lv.scalar.primitive.HasField("float_value"):
1954
+ return lv.scalar.primitive.float_value
1955
+ elif lv.scalar.primitive.HasField("integer"):
1956
+ return float(lv.scalar.primitive.integer)
1957
+ raise TypeTransformerFailedError(f"Cannot convert literal {lv} to float")
1958
+
1959
+
1960
+ def _handle_flyte_console_float_input_to_int(lv: Literal) -> int:
1961
+ """
1962
+ Flyte Console is written by JavaScript and JavaScript has only one number type which is Number.
1963
+ Sometimes it keeps track of trailing 0s and sometimes it doesn't.
1964
+ We have to convert float to int back in the following example.
1965
+
1966
+ Example Code:
1967
+ @dataclass
1968
+ class DC:
1969
+ a: int
1970
+
1971
+ @workflow
1972
+ def wf(dc: DC):
1973
+ t_int(a=dc.a)
1974
+
1975
+ Life Cycle:
1976
+ json str -> protobuf struct -> resolved float -> float
1977
+ -> int
1978
+ (console user input) (console output) (propeller) (flytekit simple transformer)
1979
+ (_handle_flyte_console_float_input_to_int)
1980
+ """
1981
+ if lv.scalar.primitive.HasField("integer"):
1982
+ return lv.scalar.primitive.integer
1983
+
1984
+ if lv.scalar.primitive.HasField("float_value"):
1985
+ logger.info(f"Converting literal float {lv.scalar.primitive.float_value} to int, might have precision loss.")
1986
+ return int(lv.scalar.primitive.float_value)
1987
+
1988
+ raise TypeTransformerFailedError(f"Cannot convert literal {lv} to int")
1989
+
1990
+
1991
+ def _check_and_convert_void(lv: Literal) -> None:
1992
+ if not lv.scalar.HasField("none_type"):
1993
+ raise TypeTransformerFailedError(f"Cannot convert literal '{lv}' to None")
1994
+ return None
1995
+
1996
+
1997
+ IntTransformer = SimpleTransformer(
1998
+ "int",
1999
+ int,
2000
+ types_pb2.LiteralType(simple=types_pb2.SimpleType.INTEGER),
2001
+ lambda x: Literal(scalar=Scalar(primitive=Primitive(integer=x))),
2002
+ _handle_flyte_console_float_input_to_int,
2003
+ )
2004
+
2005
+ FloatTransformer = SimpleTransformer(
2006
+ "float",
2007
+ float,
2008
+ types_pb2.LiteralType(simple=types_pb2.SimpleType.FLOAT),
2009
+ lambda x: Literal(scalar=Scalar(primitive=Primitive(float_value=x))),
2010
+ _check_and_covert_float,
2011
+ )
2012
+
2013
+ BoolTransformer = SimpleTransformer(
2014
+ "bool",
2015
+ bool,
2016
+ types_pb2.LiteralType(simple=types_pb2.SimpleType.BOOLEAN),
2017
+ lambda x: Literal(scalar=Scalar(primitive=Primitive(boolean=x))),
2018
+ lambda x: x.scalar.primitive.boolean,
2019
+ )
2020
+
2021
+ StrTransformer = SimpleTransformer(
2022
+ "str",
2023
+ str,
2024
+ types_pb2.LiteralType(simple=types_pb2.SimpleType.STRING),
2025
+ lambda x: Literal(scalar=Scalar(primitive=Primitive(string_value=x))),
2026
+ lambda x: x.scalar.primitive.string_value if x.scalar.primitive.HasField("string_value") else None,
2027
+ )
2028
+
2029
+ DatetimeTransformer = SimpleTransformer(
2030
+ "datetime",
2031
+ datetime.datetime,
2032
+ types_pb2.LiteralType(simple=types_pb2.SimpleType.DATETIME),
2033
+ lambda x: Literal(scalar=Scalar(primitive=Primitive(datetime=x))),
2034
+ lambda x: x.scalar.primitive.datetime.ToDatetime().replace(tzinfo=datetime.timezone.utc)
2035
+ if x.scalar.primitive.HasField("datetime")
2036
+ else None,
2037
+ )
2038
+
2039
+ TimedeltaTransformer = SimpleTransformer(
2040
+ "timedelta",
2041
+ datetime.timedelta,
2042
+ types_pb2.LiteralType(simple=types_pb2.SimpleType.DURATION),
2043
+ lambda x: Literal(scalar=Scalar(primitive=Primitive(duration=x))),
2044
+ lambda x: x.scalar.primitive.duration.ToTimedelta() if x.scalar.primitive.HasField("duration") else None,
2045
+ )
2046
+
2047
+ DateTransformer = SimpleTransformer(
2048
+ "date",
2049
+ datetime.date,
2050
+ types_pb2.LiteralType(simple=types_pb2.SimpleType.DATETIME),
2051
+ lambda x: Literal(
2052
+ scalar=Scalar(primitive=Primitive(datetime=datetime.datetime.combine(x, datetime.time.min)))
2053
+ ), # convert datetime to date
2054
+ lambda x: x.scalar.primitive.datetime.ToDatetime().replace(tzinfo=datetime.timezone.utc).date()
2055
+ if x.scalar.primitive.HasField("datetime")
2056
+ else None,
2057
+ )
2058
+
2059
+ NoneTransformer = SimpleTransformer(
2060
+ "none",
2061
+ type(None),
2062
+ types_pb2.LiteralType(simple=types_pb2.SimpleType.NONE),
2063
+ lambda x: Literal(scalar=Scalar(none_type=Void())),
2064
+ lambda x: _check_and_convert_void(x),
2065
+ )
2066
+
2067
+
2068
+ def _register_default_type_transformers():
2069
+ from types import UnionType
2070
+
2071
+ TypeEngine.register(IntTransformer)
2072
+ TypeEngine.register(FloatTransformer)
2073
+ TypeEngine.register(StrTransformer)
2074
+ TypeEngine.register(DatetimeTransformer)
2075
+ TypeEngine.register(DateTransformer)
2076
+ TypeEngine.register(TimedeltaTransformer)
2077
+ TypeEngine.register(BoolTransformer)
2078
+ TypeEngine.register(NoneTransformer, [None])
2079
+ TypeEngine.register(ListTransformer())
2080
+ TypeEngine.register(UnionTransformer(), [UnionType])
2081
+ TypeEngine.register(DictTransformer())
2082
+ TypeEngine.register(EnumTransformer())
2083
+ TypeEngine.register(ProtobufTransformer())
2084
+ TypeEngine.register(PydanticTransformer())
2085
+
2086
+ # inner type is. Also unsupported are typing's Tuples. Even though you can look inside them, Flyte's type system
2087
+ # doesn't support these currently.
2088
+ # Confusing note: typing.NamedTuple is in here even though task functions themselves can return them. We just mean
2089
+ # that the return signature of a task can be a NamedTuple that contains another NamedTuple inside it.
2090
+ # Also, it's not entirely true that Flyte IDL doesn't support tuples. We can always fake them as structs, but we'll
2091
+ # hold off on doing that for now, as we may amend the IDL formally to support tuples.
2092
+ TypeEngine.register_restricted_type("non typed tuple", tuple)
2093
+ TypeEngine.register_restricted_type("non typed tuple", typing.Tuple)
2094
+ TypeEngine.register_restricted_type("named tuple", NamedTuple)
2095
+
2096
+
2097
+ class LiteralsResolver(collections.UserDict):
2098
+ """
2099
+ LiteralsResolver is a helper class meant primarily for use with the FlyteRemote experience or any other situation
2100
+ where you might be working with LiteralMaps. This object allows the caller to specify the Python type that should
2101
+ correspond to an element of the map.
2102
+ """
2103
+
2104
+ def __init__(
2105
+ self,
2106
+ literals: typing.Dict[str, Literal],
2107
+ variable_map: Optional[Dict[str, interface_pb2.Variable]] = None,
2108
+ ):
2109
+ """
2110
+ :param literals: A Python map of strings to Flyte Literal models.
2111
+ :param variable_map: This map should be basically one side (either input or output) of the Flyte
2112
+ TypedInterface model and is used to guess the Python type through the TypeEngine if a Python type is not
2113
+ specified by the user. TypeEngine guessing is flaky though, so calls to get() should specify the as_type
2114
+ parameter when possible.
2115
+ """
2116
+ super().__init__(literals)
2117
+ if literals is None:
2118
+ raise ValueError("Cannot instantiate LiteralsResolver without a map of Literals.")
2119
+ self._literals = literals
2120
+ self._variable_map = variable_map
2121
+ self._native_values: Dict[str, type] = {}
2122
+ self._type_hints: Dict[str, type] = {}
2123
+
2124
+ def __str__(self) -> str:
2125
+ if self.literals:
2126
+ if len(self.literals) == len(self.native_values):
2127
+ return str(self.native_values)
2128
+ if self.native_values:
2129
+ header = "Partially converted to native values, call get(key, <type_hint>) to convert rest...\n"
2130
+ strs = []
2131
+ for key, literal in self._literals.items():
2132
+ if key in self._native_values:
2133
+ strs.append(f"{key}: " + str(self._native_values[key]) + "\n")
2134
+ else:
2135
+ lit_txt = str(self._literals[key])
2136
+ lit_txt = textwrap.indent(lit_txt, " " * (len(key) + 2))
2137
+ strs.append(f"{key}: \n" + lit_txt)
2138
+
2139
+ return header + "{\n" + textwrap.indent("".join(strs), " " * 2) + "\n}"
2140
+ else:
2141
+ return str(self.literals)
2142
+ return "{}"
2143
+
2144
+ def __repr__(self):
2145
+ return self.__str__()
2146
+
2147
+ @property
2148
+ def native_values(self) -> typing.Dict[str, typing.Any]:
2149
+ return self._native_values
2150
+
2151
+ @property
2152
+ def variable_map(self) -> Optional[Dict[str, interface_pb2.Variable]]:
2153
+ return self._variable_map
2154
+
2155
+ @property
2156
+ def literals(self):
2157
+ return self._literals
2158
+
2159
+ def update_type_hints(self, type_hints: typing.Dict[str, typing.Type]):
2160
+ self._type_hints.update(type_hints)
2161
+
2162
+ def get_literal(self, key: str) -> Literal:
2163
+ if key not in self._literals:
2164
+ raise ValueError(f"Key {key} is not in the literal map")
2165
+
2166
+ return self._literals[key]
2167
+
2168
+ def as_python_native(self, python_interface: NativeInterface) -> typing.Any:
2169
+ """
2170
+ This should return the native Python representation, compatible with unpacking.
2171
+ This function relies on Python interface outputs being ordered correctly.
2172
+
2173
+ :param python_interface: Only outputs are used but easier to pass the whole interface.
2174
+ """
2175
+ if len(self.literals) == 0:
2176
+ return None
2177
+
2178
+ if self.variable_map is None:
2179
+ raise AssertionError(f"Variable map is empty in literals resolver with {self.literals}")
2180
+
2181
+ # Trigger get() on everything to make sure native values are present using the python interface as type hint
2182
+ for lit_key, lit in self.literals.items():
2183
+ asyncio.run(self.get(lit_key, as_type=python_interface.outputs.get(lit_key)))
2184
+
2185
+ # if 1 item, then return 1 item
2186
+ if len(self.native_values) == 1:
2187
+ return next(iter(self.native_values.values()))
2188
+
2189
+ # if more than 1 item, then return a tuple - can ignore naming the tuple unless it becomes a problem
2190
+ # This relies on python_interface.outputs being ordered correctly.
2191
+ res = cast(typing.Tuple[typing.Any, ...], ())
2192
+ for var_name, _ in python_interface.outputs.items():
2193
+ if var_name not in self.native_values:
2194
+ raise ValueError(f"Key {var_name} is not in the native values")
2195
+
2196
+ res += (self.native_values[var_name],)
2197
+
2198
+ return res
2199
+
2200
+ def __getitem__(self, key: str):
2201
+ # First check to see if it's even in the literal map.
2202
+ if key not in self._literals:
2203
+ raise ValueError(f"Key {key} is not in the literal map")
2204
+
2205
+ # Return the cached value if it's cached
2206
+ if key in self._native_values:
2207
+ return self._native_values[key]
2208
+
2209
+ return self.get(key)
2210
+
2211
+ async def get(self, attr: str, as_type: Optional[typing.Type] = None) -> typing.Any: # type: ignore
2212
+ """
2213
+ This will get the ``attr`` value from the Literal map, and invoke the TypeEngine to convert it into a Python
2214
+ native value. A Python type can optionally be supplied. If successful, the native value will be cached and
2215
+ future calls will return the cached value instead.
2216
+
2217
+ :param attr:
2218
+ :param as_type:
2219
+ :return: Python native value from the LiteralMap
2220
+ """
2221
+ if attr not in self._literals:
2222
+ raise AttributeError(f"Attribute {attr} not found")
2223
+ if attr in self.native_values:
2224
+ return self.native_values[attr]
2225
+
2226
+ if as_type is None:
2227
+ if attr in self._type_hints:
2228
+ as_type = self._type_hints[attr]
2229
+ else:
2230
+ if self.variable_map and attr in self.variable_map:
2231
+ try:
2232
+ as_type = TypeEngine.guess_python_type(self.variable_map[attr].type)
2233
+ except ValueError as e:
2234
+ logger.error(f"Could not guess a type for Variable {self.variable_map[attr]}")
2235
+ raise e
2236
+ else:
2237
+ raise ValueError("as_type argument not supplied and Variable map not specified in LiteralsResolver")
2238
+ val = await TypeEngine.to_python_value(self._literals[attr], cast(Type, as_type))
2239
+ self._native_values[attr] = val
2240
+ return val
2241
+
2242
+
2243
+ _register_default_type_transformers()
2244
+
2245
+
2246
+ def is_annotated(t: Type) -> bool:
2247
+ return get_origin(t) is Annotated
2248
+
2249
+
2250
+ def get_underlying_type(t: Type) -> Type:
2251
+ """Return the underlying type for annotated types or the type itself"""
2252
+ if is_annotated(t):
2253
+ return get_args(t)[0]
2254
+ return t