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

Mryange 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 b42159f05de [fix](bitmap) Compute consumed bytes from input header 
when deserializing bitmaps (#71169)
b42159f05de is described below

commit b42159f05de9fdf7d6ea2d5a22f2f700ad635beb
Author: linrrarity <[email protected]>
AuthorDate: Tue Dec 1 15:29:55 2026 +0800

    [fix](bitmap) Compute consumed bytes from input header when deserializing 
bitmaps (#71169)
    
    ### Background
    
    64-bit bitmaps (`BITMAP64` / `BITMAP64_V2`) aggregate states concatenate
    multiple bitmaps without per-element byte lengths, so decoding entry `0`
    must advance the buffer pointer to entry `1`:
    
    ```text
    BITMAP64 / V2   : [ type | count | hi32_0 | roaring0 | hi32_1 | roaring1 | 
... ]
    ```
    
    On write, a 32-bit roaring with `n >= 4` array containers and `card`
    elements picks the shorter wire format:
    
    ```text
    v1 (portable): cookie=12346 (no RUN)   : 8 + 8*n + 2*card                 
bytes
                   cookie=12347 (has RUN)  : 4 + ceil(n/8) + 8*n + payload    
bytes
    v2 (native)  : tag=1 (flat uint32_t[]) : 1 + 4 + 4*card                   
bytes
                   tag=2 (portable)        : 1 + v1_size                      
bytes
    ```
    
    On read, `roaring::Roaring::read()` **only restores the integer set in
    memory and discards the wire header** (`12346`/`12347` or
    `tag=1`/`tag=2`); it does not return how many input bytes were consumed.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR:
    PR Type: Bugfix
    
    Problem Summary:
    
    To advance past each decoded entry, Doris called `getSizeInBytes()` on
    the **in-memory object**. When the wire format differs from what the
    decoded bitmap would re-encode to, the cursor jumps by the wrong offset
    and fails or corrupts subsequent groups. This PR returns consumed bytes
    directly during deserialization.
    
    For `n = 80, card = 324` with `{1, 2, 3}` in container `79` (`1` run
    saves `0 B` payload, while `12347` adds `ceil(80/8) - 4 = 6 B` header):
    
    | Format | Formula (`n = 80, card = 324`) | Wire size | Role |
    |---|---|---|---|
    | `tag=2` (no RUN, `12346` header) | `1 + 8 + 8*80 + 2*324` | `1297 B` |
    **Old reader** re-estimates here (`-4 B` short) |
    | `tag=1` (flat `uint32_t[]`) | `1 + 4 + 4*324` | `1301 B` | **Writer**
    emits this (`< 1303 B`) |
    | `tag=2` (with RUN, `12347` header) | `1 + (4 + 10) + 8*80 + 2*324` |
    `1303 B` | `runOptimize()` exceeds `tag=1` |
    
    ```text
    Wire bytes (v2, tag=1 flat):  [ tag=1 | card=324 | 324 uint32s (1301B) ][ 
hi32=9 | roaring1 ]
                                                                            ^ 
real boundary (+1301)
    Old reader: read() loads 324 ints into arrays (no RUN) -> 
getSizeInBytes(false) picks tag=2 (1297B)
                buf += 1297  --> lands 4 bytes EARLY inside roaring0 and 
misreads hi32=9!
    ```
    
    Reproduction under `bitmap_serialize_version = 2` (`4294967296 = 2^32`,
    `65536 = 2^16`):
    
    ```sql
    WITH src AS (
        SELECT
            CASE
                WHEN number < 312 THEN 4294967296 + (number DIV 4) * 65536 + 
(number % 4) * 10 -- hi32=1, containers 0..77 (4 sparse ints each)
                WHEN number < 321 THEN 4294967296 + 78 * 65536 + (number - 312) 
* 10           -- hi32=1, container 78 (9 sparse ints)
                WHEN number < 324 THEN 4294967296 + 79 * 65536 + (number - 320) 
               -- hi32=1, container 79 ({1,2,3} -> 1 RUN, 0B saved)
                ELSE 9 * 4294967296 + 10                                        
               -- hi32=9: second group (9 << 32) | 10
            END AS v
        FROM numbers("number" = "325")
    ),
    bm AS (
        SELECT bitmap_union(to_bitmap(v)) AS b FROM src
    )
    SELECT
        bitmap_count(b) AS orig_cnt,
        bitmap_count(bitmap_from_base64(bitmap_to_base64(b))) AS roundtrip_cnt,
        bitmap_contains(bitmap_from_base64(bitmap_to_base64(b)), 9 * 4294967296 
+ 10) AS has_hi9
    FROM bm;
    ```
    
    | Before the fix (`master` `e1ed017a6c2`) | With the fix |
    |---|---|
    | `ERROR 1105 (HY000) at line 1: errCode = 2, detailMessage =
    (10.26.20.3)[RUNTIME_ERROR]bitmap_from_base64 decode failed: base64:
    DQIB...` | `orig_cnt: 325`, `roundtrip_cnt: 325`, `has_hi9: 1` |
    
    ### Details
    
    - **Change map:** `+78 -12` production code
    (`be/src/core/value/bitmap_value.h`, `be/src/util/bitmap_intersect.h`)
    and `+266 -0` unit tests (`be/test/core/value/bitmap_value_test.cpp`).
    - **Frequency:** Triggers whenever an unframed `BITMAP64`,
    `BITMAP64_V2`, or `BitmapIntersect` stream contains a bitmap whose wire
    size differs from its post-decode `getSizeInBytes()` (e.g., v2 `tag=1`
    vs `tag=2`, or v1 `12346` before vs `12347` after `runOptimize()`).
    - **Root cause:** `detail::Roaring64Map::read` and
    `BitmapIntersect::deserialize` discarded wire-format framing during
    decode and inferred consumed bytes via `read_var.getSizeInBytes(is_v1)`
    / `bitmap.getSizeInBytes()`.
    - **Why existing tests missed it:** Existing unit tests
    (`BitmapValueTest.write_read`, `bitmap_serde`,
    `intersect_count_decodes_consecutive_bitmaps`) and regression suites
    (`test_bitmap_serialize.groovy`, `test_bitmap_function.groovy`) only use
    small bitmaps that never hit the `n > 32` container `12346`/`12347` or
    v2 `tag=1`/`tag=2` crossover.
    - **Fix:** Added single-pass `Roaring64Map::read_roaring`
    (`ra_portable_deserialize(..., &readbytes)` for portable/v2-`tag=2`,
    O(1) header size for v2-`tag=1`) and
    `BitmapValue::deserialize_with_size`, updating `Roaring64Map::read` and
    `BitmapIntersect::deserialize` to advance by actual consumed bytes.
    - **Other paths and branches:** Other `BitmapValue::deserialize` callers
    in `be/src/` (columns, SerDe, storage, `AggOrthBitmapBaseData`, base64)
    have explicit length framing or a single bitmap and are unaffected.
    Release branches (`branch-4.0`, `branch-4.1`, etc.) were not fetched or
    checked.
    
    ### Testing
    
    - E2E SQL query above against an isolated Release FE+BE cluster
    (`bitmap_serialize_version = 2`): fails with `ERROR 1105 ...
    bitmap_from_base64 decode failed` on `master` (`e1ed017a6c2`), and
    returns `325 | 325 | 1` with the current branch build.
    - `bash ./run-be-ut.sh --run
    --filter="BitmapValueTest.*:AggBitmapTest.*" -j 24` (ASAN_UT on
    `37d6ad5b725`): 50/50 tests passed, including the new
    `BitmapValueTest.deserialize_consumes_actual_input_size` covering v1
    (`12346` vs `12347`), v2 (`tag=1` vs `tag=2`), `BitmapIntersect`, and
    `EMPTY`/`SINGLE`/`SET`/`SET_V2`.
    - After the latest comment and `[[unlikely]]` edit in
    `be/src/core/value/bitmap_value.h`: verified with the Release BE E2E
    query above and `clang++ -fsyntax-only` on
    `be/test/core/value/bitmap_value_test.cpp`.
    
    ### Release note
    
    Fix cursor misalignment when deserializing concatenated `BITMAP64`,
    `BITMAP64_V2`, and `BitmapIntersect` payloads whose wire size differs
    from the decoded bitmap's re-encoded size.
    
    ### Check List (For Author)
    
    - Behavior changed: No
    - Does this need documentation: No
    - Pre-submission status: Partially verified: E2E Release SQL and syntax
    check passed on the latest edit; ASAN BE unit tests (50/50) ran on
    `37d6ad5b725` before the comment and `[[unlikely]]` edit
    
    ### AI Disclosure
    
    - Tool: Antigravity
    - Generated: the fix, unit tests, and this description
    - Human review: not stated
---
 be/src/core/value/bitmap_value.h         |  75 ++++++++-
 be/src/util/bitmap_intersect.h           |  16 +-
 be/test/core/value/bitmap_value_test.cpp | 266 +++++++++++++++++++++++++++++++
 3 files changed, 345 insertions(+), 12 deletions(-)

diff --git a/be/src/core/value/bitmap_value.h b/be/src/core/value/bitmap_value.h
index dd1fdc14d78..450c49e53d7 100644
--- a/be/src/core/value/bitmap_value.h
+++ b/be/src/core/value/bitmap_value.h
@@ -798,14 +798,19 @@ public:
      * This function is unsafe in the sense that if you provide bad data,
      * many bytes could be read, possibly causing a buffer overflow. See also 
readSafe.
      */
-    static Roaring64Map read(const char* buf) {
+    static Roaring64Map read(const char* buf, size_t* bytes_read = nullptr) {
         Roaring64Map result;
+        const char* start = buf;
 
         bool is_v1 = BitmapTypeCode::BITMAP32 == *buf || 
BitmapTypeCode::BITMAP64 == *buf;
         bool is_bitmap32 = BitmapTypeCode::BITMAP32 == *buf || 
BitmapTypeCode::BITMAP32_V2 == *buf;
         bool is_bitmap64 = BitmapTypeCode::BITMAP64 == *buf || 
BitmapTypeCode::BITMAP64_V2 == *buf;
         if (is_bitmap32) {
-            roaring::Roaring read = roaring::Roaring::read(buf + 1, is_v1);
+            size_t roaring_bytes = 0;
+            roaring::Roaring read = read_roaring(buf + 1, is_v1, 
&roaring_bytes);
+            if (bytes_read != nullptr) {
+                *bytes_read = 1 + roaring_bytes;
+            }
             result.emplaceOrInsert(0, std::move(read));
             return result;
         }
@@ -824,11 +829,15 @@ public:
             uint32_t key = decode_fixed32_le(reinterpret_cast<const 
uint8_t*>(buf));
             buf += sizeof(uint32_t);
             // read map value Roaring
-            roaring::Roaring read_var = roaring::Roaring::read(buf, is_v1);
+            size_t roaring_bytes = 0;
+            roaring::Roaring read_var = read_roaring(buf, is_v1, 
&roaring_bytes);
             // forward buffer past the last Roaring Bitmap
-            buf += read_var.getSizeInBytes(is_v1);
+            buf += roaring_bytes;
             result.emplaceOrInsert(key, std::move(read_var));
         }
+        if (bytes_read != nullptr) {
+            *bytes_read = static_cast<size_t>(buf - start);
+        }
         return result;
     }
 
@@ -998,6 +1007,34 @@ private:
         bitmap.setCopyOnWrite(copyOnWrite);
         return bitmap;
     }
+
+    static roaring::Roaring read_roaring(const char* buf, bool is_v1, size_t* 
bytes_read) {
+        if (!is_v1) {
+            // CRoaring native (v2) layout:
+            //   tag=1 (flat array): [ 1(1B) | card(4B) | uint32[card] ]
+            //   tag=2 (portable)  : [ 2(1B) | portable roaring bytes ]
+            const auto tag = static_cast<uint8_t>(buf[0]);
+            if (tag == 1) {
+                uint32_t card = 0;
+                memcpy(&card, buf + 1, sizeof(uint32_t));
+                *bytes_read = 1 + sizeof(uint32_t) + static_cast<size_t>(card) 
* sizeof(uint32_t);
+                return roaring::Roaring::read(buf, false);
+            }
+            if (tag != 2) [[unlikely]] {
+                throw std::runtime_error("invalid native roaring serialization 
tag");
+            }
+        }
+        const char* portable_buf = is_v1 ? buf : buf + 1;
+        roaring::Roaring r;
+        size_t readbytes = 0;
+        if 
(!roaring::internal::ra_portable_deserialize(&r.roaring.high_low_container, 
portable_buf,
+                                                        
std::numeric_limits<size_t>::max(),
+                                                        &readbytes)) {
+            throw std::runtime_error("failed to deserialize portable roaring 
bitmap");
+        }
+        *bytes_read = (is_v1 ? 0 : 1) + readbytes;
+        return r;
+    }
 };
 
 // Forked from 
https://github.com/RoaringBitmap/CRoaring/blob/v4.7.2/cpp/roaring/roaring64map.hh
@@ -2470,11 +2507,23 @@ public:
 
     // Deserialize a bitmap value from `src`.
     // Return false if `src` begins with unknown type code, true otherwise.
-    bool deserialize(const char* src) {
+    bool deserialize(const char* src) { return _deserialize(src); }
+
+    // Deserialize a bitmap value from `src` and return the consumed byte 
count, or 0 on failure.
+    size_t deserialize_with_size(const char* src) {
+        size_t consumed = 0;
+        return _deserialize(src, &consumed) ? consumed : 0;
+    }
+
+private:
+    bool _deserialize(const char* src, size_t* bytes_read = nullptr) {
         reset();
         switch (*src) {
         case BitmapTypeCode::EMPTY:
             _type = EMPTY;
+            if (bytes_read != nullptr) {
+                *bytes_read = 1;
+            }
             break;
         case BitmapTypeCode::SINGLE32:
             _type = SINGLE;
@@ -2484,6 +2533,9 @@ public:
                 _set.clear();
                 _set.insert(_sv);
             }
+            if (bytes_read != nullptr) {
+                *bytes_read = 1 + sizeof(uint32_t);
+            }
             break;
         case BitmapTypeCode::SINGLE64:
             _type = SINGLE;
@@ -2493,6 +2545,9 @@ public:
                 _set.clear();
                 _set.insert(_sv);
             }
+            if (bytes_read != nullptr) {
+                *bytes_read = 1 + sizeof(uint64_t);
+            }
             break;
         case BitmapTypeCode::BITMAP32:
         case BitmapTypeCode::BITMAP64:
@@ -2501,7 +2556,8 @@ public:
             _type = BITMAP;
             _is_shared = false;
             try {
-                _bitmap = 
std::make_shared<detail::Roaring64Map>(detail::Roaring64Map::read(src));
+                _bitmap = std::make_shared<detail::Roaring64Map>(
+                        detail::Roaring64Map::read(src, bytes_read));
             } catch (const std::runtime_error& e) {
                 LOG(ERROR) << "Decode roaring bitmap failed, " << e.what();
                 return false;
@@ -2525,6 +2581,9 @@ public:
             if (!config::enable_set_in_bitmap_value) {
                 _convert_set_to_bitmap();
             }
+            if (bytes_read != nullptr) {
+                *bytes_read = 1 + sizeof(count) + sizeof(uint64_t) * count;
+            }
             break;
         }
         case BitmapTypeCode::SET_V2: {
@@ -2545,6 +2604,9 @@ public:
                 _type = SET;
                 _set.read(src, size, true);
             }
+            if (bytes_read != nullptr) {
+                *bytes_read = 1 + sizeof(uint32_t) + sizeof(uint64_t) * size;
+            }
             break;
         }
         default:
@@ -2556,6 +2618,7 @@ public:
         return true;
     }
 
+public:
     int64_t minimum() const {
         switch (_type) {
         case SINGLE:
diff --git a/be/src/util/bitmap_intersect.h b/be/src/util/bitmap_intersect.h
index 65d4a80b45d..1d308ee85eb 100644
--- a/be/src/util/bitmap_intersect.h
+++ b/be/src/util/bitmap_intersect.h
@@ -243,9 +243,11 @@ public:
         for (int32_t i = 0; i < bitmaps_size; i++) {
             T key;
             detail::Helper::read_from(&reader, &key);
-            BitmapValue bitmap(reader);
-            reader += bitmap.getSizeInBytes();
-            _bitmaps[key] = bitmap;
+            BitmapValue bitmap;
+            const size_t consumed = bitmap.deserialize_with_size(reader);
+            DCHECK_GT(consumed, 0);
+            reader += consumed;
+            _bitmaps[key] = std::move(bitmap);
         }
     }
 
@@ -342,9 +344,11 @@ public:
         for (int32_t i = 0; i < bitmaps_size; i++) {
             std::string key;
             detail::Helper::read_from(&reader, &key);
-            BitmapValue bitmap(reader);
-            reader += bitmap.getSizeInBytes();
-            _bitmaps[key] = bitmap;
+            BitmapValue bitmap;
+            const size_t consumed = bitmap.deserialize_with_size(reader);
+            DCHECK_GT(consumed, 0);
+            reader += consumed;
+            _bitmaps[key] = std::move(bitmap);
         }
     }
 
diff --git a/be/test/core/value/bitmap_value_test.cpp 
b/be/test/core/value/bitmap_value_test.cpp
index 34abd8df63e..9bd10140c52 100644
--- a/be/test/core/value/bitmap_value_test.cpp
+++ b/be/test/core/value/bitmap_value_test.cpp
@@ -28,6 +28,7 @@
 
 #include "gtest/gtest.h"
 #include "gtest/gtest_pred_impl.h"
+#include "util/bitmap_intersect.h"
 #include "util/coding.h"
 #include "util/url_coding.h"
 
@@ -1742,5 +1743,270 @@ TEST(BitmapValueTest, invalid_data) {
     BitmapValue bitmap;
     char data[] = {0x02, static_cast<char>(0xff), 0x03};
     EXPECT_FALSE(bitmap.deserialize(data));
+    EXPECT_EQ(bitmap.deserialize_with_size(data), 0);
+}
+
+TEST(BitmapValueTest, deserialize_consumes_actual_input_size) {
+    auto encode_header_bitmap = [](uint32_t cookie, uint32_t num_containers, 
bool has_runs) {
+        // Construct a valid portable roaring buffer containing array 
containers of card=1
+        // under either cookie 12346 or 12347 (even when has_runs is false).
+        std::string out;
+        const size_t run_bitset_bytes = has_runs ? ((num_containers + 7) / 8) 
: 0;
+        const size_t offsets_bytes =
+                (num_containers >= 4) ? (num_containers * sizeof(uint32_t)) : 
0;
+        const size_t header_bytes = sizeof(uint32_t) + run_bitset_bytes +
+                                    num_containers * sizeof(uint32_t) + 
offsets_bytes;
+        out.resize(header_bytes + num_containers * sizeof(uint16_t), '\0');
+        char* p = out.data();
+        encode_fixed32_le(reinterpret_cast<uint8_t*>(p), cookie | 
((num_containers - 1) << 16));
+        p += sizeof(uint32_t) + run_bitset_bytes;
+        for (uint32_t c = 0; c < num_containers; ++c) {
+            encode_fixed16_le(reinterpret_cast<uint8_t*>(p), 
static_cast<uint16_t>(c));
+            encode_fixed16_le(reinterpret_cast<uint8_t*>(p + 2), uint16_t {0});
+            p += sizeof(uint32_t);
+        }
+        if (num_containers >= 4) {
+            for (uint32_t c = 0; c < num_containers; ++c) {
+                encode_fixed32_le(reinterpret_cast<uint8_t*>(p),
+                                  static_cast<uint32_t>(header_bytes + c * 
sizeof(uint16_t)));
+                p += sizeof(uint32_t);
+            }
+        }
+        for (uint32_t c = 0; c < num_containers; ++c) {
+            encode_fixed16_le(reinterpret_cast<uint8_t*>(p), uint16_t {1});
+            p += sizeof(uint16_t);
+        }
+        return out;
+    };
+
+    // Case 1 (v1): Unoptimized 12346 bitmap whose size grows after 
runOptimize() (+6 bytes).
+    {
+        Roaring raw;
+        for (uint32_t c = 0; c < 79; ++c) {
+            raw.add((c << 16) + 1);
+        }
+        raw.add((79U << 16) + 1);
+        raw.add((79U << 16) + 2);
+        raw.add((79U << 16) + 3);
+
+        Roaring optimized(raw);
+        optimized.runOptimize();
+        const size_t raw_portable_size = raw.getSizeInBytes(true);
+        const size_t opt_portable_size = optimized.getSizeInBytes(true);
+        ASSERT_GT(opt_portable_size, raw_portable_size);
+
+        // BITMAP32
+        std::string bm32(1 + raw_portable_size, '\0');
+        bm32[0] = BitmapTypeCode::BITMAP32;
+        ASSERT_EQ(raw.write(bm32.data() + 1, true), raw_portable_size);
+        BitmapValue decoded32;
+        EXPECT_EQ(decoded32.deserialize_with_size(bm32.data()), bm32.size());
+        EXPECT_EQ(decoded32.cardinality(), 82);
+
+        // Multi-key BITMAP64: raw unoptimized first group followed by second 
group.
+        Roaring second;
+        second.add(42);
+        std::string bm64;
+        bm64.push_back(BitmapTypeCode::BITMAP64);
+        uint8_t varint_buf[10];
+        auto* varint_end = encode_varint64(varint_buf, 2);
+        bm64.append(reinterpret_cast<const char*>(varint_buf), varint_end - 
varint_buf);
+        const size_t g0_off = bm64.size();
+        bm64.resize(g0_off + sizeof(uint32_t) + raw_portable_size);
+        encode_fixed32_le(reinterpret_cast<uint8_t*>(bm64.data() + g0_off), 1);
+        raw.write(bm64.data() + g0_off + sizeof(uint32_t), true);
+        const size_t g1_off = bm64.size();
+        bm64.resize(g1_off + sizeof(uint32_t) + second.getSizeInBytes(true));
+        encode_fixed32_le(reinterpret_cast<uint8_t*>(bm64.data() + g1_off), 2);
+        second.write(bm64.data() + g1_off + sizeof(uint32_t), true);
+
+        BitmapValue decoded64;
+        EXPECT_EQ(decoded64.deserialize_with_size(bm64.data()), bm64.size());
+        EXPECT_EQ(decoded64.cardinality(), 83);
+        EXPECT_TRUE(decoded64.contains((uint64_t {2} << 32) + 42));
+
+        // Multi-key BitmapIntersect without length prefix.
+        std::string intersect_buf;
+        intersect_buf.resize(sizeof(int32_t));
+        detail::Helper::write_to(int32_t {2}, intersect_buf.data());
+        for (auto& [k, payload] : std::vector<std::pair<int32_t, std::string>> 
{
+                     {11, bm32}, {22, std::string(1, BitmapTypeCode::EMPTY)}}) 
{
+            const size_t off = intersect_buf.size();
+            intersect_buf.resize(off + sizeof(int32_t) + payload.size());
+            char* w = detail::Helper::write_to(k, intersect_buf.data() + off);
+            memcpy(w, payload.data(), payload.size());
+        }
+        BitmapIntersect<int32_t> intersect(intersect_buf.data());
+        EXPECT_TRUE(intersect.has_same_keys([&]() {
+            BitmapIntersect<int32_t> expected;
+            expected.add_key(11);
+            expected.add_key(22);
+            return expected;
+        }()));
+        EXPECT_EQ(intersect.intersect_count(), 0);
+    }
+
+    // Case 2 (v1): Fixed SERIAL_COOKIE 12347 buffer with zero run containers 
(n=1 shorter, n=80 longer).
+    for (uint32_t n : {1U, 80U}) {
+        const std::string payload = encode_header_bitmap(12347U, n, true);
+        std::string bm64;
+        bm64.push_back(BitmapTypeCode::BITMAP64);
+        uint8_t varint_buf[10];
+        auto* varint_end = encode_varint64(varint_buf, 2);
+        bm64.append(reinterpret_cast<const char*>(varint_buf), varint_end - 
varint_buf);
+        const size_t g0_off = bm64.size();
+        bm64.resize(g0_off + sizeof(uint32_t) + payload.size());
+        encode_fixed32_le(reinterpret_cast<uint8_t*>(bm64.data() + g0_off), 1);
+        memcpy(bm64.data() + g0_off + sizeof(uint32_t), payload.data(), 
payload.size());
+
+        Roaring tail;
+        tail.add(77);
+        const size_t g1_off = bm64.size();
+        bm64.resize(g1_off + sizeof(uint32_t) + tail.getSizeInBytes(true));
+        encode_fixed32_le(reinterpret_cast<uint8_t*>(bm64.data() + g1_off), 5);
+        tail.write(bm64.data() + g1_off + sizeof(uint32_t), true);
+
+        BitmapValue decoded;
+        EXPECT_EQ(decoded.deserialize_with_size(bm64.data()), bm64.size());
+        EXPECT_EQ(decoded.cardinality(), n + 1);
+        EXPECT_TRUE(decoded.contains((uint64_t {5} << 32) + 77));
+    }
+
+    // Case 3 (v2): Native tag=1 flat uint32 array where decoded 
getSizeInBytes(false) shrinks to tag=2.
+    {
+        Roaring raw;
+        for (uint32_t c = 0; c < 78; ++c) {
+            for (uint32_t v = 0; v < 4; ++v) {
+                raw.add((c << 16) + v * 10);
+            }
+        }
+        for (uint32_t v = 0; v < 9; ++v) {
+            raw.add((78U << 16) + v * 10);
+        }
+        raw.add((79U << 16) + 1);
+        raw.add((79U << 16) + 2);
+        raw.add((79U << 16) + 3);
+        ASSERT_EQ(raw.cardinality(), 324);
+
+        Roaring optimized(raw);
+        optimized.runOptimize();
+        const size_t opt_v2_size = optimized.getSizeInBytes(false);
+        const size_t unopt_v2_size = raw.getSizeInBytes(false);
+        ASSERT_LT(unopt_v2_size, opt_v2_size);
+        std::string opt_v2_bytes(opt_v2_size, '\0');
+        ASSERT_EQ(optimized.write(opt_v2_bytes.data(), false), opt_v2_size);
+        ASSERT_EQ(static_cast<uint8_t>(opt_v2_bytes[0]), 1);
+
+        // BITMAP32_V2
+        std::string bm32_v2(1 + opt_v2_size, '\0');
+        bm32_v2[0] = BitmapTypeCode::BITMAP32_V2;
+        memcpy(bm32_v2.data() + 1, opt_v2_bytes.data(), opt_v2_size);
+        BitmapValue decoded32;
+        EXPECT_EQ(decoded32.deserialize_with_size(bm32_v2.data()), 
bm32_v2.size());
+        EXPECT_EQ(decoded32.cardinality(), 324);
+
+        // BITMAP64_V2 multi-group
+        Roaring tail;
+        tail.add(10);
+        std::string bm64_v2;
+        bm64_v2.push_back(BitmapTypeCode::BITMAP64_V2);
+        uint8_t varint_buf[10];
+        auto* varint_end = encode_varint64(varint_buf, 2);
+        bm64_v2.append(reinterpret_cast<const char*>(varint_buf), varint_end - 
varint_buf);
+        const size_t g0_off = bm64_v2.size();
+        bm64_v2.resize(g0_off + sizeof(uint32_t) + opt_v2_size);
+        encode_fixed32_le(reinterpret_cast<uint8_t*>(bm64_v2.data() + g0_off), 
1);
+        memcpy(bm64_v2.data() + g0_off + sizeof(uint32_t), 
opt_v2_bytes.data(), opt_v2_size);
+        const size_t g1_off = bm64_v2.size();
+        bm64_v2.resize(g1_off + sizeof(uint32_t) + tail.getSizeInBytes(false));
+        encode_fixed32_le(reinterpret_cast<uint8_t*>(bm64_v2.data() + g1_off), 
9);
+        tail.write(bm64_v2.data() + g1_off + sizeof(uint32_t), false);
+
+        BitmapValue decoded64;
+        EXPECT_EQ(decoded64.deserialize_with_size(bm64_v2.data()), 
bm64_v2.size());
+        EXPECT_EQ(decoded64.cardinality(), 325);
+        EXPECT_TRUE(decoded64.contains((uint64_t {9} << 32) + 10));
+
+        // Multi-key BitmapIntersect<std::string_view> (no length prefix)
+        std::string sv_buf;
+        sv_buf.resize(sizeof(int32_t));
+        detail::Helper::write_to(int32_t {2}, sv_buf.data());
+        for (const auto& [k, payload] : std::vector<std::pair<std::string, 
std::string>> {
+                     {"first", bm32_v2}, {"second", [&]() {
+                                              BitmapValue s(uint64_t {99});
+                                              std::string 
b(s.getSizeInBytes(), '\0');
+                                              s.write_to(b.data());
+                                              return b;
+                                          }()}}) {
+            const size_t off = sv_buf.size();
+            sv_buf.resize(off + detail::Helper::serialize_size(k) + 
payload.size());
+            char* w = detail::Helper::write_to(k, sv_buf.data() + off);
+            memcpy(w, payload.data(), payload.size());
+        }
+        BitmapIntersect<std::string_view> sv_intersect(sv_buf.data());
+        BitmapIntersect<std::string_view> sv_expected;
+        sv_expected.add_key("first");
+        sv_expected.add_key("second");
+        EXPECT_TRUE(sv_intersect.has_same_keys(sv_expected));
+        EXPECT_EQ(sv_intersect.intersect_count(), 0);
+    }
+
+    // Case 4: Non-roaring BitmapTypeCode variants (EMPTY, SINGLE32, SINGLE64, 
SET, SET_V2).
+    {
+        const bool old_enable_set = config::enable_set_in_bitmap_value;
+        config::enable_set_in_bitmap_value = true;
+
+        std::vector<std::string> encoded_values;
+        auto push_bm = [&](const BitmapValue& bm) {
+            std::string b(bm.getSizeInBytes(), '\0');
+            bm.write_to(b.data());
+            encoded_values.push_back(std::move(b));
+        };
+
+        push_bm(BitmapValue());
+        {
+            BitmapValue s;
+            s.add(123);
+            std::string b(1 + sizeof(uint32_t), '\0');
+            b[0] = BitmapTypeCode::SINGLE32;
+            encode_fixed32_le(reinterpret_cast<uint8_t*>(b.data() + 1), 123U);
+            encoded_values.push_back(b);
+        }
+        {
+            std::string b(1 + sizeof(uint64_t), '\0');
+            b[0] = BitmapTypeCode::SINGLE64;
+            encode_fixed64_le(reinterpret_cast<uint8_t*>(b.data() + 1), 
(uint64_t {1} << 40) + 7);
+            encoded_values.push_back(b);
+        }
+        {
+            BitmapValue set_bm;
+            set_bm.add(10);
+            set_bm.add(20);
+            push_bm(set_bm);
+        }
+        {
+            std::string b(1 + sizeof(uint32_t) + 2 * sizeof(uint64_t), '\0');
+            b[0] = BitmapTypeCode::SET_V2;
+            encode_fixed32_le(reinterpret_cast<uint8_t*>(b.data() + 1), 2U);
+            encode_fixed64_le(reinterpret_cast<uint8_t*>(b.data() + 5), 7ULL);
+            encode_fixed64_le(reinterpret_cast<uint8_t*>(b.data() + 13), 9ULL);
+            encoded_values.push_back(b);
+        }
+
+        std::string concatenated;
+        for (const auto& part : encoded_values) {
+            concatenated.append(part);
+        }
+        size_t cursor = 0;
+        for (const auto& part : encoded_values) {
+            BitmapValue bm;
+            const size_t consumed = 
bm.deserialize_with_size(concatenated.data() + cursor);
+            EXPECT_EQ(consumed, part.size());
+            cursor += consumed;
+        }
+        EXPECT_EQ(cursor, concatenated.size());
+
+        config::enable_set_in_bitmap_value = old_enable_set;
+    }
 }
 } // namespace doris


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

Reply via email to