From fd8522ae48ffaa30687f4390312b36db99cbd11b Mon Sep 17 00:00:00 2001 From: 1fanwang <1fannnw@gmail.com> Date: Sat, 21 Nov 2026 04:50:03 -0500 Subject: [PATCH 1/4] GH-55682: [C++][Parquet] Fix non-nullable list inside null ancestor The reader only padded a null fixed-size list slot when the list's own null count was nonzero, but a non-nullable list never has a validity bitmap. A null struct ancestor leaves no child values written for that row, and nothing recorded the gap. Detect it from the offsets directly: a zero-length span where list_size was expected is padded the same way an own-null run already is. Signed-off-by: 1fanwang <1fannnw@gmail.com> --- .../parquet/arrow/arrow_reader_writer_test.cc | 15 +++++++ cpp/src/parquet/arrow/reader.cc | 43 +++++++++++++++---- 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc index 6df48ff19a45..30043bf3ec9f 100644 --- a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc +++ b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc @@ -3668,6 +3668,21 @@ TEST_P(TestFixedSizeListRoundTrip, RoundTrip) { INSTANTIATE_TEST_SUITE_P(ArrowReadWrite, TestFixedSizeListRoundTrip, ::testing::ValuesIn(kFixedSizeListTestCases)); +TEST(ArrowReadWrite, NonNullableFixedSizeListInsideNullableStruct) { + // GH-55682: a non-nullable fixed-size list has no validity buffer of its + // own, so a null struct ancestor leaves no physical child values for that + // row, and nothing records the gap at the list level. + auto type = ::arrow::struct_( + {::arrow::field("shape", ::arrow::fixed_size_list(::arrow::int32(), 2), + /*nullable=*/false)}); + auto table = ::arrow::TableFromJSON(::arrow::schema({::arrow::field("x", type)}), {R"([ + {"x": {"shape": [1, 2]}}, + {"x": null}, + {"x": {"shape": [3, 4]}}])"}); + auto props_store_schema = ArrowWriterProperties::Builder().store_schema()->build(); + CheckSimpleRoundtrip(table, 2, props_store_schema); +} + TEST(ArrowReadWrite, ListOfStructOfList2) { using ::arrow::field; using ::arrow::list; diff --git a/cpp/src/parquet/arrow/reader.cc b/cpp/src/parquet/arrow/reader.cc index d3b8b5a05e45..7c6c8c78d073 100644 --- a/cpp/src/parquet/arrow/reader.cc +++ b/cpp/src/parquet/arrow/reader.cc @@ -763,9 +763,11 @@ class PARQUET_NO_EXPORT FixedSizeListReader : public ListReader { } return Status::OK(); }; - if (data->GetNullCount() != 0) { - // Rebuild the child array run-by-run so null fixed-size list slots still - // contribute list_size child values in the final layout. + // Rebuild the child array run-by-run so a fixed-size list slot with no + // physical child values - whether it is itself null, or a non-repeated + // ancestor was null so its elements were never written - still + // contributes list_size child values in the final layout. + auto rebuild_from_runs = [&](auto&& visit_runs) -> Status { ::arrow::ArrayVector child_arrays; auto visit_run = [&](int64_t start, int64_t length, bool has_elements) -> Status { @@ -785,18 +787,41 @@ class PARQUET_NO_EXPORT FixedSizeListReader : public ListReader { ::arrow::MakeArray(data->child_data[0]->Slice(offsets[start], child_length))); return Status::OK(); }; - - DCHECK_NE(data->buffers[0], nullptr); - RETURN_NOT_OK(::arrow::internal::VisitBitRuns( - data->buffers[0]->data(), data->offset, data->length, visit_run)); + RETURN_NOT_OK(visit_runs(visit_run)); // TODO(GH-50271): Build one padded child array directly instead of creating // one temporary Array/ArrayData per validity run and concatenating them. ARROW_ASSIGN_OR_RAISE(auto child_array_with_padding, ::arrow::Concatenate(child_arrays, ctx_->pool)); data->child_data[0] = child_array_with_padding->data(); - } else { - RETURN_NOT_OK(validate_offsets(/*start=*/0, data->length, /*valid=*/true)); + return Status::OK(); + }; + + if (data->GetNullCount() != 0) { + DCHECK_NE(data->buffers[0], nullptr); + RETURN_NOT_OK(rebuild_from_runs([&](auto&& visit_run) { + return ::arrow::internal::VisitBitRuns(data->buffers[0]->data(), data->offset, + data->length, visit_run); + })); + } else if (data->length > 0) { + // This field is schema non-nullable, so it has no validity buffer of + // its own: a null ancestor's "elements never written" gap can only be + // detected from the offsets directly, not from a (nonexistent) bitmap. + RETURN_NOT_OK(rebuild_from_runs([&](auto&& visit_run) -> Status { + int64_t run_start = 0; + bool run_has_elements = true; + for (int64_t i = 0; i < data->length; ++i) { + const bool has_elements = offsets[i + 1] != offsets[i]; + if (i == run_start) { + run_has_elements = has_elements; + } else if (has_elements != run_has_elements) { + RETURN_NOT_OK(visit_run(run_start, i - run_start, run_has_elements)); + run_start = i; + run_has_elements = has_elements; + } + } + return visit_run(run_start, data->length - run_start, run_has_elements); + })); } data->buffers.resize(1); std::shared_ptr result = ::arrow::MakeArray(data); From 64213807f56a3f9abde7fa5cbe54ee462e753a20 Mon Sep 17 00:00:00 2001 From: 1fanwang <1fannnw@gmail.com> Date: Sat, 21 Nov 2026 05:46:29 -0500 Subject: [PATCH 2/4] Address review: only pad on a real gap, reject corrupt ones A batch paid for a rebuild even with no gaps. A nullable field with zero nulls could pad a physically empty list instead of rejecting it, since its validity buffer is discarded whenever null count is zero, regardless of nullability. Branch on field()->nullable() instead: scan offsets for gaps only when non-nullable, since zero nulls on a nullable field already means no gap exists. Signed-off-by: 1fanwang <1fannnw@gmail.com> --- .../parquet/arrow/arrow_reader_writer_test.cc | 51 +++++++++++++++++ cpp/src/parquet/arrow/reader.cc | 55 +++++++++++++------ 2 files changed, 89 insertions(+), 17 deletions(-) diff --git a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc index 30043bf3ec9f..8f9c253f7903 100644 --- a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc +++ b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc @@ -42,6 +42,7 @@ #include "arrow/compute/api.h" #include "arrow/extension/json.h" #include "arrow/io/api.h" +#include "arrow/ipc/writer.h" #include "arrow/record_batch.h" #include "arrow/scalar.h" #include "arrow/table.h" @@ -52,6 +53,7 @@ #include "arrow/testing/util.h" #include "arrow/type_fwd.h" #include "arrow/type_traits.h" +#include "arrow/util/base64.h" #include "arrow/util/checked_cast.h" #include "arrow/util/config.h" // for ARROW_CSV and PARQUET_REQUIRE_ENCRYPTION #include "arrow/util/decimal.h" @@ -3683,6 +3685,55 @@ TEST(ArrowReadWrite, NonNullableFixedSizeListInsideNullableStruct) { CheckSimpleRoundtrip(table, 2, props_store_schema); } +TEST(ArrowReadWrite, FixedSizeListRejectsPresentEmptyListWithZeroNulls) { + // GH-55682 follow-up: a nullable fixed-size list field whose validity + // bitmap reports zero nulls must still reject a physically empty list, not + // silently reinterpret it as padding. Parquet has no native fixed-size-list + // type, so a positive fixed size is only ever reconstructed from Arrow + // schema metadata; a corrupt or adversarial file can still declare a list + // slot present (definition level one below the leaf) while writing none of + // its elements. Build that file with the low-level API, since a real + // Arrow write can never produce it. + auto arrow_schema = ::arrow::schema( + {::arrow::field("x", ::arrow::fixed_size_list(::arrow::int32(), 2))}); + ASSERT_OK_AND_ASSIGN( + std::shared_ptr serialized, + ::arrow::ipc::SerializeSchema(*arrow_schema, ::arrow::default_memory_pool())); + auto key_value_metadata = ::arrow::key_value_metadata( + {"ARROW:schema"}, {::arrow::util::base64_encode(serialized->ToString())}); + + auto element = PrimitiveNode::Make("element", Repetition::REQUIRED, ParquetType::INT32); + auto list = GroupNode::Make("list", Repetition::REPEATED, {element}); + auto x = GroupNode::Make("x", Repetition::OPTIONAL, {list}, LogicalType::List()); + auto schema_node = std::static_pointer_cast( + GroupNode::Make("schema", Repetition::REQUIRED, {x})); + + auto sink = CreateOutputStream(); + auto writer = ParquetFileWriter::Open(sink, schema_node, default_writer_properties(), + key_value_metadata); + auto row_group_writer = writer->AppendRowGroup(); + auto column_writer = + static_cast*>(row_group_writer->NextColumn()); + // Row 0: [1, 2]. Row 1: present but empty (corrupt for a fixed size of 2). + // Row 2: [3, 4]. def=2 is an element, def=1 is a present-but-empty list. + std::vector def_levels = {2, 2, 1, 2, 2}; + std::vector rep_levels = {0, 1, 0, 0, 1}; + std::vector values = {1, 2, 3, 4}; + column_writer->WriteBatch(def_levels.size(), def_levels.data(), rep_levels.data(), + values.data()); + row_group_writer->Close(); + writer->Close(); + + ASSERT_OK_AND_ASSIGN(auto buffer, sink->Finish()); + std::unique_ptr reader; + ASSERT_OK_AND_ASSIGN(reader, OpenFile(std::make_shared(buffer), + ::arrow::default_memory_pool())); + std::shared_ptr table; + EXPECT_RAISES_WITH_MESSAGE_THAT( + Invalid, testing::HasSubstr("Expected all lists to be of size=2"), + reader->ReadTable(&table)); +} + TEST(ArrowReadWrite, ListOfStructOfList2) { using ::arrow::field; using ::arrow::list; diff --git a/cpp/src/parquet/arrow/reader.cc b/cpp/src/parquet/arrow/reader.cc index 7c6c8c78d073..75741b61f1ff 100644 --- a/cpp/src/parquet/arrow/reader.cc +++ b/cpp/src/parquet/arrow/reader.cc @@ -763,16 +763,15 @@ class PARQUET_NO_EXPORT FixedSizeListReader : public ListReader { } return Status::OK(); }; - // Rebuild the child array run-by-run so a fixed-size list slot with no - // physical child values - whether it is itself null, or a non-repeated - // ancestor was null so its elements were never written - still - // contributes list_size child values in the final layout. + // Rebuild the child array run-by-run so null fixed-size list slots still + // contribute list_size child values in the final layout. `visit_runs` + // always covers the full [0, data->length) range, so an unexpected gap + // on a run that turns out not to need padding is still rejected by + // validate_offsets. auto rebuild_from_runs = [&](auto&& visit_runs) -> Status { ::arrow::ArrayVector child_arrays; - auto visit_run = [&](int64_t start, int64_t length, bool has_elements) -> Status { RETURN_NOT_OK(validate_offsets(start, length, has_elements)); - const int64_t child_length = length * list_size; // Valid runs reuse the decoded child slice; null runs materialize null // children to preserve the fixed-size list shape. @@ -788,7 +787,6 @@ class PARQUET_NO_EXPORT FixedSizeListReader : public ListReader { return Status::OK(); }; RETURN_NOT_OK(visit_runs(visit_run)); - // TODO(GH-50271): Build one padded child array directly instead of creating // one temporary Array/ArrayData per validity run and concatenating them. ARROW_ASSIGN_OR_RAISE(auto child_array_with_padding, @@ -797,17 +795,20 @@ class PARQUET_NO_EXPORT FixedSizeListReader : public ListReader { return Status::OK(); }; - if (data->GetNullCount() != 0) { - DCHECK_NE(data->buffers[0], nullptr); + if (data->buffers[0] != nullptr) { + // A real validity buffer survived, so at least one row in this batch + // is null; rebuild run-by-run so each null run is padded. RETURN_NOT_OK(rebuild_from_runs([&](auto&& visit_run) { return ::arrow::internal::VisitBitRuns(data->buffers[0]->data(), data->offset, data->length, visit_run); })); - } else if (data->length > 0) { - // This field is schema non-nullable, so it has no validity buffer of - // its own: a null ancestor's "elements never written" gap can only be - // detected from the offsets directly, not from a (nonexistent) bitmap. - RETURN_NOT_OK(rebuild_from_runs([&](auto&& visit_run) -> Status { + } else if (!field()->nullable() && data->length > 0) { + // This field is schema non-nullable, so it never has a validity buffer + // at all, with or without nulls: a null non-repeated ancestor (e.g. a + // struct) still leaves no physical child values for its row, and that + // gap can only be detected from the offsets directly. + bool any_gap = false; + auto scan_offsets = [&](auto&& visit) -> Status { int64_t run_start = 0; bool run_has_elements = true; for (int64_t i = 0; i < data->length; ++i) { @@ -815,13 +816,33 @@ class PARQUET_NO_EXPORT FixedSizeListReader : public ListReader { if (i == run_start) { run_has_elements = has_elements; } else if (has_elements != run_has_elements) { - RETURN_NOT_OK(visit_run(run_start, i - run_start, run_has_elements)); + RETURN_NOT_OK(visit(run_start, i - run_start, run_has_elements)); run_start = i; run_has_elements = has_elements; } } - return visit_run(run_start, data->length - run_start, run_has_elements); - })); + return visit(run_start, data->length - run_start, run_has_elements); + }; + // First pass: validate every run without allocating anything, and note + // whether any of them is missing its elements. + RETURN_NOT_OK( + scan_offsets([&](int64_t start, int64_t length, bool has_elements) -> Status { + RETURN_NOT_OK(validate_offsets(start, length, has_elements)); + any_gap = any_gap || !has_elements; + return Status::OK(); + })); + if (any_gap) { + // Second pass, only paid for a batch that actually needs padding. + RETURN_NOT_OK(rebuild_from_runs(scan_offsets)); + } + } else { + // Either this field is nullable but every row in this batch happens to + // be valid (so its validity buffer was discarded, the same as a + // genuinely non-nullable field), or the batch is empty. A nullable + // field's own null count already reflects any non-repeated ancestor's + // absence, so a zero null count means there is no gap anywhere: a + // single pass validating the whole range is enough, with no padding. + RETURN_NOT_OK(validate_offsets(/*start=*/0, data->length, /*has_elements=*/true)); } data->buffers.resize(1); std::shared_ptr result = ::arrow::MakeArray(data); From cc3528a915229d2c76a67ed4fde6c3c4b6ad1eaf Mon Sep 17 00:00:00 2001 From: 1fanwang <1fannnw@gmail.com> Date: Sat, 21 Nov 2026 06:08:41 -0500 Subject: [PATCH 3/4] Address review: require an optional ancestor before padding A non-nullable field has no validity buffer regardless of ancestor nullability, so the gap scan could not tell a null struct ancestor from a corrupt present-but-empty list under a bare REQUIRED list. Every repeated step raises def_level and rep_level equally, so def_level > rep_level means an ancestor is optional. Scan for gaps only then; otherwise reject any gap as corrupt. Signed-off-by: 1fanwang <1fannnw@gmail.com> --- .../parquet/arrow/arrow_reader_writer_test.cc | 47 +++++++++++++++++++ cpp/src/parquet/arrow/reader.cc | 33 ++++++++----- 2 files changed, 67 insertions(+), 13 deletions(-) diff --git a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc index 8f9c253f7903..d1d5de669f9d 100644 --- a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc +++ b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc @@ -3734,6 +3734,53 @@ TEST(ArrowReadWrite, FixedSizeListRejectsPresentEmptyListWithZeroNulls) { reader->ReadTable(&table)); } +TEST(ArrowReadWrite, FixedSizeListRejectsPresentEmptyListAtRequiredTopLevel) { + // GH-55682 follow-up: a bare top-level REQUIRED fixed-size list, with no + // optional ancestor anywhere in its path, can never legitimately have a + // missing row: there is nothing that could have been null to explain the + // gap. A physically empty list here is always corrupt data and must still + // raise the size-mismatch error, not be reinterpreted as padding. + auto arrow_schema = + ::arrow::schema({::arrow::field("x", ::arrow::fixed_size_list(::arrow::int32(), 2), + /*nullable=*/false)}); + ASSERT_OK_AND_ASSIGN( + std::shared_ptr serialized, + ::arrow::ipc::SerializeSchema(*arrow_schema, ::arrow::default_memory_pool())); + auto key_value_metadata = ::arrow::key_value_metadata( + {"ARROW:schema"}, {::arrow::util::base64_encode(serialized->ToString())}); + + auto element = PrimitiveNode::Make("element", Repetition::REQUIRED, ParquetType::INT32); + auto list = GroupNode::Make("list", Repetition::REPEATED, {element}); + auto x = GroupNode::Make("x", Repetition::REQUIRED, {list}, LogicalType::List()); + auto schema_node = std::static_pointer_cast( + GroupNode::Make("schema", Repetition::REQUIRED, {x})); + + auto sink = CreateOutputStream(); + auto writer = ParquetFileWriter::Open(sink, schema_node, default_writer_properties(), + key_value_metadata); + auto row_group_writer = writer->AppendRowGroup(); + auto column_writer = + static_cast*>(row_group_writer->NextColumn()); + // Row 0: [1, 2]. Row 1: present but empty (corrupt for a fixed size of 2). + // Row 2: [3, 4]. def=1 is an element, def=0 is a present-but-empty list. + std::vector def_levels = {1, 1, 0, 1, 1}; + std::vector rep_levels = {0, 1, 0, 0, 1}; + std::vector values = {1, 2, 3, 4}; + column_writer->WriteBatch(def_levels.size(), def_levels.data(), rep_levels.data(), + values.data()); + row_group_writer->Close(); + writer->Close(); + + ASSERT_OK_AND_ASSIGN(auto buffer, sink->Finish()); + std::unique_ptr reader; + ASSERT_OK_AND_ASSIGN(reader, OpenFile(std::make_shared(buffer), + ::arrow::default_memory_pool())); + std::shared_ptr
table; + EXPECT_RAISES_WITH_MESSAGE_THAT( + Invalid, testing::HasSubstr("Expected all lists to be of size=2"), + reader->ReadTable(&table)); +} + TEST(ArrowReadWrite, ListOfStructOfList2) { using ::arrow::field; using ::arrow::list; diff --git a/cpp/src/parquet/arrow/reader.cc b/cpp/src/parquet/arrow/reader.cc index 75741b61f1ff..94b54af5b7d8 100644 --- a/cpp/src/parquet/arrow/reader.cc +++ b/cpp/src/parquet/arrow/reader.cc @@ -604,8 +604,8 @@ class ListReader : public ColumnReaderImpl { ::parquet::internal::LevelInfo level_info, std::unique_ptr child_reader) : ctx_(std::move(ctx)), - field_(std::move(field)), level_info_(level_info), + field_(std::move(field)), item_reader_(std::move(child_reader)) {} Status GetDefLevels(const int16_t** data, int64_t* length) override { @@ -691,10 +691,10 @@ class ListReader : public ColumnReaderImpl { protected: std::shared_ptr ctx_; + ::parquet::internal::LevelInfo level_info_; private: std::shared_ptr field_; - ::parquet::internal::LevelInfo level_info_; std::unique_ptr item_reader_; }; @@ -802,11 +802,15 @@ class PARQUET_NO_EXPORT FixedSizeListReader : public ListReader { return ::arrow::internal::VisitBitRuns(data->buffers[0]->data(), data->offset, data->length, visit_run); })); - } else if (!field()->nullable() && data->length > 0) { - // This field is schema non-nullable, so it never has a validity buffer - // at all, with or without nulls: a null non-repeated ancestor (e.g. a - // struct) still leaves no physical child values for its row, and that - // gap can only be detected from the offsets directly. + } else if (!field()->nullable() && data->length > 0 && + level_info_.def_level > level_info_.rep_level) { + // This field is schema non-nullable, so it never has a validity + // buffer of its own. Since every repeated step raises def_level and + // rep_level equally, def_level > rep_level means some ancestor + // between the schema root and this list is itself optional, and that + // ancestor (e.g. a struct) being null still leaves no physical child + // values written for its row. That gap can only be detected from the + // offsets directly. bool any_gap = false; auto scan_offsets = [&](auto&& visit) -> Status { int64_t run_start = 0; @@ -836,12 +840,15 @@ class PARQUET_NO_EXPORT FixedSizeListReader : public ListReader { RETURN_NOT_OK(rebuild_from_runs(scan_offsets)); } } else { - // Either this field is nullable but every row in this batch happens to - // be valid (so its validity buffer was discarded, the same as a - // genuinely non-nullable field), or the batch is empty. A nullable - // field's own null count already reflects any non-repeated ancestor's - // absence, so a zero null count means there is no gap anywhere: a - // single pass validating the whole range is enough, with no padding. + // No ancestor between the schema root and this list can ever be null, + // since def_level == rep_level means there is no optional step + // anywhere in the path. Alternatively, this field is nullable but + // every row in this batch happens to be valid, so its validity + // buffer was discarded the same as a genuinely non-nullable field, or + // the batch is simply empty. In every one of these cases a + // zero-length span cannot be a legitimate gap, so a single pass + // validating the whole range is enough, with no padding: an + // unexpected span is rejected as corrupt data. RETURN_NOT_OK(validate_offsets(/*start=*/0, data->length, /*has_elements=*/true)); } data->buffers.resize(1); From d8efe8b1f052e30a30c5fe5dbe13543085bf5054 Mon Sep 17 00:00:00 2001 From: 1fanwang <1fannnw@gmail.com> Date: Sat, 21 Nov 2026 11:29:20 -0500 Subject: [PATCH 4/4] Address review: always compute validity from definition levels An absent ancestor and a corruptly empty required list under a present struct collapse to the same zero-length offset span, and a non-nullable field has no validity buffer to tell them apart. BuildArray always computes the per-slot bitmap from definition levels, which does distinguish them, clearing it for a non-nullable result. Added a required-list-under-present-struct regression. Signed-off-by: 1fanwang <1fannnw@gmail.com> --- .../parquet/arrow/arrow_reader_writer_test.cc | 53 +++++ cpp/src/parquet/arrow/reader.cc | 183 ++++++++++-------- 2 files changed, 156 insertions(+), 80 deletions(-) diff --git a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc index d1d5de669f9d..d347bd4c44c9 100644 --- a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc +++ b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc @@ -3781,6 +3781,59 @@ TEST(ArrowReadWrite, FixedSizeListRejectsPresentEmptyListAtRequiredTopLevel) { reader->ReadTable(&table)); } +TEST(ArrowReadWrite, FixedSizeListRejectsPresentEmptyListUnderPresentStruct) { + // GH-55682 follow-up: a REQUIRED fixed-size list nested in an OPTIONAL + // struct that is present (never null) for every row. Only the struct's + // own absence legitimately explains a missing child value; here the + // struct is present throughout, so a physically empty list is corrupt + // data and must still raise the size-mismatch error, not be padded as if + // the struct were null. + auto struct_type = ::arrow::struct_( + {::arrow::field("shape", ::arrow::fixed_size_list(::arrow::int32(), 2), + /*nullable=*/false)}); + auto arrow_schema = ::arrow::schema({::arrow::field("x", struct_type)}); + ASSERT_OK_AND_ASSIGN( + std::shared_ptr serialized, + ::arrow::ipc::SerializeSchema(*arrow_schema, ::arrow::default_memory_pool())); + auto key_value_metadata = ::arrow::key_value_metadata( + {"ARROW:schema"}, {::arrow::util::base64_encode(serialized->ToString())}); + + auto element = PrimitiveNode::Make("element", Repetition::REQUIRED, ParquetType::INT32); + auto list = GroupNode::Make("list", Repetition::REPEATED, {element}); + auto shape = + GroupNode::Make("shape", Repetition::REQUIRED, {list}, LogicalType::List()); + auto x = GroupNode::Make("x", Repetition::OPTIONAL, {shape}); + auto schema_node = std::static_pointer_cast( + GroupNode::Make("schema", Repetition::REQUIRED, {x})); + + auto sink = CreateOutputStream(); + auto writer = ParquetFileWriter::Open(sink, schema_node, default_writer_properties(), + key_value_metadata); + auto row_group_writer = writer->AppendRowGroup(); + auto column_writer = + static_cast*>(row_group_writer->NextColumn()); + // Row 0: x present, shape=[1, 2]. Row 1: x present, shape present but + // empty (corrupt for a fixed size of 2; x itself is never null here). + // Row 2: x present, shape=[3, 4]. def=2 is an element, def=1 is x present + // with shape's list present but empty, def=0 would be x null (unused). + std::vector def_levels = {2, 2, 1, 2, 2}; + std::vector rep_levels = {0, 1, 0, 0, 1}; + std::vector values = {1, 2, 3, 4}; + column_writer->WriteBatch(def_levels.size(), def_levels.data(), rep_levels.data(), + values.data()); + row_group_writer->Close(); + writer->Close(); + + ASSERT_OK_AND_ASSIGN(auto buffer, sink->Finish()); + std::unique_ptr reader; + ASSERT_OK_AND_ASSIGN(reader, OpenFile(std::make_shared(buffer), + ::arrow::default_memory_pool())); + std::shared_ptr
table; + EXPECT_RAISES_WITH_MESSAGE_THAT( + Invalid, testing::HasSubstr("Expected all lists to be of size=2"), + reader->ReadTable(&table)); +} + TEST(ArrowReadWrite, ListOfStructOfList2) { using ::arrow::field; using ::arrow::list; diff --git a/cpp/src/parquet/arrow/reader.cc b/cpp/src/parquet/arrow/reader.cc index 94b54af5b7d8..74308b498278 100644 --- a/cpp/src/parquet/arrow/reader.cc +++ b/cpp/src/parquet/arrow/reader.cc @@ -692,6 +692,7 @@ class ListReader : public ColumnReaderImpl { protected: std::shared_ptr ctx_; ::parquet::internal::LevelInfo level_info_; + ColumnReaderImpl* item_reader() const { return item_reader_.get(); } private: std::shared_ptr field_; @@ -735,10 +736,68 @@ class PARQUET_NO_EXPORT FixedSizeListReader : public ListReader { std::unique_ptr child_reader) : ListReader(std::move(ctx), std::move(field), level_info, std::move(child_reader)) {} + + Status BuildArray(int64_t length_upper_bound, + std::shared_ptr* out) override { + const int16_t* def_levels; + const int16_t* rep_levels; + int64_t num_levels; + RETURN_NOT_OK(GetDefLevels(&def_levels, &num_levels)); + RETURN_NOT_OK(GetRepLevels(&rep_levels, &num_levels)); + + // Always compute a validity bitmap here, even when this field is schema + // non-nullable: its per-slot definition levels are the only reliable + // signal that distinguishes an absent non-repeated ancestor (e.g. a null + // struct) from a present but corrupt empty fixed-size list. Both collapse + // to the same zero-length offset span once decoded, so AssembleArray + // cannot tell them apart from the offsets alone. + std::shared_ptr validity_buffer; + ::parquet::internal::ValidityBitmapInputOutput validity_io; + validity_io.values_read_upper_bound = length_upper_bound; + ARROW_ASSIGN_OR_RAISE( + validity_buffer, + AllocateResizableBuffer(bit_util::BytesForBits(length_upper_bound), ctx_->pool)); + validity_io.valid_bits = validity_buffer->mutable_data(); + + ARROW_ASSIGN_OR_RAISE( + std::shared_ptr offsets_buffer, + AllocateResizableBuffer( + sizeof(int32_t) * std::max(int64_t{1}, length_upper_bound + 1), ctx_->pool)); + // Ensure zero initialization in case we have reached a zero length list (and + // because first entry is always zero). + int32_t* offset_data = reinterpret_cast(offsets_buffer->mutable_data()); + offset_data[0] = 0; + BEGIN_PARQUET_CATCH_EXCEPTIONS + ::parquet::internal::DefRepLevelsToList(def_levels, rep_levels, num_levels, + level_info_, &validity_io, offset_data); + END_PARQUET_CATCH_EXCEPTIONS + + RETURN_NOT_OK(item_reader()->BuildArray(offset_data[validity_io.values_read], out)); + + // Resize to actual number of elements returned. + RETURN_NOT_OK( + offsets_buffer->Resize((validity_io.values_read + 1) * sizeof(int32_t))); + RETURN_NOT_OK( + validity_buffer->Resize(bit_util::BytesForBits(validity_io.values_read))); + validity_buffer->ZeroPadding(); + ARROW_ASSIGN_OR_RAISE(std::shared_ptr item_chunk, + ChunksToSingle(**out, ctx_->pool)); + + std::vector> buffers{validity_buffer, offsets_buffer}; + auto data = std::make_shared( + field()->type(), + /*length=*/validity_io.values_read, std::move(buffers), + std::vector>{item_chunk}, validity_io.null_count); + + ARROW_ASSIGN_OR_RAISE(*out, AssembleArray(std::move(data))); + return Status::OK(); + } + ::arrow::Result> AssembleArray( std::shared_ptr data) final { DCHECK_EQ(data->buffers.size(), 2); DCHECK_EQ(field()->type()->id(), ::arrow::Type::FIXED_SIZE_LIST); + DCHECK_NE(data->buffers[0], nullptr); const auto& type = checked_cast<::arrow::FixedSizeListType&>(*field()->type()); const auto* offsets = reinterpret_cast(data->buffers[1]->data()); const int32_t list_size = type.list_size(); @@ -763,93 +822,57 @@ class PARQUET_NO_EXPORT FixedSizeListReader : public ListReader { } return Status::OK(); }; - // Rebuild the child array run-by-run so null fixed-size list slots still - // contribute list_size child values in the final layout. `visit_runs` - // always covers the full [0, data->length) range, so an unexpected gap - // on a run that turns out not to need padding is still rejected by - // validate_offsets. - auto rebuild_from_runs = [&](auto&& visit_runs) -> Status { - ::arrow::ArrayVector child_arrays; - auto visit_run = [&](int64_t start, int64_t length, bool has_elements) -> Status { - RETURN_NOT_OK(validate_offsets(start, length, has_elements)); - const int64_t child_length = length * list_size; - // Valid runs reuse the decoded child slice; null runs materialize null - // children to preserve the fixed-size list shape. - if (!has_elements) { - ARROW_ASSIGN_OR_RAISE( - auto null_array, - ::arrow::MakeArrayOfNull(type.value_type(), child_length, ctx_->pool)); - child_arrays.push_back(std::move(null_array)); + + // First pass: validate every bitmap-driven run without allocating + // anything, and note whether any of them is missing its elements. The + // bitmap already reflects any absent non-repeated ancestor (its bit is + // clear there, same as for this field's own null), so a run marked + // valid but with a mismatched span is corrupt data, not a legitimate + // gap, regardless of whether this field itself is nullable. + bool any_gap = false; + RETURN_NOT_OK(::arrow::internal::VisitBitRuns( + data->buffers[0]->data(), data->offset, data->length, + [&](int64_t start, int64_t length, bool has_elements) -> Status { + RETURN_NOT_OK(validate_offsets(start, length, has_elements)); + any_gap = any_gap || !has_elements; return Status::OK(); - } - child_arrays.push_back( - ::arrow::MakeArray(data->child_data[0]->Slice(offsets[start], child_length))); - return Status::OK(); - }; - RETURN_NOT_OK(visit_runs(visit_run)); + })); + + if (any_gap) { + // Second pass, only paid for a batch that actually needs padding: + // rebuild the child array run-by-run so a null run still contributes + // list_size null child values in the final layout. + ::arrow::ArrayVector child_arrays; + RETURN_NOT_OK(::arrow::internal::VisitBitRuns( + data->buffers[0]->data(), data->offset, data->length, + [&](int64_t start, int64_t length, bool has_elements) -> Status { + const int64_t child_length = length * list_size; + // Valid runs reuse the decoded child slice; null runs materialize + // null children to preserve the fixed-size list shape. + if (!has_elements) { + ARROW_ASSIGN_OR_RAISE( + auto null_array, + ::arrow::MakeArrayOfNull(type.value_type(), child_length, ctx_->pool)); + child_arrays.push_back(std::move(null_array)); + return Status::OK(); + } + child_arrays.push_back(::arrow::MakeArray( + data->child_data[0]->Slice(offsets[start], child_length))); + return Status::OK(); + })); // TODO(GH-50271): Build one padded child array directly instead of creating // one temporary Array/ArrayData per validity run and concatenating them. ARROW_ASSIGN_OR_RAISE(auto child_array_with_padding, ::arrow::Concatenate(child_arrays, ctx_->pool)); data->child_data[0] = child_array_with_padding->data(); - return Status::OK(); - }; + } - if (data->buffers[0] != nullptr) { - // A real validity buffer survived, so at least one row in this batch - // is null; rebuild run-by-run so each null run is padded. - RETURN_NOT_OK(rebuild_from_runs([&](auto&& visit_run) { - return ::arrow::internal::VisitBitRuns(data->buffers[0]->data(), data->offset, - data->length, visit_run); - })); - } else if (!field()->nullable() && data->length > 0 && - level_info_.def_level > level_info_.rep_level) { - // This field is schema non-nullable, so it never has a validity - // buffer of its own. Since every repeated step raises def_level and - // rep_level equally, def_level > rep_level means some ancestor - // between the schema root and this list is itself optional, and that - // ancestor (e.g. a struct) being null still leaves no physical child - // values written for its row. That gap can only be detected from the - // offsets directly. - bool any_gap = false; - auto scan_offsets = [&](auto&& visit) -> Status { - int64_t run_start = 0; - bool run_has_elements = true; - for (int64_t i = 0; i < data->length; ++i) { - const bool has_elements = offsets[i + 1] != offsets[i]; - if (i == run_start) { - run_has_elements = has_elements; - } else if (has_elements != run_has_elements) { - RETURN_NOT_OK(visit(run_start, i - run_start, run_has_elements)); - run_start = i; - run_has_elements = has_elements; - } - } - return visit(run_start, data->length - run_start, run_has_elements); - }; - // First pass: validate every run without allocating anything, and note - // whether any of them is missing its elements. - RETURN_NOT_OK( - scan_offsets([&](int64_t start, int64_t length, bool has_elements) -> Status { - RETURN_NOT_OK(validate_offsets(start, length, has_elements)); - any_gap = any_gap || !has_elements; - return Status::OK(); - })); - if (any_gap) { - // Second pass, only paid for a batch that actually needs padding. - RETURN_NOT_OK(rebuild_from_runs(scan_offsets)); - } - } else { - // No ancestor between the schema root and this list can ever be null, - // since def_level == rep_level means there is no optional step - // anywhere in the path. Alternatively, this field is nullable but - // every row in this batch happens to be valid, so its validity - // buffer was discarded the same as a genuinely non-nullable field, or - // the batch is simply empty. In every one of these cases a - // zero-length span cannot be a legitimate gap, so a single pass - // validating the whole range is enough, with no padding: an - // unexpected span is rejected as corrupt data. - RETURN_NOT_OK(validate_offsets(/*start=*/0, data->length, /*has_elements=*/true)); + if (!field()->nullable()) { + // This field's own validity bitmap only exists to distinguish a + // genuine gap (now padded above) from corrupt data; a schema + // non-nullable array must not expose nulls of its own. + data->buffers[0] = nullptr; + data->null_count = 0; } data->buffers.resize(1); std::shared_ptr result = ::arrow::MakeArray(data);