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

zhjwpku 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 6f00fd9e feat(expression): implement StartsWith in 
StrictMetricsEvaluator (#1154)
6f00fd9e is described below

commit 6f00fd9e1e3c45628291f330fc1880cd75df4089
Author: Deepak N <[email protected]>
AuthorDate: Sun Nov 22 15:40:31 2026 -0800

    feat(expression): implement StartsWith in StrictMetricsEvaluator (#1154)
    
    ### **Problem**
    
    Support for StartsWith metadata-based pruning
    
    StrictMetricsEvaluator is called from DeleteFiles or OverwriteFiles for 
metadata-based evaluation / pruning. It checks whether every row in a data file 
is guaranteed to match the predicate. It is important to make sure we don't 
have false positives here, otherwise we will have correctness issues.
    
    Per the spec, string lower_bounds and upper_bounds are stored in manifest 
entries as UTF-8 bytes. The bounds are drawn only from non-null values in a 
column. If the column contains null, startsWith doesn't match all rows, so 
return false.
    
    **_Edge case:_** Writers can truncate the bounds (for example 
truncate(16)). Even with truncation, lower_bound <= min and max <= upper_bound 
still hold, so checking both bounds would still be safe. Note: If a bound was 
truncated shorter than the prefix, StartsWith should return false.
    
    ### **Fix**
    
    Java Reference Implementation: 
[StrictEvalVisitor.java](https://github.com/apache/iceberg/blob/282ff355692a71e6e974fa96c5ecd8bd9e3d5fe2/api/src/main/java/org/apache/iceberg/expressions/StrictEvalVisitor.java#L386)
    
    For StartsWith to return true, these are the conditions:
    - Top-level column reference (not a transform or nested column, where null 
counts may be missing).
    - No nulls (CanContainNulls needs to be false).
    - Both lower_bounds and upper_bounds should be present.
    - Both bounds start with the prefix.
    
    NotStartsWith will be handled in a separate follow-up PR to keep changes 
small, however Not(NotStartsWith) gets rewritten as StartsWith, so included a 
test case for this.
    
    ### **Tests**
    Mostly ported the StartsWith tests from Java, plus some cases:
    * missing bound
    * optional columns with and without null counts
    * nested string columns with stats
    * transform terms
    * non-string/null bind rejection,
    * Not(NotStartsWith(...)) rewrite
    * multibyte UTF-8 strings.
    
    To verify my understanding, also wrote an e2e test in delete_files_test.cc 
(not included in this PR to keep the diff small) using Parquet files with 
truncated bounds, Avro manifests, DeleteFiles::DeleteFromRowFilter, and 
TableScan to verify the full flow, I considered including this test in the 
current PR, but felt like an overkill.
---
 src/iceberg/expression/strict_metrics_evaluator.cc |  45 +++++-
 src/iceberg/test/strict_metrics_evaluator_test.cc  | 176 ++++++++++++++++++++-
 2 files changed, 218 insertions(+), 3 deletions(-)

diff --git a/src/iceberg/expression/strict_metrics_evaluator.cc 
b/src/iceberg/expression/strict_metrics_evaluator.cc
index 73bd5dc0..b4374cc3 100644
--- a/src/iceberg/expression/strict_metrics_evaluator.cc
+++ b/src/iceberg/expression/strict_metrics_evaluator.cc
@@ -21,6 +21,8 @@
 
 #include <algorithm>
 #include <optional>
+#include <string>
+#include <string_view>
 
 #include "iceberg/expression/binder.h"
 #include "iceberg/expression/expression_visitor.h"
@@ -429,7 +431,48 @@ class StrictMetricsVisitor : public BoundVisitor<bool> {
 
   Result<bool> StartsWith(const std::shared_ptr<Bound>& expr,
                           const Literal& lit) override {
-    return kRowsMightNotMatch;
+    RETURN_IF_NOT_REFERENCE(expr);
+
+    int32_t id = expr->reference()->field().field_id();
+
+    ICEBERG_ASSIGN_OR_RAISE(auto is_nested, IsNestedColumn(id));
+    if (is_nested) {
+      return kRowsMightNotMatch;
+    }
+
+    ICEBERG_ASSIGN_OR_RAISE(auto has_nulls, CanContainNulls(id));
+    if (has_nulls) {
+      return kRowsMightNotMatch;
+    }
+
+    auto lower_it = data_file_.lower_bounds.find(id);
+    auto upper_it = data_file_.upper_bounds.find(id);
+    if (lower_it == data_file_.lower_bounds.cend() ||
+        upper_it == data_file_.upper_bounds.cend()) {
+      return kRowsMightNotMatch;
+    }
+
+    if (expr->reference()->type()->type_id() != TypeId::kString ||
+        lit.type()->type_id() != TypeId::kString ||
+        !std::holds_alternative<std::string>(lit.value())) {
+      return InvalidExpression("StartsWith requires a string column and string 
literal");
+    }
+    std::string_view prefix = std::get<std::string>(lit.value());
+
+    ICEBERG_ASSIGN_OR_RAISE(auto lower, ParseBound(expr, lower_it->second));
+    std::string_view lower_str = std::get<std::string>(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<std::string>(upper.value());
+    if (!upper_str.starts_with(prefix)) {
+      return kRowsMightNotMatch;
+    }
+
+    // Both bounds start with the prefix, so all rows must start with the 
prefix.
+    return kRowsMustMatch;
   }
 
   Result<bool> NotStartsWith(const std::shared_ptr<Bound>& expr,
diff --git a/src/iceberg/test/strict_metrics_evaluator_test.cc 
b/src/iceberg/test/strict_metrics_evaluator_test.cc
index 6555b5d5..1767c39d 100644
--- a/src/iceberg/test/strict_metrics_evaluator_test.cc
+++ b/src/iceberg/test/strict_metrics_evaluator_test.cc
@@ -20,6 +20,8 @@
 #include "iceberg/expression/strict_metrics_evaluator.h"
 
 #include <limits>
+#include <optional>
+#include <vector>
 
 #include <gtest/gtest.h>
 
@@ -391,8 +393,8 @@ TEST_F(StrictMetricsEvaluatorTest, NotInTest) {
 }
 
 TEST_F(StrictMetricsEvaluatorTest, StartsWithTest) {
-  // always true
   TestStringCase(Expressions::StartsWith("name", "1"), kRowsMightNotMatch);
+  TestStringCase(Expressions::StartsWith("name", ""), kRowsMustMatch);
 }
 
 TEST_F(StrictMetricsEvaluatorTest, NotStartsWithTest) {
@@ -426,13 +428,15 @@ class StrictMetricsEvaluatorMigratedTest : public 
StrictMetricsEvaluatorTest {
                 15, "struct",
                 std::make_shared<StructType>(std::vector<SchemaField>{
                     SchemaField::MakeOptional(16, "nested_col_no_stats", 
int64()),
-                    SchemaField::MakeOptional(17, "nested_col_with_stats", 
int64())})),
+                    SchemaField::MakeOptional(17, "nested_col_with_stats", 
int64()),
+                    SchemaField::MakeOptional(18, "nested_string_col", 
string())})),
         },
         /*schema_id=*/0);
 
     file_ = MakePrimaryFile();
     file_with_bounds_ = MakeSomeNullsFile();
     file_with_equal_bounds_ = MakeSomeNullsEqualBoundsFile();
+    string_file_ = MakeStringFile();
   }
 
   std::shared_ptr<DataFile> MakePrimaryFile() {
@@ -520,6 +524,23 @@ class StrictMetricsEvaluatorMigratedTest : public 
StrictMetricsEvaluatorTest {
     return data_file;
   }
 
+  std::shared_ptr<DataFile> MakeStringFile() {
+    auto data_file = std::make_shared<DataFile>();
+    data_file->file_path = "string_file.avro";
+    data_file->file_format = FileFormatType::kParquet;
+    data_file->record_count = 50;
+    data_file->value_counts = {
+        {3, 50L},
+    };
+    data_file->lower_bounds = {
+        {3, Literal::String("abc").Serialize().value()},
+    };
+    data_file->upper_bounds = {
+        {3, Literal::String("abd").Serialize().value()},
+    };
+    return data_file;
+  }
+
   std::shared_ptr<DataFile> MakeMissingStatsFile() {
     auto data_file = std::make_shared<DataFile>();
     data_file->file_path = "missing.parquet";
@@ -569,6 +590,7 @@ class StrictMetricsEvaluatorMigratedTest : public 
StrictMetricsEvaluatorTest {
   std::shared_ptr<DataFile> file_;
   std::shared_ptr<DataFile> file_with_bounds_;
   std::shared_ptr<DataFile> file_with_equal_bounds_;
+  std::shared_ptr<DataFile> string_file_;
 };
 
 TEST_F(StrictMetricsEvaluatorMigratedTest, AllNulls) {
@@ -881,6 +903,156 @@ TEST_F(StrictMetricsEvaluatorMigratedTest, 
EvaluateOnNestedColumnWithStats) {
   ExpectShouldRead(Expressions::NotNull("struct.nested_col_with_stats"), 
false);
 }
 
+TEST_F(StrictMetricsEvaluatorMigratedTest, 
StartsWithPrefixBoundsEvaluatesAsExpected) {
+  struct PrefixCase {
+    const char* prefix;
+    bool expected;
+  };
+
+  const std::vector<PrefixCase> cases = {
+      {.prefix = "a", .expected = true},        // both bounds match.
+      {.prefix = "ab", .expected = true},       // both bounds match.
+      {.prefix = "abc", .expected = false},     // only lower bound matches.
+      {.prefix = "abd", .expected = false},     // only upper bound matches.
+      {.prefix = "zzz", .expected = false},     // neither bound matches.
+      {.prefix = "abcdef", .expected = false},  // prefix longer than bounds.
+      {.prefix = "", .expected = true},         // empty prefix.
+  };
+
+  for (const auto& [prefix, expected] : cases) {
+    SCOPED_TRACE(prefix);
+    ExpectShouldRead(Expressions::StartsWith("required", prefix), expected, 
string_file_);
+  }
+}
+
+TEST_F(StrictMetricsEvaluatorMigratedTest, 
StartsWithDoesNotMatchWhenStatsMissing) {
+  ExpectShouldRead(Expressions::StartsWith("required", "a"), false);
+  ExpectShouldRead(Expressions::StartsWith("required", ""), false);
+}
+
+TEST_F(StrictMetricsEvaluatorMigratedTest, 
StartsWithDoesNotMatchWhenSingleBoundMissing) {
+  auto lower_only = std::make_shared<DataFile>(*string_file_);
+  lower_only->upper_bounds.clear();
+  ExpectShouldRead(Expressions::StartsWith("required", "ab"), false, 
lower_only);
+
+  auto upper_only = std::make_shared<DataFile>(*string_file_);
+  upper_only->lower_bounds.clear();
+  ExpectShouldRead(Expressions::StartsWith("required", "ab"), false, 
upper_only);
+}
+
+TEST_F(StrictMetricsEvaluatorMigratedTest, 
StartsWithDoesNotMatchForAllNullColumn) {
+  ExpectShouldRead(Expressions::StartsWith("all_nulls", "a"), false);
+}
+
+TEST_F(StrictMetricsEvaluatorMigratedTest, 
StartsWithDoesNotMatchWhenColumnHasSomeNulls) {
+  ExpectShouldRead(Expressions::StartsWith("some_nulls", "b"), false, 
file_with_bounds_);
+  // Bounds are equal ["bbb", "bbb"], but the column still has nulls.
+  ExpectShouldRead(Expressions::StartsWith("some_nulls", "b"), false,
+                   file_with_equal_bounds_);
+  ExpectShouldRead(Expressions::StartsWith("some_nulls", ""), false,
+                   file_with_equal_bounds_);
+}
+
+TEST_F(StrictMetricsEvaluatorMigratedTest, StartsWithOptionalColumnNullCounts) 
{
+  struct NullCountCase {
+    std::optional<int64_t> null_count;
+    bool expected;
+  };
+
+  const std::vector<NullCountCase> cases = {
+      {.null_count = 0L, .expected = true},
+      {.null_count = 1L, .expected = false},
+      {.null_count = std::nullopt,
+       .expected = false},  // also check if null count is not set.
+  };
+
+  auto file = std::make_shared<DataFile>();
+  file->file_path = "optional_string.parquet";
+  file->file_format = FileFormatType::kParquet;
+  file->record_count = 50;
+  file->value_counts = {{6, 50L}};
+  file->lower_bounds = {{6, Literal::String("abc").Serialize().value()}};
+  file->upper_bounds = {{6, Literal::String("abd").Serialize().value()}};
+
+  for (const auto& [null_count, expected] : cases) {
+    SCOPED_TRACE(null_count.has_value() ? std::to_string(*null_count) : 
"missing");
+    file->null_value_counts.clear();
+    if (null_count.has_value()) {
+      file->null_value_counts[6] = *null_count;
+    }
+    ExpectShouldRead(Expressions::StartsWith("no_nulls", "ab"), expected, 
file);
+  }
+}
+
+TEST_F(StrictMetricsEvaluatorMigratedTest, 
StartsWithDoesNotMatchForNestedColumn) {
+  ExpectShouldRead(Expressions::StartsWith("struct.nested_string_col", "a"), 
false);
+
+  auto nested_with_stats = std::make_shared<DataFile>(*file_);
+  nested_with_stats->value_counts[18] = 50L;
+  nested_with_stats->null_value_counts[18] = 0L;
+  nested_with_stats->lower_bounds[18] = 
Literal::String("abc").Serialize().value();
+  nested_with_stats->upper_bounds[18] = 
Literal::String("abd").Serialize().value();
+  ExpectShouldRead(Expressions::StartsWith("struct.nested_string_col", "ab"), 
false,
+                   nested_with_stats);
+}
+
+TEST_F(StrictMetricsEvaluatorMigratedTest, 
StartsWithDoesNotMatchForTransformTerm) {
+  // Truncate is a transform, not a direct column ref, so bounds cannot be 
used.
+  ExpectShouldRead(
+      
Expressions::StartsWith<BoundTransform>(Expressions::Truncate("required", 2), 
"ab"),
+      false, string_file_);
+}
+
+TEST_F(StrictMetricsEvaluatorMigratedTest, 
StartsWithEvaluatesNegatedNotStartsWith) {
+  // Not(NotStartsWith) gets rewritten to StartsWith before evaluation.
+  ExpectShouldRead(Expressions::Not(Expressions::NotStartsWith("required", 
"ab")), true,
+                   string_file_);
+  ExpectShouldRead(Expressions::Not(Expressions::NotStartsWith("required", 
"abc")), false,
+                   string_file_);
+}
+
+TEST_F(StrictMetricsEvaluatorMigratedTest, 
StartsWithMatchesMultibyteUtf8Prefix) {
+  // String bounds use UTF-8, verify comparing multibyte prefixes works.
+  const std::string e_accent = "\xC3\xA9";                     // U+00E9
+  const std::string grinning_face_emoji = "\xF0\x9F\x98\x80";  // U+1F600
+
+  auto utf8_file = std::make_shared<DataFile>();
+  utf8_file->file_path = "utf8_file.parquet";
+  utf8_file->file_format = FileFormatType::kParquet;
+  utf8_file->record_count = 50;
+  utf8_file->value_counts = {{3, 50L}};
+  utf8_file->lower_bounds = {{3, Literal::String(e_accent + 
"a").Serialize().value()}};
+  utf8_file->upper_bounds = {{3, Literal::String(e_accent + 
"b").Serialize().value()}};
+
+  ExpectShouldRead(Expressions::StartsWith("required", e_accent), true, 
utf8_file);
+  // Only lower bound matches e_accent + "a"; emoji does not match either 
bound.
+  ExpectShouldRead(Expressions::StartsWith("required", e_accent + "a"), false, 
utf8_file);
+  ExpectShouldRead(Expressions::StartsWith("required", grinning_face_emoji), 
false,
+                   utf8_file);
+}
+
+TEST_F(StrictMetricsEvaluatorMigratedTest, 
StartsWithRejectsNonStringColumnOnBind) {
+  auto result =
+      StrictMetricsEvaluator::Make(Expressions::StartsWith("id", "ab"), 
schema_);
+  EXPECT_THAT(result, IsError(ErrorKind::kInvalidExpression));
+}
+
+TEST_F(StrictMetricsEvaluatorMigratedTest, 
StartsWithRejectsNonStringLiteralOnBind) {
+  auto result = StrictMetricsEvaluator::Make(
+      Expressions::Predicate(Expression::Operation::kStartsWith, "required",
+                             Literal::Int(123)),
+      schema_);
+  EXPECT_FALSE(result.has_value());
+}
+
+TEST_F(StrictMetricsEvaluatorMigratedTest, StartsWithRejectsNullLiteralOnBind) 
{
+  auto result = StrictMetricsEvaluator::Make(
+      Expressions::Predicate(Expression::Operation::kStartsWith, "required",
+                             Literal::Null(string())),
+      schema_);
+  EXPECT_THAT(result, IsError(ErrorKind::kInvalidExpression));
+}
+
 TEST(StrictMetricsEvaluatorRegressionTest, MissingNullCountForField) {
   // Field 14 (no_nan_stats, float64, optional) has bounds and value_counts 
but is
   // missing from null_value_counts. The evaluator must conservatively assume 
nulls

Reply via email to