Coverage Report

Created: 2025-07-28 09:55

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