feat(cloudwatch): take rates and resets of native histograms in PromQL (#10018)

rate, increase and delta of a histogram's range follow Prometheus
v3.16's histogramRate: the last histogram at the range's coarsest
schema less the first, each histogram before a counter reset added
back for a counter (the first taken as empty when the second follows a
reset), then extrapolated with the float path's factor, the count
standing in for the value. A counter reset is detected as
FloatHistogram.DetectReset detects one: a fall in the count, the zero
bucket or any bucket at the newer schema above the zero threshold, a
finer schema or a smaller zero threshold.

irate and idelta take the last two samples of either kind, resets and
changes count floats and histograms in time order, and a range of both
kinds has no rate with Prometheus's mixed-samples warning. Histograms
keep no counter reset hint, as the guide says rate treats every
histogram alike, so delta and idelta of histograms give Prometheus's
"this native histogram metric is not a gauge" warning.

Part of #7030.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-12-02 18:22:46 -04:00
1 parent 8705f7b1fe
commit 83209f39f6
6 files changed
+441 -81

No files matched your search

+17 -5
View File
@@ -690,11 +690,23 @@ with `bool` too, and Prometheus's `incompatible sample types encountered for bin
says so. `sum` and `avg` add histograms with Kahan compensation, `avg` falling back to a running mean
when the sum overflows, and so do `sum_over_time` and `avg_over_time`; a group or a range of both
floats and histograms has no result, with Prometheus's warning (`PromQL warning: encountered a mix of
histograms and floats for aggregation`) in the response's `warnings`. `rate` and the other functions
over a histogram's range, and `histogram_quantile`, come in a later part; until then they leave
histogram samples out. Histogram behavior follows Prometheus's latest release, 3.16, whose histogram
behavior the guide describes, such as the `ignored histogram` annotation that 3.0 does not have; a
histogram's counter reset hint, which only that release's warnings read, is not kept.
histograms and floats for aggregation`) in the response's `warnings`.
`rate`, `increase` and `delta` over a histogram's range take its last histogram, at the coarsest
schema of the range, less its first, extrapolated as a float's change is, the count standing in for
the value; for `rate` and `increase` each histogram before a counter reset is added back, a reset
being a fall in the count, the zero bucket or a bucket, or a finer schema, as Prometheus detects one;
an OTLP data point's start time is not read, as Prometheus reads start times only behind its
experimental `st-storage` feature.
`irate` and `idelta` take the last two samples, `resets` and `changes` count over floats and
histograms in time order, and a range of both kinds has no `rate` or `irate`, with Prometheus's
`encountered a mix of histograms and floats` warning. A histogram keeps no counter reset hint, which
the guide's "every histogram, including delta histograms" also says, so `rate` treats each as a
counter, and `delta` and `idelta`, which expect gauge histograms, give Prometheus's `this native
histogram metric is not a gauge` warning. `histogram_quantile`, `histogram_fraction`,
`histogram_stddev` and `histogram_stdvar` come in a later part. Histogram behavior follows
Prometheus's latest release, 3.16, whose histogram behavior the guide describes, such as the
`ignored histogram` annotation that 3.0 does not have.
Selectors follow Prometheus 3: a metric name or label name may be quoted, which a name with a dot has
to be (`{"http.server.active_requests", "@resource.service.name"="myservice"}`), and a matcher is
@@ -566,37 +566,9 @@ final class PromQlCalls {
}
return result;
});
case "changes" -> overTime(engine, arg, t, series -> {
int changes = 0;
for (int i = 1; i < series.size(); i++) {
double previous = series.values()[i - 1];
double current = series.values()[i];
if (current != previous && !(Double.isNaN(current) && Double.isNaN(previous))) {
changes++;
}
}
return changes;
});
case "resets" -> overTime(engine, arg, t, series -> {
int resets = 0;
for (int i = 1; i < series.size(); i++) {
if (series.values()[i] < series.values()[i - 1]) {
resets++;
}
}
return resets;
});
case "irate", "idelta" -> overTime(engine, arg, t, 2, series -> {
int last = series.size() - 1;
double current = series.values()[last];
double previous = series.values()[last - 1];
double difference = "irate".equals(name) && current < previous ? current : current - previous;
if ("idelta".equals(name)) {
return difference;
}
long interval = series.millis()[last] - series.millis()[last - 1];
return interval == 0 ? Double.NaN : difference / (interval / 1000.0);
});
case "changes", "resets" -> allOverTime(engine, arg, t,
series -> transitions(engine, series, "resets".equals(name)));
case "irate", "idelta" -> instant(engine, arg, t, "irate".equals(name));
case "deriv" -> overTime(engine, arg, t, 2, true, series -> regression(series, series.millis()[0])[0]);
default -> throw new IllegalStateException("not a function: " + name);
};
@@ -689,10 +661,122 @@ final class PromQlCalls {
return series.labels().getOrDefault(PromQlSeries.NAME, "");
}
/**
* {@code changes} or {@code resets} over a series' samples in time order, floats and histograms, as Prometheus
* counts them (v3.16): a float to a float that differs or falls, a histogram to one that differs or follows a
* counter reset ({@link PromQlHistogram#resetSince}), and a float to a histogram or back, each time.
*/
private static double transitions(PromQlEngine engine, Series series, boolean resets) {
int count = 0;
int nextFloat = 0;
int nextHistogram = 0;
boolean first = true;
double previousValue = 0;
PromQlHistogram previousHistogram = null;
while (nextFloat < series.size() || nextHistogram < series.histograms().length) {
boolean takeFloat = nextHistogram >= series.histograms().length || nextFloat < series.size()
&& series.millis()[nextFloat] < series.histogramMillis()[nextHistogram];
double value = takeFloat ? series.values()[nextFloat++] : 0;
PromQlHistogram histogram = takeFloat ? null : series.histograms()[nextHistogram++];
if (!first) {
// A pair of histograms compares every bucket: the clock is read at each pair.
engine.scan().work();
if (previousHistogram == null && histogram == null) {
boolean changed = resets ? value < previousValue
: value != previousValue && !(Double.isNaN(value) && Double.isNaN(previousValue));
count += changed ? 1 : 0;
} else if (previousHistogram == null || histogram == null) {
count++;
} else {
count += (resets ? histogram.resetSince(previousHistogram, engine.scan())
: !histogram.sameAs(previousHistogram)) ? 1 : 0;
}
}
first = false;
previousValue = value;
previousHistogram = histogram;
}
return count;
}
/**
* {@code irate} and {@code idelta}: the change between a series' last two samples, as Prometheus's
* {@code instantValue} takes it (v3.16), floats or histograms; {@code irate} takes a fall, or a histogram's counter
* reset, as a counter starting again, and per second. Two of different kinds have none, with Prometheus's
* warning, as {@code idelta} of histograms warns that they are not gauges.
*/
private static List<Sample> instant(PromQlEngine engine, PromQlExpr arg, long t, boolean rate) {
return reduced(engine, arg, t, range -> {
List<Sample> result = new ArrayList<>();
for (Series series : range) {
engine.scan().work();
if (series.samples() < 2) {
continue;
}
// The last two samples, of either kind, by time.
long[] times = new long[2];
double[] values = new double[2];
PromQlHistogram[] histograms = new PromQlHistogram[2];
lastTwo(series, times, values, histograms);
double seconds = (times[1] - times[0]) / 1000.0;
if (seconds == 0) {
continue;
}
SortedMap<String, String> labels = PromQlEngine.withoutName(series.labels());
if (histograms[0] == null && histograms[1] == null) {
double difference = rate && values[1] < values[0] ? values[1] : values[1] - values[0];
result.add(new Sample(labels, t, rate ? difference / seconds : difference));
} else if (histograms[0] != null && histograms[1] != null) {
if (!rate) {
notGauge(engine, series, arg);
}
PromQlHistogram difference = rate && histograms[1].resetSince(histograms[0], engine.scan())
? histograms[1] : histograms[1].minus(histograms[0], engine.scan());
PromQlHistogram value = rate ? difference.divided(seconds) : difference;
result.add(new Sample(labels, t, 0, PromQlAggregations.held(value, engine.scan())));
} else {
mixed(engine, series, arg);
}
}
return PromQlEngine.unique(result);
});
}
/** A series' last two samples by time, floats and histograms together. */
private static void lastTwo(Series series, long[] times, double[] values, PromQlHistogram[] histograms) {
int floats = series.size();
int histogramCount = series.histograms().length;
int nextFloat = floats - 1;
int nextHistogram = histogramCount - 1;
for (int slot = 1; slot >= 0; slot--) {
boolean takeFloat = nextHistogram < 0 || nextFloat >= 0
&& series.millis()[nextFloat] > series.histogramMillis()[nextHistogram];
if (takeFloat) {
times[slot] = series.millis()[nextFloat];
values[slot] = series.values()[nextFloat--];
} else {
times[slot] = series.histogramMillis()[nextHistogram];
histograms[slot] = series.histograms()[nextHistogram--];
}
}
}
private static void mixed(PromQlEngine engine, Series series, PromQlExpr arg) {
engine.annotations().warning("encountered a mix of histograms and floats for metric name "
+ PromQlParameters.quote(metricName(series)), arg);
}
/** A histogram here has no counter reset hint, so none is a gauge histogram, which delta and idelta warn of. */
private static void notGauge(PromQlEngine engine, Series series, PromQlExpr arg) {
engine.annotations().warning("this native histogram metric is not a gauge: "
+ PromQlParameters.quote(metricName(series)), arg);
}
/**
* {@code rate}, {@code increase} and {@code delta}: the change over the samples in range, counter resets added
* back for a counter, extrapolated to the range's boundaries as Prometheus's {@code extrapolatedRate} does, and
* for {@code rate} per second of the range.
* for {@code rate} per second of the range; of floats or of histograms, a series of both having none, with
* Prometheus's warning.
*/
private static List<Sample> extrapolated(PromQlEngine engine, PromQlExpr arg, long t, String name) {
boolean counter = !"delta".equals(name);
@@ -710,44 +794,118 @@ final class PromQlCalls {
default -> throw new IllegalStateException("not a range: " + arg);
}
long start = end - rangeMillis;
return overTime(engine, arg, t, 2, series -> {
int last = series.size() - 1;
double result = series.values()[last] - series.values()[0];
if (counter) {
double previous = series.values()[0];
for (int i = 1; i < series.size(); i++) {
double current = series.values()[i];
if (current < previous) {
result += previous;
boolean rate = "rate".equals(name);
return reduced(engine, arg, t, range -> {
List<Sample> result = new ArrayList<>();
for (Series series : range) {
engine.scan().work();
SortedMap<String, String> labels = PromQlEngine.withoutName(series.labels());
int histograms = series.histograms().length;
if (series.size() > 0 && histograms > 0) {
mixed(engine, series, arg);
} else if (histograms >= 2) {
PromQlHistogram change = histogramChange(engine, series, counter, arg);
double factor = factor(series.histogramMillis(), start, end, rangeMillis, rate, counter,
series.histograms()[0].count(), change.count());
result.add(new Sample(labels, t, 0, PromQlAggregations.held(change.scaled(factor),
engine.scan())));
} else if (series.size() >= 2) {
int last = series.size() - 1;
double change = series.values()[last] - series.values()[0];
if (counter) {
double previous = series.values()[0];
for (int i = 1; i < series.size(); i++) {
double current = series.values()[i];
if (current < previous) {
change += previous;
}
previous = current;
}
}
previous = current;
result.add(new Sample(labels, t, change * factor(series.millis(), start, end, rangeMillis, rate,
counter, series.values()[0], change)));
}
}
double toStart = (series.millis()[0] - start) / 1000.0;
double toEnd = (end - series.millis()[last]) / 1000.0;
double sampled = (series.millis()[last] - series.millis()[0]) / 1000.0;
double average = sampled / last;
double threshold = average * 1.1;
if (toStart >= threshold) {
toStart = average / 2;
}
if (counter && result > 0 && series.values()[0] >= 0) {
double toZero = sampled * (series.values()[0] / result);
if (toZero < toStart) {
toStart = toZero;
}
}
if (toEnd >= threshold) {
toEnd = average / 2;
}
double factor = (sampled + toStart + toEnd) / sampled;
if ("rate".equals(name)) {
factor /= rangeMillis / 1000.0;
}
return result * factor;
return PromQlEngine.unique(result);
});
}
/**
* What a change over samples at {@code millis} is multiplied by to extrapolate it to the range's boundaries, as
* Prometheus's {@code extrapolatedRate} computes it: a gap to a boundary up to 1.1 times the average interval is
* extrapolated over, a longer one only by half an interval, and a counter no further back than it would take to
* fall to zero, its first value, a float's or a histogram's count, against its change; per second for a rate.
*/
private static double factor(long[] millis, long start, long end, long rangeMillis, boolean rate, boolean counter,
double first, double change) {
int last = millis.length - 1;
double toStart = (millis[0] - start) / 1000.0;
double toEnd = (end - millis[last]) / 1000.0;
double sampled = (millis[last] - millis[0]) / 1000.0;
double average = sampled / last;
double threshold = average * 1.1;
if (toStart >= threshold) {
toStart = average / 2;
}
if (counter && change > 0 && first >= 0) {
double toZero = sampled * (first / change);
if (toZero < toStart) {
toStart = toZero;
}
}
if (toEnd >= threshold) {
toEnd = average / 2;
}
double factor = sampled != 0 ? (sampled + toStart + toEnd) / sampled : 1;
if (rate) {
factor /= rangeMillis / 1000.0;
}
return factor;
}
/**
* The change of a series' histograms over the range, as Prometheus's {@code histogramRate} takes it (v3.16): the
* last at the coarsest schema of the range less the first, for a counter the first taken as empty when the second
* follows a reset, and each histogram before a reset added back; {@code delta} takes no reset and warns that the
* histograms are not gauges.
*/
private static PromQlHistogram histogramChange(PromQlEngine engine, Series series, boolean counter,
PromQlExpr arg) {
PromQlHistogram[] points = series.histograms();
PromQlHistogram previous = points[0];
PromQlHistogram last = points[points.length - 1];
if (counter && points[1].resetSince(previous, engine.scan())) {
previous = new PromQlHistogram(points[1].schema(), 0, 0, 0, 0, 0, new double[0], 0, new double[0]);
}
int minSchema = Math.min(last.schema(), previous.schema());
if (counter) {
for (int i = 1; i < points.length - 1; i++) {
minSchema = Math.min(minSchema, points[i].schema());
}
}
// The last histogram's buckets merged to the coarsest schema are counted while they are taken from.
long merged = last.schema() > minSchema ? last.bytes() : 0;
engine.scan().hold(0, merged);
PromQlHistogram change;
try {
change = last.atSchema(minSchema).minus(previous, engine.scan());
} finally {
engine.scan().release(0, merged);
}
if (counter) {
for (int i = 1; i < points.length; i++) {
engine.scan().work();
if (points[i].resetSince(previous, engine.scan())) {
change = change.plus(previous, engine.scan());
}
previous = points[i];
}
} else {
notGauge(engine, series, arg);
}
return change;
}
/**
* The least-squares slope per second of a series' samples and their value at {@code interceptMillis}, as
* Prometheus's {@code linearRegression}.
@@ -211,6 +211,101 @@ final class PromQlHistogram {
return plus(other.scaled(-1), scan);
}
/**
* The histogram at a schema no finer than {@code target}, as Prometheus's {@code CopyToSchema} reduces one: bucket
* {@code i} added into bucket {@code ((i - 1) >> delta) + 1}.
*/
PromQlHistogram atSchema(int target) {
if (target >= schema) {
return this;
}
int delta = schema - target;
int[] positiveStart = {positiveOffset};
double[] reducedPositive = reduced(positiveOffset, positive, delta, positiveStart);
int[] negativeStart = {negativeOffset};
double[] reducedNegative = reduced(negativeOffset, negative, delta, negativeStart);
return new PromQlHistogram(target, zeroThreshold, zeroCount, count, sum, positiveStart[0], reducedPositive,
negativeStart[0], reducedNegative);
}
private static double[] reduced(int offset, double[] buckets, int delta, int[] start) {
if (buckets.length == 0) {
return buckets;
}
int first = ((offset - 1) >> delta) + 1;
int last = ((offset + buckets.length - 2) >> delta) + 1;
double[] reduced = new double[last - first + 1];
for (int i = 0; i < buckets.length; i++) {
reduced[((offset + i - 1) >> delta) + 1 - first] += buckets[i];
}
start[0] = first;
return reduced;
}
/**
* Whether this histogram follows a counter reset since {@code previous}, as Prometheus's {@code DetectReset} tells
* (a histogram here has no counter reset hint): a smaller count, a finer schema, a smaller zero threshold, a zero
* bucket that cannot hold or holds less than the previous one would at this threshold, or a bucket, at this
* schema and above the zero threshold, holding less than it held.
*/
boolean resetSince(PromQlHistogram previous) {
return resetSince(previous, null);
}
/** As {@link #resetSince(PromQlHistogram)}, the previous buckets merged to this schema counted against scan. */
boolean resetSince(PromQlHistogram previous, PromQlScan scan) {
if (count < previous.count || schema > previous.schema || zeroThreshold < previous.zeroThreshold) {
return true;
}
double[] widened = PromQlHistogramSum.zeroCountForLargerThreshold(previous.zeroCount, 0,
previous.zeroThreshold, zeroThreshold, previous.schema, previous.positiveOffset, previous.positive,
null, previous.negativeOffset, previous.negative, null);
if (widened[1] != zeroThreshold || zeroCount < widened[0]) {
return true;
}
long held = previous.schema > schema ? previous.bytes() : 0;
if (scan != null) {
scan.hold(0, held);
}
try {
PromQlHistogram coarse = previous.atSchema(schema);
return bucketsReset(positiveOffset, positive, coarse.positiveOffset, coarse.positive)
|| bucketsReset(negativeOffset, negative, coarse.negativeOffset, coarse.negative);
} finally {
if (scan != null) {
scan.release(0, held);
}
}
}
/**
* Whether a bucket of {@code previous}, both at this schema and past their first buckets within the zero
* threshold, holds more than this side's bucket at its index, or holds a count this side has no bucket for, as
* Prometheus's {@code detectReset} walks them.
*/
private boolean bucketsReset(int offset, double[] buckets, int previousOffset, double[] previous) {
int from = leadingWithin(offset, buckets);
int previousFrom = leadingWithin(previousOffset, previous);
for (int i = previousFrom; i < previous.length; i++) {
long index = (long) previousOffset + i;
long at = index - offset;
boolean present = at >= from && at < buckets.length;
if (present ? buckets[(int) at] < previous[i] : previous[i] != 0) {
return true;
}
}
return false;
}
/** How many leading buckets have their bound away from zero within the zero threshold. */
private int leadingWithin(int offset, double[] buckets) {
int within = 0;
while (within < buckets.length && bound(offset + within, schema) <= zeroThreshold) {
within++;
}
return within;
}
/**
* Whether {@code other} is the same histogram, as Prometheus's {@code Equals} compares them: the same schema and
* zero threshold, counts and sum of the same bits, and the same buckets, laid out alike, of the same bits.
@@ -254,16 +254,16 @@ final class PromQlHistogramSum {
double otherZeroCountC = 0;
while (otherThreshold != zeroThreshold) {
if (zeroThreshold > otherThreshold) {
double[] widened = zeroCountForLargerThreshold(other.zeroCount(), 0, zeroThreshold, other.schema(),
other.positiveOffset(), other.positiveBuckets(), null, other.negativeOffset(),
other.negativeBuckets(), null);
double[] widened = zeroCountForLargerThreshold(other.zeroCount(), 0, other.zeroThreshold(),
zeroThreshold, other.schema(), other.positiveOffset(), other.positiveBuckets(), null,
other.negativeOffset(), other.negativeBuckets(), null);
otherZeroCount = widened[0];
otherThreshold = widened[1];
otherZeroCountC = widened[2];
}
if (otherThreshold > zeroThreshold) {
double[] widened = zeroCountForLargerThreshold(zeroCount, zeroCountC, otherThreshold, schema,
positiveOffset, positive, positiveC, negativeOffset, negative, negativeC);
double[] widened = zeroCountForLargerThreshold(zeroCount, zeroCountC, zeroThreshold, otherThreshold,
schema, positiveOffset, positive, positiveC, negativeOffset, negative, negativeC);
zeroCount = widened[0];
zeroThreshold = widened[1];
zeroCountC = widened[2];
@@ -274,14 +274,18 @@ final class PromQlHistogramSum {
}
/**
* The zero count a histogram has with a threshold of at least {@code largerThreshold}, as
* {@code zeroCountForLargerThreshold} computes it, with the threshold it ends at and the compensation: a bucket
* across the threshold with a count widens it to the bucket's far bound.
* The zero count a histogram of zero threshold {@code threshold} has with a threshold of at least
* {@code largerThreshold}, as {@code zeroCountForLargerThreshold} computes it, with the threshold it ends at and
* the compensation: the same threshold changes nothing, and a bucket across a larger one with a count widens it to
* the bucket's far bound.
*/
static double[] zeroCountForLargerThreshold(double zeroCount, double zeroCountC, double largerThreshold,
int schema, int positiveOffset, double[] positive,
double[] positiveC, int negativeOffset, double[] negative,
double[] negativeC) {
static double[] zeroCountForLargerThreshold(double zeroCount, double zeroCountC, double currentThreshold,
double largerThreshold, int schema, int positiveOffset,
double[] positive, double[] positiveC, int negativeOffset,
double[] negative, double[] negativeC) {
if (largerThreshold == currentThreshold) {
return new double[] {zeroCount, largerThreshold, zeroCountC};
}
double threshold = largerThreshold;
outer:
while (true) {
@@ -742,6 +742,65 @@ class PromQlEngineTest {
.status());
}
@Test
void theRateOfAHistogramCounterIsItsExtrapolatedChangeResetsAddedBack() {
long t = T0 + 60_000;
metrics.ingest(REGION, request(exponential("lat", t - 30_000, 150, new long[] {40, 60}),
exponential("restarted", t - 30_000, 150, new long[] {40, 60})).toByteArray());
metrics.ingest(REGION, request(exponential("lat", t, 160, new long[] {42, 64}),
exponential("restarted", t, 30, new long[] {10, 20})).toByteArray());
// A change of 6 over 30 s of a 1 m range, extrapolated over the 30 s before: twice the change.
assertEquals("{count:12, sum:20, (1,2]:4, (2,4]:8}", histogram("increase({\"lat\"}[1m])", t));
assertEquals(0.2, vector("histogram_count(rate({\"lat\"}[1m]))", t).values().iterator().next(), 1e-12);
// A reset after the first sample takes the first as empty: the second histogram is the change.
assertEquals("{count:60, sum:60, (1,2]:20, (2,4]:40}", histogram("increase({\"restarted\"}[1m])", t));
assertEquals(Map.of("{__temporality__=cumulative}", 1.0), vector("resets({\"restarted\"}[1m])", t));
assertEquals(Map.of("{__temporality__=cumulative}", 0.0), vector("resets({\"lat\"}[1m])", t));
assertEquals(Map.of("{__temporality__=cumulative}", 1.0), vector("changes({\"lat\"}[1m])", t));
// irate is the last change per second, or the last histogram after a reset.
assertEquals("{count:0.2, sum:0.3333333333333333, (1,2]:0.06666666666666667, (2,4]:0.13333333333333333}",
histogram("irate({\"lat\"}[1m])", t));
assertEquals("{count:1, sum:1, (1,2]:0.3333333333333333, (2,4]:0.6666666666666666}",
histogram("irate({\"restarted\"}[1m])", t));
}
@Test
void aRangeOfFloatsAndHistogramsHasNoRateAndSaysWhy() {
long t = T0 + 60_000;
// A histogram seen only at the subquery's step T0 - 5 m and a float only at its step T0, of one label set
// once __type__ and __temporality__ are dropped: the subquery holds both kinds, the last two of each.
metrics.ingest(REGION, request(exponential("lat", T0 - 310_000)).toByteArray());
metrics.ingest(REGION, request(Metric.newBuilder().setName("lat").setGauge(Gauge.newBuilder()
.addDataPoints(NumberDataPoint.newBuilder().setTimeUnixNano((T0 - 10_000) * 1_000_000L)
.setAsDouble(1)))
.build()).toByteArray());
String both = "label_replace(label_replace({\"lat\"}, \"__type__\", \"\", \"\", \"\"), \"__temporality__\", "
+ "\"\", \"\", \"\")[10m:5m]";
String warning = "PromQL warning: encountered a mix of histograms and floats for metric name \"lat\" (1:";
for (String function : List.of("rate", "increase", "delta", "irate", "idelta")) {
PromQlQueries.Result result = queries.instant(function + "(" + both + ")", t, null);
assertEquals(List.of(), ((PromQlValue.Vector) result.value()).samples(), function);
assertEquals(List.of(warning + (function.length() + 2) + ")"), result.warnings(), function);
}
}
@Test
void deltaOfHistogramsTakesNoResetAndWarnsThatTheyAreNotGauges() {
long t = T0 + 60_000;
metrics.ingest(REGION, request(exponential("lat", t - 30_000, 150, new long[] {40, 60})).toByteArray());
metrics.ingest(REGION, request(exponential("lat", t, 30, new long[] {10, 20})).toByteArray());
PromQlQueries.Result delta = queries.instant("delta({\"lat\"}[1m])", t, null);
assertEquals("{count:-140, sum:-240, (1,2]:-60, (2,4]:-80}",
((PromQlValue.Vector) delta.value()).samples().getFirst().histogram().toString());
assertEquals(List.of("PromQL warning: this native histogram metric is not a gauge: \"lat\" (1:7)"),
delta.warnings());
PromQlQueries.Result idelta = queries.instant("idelta({\"lat\"}[1m])", t, null);
assertEquals("{count:-70, sum:-120, (1,2]:-30, (2,4]:-40}",
((PromQlValue.Vector) idelta.value()).samples().getFirst().histogram().toString());
assertEquals(List.of("PromQL warning: this native histogram metric is not a gauge: \"lat\" (1:8)"),
idelta.warnings());
}
@Test
void aRangeQueryKeepsHistogramSamplesApartFromFloats() {
long t = T0 + 60_000;
@@ -847,6 +906,12 @@ class PromQlEngineTest {
return exponential(name, millis, 0, 0, counts);
}
private static Metric exponential(String name, long millis, double sum, long[] counts) {
Metric metric = exponential(name, millis, 0, 0, counts);
return metric.toBuilder().setExponentialHistogram(metric.getExponentialHistogram().toBuilder()
.setDataPoints(0, metric.getExponentialHistogram().getDataPoints(0).toBuilder().setSum(sum))).build();
}
private static Metric exponential(String name, long millis, int scale, int offset, long[] counts) {
ExponentialHistogramDataPoint.Buckets.Builder buckets = ExponentialHistogramDataPoint.Buckets.newBuilder()
.setOffset(offset);
@@ -96,6 +96,32 @@ class PromQlHistogramTest {
assertEquals("{count:-1, sum:-0, [-1e-128,1e-128]:-1}", zero.scaled(-1).toString());
}
@Test
void aCounterResetIsAFallInTheCountOrABucketOrAFinerSchema() {
PromQlHistogram earlier = new PromQlHistogram(0, 1e-128, 0, 4, 6, 1, new double[] {1, 3}, 0, new double[0]);
PromQlHistogram later = new PromQlHistogram(0, 1e-128, 0, 6, 9, 1, new double[] {2, 4}, 0, new double[0]);
assertFalse(later.resetSince(earlier));
assertFalse(later.resetSince(later));
assertTrue(earlier.resetSince(later));
// A bucket across the zero threshold, as an OTLP point can have, is no reset at the same threshold.
PromQlHistogram straddling = PromQlHistogram.fromOtlpExponential(0, 0, 2, 1, -426, new long[] {1}, 0,
new long[0]);
assertFalse(straddling.resetSince(straddling));
// The count grew but a bucket fell.
assertTrue(new PromQlHistogram(0, 1e-128, 0, 7, 9, 1, new double[] {7, 0}, 0, new double[0])
.resetSince(earlier));
// A bucket the earlier histogram had a count in is gone.
assertTrue(new PromQlHistogram(0, 1e-128, 0, 9, 9, 2, new double[] {9}, 0, new double[0]).resetSince(earlier));
// A finer schema than before is a reset; a coarser one compares the earlier buckets merged.
assertTrue(earlier.atSchema(0).resetSince(new PromQlHistogram(-1, 1e-128, 0, 4, 6, 1, new double[] {4}, 0,
new double[0])));
PromQlHistogram fine = new PromQlHistogram(1, 1e-128, 0, 4, 6, 1, new double[] {1, 1, 1, 1}, 0,
new double[0]);
assertEquals("{count:4, sum:6, (1,2]:2, (2,4]:2}", fine.atSchema(0).toString());
assertFalse(new PromQlHistogram(0, 1e-128, 0, 4, 6, 1, new double[] {2, 2}, 0, new double[0])
.resetSince(fine));
}
@Test
void negativeBucketsComeFirstLowestFirstAndAreOpenAbove() {
PromQlHistogram histogram = PromQlHistogram.fromOtlpExponential(0, 0, 3, -5, 0, new long[0], 0,