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(ruletypes): address rule read round-trip gaps (#12110)

Srikanth Chekuri16c1fce326ac
diff --git a/pkg/types/ruletypes/api_params.go b/pkg/types/ruletypes/api_params.go
index 976e88f5a3..ed4d24de81 100644
--- a/pkg/types/ruletypes/api_params.go
+++ b/pkg/types/ruletypes/api_params.go
@@ -76,9 +76,9 @@ type PostableRule struct {
}
type NotificationSettings struct {
- GroupBy []string `json:"groupBy,omitempty"`
- Renotify Renotify `json:"renotify,omitzero"`
- UsePolicy bool `json:"usePolicy,omitempty"`
+ GroupBy []string `json:"groupBy,omitempty"`
+ Renotify *Renotify `json:"renotify,omitempty"`
+ UsePolicy bool `json:"usePolicy,omitempty"`
// NewGroupEvalDelay is the grace period for new series to be excluded from alerts evaluation
NewGroupEvalDelay valuer.TextDuration `json:"newGroupEvalDelay,omitzero"`
}
@@ -92,7 +92,7 @@ type Renotify struct {
func (ns *NotificationSettings) GetAlertManagerNotificationConfig() alertmanagertypes.NotificationConfig {
var renotifyInterval time.Duration
var noDataRenotifyInterval time.Duration
- if ns.Renotify.Enabled {
+ if ns.Renotify != nil && ns.Renotify.Enabled {
if slices.Contains(ns.Renotify.AlertStates, StateNoData) {
noDataRenotifyInterval = ns.Renotify.ReNotifyInterval.Duration()
}
@@ -204,10 +204,12 @@ func (ns *NotificationSettings) UnmarshalJSON(data []byte) error {
}
// Validate states after unmarshaling
- for _, state := range ns.Renotify.AlertStates {
- if state != StateFiring && state != StateNoData {
- return errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid alert state: %s", state)
+ if ns.Renotify != nil {
+ for _, state := range ns.Renotify.AlertStates {
+ if state != StateFiring && state != StateNoData {
+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid alert state: %s", state)
+ }
}
}
return nil
@@ -220,6 +222,11 @@ func (r *PostableRule) processRuleDefaults() {
r.SchemaVersion = DefaultSchemaVersion
}
+ // TODO(srikanthccv): remove as this is now a legacy field
+ if r.Version == "" {
+ r.Version = "v5"
+ }
+
// v2alpha1 uses the Evaluation envelope for window/frequency;
// only default top-level fields for v1.
if r.SchemaVersion != SchemaVersionV2Alpha1 {
@@ -271,7 +278,7 @@ func (r *PostableRule) processRuleDefaults() {
r.RuleCondition.Thresholds = &thresholdData
r.Evaluation = &EvaluationEnvelope{RollingEvaluation, RollingWindow{EvalWindow: r.EvalWindow, Frequency: r.Frequency}}
r.NotificationSettings = &NotificationSettings{
- Renotify: Renotify{
+ Renotify: &Renotify{
Enabled: true,
ReNotifyInterval: valuer.MustParseTextDuration("4h"),
AlertStates: []AlertState{StateFiring},
@@ -557,7 +564,7 @@ func (r *PostableRule) validateV2Alpha1() []error {
errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,
"notificationSettings: field is required for schemaVersion %q", SchemaVersionV2Alpha1))
} else {
- if r.NotificationSettings.Renotify.Enabled && !r.NotificationSettings.Renotify.ReNotifyInterval.IsPositive() {
+ if r.NotificationSettings.Renotify != nil && r.NotificationSettings.Renotify.Enabled && !r.NotificationSettings.Renotify.ReNotifyInterval.IsPositive() {
errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,
"notificationSettings.renotify.interval: must be a positive duration when renotify is enabled"))
}
diff --git a/pkg/types/ruletypes/api_params_test.go b/pkg/types/ruletypes/api_params_test.go
index cfea8aa266..bdb967b3cd 100644
--- a/pkg/types/ruletypes/api_params_test.go
+++ b/pkg/types/ruletypes/api_params_test.go
@@ -6,6 +6,7 @@ import (
"time"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
@@ -1327,3 +1328,27 @@ func TestAnomalyNegationEval(t *testing.T) {
})
}
}
+
+func TestVersionDefaultsToV5(t *testing.T) {
+ content := `{
+ "alert": "cpu high",
+ "alertType": "METRIC_BASED_ALERT",
+ "ruleType": "threshold_rule",
+ "schemaVersion": "v2alpha1",
+ "condition": {
+ "compositeQuery": {
+ "queries": [{"type": "promql", "spec": {"name": "A", "query": "up"}}],
+ "panelType": "graph",
+ "queryType": "promql"
+ },
+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90, "matchType": "1", "op": "1"}]}
+ },
+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},
+ "notificationSettings": {"usePolicy": false}
+ }`
+
+ rule := PostableRule{}
+ require.NoError(t, json.Unmarshal([]byte(content), &rule))
+ assert.Equal(t, "v5", rule.Version)
+ assert.NoError(t, rule.Validate())
+}
diff --git a/pkg/types/ruletypes/roundtrip_test.go b/pkg/types/ruletypes/roundtrip_test.go
new file mode 100644
index 0000000000..5daac5a444
--- /dev/null
+++ b/pkg/types/ruletypes/roundtrip_test.go
@@ -0,0 +1,258 @@
+package ruletypes
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func readBody(t *testing.T, stored string) map[string]json.RawMessage {
+ t.Helper()
+ g := GettableRule{}
+ require.NoError(t, json.Unmarshal([]byte(stored), &g))
+ out, err := json.Marshal(NewRule(&g))
+ require.NoError(t, err)
+ var body map[string]json.RawMessage
+ require.NoError(t, json.Unmarshal(out, &body))
+ return body
+}
+
+func TestV2RoundTripRolling(t *testing.T) {
+ thresholds := `{
+ "kind": "basic",
+ "spec": [
+ {"name": "critical", "target": 90.5, "targetUnit": "%", "recoveryTarget": 80.5, "matchType": "at_least_once", "op": "above", "channels": ["slack-critical"]},
+ {"name": "warning", "target": 75, "targetUnit": "%", "matchType": "at_least_once", "op": "above", "channels": ["slack-warnings", "email-oncall"]}
+ ]
+ }`
+ thresholdsEchoed := `{
+ "kind": "basic",
+ "spec": [
+ {"name": "critical", "target": 90.5, "targetUnit": "%", "recoveryTarget": 80.5, "matchType": "at_least_once", "op": "above", "channels": ["slack-critical"]},
+ {"name": "warning", "target": 75, "targetUnit": "%", "recoveryTarget": null, "matchType": "at_least_once", "op": "above", "channels": ["slack-warnings", "email-oncall"]}
+ ]
+ }`
+ evaluation := `{"kind": "rolling", "spec": {"evalWindow": "90m", "frequency": "90s"}}`
+ notificationSettings := `{
+ "groupBy": ["service.name", "deployment.environment"],
+ "renotify": {"enabled": true, "interval": "45m", "alertStates": ["firing", "nodata"]},
+ "usePolicy": true,
+ "newGroupEvalDelay": "10m"
+ }`
+ labels := `{"team": "infra", "severity": "critical"}`
+ annotations := `{"summary": "CPU above {{$threshold}}", "description": "value {{$value}}"}`
+
+ stored := `{
+ "alert": "cpu high",
+ "alertType": "METRIC_BASED_ALERT",
+ "description": "watches cpu",
+ "ruleType": "promql_rule",
+ "schemaVersion": "v2alpha1",
+ "version": "v5",
+ "disabled": true,
+ "labels": ` + labels + `,
+ "annotations": ` + annotations + `,
+ "condition": {
+ "compositeQuery": {
+ "queries": [{"type": "promql", "spec": {"name": "A", "query": "avg(cpu_usage)"}}],
+ "panelType": "graph",
+ "queryType": "promql",
+ "unit": "percent"
+ },
+ "selectedQueryName": "A",
+ "alertOnAbsent": true,
+ "absentFor": 10,
+ "requireMinPoints": true,
+ "requiredNumPoints": 4,
+ "thresholds": ` + thresholds + `
+ },
+ "evaluation": ` + evaluation + `,
+ "notificationSettings": ` + notificationSettings + `
+ }`
+
+ body := readBody(t, stored)
+
+ assert.JSONEq(t, `"cpu high"`, string(body["alert"]))
+ assert.JSONEq(t, `"METRIC_BASED_ALERT"`, string(body["alertType"]))
+ assert.JSONEq(t, `"watches cpu"`, string(body["description"]))
+ assert.JSONEq(t, `"promql_rule"`, string(body["ruleType"]))
+ assert.JSONEq(t, `"v2alpha1"`, string(body["schemaVersion"]))
+ assert.JSONEq(t, `true`, string(body["disabled"]))
+ assert.JSONEq(t, labels, string(body["labels"]))
+ assert.JSONEq(t, annotations, string(body["annotations"]))
+ assert.JSONEq(t, evaluation, string(body["evaluation"]))
+ assert.JSONEq(t, notificationSettings, string(body["notificationSettings"]))
+
+ var condition map[string]json.RawMessage
+ require.NoError(t, json.Unmarshal(body["condition"], &condition))
+ assert.JSONEq(t, thresholdsEchoed, string(condition["thresholds"]))
+ assert.JSONEq(t, `"A"`, string(condition["selectedQueryName"]))
+ assert.JSONEq(t, `true`, string(condition["alertOnAbsent"]))
+ assert.JSONEq(t, `10`, string(condition["absentFor"]))
+ assert.JSONEq(t, `true`, string(condition["requireMinPoints"]))
+ assert.JSONEq(t, `4`, string(condition["requiredNumPoints"]))
+}
+
+func TestV2RoundTripCumulative(t *testing.T) {
+ evaluation := `{
+ "kind": "cumulative",
+ "spec": {
+ "schedule": {"type": "daily", "minute": 30, "hour": 9},
+ "frequency": "5m",
+ "timezone": "America/New_York"
+ }
+ }`
+
+ stored := `{
+ "alert": "daily budget",
+ "alertType": "METRIC_BASED_ALERT",
+ "ruleType": "threshold_rule",
+ "schemaVersion": "v2alpha1",
+ "condition": {
+ "compositeQuery": {
+ "queries": [{"type": "promql", "spec": {"name": "A", "query": "sum(cost)"}}],
+ "panelType": "graph",
+ "queryType": "promql"
+ },
+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 100, "matchType": "at_least_once", "op": "above"}]}
+ },
+ "evaluation": ` + evaluation + `,
+ "notificationSettings": {"usePolicy": false}
+ }`
+
+ body := readBody(t, stored)
+ assert.JSONEq(t, evaluation, string(body["evaluation"]))
+}
+
+func TestV2MinimalReadShape(t *testing.T) {
+ stored := `{
+ "alert": "minimal",
+ "alertType": "METRIC_BASED_ALERT",
+ "ruleType": "threshold_rule",
+ "schemaVersion": "v2alpha1",
+ "condition": {
+ "compositeQuery": {
+ "queries": [{"type": "promql", "spec": {"name": "A", "query": "up"}}],
+ "panelType": "graph",
+ "queryType": "promql"
+ },
+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90, "matchType": "at_least_once", "op": "above"}]}
+ },
+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},
+ "notificationSettings": {"usePolicy": false}
+ }`
+
+ body := readBody(t, stored)
+
+ for _, field := range []string{"labels", "annotations", "description", "preferredChannels", "evalWindow", "frequency"} {
+ assert.NotContains(t, body, field)
+ }
+
+ var ns map[string]json.RawMessage
+ require.NoError(t, json.Unmarshal(body["notificationSettings"], &ns))
+ for _, field := range []string{"renotify", "groupBy", "newGroupEvalDelay", "usePolicy"} {
+ assert.NotContains(t, ns, field, "notificationSettings.%s", field)
+ }
+
+ assert.JSONEq(t, `false`, string(body["disabled"]))
+ assert.JSONEq(t, `"v5"`, string(body["version"]))
+
+ var condition struct {
+ Thresholds struct {
+ Spec []map[string]json.RawMessage `json:"spec"`
+ } `json:"thresholds"`
+ }
+ require.NoError(t, json.Unmarshal(body["condition"], &condition))
+ require.Len(t, condition.Thresholds.Spec, 1)
+ spec := condition.Thresholds.Spec[0]
+ assert.JSONEq(t, `""`, string(spec["targetUnit"]))
+ assert.JSONEq(t, `null`, string(spec["channels"]))
+ assert.JSONEq(t, `null`, string(spec["recoveryTarget"]))
+}
+
+func TestRenotifyRoundTrip(t *testing.T) {
+ base := `{
+ "alert": "cpu high",
+ "alertType": "METRIC_BASED_ALERT",
+ "ruleType": "threshold_rule",
+ "schemaVersion": "v2alpha1",
+ "condition": {
+ "compositeQuery": {
+ "queries": [{"type": "promql", "spec": {"name": "A", "query": "up"}}],
+ "panelType": "graph",
+ "queryType": "promql"
+ },
+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90, "matchType": "at_least_once", "op": "above"}]}
+ },
+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},
+ "notificationSettings": %s
+ }`
+
+ cases := []struct {
+ name string
+ settings string
+ wantRenotify string
+ }{
+ {
+ name: "absent renotify stays absent",
+ settings: `{"usePolicy": false}`,
+ },
+ {
+ name: "explicitly disabled renotify is echoed",
+ settings: `{"renotify": {"enabled": false}}`,
+ wantRenotify: `{"enabled": false}`,
+ },
+ {
+ name: "enabled renotify with states is echoed",
+ settings: `{"renotify": {"enabled": true, "interval": "30m", "alertStates": ["firing"]}}`,
+ wantRenotify: `{"enabled": true, "interval": "30m", "alertStates": ["firing"]}`,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ body := readBody(t, strings.Replace(base, "%s", tc.settings, 1))
+ var ns map[string]json.RawMessage
+ require.NoError(t, json.Unmarshal(body["notificationSettings"], &ns))
+ if tc.wantRenotify == "" {
+ assert.NotContains(t, ns, "renotify")
+ } else {
+ assert.JSONEq(t, tc.wantRenotify, string(ns["renotify"]))
+ }
+ })
+ }
+}
+
+func TestPatchMergePreservesUnpatchedFields(t *testing.T) {
+ stored := `{
+ "alert": "cpu high",
+ "alertType": "METRIC_BASED_ALERT",
+ "ruleType": "threshold_rule",
+ "schemaVersion": "v2alpha1",
+ "condition": {
+ "compositeQuery": {
+ "queries": [{"type": "promql", "spec": {"name": "A", "query": "up"}}],
+ "panelType": "graph",
+ "queryType": "promql"
+ },
+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90, "matchType": "at_least_once", "op": "above"}]}
+ },
+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},
+ "notificationSettings": {"renotify": {"enabled": true, "interval": "30m", "alertStates": ["firing"]}}
+ }`
+
+ rule := PostableRule{}
+ require.NoError(t, json.Unmarshal([]byte(stored), &rule))
+ require.NoError(t, json.Unmarshal([]byte(`{"disabled": true}`), &rule))
+ require.NoError(t, rule.Validate())
+
+ assert.True(t, rule.Disabled)
+ assert.NotNil(t, rule.RuleCondition.Thresholds)
+ assert.NotNil(t, rule.Evaluation)
+ require.NotNil(t, rule.NotificationSettings)
+ require.NotNil(t, rule.NotificationSettings.Renotify)
+ assert.True(t, rule.NotificationSettings.Renotify.Enabled)
+}
diff --git a/pkg/types/ruletypes/validate_test.go b/pkg/types/ruletypes/validate_test.go
index 4480176b0c..721e3c0394 100644
--- a/pkg/types/ruletypes/validate_test.go
+++ b/pkg/types/ruletypes/validate_test.go
@@ -169,12 +169,10 @@ func TestValidate_PostableRule_Common(t *testing.T) {
errSubstr: "alert",
},
- // only "v5" is allowed
+ // only "v5" is allowed; missing/empty defaults to "v5"
{
- name: "missing version",
- json: removeField(validV1Builder(), "version"),
- wantErr: true,
- errSubstr: "version",
+ name: "missing version defaults to v5",
+ json: removeField(validV1Builder(), "version"),
},
{
name: "wrong version v4",
@@ -189,10 +187,8 @@ func TestValidate_PostableRule_Common(t *testing.T) {
errSubstr: "version",
},
{
- name: "empty version",
- json: patchJSON(validV1Builder(), `{"version": ""}`),
- wantErr: true,
- errSubstr: "version",
+ name: "empty version defaults to v5",
+ json: patchJSON(validV1Builder(), `{"version": ""}`),
},
// alert type, capital case to avoid breaking changes