hello-stephen commented on code in PR #69304:
URL: https://github.com/apache/doris/pull/69304#discussion_r4734650756


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/PushDownAggStateCast.java:
##########
@@ -0,0 +1,176 @@
+// 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.
+
+package org.apache.doris.nereids.rules.rewrite;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.rules.expression.rules.ConvertAggStateCast;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.Cast;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import 
org.apache.doris.nereids.trees.expressions.functions.NoneMovableFunction;
+import 
org.apache.doris.nereids.trees.expressions.functions.combinator.CombineCombinator;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalLimit;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSort;
+import org.apache.doris.nereids.types.AggStateType;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/** Move codec-only state casts to the COMBINE producer before its bytes are 
written. */
+public class PushDownAggStateCast extends OneRewriteRuleFactory {
+    @Override
+    public Rule build() {
+        return logicalProject(subTree(LogicalAggregate.class, 
LogicalFilter.class,
+                LogicalSort.class, LogicalLimit.class, LogicalProject.class))
+                .when(project -> project.getProjects().stream().anyMatch(
+                        expr -> expr.anyMatch(e -> e instanceof Cast
+                                && ((Cast) e).getDataType() instanceof 
AggStateType)))
+                .then(PushDownAggStateCast::rewrite)
+                .toRule(RuleType.PUSH_DOWN_AGG_STATE_CAST);
+    }
+
+    private static Plan rewrite(LogicalProject<Plan> project) {
+        Plan child = project.child();
+        List<Plan> passthrough = new ArrayList<>();
+        // Keep predicates, order keys and limits unchanged. A projection can 
expose
+        // a separate target-codec value while it keeps its original outputs.
+        while (child instanceof LogicalFilter || child instanceof LogicalSort 
|| child instanceof LogicalLimit
+                || (child instanceof LogicalProject && !((LogicalProject<?>) 
child).isDistinct())) {
+            passthrough.add(child);
+            child = child.child(0);
+        }
+        if (!(child instanceof LogicalAggregate)) {

Review Comment:
   [P2] Propagate codec casts to STATE producers below LIMIT
   
   With a SUM(BIGINT NULL) AGG_STATE target created at version 19 and planning 
at 21, `INSERT INTO old_sink SELECT k, sum_state(v) FROM src LIMIT 1` follows 
this reduced plan inferred from the code:
   
   ```text
   Project(Cast(s@21 AS state@19))
     Limit(1)
       Project(sum_state(v) AS s@21)
         Scan(src)
   ```
   
   This walk reaches the scan and returns because it requires 
`LogicalAggregate`. `ConvertAggStateCast` then sees only the upper slot, and 
strict `CheckCast` rejects the version cast before the later 
project-through-limit rewrite. A previously valid insert therefore fails after 
upgrade although the STATE producer can emit version-19 bytes. Resolve scalar 
producers through these projections/limits before strict validation and cover 
this INSERT SELECT case.



##########
be/test/exprs/aggregate/aggregate_function_nullable_v2_test.cpp:
##########
@@ -0,0 +1,1459 @@
+// 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.
+
+#include <gtest/gtest.h>
+
+#include <algorithm>
+#include <array>
+#include <cstring>
+
+#include "agent/be_exec_version_manager.h"
+#include "common/exception.h"
+#include "core/arena.h"
+#include "core/block/block.h"
+#include "core/column/column_array.h"
+#include "core/column/column_complex.h"
+#include "core/column/column_fixed_length_object.h"
+#include "core/column/column_nullable.h"
+#include "core/column/column_vector.h"
+#include "core/data_type/data_type_agg_state.h"
+#include "core/data_type/data_type_array.h"
+#include "core/data_type/data_type_bitmap.h"
+#include "core/data_type/data_type_factory.hpp"
+#include "core/data_type/data_type_number.h"
+#include "core/data_type/data_type_string.h"
+#include "core/field.h"
+#include "core/string_buffer.hpp"
+#include "core/value/bitmap_value.h"
+#include "exprs/aggregate/aggregate_function_avg.h"
+#include "exprs/aggregate/aggregate_function_null_v2.h"
+#include "exprs/aggregate/aggregate_function_simple_factory.h"
+#include "exprs/aggregate/aggregate_function_state_combine.h"
+#include "exprs/aggregate/aggregate_function_state_merge.h"
+#include "exprs/aggregate/aggregate_function_state_union.h"
+#include "exprs/aggregate/aggregate_function_sum.h"
+#include "storage/storage_layout.h"
+#include "storage/tablet/tablet_schema.h"
+#include "util/slice.h"
+
+namespace doris {
+namespace {
+
+AggregateFunctionPtr nullable_function(const std::string& name, const 
DataTypes& types,
+                                       bool result_nullable = true) {
+    auto function = AggregateFunctionSimpleFactory::instance().get(
+            name, types, nullptr, result_nullable, 
BeExecVersionManager::get_newest_version());
+    EXPECT_NE(function, nullptr);
+    return function;
+}
+
+MutableColumnPtr nullable_ints(std::initializer_list<Int64> values,
+                               std::initializer_list<UInt8> nulls) {
+    auto data = ColumnInt64::create();
+    data->get_data().assign(values);
+    auto null_map = ColumnUInt8::create();
+    null_map->get_data().assign(nulls);
+    return ColumnNullable::create(std::move(data), std::move(null_map));
+}
+
+void add_column(const AggregateFunctionPtr& function, AggregateDataPtr place, 
const IColumn& column,
+                Arena& arena) {
+    const IColumn* columns[] = {&column};
+    function->add_batch_single_place(column.size(), place, columns, arena);
+}
+
+// Compare scalar accumulation with streaming -> batch merge and the 
single-row reader.
+// Selected-out rows deliberately contain no contribution and must never be 
decoded.
+void check_streaming(const AggregateFunctionPtr& function, const Columns& 
inputs,
+                     bool poison_native_nulls = false) {
+    Arena arena;
+    std::vector<const IColumn*> columns;
+    for (const auto& input : inputs) {
+        columns.push_back(input.get());
+    }
+    const size_t rows = inputs[0]->size();
+    function->check_input_columns_type(columns.data());
+    auto serialized = function->create_serialize_column();
+    function->streaming_agg_serialize_to_column(columns.data(), serialized, 
rows, arena);
+    ASSERT_EQ(serialized->size(), rows);
+    
ASSERT_TRUE(function->get_serialized_type()->check_column(*serialized).ok());
+    if (poison_native_nulls) {
+        auto& nullable = assert_cast<ColumnNullable&>(*serialized);
+        auto& payload = 
assert_cast<ColumnFixedLengthObject&>(nullable.get_nested_column());
+        for (size_t row = 0; row < rows; ++row) {
+            if (nullable.is_null_at(row)) {
+                // A NULL mark makes the payload irrelevant, even for native 
numeric readers.
+                std::memset(payload.get_data().data() + row * 
payload.item_size(), 0x7f,
+                            payload.item_size());
+            }
+        }
+    }
+    for (bool selected : {false, true}) {
+        AggregateFunctionGuard expected(function.get());
+        AggregateFunctionGuard actual(function.get());
+        std::vector<AggregateDataPtr> places(rows, actual.data());
+        for (size_t i = 0; i < rows; ++i) {
+            if (selected && i % 3 == 0) {
+                places[i] = nullptr;
+            } else {
+                function->add(expected.data(), columns.data(), i, arena);
+            }
+        }
+        Arena scratch_arena;
+        AggregateDataPtr scratch = nullptr;
+        if (function->needs_deserialize_and_merge_scratch()) {
+            scratch = scratch_arena.aligned_alloc(rows * 
function->size_of_data(),
+                                                  function->align_of_data());
+        }
+        if (selected) {
+            function->deserialize_and_merge_vec_selected(places.data(), 0, 
scratch,
+                                                         serialized.get(), 
arena, rows);
+        } else {
+            function->deserialize_and_merge_vec(places.data(), 0, scratch, 
serialized.get(), arena,
+                                                rows);
+        }
+        auto expected_result = function->get_return_type()->create_column();
+        auto actual_result = expected_result->clone_empty();
+        function->insert_result_into(expected.data(), *expected_result);
+        function->insert_result_into(actual.data(), *actual_result);
+        EXPECT_EQ(actual_result->compare_at(0, 0, *expected_result, 1), 0);
+    }
+    for (size_t i = 0; i < rows; ++i) {
+        AggregateFunctionGuard actual(function.get());
+        AggregateFunctionGuard expected(function.get());
+        function->deserialize_from_column_row(actual.data(), *serialized, i, 
arena);
+        function->add(expected.data(), columns.data(), i, arena);
+        auto expected_result = function->get_return_type()->create_column();
+        auto actual_result = expected_result->clone_empty();
+        function->insert_result_into(expected.data(), *expected_result);
+        function->insert_result_into(actual.data(), *actual_result);
+        EXPECT_EQ(actual_result->compare_at(0, 0, *expected_result, 1), 0) << 
"row=" << i;
+    }
+}
+
+// All three writers must agree with the declared state type. Merge the column 
range
+// to check empty contributions, including bare columns for non-nullable 
results.
+void check_column_serializers(const AggregateFunctionPtr& function, const 
Columns& inputs) {
+    Arena arena;
+    std::vector<const IColumn*> columns;
+    for (const auto& input : inputs) {
+        columns.push_back(input.get());
+    }
+    AggregateFunctionGuard expected(function.get());
+    for (size_t row = 0; row < inputs[0]->size(); ++row) {
+        function->add(expected.data(), columns.data(), row, arena);
+    }
+    auto expected_result = function->get_return_type()->create_column();
+    function->insert_result_into(expected.data(), *expected_result);
+    for (int mode : {0, 1, 2}) {
+        SCOPED_TRACE(mode);
+        // Bitmap batch serialization moves the value out of its state. Each 
writer
+        // needs a fresh source so a previous write cannot change the expected 
input.
+        AggregateFunctionGuard source(function.get());
+        for (size_t row = 0; row < inputs[0]->size(); ++row) {
+            function->add(source.data(), columns.data(), row, arena);
+        }
+        auto serialized = function->create_serialize_column();
+        if (mode == 0) {
+            function->streaming_agg_serialize_to_column(columns.data(), 
serialized,
+                                                        inputs[0]->size(), 
arena);
+        } else if (mode == 1) {
+            function->serialize_to_column({source.data()}, 0, serialized, 1);
+        } else {
+            function->serialize_without_key_to_column(source.data(), 
*serialized);
+        }
+        
ASSERT_TRUE(function->get_serialized_type()->check_column(*serialized).ok());
+        AggregateFunctionGuard actual(function.get());
+        // The range has an inclusive end. An empty streaming batch has no 
range to merge.
+        if (!serialized->empty()) {
+            function->deserialize_and_merge_from_column_range(actual.data(), 
*serialized, 0,
+                                                              
serialized->size() - 1, arena);
+        }
+        auto actual_result = expected_result->clone_empty();
+        function->insert_result_into(actual.data(), *actual_result);
+        EXPECT_EQ(actual_result->compare_at(0, 0, *expected_result, 1), 0);
+    }
+}
+
+struct alignas(64) StreamingArenaProbeData {
+    StringRef value;
+};
+
+class StreamingArenaProbe final
+        : public IAggregateFunctionDataHelper<StreamingArenaProbeData, 
StreamingArenaProbe> {
+    using Base = IAggregateFunctionDataHelper<StreamingArenaProbeData, 
StreamingArenaProbe>;
+
+public:
+    StreamingArenaProbe() : Base({std::make_shared<DataTypeString>()}) {}
+    String get_name() const override { return "streaming_arena_probe"; }
+    DataTypePtr get_return_type() const override { return 
std::make_shared<DataTypeString>(); }
+    void create(AggregateDataPtr place) const override {
+        EXPECT_EQ(reinterpret_cast<uintptr_t>(place) % 
alignof(StreamingArenaProbeData), 0);
+        ++creates;
+        Base::create(place);
+    }
+    void destroy(AggregateDataPtr place) const noexcept override {
+        ++destroys;
+        Base::destroy(place);
+    }
+    void reset(AggregateDataPtr place) const override { data(place).value = 
{}; }
+    void add(AggregateDataPtr place, const IColumn** columns, ssize_t row,
+             Arena& arena) const override {
+        auto value = assert_cast<const 
ColumnString&>(*columns[0]).get_data_at(row);
+        auto* copied = arena.alloc(value.size);
+        std::memcpy(copied, value.data, value.size);
+        data(place).value = {copied, value.size};
+        max_arena_used = std::max(max_arena_used, arena.used_size());
+    }
+    void merge(AggregateDataPtr place, ConstAggregateDataPtr rhs, Arena&) 
const override {
+        data(place).value = data(rhs).value;
+    }
+    void serialize(ConstAggregateDataPtr place, BufferWritable& buf) const 
override {
+        buf.write_binary(data(place).value);
+    }
+    void deserialize(AggregateDataPtr place, BufferReadable& buf, Arena&) 
const override {
+        ++reads;
+        // Inject a failure after construction to check temporary-state 
cleanup.
+        if (fail_deserialize) {
+            throw Exception(ErrorCode::INTERNAL_ERROR, "Test deserialize 
failure");
+        }
+        buf.read_binary(data(place).value);
+    }
+    void insert_result_into(ConstAggregateDataPtr place, IColumn& to) const 
override {
+        const auto value = data(place).value;
+        assert_cast<ColumnString&>(to).insert_data(value.data, value.size);
+    }
+
+    mutable size_t creates = 0;
+    mutable size_t destroys = 0;
+    mutable size_t max_arena_used = 0;
+    mutable size_t reads = 0;
+    bool fail_deserialize = false;
+};
+
+void check_streaming_arena_mode(int mode) {
+    constexpr size_t rows = 64;
+    constexpr size_t width = 8192;
+    auto values = ColumnString::create();
+    for (size_t row = 0; row < rows; ++row) {
+        values->insert_value(std::string(width, static_cast<char>('a' + row % 
26)));
+    }
+    auto* probe = new StreamingArenaProbe;
+    AggregateFunctionPtr function;
+    ColumnPtr values_column = std::move(values);
+    ColumnPtr input = values_column;
+    if (mode == 0) {
+        function.reset(probe);
+    } else {
+        auto nulls = ColumnUInt8::create(rows, 0);
+        for (size_t row = 0; row < rows; ++row) {
+            nulls->get_data()[row] = mode == 2 && row % 3 == 0;
+        }
+        input = ColumnNullable::create(values_column, std::move(nulls));
+        function = 
std::make_shared<AggregateFunctionNullUnaryInlineV2<StreamingArenaProbe, true>>(
+                probe, DataTypes 
{make_nullable(std::make_shared<DataTypeString>())}, false);
+    }
+    Arena caller_arena;
+    const IColumn* columns[] = {input.get()};
+    auto serialized = function->create_serialize_column();
+    function->streaming_agg_serialize_to_column(columns, serialized, rows, 
caller_arena);
+    EXPECT_EQ(caller_arena.used_size(), 0);
+    EXPECT_LE(probe->max_arena_used, width);
+    EXPECT_EQ(probe->creates, mode == 2 ? 42 : rows);
+    EXPECT_EQ(probe->destroys, probe->creates);
+    const IColumn* payload = serialized.get();
+    if (mode != 0) {
+        payload = &assert_cast<const 
ColumnNullable&>(*serialized).get_nested_column();
+    }
+    for (size_t row = 0; row < rows; ++row) {
+        if (mode == 2 && row % 3 == 0) {
+            EXPECT_TRUE(serialized->is_null_at(row));
+            continue;
+        }
+        // Read after the temporary arenas were destroyed: serialized rows own 
the bytes.
+        VectorBufferReader reader(assert_cast<const 
ColumnString&>(*payload).get_data_at(row));
+        StringRef decoded;
+        reader.read_binary(decoded);
+        EXPECT_EQ(decoded, values_column->get_data_at(row));
+    }
+}
+
+TEST(NullableAggregationV2Test, 
StreamingStatesAreAlignedAndTemporaryPayloadsAreRowLocal) {
+    // Bare generic, nullable/no NULL, and nullable/sparse NULL take different 
streaming paths.
+    for (int mode : {0, 1, 2}) {
+        check_streaming_arena_mode(mode);
+    }
+}
+
+TEST(NullableAggregationV2Test, 
GenericRangeReadersAndStateGuardsHonorAlignment) {
+    auto function = std::make_shared<StreamingArenaProbe>();
+    auto values = ColumnString::create();
+    values->insert_value(std::string(8192, 'a'));
+    values->insert_value("last");
+    const IColumn* columns[] = {values.get()};
+    Arena arena;
+    auto serialized = function->create_serialize_column();
+    function->streaming_agg_serialize_to_column(columns, serialized, 2, arena);
+    {
+        AggregateFunctionGuard state(function.get());
+        const auto before_creates = function->creates;
+        const auto before_destroys = function->destroys;
+        function->deserialize_and_merge_from_column_range(state.data(), 
*serialized, 0, 1, arena);
+        EXPECT_EQ(function->creates - before_creates, 2);
+        EXPECT_EQ(function->destroys - before_destroys, 2);
+        auto result = function->get_return_type()->create_column();
+        function->insert_result_into(state.data(), *result);
+        EXPECT_EQ(result->get_data_at(0), StringRef("last", 4));
+    }
+    EXPECT_EQ(function->creates, function->destroys);
+}
+
+TEST(NullableAggregationV2Test, 
AllNullStreamingDoesNotConstructTemporaryStates) {
+    auto* probe = new StreamingArenaProbe;
+    auto function = 
std::make_shared<AggregateFunctionNullUnaryInlineV2<StreamingArenaProbe, true>>(
+            probe, DataTypes 
{make_nullable(std::make_shared<DataTypeString>())}, false);
+    auto values = ColumnString::create();
+    values->insert_value("unread");
+    auto input = ColumnNullable::create(std::move(values), 
ColumnUInt8::create(1, 1));
+    const IColumn* columns[] = {input.get()};
+    Arena arena;
+    auto serialized = function->create_serialize_column();
+    function->streaming_agg_serialize_to_column(columns, serialized, 1, arena);
+    EXPECT_TRUE(serialized->is_null_at(0));
+    EXPECT_EQ(probe->creates, 0);
+    EXPECT_EQ(probe->destroys, 0);
+    EXPECT_EQ(probe->max_arena_used, 0);
+    EXPECT_EQ(arena.used_size(), 0);
+}
+
+void check_generic_nullable_merge(bool selected, bool fail_deserialize) {
+    auto* probe = new StreamingArenaProbe;
+    auto function = 
std::make_shared<AggregateFunctionNullUnaryInlineV2<StreamingArenaProbe, true>>(
+            probe, DataTypes 
{make_nullable(std::make_shared<DataTypeString>())}, false);
+    // Two rows cover a NULL partial and a valid partial. The selected reader 
needs
+    // one extra row with a skipped destination. Empty bytes in skipped rows 
cannot
+    // encode a String state. Reading either skipped row would fail this test.
+    auto payload = ColumnString::create();
+    payload->insert_default();
+    if (selected) {
+        payload->insert_default();
+    }
+    VectorBufferWriter writer(*payload);
+    writer.write_binary(StringRef("a", 1));
+    writer.commit();
+    const auto rows = payload->size();
+    auto nulls = ColumnUInt8::create(rows, 0);
+    nulls->get_data()[0] = 1;
+    auto serialized = ColumnNullable::create(std::move(payload), 
std::move(nulls));
+    Arena arena;
+    // A nonzero offset checks both the outer state offset and the nullable 
prefix.
+    // The probe requires 64-byte alignment for destination and temporary 
states.
+    constexpr size_t offset = 64;
+    auto* base = arena.aligned_alloc(offset + function->size_of_data(), 
function->align_of_data());
+    auto* place = base + offset;
+    function->create(place);
+    DEFER({ function->destroy(place); });
+    std::vector<AggregateDataPtr> places(rows, base);
+    if (selected) {
+        places[1] = nullptr;
+    }
+    auto* scratch = arena.aligned_alloc(rows * function->size_of_data(), 
function->align_of_data());
+    const auto creates = probe->creates;
+    const auto destroys = probe->destroys;
+    probe->fail_deserialize = fail_deserialize;
+    auto merge = [&] {
+        if (selected) {
+            function->deserialize_and_merge_vec_selected(places.data(), 
offset, scratch,
+                                                         serialized.get(), 
arena, rows);
+        } else {
+            function->deserialize_and_merge_vec(places.data(), offset, 
scratch, serialized.get(),
+                                                arena, rows);
+        }
+    };
+    if (fail_deserialize) {
+        EXPECT_THROW(merge(), Exception);
+    } else {
+        merge();
+        auto result = function->get_return_type()->create_column();
+        function->insert_result_into(place, *result);
+        // Compare the complete SQL value, including its NULL mark.
+        EXPECT_EQ((*result)[0], Field::create_field<TYPE_STRING>(String("a")));
+    }
+    // Only the valid row creates a state. Destruction is required even on 
failure.
+    // Check decode, construction, and destruction counts in that order.
+    const std::array<size_t, 3> calls {probe->reads, probe->creates - creates,
+                                       probe->destroys - destroys};
+    EXPECT_EQ(calls, (std::array<size_t, 3> {1, 1, 1}));
+}
+
+TEST(NullableAggregationV2Test, GenericNullableMergeSkipsUnreadableStates) {
+    for (bool selected : {false, true}) {
+        for (bool fail_deserialize : {false, true}) {
+            check_generic_nullable_merge(selected, fail_deserialize);
+        }
+    }
+}
+
+TEST(NullableAggregationV2Test, 
GenericNullableMergeWithNoValidRowsNeedsNoScratch) {
+    auto* probe = new StreamingArenaProbe;
+    auto function = 
std::make_shared<AggregateFunctionNullUnaryInlineV2<StreamingArenaProbe, true>>(
+            probe, DataTypes 
{make_nullable(std::make_shared<DataTypeString>())}, false);
+    Arena arena;
+    AggregateFunctionGuard state(function.get());
+    const auto creates = probe->creates;
+    auto serialized = function->create_serialize_column();
+    function->deserialize_and_merge_vec(nullptr, 0, nullptr, serialized.get(), 
arena, 0);
+    // One NULL partial is sufficient to check the all-NULL path. Its nested 
String is empty.
+    serialized->insert_default();
+    AggregateDataPtr places[] = {state.data()};
+    function->deserialize_and_merge_vec(places, 0, nullptr, serialized.get(), 
arena, 1);
+    function->deserialize_and_merge_vec_selected(places, 0, nullptr, 
serialized.get(), arena, 1);
+    // A non-NULL row with no destination must also leave scratch and payload 
unread.
+    assert_cast<ColumnNullable&>(*serialized).get_null_map_data()[0] = 0;
+    places[0] = nullptr;
+    function->deserialize_and_merge_vec_selected(places, 0, nullptr, 
serialized.get(), arena, 1);
+    EXPECT_EQ(probe->creates, creates);
+    EXPECT_EQ(probe->reads, 0);
+    auto result = function->get_return_type()->create_column();
+    function->insert_result_into(state.data(), *result);
+    EXPECT_TRUE(result->is_null_at(0));
+}
+
+TEST(NullableAggregationV2Test, NativeUnaryAndStableStateCodecs) {
+    auto type = make_nullable(std::make_shared<DataTypeInt64>());
+    for (const auto* name :
+         {"sum", "avg", "min", "max", "multi_distinct_sum", 
"multi_distinct_count"}) {
+        SCOPED_TRACE(name);
+        const bool result_nullable = std::string_view(name) != 
"multi_distinct_count";
+        auto function = nullable_function(name, {type}, result_nullable);
+        for (const auto& nulls : {std::initializer_list<UInt8> {0, 0, 0, 0, 0, 
0},
+                                  {1, 0, 0, 0, 0, 1},
+                                  {1, 1, 1, 0, 1, 1},
+                                  {1, 1, 1, 1, 1, 1}}) {
+            auto input = nullable_ints({999, 10, 20, 20, -10, 999}, nulls);
+            check_streaming(function, {std::move(input)},
+                            std::string_view(name) == "sum" || 
std::string_view(name) == "avg");
+        }
+        check_streaming(make_agg_state_compatible_function(function),
+                        {nullable_ints({99, 10, 20, 0, 20, 99}, {1, 0, 0, 1, 
0, 1})});
+    }
+}
+
+TEST(NullableAggregationV2Test, NativeSumAndAvgStreamingUseOptionalNullMaps) {
+    // Two rows are the minimum needed for one valid value and one NULL in a 
batch.
+    // Keep nonzero hidden values so a NULL-map dispatch error changes the 
state.
+    auto input = ColumnInt64::create();
+    input->get_data().assign({7, 13});
+    const IColumn* columns[] = {input.get()};
+    const std::array<UInt8, 2> valid {0, 0};
+    const std::array<UInt8, 2> first_null {1, 0};
+    const std::array<UInt8, 2> second_null {0, 1};
+    const std::array<UInt8, 2> all_null {1, 1};
+    struct Case {
+        const UInt8* null_map;
+        std::array<Int64, 2> sums;
+        std::array<UInt64, 2> counts;
+    };
+    const std::array<Case, 5> cases {
+            {{.null_map = nullptr, .sums = {7, 13}, .counts = {1, 1}},
+             {.null_map = valid.data(), .sums = {7, 13}, .counts = {1, 1}},
+             {.null_map = first_null.data(), .sums = {0, 13}, .counts = {0, 
1}},
+             {.null_map = second_null.data(), .sums = {7, 0}, .counts = {1, 
0}},
+             {.null_map = all_null.data(), .sums = {0, 0}, .counts = {0, 0}}}};
+    auto check = [&](const auto& function) {
+        SCOPED_TRACE(function.get_name());
+        auto output = function.create_serialize_column();
+        Arena arena;
+        for (const auto& test : cases) {
+            // Populate the same output before each call. Masked rows must 
clear the
+            // previous value and AVG count; valid rows must have count one.
+            function.streaming_agg_serialize_to_column(columns, output, 2, 
arena);
+            function.streaming_agg_serialize_to_column_with_null_map(columns, 
output, 2,
+                                                                     
test.null_map);
+            const auto& states = assert_cast<const 
ColumnFixedLengthObject&>(*output);
+            ASSERT_EQ(states.size(), 2);
+            for (size_t row = 0; row < 2; ++row) {
+                const auto& state = function.data(
+                        
reinterpret_cast<ConstAggregateDataPtr>(states.get_data().data()) +
+                        row * states.item_size());
+                EXPECT_EQ(state.sum, test.sums[row]);
+                if constexpr (requires { state.count; }) {
+                    EXPECT_EQ(state.count, test.counts[row]);
+                }
+            }
+            // Both map choices must resize a reused output to zero for an 
empty batch.
+            function.streaming_agg_serialize_to_column_with_null_map(columns, 
output, 0,
+                                                                     
test.null_map);
+            EXPECT_EQ(output->size(), 0);
+        }
+    };
+    const DataTypes arguments {std::make_shared<DataTypeInt64>()};
+    check(AggregateFunctionSumSimple<TYPE_BIGINT>(arguments));
+    check(AggregateFunctionAvg<TYPE_BIGINT, TYPE_DOUBLE, 
AggregateFunctionAvgData<TYPE_LARGEINT>>(
+            arguments));
+}
+
+TEST(NullableAggregationV2Test, AllNullNativeSumClearsAReusedOutputState) {
+    auto function = nullable_function("sum", 
{make_nullable(std::make_shared<DataTypeInt64>())});
+    auto serialized = function->create_serialize_column();
+    Arena arena;
+    // Use one row in two batches. First write 7. Then write NULL with the 
same hidden
+    // payload. The all-NULL path must replace the old state with zero and 
retain the
+    // NULL mark. The separate streaming benchmark checks the masked-load 
slowdown.
+    for (UInt8 is_null : {0, 1}) {
+        auto input = nullable_ints({7}, {is_null});
+        const IColumn* columns[] = {input.get()};
+        function->streaming_agg_serialize_to_column(columns, serialized, 1, 
arena);
+        const auto& nullable = assert_cast<const ColumnNullable&>(*serialized);
+        ASSERT_EQ(nullable.size(), 1);
+        EXPECT_EQ(nullable.get_null_map_data()[0], is_null);
+        const auto& payload =
+                assert_cast<const 
ColumnFixedLengthObject&>(nullable.get_nested_column());
+        ASSERT_EQ(payload.item_size(), sizeof(Int64));
+        EXPECT_EQ(reinterpret_cast<const 
Int64*>(payload.get_data().data())[0], is_null ? 0 : 7);
+    }
+}
+
+TEST(NullableAggregationV2Test, 
DistributeKeyStreamingAppendsWholeFixedLengthStates) {
+    auto type = make_nullable(std::make_shared<DataTypeInt64>());
+    auto function = nullable_function("multi_distinct_count_distribute_key", 
{type}, false);
+    auto input = nullable_ints({1, 2, 999, 3}, {0, 0, 1, 0});
+    const IColumn* columns[] = {input.get()};
+    Arena arena;
+    auto serialized = function->create_serialize_column();
+    function->streaming_agg_serialize_to_column(columns, serialized, 
input->size(), arena);
+
+    ASSERT_FALSE(serialized->is_nullable());
+    const auto& payload = assert_cast<const 
ColumnFixedLengthObject&>(*serialized);
+    const auto* counts = reinterpret_cast<const 
UInt64*>(payload.get_data().data());
+    EXPECT_EQ(counts[0], 1);
+    EXPECT_EQ(counts[1], 1);
+    EXPECT_EQ(counts[2], 0);
+    EXPECT_EQ(counts[3], 1);
+    auto result = function->get_return_type()->create_column();
+    for (size_t row = 0; row < input->size(); ++row) {
+        AggregateFunctionGuard state(function.get());
+        function->deserialize_from_column_row(state.data(), *serialized, row, 
arena);
+        function->insert_result_into(state.data(), *result);
+    }
+    EXPECT_EQ(assert_cast<const ColumnInt64&>(*result).get_data(),
+              ColumnInt64::Container({1, 1, 0, 1}));
+}
+
+TEST(NullableAggregationV2Test, VariadicNullableArgumentsAtEveryPosition) {
+    auto type = std::make_shared<DataTypeFloat64>();
+    for (bool nullable_first : {false, true}) {
+        for (bool nullable_second : {false, true}) {
+            if (!nullable_first && !nullable_second) {
+                continue;
+            }
+            auto function = nullable_function("avg_weighted",
+                                              {nullable_first ? 
make_nullable(type) : type,
+                                               nullable_second ? 
make_nullable(type) : type});
+            EXPECT_NE(function->get_name().find("NullableV2"), 
std::string::npos);
+            EXPECT_TRUE(function->get_serialized_type()->is_nullable());
+            auto first = ColumnFloat64::create();
+            first->get_data().assign({10, 999, 20, 30, 999, 999});
+            auto second = ColumnFloat64::create();
+            second->get_data().assign({1, 2, 999, 3, 999, 999});
+            ColumnPtr x = std::move(first);
+            ColumnPtr w = std::move(second);
+            if (nullable_first) {
+                auto nulls = ColumnUInt8::create();
+                nulls->get_data().assign({0, 1, 0, 0, 1, 1});
+                x = ColumnNullable::create(x, std::move(nulls));
+            }
+            if (nullable_second) {
+                auto nulls = ColumnUInt8::create();
+                nulls->get_data().assign({0, 0, 1, 0, 1, 1});
+                w = ColumnNullable::create(w, std::move(nulls));
+            }
+            check_streaming(function, {x, w});
+            check_streaming(make_agg_state_compatible_function(function), {x, 
w});
+        }
+    }
+}
+
+TEST(NullableAggregationV2Test, VariadicUpdatePathsSkipNullArguments) {
+    // Four rows are the minimum for all NULL pairs: valid, value NULL, weight 
NULL, both NULL.
+    // Only (10, 1) contributes. The hidden values must not change the 
expected result of 10.
+    auto values = ColumnFloat64::create();
+    values->get_data().assign({10, 777, 20, 777});
+    auto weights = ColumnFloat64::create();
+    weights->get_data().assign({1, 2, 777, 777});
+    auto value_nulls = ColumnUInt8::create();
+    value_nulls->get_data().assign({0, 1, 0, 1});
+    auto weight_nulls = ColumnUInt8::create();
+    weight_nulls->get_data().assign({0, 0, 1, 1});
+    auto value_column = ColumnNullable::create(std::move(values), 
std::move(value_nulls));
+    auto weight_column = ColumnNullable::create(std::move(weights), 
std::move(weight_nulls));
+    const IColumn* columns[] = {value_column.get(), weight_column.get()};
+    auto type = make_nullable(std::make_shared<DataTypeFloat64>());
+    auto function = nullable_function("avg_weighted", {type, type});
+    Arena arena;
+    for (int path = 0; path < 7; ++path) {
+        SCOPED_TRACE(path);
+        AggregateFunctionGuard state(function.get());
+        std::array<AggregateDataPtr, 4> places;
+        places.fill(state.data());
+        UInt8 use_null = 0;
+        UInt8 use_previous = 0;
+        switch (path) {
+        case 0:
+            for (size_t row = 0; row < 4; ++row) {
+                function->add(state.data(), columns, row, arena);
+            }
+            break;
+        case 1:
+            // Skip the only valid row. The remaining three rows must leave an 
empty state.
+            places[0] = nullptr;
+            function->add_batch_selected(4, places.data(), 0, columns, arena);
+            break;
+        case 2:
+            function->add_batch(4, places.data(), 0, columns, arena, false);
+            break;
+        case 3:
+            function->add_batch_single_place(4, state.data(), columns, arena);
+            break;
+        case 4:
+            function->add_batch_range(0, 3, state.data(), columns, arena, 
true);
+            break;
+        case 5:
+            function->add_range_single_place(0, 4, 0, 4, state.data(), 
columns, arena, &use_null,
+                                             &use_previous);
+            break;
+        case 6:
+            // An empty window has no row to read, even though the input 
column is nonempty.
+            function->add_range_single_place(0, 4, 4, 4, state.data(), 
columns, arena, &use_null,
+                                             &use_previous);
+            EXPECT_EQ(use_null, 1);
+            break;
+        }
+        auto result = function->get_return_type()->create_column();
+        function->insert_result_into(state.data(), *result);
+        const auto& nullable = assert_cast<const ColumnNullable&>(*result);
+        ASSERT_EQ(nullable.is_null_at(0), path == 1 || path == 6);
+        if (!nullable.is_null_at(0)) {
+            EXPECT_EQ(
+                    assert_cast<const 
ColumnFloat64&>(nullable.get_nested_column()).get_element(0),
+                    10);
+        }
+    }
+}
+
+void check_legacy_incremental_window(const char* name) {
+    auto type = make_nullable(std::make_shared<DataTypeInt64>());
+    auto input = nullable_ints({0, 0, 3, 5}, {1, 1, 0, 0});
+    const IColumn* columns[] = {input.get()};
+    AggregateFunctionAttr attr;
+    attr.is_window_function = true;
+    auto function =
+            AggregateFunctionSimpleFactory::instance().get(name, {type}, 
nullptr, true, 19, attr);
+    auto codec = make_nullable_wire_compatible_function(function, 19, false);
+    EXPECT_TRUE(codec->supported_incremental_mode());
+    EXPECT_EQ(codec->result_column_could_resize(), 
function->result_column_could_resize());
+    EXPECT_TRUE(codec->needs_deserialize_and_merge_scratch());
+    AggregateFunctionGuard state(codec.get());
+    Arena arena;
+    auto result = codec->get_return_type()->create_column();
+    UInt8 use_null_result = 0;
+    UInt8 could_use_previous = 0;
+    for (int64_t row = 0; row < 4; ++row) {
+        codec->execute_function_with_incremental(
+                0, 4, std::max<int64_t>(0, row - 1), row + 1, state.data(), 
columns, arena,
+                row >= 2 && input->is_null_at(row - 2), 
input->is_null_at(row), true,
+                &use_null_result, &could_use_previous);
+        codec->insert_result_into(state.data(), *result);
+        could_use_previous = 1;
+    }
+    EXPECT_TRUE(result->is_null_at(0));
+    EXPECT_TRUE(result->is_null_at(1));
+    const auto& nested = assert_cast<const 
ColumnNullable&>(*result).get_nested_column();
+    if (std::string_view(name) == "sum") {
+        const auto& values = assert_cast<const 
ColumnInt64&>(nested).get_data();
+        EXPECT_EQ(values[2], 3);
+        EXPECT_EQ(values[3], 8);
+    } else {
+        const auto& values = assert_cast<const 
ColumnFloat64&>(nested).get_data();
+        EXPECT_DOUBLE_EQ(values[2], 3);
+        EXPECT_DOUBLE_EQ(values[3], 4);
+    }
+}
+
+TEST(NullableAggregationV2Test, 
LegacyWireCodecKeepsIncrementalWindowExecution) {
+    check_legacy_incremental_window("sum");
+    check_legacy_incremental_window("avg");
+}
+
+TEST(NullableAggregationV2Test, 
WideStringReadersSkipNullPartialsBeforeDecoding) {
+    auto type = make_nullable(std::make_shared<DataTypeString>());
+    for (const auto* name : {"min", "max"}) {
+        auto strings = ColumnString::create();
+        for (const auto& value : {std::string(8192, 'x'), std::string(), 
std::string(4096, 'a'),
+                                  std::string(), std::string(8192, 'z'), 
std::string()}) {
+            strings->insert_data(value.data(), value.size());
+        }
+        auto nulls = ColumnUInt8::create();
+        nulls->get_data().assign({0, 1, 0, 1, 0, 1});
+        ColumnPtr input = ColumnNullable::create(std::move(strings), 
std::move(nulls));
+        auto function = nullable_function(name, {type});
+        check_streaming(function, {input});
+        check_streaming(make_agg_state_compatible_function(function), {input});
+    }
+}
+
+TEST(NullableAggregationV2Test, 
BitmapIntersectionIgnoresNullOnlyPartialStates) {
+    // The NULL-only middle partial must not turn {1,2} INTERSECT {2,3} into 
empty.
+    auto type = make_nullable(std::make_shared<DataTypeBitMap>());
+    auto function = nullable_function("bitmap_intersect", {type});
+    auto bitmaps = ColumnBitmap::create();
+    for (const auto& values : {std::initializer_list<UInt64> {1, 2}, {}, {2, 
3}, {}, {2}, {}}) {
+        BitmapValue bitmap;
+        for (auto value : values) {
+            bitmap.add(value);
+        }
+        bitmaps->insert_value(bitmap);
+    }
+    auto nulls = ColumnUInt8::create();
+    nulls->get_data().assign({0, 1, 0, 1, 0, 1});
+    ColumnPtr input = ColumnNullable::create(std::move(bitmaps), 
std::move(nulls));
+    check_streaming(function, {input});
+    check_streaming(make_agg_state_compatible_function(function), {input});
+    Arena arena;
+    AggregateFunctionGuard state(function.get());
+    add_column(function, state.data(), *input, arena);
+    auto output = function->get_return_type()->create_column();
+    function->insert_result_into(state.data(), *output);
+    const auto& nullable = assert_cast<const ColumnNullable&>(*output);
+    ASSERT_FALSE(nullable.is_null_at(0));
+    const auto& result = assert_cast<const 
ColumnBitmap&>(nullable.get_nested_column());
+    EXPECT_EQ(result.get_data()[0].cardinality(), 1);
+    EXPECT_TRUE(result.get_data()[0].contains(2));
+}
+
+TEST(NullableAggregationV2Test, 
NonNullableBitmapResultStillMarksEmptyPartials) {
+    auto type = make_nullable(std::make_shared<DataTypeBitMap>());
+    auto function = nullable_function("bitmap_intersect", {type}, false);
+    auto bitmaps = ColumnBitmap::create();
+    for (const auto* text : {"1,2", "", "2,3", "", "2", ""}) {
+        BitmapValue value;
+        if (std::string_view(text) == "1,2") {
+            value.add(1);
+            value.add(2);
+        } else if (std::string_view(text) == "2,3") {
+            value.add(2);
+            value.add(3);
+        } else if (std::string_view(text) == "2") {
+            value.add(2);
+        }
+        bitmaps->insert_value(value);
+    }
+    auto nulls = ColumnUInt8::create();
+    nulls->get_data().assign({0, 1, 0, 1, 0, 1});
+    ColumnPtr input = ColumnNullable::create(std::move(bitmaps), 
std::move(nulls));
+    EXPECT_FALSE(function->get_return_type()->is_nullable());
+    EXPECT_TRUE(function->get_serialized_type()->is_nullable());
+    check_streaming(function, {input});
+    check_streaming(make_agg_state_compatible_function(function), {input});
+}
+
+void check_unary_batch_update(const AggregateFunctionPtr& function, const 
ColumnPtr& input,
+                              int mode) {
+    Arena arena;
+    const IColumn* columns[] = {input.get()};
+    const size_t offset = std::max<size_t>(64, function->align_of_data());
+    AlignedAggregateData storage(offset + function->size_of_data(), 
function->align_of_data());
+    std::memset(storage.data(), 0x5a, offset);
+    auto* place = storage.data() + offset;
+    function->create(place);
+    DEFER({ function->destroy(place); });
+    AggregateFunctionGuard expected(function.get());
+    AggregateFunctionGuard merged(function.get());
+    std::vector<AggregateDataPtr> places(input->size(), storage.data());
+    for (size_t row = 0; row < input->size(); ++row) {
+        if (mode == 1 && row == 0) {
+            places[row] = nullptr;
+        } else {
+            function->add(expected.data(), columns, row, arena);
+        }
+    }
+    switch (mode) {
+    case 0:
+        function->add_batch(input->size(), places.data(), offset, columns, 
arena, false);
+        break;
+    case 1:
+        function->add_batch_selected(input->size(), places.data(), offset, 
columns, arena);
+        break;
+    case 2:
+        function->add_batch_single_place(input->size(), place, columns, arena);
+        break;
+    case 3:
+        function->add_batch_range(0, input->size() - 1, place, columns, arena, 
input->has_null());
+        break;
+    }
+    function->merge(merged.data(), place, arena);
+    auto wanted = function->get_return_type()->create_column();
+    auto actual = wanted->clone_empty();
+    function->insert_result_into(expected.data(), *wanted);
+    function->insert_result_into(merged.data(), *actual);
+    EXPECT_EQ(actual->compare_at(0, 0, *wanted, 1), 0) << "mode=" << mode;
+    EXPECT_EQ(std::string_view(storage.data(), offset), std::string(offset, 
0x5a));
+}
+
+void check_state_validity_storage(const char* name, const DataTypePtr& 
argument, int version,
+                                  bool nullable_result, bool 
needs_empty_marker) {
+    SCOPED_TRACE(name);
+    SCOPED_TRACE(version);
+    SCOPED_TRACE(nullable_result);
+    auto& factory = AggregateFunctionSimpleFactory::instance();
+    auto nested = factory.get(name, {argument}, nullptr, false, version);
+    ASSERT_NE(nested, nullptr);
+    auto function = factory.get(name, {make_nullable(argument)}, nullptr, 
nullable_result, version);
+    ASSERT_NE(function, nullptr);
+    const bool needs_flag = nullable_result || needs_empty_marker;
+    EXPECT_EQ(function->size_of_data(),
+              nested->size_of_data() + (needs_flag ? nested->align_of_data() : 
0));
+    EXPECT_EQ(function->align_of_data(), nested->align_of_data());
+    // A non-nullable result uses the nested empty state, except for INTERSECT.
+    // Its NULL-only partial must remain distinct from a valid empty bitmap.
+    const bool nullable_state =
+            nullable_result ||
+            (needs_empty_marker && version >= 
USE_UNIFIED_NULLABLE_AGGREGATION_VERSION);
+    EXPECT_EQ(function->get_serialized_type()->is_nullable(), nullable_state);
+    EXPECT_EQ(function->create_serialize_column()->is_nullable(), 
nullable_state);
+}
+
+TEST(NullableAggregationV2Test, 
StateValidityStorageIsAllocatedOnlyWhenRequired) {
+    // No rows are needed to check the allocation contract. Compare the 
wrapper with
+    // the same function on nonnullable arguments. A flag also needs alignment 
padding.
+    auto number = std::make_shared<DataTypeInt64>();
+    auto bitmap = std::make_shared<DataTypeBitMap>();
+    for (int version : {19, 20, USE_UNIFIED_NULLABLE_AGGREGATION_VERSION}) {
+        for (bool nullable_result : {false, true}) {
+            check_state_validity_storage("sum", number, version, 
nullable_result, false);
+            check_state_validity_storage("bitmap_union", bitmap, version, 
nullable_result, false);
+            check_state_validity_storage("bitmap_intersect", bitmap, version, 
nullable_result,
+                                         true);
+        }
+    }
+}
+
+TEST(NullableAggregationV2Test, 
NonNullableSumSkipsNullWithoutOverwritingNestedState) {
+    auto function =
+            nullable_function("sum", 
{make_nullable(std::make_shared<DataTypeInt64>())}, false);
+    // One valid row and one NULL are enough. Writing a flag at place[0] with 
no prefix
+    // would change the low byte of SUM. The hidden value 999 must not enter 
the sum.
+    ColumnPtr input = nullable_ints({10, 999}, {0, 1});
+    check_streaming(function, {input});
+    for (int mode : {0, 1, 2, 3}) {
+        check_unary_batch_update(function, input, mode);
+    }
+    Arena arena;
+    AggregateFunctionGuard state(function.get());
+    add_column(function, state.data(), *input, arena);
+    auto result = function->get_return_type()->create_column();
+    function->insert_result_into(state.data(), *result);
+    EXPECT_EQ(assert_cast<const ColumnInt64&>(*result).get_data()[0], 10);
+    function->reset(state.data());
+    function->insert_result_into(state.data(), *result);
+    EXPECT_EQ(assert_cast<const ColumnInt64&>(*result).get_data()[1], 0);
+}
+
+TEST(NullableAggregationV2Test, NonNullableNumericColumnsUseNestedEmptyStates) 
{
+    // Two rows are enough to put NULL before or after one value. The hidden 
value 999
+    // must not enter a partial state. One NULL row checks an all-NULL batch. 
No rows
+    // check empty streaming output and serialization of an untouched 
aggregate state.
+    Columns inputs {nullable_ints({10}, {0}), nullable_ints({10, 999}, {0, 1}),
+                    nullable_ints({999, 10}, {1, 0}), nullable_ints({999}, 
{1}),
+                    nullable_ints({}, {})};
+    auto type = std::make_shared<DataTypeInt64>();
+    for (const auto* name : {"sum", "avg", "min", "max"}) {
+        SCOPED_TRACE(name);
+        auto function = nullable_function(name, {make_nullable(type)}, false);
+        auto nested = nullable_function(name, {type}, false);
+        ASSERT_FALSE(function->create_serialize_column()->is_nullable());
+        
ASSERT_TRUE(function->get_serialized_type()->equals(*nested->get_serialized_type()));
+        for (const auto& input : inputs) {
+            check_streaming(function, {input});
+            check_column_serializers(function, {input});
+        }
+    }
+}
+
+TEST(NullableAggregationV2Test, 
NonNullableBitmapColumnsKeepOnlyRequiredNullMarks) {
+    auto type = make_nullable(std::make_shared<DataTypeBitMap>());
+    for (bool intersect : {false, true}) {
+        const auto* name = intersect ? "bitmap_intersect" : "bitmap_union";
+        SCOPED_TRACE(name);
+        auto function = nullable_function(name, {type}, false);
+        ASSERT_EQ(function->get_serialized_type()->is_nullable(), intersect);
+        // The second row is NULL or a real empty bitmap. Both have an empty 
nested
+        // payload. UNION keeps {1} in both cases. INTERSECT keeps {1} only 
for NULL.
+        for (UInt8 null_second : {0, 1}) {
+            auto bitmaps = ColumnBitmap::create();
+            BitmapValue one;
+            one.add(1);
+            bitmaps->insert_value(one);
+            bitmaps->insert_default();
+            auto nulls = ColumnUInt8::create();
+            nulls->get_data().assign({0, null_second});
+            ColumnPtr input = ColumnNullable::create(std::move(bitmaps), 
std::move(nulls));
+            check_streaming(function, {input});
+            check_column_serializers(function, {input});
+            Arena arena;
+            AggregateFunctionGuard state(function.get());
+            add_column(function, state.data(), *input, arena);
+            auto result = function->get_return_type()->create_column();
+            function->insert_result_into(state.data(), *result);
+            EXPECT_EQ(assert_cast<const 
ColumnBitmap&>(*result).get_data()[0].cardinality(),
+                      intersect && !null_second ? 0 : 1);
+        }
+    }
+}
+
+TEST(NullableAggregationV2Test, NonNullableVariadicStateNeedsNoValidityPrefix) 
{
+    auto text_type = std::make_shared<DataTypeString>();
+    auto count_type = std::make_shared<DataTypeInt32>();
+    auto function =
+            nullable_function("topn", {make_nullable(text_type), 
make_nullable(count_type)}, false);
+    auto nested = nullable_function("topn", {text_type, count_type}, false);
+    EXPECT_EQ(function->size_of_data(), nested->size_of_data());
+    EXPECT_FALSE(function->get_serialized_type()->is_nullable());
+
+    // Four rows cover every NULL pair. Only ('x', 1) is valid. A NULL count 
hides zero,
+    // which TOPN rejects if the wrapper reads it. An empty partial must merge 
as no input.
+    auto texts = ColumnString::create();
+    for (const auto* value : {"x", "hidden", "x", "hidden"}) {
+        texts->insert_value(value);
+    }
+    auto counts = ColumnInt32::create();
+    counts->get_data().assign({1, 1, 0, 0});
+    auto text_nulls = ColumnUInt8::create();
+    text_nulls->get_data().assign({0, 1, 0, 1});
+    auto count_nulls = ColumnUInt8::create();
+    count_nulls->get_data().assign({0, 0, 1, 1});
+    Columns input {ColumnNullable::create(std::move(texts), 
std::move(text_nulls)),
+                   ColumnNullable::create(std::move(counts), 
std::move(count_nulls))};
+    check_streaming(function, input);
+    check_column_serializers(function, input);
+    check_streaming(make_agg_state_compatible_function(function), input);
+    // One NULL row also checks a whole batch with no valid TOPN parameters.
+    Columns null_input {input[0]->cut(1, 1), input[1]->cut(1, 1)};
+    check_streaming(function, null_input);
+    check_column_serializers(function, null_input);
+    Arena arena;
+    const IColumn* columns[] = {input[0].get(), input[1].get()};
+    auto serialized = function->create_serialize_column();
+    function->streaming_agg_serialize_to_column(columns, serialized, 4, arena);
+    ASSERT_FALSE(serialized->is_nullable());
+    // Each NULL argument pair must produce a readable empty state. Use the 
nested
+    // serializer as the reference; an empty String cannot encode TOPN's 
parameters.
+    AggregateFunctionGuard empty(nested.get());
+    auto empty_column = nested->create_serialize_column();
+    nested->serialize_without_key_to_column(empty.data(), *empty_column);
+    for (size_t row : {1, 2, 3}) {
+        EXPECT_EQ(serialized->get_data_at(row), empty_column->get_data_at(0));
+    }
+}
+
+TEST(NullableAggregationV2Test, 
NonNullableArrayIntersectionUsesItsNestedEmptyState) {
+    auto array_type =
+            
std::make_shared<DataTypeArray>(make_nullable(std::make_shared<DataTypeInt64>()));
+    auto function = nullable_function("group_array_intersect", 
{make_nullable(array_type)}, false);
+    auto nested = nullable_function("group_array_intersect", {array_type}, 
false);
+    EXPECT_EQ(function->size_of_data(), nested->size_of_data());
+    EXPECT_FALSE(function->get_serialized_type()->is_nullable());
+
+    // Two rows distinguish [1] INTERSECT NULL from [1] INTERSECT []. Unlike 
Bitmap,
+    // this function already stores its initialized flag in the nested String 
state.
+    for (UInt8 null_second : {0, 1}) {
+        auto elements = nullable_ints({1}, {0});
+        auto offsets = ColumnArray::ColumnOffsets::create();
+        offsets->get_data().assign({1, 1});
+        auto arrays = ColumnArray::create(std::move(elements), 
std::move(offsets));
+        auto nulls = ColumnUInt8::create();
+        nulls->get_data().assign({0, null_second});
+        ColumnPtr input = ColumnNullable::create(std::move(arrays), 
std::move(nulls));
+        check_streaming(function, {input});
+        check_column_serializers(function, {input});
+        Arena arena;
+        AggregateFunctionGuard state(function.get());
+        add_column(function, state.data(), *input, arena);
+        auto result = function->get_return_type()->create_column();
+        function->insert_result_into(state.data(), *result);
+        EXPECT_EQ(assert_cast<const ColumnArray&>(*result).get_offsets()[0], 
null_second ? 1 : 0);
+    }
+}
+
+TEST(NullableAggregationV2Test, 
NonNullableUnaryBatchUpdatesHonorPrefixAndValidity) {
+    for (int version : {19, 20, USE_UNIFIED_NULLABLE_AGGREGATION_VERSION}) {
+        for (int density : {0, 50, 100}) {
+            auto nulls = ColumnUInt8::create(4, 0);
+            for (size_t row = 0; row < 4; ++row) {
+                nulls->get_data()[row] = density == 100 || (density == 50 && 
row % 2 == 1);
+            }
+            auto numbers = ColumnInt64::create();
+            numbers->get_data().assign({7, 999, 13, 999});
+            auto bitmaps = ColumnBitmap::create();
+            BitmapValue value;
+            value.add(1);
+            value.add(2);
+            for (size_t row = 0; row < 4; ++row) {
+                bitmaps->insert_value(value);
+            }
+            ColumnPtr null_map = std::move(nulls);
+            Columns inputs {ColumnNullable::create(std::move(numbers), 
null_map),
+                            ColumnNullable::create(std::move(bitmaps), 
null_map)};
+            DataTypes types {make_nullable(std::make_shared<DataTypeInt64>()),
+                             
make_nullable(std::make_shared<DataTypeBitMap>())};
+            const char* names[] = {"sum", "bitmap_intersect"};
+            for (size_t index = 0; index < inputs.size(); ++index) {
+                auto function = AggregateFunctionSimpleFactory::instance().get(
+                        names[index], {types[index]}, nullptr, false, version);
+                for (int mode : {0, 1, 2, 3}) {
+                    check_unary_batch_update(function, inputs[index], mode);
+                }
+            }
+        }
+    }
+}
+
+TEST(NullableAggregationV2Test, 
StableNullableTransferRetainsNegotiatedColumnFormat) {
+    DataTypes unary {make_nullable(std::make_shared<DataTypeInt64>())};
+    DataTypes variadic {make_nullable(std::make_shared<DataTypeString>()),
+                        std::make_shared<DataTypeString>()};
+    for (int version : {19, 20, USE_UNIFIED_NULLABLE_AGGREGATION_VERSION}) {
+        for (const auto& entry : {std::pair {"multi_distinct_min", unary},
+                                  std::pair {"multi_distinct_group_concat", 
variadic}}) {
+            auto function = AggregateFunctionSimpleFactory::instance().get(
+                    entry.first, entry.second, nullptr, false, version);
+            ASSERT_NE(function, nullptr);
+            AggregateFunctionPtr stable(function->transmit_to_stable());
+            ASSERT_NE(stable, nullptr);
+            EXPECT_EQ(stable->get_serialized_type()->get_name(),
+                      function->get_serialized_type()->get_name());
+        }
+    }
+}
+
+TEST(NullableAggregationV2Test, LegacyCodecForwardsStableDistinctOrder) {
+    auto string = std::make_shared<DataTypeString>();
+    auto function = AggregateFunctionSimpleFactory::instance().get(
+            "multi_distinct_group_concat", {make_nullable(string), string}, 
nullptr, true, 19);
+    ASSERT_NE(function, nullptr);
+    auto codec = make_agg_state_compatible_function(function);
+    codec->set_version(19);
+    AggregateFunctionPtr stable(codec->transmit_to_stable());
+    ASSERT_NE(stable, nullptr);
+    EXPECT_TRUE(stable->needs_deserialize_and_merge_scratch());
+    auto values = ColumnString::create();
+    auto separator = ColumnString::create();
+    for (const auto* value : {"b", "a", "b"}) {
+        values->insert_value(value);
+        separator->insert_value(",");
+    }
+    ColumnPtr input = ColumnNullable::create(std::move(values), 
ColumnUInt8::create(3, 0));
+    const IColumn* columns[] = {input.get(), separator.get()};
+    AggregateFunctionGuard state(stable.get());
+    Arena arena;
+    stable->add_batch_single_place(3, state.data(), columns, arena);
+    auto result = stable->get_return_type()->create_column();
+    stable->insert_result_into(state.data(), *result);
+    const auto& nullable = assert_cast<const ColumnNullable&>(*result);
+    ASSERT_FALSE(nullable.is_null_at(0));
+    EXPECT_EQ(nullable.get_nested_column().get_data_at(0).to_string(), "b,a");
+}
+
+TEST(NullableAggregationV2Test, 
LegacyUnmarkedBitmapReadersRetainValidityForLaterMerge) {
+    auto type = make_nullable(std::make_shared<DataTypeBitMap>());
+    auto function = 
AggregateFunctionSimpleFactory::instance().get("bitmap_intersect", {type},
+                                                                   nullptr, 
false, 19);
+    ASSERT_FALSE(function->get_serialized_type()->is_nullable());
+    auto bitmaps = ColumnBitmap::create();
+    BitmapValue value;
+    value.add(1);
+    value.add(2);
+    bitmaps->insert_value(value);
+    bitmaps->insert_value(value);
+    ColumnPtr input = ColumnNullable::create(std::move(bitmaps), 
ColumnUInt8::create(2, 0));
+    const IColumn* columns[] = {input.get()};
+    Arena arena;
+    auto serialized = function->create_serialize_column();
+    function->streaming_agg_serialize_to_column(columns, serialized, 2, arena);
+    for (int reader : {0, 1, 2, 3}) {
+        AggregateFunctionGuard decoded(function.get());
+        AggregateFunctionGuard merged(function.get());
+        AggregateDataPtr places[] = {decoded.data(), decoded.data()};
+        Arena scratch_arena;
+        AggregateDataPtr scratch = nullptr;
+        if (function->needs_deserialize_and_merge_scratch()) {
+            scratch = scratch_arena.aligned_alloc(2 * function->size_of_data(),
+                                                  function->align_of_data());
+        }
+        switch (reader) {
+        case 0:
+            function->deserialize_and_merge_vec(places, 0, scratch, 
serialized.get(), arena, 2);
+            break;
+        case 1:
+            places[0] = nullptr;
+            function->deserialize_and_merge_vec_selected(places, 0, scratch, 
serialized.get(),
+                                                         arena, 2);
+            break;
+        case 2:
+            function->deserialize_and_merge_from_column_range(decoded.data(), 
*serialized, 0, 1,
+                                                              arena);
+            break;
+        case 3:
+            function->deserialize_from_column_row(decoded.data(), *serialized, 
0, arena);
+            break;
+        }
+        // Finalizing decoded directly hides a missing flag for nonnullable 
SQL results.
+        function->merge(merged.data(), decoded.data(), arena);
+        auto result = function->get_return_type()->create_column();
+        function->insert_result_into(merged.data(), *result);
+        const auto& actual = assert_cast<const 
ColumnBitmap&>(*result).get_data()[0];
+        EXPECT_EQ(actual.cardinality(), 2) << "reader=" << reader;
+        EXPECT_TRUE(actual.contains(1));
+        EXPECT_TRUE(actual.contains(2));
+    }
+}
+
+TEST(NullableAggregationV2Test, 
BitmapStateMarkerSurvivesOldSchemaCompactionCodec) {
+    auto type = std::make_shared<DataTypeAggState>(
+            DataTypes {make_nullable(std::make_shared<DataTypeBitMap>())}, 
false,
+            "bitmap_intersect", 19);
+    auto function = type->get_nested_function();
+    auto serialized = type->create_column();
+    // New no-input state versus the legal historical encoding of an actual 
empty bitmap.
+    const std::array<char, 1> no_input {0};
+    const std::array<char, 3> empty_bitmap {1, 1, 0};
+    auto& strings = assert_cast<ColumnString&>(*serialized);
+    strings.insert_data(no_input.data(), no_input.size());
+    strings.insert_data(empty_bitmap.data(), empty_bitmap.size());
+    Arena arena;
+    for (size_t row = 0; row < 2; ++row) {
+        AggregateFunctionGuard state(function.get());
+        AggregateFunctionGuard partial(function.get());
+        function->deserialize_from_column_row(partial.data(), *serialized, 
row, arena);
+        auto reencoded = type->create_column();
+        function->serialize_without_key_to_column(partial.data(), *reencoded);
+        EXPECT_EQ(reencoded->get_data_at(0), serialized->get_data_at(row));
+        auto values = ColumnBitmap::create();
+        BitmapValue bitmap;
+        bitmap.add(1);
+        bitmap.add(2);
+        values->insert_value(bitmap);
+        auto nulls = ColumnUInt8::create(1, 0);
+        auto input = ColumnNullable::create(std::move(values), 
std::move(nulls));
+        const IColumn* columns[] = {input.get()};
+        function->add(state.data(), columns, 0, arena);
+        function->merge(state.data(), partial.data(), arena);
+        auto result = function->get_return_type()->create_column();
+        function->insert_result_into(state.data(), *result);
+        const auto& bitmap_result = assert_cast<const 
ColumnBitmap&>(*result).get_data()[0];
+        EXPECT_EQ(bitmap_result.cardinality(), row == 0 ? 2 : 0);
+    }
+}
+
+TEST(NullableAggregationV2Test, 
BitmapEmptyStateEncodingTracksOriginAndTypeVersion) {
+    // One real empty bitmap and one encoded no-input marker cover all three 
internal
+    // states. All type versions must retain a decoded marker, but only the 
new codec
+    // can introduce a marker for a fresh empty state. No table or cluster is 
needed.
+    const std::string no_input(1, '\0');
+    const std::string empty_bitmap("\1\1\0", 3);
+    for (int version : {19, 20, USE_UNIFIED_NULLABLE_AGGREGATION_VERSION}) {
+        SCOPED_TRACE(version);
+        auto type = std::make_shared<DataTypeAggState>(
+                DataTypes {make_nullable(std::make_shared<DataTypeBitMap>())}, 
false,
+                "bitmap_intersect", version);
+        auto function = type->get_nested_function();
+        auto encode = [&](ConstAggregateDataPtr state) {
+            auto output = type->create_column();
+            function->serialize_without_key_to_column(state, *output);
+            return output->get_data_at(0).to_string();
+        };
+        const auto& fresh_empty =
+                version < USE_UNIFIED_NULLABLE_AGGREGATION_VERSION ? 
empty_bitmap : no_input;
+        AggregateFunctionGuard fresh(function.get());
+        EXPECT_EQ(encode(fresh.data()), fresh_empty);
+
+        auto input = type->create_column();
+        assert_cast<ColumnString&>(*input).insert_value(no_input);
+        Arena arena;
+        AggregateFunctionGuard decoded(function.get());
+        function->deserialize_from_column_row(decoded.data(), *input, 0, 
arena);
+        EXPECT_EQ(encode(decoded.data()), no_input);
+
+        AggregateFunctionGuard merged(function.get());
+        function->merge(merged.data(), decoded.data(), arena);
+        function->merge(merged.data(), fresh.data(), arena);
+        EXPECT_EQ(encode(merged.data()), no_input);
+
+        // A real empty bitmap is a valid contribution. It must replace the 
no-input
+        // marker, even though both nested bitmap values are empty.
+        auto bitmaps = ColumnBitmap::create();
+        bitmaps->insert_default();
+        auto row = ColumnNullable::create(std::move(bitmaps), 
ColumnUInt8::create(1, 0));
+        const IColumn* columns[] = {row.get()};
+        function->add(merged.data(), columns, 0, arena);
+        EXPECT_EQ(encode(merged.data()), empty_bitmap);
+        function->merge(merged.data(), decoded.data(), arena);
+        EXPECT_EQ(encode(merged.data()), empty_bitmap);
+
+        // Reset discards the decoded marker. The state is fresh again and 
must use
+        // the type version's encoding, not the previous state's encoding.
+        function->reset(merged.data());
+        EXPECT_EQ(encode(merged.data()), fresh_empty);
+    }
+}
+
+TEST(NullableAggregationV2Test, StateCombinatorsKeepTheTypeVersion) {
+    // One empty state and one bitmap value are sufficient to expose a codec 
change.
+    // Version 21 encodes no input as [0]. Versions 19 and 20 encode an empty 
bitmap.
+    // A query version must not replace the version stored in the AGG_STATE 
type.
+    for (int type_version : {19, 20, 
USE_UNIFIED_NULLABLE_AGGREGATION_VERSION}) {
+        for (int query_version : {19, 20, 
USE_UNIFIED_NULLABLE_AGGREGATION_VERSION}) {
+            for (int combinator = 0; combinator < 3; ++combinator) {
+                SCOPED_TRACE(::testing::Message()
+                             << "type=" << type_version << ", query=" << 
query_version
+                             << ", combinator=" << combinator);
+                const DataTypes arguments 
{make_nullable(std::make_shared<DataTypeBitMap>())};
+                auto type = std::make_shared<DataTypeAggState>(arguments, 
false, "bitmap_intersect",
+                                                               type_version);
+                auto nested = type->get_nested_function();
+                AggregateFunctionPtr function;
+                switch (combinator) {
+                case 0:
+                    function = AggregateStateCombine::create(nested, 
arguments, type);
+                    break;
+                case 1:
+                    function = AggregateStateUnion::create(nested, {type}, 
type);
+                    break;
+                case 2:
+                    function =
+                            AggregateStateMerge::create(nested, {type}, 
nested->get_return_type());
+                    break;
+                }
+
+                // The pipeline sets this version after it creates the 
combinator.
+                function->set_version(query_version);
+                AggregateFunctionGuard empty(function.get());
+                auto serialized = function->create_serialize_column();
+                function->serialize_without_key_to_column(empty.data(), 
*serialized);
+                const std::string expected = type_version < 
USE_UNIFIED_NULLABLE_AGGREGATION_VERSION
+                                                     ? std::string("\1\1\0", 3)
+                                                     : std::string("\0", 1);
+                EXPECT_EQ(serialized->get_data_at(0), StringRef(expected));
+
+                // Read the state with a separate instance reconstructed from 
type metadata.
+                // No input must preserve {1}; a historical empty bitmap must 
remove {1}.
+                DataTypeAggState reader_type(arguments, false, 
"bitmap_intersect", type_version);
+                auto reader = reader_type.get_nested_function();
+                Arena arena;
+                AggregateFunctionGuard result(reader.get());
+                auto values = ColumnBitmap::create();
+                BitmapValue bitmap;
+                bitmap.add(1);
+                values->insert_value(bitmap);
+                auto input = ColumnNullable::create(std::move(values), 
ColumnUInt8::create(1, 0));
+                const IColumn* columns[] = {input.get()};
+                reader->add(result.data(), columns, 0, arena);
+                reader->deserialize_and_merge_from_column_range(result.data(), 
*serialized, 0, 0,
+                                                                arena);
+                auto output = reader->get_return_type()->create_column();
+                reader->insert_result_into(result.data(), *output);
+                const auto& actual = assert_cast<const 
ColumnBitmap&>(*output).get_data()[0];
+                EXPECT_EQ(actual.cardinality(), type_version == 19 ? 0 : 1);

Review Comment:
   [P2] Expect legacy bitmap semantics for type version 20
   
   This test now iterates type version 20, and its earlier serialization 
assertion correctly expects the same empty-bitmap bytes as version 19. A 
type-20 reader consequently decodes a valid empty bitmap and intersects `{1}` 
with it, yielding cardinality 0 and `contains(1) == false`. These two 
assertions instead expect the new no-input-marker semantics for every version 
other than 19, so both fail in all nine type-20 query-version/combinator 
combinations. Use the version-21 codec threshold in both expectations, matching 
the serialization assertion above.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to