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
feat(planned-downtime): scope maintenance windows to label expressions (#11186)
Jatinderjit Singh6cf22e98ddc8
diff --git a/docs/api/openapi.yml b/docs/api/openapi.ymlindex 252931a664..69e1279818 100644--- a/docs/api/openapi.yml+++ b/docs/api/openapi.yml@@ -129,6 +129,8 @@ components:type: stringschedule:$ref: '#/components/schemas/AlertmanagertypesSchedule'+ scope:+ type: stringstatus:$ref: '#/components/schemas/AlertmanagertypesMaintenanceStatus'updatedAt:@@ -272,6 +274,8 @@ components:type: stringschedule:$ref: '#/components/schemas/AlertmanagertypesSchedule'+ scope:+ type: stringrequired:- name- schedulediff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.tsindex 1452b59223..98f5f21f02 100644--- a/frontend/src/api/generated/services/sigNoz.schemas.ts+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts@@ -225,6 +225,10 @@ export interface AlertmanagertypesPlannedMaintenanceDTO {*/name: string;schedule: AlertmanagertypesScheduleDTO;+ /**+ * @type string+ */+ scope?: string;status: AlertmanagertypesMaintenanceStatusDTO;/*** @type string@@ -1714,6 +1718,10 @@ export interface AlertmanagertypesPostablePlannedMaintenanceDTO {*/name: string;schedule: AlertmanagertypesScheduleDTO;+ /**+ * @type string+ */+ scope?: string;}export interface AlertmanagertypesPostableRoutePolicyDTO {diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntimeForm.tsx b/frontend/src/container/PlannedDowntime/PlannedDowntimeForm.tsxindex dd77c07a92..17f6bb5468 100644--- a/frontend/src/container/PlannedDowntime/PlannedDowntimeForm.tsx+++ b/frontend/src/container/PlannedDowntime/PlannedDowntimeForm.tsx@@ -1,5 +1,5 @@import React, { useCallback, useEffect, useMemo, useState } from 'react';-import { Check } from '@signozhq/icons';+import { Check, Info } from '@signozhq/icons';import {Button,DatePicker,@@ -11,6 +11,7 @@ import {Select,SelectProps,Spin,+ Tooltip,} from 'antd';import { Typography } from '@signozhq/ui/typography';import type { DefaultOptionType } from 'antd/es/select';@@ -78,6 +79,7 @@ interface PlannedDowntimeFormData {alertRules: DefaultOptionType[];recurrenceSelect?: AlertmanagertypesRecurrenceDTO;timezone?: string;+ scope?: string;}const customFormat = DATE_TIME_FORMATS.ORDINAL_DATETIME;@@ -144,6 +146,7 @@ export function PlannedDowntimeForm(.map((alert) => alert.value).filter((alert) => alert !== undefined) as string[],name: values.name,+ scope: values.scope,schedule: {startTime: values.startTime?.format(),endTime: values.endTime?.format(),@@ -278,6 +281,7 @@ export function PlannedDowntimeForm(duration: getDurationInfo(schedule?.recurrence?.duration)?.value ?? '',} as AlertmanagertypesRecurrenceDTO,timezone: schedule?.timezone as string,+ scope: initialValues.scope || '',};}, [initialValues, alertOptions]);@@ -488,6 +492,36 @@ export function PlannedDowntimeForm(</Select></Form.Item></div>+ <Form.Item+ label={+ <span>+ Scope + <Tooltip+ mouseLeaveDelay={0.3}+ title={+ <span>+ Scope the planned downtime by alert labels.{' '}+ <a+ href="https://signoz.io/docs/alerts-management/planned-maintenance/#scoping-with-label-expressions"+ target="_blank"+ rel="noopener noreferrer"+ >+ Learn more+ </a>+ </span>+ }+ >+ <Info size={13} />+ </Tooltip>+ </span>+ }+ name="scope"+ >+ <Input.TextArea+ placeholder='e.g. env = "prod" AND region = "us-east-1"'+ autoSize={{ minRows: 2, maxRows: 4 }}+ />+ </Form.Item><Form.Item style={{ marginBottom: 0 }}><ModalButtonWrapper><Buttondiff --git a/pkg/alertmanager/alertmanagerserver/maintenance_muter.go b/pkg/alertmanager/alertmanagerserver/maintenance_muter.goindex 00c8856a56..15fe48b724 100644--- a/pkg/alertmanager/alertmanagerserver/maintenance_muter.go+++ b/pkg/alertmanager/alertmanagerserver/maintenance_muter.go@@ -42,7 +42,14 @@ func (m *MaintenanceMuter) Mutes(ctx context.Context, lset model.LabelSet) bool}now := time.Now()for _, mw := range m.getMaintenances(ctx) {- if mw.ShouldSkip(ruleID, now) {+ skip, err := mw.ShouldSkip(ruleID, now, lset)+ if err != nil {+ m.logger.ErrorContext(ctx, "failed to test maintenance window skip condition",+ slog.String("maintenance_id", mw.ID.StringValue()),+ slog.String("scope", mw.Scope),+ slog.Any("error", err),+ )+ } else if skip {return true}}@@ -61,7 +68,14 @@ func (m *MaintenanceMuter) MutedBy(ctx context.Context, lset model.LabelSet) []svar ids []stringnow := time.Now()for _, mw := range m.getMaintenances(ctx) {- if mw.ShouldSkip(ruleID, now) {+ skip, err := mw.ShouldSkip(ruleID, now, lset)+ if err != nil {+ m.logger.ErrorContext(ctx, "failed to test maintenance window skip condition",+ slog.String("maintenance_id", mw.ID.StringValue()),+ slog.String("scope", mw.Scope),+ slog.Any("error", err),+ )+ } else if skip {ids = append(ids, mw.ID.String())}}diff --git a/pkg/alertmanager/alertmanagerserver/server_e2e_test.go b/pkg/alertmanager/alertmanagerserver/server_e2e_test.goindex 75473db6a8..80ebe336aa 100644--- a/pkg/alertmanager/alertmanagerserver/server_e2e_test.go+++ b/pkg/alertmanager/alertmanagerserver/server_e2e_test.go@@ -41,7 +41,7 @@ func TestEndToEndAlertManagerFlow(t *testing.T) {Identifiable: types.Identifiable{ID: valuer.GenerateUUID(),},- Expression: `ruleId == "high-cpu-usage" && severity == "critical"`,+ Expression: `ruleId = "high-cpu-usage" AND severity = "critical"`,ExpressionKind: alertmanagertypes.RuleBasedExpression,Name: "high-cpu-usage",Description: "High CPU critical alerts to webhook",@@ -53,7 +53,7 @@ func TestEndToEndAlertManagerFlow(t *testing.T) {Identifiable: types.Identifiable{ID: valuer.GenerateUUID(),},- Expression: `ruleId == "high-cpu-usage" && severity == "warning"`,+ Expression: `ruleId = "high-cpu-usage" AND severity = "warning"`,ExpressionKind: alertmanagertypes.RuleBasedExpression,Name: "high-cpu-usage",Description: "High CPU warning alerts to webhook",@@ -87,18 +87,25 @@ func TestEndToEndAlertManagerFlow(t *testing.T) {err = notificationManager.SetNotificationConfig(orgID, "high-cpu-usage", ¬ifConfig)require.NoError(t, err)- mwID := valuer.GenerateUUID()+ activeSchedule := &alertmanagertypes.Schedule{+ Timezone: "UTC",+ StartTime: time.Now().Add(-time.Hour),+ EndTime: time.Now().Add(time.Hour),+ }+ // mwRuleIDAndScope: only critical high-cpu-usage alerts.+ mwRuleIDAndScope := valuer.GenerateUUID()+ // mwRuleIDOnly: all high-cpu-usage alerts regardless of severity.+ mwRuleIDOnly := valuer.GenerateUUID()+ // mwScopeOnly: all critical alerts regardless of rule ID.+ mwScopeOnly := valuer.GenerateUUID()+maintenanceStore := alertmanagertypestest.NewMockMaintenanceStore(t)maintenanceStore.On("ListPlannedMaintenance", mock.Anything, orgID).Return(- []*alertmanagertypes.PlannedMaintenance{{- ID: mwID,- Schedule: &alertmanagertypes.Schedule{- Timezone: "UTC",- StartTime: time.Now().Add(-time.Hour),- EndTime: time.Now().Add(time.Hour),- },- RuleIDs: []string{"high-cpu-usage"},- }}, nil,+ []*alertmanagertypes.PlannedMaintenance{+ {ID: mwRuleIDAndScope, Schedule: activeSchedule, RuleIDs: []string{"high-cpu-usage"}, Scope: `severity = "critical"`},+ {ID: mwRuleIDOnly, Schedule: activeSchedule, RuleIDs: []string{"high-cpu-usage"}},+ {ID: mwScopeOnly, Schedule: activeSchedule, Scope: `severity = "critical"`},+ }, nil,)srvCfg := NewConfig()@@ -249,18 +256,42 @@ func TestEndToEndAlertManagerFlow(t *testing.T) {require.Equal(t, "{__receiver__=\"webhook\"}:{cluster=\"prod-cluster\", instance=\"server-03\", ruleId=\"high-cpu-usage\"}", alertGroups[2].GroupKey)})- t.Run("verify_muting", func(t *testing.T) {- req, err := http.NewRequest(http.MethodGet, "/alerts", nil)- require.NoError(t, err)- params, err := alertmanagertypes.NewGettableAlertsParams(req)- require.NoError(t, err)- alerts, err := server.GetAlerts(ctx, params)- require.NoError(t, err)+ req, err := http.NewRequest(http.MethodGet, "/alerts", nil)+ require.NoError(t, err)+ params, err := alertmanagertypes.NewGettableAlertsParams(req)+ require.NoError(t, err)+ alerts, err := server.GetAlerts(ctx, params)+ require.NoError(t, err)++ t.Run("verify_muting_ruleid_and_scope", func(t *testing.T) {+ // Window with ruleID + scope mutes only alerts matching both.+ for _, alert := range alerts {+ if alert.Labels["ruleId"] == "high-cpu-usage" && alert.Labels["severity"] == "critical" {+ require.Contains(t, alert.Status.MutedBy, mwRuleIDAndScope.String())+ } else {+ require.NotContains(t, alert.Status.MutedBy, mwRuleIDAndScope.String())+ }+ }+ })++ t.Run("verify_muting_ruleid_only", func(t *testing.T) {+ // Window with ruleID but no scope mutes all severities for that rule.for _, alert := range alerts {if alert.Labels["ruleId"] == "high-cpu-usage" {- require.Equal(t, []string{mwID.String()}, alert.Status.MutedBy)+ require.Contains(t, alert.Status.MutedBy, mwRuleIDOnly.String())+ } else {+ require.NotContains(t, alert.Status.MutedBy, mwRuleIDOnly.String())+ }+ }+ })++ t.Run("verify_muting_scope_only", func(t *testing.T) {+ // Window with scope but no ruleIDs mutes all critical alerts regardless of rule.+ for _, alert := range alerts {+ if alert.Labels["severity"] == "critical" {+ require.Contains(t, alert.Status.MutedBy, mwScopeOnly.String())} else {- require.Empty(t, alert.Status.MutedBy)+ require.NotContains(t, alert.Status.MutedBy, mwScopeOnly.String())}}})diff --git a/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/maintenance.go b/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/maintenance.goindex a90d8ca615..328106ef0b 100644--- a/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/maintenance.go+++ b/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/maintenance.go@@ -89,6 +89,7 @@ func (r *maintenance) CreatePlannedMaintenance(ctx context.Context, maintenanceDescription: maintenance.Description,Schedule: maintenance.Schedule,OrgID: claims.OrgID,+ Scope: maintenance.Scope,}maintenanceRules := make([]*alertmanagertypes.StorablePlannedMaintenanceRule, 0)@@ -123,7 +124,6 @@ func (r *maintenance) CreatePlannedMaintenance(ctx context.Context, maintenanceNewInsert().Model(&maintenanceRules).Exec(ctx)-if err != nil {return err}@@ -141,6 +141,7 @@ func (r *maintenance) CreatePlannedMaintenance(ctx context.Context, maintenanceDescription: storablePlannedMaintenance.Description,Schedule: storablePlannedMaintenance.Schedule,RuleIDs: maintenance.AlertIds,+ Scope: maintenance.Scope,CreatedAt: storablePlannedMaintenance.CreatedAt,CreatedBy: storablePlannedMaintenance.CreatedBy,UpdatedAt: storablePlannedMaintenance.UpdatedAt,@@ -189,6 +190,7 @@ func (r *maintenance) UpdatePlannedMaintenance(ctx context.Context, maintenanceDescription: maintenance.Description,Schedule: maintenance.Schedule,OrgID: claims.OrgID,+ Scope: maintenance.Scope,}storablePlannedMaintenanceRules := make([]*alertmanagertypes.StorablePlannedMaintenanceRule, 0)@@ -224,7 +226,6 @@ func (r *maintenance) UpdatePlannedMaintenance(ctx context.Context, maintenanceModel(new(alertmanagertypes.StorablePlannedMaintenanceRule)).Where("planned_maintenance_id = ?", storablePlannedMaintenance.ID.StringValue()).Exec(ctx)-if err != nil {return err}@@ -241,7 +242,6 @@ func (r *maintenance) UpdatePlannedMaintenance(ctx context.Context, maintenance}return nil-})if err != nil {return errdiff --git a/pkg/alertmanager/nfmanager/rulebasednotification/provider.go b/pkg/alertmanager/nfmanager/rulebasednotification/provider.goindex ce1526832b..10160fe71e 100644--- a/pkg/alertmanager/nfmanager/rulebasednotification/provider.go+++ b/pkg/alertmanager/nfmanager/rulebasednotification/provider.go@@ -3,7 +3,6 @@ package rulebasednotificationimport ("context""log/slog"- "strings""sync""github.com/SigNoz/signoz/pkg/alertmanager/nfmanager"@@ -235,65 +234,13 @@ func (r *provider) Match(ctx context.Context, orgID string, ruleID string, set mreturn matchedChannels, nil}-// convertLabelSetToEnv converts a flat label set with dotted keys into a nested map structure for expr env.-// when both a leaf and a deeper nested path exist (e.g. "foo" and "foo.bar"),-// the nested structure takes precedence. That means we will replace an existing leaf at any-// intermediate path with a map so we can materialize the deeper structure.-// TODO(srikanthccv): we need a better solution to handle this, remove the following-// when we update the expr to support dotted keys.+// convertLabelSetToEnv delegates to alertmanagertypes.ConvertLabelSetToEnv and+// logs when a key is a prefix of another (e.g. "foo" alongside "foo.bar").func (r *provider) convertLabelSetToEnv(ctx context.Context, labelSet model.LabelSet) map[string]interface{} {- env := make(map[string]interface{})-- logForReview := false-- for lk, lv := range labelSet {- key := strings.TrimSpace(string(lk))- value := string(lv)-- if strings.Contains(key, ".") {- parts := strings.Split(key, ".")- current := env-- for i, raw := range parts {- part := strings.TrimSpace(raw)-- last := i == len(parts)-1- if last {- if _, isMap := current[part].(map[string]interface{}); isMap {- logForReview = true- // deeper structure already exists; do not overwrite.- break- }- current[part] = value- break- }-- // ensure a map so we can keep descending.- if nextMap, ok := current[part].(map[string]interface{}); ok {- current = nextMap- continue- }-- // if absent or a leaf, replace it with a map.- newMap := make(map[string]interface{})- current[part] = newMap- current = newMap- }- continue- }-- // if a map already sits here (due to nested keys), keep the map (nested wins).- if _, isMap := env[key].(map[string]interface{}); isMap {- logForReview = true- continue- }- env[key] = value- }-- if logForReview {+ env, conflict := alertmanagertypes.ConvertLabelSetToEnv(labelSet)+ if conflict {r.settings.Logger().InfoContext(ctx, "found label set with conflicting prefix dotted keys", slog.Any("labels", labelSet))}-return env}diff --git a/pkg/alertmanager/nfmanager/rulebasednotification/provider_test.go b/pkg/alertmanager/nfmanager/rulebasednotification/provider_test.goindex 54f736742b..d2da02a27a 100644--- a/pkg/alertmanager/nfmanager/rulebasednotification/provider_test.go+++ b/pkg/alertmanager/nfmanager/rulebasednotification/provider_test.go@@ -925,72 +925,3 @@ func TestProvider_CreateRoutes(t *testing.T) {})}}--func TestConvertLabelSetToEnv(t *testing.T) {- tests := []struct {- name string- labelSet model.LabelSet- expected map[string]interface{}- }{- {- name: "simple keys",- labelSet: model.LabelSet{- "key1": "value1",- "key2": "value2",- },- expected: map[string]interface{}{- "key1": "value1",- "key2": "value2",- },- },- {- name: "nested keys",- labelSet: model.LabelSet{- "foo.bar": "value1",- "foo.baz": "value2",- },- expected: map[string]interface{}{- "foo": map[string]interface{}{- "bar": "value1",- "baz": "value2",- },- },- },- {- name: "conflict - nested structure wins",- labelSet: model.LabelSet{- "foo.bar.baz": "deep",- "foo.bar": "shallow",- },- expected: map[string]interface{}{- "foo": map[string]interface{}{- "bar": map[string]interface{}{- "baz": "deep",- },- },- },- },- {- name: "conflict - leaf value vs nested",- labelSet: model.LabelSet{- "foo.bar": "value",- "foo": "should_be_ignored",- },- expected: map[string]interface{}{- "foo": map[string]interface{}{- "bar": "value",- },- },- },- }-- provider := &provider{- settings: factory.NewScopedProviderSettings(createTestProviderSettings(), "provider_test"),- }- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- result := provider.convertLabelSetToEnv(context.Background(), tt.labelSet)- assert.Equal(t, tt.expected, result)- })- }-}diff --git a/pkg/config/envprovider/provider_test.go b/pkg/config/envprovider/provider_test.goindex 6cebb92bc5..4906a3765c 100644--- a/pkg/config/envprovider/provider_test.go+++ b/pkg/config/envprovider/provider_test.go@@ -2,6 +2,8 @@ package envproviderimport ("context"+ "os"+ "strings""testing""github.com/SigNoz/signoz/pkg/config"@@ -9,7 +11,21 @@ import ("github.com/stretchr/testify/require")+// clearSignozEnv unsets all existing SIGNOZ_* env vars for the duration of the test.+func clearSignozEnv(t *testing.T) {+ t.Helper()+ for _, kv := range os.Environ() {+ if strings.HasPrefix(kv, prefix) {+ key := strings.SplitN(kv, "=", 2)[0]+ orig, _ := os.LookupEnv(key)+ os.Unsetenv(key)+ t.Cleanup(func() { os.Setenv(key, orig) })+ }+ }+}+func TestGetWithStrings(t *testing.T) {+ clearSignozEnv(t)t.Setenv("SIGNOZ_K1_K2", "string")t.Setenv("SIGNOZ_K3__K4", "string")t.Setenv("SIGNOZ_K5__K6_K7__K8", "string")@@ -31,6 +47,7 @@ func TestGetWithStrings(t *testing.T) {}func TestGetWithNoPrefix(t *testing.T) {+ clearSignozEnv(t)t.Setenv("K1_K2", "string")t.Setenv("K3_K4", "string")expected := map[string]any{}@@ -43,6 +60,7 @@ func TestGetWithNoPrefix(t *testing.T) {}func TestGetWithGoTypes(t *testing.T) {+ clearSignozEnv(t)t.Setenv("SIGNOZ_BOOL", "true")t.Setenv("SIGNOZ_STRING", "string")t.Setenv("SIGNOZ_INT", "1")diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.goindex a7278b5310..6c6ad226b5 100644--- a/pkg/signoz/provider.go+++ b/pkg/signoz/provider.go@@ -206,6 +206,7 @@ func NewSQLMigrationProviderFactories(sqlmigration.NewAddIntegrationDashboardFactory(sqlstore, sqlschema),sqlmigration.NewAddSourceToDashboardFactory(sqlstore, sqlschema),sqlmigration.NewMigrateCloudIntegrationDashboardsFactory(sqlstore),+ sqlmigration.NewAddScopeToPlannedMaintenanceFactory(sqlstore, sqlschema),)}diff --git a/pkg/sqlmigration/087_add_scope_to_planned_maintenance.go b/pkg/sqlmigration/087_add_scope_to_planned_maintenance.gonew file mode 100644index 0000000000..41bca48370--- /dev/null+++ b/pkg/sqlmigration/087_add_scope_to_planned_maintenance.go@@ -0,0 +1,70 @@+package sqlmigration++import (+ "context"++ "github.com/SigNoz/signoz/pkg/factory"+ "github.com/SigNoz/signoz/pkg/sqlschema"+ "github.com/SigNoz/signoz/pkg/sqlstore"+ "github.com/uptrace/bun"+ "github.com/uptrace/bun/migrate"+)++type addScopeToPlannedMaintenance struct {+ sqlstore sqlstore.SQLStore+ sqlschema sqlschema.SQLSchema+}++func NewAddScopeToPlannedMaintenanceFactory(sqlstore sqlstore.SQLStore, sqlschema sqlschema.SQLSchema) factory.ProviderFactory[SQLMigration, Config] {+ return factory.NewProviderFactory(+ factory.MustNewName("add_scope_to_planned"),+ func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {+ return &addScopeToPlannedMaintenance{+ sqlstore: sqlstore,+ sqlschema: sqlschema,+ }, nil+ },+ )+}++func (migration *addScopeToPlannedMaintenance) Register(migrations *migrate.Migrations) error {+ if err := migrations.Register(migration.Up, migration.Down); err != nil {+ return err+ }+ return nil+}++func (migration *addScopeToPlannedMaintenance) Up(ctx context.Context, db *bun.DB) error {+ tx, err := db.BeginTx(ctx, nil)+ if err != nil {+ return err+ }++ defer func() {+ _ = tx.Rollback()+ }()++ table, _, err := migration.sqlschema.GetTable(ctx, "planned_maintenance")+ if err != nil {+ return err+ }++ column := &sqlschema.Column{+ Name: sqlschema.ColumnName("scope"),+ DataType: sqlschema.DataTypeText,+ Nullable: true,+ }++ sqls := migration.sqlschema.Operator().AddColumn(table, nil, column, nil)+ for _, sql := range sqls {+ if _, err := tx.ExecContext(ctx, string(sql)); err != nil {+ return err+ }+ }++ return tx.Commit()+}++func (migration *addScopeToPlannedMaintenance) Down(ctx context.Context, db *bun.DB) error {+ return nil+}diff --git a/pkg/types/alertmanagertypes/expression.go b/pkg/types/alertmanagertypes/expression.gonew file mode 100644index 0000000000..783ce37dea--- /dev/null+++ b/pkg/types/alertmanagertypes/expression.go@@ -0,0 +1,88 @@+package alertmanagertypes++import (+ "strings"++ "github.com/expr-lang/expr"+ "github.com/prometheus/common/model"++ "github.com/SigNoz/signoz/pkg/errors"+)++var ErrCodeInvalidScopeExpression = errors.MustNewCode("invalid_scope_expression")++// ConvertLabelSetToEnv converts a label set into a map suitable for use as an+// expr environment. Dotted keys (e.g. "kubernetes.node") are expanded into+// nested maps so that expr can resolve them without panicking. When a dotted+// path conflicts with a plain key, the nested structure takes precedence.+//+// The second return value reports whether such a prefix conflict was detected+// (a plain key collided with a nested map, or a nested path overwrote a plain+// leaf).+func ConvertLabelSetToEnv(lset model.LabelSet) (map[string]any, bool) {+ env := map[string]any{}+ conflict := false+ for lk, lv := range lset {+ key := strings.TrimSpace(string(lk))+ value := string(lv)+ if strings.Contains(key, ".") {+ parts := strings.Split(key, ".")+ current := env+ for i, raw := range parts {+ part := strings.TrimSpace(raw)+ if i == len(parts)-1 {+ // Last segment: if a nested map already exists here, a+ // deeper path has been processed first — keep it and flag.+ if _, isMap := current[part].(map[string]any); isMap {+ conflict = true+ break+ }+ current[part] = value+ break+ }+ if nextMap, ok := current[part].(map[string]any); ok {+ current = nextMap+ } else {+ // Intermediate segment hit a plain leaf — overwrite with a+ // map so the deeper path can be materialised, and flag.+ if _, exists := current[part]; exists {+ conflict = true+ }+ newMap := map[string]any{}+ current[part] = newMap+ current = newMap+ }+ }+ continue+ }+ // Plain key collides with an already-built nested map — keep the map+ // (nested wins) and flag.+ if _, isMap := env[key].(map[string]any); isMap {+ conflict = true+ continue+ }+ env[key] = value+ }+ 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())+ if err != nil {+ return false, errors.Wrapf(err, errors.TypeInvalidInput, ErrCodeInvalidScopeExpression, "compile scope 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)+ }+ 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 result, nil+}diff --git a/pkg/types/alertmanagertypes/expression_test.go b/pkg/types/alertmanagertypes/expression_test.gonew file mode 100644index 0000000000..a3527c0174--- /dev/null+++ b/pkg/types/alertmanagertypes/expression_test.go@@ -0,0 +1,163 @@+package alertmanagertypes++import (+ "reflect"+ "testing"++ "github.com/prometheus/common/model"+)++func TestEvalScopeExpression(t *testing.T) {+ cases := []struct {+ name string+ expression string+ lset model.LabelSet+ want bool+ wantErr bool+ }{+ {+ name: "equality match",+ expression: `env = "production"`,+ lset: model.LabelSet{"env": "production"},+ want: true,+ },+ {+ name: "equality no match",+ expression: `env = "production"`,+ lset: model.LabelSet{"env": "staging"},+ want: false,+ },+ {+ name: "inequality match",+ expression: `env != "production"`,+ lset: model.LabelSet{"env": "staging"},+ want: true,+ },+ {+ name: "AND - both match",+ expression: `env = "production" AND service = "api"`,+ lset: model.LabelSet{"env": "production", "service": "api"},+ want: true,+ },+ {+ name: "AND - partial match",+ expression: `env = "production" AND service = "api"`,+ lset: model.LabelSet{"env": "production", "service": "worker"},+ want: false,+ },+ {+ name: "OR - first matches",+ expression: `env = "production" OR env = "staging"`,+ lset: model.LabelSet{"env": "production"},+ want: true,+ },+ {+ name: "OR - second matches",+ expression: `env = "production" OR env = "staging"`,+ lset: model.LabelSet{"env": "staging"},+ want: true,+ },+ {+ name: "OR - none match",+ expression: `env = "production" OR env = "staging"`,+ lset: model.LabelSet{"env": "development"},+ want: false,+ },+ {+ name: "undefined label returns false",+ expression: `env = "production"`,+ lset: model.LabelSet{"service": "api"},+ want: false,+ },+ {+ name: "in list - present",+ expression: `env in ["production", "staging"]`,+ lset: model.LabelSet{"env": "production"},+ want: true,+ },+ {+ name: "in list - absent",+ expression: `env in ["production", "staging"]`,+ lset: model.LabelSet{"env": "development"},+ want: false,+ },+ {+ name: "invalid expression returns error",+ expression: `env =`,+ lset: model.LabelSet{"env": "production"},+ want: false,+ wantErr: true,+ },+ {+ name: "non-bool expression returns error",+ expression: `env`,+ lset: model.LabelSet{"env": "production"},+ want: false,+ wantErr: 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)+ }+ })+ }+}++func TestConvertLabelSetToEnv(t *testing.T) {+ cases := []struct {+ name string+ lset model.LabelSet+ expected map[string]interface{}+ wantConflict bool+ }{+ {+ name: "simple keys",+ lset: model.LabelSet{"key1": "value1", "key2": "value2"},+ expected: map[string]interface{}{"key1": "value1", "key2": "value2"},+ },+ {+ name: "dotted keys become nested maps",+ lset: model.LabelSet{"foo.bar": "value1", "foo.baz": "value2"},+ expected: map[string]interface{}{+ "foo": map[string]interface{}{"bar": "value1", "baz": "value2"},+ },+ },+ {+ name: "deeper dotted key wins over shallow dotted key",+ lset: model.LabelSet{"foo.bar.baz": "deep", "foo.bar": "shallow"},+ expected: map[string]interface{}{+ "foo": map[string]interface{}{+ "bar": map[string]interface{}{"baz": "deep"},+ },+ },+ wantConflict: true,+ },+ {+ name: "nested structure wins over plain key",+ lset: model.LabelSet{"foo.bar": "value", "foo": "ignored"},+ expected: map[string]interface{}{+ "foo": map[string]interface{}{"bar": "value"},+ },+ wantConflict: true,+ },+ }++ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ got, gotConflict := ConvertLabelSetToEnv(c.lset)+ if !reflect.DeepEqual(got, c.expected) {+ t.Errorf("ConvertLabelSetToEnv() map = %v, want %v", got, c.expected)+ }+ if gotConflict != c.wantConflict {+ t.Errorf("ConvertLabelSetToEnv() conflict = %v, want %v", gotConflict, c.wantConflict)+ }+ })+ }+}diff --git a/pkg/types/alertmanagertypes/maintenance.go b/pkg/types/alertmanagertypes/maintenance.goindex e136e26291..8592417a3e 100644--- a/pkg/types/alertmanagertypes/maintenance.go+++ b/pkg/types/alertmanagertypes/maintenance.go@@ -5,14 +5,19 @@ import ("encoding/json""time"+ "github.com/expr-lang/expr"+ "github.com/prometheus/common/model"+ "github.com/uptrace/bun"+"github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/types""github.com/SigNoz/signoz/pkg/valuer"- "github.com/uptrace/bun")var ErrCodeInvalidPlannedMaintenancePayload = errors.MustNewCode("invalid_planned_maintenance_payload")+const scopeDocUrl = "https://signoz.io/docs/alerts-management/planned-maintenance/#scoping-with-label-expressions"+type MaintenanceStatus struct {valuer.String}@@ -58,6 +63,7 @@ type StorablePlannedMaintenance struct {Description string `bun:"description,type:text"`Schedule *Schedule `bun:"schedule,type:text,notnull"`OrgID string `bun:"org_id,type:text"`+ Scope string `bun:"scope,type:text"`}type PlannedMaintenance struct {@@ -66,6 +72,7 @@ type PlannedMaintenance struct {Description string `json:"description"`Schedule *Schedule `json:"schedule" required:"true"`RuleIDs []string `json:"alertIds"`+ Scope string `json:"scope,omitempty"`CreatedAt time.Time `json:"createdAt"`CreatedBy string `json:"createdBy"`UpdatedAt time.Time `json:"updatedAt"`@@ -82,6 +89,7 @@ type PostablePlannedMaintenance struct {Description string `json:"description"`Schedule *Schedule `json:"schedule" required:"true"`AlertIds []string `json:"alertIds"`+ Scope string `json:"scope"`}func (p *PostablePlannedMaintenance) Validate() error {@@ -116,6 +124,15 @@ func (p *PostablePlannedMaintenance) Validate() error {return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "end time cannot be before start time")}}+ if p.Scope != "" {+ if _, err := expr.Compile(p.Scope, expr.AllowUndefinedVariables(), expr.AsBool()); err != nil {+ err := errors.Newf(+ errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload,+ "invalid scope: %s", err.Error(),+ )+ return err.WithUrl(scopeDocUrl)+ }+ }return nil}@@ -151,7 +168,7 @@ func (m *PlannedMaintenance) HasScheduleRecurrenceBoundsMismatch() bool {(recurrence.EndTime != nil && !recurrence.EndTime.Equal(m.Schedule.EndTime))}-func (m *PlannedMaintenance) ShouldSkip(ruleID string, now time.Time) bool {+func (m *PlannedMaintenance) ShouldSkip(ruleID string, now time.Time, lset model.LabelSet) (bool, error) {// Check if the alert ID is in the maintenance windowfound := falseif len(m.RuleIDs) > 0 {@@ -168,9 +185,27 @@ func (m *PlannedMaintenance) ShouldSkip(ruleID string, now time.Time) bool {}if !found {- return false+ return false, nil}+ if !m.IsActive(now) {+ return false, nil+ }++ if m.Scope != "" {+ result, err := EvalScopeExpression(m.Scope, lset)+ if err != nil {+ return false, err+ }+ if !result {+ return false, nil+ }+ }+ return true, nil+}++// IsActive reports whether [now] falls inside the maintenance window's schedule.+func (m *PlannedMaintenance) IsActive(now time.Time) bool {// If alert is found, we check if it should be skipped based on the scheduleloc, err := time.LoadLocation(m.Schedule.Timezone)if err != nil {@@ -301,14 +336,6 @@ func (m *PlannedMaintenance) checkMonthly(currentTime time.Time, rec *Recurrencereturn currentTime.Sub(candidate) <= rec.Duration.Duration()}-func (m *PlannedMaintenance) IsActive(now time.Time) bool {- ruleID := "maintenance"- if len(m.RuleIDs) > 0 {- ruleID = (m.RuleIDs)[0]- }- return m.ShouldSkip(ruleID, now)-}-func (m *PlannedMaintenance) IsUpcoming() bool {loc, err := time.LoadLocation(m.Schedule.Timezone)if err != nil {@@ -389,6 +416,7 @@ func (m PlannedMaintenance) MarshalJSON() ([]byte, error) {Description string `json:"description" db:"description"`Schedule *Schedule `json:"schedule" db:"schedule"`AlertIds []string `json:"alertIds" db:"alert_ids"`+ Scope string `json:"scope,omitempty" db:"scope"`CreatedAt time.Time `json:"createdAt" db:"created_at"`CreatedBy string `json:"createdBy" db:"created_by"`UpdatedAt time.Time `json:"updatedAt" db:"updated_at"`@@ -401,6 +429,7 @@ func (m PlannedMaintenance) MarshalJSON() ([]byte, error) {Description: m.Description,Schedule: m.Schedule,AlertIds: m.RuleIDs,+ Scope: m.Scope,CreatedAt: m.CreatedAt,CreatedBy: m.CreatedBy,UpdatedAt: m.UpdatedAt,@@ -424,6 +453,7 @@ func (m *PlannedMaintenanceWithRules) ToPlannedMaintenance() *PlannedMaintenanceDescription: m.Description,Schedule: m.Schedule,RuleIDs: ruleIDs,+ Scope: m.Scope,CreatedAt: m.CreatedAt,UpdatedAt: m.UpdatedAt,CreatedBy: m.CreatedBy,diff --git a/pkg/types/alertmanagertypes/maintenance_test.go b/pkg/types/alertmanagertypes/maintenance_test.goindex 4c0443bd6f..4940af7f78 100644--- a/pkg/types/alertmanagertypes/maintenance_test.go+++ b/pkg/types/alertmanagertypes/maintenance_test.go@@ -5,6 +5,7 @@ import ("time""github.com/SigNoz/signoz/pkg/valuer"+ "github.com/prometheus/common/model")// Helper function to create a time pointer.@@ -668,9 +669,193 @@ func TestShouldSkipMaintenance(t *testing.T) {}for idx, c := range cases {- result := c.maintenance.ShouldSkip(c.name, c.ts)+ result, err := c.maintenance.ShouldSkip(c.name, c.ts, model.LabelSet{})+ if err != nil {+ t.Errorf("unexpected error: %v", err)+ }if result != c.skip {t.Errorf("skip %v, got %v, case:%d - %s", c.skip, result, idx, c.name)}}}++func TestShouldSkip_Scope(t *testing.T) {+ activeSchedule := func() *Schedule {+ return &Schedule{+ Timezone: "UTC",+ StartTime: time.Now().UTC().Add(-time.Hour),+ EndTime: time.Now().UTC().Add(time.Hour),+ }+ }+ now := time.Now().UTC()++ cases := []struct {+ name string+ maintenance *PlannedMaintenance+ ruleID string+ ts time.Time+ lset model.LabelSet+ skip bool+ }{+ {+ name: "empty scope - no label filtering applied",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule()},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"env": "production"},+ skip: true,+ },+ {+ name: "scope matches labels",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production"`},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"env": "production"},+ skip: true,+ },+ {+ name: "scope does not match labels",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production"`},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"env": "staging"},+ skip: false,+ },+ {+ name: "AND expression - both conditions match",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production" AND service = "api"`},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"env": "production", "service": "api"},+ skip: true,+ },+ {+ name: "AND expression - one condition does not match",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production" AND service = "api"`},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"env": "production", "service": "worker"},+ skip: false,+ },+ {+ name: "OR expression - first alternative matches",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production" OR env = "staging"`},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"env": "production"},+ skip: true,+ },+ {+ name: "OR expression - second alternative matches",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production" OR env = "staging"`},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"env": "staging"},+ skip: true,+ },+ {+ name: "OR expression - neither alternative matches",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production" OR env = "staging"`},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"env": "development"},+ skip: false,+ },+ {+ name: "scope references label absent from lset",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production"`},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"service": "api"},+ skip: false,+ },+ {+ name: "in expression - value is in list",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env in ["production", "staging"]`},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"env": "staging"},+ skip: true,+ },+ {+ name: "in expression - value not in list",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env in ["production", "staging"]`},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"env": "development"},+ skip: false,+ },+ {+ name: "ruleID in list and scope matches - should skip",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule(), RuleIDs: []string{"rule-1", "rule-2"}, Scope: `env = "production"`},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"env": "production"},+ skip: true,+ },+ {+ name: "ruleID not in list and scope matches - ruleID gate prevents skip",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule(), RuleIDs: []string{"rule-2"}, Scope: `env = "production"`},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"env": "production"},+ skip: false,+ },+ {+ name: "ruleID in list but scope does not match - should not skip",+ maintenance: &PlannedMaintenance{Schedule: activeSchedule(), RuleIDs: []string{"rule-1"}, Scope: `env = "production"`},+ ruleID: "rule-1",+ ts: now,+ lset: model.LabelSet{"env": "staging"},+ skip: false,+ },+ }++ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ got, err := c.maintenance.ShouldSkip(c.ruleID, c.ts, c.lset)+ if err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ if got != c.skip {+ t.Errorf("ShouldSkip() = %v, want %v", got, c.skip)+ }+ })+ }+}++func TestPostablePlannedMaintenance_ValidateScope(t *testing.T) {+ validSchedule := &Schedule{+ Timezone: "UTC",+ StartTime: time.Now().UTC(),+ EndTime: time.Now().UTC().Add(time.Hour),+ }++ cases := []struct {+ name string+ scope string+ wantErr bool+ }{+ {name: "empty scope", scope: "", wantErr: false},+ {name: "simple equality", scope: `env = "production"`, wantErr: false},+ {name: "AND expression", scope: `env = "production" AND service = "api"`, wantErr: false},+ {name: "OR expression", scope: `env = "production" OR env = "staging"`, wantErr: false},+ {name: "in expression", scope: `env in ["production", "staging"]`, wantErr: false},+ {name: "incomplete expression", scope: `env =`, wantErr: true},+ {name: "non-bool expression", scope: `"just a string"`, wantErr: true},+ }++ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ p := &PostablePlannedMaintenance{+ Name: "test",+ Schedule: validSchedule,+ Scope: c.scope,+ }+ err := p.Validate()+ if (err != nil) != c.wantErr {+ t.Errorf("Validate() error = %v, wantErr %v", err, c.wantErr)+ }+ })+ }+}diff --git a/pkg/types/alertmanagertypes/schedule.go b/pkg/types/alertmanagertypes/schedule.goindex 96eabba3ee..bec275d2cc 100644--- a/pkg/types/alertmanagertypes/schedule.go+++ b/pkg/types/alertmanagertypes/schedule.go@@ -108,6 +108,7 @@ func (s *Schedule) UnmarshalJSON(data []byte) error {if err != nil {return err}+ // TODO(jatinderjit): if endTime.IsZero() then we should not set the endTimes.EndTime = time.Date(endTime.Year(), endTime.Month(), endTime.Day(), endTime.Hour(), endTime.Minute(), endTime.Second(), endTime.Nanosecond(), loc)}