Skip to content

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.

fix: warning instead of error for dormant metrics in query range API (#10737)

Naman Verma65402ca3678f
diff --git a/pkg/querier/querier.go b/pkg/querier/querier.go
index b51057810b..46c0198973 100644
--- a/pkg/querier/querier.go
+++ b/pkg/querier/querier.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log/slog"
+ gomaps "maps"
"slices"
"strconv"
"strings"
@@ -282,6 +283,7 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
queries := make(map[string]qbtypes.Query)
steps := make(map[string]qbtypes.Step)
missingMetrics := []string{}
+ missingMetricQueries := []string{}
for _, query := range req.CompositeQuery.Queries {
var queryName string
@@ -374,6 +376,7 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
}
q.logger.DebugContext(ctx, "fetched metric temporalities and types", slog.Any("metric_temporality", metricTemporality), slog.Any("metric_types", metricTypes))
}
+ presentAggregations := []qbtypes.MetricAggregation{}
for i := range spec.Aggregations {
if spec.Aggregations[i].MetricName != "" && spec.Aggregations[i].Temporality == metrictypes.Unknown {
if temp, ok := metricTemporality[spec.Aggregations[i].MetricName]; ok && temp != metrictypes.Unknown {
@@ -384,13 +387,18 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
missingMetrics = append(missingMetrics, spec.Aggregations[i].MetricName)
continue
}
-
if spec.Aggregations[i].MetricName != "" && spec.Aggregations[i].Type == metrictypes.UnspecifiedType {
if foundMetricType, ok := metricTypes[spec.Aggregations[i].MetricName]; ok && foundMetricType != metrictypes.UnspecifiedType {
spec.Aggregations[i].Type = foundMetricType
}
}
+ presentAggregations = append(presentAggregations, spec.Aggregations[i])
+ }
+ if len(presentAggregations) == 0 {
+ missingMetricQueries = append(missingMetricQueries, spec.Name)
+ continue
}
+ spec.Aggregations = presentAggregations
spec.ShiftBy = extractShiftFromBuilderQuery(spec)
timeRange := adjustTimeRangeForShift(spec, qbtypes.TimeRange{From: req.Start, To: req.End}, req.RequestType)
var bq *builderQuery[qbtypes.MetricAggregation]
@@ -409,25 +417,50 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
}
}
}
+ nonExistentMetrics := []string{}
+ var dormantMetricsWarningMsg string
if len(missingMetrics) > 0 {
lastSeenInfo, _ := q.metadataStore.FetchLastSeenInfoMulti(ctx, missingMetrics...)
+ for _, missingMetricName := range missingMetrics {
+ if ts, ok := lastSeenInfo[missingMetricName]; ok && ts > 0 {
+ continue
+ }
+ nonExistentMetrics = append(nonExistentMetrics, missingMetricName)
+ }
+ if len(nonExistentMetrics) == 1 {
+ return nil, errors.NewNotFoundf(errors.CodeNotFound, "could not find the metric %s", nonExistentMetrics[0])
+ } else if len(nonExistentMetrics) > 1 {
+ return nil, errors.NewNotFoundf(errors.CodeNotFound, "the following metrics were not found: %s", strings.Join(nonExistentMetrics, ", "))
+ }
lastSeenStr := func(name string) string {
if ts, ok := lastSeenInfo[name]; ok && ts > 0 {
ago := humanize.RelTime(time.UnixMilli(ts), time.Now(), "ago", "from now")
return fmt.Sprintf("%s (last seen %s)", name, ago)
}
- return name
+ return name // this case won't come cuz lastSeenStr is never called for metrics in nonExistentMetrics
}
if len(missingMetrics) == 1 {
- return nil, errors.NewNotFoundf(errors.CodeNotFound, "no data found for the metric %s in the query time range", lastSeenStr(missingMetrics[0]))
+ dormantMetricsWarningMsg = fmt.Sprintf("no data found for the metric %s in the query time range", lastSeenStr(missingMetrics[0]))
+ } else {
+ parts := make([]string, len(missingMetrics))
+ for i, m := range missingMetrics {
+ parts[i] = lastSeenStr(m)
+ }
+ dormantMetricsWarningMsg = fmt.Sprintf("no data found for the following metrics in the query time range: %s", strings.Join(parts, ", "))
}
- parts := make([]string, len(missingMetrics))
- for i, m := range missingMetrics {
- parts[i] = lastSeenStr(m)
+ }
+ preseededResults := make(map[string]any)
+ for _, name := range missingMetricQueries { // at this point missing metrics will not have any non existent metrics, only normal ones
+ switch req.RequestType {
+ case qbtypes.RequestTypeTimeSeries:
+ preseededResults[name] = &qbtypes.TimeSeriesData{QueryName: name}
+ case qbtypes.RequestTypeScalar:
+ preseededResults[name] = &qbtypes.ScalarData{QueryName: name}
+ case qbtypes.RequestTypeRaw:
+ preseededResults[name] = &qbtypes.RawData{QueryName: name}
}
- return nil, errors.NewNotFoundf(errors.CodeNotFound, "no data found for the following metrics in the query time range: %s", strings.Join(parts, ", "))
}
- qbResp, qbErr := q.run(ctx, orgID, queries, req, steps, event)
+ qbResp, qbErr := q.run(ctx, orgID, queries, req, steps, event, preseededResults)
if qbResp != nil {
qbResp.QBEvent = event
if len(intervalWarnings) != 0 && req.RequestType == qbtypes.RequestTypeTimeSeries {
@@ -440,6 +473,14 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
}
}
}
+ if dormantMetricsWarningMsg != "" {
+ if qbResp.Warning == nil {
+ qbResp.Warning = &qbtypes.QueryWarnData{}
+ }
+ qbResp.Warning.Warnings = append(qbResp.Warning.Warnings, qbtypes.QueryWarnDataAdditional{
+ Message: dormantMetricsWarningMsg,
+ })
+ }
}
return qbResp, qbErr
}
@@ -516,7 +557,7 @@ func (q *querier) QueryRawStream(ctx context.Context, orgID valuer.UUID, req *qb
})
queries[spec.Name] = bq
- qbResp, qbErr := q.run(ctx, orgID, queries, req, nil, event)
+ qbResp, qbErr := q.run(ctx, orgID, queries, req, nil, event, nil)
if qbErr != nil {
client.Error <- qbErr
return
@@ -545,6 +586,7 @@ func (q *querier) run(
req *qbtypes.QueryRangeRequest,
steps map[string]qbtypes.Step,
qbEvent *qbtypes.QBEvent,
+ preseededResults map[string]any,
) (*qbtypes.QueryRangeResponse, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.PanelType: qbEvent.PanelType,
@@ -630,6 +672,7 @@ func (q *querier) run(
}
}
+ gomaps.Copy(results, preseededResults)
processedResults, err := q.postProcessResults(ctx, results, req)
if err != nil {
return nil, err
diff --git a/tests/integration/fixtures/querier.py b/tests/integration/fixtures/querier.py
index 9d24579dfd..70934c1213 100644
--- a/tests/integration/fixtures/querier.py
+++ b/tests/integration/fixtures/querier.py
@@ -247,6 +247,14 @@ def get_scalar_value(response_json: Dict, query_name: str) -> Optional[float]:
return None
+def get_all_warnings(response_json: Dict) -> List[Dict]:
+ return response_json.get("data", {}).get("warning", {}).get("warnings", [])
+
+
+def get_error_message(response_json: Dict) -> str:
+ return response_json.get("error", {}).get("message", "")
+
+
def compare_values(
v1: float,
v2: float,
diff --git a/tests/integration/src/querier/03_metrics.py b/tests/integration/src/querier/03_metrics.py
index baf593e0b0..0e2b7c293e 100644
--- a/tests/integration/src/querier/03_metrics.py
+++ b/tests/integration/src/querier/03_metrics.py
@@ -14,6 +14,8 @@ from fixtures.querier import (
find_named_result,
index_series_by_label,
make_query_request,
+ get_all_warnings,
+ get_error_message,
)
from fixtures.utils import get_testdata_file_path
@@ -586,7 +588,7 @@ def test_metrics_fill_formula_with_group_by(
)
-def test_histogram_p90_returns_404_outside_data_window(
+def test_histogram_p90_returns_warning_outside_data_window(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
@@ -620,4 +622,39 @@ def test_histogram_p90_returns_404_outside_data_window(
start_15m = int((now - timedelta(minutes=15)).timestamp() * 1000)
response = make_query_request(signoz, token, start_15m, end_ms, [query])
+ assert response.status_code == HTTPStatus.OK
+ data = response.json()
+ warnings = get_all_warnings(data)
+ assert len(warnings) == 1
+ assert warnings[0]["message"].startswith(
+ f"no data found for the metric {metric_name}"
+ )
+
+
+def test_non_existent_metrics_returns_404(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+) -> None:
+
+ now = datetime.now(tz=timezone.utc).replace(second=0, microsecond=0)
+ metric_name = "whatevergoennnsgoeshere"
+
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ query = build_builder_query(
+ "A",
+ metric_name,
+ "doesnotreallymatter",
+ "sum",
+ )
+
+ end_ms = int(now.timestamp() * 1000)
+
+ start_2h = int((now - timedelta(hours=2)).timestamp() * 1000)
+ response = make_query_request(signoz, token, start_2h, end_ms, [query])
assert response.status_code == HTTPStatus.NOT_FOUND
+
+ assert (
+ get_error_message(response.json())
+ == "could not find the metric whatevergoennnsgoeshere"
+ )