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