Coverage Report

Created: 2026-03-15 18:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/segment/rle_page.h
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#pragma once
19
20
#include "common/cast_set.h"
21
#include "storage/segment/options.h"      // for PageBuilderOptions/PageDecoderOptions
22
#include "storage/segment/page_builder.h" // for PageBuilder
23
#include "storage/segment/page_decoder.h" // for PageDecoder
24
#include "util/coding.h"                  // for encode_fixed32_le/decode_fixed32_le
25
#include "util/rle_encoding.h"            // for RleEncoder/RleDecoder
26
#include "util/slice.h"                   // for OwnedSlice
27
28
namespace doris {
29
#include "common/compile_check_begin.h"
30
namespace segment_v2 {
31
32
enum { RLE_PAGE_HEADER_SIZE = 4 };
33
34
// RLE builder for generic integer and bool types. What is missing is some way
35
// to enforce that this can only be instantiated for INT and BOOL types.
36
//
37
// The page format is as follows:
38
//
39
// 1. Header: (4 bytes total)
40
//
41
//    <num_elements> [32-bit]
42
//      The number of elements encoded in the page.
43
//
44
//    NOTE: all on-disk ints are encoded little-endian
45
//
46
// 2. Element data
47
//
48
//    The header is followed by the rle-encoded element data.
49
//
50
// This Rle encoding algorithm is only effective for repeated INT type and bool type,
51
// It is not good for sequence number or random number. BitshufflePage is recommended
52
// for these case.
53
//
54
// TODO(hkp): optimize rle algorithm
55
template <FieldType Type>
56
class RlePageBuilder : public PageBuilderHelper<RlePageBuilder<Type> > {
57
public:
58
    using Self = RlePageBuilder<Type>;
59
    friend class PageBuilderHelper<Self>;
60
61
13.4k
    Status init() override {
62
13.4k
        switch (Type) {
63
13.4k
        case FieldType::OLAP_FIELD_TYPE_BOOL: {
64
13.4k
            _bit_width = 1;
65
13.4k
            break;
66
0
        }
67
0
        default: {
68
0
            _bit_width = SIZE_OF_TYPE * 8;
69
0
            break;
70
0
        }
71
13.4k
        }
72
13.4k
        _rle_encoder = new RleEncoder<CppType>(&_buf, _bit_width);
73
13.4k
        return reset();
74
13.4k
    }
75
76
13.4k
    ~RlePageBuilder() { delete _rle_encoder; }
77
78
65.2k
    bool is_page_full() override { return _rle_encoder->len() >= _options.data_page_size; }
79
80
65.2k
    Status add(const uint8_t* vals, size_t* count) override {
81
65.2k
        DCHECK(!_finished);
82
65.2k
        auto new_vals = reinterpret_cast<const CppType*>(vals);
83
3.99M
        for (int i = 0; i < *count; ++i) {
84
            // note: vals is not guaranteed to be aligned for now, thus memcpy here
85
3.93M
            CppType value;
86
3.93M
            memcpy(&value, &new_vals[i], SIZE_OF_TYPE);
87
3.93M
            _rle_encoder->Put(value);
88
3.93M
        }
89
90
65.2k
        if (_count == 0) {
91
11.8k
            memcpy(&_first_value, new_vals, SIZE_OF_TYPE);
92
11.8k
        }
93
65.2k
        memcpy(&_last_value, &new_vals[*count - 1], SIZE_OF_TYPE);
94
95
65.2k
        _count += *count;
96
65.2k
        _raw_data_size += *count * SIZE_OF_TYPE;
97
65.2k
        return Status::OK();
98
65.2k
    }
99
100
12.4k
    Status finish(OwnedSlice* slice) override {
101
12.4k
        DCHECK(!_finished);
102
12.4k
        _finished = true;
103
        // here should Flush first and then encode the count header
104
        // or it will lead to a bug if the header is less than 8 byte and the data is small
105
12.4k
        _rle_encoder->Flush();
106
12.4k
        encode_fixed32_le(&_buf[0], cast_set<uint32_t>(_count));
107
12.4k
        *slice = _buf.build();
108
12.4k
        return Status::OK();
109
12.4k
    }
110
111
25.8k
    Status reset() override {
112
25.8k
        RETURN_IF_CATCH_EXCEPTION({
113
25.8k
            _count = 0;
114
25.8k
            _finished = false;
115
25.8k
            _raw_data_size = 0;
116
25.8k
            _rle_encoder->Clear();
117
25.8k
            _rle_encoder->Reserve(RLE_PAGE_HEADER_SIZE, 0);
118
25.8k
        });
119
25.9k
        return Status::OK();
120
25.8k
    }
121
122
0
    size_t count() const override { return _count; }
123
124
480
    uint64_t size() const override { return _rle_encoder->len(); }
125
126
12.4k
    uint64_t get_raw_data_size() const override { return _raw_data_size; }
127
128
0
    Status get_first_value(void* value) const override {
129
0
        DCHECK(_finished);
130
0
        if (_count == 0) {
131
0
            return Status::Error<ErrorCode::ENTRY_NOT_FOUND>("page is empty");
132
0
        }
133
0
        memcpy(value, &_first_value, SIZE_OF_TYPE);
134
0
        return Status::OK();
135
0
    }
136
137
0
    Status get_last_value(void* value) const override {
138
0
        DCHECK(_finished);
139
0
        if (_count == 0) {
140
0
            return Status::Error<ErrorCode::ENTRY_NOT_FOUND>("page is empty");
141
0
        }
142
0
        memcpy(value, &_last_value, SIZE_OF_TYPE);
143
0
        return Status::OK();
144
0
    }
145
146
private:
147
    RlePageBuilder(const PageBuilderOptions& options)
148
13.4k
            : _options(options),
149
13.4k
              _count(0),
150
13.4k
              _finished(false),
151
13.4k
              _bit_width(0),
152
13.4k
              _rle_encoder(nullptr) {}
153
154
    typedef typename TypeTraits<Type>::CppType CppType;
155
    enum { SIZE_OF_TYPE = TypeTraits<Type>::size };
156
157
    PageBuilderOptions _options;
158
    size_t _count;
159
    bool _finished;
160
    int _bit_width;
161
    RleEncoder<CppType>* _rle_encoder = nullptr;
162
    faststring _buf;
163
    CppType _first_value;
164
    CppType _last_value;
165
    uint64_t _raw_data_size = 0;
166
};
167
168
template <FieldType Type>
169
class RlePageDecoder : public PageDecoder {
170
public:
171
    RlePageDecoder(Slice slice, const PageDecoderOptions& options)
172
19.5k
            : _data(slice),
173
19.5k
              _options(options),
174
19.5k
              _parsed(false),
175
19.5k
              _num_elements(0),
176
19.5k
              _cur_index(0),
177
19.5k
              _bit_width(0) {}
178
179
19.5k
    Status init() override {
180
19.5k
        CHECK(!_parsed);
181
182
19.5k
        if (_data.size < RLE_PAGE_HEADER_SIZE) {
183
0
            return Status::Corruption("not enough bytes for header in RleBitMapBlockDecoder");
184
0
        }
185
19.5k
        _num_elements = decode_fixed32_le((const uint8_t*)&_data[0]);
186
187
19.5k
        _parsed = true;
188
189
19.5k
        switch (Type) {
190
19.5k
        case FieldType::OLAP_FIELD_TYPE_BOOL: {
191
19.5k
            _bit_width = 1;
192
19.5k
            break;
193
0
        }
194
0
        default: {
195
0
            _bit_width = SIZE_OF_TYPE * 8;
196
0
            break;
197
0
        }
198
19.5k
        }
199
200
19.5k
        _rle_decoder =
201
19.5k
                RleDecoder<CppType>((uint8_t*)_data.data + RLE_PAGE_HEADER_SIZE,
202
19.5k
                                    cast_set<int>(_data.size - RLE_PAGE_HEADER_SIZE), _bit_width);
203
204
19.5k
        RETURN_IF_ERROR(seek_to_position_in_page(0));
205
19.5k
        return Status::OK();
206
19.5k
    }
207
208
41.1k
    Status seek_to_position_in_page(size_t pos) override {
209
18.4E
        DCHECK(_parsed) << "Must call init()";
210
41.1k
        DCHECK_LE(pos, _num_elements)
211
0
                << "Tried to seek to " << pos << " which is > number of elements (" << _num_elements
212
0
                << ") in the block!";
213
        // If the block is empty (e.g. the column is filled with nulls), there is no data to seek.
214
41.1k
        if (_num_elements == 0) [[unlikely]] {
215
1.18k
            if (pos != 0) {
216
0
                return Status::Error<ErrorCode::INTERNAL_ERROR, false>(
217
0
                        "seek pos {} is larger than total elements  {}", pos, _num_elements);
218
1.18k
            } else {
219
1.18k
                return Status::OK();
220
1.18k
            }
221
1.18k
        }
222
39.9k
        if (_cur_index == pos) {
223
            // No need to seek.
224
20.1k
            return Status::OK();
225
20.1k
        } else if (_cur_index < pos) {
226
17.3k
            size_t nskip = pos - _cur_index;
227
17.3k
            _rle_decoder.Skip(nskip);
228
17.3k
        } else {
229
2.49k
            _rle_decoder = RleDecoder<CppType>((uint8_t*)_data.data + RLE_PAGE_HEADER_SIZE,
230
2.49k
                                               cast_set<int>(_data.size - RLE_PAGE_HEADER_SIZE),
231
2.49k
                                               _bit_width);
232
2.49k
            _rle_decoder.Skip(pos);
233
2.49k
        }
234
19.8k
        _cur_index = pos;
235
19.8k
        return Status::OK();
236
39.9k
    }
237
238
20.9k
    Status next_batch(size_t* n, MutableColumnPtr& dst) override {
239
20.9k
        DCHECK(_parsed);
240
20.9k
        if (*n == 0 || _cur_index >= _num_elements) [[unlikely]] {
241
0
            *n = 0;
242
0
            return Status::OK();
243
0
        }
244
245
20.9k
        size_t to_fetch = std::min(*n, static_cast<size_t>(_num_elements - _cur_index));
246
20.9k
        size_t remaining = to_fetch;
247
20.9k
        bool result = false;
248
20.9k
        CppType value;
249
6.74M
        while (remaining > 0) {
250
6.72M
            result = _rle_decoder.Get(&value);
251
6.72M
            DCHECK(result);
252
6.72M
            dst->insert_data((char*)(&value), SIZE_OF_TYPE);
253
6.72M
            remaining--;
254
6.72M
        }
255
256
20.9k
        _cur_index += to_fetch;
257
20.9k
        *n = to_fetch;
258
20.9k
        return Status::OK();
259
20.9k
    }
260
261
    Status read_by_rowids(const rowid_t* rowids, ordinal_t page_first_ordinal, size_t* n,
262
8.64k
                          MutableColumnPtr& dst) override {
263
8.64k
        DCHECK(_parsed);
264
8.65k
        if (*n == 0 || _cur_index >= _num_elements) [[unlikely]] {
265
0
            *n = 0;
266
0
            return Status::OK();
267
0
        }
268
269
8.64k
        auto total = *n;
270
8.64k
        bool result = false;
271
8.64k
        size_t read_count = 0;
272
8.64k
        CppType value;
273
1.11M
        for (size_t i = 0; i < total; ++i) {
274
1.10M
            ordinal_t ord = rowids[i] - page_first_ordinal;
275
1.10M
            if (UNLIKELY(ord >= _num_elements)) {
276
0
                *n = read_count;
277
0
                return Status::OK();
278
0
            }
279
280
1.10M
            _rle_decoder.Skip(ord - _cur_index);
281
1.10M
            _cur_index = ord;
282
283
1.10M
            result = _rle_decoder.Get(&value);
284
1.10M
            _cur_index++;
285
1.10M
            DCHECK(result);
286
1.10M
            dst->insert_data((char*)(&value), SIZE_OF_TYPE);
287
1.10M
            read_count++;
288
1.10M
        }
289
8.64k
        *n = read_count;
290
8.64k
        return Status::OK();
291
8.64k
    }
292
293
0
    size_t count() const override { return _num_elements; }
294
295
17.1k
    size_t current_index() const override { return _cur_index; }
296
297
private:
298
    typedef typename TypeTraits<Type>::CppType CppType;
299
    enum { SIZE_OF_TYPE = TypeTraits<Type>::size };
300
301
    Slice _data;
302
    PageDecoderOptions _options;
303
    bool _parsed;
304
    uint32_t _num_elements;
305
    size_t _cur_index;
306
    int _bit_width;
307
    RleDecoder<CppType> _rle_decoder;
308
};
309
310
} // namespace segment_v2
311
#include "common/compile_check_end.h"
312
} // namespace doris