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.

chore: return original error message with hints for invalid promql query (#10034)

Srikanth Chekuriee734cf78cf9
diff --git a/pkg/querier/promql_query.go b/pkg/querier/promql_query.go
index f24ca55906..0a6fd44f43 100644
--- a/pkg/querier/promql_query.go
+++ b/pkg/querier/promql_query.go
@@ -5,6 +5,7 @@ import (
"context"
"fmt"
"log/slog"
+ "regexp"
"sort"
"strings"
"text/template"
@@ -19,6 +20,50 @@ import (
"github.com/prometheus/prometheus/promql/parser"
)
+// unquotedDottedNamePattern matches unquoted identifiers containing dots
+// that appear in metric or label name positions. This helps detect queries
+// using the old syntax that needs migration to UTF-8 quoted syntax.
+// Examples it matches: k8s.pod.name, deployment.environment, http.status_code
+var unquotedDottedNamePattern = regexp.MustCompile(`(?:^|[{,(\s])([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_]+)+)(?:[}\s,=!~)\[]|$)`)
+
+// quotedMetricOutsideBracesPattern matches the incorrect syntax where a quoted
+// metric name appears outside of braces followed by a selector block.
+// Example: "kube_pod_status_ready_time"{"condition"="true"}
+// This is a common mistake when migrating to UTF-8 syntax.
+var quotedMetricOutsideBracesPattern = regexp.MustCompile(`"([^"]+)"\s*\{`)
+
+// enhancePromQLError adds helpful context to PromQL parse errors,
+// particularly for UTF-8 syntax migration issues where metric and label
+// names containing dots need to be quoted.
+func enhancePromQLError(query string, parseErr error) error {
+ errMsg := parseErr.Error()
+
+ if matches := quotedMetricOutsideBracesPattern.FindStringSubmatch(query); len(matches) > 1 {
+ metricName := matches[1]
+ return errors.NewInvalidInputf(
+ errors.CodeInvalidInput,
+ "invalid promql query: %s. Hint: The metric name should be inside the braces. Use {\"__name__\"=\"%s\", ...} or {\"%s\", ...} instead of \"%s\"{...}",
+ errMsg,
+ metricName,
+ metricName,
+ metricName,
+ )
+ }
+
+ if matches := unquotedDottedNamePattern.FindStringSubmatch(query); len(matches) > 1 {
+ dottedName := matches[1]
+ return errors.NewInvalidInputf(
+ errors.CodeInvalidInput,
+ "invalid promql query: %s. Hint: Metric and label names containing dots require quoted notation in the new UTF-8 syntax, e.g., use \"%s\" instead of %s",
+ errMsg,
+ dottedName,
+ dottedName,
+ )
+ }
+
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid promql query: %s", errMsg)
+}
+
type promqlQuery struct {
logger *slog.Logger
promEngine prometheus.Prometheus
@@ -81,7 +126,7 @@ func (q *promqlQuery) removeAllVarMatchers(query string, vars map[string]qbv5.Va
expr, err := parser.ParseExpr(query)
if err != nil {
- return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid promql query %q", query)
+ return "", enhancePromQLError(query, err)
}
// Create visitor and walk the AST
@@ -161,7 +206,7 @@ func (q *promqlQuery) Execute(ctx context.Context) (*qbv5.Result, error) {
)
if err != nil {
- return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid promql query %q", query)
+ return nil, enhancePromQLError(query, err)
}
res := qry.Exec(ctx)
diff --git a/pkg/querier/promql_query_test.go b/pkg/querier/promql_query_test.go
index b289f8ceb3..2662344752 100644
--- a/pkg/querier/promql_query_test.go
+++ b/pkg/querier/promql_query_test.go
@@ -2,8 +2,10 @@ package querier
import (
"log/slog"
+ "strings"
"testing"
+ "github.com/SigNoz/signoz/pkg/errors"
qbv5 "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/stretchr/testify/assert"
)
@@ -172,3 +174,268 @@ func TestRemoveAllVarMatchers(t *testing.T) {
})
}
}
+
+func TestEnhancePromQLError(t *testing.T) {
+ parseErr := errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "unexpected character: '.' at position 12")
+
+ t.Run("dotted name patterns", func(t *testing.T) {
+ tests := []struct {
+ name string
+ query string
+ wantDottedNameHint bool
+ wantDottedNameExample string
+ }{
+ {
+ name: "query with unquoted dotted metric name",
+ query: `sum(rate(k8s.container.restarts[5m]))`,
+ wantDottedNameHint: true,
+ wantDottedNameExample: "k8s.container.restarts",
+ },
+ {
+ name: "query with unquoted dotted label in group by",
+ query: `sum by (k8s.pod.name) (rate(requests_total[5m]))`,
+ wantDottedNameHint: true,
+ wantDottedNameExample: "k8s.pod.name",
+ },
+ {
+ name: "query with unquoted dotted label in filter",
+ query: `requests_total{k8s.namespace.name="default"}`,
+ wantDottedNameHint: true,
+ wantDottedNameExample: "k8s.namespace.name",
+ },
+ {
+ name: "query with multiple unquoted dotted names",
+ query: `sum by (k8s.pod.name, deployment.environment) (increase(k8s.container.restarts[15m]))`,
+ wantDottedNameHint: true,
+ wantDottedNameExample: "k8s.pod.name", // should match first one
+ },
+ {
+ name: "query without dotted names - no hint",
+ query: `sum(rate(http_requests_total[5m]))`,
+ wantDottedNameHint: false,
+ },
+ {
+ name: "query with properly quoted dotted names - no hint",
+ query: `sum(rate({"k8s.container.restarts"}[5m]))`,
+ wantDottedNameHint: false,
+ },
+ {
+ name: "query with dotted name inside regex string - no hint",
+ query: `requests_total{pod=~"k8s.pod.name.*"}`,
+ wantDottedNameHint: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := enhancePromQLError(tt.query, parseErr)
+ errMsg := err.Error()
+
+ assert.True(t, strings.Contains(errMsg, parseErr.Error()),
+ "error should contain original parse error message")
+
+ if tt.wantDottedNameHint {
+ assert.True(t, strings.Contains(errMsg, "Hint:"),
+ "error should contain hint for dotted name query")
+ assert.True(t, strings.Contains(errMsg, "UTF-8 syntax"),
+ "error should mention UTF-8 syntax")
+ assert.True(t, strings.Contains(errMsg, tt.wantDottedNameExample),
+ "error should contain the dotted name example: %s", tt.wantDottedNameExample)
+ } else {
+ assert.False(t, strings.Contains(errMsg, "Hint:"),
+ "error should not contain hint for non-dotted-name query")
+ }
+ })
+ }
+ })
+
+ t.Run("quoted metric outside braces patterns", func(t *testing.T) {
+ tests := []struct {
+ name string
+ query string
+ wantHint bool
+ wantMetricInHint string
+ }{
+ {
+ name: "quoted metric name followed by selector",
+ query: `"kube_pod_status_ready_time"{"condition"="true"}`,
+ wantHint: true,
+ wantMetricInHint: "kube_pod_status_ready_time",
+ },
+ {
+ name: "quoted metric with space before brace",
+ query: `"kube_pod_labels" {"label"!=""}`,
+ wantHint: true,
+ wantMetricInHint: "kube_pod_labels",
+ },
+ {
+ name: "complex query with quoted metric outside braces",
+ query: `min by (namespace) ("kube_pod_status_ready_time"{"condition"="true"})`,
+ wantHint: true,
+ wantMetricInHint: "kube_pod_status_ready_time",
+ },
+ {
+ name: "label_replace with quoted metric outside braces",
+ query: `label_replace("kube_pod_labels"{"label_cnpg_io_cluster"!=""}, "cluster","$1","label","(.+)")`,
+ wantHint: true,
+ wantMetricInHint: "kube_pod_labels",
+ },
+ {
+ name: "correctly formatted query - no hint",
+ query: `{"kube_pod_status_ready_time", condition="true"}`,
+ wantHint: false,
+ },
+ {
+ name: "old syntax without quotes - no hint for this pattern",
+ query: `kube_pod_status_ready_time{condition="true"}`,
+ wantHint: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := enhancePromQLError(tt.query, parseErr)
+ errMsg := err.Error()
+
+ assert.True(t, strings.Contains(errMsg, parseErr.Error()),
+ "error should contain original parse error message")
+
+ if tt.wantHint {
+ assert.True(t, strings.Contains(errMsg, "Hint:"),
+ "error should contain hint")
+ assert.True(t, strings.Contains(errMsg, "inside the braces"),
+ "error should mention putting metric inside braces")
+ assert.True(t, strings.Contains(errMsg, tt.wantMetricInHint),
+ "error should contain the metric name: %s", tt.wantMetricInHint)
+ }
+ })
+ }
+ })
+}
+
+func TestUnquotedDottedNamePattern(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ expected string // empty string means no match expected
+ }{
+ {
+ name: "metric name at start",
+ input: "k8s.pod.name",
+ expected: "k8s.pod.name",
+ },
+ {
+ name: "label in group by clause",
+ input: "sum by (k8s.pod.name) (rate(x[5m]))",
+ expected: "k8s.pod.name",
+ },
+ {
+ name: "label in filter",
+ input: "metric{k8s.namespace.name=\"default\"}",
+ expected: "k8s.namespace.name",
+ },
+ {
+ name: "metric with underscore and dots",
+ input: "http_server.request.duration",
+ expected: "http_server.request.duration",
+ },
+ {
+ name: "quoted metric name - no match",
+ input: `{"k8s.pod.name"}`,
+ expected: "",
+ },
+ {
+ name: "inside regex string - no match",
+ input: `{pod=~"k8s.pod.name.*"}`,
+ expected: "",
+ },
+ {
+ name: "simple metric without dots - no match",
+ input: "http_requests_total",
+ expected: "",
+ },
+ {
+ name: "single dot only - no match",
+ input: "a.b",
+ expected: "a.b",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ matches := unquotedDottedNamePattern.FindStringSubmatch(tt.input)
+ if tt.expected == "" {
+ assert.True(t, len(matches) < 2 || matches[1] == "",
+ "expected no match for input %q but got %v", tt.input, matches)
+ } else {
+ assert.True(t, len(matches) >= 2,
+ "expected match for input %q but got none", tt.input)
+ if len(matches) >= 2 {
+ assert.Equal(t, tt.expected, matches[1],
+ "unexpected match for input %q", tt.input)
+ }
+ }
+ })
+ }
+}
+
+func TestQuotedMetricOutsideBracesPattern(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ expected string // empty string means no match expected
+ }{
+ {
+ name: "quoted metric followed by braces",
+ input: `"kube_pod_status_ready_time"{"condition"="true"}`,
+ expected: "kube_pod_status_ready_time",
+ },
+ {
+ name: "quoted metric with space before brace",
+ input: `"kube_pod_labels" {"label"!=""}`,
+ expected: "kube_pod_labels",
+ },
+ {
+ name: "quoted metric in label_replace",
+ input: `label_replace("kube_pod_labels"{"x"="y"}, "a","b","c","d")`,
+ expected: "kube_pod_labels",
+ },
+ {
+ name: "quoted metric with dots",
+ input: `"k8s.container.restarts"{"pod"="test"}`,
+ expected: "k8s.container.restarts",
+ },
+ {
+ name: "correct UTF-8 syntax - no match",
+ input: `{"kube_pod_status_ready_time", condition="true"}`,
+ expected: "",
+ },
+ {
+ name: "old syntax without quotes - no match",
+ input: `kube_pod_status_ready_time{condition="true"}`,
+ expected: "",
+ },
+ {
+ name: "quoted string in label value - no match",
+ input: `metric{label="value"}{other="x"}`,
+ expected: "",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ matches := quotedMetricOutsideBracesPattern.FindStringSubmatch(tt.input)
+ if tt.expected == "" {
+ assert.True(t, len(matches) < 2 || matches[1] == "",
+ "expected no match for input %q but got %v", tt.input, matches)
+ } else {
+ assert.True(t, len(matches) >= 2,
+ "expected match for input %q but got none", tt.input)
+ if len(matches) >= 2 {
+ assert.Equal(t, tt.expected, matches[1],
+ "unexpected match for input %q", tt.input)
+ }
+ }
+ })
+ }
+}