Coverage Report

Created: 2025-07-26 21:09

/root/doris/be/src/olap/hll.cpp
Line
Count
Source (jump to first uncovered line)
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
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
1.02k
        _type = HLL_DATA_EMPTY;
37
1.02k
    }
38
1.03k
}
39
40
// Convert explicit values to register format, and clear explicit values.
41
// NOTE: this function won't modify _type.
42
415
void HyperLogLog::_convert_explicit_to_register() {
43
415
    DCHECK(_type == HLL_DATA_EXPLICIT)
44
0
            << "_type(" << _type << ") should be explicit(" << HLL_DATA_EXPLICIT << ")";
45
415
    _registers = new uint8_t[HLL_REGISTERS_COUNT];
46
415
    memset(_registers, 0, HLL_REGISTERS_COUNT);
47
66.3k
    for (auto value : _hash_set) {
48
66.3k
        _update_registers(value);
49
66.3k
    }
50
    // clear _hash_set
51
415
    vectorized::flat_hash_set<uint64_t>().swap(_hash_set);
52
415
}
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
50.3M
void HyperLogLog::update(uint64_t hash_value) {
57
50.3M
    switch (_type) {
58
49.0k
    case HLL_DATA_EMPTY:
59
49.0k
        _hash_set.insert(hash_value);
60
49.0k
        _type = HLL_DATA_EXPLICIT;
61
49.0k
        break;
62
22.4M
    case HLL_DATA_EXPLICIT:
63
22.4M
        if (_hash_set.size() < HLL_EXPLICIT_INT64_NUM) {
64
22.4M
            _hash_set.insert(hash_value);
65
22.4M
            break;
66
22.4M
        }
67
489
        _convert_explicit_to_register();
68
489
        _type = HLL_DATA_FULL;
69
        // fall through
70
490
    case HLL_DATA_SPARSE:
71
27.8M
    case HLL_DATA_FULL:
72
27.8M
        _update_registers(hash_value);
73
27.8M
        break;
74
50.3M
    }
75
50.3M
}
76
77
46.8k
void HyperLogLog::merge(const HyperLogLog& other) {
78
    // fast path
79
46.8k
    if (other._type == HLL_DATA_EMPTY) {
80
516
        return;
81
516
    }
82
46.3k
    switch (_type) {
83
32.1k
    case HLL_DATA_EMPTY: {
84
        // _type must change
85
32.1k
        _type = other._type;
86
32.1k
        switch (other._type) {
87
31.7k
        case HLL_DATA_EXPLICIT:
88
31.7k
            _hash_set = other._hash_set;
89
31.7k
            break;
90
298
        case HLL_DATA_SPARSE:
91
411
        case HLL_DATA_FULL:
92
411
            _registers = new uint8_t[HLL_REGISTERS_COUNT];
93
411
            memcpy(_registers, other._registers, HLL_REGISTERS_COUNT);
94
411
            break;
95
0
        default:
96
0
            break;
97
32.1k
        }
98
32.1k
        break;
99
32.1k
    }
100
32.1k
    case HLL_DATA_EXPLICIT: {
101
3.55k
        switch (other._type) {
102
3.55k
        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.55k
            _hash_set.insert(other._hash_set.begin(), other._hash_set.end());
106
3.55k
            if (_hash_set.size() > HLL_EXPLICIT_INT64_NUM) {
107
15
                _convert_explicit_to_register();
108
15
                _type = HLL_DATA_FULL;
109
15
            }
110
3.55k
        } 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.55k
        }
120
3.55k
        break;
121
3.55k
    }
122
3.55k
    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
46.3k
    }
140
46.3k
}
141
142
56.7k
size_t HyperLogLog::max_serialized_size() const {
143
56.7k
    switch (_type) {
144
1.27k
    case HLL_DATA_EMPTY:
145
1.27k
    default:
146
1.27k
        return 1;
147
55.1k
    case HLL_DATA_EXPLICIT:
148
55.1k
        return 2 + _hash_set.size() * 8;
149
4
    case HLL_DATA_SPARSE:
150
414
    case HLL_DATA_FULL:
151
414
        return 1 + HLL_REGISTERS_COUNT;
152
56.7k
    }
153
56.7k
}
154
155
56.4k
size_t HyperLogLog::serialize(uint8_t* dst) const {
156
56.4k
    uint8_t* ptr = dst;
157
56.4k
    switch (_type) {
158
1.25k
    case HLL_DATA_EMPTY:
159
1.25k
    default: {
160
        // When the _type is unknown, which may not happen, we encode it as
161
        // Empty HyperLogLog object.
162
1.25k
        *ptr++ = HLL_DATA_EMPTY;
163
1.25k
        break;
164
1.25k
    }
165
54.8k
    case HLL_DATA_EXPLICIT: {
166
54.8k
        DCHECK(_hash_set.size() <= HLL_EXPLICIT_INT64_NUM)
167
2
                << "Number of explicit elements(" << _hash_set.size()
168
2
                << ") should be less or equal than " << HLL_EXPLICIT_INT64_NUM;
169
54.8k
        *ptr++ = _type;
170
54.8k
        *ptr++ = (uint8_t)_hash_set.size();
171
121k
        for (auto hash_value : _hash_set) {
172
121k
            encode_fixed64_le(ptr, hash_value);
173
121k
            ptr += 8;
174
121k
        }
175
54.8k
        break;
176
1.25k
    }
177
2
    case HLL_DATA_SPARSE:
178
414
    case HLL_DATA_FULL: {
179
414
        uint32_t num_non_zero_registers = 0;
180
6.78M
        for (int i = 0; i < HLL_REGISTERS_COUNT; ++i) {
181
6.78M
            num_non_zero_registers += (_registers[i] != 0);
182
6.78M
        }
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
414
        if (num_non_zero_registers > HLL_SPARSE_THRESHOLD) {
188
113
            *ptr++ = HLL_DATA_FULL;
189
113
            memcpy(ptr, _registers, HLL_REGISTERS_COUNT);
190
113
            ptr += HLL_REGISTERS_COUNT;
191
301
        } else {
192
301
            *ptr++ = HLL_DATA_SPARSE;
193
            // 2-5(4 byte): number of registers
194
301
            encode_fixed32_le(ptr, num_non_zero_registers);
195
301
            ptr += 4;
196
197
4.93M
            for (uint32_t i = 0; i < HLL_REGISTERS_COUNT; ++i) {
198
4.93M
                if (_registers[i] == 0) {
199
4.49M
                    continue;
200
4.49M
                }
201
                // 2 bytes: register index
202
                // 1 byte: register value
203
434k
                encode_fixed16_le(ptr, i);
204
434k
                ptr += 2;
205
434k
                *ptr++ = _registers[i];
206
434k
            }
207
301
        }
208
414
        break;
209
2
    }
210
56.4k
    }
211
56.4k
    return ptr - dst;
212
56.4k
}
213
214
54.3k
bool HyperLogLog::is_valid(const Slice& slice) {
215
54.3k
    if (slice.size < 1) {
216
1
        return false;
217
1
    }
218
54.3k
    const uint8_t* ptr = (uint8_t*)slice.data;
219
54.3k
    const uint8_t* end = (uint8_t*)slice.data + slice.size;
220
54.3k
    auto type = (HllDataType)*ptr++;
221
54.3k
    switch (type) {
222
1.32k
    case HLL_DATA_EMPTY:
223
1.32k
        break;
224
52.5k
    case HLL_DATA_EXPLICIT: {
225
52.5k
        if ((ptr + 1) > end) {
226
1
            return false;
227
1
        }
228
52.5k
        uint8_t num_explicits = *ptr++;
229
52.5k
        ptr += num_explicits * 8;
230
52.5k
        break;
231
52.5k
    }
232
305
    case HLL_DATA_SPARSE: {
233
305
        if ((ptr + 4) > end) {
234
1
            return false;
235
1
        }
236
304
        uint32_t num_registers = decode_fixed32_le(ptr);
237
304
        ptr += 4 + 3 * num_registers;
238
304
        break;
239
305
    }
240
115
    case HLL_DATA_FULL: {
241
115
        ptr += HLL_REGISTERS_COUNT;
242
115
        break;
243
305
    }
244
2
    default:
245
2
        return false;
246
54.3k
    }
247
54.3k
    return ptr == end;
248
54.3k
}
249
250
// TODO(zc): check input string's length
251
54.3k
bool HyperLogLog::deserialize(const Slice& slice) {
252
    // can be called only when type is empty
253
54.3k
    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
54.3k
    if (slice.data == nullptr || slice.size <= 0) {
262
1
        return false;
263
1
    }
264
    // check if input length is valid
265
54.3k
    if (!is_valid(slice)) {
266
1.02k
        return false;
267
1.02k
    }
268
269
53.3k
    const uint8_t* ptr = (uint8_t*)slice.data;
270
    // first byte : type
271
53.3k
    _type = (HllDataType)*ptr++;
272
53.3k
    switch (_type) {
273
1.32k
    case HLL_DATA_EMPTY:
274
1.32k
        break;
275
51.5k
    case HLL_DATA_EXPLICIT: {
276
        // 2: number of explicit values
277
        // make sure that num_explicit is positive
278
51.5k
        uint8_t num_explicits = *ptr++;
279
        // 3+: 8 bytes hash value
280
170k
        for (int i = 0; i < num_explicits; ++i) {
281
118k
            _hash_set.insert(decode_fixed64_le(ptr));
282
118k
            ptr += 8;
283
118k
        }
284
51.5k
        break;
285
0
    }
286
303
    case HLL_DATA_SPARSE: {
287
303
        _registers = new uint8_t[HLL_REGISTERS_COUNT];
288
303
        memset(_registers, 0, HLL_REGISTERS_COUNT);
289
        // 2-5(4 byte): number of registers
290
303
        uint32_t num_registers = decode_fixed32_le(ptr);
291
303
        ptr += 4;
292
437k
        for (uint32_t i = 0; i < num_registers; ++i) {
293
            // 2 bytes: register index
294
            // 1 byte: register value
295
436k
            uint16_t register_idx = decode_fixed16_le(ptr);
296
436k
            ptr += 2;
297
436k
            _registers[register_idx] = *ptr++;
298
436k
        }
299
303
        break;
300
0
    }
301
113
    case HLL_DATA_FULL: {
302
113
        _registers = new uint8_t[HLL_REGISTERS_COUNT];
303
        // 2+ : hll register value
304
113
        memcpy(_registers, ptr, HLL_REGISTERS_COUNT);
305
113
        break;
306
0
    }
307
0
    default:
308
        // revert type to EMPTY
309
0
        _type = HLL_DATA_EMPTY;
310
0
        return false;
311
53.3k
    }
312
53.3k
    return true;
313
53.3k
}
314
315
31.9k
int64_t HyperLogLog::estimate_cardinality() const {
316
31.9k
    if (_type == HLL_DATA_EMPTY) {
317
1.07k
        return 0;
318
1.07k
    }
319
30.8k
    if (_type == HLL_DATA_EXPLICIT) {
320
30.4k
        return _hash_set.size();
321
30.4k
    }
322
323
425
    const int num_streams = HLL_REGISTERS_COUNT;
324
    // Empirical constants for the algorithm.
325
425
    float alpha = 0;
326
327
425
    if (num_streams == 16) {
328
0
        alpha = 0.673F;
329
425
    } else if (num_streams == 32) {
330
0
        alpha = 0.697F;
331
425
    } else if (num_streams == 64) {
332
0
        alpha = 0.709F;
333
425
    } else {
334
425
        alpha = 0.7213F / (1 + 1.079F / num_streams);
335
425
    }
336
337
425
    float harmonic_mean = 0;
338
425
    int num_zero_registers = 0;
339
340
6.96M
    for (int i = 0; i < HLL_REGISTERS_COUNT; ++i) {
341
6.96M
        harmonic_mean += powf(2.0F, -_registers[i]);
342
343
6.96M
        if (_registers[i] == 0) {
344
5.02M
            ++num_zero_registers;
345
5.02M
        }
346
6.96M
    }
347
348
425
    harmonic_mean = 1.0F / harmonic_mean;
349
425
    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
425
    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
373
        estimate = num_streams * log(static_cast<float>(num_streams) / num_zero_registers);
358
373
    } else if (num_streams == 16384 && estimate < 72000) {
359
        // when Linear Couint change to HyperLogLog according to HyperLogLog Correction,
360
        // there are relatively large fluctuations, we fixed the problem refer to redis.
361
10
        double bias = 5.9119 * 1.0e-18 * (estimate * estimate * estimate * estimate) -
362
10
                      1.4253 * 1.0e-12 * (estimate * estimate * estimate) +
363
10
                      1.2940 * 1.0e-7 * (estimate * estimate) - 5.2921 * 1.0e-3 * estimate +
364
10
                      83.3216;
365
10
        estimate -= estimate * (bias / 100);
366
10
    }
367
425
    return (int64_t)(estimate + 0.5);
368
30.8k
}
369
370
0
void HllSetResolver::parse() {
371
    // skip LengthValueType
372
0
    char* pdata = _buf_ref;
373
0
    _set_type = (HllDataType)pdata[0];
374
0
    char* sparse_data = nullptr;
375
0
    switch (_set_type) {
376
0
    case HLL_DATA_EXPLICIT:
377
        // first byte : type
378
        // second~five byte : hash values's number
379
        // five byte later : hash value
380
0
        _explicit_num = (ExplicitLengthValueType)(pdata[sizeof(SetTypeValueType)]);
381
0
        _explicit_value =
382
0
                (uint64_t*)(pdata + sizeof(SetTypeValueType) + sizeof(ExplicitLengthValueType));
383
0
        break;
384
0
    case HLL_DATA_SPARSE:
385
        // first byte : type
386
        // second ~(2^HLL_COLUMN_PRECISION)/8 byte : bitmap mark which is not zero
387
        // 2^HLL_COLUMN_PRECISION)/8 + 1以后value
388
0
        _sparse_count = (SparseLengthValueType*)(pdata + sizeof(SetTypeValueType));
389
0
        sparse_data = pdata + sizeof(SetTypeValueType) + sizeof(SparseLengthValueType);
390
0
        for (int i = 0; i < *_sparse_count; i++) {
391
0
            auto* index = (SparseIndexType*)sparse_data;
392
0
            sparse_data += sizeof(SparseIndexType);
393
0
            auto* value = (SparseValueType*)sparse_data;
394
0
            _sparse_map[*index] = *value;
395
0
            sparse_data += sizeof(SetTypeValueType);
396
0
        }
397
0
        break;
398
0
    case HLL_DATA_FULL:
399
        // first byte : type
400
        // second byte later : hll register value
401
0
        _full_value_position = pdata + sizeof(SetTypeValueType);
402
0
        break;
403
0
    default:
404
        // HLL_DATA_EMPTY
405
0
        break;
406
0
    }
407
0
}
408
409
} // namespace doris