Coverage Report

Created: 2026-01-20 17:47

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
245
void HyperLogLog::_convert_explicit_to_register() {
43
245
    DCHECK(_type == HLL_DATA_EXPLICIT)
44
0
            << "_type(" << _type << ") should be explicit(" << HLL_DATA_EXPLICIT << ")";
45
245
    _registers = new uint8_t[HLL_REGISTERS_COUNT];
46
245
    memset(_registers, 0, HLL_REGISTERS_COUNT);
47
39.1k
    for (auto value : _hash_set) {
48
39.1k
        _update_registers(value);
49
39.1k
    }
50
    // clear _hash_set
51
245
    vectorized::flat_hash_set<uint64_t>().swap(_hash_set);
52
245
}
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
100M
void HyperLogLog::update(uint64_t hash_value) {
57
100M
    switch (_type) {
58
26.7k
    case HLL_DATA_EMPTY:
59
26.7k
        _hash_set.insert(hash_value);
60
26.7k
        _type = HLL_DATA_EXPLICIT;
61
26.7k
        break;
62
5.81M
    case HLL_DATA_EXPLICIT:
63
5.81M
        if (_hash_set.size() < HLL_EXPLICIT_INT64_NUM) {
64
5.81M
            _hash_set.insert(hash_value);
65
5.81M
            break;
66
5.81M
        }
67
228
        _convert_explicit_to_register();
68
228
        _type = HLL_DATA_FULL;
69
        // fall through
70
229
    case HLL_DATA_SPARSE:
71
94.8M
    case HLL_DATA_FULL:
72
94.8M
        _update_registers(hash_value);
73
94.8M
        break;
74
100M
    }
75
100M
}
76
77
23.2k
void HyperLogLog::merge(const HyperLogLog& other) {
78
    // fast path
79
23.2k
    if (other._type == HLL_DATA_EMPTY) {
80
263
        return;
81
263
    }
82
22.9k
    switch (_type) {
83
15.9k
    case HLL_DATA_EMPTY: {
84
        // _type must change
85
15.9k
        _type = other._type;
86
15.9k
        switch (other._type) {
87
15.6k
        case HLL_DATA_EXPLICIT:
88
15.6k
            _hash_set = other._hash_set;
89
15.6k
            break;
90
208
        case HLL_DATA_SPARSE:
91
241
        case HLL_DATA_FULL:
92
241
            _registers = new uint8_t[HLL_REGISTERS_COUNT];
93
241
            memcpy(_registers, other._registers, HLL_REGISTERS_COUNT);
94
241
            break;
95
0
        default:
96
0
            break;
97
15.9k
        }
98
15.9k
        break;
99
15.9k
    }
100
15.9k
    case HLL_DATA_EXPLICIT: {
101
1.74k
        switch (other._type) {
102
1.74k
        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
1.74k
            _hash_set.insert(other._hash_set.begin(), other._hash_set.end());
106
1.74k
            if (_hash_set.size() > HLL_EXPLICIT_INT64_NUM) {
107
8
                _convert_explicit_to_register();
108
8
                _type = HLL_DATA_FULL;
109
8
            }
110
1.74k
        } 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
1.74k
        }
120
1.74k
        break;
121
1.74k
    }
122
1.74k
    case HLL_DATA_SPARSE:
123
5.27k
    case HLL_DATA_FULL: {
124
5.27k
        switch (other._type) {
125
5.27k
        case HLL_DATA_EXPLICIT:
126
5.37k
            for (auto hash_value : other._hash_set) {
127
5.37k
                _update_registers(hash_value);
128
5.37k
            }
129
5.27k
            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
5.27k
        }
137
5.27k
        break;
138
5.27k
    }
139
22.9k
    }
140
22.9k
}
141
142
33.5k
size_t HyperLogLog::max_serialized_size() const {
143
33.5k
    switch (_type) {
144
706
    case HLL_DATA_EMPTY:
145
706
    default:
146
706
        return 1;
147
32.6k
    case HLL_DATA_EXPLICIT:
148
32.6k
        return 2 + _hash_set.size() * 8;
149
2
    case HLL_DATA_SPARSE:
150
242
    case HLL_DATA_FULL:
151
242
        return 1 + HLL_REGISTERS_COUNT;
152
33.5k
    }
153
33.5k
}
154
155
33.4k
size_t HyperLogLog::serialize(uint8_t* dst) const {
156
33.4k
    uint8_t* ptr = dst;
157
33.4k
    switch (_type) {
158
700
    case HLL_DATA_EMPTY:
159
700
    default: {
160
        // When the _type is unknown, which may not happen, we encode it as
161
        // Empty HyperLogLog object.
162
700
        *ptr++ = HLL_DATA_EMPTY;
163
700
        break;
164
700
    }
165
32.5k
    case HLL_DATA_EXPLICIT: {
166
32.5k
        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
32.5k
        *ptr++ = _type;
170
32.5k
        *ptr++ = (uint8_t)_hash_set.size();
171
117k
        for (auto hash_value : _hash_set) {
172
117k
            encode_fixed64_le(ptr, hash_value);
173
117k
            ptr += 8;
174
117k
        }
175
32.5k
        break;
176
700
    }
177
1
    case HLL_DATA_SPARSE:
178
243
    case HLL_DATA_FULL: {
179
243
        uint32_t num_non_zero_registers = 0;
180
3.98M
        for (int i = 0; i < HLL_REGISTERS_COUNT; ++i) {
181
3.98M
            num_non_zero_registers += (_registers[i] != 0);
182
3.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
243
        if (num_non_zero_registers > HLL_SPARSE_THRESHOLD) {
188
33
            *ptr++ = HLL_DATA_FULL;
189
33
            memcpy(ptr, _registers, HLL_REGISTERS_COUNT);
190
33
            ptr += HLL_REGISTERS_COUNT;
191
210
        } else {
192
210
            *ptr++ = HLL_DATA_SPARSE;
193
            // 2-5(4 byte): number of registers
194
210
            encode_fixed32_le(ptr, num_non_zero_registers);
195
210
            ptr += 4;
196
197
3.44M
            for (uint16_t i = 0; i < HLL_REGISTERS_COUNT; ++i) {
198
3.44M
                if (_registers[i] == 0) {
199
3.19M
                    continue;
200
3.19M
                }
201
                // 2 bytes: register index
202
                // 1 byte: register value
203
250k
                encode_fixed16_le(ptr, i);
204
250k
                ptr += 2;
205
250k
                *ptr++ = _registers[i];
206
250k
            }
207
210
        }
208
243
        break;
209
1
    }
210
33.4k
    }
211
33.4k
    return ptr - dst;
212
33.4k
}
213
214
30.0k
bool HyperLogLog::is_valid(const Slice& slice) {
215
30.0k
    if (slice.size < 1) {
216
1
        return false;
217
1
    }
218
30.0k
    const uint8_t* ptr = (uint8_t*)slice.data;
219
30.0k
    const uint8_t* end = (uint8_t*)slice.data + slice.size;
220
30.0k
    auto type = (HllDataType)*ptr++;
221
30.0k
    switch (type) {
222
719
    case HLL_DATA_EMPTY:
223
719
        break;
224
29.0k
    case HLL_DATA_EXPLICIT: {
225
29.0k
        if ((ptr + 1) > end) {
226
1
            return false;
227
1
        }
228
29.0k
        uint8_t num_explicits = *ptr++;
229
29.0k
        ptr += num_explicits * 8;
230
29.0k
        break;
231
29.0k
    }
232
214
    case HLL_DATA_SPARSE: {
233
214
        if ((ptr + 4) > end) {
234
1
            return false;
235
1
        }
236
213
        uint32_t num_registers = decode_fixed32_le(ptr);
237
213
        ptr += 4 + 3 * num_registers;
238
213
        break;
239
214
    }
240
35
    case HLL_DATA_FULL: {
241
35
        ptr += HLL_REGISTERS_COUNT;
242
35
        break;
243
214
    }
244
3
    default:
245
3
        return false;
246
30.0k
    }
247
30.0k
    return ptr == end;
248
30.0k
}
249
250
// TODO(zc): check input string's length
251
30.0k
bool HyperLogLog::deserialize(const Slice& slice) {
252
    // can be called only when type is empty
253
30.0k
    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
30.0k
    if (slice.data == nullptr || slice.size <= 0) {
262
1
        return false;
263
1
    }
264
    // check if input length is valid
265
30.0k
    if (!is_valid(slice)) {
266
3
        return false;
267
3
    }
268
269
29.9k
    const uint8_t* ptr = (uint8_t*)slice.data;
270
    // first byte : type
271
29.9k
    _type = (HllDataType)*ptr++;
272
29.9k
    switch (_type) {
273
717
    case HLL_DATA_EMPTY:
274
717
        break;
275
29.0k
    case HLL_DATA_EXPLICIT: {
276
        // 2: number of explicit values
277
        // make sure that num_explicit is positive
278
29.0k
        uint8_t num_explicits = *ptr++;
279
        // 3+: 8 bytes hash value
280
133k
        for (int i = 0; i < num_explicits; ++i) {
281
104k
            _hash_set.insert(decode_fixed64_le(ptr));
282
104k
            ptr += 8;
283
104k
        }
284
29.0k
        break;
285
0
    }
286
211
    case HLL_DATA_SPARSE: {
287
211
        _registers = new uint8_t[HLL_REGISTERS_COUNT];
288
211
        memset(_registers, 0, HLL_REGISTERS_COUNT);
289
        // 2-5(4 byte): number of registers
290
211
        uint32_t num_registers = decode_fixed32_le(ptr);
291
211
        ptr += 4;
292
251k
        for (uint32_t i = 0; i < num_registers; ++i) {
293
            // 2 bytes: register index
294
            // 1 byte: register value
295
251k
            uint16_t register_idx = decode_fixed16_le(ptr);
296
251k
            ptr += 2;
297
251k
            _registers[register_idx] = *ptr++;
298
251k
        }
299
211
        break;
300
0
    }
301
33
    case HLL_DATA_FULL: {
302
33
        _registers = new uint8_t[HLL_REGISTERS_COUNT];
303
        // 2+ : hll register value
304
33
        memcpy(_registers, ptr, HLL_REGISTERS_COUNT);
305
33
        break;
306
0
    }
307
0
    default:
308
        // revert type to EMPTY
309
0
        _type = HLL_DATA_EMPTY;
310
0
        return false;
311
29.9k
    }
312
29.9k
    return true;
313
29.9k
}
314
315
16.3k
int64_t HyperLogLog::estimate_cardinality() const {
316
16.3k
    if (_type == HLL_DATA_EMPTY) {
317
509
        return 0;
318
509
    }
319
15.8k
    if (_type == HLL_DATA_EXPLICIT) {
320
15.5k
        return _hash_set.size();
321
15.5k
    }
322
323
253
    const int num_streams = HLL_REGISTERS_COUNT;
324
    // Empirical constants for the algorithm.
325
253
    float alpha = 0;
326
327
253
    if (num_streams == 16) {
328
0
        alpha = 0.673F;
329
253
    } else if (num_streams == 32) {
330
0
        alpha = 0.697F;
331
253
    } else if (num_streams == 64) {
332
0
        alpha = 0.709F;
333
253
    } else {
334
253
        alpha = 0.7213F / (1 + 1.079F / num_streams);
335
253
    }
336
337
253
    float harmonic_mean = 0;
338
253
    int num_zero_registers = 0;
339
340
4.14M
    for (int i = 0; i < HLL_REGISTERS_COUNT; ++i) {
341
4.14M
        harmonic_mean += powf(2.0F, -_registers[i]);
342
343
4.14M
        if (_registers[i] == 0) {
344
3.41M
            ++num_zero_registers;
345
3.41M
        }
346
4.14M
    }
347
348
253
    harmonic_mean = 1.0F / harmonic_mean;
349
253
    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
253
    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
234
        estimate = num_streams *
358
234
                   log(static_cast<double>(num_streams) / static_cast<double>(num_zero_registers));
359
234
    } 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
7
        double bias = 5.9119 * 1.0e-18 * (estimate * estimate * estimate * estimate) -
363
7
                      1.4253 * 1.0e-12 * (estimate * estimate * estimate) +
364
7
                      1.2940 * 1.0e-7 * (estimate * estimate) - 5.2921 * 1.0e-3 * estimate +
365
7
                      83.3216;
366
7
        estimate -= estimate * (bias / 100);
367
7
    }
368
253
    return (int64_t)(estimate + 0.5);
369
15.8k
}
370
#include "common/compile_check_end.h"
371
} // namespace doris