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