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


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/types/AggStateType.java:
##########
@@ -98,17 +107,67 @@ public String getFunctionName() {
         return functionName;
     }
 
+    public int getBeExecVersion() {
+        return beExecVersion;
+    }
+
+    /** Keep the aggregate signature when choosing a producer's output codec. 
*/
+    public AggStateType withBeExecVersion(int version) {
+        return new AggStateType(functionName, subTypes, subTypeNullables, 
returnNullable, version);
+    }
+
+    /** Compare the aggregate signature, without asserting that its state 
bytes are compatible. */
+    public boolean hasSameAggregateSignature(AggStateType other) {
+        return functionName.equals(other.functionName)
+                && subTypes.equals(other.subTypes)
+                && subTypeNullables.equals(other.subTypeNullables)
+                && returnNullable == other.returnNullable;
+    }
+
+    /**
+     * Allow forward storage casts among versions 19, 20 and 21 without 
changing state bytes.
+     * Version 20 adds Lance row locations and does not change the version 19 
aggregate codecs.
+     * Version 21 keeps these AGG_STATE storage columns and accepts both 
legacy payloads.
+     * For example, nullable SUM still stores a flag followed by the nested 
SUM state.
+     * This contract does not apply to native aggregation intermediate columns.
+     *
+     * Use this forward relation to select a common type for UNION and 
conditional expressions.
+     * Do not select the older type: its Bitmap cast can discard the no-input 
distinction.
+     * Use canCastStoredStateFrom for an explicit conversion to a sink type.
+     */
+    public boolean canUpgradeStoredStateFrom(AggStateType source) {
+        return source.beExecVersion >= 19 && source.beExecVersion < 
beExecVersion
+                && beExecVersion <= 
Config.UNIFIED_NULLABLE_AGGREGATION_MIN_BE_EXEC_VERSION
+                && hasSameAggregateSignature(source);
+    }
+
+    /**
+     * Convert a stored state between the known storage codecs, without 
changing its signature.
+     * The BE reuses byte-compatible columns. For nullable BITMAP_INTERSECT, a 
cast from
+     * version 21 to 19 or 20 converts the no-input marker to the legacy empty 
Bitmap.
+     * That conversion uses the target codec's merge behavior. It is not a 
byte-only relabel.
+     * Keep version-aware identity so the planner retains this CAST at the 
output boundary.
+     */
+    public boolean canCastStoredStateFrom(AggStateType source) {
+        return source.beExecVersion >= 19
+                && source.beExecVersion <= 
Config.UNIFIED_NULLABLE_AGGREGATION_MIN_BE_EXEC_VERSION
+                && beExecVersion >= 19

Review Comment:
   [P2] Allow writes to byte-compatible version-18 SUM states
   
   Create an `AGG_STATE<SUM(BIGINT NULL)> GENERIC` sink while the FE is pinned 
to supported execution version 18, then restore version 21 and run `INSERT INTO 
sink SELECT k, sum_state(v) FROM src` for nullable BIGINT `v`. The reduced plan 
is:
   
   ```text
   Sink(s@18)
     Project(k, Cast(sum_state(v)@21 AS state@18))
       Scan(src)
   ```
   
   `ConvertAggStateCast` keeps the same-signature cast and final `CheckCast` 
rejects it at this version floor. Both versions use the same flag-plus-SUM 
bytes, so the write accepted before version-aware coercion now fails. The same 
floor in `canUpgradeStoredStateFrom` also prevents a common type for these 
stored SUM states. Permit documented byte-compatible versions while retaining 
checks for aggregates whose formats actually changed.



##########
be/benchmark/nullable_allocation_counter.cpp:
##########
@@ -0,0 +1,162 @@
+// 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 "nullable_allocation_counter.h"
+
+#include <benchmark/benchmark.h>
+
+#include <atomic>
+#include <cstddef>
+#include <cstdint>
+#include <iostream>
+#include <string>
+
+namespace doris::nullable_aggregation_benchmark {
+namespace {
+std::atomic<bool> measuring {false};
+std::atomic<int64_t> allocations {0};
+std::atomic<int64_t> allocated_bytes {0};
+std::atomic<int64_t> operations {0};
+std::string benchmark_name;
+thread_local bool in_operation = false;
+thread_local bool in_allocator = false;
+
+class MemoryCounter final : public benchmark::MemoryManager {
+public:
+    void Start() override {
+        allocations = 0;
+        allocated_bytes = 0;
+        operations = 0;
+        measuring = true;
+    }
+    void Stop(Result& result) override {
+        measuring = false;
+        result.num_allocs = allocations;
+        result.total_allocated_bytes = allocated_bytes;
+        // Peak live bytes require free tracking. Use query profiles for that 
measurement;
+        // never present requested allocation bytes as a memory peak.
+        result.max_bytes_used = TombstoneValue;
+        std::cout << R"(NULLABLE_ALLOCATIONS {"benchmark":")" << benchmark_name

Review Comment:
   [P3] Keep allocation diagnostics out of stdout benchmark reports
   
   With allocation counting enabled, `MemoryCounter::Stop` prints a 
`NULLABLE_ALLOCATIONS` line to stdout. Google Benchmark v1.8.0 writes the 
display report to the same stream for `--benchmark_format=json` or 
`--benchmark_format=csv`, so the extra lines invalidate the report. Send the 
diagnostics to stderr or a separate output stream. [Google Benchmark 
runner](https://github.com/google/benchmark/blob/v1.8.0/src/benchmark_runner.cc#L409-L435)



##########
fe/fe-type/src/main/java/org/apache/doris/catalog/AggStateType.java:
##########
@@ -133,6 +154,11 @@ public boolean equals(Object o) {
             return false;
         }
         AggStateType other = (AggStateType) o;
+        // Equal argument layouts do not imply equal state codecs. Keep version
+        // differences visible when the planner translates a cast to catalog 
types.
+        if (getBeExecVersion() != other.getBeExecVersion()) {

Review Comment:
   [P2] Preserve the stored codec when MODIFY COLUMN repeats the SQL type
   
   Create `b AGG_STATE<bitmap_intersect(bitmap null)> GENERIC NOT NULL` at 
version 21 and store a no-input state and a `{7}` state under separate keys. 
With the FE temporarily at version 20 and BEs that support 21, run `ALTER TABLE 
t MODIFY COLUMN b AGG_STATE<bitmap_intersect(bitmap null)> GENERIC NOT NULL 
COMMENT 'new'`. The parsed declaration gets codec 20 even though the visible 
type is unchanged. This equality check makes `SchemaChangeHandler` create a 
shadow column, and `SchemaChangeJobV2` sends a 21-to-20 CAST for the backfill. 
That CAST replaces the no-input marker with an actual empty bitmap, so a later 
`bitmap_intersect_merge(b)` returns empty instead of `{7}`. Carry the original 
codec forward when MODIFY repeats the aggregate signature.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/types/AggStateType.java:
##########
@@ -74,6 +76,12 @@ public class AggStateType extends DataType {
      */
     public AggStateType(String functionName, List<DataType> subTypes,
             List<Boolean> subTypeNullables, boolean returnNullable) {
+        this(functionName, subTypes, subTypeNullables, returnNullable, 
Config.be_exec_version);

Review Comment:
   [P2] Use the statement's pinned version for fresh aggregate states
   
   `NereidsPlanner.plan` pins the query version before binding, but STATE reads 
the mutable global here and COMBINE does the same in its constructor. If `ADMIN 
SET FRONTEND CONFIG` changes version 21 to 20 between those steps, a query such 
as `SELECT bitmap_intersect_merge(s) FROM (SELECT bitmap_intersect_state(b) s 
FROM src) t` can reach this reduced plan:
   
   ```text
   Aggregate(bitmap_intersect_merge(s@20))
     Project(bitmap_intersect_state(b)@20 AS s)
       Scan(src)
   ```
   
   For nullable BITMAP rows NULL and `{7}`, STATE now writes a legacy empty 
bitmap for the NULL input, so MERGE returns empty even though the query pinned 
version 21. The reverse switch can put a version-21 type in a version-20 
fragment that an older BE rejects. Use the pinned statement version for fresh 
STATE and COMBINE types and preserve explicit versions on stored types.



##########
be/src/exprs/aggregate/aggregate_function_state_union.h:
##########
@@ -58,15 +66,32 @@ class AggregateStateUnion : public 
AggregateFunctionNonFinalBase,
 
     void add(AggregateDataPtr __restrict place, const IColumn** columns, 
ssize_t row_num,
              Arena& arena) const override {
+        const IColumn* column = columns[0];
+        if (_input_is_sql_nullable) {
+            const auto* nullable = assert_cast<const ColumnNullable*>(column);
+            // SQL NULL is not an empty aggregate state and has no bytes to 
decode.
+            if (nullable->is_null_at(row_num)) {
+                return;

Review Comment:
   [P2] Preserve outer NULL across bitmap partial merges
   
   For `b BITMAP NOT NULL`, let `s = CASE WHEN p THEN bitmap_intersect_state(b) 
ELSE NULL END`. In a two-phase grouped `bitmap_intersect_merge(s)`, one local 
group can contain only outer NULLs while another group for the same key 
contributes `{7}`. The NULL-only group skips all inputs here, but 
`AggregateStateUnion::serialize` delegates to the plain bitmap aggregate 
because the nested signature is nonnullable. 
`AggregateFunctionBitmapData::write` stores the bitmap without `is_first`, so 
the final merge sees a real empty bitmap and removes `{7}`. This can happen at 
version 21. Carry no-input validity in the combinator's intermediate state and 
cover a two-phase merge with both a NULL-only partial and a contributing 
partial.



-- 
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