diff --git a/python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py b/python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py new file mode 100644 --- /dev/null +++ b/python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py @@ -0,0 +1,303 @@ +# 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. + +# LoLBench augmentation suite for Apache Arrow PR-45360 (Content-Defined +# Chunking). These F2P tests are designed to kill the surviving mutants in +# mutations/Apache-Arrow_Issue-45750_..._PR-45360/ that the original F2P +# (test_parquet_content_defined_chunking, test_parquet_content_defined_chunking_parameters) +# do not fully cover. +# +# Public API only: pyarrow.parquet.write_table, pyarrow.parquet.read_table, +# pyarrow.parquet.read_metadata, and pyarrow.parquet.ParquetFile. This file +# does not reference any underscore-prefixed PyArrow submodule, any C++ +# detail/internal namespace, or any non-exported helper. The surface gate +# (classify_test_surface.py) checks for that. + +from decimal import Decimal + +import pytest + +import pyarrow as pa +import pyarrow.parquet as pq + + +def _row_group_total_byte_size(path): + meta = pq.read_metadata(path) + return sum(meta.row_group(i).total_byte_size + for i in range(meta.num_row_groups)) + + +def _stable_int_table(n_rows): + # Deterministic, non-repetitive payload large enough that the default + # 256 KiB / 1 MiB CDC window can fire multiple cuts on the int64 column. + # range(n_rows) at int64 is 8 * n_rows bytes; 400_000 rows ~= 3.2 MiB. + return pa.table({'a': pa.array(range(n_rows), type=pa.int64())}) + + +def _mixed_physical_table(n_rows): + indices = pa.array( + [None if i % 19 == 0 else i % 8 for i in range(n_rows)], + type=pa.int32()) + dictionary = pa.array([f'dict-{j}' for j in range(8)], type=pa.string()) + list_values = [ + None if i % 17 == 0 + else [i, None if i % 5 == 0 else i + 1, i + 2] + for i in range(n_rows) + ] + fixed_values = [ + ((i & 0xffffffff).to_bytes(4, 'little') + + ((i * 17) & 0xffffffff).to_bytes(4, 'little')) + for i in range(n_rows) + ] + return pa.table({ + 'flag': pa.array([(i % 3) == 0 for i in range(n_rows)], + type=pa.bool_()), + 'nullable_i32': pa.array( + [None if i % 11 == 0 else i for i in range(n_rows)], + type=pa.int32()), + 'fixed8': pa.array(fixed_values, type=pa.binary(8)), + 'large_text': pa.array( + [f'large-{i:08d}-' + 'abcdefghij' * 4 + for i in range(n_rows)], + type=pa.large_string()), + 'amount': pa.array([Decimal(i % 100000) for i in range(n_rows)], + type=pa.decimal128(18, 0)), + 'items': pa.array(list_values, type=pa.list_(pa.int32())), + 'dict_text': pa.DictionaryArray.from_arrays(indices, dictionary), + }) + + +def test_cdc_dict_min_chunk_size_affects_output_size(tempdir): + """A larger min_chunk_size must suppress fine-grained cutpoints and yield + a smaller total_byte_size than a tiny min_chunk_size, when max_chunk_size + is held constant. + + Kills surviving mutants: + * mutant_002 (dict path disables CDC) — both files identical + * mutant_003 (no hash cutpoints) — min_chunk_size has no effect; both + files are split identically at max + * mutant_004 (no page flush) — chunks computed but not flushed; both + files identical to CDC=False output + """ + table = _stable_int_table(400_000) + + fine_path = tempdir / 'cdc_min_fine.parquet' + coarse_path = tempdir / 'cdc_min_coarse.parquet' + + pq.write_table(table, fine_path, + use_dictionary=False, + column_encoding="PLAIN", + use_content_defined_chunking={ + "min_chunk_size": 4 * 1024, + "max_chunk_size": 64 * 1024, + }) + pq.write_table(table, coarse_path, + use_dictionary=False, + column_encoding="PLAIN", + use_content_defined_chunking={ + "min_chunk_size": 32 * 1024, + "max_chunk_size": 64 * 1024, + }) + + # Round-trip data must be identical (no CDC bug should lose rows). + assert pq.read_table(fine_path).equals(table) + assert pq.read_table(coarse_path).equals(table) + + fine_size = _row_group_total_byte_size(fine_path) + coarse_size = _row_group_total_byte_size(coarse_path) + + # Golden: smaller min => more hash-driven cutpoints => more pages => + # strictly larger reported total_byte_size. Even a 5% delta is enough + # to distinguish from any of the surviving mutants, which produce + # identical sizes for the two configs. + assert fine_size > coarse_size, ( + f"expected min_chunk_size=4KiB to produce a larger total_byte_size " + f"than min_chunk_size=32KiB with max=64KiB held constant; got " + f"fine={fine_size} coarse={coarse_size}" + ) + + +def test_cdc_dict_norm_level_affects_output_size(tempdir): + """norm_level must measurably shift the chunk-size distribution. A + positive norm_level widens the hash mask, raising the probability of a + cutpoint and shrinking the average chunk -> more pages -> larger + total_byte_size than norm_level=0. + + Kills surviving mutants: + * mutant_002 (dict path disables CDC) — both files identical to CDC=off + * mutant_003 (no hash cutpoints) — norm_level controls only the hash + mask; without recorded matches it has no effect + * mutant_004 (no page flush) — chunks computed but not flushed; both + files identical to CDC=off output + """ + table = _stable_int_table(400_000) + + norm0_path = tempdir / 'cdc_norm0.parquet' + norm2_path = tempdir / 'cdc_norm2.parquet' + + pq.write_table(table, norm0_path, + use_dictionary=False, + column_encoding="PLAIN", + use_content_defined_chunking={ + "min_chunk_size": 8 * 1024, + "max_chunk_size": 64 * 1024, + "norm_level": 0, + }) + pq.write_table(table, norm2_path, + use_dictionary=False, + column_encoding="PLAIN", + use_content_defined_chunking={ + "min_chunk_size": 8 * 1024, + "max_chunk_size": 64 * 1024, + "norm_level": 2, + }) + + assert pq.read_table(norm0_path).equals(table) + assert pq.read_table(norm2_path).equals(table) + + norm0_size = _row_group_total_byte_size(norm0_path) + norm2_size = _row_group_total_byte_size(norm2_path) + + # Under the golden patch, norm_level=2 produces measurably more cuts + # (smaller average chunks) and therefore a larger total_byte_size. + assert norm2_size > norm0_size, ( + f"expected norm_level=2 to produce a larger total_byte_size than " + f"norm_level=0 with identical min/max; got norm0={norm0_size} " + f"norm2={norm2_size}" + ) + + +def test_cdc_true_changes_layout_vs_false_on_string_column(tempdir): + """CDC=True must change the on-disk layout (relative to CDC=False) for a + string column large enough to span multiple default chunks. This both + extends coverage to the string-typed branch of the chunker dispatch and + re-kills mutant_001 / mutant_004 through a different data shape than the + existing test_parquet_content_defined_chunking (which uses int64 only). + + Kills surviving mutants: + * mutant_001 (True silently disables CDC) — CDC=True file is byte- + identical to CDC=False file + * mutant_004 (no page flush) — CDC=True file has the same row-group + layout as CDC=False + """ + # ~5 MiB of payload across 50_000 rows of 100-byte strings; comfortably + # above the default 256 KiB / 1 MiB CDC window so multiple cuts fire. + values = [(f"row-{i:08d}-" + "x" * 80) for i in range(50_000)] + table = pa.table({'s': pa.array(values, type=pa.string())}) + + cdc_off_path = tempdir / 'cdc_off_string.parquet' + cdc_on_path = tempdir / 'cdc_on_string.parquet' + + pq.write_table(table, cdc_off_path, + use_dictionary=False, + column_encoding="PLAIN", + use_content_defined_chunking=False) + pq.write_table(table, cdc_on_path, + use_dictionary=False, + column_encoding="PLAIN", + use_content_defined_chunking=True) + + # Data must round-trip identically under both settings. + assert pq.read_table(cdc_off_path).equals(table) + assert pq.read_table(cdc_on_path).equals(table) + + off_size = _row_group_total_byte_size(cdc_off_path) + on_size = _row_group_total_byte_size(cdc_on_path) + + # CDC=True must visibly change the page layout for a multi-chunk string + # column. Existing F2P uses int64; this catches mutants that only break + # the chunker dispatch on non-numeric types or that disable the True + # branch silently. + assert on_size > off_size, ( + f"expected use_content_defined_chunking=True to increase the " + f"reported total_byte_size on a multi-chunk string column; got " + f"off={off_size} on={on_size}" + ) + + +def test_cdc_mixed_physical_layouts_roundtrip_and_change_layout(tempdir): + """CDC must work through public writes for the physical layouts Arrow + commonly maps to Parquet pages: booleans, nullable fixed-width values, + fixed-size binary, large strings, decimals, nested list values, and + dictionary arrays. This reaches chunker branches not covered by the + original int64-only F2P while keeping the oracle at the public Parquet + read/write surface. + """ + table = _mixed_physical_table(50_000) + + cdc_off_path = tempdir / 'cdc_off_mixed.parquet' + cdc_on_path = tempdir / 'cdc_on_mixed.parquet' + + pq.write_table(table, cdc_off_path, + row_group_size=table.num_rows, + use_content_defined_chunking=False) + pq.write_table(table, cdc_on_path, + row_group_size=table.num_rows, + use_content_defined_chunking={ + "min_chunk_size": 4 * 1024, + "max_chunk_size": 32 * 1024, + "norm_level": 1, + }) + + got = pq.read_table(cdc_on_path) + assert got.num_rows == table.num_rows + assert got.column('nullable_i32').to_pylist() == ( + table.column('nullable_i32').to_pylist()) + assert got.column('items').to_pylist() == table.column('items').to_pylist() + + off_size = _row_group_total_byte_size(cdc_off_path) + on_size = _row_group_total_byte_size(cdc_on_path) + assert on_size > off_size, ( + f"expected CDC to change the metadata-visible page layout for " + f"mixed physical columns; got off={off_size} on={on_size}" + ) + + +def test_cdc_true_determinism_across_repeated_writes(tempdir): + """Two writes of the same table with use_content_defined_chunking=True + must produce byte-identical files. The CDC chunker is deterministic for + a given input (rolling hash + fixed mask), so the file size, row-group + count, and per-row-group total_byte_size must all match. + + This is a sanity check that reinforces F2P-cov: it exercises the CDC + code path twice in the same test and confirms the deterministic-rollback + property called out in the requirement doc ("ensuring that identical + data segments are consistently chunked in the same manner"). + """ + table = _stable_int_table(200_000) + + a_path = tempdir / 'cdc_det_a.parquet' + b_path = tempdir / 'cdc_det_b.parquet' + + for p in (a_path, b_path): + pq.write_table(table, p, + use_dictionary=False, + column_encoding="PLAIN", + use_content_defined_chunking=True) + + a_meta = pq.read_metadata(a_path) + b_meta = pq.read_metadata(b_path) + + assert a_meta.num_row_groups == b_meta.num_row_groups + a_sizes = [a_meta.row_group(i).total_byte_size + for i in range(a_meta.num_row_groups)] + b_sizes = [b_meta.row_group(i).total_byte_size + for i in range(b_meta.num_row_groups)] + assert a_sizes == b_sizes, ( + f"CDC must be deterministic across repeated writes of the same " + f"data; got {a_sizes} vs {b_sizes}" + ) diff --git a/python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py b/python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py new file mode 100644 --- /dev/null +++ b/python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py @@ -0,0 +1,153 @@ +# 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. + +# LoLBench augmentation suite for Apache Arrow PR-45360 — P2P (stability) +# tests. +# +# Scope: behaviors the requirement doc promises remain unchanged when the +# new ``use_content_defined_chunking`` argument is not used. Each test +# below uses ONLY pre-PR public API (no reference to +# ``use_content_defined_chunking`` in any form) so it must pass at +# ``base_commit`` as well as at ``base_commit + solution.patch`` and under +# every surviving mutant — those mutants only change CDC-related code paths. +# +# Public API only: pyarrow.parquet.{write_table, read_table, read_metadata, +# ParquetWriter, ParquetFile}. No internal symbols referenced. + +import pyarrow as pa +import pyarrow.parquet as pq + + +def _basic_int_table(n_rows=1000): + return pa.table({'a': pa.array(range(n_rows), type=pa.int64()), + 'b': pa.array([float(i) for i in range(n_rows)], + type=pa.float64())}) + + +def test_writer_default_no_cdc_arg_roundtrip(tempdir): + """Calling write_table with no CDC-related argument must round-trip the + data identically, with the schema preserved. This pins the + backwards-compat clause that the new optional parameter is purely + additive.""" + table = _basic_int_table(2000) + path = tempdir / 'default_roundtrip.parquet' + pq.write_table(table, path) + + got = pq.read_table(path) + assert got.equals(table) + assert got.schema.equals(table.schema) + + +def test_writer_compression_snappy_roundtrip_unchanged(tempdir): + """The pre-existing ``compression`` argument must continue to control + on-disk compression independently of any CDC machinery.""" + table = _basic_int_table(2000) + path = tempdir / 'snappy.parquet' + pq.write_table(table, path, compression='snappy') + + got = pq.read_table(path) + assert got.equals(table) + # Metadata must surface the requested compression. + meta = pq.read_metadata(path) + rg = meta.row_group(0) + for col in range(rg.num_columns): + assert rg.column(col).compression.lower() == 'snappy' + + +# NOTE: a column_encoding-honoured P2P probe was attempted but dropped +# from the augmented suite. Probing with DELTA_BINARY_PACKED (the only +# non-default option that could differentiate against use_dictionary=False +# defaults of PLAIN) interacts with the PR's CDC initialization path and +# surfaces an unrelated OSError at write_table call time at this base_commit. +# Probing with PLAIN cannot be differentiated from the no-dict default, +# which collapses the oracle. Rather than ship a flaky P2P we omit this +# clause from the augmented suite; the no_modification clause for +# 'column_encoding' is not pinned by an augmented test. Six other P2P +# (default writer, compression, data_page_size, ParquetWriter context +# manager, read_metadata, ParquetFile.read_row_group) cover the remaining +# no-modification surface. + + +def test_writer_data_page_size_unchanged(tempdir): + """Pre-existing ``data_page_size`` argument: a smaller data-page size + must produce a measurably larger reported total_byte_size than a larger + one, with no CDC argument involved.""" + table = pa.table({'a': pa.array(range(100_000), type=pa.int64())}) + small_path = tempdir / 'page_small.parquet' + large_path = tempdir / 'page_large.parquet' + + pq.write_table(table, small_path, + use_dictionary=False, + column_encoding='PLAIN', + data_page_size=8 * 1024) + pq.write_table(table, large_path, + use_dictionary=False, + column_encoding='PLAIN', + data_page_size=512 * 1024) + + small_meta = pq.read_metadata(small_path) + large_meta = pq.read_metadata(large_path) + small_total = sum(small_meta.row_group(i).total_byte_size + for i in range(small_meta.num_row_groups)) + large_total = sum(large_meta.row_group(i).total_byte_size + for i in range(large_meta.num_row_groups)) + assert small_total > large_total, ( + f"data_page_size=8KiB should produce a larger reported total than " + f"512KiB; got small={small_total} large={large_total}" + ) + + +def test_parquet_writer_context_manager_default_path(tempdir): + """ParquetWriter usable as a context manager with no CDC argument; the + pre-PR contract (constructor, write_table, close-on-exit) must still + hold.""" + table = _basic_int_table(1500) + path = tempdir / 'context_writer.parquet' + with pq.ParquetWriter(str(path), table.schema) as writer: + writer.write_table(table) + got = pq.read_table(path) + assert got.equals(table) + + +def test_read_metadata_for_default_file_unchanged_shape(tempdir): + """``read_metadata`` must report the expected row-group count and schema + for a vanilla file (no CDC argument). Pins the read-side + no-modification promise: nothing about default-written files moves.""" + table = _basic_int_table(5000) + path = tempdir / 'default_meta.parquet' + pq.write_table(table, path) + + meta = pq.read_metadata(path) + assert meta.num_rows == 5000 + assert meta.num_columns == 2 + # Schema columns by name match input schema. + names = [meta.schema.column(i).name for i in range(meta.num_columns)] + assert names == ['a', 'b'] + + +def test_parquet_file_read_row_group_default_unchanged(tempdir): + """``ParquetFile.read_row_group`` must work on a default-written file + and return data that ``equals`` the original.""" + table = _basic_int_table(3000) + path = tempdir / 'default_rg.parquet' + pq.write_table(table, path, row_group_size=1000) + + pf = pq.ParquetFile(path) + assert pf.num_row_groups == 3 + chunks = [pf.read_row_group(i) for i in range(pf.num_row_groups)] + full = pa.concat_tables(chunks) + assert full.equals(table)