-
Notifications
You must be signed in to change notification settings - Fork 29.2k
Expand file tree
/
Copy pathtest_arrow_udtf.py
More file actions
1729 lines (1454 loc) · 70.5 KB
/
test_arrow_udtf.py
File metadata and controls
1729 lines (1454 loc) · 70.5 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
#
# 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.
#
import unittest
import logging
from typing import Iterator, Optional
from pyspark.errors import PySparkAttributeError
from pyspark.errors import PythonException
from pyspark.sql.functions import arrow_udtf, lit
from pyspark.sql.types import Row, StructType, StructField, IntegerType
from pyspark.testing.sqlutils import ReusedSQLTestCase
from pyspark.testing.utils import have_pyarrow, pyarrow_requirement_message
from pyspark.testing import assertDataFrameEqual
from pyspark.util import is_remote_only
if have_pyarrow:
import pyarrow as pa
import pyarrow.compute as pc
@unittest.skipIf(not have_pyarrow, pyarrow_requirement_message)
class ArrowUDTFTestsMixin:
def test_arrow_udtf_data_conversion_error(self):
from pyspark.sql.functions import udtf
@udtf(returnType="x int, y int")
class DataConversionErrorUDTF:
def eval(self):
# Return a non-tuple value when multiple return values are expected.
# This will cause LocalDataToArrowConversion.convert to fail with TypeError (len() on int),
# which should be wrapped in UDTF_ARROW_DATA_CONVERSION_ERROR.
yield 1
# Enable Arrow optimization for regular UDTFs
with self.sql_conf({"spark.sql.execution.pythonUDTF.arrow.enabled": "true"}):
with self.assertRaisesRegex(PythonException, "UDTF_ARROW_DATA_CONVERSION_ERROR"):
result_df = DataConversionErrorUDTF()
result_df.collect()
def test_arrow_udtf_zero_args(self):
@arrow_udtf(returnType="id int, value string")
class TestUDTF:
def eval(self) -> Iterator["pa.Table"]:
result_table = pa.table(
{
"id": pa.array([1, 2, 3], type=pa.int32()),
"value": pa.array(["a", "b", "c"], type=pa.string()),
}
)
yield result_table
# Test direct DataFrame API usage
result_df = TestUDTF()
expected_df = self.spark.createDataFrame(
[(1, "a"), (2, "b"), (3, "c")], "id int, value string"
)
assertDataFrameEqual(result_df, expected_df)
# Test SQL registration and usage
self.spark.udtf.register("test_zero_args_udtf", TestUDTF)
sql_result_df = self.spark.sql("SELECT * FROM test_zero_args_udtf()")
assertDataFrameEqual(sql_result_df, expected_df)
def test_arrow_udtf_scalar_args_only(self):
@arrow_udtf(returnType="x int, y int, sum int")
class ScalarArgsUDTF:
def eval(self, x: "pa.Array", y: "pa.Array") -> Iterator["pa.Table"]:
assert isinstance(x, pa.Array), f"Expected pa.Array, got {type(x)}"
assert isinstance(y, pa.Array), f"Expected pa.Array, got {type(y)}"
x_val = x[0].as_py()
y_val = y[0].as_py()
result_table = pa.table(
{
"x": pa.array([x_val], type=pa.int32()),
"y": pa.array([y_val], type=pa.int32()),
"sum": pa.array([x_val + y_val], type=pa.int32()),
}
)
yield result_table
# Test direct DataFrame API usage
result_df = ScalarArgsUDTF(lit(5), lit(10))
expected_df = self.spark.createDataFrame([(5, 10, 15)], "x int, y int, sum int")
assertDataFrameEqual(result_df, expected_df)
# Test SQL registration and usage
self.spark.udtf.register("ScalarArgsUDTF", ScalarArgsUDTF)
sql_result_df = self.spark.sql("SELECT * FROM ScalarArgsUDTF(5, 10)")
assertDataFrameEqual(sql_result_df, expected_df)
# Test with different values via SQL
sql_result_df2 = self.spark.sql("SELECT * FROM ScalarArgsUDTF(4, 7)")
expected_df2 = self.spark.createDataFrame([(4, 7, 11)], "x int, y int, sum int")
assertDataFrameEqual(sql_result_df2, expected_df2)
def test_arrow_udtf_record_batch_iterator(self):
@arrow_udtf(returnType="batch_id int, name string, count int")
class RecordBatchUDTF:
def eval(self, batch_size: "pa.Array") -> Iterator["pa.RecordBatch"]:
assert isinstance(batch_size, pa.Array), (
f"Expected pa.Array, got {type(batch_size)}"
)
size = batch_size[0].as_py()
for batch_id in range(3):
# Create arrays for each column
batch_id_array = pa.array([batch_id] * size, type=pa.int32())
name_array = pa.array([f"batch_{batch_id}"] * size, type=pa.string())
count_array = pa.array(list(range(size)), type=pa.int32())
# Create record batch from arrays and names
batch = pa.record_batch(
[batch_id_array, name_array, count_array],
names=["batch_id", "name", "count"],
)
yield batch
# Test direct DataFrame API usage
result_df = RecordBatchUDTF(lit(2))
expected_data = [
(0, "batch_0", 0),
(0, "batch_0", 1),
(1, "batch_1", 0),
(1, "batch_1", 1),
(2, "batch_2", 0),
(2, "batch_2", 1),
]
expected_df = self.spark.createDataFrame(
expected_data, "batch_id int, name string, count int"
)
assertDataFrameEqual(result_df, expected_df)
# Test SQL registration and usage
self.spark.udtf.register("record_batch_udtf", RecordBatchUDTF)
sql_result_df = self.spark.sql(
"SELECT * FROM record_batch_udtf(2) ORDER BY batch_id, count"
)
assertDataFrameEqual(sql_result_df, expected_df)
# Test with different batch size via SQL
sql_result_df2 = self.spark.sql("SELECT * FROM record_batch_udtf(1) ORDER BY batch_id")
expected_data2 = [
(0, "batch_0", 0),
(1, "batch_1", 0),
(2, "batch_2", 0),
]
expected_df2 = self.spark.createDataFrame(
expected_data2, "batch_id int, name string, count int"
)
assertDataFrameEqual(sql_result_df2, expected_df2)
def test_arrow_udtf_error_not_iterator(self):
@arrow_udtf(returnType="x int, y string")
class NotIteratorUDTF:
def eval(self) -> "pa.Table":
return pa.table(
{"x": pa.array([1], type=pa.int32()), "y": pa.array(["test"], type=pa.string())}
)
with self.assertRaisesRegex(PythonException, "UDTF_RETURN_NOT_ITERABLE"):
result_df = NotIteratorUDTF()
result_df.collect()
def test_arrow_udtf_error_wrong_yield_type(self):
@arrow_udtf(returnType="x int, y string")
class WrongYieldTypeUDTF:
def eval(self) -> Iterator["pa.Table"]:
yield {"x": [1], "y": ["test"]}
with self.assertRaisesRegex(PythonException, "UDTF_ARROW_TYPE_CONVERSION_ERROR"):
result_df = WrongYieldTypeUDTF()
result_df.collect()
def test_arrow_udtf_error_invalid_arrow_type(self):
@arrow_udtf(returnType="x int, y string")
class InvalidArrowTypeUDTF:
def eval(self) -> Iterator["pa.Table"]:
yield "not_an_arrow_table"
with self.assertRaisesRegex(PythonException, "UDTF_ARROW_TYPE_CONVERSION_ERROR"):
result_df = InvalidArrowTypeUDTF()
result_df.collect()
def test_arrow_udtf_error_mismatched_schema(self):
@arrow_udtf(returnType="x int, y string")
class MismatchedSchemaUDTF:
def eval(self) -> Iterator["pa.Table"]:
result_table = pa.table(
{
"wrong_col": pa.array([1], type=pa.int32()),
"another_wrong_col": pa.array([2.5], type=pa.float64()),
}
)
yield result_table
with self.assertRaisesRegex(
PythonException,
r"(?s)Result column 'x' does not exist in the output\. "
r"Expected schema: x: int32\ny: string, "
r"got: wrong_col: int32\nanother_wrong_col: double\.",
):
result_df = MismatchedSchemaUDTF()
result_df.collect()
def test_arrow_udtf_sql_with_aggregation(self):
@arrow_udtf(returnType="category string, count int")
class CategoryCountUDTF:
def eval(self, categories: "pa.Array") -> Iterator["pa.Table"]:
# The input is a single array element, extract the array contents
cat_array = categories[0].as_py() # Get the array from the first (and only) element
# Count occurrences
counts = {}
for cat in cat_array:
if cat is not None:
counts[cat] = counts.get(cat, 0) + 1
if counts:
result_table = pa.table(
{
"category": pa.array(list(counts.keys()), type=pa.string()),
"count": pa.array(list(counts.values()), type=pa.int32()),
}
)
yield result_table
self.spark.udtf.register("category_count_udtf", CategoryCountUDTF)
# Test with array input
result_df = self.spark.sql(
"SELECT * FROM category_count_udtf(array('A', 'B', 'A', 'C', 'B', 'A')) "
"ORDER BY category"
)
expected_df = self.spark.createDataFrame(
[("A", 3), ("B", 2), ("C", 1)], "category string, count int"
)
assertDataFrameEqual(result_df, expected_df)
def test_arrow_udtf_sql_with_struct_output(self):
@arrow_udtf(returnType="person struct<name:string,age:int>, status string")
class PersonStatusUDTF:
def eval(self, name: "pa.Array", age: "pa.Array") -> Iterator["pa.Table"]:
name_val = name[0].as_py()
age_val = age[0].as_py()
status = "adult" if age_val >= 18 else "minor"
# Create struct array
person_array = pa.array(
[{"name": name_val, "age": age_val}],
type=pa.struct([("name", pa.string()), ("age", pa.int32())]),
)
result_table = pa.table(
{
"person": person_array,
"status": pa.array([status], type=pa.string()),
}
)
yield result_table
self.spark.udtf.register("person_status_udtf", PersonStatusUDTF)
result_df = self.spark.sql("SELECT * FROM person_status_udtf('John', 25)")
# Note: Using Row constructor for the expected struct value
expected_df = self.spark.createDataFrame(
[(Row(name="John", age=25), "adult")],
"person struct<name:string,age:int>, status string",
)
assertDataFrameEqual(result_df, expected_df)
def test_arrow_udtf_sql_conditional_yield(self):
@arrow_udtf(returnType="number int, type string")
class FilterNumbersUDTF:
def eval(self, start: "pa.Array", end: "pa.Array") -> Iterator["pa.Table"]:
start_val = start[0].as_py()
end_val = end[0].as_py()
numbers = []
types = []
for i in range(start_val, end_val + 1):
if i % 2 == 0: # Only yield even numbers
numbers.append(i)
types.append("even")
if numbers: # Only yield if we have data
result_table = pa.table(
{
"number": pa.array(numbers, type=pa.int32()),
"type": pa.array(types, type=pa.string()),
}
)
yield result_table
self.spark.udtf.register("filter_numbers_udtf", FilterNumbersUDTF)
result_df = self.spark.sql("SELECT * FROM filter_numbers_udtf(1, 10) ORDER BY number")
expected_df = self.spark.createDataFrame(
[(2, "even"), (4, "even"), (6, "even"), (8, "even"), (10, "even")],
"number int, type string",
)
assertDataFrameEqual(result_df, expected_df)
def test_arrow_udtf_sql_empty_result(self):
@arrow_udtf(returnType="value int")
class EmptyResultUDTF:
def eval(self, condition: "pa.Array") -> Iterator["pa.Table"]:
# Only yield if condition is true
if condition[0].as_py():
result_table = pa.table(
{
"value": pa.array([42], type=pa.int32()),
}
)
yield result_table
# If condition is false, don't yield anything
self.spark.udtf.register("empty_result_udtf", EmptyResultUDTF)
# Test with true condition
result_df_true = self.spark.sql("SELECT * FROM empty_result_udtf(true)")
expected_df_true = self.spark.createDataFrame([(42,)], "value int")
assertDataFrameEqual(result_df_true, expected_df_true)
# Test with false condition (empty result)
result_df_false = self.spark.sql("SELECT * FROM empty_result_udtf(false)")
expected_df_false = self.spark.createDataFrame([], "value int")
assertDataFrameEqual(result_df_false, expected_df_false)
def test_arrow_udtf_type_coercion_long_to_int(self):
@arrow_udtf(returnType="id int")
class LongToIntUDTF:
def eval(self) -> Iterator["pa.Table"]:
result_table = pa.table(
{
"id": pa.array([1, 2, 3], type=pa.int64()), # long values
}
)
yield result_table
# Should succeed with automatic coercion
result_df = LongToIntUDTF()
expected_df = self.spark.createDataFrame([(1,), (2,), (3,)], "id int")
assertDataFrameEqual(result_df, expected_df)
def test_arrow_udtf_type_coercion_string_to_int(self):
@arrow_udtf(returnType="id int")
class StringToIntUDTF:
def eval(self) -> Iterator["pa.Table"]:
# Return string values that cannot be coerced to int
result_table = pa.table(
{
"id": pa.array(["1", "2", "xyz"], type=pa.string()),
}
)
yield result_table
# Should fail with Arrow cast exception since string cannot be cast to int
with self.assertRaisesRegex(
PythonException,
"Result type of column 'id' does not match "
"the expected type. Expected: int32, got: string.",
):
result_df = StringToIntUDTF()
result_df.collect()
def test_arrow_udtf_type_coercion_string_to_int_safe(self):
@arrow_udtf(returnType="id int")
class StringToIntUDTF:
def eval(self) -> Iterator["pa.Table"]:
result_table = pa.table(
{
"id": pa.array(["1", "2", "3"], type=pa.string()),
}
)
yield result_table
result_df = StringToIntUDTF()
expected_df = self.spark.createDataFrame([(1,), (2,), (3,)], "id int")
assertDataFrameEqual(result_df, expected_df)
def test_arrow_udtf_type_corecion_int64_to_int32_safe(self):
@arrow_udtf(returnType="id int")
class Int64ToInt32UDTF:
def eval(self) -> Iterator["pa.Table"]:
result_table = pa.table(
{
"id": pa.array([1, 2, 3], type=pa.int64()), # long values
}
)
yield result_table
result_df = Int64ToInt32UDTF()
expected_df = self.spark.createDataFrame([(1,), (2,), (3,)], "id int")
assertDataFrameEqual(result_df, expected_df)
def test_return_type_coercion_success(self):
@arrow_udtf(returnType="value int")
class CoercionSuccessUDTF:
def eval(self) -> Iterator["pa.Table"]:
result_table = pa.table(
{
"value": pa.array([10, 20, 30], type=pa.int64()), # long -> int coercion
}
)
yield result_table
result_df = CoercionSuccessUDTF()
expected_df = self.spark.createDataFrame([(10,), (20,), (30,)], "value int")
assertDataFrameEqual(result_df, expected_df)
def test_return_type_coercion_overflow(self):
@arrow_udtf(returnType="value int")
class CoercionOverflowUDTF:
def eval(self) -> Iterator["pa.Table"]:
# Return values that will cause overflow when casting long to int
result_table = pa.table(
{
"value": pa.array([2147483647 + 1], type=pa.int64()), # int32 max + 1
}
)
yield result_table
# Should fail with PyArrow overflow exception
with self.assertRaises(Exception):
result_df = CoercionOverflowUDTF()
result_df.collect()
def test_return_type_coercion_multiple_columns(self):
@arrow_udtf(returnType="id int, price float")
class MultipleColumnCoercionUDTF:
def eval(self) -> Iterator["pa.Table"]:
result_table = pa.table(
{
"id": pa.array([1, 2, 3], type=pa.int64()), # long -> int coercion
"price": pa.array(
[10.5, 20.7, 30.9], type=pa.float64()
), # double -> float coercion
}
)
yield result_table
result_df = MultipleColumnCoercionUDTF()
expected_df = self.spark.createDataFrame(
[(1, 10.5), (2, 20.7), (3, 30.9)], "id int, price float"
)
assertDataFrameEqual(result_df, expected_df)
def test_arrow_udtf_with_empty_column_result(self):
@arrow_udtf(returnType=StructType())
class EmptyResultUDTF:
def eval(self) -> Iterator["pa.Table"]:
yield pa.Table.from_struct_array(pa.array([{}] * 3))
assertDataFrameEqual(EmptyResultUDTF(), [Row(), Row(), Row()])
@arrow_udtf(returnType="id int")
class InvalidEmptyResultUDTF:
def eval(self) -> Iterator["pa.Table"]:
yield pa.Table.from_struct_array(pa.array([{}] * 3))
with self.assertRaisesRegex(PythonException, "UDTF_RETURN_SCHEMA_MISMATCH"):
result_df = InvalidEmptyResultUDTF()
result_df.collect()
def test_arrow_udtf_blocks_analyze_method_none_return_type(self):
with self.assertRaises(PySparkAttributeError) as cm:
@arrow_udtf
class AnalyzeUDTF:
def eval(self, input_col: "pa.Array") -> Iterator["pa.Table"]:
yield pa.table({"result": pa.array([1, 2, 3])})
@staticmethod
def analyze(arg):
from pyspark.sql.udtf import AnalyzeResult
return AnalyzeResult(
schema=StructType([StructField("result", IntegerType(), True)])
)
self.assertIn("INVALID_ARROW_UDTF_WITH_ANALYZE", str(cm.exception))
def test_arrow_udtf_blocks_analyze_method_with_return_type(self):
with self.assertRaises(PySparkAttributeError) as cm:
@arrow_udtf(returnType="result: int")
class AnalyzeUDTF:
def eval(self, input_col: "pa.Array") -> Iterator["pa.Table"]:
yield pa.table({"result": pa.array([1, 2, 3])})
@staticmethod
def analyze(arg):
from pyspark.sql.udtf import AnalyzeResult
return AnalyzeResult(
schema=StructType([StructField("result", IntegerType(), True)])
)
self.assertIn("INVALID_UDTF_BOTH_RETURN_TYPE_AND_ANALYZE", str(cm.exception))
def test_arrow_udtf_with_table_argument_basic(self):
@arrow_udtf(returnType="filtered_id bigint") # Use bigint to match int64
class TableArgUDTF:
def eval(self, table_data: "pa.RecordBatch") -> Iterator["pa.Table"]:
assert isinstance(table_data, pa.RecordBatch), (
f"Expected pa.RecordBatch, got {type(table_data)}"
)
# Convert record batch to table to work with it more easily
table = pa.table(table_data)
# Filter rows where id > 5
id_column = table.column("id")
mask = pa.compute.greater(id_column, pa.scalar(5))
filtered_table = table.filter(mask)
if filtered_table.num_rows > 0:
result_table = pa.table(
{"filtered_id": filtered_table.column("id")} # Keep original type (int64)
)
yield result_table
# Test with DataFrame API using asTable()
input_df = self.spark.range(8)
result_df = TableArgUDTF(input_df.asTable())
expected_df = self.spark.createDataFrame([(6,), (7,)], "filtered_id bigint")
assertDataFrameEqual(result_df, expected_df)
# Test SQL registration and usage with TABLE() syntax
self.spark.udtf.register("test_table_arg_udtf", TableArgUDTF)
sql_result_df = self.spark.sql(
"SELECT * FROM test_table_arg_udtf(TABLE(SELECT id FROM range(0, 8)))"
)
assertDataFrameEqual(sql_result_df, expected_df)
def test_arrow_udtf_with_table_argument_and_scalar(self):
@arrow_udtf(returnType="filtered_id bigint") # Use bigint to match int64
class MixedArgsUDTF:
def eval(
self, table_data: "pa.RecordBatch", threshold: "pa.Array"
) -> Iterator["pa.Table"]:
assert isinstance(threshold, pa.Array), (
f"Expected pa.Array for threshold, got {type(threshold)}"
)
assert isinstance(table_data, pa.RecordBatch), (
f"Expected pa.RecordBatch for table_data, got {type(table_data)}"
)
threshold_val = threshold[0].as_py()
# Convert record batch to table
table = pa.table(table_data)
id_column = table.column("id")
mask = pa.compute.greater(id_column, pa.scalar(threshold_val))
filtered_table = table.filter(mask)
if filtered_table.num_rows > 0:
result_table = pa.table(
{"filtered_id": filtered_table.column("id")} # Keep original type
)
yield result_table
# # Test with DataFrame API
input_df = self.spark.range(8)
result_df = MixedArgsUDTF(input_df.asTable(), lit(5))
expected_df = self.spark.createDataFrame([(6,), (7,)], "filtered_id bigint")
assertDataFrameEqual(result_df, expected_df)
# Test SQL registration and usage
self.spark.udtf.register("test_mixed_args_udtf", MixedArgsUDTF)
sql_result_df = self.spark.sql(
"SELECT * FROM test_mixed_args_udtf(TABLE(SELECT id FROM range(0, 8)), 5)"
)
assertDataFrameEqual(sql_result_df, expected_df)
def test_arrow_udtf_lateral_join_disallowed(self):
@arrow_udtf(returnType="x int, result int")
class SimpleArrowUDTF:
def eval(self, input_val: "pa.Array") -> Iterator["pa.Table"]:
val = input_val[0].as_py()
result_table = pa.table(
{
"x": pa.array([val], type=pa.int32()),
"result": pa.array([val * 2], type=pa.int32()),
}
)
yield result_table
self.spark.udtf.register("simple_arrow_udtf", SimpleArrowUDTF)
test_df = self.spark.createDataFrame([(1,), (2,), (3,)], "id int")
test_df.createOrReplaceTempView("test_table")
with self.assertRaisesRegex(Exception, "LATERAL_JOIN_WITH_ARROW_UDTF_UNSUPPORTED"):
self.spark.sql("""
SELECT t.id, f.x, f.result
FROM test_table t, LATERAL simple_arrow_udtf(t.id) f
""")
def test_arrow_udtf_lateral_join_with_table_argument_disallowed(self):
@arrow_udtf(returnType="filtered_id bigint")
class MixedArgsUDTF:
def eval(self, input_table: "pa.Table") -> Iterator["pa.Table"]:
filtered_data = input_table.filter(pc.greater(input_table["id"], 5))
result_table = pa.table({"filtered_id": filtered_data["id"]})
yield result_table
self.spark.udtf.register("mixed_args_udtf", MixedArgsUDTF)
test_df1 = self.spark.createDataFrame([(1,), (2,), (3,)], "id int")
test_df1.createOrReplaceTempView("test_table1")
test_df2 = self.spark.createDataFrame([(6,), (7,), (8,)], "id bigint")
test_df2.createOrReplaceTempView("test_table2")
# Table arguments create nested lateral joins where our CheckAnalysis rule doesn't trigger
# because the Arrow UDTF is in the inner lateral join, not the outer one our rule checks.
# So Spark's general lateral join validation catches this first with
# NON_DETERMINISTIC_LATERAL_SUBQUERIES.
with self.assertRaisesRegex(
Exception,
"UNSUPPORTED_SUBQUERY_EXPRESSION_CATEGORY.NON_DETERMINISTIC_LATERAL_SUBQUERIES",
):
self.spark.sql("""
SELECT t1.id, f.filtered_id
FROM test_table1 t1, LATERAL mixed_args_udtf(table(SELECT * FROM test_table2)) f
""")
def test_arrow_udtf_with_table_argument_then_lateral_join_allowed(self):
@arrow_udtf(returnType="processed_id bigint")
class TableArgUDTF:
def eval(self, input_table: "pa.Table") -> Iterator["pa.Table"]:
processed_data = pc.add(input_table["id"], 100)
result_table = pa.table({"processed_id": processed_data})
yield result_table
self.spark.udtf.register("table_arg_udtf", TableArgUDTF)
source_df = self.spark.createDataFrame([(1,), (2,), (3,)], "id bigint")
source_df.createOrReplaceTempView("source_table")
join_df = self.spark.createDataFrame([("A",), ("B",), ("C",)], "label string")
join_df.createOrReplaceTempView("join_table")
result_df = self.spark.sql("""
SELECT f.processed_id, j.label
FROM table_arg_udtf(table(SELECT * FROM source_table)) f,
join_table j
ORDER BY f.processed_id, j.label
""")
expected_data = [
(101, "A"),
(101, "B"),
(101, "C"),
(102, "A"),
(102, "B"),
(102, "C"),
(103, "A"),
(103, "B"),
(103, "C"),
]
expected_df = self.spark.createDataFrame(expected_data, "processed_id bigint, label string")
assertDataFrameEqual(result_df, expected_df)
def test_arrow_udtf_table_argument_with_regular_udtf_lateral_join_allowed(self):
@arrow_udtf(returnType="computed_value int")
class ComputeUDTF:
def eval(self, input_table: "pa.Table") -> Iterator["pa.Table"]:
total = pc.sum(input_table["value"]).as_py()
result_table = pa.table({"computed_value": pa.array([total], type=pa.int32())})
yield result_table
from pyspark.sql.functions import udtf
from pyspark.sql.types import StructType, StructField, IntegerType
@udtf(returnType=StructType([StructField("multiplied", IntegerType())]))
class MultiplyUDTF:
def eval(self, input_val: int):
yield (input_val * 3,)
self.spark.udtf.register("compute_udtf", ComputeUDTF)
self.spark.udtf.register("multiply_udtf", MultiplyUDTF)
values_df = self.spark.createDataFrame([(10,), (20,), (30,)], "value int")
values_df.createOrReplaceTempView("values_table")
result_df = self.spark.sql("""
SELECT c.computed_value, m.multiplied
FROM compute_udtf(table(SELECT * FROM values_table) WITH SINGLE PARTITION) c,
LATERAL multiply_udtf(c.computed_value) m
""")
expected_df = self.spark.createDataFrame([(60, 180)], "computed_value int, multiplied int")
assertDataFrameEqual(result_df, expected_df)
def test_arrow_udtf_with_named_arguments_scalar_only(self):
@arrow_udtf(returnType="x int, y int, sum int")
class NamedArgsUDTF:
def eval(self, x: "pa.Array", y: "pa.Array") -> Iterator["pa.Table"]:
assert isinstance(x, pa.Array), f"Expected pa.Array, got {type(x)}"
assert isinstance(y, pa.Array), f"Expected pa.Array, got {type(y)}"
x_val = x[0].as_py()
y_val = y[0].as_py()
result_table = pa.table(
{
"x": pa.array([x_val], type=pa.int32()),
"y": pa.array([y_val], type=pa.int32()),
"sum": pa.array([x_val + y_val], type=pa.int32()),
}
)
yield result_table
# Test SQL registration and usage with named arguments
self.spark.udtf.register("named_args_udtf", NamedArgsUDTF)
# Test with named arguments in SQL
sql_result_df = self.spark.sql("SELECT * FROM named_args_udtf(y => 10, x => 5)")
expected_df = self.spark.createDataFrame([(5, 10, 15)], "x int, y int, sum int")
assertDataFrameEqual(sql_result_df, expected_df)
# Test with mixed positional and named arguments
sql_result_df2 = self.spark.sql("SELECT * FROM named_args_udtf(7, y => 3)")
expected_df2 = self.spark.createDataFrame([(7, 3, 10)], "x int, y int, sum int")
assertDataFrameEqual(sql_result_df2, expected_df2)
def test_arrow_udtf_with_partition_by(self):
@arrow_udtf(returnType="partition_key int, sum_value int")
class SumUDTF:
def __init__(self):
self._partition_key = None
self._sum = 0
def eval(self, table_data: "pa.RecordBatch") -> Iterator["pa.Table"]:
table = pa.table(table_data)
partition_key = pc.unique(table["partition_key"]).to_pylist()
assert len(partition_key) == 1, (
f"Expected exactly one partition key, got {partition_key}"
)
self._partition_key = partition_key[0]
self._sum += pc.sum(table["value"]).as_py()
# Don't yield here - accumulate and yield in terminate
return iter(())
def terminate(self) -> Iterator["pa.Table"]:
if self._partition_key is not None:
result_table = pa.table(
{
"partition_key": pa.array([self._partition_key], type=pa.int32()),
"sum_value": pa.array([self._sum], type=pa.int32()),
}
)
yield result_table
test_data = [
(1, 10),
(2, 5),
(1, 20),
(2, 15),
(1, 30),
(3, 100),
]
input_df = self.spark.createDataFrame(test_data, "partition_key int, value int")
self.spark.udtf.register("sum_udtf", SumUDTF)
input_df.createOrReplaceTempView("test_data")
result_df = self.spark.sql("""
SELECT * FROM sum_udtf(TABLE(test_data) PARTITION BY partition_key)
""")
expected_data = [
(1, 60),
(2, 20),
(3, 100),
]
expected_df = self.spark.createDataFrame(expected_data, "partition_key int, sum_value int")
assertDataFrameEqual(result_df, expected_df)
def test_arrow_udtf_with_partition_by_and_terminate(self):
@arrow_udtf(returnType="partition_key int, count int, sum_value int")
class TerminateUDTF:
def __init__(self):
self._partition_key = None
self._count = 0
self._sum = 0
def eval(self, table_data: "pa.RecordBatch") -> Iterator["pa.Table"]:
import pyarrow.compute as pc
table = pa.table(table_data)
# Track partition key
partition_keys = pc.unique(table["partition_key"]).to_pylist()
assert len(partition_keys) == 1, f"Expected one partition key, got {partition_keys}"
self._partition_key = partition_keys[0]
# Accumulate stats but don't yield here
self._count += table.num_rows
self._sum += pc.sum(table["value"]).as_py()
# Return empty iterator - results come from terminate
return iter(())
def terminate(self) -> Iterator["pa.Table"]:
# Yield accumulated results for this partition
if self._partition_key is not None:
result_table = pa.table(
{
"partition_key": pa.array([self._partition_key], type=pa.int32()),
"count": pa.array([self._count], type=pa.int32()),
"sum_value": pa.array([self._sum], type=pa.int32()),
}
)
yield result_table
test_data = [
(3, 50),
(1, 10),
(2, 40),
(1, 20),
(2, 30),
]
input_df = self.spark.createDataFrame(test_data, "partition_key int, value int")
self.spark.udtf.register("terminate_udtf", TerminateUDTF)
input_df.createOrReplaceTempView("test_data_terminate")
result_df = self.spark.sql("""
SELECT * FROM terminate_udtf(TABLE(test_data_terminate) PARTITION BY partition_key)
ORDER BY partition_key
""")
expected_data = [
(1, 2, 30), # partition 1: 2 rows, sum = 30
(2, 2, 70), # partition 2: 2 rows, sum = 70
(3, 1, 50), # partition 3: 1 row, sum = 50
]
expected_df = self.spark.createDataFrame(
expected_data, "partition_key int, count int, sum_value int"
)
assertDataFrameEqual(result_df, expected_df)
def test_arrow_udtf_with_partition_by_and_order_by(self):
@arrow_udtf(returnType="partition_key int, first_value int, last_value int")
class OrderByUDTF:
def __init__(self):
self._partition_key = None
self._first_value = None
self._last_value = None
def eval(self, table_data: "pa.RecordBatch") -> Iterator["pa.Table"]:
import pyarrow.compute as pc
table = pa.table(table_data)
partition_keys = pc.unique(table["partition_key"]).to_pylist()
assert len(partition_keys) == 1, f"Expected one partition key, got {partition_keys}"
self._partition_key = partition_keys[0]
# Track first and last values (should be ordered)
values = table["value"].to_pylist()
if values:
if self._first_value is None:
self._first_value = values[0]
self._last_value = values[-1]
return iter(())
def terminate(self) -> Iterator["pa.Table"]:
if self._partition_key is not None:
result_table = pa.table(
{
"partition_key": pa.array([self._partition_key], type=pa.int32()),
"first_value": pa.array([self._first_value], type=pa.int32()),
"last_value": pa.array([self._last_value], type=pa.int32()),
}
)
yield result_table
test_data = [
(1, 30),
(1, 10),
(1, 20),
(2, 60),
(2, 40),
(2, 50),
]
input_df = self.spark.createDataFrame(test_data, "partition_key int, value int")
self.spark.udtf.register("order_by_udtf", OrderByUDTF)
input_df.createOrReplaceTempView("test_data_order")
result_df = self.spark.sql("""
SELECT * FROM order_by_udtf(
TABLE(test_data_order)
PARTITION BY partition_key
ORDER BY value
)
ORDER BY partition_key
""")
expected_data = [
(1, 10, 30), # partition 1: first=10 (min), last=30 (max) after ordering
(2, 40, 60), # partition 2: first=40 (min), last=60 (max) after ordering
]
expected_df = self.spark.createDataFrame(
expected_data, "partition_key int, first_value int, last_value int"
)
assertDataFrameEqual(result_df, expected_df)
def test_arrow_udtf_partition_column_removal(self):
@arrow_udtf(returnType="col1_sum int, col2_sum int")
class PartitionColumnTestUDTF:
def __init__(self):
self._col1_sum = 0
self._col2_sum = 0
self._columns_verified = False
def eval(self, table_data: "pa.RecordBatch") -> Iterator["pa.Table"]:
import pyarrow.compute as pc
table = pa.table(table_data)
# When partitioning by an expression like "col1 + col2",
# Catalyst adds the expression result as a new column at the beginning.
# The ArrowUDTFWithPartition._remove_partition_by_exprs method should
# remove this added column, leaving only the original table columns.
# Verify columns only once per partition
if not self._columns_verified:
column_names = table.column_names
# Verify we only have the original columns, not the partition expression
assert "col1" in column_names, f"Expected col1 in columns: {column_names}"
assert "col2" in column_names, f"Expected col2 in columns: {column_names}"
# The partition expression column should have been removed
assert len(column_names) == 2, (
f"Expected only col1 and col2 after partition column removal, "
f"but got: {column_names}"
)
self._columns_verified = True
# Accumulate sums - don't yield here to avoid multiple results per partition
self._col1_sum += pc.sum(table["col1"]).as_py()
self._col2_sum += pc.sum(table["col2"]).as_py()
# Return empty iterator - results come from terminate
return iter(())
def terminate(self) -> Iterator["pa.Table"]:
# Yield accumulated results for this partition
result_table = pa.table(
{
"col1_sum": pa.array([self._col1_sum], type=pa.int32()),
"col2_sum": pa.array([self._col2_sum], type=pa.int32()),
}
)
yield result_table
test_data = [
(1, 1), # partition: 1+1=2
(1, 2), # partition: 1+2=3
(2, 0), # partition: 2+0=2
(2, 1), # partition: 2+1=3
]
input_df = self.spark.createDataFrame(test_data, "col1 int, col2 int")
self.spark.udtf.register("partition_column_test_udtf", PartitionColumnTestUDTF)
input_df.createOrReplaceTempView("test_partition_removal")
# Partition by col1 + col2 expression
result_df = self.spark.sql("""
SELECT * FROM partition_column_test_udtf(
TABLE(test_partition_removal)
PARTITION BY col1 + col2
)
ORDER BY col1_sum, col2_sum
""")
expected_data = [
(3, 1), # partition 2: sum of col1s (1+2), sum of col2s (1+0)
(3, 3), # partition 3: sum of col1s (1+2), sum of col2s (2+1)
]
expected_df = self.spark.createDataFrame(expected_data, "col1_sum int, col2_sum int")