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(alertmanager): treat missing dotted labels as nil in downtime scope (#13118)

praneeth-signoz50b48649ddac
diff --git a/pkg/alertmanager/nfmanager/rulebasednotification/provider.go b/pkg/alertmanager/nfmanager/rulebasednotification/provider.go
index 10160fe71e..4ba581faa8 100644
--- a/pkg/alertmanager/nfmanager/rulebasednotification/provider.go
+++ b/pkg/alertmanager/nfmanager/rulebasednotification/provider.go
@@ -8,7 +8,6 @@ import (
"github.com/SigNoz/signoz/pkg/alertmanager/nfmanager"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
- "github.com/expr-lang/expr"
"github.com/prometheus/common/model"
"github.com/SigNoz/signoz/pkg/factory"
@@ -219,8 +218,9 @@ func (r *provider) Match(ctx context.Context, orgID string, ruleID string, set m
return matchedChannels, nil
}
+ env := r.convertLabelSetToEnv(ctx, set)
for _, route := range expressionRoutes {
- evaluateExpr, err := r.evaluateExpr(ctx, route.Expression, set)
+ evaluateExpr, err := alertmanagertypes.EvalExpression(route.Expression, env)
if err != nil {
//nolint:sloglint
r.settings.Logger().WarnContext(ctx, "failed to evaluate route policy expression", errors.Attr(err), slog.String("rule.id", ruleID))
@@ -243,23 +243,3 @@ func (r *provider) convertLabelSetToEnv(ctx context.Context, labelSet model.Labe
}
return env
}
-
-func (r *provider) evaluateExpr(ctx context.Context, expression string, labelSet model.LabelSet) (bool, error) {
- env := r.convertLabelSetToEnv(ctx, labelSet)
-
- program, err := expr.Compile(expression, expr.Env(env), expr.AllowUndefinedVariables())
- if err != nil {
- return false, errors.NewInternalf(errors.CodeInternal, "error compiling route policy %s: %v", expression, err)
- }
-
- output, err := expr.Run(program, env)
- if err != nil {
- return false, errors.NewInternalf(errors.CodeInternal, "error running route policy %s: %v", expression, err)
- }
-
- if boolVal, ok := output.(bool); ok {
- return boolVal, nil
- }
-
- return false, errors.NewInternalf(errors.CodeInternal, "error in evaluating route policy %s: %v", expression, err)
-}
diff --git a/pkg/alertmanager/nfmanager/rulebasednotification/provider_test.go b/pkg/alertmanager/nfmanager/rulebasednotification/provider_test.go
index d2da02a27a..cd46710e9f 100644
--- a/pkg/alertmanager/nfmanager/rulebasednotification/provider_test.go
+++ b/pkg/alertmanager/nfmanager/rulebasednotification/provider_test.go
@@ -277,400 +277,6 @@ func TestProvider_ConcurrentAccess(t *testing.T) {
wg.Wait()
}
-func TestProvider_EvaluateExpression(t *testing.T) {
- provider := &provider{
- settings: factory.NewScopedProviderSettings(createTestProviderSettings(), "provider_test"),
- }
-
- tests := []struct {
- name string
- expression string
- labelSet model.LabelSet
- expected bool
- }{
- {
- name: "simple equality check - match",
- expression: `threshold.name == 'auth' && ruleId == 'rule1'`,
- labelSet: model.LabelSet{
- "threshold.name": "auth",
- "ruleId": "rule1",
- },
- expected: true,
- },
- {
- name: "simple equality check - match",
- expression: `threshold.name = 'auth' AND ruleId = 'rule1'`,
- labelSet: model.LabelSet{
- "threshold.name": "auth",
- "ruleId": "rule1",
- },
- expected: true,
- },
- {
- name: "simple equality check - no match",
- expression: `service == "payment"`,
- labelSet: model.LabelSet{
- "service": "auth",
- "env": "production",
- },
- expected: false,
- },
- {
- name: "simple equality check - no match",
- expression: `service = "payment"`,
- labelSet: model.LabelSet{
- "service": "auth",
- "env": "production",
- },
- expected: false,
- },
- {
- name: "multiple conditions with AND - both match",
- expression: `service == "auth" && env == "production"`,
- labelSet: model.LabelSet{
- "service": "auth",
- "env": "production",
- },
- expected: true,
- },
- {
- name: "multiple conditions with AND - both match",
- expression: `service = "auth" AND env = "production"`,
- labelSet: model.LabelSet{
- "service": "auth",
- "env": "production",
- },
- expected: true,
- },
- {
- name: "multiple conditions with AND - one doesn't match",
- expression: `service == "auth" && env == "staging"`,
- labelSet: model.LabelSet{
- "service": "auth",
- "env": "production",
- },
- expected: false,
- },
- {
- name: "multiple conditions with AND - one doesn't match",
- expression: `service = "auth" AND env = "staging"`,
- labelSet: model.LabelSet{
- "service": "auth",
- "env": "production",
- },
- expected: false,
- },
- {
- name: "multiple conditions with OR - one matches",
- expression: `service == "payment" || env == "production"`,
- labelSet: model.LabelSet{
- "service": "auth",
- "env": "production",
- },
- expected: true,
- },
- {
- name: "multiple conditions with OR - one matches",
- expression: `service = "payment" OR env = "production"`,
- labelSet: model.LabelSet{
- "service": "auth",
- "env": "production",
- },
- expected: true,
- },
- {
- name: "multiple conditions with OR - none match",
- expression: `service == "payment" || env == "staging"`,
- labelSet: model.LabelSet{
- "service": "auth",
- "env": "production",
- },
- expected: false,
- },
- {
- name: "multiple conditions with OR - none match",
- expression: `service = "payment" OR env = "staging"`,
- labelSet: model.LabelSet{
- "service": "auth",
- "env": "production",
- },
- expected: false,
- },
- {
- name: "in operator - value in list",
- expression: `service in ["auth", "payment", "notification"]`,
- labelSet: model.LabelSet{
- "service": "auth",
- },
- expected: true,
- },
- {
- name: "in operator - value in list",
- expression: `service IN ["auth", "payment", "notification"]`,
- labelSet: model.LabelSet{
- "service": "auth",
- },
- expected: true,
- },
- {
- name: "in operator - value not in list",
- expression: `service in ["payment", "notification"]`,
- labelSet: model.LabelSet{
- "service": "auth",
- },
- expected: false,
- },
- {
- name: "in operator - value not in list",
- expression: `service IN ["payment", "notification"]`,
- labelSet: model.LabelSet{
- "service": "auth",
- },
- expected: false,
- },
- {
- name: "contains operator - substring match",
- expression: `host contains "prod"`,
- labelSet: model.LabelSet{
- "host": "prod-server-01",
- },
- expected: true,
- },
- {
- name: "contains operator - substring match",
- expression: `host CONTAINS "prod"`,
- labelSet: model.LabelSet{
- "host": "prod-server-01",
- },
- expected: true,
- },
- {
- name: "contains operator - no substring match",
- expression: `host contains "staging"`,
- labelSet: model.LabelSet{
- "host": "prod-server-01",
- },
- expected: false,
- },
- {
- name: "contains operator - no substring match",
- expression: `host CONTAINS "staging"`,
- labelSet: model.LabelSet{
- "host": "prod-server-01",
- },
- expected: false,
- },
- {
- name: "complex expression with parentheses",
- expression: `(service == "auth" && env == "production") || critical == "true"`,
- labelSet: model.LabelSet{
- "service": "payment",
- "env": "staging",
- "critical": "true",
- },
- expected: true,
- },
- {
- name: "complex expression with parentheses",
- expression: `(service = "auth" AND env = "production") OR critical = "true"`,
- labelSet: model.LabelSet{
- "service": "payment",
- "env": "staging",
- "critical": "true",
- },
- expected: true,
- },
- {
- name: "missing label key",
- expression: `"missing_key" == "value"`,
- labelSet: model.LabelSet{
- "service": "auth",
- },
- expected: false,
- },
- {
- name: "missing label key",
- expression: `"missing_key" = "value"`,
- labelSet: model.LabelSet{
- "service": "auth",
- },
- expected: false,
- },
- {
- name: "rule-based expression with threshold name and ruleId",
- expression: `'threshold.name' == "high-cpu" && ruleId == "rule-123"`,
- labelSet: model.LabelSet{
- "threshold.name": "high-cpu",
- "ruleId": "rule-123",
- "service": "auth",
- },
- expected: false, //no commas
- },
- {
- name: "rule-based expression with threshold name and ruleId",
- expression: `'threshold.name' = "high-cpu" AND ruleId == "rule-123"`,
- labelSet: model.LabelSet{
- "threshold.name": "high-cpu",
- "ruleId": "rule-123",
- "service": "auth",
- },
- expected: false, //no commas
- },
- {
- name: "alertname and ruleId combination",
- expression: `alertname == "HighCPUUsage" && ruleId == "cpu-alert-001"`,
- labelSet: model.LabelSet{
- "alertname": "HighCPUUsage",
- "ruleId": "cpu-alert-001",
- "severity": "critical",
- },
- expected: true,
- },
- {
- name: "alertname and ruleId combination",
- expression: `alertname = "HighCPUUsage" AND ruleId = "cpu-alert-001"`,
- labelSet: model.LabelSet{
- "alertname": "HighCPUUsage",
- "ruleId": "cpu-alert-001",
- "severity": "critical",
- },
- expected: true,
- },
- {
- name: "kubernetes namespace filtering",
- expression: `k8s.namespace.name == "auth" && service in ["auth", "payment"]`,
- labelSet: model.LabelSet{
- "k8s.namespace.name": "auth",
- "service": "auth",
- "host": "k8s-node-1",
- },
- expected: true,
- },
- {
- name: "kubernetes namespace filtering",
- expression: `k8s.namespace.name = "auth" && service IN ["auth", "payment"]`,
- labelSet: model.LabelSet{
- "k8s.namespace.name": "auth",
- "service": "auth",
- "host": "k8s-node-1",
- },
- expected: true,
- },
- {
- name: "migration expression format from SQL migration",
- expression: `threshold.name == "HighCPUUsage" && ruleId == "rule-uuid-123"`,
- labelSet: model.LabelSet{
- "threshold.name": "HighCPUUsage",
- "ruleId": "rule-uuid-123",
- "severity": "warning",
- },
- expected: true,
- },
- {
- name: "migration expression format from SQL migration",
- expression: `threshold.name = "HighCPUUsage" && ruleId = "rule-uuid-123"`,
- labelSet: model.LabelSet{
- "threshold.name": "HighCPUUsage",
- "ruleId": "rule-uuid-123",
- "severity": "warning",
- },
- expected: true,
- },
- {
- name: "case sensitive matching",
- expression: `service == "Auth"`, // capital A
- labelSet: model.LabelSet{
- "service": "auth", // lowercase a
- },
- expected: false,
- },
- {
- name: "case sensitive matching",
- expression: `service = "Auth"`, // capital A
- labelSet: model.LabelSet{
- "service": "auth", // lowercase a
- },
- expected: false,
- },
- {
- name: "numeric comparison as strings",
- expression: `port == "8080"`,
- labelSet: model.LabelSet{
- "port": "8080",
- },
- expected: true,
- },
- {
- name: "numeric comparison as strings",
- expression: `port = "8080"`,
- labelSet: model.LabelSet{
- "port": "8080",
- },
- expected: true,
- },
- {
- name: "quoted string with special characters",
- expression: `service == "auth-service-v2"`,
- labelSet: model.LabelSet{
- "service": "auth-service-v2",
- },
- expected: true,
- },
- {
- name: "quoted string with special characters",
- expression: `service = "auth-service-v2"`,
- labelSet: model.LabelSet{
- "service": "auth-service-v2",
- },
- expected: true,
- },
- {
- name: "boolean operators precedence",
- expression: `service == "auth" && env == "prod" || critical == "true"`,
- labelSet: model.LabelSet{
- "service": "payment",
- "env": "staging",
- "critical": "true",
- },
- expected: true,
- },
- {
- name: "boolean operators precedence",
- expression: `service = "auth" AND env = "prod" OR critical = "true"`,
- labelSet: model.LabelSet{
- "service": "payment",
- "env": "staging",
- "critical": "true",
- },
- expected: true,
- },
- {
- name: "nonexistent key OR check",
- expression: `threshold.name = 'warning' OR ruleId = 'rule1'`,
- labelSet: model.LabelSet{
- "threshold.name": "warning",
- },
- expected: true,
- },
- {
- name: "nonexistent key && check",
- expression: `threshold.name = 'warning' && nonexistent = 'auth'`,
- labelSet: model.LabelSet{
- "threshold.name": "warning",
- },
- expected: false,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- result, err := provider.evaluateExpr(context.Background(), tt.expression, tt.labelSet)
- assert.NoError(t, err)
- assert.Equal(t, tt.expected, result, "Expression: %s", tt.expression)
- })
- }
-}
-
func TestProvider_DeleteRoute(t *testing.T) {
ctx := context.Background()
providerSettings := createTestProviderSettings()
diff --git a/pkg/types/alertmanagertypes/expression.go b/pkg/types/alertmanagertypes/expression.go
index 783ce37dea..38927de011 100644
--- a/pkg/types/alertmanagertypes/expression.go
+++ b/pkg/types/alertmanagertypes/expression.go
@@ -4,12 +4,34 @@ import (
"strings"
"github.com/expr-lang/expr"
+ "github.com/expr-lang/expr/ast"
"github.com/prometheus/common/model"
"github.com/SigNoz/signoz/pkg/errors"
)
-var ErrCodeInvalidScopeExpression = errors.MustNewCode("invalid_scope_expression")
+var ErrCodeInvalidExpression = errors.MustNewCode("invalid_expression")
+
+const nilSafeMemberFunc = "__nilSafeMember"
+
+// NilSafeMemberAccess rewrites every string-keyed member access a.b into a
+// lookup that yields nil unless a is a map, so a dotted label that is missing,
+// or whose prefix is a plain label, evaluates to nil instead of failing the run.
+type NilSafeMemberAccess struct{}
+
+func (NilSafeMemberAccess) Visit(node *ast.Node) {
+ member, ok := (*node).(*ast.MemberNode)
+ if !ok {
+ return
+ }
+ if _, ok := member.Property.(*ast.StringNode); !ok {
+ return
+ }
+ ast.Patch(node, &ast.CallNode{
+ Callee: &ast.IdentifierNode{Value: nilSafeMemberFunc},
+ Arguments: []ast.Node{member.Node, member.Property},
+ })
+}
// ConvertLabelSetToEnv converts a label set into a map suitable for use as an
// expr environment. Dotted keys (e.g. "kubernetes.node") are expanded into
@@ -66,23 +88,28 @@ func ConvertLabelSetToEnv(lset model.LabelSet) (map[string]any, bool) {
return env, conflict
}
-// EvalScopeExpression compiles and runs the expression against the provided
-// labels. It returns (result, error). Callers should log the error and
-// decide how to handle a failed evaluation (the maintenance muter treats a
-// failure as "don't skip" so alerts pass through).
-func EvalScopeExpression(expression string, lset model.LabelSet) (bool, error) {
- env, _ := ConvertLabelSetToEnv(lset)
- program, err := expr.Compile(expression, expr.Env(env), expr.AllowUndefinedVariables())
+// EvalExpression compiles and runs the expression against env, as built by
+// ConvertLabelSetToEnv. Callers should log the error and decide how to handle
+// a failed evaluation (the maintenance muter treats a failure as "don't skip"
+// so alerts pass through).
+func EvalExpression(expression string, env map[string]any) (bool, error) {
+ program, err := expr.Compile(expression, expr.Env(env), expr.AllowUndefinedVariables(), expr.Function(nilSafeMemberFunc, nilSafeMember), expr.Patch(NilSafeMemberAccess{}))
if err != nil {
- return false, errors.Wrapf(err, errors.TypeInvalidInput, ErrCodeInvalidScopeExpression, "compile scope expression %q", expression)
+ return false, errors.Wrapf(err, errors.TypeInvalidInput, ErrCodeInvalidExpression, "compile expression %q", expression)
}
output, err := expr.Run(program, env)
if err != nil {
- return false, errors.Wrapf(err, errors.TypeInternal, ErrCodeInvalidScopeExpression, "run scope expression %q", expression)
+ return false, errors.Wrapf(err, errors.TypeInternal, ErrCodeInvalidExpression, "run expression %q", expression)
}
result, ok := output.(bool)
if !ok {
- return false, errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidScopeExpression, "scope expression %q returned non-bool value %T (%v)", expression, output, output)
+ return false, errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidExpression, "expression %q returned non-bool value %T (%v)", expression, output, output)
}
return result, nil
}
+
+func nilSafeMember(params ...any) (any, error) {
+ m, _ := params[0].(map[string]any)
+ key, _ := params[1].(string)
+ return m[key], nil
+}
diff --git a/pkg/types/alertmanagertypes/expression_test.go b/pkg/types/alertmanagertypes/expression_test.go
index a3527c0174..c16ceb9bde 100644
--- a/pkg/types/alertmanagertypes/expression_test.go
+++ b/pkg/types/alertmanagertypes/expression_test.go
@@ -5,10 +5,12 @@ import (
"testing"
"github.com/prometheus/common/model"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
-func TestEvalScopeExpression(t *testing.T) {
- cases := []struct {
+func TestEvalExpression(t *testing.T) {
+ testCases := []struct {
name string
expression string
lset model.LabelSet
@@ -16,96 +18,419 @@ func TestEvalScopeExpression(t *testing.T) {
wantErr bool
}{
{
- name: "equality match",
+ name: "Equality_Match",
expression: `env = "production"`,
lset: model.LabelSet{"env": "production"},
want: true,
},
{
- name: "equality no match",
+ name: "Equality_NoMatch",
expression: `env = "production"`,
lset: model.LabelSet{"env": "staging"},
want: false,
},
{
- name: "inequality match",
+ name: "Inequality_Match",
expression: `env != "production"`,
lset: model.LabelSet{"env": "staging"},
want: true,
},
{
- name: "AND - both match",
+ name: "And_BothMatch",
expression: `env = "production" AND service = "api"`,
lset: model.LabelSet{"env": "production", "service": "api"},
want: true,
},
{
- name: "AND - partial match",
+ name: "And_PartialMatch",
expression: `env = "production" AND service = "api"`,
lset: model.LabelSet{"env": "production", "service": "worker"},
want: false,
},
{
- name: "OR - first matches",
+ name: "Or_FirstMatches",
expression: `env = "production" OR env = "staging"`,
lset: model.LabelSet{"env": "production"},
want: true,
},
{
- name: "OR - second matches",
+ name: "Or_SecondMatches",
expression: `env = "production" OR env = "staging"`,
lset: model.LabelSet{"env": "staging"},
want: true,
},
{
- name: "OR - none match",
+ name: "Or_NoneMatch",
expression: `env = "production" OR env = "staging"`,
lset: model.LabelSet{"env": "development"},
want: false,
},
{
- name: "undefined label returns false",
+ name: "UndefinedLabel_ReturnsFalse",
expression: `env = "production"`,
lset: model.LabelSet{"service": "api"},
want: false,
},
{
- name: "in list - present",
+ name: "MissingDottedLabel_ReturnsFalse",
+ expression: `service.name = "api"`,
+ lset: model.LabelSet{"env": "production"},
+ want: false,
+ },
+ {
+ name: "MissingDeepDottedLabel_ReturnsFalse",
+ expression: `k8s.namespace.name = "api"`,
+ lset: model.LabelSet{"env": "production"},
+ want: false,
+ },
+ {
+ name: "Or_MissingDottedLabelFirst_SecondMatches",
+ expression: `service.name = "api" OR http.status_code = "501"`,
+ lset: model.LabelSet{"http.status_code": "501"},
+ want: true,
+ },
+ {
+ name: "Or_FirstFails_MissingDottedLabelSecond",
+ expression: `env = "production" OR service.name = "api"`,
+ lset: model.LabelSet{"env": "staging"},
+ want: false,
+ },
+ {
+ name: "InList_Present",
expression: `env in ["production", "staging"]`,
lset: model.LabelSet{"env": "production"},
want: true,
},
{
- name: "in list - absent",
+ name: "InList_Absent",
expression: `env in ["production", "staging"]`,
lset: model.LabelSet{"env": "development"},
want: false,
},
{
- name: "invalid expression returns error",
+ name: "InvalidExpression_ReturnsError",
expression: `env =`,
lset: model.LabelSet{"env": "production"},
want: false,
wantErr: true,
},
{
- name: "non-bool expression returns error",
+ name: "NonBoolExpression_ReturnsError",
expression: `env`,
lset: model.LabelSet{"env": "production"},
want: false,
wantErr: true,
},
+ {
+ name: "Equality_Match_ExprSyntax",
+ expression: `threshold.name == 'auth' && ruleId == 'rule1'`,
+ lset: model.LabelSet{
+ "threshold.name": "auth",
+ "ruleId": "rule1",
+ },
+ want: true,
+ },
+ {
+ name: "Equality_Match_QBSyntax",
+ expression: `threshold.name = 'auth' AND ruleId = 'rule1'`,
+ lset: model.LabelSet{
+ "threshold.name": "auth",
+ "ruleId": "rule1",
+ },
+ want: true,
+ },
+ {
+ name: "Equality_NoMatch_ExprSyntax",
+ expression: `service == "payment"`,
+ lset: model.LabelSet{
+ "service": "auth",
+ "env": "production",
+ },
+ want: false,
+ },
+ {
+ name: "And_BothMatch_ExprSyntax",
+ expression: `service == "auth" && env == "production"`,
+ lset: model.LabelSet{
+ "service": "auth",
+ "env": "production",
+ },
+ want: true,
+ },
+ {
+ name: "And_OneMismatch_ExprSyntax",
+ expression: `service == "auth" && env == "staging"`,
+ lset: model.LabelSet{
+ "service": "auth",
+ "env": "production",
+ },
+ want: false,
+ },
+ {
+ name: "Or_OneMatches_ExprSyntax",
+ expression: `service == "payment" || env == "production"`,
+ lset: model.LabelSet{
+ "service": "auth",
+ "env": "production",
+ },
+ want: true,
+ },
+ {
+ name: "Or_NoneMatch_ExprSyntax",
+ expression: `service == "payment" || env == "staging"`,
+ lset: model.LabelSet{
+ "service": "auth",
+ "env": "production",
+ },
+ want: false,
+ },
+ {
+ name: "In_ValueInList_Uppercase",
+ expression: `service IN ["auth", "payment", "notification"]`,
+ lset: model.LabelSet{
+ "service": "auth",
+ },
+ want: true,
+ },
+ {
+ name: "In_ValueNotInList_Uppercase",
+ expression: `service IN ["payment", "notification"]`,
+ lset: model.LabelSet{
+ "service": "auth",
+ },
+ want: false,
+ },
+ {
+ name: "Contains_SubstringMatch_Lowercase",
+ expression: `host contains "prod"`,
+ lset: model.LabelSet{
+ "host": "prod-server-01",
+ },
+ want: true,
+ },
+ {
+ name: "Contains_SubstringMatch_Uppercase",
+ expression: `host CONTAINS "prod"`,
+ lset: model.LabelSet{
+ "host": "prod-server-01",
+ },
+ want: true,
+ },
+ {
+ name: "Contains_NoSubstringMatch_Lowercase",
+ expression: `host contains "staging"`,
+ lset: model.LabelSet{
+ "host": "prod-server-01",
+ },
+ want: false,
+ },
+ {
+ name: "Contains_NoSubstringMatch_Uppercase",
+ expression: `host CONTAINS "staging"`,
+ lset: model.LabelSet{
+ "host": "prod-server-01",
+ },
+ want: false,
+ },
+ {
+ name: "Parentheses_Match_ExprSyntax",
+ expression: `(service == "auth" && env == "production") || critical == "true"`,
+ lset: model.LabelSet{
+ "service": "payment",
+ "env": "staging",
+ "critical": "true",
+ },
+ want: true,
+ },
+ {
+ name: "Parentheses_Match_QBSyntax",
+ expression: `(service = "auth" AND env = "production") OR critical = "true"`,
+ lset: model.LabelSet{
+ "service": "payment",
+ "env": "staging",
+ "critical": "true",
+ },
+ want: true,
+ },
+ {
+ name: "MissingLabelKey_NoMatch_ExprSyntax",
+ expression: `"missing_key" == "value"`,
+ lset: model.LabelSet{
+ "service": "auth",
+ },
+ want: false,
+ },
+ {
+ name: "MissingLabelKey_NoMatch_QBSyntax",
+ expression: `"missing_key" = "value"`,
+ lset: model.LabelSet{
+ "service": "auth",
+ },
+ want: false,
+ },
+ {
+ name: "QuotedThresholdName_NoMatch_ExprSyntax",
+ expression: `'threshold.name' == "high-cpu" && ruleId == "rule-123"`,
+ lset: model.LabelSet{
+ "threshold.name": "high-cpu",
+ "ruleId": "rule-123",
+ "service": "auth",
+ },
+ want: false, //no commas
+ },
+ {
+ name: "QuotedThresholdName_NoMatch_MixedSyntax",
+ expression: `'threshold.name' = "high-cpu" AND ruleId == "rule-123"`,
+ lset: model.LabelSet{
+ "threshold.name": "high-cpu",
+ "ruleId": "rule-123",
+ "service": "auth",
+ },
+ want: false, //no commas
+ },
+ {
+ name: "KubernetesNamespace_Match_ExprSyntax",
+ expression: `k8s.namespace.name == "auth" && service in ["auth", "payment"]`,
+ lset: model.LabelSet{
+ "k8s.namespace.name": "auth",
+ "service": "auth",
+ "host": "k8s-node-1",
+ },
+ want: true,
+ },
+ {
+ name: "KubernetesNamespace_Match_MixedSyntax",
+ expression: `k8s.namespace.name = "auth" && service IN ["auth", "payment"]`,
+ lset: model.LabelSet{
+ "k8s.namespace.name": "auth",
+ "service": "auth",
+ "host": "k8s-node-1",
+ },
+ want: true,
+ },
+ {
+ name: "MigrationFormat_Match_MixedSyntax",
+ expression: `threshold.name = "HighCPUUsage" && ruleId = "rule-uuid-123"`,
+ lset: model.LabelSet{
+ "threshold.name": "HighCPUUsage",
+ "ruleId": "rule-uuid-123",
+ "severity": "warning",
+ },
+ want: true,
+ },
+ {
+ name: "CaseSensitive_NoMatch_ExprSyntax",
+ expression: `service == "Auth"`, // capital A
+ lset: model.LabelSet{
+ "service": "auth", // lowercase a
+ },
+ want: false,
+ },
+ {
+ name: "CaseSensitive_NoMatch_QBSyntax",
+ expression: `service = "Auth"`, // capital A
+ lset: model.LabelSet{
+ "service": "auth", // lowercase a
+ },
+ want: false,
+ },
+ {
+ name: "OperatorPrecedence_Match_ExprSyntax",
+ expression: `service == "auth" && env == "prod" || critical == "true"`,
+ lset: model.LabelSet{
+ "service": "payment",
+ "env": "staging",
+ "critical": "true",
+ },
+ want: true,
+ },
+ {
+ name: "OperatorPrecedence_Match_QBSyntax",
+ expression: `service = "auth" AND env = "prod" OR critical = "true"`,
+ lset: model.LabelSet{
+ "service": "payment",
+ "env": "staging",
+ "critical": "true",
+ },
+ want: true,
+ },
+ {
+ name: "Or_MissingKey_OtherSideMatches",
+ expression: `threshold.name = 'warning' OR ruleId = 'rule1'`,
+ lset: model.LabelSet{
+ "threshold.name": "warning",
+ },
+ want: true,
+ },
+ {
+ name: "And_MissingKey_NoMatch",
+ expression: `threshold.name = 'warning' && nonexistent = 'auth'`,
+ lset: model.LabelSet{
+ "threshold.name": "warning",
+ },
+ want: false,
+ },
+ {
+ name: "Or_MissingDottedLabelSecond_OtherSideMatches",
+ expression: `http.status_code = '501' OR service.name = 'otel-demo'`,
+ lset: model.LabelSet{
+ "http.status_code": "501",
+ },
+ want: true,
+ },
+ {
+ name: "And_MissingDottedLabel_NoMatch",
+ expression: `service.name = 'otel-demo' AND http.status_code = '501'`,
+ lset: model.LabelSet{
+ "http.status_code": "501",
+ },
+ want: false,
+ },
+ {
+ name: "MissingLeafUnderExistingPrefix_NoMatch",
+ expression: `k8s.pod.name = 'checkout'`,
+ lset: model.LabelSet{
+ "k8s.node.name": "node-1",
+ },
+ want: false,
+ },
+ {
+ name: "PlainLabelUsedAsPrefix_IsNil",
+ expression: `deployment.environment = nil`,
+ lset: model.LabelSet{
+ "deployment": "blue",
+ },
+ want: true,
+ },
+ {
+ name: "Or_PlainLabelUsedAsPrefix_OtherSideMatches",
+ expression: `region.zone = 'us-east-1a' OR team = 'payments'`,
+ lset: model.LabelSet{
+ "region": "us-east-1",
+ "team": "payments",
+ },
+ want: true,
+ },
+ {
+ name: "BracketAccessOnDottedLabel_Match",
+ expression: `cloud["provider"] = 'aws'`,
+ lset: model.LabelSet{
+ "cloud.provider": "aws",
+ },
+ want: true,
+ },
}
- for _, c := range cases {
- t.Run(c.name, func(t *testing.T) {
- got, err := EvalScopeExpression(c.expression, c.lset)
- if (err != nil) != c.wantErr {
- t.Errorf("EvalScopeExpression(%q, %v) error = %v, wantErr %v", c.expression, c.lset, err, c.wantErr)
- }
- if got != c.want {
- t.Errorf("EvalScopeExpression(%q, %v) = %v, want %v", c.expression, c.lset, got, c.want)
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ env, _ := ConvertLabelSetToEnv(testCase.lset)
+ got, err := EvalExpression(testCase.expression, env)
+ if testCase.wantErr {
+ assert.Error(t, err)
+ } else {
+ require.NoError(t, err)
}
+ assert.Equal(t, testCase.want, got)
})
}
}
diff --git a/pkg/types/alertmanagertypes/maintenance.go b/pkg/types/alertmanagertypes/maintenance.go
index bebad257f9..bd27d7e579 100644
--- a/pkg/types/alertmanagertypes/maintenance.go
+++ b/pkg/types/alertmanagertypes/maintenance.go
@@ -149,7 +149,8 @@ func (m *PlannedMaintenance) ShouldSkip(ruleID string, now time.Time, lset model
}
if m.Scope != "" {
- skip, err := EvalScopeExpression(m.Scope, lset)
+ env, _ := ConvertLabelSetToEnv(lset)
+ skip, err := EvalExpression(m.Scope, env)
if err != nil || !skip {
return false, err
}
diff --git a/tests/fixtures/alerts.py b/tests/fixtures/alerts.py
index b905d99910..153286857c 100644
--- a/tests/fixtures/alerts.py
+++ b/tests/fixtures/alerts.py
@@ -88,6 +88,73 @@ def create_alert_rule_with_channel(
return _create_alert_rule_with_channel
[email protected](name="create_route_policy", scope="function")
+def create_route_policy(signoz: types.SigNoz, get_token: Callable[[str, str], str]) -> Callable[[dict], str]:
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ policy_ids = []
+
+ def _create_route_policy(policy: dict) -> str:
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v1/route_policies"),
+ json=policy,
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.CREATED, f"Failed to create route policy, api returned {response.status_code} with response: {response.text}"
+ policy_id = response.json()["data"]["id"]
+ policy_ids.append(policy_id)
+ return policy_id
+
+ yield _create_route_policy
+
+ for policy_id in policy_ids:
+ response = requests.delete(
+ signoz.self.host_configs["8080"].get(f"/api/v1/route_policies/{policy_id}"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ if response.status_code != HTTPStatus.NO_CONTENT:
+ logger.error("Failed to delete route policy: %s", {"policy_id": policy_id, "status": response.status_code, "response": response.text})
+
+
[email protected](name="create_downtime_schedule", scope="function")
+def create_downtime_schedule(signoz: types.SigNoz, get_token: Callable[[str, str], str]) -> Callable[[dict], str]:
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ schedules = {}
+
+ def _create_downtime_schedule(schedule: dict) -> str:
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v1/downtime_schedules"),
+ json=schedule,
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.CREATED, f"Failed to create downtime schedule, api returned {response.status_code} with response: {response.text}"
+ schedule_id = response.json()["data"]["id"]
+ schedules[schedule_id] = schedule
+ return schedule_id
+
+ yield _create_downtime_schedule
+
+ for schedule_id, schedule in schedules.items():
+ # a schedule still referencing rules cannot be deleted
+ requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v1/downtime_schedules/{schedule_id}"),
+ json={**schedule, "alertIds": []},
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ response = requests.delete(
+ signoz.self.host_configs["8080"].get(f"/api/v1/downtime_schedules/{schedule_id}"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ if response.status_code != HTTPStatus.NO_CONTENT:
+ logger.error("Failed to delete downtime schedule: %s", {"schedule_id": schedule_id, "status": response.status_code, "response": response.text})
+
+
def delete_all_rules(signoz: types.SigNoz, token: str) -> None:
response = requests.get(
signoz.self.host_configs["8080"].get("/api/v2/rules"),
diff --git a/tests/fixtures/types.py b/tests/fixtures/types.py
index fd9fda90ba..6861d33f79 100644
--- a/tests/fixtures/types.py
+++ b/tests/fixtures/types.py
@@ -1,4 +1,5 @@
from dataclasses import dataclass, field
+from datetime import timedelta
from typing import Literal
from urllib.parse import urljoin
@@ -254,3 +255,30 @@ class AlertManagerNotificationTestCase:
channel_config: dict[str, any]
# notification expectations for the test case
notification_expectation: AMNotificationExpectation
+
+
+@dataclass(frozen=True)
+class RoutePolicyExpectation:
+ # expression of the route policy, each policy routes to its own channel
+ expression: str
+ # alerts expected on the policy's channel, empty when none should arrive
+ expected_alerts: list[FiringAlert]
+
+
+@dataclass(frozen=True)
+class RoutingPolicyTestCase:
+ # name of the test case
+ name: str
+ policies: list[RoutePolicyExpectation]
+
+
+@dataclass(frozen=True)
+class PlannedDowntimeTestCase:
+ # name of the test case
+ name: str
+ # scope expression of the downtime, empty to mute every alert of the rule
+ scope: str
+ # offset of the downtime start from now
+ start_offset: timedelta
+ # alerts expected to get through the downtime
+ expected_alerts: list[FiringAlert]
diff --git a/tests/integration/testdata/alertmanager/notification_routing_alert_data.jsonl b/tests/integration/testdata/alertmanager/notification_routing_alert_data.jsonl
new file mode 100644
index 0000000000..def3dd2d82
--- /dev/null
+++ b/tests/integration/testdata/alertmanager/notification_routing_alert_data.jsonl
@@ -0,0 +1,10 @@
+{"metric_name":"cpu_usage_notification_routing","labels":{"tier":"frontend","service.name":"checkout"},"timestamp":"2026-01-29T10:01:00+00:00","value":95,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"percent","env":"default","resource_attrs":{},"scope_attrs":{}}
+{"metric_name":"cpu_usage_notification_routing","labels":{"tier":"frontend","service.name":"checkout"},"timestamp":"2026-01-29T10:02:00+00:00","value":95,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"percent","env":"default","resource_attrs":{},"scope_attrs":{}}
+{"metric_name":"cpu_usage_notification_routing","labels":{"tier":"frontend","service.name":"checkout"},"timestamp":"2026-01-29T10:03:00+00:00","value":95,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"percent","env":"default","resource_attrs":{},"scope_attrs":{}}
+{"metric_name":"cpu_usage_notification_routing","labels":{"tier":"frontend","service.name":"checkout"},"timestamp":"2026-01-29T10:04:00+00:00","value":95,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"percent","env":"default","resource_attrs":{},"scope_attrs":{}}
+{"metric_name":"cpu_usage_notification_routing","labels":{"tier":"frontend","service.name":"checkout"},"timestamp":"2026-01-29T10:05:00+00:00","value":95,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"percent","env":"default","resource_attrs":{},"scope_attrs":{}}
+{"metric_name":"cpu_usage_notification_routing","labels":{"tier":"backend","service.name":"payment"},"timestamp":"2026-01-29T10:01:00+00:00","value":92,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"percent","env":"default","resource_attrs":{},"scope_attrs":{}}
+{"metric_name":"cpu_usage_notification_routing","labels":{"tier":"backend","service.name":"payment"},"timestamp":"2026-01-29T10:02:00+00:00","value":92,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"percent","env":"default","resource_attrs":{},"scope_attrs":{}}
+{"metric_name":"cpu_usage_notification_routing","labels":{"tier":"backend","service.name":"payment"},"timestamp":"2026-01-29T10:03:00+00:00","value":92,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"percent","env":"default","resource_attrs":{},"scope_attrs":{}}
+{"metric_name":"cpu_usage_notification_routing","labels":{"tier":"backend","service.name":"payment"},"timestamp":"2026-01-29T10:04:00+00:00","value":92,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"percent","env":"default","resource_attrs":{},"scope_attrs":{}}
+{"metric_name":"cpu_usage_notification_routing","labels":{"tier":"backend","service.name":"payment"},"timestamp":"2026-01-29T10:05:00+00:00","value":92,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"percent","env":"default","resource_attrs":{},"scope_attrs":{}}
diff --git a/tests/integration/testdata/alertmanager/planned_downtime_rule.json b/tests/integration/testdata/alertmanager/planned_downtime_rule.json
new file mode 100644
index 0000000000..4319cfb2f2
--- /dev/null
+++ b/tests/integration/testdata/alertmanager/planned_downtime_rule.json
@@ -0,0 +1,77 @@
+{
+ "alert": "notification_routing",
+ "ruleType": "threshold_rule",
+ "alertType": "METRIC_BASED_ALERT",
+ "condition": {
+ "thresholds": {
+ "kind": "basic",
+ "spec": [
+ {
+ "name": "critical",
+ "target": 90,
+ "matchType": "1",
+ "op": "1",
+ "channels": [
+ "test channel"
+ ]
+ }
+ ]
+ },
+ "compositeQuery": {
+ "queryType": "builder",
+ "panelType": "graph",
+ "queries": [
+ {
+ "type": "builder_query",
+ "spec": {
+ "name": "A",
+ "signal": "metrics",
+ "aggregations": [
+ {
+ "metricName": "cpu_usage_notification_routing",
+ "timeAggregation": "avg",
+ "spaceAggregation": "max"
+ }
+ ],
+ "groupBy": [
+ {
+ "name": "tier",
+ "fieldContext": "attribute",
+ "fieldDataType": "string"
+ },
+ {
+ "name": "service.name",
+ "fieldContext": "attribute",
+ "fieldDataType": "string"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ "selectedQueryName": "A"
+ },
+ "evaluation": {
+ "kind": "rolling",
+ "spec": {
+ "evalWindow": "5m0s",
+ "frequency": "15s"
+ }
+ },
+ "labels": {},
+ "annotations": {
+ "description": "CPU usage is above threshold",
+ "summary": "High CPU usage"
+ },
+ "notificationSettings": {
+ "groupBy": [],
+ "usePolicy": false,
+ "renotify": {
+ "enabled": false,
+ "interval": "30m",
+ "alertStates": []
+ }
+ },
+ "version": "v5",
+ "schemaVersion": "v2alpha1"
+}
diff --git a/tests/integration/testdata/alertmanager/routing_policies_rule.json b/tests/integration/testdata/alertmanager/routing_policies_rule.json
new file mode 100644
index 0000000000..81a5af6e94
--- /dev/null
+++ b/tests/integration/testdata/alertmanager/routing_policies_rule.json
@@ -0,0 +1,77 @@
+{
+ "alert": "notification_routing",
+ "ruleType": "threshold_rule",
+ "alertType": "METRIC_BASED_ALERT",
+ "condition": {
+ "thresholds": {
+ "kind": "basic",
+ "spec": [
+ {
+ "name": "critical",
+ "target": 90,
+ "matchType": "1",
+ "op": "1",
+ "channels": [
+ "test channel"
+ ]
+ }
+ ]
+ },
+ "compositeQuery": {
+ "queryType": "builder",
+ "panelType": "graph",
+ "queries": [
+ {
+ "type": "builder_query",
+ "spec": {
+ "name": "A",
+ "signal": "metrics",
+ "aggregations": [
+ {
+ "metricName": "cpu_usage_notification_routing",
+ "timeAggregation": "avg",
+ "spaceAggregation": "max"
+ }
+ ],
+ "groupBy": [
+ {
+ "name": "tier",
+ "fieldContext": "attribute",
+ "fieldDataType": "string"
+ },
+ {
+ "name": "service.name",
+ "fieldContext": "attribute",
+ "fieldDataType": "string"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ "selectedQueryName": "A"
+ },
+ "evaluation": {
+ "kind": "rolling",
+ "spec": {
+ "evalWindow": "5m0s",
+ "frequency": "15s"
+ }
+ },
+ "labels": {},
+ "annotations": {
+ "description": "CPU usage is above threshold",
+ "summary": "High CPU usage"
+ },
+ "notificationSettings": {
+ "groupBy": [],
+ "usePolicy": true,
+ "renotify": {
+ "enabled": false,
+ "interval": "30m",
+ "alertStates": []
+ }
+ },
+ "version": "v5",
+ "schemaVersion": "v2alpha1"
+}
diff --git a/tests/integration/tests/alertmanager/19_routing_policies.py b/tests/integration/tests/alertmanager/19_routing_policies.py
new file mode 100644
index 0000000000..3c6e34426e
--- /dev/null
+++ b/tests/integration/tests/alertmanager/19_routing_policies.py
@@ -0,0 +1,107 @@
+import json
+import uuid
+from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from wiremock.client import HttpMethods, Mapping, MappingRequest, MappingResponse
+
+from fixtures import types
+from fixtures.alerts import (
+ collect_webhook_firing_alerts,
+ get_testdata_file_path,
+ update_rule_channel_name,
+ verify_webhook_alert_expectation,
+)
+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
+from fixtures.notification_channel import wait_for_alertmanager_sync
+
+FRONTEND_ALERT = types.FiringAlert(labels={"tier": "frontend", "service.name": "checkout"})
+BACKEND_ALERT = types.FiringAlert(labels={"tier": "backend", "service.name": "payment"})
+
+ROUTING_POLICY_CASES = [
+ types.RoutingPolicyTestCase(
+ name="plain_label",
+ policies=[
+ types.RoutePolicyExpectation(expression='tier == "frontend"', expected_alerts=[FRONTEND_ALERT]),
+ types.RoutePolicyExpectation(expression='tier == "backend"', expected_alerts=[BACKEND_ALERT]),
+ ],
+ ),
+]
+
+
+ "routing_policy_test_case",
+ ROUTING_POLICY_CASES,
+ ids=lambda c: c.name,
+)
+def test_routing_policies( # pylint: disable=too-many-arguments,too-many-positional-arguments
+ signoz: types.SigNoz,
+ get_token: Callable[[str, str], str],
+ notification_channel: types.TestContainerDocker,
+ make_http_mocks: Callable[[types.TestContainerDocker, list[Mapping]], None],
+ create_notification_channel: Callable[[dict], str],
+ create_route_policy: Callable[[dict], str],
+ create_alert_rule: Callable[[dict], str],
+ insert_alert_data: Callable[[list[types.AlertData], datetime], None],
+ routing_policy_test_case: types.RoutingPolicyTestCase,
+):
+ # one channel per policy, so a delivery to a channel shows which policy matched
+ policies = routing_policy_test_case.policies
+ channel_names = [str(uuid.uuid4()) for _ in policies]
+ make_http_mocks(
+ notification_channel,
+ [
+ Mapping(
+ request=MappingRequest(method=HttpMethods.POST, url=f"/alert/{channel_name}"),
+ response=MappingResponse(status=200, json_body={}),
+ persistent=False,
+ )
+ for channel_name in channel_names
+ ],
+ )
+ for channel_name, policy in zip(channel_names, policies, strict=True):
+ create_notification_channel(
+ {
+ "name": channel_name,
+ "webhook_configs": [{"url": notification_channel.container_configs["8080"].get(f"/alert/{channel_name}"), "send_resolved": False}],
+ }
+ )
+ create_route_policy({"name": channel_name, "expression": policy.expression, "channels": [channel_name]})
+
+ # waits for the org's alertmanager only; the channels load on its next config poll
+ # and alerts sent to them before that are replayed after the reload
+ wait_for_alertmanager_sync(signoz, get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD), notification_channel)
+
+ insert_alert_data(
+ [types.AlertData(type="metrics", data_path="alertmanager/notification_routing_alert_data.jsonl")],
+ base_time=datetime.now(tz=UTC) - timedelta(minutes=5),
+ )
+
+ with open(get_testdata_file_path("alertmanager/routing_policies_rule.json"), encoding="utf-8") as f:
+ rule_data = json.loads(f.read())
+ update_rule_channel_name(rule_data, channel_names[0])
+ create_alert_rule(rule_data)
+
+ # each channel receives the alerts its policy matches
+ for channel_name, policy in zip(channel_names, policies, strict=True):
+ if len(policy.expected_alerts) > 0:
+ verify_webhook_alert_expectation(
+ notification_channel,
+ channel_name,
+ types.AlertExpectation(should_alert=True, expected_alerts=policy.expected_alerts, wait_time_seconds=120),
+ )
+
+ # the rule has fired by now, so an empty channel means its policy did not match
+ for channel_name, policy in zip(channel_names, policies, strict=True):
+ if len(policy.expected_alerts) == 0:
+ verify_webhook_alert_expectation(
+ notification_channel,
+ channel_name,
+ types.AlertExpectation(should_alert=False, expected_alerts=[], wait_time_seconds=15),
+ )
+
+ # no channel received alerts its policy did not match
+ for channel_name, policy in zip(channel_names, policies, strict=True):
+ received_services = {alert.labels["service.name"] for alert in collect_webhook_firing_alerts(notification_channel, channel_name)}
+ assert received_services == {alert.labels["service.name"] for alert in policy.expected_alerts}, f"channel {channel_name} received alerts for {received_services}, expected {policy.expected_alerts}"
diff --git a/tests/integration/tests/alertmanager/20_planned_downtime.py b/tests/integration/tests/alertmanager/20_planned_downtime.py
new file mode 100644
index 0000000000..e50403471e
--- /dev/null
+++ b/tests/integration/tests/alertmanager/20_planned_downtime.py
@@ -0,0 +1,100 @@
+import json
+import time
+import uuid
+from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from wiremock.client import HttpMethods, Mapping, MappingRequest, MappingResponse
+
+from fixtures import types
+from fixtures.alerts import (
+ collect_webhook_firing_alerts,
+ get_testdata_file_path,
+ update_rule_channel_name,
+ verify_webhook_alert_expectation,
+)
+
+BACKEND_ALERT = types.FiringAlert(labels={"tier": "backend", "service.name": "payment"})
+
+# MaintenanceMuter caches downtime schedules for 30s
+MAINTENANCE_CACHE_TTL_SECONDS = 30
+
+
+PLANNED_DOWNTIME_CASES = [
+ types.PlannedDowntimeTestCase(name="dotted_label_scope", scope='service.name == "checkout"', start_offset=timedelta(0), expected_alerts=[BACKEND_ALERT]),
+]
+
+
+ "planned_downtime_test_case",
+ PLANNED_DOWNTIME_CASES,
+ ids=lambda c: c.name,
+)
+def test_planned_downtime( # pylint: disable=too-many-arguments,too-many-positional-arguments
+ notification_channel: types.TestContainerDocker,
+ make_http_mocks: Callable[[types.TestContainerDocker, list[Mapping]], None],
+ create_notification_channel: Callable[[dict], str],
+ create_alert_rule: Callable[[dict], str],
+ create_downtime_schedule: Callable[[dict], str],
+ insert_alert_data: Callable[[list[types.AlertData], datetime], None],
+ planned_downtime_test_case: types.PlannedDowntimeTestCase,
+):
+ expected_alerts = planned_downtime_test_case.expected_alerts
+ channel_name = str(uuid.uuid4())
+ make_http_mocks(
+ notification_channel,
+ [
+ Mapping(
+ request=MappingRequest(method=HttpMethods.POST, url=f"/alert/{channel_name}"),
+ response=MappingResponse(status=200, json_body={}),
+ persistent=False,
+ )
+ ],
+ )
+ create_notification_channel(
+ {
+ "name": channel_name,
+ "webhook_configs": [{"url": notification_channel.container_configs["8080"].get(f"/alert/{channel_name}"), "send_resolved": False}],
+ }
+ )
+
+ with open(get_testdata_file_path("alertmanager/planned_downtime_rule.json"), encoding="utf-8") as f:
+ rule_data = json.loads(f.read())
+ update_rule_channel_name(rule_data, channel_name)
+ rule_id = create_alert_rule(rule_data)
+
+ start = datetime.now(tz=UTC).replace(microsecond=0) + planned_downtime_test_case.start_offset
+ create_downtime_schedule(
+ {
+ "name": channel_name,
+ "alertIds": [rule_id],
+ "scope": planned_downtime_test_case.scope,
+ "schedule": {
+ "timezone": "UTC",
+ "startTime": start.isoformat(),
+ "endTime": (start + timedelta(hours=1)).isoformat(),
+ },
+ }
+ )
+
+ # the rule has no data to fire on until the downtime is visible to the muter
+ time.sleep(MAINTENANCE_CACHE_TTL_SECONDS + 5)
+
+ insert_alert_data(
+ [types.AlertData(type="metrics", data_path="alertmanager/notification_routing_alert_data.jsonl")],
+ base_time=datetime.now(tz=UTC) - timedelta(minutes=5),
+ )
+
+ verify_webhook_alert_expectation(
+ notification_channel,
+ channel_name,
+ types.AlertExpectation(
+ should_alert=len(expected_alerts) > 0,
+ expected_alerts=expected_alerts,
+ wait_time_seconds=120,
+ ),
+ )
+
+ received_services = {alert.labels["service.name"] for alert in collect_webhook_firing_alerts(notification_channel, channel_name)}
+ assert received_services == {alert.labels["service.name"] for alert in expected_alerts}, f"received alerts for {received_services}, expected {expected_alerts}"