Skip to content

Commit 6d62e09

Browse files
authored
Make TDigestState configurable (#96794)
* Initial import for TDigest forking. * Fix MedianTest. More work needed for TDigestPercentile*Tests and the TDigestTest (and the rest of the tests) in the tdigest lib to pass. * Fix Dist. * Fix AVLTreeDigest.quantile to match Dist for uniform centroids. * Update docs/changelog/96086.yaml * Fix `MergingDigest.quantile` to match `Dist` on uniform distribution. * Add merging to TDigestState.hashCode and .equals. Remove wrong asserts from tests and MergingDigest. * Fix style violations for tdigest library. * Fix typo. * Fix more style violations. * Fix more style violations. * Fix remaining style violations in tdigest library. * Update results in docs based on the forked tdigest. * Fix YAML tests in aggs module. * Fix YAML tests in x-pack/plugin. * Skip failing V7 compat tests in modules/aggregations. * Fix TDigest library unittests. Remove redundant serializing interfaces from the library. * Remove YAML test versions for older releases. These tests don't address compatibility issues in mixed cluster tests as the latter contain a mix of older and newer nodes, so the output depends on which node is picked as a data node since the forked TDigest library is not backwards compatible (produces slightly different results). * Fix test failures in docs and mixed cluster. * Reduce buffer sizes in MergingDigest to avoid oom. * Exclude more failing V7 compatibility tests. * Update results for JdbcCsvSpecIT tests. * Update results for JdbcDocCsvSpecIT tests. * Revert unrelated change. * More test fixes. * Use version skips instead of blacklisting in mixed cluster tests. * Switch TDigestState back to AVLTreeDigest. * Update docs and tests with AVLTreeDigest output. * Update flaky test. * Remove dead code, esp around tracking of incoming data. * Update docs/changelog/96086.yaml * Delete docs/changelog/96086.yaml * Remove explicit compression calls. This was added to prevent concurrency tests from failing, but it leads to reduces precision. Submit this to see if the concurrency tests are still failing. * Revert "Remove explicit compression calls." This reverts commit 5352c96. * Remove explicit compression calls to MedianAbsoluteDeviation input. * Add unittests for AVL and merging digest accuracy. * Fix spotless violations. * Delete redundant tests and benchmarks. * Fix spotless violation. * Use the old implementation of AVLTreeDigest. The latest library version is 50% slower and less accurate, as verified by ComparisonTests. * Update docs with latest percentile results. * Update docs with latest percentile results. * Remove repeated compression calls. * Update more percentile results. * Use approximate percentile values in integration tests. This helps with mixed cluster tests, where some of the tests where blocked. * Fix expected percentile value in test. * Revert in-place node updates in AVL tree. Update quantile calculations between centroids and min/max values to match v.3.2. * Add SortingDigest and HybridDigest. The SortingDigest tracks all samples in an ArrayList that gets sorted for quantile calculations. This approach provides perfectly accurate results and is the most efficient implementation for up to millions of samples, at the cost of bloated memory footprint. The HybridDigest uses a SortingDigest for small sample populations, then switches to a MergingDigest. This approach combines to the best performance and results for small sample counts with very good performance and acceptable accuracy for effectively unbounded sample counts. * Remove deps to the 3.2 library. * Remove unused licenses for tdigest. * Revert changes for SortingDigest and HybridDigest. These will be submitted in a follow-up PR for enabling MergingDigest. * Remove unused Histogram classes and unit tests. Delete dead and commented out code, make the remaining tests run reasonably fast. Remove unused annotations, esp. SuppressWarnings. * Remove Comparison class, not used. * Revert "Revert changes for SortingDigest and HybridDigest." This reverts commit 2336b11. * Use HybridDigest as default tdigest implementation Add SortingDigest as a simple structure for percentile calculations that tracks all data points in a sorted array. This is a fast and perfectly accurate solution that leads to bloated memory allocation. Add HybridDigest that uses SortingDigest for small sample counts, then switches to MergingDigest. This approach delivers extreme performance and accuracy for small populations while scaling indefinitely and maintaining acceptable performance and accuracy with constant memory allocation (15kB by default). Provide knobs to switch back to AVLTreeDigest, either per query or through ClusterSettings. * Small fixes. * Add javadoc and tests. * Add javadoc and tests. * Remove special logic for singletons in the boundaries. While this helps with the case where the digest contains only singletons (perfect accuracy), it has a major issue problem (non-monotonic quantile function) when the first singleton is followed by a non-singleton centroid. It's preferable to revert to the old version from 3.2; inaccuracies in a singleton-only digest should be mitigated by using a sorted array for small sample counts. * Revert changes to expected values in tests. This is due to restoring quantile functions to match head. * Revert changes to expected values in tests. This is due to restoring quantile functions to match head. * Tentatively restore percentile rank expected results. * Use cdf version from 3.2 Update Dist.cdf to use interpolation, use the same cdf version in AVLTreeDigest and MergingDigest. * Revert "Tentatively restore percentile rank expected results." This reverts commit 7718dbb. * Revert remaining changes compared to main. * Revert excluded V7 compat tests. * Exclude V7 compat tests still failing. * Exclude V7 compat tests still failing. * Remove ClusterSettings tentatively. * Initial import for TDigest forking. * Fix MedianTest. More work needed for TDigestPercentile*Tests and the TDigestTest (and the rest of the tests) in the tdigest lib to pass. * Fix Dist. * Fix AVLTreeDigest.quantile to match Dist for uniform centroids. * Update docs/changelog/96086.yaml * Fix `MergingDigest.quantile` to match `Dist` on uniform distribution. * Add merging to TDigestState.hashCode and .equals. Remove wrong asserts from tests and MergingDigest. * Fix style violations for tdigest library. * Fix typo. * Fix more style violations. * Fix more style violations. * Fix remaining style violations in tdigest library. * Update results in docs based on the forked tdigest. * Fix YAML tests in aggs module. * Fix YAML tests in x-pack/plugin. * Skip failing V7 compat tests in modules/aggregations. * Fix TDigest library unittests. Remove redundant serializing interfaces from the library. * Remove YAML test versions for older releases. These tests don't address compatibility issues in mixed cluster tests as the latter contain a mix of older and newer nodes, so the output depends on which node is picked as a data node since the forked TDigest library is not backwards compatible (produces slightly different results). * Fix test failures in docs and mixed cluster. * Reduce buffer sizes in MergingDigest to avoid oom. * Exclude more failing V7 compatibility tests. * Update results for JdbcCsvSpecIT tests. * Update results for JdbcDocCsvSpecIT tests. * Revert unrelated change. * More test fixes. * Use version skips instead of blacklisting in mixed cluster tests. * Switch TDigestState back to AVLTreeDigest. * Update docs and tests with AVLTreeDigest output. * Update flaky test. * Remove dead code, esp around tracking of incoming data. * Remove explicit compression calls. This was added to prevent concurrency tests from failing, but it leads to reduces precision. Submit this to see if the concurrency tests are still failing. * Update docs/changelog/96086.yaml * Delete docs/changelog/96086.yaml * Revert "Remove explicit compression calls." This reverts commit 5352c96. * Remove explicit compression calls to MedianAbsoluteDeviation input. * Add unittests for AVL and merging digest accuracy. * Fix spotless violations. * Delete redundant tests and benchmarks. * Fix spotless violation. * Use the old implementation of AVLTreeDigest. The latest library version is 50% slower and less accurate, as verified by ComparisonTests. * Update docs with latest percentile results. * Update docs with latest percentile results. * Remove repeated compression calls. * Update more percentile results. * Use approximate percentile values in integration tests. This helps with mixed cluster tests, where some of the tests where blocked. * Fix expected percentile value in test. * Revert in-place node updates in AVL tree. Update quantile calculations between centroids and min/max values to match v.3.2. * Add SortingDigest and HybridDigest. The SortingDigest tracks all samples in an ArrayList that gets sorted for quantile calculations. This approach provides perfectly accurate results and is the most efficient implementation for up to millions of samples, at the cost of bloated memory footprint. The HybridDigest uses a SortingDigest for small sample populations, then switches to a MergingDigest. This approach combines to the best performance and results for small sample counts with very good performance and acceptable accuracy for effectively unbounded sample counts. * Remove deps to the 3.2 library. * Remove unused licenses for tdigest. * Revert changes for SortingDigest and HybridDigest. These will be submitted in a follow-up PR for enabling MergingDigest. * Remove unused Histogram classes and unit tests. Delete dead and commented out code, make the remaining tests run reasonably fast. Remove unused annotations, esp. SuppressWarnings. * Remove Comparison class, not used. * Revert "Revert changes for SortingDigest and HybridDigest." This reverts commit 2336b11. * Use HybridDigest as default tdigest implementation Add SortingDigest as a simple structure for percentile calculations that tracks all data points in a sorted array. This is a fast and perfectly accurate solution that leads to bloated memory allocation. Add HybridDigest that uses SortingDigest for small sample counts, then switches to MergingDigest. This approach delivers extreme performance and accuracy for small populations while scaling indefinitely and maintaining acceptable performance and accuracy with constant memory allocation (15kB by default). Provide knobs to switch back to AVLTreeDigest, either per query or through ClusterSettings. * Add javadoc and tests. * Remove ClusterSettings tentatively. * Restore bySize function in TDigest and subclasses. * Update Dist.cdf to match the rest. Update tests. * Revert outdated test changes. * Revert outdated changes. * Small fixes. * Update docs/changelog/96794.yaml * Make HybridDigest the default implementation. * Update boxplot documentation. * Restore AVLTreeDigest as the default in TDigestState. TDigest.createHybridDigest nw returns the right type. The switch in TDigestState will happen in a separate PR as it requires many test updates. * Use execution_hint in tdigest spec. * Fix Dist.cdf for empty digest. * Bump up TransportVersion. * Bump up TransportVersion for real. * HybridDigest uses its final implementation during deserialization. * Restore the right TransportVersion in TDigestState.read * Use TDigestExecutionHint instead of strings. * Add link to TDigest javadoc. * Spotless fix. * Small fixes. * Bump up TransportVersion. * Bump up the TransportVersion, again.
1 parent 09db486 commit 6d62e09

File tree

58 files changed

+1330
-198
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

58 files changed

+1330
-198
lines changed

docs/changelog/96794.yaml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
pr: 96794
2+
summary: Make TDigestState configurable
3+
area: Aggregations
4+
type: enhancement
5+
issues: []

docs/reference/aggregations/metrics/boxplot-aggregation.asciidoc

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,35 @@ GET latency/_search
166166

167167
include::percentile-aggregation.asciidoc[tags=t-digest]
168168

169+
==== Execution hint
170+
171+
The default implementation of TDigest is optimized for performance, scaling to millions or even
172+
billions of sample values while maintaining acceptable accuracy levels (close to 1% relative error
173+
for millions of samples in some cases). There's an option to use an implementation optimized
174+
for accuracy by setting parameter `execution_hint` to value `high_accuracy`:
175+
176+
[source,console]
177+
--------------------------------------------------
178+
GET latency/_search
179+
{
180+
"size": 0,
181+
"aggs": {
182+
"load_time_boxplot": {
183+
"boxplot": {
184+
"field": "load_time",
185+
"execution_hint": "high_accuracy" <1>
186+
}
187+
}
188+
}
189+
}
190+
--------------------------------------------------
191+
// TEST[setup:latency]
192+
193+
<1> Optimize TDigest for accuracy, at the expense of performance
194+
195+
This option can lead to improved accuracy (relative error close to 0.01% for millions of samples in some
196+
cases) but then percentile queries take 2x-10x longer to complete.
197+
169198
==== Missing value
170199

171200
The `missing` parameter defines how documents that are missing a value should be treated.

docs/reference/aggregations/metrics/percentile-aggregation.asciidoc

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,38 @@ TDigest roughly 64KB in size. In practice data tends to be more random and
306306
the TDigest will use less memory.
307307
// end::t-digest[]
308308

309+
[[search-aggregations-metrics-percentile-aggregation-execution-hint]]
310+
==== Execution hint
311+
312+
The default implementation of TDigest is optimized for performance, scaling to millions or even
313+
billions of sample values while maintaining acceptable accuracy levels (close to 1% relative error
314+
for millions of samples in some cases). There's an option to use an implementation optimized
315+
for accuracy by setting parameter `execution_hint` to value `high_accuracy`:
316+
317+
[source,console]
318+
--------------------------------------------------
319+
GET latency/_search
320+
{
321+
"size": 0,
322+
"aggs": {
323+
"load_time_outlier": {
324+
"percentiles": {
325+
"field": "load_time",
326+
"tdigest": {
327+
"execution_hint": "high_accuracy" <1>
328+
}
329+
}
330+
}
331+
}
332+
}
333+
--------------------------------------------------
334+
// TEST[setup:latency]
335+
336+
<1> Optimize TDigest for accuracy, at the expense of performance
337+
338+
This option can lead to improved accuracy (relative error close to 0.01% for millions of samples in some
339+
cases) but then percentile queries take 2x-10x longer to complete.
340+
309341
==== HDR Histogram
310342

311343
https://github.com/HdrHistogram/HdrHistogram[HDR Histogram] (High Dynamic Range Histogram) is an alternative implementation

docs/reference/aggregations/metrics/percentile-rank-aggregation.asciidoc

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@ extracted from specific numeric or <<histogram,histogram fields>> in the documen
1010

1111
[NOTE]
1212
==================================================
13-
Please see <<search-aggregations-metrics-percentile-aggregation-approximation>>
14-
and <<search-aggregations-metrics-percentile-aggregation-compression>> for advice
15-
regarding approximation and memory use of the percentile ranks aggregation
13+
Please see <<search-aggregations-metrics-percentile-aggregation-approximation>>,
14+
<<search-aggregations-metrics-percentile-aggregation-compression>> and
15+
<<search-aggregations-metrics-percentile-aggregation-execution-hint>> for advice
16+
regarding approximation, performance and memory use of the percentile ranks aggregation
1617
==================================================
1718

1819
Percentile rank show the percentage of observed values which are below certain

libs/tdigest/src/main/java/org/elasticsearch/tdigest/Dist.java

Lines changed: 55 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -30,30 +30,68 @@
3030
public class Dist {
3131

3232
private static double cdf(final double x, final int length, Function<Integer, Double> elementGetter) {
33+
if (length == 0) {
34+
// no data to examine
35+
return Double.NaN;
36+
}
37+
if (length == 1) {
38+
double value = elementGetter.apply(0);
39+
if (x < value) return 0;
40+
if (x > value) return 1;
41+
return 0.5;
42+
}
43+
3344
if (Double.compare(x, elementGetter.apply(0)) < 0) {
3445
return 0;
3546
}
3647

37-
double n1 = 0.5;
38-
int n2 = 0;
39-
for (int i = 1; i < length; i++) {
40-
double value = elementGetter.apply(i);
41-
int compareResult = Double.compare(value, x);
42-
if (compareResult > 0) {
43-
if (Double.compare(n2, 0) > 0) {
44-
return (n1 + 0.5 * n2) / length;
45-
}
46-
double previousValue = elementGetter.apply(i - 1);
47-
double factor = (x - previousValue) / (value - previousValue);
48-
return (n1 + factor) / length;
48+
if (Double.compare(x, elementGetter.apply(0)) == 0) {
49+
// we have one or more centroids == x, treat them as one
50+
// dw will accumulate the weight of all of the centroids at x
51+
double dw = 0;
52+
for (int i = 0; i < length && Double.compare(elementGetter.apply(i), x) == 0; i++) {
53+
dw += 1;
54+
}
55+
return dw / 2.0 / length;
56+
}
57+
58+
if (x > elementGetter.apply(length - 1)) {
59+
return 1;
60+
}
61+
if (x == elementGetter.apply(length - 1)) {
62+
double dw = 0;
63+
for (int i = length - 1; i >= 0 && Double.compare(elementGetter.apply(i), x) == 0; i--) {
64+
dw += 1;
4965
}
50-
if (compareResult < 0) {
51-
n1++;
52-
} else {
53-
n2++;
66+
return (length - dw / 2.0) / length;
67+
}
68+
69+
// initially, we set left width equal to right width
70+
double left = (elementGetter.apply(1) - elementGetter.apply(0)) / 2;
71+
double weightSoFar = 0;
72+
73+
for (int i = 0; i < length - 1; i++) {
74+
double right = (elementGetter.apply(i + 1) - elementGetter.apply(i)) / 2;
75+
if (x < elementGetter.apply(i) + right) {
76+
double value = (weightSoFar + AbstractTDigest.interpolate(x, elementGetter.apply(i) - left, elementGetter.apply(i) + right))
77+
/ length;
78+
return Math.max(value, 0.0);
5479
}
80+
weightSoFar += 1;
81+
left = right;
82+
}
83+
84+
// for the last element, assume right width is same as left
85+
int lastOffset = length - 1;
86+
double right = (elementGetter.apply(lastOffset) - elementGetter.apply(lastOffset - 1)) / 2;
87+
if (x < elementGetter.apply(lastOffset) + right) {
88+
return (weightSoFar + AbstractTDigest.interpolate(
89+
x,
90+
elementGetter.apply(lastOffset) - right,
91+
elementGetter.apply(lastOffset) + right
92+
)) / length;
5593
}
56-
return (length - 0.5 * n2) / length;
94+
return 1;
5795
}
5896

5997
public static double cdf(final double x, double[] data) {
Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
/*
2+
* Licensed to Elasticsearch B.V. under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch B.V. licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
package org.elasticsearch.tdigest;
21+
22+
import java.util.Collection;
23+
import java.util.List;
24+
25+
/**
26+
* Uses a {@link SortingDigest} implementation under the covers for small sample populations, then switches to {@link MergingDigest}.
27+
* The {@link SortingDigest} is perfectly accurate and the fastest implementation for up to millions of samples, at the cost of increased
28+
* memory footprint as it tracks all samples. Conversely, the {@link MergingDigest} pre-allocates its memory (tens of KBs) and provides
29+
* better performance for hundreds of millions of samples and more, while accuracy stays bounded to 0.1-1% for most cases.
30+
*
31+
* This hybrid approach provides the best of both worlds, i.e. speedy and accurate percentile calculations for small populations with
32+
* bounded memory allocation and acceptable speed and accuracy for larger ones.
33+
*/
34+
public class HybridDigest extends AbstractTDigest {
35+
36+
// See MergingDigest's compression param.
37+
private final double compression;
38+
39+
// Indicates the sample size over which it switches from SortingDigest to MergingDigest.
40+
private final long maxSortingSize;
41+
42+
// This is set to null when the implementation switches to MergingDigest.
43+
private SortingDigest sortingDigest = new SortingDigest();
44+
45+
// This gets initialized when the implementation switches to MergingDigest.
46+
private MergingDigest mergingDigest;
47+
48+
/**
49+
* Creates a hybrid digest that uses a {@link SortingDigest} for up to {@param maxSortingSize} samples,
50+
* then switches to a {@link MergingDigest}.
51+
*
52+
* @param compression The compression factor for the MergingDigest
53+
* @param maxSortingSize The sample size limit for switching from a {@link SortingDigest} to a {@link MergingDigest} implementation
54+
*/
55+
HybridDigest(double compression, long maxSortingSize) {
56+
this.compression = compression;
57+
this.maxSortingSize = maxSortingSize;
58+
}
59+
60+
/**
61+
* Similar to the constructor above. The limit for switching from a {@link SortingDigest} to a {@link MergingDigest} implementation
62+
* is calculated based on the passed compression factor.
63+
*
64+
* @param compression The compression factor for the MergingDigest
65+
*/
66+
HybridDigest(double compression) {
67+
// The default maxSortingSize is calculated so that the SortingDigest will have comparable size with the MergingDigest
68+
// at the point where implementations switch, e.g. for default compression 100 SortingDigest allocates ~16kB and MergingDigest
69+
// allocates ~15kB.
70+
this(compression, Math.round(compression) * 20);
71+
}
72+
73+
@Override
74+
public void add(double x, int w) {
75+
reserve(w);
76+
if (mergingDigest != null) {
77+
mergingDigest.add(x, w);
78+
} else {
79+
sortingDigest.add(x, w);
80+
}
81+
}
82+
83+
@Override
84+
public void reserve(long size) {
85+
if (mergingDigest != null) {
86+
mergingDigest.reserve(size);
87+
return;
88+
}
89+
// Check if we need to switch implementations.
90+
assert sortingDigest != null;
91+
if (sortingDigest.size() + size >= maxSortingSize) {
92+
mergingDigest = new MergingDigest(compression);
93+
for (double value : sortingDigest.values) {
94+
mergingDigest.add(value);
95+
}
96+
mergingDigest.reserve(size);
97+
// Release the allocated SortingDigest.
98+
sortingDigest = null;
99+
} else {
100+
sortingDigest.reserve(size);
101+
}
102+
}
103+
104+
@Override
105+
public void add(List<? extends TDigest> others) {
106+
if (mergingDigest != null) {
107+
mergingDigest.add(others);
108+
} else {
109+
sortingDigest.add(others);
110+
}
111+
}
112+
113+
@Override
114+
public void compress() {
115+
if (mergingDigest != null) {
116+
mergingDigest.compress();
117+
} else {
118+
sortingDigest.compress();
119+
}
120+
}
121+
122+
@Override
123+
public long size() {
124+
if (mergingDigest != null) {
125+
return mergingDigest.size();
126+
}
127+
return sortingDigest.size();
128+
}
129+
130+
@Override
131+
public double cdf(double x) {
132+
if (mergingDigest != null) {
133+
return mergingDigest.cdf(x);
134+
}
135+
return sortingDigest.cdf(x);
136+
}
137+
138+
@Override
139+
public double quantile(double q) {
140+
if (mergingDigest != null) {
141+
return mergingDigest.quantile(q);
142+
}
143+
return sortingDigest.quantile(q);
144+
}
145+
146+
@Override
147+
public Collection<Centroid> centroids() {
148+
if (mergingDigest != null) {
149+
return mergingDigest.centroids();
150+
}
151+
return sortingDigest.centroids();
152+
}
153+
154+
@Override
155+
public double compression() {
156+
if (mergingDigest != null) {
157+
return mergingDigest.compression();
158+
}
159+
return sortingDigest.compression();
160+
}
161+
162+
@Override
163+
public int centroidCount() {
164+
if (mergingDigest != null) {
165+
return mergingDigest.centroidCount();
166+
}
167+
return sortingDigest.centroidCount();
168+
}
169+
170+
@Override
171+
public double getMin() {
172+
if (mergingDigest != null) {
173+
return mergingDigest.getMin();
174+
}
175+
return sortingDigest.getMin();
176+
}
177+
178+
@Override
179+
public double getMax() {
180+
if (mergingDigest != null) {
181+
return mergingDigest.getMax();
182+
}
183+
return sortingDigest.getMax();
184+
}
185+
186+
@Override
187+
public int byteSize() {
188+
if (mergingDigest != null) {
189+
return mergingDigest.byteSize();
190+
}
191+
return sortingDigest.byteSize();
192+
}
193+
}

0 commit comments

Comments
 (0)