Skip to content

Commit 8bec128

Browse files
authored
MAL: Inf histogram bounds; percentile overflow uses highest finite bound (#14275)
Behavior change: a MAL histogram_percentile or TAL percentile rank that falls in a histogram's overflow (+Inf, Long.MAX_VALUE) bucket now reads the highest finite bucket bound instead of Long.MAX_VALUE, as Prometheus histogram_quantile does. A percentile that reads that bound may be above it, and none reads above it, so an alarm condition that needs a value above it no longer fires. The MAL, TAL and trace-analyzer docs and the changelog say so. histogram() also accepts the +Inf / -Inf / Inf bucket bound spellings and rejects NaN; the shipped receivers send numbers (OTLP labels the overflow bucket "Infinity", which already parsed). The percentile functions sort the negative-infinity bucket key ("infinite-") instead of failing Long.parseLong on it.
1 parent 1d52e07 commit 8bec128

16 files changed

Lines changed: 521 additions & 21 deletions

File tree

‎docs/en/changes/changes.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@
113113
* BanyanDB: an init or default-mode OAP now applies additive schema changes (new columns, tags or fields) at boot to every measure, stream and trace, as it already did on JDBC and Elasticsearch, so a metric whose storage only gained columns in an upgrade no longer stays disabled. A breaking change (a removed or retyped column, a different entity) is still refused at boot. The OAP logs one line for each storage resource outcome its installers record: DEBUG when unchanged, INFO when created, updated or dropped, ERROR when an incompatible change is refused; the storage plugins log the DDL they run at DEBUG.
114114
* Virtual GenAI reads the time to first token from `gen_ai.response.time_to_first_chunk`, a number of seconds, the span attribute the OpenTelemetry GenAI semantic conventions define for it, on the spans of a SkyWalking agent and on OTLP and Zipkin spans alike. Before, only `gen_ai.server.time_to_first_token`, in milliseconds, was read, a name the conventions give to a metric and not to a span attribute, so a span following the conventions reported no time to first token to `gen_ai_model_ttft_avg` and `gen_ai_model_ttft_percentile`. `gen_ai.server.time_to_first_token` is still read when a span has no `gen_ai.response.time_to_first_chunk`, for SkyWalking Java Agent 9.7 and 9.8, which report it. TAL gets the `parseSecondsAsMillisOrZero(text)` function for the conversion.
115115
* Virtual GenAI on OTLP and Zipkin spans counts a span without `gen_ai.response.model` by its `gen_ai.request.model`: a call that failed before the provider answered has no response model and was skipped, so `gen_ai_provider_sla` and `gen_ai_model_sla` missed such failures. A span whose `gen_ai.operation.name` describes no model call of its own (`fetch_response`, `create_agent`, `execute_tool`, `plan`, `retrieval`, `user_speech`, the memory operations and every `invoke_*` name) is no longer counted, because it can repeat the model and the token usage of the calls under it or of an earlier call; spans with another operation name, or none, are counted as before. Spans of the SkyWalking agents are identified as before.
116+
* Behavior change: a MAL `histogram_percentile` or TAL `percentile` rank that falls in a histogram's overflow (`+Inf`) bucket reads the highest finite bucket bound instead of `9223372036854775807` (`Long.MAX_VALUE`). A percentile that reads that bound may be above it, and none reads above it, so an alarm condition that needs a value above it, such as `p99 > 10000` on buckets that end at 10000, no longer fires: set such a threshold below the highest bound, or add a higher bucket. MAL `histogram()` also accepts the `+Inf`, `-Inf` and `Inf` bucket bound spellings and rejects `NaN`, and a native meter histogram whose first bucket is negative infinity no longer fails its percentile.
116117

117118
#### UI
118119

‎docs/en/concepts-and-designs/mal.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,9 +249,18 @@ Examples:
249249
histogram buckets in the meter system. (If the metrics from the Prometheus are based on the `seconds-based` histogram
250250
buckets, will multiply the bucket value by 1000.)
251251

252+
`le` accepts Prometheus/OpenMetrics (`+Inf` / `-Inf` / `Inf`) and Java (`Infinity` / `-Infinity`) spellings for the
253+
overflow and underflow bounds, mapped to `Long.MAX_VALUE` and `Long.MIN_VALUE`. `NaN` is rejected.
254+
252255
#### histogram_percentile
253256
`histogram_percentile([<p scalar>])`: Represents the meter-system to calculate the p-percentile (0 ≤ p ≤ 100) from the buckets.
254257

258+
A rank reads as the bound of the bucket it falls in. A rank that falls in the overflow bucket (`le` is `+Inf`, which
259+
`histogram()` turns into `Long.MAX_VALUE`) reads the highest finite bound instead, as Prometheus `histogram_quantile`
260+
does. So a percentile that reads the highest finite bound may be above it, and no percentile reads above it: an alarm
261+
condition that needs a value above it, such as `p99 > 10000` on buckets that end at 10000, never fires. A histogram
262+
whose only bucket is the overflow bucket reads `Long.MAX_VALUE`.
263+
255264
#### time
256265
`time()`: Returns the number of seconds since January 1, 1970 UTC.
257266

‎docs/en/concepts-and-designs/tal.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@ The functions are the meter system's, named for what they do to the values of on
383383
| `percent` | `match` condition | `matches * 10000 / total`, the `core.oal` `percent` scale; `match meta.statusCode != "ERROR"` is the success rate |
384384
| `apdex` | `value` and `status` | the `core.oal` `apdex`: thresholds from `service-apdex-threshold.yml` looked up by the entity's service name as stored, after the service name length limit, satisfied under `T`, tolerated under `4T`; a relation scope is a compile error |
385385
| `sumLabeled`, `avgLabeled`, `maxLabeled`, `minLabeled`, `latestLabeled`, `sumPerMinLabeled` | number, by `labels` | one series per label set; `labels status: attr("http.response.status_code", "http.status_code")` splits a count by status code |
386-
| `percentile` | number, by `buckets` | the observation counted in the first bucket whose bound is not below it, so each bound is its bucket's upper edge, as MAL keys OTel's `le`; a value above the last bound counts in an overflow bucket keyed `9223372036854775807` (`Long.MAX_VALUE`), the key MAL gives OTel's `+Inf` bucket. The buckets are reduced to the `ranks` when the minute is persisted; a rank reads as the upper edge of the bucket it falls in, and a rank that falls in the overflow bucket reads `9223372036854775807` |
386+
| `percentile` | number, by `buckets` | the observation counted in the first bucket whose bound is not below it, so each bound is its bucket's upper edge, as MAL keys OTel's `le`; a value above the last bound counts in an overflow bucket keyed `9223372036854775807` (`Long.MAX_VALUE`), the key MAL gives OTel's `+Inf` bucket. The buckets are reduced to the `ranks` when the minute is persisted; a rank reads as the upper edge of the bucket it falls in, and a rank that falls in the overflow bucket reads the last bound, so a rank that reads the last bound may be above it, and an alarm condition that needs a value above the last bound never fires |
387387

388388
With `cpm`, `percent` and `apdex` a TAL metric named like an agent metric holds the same number in the same unit, so
389389
an alarm rule or a dashboard widget written for `service_sla` ports to `otlp_service_sla` by renaming the metric.

‎docs/en/setup/backend/trace-analyzer.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,8 @@ Two metrics read differently:
179179
- `*_percentile`: `core.oal` computes `percentile2(10)`, which floors a latency to 10 ms steps, so a 110 ms p99
180180
reads 110. The TAL `percentile` counts a latency in the bucket whose upper edge is the first bound not below it,
181181
and a rank reads that edge, so the same p99 reads 250 with the shipped buckets, and a rank above the last bound,
182-
10 s, reads `9223372036854775807`. An alarm threshold such as `p99 > 200` needs restating against the buckets.
182+
10 s, reads 10000, the last bound. An alarm threshold such as `p99 > 200` needs restating against the buckets, and
183+
one that needs a p99 above 10000, such as `p99 > 10000`, never fires.
183184
- `*_resp_time`: a minute whose mean is above 0 but below 1 ms reads 1, the meter system's `avg`; `core.oal`'s
184185
`longAvg` reads 0.
185186

‎oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/Analyzer.java‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -357,9 +357,11 @@ public void analyse(final ImmutableMap<String, SampleFamily> sampleFamilies) {
357357
long[] vv = new long[bb.length];
358358
for (int i = 0; i < subSs.size(); i++) {
359359
Sample s = subSs.get(i);
360-
final double leVal = Double.parseDouble(s.getLabels().get("le"));
360+
final double leVal = SampleFamily.parseBucketBound(s.getLabels().get("le"));
361361
if (leVal == Double.NEGATIVE_INFINITY) {
362362
bb[i] = Long.MIN_VALUE;
363+
} else if (leVal == Double.POSITIVE_INFINITY) {
364+
bb[i] = Long.MAX_VALUE;
363365
} else {
364366
bb[i] = (long) leVal;
365367
}

‎oap-server/analyzer/meter-analyzer/src/main/java/org/apache/skywalking/oap/meter/analyzer/v2/dsl/SampleFamily.java‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -548,17 +548,20 @@ public SampleFamily histogram(String le, TimeUnit unit) {
548548
Arrays.stream(samples).filter(s -> !s.labels.containsKey(le)),
549549
Arrays.stream(samples)
550550
.filter(s -> s.labels.containsKey(le))
551-
.sorted(Comparator.comparingDouble(s -> Double.parseDouble(s.labels.get(le))))
551+
.sorted(Comparator.comparingDouble(s -> parseBucketBound(s.labels.get(le))))
552552
.map(s -> {
553553
double r = s.value;
554+
final double bound = parseBucketBound(s.labels.get(le));
555+
// OTel/Prometheus +Inf becomes Long.MAX_VALUE after unit scale (HeatMap / Analyzer).
556+
final long scaled = Double.isInfinite(bound)
557+
? (bound > 0 ? Long.MAX_VALUE : Long.MIN_VALUE)
558+
: (long) (bound * scale);
554559
ImmutableMap<String, String> ll = ImmutableMap.<String, String>builder()
555560
.putAll(Maps.filterKeys(s.labels,
556561
key -> !Objects.equals(
557562
key, le)
558563
))
559-
.put(
560-
"le",
561-
String.valueOf((long) ((Double.parseDouble(s.labels.get(le))) * scale)))
564+
.put("le", String.valueOf(scaled))
562565
.build();
563566
return InternalOps.newSample(s.name, ll, s.timestamp, r);
564567
})
@@ -799,6 +802,32 @@ static RunningContext instance() {
799802
private TimeUnit defaultHistogramBucketUnit;
800803
}
801804

805+
/**
806+
* Parse a histogram bucket upper bound. Accepts Prometheus text ({@code +Inf}/{@code -Inf})
807+
* and Java {@link Double#toString()} forms ({@code Infinity}/{@code -Infinity}).
808+
* Rejects {@code NaN}: OpenMetrics forbids it as a bucket bound, and casting NaN to {@code long}
809+
* would silently become {@code 0}.
810+
*/
811+
public static double parseBucketBound(final String raw) {
812+
if (raw == null) {
813+
throw new NumberFormatException("null histogram bucket bound");
814+
}
815+
if ("+Inf".equalsIgnoreCase(raw) || "Inf".equalsIgnoreCase(raw) || "Infinity".equalsIgnoreCase(raw)) {
816+
return Double.POSITIVE_INFINITY;
817+
}
818+
if ("-Inf".equalsIgnoreCase(raw) || "-Infinity".equalsIgnoreCase(raw)) {
819+
return Double.NEGATIVE_INFINITY;
820+
}
821+
if ("NaN".equalsIgnoreCase(raw)) {
822+
throw new NumberFormatException("NaN histogram bucket bound");
823+
}
824+
final double value = Double.parseDouble(raw);
825+
if (Double.isNaN(value)) {
826+
throw new NumberFormatException("NaN histogram bucket bound");
827+
}
828+
return value;
829+
}
830+
802831
private static class InternalOps {
803832

804833
private static Sample[] left(List<Sample> samples, List<String> labelKeys) {
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*
17+
*/
18+
19+
package org.apache.skywalking.oap.meter.analyzer.v2;
20+
21+
import com.google.common.collect.ImmutableMap;
22+
import org.apache.skywalking.oap.meter.analyzer.v2.dsl.Sample;
23+
import org.apache.skywalking.oap.meter.analyzer.v2.dsl.SampleFamily;
24+
import org.apache.skywalking.oap.meter.analyzer.v2.dsl.SampleFamilyBuilder;
25+
import org.apache.skywalking.oap.server.core.analysis.meter.MeterEntity;
26+
import org.apache.skywalking.oap.server.core.analysis.meter.MeterSystem;
27+
import org.apache.skywalking.oap.server.core.analysis.meter.function.AcceptableValue;
28+
import org.apache.skywalking.oap.server.core.analysis.meter.function.BucketedValues;
29+
import org.apache.skywalking.oap.server.core.analysis.meter.function.PercentileArgument;
30+
import org.apache.skywalking.oap.server.core.analysis.worker.MetricsStreamProcessor;
31+
import org.apache.skywalking.oap.server.core.config.NamingControl;
32+
import org.apache.skywalking.oap.server.core.config.group.EndpointNameGrouping;
33+
import org.junit.jupiter.api.AfterAll;
34+
import org.junit.jupiter.api.BeforeAll;
35+
import org.junit.jupiter.api.Test;
36+
import org.junit.jupiter.api.extension.ExtendWith;
37+
import org.mockito.ArgumentCaptor;
38+
import org.mockito.Mock;
39+
import org.mockito.MockedStatic;
40+
import org.mockito.junit.jupiter.MockitoExtension;
41+
42+
import static com.google.common.collect.ImmutableMap.of;
43+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
44+
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
45+
import static org.junit.jupiter.api.Assertions.assertEquals;
46+
import static org.mockito.ArgumentMatchers.any;
47+
import static org.mockito.ArgumentMatchers.anyString;
48+
import static org.mockito.ArgumentMatchers.eq;
49+
import static org.mockito.Mockito.doNothing;
50+
import static org.mockito.Mockito.mock;
51+
import static org.mockito.Mockito.mockStatic;
52+
import static org.mockito.Mockito.verify;
53+
import static org.mockito.Mockito.when;
54+
55+
/**
56+
* End-to-end coverage for Analyzer building histogram / percentile meters when a bucket
57+
* is labeled {@code le="+Inf"} (Prometheus) or {@code Infinity} (Java). FunctionTest only
58+
* asserts the MAL expression result; this hits {@link Analyzer#analyse} which parses {@code le}
59+
* again while assembling {@link BucketedValues}.
60+
*/
61+
@ExtendWith(MockitoExtension.class)
62+
public class AnalyzerHistogramInfTest {
63+
64+
@Mock
65+
private MeterSystem meterSystem;
66+
67+
@BeforeAll
68+
public static void setUp() {
69+
MeterEntity.setNamingControl(new NamingControl(512, 512, 512, new EndpointNameGrouping()));
70+
}
71+
72+
@AfterAll
73+
public static void tearDown() {
74+
MeterEntity.setNamingControl(null);
75+
}
76+
77+
@Test
78+
void analysePercentileAcceptsPrometheusPlusInfBucket() {
79+
final AcceptableValue<PercentileArgument> sink = mock(AcceptableValue.class);
80+
when(meterSystem.buildMetrics(anyString(), eq(PercentileArgument.class))).thenReturn(sink);
81+
doNothing().when(meterSystem).create(anyString(), anyString(), any());
82+
doNothing().when(meterSystem).doStreamingCalculation(any());
83+
84+
final Analyzer analyzer = Analyzer.build(
85+
"http_latency_percentile",
86+
null,
87+
"http_request_duration_bucket.histogram().histogram_percentile([75, 99])"
88+
+ ".service(['service'], Layer.GENERAL)",
89+
meterSystem
90+
);
91+
92+
final ImmutableMap<String, SampleFamily> input = of(
93+
"http_request_duration_bucket",
94+
SampleFamilyBuilder.newBuilder(
95+
sample("0.025", 100),
96+
sample("0.75", 22),
97+
sample("1.25", 30),
98+
sample("+Inf", 40)
99+
).build()
100+
);
101+
102+
try (MockedStatic<MetricsStreamProcessor> ignored = mockStatic(MetricsStreamProcessor.class)) {
103+
final MetricsStreamProcessor processor = mock(MetricsStreamProcessor.class);
104+
ignored.when(MetricsStreamProcessor::getInstance).thenReturn(processor);
105+
assertDoesNotThrow(() -> analyzer.analyse(input));
106+
}
107+
108+
final ArgumentCaptor<PercentileArgument> captor = ArgumentCaptor.forClass(PercentileArgument.class);
109+
verify(sink).accept(any(MeterEntity.class), captor.capture());
110+
final BucketedValues buckets = captor.getValue().getBucketedValues();
111+
assertArrayEquals(
112+
new long[] {25L, 750L, 1250L, Long.MAX_VALUE},
113+
buckets.getBuckets()
114+
);
115+
assertArrayEquals(new long[] {100L, 22L, 30L, 40L}, buckets.getValues());
116+
assertArrayEquals(new int[] {75, 99}, captor.getValue().getRanks());
117+
}
118+
119+
@Test
120+
void analyseHistogramAcceptsJavaInfinityAndNegInfBuckets() {
121+
final AcceptableValue<BucketedValues> sink = mock(AcceptableValue.class);
122+
when(meterSystem.buildMetrics(anyString(), eq(BucketedValues.class))).thenReturn(sink);
123+
doNothing().when(meterSystem).create(anyString(), anyString(), any());
124+
doNothing().when(meterSystem).doStreamingCalculation(any());
125+
126+
final Analyzer analyzer = Analyzer.build(
127+
"http_latency_histogram",
128+
null,
129+
"http_request_duration_bucket.histogram().service(['service'], Layer.GENERAL)",
130+
meterSystem
131+
);
132+
133+
final ImmutableMap<String, SampleFamily> input = of(
134+
"http_request_duration_bucket",
135+
SampleFamilyBuilder.newBuilder(
136+
sample("-Inf", 1),
137+
sample("0.025", 100),
138+
sample("Infinity", 120)
139+
).build()
140+
);
141+
142+
try (MockedStatic<MetricsStreamProcessor> ignored = mockStatic(MetricsStreamProcessor.class)) {
143+
final MetricsStreamProcessor processor = mock(MetricsStreamProcessor.class);
144+
ignored.when(MetricsStreamProcessor::getInstance).thenReturn(processor);
145+
assertDoesNotThrow(() -> analyzer.analyse(input));
146+
}
147+
148+
final ArgumentCaptor<BucketedValues> captor = ArgumentCaptor.forClass(BucketedValues.class);
149+
verify(sink).accept(any(MeterEntity.class), captor.capture());
150+
assertArrayEquals(
151+
new long[] {Long.MIN_VALUE, 25L, Long.MAX_VALUE},
152+
captor.getValue().getBuckets()
153+
);
154+
assertEquals(3, captor.getValue().getValues().length);
155+
}
156+
157+
private static Sample sample(final String le, final double value) {
158+
return Sample.builder()
159+
.name("http_request_duration_bucket")
160+
.labels(of("service", "ds-api", "le", le))
161+
.value(value)
162+
.timestamp(1_700_000_000_000L)
163+
.build();
164+
}
165+
}

0 commit comments

Comments
 (0)