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 f926712c perf(expression): Support split and parallel scans -
Part-3.5: compile Evaluator expressions and compare raw values (#1166)
f926712c is described below
commit f926712c880da36c9e952c15334f8514d4d2c97c
Author: kamcheungting-db <[email protected]>
AuthorDate: Thu Nov 26 19:19:55 2026 -0800
perf(expression): Support split and parallel scans - Part-3.5: compile
Evaluator expressions and compare raw values (#1166)
Evaluator::Evaluate() visited the bound expression for every row, copying
shared_ptrs while dispatching on each predicate, and built a Literal for
every compared value. Building a Literal copies the type's shared_ptr
singleton and, for strings and bytes, the value itself. With several
threads evaluating residual filters, the atomic reference count of the
shared type object became the bottleneck: a parallel scan with a per-row
residual ran slower than a serial one.
Evaluator::Make() now compiles the bound expression once into evaluation
nodes. Literal and unary predicates on a field reference of a primitive
type read the field's raw scalar and compare it with the bound literal,
matching Literal ordering: null and out-of-range literals are unordered,
floating-point values use the total order, decimals compare across
scales, and strings and bytes compare as unsigned bytes. Set predicates,
transforms, and any value without a raw representation still go through
the literal-based visitor, so results and errors are unchanged. And/Or
still evaluate both sides, so a failing row still reports its error.
Co-authored-by: Isaac <[email protected]>
---
src/iceberg/expression/evaluator.cc | 426 +++++++++++++++++++++++++++++++++++-
src/iceberg/expression/evaluator.h | 11 +-
src/iceberg/test/evaluator_test.cc | 246 +++++++++++++++++++++
3 files changed, 677 insertions(+), 6 deletions(-)
diff --git a/src/iceberg/expression/evaluator.cc
b/src/iceberg/expression/evaluator.cc
index 417e6712..795ed4bd 100644
--- a/src/iceberg/expression/evaluator.cc
+++ b/src/iceberg/expression/evaluator.cc
@@ -19,14 +19,31 @@
#include "iceberg/expression/evaluator.h"
+#include <algorithm>
+#include <cmath>
+#include <compare>
+#include <cstring>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <utility>
+#include <variant>
+#include <vector>
+
#include "iceberg/expression/binder.h"
#include "iceberg/expression/expression_visitor.h"
+#include "iceberg/expression/predicate.h"
+#include "iceberg/expression/term.h"
#include "iceberg/row/struct_like.h"
#include "iceberg/schema.h"
+#include "iceberg/type.h"
+#include "iceberg/util/checked_cast.h"
#include "iceberg/util/macros.h"
namespace iceberg {
+namespace {
+
class EvalVisitor : public BoundVisitor<bool> {
public:
explicit EvalVisitor(const StructLike& row) : row_(row) {}
@@ -139,8 +156,406 @@ class EvalVisitor : public BoundVisitor<bool> {
const StructLike& row_;
};
-Evaluator::Evaluator(std::shared_ptr<Expression> bound_expr)
- : bound_expr_(std::move(bound_expr)) {}
+} // namespace
+
+namespace internal {
+
+/// \brief One node of a compiled bound expression, evaluated once per row.
+class EvaluatorNode {
+ public:
+ virtual ~EvaluatorNode() = default;
+ virtual Result<bool> Evaluate(const StructLike& row) const = 0;
+};
+
+} // namespace internal
+
+namespace {
+
+using internal::EvaluatorNode;
+using NodePtr = std::unique_ptr<const EvaluatorNode>;
+using Operation = Expression::Operation;
+
+class ConstantNode : public EvaluatorNode {
+ public:
+ explicit ConstantNode(bool value) : value_(value) {}
+ Result<bool> Evaluate(const StructLike& /*row*/) const override { return
value_; }
+
+ private:
+ bool value_;
+};
+
+class NotNode : public EvaluatorNode {
+ public:
+ explicit NotNode(NodePtr child) : child_(std::move(child)) {}
+ Result<bool> Evaluate(const StructLike& row) const override {
+ ICEBERG_ASSIGN_OR_RAISE(auto result, child_->Evaluate(row));
+ return !result;
+ }
+
+ private:
+ NodePtr child_;
+};
+
+// Evaluates both children, left first, like the expression visitor, so a row
that
+// fails to evaluate on either side still reports its error.
+class AndNode : public EvaluatorNode {
+ public:
+ AndNode(NodePtr left, NodePtr right)
+ : left_(std::move(left)), right_(std::move(right)) {}
+ Result<bool> Evaluate(const StructLike& row) const override {
+ ICEBERG_ASSIGN_OR_RAISE(auto left, left_->Evaluate(row));
+ ICEBERG_ASSIGN_OR_RAISE(auto right, right_->Evaluate(row));
+ return left && right;
+ }
+
+ private:
+ NodePtr left_;
+ NodePtr right_;
+};
+
+class OrNode : public EvaluatorNode {
+ public:
+ OrNode(NodePtr left, NodePtr right)
+ : left_(std::move(left)), right_(std::move(right)) {}
+ Result<bool> Evaluate(const StructLike& row) const override {
+ ICEBERG_ASSIGN_OR_RAISE(auto left, left_->Evaluate(row));
+ ICEBERG_ASSIGN_OR_RAISE(auto right, right_->Evaluate(row));
+ return left || right;
+ }
+
+ private:
+ NodePtr left_;
+ NodePtr right_;
+};
+
+// Evaluates an expression with EvalVisitor, which converts values to literals.
+// Used for expressions without a raw-value fast path, and as the fast path's
+// fallback, so both report identical results and errors.
+class VisitorNode : public EvaluatorNode {
+ public:
+ explicit VisitorNode(std::shared_ptr<Expression> expr) :
expr_(std::move(expr)) {}
+ Result<bool> Evaluate(const StructLike& row) const override {
+ EvalVisitor visitor(row);
+ return Visit<bool, EvalVisitor>(expr_, visitor);
+ }
+
+ private:
+ std::shared_ptr<Expression> expr_;
+};
+
+// Compares `lhs` with `rhs` as unsigned bytes, like std::vector<uint8_t> and
+// std::string comparisons.
+std::strong_ordering CompareBytes(std::string_view lhs, const void* rhs,
+ size_t rhs_size) {
+ const size_t common = std::min(lhs.size(), rhs_size);
+ if (common > 0) {
+ if (int result = std::memcmp(lhs.data(), rhs, common); result != 0) {
+ return result <=> 0;
+ }
+ }
+ return lhs.size() <=> rhs_size;
+}
+
+bool HasRawComparison(TypeId type_id) {
+ switch (type_id) {
+ case TypeId::kBoolean:
+ case TypeId::kInt:
+ case TypeId::kDate:
+ case TypeId::kLong:
+ case TypeId::kTime:
+ case TypeId::kTimestamp:
+ case TypeId::kTimestampTz:
+ case TypeId::kTimestampNs:
+ case TypeId::kTimestampTzNs:
+ case TypeId::kFloat:
+ case TypeId::kDouble:
+ case TypeId::kDecimal:
+ case TypeId::kString:
+ case TypeId::kBinary:
+ case TypeId::kFixed:
+ case TypeId::kUuid:
+ return true;
+ default:
+ return false;
+ }
+}
+
+int32_t DecimalScale(const Type& type) {
+ return type.type_id() == TypeId::kDecimal
+ ? internal::checked_cast<const DecimalType&>(type).scale()
+ : 0;
+}
+
+// A literal or unary predicate on a field reference, evaluated on the field's
raw
+// scalar instead of a Literal built for each row. Matches Literal ordering:
null
+// and out-of-range literals are unordered, floats use the total order,
decimals
+// compare across scales, and strings and bytes compare as unsigned bytes. Any
+// value it cannot compare that way is evaluated by the fallback.
+class ReferencePredicateNode : public EvaluatorNode {
+ public:
+ ReferencePredicateNode(const BoundReference& reference, Operation op,
+ const Literal* literal, std::shared_ptr<Expression>
predicate)
+ : accessor_(reference.accessor()),
+ type_id_(reference.type()->type_id()),
+ scale_(DecimalScale(*reference.type())),
+ op_(op),
+ literal_(literal),
+ literal_scale_(literal != nullptr ? DecimalScale(*literal->type()) :
0),
+ fallback_(std::move(predicate)) {}
+
+ Result<bool> Evaluate(const StructLike& row) const override {
+ ICEBERG_ASSIGN_OR_RAISE(auto value, accessor_.Get(row));
+ const bool is_null = std::holds_alternative<std::monostate>(value);
+ switch (op_) {
+ case Operation::kIsNull:
+ return is_null;
+ case Operation::kNotNull:
+ return !is_null;
+ case Operation::kIsNan:
+ case Operation::kNotNan: {
+ bool is_nan;
+ if (is_null) {
+ is_nan = false;
+ } else if (const auto* f = std::get_if<float>(&value);
+ type_id_ == TypeId::kFloat && f != nullptr) {
+ is_nan = std::isnan(*f);
+ } else if (const auto* d = std::get_if<double>(&value);
+ type_id_ == TypeId::kDouble && d != nullptr) {
+ is_nan = std::isnan(*d);
+ } else {
+ return fallback_.Evaluate(row);
+ }
+ return op_ == Operation::kIsNan ? is_nan : !is_nan;
+ }
+ case Operation::kStartsWith:
+ case Operation::kNotStartsWith: {
+ const auto* prefix = std::get_if<std::string>(&literal_->value());
+ bool starts = false;
+ if (const auto* str = std::get_if<std::string_view>(&value);
+ str != nullptr && prefix != nullptr) {
+ starts = str->starts_with(*prefix);
+ } else if (!is_null) {
+ return fallback_.Evaluate(row);
+ }
+ return op_ == Operation::kStartsWith ? starts : !starts;
+ }
+ default:
+ break;
+ }
+
+ auto order = Compare(value);
+ if (!order.has_value()) {
+ return fallback_.Evaluate(row);
+ }
+ switch (op_) {
+ case Operation::kLt:
+ return *order < 0;
+ case Operation::kLtEq:
+ return *order <= 0;
+ case Operation::kGt:
+ return *order > 0;
+ case Operation::kGtEq:
+ return *order >= 0;
+ case Operation::kEq:
+ return *order == 0;
+ case Operation::kNotEq:
+ return !(*order == 0);
+ default:
+ return fallback_.Evaluate(row);
+ }
+ }
+
+ static bool Supports(const BoundPredicate& predicate, TypeId type_id) {
+ using Kind = BoundPredicate::Kind;
+ const auto kind = predicate.kind();
+ switch (predicate.op()) {
+ case Operation::kIsNull:
+ case Operation::kNotNull:
+ return kind == Kind::kUnary;
+ case Operation::kIsNan:
+ case Operation::kNotNan:
+ return kind == Kind::kUnary &&
+ (type_id == TypeId::kFloat || type_id == TypeId::kDouble);
+ case Operation::kStartsWith:
+ case Operation::kNotStartsWith:
+ return kind == Kind::kLiteral && type_id == TypeId::kString;
+ case Operation::kLt:
+ case Operation::kLtEq:
+ case Operation::kGt:
+ case Operation::kGtEq:
+ case Operation::kEq:
+ case Operation::kNotEq:
+ return kind == Kind::kLiteral && HasRawComparison(type_id);
+ default:
+ return false;
+ }
+ }
+
+ private:
+ // Orders `value` against the literal like Literal::operator<=>, or returns
+ // std::nullopt when the scalar does not hold the field type's
representation.
+ std::optional<std::partial_ordering> Compare(const Scalar& value) const {
+ const auto& literal = literal_->value();
+ if (std::holds_alternative<std::monostate>(value) || literal_->IsNull() ||
+ literal_->IsAboveMax() || literal_->IsBelowMin()) {
+ return std::partial_ordering::unordered;
+ }
+ auto compare = [&]<typename ScalarT, typename LiteralT>(
+ auto&& order) -> std::optional<std::partial_ordering> {
+ const auto* lhs = std::get_if<ScalarT>(&value);
+ const auto* rhs = std::get_if<LiteralT>(&literal);
+ if (lhs == nullptr || rhs == nullptr) {
+ return std::nullopt;
+ }
+ return order(*lhs, *rhs);
+ };
+ auto three_way = [](const auto& lhs, const auto& rhs) ->
std::partial_ordering {
+ return lhs <=> rhs;
+ };
+ auto total_order = [](auto lhs, auto rhs) -> std::partial_ordering {
+ return std::strong_order(lhs, rhs);
+ };
+ auto bytes = [](std::string_view lhs, const auto& rhs) ->
std::partial_ordering {
+ return CompareBytes(lhs, rhs.data(), rhs.size());
+ };
+
+ switch (type_id_) {
+ case TypeId::kBoolean:
+ return compare.template operator()<bool, bool>(three_way);
+ case TypeId::kInt:
+ case TypeId::kDate:
+ return compare.template operator()<int32_t, int32_t>(three_way);
+ case TypeId::kLong:
+ case TypeId::kTime:
+ case TypeId::kTimestamp:
+ case TypeId::kTimestampTz:
+ case TypeId::kTimestampNs:
+ case TypeId::kTimestampTzNs:
+ return compare.template operator()<int64_t, int64_t>(three_way);
+ case TypeId::kFloat:
+ return compare.template operator()<float, float>(total_order);
+ case TypeId::kDouble:
+ return compare.template operator()<double, double>(total_order);
+ case TypeId::kDecimal:
+ return compare.template operator()<Decimal, Decimal>(
+ [this](const Decimal& lhs, const Decimal& rhs) {
+ return Decimal::Compare(lhs, rhs, scale_, literal_scale_);
+ });
+ case TypeId::kString:
+ return compare.template operator()<std::string_view,
std::string>(bytes);
+ case TypeId::kBinary:
+ case TypeId::kFixed:
+ return compare.template operator()<std::string_view,
std::vector<uint8_t>>(bytes);
+ case TypeId::kUuid: {
+ // Literal conversion rejects values that are not 16 bytes; let it
report that.
+ const auto* raw = std::get_if<std::string_view>(&value);
+ if (raw == nullptr || raw->size() != Uuid::kLength) {
+ return std::nullopt;
+ }
+ return compare.template operator()<std::string_view, Uuid>(
+ [](std::string_view lhs, const Uuid& rhs) -> std::partial_ordering
{
+ return CompareBytes(lhs, rhs.bytes().data(), Uuid::kLength);
+ });
+ }
+ default:
+ return std::nullopt;
+ }
+ }
+
+ // Reads the referenced field's raw scalar from a row. Owned by the bound
+ // reference, which the evaluator keeps alive through its bound expression.
+ const StructLikeAccessor& accessor_;
+ // The field's type, which selects the scalar representation to compare.
+ TypeId type_id_;
+ // The field's decimal scale, or 0 for other types.
+ int32_t scale_;
+ // The predicate operation, e.g. kLt or kIsNull.
+ Operation op_;
+ // The literal to compare with, or nullptr for unary predicates. Owned by the
+ // bound predicate, which the evaluator keeps alive.
+ const Literal* literal_;
+ // The literal's decimal scale, or 0 for other types or unary predicates.
+ int32_t literal_scale_;
+ // Evaluates the whole predicate with Literal semantics for rows whose scalar
+ // does not have the field type's representation, so they keep the same
result
+ // or error as before.
+ VisitorNode fallback_;
+};
+
+// Returns a fast node for a predicate on a field reference, or nullptr.
+NodePtr CompileReferencePredicate(const std::shared_ptr<Expression>& expr) {
+ const auto* predicate = dynamic_cast<const BoundPredicate*>(expr.get());
+ if (predicate == nullptr) {
+ return nullptr;
+ }
+ const auto* reference = dynamic_cast<const
BoundReference*>(predicate->term().get());
+ if (reference == nullptr) {
+ return nullptr;
+ }
+ const TypeId type_id = reference->type()->type_id();
+ if (!ReferencePredicateNode::Supports(*predicate, type_id)) {
+ return nullptr;
+ }
+
+ const Literal* literal = nullptr;
+ switch (predicate->kind()) {
+ case BoundPredicate::Kind::kUnary:
+ break;
+ case BoundPredicate::Kind::kLiteral:
+ literal =
+ &internal::checked_cast<const
BoundLiteralPredicate&>(*predicate).literal();
+ // Raw values carry the field's representation, so the literal must
share it.
+ if (literal->type()->type_id() != type_id) {
+ return nullptr;
+ }
+ break;
+ case BoundPredicate::Kind::kSet:
+ return nullptr;
+ }
+ return std::make_unique<ReferencePredicateNode>(*reference, predicate->op(),
literal,
+ expr);
+}
+
+NodePtr Compile(const std::shared_ptr<Expression>& expr) {
+ if (expr->is_bound_predicate()) {
+ if (auto node = CompileReferencePredicate(expr)) {
+ return node;
+ }
+ return std::make_unique<VisitorNode>(expr);
+ }
+ if (expr->is_unbound_predicate() || expr->is_bound_aggregate() ||
+ expr->is_unbound_aggregate()) {
+ return std::make_unique<VisitorNode>(expr);
+ }
+ switch (expr->op()) {
+ case Operation::kTrue:
+ return std::make_unique<ConstantNode>(true);
+ case Operation::kFalse:
+ return std::make_unique<ConstantNode>(false);
+ case Operation::kNot:
+ return std::make_unique<NotNode>(
+ Compile(internal::checked_pointer_cast<Not>(expr)->child()));
+ case Operation::kAnd: {
+ const auto& and_expr = internal::checked_pointer_cast<And>(expr);
+ return std::make_unique<AndNode>(Compile(and_expr->left()),
+ Compile(and_expr->right()));
+ }
+ case Operation::kOr: {
+ const auto& or_expr = internal::checked_pointer_cast<Or>(expr);
+ return std::make_unique<OrNode>(Compile(or_expr->left()),
+ Compile(or_expr->right()));
+ }
+ default:
+ // Reports the visitor's error for unknown operations when evaluated.
+ return std::make_unique<VisitorNode>(expr);
+ }
+}
+
+} // namespace
+
+Evaluator::Evaluator(std::shared_ptr<Expression> bound_expr,
+ std::unique_ptr<const internal::EvaluatorNode> root)
+ : bound_expr_(std::move(bound_expr)), root_(std::move(root)) {}
Evaluator::~Evaluator() = default;
@@ -148,12 +563,13 @@ Result<std::unique_ptr<Evaluator>> Evaluator::Make(const
Schema& schema,
std::shared_ptr<Expression>
unbound,
bool case_sensitive) {
ICEBERG_ASSIGN_OR_RAISE(auto bound_expr, Binder::Bind(schema, unbound,
case_sensitive));
- return std::unique_ptr<Evaluator>(new Evaluator(std::move(bound_expr)));
+ auto root = Compile(bound_expr);
+ return std::unique_ptr<Evaluator>(
+ new Evaluator(std::move(bound_expr), std::move(root)));
}
Result<bool> Evaluator::Evaluate(const StructLike& row) const {
- EvalVisitor visitor(row);
- return Visit<bool, EvalVisitor>(bound_expr_, visitor);
+ return root_->Evaluate(row);
}
} // namespace iceberg
diff --git a/src/iceberg/expression/evaluator.h
b/src/iceberg/expression/evaluator.h
index aca862e4..698c6f0f 100644
--- a/src/iceberg/expression/evaluator.h
+++ b/src/iceberg/expression/evaluator.h
@@ -30,6 +30,10 @@
namespace iceberg {
+namespace internal {
+class EvaluatorNode;
+} // namespace internal
+
/// \brief Evaluates an Expression against data rows.
///
/// This class evaluates bound expressions against StructLike data rows to
determine
@@ -57,9 +61,14 @@ class ICEBERG_EXPORT Evaluator {
Result<bool> Evaluate(const StructLike& row) const;
private:
- explicit Evaluator(std::shared_ptr<Expression> bound_expr);
+ Evaluator(std::shared_ptr<Expression> bound_expr,
+ std::unique_ptr<const internal::EvaluatorNode> root);
+ // Owns the bound expression that the compiled nodes refer to.
std::shared_ptr<Expression> bound_expr_;
+ // The bound expression compiled once into evaluation nodes, so evaluating a
row
+ // does not traverse or cast the expression tree.
+ std::unique_ptr<const internal::EvaluatorNode> root_;
};
} // namespace iceberg
diff --git a/src/iceberg/test/evaluator_test.cc
b/src/iceberg/test/evaluator_test.cc
index beda8085..b0e9af20 100644
--- a/src/iceberg/test/evaluator_test.cc
+++ b/src/iceberg/test/evaluator_test.cc
@@ -19,10 +19,18 @@
#include "iceberg/expression/evaluator.h"
+#include <array>
+#include <cmath>
#include <cstddef>
+#include <cstdint>
+#include <exception>
+#include <format>
#include <limits>
#include <memory>
#include <string>
+#include <string_view>
+#include <utility>
+#include <variant>
#include <vector>
#include <arrow/array.h>
@@ -34,15 +42,20 @@
#include <gtest/gtest.h>
#include "iceberg/arrow_c_data_guard_internal.h"
+#include "iceberg/expression/binder.h"
#include "iceberg/expression/expressions.h"
#include "iceberg/expression/literal.h"
+#include "iceberg/expression/predicate.h"
#include "iceberg/expression/rewrite_not.h"
+#include "iceberg/expression/term.h"
#include "iceberg/result.h"
#include "iceberg/row/arrow_array_wrapper.h"
+#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/uuid.h"
namespace iceberg {
@@ -1019,4 +1032,237 @@ TEST_F(EvaluatorTest, InExceptions) {
}
}
+namespace {
+
+// A row of raw scalars, one per top-level field.
+class ScalarRow : public StructLike {
+ public:
+ explicit ScalarRow(std::vector<Scalar> values) : values_(std::move(values))
{}
+ Result<Scalar> GetField(size_t pos) const override { return values_.at(pos);
}
+ size_t num_fields() const override { return values_.size(); }
+
+ private:
+ std::vector<Scalar> values_;
+};
+
+// One column under test: its type, row values, and literals to compare with.
+struct ColumnCase {
+ std::shared_ptr<PrimitiveType> type;
+ std::vector<Scalar> values;
+ std::vector<Literal> literals;
+};
+
+std::string Bytes(std::initializer_list<int> bytes) {
+ std::string result;
+ for (int byte : bytes) {
+ result.push_back(static_cast<char>(byte));
+ }
+ return result;
+}
+
+std::vector<uint8_t> ByteVector(std::string_view bytes) {
+ return {bytes.begin(), bytes.end()};
+}
+
+} // namespace
+
+// The evaluator compares raw scalars for reference predicates. It must match
the
+// literal-based semantics of BoundPredicate::Test for every type, operation,
and
+// edge value, including nulls, NaNs, signed zeros, and unsigned byte order.
+TEST(EvaluatorRawComparisonTest, MatchesLiteralSemantics) {
+ const float nan_f = std::numeric_limits<float>::quiet_NaN();
+ const double nan_d = std::numeric_limits<double>::quiet_NaN();
+ const double inf = std::numeric_limits<double>::infinity();
+ const std::string high = Bytes({0xff, 0x01});
+ const std::string low = Bytes({0x01, 0xff});
+ static const std::array<std::string, 7> kStrings = {"", "a", "ab", "abc",
+ "b", high, low};
+ auto uuid_a =
Uuid::FromString("123e4567-e89b-12d3-a456-426614174000").value();
+ auto uuid_b =
Uuid::FromString("f23e4567-e89b-12d3-a456-426614174000").value();
+ static std::string uuid_a_bytes;
+ static std::string uuid_b_bytes;
+ uuid_a_bytes.assign(reinterpret_cast<const char*>(uuid_a.bytes().data()),
16);
+ uuid_b_bytes.assign(reinterpret_cast<const char*>(uuid_b.bytes().data()),
16);
+
+ std::vector<ColumnCase> cases;
+ cases.push_back({.type = boolean(),
+ .values = {std::monostate{}, false, true},
+ .literals = {Literal::Boolean(false),
Literal::Boolean(true)}});
+ cases.push_back({.type = int32(),
+ .values = {std::monostate{}, int32_t{-5}, int32_t{0},
int32_t{7},
+ std::numeric_limits<int32_t>::max()},
+ .literals = {Literal::Int(0), Literal::Int(7),
Literal::Int(-100)}});
+ cases.push_back({.type = date(),
+ .values = {std::monostate{}, int32_t{18000},
int32_t{19000}},
+ .literals = {Literal::Date(18500), Literal::Date(18000)}});
+ cases.push_back(
+ {.type = int64(),
+ .values = {std::monostate{}, int64_t{-1}, int64_t{0}, int64_t{1} << 40},
+ .literals = {Literal::Long(0), Literal::Long(int64_t{1} << 40)}});
+ cases.push_back({.type = timestamp(),
+ .values = {std::monostate{}, int64_t{1000}, int64_t{2000}},
+ .literals = {Literal::Timestamp(1500),
Literal::Timestamp(2000)}});
+ cases.push_back({.type = timestamp_tz(),
+ .values = {std::monostate{}, int64_t{1000}},
+ .literals = {Literal::TimestampTz(1000)}});
+ cases.push_back({.type = time(),
+ .values = {std::monostate{}, int64_t{5}},
+ .literals = {Literal::Time(6)}});
+ cases.push_back(
+ {.type = float32(),
+ .values = {std::monostate{}, -0.0f, 0.0f, 1.5f, nan_f, -nan_f,
+ std::numeric_limits<float>::infinity()},
+ .literals = {Literal::Float(0.0f), Literal::Float(-0.0f),
Literal::Float(1.5f)}});
+ cases.push_back({.type = float64(),
+ .values = {std::monostate{}, -0.0, 0.0, -inf, inf, nan_d,
2.25},
+ .literals = {Literal::Double(0.0), Literal::Double(-0.0),
+ Literal::Double(2.25), Literal::Double(inf)}});
+ cases.push_back({.type = decimal(9, 2),
+ .values = {std::monostate{}, Decimal(int128_t{-150}),
+ Decimal(int128_t{0}), Decimal(int128_t{12345})},
+ .literals = {Literal::Decimal(0, 9, 2),
Literal::Decimal(12345, 9, 2),
+ Literal::Decimal(-151, 9, 2)}});
+ std::vector<Scalar> strings{std::monostate{}};
+ for (const auto& value : kStrings) {
+ strings.emplace_back(std::string_view(value));
+ }
+ cases.push_back(
+ {.type = string(),
+ .values = strings,
+ .literals = {Literal::String(""), Literal::String("a"),
Literal::String("ab"),
+ Literal::String(high), Literal::String("b")}});
+ cases.push_back({.type = binary(),
+ .values = strings,
+ .literals = {Literal::Binary({}),
Literal::Binary(ByteVector("ab")),
+ Literal::Binary(ByteVector(high)),
+ Literal::Binary(ByteVector(low))}});
+ static const std::array<std::string, 3> kFixed = {"abc", "abd",
+ Bytes({0xff, 0x00, 0x00})};
+ std::vector<Scalar> fixed_values{std::monostate{}};
+ for (const auto& value : kFixed) {
+ fixed_values.emplace_back(std::string_view(value));
+ }
+ cases.push_back({.type = fixed(3),
+ .values = fixed_values,
+ .literals = {Literal::Fixed(ByteVector("abd")),
+ Literal::Fixed(ByteVector(Bytes({0xff, 0x00,
0x00})))}});
+ cases.push_back({.type = uuid(),
+ .values = {std::monostate{}, std::string_view(uuid_a_bytes),
+ std::string_view(uuid_b_bytes)},
+ .literals = {Literal::UUID(uuid_a),
Literal::UUID(uuid_b)}});
+
+ using Op = Expression::Operation;
+ const std::array literal_ops = {Op::kLt, Op::kLtEq, Op::kGt,
+ Op::kGtEq, Op::kEq,
Op::kNotEq,
+ Op::kStartsWith, Op::kNotStartsWith};
+ const std::array unary_ops = {Op::kIsNull, Op::kNotNull, Op::kIsNan,
Op::kNotNan};
+
+ int checked = 0;
+ for (const auto& column : cases) {
+ Schema schema({SchemaField::MakeOptional(1, "c", column.type)});
+ std::vector<std::shared_ptr<Expression>> predicates;
+ for (Op op : unary_ops) {
+ predicates.push_back(Expressions::Predicate(op, "c"));
+ }
+ for (const auto& literal : column.literals) {
+ for (Op op : literal_ops) {
+ predicates.push_back(Expressions::Predicate(op, "c", literal));
+ }
+ }
+ for (const auto& unbound : predicates) {
+ auto bound = Binder::Bind(schema, unbound, /*case_sensitive=*/true);
+ auto evaluator = Evaluator::Make(schema, unbound);
+ if (!bound.has_value()) {
+ // Invalid for this type, e.g. starts_with on an int.
+ EXPECT_FALSE(evaluator.has_value()) << unbound->ToString();
+ continue;
+ }
+ ASSERT_TRUE(evaluator.has_value()) << evaluator.error().message;
+ for (const auto& value : column.values) {
+ ScalarRow row({value});
+ SCOPED_TRACE(
+ std::format("{} on {}", unbound->ToString(),
column.type->ToString()));
+ Result<bool> expected = false;
+ if ((*bound)->op() == Op::kTrue || (*bound)->op() == Op::kFalse) {
+ expected = (*bound)->op() == Op::kTrue;
+ } else {
+ const auto& predicate =
std::dynamic_pointer_cast<BoundPredicate>(*bound);
+ ASSERT_NE(predicate, nullptr) << (*bound)->ToString();
+ auto literal = predicate->term()->Evaluate(row);
+ ASSERT_TRUE(literal.has_value()) << literal.error().message;
+ expected = predicate->Test(*literal);
+ }
+ auto actual = (*evaluator)->Evaluate(row);
+ ASSERT_EQ(expected.has_value(), actual.has_value());
+ if (expected.has_value()) {
+ EXPECT_EQ(*expected, *actual)
+ << "row value index in " << column.type->ToString();
+ }
+ ++checked;
+ }
+ }
+ }
+ EXPECT_GT(checked, 1000);
+}
+
+TEST(EvaluatorRawComparisonTest, RejectsUnaryOperationOnLiteralPredicate) {
+ Schema schema({SchemaField::MakeOptional(1, "id", int32())});
+ auto expr = Expressions::Predicate(Expression::Operation::kIsNull, "id",
+ std::vector<Literal>{Literal::Int(1)});
+ ICEBERG_UNWRAP_OR_FAIL(auto evaluator, Evaluator::Make(schema, expr));
+ EXPECT_THAT(evaluator->Evaluate(ScalarRow({int32_t{1}})),
+ IsError(ErrorKind::kInvalidExpression));
+}
+
+TEST(EvaluatorRawComparisonTest, NanPredicatesRejectMismatchedFloatTypes) {
+ Schema schema({SchemaField::MakeOptional(1, "f", float32()),
+ SchemaField::MakeOptional(2, "d", float64())});
+ ScalarRow row({std::numeric_limits<double>::quiet_NaN(),
+ std::numeric_limits<float>::quiet_NaN()});
+ for (auto op : {Expression::Operation::kIsNan,
Expression::Operation::kNotNan}) {
+ for (const auto* field : {"f", "d"}) {
+ auto expr = Expressions::Predicate(op, field);
+ SCOPED_TRACE(expr->ToString());
+ ICEBERG_UNWRAP_OR_FAIL(auto evaluator, Evaluator::Make(schema, expr));
+ EXPECT_THROW(static_cast<void>(evaluator->Evaluate(row)),
std::bad_variant_access);
+ }
+ }
+}
+
+TEST(EvaluatorRawComparisonTest, CompoundExpressionsKeepErrorsFromBothSides) {
+ Schema schema({SchemaField::MakeRequired(1, "id", int32()),
+ SchemaField::MakeOptional(2, "name", string())});
+ // A required field that is null is an error. The left side is false, but the
+ // right side is still evaluated, as before.
+ auto expr = Expressions::And(Expressions::Equal("name",
Literal::String("x")),
+ Expressions::GreaterThan("id",
Literal::Int(0)));
+ ICEBERG_UNWRAP_OR_FAIL(auto evaluator, Evaluator::Make(schema, expr));
+ ScalarRow bad_row({std::monostate{}, std::string_view("y")});
+ EXPECT_FALSE(evaluator->Evaluate(bad_row).has_value());
+ ScalarRow good_row({int32_t{1}, std::string_view("x")});
+ EXPECT_THAT(evaluator->Evaluate(good_row), HasValue(::testing::Eq(true)));
+}
+
+TEST(EvaluatorRawComparisonTest, TransformsAndSetsUseLiteralEvaluation) {
+ Schema schema({SchemaField::MakeOptional(1, "id", int32())});
+ auto in = Expressions::In("id", {Literal::Int(1), Literal::Int(3)});
+ ICEBERG_UNWRAP_OR_FAIL(auto in_evaluator, Evaluator::Make(schema, in));
+ EXPECT_THAT(in_evaluator->Evaluate(ScalarRow({int32_t{3}})),
+ HasValue(::testing::Eq(true)));
+ EXPECT_THAT(in_evaluator->Evaluate(ScalarRow({int32_t{2}})),
+ HasValue(::testing::Eq(false)));
+ EXPECT_THAT(in_evaluator->Evaluate(ScalarRow({std::monostate{}})),
+ HasValue(::testing::Eq(false)));
+
+ auto bucket = Expressions::Equal(
+ std::shared_ptr<UnboundTerm<BoundTransform>>(Expressions::Bucket("id",
4)),
+ Literal::Int(3));
+ ICEBERG_UNWRAP_OR_FAIL(auto bucket_evaluator, Evaluator::Make(schema,
bucket));
+ // bucket[4](34) is 3 and bucket[4](0) is 0.
+ EXPECT_THAT(bucket_evaluator->Evaluate(ScalarRow({int32_t{34}})),
+ HasValue(::testing::Eq(true)));
+ EXPECT_THAT(bucket_evaluator->Evaluate(ScalarRow({int32_t{0}})),
+ HasValue(::testing::Eq(false)));
+}
+
} // namespace iceberg