-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathudf_utils.py
More file actions
1736 lines (1571 loc) · 65.2 KB
/
udf_utils.py
File metadata and controls
1736 lines (1571 loc) · 65.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) 2012-2025 Snowflake Computing Inc. All rights reserved.
#
import collections.abc
import inspect
import io
import os
import pickle
import sys
import typing
import zipfile
from copy import deepcopy
from enum import Enum
from logging import getLogger
from types import ModuleType
from typing import (
Any,
Callable,
Dict,
List,
NamedTuple,
Optional,
Tuple,
Union,
get_type_hints,
)
import cloudpickle
from packaging.requirements import Requirement
import snowflake.snowpark
from snowflake.connector.options import installed_pandas, pandas
from snowflake.snowpark._internal import code_generation, type_utils
from snowflake.snowpark._internal.analyzer.datatype_mapper import to_sql, to_sql_no_cast
from snowflake.snowpark._internal.telemetry import TelemetryField
from snowflake.snowpark._internal.type_utils import (
NoneType,
convert_sp_to_sf_type,
infer_type,
python_type_str_to_object,
python_type_to_snow_type,
python_value_str_to_object,
retrieve_func_arg_names_from_source,
retrieve_func_defaults_from_source,
retrieve_func_type_hints_from_source,
)
from snowflake.snowpark._internal.utils import (
STAGE_PREFIX,
TempObjectType,
escape_single_quotes,
get_udf_upload_prefix,
is_single_quoted,
normalize_remote_file_or_dir,
random_name_for_temp_object,
random_number,
unwrap_stage_location_single_quote,
validate_object_name,
warning,
)
from snowflake.snowpark.types import DataType, StructField, StructType
from snowflake.snowpark.version import VERSION
if installed_pandas:
from snowflake.snowpark.types import (
PandasDataFrame,
PandasDataFrameType,
PandasSeriesType,
)
# Python 3.8 needs to use typing.Iterable because collections.abc.Iterable is not subscriptable
# Python 3.9 can use both
# Python 3.10 needs to use collections.abc.Iterable because typing.Iterable is removed
if sys.version_info <= (3, 9):
from typing import Iterable
else:
from collections.abc import Iterable
logger = getLogger(__name__)
# the default handler name for generated udf python file
_DEFAULT_HANDLER_NAME = "compute"
# Max code size to inline generated closure. Beyond this threshold, the closure will be uploaded to a stage for imports.
# Current number is the same as scala. We might have the potential to make it larger but that requires further benchmark
# because zip compression ratio is quite high.
_MAX_INLINE_CLOSURE_SIZE_BYTES = 8192
# Every table function handler class must define the process method.
TABLE_FUNCTION_PROCESS_METHOD = "process"
TABLE_FUNCTION_END_PARTITION_METHOD = "end_partition"
# Every aggregate function handler class must define accumulate and finish methods.
AGGREGATE_FUNCTION_ACCULUMATE_METHOD = "accumulate"
AGGREGATE_FUNCTION_FINISH_METHOD = "finish"
AGGREGATE_FUNCTION_MERGE_METHOD = "merge"
AGGREGATE_FUNCTION_STATE_METHOD = "aggregate_state"
EXECUTE_AS_WHITELIST = frozenset(["owner", "caller", "restricted caller"])
REGISTER_KWARGS_ALLOWLIST = {
"native_app_params",
"anonymous",
"force_inline_code",
"_from_pandas_udf_function",
"input_names", # for pandas_udtf
"max_batch_size", # for pandas_udtf
"_registered_object_name", # object name within Snowflake (post registration)
}
ALLOWED_CONSTRAINT_CONFIGURATION = {"architecture": {"x86"}}
class UDFColumn(NamedTuple):
datatype: DataType
name: str
class RegistrationType(Enum):
UDF = "UDF"
UDAF = "UDAF"
UDTF = "UDTF"
SPROC = "SPROC"
class ExtensionFunctionProperties:
"""
This is a data class to hold all information, resolved or otherwise, about a UDF/UDTF/UDAF/Sproc object
that we want to create in a user's Snowflake account.
One of the use cases of this class is to be able to pass on information to a callback that may be installed
in the execution environment, such as for testing.
"""
def __init__(
self,
object_type: TempObjectType,
object_name: str,
input_args: List[UDFColumn],
input_sql_types: List[str],
return_sql: str,
runtime_version: str,
all_imports: Optional[str],
all_packages: str,
handler: Optional[str],
external_access_integrations: Optional[List[str]],
secrets: Optional[Dict[str, str]],
inline_python_code: Optional[str],
native_app_params: Optional[Dict[str, Any]],
raw_imports: Optional[List[Union[str, Tuple[str, str]]]],
func: Union[Callable, Tuple[str, str]],
replace: bool = False,
if_not_exists: bool = False,
execute_as: Optional[
typing.Literal["caller", "owner", "restricted caller"]
] = None,
anonymous: bool = False,
) -> None:
self.func = func
self.replace = replace
self.object_type = object_type
self.if_not_exists = if_not_exists
self.object_name = object_name
self.input_args = deepcopy(input_args)
self.input_sql_types = input_sql_types
self.return_sql = return_sql
self.runtime_version = runtime_version
self.all_imports = all_imports
self.all_packages = all_packages
self.external_access_integrations = deepcopy(external_access_integrations)
self.secrets = deepcopy(secrets)
self.handler = handler
self.execute_as = execute_as
self.inline_python_code = inline_python_code
self.native_app_params = deepcopy(native_app_params)
self.raw_imports = deepcopy(raw_imports)
self.anonymous = anonymous
def get_wrapped_attr(func: Callable, attr_name: str) -> Optional[Any]:
"""Return attribute from a function, following functools.wraps __wrapped__ chain.
Looks for `attr_name` on `func`; if not found and `func` has a `__wrapped__` attribute,
follows the chain until the attribute is found or the end is reached.
"""
f: Callable = func
while True:
value = getattr(f, attr_name, None)
if value is not None:
return value
if not hasattr(f, "__wrapped__"):
return None
f = f.__wrapped__
def is_local_python_file(file_path: str) -> bool:
return not file_path.startswith(STAGE_PREFIX) and file_path.endswith(".py")
def get_python_types_dict_for_udaf(
accumulate_hints: Dict[str, Any], finish_hints: Dict[str, Any]
) -> Dict[str, Any]:
python_types_dict = {k: v for k, v in accumulate_hints.items() if k != "return"}
if "return" in finish_hints:
python_types_dict["return"] = finish_hints["return"]
return python_types_dict
def get_python_types_dict_for_udtf(
process: Dict[str, Any], end_partition: Dict[str, Any]
) -> Dict[str, Any]:
# Prefer input types from process and return types from end_partition
python_types_dict = {**end_partition, **process}
if "return" in end_partition:
python_types_dict["return"] = end_partition["return"]
return python_types_dict
def extract_return_type_from_udtf_type_hints(
return_type_hint, output_schema, func_name
) -> Union[StructType, "PandasDataFrameType", None]:
if return_type_hint is None and output_schema is not None:
raise ValueError(
"The return type hint is not set but 'output_schema' has only column names. You can either use a StructType instance for 'output_schema', or use"
"a combination of a return type hint for method 'process' and column names for 'output_schema'."
)
if typing.get_origin(return_type_hint) in [
list,
tuple,
collections.abc.Iterable,
collections.abc.Iterator,
]:
row_type_hint = typing.get_args(return_type_hint)[0] # The inner Tuple
if typing.get_origin(row_type_hint) != tuple:
raise ValueError(
f"The return type hint of method '{func_name}.process' must be a collection of tuples, for instance, Iterable[Tuple[str, int]], if you specify return type hint."
)
column_type_hints = typing.get_args(row_type_hint)
if len(column_type_hints) > 1 and column_type_hints[1] == Ellipsis:
return StructType(
[
StructField(
name,
type_utils.python_type_to_snow_type(column_type_hints[0])[0],
)
for name in output_schema
]
)
elif output_schema:
if len(column_type_hints) != len(output_schema):
raise ValueError(
f"'output_schema' has {len(output_schema)} names while type hints Tuple has only {len(column_type_hints)}."
)
return StructType(
[
StructField(
name,
type_utils.python_type_to_snow_type(column_type)[0],
)
for name, column_type in zip(output_schema, column_type_hints)
]
)
else: # both type hints and return type are specified
return None
elif return_type_hint is None:
return None
else:
if installed_pandas: # Vectorized UDTF
if typing.get_origin(return_type_hint) == PandasDataFrame:
return PandasDataFrameType(
col_types=[
python_type_to_snow_type(x)[0]
for x in typing.get_args(return_type_hint)
],
col_names=output_schema,
)
elif return_type_hint is pandas.DataFrame:
return PandasDataFrameType(
[]
) # placeholder, indicating the return type is pandas DataFrame
if return_type_hint is NoneType:
return None
else:
raise ValueError(
f"The return type hint for a UDTF handler must be a collection type or None or a PandasDataFrame. {return_type_hint} is used."
)
def get_types_from_type_hints(
func: Union[Callable, Tuple[str, str]],
object_type: TempObjectType,
output_schema: Optional[List[str]] = None,
) -> Tuple[DataType, List[DataType]]:
if isinstance(func, Callable):
# For Python 3.10+, the result values of get_type_hints()
# will become strings, which we have to change the implementation
# here at that time. https://www.python.org/dev/peps/pep-0563/
func_name = func.__name__
try:
if object_type == TempObjectType.AGGREGATE_FUNCTION:
accumulate_hints = get_type_hints(
getattr(func, AGGREGATE_FUNCTION_ACCULUMATE_METHOD, func)
)
finish_hints = get_type_hints(
getattr(func, AGGREGATE_FUNCTION_FINISH_METHOD, func)
)
python_types_dict = get_python_types_dict_for_udaf(
accumulate_hints, finish_hints
)
elif object_type == TempObjectType.TABLE_FUNCTION:
if not (
hasattr(func, TABLE_FUNCTION_END_PARTITION_METHOD)
or hasattr(func, TABLE_FUNCTION_PROCESS_METHOD)
):
raise AttributeError(
f"Neither `{TABLE_FUNCTION_PROCESS_METHOD}` nor `{TABLE_FUNCTION_END_PARTITION_METHOD}` is defined for class {func}"
)
process_types_dict = {}
end_partition_types_dict = {}
# PROCESS and END_PARTITION have the same return type but input types might be different, favor PROCESS's types if both methods are present
if hasattr(func, TABLE_FUNCTION_PROCESS_METHOD):
process_types_dict = get_type_hints(
getattr(func, TABLE_FUNCTION_PROCESS_METHOD)
)
if hasattr(func, TABLE_FUNCTION_END_PARTITION_METHOD):
end_partition_types_dict = get_type_hints(
getattr(func, TABLE_FUNCTION_END_PARTITION_METHOD)
)
python_types_dict = get_python_types_dict_for_udtf(
process_types_dict, end_partition_types_dict
)
else:
python_types_dict = get_type_hints(func)
except TypeError:
# if we fail to run get_type_hints on a function (a TypeError will be raised),
# return empty type dict. This will fail for functions like numpy.ufunc
# (e.g., get_type_hints(np.exp))
python_types_dict = {}
return_type_hint = python_types_dict.get("return")
else:
# Register from file
filename, func_name = func[0], func[1]
if not is_local_python_file(filename):
python_types_dict = {}
elif object_type == TempObjectType.AGGREGATE_FUNCTION:
accumulate_hints = retrieve_func_type_hints_from_source(
filename, AGGREGATE_FUNCTION_ACCULUMATE_METHOD, class_name=func_name
)
finish_hints = retrieve_func_type_hints_from_source(
filename, AGGREGATE_FUNCTION_FINISH_METHOD, class_name=func_name
)
python_types_dict = get_python_types_dict_for_udaf(
accumulate_hints, finish_hints
)
elif object_type == TempObjectType.TABLE_FUNCTION:
process_types_dict = retrieve_func_type_hints_from_source(
filename, TABLE_FUNCTION_PROCESS_METHOD, class_name=func[1]
)
end_partition_types_dict = retrieve_func_type_hints_from_source(
func[0], TABLE_FUNCTION_END_PARTITION_METHOD, class_name=func[1]
)
if process_types_dict is None and end_partition_types_dict is None:
raise ValueError(
f"Neither {func_name}.{TABLE_FUNCTION_PROCESS_METHOD} or {func_name}.{TABLE_FUNCTION_END_PARTITION_METHOD} could be found from {filename}"
)
python_types_dict = get_python_types_dict_for_udtf(
process_types_dict or {}, end_partition_types_dict or {}
)
elif object_type in (TempObjectType.FUNCTION, TempObjectType.PROCEDURE):
python_types_dict = retrieve_func_type_hints_from_source(
filename, func_name
)
else:
raise ValueError(
f"Expecting FUNCTION, PROCEDURE, TABLE_FUNCTION, or AGGREGATE_FUNCTION as object_type, got {object_type}"
)
if "return" in python_types_dict:
return_type_hint = python_type_str_to_object(
python_types_dict["return"], object_type == TempObjectType.PROCEDURE
)
else:
return_type_hint = None
if object_type == TempObjectType.TABLE_FUNCTION:
return_type = extract_return_type_from_udtf_type_hints(
return_type_hint, output_schema, func_name
)
else:
return_type = (
python_type_to_snow_type(
python_types_dict["return"], object_type == TempObjectType.PROCEDURE
)[0]
if "return" in python_types_dict
else None
)
input_types = []
# types are in order
index = 0
for key, python_type in python_types_dict.items():
# The first parameter of sp function should be Session
if object_type == TempObjectType.PROCEDURE and index == 0:
if python_type != snowflake.snowpark.Session and python_type not in [
"Session",
"snowflake.snowpark.Session",
]:
raise TypeError(
"The first argument of stored proc function should be Session"
)
elif key != "return":
input_types.append(
python_type_to_snow_type(
python_type, object_type == TempObjectType.PROCEDURE
)[0]
)
index += 1
return return_type, input_types
def get_opt_arg_defaults(
func: Union[Callable, Tuple[str, str]],
object_type: TempObjectType,
input_types: List[DataType],
) -> List[Optional[str]]:
EMPTY_DEFAULT_VALUES = [None] * len(input_types)
def build_default_values_result(
default_values: Any,
input_types: List[DataType],
convert_python_str_to_object: bool,
) -> List[Optional[str]]:
if default_values is None:
return EMPTY_DEFAULT_VALUES
num_optional_args = len(default_values)
num_positional_args = len(input_types) - num_optional_args
input_types_for_default_args = input_types[-num_optional_args:]
if convert_python_str_to_object:
default_values = [
python_value_str_to_object(value, tp)
for value, tp in zip(default_values, input_types_for_default_args)
]
if num_optional_args != 0:
default_values_to_sql_str = [
to_sql(value, datatype)
for value, datatype in zip(default_values, input_types_for_default_args)
]
else:
default_values_to_sql_str = []
return [None] * num_positional_args + default_values_to_sql_str
def get_opt_arg_defaults_from_callable():
target_func = None
if object_type == TempObjectType.TABLE_FUNCTION:
# extract from process method
if hasattr(func, TABLE_FUNCTION_PROCESS_METHOD):
target_func = getattr(func, TABLE_FUNCTION_PROCESS_METHOD)
if object_type in (TempObjectType.PROCEDURE, TempObjectType.FUNCTION):
# sproc and udf
target_func = func
if target_func is None:
return EMPTY_DEFAULT_VALUES
arg_spec = inspect.getfullargspec(target_func)
return build_default_values_result(arg_spec.defaults, input_types, False)
def get_opt_arg_defaults_from_file():
filename, func_name = func[0], func[1]
default_values_str = None
if not is_local_python_file(filename):
return EMPTY_DEFAULT_VALUES
if object_type == TempObjectType.TABLE_FUNCTION:
default_values_str = retrieve_func_defaults_from_source(
filename, TABLE_FUNCTION_PROCESS_METHOD, func_name
)
elif object_type in (TempObjectType.FUNCTION, TempObjectType.PROCEDURE):
default_values_str = retrieve_func_defaults_from_source(filename, func_name)
return build_default_values_result(default_values_str, input_types, True)
try:
if isinstance(func, Callable):
return get_opt_arg_defaults_from_callable()
else:
return get_opt_arg_defaults_from_file()
except TypeError as e:
logger.warn(
f"Got error {e} when trying to read default values from function: {func}. "
"Proceeding without creating optional arguments"
)
return EMPTY_DEFAULT_VALUES
def get_func_arg_names(
func: Union[Callable, Tuple[str, str]],
object_type: TempObjectType,
num_args: int,
preserve_parameter_names: bool,
) -> List[str]:
default_arg_names = [f"arg{i + 1}" for i in range(num_args)]
if not preserve_parameter_names:
return default_arg_names
def get_arg_names_from_callable() -> Optional[List[str]]:
target_func = None
if object_type == TempObjectType.TABLE_FUNCTION:
if hasattr(func, TABLE_FUNCTION_PROCESS_METHOD):
target_func = getattr(func, TABLE_FUNCTION_PROCESS_METHOD)
if object_type == TempObjectType.AGGREGATE_FUNCTION:
if hasattr(func, AGGREGATE_FUNCTION_ACCULUMATE_METHOD):
target_func = getattr(func, AGGREGATE_FUNCTION_ACCULUMATE_METHOD)
if object_type in (TempObjectType.PROCEDURE, TempObjectType.FUNCTION):
target_func = func
if target_func is None:
return None
return inspect.getfullargspec(target_func).args
def get_arg_names_from_file() -> Optional[List[str]]:
filename, func_name = func[0], func[1]
if not is_local_python_file(filename):
return None
arg_names = None
if object_type == TempObjectType.TABLE_FUNCTION:
arg_names = retrieve_func_arg_names_from_source(
filename, TABLE_FUNCTION_PROCESS_METHOD, func_name
)
elif object_type == TempObjectType.AGGREGATE_FUNCTION:
arg_names = retrieve_func_arg_names_from_source(
filename, AGGREGATE_FUNCTION_ACCULUMATE_METHOD, func_name
)
elif object_type in (TempObjectType.FUNCTION, TempObjectType.PROCEDURE):
arg_names = retrieve_func_arg_names_from_source(filename, func_name)
return arg_names
try:
arg_names = (
get_arg_names_from_callable()
if isinstance(func, Callable)
else get_arg_names_from_file()
)
if arg_names is None:
return default_arg_names
# Skip the first argument when:
# 1. It's a stored procedure, ignore the "session" argument
# 2. It's a table/aggregate function, ignore the "self" argument of the method
if object_type in (
TempObjectType.PROCEDURE,
TempObjectType.TABLE_FUNCTION,
TempObjectType.AGGREGATE_FUNCTION,
):
arg_names = arg_names[1:]
if len(arg_names) != num_args:
# This could happen for vectorized UDxFs, since there could be a single dataframe argument
# but potentially more than one column. We will do best-effort preservation but fallback if needed.
return default_arg_names
return arg_names
except Exception as e:
logger.warning(
f"Got error {e} when trying to read argument names from function: {func}. "
"Proceeding with generic argument names."
)
return default_arg_names
def get_error_message_abbr(object_type: TempObjectType) -> str:
if object_type == TempObjectType.FUNCTION:
return "udf"
if object_type == TempObjectType.PROCEDURE:
return "stored proc"
if object_type == TempObjectType.TABLE_FUNCTION:
return "table function"
if object_type == TempObjectType.AGGREGATE_FUNCTION:
return "aggregate function"
raise ValueError(f"Expect FUNCTION of PROCEDURE, but get {object_type}")
def check_decorator_args(**kwargs):
for key, _ in kwargs.items():
if key not in REGISTER_KWARGS_ALLOWLIST:
raise ValueError(
f"Invalid key-value argument passed to the decorator: {key}"
)
def check_register_args(
object_type: TempObjectType,
name: Optional[Union[str, Iterable[str]]] = None,
is_permanent: bool = False,
stage_location: Optional[str] = None,
parallel: int = 4,
):
if is_permanent:
if not name:
raise ValueError(
f"name must be specified for permanent {get_error_message_abbr(object_type)}"
)
if not stage_location:
raise ValueError(
f"stage_location must be specified for permanent {get_error_message_abbr(object_type)}"
)
if parallel < 1 or parallel > 99:
raise ValueError(
"Supported values of parallel are from 1 to 99, " f"but got {parallel}"
)
def check_execute_as_arg(
execute_as: typing.Literal["caller", "owner", "restricted caller"]
):
if (
not isinstance(execute_as, str)
or execute_as.lower() not in EXECUTE_AS_WHITELIST
):
raise TypeError(
f"'execute_as' value '{execute_as}' is invalid, choose from "
f"{', '.join(EXECUTE_AS_WHITELIST, )}"
)
def check_python_runtime_version(runtime_version_from_requirement: Optional[str]):
system_version = f"{sys.version_info[0]}.{sys.version_info[1]}"
if (
runtime_version_from_requirement is not None
and runtime_version_from_requirement != system_version
):
raise ValueError(
f"Cloudpickle can only be used to send objects between the exact same version of Python. "
f"Your system version is {system_version} while your requirements have specified version "
f"{runtime_version_from_requirement}!"
)
def check_resource_constraint(constraint: Optional[Dict[str, str]]):
if constraint is None:
return
errors = []
for key, value in constraint.items():
if key.lower() not in ALLOWED_CONSTRAINT_CONFIGURATION:
errors.append(ValueError(f"Unknown resource constraint key '{key}'"))
continue
if value.lower() not in ALLOWED_CONSTRAINT_CONFIGURATION[key]:
errors.append(ValueError(f"Unknown value '{value}' for key '{key}'"))
if errors:
raise Exception(errors)
def process_file_path(file_path: str) -> str:
file_path = file_path.strip()
if not file_path.startswith(STAGE_PREFIX) and not os.path.exists(file_path):
raise ValueError(f"file_path {file_path} does not exist")
return file_path
def extract_return_input_types(
func: Union[Callable, Tuple[str, str]],
return_type: Optional[DataType],
input_types: Optional[List[DataType]],
object_type: TempObjectType,
output_schema: Optional[List[str]] = None,
) -> Tuple[bool, bool, Union[DataType, List[DataType]], List[DataType]]:
"""
Returns:
is_pandas_udf
is_dataframe_input
return_types
input_types
Notes:
There are 3 cases:
1. return_type and input_types are provided:
a. type hints are provided and they are all pandas.Series or pandas.DataFrame,
then combine them to pandas-related types.
b. otherwise, just use return_type and input_types.
2. return_type and input_types are not provided, but type hints are provided,
then just use the types inferred from type hints.
"""
(
return_type_from_type_hints,
input_types_from_type_hints,
) = get_types_from_type_hints(func, object_type, output_schema)
# Detect vectorized decorator hints on UDF functions (minimal surface change).
forced_pandas_udf = False
forced_is_dataframe_input = False
if object_type == TempObjectType.FUNCTION and isinstance(func, Callable):
vectorized_input_attr = get_wrapped_attr(func, "_sf_vectorized_input")
if vectorized_input_attr is not None:
forced_pandas_udf = True
if installed_pandas and vectorized_input_attr is pandas.DataFrame:
forced_is_dataframe_input = True
if installed_pandas and return_type and return_type_from_type_hints:
if isinstance(return_type_from_type_hints, PandasSeriesType):
res_return_type = (
return_type.element_type
if isinstance(return_type, PandasSeriesType)
else return_type
)
res_input_types = (
input_types[0].col_types
if len(input_types) == 1
and isinstance(input_types[0], PandasDataFrameType)
else input_types
)
res_input_types = [
tp.element_type if isinstance(tp, PandasSeriesType) else tp
for tp in res_input_types
]
if len(input_types_from_type_hints) == 0:
return True, False, res_return_type, []
elif len(input_types_from_type_hints) == 1 and isinstance(
input_types_from_type_hints[0], PandasDataFrameType
):
return True, True, res_return_type, res_input_types
elif all(
isinstance(tp, PandasSeriesType) for tp in input_types_from_type_hints
):
return True, False, res_return_type, res_input_types
elif isinstance(
return_type_from_type_hints, PandasDataFrameType
): # vectorized UDTF
return_type = PandasDataFrameType(
[x.datatype for x in return_type], [x.name for x in return_type]
)
res_return_type = return_type or return_type_from_type_hints
res_input_types = input_types or input_types_from_type_hints
if not res_return_type or (
installed_pandas
and isinstance(res_return_type, PandasSeriesType)
and not res_return_type.element_type
):
raise TypeError("The return type must be specified")
# We only want to have this check when only type hints are provided
if (
not return_type
and not input_types
and isinstance(func, Callable)
and hasattr(func, "__code__")
):
# don't count Session if it's a SP
num_args = (
func.__code__.co_argcount
if object_type == TempObjectType.FUNCTION
else func.__code__.co_argcount - 1
)
if num_args != len(input_types_from_type_hints):
raise TypeError(
f'{"" if object_type == TempObjectType.FUNCTION else f"Excluding session argument in stored procedure, "}'
f"the number of arguments ({num_args}) is different from "
f"the number of argument type hints ({len(input_types_from_type_hints)})"
)
if not installed_pandas:
return False, False, res_return_type, res_input_types
if isinstance(res_return_type, PandasSeriesType):
if len(res_input_types) == 0:
return True, False, res_return_type.element_type, []
elif len(res_input_types) == 1 and isinstance(
res_input_types[0], PandasDataFrameType
):
return (
True,
True,
res_return_type.element_type,
res_input_types[0].get_snowflake_col_datatypes(),
)
elif all(isinstance(tp, PandasSeriesType) for tp in res_input_types):
return (
True,
False,
res_return_type.element_type,
[tp.element_type for tp in res_input_types],
)
elif isinstance(res_return_type, PandasDataFrameType):
if len(res_input_types) == 0:
return True, True, res_return_type, []
elif len(res_input_types) == 1 and isinstance(
res_input_types[0], PandasDataFrameType
):
return (
True,
True,
res_return_type,
res_input_types[0].get_snowflake_col_datatypes(),
)
else:
return True, True, res_return_type, res_input_types
# If explicitly marked as vectorized via decorator, treat as pandas UDF regardless of type hints
if forced_pandas_udf:
return (
True,
forced_is_dataframe_input,
res_return_type.element_type
if isinstance(res_return_type, PandasSeriesType)
else res_return_type,
res_input_types,
)
# not pandas UDF
if not isinstance(res_return_type, (PandasSeriesType, PandasDataFrameType)) and all(
not isinstance(tp, (PandasSeriesType, PandasDataFrameType))
for tp in res_input_types
):
return False, False, res_return_type, res_input_types
raise TypeError(
f"Invalid return type or input types: return type {res_return_type}, input types {res_input_types}"
)
def process_registration_inputs(
session: "snowflake.snowpark.Session",
object_type: TempObjectType,
func: Union[Callable, Tuple[str, str]],
return_type: Optional[DataType],
input_types: Optional[List[DataType]],
name: Optional[Union[str, Iterable[str]]],
anonymous: bool = False,
output_schema: Optional[List[str]] = None,
) -> Tuple[str, bool, bool, DataType, List[DataType], List[Optional[str]]]:
"""
Args:
output_schema: List of column names of in the output, only applicable to UDTF
"""
if name:
object_name = name if isinstance(name, str) else ".".join(name)
else:
object_name = random_name_for_temp_object(object_type)
if (not anonymous) and (session is not None):
object_name = session.get_fully_qualified_name_if_possible(object_name)
validate_object_name(object_name)
# get return and input types
(
is_pandas_udf,
is_dataframe_input,
return_type,
input_types,
) = extract_return_input_types(
func, return_type, input_types or [], object_type, output_schema
)
if is_pandas_udf or is_dataframe_input:
# vectorized UDF/UDTF does not support default values. They only
# take a single input which is of type DataFrame
opt_arg_defaults = [None] * len(input_types)
else:
opt_arg_defaults = get_opt_arg_defaults(func, object_type, input_types)
return (
object_name,
is_pandas_udf,
is_dataframe_input,
return_type,
input_types,
opt_arg_defaults,
)
def cleanup_failed_permanent_registration(
session: "snowflake.snowpark.Session",
upload_file_stage_location: str,
stage_location: str,
) -> None:
if stage_location and upload_file_stage_location:
try:
logger.debug(
"Removing Snowpark uploaded file: %s",
upload_file_stage_location,
)
session._run_query(f"REMOVE {upload_file_stage_location}")
logger.info(
"Finished removing Snowpark uploaded file: %s",
upload_file_stage_location,
)
except Exception as clean_ex:
logger.warning("Failed to clean uploaded file: %s", clean_ex)
def pickle_function(func: Callable) -> bytes:
failure_hint = (
"you might have to save the unpicklable object in the local environment first, "
"add it to the UDF with session.add_import(), and read it from the UDF."
)
try:
return cloudpickle.dumps(func, protocol=pickle.HIGHEST_PROTOCOL)
# it happens when copying the global object inside the UDF that can't be pickled
except TypeError as ex:
error_message = str(ex)
if "cannot pickle" in error_message:
raise TypeError(f"{error_message}: {failure_hint}")
raise ex
# it shouldn't happen because the function can always be pickled
# but we still catch this exception here in case cloudpickle changes its implementation
except pickle.PicklingError as ex:
raise pickle.PicklingError(f"{str(ex)}: {failure_hint}")
def generate_python_code(
func: Callable,
arg_names: List[str],
object_type: TempObjectType,
is_pandas_udf: bool,
is_dataframe_input: bool,
max_batch_size: Optional[int] = None,
source_code_display: bool = False,
) -> str:
# if func is a method object, we need to extract the target function first to check
# annotations. However, we still serialize the original method because the extracted
# function will have an extra argument `cls` or `self` from the class.
if object_type == TempObjectType.TABLE_FUNCTION:
annotated_funcs = []
# clean-up annotations from process and end_partition methods if they are defined
if hasattr(func, TABLE_FUNCTION_PROCESS_METHOD):
annotated_funcs.append(getattr(func, TABLE_FUNCTION_PROCESS_METHOD))
if hasattr(func, TABLE_FUNCTION_END_PARTITION_METHOD):
annotated_funcs.append(getattr(func, TABLE_FUNCTION_END_PARTITION_METHOD))
elif object_type == TempObjectType.AGGREGATE_FUNCTION:
annotated_funcs = [
getattr(func, AGGREGATE_FUNCTION_ACCULUMATE_METHOD),
getattr(func, AGGREGATE_FUNCTION_FINISH_METHOD),
getattr(func, AGGREGATE_FUNCTION_MERGE_METHOD),
getattr(func, AGGREGATE_FUNCTION_STATE_METHOD).fget,
]
elif object_type in (TempObjectType.FUNCTION, TempObjectType.PROCEDURE):
annotated_funcs = [getattr(func, "__func__", func)]
else:
raise ValueError(
f"Expecting FUNCTION, PROCEDURE, TABLE_FUNCTION or AGGREGATE_FUNCTION for object_type, got {object_type}"
)
# clear the annotations because when the user annotates Variant and Geography,
# which are from snowpark modules and will not work on the server side
# built-in functions don't have __annotations__
# TODO(SNOW-861329): This removal could cause race condition if two sessions are trying to register UDF using the
# same decorated function/class.
annotations = [
getattr(annotated_func, "__annotations__", None)
for annotated_func in annotated_funcs
]
if any(annotations):
try:
for annotated_func in annotated_funcs:
annotated_func.__annotations__ = {}
# we still serialize the original function
pickled_func = pickle_function(func)
finally:
# restore the annotations so we don't change the original function
for annotated_func, annotation in zip(annotated_funcs, annotations):
if annotation:
annotated_func.__annotations__ = annotation
else:
pickled_func = pickle_function(func)
args = ",".join(arg_names)
try:
source_code_comment = (
code_generation.generate_source_code(func) if source_code_display else ""
)
except Exception as exc:
error_msg = (
f"Source code comment could not be generated for {func} due to error {exc}."
)
logger.debug(error_msg)
# We shall also have telemetry for the code generation
# check https://snowflakecomputing.atlassian.net/browse/SNOW-651381
source_code_comment = code_generation.comment_source_code(error_msg)
deserialization_code = f"""
import pickle
func = pickle.loads(bytes.fromhex('{pickled_func.hex()}'))
{source_code_comment}
""".rstrip()
if object_type == TempObjectType.PROCEDURE:
func_code = f"""
def {_DEFAULT_HANDLER_NAME}({args}):
return func({args})
"""