flyte 0.1.0__py3-none-any.whl → 0.2.0a0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

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