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: Make PromQL queries work with dynamic variable ALL section (#9607)
Nikhil Mantric7c2d2a7ef42
diff --git a/pkg/querier/promql_query.go b/pkg/querier/promql_query.goindex e39ce65268..f24ca55906 100644--- a/pkg/querier/promql_query.go+++ b/pkg/querier/promql_query.go@@ -16,6 +16,7 @@ import (qbv5 "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/telemetrytypes""github.com/prometheus/prometheus/promql"+ "github.com/prometheus/prometheus/promql/parser")type promqlQuery struct {@@ -59,8 +60,50 @@ func (q *promqlQuery) Window() (uint64, uint64) {return q.tr.From, q.tr.To}+// removeAllVarMatchers removes label matchers from a PromQL query that reference variables with __all__ value.+// This method parses the query, walks the AST to remove matching matchers, and returns the modified query string.+// If parsing or walking fails, it returns an error.+func (q *promqlQuery) removeAllVarMatchers(query string, vars map[string]qbv5.VariableItem) (string, error) {+ // Find all variables that have __all__ value+ allVars := make(map[string]bool)+ for k, v := range vars {+ if v.Type == qbv5.DynamicVariableType {+ if allVal, ok := v.Value.(string); ok && allVal == "__all__" {+ allVars[k] = true+ }+ }+ }++ // If no variables have __all__ value, return the query unchanged+ if len(allVars) == 0 {+ return query, nil+ }++ expr, err := parser.ParseExpr(query)+ if err != nil {+ return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid promql query %q", query)+ }++ // Create visitor and walk the AST+ visitor := &allVarRemover{allVars: allVars}+ if err := parser.Walk(visitor, expr, nil); err != nil {+ q.logger.ErrorContext(context.TODO(), "unexpected error while removing __all__ variable matchers", "error", err, "query", query)+ return "", errors.WrapInternalf(err, errors.CodeInternal, "error while removing __all__ variable matchers")+ }++ // Convert the modified AST back to a string+ return expr.String(), nil+}+// TODO(srikanthccv): cleanup the templating logicfunc (q *promqlQuery) renderVars(query string, vars map[string]qbv5.VariableItem, start, end uint64) (string, error) {+ // First, remove label matchers that use variables with __all__ value.+ // This must happen before variable substitution so we can detect variable references+ // in their original form ($var, {{var}}, [[var]]).+ query, err := q.removeAllVarMatchers(query, vars)+ if err != nil {+ return "", err+ }varsData := map[string]any{}for k, v := range vars {varsData[k] = formatValueForProm(v.Value)@@ -83,7 +126,7 @@ func (q *promqlQuery) renderVars(query string, vars map[string]qbv5.VariableItem}tmpl := template.New("promql-query")- tmpl, err := tmpl.Parse(query)+ tmpl, err = tmpl.Parse(query)if err != nil {return "", errors.WrapInternalf(err, errors.CodeInternal, "error while replacing template variables")}diff --git a/pkg/querier/promql_query_parser.go b/pkg/querier/promql_query_parser.gonew file mode 100644index 0000000000..483e30712e--- /dev/null+++ b/pkg/querier/promql_query_parser.go@@ -0,0 +1,66 @@+package querier++import (+ "strings"++ "github.com/prometheus/prometheus/model/labels"+ "github.com/prometheus/prometheus/promql/parser"+)++// allVarRemover is a visitor that removes label matchers referencing variables with __all__ value.+// This must run before variable substitution so it can detect variable references in their original form.+type allVarRemover struct {+ allVars map[string]bool // map of variable names that have __all__ value+}++// Visit implements the parser.Visitor interface to traverse and modify the PromQL AST.+func (v *allVarRemover) Visit(node parser.Node, path []parser.Node) (parser.Visitor, error) {+ if node == nil {+ return v, nil+ }+ switch n := node.(type) {+ case *parser.VectorSelector:+ // Remove matchers that reference variables with __all__ value+ var keptMatchers []*labels.Matcher+ for _, matcher := range n.LabelMatchers {+ if !v.shouldRemoveMatcher(matcher.Value) {+ keptMatchers = append(keptMatchers, matcher)+ }+ }+ // Update the label matchers+ n.LabelMatchers = keptMatchers+ }+ return v, nil+}++// shouldRemoveMatcher checks if a matcher value contains a variable reference that has __all__ value.+func (v *allVarRemover) shouldRemoveMatcher(value string) bool {++ // Check for $var pattern+ if strings.Contains(value, "$") {+ keyValue := strings.TrimPrefix(value, "$")+ if _, ok := v.allVars[keyValue]; ok {+ return true+ }+ }++ // Check for {{var}} pattern+ if strings.Contains(value, "{{") {+ keyValue := strings.TrimPrefix(value, "{{")+ keyValue = strings.TrimSuffix(keyValue, "}}")+ if _, ok := v.allVars[keyValue]; ok {+ return true+ }+ }++ // Check for [[var]] pattern+ if strings.Contains(value, "[[") {+ keyValue := strings.TrimPrefix(value, "[[")+ keyValue = strings.TrimSuffix(keyValue, "]]")+ if _, ok := v.allVars[keyValue]; ok {+ return true+ }+ }++ return false+}diff --git a/pkg/querier/promql_query_parser_test.go b/pkg/querier/promql_query_parser_test.gonew file mode 100644index 0000000000..e0d7a1d143--- /dev/null+++ b/pkg/querier/promql_query_parser_test.go@@ -0,0 +1,85 @@+package querier++import (+ "testing"++ "github.com/stretchr/testify/assert"+)++func TestShouldRemoveMatcher(t *testing.T) {+ tests := []struct {+ name string+ value string+ allVars map[string]bool+ expected bool+ }{+ {+ name: "$var pattern match",+ value: "$host.name",+ allVars: map[string]bool{"host.name": true},+ expected: true,+ },+ {+ name: "{{var}} pattern match",+ value: "{{host.name}}",+ allVars: map[string]bool{"host.name": true},+ expected: true,+ },+ {+ name: "[[var]] pattern match",+ value: "[[host.name]]",+ allVars: map[string]bool{"host.name": true},+ expected: true,+ },+ {+ name: "variable not in allVars",+ value: "$other.var",+ allVars: map[string]bool{"host.name": true},+ expected: false,+ },+ {+ name: "no variable pattern in value",+ value: "host.name",+ allVars: map[string]bool{"host.name": true},+ expected: false,+ },+ {+ name: "variable in middle of string (not at start, won't match)",+ value: "prefix$host.namesuffix",+ allVars: map[string]bool{"host.name": true},+ expected: false, // TrimPrefix only works if $ is at the start+ },+ {+ name: "empty allVars",+ value: "$host.name",+ allVars: map[string]bool{},+ expected: false,+ },+ {+ name: "incomplete {{var}} pattern (missing closing, still matches)",+ value: "{{host.name",+ allVars: map[string]bool{"host.name": true},+ expected: true, // TrimPrefix removes {{, TrimSuffix does nothing, checks "host.name"+ },+ {+ name: "mixed patterns (only first pattern at start matches)",+ value: "$host.name{{env}}",+ allVars: map[string]bool{"host.name": true},+ expected: false, // TrimPrefix removes $, checks "host.name{{env}}" which is not in allVars+ },+ {+ name: "partial match should not match for {{var}}",+ value: "{{host.name.suffix}}",+ allVars: map[string]bool{"host.name": true},+ expected: false,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ remover := &allVarRemover{allVars: tt.allVars}+ result := remover.shouldRemoveMatcher(tt.value)+ assert.Equal(t, tt.expected, result, "shouldRemoveMatcher(%q) with allVars=%v", tt.value, tt.allVars)+ })+ }+}diff --git a/pkg/querier/promql_query_test.go b/pkg/querier/promql_query_test.gonew file mode 100644index 0000000000..b289f8ceb3--- /dev/null+++ b/pkg/querier/promql_query_test.go@@ -0,0 +1,174 @@+package querier++import (+ "log/slog"+ "testing"++ qbv5 "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"+ "github.com/stretchr/testify/assert"+)++func TestRemoveAllVarMatchers(t *testing.T) {+ logger := slog.Default()+ q := &promqlQuery{logger: logger}++ tests := []struct {+ name string+ query string+ vars map[string]qbv5.VariableItem+ expected string+ expectErr bool+ }{+ {+ name: "remove $var pattern with __all__",+ query: `sum(rate({__name__="system.cpu.time", "host.name"=~"$host.name"}[5m]))`,+ vars: map[string]qbv5.VariableItem{+ "host.name": {+ Type: qbv5.DynamicVariableType,+ Value: "__all__",+ },+ },+ expected: `sum(rate({__name__="system.cpu.time"}[5m]))`,+ expectErr: false,+ },+ {+ name: "remove {{var}} pattern with __all__",+ query: `sum(rate({__name__="system.cpu.time", "host.name"=~"{{host.name}}"}[5m]))`,+ vars: map[string]qbv5.VariableItem{+ "host.name": {+ Type: qbv5.DynamicVariableType,+ Value: "__all__",+ },+ },+ expected: `sum(rate({__name__="system.cpu.time"}[5m]))`,+ expectErr: false,+ },+ {+ name: "remove [[var]] pattern with __all__",+ query: `sum(rate({__name__="system.cpu.time", "host.name"=~"[[host.name]]"}[5m]))`,+ vars: map[string]qbv5.VariableItem{+ "host.name": {+ Type: qbv5.DynamicVariableType,+ Value: "__all__",+ },+ },+ expected: `sum(rate({__name__="system.cpu.time"}[5m]))`,+ expectErr: false,+ },+ {+ name: "multiple variables, one with __all__",+ query: `sum(rate({__name__="system.cpu.time", "host.name"=~"$host.name", "env"="$env"}[5m]))`,+ vars: map[string]qbv5.VariableItem{+ "host.name": {+ Type: qbv5.DynamicVariableType,+ Value: "__all__",+ },+ "env": {+ Type: qbv5.DynamicVariableType,+ Value: "production",+ },+ },+ expected: `sum(rate({__name__="system.cpu.time",env="$env"}[5m]))`,+ expectErr: false,+ },+ {+ name: "no __all__ variables, query unchanged",+ query: `sum(rate({__name__="system.cpu.time", "host.name"=~"$host.name"}[5m]))`,+ vars: map[string]qbv5.VariableItem{+ "host.name": {+ Type: qbv5.DynamicVariableType,+ Value: "host1",+ },+ },+ expected: `sum(rate({__name__="system.cpu.time", "host.name"=~"$host.name"}[5m]))`,+ expectErr: false,+ },+ {+ name: "non-dynamic variable type, not removed",+ query: `sum(rate({__name__="system.cpu.time", "host.name"=~"$host.name"}[5m]))`,+ vars: map[string]qbv5.VariableItem{+ "host.name": {+ Type: qbv5.QueryVariableType,+ Value: "__all__",+ },+ },+ expected: `sum(rate({__name__="system.cpu.time", "host.name"=~"$host.name"}[5m]))`,+ expectErr: false,+ },+ {+ name: "invalid PromQL query",+ query: `invalid promql query syntax {`,+ vars: map[string]qbv5.VariableItem{+ "host.name": {+ Type: qbv5.DynamicVariableType,+ Value: "__all__",+ },+ },+ expected: "",+ expectErr: true,+ },+ {+ name: "invalid PromQL query with mismatched brackets",+ query: `sum(rate({__name__="system.cpu.time", "host.name"=~"$host.name"}[5m]`,+ vars: map[string]qbv5.VariableItem{+ "host.name": {+ Type: qbv5.DynamicVariableType,+ Value: "__all__",+ },+ },+ expected: "",+ expectErr: true,+ },+ {+ name: "empty vars map",+ query: `sum(rate({__name__="system.cpu.time", "host.name"=~"$host.name"}[5m]))`,+ vars: map[string]qbv5.VariableItem{},+ expected: `sum(rate({__name__="system.cpu.time", "host.name"=~"$host.name"}[5m]))`,+ expectErr: false,+ },+ {+ name: "multiple matchers with __all__ variable",+ query: `sum(rate({__name__="system.cpu.time", "host.name"=~"$host.name", "env"="$env", "region"=~"$region"}[5m]))`,+ vars: map[string]qbv5.VariableItem{+ "host.name": {+ Type: qbv5.DynamicVariableType,+ Value: "__all__",+ },+ "env": {+ Type: qbv5.DynamicVariableType,+ Value: "__all__",+ },+ "region": {+ Type: qbv5.DynamicVariableType,+ Value: "us-east",+ },+ },+ expected: `sum(rate({__name__="system.cpu.time",region=~"$region"}[5m]))`,+ expectErr: false,+ },+ {+ name: "__all__ value not string type",+ query: `sum(rate({__name__="system.cpu.time", "host.name"=~"$host.name"}[5m]))`,+ vars: map[string]qbv5.VariableItem{+ "host.name": {+ Type: qbv5.DynamicVariableType,+ Value: 123, // Not a string+ },+ },+ expected: `sum(rate({__name__="system.cpu.time", "host.name"=~"$host.name"}[5m]))`,+ expectErr: false,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ result, err := q.removeAllVarMatchers(tt.query, tt.vars)+ if tt.expectErr {+ assert.Error(t, err)+ } else {+ assert.NoError(t, err)+ assert.Equal(t, tt.expected, result, "removeAllVarMatchers(%q) with vars=%v", tt.query, tt.vars)+ }+ })+ }+}