SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
fix: put non-positive formula heatmap values in the zero bucket (#13217)
Naman Vermae5a39e34894c
diff --git a/pkg/querier/postprocess.go b/pkg/querier/postprocess.goindex e730d56e67..0cb370e481 100644--- a/pkg/querier/postprocess.go+++ b/pkg/querier/postprocess.go@@ -497,6 +497,9 @@ func bucketFormulaOutputAsHeatmap(tsData *qbtypes.TimeSeriesData, bucketing qbty// to stay identical to them: a formula heatmap and a metric heatmap that// disagreed here would put their counts in different buckets.func calculateLinearValueUpperBound(bucketing qbtypes.HeatmapBucketing, value float64) float64 {+ if value <= 0 {+ return 0+ }if value > bucketing.MaxValue {return math.Inf(1)}diff --git a/pkg/types/querybuildertypes/querybuildertypesv5/heatmap.go b/pkg/types/querybuildertypes/querybuildertypesv5/heatmap.goindex 8e2cc9db35..8908c1e821 100644--- a/pkg/types/querybuildertypes/querybuildertypesv5/heatmap.go+++ b/pkg/types/querybuildertypes/querybuildertypesv5/heatmap.go@@ -242,19 +242,28 @@ func addHeatmapBucketsWithNoCountsForAggregation(aggBucket *AggregationBucket, b}indexes[i] = bucketing.calculateIndexOfUpperBound(upperBound)}- lowest, highest := slices.Min(indexes), slices.Max(indexes)-- // The lowest bucket reached needs the rung under it on the axis, or its own- // lower bound goes unstated and it reads as holding everything below. That- // one rung is enough: everything under it merges into the single leading- // bucket, which no series reached.- from := lowest - 1- if offset == 1 && bucketing.calculateUpperBoundAtIndex(from) <= aggBucket.Meta.Buckets[0] {- from = lowest+ lowestIndexOnAxis, highestIndexOnAxis := slices.Min(indexes), slices.Max(indexes)++ // Start one rung below the lowest bucket that holds a count, so its lower+ // bound is on the axis. The axis may already begin with an empty bucket that+ // states that bound, in which case nothing is added beneath it.+ firstDenseIndex := lowestIndexOnAxis+ for _, series := range aggBucket.Series {+ for _, point := range series.Values {+ for i := offset; i < len(point.Values) && i < len(aggBucket.Meta.Buckets); i++ {+ if point.Values[i] != 0 {+ firstDenseIndex = min(firstDenseIndex, indexes[i-offset]-1)+ }+ }+ }+ }+ // The zero bucket is the floor, so no rung goes at or under it.+ if offset == 1 && bucketing.calculateUpperBoundAtIndex(firstDenseIndex) <= aggBucket.Meta.Buckets[0] {+ firstDenseIndex = lowestIndexOnAxis}denseUpperBounds := append([]float64{}, aggBucket.Meta.Buckets[:offset]...)- for index := from; index <= highest; index++ {+ for index := firstDenseIndex; index <= highestIndexOnAxis; index++ {denseUpperBounds = append(denseUpperBounds, bucketing.calculateUpperBoundAtIndex(index))}if len(denseUpperBounds) == len(aggBucket.Meta.Buckets) {@@ -266,7 +275,7 @@ func addHeatmapBucketsWithNoCountsForAggregation(aggBucket *AggregationBucket, b// lands where it came from.shiftedTo := make([]int, len(aggBucket.Meta.Buckets))for i, index := range indexes {- shiftedTo[i+offset] = index - from + offset+ shiftedTo[i+offset] = index - firstDenseIndex + offset}overflowIndex := len(denseUpperBounds)diff --git a/tests/integration/tests/queriermetrics/15_heatmap.py b/tests/integration/tests/queriermetrics/15_heatmap.pyindex 83a5af5ddb..df5de5bc2f 100644--- a/tests/integration/tests/queriermetrics/15_heatmap.py+++ b/tests/integration/tests/queriermetrics/15_heatmap.py@@ -302,11 +302,30 @@ def test_linear_buckets(]+ "bucket_options, expected_buckets, expected_columns",+ [+ (+ build_log_bucket_options(0),+ [0.0, 128.0, 256.0, 512.0, 1024.0],+ [[1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0]],+ ),+ (+ build_linear_bucket_options(1024, 4),+ [0.0, 256.0, 512.0, 768.0, 1024.0],+ [[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0]],+ ),+ ],+ ids=["log", "linear"],+)def test_zero_bucket(signoz: types.SigNoz,create_user_admin: None, # pylint: disable=unused-argumentget_token: Callable[[str, str], str],insert_metrics: Callable[[list[Metrics]], None],+ bucket_options: dict,+ expected_buckets: list[float],+ expected_columns: list[list[int]],) -> None:now = datetime.now(tz=UTC).replace(second=0, microsecond=0)start_ms = int((now - timedelta(minutes=30)).timestamp() * 1000)@@ -334,23 +353,16 @@ def test_zero_bucket(token,start_ms,end_ms,- [build_builder_query("A", metric_name, "max", "max", bucket_options=build_log_bucket_options(0))],+ [build_builder_query("A", metric_name, "max", "max", bucket_options=bucket_options)],request_type=RequestType.HEATMAP,)assert response.status_code == HTTPStatus.OK, response.textdata = response.json()- # a log axis cannot place a value at or below zero, so those share a bucket- # of their own beneath the rest. 128 separates that bucket from the lowest- # one holding anything, and 512 is spanned above it- assert get_heatmap_buckets(data, "A") == pytest.approx([0.0, 128.0, 256.0, 512.0, 1024.0])+ assert get_heatmap_buckets(data, "A") == pytest.approx(expected_buckets)columns = get_heatmap_columns(data, "A")- assert [column["values"] for column in columns] == [- [1, 0, 0, 0, 0, 0],- [0, 0, 1, 0, 0, 0],- [0, 0, 0, 0, 1, 0],- ]+ assert [column["values"] for column in columns] == expected_columnsdef test_single_bucket(@@ -830,3 +842,127 @@ def test_metric_with_no_data(assert get_heatmap_buckets(data, "A") == []assert get_heatmap_columns(data, "A") == []assert any(missing_metric in warning["message"] for warning in get_all_warnings(data))+++ "bucket_options, expected_buckets",+ [+ (build_linear_bucket_options(1000, 10), [0.0, 200.0, 300.0]),+ (build_log_bucket_options(0), [0.0, 128.0, 256.0]),+ ],+ ids=["linear", "log"],+)+def test_negative_values(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_metrics: Callable[[list[Metrics]], None],+ bucket_options: dict,+ expected_buckets: list[float],+) -> None:+ now = datetime.now(tz=UTC).replace(second=0, microsecond=0)+ start_ms = int((now - timedelta(minutes=30)).timestamp() * 1000)+ end_ms = int(now.timestamp() * 1000)+ metric_name = "test_heatmap_negative_values"++ values = [-1500, -50, 0, 250]+ insert_metrics(+ [+ Metrics(+ metric_name=metric_name,+ labels={"service": "api"},+ timestamp=now - timedelta(minutes=len(values) - minute),+ value=value,+ type_="Gauge",+ is_monotonic=False,+ )+ for minute, value in enumerate(values)+ ]+ )++ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ response = make_query_request(+ signoz,+ token,+ start_ms,+ end_ms,+ [build_builder_query("A", metric_name, "max", "max", bucket_options=bucket_options)],+ request_type=RequestType.HEATMAP,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ data = response.json()+ assert get_heatmap_buckets(data, "A") == pytest.approx(expected_buckets)++ columns = get_heatmap_columns(data, "A")+ assert [column["values"] for column in columns] == [+ [1, 0, 0, 0],+ [1, 0, 0, 0],+ [1, 0, 0, 0],+ [0, 0, 1, 0],+ ]+++# a formula's output is bucketed after the query runs rather than by it, and+# has to put everything at or below zero where a metric query does: in the zero+# bucket, never in the lowest bucket above it+ "bucket_options, expected_buckets",+ [+ (build_linear_bucket_options(1000, 10), [0.0, 200.0, 300.0]),+ (build_log_bucket_options(0), [0.0, 128.0, 256.0]),+ ],+ ids=["linear", "log"],+)+def test_formula_negative_values(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_metrics: Callable[[list[Metrics]], None],+ bucket_options: dict,+ expected_buckets: list[float],+) -> None:+ now = datetime.now(tz=UTC).replace(second=0, microsecond=0)+ start_ms = int((now - timedelta(minutes=30)).timestamp() * 1000)+ end_ms = int(now.timestamp() * 1000)+ metric_name = "test_heatmap_formula_negative_values"++ values = [-1500, -50, 0, 250]+ insert_metrics(+ [+ Metrics(+ metric_name=metric_name,+ labels={"service": "api"},+ timestamp=now - timedelta(minutes=len(values) - minute),+ value=value,+ type_="Gauge",+ is_monotonic=False,+ )+ for minute, value in enumerate(values)+ ]+ )++ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ response = make_query_request(+ signoz,+ token,+ start_ms,+ end_ms,+ [+ build_builder_query("A", metric_name, "max", "max", disabled=True),+ build_formula_query("F1", "A", bucket_options=bucket_options),+ ],+ request_type=RequestType.HEATMAP,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ data = response.json()+ assert get_heatmap_buckets(data, "F1") == pytest.approx(expected_buckets)++ columns = get_heatmap_columns(data, "F1")+ assert [column["values"] for column in columns] == [+ [1, 0, 0, 0],+ [1, 0, 0, 0],+ [1, 0, 0, 0],+ [0, 0, 1, 0],+ ]