From 2d28428db5b621234353501304e5409d31efb86a Mon Sep 17 00:00:00 2001 From: Junwang Zhao Date: Tue, 24 Nov 2026 14:38:31 +0800 Subject: [PATCH 1/4] fix: decode promoted date bounds in timestamp units Read four-byte bounds for timestamp and timestamp_ns as epoch days. Treat date bounds outside the target range as unknown when evaluating file and manifest statistics, while propagating malformed bounds as errors. --- src/iceberg/delete_file_index.cc | 25 ++--- src/iceberg/delete_file_index.h | 12 --- src/iceberg/expression/aggregate.cc | 98 ++++++++++--------- .../expression/inclusive_metrics_evaluator.cc | 5 +- src/iceberg/expression/manifest_evaluator.cc | 35 ++++--- .../expression/strict_metrics_evaluator.cc | 60 ++++++------ src/iceberg/test/aggregate_test.cc | 27 +++++ src/iceberg/test/delete_file_index_test.cc | 32 ++++++ .../test/inclusive_metrics_evaluator_test.cc | 16 +++ src/iceberg/test/literal_test.cc | 30 ++++++ .../test/strict_metrics_evaluator_test.cc | 39 ++++++++ src/iceberg/util/conversions.cc | 61 +++++++++--- src/iceberg/util/conversions_internal.h | 33 +++++++ 13 files changed, 351 insertions(+), 122 deletions(-) create mode 100644 src/iceberg/util/conversions_internal.h diff --git a/src/iceberg/delete_file_index.cc b/src/iceberg/delete_file_index.cc index 0f6044027a..4fc7833ee3 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,19 +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(), - delete_upper->get())) { + if ((data_lower && delete_upper && *data_lower > delete_upper->get()) || + (data_upper && delete_lower && *data_upper < delete_lower->get())) { return false; // Ranges don't overlap - cannot match } } diff --git a/src/iceberg/delete_file_index.h b/src/iceberg/delete_file_index.h index c8e34ad47b..72462000c4 100644 --- a/src/iceberg/delete_file_index.h +++ b/src/iceberg/delete_file_index.h @@ -87,18 +87,6 @@ struct ICEBERG_EXPORT EqualityDeleteFile { Status ConvertBoundsIfNeeded() const; }; -/// \brief Check if two ranges overlap. -inline bool RangesOverlap(const Literal& data_lower, const Literal& data_upper, - const Literal& delete_lower, const Literal& delete_upper) { - if (data_lower > delete_upper) { - return false; - } - if (delete_lower > data_upper) { - return false; - } - return true; -} - /// \brief Check if a value count map indicates all values are null. inline bool AllNull(const std::map& null_counts, const std::map& value_counts, int32_t field_id, diff --git a/src/iceberg/expression/aggregate.cc b/src/iceberg/expression/aggregate.cc index 12bb3f03fe..ff70d22021 100644 --- a/src/iceberg/expression/aggregate.cc +++ b/src/iceberg/expression/aggregate.cc @@ -32,6 +32,7 @@ #include "iceberg/row/struct_like.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 +57,32 @@ 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(); + 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; + if (auto it = bounds.find(id); 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); + } } - - ICEBERG_ASSIGN_OR_RAISE(auto literal, Literal::Deserialize(*bound, ptype)); - SingleValueStructLike data(std::move(literal)); - 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; } class CountAggregator : public BoundAggregate::Aggregator { @@ -139,27 +155,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 +226,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 +422,11 @@ 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); + ICEBERG_ASSIGN_OR_RAISE(auto value, EvaluateFileExtremum(*this, file)); + if (!value) { + return Literal::Null(GetPrimitiveType(*term())); + } + return std::move(*value); } std::unique_ptr MaxAggregate::NewAggregator() const { @@ -416,13 +434,8 @@ 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; + auto value = EvaluateFileExtremum(*this, file); + return value && value->has_value(); } MinAggregate::MinAggregate(std::shared_ptr term) @@ -444,9 +457,11 @@ 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); + ICEBERG_ASSIGN_OR_RAISE(auto value, EvaluateFileExtremum(*this, file)); + if (!value) { + return Literal::Null(GetPrimitiveType(*term())); + } + return std::move(*value); } std::unique_ptr MinAggregate::NewAggregator() const { @@ -454,13 +469,8 @@ 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; + auto value = EvaluateFileExtremum(*this, file); + return value && value->has_value(); } // -------------------- Unbound binding -------------------- diff --git a/src/iceberg/expression/inclusive_metrics_evaluator.cc b/src/iceberg/expression/inclusive_metrics_evaluator.cc index cb0ea61391..b6d55fd837 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/manifest_evaluator.cc b/src/iceberg/expression/manifest_evaluator.cc index 3042b52332..a79afb03d4 100644 --- a/src/iceberg/expression/manifest_evaluator.cc +++ b/src/iceberg/expression/manifest_evaluator.cc @@ -26,6 +26,7 @@ #include "iceberg/manifest/manifest_list.h" #include "iceberg/row/struct_like.h" #include "iceberg/schema.h" +#include "iceberg/util/conversions_internal.h" #include "iceberg/util/macros.h" namespace iceberg { @@ -113,7 +114,7 @@ class ManifestEvalVisitor : public BoundVisitor { } ICEBERG_ASSIGN_OR_RAISE( auto lower, DeserializeBoundLiteral(summary.lower_bound.value(), ref->type())); - if (lower >= lit) { + if (lower && *lower >= lit) { return kRowCannotMatch; } return kRowsMightMatch; @@ -128,7 +129,7 @@ class ManifestEvalVisitor : public BoundVisitor { } ICEBERG_ASSIGN_OR_RAISE( auto lower, DeserializeBoundLiteral(summary.lower_bound.value(), ref->type())); - if (lower > lit) { + if (lower && *lower > lit) { return kRowCannotMatch; } return kRowsMightMatch; @@ -143,7 +144,7 @@ class ManifestEvalVisitor : public BoundVisitor { } ICEBERG_ASSIGN_OR_RAISE( auto upper, DeserializeBoundLiteral(summary.upper_bound.value(), ref->type())); - if (upper <= lit) { + if (upper && *upper <= lit) { return kRowCannotMatch; } return kRowsMightMatch; @@ -159,7 +160,7 @@ class ManifestEvalVisitor : public BoundVisitor { ICEBERG_ASSIGN_OR_RAISE( auto upper, DeserializeBoundLiteral(summary.upper_bound.value(), expr->reference()->type())); - if (upper < lit) { + if (upper && *upper < lit) { return kRowCannotMatch; } return kRowsMightMatch; @@ -174,13 +175,13 @@ class ManifestEvalVisitor : public BoundVisitor { } ICEBERG_ASSIGN_OR_RAISE( auto lower, DeserializeBoundLiteral(summary.lower_bound.value(), ref->type())); - if (lower > lit) { + if (lower && *lower > lit) { return kRowCannotMatch; } ICEBERG_ASSIGN_OR_RAISE( auto upper, DeserializeBoundLiteral(summary.upper_bound.value(), ref->type())); - if (upper < lit) { + if (upper && *upper < lit) { return kRowCannotMatch; } @@ -214,7 +215,7 @@ class ManifestEvalVisitor : public BoundVisitor { auto upper, DeserializeBoundLiteral(summary.upper_bound.value(), ref->type())); if (std::ranges::all_of(literal_set, [&](const Literal& lit) { - return lit < lower || lit > upper; + return (lower && lit < *lower) || (upper && lit > *upper); })) { // if all values are less than lower bound or greater than upper bound, // rows cannot match. @@ -247,8 +248,11 @@ class ManifestEvalVisitor : public BoundVisitor { auto lower, DeserializeBoundLiteral(summary.lower_bound.value(), ref->type())); ICEBERG_ASSIGN_OR_RAISE( auto upper, DeserializeBoundLiteral(summary.upper_bound.value(), ref->type())); - const auto& lower_bound = std::get(lower.value()); - const auto& upper_bound = std::get(upper.value()); + if (!lower || !upper) { + return kRowsMightMatch; + } + const auto& lower_bound = std::get(lower->value()); + const auto& upper_bound = std::get(upper->value()); // truncate lower bound so that its length in bytes is not greater than the length of // prefix size_t length = std::min(prefix.size(), lower_bound.size()); @@ -281,8 +285,11 @@ class ManifestEvalVisitor : public BoundVisitor { auto lower, DeserializeBoundLiteral(summary.lower_bound.value(), ref->type())); ICEBERG_ASSIGN_OR_RAISE( auto upper, DeserializeBoundLiteral(summary.upper_bound.value(), ref->type())); - const auto& lower_bound = std::get(lower.value()); - const auto& upper_bound = std::get(upper.value()); + if (!lower || !upper) { + return kRowsMightMatch; + } + const auto& lower_bound = std::get(lower->value()); + const auto& upper_bound = std::get(upper->value()); // if lower is shorter than the prefix, it can't start with the prefix if (lower_bound.size() < prefix.size()) { @@ -335,12 +342,12 @@ class ManifestEvalVisitor : public BoundVisitor { return allNull; } - Result DeserializeBoundLiteral(const std::vector& bound, - const std::shared_ptr& type) const { + Result> DeserializeBoundLiteral( + const std::vector& bound, const std::shared_ptr& type) const { if (!type->is_primitive()) { return NotSupported("Bounds of non-primitive partition fields are not supported."); } - return Literal::Deserialize( + return internal::DeserializeBound( bound, std::move(internal::checked_pointer_cast(type))); } diff --git a/src/iceberg/expression/strict_metrics_evaluator.cc b/src/iceberg/expression/strict_metrics_evaluator.cc index 878a7df92b..0b856172ed 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 9885c7a6f4..48422c04c1 100644 --- a/src/iceberg/test/aggregate_test.cc +++ b/src/iceberg/test/aggregate_test.cc @@ -327,6 +327,33 @@ TEST(AggregateTest, AggregatesFromDataFileWithTransform) { EXPECT_TRUE(evaluator->AllAggregatorsValid()); } +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 5cb58ea465..1e70856343 100644 --- a/src/iceberg/test/delete_file_index_test.cc +++ b/src/iceberg/test/delete_file_index_test.cc @@ -45,9 +45,41 @@ #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, overflow, epoch, epoch, false); + check(epoch, epoch, date, overflow, false); +} + 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 e8c7b75ed7..15b792f17f 100644 --- a/src/iceberg/test/inclusive_metrics_evaluator_test.cc +++ b/src/iceberg/test/inclusive_metrics_evaluator_test.cc @@ -131,6 +131,22 @@ 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_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 60bd8f3ec5..262a1d60c5 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 70ad2d97c2..1eb7c352b9 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 5c5356103a..0c0a082623 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 0000000000..c0741d2885 --- /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 From 0c3468f9171950dd4f1a18a6869a1fa34be47949 Mon Sep 17 00:00:00 2001 From: Junwang Zhao Date: Tue, 24 Nov 2026 15:04:31 +0800 Subject: [PATCH 2/4] fix: keep equality delete pruning conservative after date promotion Require all four bounds for equality delete range checks. Keep partition summary evaluation on its existing path and cover timestamp source bounds in transformed aggregates and inclusive file pruning. --- src/iceberg/delete_file_index.cc | 7 ++-- src/iceberg/delete_file_index.h | 12 +++++++ src/iceberg/expression/aggregate.cc | 32 +++++++++-------- src/iceberg/expression/manifest_evaluator.cc | 35 ++++++++----------- src/iceberg/test/aggregate_test.cc | 12 +++++++ src/iceberg/test/delete_file_index_test.cc | 6 ++-- .../test/inclusive_metrics_evaluator_test.cc | 24 +++++++++++++ 7 files changed, 88 insertions(+), 40 deletions(-) diff --git a/src/iceberg/delete_file_index.cc b/src/iceberg/delete_file_index.cc index 4fc7833ee3..bbf5a747c1 100644 --- a/src/iceberg/delete_file_index.cc +++ b/src/iceberg/delete_file_index.cc @@ -186,7 +186,7 @@ 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 && !delete_upper) { + if (!delete_lower || !delete_upper) { continue; // Missing bounds, assume may match } @@ -197,8 +197,9 @@ Result CanContainEqDeletesForFile(const DataFile& data_file, ICEBERG_ASSIGN_OR_RAISE(auto data_upper, DeserializeBound(data_upper_it->second, primitive_type)); - if ((data_lower && delete_upper && *data_lower > delete_upper->get()) || - (data_upper && delete_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/delete_file_index.h b/src/iceberg/delete_file_index.h index 72462000c4..c8e34ad47b 100644 --- a/src/iceberg/delete_file_index.h +++ b/src/iceberg/delete_file_index.h @@ -87,6 +87,18 @@ struct ICEBERG_EXPORT EqualityDeleteFile { Status ConvertBoundsIfNeeded() const; }; +/// \brief Check if two ranges overlap. +inline bool RangesOverlap(const Literal& data_lower, const Literal& data_upper, + const Literal& delete_lower, const Literal& delete_upper) { + if (data_lower > delete_upper) { + return false; + } + if (delete_lower > data_upper) { + return false; + } + return true; +} + /// \brief Check if a value count map indicates all values are null. inline bool AllNull(const std::map& null_counts, const std::map& value_counts, int32_t field_id, diff --git a/src/iceberg/expression/aggregate.cc b/src/iceberg/expression/aggregate.cc index ff70d22021..f77d880c68 100644 --- a/src/iceberg/expression/aggregate.cc +++ b/src/iceberg/expression/aggregate.cc @@ -85,6 +85,20 @@ Result> EvaluateFileExtremum(const BoundAggregate& aggreg 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); +} + +bool HasFileExtremum(const BoundAggregate& aggregate, const DataFile& file) { + auto value = EvaluateFileExtremum(aggregate, file); + return value && value->has_value(); +} + class CountAggregator : public BoundAggregate::Aggregator { public: explicit CountAggregator(const CountAggregate& aggregate) : aggregate_(aggregate) {} @@ -422,11 +436,7 @@ Result MaxAggregate::Evaluate(const StructLike& data) const { } Result MaxAggregate::Evaluate(const DataFile& file) const { - ICEBERG_ASSIGN_OR_RAISE(auto value, EvaluateFileExtremum(*this, file)); - if (!value) { - return Literal::Null(GetPrimitiveType(*term())); - } - return std::move(*value); + return FileExtremumOrNull(*this, file); } std::unique_ptr MaxAggregate::NewAggregator() const { @@ -434,8 +444,7 @@ std::unique_ptr MaxAggregate::NewAggregator() const } bool MaxAggregate::HasValue(const DataFile& file) const { - auto value = EvaluateFileExtremum(*this, file); - return value && value->has_value(); + return HasFileExtremum(*this, file); } MinAggregate::MinAggregate(std::shared_ptr term) @@ -457,11 +466,7 @@ Result MinAggregate::Evaluate(const StructLike& data) const { } Result MinAggregate::Evaluate(const DataFile& file) const { - ICEBERG_ASSIGN_OR_RAISE(auto value, EvaluateFileExtremum(*this, file)); - if (!value) { - return Literal::Null(GetPrimitiveType(*term())); - } - return std::move(*value); + return FileExtremumOrNull(*this, file); } std::unique_ptr MinAggregate::NewAggregator() const { @@ -469,8 +474,7 @@ std::unique_ptr MinAggregate::NewAggregator() const } bool MinAggregate::HasValue(const DataFile& file) const { - auto value = EvaluateFileExtremum(*this, file); - return value && value->has_value(); + return HasFileExtremum(*this, file); } // -------------------- Unbound binding -------------------- diff --git a/src/iceberg/expression/manifest_evaluator.cc b/src/iceberg/expression/manifest_evaluator.cc index a79afb03d4..3042b52332 100644 --- a/src/iceberg/expression/manifest_evaluator.cc +++ b/src/iceberg/expression/manifest_evaluator.cc @@ -26,7 +26,6 @@ #include "iceberg/manifest/manifest_list.h" #include "iceberg/row/struct_like.h" #include "iceberg/schema.h" -#include "iceberg/util/conversions_internal.h" #include "iceberg/util/macros.h" namespace iceberg { @@ -114,7 +113,7 @@ class ManifestEvalVisitor : public BoundVisitor { } ICEBERG_ASSIGN_OR_RAISE( auto lower, DeserializeBoundLiteral(summary.lower_bound.value(), ref->type())); - if (lower && *lower >= lit) { + if (lower >= lit) { return kRowCannotMatch; } return kRowsMightMatch; @@ -129,7 +128,7 @@ class ManifestEvalVisitor : public BoundVisitor { } ICEBERG_ASSIGN_OR_RAISE( auto lower, DeserializeBoundLiteral(summary.lower_bound.value(), ref->type())); - if (lower && *lower > lit) { + if (lower > lit) { return kRowCannotMatch; } return kRowsMightMatch; @@ -144,7 +143,7 @@ class ManifestEvalVisitor : public BoundVisitor { } ICEBERG_ASSIGN_OR_RAISE( auto upper, DeserializeBoundLiteral(summary.upper_bound.value(), ref->type())); - if (upper && *upper <= lit) { + if (upper <= lit) { return kRowCannotMatch; } return kRowsMightMatch; @@ -160,7 +159,7 @@ class ManifestEvalVisitor : public BoundVisitor { ICEBERG_ASSIGN_OR_RAISE( auto upper, DeserializeBoundLiteral(summary.upper_bound.value(), expr->reference()->type())); - if (upper && *upper < lit) { + if (upper < lit) { return kRowCannotMatch; } return kRowsMightMatch; @@ -175,13 +174,13 @@ class ManifestEvalVisitor : public BoundVisitor { } ICEBERG_ASSIGN_OR_RAISE( auto lower, DeserializeBoundLiteral(summary.lower_bound.value(), ref->type())); - if (lower && *lower > lit) { + if (lower > lit) { return kRowCannotMatch; } ICEBERG_ASSIGN_OR_RAISE( auto upper, DeserializeBoundLiteral(summary.upper_bound.value(), ref->type())); - if (upper && *upper < lit) { + if (upper < lit) { return kRowCannotMatch; } @@ -215,7 +214,7 @@ class ManifestEvalVisitor : public BoundVisitor { auto upper, DeserializeBoundLiteral(summary.upper_bound.value(), ref->type())); if (std::ranges::all_of(literal_set, [&](const Literal& lit) { - return (lower && lit < *lower) || (upper && lit > *upper); + return lit < lower || lit > upper; })) { // if all values are less than lower bound or greater than upper bound, // rows cannot match. @@ -248,11 +247,8 @@ class ManifestEvalVisitor : public BoundVisitor { auto lower, DeserializeBoundLiteral(summary.lower_bound.value(), ref->type())); ICEBERG_ASSIGN_OR_RAISE( auto upper, DeserializeBoundLiteral(summary.upper_bound.value(), ref->type())); - if (!lower || !upper) { - return kRowsMightMatch; - } - const auto& lower_bound = std::get(lower->value()); - const auto& upper_bound = std::get(upper->value()); + const auto& lower_bound = std::get(lower.value()); + const auto& upper_bound = std::get(upper.value()); // truncate lower bound so that its length in bytes is not greater than the length of // prefix size_t length = std::min(prefix.size(), lower_bound.size()); @@ -285,11 +281,8 @@ class ManifestEvalVisitor : public BoundVisitor { auto lower, DeserializeBoundLiteral(summary.lower_bound.value(), ref->type())); ICEBERG_ASSIGN_OR_RAISE( auto upper, DeserializeBoundLiteral(summary.upper_bound.value(), ref->type())); - if (!lower || !upper) { - return kRowsMightMatch; - } - const auto& lower_bound = std::get(lower->value()); - const auto& upper_bound = std::get(upper->value()); + const auto& lower_bound = std::get(lower.value()); + const auto& upper_bound = std::get(upper.value()); // if lower is shorter than the prefix, it can't start with the prefix if (lower_bound.size() < prefix.size()) { @@ -342,12 +335,12 @@ class ManifestEvalVisitor : public BoundVisitor { return allNull; } - Result> DeserializeBoundLiteral( - const std::vector& bound, const std::shared_ptr& type) const { + Result DeserializeBoundLiteral(const std::vector& bound, + const std::shared_ptr& type) const { if (!type->is_primitive()) { return NotSupported("Bounds of non-primitive partition fields are not supported."); } - return internal::DeserializeBound( + return Literal::Deserialize( bound, std::move(internal::checked_pointer_cast(type))); } diff --git a/src/iceberg/test/aggregate_test.cc b/src/iceberg/test/aggregate_test.cc index 48422c04c1..e41a6975e2 100644 --- a/src/iceberg/test/aggregate_test.cc +++ b/src/iceberg/test/aggregate_test.cc @@ -28,6 +28,7 @@ #include "iceberg/schema.h" #include "iceberg/test/matchers.h" #include "iceberg/type.h" +#include "iceberg/util/temporal_util.h" namespace iceberg { @@ -327,6 +328,17 @@ TEST(AggregateTest, AggregatesFromDataFileWithTransform) { EXPECT_TRUE(evaluator->AllAggregatorsValid()); } +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()); diff --git a/src/iceberg/test/delete_file_index_test.cc b/src/iceberg/test/delete_file_index_test.cc index 1e70856343..f02be7109f 100644 --- a/src/iceberg/test/delete_file_index_test.cc +++ b/src/iceberg/test/delete_file_index_test.cc @@ -76,8 +76,10 @@ TEST(DeleteFileDatePromotionTest, DataAndDeleteBoundsUseTimestampUnits) { check(midnight, midnight, date, date, true); check(epoch, overflow, midnight, midnight, true); check(midnight, midnight, date, overflow, true); - check(date, overflow, epoch, epoch, false); - check(epoch, epoch, date, overflow, false); + 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 { diff --git a/src/iceberg/test/inclusive_metrics_evaluator_test.cc b/src/iceberg/test/inclusive_metrics_evaluator_test.cc index 15b792f17f..16906440ab 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 @@ -147,6 +148,29 @@ TEST(InclusiveMetricsDatePromotionTest, UsesDaysForTimestampBounds) { 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)); From 79e301f57b86e53013af452e9bce3b87ca46ce7b Mon Sep 17 00:00:00 2001 From: Zhao Junwang Date: Thu, 26 Nov 2026 00:46:32 +0800 Subject: [PATCH 3/4] fix(expression): skip file bounds for bucket min and max Bucket numbers can decrease as source values increase. Applying bucket to a file's upper bound can therefore produce the wrong maximum, even when the bound is the largest value in the file. Use source bounds only for references and order-preserving transforms. Counts can still establish a null result for an all-null column. --- src/iceberg/expression/aggregate.cc | 8 ++++++- src/iceberg/test/aggregate_test.cc | 37 +++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/iceberg/expression/aggregate.cc b/src/iceberg/expression/aggregate.cc index f77d880c68..2d87050fc3 100644 --- a/src/iceberg/expression/aggregate.cc +++ b/src/iceberg/expression/aggregate.cc @@ -30,6 +30,7 @@ #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" @@ -65,7 +66,12 @@ Result> EvaluateFileExtremum(const BoundAggregate& aggreg const auto id = ref->field().field_id(); const auto& bounds = aggregate.op() == Expression::Operation::kMax ? file.upper_bounds : file.lower_bounds; - if (auto it = bounds.find(id); it != bounds.end()) { + // A source endpoint can determine the extremum only if the term preserves order. + const bool preserves_order = + term.kind() == Term::Kind::kReference || + (term.kind() == Term::Kind::kTransform && + internal::checked_cast(term).transform()->PreservesOrder()); + 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) { diff --git a/src/iceberg/test/aggregate_test.cc b/src/iceberg/test/aggregate_test.cc index e41a6975e2..4e3629e98c 100644 --- a/src/iceberg/test/aggregate_test.cc +++ b/src/iceberg/test/aggregate_test.cc @@ -328,6 +328,43 @@ 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, MaxDayUsesTimestampUpperBound) { Schema schema({SchemaField::MakeRequired(1, "ts", timestamp())}); auto max_day = BindAggregate(schema, Expressions::Max(Expressions::Day("ts"))); From 9b82e2dcdf2d96e6b3d8bf1c90f3e456a2900c0e Mon Sep 17 00:00:00 2001 From: Zhao Junwang Date: Fri, 27 Nov 2026 22:35:44 +0800 Subject: [PATCH 4/4] fix(expression): preserve known null for void min and max The void transform returns null for every input. Return a typed null before reading file metrics so both accumulators stay valid with or without source bounds. --- src/iceberg/expression/aggregate.cc | 14 ++++++++++---- src/iceberg/test/aggregate_test.cc | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/iceberg/expression/aggregate.cc b/src/iceberg/expression/aggregate.cc index 2d87050fc3..1360dd31b5 100644 --- a/src/iceberg/expression/aggregate.cc +++ b/src/iceberg/expression/aggregate.cc @@ -62,15 +62,21 @@ class SingleValueStructLike : public StructLike { 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. - const bool preserves_order = - term.kind() == Term::Kind::kReference || - (term.kind() == Term::Kind::kTransform && - internal::checked_cast(term).transform()->PreservesOrder()); if (auto it = bounds.find(id); preserves_order && it != bounds.end()) { ICEBERG_ASSIGN_OR_RAISE( auto bound, internal::DeserializeBound(it->second, GetPrimitiveType(*ref))); diff --git a/src/iceberg/test/aggregate_test.cc b/src/iceberg/test/aggregate_test.cc index 4e3629e98c..a7f775aeea 100644 --- a/src/iceberg/test/aggregate_test.cc +++ b/src/iceberg/test/aggregate_test.cc @@ -27,6 +27,7 @@ #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" @@ -365,6 +366,28 @@ TEST(AggregateTest, BucketDoesNotUseFileBounds) { 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")));