diff --git a/cpp/src/arrow/compute/expression.cc b/cpp/src/arrow/compute/expression.cc index cd952055666..6c0ad45a15d 100644 --- a/cpp/src/arrow/compute/expression.cc +++ b/cpp/src/arrow/compute/expression.cc @@ -1422,7 +1422,7 @@ Result SimplifyIsValidGuarantee(Expression expr, std::move(expr), [](Expression expr) { return expr; }, [&](Expression expr, ...) -> Result { auto call = expr.call(); - if (!call) return expr; + if (!call || call->arguments.empty()) return expr; if (call->arguments[0] != guarantee.arguments[0]) return expr; @@ -1430,7 +1430,12 @@ Result SimplifyIsValidGuarantee(Expression expr, if (call->function_name == "true_unless_null") return literal(true); - if (call->function_name == "is_null") return literal(false); + if (call->function_name == "is_null" && + (!call->options || + !checked_cast(*call->options).nan_is_null || + !is_floating(call->arguments[0].type()->id()))) { + return literal(false); + } return expr; }); diff --git a/cpp/src/arrow/compute/expression_test.cc b/cpp/src/arrow/compute/expression_test.cc index e123411a3c7..ec9a6f7e34b 100644 --- a/cpp/src/arrow/compute/expression_test.cc +++ b/cpp/src/arrow/compute/expression_test.cc @@ -1994,6 +1994,17 @@ TEST(Expression, SimplifyWithGuarantee) { } TEST(Expression, SimplifyWithValidityGuarantee) { + auto nan_is_null = is_null(field_ref("f64"), /*nan_is_null=*/true); + Simplify{nan_is_null}.WithGuarantee(is_valid(field_ref("f64"))).Expect(nan_is_null); + Simplify{is_null(field_ref("i32"), /*nan_is_null=*/true)} + .WithGuarantee(is_valid(field_ref("i32"))) + .Expect(literal(false)); + Simplify{call("is_null", {field_ref("f64")})} + .WithGuarantee(is_valid(field_ref("f64"))) + .Expect(literal(false)); + auto random = call("random", {}, RandomOptions::FromSeed(7)); + Simplify{random}.WithGuarantee(is_valid(field_ref("f64"))).Expect(random); + Simplify{is_null(field_ref("i32"))} .WithGuarantee(is_null(field_ref("i32"))) .Expect(literal(true)); diff --git a/cpp/src/arrow/dataset/file_parquet.cc b/cpp/src/arrow/dataset/file_parquet.cc index 8aa96926e49..76b2b152ebe 100644 --- a/cpp/src/arrow/dataset/file_parquet.cc +++ b/cpp/src/arrow/dataset/file_parquet.cc @@ -17,6 +17,7 @@ #include "arrow/dataset/file_parquet.h" +#include #include #include #include @@ -26,11 +27,13 @@ #include "arrow/compute/cast.h" #include "arrow/compute/exec.h" +#include "arrow/compute/util.h" #include "arrow/dataset/dataset_internal.h" #include "arrow/dataset/parquet_encryption_config.h" #include "arrow/dataset/scanner.h" #include "arrow/filesystem/path_util.h" #include "arrow/table.h" +#include "arrow/type_traits.h" #include "arrow/util/checked_cast.h" #include "arrow/util/future.h" #include "arrow/util/iterator.h" @@ -589,6 +592,53 @@ struct SlicingGenerator { std::shared_ptr state; }; +namespace { + +bool HasUnambiguousNames(const FieldPath& path, const Schema& schema) { + const FieldVector* fields = &schema.fields(); + for (int index : path.indices()) { + const auto& field = (*fields)[index]; + if (std::count_if(fields->begin(), fields->end(), [&](const auto& sibling) { + return sibling->name() == field->name(); + }) != 1) { + return false; + } + fields = &field->type()->fields(); + } + return true; +} + +// Canonicalize references before consulting a cache shared by scans with different +// schemas. Keep the parameter's logical type and bound indices unchanged. +Result StatisticsFieldRefs(compute::Expression predicate, + const Schema& schema) { + return compute::ModifyExpression( + std::move(predicate), + [&schema](compute::Expression expr) -> Result { + const auto* parameter = expr.parameter(); + if (!parameter || parameter->ref.IsNameSequence()) return expr; + auto matches = parameter->ref.FindAll(schema); + if (matches.size() != 1 || !HasUnambiguousNames(matches.front(), schema)) { + return expr; + } + const auto& path = matches.front(); + std::vector names; + const FieldVector* fields = &schema.fields(); + for (int index : path.indices()) { + const auto& field = (*fields)[index]; + names.emplace_back(field->name()); + fields = &field->type()->fields(); + } + FieldRef ref(std::move(names)); + auto named = *parameter; + named.ref = std::move(ref); + return compute::Expression(std::move(named)); + }, + [](compute::Expression expr, compute::Expression*) { return expr; }); +} + +} // namespace + Result ParquetFileFormat::ScanBatchesAsync( const std::shared_ptr& options, const std::shared_ptr& file) const { @@ -600,7 +650,9 @@ Result ParquetFileFormat::ScanBatchesAsync( // prior statistics knowledge. In the case where a RowGroup doesn't have statistics // metadata, it will not be excluded. if (parquet_fragment->metadata() != nullptr) { - ARROW_ASSIGN_OR_RAISE(row_groups, parquet_fragment->FilterRowGroups(options->filter)); + ARROW_ASSIGN_OR_RAISE( + row_groups, parquet_fragment->FilterRowGroups(options->filter, + options->dataset_schema.get())); pre_filtered = true; if (row_groups.empty()) return MakeEmptyGenerator>(); } @@ -613,8 +665,9 @@ Result ParquetFileFormat::ScanBatchesAsync( RETURN_NOT_OK(parquet_fragment->EnsureCompleteMetadata(reader.get())); if (!pre_filtered) { // row groups were not already filtered; do this now - ARROW_ASSIGN_OR_RAISE(row_groups, - parquet_fragment->FilterRowGroups(options->filter)); + ARROW_ASSIGN_OR_RAISE( + row_groups, parquet_fragment->FilterRowGroups(options->filter, + options->dataset_schema.get())); if (row_groups.empty()) return MakeEmptyGenerator>(); } ARROW_ASSIGN_OR_RAISE(auto column_projection, @@ -653,14 +706,16 @@ Future> ParquetFileFormat::CountRows( const std::shared_ptr& options) { auto parquet_file = checked_pointer_cast(file); if (parquet_file->metadata()) { - ARROW_ASSIGN_OR_RAISE(auto maybe_count, - parquet_file->TryCountRows(std::move(predicate))); + ARROW_ASSIGN_OR_RAISE( + auto maybe_count, + parquet_file->TryCountRows(std::move(predicate), options->dataset_schema.get())); return Future>::MakeFinished(maybe_count); } else { return DeferNotOk(options->io_context.executor()->Submit( - [parquet_file, predicate]() -> Result> { + [parquet_file, predicate, + schema = options->dataset_schema]() -> Result> { RETURN_NOT_OK(parquet_file->EnsureCompleteMetadata()); - return parquet_file->TryCountRows(predicate); + return parquet_file->TryCountRows(predicate, schema.get()); })); } } @@ -829,9 +884,6 @@ Status ParquetFileFragment::SetMetadata( physical_schema_ = given_physical_schema_; } - statistics_expressions_.resize(row_groups_->size(), compute::literal(true)); - statistics_expressions_complete_.resize(manifest_->descr->num_columns(), false); - for (int row_group : *row_groups_) { // Ensure RowGroups are indexing valid RowGroups before augmenting. if (row_group < metadata_->num_row_groups()) continue; @@ -845,16 +897,25 @@ Status ParquetFileFragment::SetMetadata( } Status ParquetFileFragment::ClearCachedMetadata() { + auto lock = physical_schema_mutex_.Lock(); metadata_.reset(); manifest_.reset(); original_metadata_.reset(); - return FileFragment::ClearCachedMetadata(); + statistics_expressions_.clear(); + physical_schema_.reset(); + return Status::OK(); } Result ParquetFileFragment::SplitByRowGroup( compute::Expression predicate) { + return SplitByRowGroup(std::move(predicate), nullptr); +} + +Result ParquetFileFragment::SplitByRowGroup( + compute::Expression predicate, const Schema* dataset_schema) { RETURN_NOT_OK(EnsureCompleteMetadata()); - ARROW_ASSIGN_OR_RAISE(auto row_groups, FilterRowGroups(predicate)); + ARROW_ASSIGN_OR_RAISE(auto row_groups, + FilterRowGroups(std::move(predicate), dataset_schema)); FragmentVector fragments(row_groups.size()); int i = 0; @@ -873,8 +934,14 @@ Result ParquetFileFragment::SplitByRowGroup( Result> ParquetFileFragment::Subset( compute::Expression predicate) { + return Subset(std::move(predicate), nullptr); +} + +Result> ParquetFileFragment::Subset( + compute::Expression predicate, const Schema* dataset_schema) { RETURN_NOT_OK(EnsureCompleteMetadata()); - ARROW_ASSIGN_OR_RAISE(auto row_groups, FilterRowGroups(predicate)); + ARROW_ASSIGN_OR_RAISE(auto row_groups, + FilterRowGroups(std::move(predicate), dataset_schema)); return Subset(std::move(row_groups)); } @@ -897,10 +964,78 @@ inline void FoldingAnd(compute::Expression* l, compute::Expression r) { } } +namespace { + +// Bounds remain valid when the schema cast preserves ordering and every value. +bool CanUseStatistics(const DataType& physical, const DataType& logical) { + if (physical.Equals(logical)) return true; + if (is_integer(physical.id()) && is_integer(logical.id())) { + if (is_signed_integer(physical.id()) == is_signed_integer(logical.id())) { + return logical.bit_width() > physical.bit_width(); + } + return is_unsigned_integer(physical.id()) && + logical.bit_width() > physical.bit_width(); + } + if (is_floating(physical.id()) && is_floating(logical.id())) { + return logical.bit_width() > physical.bit_width(); + } + if (is_integer(physical.id()) && + (logical.id() == Type::FLOAT || logical.id() == Type::DOUBLE)) { + int precision = logical.id() == Type::DOUBLE ? 53 : 24; + return physical.bit_width() - is_signed_integer(physical.id()) <= precision; + } + if ((is_string(physical.id()) && is_string(logical.id())) || + (is_binary(physical.id()) && is_binary(logical.id()))) { + return true; + } + if (physical.id() == Type::FIXED_SIZE_BINARY && logical.id() == Type::LARGE_BINARY) { + return true; + } + if (is_string(physical.id()) && + (logical.id() == Type::LARGE_BINARY || + (physical.id() == Type::STRING && logical.id() == Type::BINARY))) { + return true; + } + if (is_decimal(physical.id()) && is_decimal(logical.id())) { + const auto& from = checked_cast(physical); + const auto& to = checked_cast(logical); + return from.scale() == to.scale() && from.precision() <= to.precision(); + } + if (physical.id() == Type::DATE32 && logical.id() == Type::DATE64) return true; + if (physical.id() == Type::DATE32 && logical.id() == Type::TIMESTAMP) { + const auto& to = checked_cast(logical); + return to.timezone().empty() && to.unit() <= TimeUnit::MILLI; + } + if (physical.id() == Type::TIMESTAMP && logical.id() == Type::TIMESTAMP) { + const auto& from = checked_cast(physical); + const auto& to = checked_cast(logical); + return from.timezone() == to.timezone() && from.unit() <= to.unit(); + } + // Parquet stores time32 seconds as milliseconds. Keep time-of-day comparisons. + return is_time(physical.id()) && + (physical.id() == logical.id() || + (physical.id() == Type::TIME32 && logical.id() == Type::TIME64)); +} + +void CollectFieldParameters( + const compute::Expression& expression, + std::vector* parameters) { + if (const auto* parameter = expression.parameter()) { + parameters->push_back(parameter); + } else if (const auto* call = expression.call()) { + for (const auto& argument : call->arguments) { + CollectFieldParameters(argument, parameters); + } + } +} + +} // namespace + Result> ParquetFileFragment::FilterRowGroups( - compute::Expression predicate) { + compute::Expression predicate, const Schema* dataset_schema) { std::vector row_groups; - ARROW_ASSIGN_OR_RAISE(auto expressions, TestRowGroups(std::move(predicate))); + ARROW_ASSIGN_OR_RAISE(auto expressions, + TestRowGroups(std::move(predicate), dataset_schema)); auto lock = physical_schema_mutex_.Lock(); DCHECK(expressions.empty() || (expressions.size() == row_groups_->size())); @@ -913,21 +1048,39 @@ Result> ParquetFileFragment::FilterRowGroups( } Result> ParquetFileFragment::TestRowGroups( - compute::Expression predicate) { + compute::Expression predicate, const Schema* dataset_schema) { auto lock = physical_schema_mutex_.Lock(); DCHECK_NE(metadata_, nullptr); ARROW_ASSIGN_OR_RAISE( - predicate, SimplifyWithGuarantee(std::move(predicate), partition_expression_)); + predicate, + StatisticsFieldRefs(std::move(predicate), + dataset_schema ? *dataset_schema : *physical_schema_)); + ARROW_ASSIGN_OR_RAISE( + auto partition, + StatisticsFieldRefs(partition_expression_, + dataset_schema ? *dataset_schema : *physical_schema_)); + ARROW_ASSIGN_OR_RAISE(predicate, + SimplifyWithGuarantee(std::move(predicate), partition)); if (!predicate.IsSatisfiable()) { return std::vector{}; } - for (const FieldRef& ref : FieldsInExpression(predicate)) { - ARROW_ASSIGN_OR_RAISE(auto match, ref.FindOneOrNone(*physical_schema_)); - - if (match.empty()) continue; + std::vector parameters; + CollectFieldParameters(predicate, ¶meters); + std::unordered_set seen_columns; + std::vector*, compute::Expression>> + applicable_statistics; + for (const auto* parameter : parameters) { + const auto& ref = parameter->ref; + // Do not mark ambiguous positional references as having cached statistics. + if (!ref.IsNameSequence()) continue; + auto matches = ref.FindAll(*physical_schema_); + if (matches.size() != 1 || !HasUnambiguousNames(matches.front(), *physical_schema_)) { + continue; + } + const auto& match = matches.front(); const SchemaField* schema_field = &manifest_->schema_fields[match[0]]; for (size_t i = 1; i < match.indices().size(); ++i) { @@ -937,39 +1090,73 @@ Result> ParquetFileFragment::TestRowGroups( schema_field = &schema_field->children[match[i]]; } + // Statistics are bound to the physical Arrow schema, before any dataset cast. + ARROW_ASSIGN_OR_RAISE(auto physical_field, match.Get(*physical_schema_)); if (!schema_field->is_leaf()) continue; - if (statistics_expressions_complete_[schema_field->column_index]) continue; - statistics_expressions_complete_[schema_field->column_index] = true; - - int i = 0; - for (int row_group : *row_groups_) { - auto row_group_metadata = metadata_->RowGroup(row_group); - - if (auto minmax = ColumnChunkStatisticsAsExpression(ref, *schema_field, - *row_group_metadata)) { - FoldingAnd(&statistics_expressions_[i], std::move(*minmax)); - ARROW_ASSIGN_OR_RAISE(statistics_expressions_[i], - statistics_expressions_[i].Bind(*physical_schema_)); - } + auto null_test = compute::literal(true); + if (!CanUseStatistics(*physical_field->type(), *parameter->type)) { + ARROW_ASSIGN_OR_RAISE(null_test, + is_null(compute::field_ref(ref)).Bind(*physical_schema_)); + } + const int column_index = schema_field->column_index; + if (!seen_columns.insert(column_index).second) continue; - ++i; + if (statistics_expressions_.empty()) { + statistics_expressions_.resize(manifest_->descr->num_columns()); + } + auto& column_statistics = statistics_expressions_[column_index]; + if (!column_statistics) { + std::vector statistics; + for (size_t i = 0; i < row_groups_->size(); ++i) { + auto row_group_metadata = metadata_->RowGroup((*row_groups_)[i]); + auto minmax = + ColumnChunkStatisticsAsExpression(ref, *schema_field, *row_group_metadata); + if (minmax) { + ARROW_ASSIGN_OR_RAISE(auto bound, minmax->Bind(*physical_schema_)); + if (statistics.empty()) { + statistics.resize(row_groups_->size(), compute::literal(true)); + } + statistics[i] = std::move(bound); + } + } + column_statistics = std::move(statistics); + } + if (!column_statistics->empty()) { + applicable_statistics.emplace_back(&*column_statistics, std::move(null_test)); } } std::vector row_groups(row_groups_->size()); for (size_t i = 0; i < row_groups_->size(); ++i) { + auto guarantee = compute::literal(true); + for (const auto& [column, null_test] : applicable_statistics) { + auto statistics = (*column)[i]; + if (null_test != compute::literal(true)) { + ARROW_ASSIGN_OR_RAISE(auto nullness, + SimplifyWithGuarantee(null_test, statistics)); + if (!nullness.literal()) continue; + statistics = nullness.IsSatisfiable() ? null_test + : is_valid(null_test.call()->arguments[0]); + } + if (statistics != compute::literal(true)) { + FoldingAnd(&guarantee, statistics); + } + } ARROW_ASSIGN_OR_RAISE(auto row_group_predicate, - SimplifyWithGuarantee(predicate, statistics_expressions_[i])); + SimplifyWithGuarantee(predicate, guarantee)); row_groups[i] = std::move(row_group_predicate); } return row_groups; } Result> ParquetFileFragment::TryCountRows( - compute::Expression predicate) { + compute::Expression predicate, const Schema* dataset_schema) { DCHECK_NE(metadata_, nullptr); if (ExpressionHasFieldRefs(predicate)) { - ARROW_ASSIGN_OR_RAISE(auto expressions, TestRowGroups(std::move(predicate))); + ARROW_ASSIGN_OR_RAISE(auto expressions, + TestRowGroups(std::move(predicate), dataset_schema)); + if (expressions.empty()) return int64_t{0}; + DCHECK_EQ(expressions.size(), row_groups_->size()); int64_t rows = 0; for (size_t i = 0; i < row_groups_->size(); i++) { // If the row group is entirely excluded, exclude it from the row count diff --git a/cpp/src/arrow/dataset/file_parquet.h b/cpp/src/arrow/dataset/file_parquet.h index 1811a96bf98..fdf638c04ba 100644 --- a/cpp/src/arrow/dataset/file_parquet.h +++ b/cpp/src/arrow/dataset/file_parquet.h @@ -158,6 +158,11 @@ class ARROW_DS_EXPORT ParquetFileFormat : public FileFormat { class ARROW_DS_EXPORT ParquetFileFragment : public FileFragment { public: Result SplitByRowGroup(compute::Expression predicate); + /// Resolve field references using the schema against which predicate was bound. + /// A null schema uses the physical schema. The schema is borrowed for this + /// synchronous call; the fragment does not retain the pointer. + Result SplitByRowGroup(compute::Expression predicate, + const Schema* dataset_schema); /// \brief Return the RowGroups selected by this fragment. const std::vector& row_groups() const { @@ -179,6 +184,11 @@ class ARROW_DS_EXPORT ParquetFileFragment : public FileFragment { /// \brief Return fragment which selects a filtered subset of this fragment's RowGroups. Result> Subset(compute::Expression predicate); + /// Resolve field references using the schema against which predicate was bound. + /// A null schema uses the physical schema. The schema is borrowed for this + /// synchronous call; the fragment does not retain the pointer. + Result> Subset(compute::Expression predicate, + const Schema* dataset_schema); Result> Subset(std::vector row_group_ids); static std::optional EvaluateStatisticsAsExpression( @@ -205,13 +215,16 @@ class ARROW_DS_EXPORT ParquetFileFragment : public FileFragment { } /// Return a filtered subset of row group indices. - Result> FilterRowGroups(compute::Expression predicate); + Result> FilterRowGroups(compute::Expression predicate, + const Schema* dataset_schema = nullptr); /// Simplify the predicate against the statistics of each row group. - Result> TestRowGroups(compute::Expression predicate); + Result> TestRowGroups(compute::Expression predicate, + const Schema* dataset_schema); /// Try to count rows matching the predicate using metadata. Expects /// metadata to be present, and expects the predicate to have been /// simplified against the partition expression already. - Result> TryCountRows(compute::Expression predicate); + Result> TryCountRows(compute::Expression predicate, + const Schema* dataset_schema); ParquetFileFormat& parquet_format_; @@ -219,12 +232,10 @@ class ARROW_DS_EXPORT ParquetFileFragment : public FileFragment { /// or std::nullopt if all row groups are selected. std::optional> row_groups_; - // the expressions (combined for all columns for which statistics have been - // processed) are stored per column group - std::vector statistics_expressions_; - // statistics status are kept track of by Parquet Schema column indices - // (i.e. not Arrow schema field index) - std::vector statistics_expressions_complete_; + // Lazily allocated statistics indexed by Parquet column, then by row group + // position in this fragment. A disengaged entry has not been read yet; + // an empty vector means that the column has no usable statistics. + std::vector>> statistics_expressions_; std::shared_ptr metadata_; std::shared_ptr manifest_; // The FileMetaData that owns the SchemaDescriptor pointed by SchemaManifest. diff --git a/cpp/src/arrow/dataset/file_parquet_test.cc b/cpp/src/arrow/dataset/file_parquet_test.cc index 0d86f5eaa0d..907f2b7a18a 100644 --- a/cpp/src/arrow/dataset/file_parquet_test.cc +++ b/cpp/src/arrow/dataset/file_parquet_test.cc @@ -304,6 +304,416 @@ TEST_F(TestParquetFileFormat, CountRows) { TestCountRows(); } TEST_F(TestParquetFileFormat, FragmentEquals) { TestFragmentEquals(); } +TEST_F(TestParquetFileFormat, PredicatePushdownWithCast) { + auto physical_schema = schema({field("x", utf8())}); + auto dataset_schema = schema({field("x", timestamp(TimeUnit::SECOND))}); + auto timestamp_filter = + less_equal(field_ref("x"), literal(TimestampScalar(1230854400, TimeUnit::SECOND))); + ASSERT_OK_AND_ASSIGN( + auto string_filter, + less(field_ref("x"), literal("2009-01-01")).Bind(*physical_schema)); + auto options = std::make_shared(); + + struct Case { + const char* rows; + const char* expected; + }; + for (const auto& test : + {Case{R"([["2009-01-01 12:00:00"], ["2009-01-03 12:00:00"]])", + R"([["2009-01-01 12:00:00"]])"}, + Case{R"([["2009-01-01 12:00:00"], ["2009-01-01 12:00:00"]])", + R"([["2009-01-01 12:00:00"], ["2009-01-01 12:00:00"]])"}, + Case{R"([["2009-01-01 12:00:00"], ["2009-01-03 12:00:00"], [null]])", + R"([["2009-01-01 12:00:00"]])"}, + Case{R"([[null], [null]])", "[]"}}) { + SCOPED_TRACE(test.rows); + auto batch = RecordBatchFromJSON(physical_schema, test.rows); + ASSERT_OK_AND_ASSIGN(auto reader, RecordBatchReader::Make({batch}, physical_schema)); + auto source = GetFileSource(reader.get()); + auto expected = TableFromJSON(dataset_schema, {test.expected}); + ASSERT_OK_AND_ASSIGN(auto control, format_->MakeFragment(*source)); + ASSERT_OK_AND_ASSIGN(auto expected_count, + control->CountRows(string_filter, options).result()); + if (batch->column(0)->null_count() == 0) { + ASSERT_EQ(expected_count, std::make_optional(0)); + } + + for (bool scan_strings_first : {true, false}) { + SCOPED_TRACE(scan_strings_first); + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + auto check_string_pruning = [&] { + // Preserve the physical-schema fast count, including its nullable limitation. + ASSERT_FINISHES_OK_AND_EQ(expected_count, + fragment->CountRows(string_filter, options)); + }; + if (scan_strings_first) check_string_pruning(); + + // Filtering must produce the same result when this fragment has cached statistics. + ScannerBuilder builder(dataset_schema, fragment, std::make_shared()); + ASSERT_OK(builder.Filter(timestamp_filter)); + ASSERT_OK_AND_ASSIGN(auto scanner, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto actual, scanner->ToTable()); + AssertTablesEqual(*expected, *actual, /*same_chunk_layout=*/false); + + if (!scan_strings_first) check_string_pruning(); + } + } +} + +TEST_F(TestParquetFileFormat, PredicatePushdownWithCastKeepsOtherColumnStatistics) { + auto physical_schema = schema({field("x", utf8()), field("y", int32())}); + auto dataset_schema = + schema({field("x", timestamp(TimeUnit::SECOND)), field("y", int32())}); + auto table = TableFromJSON( + physical_schema, {R"([["2009-01-01 12:00:00", 1], ["2009-01-03 12:00:00", 1]])", + R"([["2009-01-01 12:00:00", 2], ["2009-01-03 12:00:00", 2]])"}); + TableBatchReader reader(*table); + auto source = GetFileSource(&reader); + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + auto parquet_fragment = checked_pointer_cast(fragment); + ASSERT_OK(parquet_fragment->EnsureCompleteMetadata()); + ASSERT_EQ(parquet_fragment->metadata()->num_row_groups(), 2); + + // Cache both physical columns before scanning with a different type for x. + ASSERT_OK_AND_ASSIGN(auto warmup, and_(greater(field_ref("x"), literal("2009")), + less(field_ref("y"), literal(3))) + .Bind(*physical_schema)); + ASSERT_OK_AND_ASSIGN(auto warmup_groups, parquet_fragment->SplitByRowGroup(warmup)); + ASSERT_EQ(warmup_groups.size(), 2); + + auto filter = and_( + less_equal(field_ref("x"), literal(TimestampScalar(1230854400, TimeUnit::SECOND))), + equal(field_ref("y"), literal(1))); + ASSERT_OK_AND_ASSIGN(auto bound_filter, filter.Bind(*dataset_schema)); + ASSERT_OK_AND_ASSIGN(auto groups, parquet_fragment->SplitByRowGroup(bound_filter)); + ASSERT_EQ(groups.size(), 1); + EXPECT_EQ(checked_pointer_cast(groups[0])->row_groups(), + (std::vector{0})); + + ScannerBuilder builder(dataset_schema, fragment, std::make_shared()); + ASSERT_OK(builder.Filter(filter)); + ASSERT_OK_AND_ASSIGN(auto scanner, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto actual, scanner->ToTable()); + auto expected = TableFromJSON(dataset_schema, {R"([["2009-01-01 12:00:00", 1]])"}); + AssertTablesEqual(*expected, *actual, /*same_chunk_layout=*/false); +} + +TEST_F(TestParquetFileFormat, PredicatePushdownTimestampSchemaChange) { + struct Case { + std::shared_ptr physical; + std::shared_ptr logical; + const char* rows; + int64_t upper_bound; + const char* expected; + }; + for (const auto& test : + {Case{timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MILLI, "UTC"), + "[[1000], [2000]]", 1000, "[[1000]]"}, + Case{timestamp(TimeUnit::NANO), timestamp(TimeUnit::SECOND), + "[[1000000000], [2000000000]]", 32503680000LL, "[[1], [2]]"}}) { + SCOPED_TRACE(test.logical->ToString()); + auto physical_schema = schema({field("x", test.physical)}); + auto logical_schema = schema({field("x", test.logical)}); + auto batch = RecordBatchFromJSON(physical_schema, test.rows); + ASSERT_OK_AND_ASSIGN(auto reader, RecordBatchReader::Make({batch}, physical_schema)); + auto source = GetFileSource(reader.get()); + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + ScannerBuilder builder(logical_schema, fragment, std::make_shared()); + ASSERT_OK(builder.Filter(less_equal( + field_ref("x"), + literal(std::make_shared(test.upper_bound, test.logical))))); + ASSERT_OK_AND_ASSIGN(auto scanner, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto actual, scanner->ToTable()); + auto expected = TableFromJSON(logical_schema, {test.expected}); + AssertTablesEqual(*expected, *actual, /*same_chunk_layout=*/false); + } +} + +TEST_F(TestParquetFileFormat, PredicatePushdownWithLosslessCasts) { + struct Case { + std::shared_ptr physical; + std::shared_ptr logical; + const char* rows; + const char* cutoff; + const char* expected = nullptr; + }; + const char* numbers = "[[1], [2], [20], [21]]"; + const char* strings = R"([["a"], ["b"], ["x"], ["y"]])"; + for (const auto& test : + {Case{int32(), int64(), numbers, "[10]"}, + Case{uint32(), uint64(), numbers, "[10]"}, + Case{uint32(), int64(), numbers, "[10]"}, + Case{float32(), float64(), numbers, "[10]"}, + Case{int32(), float64(), numbers, "[10]"}, + Case{uint32(), float64(), numbers, "[10]"}, + Case{int16(), float32(), numbers, "[10]"}, + Case{uint16(), float32(), numbers, "[10]"}, + Case{large_utf8(), utf8(), strings, R"(["m"])"}, + Case{utf8(), large_utf8(), strings, R"(["m"])"}, + Case{large_binary(), binary(), strings, R"(["m"])"}, + Case{binary(), large_binary(), strings, R"(["m"])"}, + Case{fixed_size_binary(2), large_binary(), R"([["aa"], ["bb"], ["xx"], ["yy"]])", + R"(["mm"])"}, + Case{utf8(), binary(), strings, R"(["m"])"}, + Case{large_utf8(), large_binary(), strings, R"(["m"])"}, + Case{time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), numbers, "[10000]", + "[[1000], [2000]]"}, + Case{time32(TimeUnit::MILLI), time64(TimeUnit::NANO), numbers, "[10000000]", + "[[1000000], [2000000]]"}, + Case{time64(TimeUnit::MICRO), time64(TimeUnit::NANO), numbers, "[10000]", + "[[1000], [2000]]"}, + Case{time64(TimeUnit::NANO), time64(TimeUnit::MICRO), + "[[1000], [2000], [20000], [21000]]", "[10]", "[[1], [2]]"}, + Case{decimal128(10, 2), decimal128(12, 2), + R"([["1.00"], ["2.00"], ["20.00"], ["21.00"]])", R"(["10.00"])"}, + Case{timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO), numbers, "[10000]", + "[[1000], [2000]]"}, + Case{timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), numbers, "[10000]", + "[[1000], [2000]]"}, + Case{timestamp(TimeUnit::MICRO, "UTC"), timestamp(TimeUnit::NANO, "UTC"), numbers, + "[10000]", "[[1000], [2000]]"}, + Case{date32(), date64(), numbers, "[864000000]", "[[86400000], [172800000]]"}, + Case{date32(), timestamp(TimeUnit::SECOND), numbers, "[864000]", + "[[86400], [172800]]"}, + Case{date32(), timestamp(TimeUnit::MILLI), numbers, "[864000000]", + "[[86400000], [172800000]]"}}) { + SCOPED_TRACE(test.physical->ToString() + " -> " + test.logical->ToString()); + auto physical_schema = schema({field("x", test.physical)}); + auto logical_schema = schema({field("x", test.logical)}); + auto batch = RecordBatchFromJSON(physical_schema, test.rows); + auto table = + Table::FromRecordBatches({batch->Slice(0, 2), batch->Slice(2)}).ValueOrDie(); + TableBatchReader reader(*table); + ASSERT_OK_AND_ASSIGN( + auto source, + ParquetFormatHelper::Write( + &reader, ArrowWriterProperties::Builder().store_schema()->build()) + .As()); + ASSERT_OK_AND_ASSIGN(auto cutoff, + ArrayFromJSON(test.logical, test.cutoff)->GetScalar(0)); + auto expected = + TableFromJSON(logical_schema, {test.expected ? test.expected : test.rows}) + ->Slice(0, 2); + for (bool by_index : {false, true}) { + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(source)); + ASSERT_OK_AND_ASSIGN(auto actual_schema, fragment->ReadPhysicalSchema()); + AssertSchemaEqual(*physical_schema, *actual_schema); + auto parquet_fragment = checked_pointer_cast(fragment); + for (int reuse = 0; reuse < 2; ++reuse) { + SCOPED_TRACE(reuse); + SCOPED_TRACE(by_index); + auto filter = + less(field_ref(by_index ? FieldRef(0) : FieldRef("x")), literal(cutoff)); + ASSERT_OK_AND_ASSIGN(auto bound, filter.Bind(*logical_schema)); + ASSERT_OK_AND_ASSIGN(auto groups, parquet_fragment->SplitByRowGroup(bound)); + ASSERT_EQ(groups.size(), 1); + EXPECT_EQ(checked_pointer_cast(groups[0])->row_groups(), + (std::vector{0})); + auto options = std::make_shared(); + options->dataset_schema = logical_schema; + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(2), + fragment->CountRows(bound, options)); + ScannerBuilder builder(logical_schema, fragment, options); + ASSERT_OK(builder.Filter(filter)); + ASSERT_OK_AND_ASSIGN(auto scanner, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto actual, scanner->ToTable()); + AssertTablesEqual(*expected, *actual, /*same_chunk_layout=*/false); + } + } + } +} + +TEST_F(TestParquetFileFormat, CastStatisticsPreserveNulls) { + auto physical = schema({field("x", utf8())}); + auto logical = schema({field("x", timestamp(TimeUnit::SECOND))}); + auto table = TableFromJSON( + physical, + {R"([[null], [null]])", R"([["2009-01-01"], ["2009-01-03"], ["2009-01-04"]])"}); + TableBatchReader reader(*table); + auto source = GetFileSource(&reader); + auto options = std::make_shared(); + options->dataset_schema = logical; + for (bool physical_first : {false, true}) { + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + auto parquet = checked_pointer_cast(fragment); + ASSERT_OK_AND_ASSIGN(auto warmup, + less(field_ref("x"), literal("2010")).Bind(*physical)); + if (physical_first) { + ASSERT_OK(parquet->SplitByRowGroup(warmup)); + } + for (bool nulls : {true, false}) { + auto filter = nulls ? is_null(field_ref("x")) : is_valid(field_ref("x")); + ASSERT_OK_AND_ASSIGN(auto bound, filter.Bind(*logical)); + ASSERT_OK_AND_ASSIGN(auto groups, parquet->SplitByRowGroup(bound)); + ASSERT_EQ(groups.size(), 1); + EXPECT_EQ(checked_pointer_cast(groups[0])->row_groups(), + (std::vector{nulls ? 0 : 1})); + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(nulls ? 2 : 3), + fragment->CountRows(bound, options)); + ScannerBuilder builder(logical, fragment, options); + ASSERT_OK(builder.Filter(filter)); + ASSERT_OK_AND_ASSIGN(auto scanner, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto actual, scanner->ToTable()); + EXPECT_EQ(actual->num_rows(), nulls ? 2 : 3); + } + ASSERT_OK_AND_ASSIGN(auto groups, parquet->SplitByRowGroup(warmup)); + ASSERT_EQ(groups.size(), 1); + EXPECT_EQ(checked_pointer_cast(groups[0])->row_groups(), + (std::vector{1})); + } +} + +TEST_F(TestParquetFileFormat, CastStatisticsPreserveNaNOptions) { + auto physical = schema({field("x", utf8())}); + auto logical = schema({field("x", float64())}); + auto table = TableFromJSON(physical, {R"([["NaN"], ["NaN"]])", R"([["1"], ["1"]])"}); + TableBatchReader reader(*table); + auto source = GetFileSource(&reader); + for (bool nan_is_null : {false, true}) { + for (bool negate : {false, true}) { + auto filter = is_null(field_ref("x"), nan_is_null); + if (negate) filter = compute::not_(filter); + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + auto parquet = checked_pointer_cast(fragment); + auto options = std::make_shared(); + options->dataset_schema = logical; + ASSERT_OK_AND_ASSIGN(auto bound, filter.Bind(*logical)); + ASSERT_OK_AND_ASSIGN(auto groups, parquet->SplitByRowGroup(bound)); + EXPECT_EQ(groups.size(), nan_is_null || negate ? 2 : 0); + auto expected_fast = nan_is_null ? std::optional{} + : std::make_optional(negate ? 4 : 0); + ASSERT_FINISHES_OK_AND_EQ(expected_fast, fragment->CountRows(bound, options)); + ScannerBuilder builder(logical, fragment, options); + ASSERT_OK(builder.Filter(filter)); + ASSERT_OK_AND_ASSIGN(auto scanner, builder.Finish()); + int64_t expected = nan_is_null ? 2 : (negate ? 4 : 0); + ASSERT_OK_AND_ASSIGN(auto count, scanner->CountRows()); + EXPECT_EQ(count, expected); + ASSERT_OK_AND_ASSIGN(auto actual, scanner->ToTable()); + EXPECT_EQ(actual->num_rows(), expected); + } + } +} + +TEST_F(TestParquetFileFormat, CastStatisticsWithZeroArgumentCall) { + auto physical = schema({field("x", utf8())}); + auto logical = schema({field("x", float64())}); + auto table = TableFromJSON(physical, {R"([["1"], ["2"]])"}); + TableBatchReader reader(*table); + auto source = GetFileSource(&reader); + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + auto filter = + and_(is_valid(field_ref("x")), + less(compute::call("random", {}, compute::RandomOptions::FromSeed(7)), + literal(2.0))); + auto options = std::make_shared(); + options->dataset_schema = logical; + ASSERT_OK_AND_ASSIGN(auto bound, filter.Bind(*logical)); + ASSERT_FINISHES_OK_AND_EQ(std::optional{}, + fragment->CountRows(bound, options)); + ScannerBuilder builder(logical, fragment, options); + ASSERT_OK(builder.Filter(filter)); + ASSERT_OK_AND_ASSIGN(auto scanner, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto actual, scanner->ToTable()); + EXPECT_EQ(actual->num_rows(), 2); +} + +TEST_F(TestParquetFileFormat, PredicatePushdownWithFloatNarrowing) { + auto physical = schema({field("x", float64())}); + auto logical = schema({field("x", float32())}); + auto table = + TableFromJSON(physical, {"[[0.5], [0.75]]", "[[1.0000000001], [1.0000000002]]"}); + TableBatchReader reader(*table); + auto source = GetFileSource(&reader); + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + ScannerBuilder builder(logical, fragment, std::make_shared()); + // Both values in the second row group round to the inclusive filter boundary. + ASSERT_OK(builder.Filter(less_equal(field_ref("x"), literal(1.0F)))); + ASSERT_OK_AND_ASSIGN(auto scanner, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto count, scanner->CountRows()); + EXPECT_EQ(count, 4); + ASSERT_OK_AND_ASSIGN(auto actual, scanner->ToTable()); + auto expected = TableFromJSON(logical, {"[[0.5], [0.75], [1.0], [1.0]]"}); + AssertTablesEqual(*expected, *actual, /*same_chunk_layout=*/false); +} + +TEST_F(TestParquetFileFormat, CastStatisticsConservativeFallback) { + for (const auto& types : + {std::make_pair(int32(), int16()), std::make_pair(int32(), uint64()), + std::make_pair(int64(), float64()), std::make_pair(float64(), float32()), + std::make_pair(date32(), timestamp(TimeUnit::MICRO)), + std::make_pair(time64(TimeUnit::MICRO), time32(TimeUnit::MILLI))}) { + SCOPED_TRACE(types.first->ToString() + " -> " + types.second->ToString()); + auto physical = schema({field("x", types.first)}); + auto logical = schema({field("x", types.second)}); + auto table = TableFromJSON(physical, {"[[1], [2]]", "[[20], [21]]"}); + TableBatchReader reader(*table); + auto source = GetFileSource(&reader); + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + auto parquet = checked_pointer_cast(fragment); + ASSERT_OK_AND_ASSIGN(auto cutoff, ArrayFromJSON(types.second, "[10]")->GetScalar(0)); + ASSERT_OK_AND_ASSIGN(auto bound, + less(field_ref("x"), literal(cutoff)).Bind(*logical)); + ASSERT_OK_AND_ASSIGN(auto groups, parquet->SplitByRowGroup(bound)); + ASSERT_EQ(groups.size(), 2); + auto options = std::make_shared(); + options->dataset_schema = logical; + ASSERT_FINISHES_OK_AND_EQ(std::optional{}, + fragment->CountRows(bound, options)); + } +} + +TEST_F(TestParquetFileFormat, MissingColumnStatistics) { + auto physical = schema({field("x", int32()), field("y", int32())}); + auto table = TableFromJSON(physical, {"[[1, 1], [2, 2]]", "[[20, 20], [21, 21]]"}); + auto sink = CreateOutputStream(default_memory_pool()); + auto properties = WriterProperties::Builder().disable_statistics("x")->build(); + ASSERT_OK(WriteTable(*table, default_memory_pool(), sink, 2, properties)); + ASSERT_OK_AND_ASSIGN(auto buffer, sink->Finish()); + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(FileSource(buffer))); + auto parquet = checked_pointer_cast(fragment); + auto options = std::make_shared(); + options->dataset_schema = physical; + ASSERT_OK_AND_ASSIGN(auto x, less(field_ref("x"), literal(10)).Bind(*physical)); + ASSERT_OK_AND_ASSIGN(auto y, less(field_ref("y"), literal(10)).Bind(*physical)); + for (int reuse = 0; reuse < 2; ++reuse) { + ASSERT_OK_AND_ASSIGN(auto groups, parquet->SplitByRowGroup(x)); + EXPECT_EQ(groups.size(), 2); + ASSERT_FINISHES_OK_AND_EQ(std::optional{}, fragment->CountRows(x, options)); + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(2), + fragment->CountRows(y, options)); + } +} + +TEST_F(TestParquetFileFormat, ClearCachedMetadataClearsStatistics) { + auto mock_fs = std::make_shared(fs::kNoTime); + auto physical_schema = schema({field("x", int32())}); + auto write_file = [&](const char* rows) -> Status { + auto batch = RecordBatchFromJSON(physical_schema, rows); + ARROW_ASSIGN_OR_RAISE(auto reader, RecordBatchReader::Make({batch}, physical_schema)); + ARROW_ASSIGN_OR_RAISE(auto buffer, ParquetFormatHelper::Write(reader.get())); + ARROW_ASSIGN_OR_RAISE(auto output, mock_fs->OpenOutputStream("/cached.parquet")); + RETURN_NOT_OK(output->Write(buffer)); + return output->Close(); + }; + ASSERT_OK(write_file("[[1], [2]]")); + ASSERT_OK_AND_ASSIGN(auto fragment, + format_->MakeFragment(FileSource("/cached.parquet", mock_fs))); + ASSERT_OK_AND_ASSIGN(auto predicate, + greater(field_ref("x"), literal(8)).Bind(*physical_schema)); + auto options = std::make_shared(); + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(0), + fragment->CountRows(predicate, options)); + ASSERT_OK(fragment->ClearCachedMetadata()); + ASSERT_OK(write_file("[[10], [20]]")); + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(2), + fragment->CountRows(predicate, options)); + ASSERT_OK_AND_ASSIGN(auto fresh, + format_->MakeFragment(FileSource("/cached.parquet", mock_fs))); + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(2), + fresh->CountRows(predicate, options)); +} + TEST_F(TestParquetFileFormat, CountRowsPredicatePushdown) { constexpr int64_t kNumRowGroups = 16; constexpr int64_t kTotalNumRows = kNumRowGroups * (kNumRowGroups + 1) / 2; @@ -375,6 +785,229 @@ TEST_F(TestParquetFileFormat, CountRowsPredicatePushdown) { } } +TEST_F(TestParquetFileFormat, PredicatePushdownWithReorderedSchemaAndFieldIndex) { + auto time_type = timestamp(TimeUnit::MILLI); + auto physical_schema = schema({field("other", int32()), field("x", time_type)}); + auto logical_schema = schema({field("x", time_type), field("other", int32())}); + auto batch = RecordBatchFromJSON(physical_schema, "[[3000, 1000], [4000, 2000]]"); + ASSERT_OK_AND_ASSIGN(auto reader, RecordBatchReader::Make({batch}, physical_schema)); + auto source = GetFileSource(reader.get()); + auto expected = TableFromJSON(logical_schema, {"[[1000, 3000]]"}); + for (bool index_first : {false, true}) { + SCOPED_TRACE(index_first); + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + for (bool by_index : {index_first, !index_first}) { + SCOPED_TRACE(by_index); + auto ref = by_index ? FieldRef(0) : FieldRef("x"); + ScannerBuilder builder(logical_schema, fragment, std::make_shared()); + ASSERT_OK(builder.Filter(less_equal( + field_ref(ref), literal(std::make_shared(1000, time_type))))); + ASSERT_OK_AND_ASSIGN(auto scanner, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto actual, scanner->ToTable()); + AssertTablesEqual(*expected, *actual, /*same_chunk_layout=*/false); + } + } +} + +TEST_F(TestParquetFileFormat, PredicatePushdownWithReorderedIntegerFields) { + auto physical_schema = schema({field("other", int32()), field("x", int32())}); + auto logical_schema = schema({field("x", int32()), field("other", int32())}); + auto table = TableFromJSON(physical_schema, + {"[[100, 1], [100, 2], [100, 3]]", "[[0, 20], [0, 21]]"}); + TableBatchReader reader(*table); + auto source = GetFileSource(&reader); + auto expected = TableFromJSON(logical_schema, {"[[1, 100], [2, 100], [3, 100]]"}); + for (bool index_first : {false, true}) { + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + for (bool by_index : {index_first, !index_first}) { + auto options = std::make_shared(); + options->dataset_schema = logical_schema; + auto filter = less(field_ref(by_index ? FieldRef(0) : FieldRef("x")), literal(10)); + ASSERT_OK_AND_ASSIGN(auto bound, filter.Bind(*logical_schema)); + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(3), + fragment->CountRows(bound, options)); + ScannerBuilder builder(logical_schema, fragment, options); + ASSERT_OK(builder.Filter(filter)); + ASSERT_OK_AND_ASSIGN(auto scanner, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto actual, scanner->ToTable()); + AssertTablesEqual(*expected, *actual, /*same_chunk_layout=*/false); + } + } +} + +TEST_F(TestParquetFileFormat, AmbiguousFieldReferenceDoesNotCacheStatistics) { + auto physical_schema = schema({field("x", int32()), field("other", int32())}); + auto ambiguous_schema = schema({field("x", int32()), field("x", int32())}); + auto table = + TableFromJSON(physical_schema, {"[[1, 100], [2, 100]]", "[[20, 0], [21, 0]]"}); + TableBatchReader reader(*table); + auto source = GetFileSource(&reader); + ASSERT_OK_AND_ASSIGN(auto named, + less(field_ref("x"), literal(10)).Bind(*physical_schema)); + ASSERT_OK_AND_ASSIGN(auto positional, + less(field_ref(0), literal(10)).Bind(*ambiguous_schema)); + auto named_options = std::make_shared(); + named_options->dataset_schema = physical_schema; + auto ambiguous_options = std::make_shared(); + ambiguous_options->dataset_schema = ambiguous_schema; + for (bool ambiguous_first : {false, true}) { + SCOPED_TRACE(ambiguous_first); + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + if (!ambiguous_first) { + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(2), + fragment->CountRows(named, named_options)); + } + ASSERT_FINISHES_OK_AND_EQ(std::optional{}, + fragment->CountRows(positional, ambiguous_options)); + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(2), + fragment->CountRows(named, named_options)); + } +} + +TEST_F(TestParquetFileFormat, MissingStatisticsFieldReference) { + auto physical_schema = schema({field("x", int32())}); + auto table = TableFromJSON(physical_schema, {"[[1], [2]]", "[[20], [21]]"}); + TableBatchReader reader(*table); + auto source = GetFileSource(&reader); + for (bool nested : {false, true}) { + auto extra_type = nested ? struct_({field("value", int32())}) : int32(); + auto bound_schema = schema({field("x", int32()), field("extra", extra_type)}); + auto ref = nested ? FieldRef(1, 0) : FieldRef(1); + ASSERT_OK_AND_ASSIGN(auto predicate, + less(field_ref(ref), literal(10)).Bind(*bound_schema)); + auto options = std::make_shared(); + options->dataset_schema = physical_schema; + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + ASSERT_FINISHES_OK_AND_EQ(std::optional{}, + fragment->CountRows(predicate, options)); + ASSERT_OK_AND_ASSIGN(auto named, + less(field_ref("x"), literal(10)).Bind(*physical_schema)); + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(2), + fragment->CountRows(named, options)); + } +} + +TEST_F(TestParquetFileFormat, PartitionPruningWithFieldIndices) { + auto physical = schema({field("y", int32())}); + auto logical = schema({field("y", int32()), field("part", int32())}); + auto table = TableFromJSON(physical, {"[[1], [2]]", "[[3], [4], [5]]"}); + TableBatchReader reader(*table); + auto source = GetFileSource(&reader); + for (bool partition_by_index : {false, true}) { + auto partition = + equal(field_ref(partition_by_index ? FieldRef(1) : FieldRef("part")), literal(1)); + for (bool filter_by_index : {false, true}) { + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source, partition)); + auto parquet = checked_pointer_cast(fragment); + auto filter = + equal(field_ref(filter_by_index ? FieldRef(1) : FieldRef("part")), literal(2)); + ASSERT_OK_AND_ASSIGN(auto bound, filter.Bind(*logical)); + auto options = std::make_shared(); + options->dataset_schema = logical; + // Count first: this used to index an empty vector after canonicalization. + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(0), + fragment->CountRows(bound, options)); + ASSERT_OK_AND_ASSIGN(auto groups, parquet->SplitByRowGroup(bound, logical.get())); + EXPECT_TRUE(groups.empty()); + ASSERT_OK_AND_ASSIGN(auto subset, parquet->Subset(bound, logical.get())); + EXPECT_TRUE( + checked_pointer_cast(subset)->row_groups().empty()); + ScannerBuilder builder(logical, fragment, options); + ASSERT_OK(builder.Filter(filter)); + ASSERT_OK_AND_ASSIGN(auto scanner, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto actual, scanner->ToTable()); + EXPECT_EQ(actual->num_rows(), 0); + } + } +} + +TEST_F(TestParquetFileFormat, DuplicatePhysicalParentNamesSkipStatistics) { + auto physical = + schema({field("s", struct_({field("u", int32())})), + field("s", struct_({field("x", int32())})), field("y", int32())}); + auto logical = + schema({field("s", struct_({field("x", int32())})), field("y", int32())}); + auto table = + TableFromJSON(physical, {R"([[{"u":null},{"x":1},1],[{"u":null},{"x":2},1]])", + R"([[{"u":null},{"x":3},2]])"}); + TableBatchReader reader(*table); + auto source = GetFileSource(&reader); + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + auto parquet = checked_pointer_cast(fragment); + auto options = std::make_shared(); + options->dataset_schema = logical; + for (bool nulls : {true, false}) { + auto x = field_ref(FieldRef(0, 0)); + auto filter = nulls ? is_null(x) : is_valid(x); + ASSERT_OK_AND_ASSIGN(auto bound, filter.Bind(*logical)); + ASSERT_OK_AND_ASSIGN(auto groups, parquet->SplitByRowGroup(bound, logical.get())); + EXPECT_EQ(groups.size(), 2); + ASSERT_OK_AND_ASSIGN(auto subset, parquet->Subset(bound, logical.get())); + EXPECT_EQ(checked_pointer_cast(subset)->row_groups(), + (std::vector{0, 1})); + ASSERT_FINISHES_OK_AND_EQ(std::optional{}, + fragment->CountRows(bound, options)); + ScannerBuilder builder(logical, fragment, options); + ASSERT_OK(builder.Filter(filter)); + ASSERT_OK_AND_ASSIGN(auto scanner, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto count, scanner->CountRows()); + EXPECT_EQ(count, nulls ? 3 : 0); + ASSERT_OK_AND_ASSIGN(auto actual, scanner->ToTable()); + EXPECT_EQ(actual->num_rows(), nulls ? 3 : 0); + } + ASSERT_OK_AND_ASSIGN(auto y, less(field_ref("y"), literal(2)).Bind(*logical)); + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(2), + fragment->CountRows(y, options)); +} + +TEST_F(TestParquetFileFormat, DuplicatePhysicalNamesSkipStatistics) { + auto physical = schema({field("x", int32()), field("x", int32()), field("y", int32())}); + auto logical = schema({field("x", int32()), field("y", int32())}); + auto table = TableFromJSON( + physical, {"[[1, 1, 1], [2, 2, 2]]", "[[20, 20, 20], [21, 21, 21], [22, 22, 22]]"}); + TableBatchReader reader(*table); + auto source = GetFileSource(&reader); + auto options = std::make_shared(); + options->dataset_schema = logical; + ASSERT_OK_AND_ASSIGN(auto x, less(field_ref(0), literal(10)).Bind(*logical)); + ASSERT_OK_AND_ASSIGN(auto y, less(field_ref("y"), literal(10)).Bind(*logical)); + for (bool unique_first : {false, true}) { + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + auto parquet = checked_pointer_cast(fragment); + if (unique_first) { + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(2), + fragment->CountRows(y, options)); + } + ASSERT_FINISHES_OK_AND_EQ(std::optional{}, fragment->CountRows(x, options)); + ASSERT_OK_AND_ASSIGN(auto groups, parquet->SplitByRowGroup(x, logical.get())); + EXPECT_EQ(groups.size(), 2); + ASSERT_OK_AND_ASSIGN(auto subset, parquet->Subset(x, logical.get())); + EXPECT_EQ(checked_pointer_cast(subset)->row_groups(), + (std::vector{0, 1})); + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(2), + fragment->CountRows(y, options)); + ScannerBuilder builder(logical, fragment, options); + ASSERT_OK(builder.Filter(less(field_ref(0), literal(10)))); + ASSERT_OK_AND_ASSIGN(auto scanner, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto actual, scanner->ToTable()); + auto expected = TableFromJSON(logical, {"[[1, 1], [2, 2]]"}); + AssertTablesEqual(*expected, *actual, false); + } +} + +TEST_F(TestParquetFileFormat, UnboundPredicateWithSchema) { + auto physical = schema({field("x", int32())}); + auto table = TableFromJSON(physical, {"[[1], [2]]"}); + TableBatchReader reader(*table); + auto source = GetFileSource(&reader); + ASSERT_OK_AND_ASSIGN(auto fragment, format_->MakeFragment(*source)); + auto parquet = checked_pointer_cast(fragment); + ASSERT_RAISES( + Invalid, parquet->SplitByRowGroup(less(field_ref(0), literal(10)), physical.get())); + ASSERT_RAISES(Invalid, + parquet->Subset(less(field_ref("x"), literal(10)), physical.get())); +} + TEST_F(TestParquetFileFormat, CachedMetadata) { // Create a test file auto mock_fs = std::make_shared(fs::kNoTime); diff --git a/python/pyarrow/_dataset_parquet.pyx b/python/pyarrow/_dataset_parquet.pyx index 3dcc782eaff..f3651b44f06 100644 --- a/python/pyarrow/_dataset_parquet.pyx +++ b/python/pyarrow/_dataset_parquet.pyx @@ -438,7 +438,8 @@ cdef class ParquetFileFragment(FileFragment): c_filter = _bind(filter, schema) with nogil: c_fragments = move(GetResultValue( - self.parquet_file_fragment.SplitByRowGroup(move(c_filter)))) + self.parquet_file_fragment.SplitByRowGroup( + move(c_filter), schema.sp_schema.get()))) return [Fragment.wrap(c_fragment) for c_fragment in c_fragments] @@ -483,7 +484,7 @@ cdef class ParquetFileFragment(FileFragment): with nogil: c_fragment = move(GetResultValue( self.parquet_file_fragment.SubsetWithFilter( - move(c_filter)))) + move(c_filter), schema.sp_schema.get()))) elif row_group_ids is not None: c_row_group_ids = [ row_group for row_group in sorted(set(row_group_ids)) diff --git a/python/pyarrow/includes/libarrow_dataset_parquet.pxd b/python/pyarrow/includes/libarrow_dataset_parquet.pxd index 8f4917f6c0c..60a34a824ca 100644 --- a/python/pyarrow/includes/libarrow_dataset_parquet.pxd +++ b/python/pyarrow/includes/libarrow_dataset_parquet.pxd @@ -53,8 +53,12 @@ cdef extern from "arrow/dataset/api.h" namespace "arrow::dataset" nogil: shared_ptr[CFileMetaData] metadata() const CResult[vector[shared_ptr[CFragment]]] SplitByRowGroup( CExpression predicate) + CResult[vector[shared_ptr[CFragment]]] SplitByRowGroup( + CExpression predicate, const CSchema* dataset_schema) CResult[shared_ptr[CFragment]] SubsetWithFilter "Subset"( CExpression predicate) + CResult[shared_ptr[CFragment]] SubsetWithFilter "Subset"( + CExpression predicate, const CSchema* dataset_schema) CResult[shared_ptr[CFragment]] SubsetWithIds "Subset"( vector[int] row_group_ids) CStatus EnsureCompleteMetadata() diff --git a/python/pyarrow/tests/test_dataset.py b/python/pyarrow/tests/test_dataset.py index 2ef4c0f2284..30902092b8f 100644 --- a/python/pyarrow/tests/test_dataset.py +++ b/python/pyarrow/tests/test_dataset.py @@ -1789,6 +1789,217 @@ def test_fragments_parquet_row_groups_predicate(tempdir): assert len(row_group_fragments) == 0 +@pytest.mark.parquet +@pytest.mark.parametrize("physical_first", [False, True]) +@pytest.mark.parametrize("nulls", [False, True]) +def test_parquet_cast_null_statistics(physical_first, nulls): + import io + + class TrackedBuffer(io.BytesIO): + bytes_read = 0 + + def read(self, size=-1): + result = super().read(size) + self.bytes_read += len(result) + return result + + table = pa.table({"x": [None, None, "2009-01-01", "2009-01-03", "2009-01-04"]}) + sink = pa.BufferOutputStream() + pq.write_table(table, sink, row_group_size=2, compression=None) + stream = TrackedBuffer(sink.getvalue().to_pybytes()) + fragment = ds.ParquetFileFormat().make_fragment(pa.PythonFile(stream, mode="r")) + fragment.ensure_complete_metadata() + if physical_first: + assert [f.row_groups[0].id for f in fragment.split_by_row_group( + ds.field("x") < "2010")] == [1, 2] + schema = pa.schema([("x", pa.timestamp("s"))]) + expression = ds.field("x").is_null() if nulls else ds.field("x").is_valid() + expected_groups = [0] if nulls else [1, 2] + assert [f.row_groups[0].id for f in fragment.split_by_row_group( + expression, schema=schema)] == expected_groups + scanner = ds.Scanner.from_fragment(fragment, schema=schema, filter=expression) + before = stream.bytes_read + assert scanner.count_rows() == (2 if nulls else 3) + assert stream.bytes_read == before + assert scanner.to_table().num_rows == (2 if nulls else 3) + assert [f.row_groups[0].id for f in fragment.split_by_row_group( + ds.field("x") < "2010")] == [1, 2] + + +@pytest.mark.parquet +@pytest.mark.parametrize("nan_is_null", [False, True]) +@pytest.mark.parametrize("negate", [False, True]) +@pytest.mark.parametrize("ref", ["x", 0]) +def test_parquet_cast_null_options(nan_is_null, negate, ref): + table = pa.table({"x": ["NaN", "NaN", "1", "1"]}) + sink = pa.BufferOutputStream() + pq.write_table(table, sink, row_group_size=2, compression=None) + fragment = ds.ParquetFileFormat().make_fragment( + pa.BufferReader(sink.getvalue())) + schema = pa.schema([("x", pa.float64())]) + expression = ds.field(ref).is_null(nan_is_null=nan_is_null) + if negate: + expression = ~expression + expected_rows = 2 if nan_is_null else (4 if negate else 0) + expected_groups = [0, 1] if nan_is_null or negate else [] + for _ in range(2): + assert [g.id for f in fragment.split_by_row_group( + expression, schema=schema) for g in f.row_groups] == expected_groups + assert [g.id for g in fragment.subset( + filter=expression, schema=schema).row_groups] == expected_groups + scanner = ds.Scanner.from_fragment( + fragment, schema=schema, filter=expression) + assert scanner.count_rows() == expected_rows + actual = scanner.to_table() + expected = fragment.to_table(schema=schema).filter(expression) + assert actual.num_rows == expected_rows + assert actual.column("x").is_null(nan_is_null=True).to_pylist() == ( + expected.column("x").is_null(nan_is_null=True).to_pylist()) + + +@pytest.mark.parquet +@pytest.mark.parametrize("method", ["split_by_row_group", "subset"]) +@pytest.mark.parametrize("nested", [False, True]) +def test_parquet_fragment_reordered_filter_schema(method, nested): + values = pa.array([1, 2, 20, 21], type=pa.int32()) + if nested: + column = pa.StructArray.from_arrays([values], names=["x"]) + name, named, positional, physical_ref = ( + "info", ds.field("info", "x"), ds.field(0, 0), ds.field(1, 0)) + else: + column = values + name, named, positional, physical_ref = ( + "x", ds.field("x"), ds.field(0), ds.field(1)) + table = pa.table({ + "other": pa.array([100, 100, 0, 0], type=pa.int32()), + name: column, + }) + logical = pa.schema([table.schema.field(name), table.schema.field("other")]) + sink = pa.BufferOutputStream() + pq.write_table(table, sink, row_group_size=2, compression=None) + data = sink.getvalue() + + def selected(fragment, expression, schema=None): + result = getattr(fragment, method)(filter=expression < 10, schema=schema) + fragments = result if isinstance(result, list) else [result] + return [group.id for part in fragments for group in part.row_groups] + + for refs in [(named, positional), (positional, named)]: + fragment = ds.ParquetFileFormat().make_fragment(pa.BufferReader(data)) + for ref in refs: + assert selected(fragment, ref, logical) == [0] + fragment = ds.ParquetFileFormat().make_fragment(pa.BufferReader(data)) + assert selected(fragment, physical_ref) == [0] + fragment = ds.ParquetFileFormat().make_fragment(pa.BufferReader(data)) + assert selected(fragment, ds.field(0)) == [1] + + +@pytest.mark.parquet +@pytest.mark.parametrize("partition_ref", ["part", 1]) +@pytest.mark.parametrize("filter_ref", ["part", 1]) +def test_parquet_partition_pruning_field_refs(partition_ref, filter_ref): + table = pa.table({"y": [1, 2, 3, 4, 5]}) + sink = pa.BufferOutputStream() + pq.write_table(table, sink, row_group_size=2, compression=None) + fragment = ds.ParquetFileFormat().make_fragment( + pa.BufferReader(sink.getvalue()), + partition_expression=ds.field(partition_ref) == 1) + schema = pa.schema([("y", pa.int64()), ("part", pa.int64())]) + expression = ds.field(filter_ref) == 2 + scanner = ds.Scanner.from_fragment(fragment, schema=schema, filter=expression) + assert scanner.count_rows() == 0 + assert scanner.to_table().num_rows == 0 + assert fragment.split_by_row_group(expression, schema=schema) == [] + assert fragment.subset(filter=expression, schema=schema).row_groups == [] + + +@pytest.mark.parquet +@pytest.mark.parametrize("unique_first", [False, True]) +@pytest.mark.parametrize("ref", ["x", 0]) +def test_parquet_duplicate_physical_names(unique_first, ref): + values = pa.array([1, 2, 20, 21, 22], type=pa.int32()) + table = pa.Table.from_arrays([values, values, values], names=["x", "x", "y"]) + sink = pa.BufferOutputStream() + pq.write_table(table, sink, row_group_size=2, compression=None) + fragment = ds.ParquetFileFormat().make_fragment(pa.BufferReader(sink.getvalue())) + schema = pa.schema([("x", pa.int32()), ("y", pa.int32())]) + if unique_first: + assert [f.row_groups[0].id for f in fragment.split_by_row_group( + ds.field("y") < 10, schema=schema)] == [0] + expression = ds.field(ref) < 10 + assert [f.row_groups[0].id for f in fragment.split_by_row_group( + expression, schema=schema)] == [0, 1, 2] + assert [r.id for r in fragment.subset( + filter=expression, schema=schema).row_groups] == [0, 1, 2] + scanner = ds.Scanner.from_fragment(fragment, schema=schema, filter=expression) + assert scanner.count_rows() == 2 + assert scanner.to_table().to_pydict() == {"x": [1, 2], "y": [1, 2]} + assert [f.row_groups[0].id for f in fragment.split_by_row_group( + ds.field("y") < 10, schema=schema)] == [0] + + +@pytest.mark.parquet +@pytest.mark.parametrize("nested", [False, True]) +@pytest.mark.parametrize("nulls", [False, True]) +def test_parquet_duplicate_parent_statistics(nested, nulls): + first = pa.array([{"u": None}] * 3, type=pa.struct([("u", pa.int32())])) + second = pa.array([{"x": 1}, {"x": 2}, {"x": 3}], + type=pa.struct([("x", pa.int32())])) + if nested: + column = pa.StructArray.from_arrays([first, second], names=["d", "d"]) + table = pa.table({"s": column, "y": [1, 1, 2]}) + schema = pa.schema([ + ("s", pa.struct([("d", pa.struct([("x", pa.int32())]))])), + ("y", pa.int64()), + ]) + ref = ds.field(0, 0, 0) + else: + table = pa.Table.from_arrays( + [first, second, pa.array([1, 1, 2])], names=["s", "s", "y"]) + schema = pa.schema([ + ("s", pa.struct([("x", pa.int32())])), ("y", pa.int64())]) + ref = ds.field(0, 0) + sink = pa.BufferOutputStream() + pq.write_table(table, sink, row_group_size=2, compression=None) + fragment = ds.ParquetFileFormat().make_fragment( + pa.BufferReader(sink.getvalue())) + expression = ref.is_null() if nulls else ref.is_valid() + for _ in range(2): + assert [g.id for f in fragment.split_by_row_group( + expression, schema=schema) for g in f.row_groups] == [0, 1] + assert [g.id for g in fragment.subset( + filter=expression, schema=schema).row_groups] == [0, 1] + assert [g.id for f in fragment.split_by_row_group( + ds.field("y") < 2, schema=schema) for g in f.row_groups] == [0] + if not nested: + scanner = ds.Scanner.from_fragment( + fragment, schema=schema, filter=expression) + assert scanner.count_rows() == (3 if nulls else 0) + assert scanner.to_table().num_rows == (3 if nulls else 0) + + +@pytest.mark.parquet +def test_parquet_reordered_cast_statistics_both_fixes(): + ts = pa.timestamp("ms") + dates = [datetime.datetime(2009, 1, day) for day in [10, 10, 10, 1, 1, 1]] + table = pa.table({ + "other": pa.array(dates, type=ts), + "x": [f"2009-01-{day:02d}" for day in [1, 2, 3, 4, 20, 21]], + }) + sink = pa.BufferOutputStream() + pq.write_table(table, sink, row_group_size=2, compression=None) + schema = pa.schema([("x", ts), ("other", ts)]) + for ref in ["x", 0]: + fragment = ds.ParquetFileFormat().make_fragment( + pa.BufferReader(sink.getvalue())) + scanner = ds.Scanner.from_fragment( + fragment, schema=schema, + filter=ds.field(ref) < pa.scalar(datetime.datetime(2009, 1, 5), type=ts)) + assert scanner.count_rows() == 4 + assert scanner.to_table().column("x").to_pylist() == [ + datetime.datetime(2009, 1, day) for day in [1, 2, 3, 4]] + + @pytest.mark.parquet def test_fragments_parquet_row_groups_reconstruct(tempdir, dataset_reader, pickle_module):