This repository has been archived by the owner on Mar 27, 2021. It is now read-only.
/
AbstractClusterQueryIT.java
693 lines (561 loc) · 26.9 KB
/
AbstractClusterQueryIT.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
package com.spotify.heroic;
import static com.spotify.heroic.test.Matchers.containsChild;
import static com.spotify.heroic.test.Matchers.hasIdentifier;
import static com.spotify.heroic.test.Matchers.identifierContains;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.spotify.heroic.aggregation.ComputeDistributionStat;
import com.spotify.heroic.common.Feature;
import com.spotify.heroic.common.FeatureSet;
import com.spotify.heroic.common.Series;
import com.spotify.heroic.dagger.CoreComponent;
import com.spotify.heroic.ingestion.Ingestion;
import com.spotify.heroic.ingestion.IngestionComponent;
import com.spotify.heroic.ingestion.IngestionManager;
import com.spotify.heroic.ingestion.Request;
import com.spotify.heroic.metric.FullQuery;
import com.spotify.heroic.metric.MetricCollection;
import com.spotify.heroic.metric.MetricType;
import com.spotify.heroic.metric.Point;
import com.spotify.heroic.metric.QueryError;
import com.spotify.heroic.metric.QueryResult;
import com.spotify.heroic.metric.RequestError;
import com.spotify.heroic.metric.ResultLimit;
import com.spotify.heroic.metric.ResultLimits;
import com.spotify.heroic.metric.ShardedResultGroup;
import com.spotify.heroic.querylogging.QueryContext;
import com.spotify.heroic.querylogging.QueryLogger;
import com.spotify.heroic.test.Data;
import eu.toolchain.async.AsyncFuture;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public abstract class AbstractClusterQueryIT extends AbstractLocalClusterIT {
private final static int RECORD_COUNT = 100_000; // Number of datapoint recorded in each tdigest
private static double EXPECTED_ERROR_RATE = 0.01d;
private final Series s1 = new Series("key1", ImmutableSortedMap.of("shared", "a", "diff", "a"),
ImmutableSortedMap.of("resource", "a"));
private final Series s2 = new Series("key1", ImmutableSortedMap.of("shared", "a", "diff", "b"),
ImmutableSortedMap.of("resource", "b"));
private final Series s3 = new Series("key1", ImmutableSortedMap.of("shared", "a", "diff", "c"),
ImmutableSortedMap.of("resource", "c"));
private final RandomData randDataset1 =
HeroicDistributionGenerator.generateRandomDataset(RECORD_COUNT);
private final RandomData randDataset2 =
HeroicDistributionGenerator.generateRandomDataset(RECORD_COUNT);
private final RandomData randDataset3 =
HeroicDistributionGenerator.generateRandomDataset(RECORD_COUNT);
protected boolean cardinalitySupport = true;
/* the number of queries run */
private int queryCount = 0;
private QueryManager query;
private QueryContext queryContext;
protected void setupSupport() {
}
@Before
public final void setupAbstract() {
setupSupport();
queryContext = QueryContext.empty();
query = instances.get(0).inject(CoreComponent::queryManager);
}
@After
public final void verifyLoggers() {
final QueryLogger coreQueryManagerLogger = getQueryLogger("CoreQueryManager").orElseThrow(
() -> new AssertionError("Should have logger for CoreQueryManager"));
final QueryLogger localMetricManagerLogger =
getQueryLogger("LocalMetricManager").orElseThrow(
() -> new AssertionError("Should have logger for LocalMetricManager"));
/* number of expected log-calls is related to the number of queries performed during the
* test */
final int apiNodeCount = queryCount;
final int dataNodeCount = queryCount * 2;
verify(coreQueryManagerLogger, times(apiNodeCount)).logQuery(any(QueryContext.class),
any(Query.class));
verify(coreQueryManagerLogger, times(apiNodeCount)).logOutgoingRequestToShards(
any(QueryContext.class), any(FullQuery.Request.class));
verify(localMetricManagerLogger, times(dataNodeCount)).logIncomingRequestAtNode(
any(QueryContext.class), any(FullQuery.Request.class));
verify(localMetricManagerLogger, times(dataNodeCount)).logOutgoingResponseAtNode(
any(QueryContext.class), any(FullQuery.class));
verify(coreQueryManagerLogger, times(dataNodeCount)).logIncomingResponseFromShard(
any(QueryContext.class), any(FullQuery.class));
verifyNoMoreInteractions(coreQueryManagerLogger, localMetricManagerLogger);
}
@Override
protected AsyncFuture<Void> prepareEnvironment() {
final List<IngestionManager> ingestion = instances
.stream()
.map(i -> i.inject(IngestionComponent::ingestionManager))
.collect(Collectors.toList());
final List<AsyncFuture<Ingestion>> writes = new ArrayList<>();
final IngestionManager m1 = ingestion.get(0);
final IngestionManager m2 = ingestion.get(1);
writes.add(m1
.useDefaultGroup()
.write(new Request(s1, Data.points().p(10, 1D).p(30, 2D).build())));
writes.add(m2
.useDefaultGroup()
.write(new Request(s2, Data.points().p(10, 1D).p(20, 4D).build())));
writes.add(m1
.useDefaultGroup()
.write(new Request(s2, Data.distributionPoints()
.p(10, randDataset1.getRandomData())
.p(30, randDataset3.getRandomData())
.build())));
writes.add(m2
.useDefaultGroup()
.write(new Request(s1, Data.distributionPoints()
.p(10, randDataset1.getRandomData())
.p(20, randDataset2.getRandomData())
.build())));
return async.collectAndDiscard(writes);
}
public QueryResult query(final String queryString) throws Exception {
return query(query.newQueryFromString(queryString), builder -> {
},
MetricType.POINT,
true);
}
public QueryResult query(final String queryString,
final Consumer<QueryBuilder> modifier)
throws Exception {
return query(query.newQueryFromString(queryString),
modifier,
MetricType.POINT,
true);
}
public QueryResult query(final QueryBuilder builder,
final Consumer<QueryBuilder> modifier,
final MetricType source,
final boolean isDistributed)
throws Exception {
queryCount += 1;
builder
.source(Optional.of(source))
.rangeIfAbsent(Optional.of(new QueryDateRange.Absolute(0, 40)));
if (isDistributed) {
builder
.features(Optional.of(FeatureSet.of(Feature.DISTRIBUTED_AGGREGATIONS)));
}
modifier.accept(builder);
return query.useDefaultGroup().query(builder.build(), queryContext).get();
}
/**
* Aggregation that's not distributed usually returns one group.
* But in case of tdigest, the number of group return is equal
* to the number of stat that was computed.
*
* @throws Exception
*/
@Test
public void testSimpleTdigestAggregation() throws Exception {
final QueryResult result =
query(query.newQueryFromString("tdigest(10ms)"),
builder -> {
},
MetricType.DISTRIBUTION_POINTS,
true);
final int numberSeries = 2; // s1 and s2
final int datapointCount = 3;
final long expectedCadence = 10L;
assertEquals(3, result.getGroups().size());
for (ShardedResultGroup shardedResultGroup : result.getGroups()) {
assertEquals(numberSeries, shardedResultGroup.getSeries().size());
assertEquals(datapointCount, shardedResultGroup.getMetrics().size());
assertEquals(0, shardedResultGroup.getShard().size());
assertEquals(0, shardedResultGroup.getKey().size());
}
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(expectedCadence, expectedCadence, expectedCadence), cadences);
Map<Long, Double> mapRes = AbstractClusterQueryIT.extractResult(result,
new ComputeDistributionStat.Percentile("P99", 0.99));
// ensure that result is within the error margin
validateStatAccuracy(mapRes);
}
@Test
public void testDistributedTdigestAggregation() throws Exception {
final QueryResult result =
query(query.newQueryFromString("tdigest(10ms) by diff"),
builder -> {
},
MetricType.DISTRIBUTION_POINTS,
true);
final int expectedGroupCount = 6;
final int numberSeries = 1;
final int datapointCount = 2;
final long expectedCadence = 10L;
assertEquals(expectedGroupCount, result.getGroups().size());
for (ShardedResultGroup shardedResultGroup : result.getGroups()) {
assertEquals(numberSeries, shardedResultGroup.getSeries().size());
assertEquals(datapointCount, shardedResultGroup.getMetrics().size());
assertEquals(0, shardedResultGroup.getShard().size());
assertEquals(1, shardedResultGroup.getKey().size());
}
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(expectedCadence, expectedCadence,
expectedCadence, expectedCadence, expectedCadence, expectedCadence), cadences);
Map<Long, Double> mapRes = AbstractClusterQueryIT.extractResult(result,
new ComputeDistributionStat.Percentile("P99", 0.99));
validateStatAccuracy(mapRes);
}
@Test
public void testDistributionWithNoAggregation() throws Exception {
final int expectedGroupCount = 2; // m1 and m2
final QueryResult result =
query(query.newQueryFromString("empty"),
builder -> {
},
MetricType.DISTRIBUTION_POINTS,
false);
assertEquals(expectedGroupCount, result.getGroups().size());
//Validate record count
for (ShardedResultGroup group : result.getGroups()) {
List<Point> metrics = group.getMetrics().getDataAs(Point.class);
metrics.forEach(p -> assertEquals(RECORD_COUNT, p.getValue(), 0));
}
}
@Test
public void testbasicWithNoDistribution() throws Exception {
final int expectedGroupCount = 2; // m1 and m2
final QueryResult result =
query(query.newQueryFromString("empty"),
builder -> {
},
MetricType.POINT,
false);
assertEquals(expectedGroupCount, result.getGroups().size());
}
@Test
public void basicQueryTest() throws Exception {
final QueryResult result = query("sum(10ms)");
// check the number of ShardedResultGroup
assertEquals(1, result.getGroups().size());
assertEquals(2, result.getGroups().get(0).getSeries().size());
assertEquals(3, result.getGroups().get(0).getMetrics().size());
assertEquals(0, result.getGroups().get(0).getShard().size());
assertEquals(0, result.getGroups().get(0).getKey().size());
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(10L), cadences);
assertEquals(ImmutableSet.of(Data.points().p(10, 2D).p(20, 4D).p(30, 2D).build()), m);
}
@Test
public void distributedQueryTest() throws Exception {
final QueryResult result = query("sum(10ms) by shared");
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(10L), cadences);
assertEquals(ImmutableSet.of(Data.points().p(10, 2D).p(20, 4D).p(30, 2D).build()), m);
}
@Test
public void distributedQueryTraceTest() throws Exception {
final QueryResult result = query("sum(10ms) by shared");
// Verify that the top level QueryTrace is for CoreQueryManager
assertThat(result.getTrace(), hasIdentifier(equalTo(CoreQueryManager.QUERY)));
// Verify that second level is of type QUERY_SHARD
assertThat(result.getTrace(), containsChild(
hasIdentifier(identifierContains(CoreQueryManager.QUERY_SHARD.toString()))));
/* Verify that the third level (under QUERY_SHARD) contains at least one entry for the
* local node and at least one for the remote node */
assertThat(result.getTrace(), containsChild(
allOf(hasIdentifier(identifierContains(CoreQueryManager.QUERY_SHARD.toString())),
containsChild(hasIdentifier(identifierContains("[local]"))))));
assertThat(result.getTrace(), containsChild(
allOf(hasIdentifier(identifierContains(CoreQueryManager.QUERY_SHARD.toString())),
containsChild(hasIdentifier(not(identifierContains("[local]")))))));
}
@Test
public void distributedDifferentQueryTest() throws Exception {
final QueryResult result = query("sum(10ms) by diff");
// check the number of ShardedResultGroup
assertEquals(2, result.getGroups().size());
assertEquals(1, result.getGroups().get(0).getSeries().size());
assertEquals(2, result.getGroups().get(0).getMetrics().size());
assertEquals(0, result.getGroups().get(0).getShard().size());
assertEquals(1, result.getGroups().get(0).getKey().size());
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(10L, 10L), cadences);
assertEquals(ImmutableSet.of(Data.points().p(10, 1D).p(30, 2D).build(),
Data.points().p(10, 1D).p(20, 4D).build()), m);
}
@Test
public void distributedFilterQueryTest() throws Exception {
final QueryResult result = query("average(10ms) by * | topk(2) | bottomk(1) | sum(10ms)");
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(10L), cadences);
assertEquals(ImmutableSet.of(Data.points().p(10, 1D).p(20, 4D).build()), m);
}
@Test
public void filterQueryTest() throws Exception {
final QueryResult result =
query("average(10ms) by * | topk(2) | bottomk(1) | sum(10ms)", builder -> {
builder.features(Optional.empty());
});
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(10L, 10L), cadences);
assertEquals(ImmutableSet.of(Data.points().p(10, 1D).p(20, 4D).build(),
Data.points().p(10, 1D).p(30, 2D).build()), m);
}
@Test
public void pointsAboveTest() throws Exception {
final QueryResult result = query("pointsabove(2) by *", builder -> {
builder.features(Optional.empty());
});
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(0L), cadences);
assertEquals(ImmutableSet.of(Data.points().p(20, 4D).build()), m);
}
@Test
public void pointsBelowTest() throws Exception {
final QueryResult result = query("pointsbelow(3) by *", builder -> {
builder.features(Optional.empty());
});
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(0L, 0L), cadences);
assertEquals(
ImmutableSet.of(Data.points().p(10, 1D).build(),
Data.points().p(10, 1D).p(30, 2.0D).build()), m);
}
@Test
public void deltaQueryTest() throws Exception {
final QueryResult result = query("delta", builder -> {
builder.features(Optional.empty());
});
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(-1L, -1L), cadences);
assertEquals(
ImmutableSet.of(Data.points().p(30, 1D).build(), Data.points().p(20, 3D).build()),
m);
}
@Test
public void distributedDeltaQueryTest() throws Exception {
final QueryResult result = query("max | delta");
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(1L), cadences);
assertEquals(ImmutableSet.of(Data.points().p(20, 3D).p(30, -2D).build()), m);
}
@Test
public void deltaPerSecondQueryTest() throws Exception {
final QueryResult result = query("deltaPerSecond", builder -> {
builder.features(Optional.empty());
});
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(-1L, -1L), cadences);
assertEquals(ImmutableSet
.of(Data.points().p(30, 50D).build(), Data.points().p(20, 300D).build()), m);
}
@Test
public void distributedDeltaPerSecondQueryTest() throws Exception {
final QueryResult result = query("max | deltaPerSecond");
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(1L), cadences);
assertEquals(ImmutableSet.of(Data.points().p(20, 300D).p(30, -200D).build()), m);
}
@Test
public void distributedDeltaPerSecondWithNoNegativeQueryTest() throws Exception {
final QueryResult result = query("max | deltaPerSecond | notNegative ");
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(1L), cadences);
assertEquals(ImmutableSet.of(Data.points().p(20, 300D).build()), m);
}
@Test
public void filterLastQueryTest() throws Exception {
final QueryResult result = query("average(10ms) by * | topk(2) | bottomk(1)");
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(10L), cadences);
assertEquals(ImmutableSet.of(Data.points().p(10, 1D).p(20, 4D).build()), m);
}
@Test
public void cardinalityTest() throws Exception {
assumeTrue(cardinalitySupport);
final QueryResult result = query("cardinality(10ms)");
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(10L), cadences);
assertEquals(ImmutableSet.of(Data.points().p(10, 1D).p(20, 1D).p(30, 1D).p(40, 0D).build()),
m);
}
@Test
public void cardinalityWithKeyTest() throws Exception {
assumeTrue(cardinalitySupport);
// TODO: support native booleans in expressions
final QueryResult result = query("cardinality(10ms, method=hllp(includeKey=\"true\"))");
final Set<MetricCollection> m = getResults(result);
final List<Long> cadences = getCadences(result);
assertEquals(ImmutableList.of(10L), cadences);
assertEquals(ImmutableSet.of(Data.points().p(10, 2D).p(20, 1D).p(30, 1D).p(40, 0D).build()),
m);
}
@Test
public void dataLimit() throws Exception {
testDataLimit(MetricType.DISTRIBUTION_POINTS);
testDataLimit(MetricType.POINT);
}
@Test
public void testGroupLimit() throws Exception {
final QueryResult result = query("*", builder -> {
builder.options(Optional.of(QueryOptions.builder().groupLimit(1L).build()));
});
assertEquals(0, result.getErrors().size());
assertEquals(ResultLimits.of(ResultLimit.GROUP), result.getLimits());
assertEquals(1, result.getGroups().size());
}
@Test
public void seriesLimitFailure() throws Exception {
testSeriesLimitFailure(MetricType.DISTRIBUTION_POINTS);
testSeriesLimitFailure(MetricType.POINT);
}
@Test
public void groupLimitFailure() throws Exception {
testGroupLimitFailure(MetricType.DISTRIBUTION_POINTS);
testGroupLimitFailure(MetricType.POINT);
}
private void testDataLimit(final MetricType metricType) throws Exception {
final QueryResult result = query("*", builder -> {
builder.options(Optional.of(QueryOptions.builder().dataLimit(1L).build()));
});
// quota limits are always errors
assertEquals(2, result.getErrors().size());
for (final RequestError e : result.getErrors()) {
assertTrue((e instanceof QueryError));
final QueryError q = (QueryError) e;
assertThat(q.getError(),
containsString("Some fetches failed (1) or were cancelled (0)"));
}
assertEquals(ResultLimits.of(ResultLimit.QUOTA), result.getLimits());
}
private void testSeriesLimitFailure(final MetricType metricType) throws Exception {
final QueryResult result = query("*", builder -> {
builder.options(
Optional.of(QueryOptions.builder().seriesLimit(0L).failOnLimits(true).build()));
});
assertEquals(2, result.getErrors().size());
for (final RequestError e : result.getErrors()) {
assertTrue((e instanceof QueryError));
final QueryError q = (QueryError) e;
assertThat(q.getError(), containsString(
"The number of series requested is more than the allowed limit of [0]"));
}
assertEquals(ResultLimits.of(ResultLimit.SERIES), result.getLimits());
}
private void testGroupLimitFailure(MetricType metricType) throws Exception {
final QueryResult result = query("*", builder -> {
builder.options(
Optional.of(QueryOptions.builder().groupLimit(0L).failOnLimits(true).build()));
});
assertEquals(2, result.getErrors().size());
for (final RequestError e : result.getErrors()) {
assertTrue((e instanceof QueryError));
final QueryError q = (QueryError) e;
assertThat(q.getError(), containsString(
"The number of result groups is more than the allowed limit of [0]"));
}
assertEquals(ResultLimits.of(ResultLimit.GROUP), result.getLimits());
assertEquals(0, result.getGroups().size());
}
private void testAggregationLimit(final MetricType metricType, final String query)
throws Exception {
final QueryResult result = query(query, builder -> {
builder.options(Optional.of(QueryOptions.builder().aggregationLimit(1L).build()));
});
// quota limits are always errors
assertEquals(2, result.getErrors().size());
for (final RequestError e : result.getErrors()) {
assertTrue((e instanceof QueryError));
final QueryError q = (QueryError) e;
assertThat(q.getError(),
containsString("Some fetches failed (1) or were cancelled (0)"));
}
assertEquals(ResultLimits.of(ResultLimit.AGGREGATION), result.getLimits());
}
private static Set<MetricCollection> getResults(final QueryResult result) {
return result
.getGroups()
.stream()
.map(ShardedResultGroup::getMetrics)
.collect(Collectors.toSet());
}
// Percentile name.
private static Map<Long, Double> extractResult(final QueryResult res,
final ComputeDistributionStat.Percentile percentile) {
final Map<Long, Double> resMap = new HashMap<>();
List<ShardedResultGroup> shardedResultGroups = res.getGroups();
for (ShardedResultGroup shardedGrpRes : shardedResultGroups) {
Set<String> pTags = new HashSet<>();
shardedGrpRes.getSeries().forEach(s -> s.getTags().entrySet().stream()
.filter(t -> t.getKey().contentEquals("tdigeststat"))
.forEach(ss -> pTags.add(ss.getValue())));
assertEquals(1, pTags.size()); // Each group represents one stat
if (!pTags.contains(percentile.getName())) {
continue;
}
MetricCollection metricCollection = shardedGrpRes.getMetrics();
for (Point p : metricCollection.getDataAs(Point.class)) {
resMap.put(p.getTimestamp(), p.getValue());
}
}
return resMap;
}
private void validateStatAccuracy(final Map<Long, Double> resMap) {
double expected = randDataset1.getDataStat().get(99);
double actual = resMap.get(10L);
assertTrue(errorRate(expected, actual) <= EXPECTED_ERROR_RATE);
expected = randDataset2.getDataStat().get(99);
actual = resMap.get(20L);
assertTrue(errorRate(expected, actual) <= EXPECTED_ERROR_RATE);
expected = randDataset3.getDataStat().get(99);
actual = resMap.get(30L);
assertTrue(errorRate(expected, actual) <= EXPECTED_ERROR_RATE);
}
private static double errorRate(final double num1, final double num2) {
BigDecimal expected = BigDecimal.valueOf(num1);
BigDecimal actual = BigDecimal.valueOf(num2);
return expected.add(actual.negate())
.divide(expected, RoundingMode.CEILING).doubleValue();
}
private static List<Long> getCadences(final QueryResult result) {
final List<Long> cadences = result
.getGroups()
.stream()
.map(ShardedResultGroup::getCadence)
.collect(Collectors.toList());
Collections.sort(cadences);
return cadences;
}
}