Skip to content

Commit eedc06d

Browse files
committed
Fix NPE when CumulativeSum agg encounters null/empty bucket (#29641)
If the cusum agg encounters a null value, it's because the value is missing (like the first value from a derivative agg), the path is not valid, or the bucket in the path was empty. Previously cusum would just explode on the null, but this changes it so we only increment the sum if the value is non-null and finite. This is safe because even if the cusum encounters all null or empty buckets, the cumulative sum is still zero (like how the sum agg returns zero even if all the docs were missing values) I went ahead and tweaked AggregatorTestCase to allow testing pipelines, so that I could delete the IT test and reimplement it as AggTests. Closes #27544
1 parent b093c14 commit eedc06d

File tree

5 files changed

+336
-172
lines changed

5 files changed

+336
-172
lines changed

docs/CHANGELOG.asciidoc

+3
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ option. ({pull}30140[#29658])
6464

6565
Do not ignore request analysis/similarity settings on index resize operations when the source index already contains such settings ({pull}30216[#30216])
6666

67+
Fix NPE when CumulativeSum agg encounters null value/empty bucket ({pull}29641[#29641])
6768

6869
//[float]
6970
//=== Regressions
@@ -151,6 +152,7 @@ Search::
151152
Settings::
152153
* Archive unknown or invalid settings on updates {pull}28888[#28888] (issue: {issue}28609[#28609])
153154

155+
154156
//[float]
155157
//=== Regressions
156158

@@ -639,6 +641,7 @@ Stats::
639641

640642
Term Vectors::
641643
* Fix term vectors generator with keyword and normalizer {pull}27608[#27608] (issue: {issue}27320[#27320])
644+
Fix NPE when CumulativeSum agg encounters null value/empty bucket ({pull}29641[#29641])
642645

643646
//[float]
644647
//=== Regressions

server/src/main/java/org/elasticsearch/search/aggregations/pipeline/cumulativesum/CumulativeSumPipelineAggregator.java

+11-5
Original file line numberDiff line numberDiff line change
@@ -79,11 +79,17 @@ public InternalAggregation reduce(InternalAggregation aggregation, ReduceContext
7979
double sum = 0;
8080
for (InternalMultiBucketAggregation.InternalBucket bucket : buckets) {
8181
Double thisBucketValue = resolveBucketValue(histo, bucket, bucketsPaths()[0], GapPolicy.INSERT_ZEROS);
82-
sum += thisBucketValue;
83-
List<InternalAggregation> aggs = StreamSupport.stream(bucket.getAggregations().spliterator(), false).map((p) -> {
84-
return (InternalAggregation) p;
85-
}).collect(Collectors.toList());
86-
aggs.add(new InternalSimpleValue(name(), sum, formatter, new ArrayList<PipelineAggregator>(), metaData()));
82+
83+
// Only increment the sum if it's a finite value, otherwise "increment by zero" is correct
84+
if (thisBucketValue != null && thisBucketValue.isInfinite() == false && thisBucketValue.isNaN() == false) {
85+
sum += thisBucketValue;
86+
}
87+
88+
List<InternalAggregation> aggs = StreamSupport
89+
.stream(bucket.getAggregations().spliterator(), false)
90+
.map((p) -> (InternalAggregation) p)
91+
.collect(Collectors.toList());
92+
aggs.add(new InternalSimpleValue(name(), sum, formatter, new ArrayList<>(), metaData()));
8793
Bucket newBucket = factory.createBucket(factory.getKey(bucket), bucket.getDocCount(), new InternalAggregations(aggs));
8894
newBuckets.add(newBucket);
8995
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,316 @@
1+
/*
2+
* Licensed to Elasticsearch 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 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.search.aggregations.pipeline;
21+
22+
import org.apache.lucene.document.Document;
23+
import org.apache.lucene.document.NumericDocValuesField;
24+
import org.apache.lucene.document.SortedNumericDocValuesField;
25+
import org.apache.lucene.index.DirectoryReader;
26+
import org.apache.lucene.index.IndexReader;
27+
import org.apache.lucene.index.RandomIndexWriter;
28+
import org.apache.lucene.search.IndexSearcher;
29+
import org.apache.lucene.search.MatchAllDocsQuery;
30+
import org.apache.lucene.search.MatchNoDocsQuery;
31+
import org.apache.lucene.search.Query;
32+
import org.apache.lucene.store.Directory;
33+
import org.elasticsearch.common.CheckedConsumer;
34+
import org.elasticsearch.index.mapper.DateFieldMapper;
35+
import org.elasticsearch.index.mapper.MappedFieldType;
36+
import org.elasticsearch.index.mapper.NumberFieldMapper;
37+
import org.elasticsearch.search.aggregations.AggregationBuilder;
38+
import org.elasticsearch.search.aggregations.AggregatorTestCase;
39+
import org.elasticsearch.search.aggregations.InternalAggregation;
40+
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
41+
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
42+
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
43+
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
44+
import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregationBuilder;
45+
import org.elasticsearch.search.aggregations.metrics.avg.InternalAvg;
46+
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
47+
import org.elasticsearch.search.aggregations.metrics.sum.SumAggregationBuilder;
48+
import org.elasticsearch.search.aggregations.pipeline.cumulativesum.CumulativeSumPipelineAggregationBuilder;
49+
import org.elasticsearch.search.aggregations.pipeline.derivative.DerivativePipelineAggregationBuilder;
50+
51+
import java.io.IOException;
52+
import java.util.Arrays;
53+
import java.util.List;
54+
import java.util.function.Consumer;
55+
56+
import static org.hamcrest.Matchers.equalTo;
57+
import static org.hamcrest.core.IsNull.notNullValue;
58+
59+
public class CumulativeSumAggregatorTests extends AggregatorTestCase {
60+
61+
private static final String HISTO_FIELD = "histo";
62+
private static final String VALUE_FIELD = "value_field";
63+
64+
private static final List<String> datasetTimes = Arrays.asList(
65+
"2017-01-01T01:07:45",
66+
"2017-01-02T03:43:34",
67+
"2017-01-03T04:11:00",
68+
"2017-01-04T05:11:31",
69+
"2017-01-05T08:24:05",
70+
"2017-01-06T13:09:32",
71+
"2017-01-07T13:47:43",
72+
"2017-01-08T16:14:34",
73+
"2017-01-09T17:09:50",
74+
"2017-01-10T22:55:46");
75+
76+
private static final List<Integer> datasetValues = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
77+
78+
public void testSimple() throws IOException {
79+
Query query = new MatchAllDocsQuery();
80+
81+
DateHistogramAggregationBuilder aggBuilder = new DateHistogramAggregationBuilder("histo");
82+
aggBuilder.dateHistogramInterval(DateHistogramInterval.DAY).field(HISTO_FIELD);
83+
aggBuilder.subAggregation(new AvgAggregationBuilder("the_avg").field(VALUE_FIELD));
84+
aggBuilder.subAggregation(new CumulativeSumPipelineAggregationBuilder("cusum", "the_avg"));
85+
86+
executeTestCase(query, aggBuilder, histogram -> {
87+
assertEquals(10, ((Histogram)histogram).getBuckets().size());
88+
List<? extends Histogram.Bucket> buckets = ((Histogram)histogram).getBuckets();
89+
double sum = 0.0;
90+
for (Histogram.Bucket bucket : buckets) {
91+
sum += ((InternalAvg) (bucket.getAggregations().get("the_avg"))).value();
92+
assertThat(((InternalSimpleValue) (bucket.getAggregations().get("cusum"))).value(), equalTo(sum));
93+
}
94+
});
95+
}
96+
97+
/**
98+
* First value from a derivative is null, so this makes sure the cusum can handle that
99+
*/
100+
public void testDerivative() throws IOException {
101+
Query query = new MatchAllDocsQuery();
102+
103+
DateHistogramAggregationBuilder aggBuilder = new DateHistogramAggregationBuilder("histo");
104+
aggBuilder.dateHistogramInterval(DateHistogramInterval.DAY).field(HISTO_FIELD);
105+
aggBuilder.subAggregation(new AvgAggregationBuilder("the_avg").field(VALUE_FIELD));
106+
aggBuilder.subAggregation(new DerivativePipelineAggregationBuilder("the_deriv", "the_avg"));
107+
aggBuilder.subAggregation(new CumulativeSumPipelineAggregationBuilder("cusum", "the_deriv"));
108+
109+
executeTestCase(query, aggBuilder, histogram -> {
110+
assertEquals(10, ((Histogram)histogram).getBuckets().size());
111+
List<? extends Histogram.Bucket> buckets = ((Histogram)histogram).getBuckets();
112+
double sum = 0.0;
113+
for (int i = 0; i < buckets.size(); i++) {
114+
if (i == 0) {
115+
assertThat(((InternalSimpleValue)(buckets.get(i).getAggregations().get("cusum"))).value(), equalTo(0.0));
116+
} else {
117+
sum += 1.0;
118+
assertThat(((InternalSimpleValue)(buckets.get(i).getAggregations().get("cusum"))).value(), equalTo(sum));
119+
}
120+
}
121+
});
122+
}
123+
124+
public void testDocCount() throws IOException {
125+
Query query = new MatchAllDocsQuery();
126+
127+
int numDocs = randomIntBetween(6, 20);
128+
int interval = randomIntBetween(2, 5);
129+
130+
int minRandomValue = 0;
131+
int maxRandomValue = 20;
132+
133+
int numValueBuckets = ((maxRandomValue - minRandomValue) / interval) + 1;
134+
long[] valueCounts = new long[numValueBuckets];
135+
136+
HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("histo")
137+
.field(VALUE_FIELD)
138+
.interval(interval)
139+
.extendedBounds(minRandomValue, maxRandomValue);
140+
aggBuilder.subAggregation(new CumulativeSumPipelineAggregationBuilder("cusum", "_count"));
141+
142+
executeTestCase(query, aggBuilder, histogram -> {
143+
List<? extends Histogram.Bucket> buckets = ((Histogram)histogram).getBuckets();
144+
145+
assertThat(buckets.size(), equalTo(numValueBuckets));
146+
147+
double sum = 0;
148+
for (int i = 0; i < numValueBuckets; ++i) {
149+
Histogram.Bucket bucket = buckets.get(i);
150+
assertThat(bucket, notNullValue());
151+
assertThat(((Number) bucket.getKey()).longValue(), equalTo((long) i * interval));
152+
assertThat(bucket.getDocCount(), equalTo(valueCounts[i]));
153+
sum += bucket.getDocCount();
154+
InternalSimpleValue cumulativeSumValue = bucket.getAggregations().get("cusum");
155+
assertThat(cumulativeSumValue, notNullValue());
156+
assertThat(cumulativeSumValue.getName(), equalTo("cusum"));
157+
assertThat(cumulativeSumValue.value(), equalTo(sum));
158+
}
159+
}, indexWriter -> {
160+
Document document = new Document();
161+
162+
for (int i = 0; i < numDocs; i++) {
163+
int fieldValue = randomIntBetween(minRandomValue, maxRandomValue);
164+
document.add(new NumericDocValuesField(VALUE_FIELD, fieldValue));
165+
final int bucket = (fieldValue / interval);
166+
valueCounts[bucket]++;
167+
168+
indexWriter.addDocument(document);
169+
document.clear();
170+
}
171+
});
172+
}
173+
174+
public void testMetric() throws IOException {
175+
Query query = new MatchAllDocsQuery();
176+
177+
int numDocs = randomIntBetween(6, 20);
178+
int interval = randomIntBetween(2, 5);
179+
180+
int minRandomValue = 0;
181+
int maxRandomValue = 20;
182+
183+
int numValueBuckets = ((maxRandomValue - minRandomValue) / interval) + 1;
184+
long[] valueCounts = new long[numValueBuckets];
185+
186+
HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("histo")
187+
.field(VALUE_FIELD)
188+
.interval(interval)
189+
.extendedBounds(minRandomValue, maxRandomValue);
190+
aggBuilder.subAggregation(new SumAggregationBuilder("sum").field(VALUE_FIELD));
191+
aggBuilder.subAggregation(new CumulativeSumPipelineAggregationBuilder("cusum", "sum"));
192+
193+
executeTestCase(query, aggBuilder, histogram -> {
194+
List<? extends Histogram.Bucket> buckets = ((Histogram)histogram).getBuckets();
195+
196+
assertThat(buckets.size(), equalTo(numValueBuckets));
197+
198+
double bucketSum = 0;
199+
for (int i = 0; i < numValueBuckets; ++i) {
200+
Histogram.Bucket bucket = buckets.get(i);
201+
assertThat(bucket, notNullValue());
202+
assertThat(((Number) bucket.getKey()).longValue(), equalTo((long) i * interval));
203+
Sum sum = bucket.getAggregations().get("sum");
204+
assertThat(sum, notNullValue());
205+
bucketSum += sum.value();
206+
207+
InternalSimpleValue sumBucketValue = bucket.getAggregations().get("cusum");
208+
assertThat(sumBucketValue, notNullValue());
209+
assertThat(sumBucketValue.getName(), equalTo("cusum"));
210+
assertThat(sumBucketValue.value(), equalTo(bucketSum));
211+
}
212+
}, indexWriter -> {
213+
Document document = new Document();
214+
215+
for (int i = 0; i < numDocs; i++) {
216+
int fieldValue = randomIntBetween(minRandomValue, maxRandomValue);
217+
document.add(new NumericDocValuesField(VALUE_FIELD, fieldValue));
218+
final int bucket = (fieldValue / interval);
219+
valueCounts[bucket]++;
220+
221+
indexWriter.addDocument(document);
222+
document.clear();
223+
}
224+
});
225+
}
226+
227+
public void testNoBuckets() throws IOException {
228+
int numDocs = randomIntBetween(6, 20);
229+
int interval = randomIntBetween(2, 5);
230+
231+
int minRandomValue = 0;
232+
int maxRandomValue = 20;
233+
234+
int numValueBuckets = ((maxRandomValue - minRandomValue) / interval) + 1;
235+
long[] valueCounts = new long[numValueBuckets];
236+
237+
Query query = new MatchNoDocsQuery();
238+
239+
HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("histo")
240+
.field(VALUE_FIELD)
241+
.interval(interval);
242+
aggBuilder.subAggregation(new SumAggregationBuilder("sum").field(VALUE_FIELD));
243+
aggBuilder.subAggregation(new CumulativeSumPipelineAggregationBuilder("cusum", "sum"));
244+
245+
executeTestCase(query, aggBuilder, histogram -> {
246+
List<? extends Histogram.Bucket> buckets = ((Histogram)histogram).getBuckets();
247+
248+
assertThat(buckets.size(), equalTo(0));
249+
250+
}, indexWriter -> {
251+
Document document = new Document();
252+
253+
for (int i = 0; i < numDocs; i++) {
254+
int fieldValue = randomIntBetween(minRandomValue, maxRandomValue);
255+
document.add(new NumericDocValuesField(VALUE_FIELD, fieldValue));
256+
final int bucket = (fieldValue / interval);
257+
valueCounts[bucket]++;
258+
259+
indexWriter.addDocument(document);
260+
document.clear();
261+
}
262+
});
263+
}
264+
265+
@SuppressWarnings("unchecked")
266+
private void executeTestCase(Query query, AggregationBuilder aggBuilder, Consumer<InternalAggregation> verify) throws IOException {
267+
executeTestCase(query, aggBuilder, verify, indexWriter -> {
268+
Document document = new Document();
269+
int counter = 0;
270+
for (String date : datasetTimes) {
271+
if (frequently()) {
272+
indexWriter.commit();
273+
}
274+
275+
long instant = asLong(date);
276+
document.add(new SortedNumericDocValuesField(HISTO_FIELD, instant));
277+
document.add(new NumericDocValuesField(VALUE_FIELD, datasetValues.get(counter)));
278+
indexWriter.addDocument(document);
279+
document.clear();
280+
counter += 1;
281+
}
282+
});
283+
}
284+
285+
@SuppressWarnings("unchecked")
286+
private void executeTestCase(Query query, AggregationBuilder aggBuilder, Consumer<InternalAggregation> verify,
287+
CheckedConsumer<RandomIndexWriter, IOException> setup) throws IOException {
288+
289+
try (Directory directory = newDirectory()) {
290+
try (RandomIndexWriter indexWriter = new RandomIndexWriter(random(), directory)) {
291+
setup.accept(indexWriter);
292+
}
293+
294+
try (IndexReader indexReader = DirectoryReader.open(directory)) {
295+
IndexSearcher indexSearcher = newSearcher(indexReader, true, true);
296+
297+
DateFieldMapper.Builder builder = new DateFieldMapper.Builder("_name");
298+
DateFieldMapper.DateFieldType fieldType = builder.fieldType();
299+
fieldType.setHasDocValues(true);
300+
fieldType.setName(HISTO_FIELD);
301+
302+
MappedFieldType valueFieldType = new NumberFieldMapper.NumberFieldType(NumberFieldMapper.NumberType.LONG);
303+
valueFieldType.setHasDocValues(true);
304+
valueFieldType.setName("value_field");
305+
306+
InternalAggregation histogram;
307+
histogram = searchAndReduce(indexSearcher, query, aggBuilder, new MappedFieldType[]{fieldType, valueFieldType});
308+
verify.accept(histogram);
309+
}
310+
}
311+
}
312+
313+
private static long asLong(String dateTime) {
314+
return DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.parser().parseDateTime(dateTime).getMillis();
315+
}
316+
}

0 commit comments

Comments
 (0)