-
Notifications
You must be signed in to change notification settings - Fork 28.1k
/
worker.py
1874 lines (1577 loc) · 73.7 KB
/
worker.py
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
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Worker that receives input from Piped RDD.
"""
import os
import sys
import dataclasses
import time
import inspect
import json
from typing import Any, Callable, Iterable, Iterator, Optional
import faulthandler
from pyspark.accumulators import (
SpecialAccumulatorIds,
_accumulatorRegistry,
_deserialize_accumulator,
)
from pyspark.taskcontext import BarrierTaskContext, TaskContext
from pyspark.resource import ResourceInformation
from pyspark.util import PythonEvalType, local_connect_and_auth
from pyspark.serializers import (
write_int,
read_long,
read_bool,
write_long,
read_int,
SpecialLengths,
UTF8Deserializer,
CPickleSerializer,
BatchedSerializer,
)
from pyspark.sql.functions import SkipRestOfInputTableException
from pyspark.sql.pandas.serializers import (
ArrowStreamPandasUDFSerializer,
ArrowStreamPandasUDTFSerializer,
CogroupArrowUDFSerializer,
CogroupPandasUDFSerializer,
ArrowStreamUDFSerializer,
ArrowStreamGroupUDFSerializer,
ApplyInPandasWithStateSerializer,
)
from pyspark.sql.pandas.types import to_arrow_type
from pyspark.sql.types import (
ArrayType,
BinaryType,
DataType,
MapType,
Row,
StringType,
StructType,
_create_row,
_parse_datatype_json_string,
)
from pyspark.util import fail_on_stopiteration, handle_worker_exception
from pyspark import shuffle
from pyspark.errors import PySparkRuntimeError, PySparkTypeError
from pyspark.worker_util import (
check_python_version,
read_command,
pickleSer,
send_accumulator_updates,
setup_broadcasts,
setup_memory_limits,
setup_spark_files,
utf8_deserializer,
)
try:
import memory_profiler # noqa: F401
has_memory_profiler = True
except Exception:
has_memory_profiler = False
def report_times(outfile, boot, init, finish):
write_int(SpecialLengths.TIMING_DATA, outfile)
write_long(int(1000 * boot), outfile)
write_long(int(1000 * init), outfile)
write_long(int(1000 * finish), outfile)
def chain(f, g):
"""chain two functions together"""
return lambda *a: g(f(*a))
def wrap_udf(f, args_offsets, kwargs_offsets, return_type):
func, args_kwargs_offsets = wrap_kwargs_support(f, args_offsets, kwargs_offsets)
if return_type.needConversion():
toInternal = return_type.toInternal
return args_kwargs_offsets, lambda *a: toInternal(func(*a))
else:
return args_kwargs_offsets, lambda *a: func(*a)
def wrap_scalar_pandas_udf(f, args_offsets, kwargs_offsets, return_type):
func, args_kwargs_offsets = wrap_kwargs_support(f, args_offsets, kwargs_offsets)
arrow_return_type = to_arrow_type(return_type)
def verify_result_type(result):
if not hasattr(result, "__len__"):
pd_type = "pandas.DataFrame" if type(return_type) == StructType else "pandas.Series"
raise PySparkTypeError(
errorClass="UDF_RETURN_TYPE",
messageParameters={
"expected": pd_type,
"actual": type(result).__name__,
},
)
return result
def verify_result_length(result, length):
if len(result) != length:
raise PySparkRuntimeError(
errorClass="SCHEMA_MISMATCH_FOR_PANDAS_UDF",
messageParameters={
"expected": str(length),
"actual": str(len(result)),
},
)
return result
return (
args_kwargs_offsets,
lambda *a: (
verify_result_length(verify_result_type(func(*a)), len(a[0])),
arrow_return_type,
),
)
def wrap_arrow_batch_udf(f, args_offsets, kwargs_offsets, return_type):
import pandas as pd
func, args_kwargs_offsets = wrap_kwargs_support(f, args_offsets, kwargs_offsets)
arrow_return_type = to_arrow_type(return_type)
# "result_func" ensures the result of a Python UDF to be consistent with/without Arrow
# optimization.
# Otherwise, an Arrow-optimized Python UDF raises "pyarrow.lib.ArrowTypeError: Expected a
# string or bytes dtype, got ..." whereas a non-Arrow-optimized Python UDF returns
# successfully.
result_func = lambda pdf: pdf # noqa: E731
if type(return_type) == StringType:
result_func = lambda r: str(r) if r is not None else r # noqa: E731
elif type(return_type) == BinaryType:
result_func = lambda r: bytes(r) if r is not None else r # noqa: E731
@fail_on_stopiteration
def evaluate(*args: pd.Series) -> pd.Series:
return pd.Series([result_func(func(*row)) for row in zip(*args)])
def verify_result_length(result, length):
if len(result) != length:
raise PySparkRuntimeError(
errorClass="SCHEMA_MISMATCH_FOR_PANDAS_UDF",
messageParameters={
"expected": str(length),
"actual": str(len(result)),
},
)
return result
return (
args_kwargs_offsets,
lambda *a: (verify_result_length(evaluate(*a), len(a[0])), arrow_return_type),
)
def wrap_pandas_batch_iter_udf(f, return_type):
arrow_return_type = to_arrow_type(return_type)
iter_type_label = "pandas.DataFrame" if type(return_type) == StructType else "pandas.Series"
def verify_result(result):
if not isinstance(result, Iterator) and not hasattr(result, "__iter__"):
raise PySparkTypeError(
errorClass="UDF_RETURN_TYPE",
messageParameters={
"expected": "iterator of {}".format(iter_type_label),
"actual": type(result).__name__,
},
)
return result
def verify_element(elem):
import pandas as pd
if not isinstance(elem, pd.DataFrame if type(return_type) == StructType else pd.Series):
raise PySparkTypeError(
errorClass="UDF_RETURN_TYPE",
messageParameters={
"expected": "iterator of {}".format(iter_type_label),
"actual": "iterator of {}".format(type(elem).__name__),
},
)
verify_pandas_result(
elem, return_type, assign_cols_by_name=True, truncate_return_schema=True
)
return elem
return lambda *iterator: map(
lambda res: (res, arrow_return_type), map(verify_element, verify_result(f(*iterator)))
)
def verify_pandas_result(result, return_type, assign_cols_by_name, truncate_return_schema):
import pandas as pd
if type(return_type) == StructType:
if not isinstance(result, pd.DataFrame):
raise PySparkTypeError(
errorClass="UDF_RETURN_TYPE",
messageParameters={
"expected": "pandas.DataFrame",
"actual": type(result).__name__,
},
)
# check the schema of the result only if it is not empty or has columns
if not result.empty or len(result.columns) != 0:
# if any column name of the result is a string
# the column names of the result have to match the return type
# see create_array in pyspark.sql.pandas.serializers.ArrowStreamPandasSerializer
field_names = set([field.name for field in return_type.fields])
# only the first len(field_names) result columns are considered
# when truncating the return schema
result_columns = (
result.columns[: len(field_names)] if truncate_return_schema else result.columns
)
column_names = set(result_columns)
if (
assign_cols_by_name
and any(isinstance(name, str) for name in result.columns)
and column_names != field_names
):
missing = sorted(list(field_names.difference(column_names)))
missing = f" Missing: {', '.join(missing)}." if missing else ""
extra = sorted(list(column_names.difference(field_names)))
extra = f" Unexpected: {', '.join(extra)}." if extra else ""
raise PySparkRuntimeError(
errorClass="RESULT_COLUMNS_MISMATCH_FOR_PANDAS_UDF",
messageParameters={
"missing": missing,
"extra": extra,
},
)
# otherwise the number of columns of result have to match the return type
elif len(result_columns) != len(return_type):
raise PySparkRuntimeError(
errorClass="RESULT_LENGTH_MISMATCH_FOR_PANDAS_UDF",
messageParameters={
"expected": str(len(return_type)),
"actual": str(len(result.columns)),
},
)
else:
if not isinstance(result, pd.Series):
raise PySparkTypeError(
errorClass="UDF_RETURN_TYPE",
messageParameters={"expected": "pandas.Series", "actual": type(result).__name__},
)
def wrap_arrow_batch_iter_udf(f, return_type):
arrow_return_type = to_arrow_type(return_type)
def verify_result(result):
if not isinstance(result, Iterator) and not hasattr(result, "__iter__"):
raise PySparkTypeError(
errorClass="UDF_RETURN_TYPE",
messageParameters={
"expected": "iterator of pyarrow.RecordBatch",
"actual": type(result).__name__,
},
)
return result
def verify_element(elem):
import pyarrow as pa
if not isinstance(elem, pa.RecordBatch):
raise PySparkTypeError(
errorClass="UDF_RETURN_TYPE",
messageParameters={
"expected": "iterator of pyarrow.RecordBatch",
"actual": "iterator of {}".format(type(elem).__name__),
},
)
return elem
return lambda *iterator: map(
lambda res: (res, arrow_return_type), map(verify_element, verify_result(f(*iterator)))
)
def wrap_cogrouped_map_arrow_udf(f, return_type, argspec, runner_conf):
_assign_cols_by_name = assign_cols_by_name(runner_conf)
if _assign_cols_by_name:
expected_cols_and_types = {
col.name: to_arrow_type(col.dataType) for col in return_type.fields
}
else:
expected_cols_and_types = [
(col.name, to_arrow_type(col.dataType)) for col in return_type.fields
]
def wrapped(left_key_table, left_value_table, right_key_table, right_value_table):
if len(argspec.args) == 2:
result = f(left_value_table, right_value_table)
elif len(argspec.args) == 3:
key_table = left_key_table if left_key_table.num_rows > 0 else right_key_table
key = tuple(c[0] for c in key_table.columns)
result = f(key, left_value_table, right_value_table)
verify_arrow_result(result, _assign_cols_by_name, expected_cols_and_types)
return result.to_batches()
return lambda kl, vl, kr, vr: (wrapped(kl, vl, kr, vr), to_arrow_type(return_type))
def wrap_cogrouped_map_pandas_udf(f, return_type, argspec, runner_conf):
_assign_cols_by_name = assign_cols_by_name(runner_conf)
def wrapped(left_key_series, left_value_series, right_key_series, right_value_series):
import pandas as pd
left_df = pd.concat(left_value_series, axis=1)
right_df = pd.concat(right_value_series, axis=1)
if len(argspec.args) == 2:
result = f(left_df, right_df)
elif len(argspec.args) == 3:
key_series = left_key_series if not left_df.empty else right_key_series
key = tuple(s[0] for s in key_series)
result = f(key, left_df, right_df)
verify_pandas_result(
result, return_type, _assign_cols_by_name, truncate_return_schema=False
)
return result
return lambda kl, vl, kr, vr: [(wrapped(kl, vl, kr, vr), to_arrow_type(return_type))]
def verify_arrow_result(table, assign_cols_by_name, expected_cols_and_types):
import pyarrow as pa
if not isinstance(table, pa.Table):
raise PySparkTypeError(
errorClass="UDF_RETURN_TYPE",
messageParameters={
"expected": "pyarrow.Table",
"actual": type(table).__name__,
},
)
# the types of the fields have to be identical to return type
# an empty table can have no columns; if there are columns, they have to match
if table.num_columns != 0 or table.num_rows != 0:
# columns are either mapped by name or position
if assign_cols_by_name:
actual_cols_and_types = {
name: dataType for name, dataType in zip(table.schema.names, table.schema.types)
}
missing = sorted(
list(set(expected_cols_and_types.keys()).difference(actual_cols_and_types.keys()))
)
extra = sorted(
list(set(actual_cols_and_types.keys()).difference(expected_cols_and_types.keys()))
)
if missing or extra:
missing = f" Missing: {', '.join(missing)}." if missing else ""
extra = f" Unexpected: {', '.join(extra)}." if extra else ""
raise PySparkRuntimeError(
errorClass="RESULT_COLUMNS_MISMATCH_FOR_ARROW_UDF",
messageParameters={
"missing": missing,
"extra": extra,
},
)
column_types = [
(name, expected_cols_and_types[name], actual_cols_and_types[name])
for name in sorted(expected_cols_and_types.keys())
]
else:
actual_cols_and_types = [
(name, dataType) for name, dataType in zip(table.schema.names, table.schema.types)
]
column_types = [
(expected_name, expected_type, actual_type)
for (expected_name, expected_type), (actual_name, actual_type) in zip(
expected_cols_and_types, actual_cols_and_types
)
]
type_mismatch = [
(name, expected, actual)
for name, expected, actual in column_types
if actual != expected
]
if type_mismatch:
raise PySparkRuntimeError(
errorClass="RESULT_TYPE_MISMATCH_FOR_ARROW_UDF",
messageParameters={
"mismatch": ", ".join(
"column '{}' (expected {}, actual {})".format(name, expected, actual)
for name, expected, actual in type_mismatch
)
},
)
def wrap_grouped_map_arrow_udf(f, return_type, argspec, runner_conf):
_assign_cols_by_name = assign_cols_by_name(runner_conf)
if _assign_cols_by_name:
expected_cols_and_types = {
col.name: to_arrow_type(col.dataType) for col in return_type.fields
}
else:
expected_cols_and_types = [
(col.name, to_arrow_type(col.dataType)) for col in return_type.fields
]
def wrapped(key_table, value_table):
if len(argspec.args) == 1:
result = f(value_table)
elif len(argspec.args) == 2:
key = tuple(c[0] for c in key_table.columns)
result = f(key, value_table)
verify_arrow_result(result, _assign_cols_by_name, expected_cols_and_types)
return result.to_batches()
return lambda k, v: (wrapped(k, v), to_arrow_type(return_type))
def wrap_grouped_map_pandas_udf(f, return_type, argspec, runner_conf):
_assign_cols_by_name = assign_cols_by_name(runner_conf)
def wrapped(key_series, value_series):
import pandas as pd
if len(argspec.args) == 1:
result = f(pd.concat(value_series, axis=1))
elif len(argspec.args) == 2:
key = tuple(s[0] for s in key_series)
result = f(key, pd.concat(value_series, axis=1))
verify_pandas_result(
result, return_type, _assign_cols_by_name, truncate_return_schema=False
)
return result
return lambda k, v: [(wrapped(k, v), to_arrow_type(return_type))]
def wrap_grouped_map_pandas_udf_with_state(f, return_type):
"""
Provides a new lambda instance wrapping user function of applyInPandasWithState.
The lambda instance receives (key series, iterator of value series, state) and performs
some conversion to be adapted with the signature of user function.
See the function doc of inner function `wrapped` for more details on what adapter does.
See the function doc of `mapper` function for
`eval_type == PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF_WITH_STATE` for more details on
the input parameters of lambda function.
Along with the returned iterator, the lambda instance will also produce the return_type as
converted to the arrow schema.
"""
def wrapped(key_series, value_series_gen, state):
"""
Provide an adapter of the user function performing below:
- Extract the first value of all columns in key series and produce as a tuple.
- If the state has timed out, call the user function with empty pandas DataFrame.
- If not, construct a new generator which converts each element of value series to
pandas DataFrame (lazy evaluation), and call the user function with the generator
- Verify each element of returned iterator to check the schema of pandas DataFrame.
"""
import pandas as pd
key = tuple(s[0] for s in key_series)
if state.hasTimedOut:
# Timeout processing pass empty iterator. Here we return an empty DataFrame instead.
values = [
pd.DataFrame(columns=pd.concat(next(value_series_gen), axis=1).columns),
]
else:
values = (pd.concat(x, axis=1) for x in value_series_gen)
result_iter = f(key, values, state)
def verify_element(result):
if not isinstance(result, pd.DataFrame):
raise PySparkTypeError(
errorClass="UDF_RETURN_TYPE",
messageParameters={
"expected": "iterator of pandas.DataFrame",
"actual": "iterator of {}".format(type(result).__name__),
},
)
# the number of columns of result have to match the return type
# but it is fine for result to have no columns at all if it is empty
if not (
len(result.columns) == len(return_type)
or (len(result.columns) == 0 and result.empty)
):
raise PySparkRuntimeError(
errorClass="RESULT_LENGTH_MISMATCH_FOR_PANDAS_UDF",
messageParameters={
"expected": str(len(return_type)),
"actual": str(len(result.columns)),
},
)
return result
if isinstance(result_iter, pd.DataFrame):
raise PySparkTypeError(
errorClass="UDF_RETURN_TYPE",
messageParameters={
"expected": "iterable of pandas.DataFrame",
"actual": type(result_iter).__name__,
},
)
try:
iter(result_iter)
except TypeError:
raise PySparkTypeError(
errorClass="UDF_RETURN_TYPE",
messageParameters={"expected": "iterable", "actual": type(result_iter).__name__},
)
result_iter_with_validation = (verify_element(x) for x in result_iter)
return (
result_iter_with_validation,
state,
)
return lambda k, v, s: [(wrapped(k, v, s), to_arrow_type(return_type))]
def wrap_grouped_agg_pandas_udf(f, args_offsets, kwargs_offsets, return_type):
func, args_kwargs_offsets = wrap_kwargs_support(f, args_offsets, kwargs_offsets)
arrow_return_type = to_arrow_type(return_type)
def wrapped(*series):
import pandas as pd
result = func(*series)
return pd.Series([result])
return (
args_kwargs_offsets,
lambda *a: (wrapped(*a), arrow_return_type),
)
def wrap_window_agg_pandas_udf(
f, args_offsets, kwargs_offsets, return_type, runner_conf, udf_index
):
window_bound_types_str = runner_conf.get("pandas_window_bound_types")
window_bound_type = [t.strip().lower() for t in window_bound_types_str.split(",")][udf_index]
if window_bound_type == "bounded":
return wrap_bounded_window_agg_pandas_udf(f, args_offsets, kwargs_offsets, return_type)
elif window_bound_type == "unbounded":
return wrap_unbounded_window_agg_pandas_udf(f, args_offsets, kwargs_offsets, return_type)
else:
raise PySparkRuntimeError(
errorClass="INVALID_WINDOW_BOUND_TYPE",
messageParameters={
"window_bound_type": window_bound_type,
},
)
def wrap_unbounded_window_agg_pandas_udf(f, args_offsets, kwargs_offsets, return_type):
func, args_kwargs_offsets = wrap_kwargs_support(f, args_offsets, kwargs_offsets)
# This is similar to grouped_agg_pandas_udf, the only difference
# is that window_agg_pandas_udf needs to repeat the return value
# to match window length, where grouped_agg_pandas_udf just returns
# the scalar value.
arrow_return_type = to_arrow_type(return_type)
def wrapped(*series):
import pandas as pd
result = func(*series)
return pd.Series([result]).repeat(len(series[0]))
return (
args_kwargs_offsets,
lambda *a: (wrapped(*a), arrow_return_type),
)
def wrap_bounded_window_agg_pandas_udf(f, args_offsets, kwargs_offsets, return_type):
# args_offsets should have at least 2 for begin_index, end_index.
assert len(args_offsets) >= 2, len(args_offsets)
func, args_kwargs_offsets = wrap_kwargs_support(f, args_offsets[2:], kwargs_offsets)
arrow_return_type = to_arrow_type(return_type)
def wrapped(begin_index, end_index, *series):
import pandas as pd
result = []
# Index operation is faster on np.ndarray,
# So we turn the index series into np array
# here for performance
begin_array = begin_index.values
end_array = end_index.values
for i in range(len(begin_array)):
# Note: Create a slice from a series for each window is
# actually pretty expensive. However, there
# is no easy way to reduce cost here.
# Note: s.iloc[i : j] is about 30% faster than s[i: j], with
# the caveat that the created slices shares the same
# memory with s. Therefore, user are not allowed to
# change the value of input series inside the window
# function. It is rare that user needs to modify the
# input series in the window function, and therefore,
# it is be a reasonable restriction.
# Note: Calling reset_index on the slices will increase the cost
# of creating slices by about 100%. Therefore, for performance
# reasons we don't do it here.
series_slices = [s.iloc[begin_array[i] : end_array[i]] for s in series]
result.append(func(*series_slices))
return pd.Series(result)
return (
args_offsets[:2] + args_kwargs_offsets,
lambda *a: (wrapped(*a), arrow_return_type),
)
def wrap_kwargs_support(f, args_offsets, kwargs_offsets):
if len(kwargs_offsets):
keys = list(kwargs_offsets.keys())
len_args_offsets = len(args_offsets)
if len_args_offsets > 0:
def func(*args):
return f(*args[:len_args_offsets], **dict(zip(keys, args[len_args_offsets:])))
else:
def func(*args):
return f(**dict(zip(keys, args)))
return func, args_offsets + [kwargs_offsets[key] for key in keys]
else:
return f, args_offsets
def _supports_profiler(eval_type: int) -> bool:
return eval_type not in (
PythonEvalType.SQL_SCALAR_PANDAS_ITER_UDF,
PythonEvalType.SQL_MAP_PANDAS_ITER_UDF,
PythonEvalType.SQL_MAP_ARROW_ITER_UDF,
PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF_WITH_STATE,
)
def wrap_perf_profiler(f, result_id):
import cProfile
import pstats
from pyspark.sql.profiler import ProfileResultsParam
accumulator = _deserialize_accumulator(
SpecialAccumulatorIds.SQL_UDF_PROFIER, None, ProfileResultsParam
)
def profiling_func(*args, **kwargs):
with cProfile.Profile() as pr:
ret = f(*args, **kwargs)
st = pstats.Stats(pr)
st.stream = None # make it picklable
st.strip_dirs()
accumulator.add({result_id: (st, None)})
return ret
return profiling_func
def wrap_memory_profiler(f, result_id):
from pyspark.sql.profiler import ProfileResultsParam
from pyspark.profiler import UDFLineProfilerV2
accumulator = _deserialize_accumulator(
SpecialAccumulatorIds.SQL_UDF_PROFIER, None, ProfileResultsParam
)
def profiling_func(*args, **kwargs):
profiler = UDFLineProfilerV2()
wrapped = profiler(f)
ret = wrapped(*args, **kwargs)
codemap_dict = {
filename: list(line_iterator) for filename, line_iterator in profiler.code_map.items()
}
accumulator.add({result_id: (None, codemap_dict)})
return ret
return profiling_func
def read_single_udf(pickleSer, infile, eval_type, runner_conf, udf_index, profiler):
num_arg = read_int(infile)
if eval_type in (
PythonEvalType.SQL_BATCHED_UDF,
PythonEvalType.SQL_ARROW_BATCHED_UDF,
PythonEvalType.SQL_SCALAR_PANDAS_UDF,
PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF,
PythonEvalType.SQL_WINDOW_AGG_PANDAS_UDF,
# The below doesn't support named argument, but shares the same protocol.
PythonEvalType.SQL_SCALAR_PANDAS_ITER_UDF,
):
args_offsets = []
kwargs_offsets = {}
for _ in range(num_arg):
offset = read_int(infile)
if read_bool(infile):
name = utf8_deserializer.loads(infile)
kwargs_offsets[name] = offset
else:
args_offsets.append(offset)
else:
args_offsets = [read_int(infile) for i in range(num_arg)]
kwargs_offsets = {}
chained_func = None
for i in range(read_int(infile)):
f, return_type = read_command(pickleSer, infile)
if chained_func is None:
chained_func = f
else:
chained_func = chain(chained_func, f)
if profiler == "perf":
result_id = read_long(infile)
if _supports_profiler(eval_type):
profiling_func = wrap_perf_profiler(chained_func, result_id)
else:
profiling_func = chained_func
elif profiler == "memory":
result_id = read_long(infile)
if _supports_profiler(eval_type) and has_memory_profiler:
profiling_func = wrap_memory_profiler(chained_func, result_id)
else:
profiling_func = chained_func
else:
profiling_func = chained_func
if eval_type in (
PythonEvalType.SQL_SCALAR_PANDAS_ITER_UDF,
PythonEvalType.SQL_ARROW_BATCHED_UDF,
):
func = profiling_func
else:
# make sure StopIteration's raised in the user code are not ignored
# when they are processed in a for loop, raise them as RuntimeError's instead
func = fail_on_stopiteration(profiling_func)
# the last returnType will be the return type of UDF
if eval_type == PythonEvalType.SQL_SCALAR_PANDAS_UDF:
return wrap_scalar_pandas_udf(func, args_offsets, kwargs_offsets, return_type)
elif eval_type == PythonEvalType.SQL_ARROW_BATCHED_UDF:
return wrap_arrow_batch_udf(func, args_offsets, kwargs_offsets, return_type)
elif eval_type == PythonEvalType.SQL_SCALAR_PANDAS_ITER_UDF:
return args_offsets, wrap_pandas_batch_iter_udf(func, return_type)
elif eval_type == PythonEvalType.SQL_MAP_PANDAS_ITER_UDF:
return args_offsets, wrap_pandas_batch_iter_udf(func, return_type)
elif eval_type == PythonEvalType.SQL_MAP_ARROW_ITER_UDF:
return args_offsets, wrap_arrow_batch_iter_udf(func, return_type)
elif eval_type == PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF:
argspec = inspect.getfullargspec(chained_func) # signature was lost when wrapping it
return args_offsets, wrap_grouped_map_pandas_udf(func, return_type, argspec, runner_conf)
elif eval_type == PythonEvalType.SQL_GROUPED_MAP_ARROW_UDF:
argspec = inspect.getfullargspec(chained_func) # signature was lost when wrapping it
return args_offsets, wrap_grouped_map_arrow_udf(func, return_type, argspec, runner_conf)
elif eval_type == PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF_WITH_STATE:
return args_offsets, wrap_grouped_map_pandas_udf_with_state(func, return_type)
elif eval_type == PythonEvalType.SQL_COGROUPED_MAP_PANDAS_UDF:
argspec = inspect.getfullargspec(chained_func) # signature was lost when wrapping it
return args_offsets, wrap_cogrouped_map_pandas_udf(func, return_type, argspec, runner_conf)
elif eval_type == PythonEvalType.SQL_COGROUPED_MAP_ARROW_UDF:
argspec = inspect.getfullargspec(chained_func) # signature was lost when wrapping it
return args_offsets, wrap_cogrouped_map_arrow_udf(func, return_type, argspec, runner_conf)
elif eval_type == PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF:
return wrap_grouped_agg_pandas_udf(func, args_offsets, kwargs_offsets, return_type)
elif eval_type == PythonEvalType.SQL_WINDOW_AGG_PANDAS_UDF:
return wrap_window_agg_pandas_udf(
func, args_offsets, kwargs_offsets, return_type, runner_conf, udf_index
)
elif eval_type == PythonEvalType.SQL_BATCHED_UDF:
return wrap_udf(func, args_offsets, kwargs_offsets, return_type)
else:
raise ValueError("Unknown eval type: {}".format(eval_type))
# Used by SQL_GROUPED_MAP_PANDAS_UDF, SQL_GROUPED_MAP_ARROW_UDF,
# SQL_COGROUPED_MAP_PANDAS_UDF, SQL_COGROUPED_MAP_ARROW_UDF,
# SQL_GROUPED_MAP_PANDAS_UDF_WITH_STATE,
# SQL_SCALAR_PANDAS_UDF and SQL_ARROW_BATCHED_UDF when
# returning StructType
def assign_cols_by_name(runner_conf):
return (
runner_conf.get(
"spark.sql.legacy.execution.pandas.groupedMap.assignColumnsByName", "true"
).lower()
== "true"
)
# Read and process a serialized user-defined table function (UDTF) from a socket.
# It expects the UDTF to be in a specific format and performs various checks to
# ensure the UDTF is valid. This function also prepares a mapper function for applying
# the UDTF logic to input rows.
def read_udtf(pickleSer, infile, eval_type):
if eval_type == PythonEvalType.SQL_ARROW_TABLE_UDF:
runner_conf = {}
# Load conf used for arrow evaluation.
num_conf = read_int(infile)
for i in range(num_conf):
k = utf8_deserializer.loads(infile)
v = utf8_deserializer.loads(infile)
runner_conf[k] = v
# NOTE: if timezone is set here, that implies respectSessionTimeZone is True
timezone = runner_conf.get("spark.sql.session.timeZone", None)
safecheck = (
runner_conf.get("spark.sql.execution.pandas.convertToArrowArraySafely", "false").lower()
== "true"
)
ser = ArrowStreamPandasUDTFSerializer(timezone, safecheck)
else:
# Each row is a group so do not batch but send one by one.
ser = BatchedSerializer(CPickleSerializer(), 1)
# See 'PythonUDTFRunner.PythonUDFWriterThread.writeCommand'
num_arg = read_int(infile)
args_offsets = []
kwargs_offsets = {}
for _ in range(num_arg):
offset = read_int(infile)
if read_bool(infile):
name = utf8_deserializer.loads(infile)
kwargs_offsets[name] = offset
else:
args_offsets.append(offset)
num_partition_child_indexes = read_int(infile)
partition_child_indexes = [read_int(infile) for i in range(num_partition_child_indexes)]
has_pickled_analyze_result = read_bool(infile)
if has_pickled_analyze_result:
pickled_analyze_result = pickleSer._read_with_length(infile)
else:
pickled_analyze_result = None
# Initially we assume that the UDTF __init__ method accepts the pickled AnalyzeResult,
# although we may set this to false later if we find otherwise.
handler = read_command(pickleSer, infile)
if not isinstance(handler, type):
raise PySparkRuntimeError(
f"Invalid UDTF handler type. Expected a class (type 'type'), but "
f"got an instance of {type(handler).__name__}."
)
return_type = _parse_datatype_json_string(utf8_deserializer.loads(infile))
if not isinstance(return_type, StructType):
raise PySparkRuntimeError(
f"The return type of a UDTF must be a struct type, but got {type(return_type)}."
)
udtf_name = utf8_deserializer.loads(infile)
# Update the handler that creates a new UDTF instance to first try calling the UDTF constructor
# with one argument containing the previous AnalyzeResult. If that fails, then try a constructor
# with no arguments. In this way each UDTF class instance can decide if it wants to inspect the
# AnalyzeResult.
udtf_init_args = inspect.getfullargspec(handler)
if has_pickled_analyze_result:
if len(udtf_init_args.args) > 2:
raise PySparkRuntimeError(
errorClass="UDTF_CONSTRUCTOR_INVALID_IMPLEMENTS_ANALYZE_METHOD",
messageParameters={"name": udtf_name},
)
elif len(udtf_init_args.args) == 2:
prev_handler = handler
def construct_udtf():
# Here we pass the AnalyzeResult to the UDTF's __init__ method.
return prev_handler(dataclasses.replace(pickled_analyze_result))
handler = construct_udtf
elif len(udtf_init_args.args) > 1:
raise PySparkRuntimeError(
errorClass="UDTF_CONSTRUCTOR_INVALID_NO_ANALYZE_METHOD",
messageParameters={"name": udtf_name},
)
class UDTFWithPartitions:
"""
This implements the logic of a UDTF that accepts an input TABLE argument with one or more
PARTITION BY expressions.
For example, let's assume we have a table like:
CREATE TABLE t (c1 INT, c2 INT) USING delta;
Then for the following queries:
SELECT * FROM my_udtf(TABLE (t) PARTITION BY c1, c2);
The partition_child_indexes will be: 0, 1.
SELECT * FROM my_udtf(TABLE (t) PARTITION BY c1, c2 + 4);
The partition_child_indexes will be: 0, 2 (where we add a projection for "c2 + 4").
"""
def __init__(self, create_udtf: Callable, partition_child_indexes: list):
"""
Creates a new instance of this class to wrap the provided UDTF with another one that
checks the values of projected partitioning expressions on consecutive rows to figure
out when the partition boundaries change.
Parameters
----------
create_udtf: function
Function to create a new instance of the UDTF to be invoked.
partition_child_indexes: list
List of integers identifying zero-based indexes of the columns of the input table
that contain projected partitioning expressions. This class will inspect these
values for each pair of consecutive input rows. When they change, this indicates
the boundary between two partitions, and we will invoke the 'terminate' method on
the UDTF class instance and then destroy it and create a new one to implement the
desired partitioning semantics.
"""
self._create_udtf: Callable = create_udtf
self._udtf = create_udtf()
self._prev_arguments: list = list()
self._partition_child_indexes: list = partition_child_indexes
self._eval_raised_skip_rest_of_input_table: bool = False
def eval(self, *args, **kwargs) -> Iterator:
changed_partitions = self._check_partition_boundaries(
list(args) + list(kwargs.values())
)
if changed_partitions:
if self._udtf.terminate is not None:
result = self._udtf.terminate()
if result is not None:
for row in result:
yield row
self._udtf = self._create_udtf()
self._eval_raised_skip_rest_of_input_table = False