This is an automated email from the ASF dual-hosted git repository.

wgtmac pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg-cpp.git


The following commit(s) were added to refs/heads/main by this push:
     new 372e4212 fix(expression): skip file pruning when timestamp hours can 
wrap (#1176)
372e4212 is described below

commit 372e4212a1d22ade516d4cdc5d41be9b85bd4417
Author: Junwang Zhao <[email protected]>
AuthorDate: Thu Nov 26 22:52:50 2026 +0800

    fix(expression): skip file pruning when timestamp hours can wrap (#1176)
    
    The hour transform returns an int32. A large microsecond timestamp can
    wrap to a negative hour, causing hour(ts) >= 0 to skip a file that
    contains the epoch.
    
    Use hour bounds for pruning only when both ends of the microsecond
    timestamp range fit in int32 hours. Nanosecond timestamps always fit,
    so they can still use a single bound.
---
 .../expression/inclusive_metrics_evaluator.cc      | 54 ++++++++++-------
 ...lusive_metrics_evaluator_with_transform_test.cc | 67 ++++++++++++++++++++++
 2 files changed, 99 insertions(+), 22 deletions(-)

diff --git a/src/iceberg/expression/inclusive_metrics_evaluator.cc 
b/src/iceberg/expression/inclusive_metrics_evaluator.cc
index d16e58ee..cb0ea613 100644
--- a/src/iceberg/expression/inclusive_metrics_evaluator.cc
+++ b/src/iceberg/expression/inclusive_metrics_evaluator.cc
@@ -20,6 +20,7 @@
 #include "iceberg/expression/inclusive_metrics_evaluator.h"
 
 #include <ranges>
+#include <utility>
 
 #include "iceberg/expression/binder.h"
 #include "iceberg/expression/expression_visitor.h"
@@ -28,6 +29,8 @@
 #include "iceberg/schema.h"
 #include "iceberg/transform.h"
 #include "iceberg/util/macros.h"
+#include "iceberg/util/math_util_internal.h"
+#include "iceberg/util/temporal_util.h"
 
 namespace iceberg {
 
@@ -35,6 +38,12 @@ namespace {
 constexpr bool kRowsMightMatch = true;
 constexpr bool kRowCannotMatch = false;
 constexpr int32_t kInPredicateLimit = 200;
+
+bool HourFitsInInt32(const Literal& timestamp) {
+  constexpr auto kMicrosPerHour = internal::kMicrosPerSecond * 
internal::kSecondsPerHour;
+  return std::in_range<int32_t>(
+      FloorDiv(std::get<int64_t>(timestamp.value()), kMicrosPerHour));
+}
 }  // namespace
 
 class InclusiveMetricsVisitor : public BoundVisitor<bool> {
@@ -415,7 +424,7 @@ class InclusiveMetricsVisitor : public BoundVisitor<bool> {
       return ParseLowerBound(*reference);
     } else if (auto transform = dynamic_cast<BoundTransform*>(expr.get());
                transform != nullptr) {
-      return TransformLowerBound(*transform);
+      return TransformBound(*transform, /*lower=*/true);
     } else {
       return std::nullopt;
     }
@@ -428,7 +437,7 @@ class InclusiveMetricsVisitor : public BoundVisitor<bool> {
       return ParseUpperBound(*reference);
     } else if (auto transform = dynamic_cast<BoundTransform*>(expr.get());
                transform != nullptr) {
-      return TransformUpperBound(*transform);
+      return TransformBound(*transform, /*lower=*/false);
     } else {
       return std::nullopt;
     }
@@ -492,32 +501,33 @@ class InclusiveMetricsVisitor : public BoundVisitor<bool> 
{
     return std::nullopt;
   }
 
-  Result<std::optional<Literal>> TransformLowerBound(BoundTransform& 
boundTransform) {
-    auto transform = boundTransform.transform();
-    if (transform->PreservesOrder()) {
-      ICEBERG_ASSIGN_OR_RAISE(auto lower, 
ParseLowerBound(*boundTransform.reference()));
-      if (lower.has_value()) {
-        ICEBERG_ASSIGN_OR_RAISE(auto transform_func,
-                                
transform->Bind(boundTransform.reference()->type()));
-        return transform_func->Transform(lower.value());
-      }
+  Result<std::optional<Literal>> TransformBound(const BoundTransform& term, 
bool lower) {
+    const auto& transform = term.transform();
+    if (!transform->PreservesOrder()) {
+      return std::nullopt;
     }
 
-    return std::nullopt;
-  }
+    const auto ref = term.reference();
+    ICEBERG_ASSIGN_OR_RAISE(auto bound,
+                            lower ? ParseLowerBound(*ref) : 
ParseUpperBound(*ref));
+    if (!bound) {
+      return std::nullopt;
+    }
 
-  Result<std::optional<Literal>> TransformUpperBound(BoundTransform& 
boundTransform) {
-    auto transform = boundTransform.transform();
-    if (transform->PreservesOrder()) {
-      ICEBERG_ASSIGN_OR_RAISE(auto upper, 
ParseUpperBound(*boundTransform.reference()));
-      if (upper.has_value()) {
-        ICEBERG_ASSIGN_OR_RAISE(auto transform_func,
-                                
transform->Bind(boundTransform.reference()->type()));
-        return transform_func->Transform(upper.value());
+    const auto type_id = ref->type()->type_id();
+    if (transform->transform_type() == TransformType::kHour &&
+        (type_id == TypeId::kTimestamp || type_id == TypeId::kTimestampTz)) {
+      // Microsecond timestamps can span more hours than fit in int32. Either 
end
+      // of the file's range could wrap, invalidating both transformed bounds.
+      ICEBERG_ASSIGN_OR_RAISE(auto other,
+                              lower ? ParseUpperBound(*ref) : 
ParseLowerBound(*ref));
+      if (!other || !HourFitsInInt32(*bound) || !HourFitsInInt32(*other)) {
+        return std::nullopt;
       }
     }
 
-    return std::nullopt;
+    ICEBERG_ASSIGN_OR_RAISE(auto transform_func, transform->Bind(ref->type()));
+    return transform_func->Transform(*bound);
   }
 
   /** Returns true if the expression term produces a non-null value for 
non-null input. */
diff --git 
a/src/iceberg/test/inclusive_metrics_evaluator_with_transform_test.cc 
b/src/iceberg/test/inclusive_metrics_evaluator_with_transform_test.cc
index 4502cda7..f3aacf0d 100644
--- a/src/iceberg/test/inclusive_metrics_evaluator_with_transform_test.cc
+++ b/src/iceberg/test/inclusive_metrics_evaluator_with_transform_test.cc
@@ -17,7 +17,9 @@
  * under the License.
  */
 
+#include <limits>
 #include <memory>
+#include <optional>
 #include <utility>
 #include <vector>
 
@@ -482,4 +484,69 @@ TEST_F(InclusiveMetricsEvaluatorWithTransformTest, 
IntegerNotIn) {
   ExpectShouldRead(Expressions::NotIn(day_ts, ids), kRowsMightMatch);
 }
 
+TEST(InclusiveMetricsHourTest, PruneOnlyWithinInt32HourRange) {
+  constexpr int64_t kMicrosPerHour =
+      internal::kMicrosPerSecond * internal::kSecondsPerHour;
+  constexpr int64_t kFirstMicros = std::numeric_limits<int32_t>::min() * 
kMicrosPerHour;
+  constexpr int64_t kPastLastMicros = -kFirstMicros;
+  for (const auto& type :
+       std::vector<std::shared_ptr<PrimitiveType>>{timestamp(), 
timestamp_tz()}) {
+    SCOPED_TRACE(type->ToString());
+    Schema schema({SchemaField::MakeRequired(1, "ts", type)});
+    auto hour = ToBoundTransform(Expressions::Hour("ts"));
+    ICEBERG_UNWRAP_OR_FAIL(
+        auto negative, InclusiveMetricsEvaluator::Make(
+                           Expressions::LessThan(hour, Literal::Int(0)), 
schema, true));
+    ICEBERG_UNWRAP_OR_FAIL(
+        auto positive,
+        InclusiveMetricsEvaluator::Make(Expressions::GreaterThan(hour, 
Literal::Int(0)),
+                                        schema, true));
+
+    auto check = [&](std::optional<int64_t> lower, std::optional<int64_t> 
upper,
+                     bool may_be_negative, bool may_be_positive) {
+      SCOPED_TRACE(::testing::Message() << "lower=" << 
::testing::PrintToString(lower)
+                                        << ", upper=" << 
::testing::PrintToString(upper));
+      DataFile file{.record_count = 2};
+      if (lower) {
+        ICEBERG_UNWRAP_OR_FAIL(file.lower_bounds[1],
+                               Literal::Timestamp(*lower).Serialize());
+      }
+      if (upper) {
+        ICEBERG_UNWRAP_OR_FAIL(file.upper_bounds[1],
+                               Literal::Timestamp(*upper).Serialize());
+      }
+      ICEBERG_UNWRAP_OR_FAIL(auto negative_matches, negative->Evaluate(file));
+      ICEBERG_UNWRAP_OR_FAIL(auto positive_matches, positive->Evaluate(file));
+      EXPECT_EQ(negative_matches, may_be_negative);
+      EXPECT_EQ(positive_matches, may_be_positive);
+    };
+
+    check(0, kPastLastMicros - 1, false, true);
+    check(kFirstMicros, 0, true, false);
+    // Crossing either edge by one microsecond wraps the hour to the opposite 
sign.
+    check(0, kPastLastMicros, true, true);
+    check(kFirstMicros - 1, 0, true, true);
+    check(0, std::nullopt, true, true);
+    check(std::nullopt, 0, true, true);
+  }
+}
+
+TEST(InclusiveMetricsHourTest, NanosecondTimestampSupportsOneSidedPruning) {
+  for (const auto& type :
+       std::vector<std::shared_ptr<PrimitiveType>>{timestamp_ns(), 
timestamptz_ns()}) {
+    SCOPED_TRACE(type->ToString());
+    Schema schema({SchemaField::MakeRequired(1, "ts", type)});
+    ICEBERG_UNWRAP_OR_FAIL(
+        auto negative,
+        InclusiveMetricsEvaluator::Make(
+            Expressions::LessThan(ToBoundTransform(Expressions::Hour("ts")),
+                                  Literal::Int(0)),
+            schema, true));
+    ICEBERG_UNWRAP_OR_FAIL(auto epoch, Literal::TimestampNs(0).Serialize());
+    DataFile file{.record_count = 1, .lower_bounds = {{1, epoch}}};
+    ICEBERG_UNWRAP_OR_FAIL(auto matches, negative->Evaluate(file));
+    EXPECT_EQ(matches, kRowCannotMatch);
+  }
+}
+
 }  // namespace iceberg

Reply via email to