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

Gabriel39 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 7dd131e514c [fix](orc) Fall back from floating metadata aggregates 
when NaNs may be hidden (#70930)
7dd131e514c is described below

commit 7dd131e514cfa27ed4d40d15f51b2d1cd68272c0
Author: Gabriel <[email protected]>
AuthorDate: Wed Nov 25 15:00:48 2026 +0800

    [fix](orc) Fall back from floating metadata aggregates when NaNs may be 
hidden (#70930)
    
    ### Background
    
    The native ORC reader can answer MIN/MAX from selected stripe statistics
    instead of decoding rows. ORC floating statistics also contain an
    optional sum, which standard writers make NaN when a stripe contains a
    NaN.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #65183 (introduced native ORC metadata aggregates), #65559
    (4.1 backport)
    PR Type: Bugfix
    
    Problem Summary:
    
    An ORC stripe containing `[1, NaN, 2]` can expose finite bounds, so
    metadata aggregation returns `2` while an ordinary scan returns `NaN`.
    Require an available, finite sum before trusting floating bounds and
    otherwise use the existing row-scan fallback. Most of the diff adds
    tests for the fallback and the finite-value optimization.
    
    | FLOAT and DOUBLE values | MAX before | MAX after / ordinary scan |
    |---|---|---|
    | `1, NaN, 2` | `2` | `NaN` |
    
    ### Details
    
    - **Change map:** Production code +4/-1 lines; tests +649/-2; generated
    regression output +85/-0; no documentation changes. The production
    change is one statistics eligibility guard; the tests author standard
    ORC files and exercise reader fallback, selected stripes and SQL
    aggregates.
    - **Frequency:** Always when native MIN/MAX uses finite floating bounds
    from a selected stripe whose values contain a hidden NaN; reproduced
    with both FLOAT and DOUBLE using standard writers.
    - **Root cause:** `set_floating_zone_map` accepted minimum and maximum
    without checking the sum. A writer can keep finite endpoints after
    observing a NaN, so those endpoints do not preserve row aggregation
    semantics.
    - **Why existing tests missed it:** Existing
    `NewOrcReaderTest.AggregatePushdown*` tests cover primitive and nested
    bounds, stripe selection, timestamps and COUNT without floating NaNs.
    Iceberg regressions such as `test_iceberg_orc_decimal_bounds` check
    decimal metadata rather than floating MIN/MAX; fuzzy floating
    comparisons can also miss a NaN mismatch. New SQL tests compare strings
    and NaN flags explicitly.
    - **Fix:** Reject missing or non-finite floating sums at native metadata
    conversion. This conservatively scans infinities and sum overflows as
    well, while finite sums retain metadata aggregation. COUNT, integer
    bounds and ordinary ORC predicate pruning retain their existing
    behavior.
    - **Other paths and branches:** The conversion is shared by native ORC
    catalog scans, including Iceberg and Hive. It has one aggregate call
    site; ordinary ORC SARG pruning uses the SDK separately. Parquet
    metadata aggregation uses a separate implementation. Static inspection
    finds the same unchecked guard in branch-4.1 and branch-4.2; branch-3.1
    and branch-4.0 lack this native path. Release branches were not executed
    locally.
    
    ### Testing
    
    - Local ASAN: all 201 `NewOrcReaderTest` tests passed. Four new tests
    cover 24 floating-statistics inputs, real `TableReader` fallback without
    losing NaNs or rows, valid missing-sum compatibility files, and
    safe/unsafe stripe selection and pruning. The new cases fail against the
    original guard.
    - Local launcher reproduction: interpolated arguments trigger
    ArrayStoreException before normalization; literal arguments and
    child-command errors pass afterward.
    - Local native SQL: `test_iceberg_orc_floating_minmax` fails before the
    fix (`2` versus `NaN`) and passes after it. Fourteen standard SDK
    fixtures cover NaN positions, NULLs, infinities, overflow, independent
    FLOAT/DOUBLE columns and empty tables. Generated output was
    independently checked against scan results and known fixture counts,
    then replayed normally. The final fixture launcher joins its output
    readers before checking SDK markers.
    - The fixture helper authored and read back all 14 cases with Iceberg
    1.12 and the stock 1.10.1 runtime SDK. No data or statistics editing is
    used for the NaN reproduction.
    
    ### Notes for Reviewers
    
    The missing-sum unit fixture only renames an optional protobuf field
    while preserving bounds and data; it tests compatibility separately from
    standard-writer NaNs. The SQL suite supports an existing Spark/REST
    Docker environment or an explicitly configured local SDK/file warehouse.
    Full Docker fixture execution after argument normalization awaits CI.
    
    ### Release note
    
    Fix incorrect floating MIN/MAX results from ORC stripe metadata when a
    stripe contains NaN values.
    
    ### Check List (For Author)
    
    - Behavior changed: No
    - Does this need documentation: No
    - Pre-submission status: Partially verified: full Docker fixture
    execution after argument normalization awaits CI; command-boundary
    checks and the SQL suite passed locally
    
    ### AI Disclosure
    
    - Tool: Codex (GPT-6)
    - Generated: Code, unit tests, regression tests and this description
    - Human review: not stated
---
 be/src/format_v2/orc/orc_reader.cpp                |   5 +-
 be/test/format_v2/orc/orc_reader_test.cpp          | 382 ++++++++++++++++++++-
 .../iceberg/test_iceberg_orc_floating_minmax.out   |  85 +++++
 .../orc_data/CreateOrcFloatingStatsFixtures.java   | 139 ++++++++
 .../test_iceberg_orc_floating_minmax.groovy        | 130 +++++++
 5 files changed, 738 insertions(+), 3 deletions(-)

diff --git a/be/src/format_v2/orc/orc_reader.cpp 
b/be/src/format_v2/orc/orc_reader.cpp
index de4e50f2778..be8a6441a6e 100644
--- a/be/src/format_v2/orc/orc_reader.cpp
+++ b/be/src/format_v2/orc/orc_reader.cpp
@@ -461,8 +461,11 @@ bool set_boolean_zone_map(const ::orc::ColumnStatistics& 
statistics,
 bool set_floating_zone_map(const ::orc::Type& type, const 
::orc::ColumnStatistics& statistics,
                            segment_v2::ZoneMap* zone_map) {
     const auto* double_statistics = dynamic_cast<const 
::orc::DoubleColumnStatistics*>(&statistics);
+    // A standard writer can give [1, NaN, 2] finite bounds but a NaN sum. 
Without a finite
+    // sum, metadata MIN/MAX cannot preserve the row scanner's NaN ordering.
     if (double_statistics == nullptr || !double_statistics->hasMinimum() ||
-        !double_statistics->hasMaximum()) {
+        !double_statistics->hasMaximum() || !double_statistics->hasSum() ||
+        !std::isfinite(double_statistics->getSum())) {
         return false;
     }
     if (type.getKind() == ::orc::TypeKind::FLOAT) {
diff --git a/be/test/format_v2/orc/orc_reader_test.cpp 
b/be/test/format_v2/orc/orc_reader_test.cpp
index f3d1ae9e0a0..cd9f3e90425 100644
--- a/be/test/format_v2/orc/orc_reader_test.cpp
+++ b/be/test/format_v2/orc/orc_reader_test.cpp
@@ -26,6 +26,7 @@
 #include <array>
 #include <atomic>
 #include <cctype>
+#include <cmath>
 #include <cstdlib>
 #include <cstring>
 #include <filesystem>
@@ -318,7 +319,7 @@ TExprNode make_filter_in_node(TExprNodeType::type 
node_type) {
 
 class NullableInt32GreaterThanExpr final : public VExpr {
 public:
-    NullableInt32GreaterThanExpr(int column_id, int32_t value)
+    NullableInt32GreaterThanExpr(int column_id, int32_t value, const char* 
column_name = "id")
             : VExpr(std::make_shared<DataTypeUInt8>(), false),
               _column_id(column_id),
               _value(value) {
@@ -326,7 +327,7 @@ public:
         _opcode = TExprOpcode::GT;
         const auto int_type = std::make_shared<DataTypeInt32>();
         add_child(TableSlotRef::create_shared(column_id, column_id, -1, 
make_nullable(int_type),
-                                              "id"));
+                                              column_name));
         add_child(TableLiteral::create_shared(int_type, 
Field::create_field<TYPE_INT>(value)));
     }
 
@@ -4512,6 +4513,112 @@ void write_two_stripe_constant_timestamp_file(const 
std::string& file_path,
     out.write(memory_stream.getData(), 
static_cast<std::streamsize>(memory_stream.getLength()));
 }
 
+void write_orc_floating_statistics_file(
+        const std::string& path, bool single_precision,
+        const std::vector<std::vector<std::optional<double>>>& stripes) {
+    const auto type = ::orc::Type::buildTypeFromString(
+            single_precision ? 
"struct<value:float,stripe_id:int,payload:string>"
+                             : 
"struct<value:double,stripe_id:int,payload:string>");
+    MemoryOutputStream output(4 * 1024 * 1024);
+    ::orc::WriterOptions options;
+    options.setCompression(::orc::CompressionKind_NONE);
+    options.setStripeSize(1);
+    options.setDictionaryKeySizeThreshold(0);
+    auto writer = ::orc::createWriter(*type, &output, options);
+    int64_t stripe_id = 0;
+    for (const auto& values : stripes) {
+        auto batch = writer->createRowBatch(values.size());
+        auto& rows = dynamic_cast<::orc::StructVectorBatch&>(*batch);
+        auto& numbers = 
dynamic_cast<::orc::DoubleVectorBatch&>(*rows.fields[0]);
+        auto& ids = dynamic_cast<::orc::LongVectorBatch&>(*rows.fields[1]);
+        auto& payload = 
dynamic_cast<::orc::StringVectorBatch&>(*rows.fields[2]);
+        numbers.hasNulls = std::any_of(values.begin(), values.end(),
+                                       [](const auto& value) { return 
!value.has_value(); });
+        std::vector<std::string> strings;
+        strings.reserve(values.size());
+        for (size_t row = 0; row < values.size(); ++row) {
+            numbers.notNull[row] = values[row].has_value();
+            numbers.data[row] = values[row].value_or(0);
+            ids.data[row] = stripe_id;
+            strings.push_back(std::string(2048, static_cast<char>('a' + row % 
26)));
+            set_string_value(payload, row, strings.back());
+        }
+        rows.numElements = values.size();
+        numbers.numElements = values.size();
+        ids.numElements = values.size();
+        payload.numElements = values.size();
+        writer->add(*batch);
+        ++stripe_id;
+    }
+    writer->close();
+    std::ofstream file(path, std::ios::binary);
+    file.write(output.getData(), 
static_cast<std::streamsize>(output.getLength()));
+}
+
+size_t omit_orc_floating_sum(const std::string& path) {
+    std::ifstream input(path, std::ios::binary | std::ios::ate);
+    const auto size = static_cast<size_t>(input.tellg());
+    input.seekg(0);
+    std::vector<char> data(size);
+    input.read(data.data(), static_cast<std::streamsize>(size));
+    auto reader = 
::orc::createReader(std::make_unique<MemoryInputStream>(data.data(), size),
+                                      ::orc::ReaderOptions());
+    const size_t metadata_size = reader->getStripeStatisticsLength();
+    const size_t begin = size - metadata_size - reader->getFileFooterLength() -
+                         reader->getFilePostscriptLength() - 1;
+    auto varint = [&](size_t& offset) {
+        uint64_t value = 0;
+        for (int shift = 0; shift < 64; shift += 7) {
+            const auto byte = static_cast<uint8_t>(data.at(offset++));
+            value |= static_cast<uint64_t>(byte & 0x7f) << shift;
+            if ((byte & 0x80) == 0) {
+                return value;
+            }
+        }
+        throw std::runtime_error("Invalid fixture protobuf varint");
+    };
+    size_t omitted = 0;
+    auto visit = [&](auto&& self, size_t offset, size_t end, int depth) -> 
void {
+        while (offset < end) {
+            const auto tag_offset = offset;
+            const auto tag = varint(offset);
+            const auto field = tag >> 3;
+            switch (tag & 7) {
+            case 0:
+                varint(offset);
+                break;
+            case 1:
+                if (depth == 3 && field == 3) {
+                    // Rename the optional sum to an unknown fixed64 field 
without changing any lengths.
+                    // This valid compatibility fixture keeps min/max and 
every data stream intact.
+                    data[tag_offset] = 0x79;
+                    ++omitted;
+                }
+                offset += 8;
+                break;
+            case 2: {
+                const auto length = varint(offset);
+                // Metadata.stripeStats -> StripeStatistics.colStats -> 
ColumnStatistics.doubleStatistics.
+                if ((depth < 2 && field == 1) || (depth == 2 && field == 3)) {
+                    self(self, offset, offset + length, depth + 1);
+                }
+                offset += length;
+                break;
+            }
+            case 5:
+                offset += 4;
+                break;
+            default:
+                throw std::runtime_error("Unexpected fixture protobuf wire 
type");
+            }
+        }
+    };
+    visit(visit, begin, begin + metadata_size, 0);
+    std::ofstream output(path, std::ios::binary | std::ios::trunc);
+    output.write(data.data(), static_cast<std::streamsize>(size));
+    return omitted;
+}
+
 uint64_t get_orc_stripe_count(const std::string& file_path) {
     std::ifstream in(file_path, std::ios::binary | std::ios::ate);
     const auto file_size = in.tellg();
@@ -5349,6 +5456,277 @@ TEST_F(NewOrcReaderTest, 
InitReturnsEndOfFileWhenIoContextShouldStop) {
     EXPECT_TRUE(status.is<ErrorCode::END_OF_FILE>()) << status;
 }
 
+TEST_F(NewOrcReaderTest, AggregatePushdownFloatingStatisticsRequireFiniteSums) 
{
+    const double nan = std::numeric_limits<double>::quiet_NaN();
+    const double infinity = std::numeric_limits<double>::infinity();
+    struct Case {
+        std::string name;
+        std::vector<std::optional<double>> values;
+        bool metadata;
+        bool has_values;
+        double minimum = 0;
+        double maximum = 0;
+    };
+    const std::vector<Case> cases {{"finite", {1, -2, 3}, true, true, -2, 3},
+                                   {"finite_nullable", {std::nullopt, 1, 2}, 
true, true, 1, 2},
+                                   {"all_null", {std::nullopt, std::nullopt}, 
false, false},
+                                   {"nan_middle", {1, nan, 2}, false, true},
+                                   {"nan_last", {1, 2, nan}, false, true},
+                                   {"nan_first", {nan, 1, 2}, false, true},
+                                   {"all_nan", {nan, nan}, false, true},
+                                   {"nan_nullable", {std::nullopt, 1, nan, 2}, 
false, true},
+                                   {"positive_infinity", {1, infinity}, false, 
true},
+                                   {"negative_infinity", {-infinity, 2}, 
false, true},
+                                   {"opposite_infinities", {-infinity, 
infinity}, false, true}};
+    for (bool single_precision : {false, true}) {
+        auto inputs = cases;
+        if (!single_precision) {
+            inputs.push_back(
+                    {"sum_overflow",
+                     {std::numeric_limits<double>::max(), 
std::numeric_limits<double>::max()},
+                     false,
+                     true});
+        } else {
+            const double maximum = std::numeric_limits<float>::max();
+            inputs.push_back(
+                    {"finite_float_max", {maximum, maximum}, true, true, 
maximum, maximum});
+        }
+        for (const auto& input : inputs) {
+            SCOPED_TRACE(input.name + (single_precision ? " float" : " 
double"));
+            const auto path =
+                    (_test_dir / (input.name + (single_precision ? "_f.orc" : 
"_d.orc"))).string();
+            write_orc_floating_statistics_file(path, single_precision, 
{input.values});
+            auto reader = create_reader_for_path(path);
+            RuntimeState state {TQueryOptions(), TQueryGlobals()};
+            ASSERT_TRUE(reader->init(&state).ok());
+            auto request = std::make_shared<format::FileScanRequest>();
+            request->non_predicate_columns = {field_projection(0)};
+            ASSERT_TRUE(reader->open(request).ok());
+            format::FileAggregateRequest aggregate_request;
+            aggregate_request.agg_type = TPushAggOp::MINMAX;
+            aggregate_request.columns.push_back({.projection = 
field_projection(0)});
+            format::FileAggregateResult result;
+            auto status = reader->get_aggregate_result(aggregate_request, 
&result);
+            if (!input.metadata) {
+                EXPECT_TRUE(status.is<ErrorCode::NOT_IMPLEMENTED_ERROR>()) << 
status;
+                continue;
+            }
+            ASSERT_TRUE(status.ok()) << status;
+            EXPECT_EQ(result.count, input.values.size());
+            ASSERT_EQ(result.columns.size(), 1);
+            EXPECT_EQ(result.columns[0].has_min, input.has_values);
+            EXPECT_EQ(result.columns[0].has_max, input.has_values);
+            if (input.has_values) {
+                const double minimum =
+                        single_precision
+                                ? 
static_cast<double>(result.columns[0].min_value.get<TYPE_FLOAT>())
+                                : 
result.columns[0].min_value.get<TYPE_DOUBLE>();
+                const double maximum =
+                        single_precision
+                                ? 
static_cast<double>(result.columns[0].max_value.get<TYPE_FLOAT>())
+                                : 
result.columns[0].max_value.get<TYPE_DOUBLE>();
+                EXPECT_DOUBLE_EQ(minimum, input.minimum);
+                EXPECT_DOUBLE_EQ(maximum, input.maximum);
+            }
+        }
+    }
+}
+
+TEST_F(NewOrcReaderTest, MetadataFloatingFallbackPreservesRowsAndNaN) {
+    for (bool single_precision : {false, true}) {
+        for (bool include_nan : {false, true}) {
+            SCOPED_TRACE(single_precision);
+            SCOPED_TRACE(include_nan);
+            // Give each fixture its own identity: metadata cache keys can 
fall back to path and size.
+            const auto path = (_test_dir / (std::string("floating_metadata_") +
+                                            (single_precision ? "float_" : 
"double_") +
+                                            (include_nan ? "nan.orc" : 
"finite.orc")))
+                                      .string();
+            write_orc_floating_statistics_file(
+                    path, single_precision,
+                    {{{1}, {include_nan ? 
std::numeric_limits<double>::quiet_NaN() : 3}, {2}}});
+            RuntimeState state {TQueryOptions(), TQueryGlobals()};
+            format::ColumnDefinition column;
+            column.identifier = Field::create_field<TYPE_STRING>("value");
+            column.name = "value";
+            column.type = single_precision ? 
make_nullable(std::make_shared<DataTypeFloat32>())
+                                           : 
make_nullable(std::make_shared<DataTypeFloat64>());
+            format::TableReader reader;
+            ASSERT_TRUE(reader.init({.projected_columns = {column},
+                                     .conjuncts = {},
+                                     .format = format::FileFormat::ORC,
+                                     .scan_params = nullptr,
+                                     .io_ctx = nullptr,
+                                     .runtime_state = &state,
+                                     .scanner_profile = nullptr,
+                                     .push_down_agg_type = TPushAggOp::MINMAX})
+                                .ok());
+            format::SplitReadOptions options;
+            options.current_split_format = format::FileFormat::ORC;
+            options.current_range.__set_path(path);
+            
options.current_range.__set_file_size(std::filesystem::file_size(path));
+            options.current_range.__set_start_offset(0);
+            options.current_range.__set_size(std::filesystem::file_size(path));
+            ASSERT_TRUE(reader.prepare_split(options).ok());
+            FileScanSplit source;
+            source.range = options.current_range;
+            source.is_source_split = true;
+            std::vector<FileScanSplit> children;
+            bool was_split = false;
+            ASSERT_TRUE(reader.build_physical_splits(source, &children, 
&was_split).ok());
+            EXPECT_FALSE(was_split);
+            EXPECT_EQ(reader._metadata_aggregate_result.has_value(), 
!include_nan);
+            Block block = build_file_block({column});
+            bool eos = false;
+            size_t rows = 0;
+            size_t nan_rows = 0;
+            while (!eos) {
+                block.clear_column_data();
+                ASSERT_TRUE(reader.get_block(&block, &eos).ok());
+                const auto& nullable =
+                        assert_cast<const 
ColumnNullable&>(*block.get_by_position(0).column);
+                for (size_t row = 0; row < block.rows(); ++row) {
+                    ASSERT_FALSE(nullable.is_null_at(row));
+                    const double value =
+                            single_precision
+                                    ? static_cast<double>(assert_cast<const 
ColumnFloat32&>(
+                                                                  
nullable.get_nested_column())
+                                                                  
.get_data()[row])
+                                    : assert_cast<const ColumnFloat64&>(
+                                              nullable.get_nested_column())
+                                              .get_data()[row];
+                    nan_rows += std::isnan(value);
+                }
+                rows += block.rows();
+            }
+            EXPECT_EQ(rows, include_nan ? 3 : 2);
+            EXPECT_EQ(nan_rows, include_nan ? 1 : 0);
+            ASSERT_TRUE(reader.close().ok());
+        }
+    }
+}
+
+TEST_F(NewOrcReaderTest, 
AggregatePushdownFloatingMissingSumFallsBackOnValidFile) {
+    for (bool single_precision : {false, true}) {
+        const auto path =
+                (_test_dir / (single_precision ? "floating_no_sum_f.orc" : 
"floating_no_sum_d.orc"))
+                        .string();
+        write_orc_floating_statistics_file(path, single_precision, {{{1}, {2}, 
{3}}});
+        ASSERT_EQ(omit_orc_floating_sum(path), 1);
+        auto physical_reader =
+                ::orc::createReader(::orc::readLocalFile(path), 
::orc::ReaderOptions());
+        auto statistics = physical_reader->getStripeStatistics(0);
+        const auto* numbers = dynamic_cast<const 
::orc::DoubleColumnStatistics*>(
+                statistics->getColumnStatistics(1));
+        ASSERT_NE(numbers, nullptr);
+        ASSERT_TRUE(numbers->hasMinimum());
+        ASSERT_TRUE(numbers->hasMaximum());
+        EXPECT_DOUBLE_EQ(numbers->getMinimum(), 1);
+        EXPECT_DOUBLE_EQ(numbers->getMaximum(), 3);
+        EXPECT_FALSE(numbers->hasSum());
+
+        auto reader = create_reader_for_path(path);
+        RuntimeState state {TQueryOptions(), TQueryGlobals()};
+        ASSERT_TRUE(reader->init(&state).ok());
+        auto request = std::make_shared<format::FileScanRequest>();
+        request->non_predicate_columns = {field_projection(0)};
+        ASSERT_TRUE(reader->open(request).ok());
+        format::FileAggregateRequest aggregate_request;
+        aggregate_request.agg_type = TPushAggOp::MINMAX;
+        aggregate_request.columns.push_back({.projection = 
field_projection(0)});
+        format::FileAggregateResult result;
+        EXPECT_TRUE(reader->get_aggregate_result(aggregate_request, &result)
+                            .is<ErrorCode::NOT_IMPLEMENTED_ERROR>());
+        std::vector<format::ColumnDefinition> schema;
+        ASSERT_TRUE(reader->get_schema(&schema).ok());
+        Block block = build_file_block({schema[0]});
+        size_t rows = 0;
+        bool eof = false;
+        while (!eof) {
+            block.clear_column_data();
+            size_t read_rows = 0;
+            ASSERT_TRUE(reader->get_block(&block, &read_rows, &eof).ok());
+            EXPECT_EQ(block.rows(), read_rows);
+            rows += read_rows;
+        }
+        EXPECT_EQ(rows, 3);
+    }
+}
+
+TEST_F(NewOrcReaderTest, AggregatePushdownFloatingUsesOnlySelectedSafeStripes) 
{
+    for (bool single_precision : {false, true}) {
+        for (bool unsafe_first : {false, true}) {
+            SCOPED_TRACE(single_precision);
+            SCOPED_TRACE(unsafe_first);
+            std::vector<std::optional<double>> unsafe(200, 1);
+            unsafe[1] = std::numeric_limits<double>::quiet_NaN();
+            std::vector<std::optional<double>> safe(200, 1000);
+            const auto path = (_test_dir / (std::string("floating_stripes_") +
+                                            (single_precision ? "float_" : 
"double_") +
+                                            (unsafe_first ? "first.orc" : 
"last.orc")))
+                                      .string();
+            write_orc_floating_statistics_file(
+                    path, single_precision,
+                    unsafe_first ? std::vector {unsafe, safe} : std::vector 
{safe, unsafe});
+            const auto layout = get_orc_stripe_layout(path);
+            ASSERT_EQ(layout.size(), 2);
+            RuntimeState state {TQueryOptions(), TQueryGlobals()};
+            format::FileAggregateRequest aggregate_request;
+            aggregate_request.agg_type = TPushAggOp::MINMAX;
+            aggregate_request.columns.push_back({.projection = 
field_projection(0)});
+            auto aggregate = [&](auto& reader, bool expect_metadata) {
+                format::FileAggregateResult result;
+                const auto status = 
reader->get_aggregate_result(aggregate_request, &result);
+                if (!expect_metadata) {
+                    EXPECT_TRUE(status.template 
is<ErrorCode::NOT_IMPLEMENTED_ERROR>()) << status;
+                    return;
+                }
+                ASSERT_TRUE(status.ok()) << status;
+                EXPECT_EQ(result.count, 200);
+                ASSERT_EQ(result.columns.size(), 1);
+                const auto& bounds = result.columns[0];
+                const double minimum = single_precision
+                                               ? bounds.min_value.template 
get<TYPE_FLOAT>()
+                                               : bounds.min_value.template 
get<TYPE_DOUBLE>();
+                const double maximum = single_precision
+                                               ? bounds.max_value.template 
get<TYPE_FLOAT>()
+                                               : bounds.max_value.template 
get<TYPE_DOUBLE>();
+                EXPECT_DOUBLE_EQ(minimum, 1000);
+                EXPECT_DOUBLE_EQ(maximum, 1000);
+            };
+            auto request = std::make_shared<format::FileScanRequest>();
+            request->non_predicate_columns = {field_projection(0)};
+            auto whole = create_reader_for_path(path);
+            ASSERT_TRUE(whole->init(&state).ok());
+            ASSERT_TRUE(whole->open(request).ok());
+            aggregate(whole, false);
+            for (size_t stripe = 0; stripe < layout.size(); ++stripe) {
+                auto selected = create_reader_with_range(path, 
layout[stripe].offset,
+                                                         
layout[stripe].length);
+                ASSERT_TRUE(selected->init(&state).ok());
+                ASSERT_TRUE(selected->open(request).ok());
+                aggregate(selected, stripe != (unsafe_first ? 0 : 1));
+            }
+            if (unsafe_first) {
+                auto pruned = create_reader_for_path(path);
+                ASSERT_TRUE(pruned->init(&state).ok());
+                std::vector<format::ColumnDefinition> file_schema;
+                ASSERT_TRUE(pruned->get_schema(&file_schema).ok());
+                ASSERT_EQ(file_schema.size(), 3);
+                auto filtered_request = 
std::make_shared<format::FileScanRequest>();
+                format::FileScanRequestBuilder builder(filtered_request.get());
+                
ASSERT_TRUE(builder.add_non_predicate_column(field_projection(0)).ok());
+                
ASSERT_TRUE(builder.add_predicate_column(field_projection(1)).ok());
+                
filtered_request->conjuncts.push_back(VExprContext::create_shared(
+                        std::make_shared<NullableInt32GreaterThanExpr>(1, 0, 
"stripe_id")));
+                ASSERT_TRUE(pruned->open(filtered_request).ok());
+                aggregate(pruned, true);
+                EXPECT_EQ(pruned->reader_statistics().filtered_row_groups, 1);
+            }
+        }
+    }
+}
+
 TEST_F(NewOrcReaderTest, AggregatePushdownReturnsMinMaxForPrimitiveColumn) {
     const auto multi_stripe_file_path = (_test_dir / 
"aggregate_minmax_int.orc").string();
     write_multi_stripe_orc_int_file(multi_stripe_file_path);
diff --git 
a/regression-test/data/external_table_p0/iceberg/test_iceberg_orc_floating_minmax.out
 
b/regression-test/data/external_table_p0/iceberg/test_iceberg_orc_floating_minmax.out
new file mode 100644
index 00000000000..22e08e61d6d
--- /dev/null
+++ 
b/regression-test/data/external_table_p0/iceberg/test_iceberg_orc_floating_minmax.out
@@ -0,0 +1,85 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !nan_middle --
+1      NaN     true    1       NaN     true
+
+-- !nan_middle_counts --
+3      3       3
+
+-- !nan_last --
+1      NaN     true    1       NaN     true
+
+-- !nan_last_counts --
+3      3       3
+
+-- !nan_first --
+1      NaN     true    1       NaN     true
+
+-- !nan_first_counts --
+3      3       3
+
+-- !all_nan --
+NaN    NaN     true    NaN     NaN     true
+
+-- !all_nan_counts --
+2      2       2
+
+-- !nullable_nan --
+1      NaN     true    1       NaN     true
+
+-- !nullable_nan_counts --
+4      3       3
+
+-- !finite --
+-2     3       false   -2      3       false
+
+-- !finite_counts --
+4      3       3
+
+-- !all_null --
+\N     \N      \N      \N      \N      \N
+
+-- !all_null_counts --
+2      0       0
+
+-- !positive_inf --
+1      Infinity        false   1       Infinity        false
+
+-- !positive_inf_counts --
+2      2       2
+
+-- !negative_inf --
+-Infinity      2       false   -Infinity       2       false
+
+-- !negative_inf_counts --
+2      2       2
+
+-- !opposite_inf --
+-Infinity      Infinity        false   -Infinity       Infinity        false
+
+-- !opposite_inf_counts --
+2      2       2
+
+-- !double_overflow --
+1      2       false   1.7976931348623157e+308 1.7976931348623157e+308 false
+
+-- !double_overflow_counts --
+2      2       2
+
+-- !float_nan_only --
+1      NaN     true    1       3       false
+
+-- !float_nan_only_counts --
+3      3       3
+
+-- !double_nan_only --
+1      3       false   1       NaN     true
+
+-- !double_nan_only_counts --
+3      3       3
+
+-- !empty --
+\N     \N      \N      \N      \N      \N
+
+-- !empty_counts --
+0      0       0
+
diff --git 
a/regression-test/suites/external_table_p0/iceberg/orc_data/CreateOrcFloatingStatsFixtures.java
 
b/regression-test/suites/external_table_p0/iceberg/orc_data/CreateOrcFloatingStatsFixtures.java
new file mode 100644
index 00000000000..f98cbbec556
--- /dev/null
+++ 
b/regression-test/suites/external_table_p0/iceberg/orc_data/CreateOrcFloatingStatsFixtures.java
@@ -0,0 +1,139 @@
+// 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.
+
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.iceberg.CatalogUtil;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.catalog.Catalog;
+import org.apache.iceberg.catalog.Namespace;
+import org.apache.iceberg.catalog.SupportsNamespaces;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.data.GenericRecord;
+import org.apache.iceberg.data.IcebergGenerics;
+import org.apache.iceberg.data.Record;
+import org.apache.iceberg.data.orc.GenericOrcWriter;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.orc.ORC;
+import org.apache.iceberg.types.Types;
+
+/** Standard SDK fixtures; neither data streams nor ORC statistics are edited. 
*/
+public final class CreateOrcFloatingStatsFixtures {
+    private CreateOrcFloatingStatsFixtures() {
+    }
+
+    private static void sameValues(Map<String, Double[][]> cases, String name, 
Double... values) {
+        Double[][] rows = new Double[values.length][2];
+        for (int row = 0; row < values.length; ++row) {
+            rows[row][0] = values[row];
+            rows[row][1] = values[row];
+        }
+        cases.put(name, rows);
+    }
+
+    public static void main(String[] args) throws Exception {
+        Map<String, String> properties = new HashMap<>();
+        if (args.length == 2) {
+            properties.put("type", "hadoop");
+            properties.put("warehouse", args[1]);
+        } else {
+            properties.put("type", "rest");
+            properties.put("uri", "http://rest:8181";);
+            properties.put("warehouse", "s3://warehouse/wh/");
+            properties.put("io-impl", "org.apache.iceberg.aws.s3.S3FileIO");
+            properties.put("s3.endpoint", "http://minio:9000";);
+            properties.put("s3.path-style-access", "true");
+            properties.put("s3.region", "us-east-1");
+        }
+        Catalog catalog = CatalogUtil.buildIcebergCatalog("orc_stats", 
properties, new Configuration());
+        try (AutoCloseable ignored = (AutoCloseable) catalog) {
+            Namespace namespace = Namespace.of(args[0]);
+            SupportsNamespaces namespaces = (SupportsNamespaces) catalog;
+            if (!namespaces.namespaceExists(namespace)) {
+                namespaces.createNamespace(namespace);
+            }
+            Map<String, Double[][]> cases = new LinkedHashMap<>();
+            sameValues(cases, "nan_middle", 1.0, Double.NaN, 2.0);
+            sameValues(cases, "nan_last", 1.0, 2.0, Double.NaN);
+            sameValues(cases, "nan_first", Double.NaN, 1.0, 2.0);
+            sameValues(cases, "all_nan", Double.NaN, Double.NaN);
+            sameValues(cases, "nullable_nan", null, 1.0, Double.NaN, 2.0);
+            sameValues(cases, "finite", null, -2.0, 3.0, 1.0);
+            sameValues(cases, "all_null", null, null);
+            sameValues(cases, "positive_inf", 1.0, Double.POSITIVE_INFINITY);
+            sameValues(cases, "negative_inf", Double.NEGATIVE_INFINITY, 2.0);
+            sameValues(cases, "opposite_inf", Double.NEGATIVE_INFINITY, 
Double.POSITIVE_INFINITY);
+            cases.put("double_overflow", new Double[][] {{1.0, 
Double.MAX_VALUE}, {2.0, Double.MAX_VALUE}});
+            cases.put("float_nan_only", new Double[][] {{1.0, 1.0}, 
{Double.NaN, 2.0}, {2.0, 3.0}});
+            cases.put("double_nan_only", new Double[][] {{1.0, 1.0}, {2.0, 
Double.NaN}, {3.0, 2.0}});
+            sameValues(cases, "empty");
+            Schema schema = new Schema(Types.NestedField.required(1, "id", 
Types.IntegerType.get()),
+                    Types.NestedField.optional(2, "f", Types.FloatType.get()),
+                    Types.NestedField.optional(3, "d", 
Types.DoubleType.get()));
+            for (Map.Entry<String, Double[][]> entry : cases.entrySet()) {
+                TableIdentifier identifier = TableIdentifier.of(namespace, 
entry.getKey());
+                catalog.dropTable(identifier, true);
+                Table table = catalog.createTable(identifier, schema, 
PartitionSpec.unpartitioned(),
+                        Map.of("format-version", "3", "write.format.default", 
"orc"));
+                OutputFile file = table.io().newOutputFile(table.location() + 
"/data/" + UUID.randomUUID() + ".orc");
+                FileAppender<Record> appender = ORC.write(file).schema(schema)
+                        
.createWriterFunc(GenericOrcWriter::buildWriter).build();
+                Double[][] rows = entry.getValue();
+                try (FileAppender<Record> writer = appender) {
+                    for (int id = 0; id < rows.length; ++id) {
+                        GenericRecord record = GenericRecord.create(schema);
+                        record.setField("id", id);
+                        record.setField("f", rows[id][0] == null ? null : 
rows[id][0].floatValue());
+                        record.setField("d", rows[id][1]);
+                        writer.add(record);
+                    }
+                }
+                // Column metrics are optional. Omitting them makes SQL reach 
physical ORC statistics.
+                
table.newAppend().appendFile(DataFiles.builder(table.spec()).withPath(file.location())
+                        
.withFormat(FileFormat.ORC).withRecordCount(rows.length)
+                        
.withFileSizeInBytes(appender.length()).build()).commit();
+                int seen = 0;
+                try (CloseableIterable<Record> records = 
IcebergGenerics.read(table).build()) {
+                    for (Record record : records) {
+                        Float expectedFloat = rows[seen][0] == null ? null : 
rows[seen][0].floatValue();
+                        if (!Objects.equals(record.getField("id"), seen)
+                                || !Objects.equals(record.getField("f"), 
expectedFloat)
+                                || !Objects.equals(record.getField("d"), 
rows[seen][1])) {
+                            throw new IllegalStateException("SDK row mismatch 
for " + entry.getKey() + " at " + seen);
+                        }
+                        ++seen;
+                    }
+                }
+                if (seen != rows.length) {
+                    throw new IllegalStateException("SDK row count mismatch 
for " + entry.getKey());
+                }
+                System.out.println("ORC_STATS_FIXTURE " + entry.getKey() + " " 
+ seen);
+            }
+        }
+    }
+}
diff --git 
a/regression-test/suites/external_table_p0/iceberg/test_iceberg_orc_floating_minmax.groovy
 
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_orc_floating_minmax.groovy
new file mode 100644
index 00000000000..035bab5422b
--- /dev/null
+++ 
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_orc_floating_minmax.groovy
@@ -0,0 +1,130 @@
+// 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.
+
+suite("test_iceberg_orc_floating_minmax", 
"p0,external,iceberg,external_docker,external_docker_iceberg") {
+    String sdk = context.config.otherConfigs.get("icebergFixtureSdkDir")
+    String warehouse = 
context.config.otherConfigs.get("icebergFixtureWarehouse")
+    boolean local = sdk != null && warehouse != null
+    assertTrue((sdk == null) == (warehouse == null), "Set both local fixture 
SDK and warehouse")
+    if (!local && 
!"true".equalsIgnoreCase(context.config.otherConfigs.get("enableIcebergTest"))) 
{
+        logger.info("disable iceberg test")
+        return
+    }
+    def execute = { List<String> command ->
+        StringBuilder stdout = new StringBuilder()
+        StringBuilder stderr = new StringBuilder()
+        // List<String> can still contain GStrings; ProcessBuilder copies its 
elements into String[].
+        def process = new ProcessBuilder(command.collect { it.toString() 
}).start()
+        Thread outputReader = process.consumeProcessOutputStream(stdout)
+        Thread errorReader = process.consumeProcessErrorStream(stderr)
+        process.waitForOrKill(300000)
+        // Process exit can precede output-consumer completion; read every SDK 
marker before checking.
+        outputReader.join()
+        errorReader.join()
+        assertEquals(0, process.exitValue(), "SDK command failed: 
${stderr}\n${stdout}")
+        return stdout.toString()
+    }
+    def shellQuote = { String value -> "'" + value.replace("'", "'\"'\"'") + 
"'" }
+    File source = new File(context.file.parentFile, 
"orc_data/CreateOrcFloatingStatsFixtures.java")
+    String fixtureOutput
+    if (local) {
+        assertTrue(warehouse.startsWith("file:"), "Local SDK mode requires a 
shared file warehouse")
+        File classes = new File(context.file.parentFile, 
".orc_stats_${UUID.randomUUID()}")
+        assertTrue(classes.mkdirs())
+        try {
+            String bin = System.getProperty("java.home") + "/bin/"
+            execute([bin + "javac", "-cp", sdk + "/*", "-d", 
classes.absolutePath, source.absolutePath])
+            fixtureOutput = execute([bin + "java", "-cp", classes.absolutePath 
+ ":" + sdk + "/*",
+                    "CreateOrcFloatingStatsFixtures", "orc_floating_minmax", 
warehouse])
+        } finally {
+            assertTrue(classes.deleteDir())
+        }
+    } else {
+        String docker = 
context.config.otherConfigs.get("externalDockerCommand") ?: "docker"
+        String container = 
context.config.otherConfigs.get("icebergSparkContainer")
+        if (container == null || container.isEmpty()) {
+            def candidates = execute(["bash", "-c", "${docker} ps --format 
'{{.ID}}'"]).readLines()
+            def matches = candidates.findAll { String candidate ->
+                def probe = new ProcessBuilder("bash", "-c", "${docker} exec 
${shellQuote(candidate)} " +
+                        "bash -lc 'test -f /mnt/SUCCESS && command -v 
spark-sql >/dev/null'").start()
+                probe.consumeProcessOutput(new StringBuilder(), new 
StringBuilder())
+                probe.waitForOrKill(30000)
+                return probe.exitValue() == 0
+            }
+            assertEquals(1, matches.size(), "Set icebergSparkContainer to the 
Spark Iceberg container")
+            container = matches[0]
+        }
+        String directory = "/tmp/doris_orc_stats_${UUID.randomUUID()}"
+        String encoded = 
source.getText("UTF-8").getBytes("UTF-8").encodeBase64().toString()
+        String command = "mkdir -p ${directory} && echo ${encoded} | base64 -d 
> ${directory}/${source.name} && " +
+                "javac -cp \"/opt/spark/jars/*\" -d ${directory} 
${directory}/${source.name} && " +
+                "java -cp \"${directory}:/opt/spark/jars/*\" 
CreateOrcFloatingStatsFixtures orc_floating_minmax"
+        try {
+            fixtureOutput = execute(["bash", "-c",
+                    "${docker} exec ${shellQuote(container)} bash -lc 
${shellQuote(command)}"])
+        } finally {
+            execute(["bash", "-c", "${docker} exec ${shellQuote(container)} rm 
-rf ${shellQuote(directory)}"])
+        }
+    }
+    def cases = ["nan_middle", "nan_last", "nan_first", "all_nan", 
"nullable_nan", "finite", "all_null",
+            "positive_inf", "negative_inf", "opposite_inf", "double_overflow", 
"float_nan_only", "double_nan_only", "empty"]
+    def authored = fixtureOutput.readLines().findAll { 
it.startsWith("ORC_STATS_FIXTURE ") }
+            .collect { it.split(" ")[1] }
+    assertEquals(cases.toSet(), authored.toSet(), "The SDK must write and read 
back every fixture")
+    assertEquals(cases.size(), authored.size())
+
+    String originalSqlCache = (sql "SHOW VARIABLES LIKE 
'enable_sql_cache'")[0][1].toString()
+    String originalQueryCache = (sql "SHOW VARIABLES LIKE 
'enable_query_cache'")[0][1].toString()
+    try {
+        sql "SET enable_sql_cache=false"
+        sql "SET enable_query_cache=false"
+        sql "DROP CATALOG IF EXISTS orc_floating_minmax_catalog"
+        if (local) {
+            sql """CREATE CATALOG orc_floating_minmax_catalog PROPERTIES (
+                    'type'='iceberg', 'iceberg.catalog.type'='hadoop',
+                    'warehouse'='${warehouse.replace("'", "''")}')"""
+        } else {
+            String host = context.config.otherConfigs.get("externalEnvIp")
+            String rest = 
context.config.otherConfigs.get("iceberg_rest_uri_port")
+            String minio = 
context.config.otherConfigs.get("iceberg_minio_port")
+            sql """CREATE CATALOG orc_floating_minmax_catalog PROPERTIES (
+                    'type'='iceberg', 'iceberg.catalog.type'='rest', 
'uri'='http://${host}:${rest}',
+                    's3.access_key'='admin', 's3.secret_key'='password',
+                    's3.endpoint'='http://${host}:${minio}', 
's3.region'='us-east-1')"""
+        }
+        for (String name : cases) {
+            String table = 
"orc_floating_minmax_catalog.orc_floating_minmax.${name}"
+            // Compare textual values and NaN flags: fuzzy floating comparison 
can hide a NaN mismatch.
+            String expressions = "CAST(min(f) AS STRING), CAST(max(f) AS 
STRING), isnan(max(f)), " +
+                    "CAST(min(d) AS STRING), CAST(max(d) AS STRING), 
isnan(max(d))"
+            String pushed = "SELECT /*+ 
SET_VAR(enable_push_down_no_group_agg=true,enable_file_scanner_v2=true) */ 
${expressions} FROM ${table}"
+            String scanned = "SELECT /*+ 
SET_VAR(enable_push_down_no_group_agg=false,enable_file_scanner_v2=true) */ 
${expressions} FROM ${table}"
+            if (name != "empty") {
+                explain {
+                    sql pushed
+                    contains "pushdown agg=MINMAX"
+                }
+            }
+            quickTest("${name}_matches_scan", pushed, scanned)
+            "qt_${name}" pushed
+            "qt_${name}_counts" "SELECT count(*), count(f), count(d) FROM 
${table}"
+        }
+    } finally {
+        sql "SET enable_sql_cache=${originalSqlCache}"
+        sql "SET enable_query_cache=${originalQueryCache}"
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to