Repository navigation
Expand file tree
/
Copy pathtest_parquet.py
More file actions
1822 lines (1626 loc) · 56.3 KB
/
Copy pathtest_parquet.py
File metadata and controls
1822 lines (1626 loc) · 56.3 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
# SPDX-FileCopyrightText: Copyright (c) 2024-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import datetime
import decimal
import io
import json
import os
import struct
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
import pytest
from pyarrow.parquet import read_table, write_table
from utils import (
BLOOM_FILTER_OPTIONS,
assert_table_and_meta_eq,
get_bytes_from_source,
make_source,
requires_pyarrow_bloom_filters,
synchronize_stream,
)
from rmm.pylibrmm.device_buffer import DeviceBuffer
from rmm.pylibrmm.stream import Stream
import pylibcudf as plc
from pylibcudf.expressions import (
ASTOperator,
ColumnNameReference,
ColumnReference,
Literal,
Operation,
)
# Shared kwargs to pass to make_source
_COMMON_PARQUET_SOURCE_KWARGS = {"format": "parquet"}
def _extract_footer_bytes_with_suffix(
file_bytes: bytes,
) -> tuple[memoryview, memoryview]:
"""Return footer bytes with and without the parquet footer suffix."""
parquet_suffix_size = 8 # 4-byte footer length + 4-byte magic bytes (PAR1)
file_memoryview = memoryview(file_bytes)
footer_size = int.from_bytes(
file_memoryview[-parquet_suffix_size:-4], byteorder="little"
)
footer_start = len(file_memoryview) - parquet_suffix_size - footer_size
footer_stop = len(file_memoryview)
footer_with_suffix = file_memoryview[footer_start:footer_stop]
footer_without_suffix = file_memoryview[
footer_start : footer_stop - parquet_suffix_size
]
return footer_without_suffix, footer_with_suffix
@pytest.mark.parametrize("stream", [None, Stream()])
@pytest.mark.parametrize("column_names", [None, ["col_int64", "col_bool"]])
@pytest.mark.parametrize("column_indices", [None, [2, 0]])
@pytest.mark.parametrize("source_strategy", ["inline", "set_source"])
def test_read_parquet_basic(
table_data,
binary_source_or_sink,
nrows_skiprows,
column_names,
column_indices,
stream,
source_strategy,
):
_, pa_table = table_data
nrows, skiprows = nrows_skiprows
source = make_source(
binary_source_or_sink, pa_table, **_COMMON_PARQUET_SOURCE_KWARGS
)
source_info = plc.io.SourceInfo([source])
options = plc.io.parquet.ParquetReaderOptions.builder(
source_info if source_strategy == "inline" else plc.io.SourceInfo([])
).build()
if source_strategy == "set_source":
options.set_source(source_info)
if nrows > -1:
options.set_num_rows(nrows)
if skiprows != 0:
options.set_skip_rows(skiprows)
if column_names is not None:
options.set_column_names(column_names)
elif column_indices is not None:
options.set_column_indices(column_indices)
res = plc.io.parquet.read_parquet(options, stream)
if column_names is not None:
pa_table = pa_table.select(column_names)
elif column_indices is not None:
column_names = [pa_table.column_names[idx] for idx in column_indices]
pa_table = pa_table.select(column_names)
# Adapt to nrows/skiprows
pa_table = pa_table.slice(
offset=skiprows, length=nrows if nrows > -1 else None
)
assert_table_and_meta_eq(pa_table, res, check_field_nullability=False)
# No filtering done
assert res.num_row_groups_after_stats_filter is None
assert res.num_row_groups_after_bloom_filter is None
def test_read_parquet_column_field_ids(binary_source_or_sink):
schema = pa.schema(
[
pa.field(
"col_int64",
pa.int64(),
metadata={b"PARQUET:field_id": b"10"},
),
pa.field(
"col_string",
pa.string(),
metadata={b"PARQUET:field_id": b"20"},
),
pa.field(
"col_bool",
pa.bool_(),
metadata={b"PARQUET:field_id": b"30"},
),
]
)
pa_table = pa.Table.from_arrays(
[
pa.array([1, 2, 3], type=pa.int64()),
pa.array(["a", "b", "c"], type=pa.string()),
pa.array([True, False, True], type=pa.bool_()),
],
schema=schema,
)
source = make_source(
binary_source_or_sink, pa_table, **_COMMON_PARQUET_SOURCE_KWARGS
)
source_info = plc.io.SourceInfo([source])
options = (
plc.io.parquet.ParquetReaderOptions.builder(source_info)
.column_field_ids([30, 10])
.build()
)
res = plc.io.parquet.read_parquet(options)
assert_table_and_meta_eq(
pa_table.select(["col_bool", "col_int64"]),
res,
check_field_nullability=False,
)
@pytest.mark.parametrize("if_prune_rowgroup,result", [(True, 0), (False, 1)])
def test_read_parquet_filters_metadata(tmp_path, if_prune_rowgroup, result):
col_list = list(range(1, 10))
min_element = min(col_list)
max_element = max(col_list)
tbl1 = pa.Table.from_pydict({"a": col_list})
path1 = tmp_path / "tbl1.parquet"
write_table(tbl1, path1)
source = plc.io.SourceInfo([path1])
options = plc.io.parquet.ParquetReaderOptions.builder(source).build()
if if_prune_rowgroup:
# Prune the only row group since the filter aims to find elements larger than the max
filter = Operation(
ASTOperator.LESS,
Literal(plc.Scalar.from_arrow(pa.scalar(max_element))),
ColumnNameReference("a"),
)
else:
# No real pruning
filter = Operation(
ASTOperator.LESS,
Literal(plc.Scalar.from_arrow(pa.scalar(min_element))),
ColumnNameReference("a"),
)
options.set_filter(filter)
plc_table_w_meta = plc.io.parquet.read_parquet(options)
assert (
plc_table_w_meta.num_input_row_groups == 1
) # Input has only one rowgroup
assert plc_table_w_meta.num_row_groups_after_stats_filter == result
@pytest.mark.parametrize("chunked", [True, False])
@pytest.mark.parametrize("use_builder", [True, False])
def test_read_parquet_filter_outlives_expression_reference(
tmp_path, use_builder, chunked
):
tbl = pa.Table.from_pydict({"a": list(range(10))})
path = tmp_path / "tbl.parquet"
write_table(tbl, path)
def make_filter():
return Operation(
ASTOperator.GREATER_EQUAL,
ColumnNameReference("a"),
Literal(plc.Scalar.from_arrow(pa.scalar(5))),
)
builder = plc.io.parquet.ParquetReaderOptions.builder(
plc.io.SourceInfo([path])
)
# The filter is a temporary, so only pylibcudf objects can keep it alive
if use_builder:
options = builder.filter(make_filter()).build()
else:
options = builder.build()
options.set_filter(make_filter())
del builder
if chunked:
reader = plc.io.parquet.ChunkedParquetReader(options)
del options
result = reader.read_chunk()
else:
result = plc.io.parquet.read_parquet(options)
assert_table_and_meta_eq(tbl.filter(pc.field("a") >= 5), result)
@pytest.mark.parametrize(
"pa_filters,plc_filters",
[
(
pc.field("col_int64") >= 10,
Operation(
ASTOperator.GREATER_EQUAL,
ColumnNameReference("col_int64"),
Literal(plc.Scalar.from_arrow(pa.scalar(10))),
),
),
(
(pc.field("col_int64") >= 10) & (pc.field("col_double") < 0),
Operation(
ASTOperator.LOGICAL_AND,
Operation(
ASTOperator.GREATER_EQUAL,
ColumnNameReference("col_int64"),
Literal(plc.Scalar.from_arrow(pa.scalar(10))),
),
Operation(
ASTOperator.GREATER,
Literal(plc.Scalar.from_arrow(pa.scalar(0.0))),
ColumnNameReference("col_double"),
),
),
),
(
(pc.field(0) == 10),
Operation(
ASTOperator.EQUAL,
ColumnReference(0),
Literal(plc.Scalar.from_arrow(pa.scalar(10))),
),
),
],
)
def test_read_parquet_filters(
table_data, binary_source_or_sink, pa_filters, plc_filters
):
_, pa_table = table_data
source = make_source(
binary_source_or_sink, pa_table, **_COMMON_PARQUET_SOURCE_KWARGS
)
options = plc.io.parquet.ParquetReaderOptions.builder(
plc.io.SourceInfo([source])
).build()
options.set_filter(plc_filters)
plc_table_w_meta = plc.io.parquet.read_parquet(options)
exp = read_table(source, filters=pa_filters)
assert_table_and_meta_eq(
exp, plc_table_w_meta, check_field_nullability=False
)
def _read_parquet_equal_to(path, column, value, and_expr=None):
options = plc.io.parquet.ParquetReaderOptions.builder(
plc.io.SourceInfo([path])
).build()
expr = Operation(
ASTOperator.EQUAL,
ColumnNameReference(column),
Literal(plc.Scalar.from_arrow(value)),
)
if and_expr is not None:
expr = Operation(ASTOperator.LOGICAL_AND, expr, and_expr)
options.set_filter(expr)
return plc.io.parquet.read_parquet(options)
# The default 28-digit context would round 38-digit decimals
_DECIMAL_CONTEXT = decimal.Context(prec=40)
def _decimal(offset):
return lambda v: decimal.Decimal(v + offset).scaleb(-2, _DECIMAL_CONTEXT)
def _timestamp(start):
return lambda v: start + datetime.timedelta(seconds=v)
@requires_pyarrow_bloom_filters
@pytest.mark.parametrize(
"arrow_type,literal_type,to_value,write_kwargs",
[
(pa.int8(), pa.int8(), lambda v: v - 60, {}),
(pa.int16(), pa.int16(), lambda v: v - 20_000, {}),
(pa.int32(), pa.int32(), lambda v: v - 2**31, {}),
(pa.uint8(), pa.uint8(), lambda v: v + 150, {}),
(pa.uint16(), pa.uint16(), lambda v: v + 60_000, {}),
(pa.uint32(), pa.uint32(), lambda v: v + 3_000_000_000, {}),
(pa.time32("ms"), pa.duration("ms"), lambda v: v, {}),
(pa.decimal128(5, 2), pa.decimal32(5, 2), _decimal(-60), {}),
(
pa.decimal128(9, 2),
pa.decimal32(9, 2),
_decimal(-60),
{"store_decimal_as_integer": True},
),
(pa.decimal128(12, 2), pa.decimal64(12, 2), _decimal(-60), {}),
(
pa.decimal128(18, 2),
pa.decimal64(18, 2),
_decimal(-60),
{"store_decimal_as_integer": True},
),
(pa.decimal128(20, 2), pa.decimal128(20, 2), _decimal(-60), {}),
(pa.decimal128(38, 2), pa.decimal128(38, 2), _decimal(-60), {}),
# Unscaled values beyond the int64 range
(
pa.decimal128(20, 2),
pa.decimal128(20, 2),
_decimal(9_500_000_000_000_000_000),
{},
),
(
pa.decimal128(20, 2),
pa.decimal128(20, 2),
_decimal(-9_500_000_000_000_000_000),
{},
),
(pa.decimal128(38, 2), pa.decimal128(38, 2), _decimal(10**37), {}),
(pa.decimal128(38, 2), pa.decimal128(38, 2), _decimal(-(10**37)), {}),
(
pa.decimal128(38, 2),
pa.decimal128(38, 2),
_decimal(0x0102030405060708090A0B0C0D0E0F),
{},
),
(
pa.timestamp("ns"),
pa.timestamp("ns"),
_timestamp(datetime.datetime(2020, 1, 1, 6, 30)),
{"use_deprecated_int96_timestamps": True},
),
(
pa.timestamp("ns"),
pa.timestamp("ns"),
_timestamp(datetime.datetime(1965, 6, 1, 12)),
{"use_deprecated_int96_timestamps": True},
),
],
)
def test_read_parquet_bloom_filter_physical_types(
tmp_path, arrow_type, literal_type, to_value, write_kwargs
):
# Bloom filters hash the physical type's plain encoding: INT32 for 8 and
# 16-bit integers and TIME(MILLIS), big-endian bytes for
# FIXED_LEN_BYTE_ARRAY decimals, and nanoseconds of the day followed by
# the Julian day for INT96. Both row groups have the same min and max, so
# only the bloom filter can prune the one without the value.
evens = [to_value((i % 50) * 2) for i in range(1000)]
with_five = [
to_value(5) if i % 50 == 1 else v for i, v in enumerate(evens)
]
path = tmp_path / "bloom.parquet"
write_table(
pa.table(
{
"c": pa.array(with_five + evens, arrow_type),
"b": pa.array([True] * (2 * len(evens))),
}
),
path,
row_group_size=len(evens),
bloom_filter_options={"c": BLOOM_FILTER_OPTIONS},
**write_kwargs,
)
# Bools have no bloom filters, and an equality on one must not stop "c"
# from using its bloom filters
b_is_true = Operation(
ASTOperator.EQUAL,
ColumnNameReference("b"),
Literal(plc.Scalar.from_arrow(pa.scalar(True))),
)
for value, num_rows, num_row_groups in [(5, 20, 1), (7, 0, 0)]:
literal = pa.array([to_value(value)], literal_type)[0]
result = _read_parquet_equal_to(path, "c", literal, b_is_true)
assert result.tbl.num_rows() == num_rows
assert result.num_row_groups_after_stats_filter == 2
assert result.num_row_groups_after_bloom_filter == num_row_groups
@requires_pyarrow_bloom_filters
def test_read_parquet_bloom_filter_decimal_scale_mismatch(tmp_path):
# A literal whose scale differs from the column's is not probed, so no
# row group is pruned by the bloom filter
to_value = _decimal(-60)
evens = [to_value((i % 50) * 2) for i in range(1000)]
with_five = [
to_value(5) if i % 50 == 1 else v for i, v in enumerate(evens)
]
path = tmp_path / "bloom.parquet"
write_table(
pa.table({"c": pa.array(with_five + evens, pa.decimal128(5, 2))}),
path,
row_group_size=len(evens),
bloom_filter_options={"c": BLOOM_FILTER_OPTIONS},
)
for value, num_rows in [(5, 20), (7, 0)]:
literal = pa.array([to_value(value)], pa.decimal32(5, 3))[0]
result = _read_parquet_equal_to(path, "c", literal)
assert result.tbl.num_rows() == num_rows
assert result.num_row_groups_after_stats_filter == 2
assert result.num_row_groups_after_bloom_filter is None
@requires_pyarrow_bloom_filters
@pytest.mark.parametrize("arrow_type", [pa.float32(), pa.float64()])
@pytest.mark.parametrize("zero,literal", [(-0.0, 0.0), (0.0, -0.0)])
def test_read_parquet_bloom_filter_signed_zero(
tmp_path, arrow_type, zero, literal
):
# +0.0 and -0.0 compare equal but have different bloom filter hashes
odds = [(i % 50) * 2 - 49.0 for i in range(1000)]
with_zero = [zero if i % 50 == 1 else v for i, v in enumerate(odds)]
path = tmp_path / "bloom.parquet"
write_table(
pa.table({"c": pa.array(with_zero + odds, arrow_type)}),
path,
row_group_size=len(odds),
bloom_filter_options={"c": BLOOM_FILTER_OPTIONS},
)
result = _read_parquet_equal_to(path, "c", pa.scalar(literal, arrow_type))
assert result.tbl.num_rows() == 20
assert result.num_row_groups_after_bloom_filter == 1
class FooSpan:
def __init__(self, owner):
# Keep the owning object alive
self._data = owner
@property
def ptr(self):
return self._data.ptr
@property
def size(self):
return self._data.size
@pytest.mark.parametrize("num_buffers", [1, 2])
@pytest.mark.parametrize("stream", [None, Stream()])
@pytest.mark.parametrize("column_names", [None, ["col_int64", "col_bool"]])
@pytest.mark.parametrize("column_indices", [None, [2, 0]])
@pytest.mark.parametrize("use_foo_span", [False, True])
def test_read_parquet_from_device_buffers(
table_data,
binary_source_or_sink,
nrows_skiprows,
stream,
column_names,
column_indices,
num_buffers,
use_foo_span,
):
_, pa_table = table_data
nrows, skiprows = nrows_skiprows
# Load data from source
source = make_source(
binary_source_or_sink, pa_table, **_COMMON_PARQUET_SOURCE_KWARGS
)
# to_device() is documented as fully async on a non-default stream, and
# the caller is responsible for keeping the source bytes alive until
# synchronize_stream() below runs.
# See https://github.com/rapidsai/rmm/issues/2521
src_bytes = get_bytes_from_source(source)
rmm_buf = DeviceBuffer.to_device(src_bytes, plc.utils._get_stream(stream))
synchronize_stream(stream)
buf = FooSpan(rmm_buf) if use_foo_span else rmm_buf
options = plc.io.parquet.ParquetReaderOptions.builder(
plc.io.SourceInfo([buf] * num_buffers)
).build()
if nrows > -1:
options.set_num_rows(nrows)
if skiprows != 0:
options.set_skip_rows(skiprows)
if column_names is not None:
options.set_column_names(column_names)
elif column_indices is not None:
options.set_column_indices(column_indices)
res = plc.io.parquet.read_parquet(options, stream)
expected = (
pa_table
if num_buffers == 1
else pa.concat_tables([pa_table] * num_buffers)
)
if column_names is not None:
expected = expected.select(column_names)
elif column_indices is not None:
column_names = [expected.column_names[idx] for idx in column_indices]
expected = expected.select(column_names)
expected = expected.slice(skiprows, nrows if nrows > -1 else None)
assert_table_and_meta_eq(expected, res, check_field_nullability=False)
def test_read_parquet_with_pre_materialized_metadata(
table_data: tuple[plc.io.types.TableWithMetadata, pa.Table],
binary_source_or_sink: str | os.PathLike[str] | io.BytesIO,
) -> None:
_, pa_table = table_data
source = make_source(
binary_source_or_sink, pa_table, **_COMMON_PARQUET_SOURCE_KWARGS
)
source_info = plc.io.SourceInfo([source])
options = plc.io.parquet.ParquetReaderOptions.builder(source_info).build()
parquet_metadatas = plc.io.parquet_metadata.read_parquet_footers(
source_info
)
result = plc.io.parquet.read_parquet(
options, parquet_metadatas=parquet_metadatas
)
assert_table_and_meta_eq(pa_table, result, check_field_nullability=False)
def test_read_parquet_with_pre_materialized_metadata_len_mismatch(
table_data: tuple[plc.io.types.TableWithMetadata, pa.Table],
binary_source_or_sink: str | os.PathLike[str] | io.BytesIO,
) -> None:
_, pa_table = table_data
source = make_source(
binary_source_or_sink, pa_table, **_COMMON_PARQUET_SOURCE_KWARGS
)
source_info = plc.io.SourceInfo([source])
options = plc.io.parquet.ParquetReaderOptions.builder(source_info).build()
with pytest.raises(
ValueError,
match=r"Length of 'parquet_metadatas' \(0\) must match the number of input sources \(1\)",
):
plc.io.parquet.read_parquet(options, parquet_metadatas=[])
def test_chunked_parquet_reader_with_pre_materialized_metadata(
table_data: tuple[plc.io.types.TableWithMetadata, pa.Table],
binary_source_or_sink: str | os.PathLike[str] | io.BytesIO,
) -> None:
_, pa_table = table_data
source = make_source(
binary_source_or_sink, pa_table, **_COMMON_PARQUET_SOURCE_KWARGS
)
source_info = plc.io.SourceInfo([source])
options = plc.io.parquet.ParquetReaderOptions.builder(source_info).build()
parquet_metadatas = plc.io.parquet_metadata.read_parquet_footers(
source_info
)
default_reader = plc.io.parquet.ChunkedParquetReader(
options,
chunk_read_limit=512,
)
default_chunks: list[pa.Table] = []
while default_reader.has_next():
default_chunks.append(default_reader.read_chunk().tbl.to_arrow())
metadata_reader = plc.io.parquet.ChunkedParquetReader(
options,
chunk_read_limit=512,
parquet_metadatas=parquet_metadatas,
)
metadata_chunks: list[pa.Table] = []
while metadata_reader.has_next():
metadata_chunks.append(metadata_reader.read_chunk().tbl.to_arrow())
if default_chunks:
expected = pa.concat_tables(default_chunks)
else:
expected = pa_table.slice(0, 0)
if metadata_chunks:
result = pa.concat_tables(metadata_chunks)
else:
result = pa_table.slice(0, 0)
assert result.equals(expected)
def test_file_metadata_from_bytes(
table_data: tuple[plc.io.types.TableWithMetadata, pa.Table],
binary_source_or_sink: str | os.PathLike[str] | io.BytesIO,
) -> None:
_, pa_table = table_data
source = make_source(
binary_source_or_sink, pa_table, **_COMMON_PARQUET_SOURCE_KWARGS
)
source_bytes = get_bytes_from_source(source)
footer_without_suffix, footer_with_suffix = (
_extract_footer_bytes_with_suffix(source_bytes)
)
metadata_from_footer_only = (
plc.io.parquet_metadata.FileMetaData.from_bytes(footer_without_suffix)
)
metadata_from_footer_with_suffix = (
plc.io.parquet_metadata.FileMetaData.from_bytes(footer_with_suffix)
)
assert (
metadata_from_footer_only.version
== metadata_from_footer_with_suffix.version
)
assert (
metadata_from_footer_only.num_rows
== metadata_from_footer_with_suffix.num_rows
)
assert (
metadata_from_footer_only.created_by
== metadata_from_footer_with_suffix.created_by
)
assert metadata_from_footer_only.num_rows == pa_table.num_rows
def test_file_metadata_from_bytes_empty() -> None:
with pytest.raises(RuntimeError, match="Cannot initialize schema"):
plc.io.parquet_metadata.FileMetaData.from_bytes(memoryview(b""))
def test_file_metadata_row_groups_and_column_chunks() -> None:
table = pa.table(
{
"a": list(range(100)),
"b": [x * 10 for x in range(100)],
}
)
sink = io.BytesIO()
write_table(table, sink, row_group_size=25)
sink.seek(0)
parquet_file = pq.ParquetFile(sink)
sink.seek(0)
source_info = plc.io.SourceInfo([sink])
file_metadata = plc.io.parquet_metadata.read_parquet_footers(source_info)[
0
]
assert (
len(file_metadata.row_groups) == parquet_file.metadata.num_row_groups
)
for rg_idx, row_group in enumerate(file_metadata.row_groups):
pa_row_group = parquet_file.metadata.row_group(rg_idx)
assert row_group.num_rows == pa_row_group.num_rows
assert row_group.total_byte_size == pa_row_group.total_byte_size
assert row_group.total_compressed_size is None or (
row_group.total_compressed_size >= 0
)
assert row_group.file_offset is None or row_group.file_offset >= 0
assert row_group.ordinal is None or row_group.ordinal == rg_idx
assert len(row_group.columns) == pa_row_group.num_columns
for col_idx, column_chunk in enumerate(row_group.columns):
pa_col_chunk = pa_row_group.column(col_idx)
meta_data = column_chunk.meta_data
assert column_chunk.file_path == ""
assert column_chunk.file_offset == 0
assert isinstance(column_chunk.offset_index_offset, int)
assert isinstance(column_chunk.offset_index_length, int)
assert isinstance(column_chunk.column_index_offset, int)
assert isinstance(column_chunk.column_index_length, int)
assert isinstance(column_chunk.schema_idx, int)
assert meta_data.num_values == pa_col_chunk.num_values
assert (
meta_data.total_uncompressed_size
== pa_col_chunk.total_uncompressed_size
)
assert (
meta_data.total_compressed_size
== pa_col_chunk.total_compressed_size
)
assert meta_data.path_in_schema[-1] == pa_col_chunk.path_in_schema
def test_file_metadata_columnchunk_statistics() -> None:
table = pa.table(
{
"a": pa.array([1, 2, 3, None], type=pa.int64()),
"s": pa.array(["aa", "bb", "cc", None]),
}
)
sink = io.BytesIO()
write_table(table, sink, row_group_size=2)
sink.seek(0)
source_info = plc.io.SourceInfo([sink])
file_metadata = plc.io.parquet_metadata.read_parquet_footers(source_info)[
0
]
expected = [
(1, 2, 0, b"aa", b"bb"),
(3, 3, 1, b"cc", b"cc"),
]
for row_group, (
min_a,
max_a,
null_count,
min_s,
max_s,
) in zip(file_metadata.row_groups, expected, strict=True):
stats_by_name = {
column.meta_data.path_in_schema[-1]: column.meta_data.statistics
for column in row_group.columns
}
a_stats = stats_by_name["a"]
assert a_stats.has_min_max
assert a_stats.min_encoded == struct.pack("<q", min_a)
assert a_stats.max_encoded == struct.pack("<q", max_a)
assert a_stats.null_count == null_count
assert a_stats.distinct_count is None
s_stats = stats_by_name["s"]
assert s_stats.has_min_max
assert s_stats.min_encoded == min_s
assert s_stats.max_encoded == max_s
assert s_stats.null_count == null_count
assert s_stats.distinct_count is None
def test_file_metadata_columnchunk_statistics_without_minmax() -> None:
table = pa.table({"a": pa.array([1, 2], type=pa.int64())})
sink = io.BytesIO()
write_table(table, sink, write_statistics=False)
sink.seek(0)
source_info = plc.io.SourceInfo([sink])
file_metadata = plc.io.parquet_metadata.read_parquet_footers(source_info)[
0
]
statistics = file_metadata.row_groups[0].columns[0].meta_data.statistics
assert not statistics.has_min_max
assert statistics.min_encoded is None
assert statistics.max_encoded is None
assert statistics.is_min_value_exact is None
assert statistics.is_max_value_exact is None
def test_read_parquet_column_chunk_bounds(tmp_path) -> None:
table_0 = pa.table(
{
"a": pa.array([1, 2, 3, 4], type=pa.int64()),
"s": ["b", "a", "d", "c"],
"ts": pa.array([0, 1, 2, 3], type=pa.timestamp("us")),
"n": pa.array([None, 2, None, None], type=pa.int64()),
}
)
table_1 = pa.table(
{
"a": pa.array([10, 20, 30, 40], type=pa.int64()),
"s": ["z", "y", "x", "w"],
"ts": pa.array([10, 20, 30, 40], type=pa.timestamp("us")),
"n": pa.array([5, None, None, 8], type=pa.int64()),
}
)
path_0 = tmp_path / "part-0.parquet"
path_1 = tmp_path / "part-1.parquet"
write_table(table_0, path_0, row_group_size=2)
write_table(table_1, path_1, row_group_size=2)
file_metadatas = plc.io.parquet_metadata.read_parquet_footers(
plc.io.SourceInfo([path_0, path_1])
)
bounds = plc.io.parquet_metadata.read_parquet_column_chunk_bounds(
file_metadatas,
columns=["a", "s", "ts", "n"],
)
columns = bounds.columns()
assert len(columns) == 10
assert columns[0].to_pylist() == [0, 0, 1, 1]
assert columns[1].to_pylist() == [0, 1, 0, 1]
a_min, a_max = columns[2], columns[3]
assert a_min.to_pylist() == [1, 3, 10, 30]
assert a_max.to_pylist() == [2, 4, 20, 40]
s_min, s_max = columns[4], columns[5]
assert s_min.to_pylist() == ["a", "c", "y", "w"]
assert s_max.to_pylist() == ["b", "d", "z", "x"]
ts_min, ts_max = columns[6], columns[7]
assert ts_min.to_arrow().equals(
pa.array([0, 2, 10, 30], type=pa.timestamp("us"))
)
assert ts_max.to_arrow().equals(
pa.array([1, 3, 20, 40], type=pa.timestamp("us"))
)
n_min, n_max = columns[8], columns[9]
assert n_min.to_pylist() == [2, None, 5, 8]
assert n_max.to_pylist() == [2, None, 5, 8]
def test_read_parquet_column_chunk_bounds_without_minmax(tmp_path) -> None:
table = pa.table({"a": pa.array([1, 2], type=pa.int64())})
path = tmp_path / "no-stats.parquet"
write_table(table, path, write_statistics=False)
file_metadatas = plc.io.parquet_metadata.read_parquet_footers(
plc.io.SourceInfo([path])
)
bounds = plc.io.parquet_metadata.read_parquet_column_chunk_bounds(
file_metadatas,
columns=["a"],
)
columns = bounds.columns()
assert len(columns) == 4
assert columns[0].to_pylist() == [0]
assert columns[1].to_pylist() == [0]
min_col, max_col = columns[2], columns[3]
assert min_col.to_pylist() == [None]
assert max_col.to_pylist() == [None]
def test_read_parquet_column_chunk_bounds_invalid_inputs(tmp_path) -> None:
table = pa.table({"a": pa.array([1, 2], type=pa.int64())})
path = tmp_path / "input.parquet"
write_table(table, path)
file_metadatas = plc.io.parquet_metadata.read_parquet_footers(
plc.io.SourceInfo([path])
)
with pytest.raises(
ValueError, match="Parquet leaf column path not found: missing"
):
plc.io.parquet_metadata.read_parquet_column_chunk_bounds(
file_metadatas,
columns=["missing"],
)
with pytest.raises(TypeError, match="columns must contain only strings"):
plc.io.parquet_metadata.read_parquet_column_chunk_bounds(
file_metadatas,
columns=[1],
)
with pytest.raises(
TypeError, match="columns must be a sequence of strings"
):
plc.io.parquet_metadata.read_parquet_column_chunk_bounds(
file_metadatas,
columns="a",
)
with pytest.raises(
TypeError,
match="file_metadatas must contain only FileMetaData objects",
):
plc.io.parquet_metadata.read_parquet_column_chunk_bounds(
[object()],
columns=["a"],
)
with pytest.raises(
ValueError,
match="without source metadata",
):
plc.io.parquet_metadata.read_parquet_column_chunk_bounds(
[],
columns=["a"],
)
def test_file_metadata_wrappers_not_directly_constructible() -> None:
with pytest.raises(
ValueError, match="SortingColumn cannot be constructed directly"
):
plc.io.parquet_metadata.SortingColumn()
with pytest.raises(
ValueError, match="ColumnChunk cannot be constructed directly"
):
plc.io.parquet_metadata.ColumnChunk()
with pytest.raises(
ValueError, match="ColumnChunkMetaData cannot be constructed directly"
):
plc.io.parquet_metadata.ColumnChunkMetaData()
with pytest.raises(
ValueError,
match="ColumnChunkStatistics cannot be constructed directly",
):
plc.io.parquet_metadata.ColumnChunkStatistics()
with pytest.raises(
ValueError, match="RowGroup cannot be constructed directly"
):
plc.io.parquet_metadata.RowGroup()
with pytest.raises(
ValueError, match="SchemaElement cannot be constructed directly"
):
plc.io.parquet_metadata.SchemaElement()
with pytest.raises(
ValueError, match="LogicalType cannot be constructed directly"
):
plc.io.parquet_metadata.LogicalType()
with pytest.raises(
ValueError, match="DecimalType cannot be constructed directly"
):
plc.io.parquet_metadata.DecimalType()
with pytest.raises(
ValueError, match="TimeType cannot be constructed directly"
):
plc.io.parquet_metadata.TimeType()
with pytest.raises(
ValueError, match="TimestampType cannot be constructed directly"
):
plc.io.parquet_metadata.TimestampType()
with pytest.raises(
ValueError, match="IntType cannot be constructed directly"
):
plc.io.parquet_metadata.IntType()
def test_file_metadata_schema_elements() -> None:
schema = pa.schema(
[
pa.field("a", pa.int64(), metadata={b"PARQUET:field_id": b"10"}),
pa.field(
"s",
pa.struct(
[
pa.field(
"x",
pa.int32(),
metadata={b"PARQUET:field_id": b"21"},
),
pa.field(
"y",
pa.string(),
metadata={b"PARQUET:field_id": b"22"},
),
]
),
metadata={b"PARQUET:field_id": b"20"},
),
pa.field(
"dec",
pa.decimal128(12, 2),
metadata={b"PARQUET:field_id": b"30"},
),
pa.field(
"fixed",
pa.binary(4),
metadata={b"PARQUET:field_id": b"40"},
),
pa.field("i8", pa.int8(), metadata={b"PARQUET:field_id": b"50"}),
pa.field(
"u16", pa.uint16(), metadata={b"PARQUET:field_id": b"51"}
),
pa.field(
"date", pa.date32(), metadata={b"PARQUET:field_id": b"52"}
),