Coverage Report

Created: 2026-01-04 14:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/olap/hll.cpp
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
#include "olap/hll.h"
19
20
#include <cmath>
21
#include <map>
22
#include <ostream>
23
24
#include "common/logging.h"
25
#include "util/coding.h"
26
#include "util/slice.h"
27
28
using std::string;
29
using std::stringstream;
30
31
namespace doris {
32
#include "common/compile_check_begin.h"
33
1.06k
HyperLogLog::HyperLogLog(const Slice& src) {
34
    // When deserialize return false, we make this object a empty
35
1.06k
    if (!deserialize(src)) {
36
3
        _type = HLL_DATA_EMPTY;
37
3
    }
38
1.06k
}
39
40
// Convert explicit values to register format, and clear explicit values.
41
// NOTE: this function won't modify _type.
42
185
void HyperLogLog::_convert_explicit_to_register() {
43
185
    DCHECK(_type == HLL_DATA_EXPLICIT)
44
0
            << "_type(" << _type << ") should be explicit(" << HLL_DATA_EXPLICIT << ")";
45
185
    _registers = new uint8_t[HLL_REGISTERS_COUNT];
46
185
    memset(_registers, 0, HLL_REGISTERS_COUNT);
47
29.5k
    for (auto value : _hash_set) {
48
29.5k
        _update_registers(value);
49
29.5k
    }
50
    // clear _hash_set
51
185
    vectorized::flat_hash_set<uint64_t>().swap(_hash_set);
52
185
}
53
54
// Change HLL_DATA_EXPLICIT to HLL_DATA_FULL directly, because HLL_DATA_SPARSE
55
// is implemented in the same way in memory with HLL_DATA_FULL.
56
89.6M
void HyperLogLog::update(uint64_t hash_value) {
57
89.6M
    switch (_type) {
58
6.41k
    case HLL_DATA_EMPTY:
59
6.41k
        _hash_set.insert(hash_value);
60
6.41k
        _type = HLL_DATA_EXPLICIT;
61
6.41k
        break;
62
332k
    case HLL_DATA_EXPLICIT:
63
332k
        if (_hash_set.size() < HLL_EXPLICIT_INT64_NUM) {
64
332k
            _hash_set.insert(hash_value);
65
332k
            break;
66
332k
        }
67
183
        _convert_explicit_to_register();
68
183
        _type = HLL_DATA_FULL;
69
        // fall through
70
184
    case HLL_DATA_SPARSE:
71
89.2M
    case HLL_DATA_FULL:
72
89.2M
        _update_registers(hash_value);
73
89.2M
        break;
74
89.6M
    }
75
89.6M
}
76
77
3.25k
void HyperLogLog::merge(const HyperLogLog& other) {
78
    // fast path
79
3.25k
    if (other._type == HLL_DATA_EMPTY) {
80
32
        return;
81
32
    }
82
3.22k
    switch (_type) {
83
3.11k
    case HLL_DATA_EMPTY: {
84
        // _type must change
85
3.11k
        _type = other._type;
86
3.11k
        switch (other._type) {
87
2.93k
        case HLL_DATA_EXPLICIT:
88
2.93k
            _hash_set = other._hash_set;
89
2.93k
            break;
90
159
        case HLL_DATA_SPARSE:
91
181
        case HLL_DATA_FULL:
92
181
            _registers = new uint8_t[HLL_REGISTERS_COUNT];
93
181
            memcpy(_registers, other._registers, HLL_REGISTERS_COUNT);
94
181
            break;
95
0
        default:
96
0
            break;
97
3.11k
        }
98
3.11k
        break;
99
3.11k
    }
100
3.11k
    case HLL_DATA_EXPLICIT: {
101
110
        switch (other._type) {
102
109
        case HLL_DATA_EXPLICIT: {
103
            // Merge other's explicit values first, then check if the number is exceed
104
            // HLL_EXPLICIT_INT64_NUM. This is OK because the max value is 2 * 160.
105
109
            _hash_set.insert(other._hash_set.begin(), other._hash_set.end());
106
109
            if (_hash_set.size() > HLL_EXPLICIT_INT64_NUM) {
107
1
                _convert_explicit_to_register();
108
1
                _type = HLL_DATA_FULL;
109
1
            }
110
109
        } break;
111
0
        case HLL_DATA_SPARSE:
112
1
        case HLL_DATA_FULL:
113
1
            _convert_explicit_to_register();
114
1
            _merge_registers(other._registers);
115
1
            _type = HLL_DATA_FULL;
116
1
            break;
117
0
        default:
118
0
            break;
119
110
        }
120
110
        break;
121
110
    }
122
110
    case HLL_DATA_SPARSE:
123
3
    case HLL_DATA_FULL: {
124
3
        switch (other._type) {
125
1
        case HLL_DATA_EXPLICIT:
126
100
            for (auto hash_value : other._hash_set) {
127
100
                _update_registers(hash_value);
128
100
            }
129
1
            break;
130
0
        case HLL_DATA_SPARSE:
131
2
        case HLL_DATA_FULL:
132
2
            _merge_registers(other._registers);
133
2
            break;
134
0
        default:
135
0
            break;
136
3
        }
137
3
        break;
138
3
    }
139
3.22k
    }
140
3.22k
}
141
142
10.0k
size_t HyperLogLog::max_serialized_size() const {
143
10.0k
    switch (_type) {
144
78
    case HLL_DATA_EMPTY:
145
78
    default:
146
78
        return 1;
147
9.80k
    case HLL_DATA_EXPLICIT:
148
9.80k
        return 2 + _hash_set.size() * 8;
149
0
    case HLL_DATA_SPARSE:
150
180
    case HLL_DATA_FULL:
151
180
        return 1 + HLL_REGISTERS_COUNT;
152
10.0k
    }
153
10.0k
}
154
155
10.0k
size_t HyperLogLog::serialize(uint8_t* dst) const {
156
10.0k
    uint8_t* ptr = dst;
157
10.0k
    switch (_type) {
158
72
    case HLL_DATA_EMPTY:
159
72
    default: {
160
        // When the _type is unknown, which may not happen, we encode it as
161
        // Empty HyperLogLog object.
162
72
        *ptr++ = HLL_DATA_EMPTY;
163
72
        break;
164
72
    }
165
9.77k
    case HLL_DATA_EXPLICIT: {
166
9.77k
        DCHECK(_hash_set.size() <= HLL_EXPLICIT_INT64_NUM)
167
0
                << "Number of explicit elements(" << _hash_set.size()
168
0
                << ") should be less or equal than " << HLL_EXPLICIT_INT64_NUM;
169
9.77k
        *ptr++ = _type;
170
9.77k
        *ptr++ = (uint8_t)_hash_set.size();
171
64.2k
        for (auto hash_value : _hash_set) {
172
64.2k
            encode_fixed64_le(ptr, hash_value);
173
64.2k
            ptr += 8;
174
64.2k
        }
175
9.77k
        break;
176
72
    }
177
0
    case HLL_DATA_SPARSE:
178
182
    case HLL_DATA_FULL: {
179
182
        uint32_t num_non_zero_registers = 0;
180
2.98M
        for (int i = 0; i < HLL_REGISTERS_COUNT; ++i) {
181
2.98M
            num_non_zero_registers += (_registers[i] != 0);
182
2.98M
        }
183
184
        // each register in sparse format will occupy 3bytes, 2 for index and
185
        // 1 for register value. So if num_non_zero_registers is greater than
186
        // 4K we use full encode format.
187
182
        if (num_non_zero_registers > HLL_SPARSE_THRESHOLD) {
188
22
            *ptr++ = HLL_DATA_FULL;
189
22
            memcpy(ptr, _registers, HLL_REGISTERS_COUNT);
190
22
            ptr += HLL_REGISTERS_COUNT;
191
160
        } else {
192
160
            *ptr++ = HLL_DATA_SPARSE;
193
            // 2-5(4 byte): number of registers
194
160
            encode_fixed32_le(ptr, num_non_zero_registers);
195
160
            ptr += 4;
196
197
2.62M
            for (uint16_t i = 0; i < HLL_REGISTERS_COUNT; ++i) {
198
2.62M
                if (_registers[i] == 0) {
199
2.43M
                    continue;
200
2.43M
                }
201
                // 2 bytes: register index
202
                // 1 byte: register value
203
188k
                encode_fixed16_le(ptr, i);
204
188k
                ptr += 2;
205
188k
                *ptr++ = _registers[i];
206
188k
            }
207
160
        }
208
182
        break;
209
0
    }
210
10.0k
    }
211
10.0k
    return ptr - dst;
212
10.0k
}
213
214
7.09k
bool HyperLogLog::is_valid(const Slice& slice) {
215
7.09k
    if (slice.size < 1) {
216
1
        return false;
217
1
    }
218
7.09k
    const uint8_t* ptr = (uint8_t*)slice.data;
219
7.09k
    const uint8_t* end = (uint8_t*)slice.data + slice.size;
220
7.09k
    auto type = (HllDataType)*ptr++;
221
7.09k
    switch (type) {
222
89
    case HLL_DATA_EMPTY:
223
89
        break;
224
6.81k
    case HLL_DATA_EXPLICIT: {
225
6.81k
        if ((ptr + 1) > end) {
226
1
            return false;
227
1
        }
228
6.81k
        uint8_t num_explicits = *ptr++;
229
6.81k
        ptr += num_explicits * 8;
230
6.81k
        break;
231
6.81k
    }
232
163
    case HLL_DATA_SPARSE: {
233
163
        if ((ptr + 4) > end) {
234
1
            return false;
235
1
        }
236
162
        uint32_t num_registers = decode_fixed32_le(ptr);
237
162
        ptr += 4 + 3 * num_registers;
238
162
        break;
239
163
    }
240
24
    case HLL_DATA_FULL: {
241
24
        ptr += HLL_REGISTERS_COUNT;
242
24
        break;
243
163
    }
244
3
    default:
245
3
        return false;
246
7.09k
    }
247
7.08k
    return ptr == end;
248
7.09k
}
249
250
// TODO(zc): check input string's length
251
7.08k
bool HyperLogLog::deserialize(const Slice& slice) {
252
    // can be called only when type is empty
253
7.08k
    DCHECK(_type == HLL_DATA_EMPTY);
254
255
    // NOTE(zc): Don't remove this check unless you known what
256
    // you are doing. Because of history bug, we ingest some
257
    // invalid HLL data in storage, which ptr is nullptr.
258
    // we must handle this case to avoid process crash.
259
    // This bug is in release 0.10, I think we can remove this
260
    // in release 0.12 or later.
261
7.08k
    if (slice.data == nullptr || slice.size <= 0) {
262
1
        return false;
263
1
    }
264
    // check if input length is valid
265
7.08k
    if (!is_valid(slice)) {
266
3
        return false;
267
3
    }
268
269
7.07k
    const uint8_t* ptr = (uint8_t*)slice.data;
270
    // first byte : type
271
7.07k
    _type = (HllDataType)*ptr++;
272
7.07k
    switch (_type) {
273
87
    case HLL_DATA_EMPTY:
274
87
        break;
275
6.81k
    case HLL_DATA_EXPLICIT: {
276
        // 2: number of explicit values
277
        // make sure that num_explicit is positive
278
6.81k
        uint8_t num_explicits = *ptr++;
279
        // 3+: 8 bytes hash value
280
58.1k
        for (int i = 0; i < num_explicits; ++i) {
281
51.3k
            _hash_set.insert(decode_fixed64_le(ptr));
282
51.3k
            ptr += 8;
283
51.3k
        }
284
6.81k
        break;
285
0
    }
286
160
    case HLL_DATA_SPARSE: {
287
160
        _registers = new uint8_t[HLL_REGISTERS_COUNT];
288
160
        memset(_registers, 0, HLL_REGISTERS_COUNT);
289
        // 2-5(4 byte): number of registers
290
160
        uint32_t num_registers = decode_fixed32_le(ptr);
291
160
        ptr += 4;
292
188k
        for (uint32_t i = 0; i < num_registers; ++i) {
293
            // 2 bytes: register index
294
            // 1 byte: register value
295
188k
            uint16_t register_idx = decode_fixed16_le(ptr);
296
188k
            ptr += 2;
297
188k
            _registers[register_idx] = *ptr++;
298
188k
        }
299
160
        break;
300
0
    }
301
22
    case HLL_DATA_FULL: {
302
22
        _registers = new uint8_t[HLL_REGISTERS_COUNT];
303
        // 2+ : hll register value
304
22
        memcpy(_registers, ptr, HLL_REGISTERS_COUNT);
305
22
        break;
306
0
    }
307
0
    default:
308
        // revert type to EMPTY
309
0
        _type = HLL_DATA_EMPTY;
310
0
        return false;
311
7.07k
    }
312
7.08k
    return true;
313
7.07k
}
314
315
3.64k
int64_t HyperLogLog::estimate_cardinality() const {
316
3.64k
    if (_type == HLL_DATA_EMPTY) {
317
204
        return 0;
318
204
    }
319
3.44k
    if (_type == HLL_DATA_EXPLICIT) {
320
3.25k
        return _hash_set.size();
321
3.25k
    }
322
323
193
    const int num_streams = HLL_REGISTERS_COUNT;
324
    // Empirical constants for the algorithm.
325
193
    float alpha = 0;
326
327
193
    if (num_streams == 16) {
328
0
        alpha = 0.673F;
329
193
    } else if (num_streams == 32) {
330
0
        alpha = 0.697F;
331
193
    } else if (num_streams == 64) {
332
0
        alpha = 0.709F;
333
193
    } else {
334
193
        alpha = 0.7213F / (1 + 1.079F / num_streams);
335
193
    }
336
337
193
    float harmonic_mean = 0;
338
193
    int num_zero_registers = 0;
339
340
3.16M
    for (int i = 0; i < HLL_REGISTERS_COUNT; ++i) {
341
3.16M
        harmonic_mean += powf(2.0F, -_registers[i]);
342
343
3.16M
        if (_registers[i] == 0) {
344
2.61M
            ++num_zero_registers;
345
2.61M
        }
346
3.16M
    }
347
348
193
    harmonic_mean = 1.0F / harmonic_mean;
349
193
    double estimate = alpha * num_streams * num_streams * harmonic_mean;
350
    // according to HyperLogLog current correction, if E is cardinal
351
    // E =< num_streams * 2.5 , LC has higher accuracy.
352
    // num_streams * 2.5 < E , HyperLogLog has higher accuracy.
353
    // Generally , we can use HyperLogLog to produce value as E.
354
193
    if (estimate <= num_streams * 2.5 && num_zero_registers != 0) {
355
        // Estimated cardinality is too low. Hll is too inaccurate here, instead use
356
        // linear counting.
357
175
        estimate = num_streams *
358
175
                   log(static_cast<double>(num_streams) / static_cast<double>(num_zero_registers));
359
175
    } else if (num_streams == 16384 && estimate < 72000) {
360
        // when Linear Couint change to HyperLogLog according to HyperLogLog Correction,
361
        // there are relatively large fluctuations, we fixed the problem refer to redis.
362
6
        double bias = 5.9119 * 1.0e-18 * (estimate * estimate * estimate * estimate) -
363
6
                      1.4253 * 1.0e-12 * (estimate * estimate * estimate) +
364
6
                      1.2940 * 1.0e-7 * (estimate * estimate) - 5.2921 * 1.0e-3 * estimate +
365
6
                      83.3216;
366
6
        estimate -= estimate * (bias / 100);
367
6
    }
368
193
    return (int64_t)(estimate + 0.5);
369
3.44k
}
370
#include "common/compile_check_end.h"
371
} // namespace doris