diff --git a/src/iceberg/delete_file_index.cc b/src/iceberg/delete_file_index.cc index 0f6044027..bbf5a747c 100644 --- a/src/iceberg/delete_file_index.cc +++ b/src/iceberg/delete_file_index.cc @@ -39,6 +39,7 @@ #include "iceberg/util/cache_internal.h" #include "iceberg/util/checked_cast.h" #include "iceberg/util/content_file_util.h" +#include "iceberg/util/conversions_internal.h" #include "iceberg/util/executor_util_internal.h" #include "iceberg/util/macros.h" @@ -104,17 +105,19 @@ Status EqualityDeleteFile::ConvertBoundsIfNeeded() const { // Convert lower bound if (auto it = wrapped.data_file->lower_bounds.find(field_id); it != wrapped.data_file->lower_bounds.cend() && !it->second.empty()) { - ICEBERG_ASSIGN_OR_RAISE(auto lower, - Literal::Deserialize(it->second, primitive_type)); - lower_bounds.emplace(field_id, std::move(lower)); + ICEBERG_ASSIGN_OR_RAISE(auto lower, DeserializeBound(it->second, primitive_type)); + if (lower) { + lower_bounds.emplace(field_id, std::move(*lower)); + } } // Convert upper bound if (auto it = wrapped.data_file->upper_bounds.find(field_id); it != wrapped.data_file->upper_bounds.cend() && !it->second.empty()) { - ICEBERG_ASSIGN_OR_RAISE(auto upper, - Literal::Deserialize(it->second, primitive_type)); - upper_bounds.emplace(field_id, std::move(upper)); + ICEBERG_ASSIGN_OR_RAISE(auto upper, DeserializeBound(it->second, primitive_type)); + if (upper) { + upper_bounds.emplace(field_id, std::move(*upper)); + } } } @@ -183,18 +186,19 @@ Result CanContainEqDeletesForFile(const DataFile& data_file, ICEBERG_ASSIGN_OR_RAISE(auto delete_lower, delete_file.LowerBound(field_id)); ICEBERG_ASSIGN_OR_RAISE(auto delete_upper, delete_file.UpperBound(field_id)); - if (!delete_lower.has_value() || !delete_upper.has_value()) { + if (!delete_lower || !delete_upper) { continue; // Missing bounds, assume may match } // Convert data bounds auto primitive_type = checked_pointer_cast(field.type()); ICEBERG_ASSIGN_OR_RAISE(auto data_lower, - Literal::Deserialize(data_lower_it->second, primitive_type)); + DeserializeBound(data_lower_it->second, primitive_type)); ICEBERG_ASSIGN_OR_RAISE(auto data_upper, - Literal::Deserialize(data_upper_it->second, primitive_type)); + DeserializeBound(data_upper_it->second, primitive_type)); - if (!RangesOverlap(data_lower, data_upper, delete_lower->get(), + if (data_lower && data_upper && + !RangesOverlap(*data_lower, *data_upper, delete_lower->get(), delete_upper->get())) { return false; // Ranges don't overlap - cannot match } diff --git a/src/iceberg/expression/aggregate.cc b/src/iceberg/expression/aggregate.cc index 12bb3f03f..1360dd31b 100644 --- a/src/iceberg/expression/aggregate.cc +++ b/src/iceberg/expression/aggregate.cc @@ -30,8 +30,10 @@ #include "iceberg/expression/literal.h" #include "iceberg/manifest/manifest_entry.h" #include "iceberg/row/struct_like.h" +#include "iceberg/transform.h" #include "iceberg/type.h" #include "iceberg/util/checked_cast.h" +#include "iceberg/util/conversions_internal.h" #include "iceberg/util/macros.h" namespace iceberg { @@ -56,17 +58,57 @@ class SingleValueStructLike : public StructLike { Literal literal_; }; -Result EvaluateBoundTerm(const BoundTerm& term, - const std::optional>& bound) { - auto ptype = GetPrimitiveType(term); - if (!bound.has_value()) { - SingleValueStructLike data(Literal::Null(ptype)); - return term.Evaluate(data); +// A disengaged optional means the file metrics cannot determine the extremum. +Result> EvaluateFileExtremum(const BoundAggregate& aggregate, + const DataFile& file) { + const auto& term = *aggregate.term(); + bool preserves_order = term.kind() == Term::Kind::kReference; + if (term.kind() == Term::Kind::kTransform) { + const auto& transform = + internal::checked_cast(term).transform(); + if (transform->transform_type() == TransformType::kVoid) { + return Literal::Null(GetPrimitiveType(term)); + } + preserves_order = transform->PreservesOrder(); + } + + const auto ref = term.reference(); + const auto id = ref->field().field_id(); + const auto& bounds = aggregate.op() == Expression::Operation::kMax ? file.upper_bounds + : file.lower_bounds; + // A source endpoint can determine the extremum only if the term preserves order. + if (auto it = bounds.find(id); preserves_order && it != bounds.end()) { + ICEBERG_ASSIGN_OR_RAISE( + auto bound, internal::DeserializeBound(it->second, GetPrimitiveType(*ref))); + if (bound) { + if (term.kind() == Term::Kind::kReference) { + return bound; + } + SingleValueStructLike data(std::move(*bound)); + return term.Evaluate(data); + } + } + const auto values = file.value_counts.find(id); + const auto nulls = file.null_value_counts.find(id); + if (values != file.value_counts.end() && values->second > 0 && + nulls != file.null_value_counts.end() && values->second == nulls->second) { + return Literal::Null(GetPrimitiveType(term)); + } + return std::nullopt; +} + +Result FileExtremumOrNull(const BoundAggregate& aggregate, + const DataFile& file) { + ICEBERG_ASSIGN_OR_RAISE(auto value, EvaluateFileExtremum(aggregate, file)); + if (!value) { + return Literal::Null(GetPrimitiveType(*aggregate.term())); } + return std::move(*value); +} - ICEBERG_ASSIGN_OR_RAISE(auto literal, Literal::Deserialize(*bound, ptype)); - SingleValueStructLike data(std::move(literal)); - return term.Evaluate(data); +bool HasFileExtremum(const BoundAggregate& aggregate, const DataFile& file) { + auto value = EvaluateFileExtremum(aggregate, file); + return value && value->has_value(); } class CountAggregator : public BoundAggregate::Aggregator { @@ -139,27 +181,27 @@ class MaxAggregator : public BoundAggregate::Aggregator { if (!valid_) { return {}; } - if (!aggregate_.HasValue(file)) { + ICEBERG_ASSIGN_OR_RAISE(auto value, EvaluateFileExtremum(aggregate_, file)); + if (!value) { valid_ = false; return {}; } - ICEBERG_ASSIGN_OR_RAISE(auto value, aggregate_.Evaluate(file)); - if (value.IsNull()) { + if (value->IsNull()) { return {}; } if (current_.IsNull()) { - current_ = std::move(value); + current_ = std::move(*value); return {}; } - if (auto ordering = value <=> current_; + if (auto ordering = *value <=> current_; ordering == std::partial_ordering::unordered) { valid_ = false; return InvalidArgument("Cannot compare literal {} with current value {}", - value.ToString(), current_.ToString()); + value->ToString(), current_.ToString()); } else if (ordering == std::partial_ordering::greater) { - current_ = std::move(value); + current_ = std::move(*value); } return {}; } @@ -210,27 +252,27 @@ class MinAggregator : public BoundAggregate::Aggregator { if (!valid_) { return {}; } - if (!aggregate_.HasValue(file)) { + ICEBERG_ASSIGN_OR_RAISE(auto value, EvaluateFileExtremum(aggregate_, file)); + if (!value) { valid_ = false; return {}; } - ICEBERG_ASSIGN_OR_RAISE(auto value, aggregate_.Evaluate(file)); - if (value.IsNull()) { + if (value->IsNull()) { return {}; } if (current_.IsNull()) { - current_ = std::move(value); + current_ = std::move(*value); return {}; } - if (auto ordering = value <=> current_; + if (auto ordering = *value <=> current_; ordering == std::partial_ordering::unordered) { valid_ = false; return InvalidArgument("Cannot compare literal {} with current value {}", - value.ToString(), current_.ToString()); + value->ToString(), current_.ToString()); } else if (ordering == std::partial_ordering::less) { - current_ = std::move(value); + current_ = std::move(*value); } return {}; } @@ -406,9 +448,7 @@ Result MaxAggregate::Evaluate(const StructLike& data) const { } Result MaxAggregate::Evaluate(const DataFile& file) const { - auto field_id = GetFieldId(term()); - auto upper = GetMapValue(file.upper_bounds, field_id); - return EvaluateBoundTerm(*term(), upper); + return FileExtremumOrNull(*this, file); } std::unique_ptr MaxAggregate::NewAggregator() const { @@ -416,13 +456,7 @@ std::unique_ptr MaxAggregate::NewAggregator() const } bool MaxAggregate::HasValue(const DataFile& file) const { - auto field_id = GetFieldId(term()); - bool has_bound = file.upper_bounds.contains(field_id); - auto value_count = GetMapValue(file.value_counts, field_id); - auto null_count = GetMapValue(file.null_value_counts, field_id); - bool all_null = value_count.has_value() && *value_count > 0 && null_count.has_value() && - null_count.value() == value_count.value(); - return has_bound || all_null; + return HasFileExtremum(*this, file); } MinAggregate::MinAggregate(std::shared_ptr term) @@ -444,9 +478,7 @@ Result MinAggregate::Evaluate(const StructLike& data) const { } Result MinAggregate::Evaluate(const DataFile& file) const { - auto field_id = GetFieldId(term()); - auto lower = GetMapValue(file.lower_bounds, field_id); - return EvaluateBoundTerm(*term(), lower); + return FileExtremumOrNull(*this, file); } std::unique_ptr MinAggregate::NewAggregator() const { @@ -454,13 +486,7 @@ std::unique_ptr MinAggregate::NewAggregator() const } bool MinAggregate::HasValue(const DataFile& file) const { - auto field_id = GetFieldId(term()); - bool has_bound = file.lower_bounds.contains(field_id); - auto value_count = GetMapValue(file.value_counts, field_id); - auto null_count = GetMapValue(file.null_value_counts, field_id); - bool all_null = value_count.has_value() && *value_count > 0 && null_count.has_value() && - null_count.value() == value_count.value(); - return has_bound || all_null; + return HasFileExtremum(*this, file); } // -------------------- Unbound binding -------------------- diff --git a/src/iceberg/expression/inclusive_metrics_evaluator.cc b/src/iceberg/expression/inclusive_metrics_evaluator.cc index cb0ea6139..b6d55fd83 100644 --- a/src/iceberg/expression/inclusive_metrics_evaluator.cc +++ b/src/iceberg/expression/inclusive_metrics_evaluator.cc @@ -28,6 +28,7 @@ #include "iceberg/manifest/manifest_entry.h" #include "iceberg/schema.h" #include "iceberg/transform.h" +#include "iceberg/util/conversions_internal.h" #include "iceberg/util/macros.h" #include "iceberg/util/math_util_internal.h" #include "iceberg/util/temporal_util.h" @@ -481,7 +482,7 @@ class InclusiveMetricsVisitor : public BoundVisitor { } auto primitive_type = internal::checked_pointer_cast(type); if (data_file_.lower_bounds.contains(id)) { - return Literal::Deserialize(data_file_.lower_bounds.at(id), primitive_type); + return internal::DeserializeBound(data_file_.lower_bounds.at(id), primitive_type); } return std::nullopt; @@ -495,7 +496,7 @@ class InclusiveMetricsVisitor : public BoundVisitor { } auto primitive_type = internal::checked_pointer_cast(type); if (data_file_.upper_bounds.contains(id)) { - return Literal::Deserialize(data_file_.upper_bounds.at(id), primitive_type); + return internal::DeserializeBound(data_file_.upper_bounds.at(id), primitive_type); } return std::nullopt; diff --git a/src/iceberg/expression/strict_metrics_evaluator.cc b/src/iceberg/expression/strict_metrics_evaluator.cc index 878a7df92..0b856172e 100644 --- a/src/iceberg/expression/strict_metrics_evaluator.cc +++ b/src/iceberg/expression/strict_metrics_evaluator.cc @@ -31,6 +31,7 @@ #include "iceberg/manifest/manifest_entry.h" #include "iceberg/schema.h" #include "iceberg/type.h" +#include "iceberg/util/conversions_internal.h" #include "iceberg/util/macros.h" namespace iceberg { @@ -156,7 +157,7 @@ class StrictMetricsVisitor : public BoundVisitor { auto it = data_file_.upper_bounds.find(id); if (it != data_file_.upper_bounds.cend()) { ICEBERG_ASSIGN_OR_RAISE(auto upper, ParseBound(expr, it->second)); - if (upper < lit) { + if (upper && *upper < lit) { return kRowsMustMatch; } } @@ -184,7 +185,7 @@ class StrictMetricsVisitor : public BoundVisitor { auto it = data_file_.upper_bounds.find(id); if (it != data_file_.upper_bounds.cend()) { ICEBERG_ASSIGN_OR_RAISE(auto upper, ParseBound(expr, it->second)); - if (upper <= lit) { + if (upper && *upper <= lit) { return kRowsMustMatch; } } @@ -212,13 +213,13 @@ class StrictMetricsVisitor : public BoundVisitor { auto it = data_file_.lower_bounds.find(id); if (it != data_file_.lower_bounds.cend()) { ICEBERG_ASSIGN_OR_RAISE(auto lower, ParseBound(expr, it->second)); - if (lower.IsNaN()) { + if (lower && lower->IsNaN()) { // NaN indicates unreliable bounds. See the StrictMetricsEvaluator docs for // more. return kRowsMightNotMatch; } - if (lower > lit) { + if (lower && *lower > lit) { return kRowsMustMatch; } } @@ -246,13 +247,13 @@ class StrictMetricsVisitor : public BoundVisitor { auto it = data_file_.lower_bounds.find(id); if (it != data_file_.lower_bounds.cend()) { ICEBERG_ASSIGN_OR_RAISE(auto lower, ParseBound(expr, it->second)); - if (lower.IsNaN()) { + if (lower && lower->IsNaN()) { // NaN indicates unreliable bounds. See the StrictMetricsEvaluator docs for // more. return kRowsMightNotMatch; } - if (lower >= lit) { + if (lower && *lower >= lit) { return kRowsMustMatch; } } @@ -281,11 +282,11 @@ class StrictMetricsVisitor : public BoundVisitor { if (lower_it != data_file_.lower_bounds.cend() && upper_it != data_file_.upper_bounds.cend()) { ICEBERG_ASSIGN_OR_RAISE(auto lower, ParseBound(expr, lower_it->second)); - if (lower != lit) { + if (!lower || *lower != lit) { return kRowsMightNotMatch; } ICEBERG_ASSIGN_OR_RAISE(auto upper, ParseBound(expr, upper_it->second)); - if (upper != lit) { + if (!upper || *upper != lit) { return kRowsMightNotMatch; } @@ -313,12 +314,12 @@ class StrictMetricsVisitor : public BoundVisitor { auto lower_it = data_file_.lower_bounds.find(id); if (lower_it != data_file_.lower_bounds.cend()) { ICEBERG_ASSIGN_OR_RAISE(auto lower, ParseBound(expr, lower_it->second)); - if (lower.IsNaN()) { + if (lower && lower->IsNaN()) { // NaN indicates unreliable bounds. See the StrictMetricsEvaluator docs for // more. return kRowsMightNotMatch; } - if (lower > lit) { + if (lower && *lower > lit) { return kRowsMustMatch; } } @@ -326,7 +327,7 @@ class StrictMetricsVisitor : public BoundVisitor { auto upper_it = data_file_.upper_bounds.find(id); if (upper_it != data_file_.upper_bounds.cend()) { ICEBERG_ASSIGN_OR_RAISE(auto upper, ParseBound(expr, upper_it->second)); - if (upper < lit) { + if (upper && *upper < lit) { return kRowsMustMatch; } } @@ -357,16 +358,16 @@ class StrictMetricsVisitor : public BoundVisitor { // similar to the implementation in eq, first check if the lower bound is in the // set ICEBERG_ASSIGN_OR_RAISE(auto lower, ParseBound(expr, lower_it->second)); - if (!literal_set.contains(lower)) { + if (!lower || !literal_set.contains(*lower)) { return kRowsMightNotMatch; } // check if the upper bound is in the set ICEBERG_ASSIGN_OR_RAISE(auto upper, ParseBound(expr, upper_it->second)); - if (!literal_set.contains(upper)) { + if (!upper || !literal_set.contains(*upper)) { return kRowsMightNotMatch; } // finally check if the lower bound and the upper bound are equal - if (lower != upper) { + if (*lower != *upper) { return kRowsMightNotMatch; } @@ -395,20 +396,18 @@ class StrictMetricsVisitor : public BoundVisitor { std::optional lower_bound; auto lower_it = data_file_.lower_bounds.find(id); if (lower_it != data_file_.lower_bounds.cend()) { - ICEBERG_ASSIGN_OR_RAISE(auto lower, ParseBound(expr, lower_it->second)); - if (lower.IsNaN()) { + ICEBERG_ASSIGN_OR_RAISE(lower_bound, ParseBound(expr, lower_it->second)); + if (lower_bound && lower_bound->IsNaN()) { // NaN indicates unreliable bounds. See the StrictMetricsEvaluator docs for // more. return kRowsMightNotMatch; } - lower_bound = std::move(lower); } std::optional upper_bound; auto upper_it = data_file_.upper_bounds.find(id); if (upper_it != data_file_.upper_bounds.cend()) { - ICEBERG_ASSIGN_OR_RAISE(auto upper, ParseBound(expr, upper_it->second)); - upper_bound = std::move(upper); + ICEBERG_ASSIGN_OR_RAISE(upper_bound, ParseBound(expr, upper_it->second)); } if (!lower_bound.has_value() && !upper_bound.has_value()) { @@ -460,13 +459,19 @@ class StrictMetricsVisitor : public BoundVisitor { std::string_view prefix = std::get(lit.value()); ICEBERG_ASSIGN_OR_RAISE(auto lower, ParseBound(expr, lower_it->second)); - std::string_view lower_str = std::get(lower.value()); + if (!lower) { + return kRowsMightNotMatch; + } + std::string_view lower_str = std::get(lower->value()); if (!lower_str.starts_with(prefix)) { return kRowsMightNotMatch; } ICEBERG_ASSIGN_OR_RAISE(auto upper, ParseBound(expr, upper_it->second)); - std::string_view upper_str = std::get(upper.value()); + if (!upper) { + return kRowsMightNotMatch; + } + std::string_view upper_str = std::get(upper->value()); if (!upper_str.starts_with(prefix)) { return kRowsMightNotMatch; } @@ -507,8 +512,8 @@ class StrictMetricsVisitor : public BoundVisitor { if (auto lower_it = data_file_.lower_bounds.find(id); lower_it != data_file_.lower_bounds.cend()) { ICEBERG_ASSIGN_OR_RAISE(auto lower, ParseBound(expr, lower_it->second)); - std::string_view lower_str = std::get(lower.value()); - if (lower_str.compare(0, prefix.size(), prefix) > 0) { + if (lower && + std::get(lower->value()).compare(0, prefix.size(), prefix) > 0) { return kRowsMustMatch; } } @@ -516,8 +521,7 @@ class StrictMetricsVisitor : public BoundVisitor { if (auto upper_it = data_file_.upper_bounds.find(id); upper_it != data_file_.upper_bounds.cend()) { ICEBERG_ASSIGN_OR_RAISE(auto upper, ParseBound(expr, upper_it->second)); - std::string_view upper_str = std::get(upper.value()); - if (upper_str < prefix) { + if (upper && std::get(upper->value()) < prefix) { return kRowsMustMatch; } } @@ -526,14 +530,14 @@ class StrictMetricsVisitor : public BoundVisitor { } private: - Result ParseBound(const std::shared_ptr& expr, - const std::vector& stats) { + Result> ParseBound(const std::shared_ptr& expr, + const std::vector& stats) { auto type = expr->reference()->type(); if (!type->is_primitive()) { return NotSupported("Bound of non-primitive type is not supported."); } auto primitive_type = internal::checked_pointer_cast(type); - return Literal::Deserialize(stats, primitive_type); + return internal::DeserializeBound(stats, primitive_type); } Result CanContainNulls(int32_t id) { diff --git a/src/iceberg/test/aggregate_test.cc b/src/iceberg/test/aggregate_test.cc index 9885c7a6f..a7f775aee 100644 --- a/src/iceberg/test/aggregate_test.cc +++ b/src/iceberg/test/aggregate_test.cc @@ -27,7 +27,9 @@ #include "iceberg/row/struct_like.h" #include "iceberg/schema.h" #include "iceberg/test/matchers.h" +#include "iceberg/transform.h" #include "iceberg/type.h" +#include "iceberg/util/temporal_util.h" namespace iceberg { @@ -327,6 +329,103 @@ TEST(AggregateTest, AggregatesFromDataFileWithTransform) { EXPECT_TRUE(evaluator->AllAggregatorsValid()); } +TEST(AggregateTest, BucketDoesNotUseFileBounds) { + auto check = [](const Literal& lower, const Literal& upper, int32_t num_buckets) { + Schema schema({SchemaField::MakeOptional(1, "value", lower.type())}); + auto bucket = Expressions::Bucket("value", num_buckets); + ICEBERG_UNWRAP_OR_FAIL(auto lower_bytes, lower.Serialize()); + ICEBERG_UNWRAP_OR_FAIL(auto upper_bytes, upper.Serialize()); + DataFile file{.record_count = 2, + .value_counts = {{1, 2}}, + .null_value_counts = {{1, 0}}, + .lower_bounds = {{1, lower_bytes}}, + .upper_bounds = {{1, upper_bytes}}}; + DataFile all_nulls{ + .record_count = 2, .value_counts = {{1, 2}}, .null_value_counts = {{1, 2}}}; + for (const auto& expr : {Expressions::Min(bucket), Expressions::Max(bucket)}) { + auto agg = BindAggregate(schema, expr); + SCOPED_TRACE(agg->ToString()); + EXPECT_FALSE(agg->HasValue(file)); + ICEBERG_UNWRAP_OR_FAIL(auto from_bounds, agg->Evaluate(file)); + EXPECT_TRUE(from_bounds.IsNull()) << from_bounds.ToString(); + auto accumulator = agg->NewAggregator(); + ASSERT_THAT(accumulator->Update(file), IsOk()); + EXPECT_FALSE(accumulator->IsValid()); + + EXPECT_TRUE(agg->HasValue(all_nulls)); + ICEBERG_UNWRAP_OR_FAIL(auto value, agg->Evaluate(all_nulls)); + EXPECT_TRUE(value.IsNull()); + EXPECT_EQ(value.type()->type_id(), TypeId::kInt); + } + }; + + // The Appendix B timestamps fall in buckets 1 and 0, respectively. + ICEBERG_UNWRAP_OR_FAIL(auto micros, + TemporalUtils::ParseTimestamp("2017-11-16T22:31:08")); + check(Literal::Timestamp(micros), Literal::Timestamp(micros + 1), 2); + check(Literal::Int(3), Literal::Int(4), 4); // buckets 3 and 2 +} + +TEST(AggregateTest, VoidExtremaAreKnownNullWithOrWithoutBounds) { + Schema schema({SchemaField::MakeRequired(1, "id", int32())}); + auto term = Expressions::Transform("id", Transform::Void()); + ICEBERG_UNWRAP_OR_FAIL(auto bound, Literal::Int(42).Serialize()); + DataFile with_bounds{ + .record_count = 1, .lower_bounds = {{1, bound}}, .upper_bounds = {{1, bound}}}; + DataFile without_bounds{.record_count = 1}; + for (const auto& expr : {Expressions::Min(term), Expressions::Max(term)}) { + auto agg = BindAggregate(schema, expr); + SCOPED_TRACE(agg->ToString()); + auto accumulator = agg->NewAggregator(); + for (const auto* file : {&with_bounds, &without_bounds}) { + EXPECT_TRUE(agg->HasValue(*file)); + ASSERT_THAT(accumulator->Update(*file), IsOk()); + EXPECT_TRUE(accumulator->IsValid()); + } + auto value = accumulator->GetResult(); + EXPECT_TRUE(value.IsNull()); + EXPECT_EQ(value.type()->type_id(), TypeId::kInt); + } +} + +TEST(AggregateTest, MaxDayUsesTimestampUpperBound) { + Schema schema({SchemaField::MakeRequired(1, "ts", timestamp())}); + auto max_day = BindAggregate(schema, Expressions::Max(Expressions::Day("ts"))); + ICEBERG_UNWRAP_OR_FAIL(auto upper, + Literal::Timestamp(2 * internal::kMicrosPerDay + 1).Serialize()); + DataFile file{.record_count = 1, .upper_bounds = {{1, upper}}}; + EXPECT_TRUE(max_day->HasValue(file)); + ICEBERG_UNWRAP_OR_FAIL(auto result, max_day->Evaluate(file)); + EXPECT_EQ(std::get(result.value()), 2); +} + +TEST(AggregateTest, PromotedDateBoundsDistinguishUnknownAndInvalid) { + ICEBERG_UNWRAP_OR_FAIL(auto lower, Literal::Date(-106752).Serialize()); + ICEBERG_UNWRAP_OR_FAIL(auto upper, Literal::Date(106752).Serialize()); + for (const auto& field : {SchemaField::MakeRequired(1, "ts", timestamp_ns()), + SchemaField::MakeOptional(1, "ts", timestamp_ns())}) { + Schema schema({field}); + for (const auto& agg : {BindAggregate(schema, Expressions::Min("ts")), + BindAggregate(schema, Expressions::Max("ts"))}) { + DataFile file{ + .record_count = 1, .lower_bounds = {{1, lower}}, .upper_bounds = {{1, upper}}}; + EXPECT_FALSE(agg->HasValue(file)); + ICEBERG_UNWRAP_OR_FAIL(auto value, agg->Evaluate(file)); + EXPECT_TRUE(value.IsNull()); + EXPECT_EQ(value.type()->type_id(), TypeId::kTimestampNs); + auto accumulator = agg->NewAggregator(); + ASSERT_TRUE(accumulator->Update(file).has_value()); + EXPECT_FALSE(accumulator->IsValid()); + + file.lower_bounds[1] = file.upper_bounds[1] = {0, 1, 2}; + EXPECT_FALSE(agg->HasValue(file)); + EXPECT_THAT(agg->Evaluate(file), IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(agg->NewAggregator()->Update(file), + IsError(ErrorKind::kInvalidArgument)); + } + } +} + TEST(AggregateTest, DataFileAggregatorParity) { Schema schema({SchemaField::MakeRequired(1, "id", int32()), SchemaField::MakeOptional(2, "no_stats", int32()), diff --git a/src/iceberg/test/delete_file_index_test.cc b/src/iceberg/test/delete_file_index_test.cc index 5cb58ea46..f02be7109 100644 --- a/src/iceberg/test/delete_file_index_test.cc +++ b/src/iceberg/test/delete_file_index_test.cc @@ -45,9 +45,43 @@ #include "iceberg/transform.h" #include "iceberg/type.h" #include "iceberg/util/partition_value_util.h" +#include "iceberg/util/temporal_util.h" namespace iceberg { +TEST(DeleteFileDatePromotionTest, DataAndDeleteBoundsUseTimestampUnits) { + Schema schema({SchemaField::MakeRequired(1, "ts", timestamp_ns())}); + ICEBERG_UNWRAP_OR_FAIL(auto date, Literal::Date(1).Serialize()); + ICEBERG_UNWRAP_OR_FAIL(auto midnight, + Literal::TimestampNs(internal::kNanosPerDay).Serialize()); + ICEBERG_UNWRAP_OR_FAIL(auto epoch, Literal::TimestampNs(0).Serialize()); + ICEBERG_UNWRAP_OR_FAIL(auto overflow, Literal::Date(106752).Serialize()); + auto check = [&](const auto& data_lower, const auto& data_upper, + const auto& delete_lower, const auto& delete_upper, bool expected) { + DataFile data{.record_count = 1, + .lower_bounds = {{1, data_lower}}, + .upper_bounds = {{1, data_upper}}}; + auto deletes = std::make_shared( + DataFile{.content = DataFile::Content::kEqualityDeletes, + .lower_bounds = {{1, delete_lower}}, + .upper_bounds = {{1, delete_upper}}, + .equality_ids = {1}}); + internal::EqualityDeleteFile eq( + &schema, ManifestEntry{.sequence_number = 2, .data_file = std::move(deletes)}); + ICEBERG_UNWRAP_OR_FAIL(auto may_match, + internal::CanContainEqDeletesForFile(data, eq)); + EXPECT_EQ(may_match, expected); + }; + check(date, date, midnight, midnight, true); + check(midnight, midnight, date, date, true); + check(epoch, overflow, midnight, midnight, true); + check(midnight, midnight, date, overflow, true); + check(date, date, epoch, epoch, false); + check(epoch, epoch, date, date, false); + check(date, overflow, epoch, epoch, true); + check(epoch, epoch, date, overflow, true); +} + class DeleteFileIndexTest : public testing::TestWithParam { protected: void SetUp() override { diff --git a/src/iceberg/test/inclusive_metrics_evaluator_test.cc b/src/iceberg/test/inclusive_metrics_evaluator_test.cc index e8c7b75ed..16906440a 100644 --- a/src/iceberg/test/inclusive_metrics_evaluator_test.cc +++ b/src/iceberg/test/inclusive_metrics_evaluator_test.cc @@ -19,6 +19,7 @@ #include "iceberg/expression/inclusive_metrics_evaluator.h" +#include #include #include #include @@ -131,6 +132,45 @@ class InclusiveMetricsEvaluatorTest : public ::testing::Test { std::shared_ptr schema_; }; +TEST(InclusiveMetricsDatePromotionTest, UsesDaysForTimestampBounds) { + Schema schema({SchemaField::MakeRequired(1, "ts", timestamp())}); + ICEBERG_UNWRAP_OR_FAIL(auto lower, Literal::Date(1).Serialize()); + ICEBERG_UNWRAP_OR_FAIL(auto upper, Literal::Date(2).Serialize()); + DataFile file{ + .record_count = 1, .lower_bounds = {{1, lower}}, .upper_bounds = {{1, upper}}}; + auto check = [&](const std::shared_ptr& expr, bool expected) { + ICEBERG_UNWRAP_OR_FAIL(auto eval, + InclusiveMetricsEvaluator::Make(expr, schema, true)); + ICEBERG_UNWRAP_OR_FAIL(auto result, eval->Evaluate(file)); + EXPECT_EQ(result, expected); + }; + check(Expressions::GreaterThan("ts", Literal::Timestamp(5)), true); + check(Expressions::LessThan("ts", Literal::Timestamp(5)), false); +} + +TEST(InclusiveMetricsDatePromotionTest, OutOfRangeUpperBoundKeepsUsableLowerBound) { + Schema schema({SchemaField::MakeRequired(1, "ts", timestamp_ns())}); + ICEBERG_UNWRAP_OR_FAIL(auto lower, Literal::Date(0).Serialize()); + ICEBERG_UNWRAP_OR_FAIL(auto upper, Literal::Date(106752).Serialize()); + DataFile file{ + .record_count = 1, .lower_bounds = {{1, lower}}, .upper_bounds = {{1, upper}}}; + + ICEBERG_UNWRAP_OR_FAIL( + auto above, + InclusiveMetricsEvaluator::Make( + Expressions::GreaterThan( + "ts", Literal::TimestampNs(std::numeric_limits::max() - 1)), + schema, true)); + ICEBERG_UNWRAP_OR_FAIL( + auto below, + InclusiveMetricsEvaluator::Make( + Expressions::LessThan("ts", Literal::TimestampNs(0)), schema, true)); + ICEBERG_UNWRAP_OR_FAIL(auto might_match_above, above->Evaluate(file)); + ICEBERG_UNWRAP_OR_FAIL(auto might_match_below, below->Evaluate(file)); + EXPECT_EQ(might_match_above, kRowsMightMatch); + EXPECT_EQ(might_match_below, kRowCannotMatch); +} + TEST_F(InclusiveMetricsEvaluatorTest, CaseSensitiveTest) { { auto unbound = Expressions::Equal("id", Literal::Long(300)); diff --git a/src/iceberg/test/literal_test.cc b/src/iceberg/test/literal_test.cc index 60bd8f3ec..262a1d60c 100644 --- a/src/iceberg/test/literal_test.cc +++ b/src/iceberg/test/literal_test.cc @@ -649,6 +649,36 @@ TEST(LiteralSerDeTest, TypePromotion) { EXPECT_EQ(double_result->type()->type_id(), TypeId::kDouble); EXPECT_DOUBLE_EQ(std::get(double_result->value()), 1.0); } + +TEST(LiteralSerDeTest, DatePromotion) { + for (const auto& type : + std::vector>{timestamp(), timestamp_ns()}) { + const auto units_per_day = type->type_id() == TypeId::kTimestamp + ? internal::kMicrosPerDay + : internal::kNanosPerDay; + const auto max_days = + static_cast(std::numeric_limits::max() / units_per_day); + for (int32_t days : {-max_days, -1, 0, 1, max_days}) { + ICEBERG_UNWRAP_OR_FAIL(auto bytes, Literal::Date(days).Serialize()); + ICEBERG_UNWRAP_OR_FAIL(auto decoded, Literal::Deserialize(bytes, type)); + EXPECT_EQ(std::get(decoded.value()), days * units_per_day); + } + for (int32_t days : {-max_days - 1, max_days + 1}) { + ICEBERG_UNWRAP_OR_FAIL(auto bytes, Literal::Date(days).Serialize()); + EXPECT_THAT(Literal::Deserialize(bytes, type), + IsError(ErrorKind::kInvalidArgument)); + } + } +} + +TEST(LiteralSerDeTest, FourByteTemporalValuesRequireDatePromotion) { + ICEBERG_UNWRAP_OR_FAIL(auto bytes, Literal::Date(1).Serialize()); + for (const auto& type : std::vector>{ + time(), timestamp_tz(), timestamptz_ns()}) { + EXPECT_THAT(Literal::Deserialize(bytes, type), IsError(ErrorKind::kInvalidArgument)); + } +} + // Instantiate parameterized tests INSTANTIATE_TEST_SUITE_P( diff --git a/src/iceberg/test/strict_metrics_evaluator_test.cc b/src/iceberg/test/strict_metrics_evaluator_test.cc index 70ad2d97c..1eb7c352b 100644 --- a/src/iceberg/test/strict_metrics_evaluator_test.cc +++ b/src/iceberg/test/strict_metrics_evaluator_test.cc @@ -31,6 +31,7 @@ #include "iceberg/schema.h" #include "iceberg/test/matchers.h" #include "iceberg/type.h" +#include "iceberg/util/temporal_util.h" namespace iceberg { @@ -1327,6 +1328,44 @@ TEST(StrictMetricsEvaluatorRegressionTest, NotInWithMissingLowerBound) { kRowsMustMatch); } +TEST(StrictMetricsEvaluatorRegressionTest, NotInWithPromotedDateUpperBound) { + auto schema = std::make_shared( + std::vector{SchemaField::MakeRequired(1, "ts", timestamp())}, + /*schema_id=*/0); + DataFile file; + file.record_count = 1; + file.null_value_counts = {{1, 0}}; + ICEBERG_UNWRAP_OR_FAIL(auto upper, Literal::Date(1).Serialize()); + file.upper_bounds = {{1, upper}}; + + // The file may contain midnight on January 2, 1970. + auto expr = Expressions::NotIn("ts", {Literal::Timestamp(internal::kMicrosPerDay), + Literal::Timestamp(2 * internal::kMicrosPerDay)}); + ICEBERG_UNWRAP_OR_FAIL(auto eval, StrictMetricsEvaluator::Make(expr, schema, true)); + ICEBERG_UNWRAP_OR_FAIL(auto result, eval->Evaluate(file)); + EXPECT_EQ(result, kRowsMightNotMatch); +} + +TEST(StrictMetricsEvaluatorRegressionTest, NotInWithOutOfRangeDateBound) { + auto schema = std::make_shared( + std::vector{SchemaField::MakeRequired(1, "ts", timestamp_ns())}); + ICEBERG_UNWRAP_OR_FAIL(auto epoch, Literal::Date(0).Serialize()); + ICEBERG_UNWRAP_OR_FAIL(auto loose_upper, Literal::Date(106752).Serialize()); + DataFile file{.record_count = 1, + .lower_bounds = {{1, epoch}}, + .upper_bounds = {{1, loose_upper}}}; + + auto expect_not_in = [&](int64_t first, int64_t second, bool expected) { + auto expr = Expressions::NotIn( + "ts", {Literal::TimestampNs(first), Literal::TimestampNs(second)}); + ICEBERG_UNWRAP_OR_FAIL(auto eval, StrictMetricsEvaluator::Make(expr, schema, true)); + ICEBERG_UNWRAP_OR_FAIL(auto result, eval->Evaluate(file)); + EXPECT_EQ(result, expected); + }; + expect_not_in(0, 1, kRowsMightNotMatch); + expect_not_in(-2, -1, kRowsMustMatch); // The lower bound is still usable. +} + TEST(StrictMetricsEvaluatorRegressionTest, NotInWithMissingUpperBound) { auto schema = std::make_shared( std::vector{SchemaField::MakeRequired(1, "id", int32())}, diff --git a/src/iceberg/util/conversions.cc b/src/iceberg/util/conversions.cc index 5c5356103..0c0a08262 100644 --- a/src/iceberg/util/conversions.cc +++ b/src/iceberg/util/conversions.cc @@ -20,12 +20,15 @@ #include "iceberg/util/conversions.h" #include +#include #include #include +#include "iceberg/util/conversions_internal.h" #include "iceberg/util/decimal.h" #include "iceberg/util/endian.h" #include "iceberg/util/macros.h" +#include "iceberg/util/temporal_util.h" #include "iceberg/util/uuid.h" namespace iceberg { @@ -141,6 +144,35 @@ Result> Conversions::ToBytes(const Literal& literal) { return ToBytes(*literal.type(), literal.value()); } +namespace { + +std::optional PromoteDate(int32_t days, TypeId type_id) { + const auto units_per_day = + type_id == TypeId::kTimestamp ? internal::kMicrosPerDay : internal::kNanosPerDay; + if (days < std::numeric_limits::min() / units_per_day || + days > std::numeric_limits::max() / units_per_day) { + return std::nullopt; + } + return days * units_per_day; +} + +} // namespace + +Result> internal::DeserializeBound( + std::span data, const std::shared_ptr& type) { + if (type && data.size() == sizeof(int32_t) && + (type->type_id() == TypeId::kTimestamp || + type->type_id() == TypeId::kTimestampNs)) { + auto value = PromoteDate(ReadLittleEndian(data.data()), type->type_id()); + if (!value) { + return std::nullopt; + } + return type->type_id() == TypeId::kTimestamp ? Literal::Timestamp(*value) + : Literal::TimestampNs(*value); + } + return Literal::Deserialize(data, type); +} + Result Conversions::FromBytes(const PrimitiveType& type, std::span data) { const auto type_id = type.type_id(); @@ -158,20 +190,27 @@ Result Conversions::FromBytes(const PrimitiveType& type, return Literal::Value{value}; } case TypeId::kLong: - case TypeId::kTime: case TypeId::kTimestamp: - case TypeId::kTimestampTz: case TypeId::kTimestampNs: - case TypeId::kTimestampTzNs: { - int64_t value; - if (data.size() < 8) { - // Type was promoted from int to long - ICEBERG_ASSIGN_OR_RAISE(auto int_value, ReadLittleEndian(data)); - value = static_cast(int_value); - } else { - ICEBERG_ASSIGN_OR_RAISE(auto long_value, ReadLittleEndian(data)); - value = long_value; + if (data.size() == sizeof(int32_t)) { + ICEBERG_ASSIGN_OR_RAISE(auto value, ReadLittleEndian(data)); + if (type_id == TypeId::kLong) { + return Literal::Value{static_cast(value)}; + } + // Only timestamps without a zone can be promoted from a four-byte date. + // https://iceberg.apache.org/spec/#schema-evolution + auto timestamp = PromoteDate(value, type_id); + if (!timestamp) { + return InvalidArgument("Date {} is outside the range of {}", value, + type.ToString()); + } + return Literal::Value{*timestamp}; } + [[fallthrough]]; + case TypeId::kTime: + case TypeId::kTimestampTz: + case TypeId::kTimestampTzNs: { + ICEBERG_ASSIGN_OR_RAISE(auto value, ReadLittleEndian(data)); return Literal::Value{value}; } case TypeId::kFloat: { diff --git a/src/iceberg/util/conversions_internal.h b/src/iceberg/util/conversions_internal.h new file mode 100644 index 000000000..c0741d288 --- /dev/null +++ b/src/iceberg/util/conversions_internal.h @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#pragma once + +#include +#include + +#include "iceberg/expression/literal.h" + +namespace iceberg::internal { + +/// A loose date bound outside the promoted timestamp range is unknown. +Result> DeserializeBound( + std::span data, const std::shared_ptr& type); + +} // namespace iceberg::internal