Coverage Report

Created: 2026-10-24 06:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/util/tdigest.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
/*
19
 * Licensed to Derrick R. Burns under one or more
20
 * contributor license agreements.  See the NOTICES file distributed with
21
 * this work for additional information regarding copyright ownership.
22
 * The ASF licenses this file to You under the Apache License, Version 2.0
23
 * (the "License"); you may not use this file except in compliance with
24
 * the License.  You may obtain a copy of the License at
25
 *
26
 *     http://www.apache.org/licenses/LICENSE-2.0
27
 *
28
 * Unless required by applicable law or agreed to in writing, software
29
 * distributed under the License is distributed on an "AS IS" BASIS,
30
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31
 * See the License for the specific language governing permissions and
32
 * limitations under the License.
33
 */
34
35
// T-Digest :  Percentile and Quantile Estimation of Big Data
36
// A new data structure for accurate on-line accumulation of rank-based statistics
37
// such as quantiles and trimmed means.
38
// See original paper: "Computing extremely accurate quantiles using t-digest"
39
// by Ted Dunning and Otmar Ertl for more details
40
// https://github.com/tdunning/t-digest/blob/07b8f2ca2be8d0a9f04df2feadad5ddc1bb73c88/docs/t-digest-paper/histo.pdf.
41
// https://github.com/derrickburns/tdigest
42
43
#pragma once
44
45
#include <pdqsort.h>
46
47
#include <algorithm>
48
#include <cfloat>
49
#include <cmath>
50
#include <iostream>
51
#include <memory>
52
#include <queue>
53
#include <utility>
54
#include <vector>
55
56
#include "common/factory_creator.h"
57
#include "common/logging.h"
58
59
namespace doris {
60
61
using Value = float;
62
using Weight = float;
63
using Index = size_t;
64
65
constexpr size_t K_HIGH_WATER = 40000;
66
67
class Centroid {
68
public:
69
438k
    Centroid() : Centroid(0.0, 0.0) {}
70
71
707k
    Centroid(Value mean, Weight weight) : _mean(mean), _weight(weight) {}
72
73
298M
    Value mean() const noexcept { return _mean; }
74
75
439M
    Weight weight() const noexcept { return _weight; }
76
77
29.4k
    Value& mean() noexcept { return _mean; }
78
79
27.8k
    Weight& weight() noexcept { return _weight; }
80
81
1.11M
    void add(const Centroid& c) {
82
1.11M
        DCHECK_GT(c._weight, 0);
83
1.11M
        if (_weight != 0.0) {
84
1.11M
            _weight += c._weight;
85
1.11M
            _mean += c._weight * (c._mean - _mean) / _weight;
86
18.4E
        } else {
87
18.4E
            _weight = c._weight;
88
18.4E
            _mean = c._mean;
89
18.4E
        }
90
1.11M
    }
91
92
private:
93
    Value _mean = 0;
94
    Weight _weight = 0;
95
};
96
97
struct CentroidList {
98
871
    CentroidList(const std::vector<Centroid>& s) : iter(s.cbegin()), end(s.cend()) {}
99
    std::vector<Centroid>::const_iterator iter;
100
    std::vector<Centroid>::const_iterator end;
101
102
2.05M
    bool advance() { return ++iter != end; }
103
};
104
105
class CentroidListComparator {
106
public:
107
    CentroidListComparator() = default;
108
109
1.89M
    bool operator()(const CentroidList& left, const CentroidList& right) const {
110
1.89M
        return left.iter->mean() > right.iter->mean();
111
1.89M
    }
112
};
113
114
using CentroidListQueue =
115
        std::priority_queue<CentroidList, std::vector<CentroidList>, CentroidListComparator>;
116
117
struct CentroidComparator {
118
147M
    bool operator()(const Centroid& a, const Centroid& b) const { return a.mean() < b.mean(); }
119
};
120
121
class TDigest {
122
    ENABLE_FACTORY_CREATOR(TDigest);
123
124
    class TDigestComparator {
125
    public:
126
        TDigestComparator() = default;
127
128
0
        bool operator()(const TDigest* left, const TDigest* right) const {
129
0
            return left->total_size() > right->total_size();
130
0
        }
131
    };
132
    using TDigestQueue =
133
            std::priority_queue<const TDigest*, std::vector<const TDigest*>, TDigestComparator>;
134
135
public:
136
0
    TDigest() : TDigest(10000) {}
137
138
4.61k
    explicit TDigest(Value compression) : TDigest(compression, 0) {}
139
140
4.61k
    TDigest(Value compression, Index buffer_size) : TDigest(compression, buffer_size, 0) {}
141
142
    TDigest(Value compression, Index unmerged_size, Index merged_size)
143
4.61k
            : _compression(compression),
144
4.61k
              _max_processed(processed_size(merged_size, compression)),
145
4.61k
              _max_unprocessed(unprocessed_size(unmerged_size, compression)) {
146
        // Deliberately do not preallocate. Aggregations keep one digest per group
147
        // (percentile_approx, quantile_union), so reserving 2*compression processed and
148
        // 8*compression unprocessed centroids up front costs O(groups * compression) memory
149
        // before any value is stored: 800KB per group at the default compression 10000, which
150
        // is 480GB of virtual address space for 600K singleton groups. The buffers grow on
151
        // demand instead; _max_processed and _max_unprocessed still bound them and drive
152
        // exactly the same compression thresholds as before.
153
4.61k
    }
154
155
    TDigest(std::vector<Centroid>&& processed, std::vector<Centroid>&& unprocessed,
156
            Value compression, Index unmerged_size, Index merged_size)
157
0
            : TDigest(compression, unmerged_size, merged_size) {
158
0
        _processed = std::move(processed);
159
0
        _unprocessed = std::move(unprocessed);
160
0
161
0
        _processed_weight = weight(_processed);
162
0
        _unprocessed_weight = weight(_unprocessed);
163
0
        if (_processed.size() > 0) {
164
0
            _min = std::min(_min, _processed[0].mean());
165
0
            _max = std::max(_max, (_processed.cend() - 1)->mean());
166
0
        }
167
0
        _update_cumulative();
168
0
    }
169
170
0
    static Weight weight(std::vector<Centroid>& centroids) noexcept {
171
0
        Weight w = 0.0;
172
0
        for (auto centroid : centroids) {
173
0
            w += centroid.weight();
174
0
        }
175
0
        return w;
176
0
    }
177
178
24.0k
    TDigest(const TDigest&) = default;
179
180
0
    TDigest& operator=(TDigest&& o) {
181
0
        _compression = o._compression;
182
0
        _max_processed = o._max_processed;
183
0
        _max_unprocessed = o._max_unprocessed;
184
0
        _processed_weight = o._processed_weight;
185
0
        _unprocessed_weight = o._unprocessed_weight;
186
0
        _processed = std::move(o._processed);
187
0
        _unprocessed = std::move(o._unprocessed);
188
0
        _cumulative = std::move(o._cumulative);
189
0
        _min = o._min;
190
0
        _max = o._max;
191
0
        return *this;
192
0
    }
193
194
    TDigest(TDigest&& o)
195
            : TDigest(std::move(o._processed), std::move(o._unprocessed), o._compression,
196
0
                      o._max_unprocessed, o._max_processed) {}
197
198
4.61k
    static inline Index processed_size(Index size, Value compression) noexcept {
199
4.61k
        return (size == 0) ? static_cast<Index>(2 * std::ceil(compression)) : size;
200
4.61k
    }
201
202
4.61k
    static inline Index unprocessed_size(Index size, Value compression) noexcept {
203
4.61k
        return (size == 0) ? static_cast<Index>(8 * std::ceil(compression)) : size;
204
4.61k
    }
205
206
    // merge in another t-digest
207
1.26k
    void merge(const TDigest* other) {
208
1.26k
        std::vector<const TDigest*> others {other};
209
1.26k
        add(others.cbegin(), others.cend());
210
1.26k
    }
211
212
    const std::vector<Centroid>& processed() const { return _processed; }
213
214
    const std::vector<Centroid>& unprocessed() const { return _unprocessed; }
215
216
    Index max_unprocessed() const { return _max_unprocessed; }
217
218
    Index max_processed() const { return _max_processed; }
219
220
    void add(std::vector<const TDigest*> digests) { add(digests.cbegin(), digests.cend()); }
221
222
    // merge in a vector of tdigests in the most efficient manner possible
223
    // in constant space
224
    // works for any value of K_HIGH_WATER
225
    void add(std::vector<const TDigest*>::const_iterator iter,
226
1.26k
             std::vector<const TDigest*>::const_iterator end) {
227
1.26k
        if (iter != end) {
228
1.26k
            auto size = std::distance(iter, end);
229
1.26k
            TDigestQueue pq(TDigestComparator {});
230
2.53k
            for (; iter != end; iter++) {
231
1.26k
                pq.push((*iter));
232
1.26k
            }
233
1.26k
            std::vector<const TDigest*> batch;
234
1.26k
            batch.reserve(size);
235
236
1.26k
            size_t total_size = 0;
237
2.53k
            while (!pq.empty()) {
238
1.26k
                const auto* td = pq.top();
239
1.26k
                batch.push_back(td);
240
1.26k
                pq.pop();
241
1.26k
                total_size += td->total_size();
242
1.26k
                if (total_size >= K_HIGH_WATER || pq.empty()) {
243
1.26k
                    _merge_processed(batch);
244
1.26k
                    _merge_unprocessed(batch);
245
1.26k
                    _process_if_necessary();
246
1.26k
                    batch.clear();
247
1.26k
                    total_size = 0;
248
1.26k
                }
249
1.26k
            }
250
1.26k
            _update_cumulative();
251
1.26k
        }
252
1.26k
    }
253
254
0
    Weight processed_weight() const { return _processed_weight; }
255
256
0
    Weight unprocessed_weight() const { return _unprocessed_weight; }
257
258
51.7k
    bool have_unprocessed() const { return _unprocessed.size() > 0; }
259
260
3.73k
    size_t total_size() const { return _processed.size() + _unprocessed.size(); }
261
262
    long total_weight() const { return static_cast<long>(_processed_weight + _unprocessed_weight); }
263
264
    // return the cdf on the t-digest
265
    Value cdf(Value x) {
266
        if (have_unprocessed() || is_dirty()) {
267
            _process();
268
        }
269
        return cdf_processed(x);
270
    }
271
272
269k
    bool is_dirty() {
273
269k
        return _processed.size() > _max_processed || _unprocessed.size() > _max_unprocessed;
274
269k
    }
275
276
    // return the cdf on the processed values
277
0
    Value cdf_processed(Value x) const {
278
0
        VLOG_CRITICAL << "cdf value " << x;
279
0
        VLOG_CRITICAL << "processed size " << _processed.size();
280
0
        if (_processed.size() == 0) {
281
0
            // no data to examine
282
0
            VLOG_CRITICAL << "no processed values";
283
0
284
0
            return 0.0;
285
0
        } else if (_processed.size() == 1) {
286
0
            VLOG_CRITICAL << "one processed value "
287
0
                          << " _min " << _min << " _max " << _max;
288
0
            // exactly one centroid, should have _max==_min
289
0
            auto width = _max - _min;
290
0
            if (x < _min) {
291
0
                return 0.0;
292
0
            } else if (x > _max) {
293
0
                return 1.0;
294
0
            } else if (x - _min <= width) {
295
0
                // _min and _max are too close together to do any viable interpolation
296
0
                return 0.5;
297
0
            } else {
298
0
                // interpolate if somehow we have weight > 0 and _max != _min
299
0
                return (x - _min) / (_max - _min);
300
0
            }
301
0
        } else {
302
0
            auto n = _processed.size();
303
0
            if (x <= _min) {
304
0
                VLOG_CRITICAL << "below _min "
305
0
                              << " _min " << _min << " x " << x;
306
0
                return 0;
307
0
            }
308
0
309
0
            if (x >= _max) {
310
0
                VLOG_CRITICAL << "above _max "
311
0
                              << " _max " << _max << " x " << x;
312
0
                return 1;
313
0
            }
314
0
315
0
            // check for the left tail
316
0
            if (x <= _mean(0)) {
317
0
                VLOG_CRITICAL << "left tail "
318
0
                              << " _min " << _min << " mean(0) " << _mean(0) << " x " << x;
319
0
320
0
                // note that this is different than mean(0) > _min ... this guarantees interpolation works
321
0
                if (_mean(0) - _min > 0) {
322
0
                    return static_cast<Value>((x - _min) / (_mean(0) - _min) * _weight(0) /
323
0
                                              _processed_weight / 2.0);
324
0
                } else {
325
0
                    return 0;
326
0
                }
327
0
            }
328
0
329
0
            // and the right tail
330
0
            if (x >= _mean(n - 1)) {
331
0
                VLOG_CRITICAL << "right tail"
332
0
                              << " _max " << _max << " mean(n - 1) " << _mean(n - 1) << " x " << x;
333
0
334
0
                if (_max - _mean(n - 1) > 0) {
335
0
                    return static_cast<Value>(1.0 - (_max - x) / (_max - _mean(n - 1)) *
336
0
                                                            _weight(n - 1) / _processed_weight /
337
0
                                                            2.0);
338
0
                } else {
339
0
                    return 1;
340
0
                }
341
0
            }
342
0
343
0
            CentroidComparator cc;
344
0
            auto iter =
345
0
                    std::upper_bound(_processed.cbegin(), _processed.cend(), Centroid(x, 0), cc);
346
0
347
0
            auto i = std::distance(_processed.cbegin(), iter);
348
0
            auto z1 = x - (iter - 1)->mean();
349
0
            auto z2 = (iter)->mean() - x;
350
0
            DCHECK_LE(0.0, z1);
351
0
            DCHECK_LE(0.0, z2);
352
0
            VLOG_CRITICAL << "middle "
353
0
                          << " z1 " << z1 << " z2 " << z2 << " x " << x;
354
0
355
0
            return _weighted_average(_cumulative[i - 1], z2, _cumulative[i], z1) /
356
0
                   _processed_weight;
357
0
        }
358
0
    }
359
360
    // this returns a quantile on the t-digest
361
1.84k
    Value quantile(Value q) {
362
1.84k
        if (have_unprocessed() || is_dirty()) {
363
1.62k
            _process();
364
1.62k
        }
365
1.84k
        return quantile_processed(q);
366
1.84k
    }
367
368
    void quantiles(const double* quantile_levels, const size_t* permutation, size_t size,
369
427
                   double* result) {
370
427
        if (size == 0) {
371
0
            return;
372
0
        }
373
427
        if (have_unprocessed() || is_dirty()) {
374
389
            _process();
375
389
        }
376
377
427
        if (_processed.empty()) {
378
1
            std::fill(result, result + size, NAN);
379
1
            return;
380
1
        }
381
382
426
        if (_processed.size() == 1) {
383
359
            std::fill(result, result + size, static_cast<double>(_mean(0)));
384
359
            return;
385
359
        }
386
387
67
        const auto n = _processed.size();
388
67
        size_t cumulative_index = 0;
389
201
        for (size_t result_index = 0; result_index < size; ++result_index) {
390
134
            const size_t level_index = permutation[result_index];
391
134
            const auto q = static_cast<Value>(quantile_levels[level_index]);
392
134
            DCHECK_GE(q, 0);
393
134
            DCHECK_LE(q, 1);
394
395
134
            const auto index = q * _processed_weight;
396
134
            if (index <= _weight(0) / 2.0) {
397
39
                DCHECK_GT(_weight(0), 0);
398
39
                result[level_index] =
399
39
                        static_cast<Value>(_min + 2.0 * index / _weight(0) * (_mean(0) - _min));
400
39
                continue;
401
39
            }
402
403
1.33k
            while (cumulative_index < _cumulative.size() && _cumulative[cumulative_index] < index) {
404
1.24k
                ++cumulative_index;
405
1.24k
            }
406
407
95
            if (cumulative_index > 0 && cumulative_index + 1 < _cumulative.size()) {
408
85
                auto z1 = index - _cumulative[cumulative_index - 1];
409
85
                auto z2 = _cumulative[cumulative_index] - index;
410
85
                result[level_index] = static_cast<double>(_weighted_average(
411
85
                        _mean(cumulative_index - 1), z2, _mean(cumulative_index), z1));
412
85
                continue;
413
85
            }
414
415
95
            DCHECK_LE(index, _processed_weight);
416
10
            DCHECK_GE(index, _processed_weight - _weight(n - 1) / 2.0);
417
10
            auto z1 = static_cast<Value>(index - _processed_weight - _weight(n - 1) / 2.0);
418
10
            auto z2 = static_cast<Value>(_weight(n - 1) / 2 - z1);
419
10
            result[level_index] =
420
10
                    static_cast<double>(_weighted_average(_mean(n - 1), z1, _max, z2));
421
10
        }
422
67
    }
423
424
    // this returns a quantile on the currently processed values without changing the t-digest
425
    // the value will not represent the unprocessed values
426
2.79k
    Value quantile_processed(Value q) const {
427
2.79k
        if (q < 0 || q > 1) {
428
0
            VLOG_CRITICAL << "q should be in [0,1], got " << q;
429
0
            return NAN;
430
0
        }
431
432
2.79k
        if (_processed.size() == 0) {
433
            // no sorted means no data, no way to get a quantile
434
121
            return NAN;
435
2.66k
        } else if (_processed.size() == 1) {
436
            // with one data point, all quantiles lead to Rome
437
438
1.32k
            return _mean(0);
439
1.32k
        }
440
441
        // we know that there are at least two sorted now
442
1.34k
        auto n = _processed.size();
443
444
        // if values were stored in a sorted array, index would be the offset we are Weighterested in
445
1.34k
        const auto index = q * _processed_weight;
446
447
        // at the boundaries, we return _min or _max
448
1.34k
        if (index <= _weight(0) / 2.0) {
449
89
            DCHECK_GT(_weight(0), 0);
450
89
            return static_cast<Value>(_min + 2.0 * index / _weight(0) * (_mean(0) - _min));
451
89
        }
452
453
1.25k
        auto iter = std::lower_bound(_cumulative.cbegin(), _cumulative.cend(), index);
454
455
1.25k
        if (iter != _cumulative.cend() && iter != _cumulative.cbegin() &&
456
1.25k
            iter + 1 != _cumulative.cend()) {
457
519
            auto i = std::distance(_cumulative.cbegin(), iter);
458
519
            auto z1 = index - *(iter - 1);
459
519
            auto z2 = *(iter)-index;
460
            // VLOG_CRITICAL << "z2 " << z2 << " index " << index << " z1 " << z1;
461
519
            return _weighted_average(_mean(i - 1), z2, _mean(i), z1);
462
519
        }
463
464
1.25k
        DCHECK_LE(index, _processed_weight);
465
735
        DCHECK_GE(index, _processed_weight - _weight(n - 1) / 2.0);
466
467
735
        auto z1 = static_cast<Value>(index - _processed_weight - _weight(n - 1) / 2.0);
468
735
        auto z2 = static_cast<Value>(_weight(n - 1) / 2 - z1);
469
735
        return _weighted_average(_mean(n - 1), z1, _max, z2);
470
1.25k
    }
471
472
0
    Value compression() const { return _compression; }
473
474
258k
    void add(Value x) { add(x, 1); }
475
476
24.1k
    void compress() { _process(); }
477
478
    // add a single centroid to the unprocessed vector, processing previously unprocessed sorted if our limit has
479
    // been reached.
480
268k
    bool add(Value x, Weight w) {
481
268k
        if (std::isnan(x)) {
482
478
            return false;
483
478
        }
484
268k
        _unprocessed.emplace_back(x, w);
485
268k
        _unprocessed_weight += w;
486
268k
        _process_if_necessary();
487
268k
        return true;
488
268k
    }
489
490
    void add(std::vector<Centroid>::const_iterator iter,
491
0
             std::vector<Centroid>::const_iterator end) {
492
0
        while (iter != end) {
493
0
            const size_t diff = std::distance(iter, end);
494
0
            const size_t room = _max_unprocessed - _unprocessed.size();
495
0
            auto mid = iter + std::min(diff, room);
496
0
            while (iter != mid) {
497
0
                _unprocessed.push_back(*(iter++));
498
0
            }
499
0
            if (_unprocessed.size() >= _max_unprocessed) {
500
0
                _process();
501
0
            }
502
0
        }
503
0
    }
504
505
1.94k
    uint32_t serialized_size() {
506
1.94k
        return static_cast<uint32_t>(sizeof(uint32_t) + sizeof(Value) * 5 + sizeof(Index) * 2 +
507
1.94k
                                     sizeof(uint32_t) * 3 + _processed.size() * sizeof(Centroid) +
508
1.94k
                                     _unprocessed.size() * sizeof(Centroid) +
509
1.94k
                                     _cumulative.size() * sizeof(Weight));
510
1.94k
    }
511
512
962
    size_t serialize(uint8_t* writer) {
513
962
        uint8_t* dst = writer;
514
962
        uint32_t total_size = serialized_size();
515
962
        memcpy(writer, &total_size, sizeof(uint32_t));
516
962
        writer += sizeof(uint32_t);
517
962
        memcpy(writer, &_compression, sizeof(Value));
518
962
        writer += sizeof(Value);
519
962
        memcpy(writer, &_min, sizeof(Value));
520
962
        writer += sizeof(Value);
521
962
        memcpy(writer, &_max, sizeof(Value));
522
962
        writer += sizeof(Value);
523
962
        memcpy(writer, &_max_processed, sizeof(Index));
524
962
        writer += sizeof(Index);
525
962
        memcpy(writer, &_max_unprocessed, sizeof(Index));
526
962
        writer += sizeof(Index);
527
962
        memcpy(writer, &_processed_weight, sizeof(Value));
528
962
        writer += sizeof(Value);
529
962
        memcpy(writer, &_unprocessed_weight, sizeof(Value));
530
962
        writer += sizeof(Value);
531
532
962
        auto size = static_cast<uint32_t>(_processed.size());
533
962
        memcpy(writer, &size, sizeof(uint32_t));
534
962
        writer += sizeof(uint32_t);
535
379k
        for (int i = 0; i < size; i++) {
536
378k
            memcpy(writer, &_processed[i], sizeof(Centroid));
537
378k
            writer += sizeof(Centroid);
538
378k
        }
539
540
962
        size = static_cast<uint32_t>(_unprocessed.size());
541
962
        memcpy(writer, &size, sizeof(uint32_t));
542
962
        writer += sizeof(uint32_t);
543
        //TODO(weixiang): may be once memcpy is enough!
544
6.12k
        for (int i = 0; i < size; i++) {
545
5.16k
            memcpy(writer, &_unprocessed[i], sizeof(Centroid));
546
5.16k
            writer += sizeof(Centroid);
547
5.16k
        }
548
549
962
        size = static_cast<uint32_t>(_cumulative.size());
550
962
        memcpy(writer, &size, sizeof(uint32_t));
551
962
        writer += sizeof(uint32_t);
552
380k
        for (int i = 0; i < size; i++) {
553
379k
            memcpy(writer, &_cumulative[i], sizeof(Weight));
554
379k
            writer += sizeof(Weight);
555
379k
        }
556
962
        return writer - dst;
557
962
    }
558
559
974
    void unserialize(const uint8_t* type_reader) {
560
974
        uint32_t total_length = 0;
561
974
        memcpy(&total_length, type_reader, sizeof(uint32_t));
562
974
        type_reader += sizeof(uint32_t);
563
974
        memcpy(&_compression, type_reader, sizeof(Value));
564
974
        type_reader += sizeof(Value);
565
974
        memcpy(&_min, type_reader, sizeof(Value));
566
974
        type_reader += sizeof(Value);
567
974
        memcpy(&_max, type_reader, sizeof(Value));
568
974
        type_reader += sizeof(Value);
569
570
974
        memcpy(&_max_processed, type_reader, sizeof(Index));
571
974
        type_reader += sizeof(Index);
572
974
        memcpy(&_max_unprocessed, type_reader, sizeof(Index));
573
974
        type_reader += sizeof(Index);
574
974
        memcpy(&_processed_weight, type_reader, sizeof(Value));
575
974
        type_reader += sizeof(Value);
576
974
        memcpy(&_unprocessed_weight, type_reader, sizeof(Value));
577
974
        type_reader += sizeof(Value);
578
579
974
        uint32_t size;
580
974
        memcpy(&size, type_reader, sizeof(uint32_t));
581
974
        type_reader += sizeof(uint32_t);
582
974
        _processed.resize(size);
583
434k
        for (int i = 0; i < size; i++) {
584
433k
            memcpy(&_processed[i], type_reader, sizeof(Centroid));
585
433k
            type_reader += sizeof(Centroid);
586
433k
        }
587
974
        memcpy(&size, type_reader, sizeof(uint32_t));
588
974
        type_reader += sizeof(uint32_t);
589
974
        _unprocessed.resize(size);
590
6.06k
        for (int i = 0; i < size; i++) {
591
5.09k
            memcpy(&_unprocessed[i], type_reader, sizeof(Centroid));
592
5.09k
            type_reader += sizeof(Centroid);
593
5.09k
        }
594
974
        memcpy(&size, type_reader, sizeof(uint32_t));
595
974
        type_reader += sizeof(uint32_t);
596
974
        _cumulative.resize(size);
597
435k
        for (int i = 0; i < size; i++) {
598
434k
            memcpy(&_cumulative[i], type_reader, sizeof(Weight));
599
434k
            type_reader += sizeof(Weight);
600
434k
        }
601
974
    }
602
603
private:
604
    Value _compression;
605
606
    Value _min = std::numeric_limits<Value>::max();
607
608
    // min() is the smallest positive value, so use lowest() for all-negative input,
609
    // e.g. {-3, -2, -1} must set _max to -1.
610
    Value _max = std::numeric_limits<Value>::lowest();
611
612
    Index _max_processed;
613
614
    Index _max_unprocessed;
615
616
    Value _processed_weight = 0.0;
617
618
    Value _unprocessed_weight = 0.0;
619
620
    std::vector<Centroid> _processed;
621
622
    std::vector<Centroid> _unprocessed;
623
624
    std::vector<Weight> _cumulative;
625
626
    // return mean of i-th centroid
627
3.77k
    Value _mean(int64_t i) const noexcept { return _processed[i].mean(); }
628
629
    // return weight of i-th centroid
630
147M
    Weight _weight(int64_t i) const noexcept { return _processed[i].weight(); }
631
632
    // append all unprocessed centroids into current unprocessed vector
633
1.26k
    void _merge_unprocessed(const std::vector<const TDigest*>& tdigests) {
634
1.26k
        if (tdigests.size() == 0) {
635
0
            return;
636
0
        }
637
638
        // Insert directly instead of reserving the exact merged size: reserve() reallocates
639
        // and copies the whole buffer whenever `total` exceeds the current capacity, so
640
        // merging many small digests would cost O(n^2) copies. insert() grows geometrically.
641
1.26k
        for (const auto& td : tdigests) {
642
1.26k
            _unprocessed.insert(_unprocessed.end(), td->_unprocessed.cbegin(),
643
1.26k
                                td->_unprocessed.cend());
644
1.26k
            _unprocessed_weight += td->_unprocessed_weight;
645
1.26k
        }
646
1.26k
    }
647
648
    // merge all processed centroids together into a single sorted vector
649
1.26k
    void _merge_processed(const std::vector<const TDigest*>& tdigests) {
650
1.26k
        if (tdigests.size() == 0) {
651
0
            return;
652
0
        }
653
654
1.26k
        size_t total = 0;
655
1.26k
        CentroidListQueue pq(CentroidListComparator {});
656
1.26k
        for (const auto& td : tdigests) {
657
1.26k
            const auto& sorted = td->_processed;
658
1.26k
            auto size = sorted.size();
659
1.26k
            if (size > 0) {
660
436
                pq.push(CentroidList(sorted));
661
436
                total += size;
662
436
                _processed_weight += td->_processed_weight;
663
436
            }
664
1.26k
        }
665
1.26k
        if (total == 0) {
666
833
            return;
667
833
        }
668
669
435
        if (_processed.size() > 0) {
670
435
            pq.push(CentroidList(_processed));
671
435
            total += _processed.size();
672
435
        }
673
674
435
        std::vector<Centroid> sorted;
675
435
        VLOG_CRITICAL << "total " << total;
676
435
        sorted.reserve(total);
677
678
2.10M
        while (!pq.empty()) {
679
2.10M
            auto best = pq.top();
680
2.10M
            pq.pop();
681
2.10M
            sorted.push_back(*(best.iter));
682
2.10M
            if (best.advance()) {
683
2.06M
                pq.push(best);
684
2.06M
            }
685
2.10M
        }
686
435
        _processed = std::move(sorted);
687
436
        if (_processed.size() > 0) {
688
436
            _min = std::min(_min, _processed[0].mean());
689
436
            _max = std::max(_max, (_processed.cend() - 1)->mean());
690
436
        }
691
435
    }
692
693
269k
    void _process_if_necessary() {
694
269k
        if (is_dirty()) {
695
437
            _process();
696
437
        }
697
269k
    }
698
699
27.8k
    void _update_cumulative() {
700
27.8k
        const auto n = _processed.size();
701
27.8k
        _cumulative.clear();
702
27.8k
        _cumulative.reserve(n + 1);
703
27.8k
        Weight previous = 0.0;
704
147M
        for (Index i = 0; i < n; i++) {
705
147M
            Weight current = _weight(i);
706
147M
            auto half_current = static_cast<Weight>(current / 2.0);
707
147M
            _cumulative.push_back(previous + half_current);
708
147M
            previous = previous + current;
709
147M
        }
710
27.8k
        _cumulative.push_back(previous);
711
27.8k
    }
712
713
    // merges _unprocessed centroids and _processed centroids together and processes them
714
    // when complete, _unprocessed will be empty and _processed will have at most _max_processed centroids
715
26.6k
    void _process() {
716
26.6k
        CentroidComparator cc;
717
        // select percentile_approx(lo_orderkey,0.5) from lineorder;
718
        // have test pdqsort and RadixSort, find here pdqsort performance is better when data is struct Centroid
719
        // But when sort plain type like int/float of std::vector<T>, find RadixSort is better
720
26.6k
        pdqsort(_unprocessed.begin(), _unprocessed.end(), cc);
721
26.6k
        auto count = _unprocessed.size();
722
26.6k
        _unprocessed.insert(_unprocessed.end(), _processed.cbegin(), _processed.cend());
723
26.6k
        std::inplace_merge(_unprocessed.begin(), _unprocessed.begin() + count, _unprocessed.end(),
724
26.6k
                           cc);
725
726
26.6k
        _processed_weight += _unprocessed_weight;
727
26.6k
        _unprocessed_weight = 0;
728
26.6k
        _processed.clear();
729
730
26.6k
        _processed.push_back(_unprocessed[0]);
731
26.6k
        Weight w_so_far = _unprocessed[0].weight();
732
26.6k
        Weight w_limit = _processed_weight * _integrated_q(1.0);
733
734
26.6k
        auto end = _unprocessed.end();
735
147M
        for (auto iter = _unprocessed.cbegin() + 1; iter < end; iter++) {
736
147M
            const auto& centroid = *iter;
737
147M
            Weight projected_w = w_so_far + centroid.weight();
738
147M
            if (projected_w <= w_limit) {
739
1.10M
                w_so_far = projected_w;
740
1.10M
                (_processed.end() - 1)->add(centroid);
741
145M
            } else {
742
145M
                auto k1 = _integrated_location(w_so_far / _processed_weight);
743
145M
                w_limit = _processed_weight * _integrated_q(static_cast<Value>(k1 + 1.0));
744
145M
                w_so_far += centroid.weight();
745
145M
                _processed.emplace_back(centroid);
746
145M
            }
747
147M
        }
748
26.6k
        _unprocessed.clear();
749
26.6k
        _min = std::min(_min, _processed[0].mean());
750
26.6k
        VLOG_CRITICAL << "new _min " << _min;
751
26.6k
        _max = std::max(_max, (_processed.cend() - 1)->mean());
752
26.6k
        VLOG_CRITICAL << "new _max " << _max;
753
26.6k
        _update_cumulative();
754
26.6k
    }
755
756
0
    size_t _check_weights(const std::vector<Centroid>& sorted, Value total) {
757
0
        size_t bad_weight = 0;
758
0
        auto k1 = 0.0;
759
0
        auto q = 0.0;
760
0
        for (auto iter = sorted.cbegin(); iter != sorted.cend(); iter++) {
761
0
            auto w = iter->weight();
762
0
            auto dq = w / total;
763
0
            auto k2 = _integrated_location(static_cast<Value>(q + dq));
764
0
            if (k2 - k1 > 1 && w != 1) {
765
0
                VLOG_CRITICAL << "Oversize centroid at " << std::distance(sorted.cbegin(), iter)
766
0
                              << " k1 " << k1 << " k2 " << k2 << " dk " << (k2 - k1) << " w " << w
767
0
                              << " q " << q;
768
0
                bad_weight++;
769
0
            }
770
0
            if (k2 - k1 > 1.5 && w != 1) {
771
0
                VLOG_CRITICAL << "Egregiously Oversize centroid at "
772
0
                              << std::distance(sorted.cbegin(), iter) << " k1 " << k1 << " k2 "
773
0
                              << k2 << " dk " << (k2 - k1) << " w " << w << " q " << q;
774
0
                bad_weight++;
775
0
            }
776
0
            q += dq;
777
0
            k1 = k2;
778
0
        }
779
0
780
0
        return bad_weight;
781
0
    }
782
783
    /**
784
    * Converts a quantile into a centroid scale value.  The centroid scale is nomin_ally
785
    * the number k of the centroid that a quantile point q should belong to.  Due to
786
    * round-offs, however, we can't align things perfectly without splitting points
787
    * and sorted.  We don't want to do that, so we have to allow for offsets.
788
    * In the end, the criterion is that any quantile range that spans a centroid
789
    * scale range more than one should be split across more than one centroid if
790
    * possible.  This won't be possible if the quantile range refers to a single point
791
    * or an already existing centroid.
792
    * <p/>
793
    * This mapping is steep near q=0 or q=1 so each centroid there will correspond to
794
    * less q range.  Near q=0.5, the mapping is flatter so that sorted there will
795
    * represent a larger chunk of quantiles.
796
    *
797
    * @param q The quantile scale value to be mapped.
798
    * @return The centroid scale value corresponding to q.
799
    */
800
145M
    Value _integrated_location(Value q) const {
801
145M
        return static_cast<Value>(_compression * (std::asin(2.0 * q - 1.0) + M_PI / 2) / M_PI);
802
145M
    }
803
804
145M
    Value _integrated_q(Value k) const {
805
145M
        return static_cast<Value>(
806
145M
                (std::sin(std::min(k, _compression) * M_PI / _compression - M_PI / 2) + 1) / 2);
807
145M
    }
808
809
    /**
810
     * Same as {@link #_weighted_average_sorted(Value, Value, Value, Value)} but flips
811
     * the order of the variables if <code>x2</code> is greater than
812
     * <code>x1</code>.
813
    */
814
1.35k
    static Value _weighted_average(Value x1, Value w1, Value x2, Value w2) {
815
1.35k
        return (x1 <= x2) ? _weighted_average_sorted(x1, w1, x2, w2)
816
1.35k
                          : _weighted_average_sorted(x2, w2, x1, w1);
817
1.35k
    }
818
819
    /**
820
    * Compute the weighted average between <code>x1</code> with a weight of
821
    * <code>w1</code> and <code>x2</code> with a weight of <code>w2</code>.
822
    * This expects <code>x1</code> to be less than or equal to <code>x2</code>
823
    * and is guaranteed to return a number between <code>x1</code> and
824
    * <code>x2</code>.
825
    */
826
1.35k
    static Value _weighted_average_sorted(Value x1, Value w1, Value x2, Value w2) {
827
1.35k
        DCHECK_LE(x1, x2);
828
1.35k
        const Value x = (x1 * w1 + x2 * w2) / (w1 + w2);
829
1.35k
        return std::max(x1, std::min(x, x2));
830
1.35k
    }
831
832
0
    static Value _interpolate(Value x, Value x0, Value x1) { return (x - x0) / (x1 - x0); }
833
834
    /**
835
    * Computes an interpolated value of a quantile that is between two sorted.
836
    *
837
    * Index is the quantile desired multiplied by the total number of samples - 1.
838
    *
839
    * @param index              Denormalized quantile desired
840
    * @param previous_index     The denormalized quantile corresponding to the center of the previous centroid.
841
    * @param next_index         The denormalized quantile corresponding to the center of the following centroid.
842
    * @param previous_mean      The mean of the previous centroid.
843
    * @param next_mean          The mean of the following centroid.
844
    * @return  The interpolated mean.
845
    */
846
    static Value _quantile(Value index, Value previous_index, Value next_index, Value previous_mean,
847
0
                           Value next_mean) {
848
0
        const auto delta = next_index - previous_index;
849
0
        const auto previous_weight = (next_index - index) / delta;
850
0
        const auto next_weight = (index - previous_index) / delta;
851
0
        return previous_mean * previous_weight + next_mean * next_weight;
852
0
    }
853
};
854
} // namespace doris