Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 166 additions & 0 deletions cpp/src/parquet/arrow/arrow_reader_writer_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"
Expand Down Expand Up @@ -3668,6 +3670,170 @@ 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, 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<Buffer> 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>(
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<TypedColumnWriter<Int32Type>*>(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<int16_t> def_levels = {2, 2, 1, 2, 2};
std::vector<int16_t> rep_levels = {0, 1, 0, 0, 1};
std::vector<int32_t> 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<FileReader> reader;
ASSERT_OK_AND_ASSIGN(reader, OpenFile(std::make_shared<BufferReader>(buffer),
::arrow::default_memory_pool()));
std::shared_ptr<Table> table;
EXPECT_RAISES_WITH_MESSAGE_THAT(
Invalid, testing::HasSubstr("Expected all lists to be of size=2"),
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<Buffer> 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>(
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<TypedColumnWriter<Int32Type>*>(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<int16_t> def_levels = {1, 1, 0, 1, 1};
std::vector<int16_t> rep_levels = {0, 1, 0, 0, 1};
std::vector<int32_t> 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<FileReader> reader;
ASSERT_OK_AND_ASSIGN(reader, OpenFile(std::make_shared<BufferReader>(buffer),
::arrow::default_memory_pool()));
std::shared_ptr<Table> table;
EXPECT_RAISES_WITH_MESSAGE_THAT(
Invalid, testing::HasSubstr("Expected all lists to be of size=2"),
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<Buffer> 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>(
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<TypedColumnWriter<Int32Type>*>(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<int16_t> def_levels = {2, 2, 1, 2, 2};
std::vector<int16_t> rep_levels = {0, 1, 0, 0, 1};
std::vector<int32_t> 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<FileReader> reader;
ASSERT_OK_AND_ASSIGN(reader, OpenFile(std::make_shared<BufferReader>(buffer),
::arrow::default_memory_pool()));
std::shared_ptr<Table> 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;
Expand Down
130 changes: 103 additions & 27 deletions cpp/src/parquet/arrow/reader.cc
Original file line number Diff line number Diff line change
Expand Up @@ -604,8 +604,8 @@ class ListReader : public ColumnReaderImpl {
::parquet::internal::LevelInfo level_info,
std::unique_ptr<ColumnReaderImpl> 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 {
Expand Down Expand Up @@ -691,10 +691,11 @@ class ListReader : public ColumnReaderImpl {

protected:
std::shared_ptr<ReaderContext> ctx_;
::parquet::internal::LevelInfo level_info_;
ColumnReaderImpl* item_reader() const { return item_reader_.get(); }

private:
std::shared_ptr<Field> field_;
::parquet::internal::LevelInfo level_info_;
std::unique_ptr<ColumnReaderImpl> item_reader_;
};

Expand Down Expand Up @@ -735,10 +736,68 @@ class PARQUET_NO_EXPORT FixedSizeListReader : public ListReader<int32_t> {
std::unique_ptr<ColumnReaderImpl> 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<ChunkedArray>* 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<ResizableBuffer> 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<ResizableBuffer> 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<int32_t*>(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<ArrayData> item_chunk,
ChunksToSingle(**out, ctx_->pool));

std::vector<std::shared_ptr<Buffer>> buffers{validity_buffer, offsets_buffer};
auto data = std::make_shared<ArrayData>(
field()->type(),
/*length=*/validity_io.values_read, std::move(buffers),
std::vector<std::shared_ptr<ArrayData>>{item_chunk}, validity_io.null_count);

ARROW_ASSIGN_OR_RAISE(*out, AssembleArray(std::move(data)));
return Status::OK();
}

::arrow::Result<std::shared_ptr<ChunkedArray>> AssembleArray(
std::shared_ptr<ArrayData> 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<const int32_t*>(data->buffers[1]->data());
const int32_t list_size = type.list_size();
Expand All @@ -763,40 +822,57 @@ class PARQUET_NO_EXPORT FixedSizeListReader : public ListReader<int32_t> {
}
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.
::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();
};
}));

DCHECK_NE(data->buffers[0], nullptr);
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, visit_run));

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();
} else {
RETURN_NOT_OK(validate_offsets(/*start=*/0, data->length, /*valid=*/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<Array> result = ::arrow::MakeArray(data);
Expand Down
Loading