forked from ray-project/ray
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_parquet.py
More file actions
3232 lines (2672 loc) · 111 KB
/
Copy pathtest_parquet.py
File metadata and controls
3232 lines (2672 loc) · 111 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
import os
import pathlib
import pickle
import shutil
import time
from dataclasses import dataclass
from typing import Optional, Union
from unittest.mock import MagicMock
import fsspec
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.dataset as pds
import pyarrow.fs as pafs
import pyarrow.parquet as pq
import pytest
from packaging.version import parse as parse_version
from pyarrow.fs import FSSpecHandler, PyFileSystem
from pytest_lazy_fixtures import lf as lazy_fixture
import ray
from ray.data import FileShuffleConfig, Schema
from ray.data._internal.datasource.parquet_datasource import (
_MAX_PYARROW_TO_BATCHES_BATCH_SIZE,
ParquetDatasource,
_coerce_pyarrow_fragment_batch_size,
_infer_schema,
_read_batches_from,
)
from ray.data._internal.execution.interfaces.ref_bundle import (
_ref_bundles_iterator_to_block_refs_list,
)
from ray.data._internal.object_extensions.arrow import ArrowPythonObjectType
from ray.data._internal.tensor_extensions.arrow import (
get_arrow_extension_fixed_shape_tensor_types,
)
from ray.data._internal.util import explain_plan, rows_same
from ray.data._internal.utils.arrow_utils import get_pyarrow_version
from ray.data.block import BlockAccessor
from ray.data.context import DataContext
from ray.data.datasource.partitioning import Partitioning, PathPartitionFilter
from ray.data.datasource.path_util import _unwrap_protocol
from ray.data.tests.conftest import * # noqa
from ray.data.tests.mock_http_server import * # noqa
from ray.data.tests.test_util import ConcurrencyCounter # noqa
from ray.tests.conftest import * # noqa
@pytest.fixture(params=[False, True], ids=["v1", "v2"])
def use_datasource_v2(request, restore_data_context):
restore_data_context.use_datasource_v2 = request.param
def test_read_parquet_allows_pickle_object_columns_with_env_var(
tmp_path, shutdown_only, use_datasource_v2, monkeypatch
):
# Set the environment variable on both the driver and the worker processes.
monkeypatch.setenv("RAY_DATA_AUTOLOAD_PICKLE_OBJECT_SCALAR", "1")
ray.init(runtime_env={"env_vars": {"RAY_DATA_AUTOLOAD_PICKLE_OBJECT_SCALAR": "1"}})
ext_type = ArrowPythonObjectType()
storage = pa.array([pickle.dumps({"key": "value"})], type=ext_type.storage_type)
table = pa.table({"col": pa.ExtensionArray.from_storage(ext_type, storage)})
pq.write_table(table, str(tmp_path / "data.parquet"))
ds = ray.data.read_parquet(str(tmp_path))
rows = ds.take_all()
assert len(rows) == 1
assert rows[0]["col"] == {"key": "value"}
def test_read_parquet_rejects_pickle_object_columns(
tmp_path, ray_start_regular_shared, use_datasource_v2
):
marker = tmp_path / "exploit_marker"
class Exploit:
def __reduce__(self):
import os
return (os.system, (f"touch {marker}",))
ext_type = ArrowPythonObjectType()
storage = pa.array([pickle.dumps(Exploit())], type=ext_type.storage_type)
table = pa.table({"col": pa.ExtensionArray.from_storage(ext_type, storage)})
pq.write_table(table, str(tmp_path / "data.parquet"))
ds = ray.data.read_parquet(str(tmp_path))
with pytest.raises(Exception, match="arrow_pickled_object"):
ds.take_all()
assert not marker.exists(), "pickle.load executed attacker code"
def test_write_parquet_handles_per_block_column_reorder(
ray_start_regular_shared, tmp_path
):
# When the Write task receives multiple blocks whose schemas share the same
# field names in a different order, `pa.unify_schemas` fixes the column
# order from the first block. Previously the per-block `Table.cast` was
# positional and rejected the second block; ParquetDatasink now reorders
# columns by name before casting.
from ray.data._internal.datasource.parquet_datasink import (
WRITE_UUID_KWARG_NAME,
ParquetDatasink,
)
from ray.data._internal.execution.interfaces import TaskContext
t1 = pa.table({"x": [1], "y": [2]})
t2 = pa.table({"y": [3], "x": [4]})
sink = ParquetDatasink(path=str(tmp_path))
ctx = TaskContext(task_idx=0, op_name="Write")
ctx.kwargs = {WRITE_UUID_KWARG_NAME: "wuid"}
sink.write([t1, t2], ctx)
out = pq.read_table(str(tmp_path))
assert sorted(out.column_names) == ["x", "y"]
assert out.num_rows == 2
# Pair each row's (x, y) regardless of the unified output order.
assert sorted(zip(out.column("x").to_pylist(), out.column("y").to_pylist())) == [
(1, 2),
(4, 3),
]
def test_write_parquet_supports_gzip(ray_start_regular_shared, tmp_path):
ray.data.range(1).write_parquet(tmp_path, compression="gzip")
# Test that all written files are gzip compressed.
for filename in os.listdir(tmp_path):
file_metadata = pq.ParquetFile(tmp_path / filename).metadata
compression = file_metadata.row_group(0).column(0).compression
assert compression == "GZIP", compression
# Test that you can read the written files.
assert pq.read_table(tmp_path).to_pydict() == {"id": [0]}
def test_write_parquet_partition_cols(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
num_partitions = 10
rows_per_partition = 10
num_rows = num_partitions * rows_per_partition
df = pd.DataFrame(
{
"a": list(range(num_partitions)) * rows_per_partition,
"b": list(range(num_partitions)) * rows_per_partition,
"c": list(range(num_rows)),
"d": list(range(num_rows)),
# Make sure algorithm does not fail for tensor types.
"e": list(np.random.random((num_rows, 128))),
}
)
ds = ray.data.from_pandas(df)
ds.write_parquet(tmp_path, partition_cols=["a", "b"])
# Test that files are written in partition style
for i in range(num_partitions):
partition = os.path.join(tmp_path, f"a={i}", f"b={i}")
ds_partition = ray.data.read_parquet(partition)
dsf_partition = ds_partition.to_pandas()
c_expected = [k * i for k in range(rows_per_partition)].sort()
d_expected = [k * i for k in range(rows_per_partition)].sort()
assert c_expected == dsf_partition["c"].tolist().sort()
assert d_expected == dsf_partition["d"].tolist().sort()
assert dsf_partition["e"].shape == (rows_per_partition,)
# Test that partition are read back properly into original dataset schema
ds1 = ray.data.read_parquet(tmp_path)
assert set(ds.schema().names) == set(ds1.schema().names)
assert ds.count() == ds1.count()
df = df.sort_values(by=["a", "b", "c", "d"])
df1 = ds1.to_pandas().sort_values(by=["a", "b", "c", "d"])
for (index1, row1), (index2, row2) in zip(df.iterrows(), df1.iterrows()):
row1_dict = row1.to_dict()
row2_dict = row2.to_dict()
assert row1_dict["c"] == row2_dict["c"]
assert row1_dict["d"] == row2_dict["d"]
def test_include_paths(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
path = os.path.join(tmp_path, "test.parquet")
table = pa.Table.from_pydict({"animals": ["cat", "dog"]})
pq.write_table(table, path)
ds = ray.data.read_parquet(path, include_paths=True)
# Verify that the path column is present in the schema
schema_names = ds.schema().names
assert "path" in schema_names, f"'path' column not found in schema: {schema_names}"
paths = [row["path"] for row in ds.take_all()]
assert paths == [path, path]
def test_include_paths_with_column_projection(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
path = os.path.join(tmp_path, "test.parquet")
table = pa.Table.from_pydict({"animals": ["cat", "dog"], "id": [1, 2]})
pq.write_table(table, path)
# Exercises the deprecated ``columns=`` arg: V1 retained ``"path"``
# implicitly under ``include_paths=True``, and read_api preserves that
# by appending it to the projection on the caller's behalf.
with pytest.warns(DeprecationWarning, match="`columns=` on `read_parquet`"):
ds = ray.data.read_parquet(path, columns=["id"], include_paths=True)
schema_names = ds.schema().names
assert "id" in schema_names, f"'id' column not found in schema: {schema_names}"
assert "path" in schema_names, f"'path' column not found in schema: {schema_names}"
# Verify that the path column contains the expected paths
rows = ds.take_all()
for row in rows:
assert "path" in row
assert row["path"] == path
def test_include_row_hash(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
path = os.path.join(tmp_path, "test.parquet")
table = pa.Table.from_pydict({"animals": ["cat", "dog", "bird"]})
pq.write_table(table, path)
ds = ray.data.read_parquet(path, include_row_hash=True)
schema_names = ds.schema().names
assert "row_hash" in schema_names
rows = ds.take_all()
hashes = [row["row_hash"] for row in rows]
assert len(hashes) == 3
assert len(set(hashes)) == 3, "Hashes must be unique"
assert all(isinstance(h, int) for h in hashes)
def test_include_row_hash_reproducible(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
path = os.path.join(tmp_path, "test.parquet")
table = pa.Table.from_pydict({"val": list(range(10))})
pq.write_table(table, path)
hashes1 = [
row["row_hash"]
for row in ray.data.read_parquet(path, include_row_hash=True).take_all()
]
hashes2 = [
row["row_hash"]
for row in ray.data.read_parquet(path, include_row_hash=True).take_all()
]
assert hashes1 == hashes2, "Hashes must be reproducible across reads"
def test_include_row_hash_unique_across_files(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
for i in range(3):
path = os.path.join(tmp_path, f"file{i}.parquet")
table = pa.Table.from_pydict({"val": [i * 10, i * 10 + 1]})
pq.write_table(table, path)
ds = ray.data.read_parquet(str(tmp_path), include_row_hash=True)
rows = ds.take_all()
hashes = [row["row_hash"] for row in rows]
assert len(hashes) == 6
assert len(set(hashes)) == 6, "Hashes must be unique across files"
def test_include_row_hash_same_data_different_files(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
"""Files with identical content must produce different hashes because
the hash is derived from the file path, not the data."""
table = pa.Table.from_pydict({"val": [1, 2, 3]})
for name in ("a.parquet", "b.parquet", "c.parquet"):
pq.write_table(table, os.path.join(tmp_path, name))
ds = ray.data.read_parquet(str(tmp_path), include_row_hash=True)
rows = ds.take_all()
hashes = [row["row_hash"] for row in rows]
assert len(hashes) == 9
assert (
len(set(hashes)) == 9
), "Identical data in different files must produce distinct hashes"
def test_include_row_hash_with_column_projection(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
path = os.path.join(tmp_path, "test.parquet")
table = pa.Table.from_pydict({"a": [1, 2], "b": [3, 4]})
pq.write_table(table, path)
# Exercises the deprecated ``columns=`` arg: V1 retained ``"row_hash"``
# implicitly under ``include_row_hash=True``, and read_api preserves
# that by appending it to the projection on the caller's behalf.
with pytest.warns(DeprecationWarning, match="`columns=` on `read_parquet`"):
ds = ray.data.read_parquet(path, columns=["a"], include_row_hash=True)
schema_names = ds.schema().names
assert "a" in schema_names
assert "b" not in schema_names
assert "row_hash" in schema_names
rows = ds.take_all()
assert len(rows) == 2
assert all("row_hash" in row and "a" in row and "b" not in row for row in rows)
def test_include_row_hash_with_include_paths(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
path = os.path.join(tmp_path, "test.parquet")
table = pa.Table.from_pydict({"val": [1, 2]})
pq.write_table(table, path)
ds = ray.data.read_parquet(path, include_paths=True, include_row_hash=True)
schema_names = ds.schema().names
assert "path" in schema_names
assert "row_hash" in schema_names
df = ds.to_pandas()
assert "path" in df.columns
assert len(set(df["row_hash"])) == 2
def test_include_row_hash_existing_column(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
"""When the file already has a 'row_hash' column, it should be
overwritten by the generated one without crashing."""
path = os.path.join(tmp_path, "test.parquet")
table = pa.Table.from_pydict({"val": [1, 2, 3], "row_hash": [100, 200, 300]})
pq.write_table(table, path)
ds = ray.data.read_parquet(path, include_row_hash=True)
rows = ds.take_all()
hashes = [row["row_hash"] for row in rows]
assert len(hashes) == 3
assert len(set(hashes)) == 3, "Hashes must be unique"
assert all(
h not in (100, 200, 300) for h in hashes
), "Generated hashes must overwrite the original column values"
def test_include_row_hash_existing_column_with_projection(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
"""Column projection + pre-existing row_hash column should work."""
path = os.path.join(tmp_path, "test.parquet")
table = pa.Table.from_pydict({"val": [1, 2], "row_hash": [10, 20]})
pq.write_table(table, path)
ds = ray.data.read_parquet(path, include_row_hash=True).select_columns(
["val", "row_hash"]
)
schema_names = ds.schema().names
assert "val" in schema_names
assert "row_hash" in schema_names
rows = ds.take_all()
assert all(row["row_hash"] not in (10, 20) for row in rows)
@pytest.mark.parametrize(
"fs,data_path",
[
(None, lazy_fixture("local_path")),
(lazy_fixture("local_fs"), lazy_fixture("local_path")),
(lazy_fixture("s3_fs"), lazy_fixture("s3_path")),
(
lazy_fixture("s3_fs_with_space"),
lazy_fixture("s3_path_with_space"),
), # Path contains space.
(
lazy_fixture("s3_fs_with_anonymous_crendential"),
lazy_fixture("s3_path_with_anonymous_crendential"),
),
],
)
def test_parquet_read_basic(
ray_start_regular_shared, fs, data_path, target_max_block_size_infinite_or_default
):
df1 = pd.DataFrame({"one": [1, 2, 3], "two": ["a", "b", "c"]})
table = pa.Table.from_pandas(df1)
setup_data_path = _unwrap_protocol(data_path)
path1 = os.path.join(setup_data_path, "test1.parquet")
pq.write_table(table, path1, filesystem=fs)
df2 = pd.DataFrame({"one": [4, 5, 6], "two": ["e", "f", "g"]})
table = pa.Table.from_pandas(df2)
path2 = os.path.join(setup_data_path, "test2.parquet")
pq.write_table(table, path2, filesystem=fs)
ds = ray.data.read_parquet(data_path, filesystem=fs)
# Schema is available pre-execution via driver-side first-file sampling.
assert ds.schema() == Schema(pa.schema({"one": pa.int64(), "two": pa.string()}))
# Forces a data read.
values = [[s["one"], s["two"]] for s in ds.take_all()]
assert sorted(values) == [
[1, "a"],
[2, "b"],
[3, "c"],
[4, "e"],
[5, "f"],
[6, "g"],
]
# Post-materialization count / size checks. ``input_files()`` is a
# V1 construction-time-only capability that doesn't carry through
# V2's ``ListFiles → ReadFiles`` split (or through V1 materialization),
# so we don't assert on it here.
materialized = ds.materialize()
assert materialized.count() == 6
assert materialized.size_bytes() > 0
# Test column selection.
ds = ray.data.read_parquet(data_path, filesystem=fs).select_columns(["one"])
values = [s["one"] for s in ds.take()]
assert sorted(values) == [1, 2, 3, 4, 5, 6]
assert ds.schema().names == ["one"]
# Test concurrency.
ds = ray.data.read_parquet(data_path, filesystem=fs, concurrency=1)
values = [s["one"] for s in ds.take()]
assert sorted(values) == [1, 2, 3, 4, 5, 6]
@pytest.mark.parametrize(
"fs,data_path",
[
(None, lazy_fixture("local_path")),
(lazy_fixture("local_fs"), lazy_fixture("local_path")),
(lazy_fixture("s3_fs"), lazy_fixture("s3_path")),
],
)
def test_parquet_read_with_success_file(ray_start_regular_shared, fs, data_path):
df = pd.DataFrame({"one": [1, 2, 3], "two": ["a", "b", "c"]})
table = pa.Table.from_pandas(df)
setup_data_path = _unwrap_protocol(data_path)
path = os.path.join(setup_data_path, "test.parquet")
pq.write_table(table, path, filesystem=fs)
# Add _SUCCESS file to ensure it's ignored
success_path = os.path.join(setup_data_path, "_SUCCESS")
if fs is None:
open(success_path, "wb").close()
else:
with fs.open_output_stream(success_path):
pass
ds = ray.data.read_parquet(data_path, filesystem=fs)
assert ds.count() == 3
values = [s["one"] for s in ds.take_all()]
assert sorted(values) == [1, 2, 3]
@pytest.mark.parametrize(
"fs,data_path",
[
(None, lazy_fixture("local_path")),
(lazy_fixture("local_fs"), lazy_fixture("local_path")),
(lazy_fixture("s3_fs"), lazy_fixture("s3_path")),
(
lazy_fixture("s3_fs_with_space"),
lazy_fixture("s3_path_with_space"),
), # Path contains space.
(
lazy_fixture("s3_fs_with_anonymous_crendential"),
lazy_fixture("s3_path_with_anonymous_crendential"),
),
],
)
def test_parquet_read_random_shuffle(
ray_start_regular_shared,
restore_data_context,
fs,
data_path,
target_max_block_size_infinite_or_default,
):
# NOTE: set preserve_order to True to allow consistent output behavior.
context = ray.data.DataContext.get_current()
context.execution_options.preserve_order = True
num_files = 10
input_list = list(range(num_files))
setup_data_path = _unwrap_protocol(data_path)
for i in range(num_files):
table = pa.Table.from_pydict({"id": [i]})
path = os.path.join(setup_data_path, f"test_{i}.parquet")
pq.write_table(table, path, filesystem=fs)
shuffle = FileShuffleConfig(seed=0)
ds = ray.data.read_parquet(data_path, filesystem=fs, shuffle=shuffle)
first = [row["id"] for row in ds.take_all()]
second = [row["id"] for row in ds.take_all()]
assert sorted(first) == input_list
assert sorted(second) == input_list
assert first != second
@pytest.mark.parametrize(
"fs,data_path",
[
(None, lazy_fixture("local_path")),
(lazy_fixture("local_fs"), lazy_fixture("local_path")),
(lazy_fixture("s3_fs"), lazy_fixture("s3_path")),
(
lazy_fixture("s3_fs_with_anonymous_crendential"),
lazy_fixture("s3_path_with_anonymous_crendential"),
),
],
)
def test_parquet_read_partitioned(
ray_start_regular_shared, fs, data_path, target_max_block_size_infinite_or_default
):
df = pd.DataFrame(
{"one": [1, 1, 1, 3, 3, 3], "two": ["a", "b", "c", "e", "f", "g"]}
)
table = pa.Table.from_pandas(df)
pq.write_to_dataset(
table,
root_path=_unwrap_protocol(data_path),
partition_cols=["one"],
filesystem=fs,
)
ds = ray.data.read_parquet(data_path, filesystem=fs)
# Schema is available pre-execution via driver-side first-file sampling.
assert ds.schema() == Schema(pa.schema({"two": pa.string(), "one": pa.string()}))
# Forces a data read.
values = [[s["one"], s["two"]] for s in ds.take()]
assert sorted(values) == [
["1", "a"],
["1", "b"],
["1", "c"],
["3", "e"],
["3", "f"],
["3", "g"],
]
# Post-materialization count / size checks (no input_files — see note
# in ``test_parquet_read_basic``).
materialized = ds.materialize()
assert materialized.count() == 6
assert materialized.size_bytes() > 0
# Test column selection.
ds = ray.data.read_parquet(data_path, filesystem=fs).select_columns(["one"])
values = [s["one"] for s in ds.take()]
assert sorted(values) == ["1", "1", "1", "3", "3", "3"]
def test_parquet_read_partitioned_with_filter(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
from ray.data.expressions import col, lit
df = pd.DataFrame(
{"one": [1, 1, 1, 3, 3, 3], "two": ["a", "a", "b", "b", "c", "c"]}
)
table = pa.Table.from_pandas(df)
pq.write_to_dataset(
table,
root_path=str(tmp_path),
partition_cols=["one"],
)
# 2 partitions, 1 empty partition, 1 block/read task
ds = ray.data.read_parquet(str(tmp_path), override_num_blocks=1).filter(
expr=col("two") == lit("a")
)
values = [[s["one"], s["two"]] for s in ds.take()]
assert sorted(values) == [["1", "a"], ["1", "a"]]
assert ds.count() == 2
# 2 partitions, 1 empty partition, 2 block/read tasks, 1 empty block
ds = ray.data.read_parquet(str(tmp_path), override_num_blocks=2).filter(
expr=col("two") == lit("a")
)
values = [[s["one"], s["two"]] for s in ds.take()]
assert sorted(values) == [["1", "a"], ["1", "a"]]
assert ds.count() == 2
@pytest.mark.parametrize(
"fs,data_path",
[
(None, lazy_fixture("local_path")),
(lazy_fixture("local_fs"), lazy_fixture("local_path")),
(lazy_fixture("s3_fs"), lazy_fixture("s3_path")),
(
lazy_fixture("s3_fs_with_anonymous_crendential"),
lazy_fixture("s3_path_with_anonymous_crendential"),
),
],
)
def test_parquet_read_partitioned_with_columns(
ray_start_regular_shared, fs, data_path, target_max_block_size_infinite_or_default
):
data = {
"x": [0, 0, 1, 1, 2, 2],
"y": ["a", "b", "a", "b", "a", "b"],
"z": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6],
}
table = pa.Table.from_pydict(data)
pq.write_to_dataset(
table,
root_path=_unwrap_protocol(data_path),
filesystem=fs,
partition_cols=["x", "y"],
)
ds = ray.data.read_parquet(
_unwrap_protocol(data_path),
filesystem=fs,
).select_columns(["y", "z"])
assert set(ds.columns()) == {"y", "z"}
values = [[s["y"], s["z"]] for s in ds.take()]
assert sorted(values) == [
["a", 0.1],
["a", 0.3],
["a", 0.5],
["b", 0.2],
["b", 0.4],
["b", 0.6],
]
def test_parquet_read_partitioned_excludes_unrequested_partition_columns(
ray_start_regular_shared, tmp_path
):
"""Test that partition columns are excluded when not explicitly requested.
This is a regression test to ensure that when a user uses select_columns()
with only data columns, partition columns are NOT automatically included.
"""
table = pa.table(
{
"partition_col0": [1, 1, 2, 2],
"partition_col1": ["a", "a", "b", "b"],
"data_col0": [10.5, 20.3, 30.2, 25.8],
"data_col1": [100, 200, 300, 400],
}
)
pq.write_to_dataset(
table,
root_path=tmp_path,
partition_cols=["partition_col0", "partition_col1"],
)
# Request only data columns excluding partition columns
ds = ray.data.read_parquet(
tmp_path,
partitioning=Partitioning("hive"),
).select_columns(["data_col0"])
# Verify only the requested column is present
assert ds.columns() == ["data_col0"]
# Verify the data is correct
result_df = ds.to_pandas()
expected_df = pd.DataFrame({"data_col0": [10.5, 20.3, 25.8, 30.2]})
assert rows_same(result_df, expected_df)
@pytest.mark.parametrize(
"fs,data_path",
[
(None, lazy_fixture("local_path")),
(lazy_fixture("local_fs"), lazy_fixture("local_path")),
(lazy_fixture("s3_fs"), lazy_fixture("s3_path")),
(
lazy_fixture("s3_fs_with_anonymous_crendential"),
lazy_fixture("s3_path_with_anonymous_crendential"),
),
],
)
def test_parquet_read_partitioned_with_partition_filter(
ray_start_regular_shared, fs, data_path, target_max_block_size_infinite_or_default
):
# This test is to make sure when only one file remains
# after partition filtering, Ray data can still parse the
# partitions correctly.
data = {
"x": [0, 0, 1, 1, 2, 2],
"y": ["a", "b", "a", "b", "a", "b"],
"z": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6],
}
table = pa.Table.from_pydict(data)
pq.write_to_dataset(
table,
root_path=_unwrap_protocol(data_path),
filesystem=fs,
partition_cols=["x", "y"],
)
ds = ray.data.read_parquet(
_unwrap_protocol(data_path),
filesystem=fs,
partition_filter=ray.data.datasource.partitioning.PathPartitionFilter.of(
filter_fn=lambda x: (x["x"] == "0") and (x["y"] == "a"), style="hive"
),
).select_columns(["x", "y", "z"])
# Where we insert partition columns is an implementation detail, so we don't check
# the order of the columns.
assert sorted(zip(ds.schema().names, ds.schema().types)) == [
("x", pa.string()),
("y", pa.string()),
("z", pa.float64()),
]
values = [[s["x"], s["y"], s["z"]] for s in ds.take()]
assert sorted(values) == [["0", "a", 0.1]]
def test_parquet_read_partitioned_explicit(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
df = pd.DataFrame(
{"one": [1, 1, 1, 3, 3, 3], "two": ["a", "b", "c", "e", "f", "g"]}
)
table = pa.Table.from_pandas(df)
pq.write_to_dataset(
table,
root_path=str(tmp_path),
partition_cols=["one"],
)
partitioning = Partitioning("hive", field_types={"one": int})
ds = ray.data.read_parquet(str(tmp_path), partitioning=partitioning)
# Schema is available pre-execution via driver-side sampling.
assert ds.schema() == Schema(pa.schema({"two": pa.string(), "one": pa.int64()}))
# Forces a data read.
values = [[s["one"], s["two"]] for s in ds.take()]
assert sorted(values) == [
[1, "a"],
[1, "b"],
[1, "c"],
[3, "e"],
[3, "f"],
[3, "g"],
]
# Post-materialization count / size checks (no input_files — see note
# in ``test_parquet_read_basic``).
materialized = ds.materialize()
assert materialized.count() == 6
assert materialized.size_bytes() > 0
def test_projection_pushdown_non_partitioned(ray_start_regular_shared, temp_dir):
if ray.data.DataContext.get_current().use_datasource_v2:
pytest.skip(
"Plan-string assertion is V1-specific (``Read[ReadParquet]``); V2 "
"produces a ``ListFiles → ReadFiles`` chain. Projection correctness "
"is covered by the schema/count assertions below for both paths."
)
path = "example://iris.parquet"
# Test projection from read_parquet
ds = ray.data.read_parquet(path).select_columns(["variety"])
schema = ds.schema()
assert ["variety"] == schema.base_schema.names
assert ds.count() == 150
# Test projection pushed down into read op
ds = ray.data.read_parquet(path, override_num_blocks=1).select_columns("variety")
assert explain_plan(ds._logical_plan).strip() == (
"-------- Logical Plan --------\n"
"Project[Project]\n"
"+- Read[ReadParquet]\n"
"\n-------- Logical Plan (Optimized) --------\n"
"Read[ReadParquet]\n"
"\n-------- Physical Plan --------\n"
"TaskPoolMapOperator[ReadParquet]\n"
"+- InputDataBuffer[Input]\n"
"\n-------- Physical Plan (Optimized) --------\n"
"TaskPoolMapOperator[ReadParquet]\n"
"+- InputDataBuffer[Input]"
)
# Assert schema being appropriately projected
schema = ds.schema()
assert ["variety"] == schema.base_schema.names
assert ds.count() == 150
# Assert empty projection is reading no data
ds = ray.data.read_parquet(path, override_num_blocks=1).select_columns([])
summary = ds.materialize()._raw_stats().to_summary()
assert "ReadParquet" in summary.base_name
assert summary.extra_metrics["bytes_task_outputs_generated"] == 0
def test_projection_pushdown_partitioned(ray_start_regular_shared, temp_dir):
ds = ray.data.read_parquet("example://iris.parquet").materialize()
partitioned_ds_path = f"{temp_dir}/partitioned_iris"
# Write out partitioned dataset
ds.write_parquet(partitioned_ds_path, partition_cols=["variety"])
partitioned_ds = (
ray.data.read_parquet(partitioned_ds_path)
.select_columns(["variety"])
.materialize()
)
print(partitioned_ds.schema())
assert [
"sepal.length",
"sepal.width",
"petal.length",
"petal.width",
"variety",
] == ds.take_batch(batch_format="pyarrow").column_names
assert ["variety"] == partitioned_ds.take_batch(batch_format="pyarrow").column_names
assert ds.count() == partitioned_ds.count()
def test_projection_pushdown_on_count(ray_start_regular_shared, temp_dir):
path = "example://iris.parquet"
# Test reading full dataset
# ds = ray.data.read_parquet(path).materialize()
# Test projection from read_parquet
num_rows = ray.data.read_parquet(path).count()
assert num_rows == 150
def test_parquet_read_with_udf(
ray_start_regular_shared, tmp_path, target_max_block_size_infinite_or_default
):
one_data = list(range(6))
df = pd.DataFrame({"one": one_data, "two": 2 * ["a"] + 2 * ["b"] + 2 * ["c"]})
table = pa.Table.from_pandas(df)
pq.write_to_dataset(
table,
root_path=str(tmp_path),
partition_cols=["two"],
)
def _block_udf(block: pa.Table):
df = block.to_pandas()
df["one"] += 1
return pa.Table.from_pandas(df)
# 1 block/read task
ds = ray.data.read_parquet(
str(tmp_path), override_num_blocks=1, _block_udf=_block_udf
)
ones, twos = zip(*[[s["one"], s["two"]] for s in ds.take()])
np.testing.assert_array_equal(sorted(ones), np.array(one_data) + 1)
# 2 blocks/read tasks
ds = ray.data.read_parquet(
str(tmp_path), override_num_blocks=2, _block_udf=_block_udf
)
ones, twos = zip(*[[s["one"], s["two"]] for s in ds.take()])
np.testing.assert_array_equal(sorted(ones), np.array(one_data) + 1)
# 2 blocks/read tasks, 1 empty block
ds = ray.data.read_parquet(
str(tmp_path),
override_num_blocks=2,
partition_filter=PathPartitionFilter.of(
lambda partitions: partitions["two"] == "a"
),
_block_udf=_block_udf,
)
ones, twos = zip(*[[s["one"], s["two"]] for s in ds.take()])
np.testing.assert_array_equal(sorted(ones), np.array(one_data[:2]) + 1)
def test_parquet_reader_estimate_data_size(shutdown_only, tmp_path):
ctx = ray.data.context.DataContext.get_current()
old_decoding_size_estimation = ctx.decoding_size_estimation
ctx.decoding_size_estimation = True
try:
tensor_output_path = os.path.join(tmp_path, "tensor")
# NOTE: It's crucial to override # of blocks to get stable # of files
# produced and make sure data size estimates are stable
ray.data.range_tensor(
1000, shape=(1000,), override_num_blocks=10
).write_parquet(tensor_output_path)
ds = ray.data.read_parquet(tensor_output_path)
data_size = ds.size_bytes()
assert (
data_size >= 6_000_000 and data_size <= 10_000_000
), "estimated data size is out of expected bound"
data_size = ds.materialize().size_bytes()
assert (
data_size >= 7_000_000 and data_size <= 10_000_000
), "actual data size is out of expected bound"
datasource = ParquetDatasource(tensor_output_path)
assert (
datasource._encoding_ratio >= 300 and datasource._encoding_ratio <= 600
), "encoding ratio is out of expected bound"
data_size = datasource.estimate_inmemory_data_size()
assert (
data_size >= 6_000_000 and data_size <= 10_000_000
), "estimated data size is either out of expected bound"
assert (
data_size
== ParquetDatasource(tensor_output_path).estimate_inmemory_data_size()
), "estimated data size is not deterministic in multiple calls."
text_output_path = os.path.join(tmp_path, "text")
ray.data.range(1000).map(lambda _: {"text": "a" * 1000}).write_parquet(
text_output_path
)
ds = ray.data.read_parquet(text_output_path)
data_size = ds.size_bytes()
assert (
data_size >= 700_000 and data_size <= 2_200_000
), "estimated data size is out of expected bound"
data_size = ds.materialize().size_bytes()
assert (
data_size >= 1_000_000 and data_size <= 2_000_000
), "actual data size is out of expected bound"
datasource = ParquetDatasource(text_output_path)
assert (
datasource._encoding_ratio >= 6 and datasource._encoding_ratio <= 300
), "encoding ratio is out of expected bound"
data_size = datasource.estimate_inmemory_data_size()
assert (
data_size >= 700_000 and data_size <= 2_200_000
), "estimated data size is out of expected bound"
assert (
data_size
== ParquetDatasource(text_output_path).estimate_inmemory_data_size()
), "estimated data size is not deterministic in multiple calls."
finally:
ctx.decoding_size_estimation = old_decoding_size_estimation
def test_parquet_write(ray_start_regular_shared, tmp_path):
input_df = pd.DataFrame({"id": [0]})
ds = ray.data.from_blocks([input_df])
ds.write_parquet(tmp_path)
output_df = pd.concat(
[
pd.read_parquet(os.path.join(tmp_path, filename))
for filename in os.listdir(tmp_path)
]
)
assert rows_same(input_df, output_df)
def test_parquet_write_ignore_save_mode(ray_start_regular_shared, local_path):
data_path = local_path
path = os.path.join(data_path, "test_parquet_dir")
os.mkdir(path)
in_memory_table = pa.Table.from_pydict({"one": [1]})