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
chore: add schema version specific validations (#10808)
Srikanth Chekuri1eb27d0bc4c5
diff --git a/ee/query-service/rules/anomaly.go b/ee/query-service/rules/anomaly.goindex 46fc89c1e5..a9dcfff891 100644--- a/ee/query-service/rules/anomaly.go+++ b/ee/query-service/rules/anomaly.go@@ -5,7 +5,6 @@ import ("encoding/json""fmt""log/slog"- "strings""sync""time"@@ -64,12 +63,12 @@ func NewAnomalyRule(BaseRule: baseRule,}- switch strings.ToLower(p.RuleCondition.Seasonality) {- case "hourly":+ switch p.RuleCondition.Seasonality {+ case ruletypes.SeasonalityHourly:t.seasonality = anomaly.SeasonalityHourly- case "daily":+ case ruletypes.SeasonalityDaily:t.seasonality = anomaly.SeasonalityDaily- case "weekly":+ case ruletypes.SeasonalityWeekly:t.seasonality = anomaly.SeasonalityWeeklydefault:t.seasonality = anomaly.SeasonalityDailydiff --git a/ee/query-service/rules/anomaly_test.go b/ee/query-service/rules/anomaly_test.goindex 876509be80..81c7e8094a 100644--- a/ee/query-service/rules/anomaly_test.go+++ b/ee/query-service/rules/anomaly_test.go@@ -67,7 +67,7 @@ func TestAnomalyRule_NoData_AlertOnAbsent(t *testing.T) {}},},SelectedQuery: "A",- Seasonality: "daily",+ Seasonality: ruletypes.SeasonalityDaily,Thresholds: &ruletypes.RuleThresholdData{Kind: ruletypes.BasicThresholdKind,Spec: ruletypes.BasicRuleThresholds{{@@ -170,7 +170,7 @@ func TestAnomalyRule_NoData_AbsentFor(t *testing.T) {}},},SelectedQuery: "A",- Seasonality: "daily",+ Seasonality: ruletypes.SeasonalityDaily,Thresholds: &ruletypes.RuleThresholdData{Kind: ruletypes.BasicThresholdKind,Spec: ruletypes.BasicRuleThresholds{{diff --git a/pkg/alertmanager/nfmanager/nfmanagertest/provider.go b/pkg/alertmanager/nfmanager/nfmanagertest/provider.goindex 4a6a8a72d1..361f0dc6a6 100644--- a/pkg/alertmanager/nfmanager/nfmanagertest/provider.go+++ b/pkg/alertmanager/nfmanager/nfmanagertest/provider.go@@ -240,6 +240,26 @@ func (m *MockNotificationManager) DeleteAllRoutePoliciesByName(ctx context.Contereturn nil}+func (m *MockNotificationManager) GetRoutePoliciesByChannel(ctx context.Context, orgID string, channelName string) ([]*alertmanagertypes.RoutePolicy, error) {+ if orgID == "" {+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "orgID cannot be empty")+ }++ var matched []*alertmanagertypes.RoutePolicy+ for _, route := range m.routes {+ if route.OrgID != orgID {+ continue+ }+ for _, ch := range route.Channels {+ if ch == channelName {+ matched = append(matched, route)+ break+ }+ }+ }+ return matched, nil+}+func (m *MockNotificationManager) Match(ctx context.Context, orgID string, ruleID string, set model.LabelSet) ([]string, error) {key := getKey(orgID, ruleID)if err := m.errors[key]; err != nil {diff --git a/pkg/alertmanager/nfmanager/nfroutingstore/nfroutingstoretest/route.go b/pkg/alertmanager/nfmanager/nfroutingstore/nfroutingstoretest/route.goindex f0fb06689e..7acb0cb0d6 100644--- a/pkg/alertmanager/nfmanager/nfroutingstore/nfroutingstoretest/route.go+++ b/pkg/alertmanager/nfmanager/nfroutingstore/nfroutingstoretest/route.go@@ -59,6 +59,10 @@ func (m *MockSQLRouteStore) DeleteRouteByName(ctx context.Context, orgID string,return m.routeStore.DeleteRouteByName(ctx, orgID, name)}+func (m *MockSQLRouteStore) GetAll(ctx context.Context, orgID string) ([]*alertmanagertypes.RoutePolicy, error) {+ return m.routeStore.GetAll(ctx, orgID)+}+func (m *MockSQLRouteStore) ExpectGetByID(orgID, id string, route *alertmanagertypes.RoutePolicy) {rows := sqlmock.NewRows([]string{"id", "org_id", "name", "expression", "kind", "description", "enabled", "tags", "channels", "created_at", "updated_at", "created_by", "updated_by"})diff --git a/pkg/alertmanager/nfmanager/nfroutingstore/sqlroutingstore/store.go b/pkg/alertmanager/nfmanager/nfroutingstore/sqlroutingstore/store.goindex 78504834c5..c768b69d68 100644--- a/pkg/alertmanager/nfmanager/nfroutingstore/sqlroutingstore/store.go+++ b/pkg/alertmanager/nfmanager/nfroutingstore/sqlroutingstore/store.go@@ -83,6 +83,18 @@ func (store *store) GetAllByName(ctx context.Context, orgID string, name string)return routes, nil}+func (store *store) GetAll(ctx context.Context, orgID string) ([]*routeTypes.RoutePolicy, error) {+ var routes []*routeTypes.RoutePolicy+ err := store.sqlstore.BunDBCtx(ctx).NewSelect().Model(&routes).Where("org_id = ?", orgID).Scan(ctx)+ if err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ return nil, errors.Wrapf(err, errors.TypeInternal, errors.CodeInternal, "unable to fetch routing policies for orgID: %s", orgID)+ }+ return routes, nil+}+func (store *store) DeleteRouteByName(ctx context.Context, orgID string, name string) error {_, err := store.sqlstore.BunDBCtx(ctx).NewDelete().Model((*routeTypes.RoutePolicy)(nil)).Where("org_id = ?", orgID).Where("name = ?", name).Exec(ctx)if err != nil {diff --git a/pkg/alertmanager/nfmanager/notificationmanager.go b/pkg/alertmanager/nfmanager/notificationmanager.goindex 5f44e385be..138f21de31 100644--- a/pkg/alertmanager/nfmanager/notificationmanager.go+++ b/pkg/alertmanager/nfmanager/notificationmanager.go@@ -23,6 +23,10 @@ type NotificationManager interface {DeleteRoutePolicy(ctx context.Context, orgID string, routeID string) errorDeleteAllRoutePoliciesByName(ctx context.Context, orgID string, name string) error+ // GetRoutePoliciesByChannel returns all route policies (both rule-based and policy-based)+ // that reference the given channel name.+ GetRoutePoliciesByChannel(ctx context.Context, orgID string, channelName string) ([]*alertmanagertypes.RoutePolicy, error)+// Route matchingMatch(ctx context.Context, orgID string, ruleID string, set model.LabelSet) ([]string, error)}diff --git a/pkg/alertmanager/nfmanager/rulebasednotification/provider.go b/pkg/alertmanager/nfmanager/rulebasednotification/provider.goindex ffe696f988..1fa2b0abe3 100644--- a/pkg/alertmanager/nfmanager/rulebasednotification/provider.go+++ b/pkg/alertmanager/nfmanager/rulebasednotification/provider.go@@ -155,6 +155,28 @@ func (r *provider) GetAllRoutePolicies(ctx context.Context, orgID string) ([]*alreturn r.routeStore.GetAllByKind(ctx, orgID, alertmanagertypes.PolicyBasedExpression)}+func (r *provider) GetRoutePoliciesByChannel(ctx context.Context, orgID string, channelName string) ([]*alertmanagertypes.RoutePolicy, error) {+ if orgID == "" {+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "orgID cannot be empty")+ }++ allRoutes, err := r.routeStore.GetAll(ctx, orgID)+ if err != nil {+ return nil, err+ }++ var matched []*alertmanagertypes.RoutePolicy+ for _, route := range allRoutes {+ for _, ch := range route.Channels {+ if ch == channelName {+ matched = append(matched, route)+ break+ }+ }+ }+ return matched, nil+}+func (r *provider) DeleteRoutePolicy(ctx context.Context, orgID string, routeID string) error {if routeID == "" {return errors.NewInvalidInputf(errors.CodeInvalidInput, "routeID cannot be empty")diff --git a/pkg/alertmanager/signozalertmanager/provider.go b/pkg/alertmanager/signozalertmanager/provider.goindex 92ef7e3fe1..63614fefda 100644--- a/pkg/alertmanager/signozalertmanager/provider.go+++ b/pkg/alertmanager/signozalertmanager/provider.go@@ -169,6 +169,21 @@ func (provider *provider) DeleteChannelByID(ctx context.Context, orgID string, creturn err}+ // Check if channel is referenced by any route policy (rule-based or policy-based)+ policies, err := provider.notificationManager.GetRoutePoliciesByChannel(ctx, orgID, channel.Name)+ if err != nil {+ return err+ }+ if len(policies) > 0 {+ names := make([]string, 0, len(policies))+ for _, p := range policies {+ names = append(names, p.Name)+ }+ return errors.NewInvalidInputf(errors.CodeInvalidInput,+ "channel %q cannot be deleted because it is used by the following routing policies: %v",+ channel.Name, names)+ }+config, err := provider.configStore.Get(ctx, orgID)if err != nil {return errdiff --git a/pkg/query-service/rules/base_rule.go b/pkg/query-service/rules/base_rule.goindex 5f054f47ed..8ff1cfccd2 100644--- a/pkg/query-service/rules/base_rule.go+++ b/pkg/query-service/rules/base_rule.go@@ -139,9 +139,6 @@ func WithRuleStateHistoryModule(module rulestatehistory.Module) RuleOption {}func NewBaseRule(id string, orgID valuer.UUID, p *ruletypes.PostableRule, opts ...RuleOption) (*BaseRule, error) {- if p.RuleCondition == nil || !p.RuleCondition.IsValid() {- return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid rule condition")- }threshold, err := p.RuleCondition.Thresholds.GetRuleThreshold()if err != nil {return nil, errdiff --git a/pkg/query-service/rules/manager.go b/pkg/query-service/rules/manager.goindex 1a4f4ed835..949ad0f7ac 100644--- a/pkg/query-service/rules/manager.go+++ b/pkg/query-service/rules/manager.go@@ -320,6 +320,38 @@ func (m *Manager) Stop(_ context.Context) {m.logger.Info("rule manager stopped")}+// validateChannels checks that every channel referenced by the rule+// exists as a notification channel for the given org.+func (m *Manager) validateChannels(ctx context.Context, orgID string, rule *ruletypes.PostableRule) error {+ channels := rule.Channels()+ if len(channels) == 0 {+ return nil+ }++ orgChannels, err := m.alertmanager.ListChannels(ctx, orgID)+ if err != nil {+ return err+ }++ known := make(map[string]struct{}, len(orgChannels))+ for _, ch := range orgChannels {+ known[ch.Name] = struct{}{}+ }++ var unknown []string+ for _, name := range channels {+ if _, ok := known[name]; !ok {+ unknown = append(unknown, name)+ }+ }++ if len(unknown) > 0 {+ return errors.NewInvalidInputf(errors.CodeInvalidInput,+ "channels: the following channels do not exist: %v", unknown)+ }+ return nil+}+// EditRule writes the rule definition to the// datastore and also updates the rule executorfunc (m *Manager) EditRule(ctx context.Context, ruleStr string, id valuer.UUID) error {@@ -336,7 +368,12 @@ func (m *Manager) EditRule(ctx context.Context, ruleStr string, id valuer.UUID)if err != nil {return err}-+ if err := parsedRule.Validate(); err != nil {+ return err+ }+ if err := m.validateChannels(ctx, claims.OrgID, &parsedRule); err != nil {+ return err+ }existingRule, err := m.ruleStore.GetStoredRule(ctx, id)if err != nil {return err@@ -533,7 +570,12 @@ func (m *Manager) CreateRule(ctx context.Context, ruleStr string) (*ruletypes.Geif err != nil {return nil, err}-+ if err := parsedRule.Validate(); err != nil {+ return nil, err+ }+ if err := m.validateChannels(ctx, claims.OrgID, &parsedRule); err != nil {+ return nil, err+ }now := time.Now()storedRule := &ruletypes.Rule{Identifiable: types.Identifiable{@@ -920,7 +962,12 @@ func (m *Manager) PatchRule(ctx context.Context, ruleStr string, id valuer.UUID)m.logger.ErrorContext(ctx, "failed to unmarshal patched rule with given id", slog.String("rule.id", id.StringValue()), errors.Attr(err))return nil, err}-+ if err := storedRule.Validate(); err != nil {+ return nil, err+ }+ if err := m.validateChannels(ctx, claims.OrgID, &storedRule); err != nil {+ return nil, err+ }// deploy or un-deploy task according to patched (new) rule stateif err := m.syncRuleStateWithTask(ctx, orgID, taskName, &storedRule); err != nil {m.logger.ErrorContext(ctx, "failed to sync stored rule state with the task", slog.String("task.name", taskName), errors.Attr(err))@@ -971,6 +1018,12 @@ func (m *Manager) TestNotification(ctx context.Context, orgID valuer.UUID, ruleSif err != nil {return 0, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "failed to unmarshal rule")}+ if err := parsedRule.Validate(); err != nil {+ return 0, err+ }+ if err := m.validateChannels(ctx, orgID.StringValue(), &parsedRule); err != nil {+ return 0, err+ }if !parsedRule.NotificationSettings.UsePolicy {parsedRule.NotificationSettings.GroupBy = append(parsedRule.NotificationSettings.GroupBy, ruletypes.LabelThresholdName)}diff --git a/pkg/types/alertmanagertypes/expressionroute.go b/pkg/types/alertmanagertypes/expressionroute.goindex a8c4390ef1..45f51aa6e2 100644--- a/pkg/types/alertmanagertypes/expressionroute.go+++ b/pkg/types/alertmanagertypes/expressionroute.go@@ -136,4 +136,5 @@ type RouteStore interface {GetAllByKind(ctx context.Context, orgID string, kind ExpressionKind) ([]*RoutePolicy, error)GetAllByName(ctx context.Context, orgID string, name string) ([]*RoutePolicy, error)DeleteRouteByName(ctx context.Context, orgID string, name string) error+ GetAll(ctx context.Context, orgID string) ([]*RoutePolicy, error)}diff --git a/pkg/types/ruletypes/alerting.go b/pkg/types/ruletypes/alerting.goindex 3d48e7b10b..39dad8f94f 100644--- a/pkg/types/ruletypes/alerting.go+++ b/pkg/types/ruletypes/alerting.go@@ -103,7 +103,7 @@ type RuleCondition struct {MatchType MatchType `json:"matchType"`TargetUnit string `json:"targetUnit,omitempty"`Algorithm string `json:"algorithm,omitempty"`- Seasonality string `json:"seasonality,omitempty"`+ Seasonality Seasonality `json:"seasonality,omitzero"`SelectedQuery string `json:"selectedQueryName,omitempty"`RequireMinPoints bool `json:"requireMinPoints,omitempty"`RequiredNumPoints int `json:"requiredNumPoints,omitempty"`@@ -158,10 +158,6 @@ func (rc *RuleCondition) SelectedQueryName() string {return keys[len(keys)-1]}-func (rc *RuleCondition) IsValid() bool {- return true-}-// ShouldEval checks if the further series should be evaluated at all for alerts.func (rc *RuleCondition) ShouldEval(series *qbtypes.TimeSeries) bool {return !rc.RequireMinPoints || len(series.Values) >= rc.RequiredNumPointsdiff --git a/pkg/types/ruletypes/api_params.go b/pkg/types/ruletypes/api_params.goindex 4f36d7fdf0..462127e77b 100644--- a/pkg/types/ruletypes/api_params.go+++ b/pkg/types/ruletypes/api_params.go@@ -12,6 +12,7 @@ import ("github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/types/alertmanagertypes"+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/valuer")@@ -25,7 +26,8 @@ const ()const (- DefaultSchemaVersion = "v1"+ DefaultSchemaVersion = "v1"+ SchemaVersionV2Alpha1 = "v2alpha1")type RuleDataKind string@@ -39,9 +41,9 @@ type PostableRule struct {AlertName string `json:"alert"`AlertType AlertType `json:"alertType,omitempty"`Description string `json:"description,omitempty"`- RuleType RuleType `json:"ruleType,omitempty"`- EvalWindow valuer.TextDuration `json:"evalWindow,omitempty"`- Frequency valuer.TextDuration `json:"frequency,omitempty"`+ RuleType RuleType `json:"ruleType,omitzero"`+ EvalWindow valuer.TextDuration `json:"evalWindow,omitzero"`+ Frequency valuer.TextDuration `json:"frequency,omitzero"`RuleCondition *RuleCondition `json:"condition,omitempty"`Labels map[string]string `json:"labels,omitempty"`@@ -64,7 +66,7 @@ type PostableRule struct {type NotificationSettings struct {GroupBy []string `json:"groupBy,omitempty"`- Renotify Renotify `json:"renotify,omitempty"`+ Renotify Renotify `json:"renotify,omitzero"`UsePolicy bool `json:"usePolicy,omitempty"`// NewGroupEvalDelay is the grace period for new series to be excluded from alerts evaluationNewGroupEvalDelay valuer.TextDuration `json:"newGroupEvalDelay,omitzero"`@@ -93,6 +95,28 @@ func (ns *NotificationSettings) GetAlertManagerNotificationConfig() alertmanagerreturn alertmanagertypes.NewNotificationConfig(ns.GroupBy, renotifyInterval, noDataRenotifyInterval, ns.UsePolicy)}+// Channels returns all unique channel names referenced by the rule's thresholds.+func (r *PostableRule) Channels() []string {+ if r.RuleCondition == nil || r.RuleCondition.Thresholds == nil {+ return nil+ }+ threshold, err := r.RuleCondition.Thresholds.GetRuleThreshold()+ if err != nil {+ return nil+ }+ seen := make(map[string]struct{})+ var channels []string+ for _, receiver := range threshold.GetRuleReceivers() {+ for _, ch := range receiver.Channels {+ if _, ok := seen[ch]; !ok {+ seen[ch] = struct{}{}+ channels = append(channels, ch)+ }+ }+ }+ return channels+}+func (r *PostableRule) GetRuleRouteRequest(ruleID string) ([]*alertmanagertypes.PostableRoutePolicy, error) {threshold, err := r.RuleCondition.Thresholds.GetRuleThreshold()if err != nil {@@ -185,15 +209,19 @@ func (r *PostableRule) processRuleDefaults() {r.SchemaVersion = DefaultSchemaVersion}- if r.EvalWindow.IsZero() {- r.EvalWindow = valuer.MustParseTextDuration("5m")- }+ // v2alpha1 uses the Evaluation envelope for window/frequency;+ // only default top-level fields for v1.+ if r.SchemaVersion != SchemaVersionV2Alpha1 {+ if r.EvalWindow.IsZero() {+ r.EvalWindow = valuer.MustParseTextDuration("5m")+ }- if r.Frequency.IsZero() {- r.Frequency = valuer.MustParseTextDuration("1m")+ if r.Frequency.IsZero() {+ r.Frequency = valuer.MustParseTextDuration("1m")+ }}- if r.RuleCondition != nil {+ if r.RuleCondition != nil && r.RuleCondition.CompositeQuery != nil {switch r.RuleCondition.CompositeQuery.QueryType {case QueryTypeBuilder:if r.RuleType.IsZero() {@@ -259,6 +287,10 @@ func (r *PostableRule) MarshalJSON() ([]byte, error) {aux.SchemaVersion = ""aux.NotificationSettings = nilreturn json.Marshal(aux)+ case SchemaVersionV2Alpha1:+ copyStruct := *r+ aux := Alias(copyStruct)+ return json.Marshal(aux)default:copyStruct := *raux := Alias(copyStruct)@@ -292,23 +324,124 @@ func isValidLabelValue(v string) bool {return utf8.ValidString(v)}+// validate runs during UnmarshalJSON (read + write path).+// Preserves the original pre-existing checks only so that stored rules+// continue to load without errors.func (r *PostableRule) validate() error {-var errs []errorif r.RuleCondition == nil {- return errors.NewInvalidInputf(errors.CodeInvalidInput, "rule condition is required")+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "condition: field is required")}if r.Version != "v5" {- errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "only version v5 is supported, got %q", r.Version))+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "version: only v5 is supported, got %q", r.Version))}for k, v := range r.Labels {if !isValidLabelName(k) {errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid label name: %s", k))}+ if !isValidLabelValue(v) {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid label value: %s", v))+ }+ }++ for k := range r.Annotations {+ if !isValidLabelName(k) {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid annotation name: %s", k))+ }+ }++ errs = append(errs, testTemplateParsing(r)...)++ joined := errors.Join(errs...)+ if joined != nil {+ return errors.WrapInvalidInputf(joined, errors.CodeInvalidInput, "validation failed")+ }+ return nil+}++// Validate enforces all validation rules. For now, this is invoked on the write path+// (create, update, patch, test) before persisting. This is intentionally+// not called from UnmarshalJSON so that existing stored rules can always+// be loaded regardless of new validation rules.+func (r *PostableRule) Validate() error {+ var errs []error++ if r.AlertName == "" {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "alert: field is required"))+ }++ if r.RuleCondition == nil {+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "condition: field is required")+ }++ if r.Version != "v5" {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "version: only v5 is supported, got %q", r.Version))+ }++ if r.AlertType != "" {+ switch r.AlertType {+ case AlertTypeMetric, AlertTypeTraces, AlertTypeLogs, AlertTypeExceptions:+ default:+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,+ "alertType: unsupported value %q; must be one of %q, %q, %q, %q",+ r.AlertType, AlertTypeMetric, AlertTypeTraces, AlertTypeLogs, AlertTypeExceptions))+ }+ }++ if !r.RuleType.IsZero() {+ if err := r.RuleType.Validate(); err != nil {+ errs = append(errs, err)+ }+ }++ if r.RuleType == RuleTypeAnomaly && !r.RuleCondition.Seasonality.IsZero() {+ if err := r.RuleCondition.Seasonality.Validate(); err != nil {+ errs = append(errs, err)+ }+ }+ if r.RuleCondition.CompositeQuery == nil {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "condition.compositeQuery: field is required"))+ } else {+ if len(r.RuleCondition.CompositeQuery.Queries) == 0 {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "condition.compositeQuery.queries: must have at least one query"))+ } else {+ cq := &qbtypes.CompositeQuery{Queries: r.RuleCondition.CompositeQuery.Queries}+ if err := cq.Validate(qbtypes.GetValidationOptions(qbtypes.RequestTypeTimeSeries)...); err != nil {+ errs = append(errs, err)+ }+ }+ }++ if r.RuleCondition.SelectedQuery != "" && r.RuleCondition.CompositeQuery != nil && len(r.RuleCondition.CompositeQuery.Queries) > 0 {+ found := false+ for _, query := range r.RuleCondition.CompositeQuery.Queries {+ if query.GetQueryName() == r.RuleCondition.SelectedQuery {+ found = true+ break+ }+ }+ if !found {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,+ "condition.selectedQueryName: %q does not match any query in compositeQuery",+ r.RuleCondition.SelectedQuery))+ }+ }++ if r.RuleCondition.RequireMinPoints && r.RuleCondition.RequiredNumPoints <= 0 {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,+ "condition.requiredNumPoints: must be greater than 0 when requireMinPoints is enabled"))+ }++ errs = append(errs, r.validateSchemaVersion()...)++ for k, v := range r.Labels {+ if !isValidLabelName(k) {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid label name: %s", k))+ }if !isValidLabelValue(v) {errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid label value: %s", v))}@@ -321,7 +454,96 @@ func (r *PostableRule) validate() error {}errs = append(errs, testTemplateParsing(r)...)- return errors.Join(errs...)++ joined := errors.Join(errs...)+ if joined != nil {+ return errors.WrapInvalidInputf(joined, errors.CodeInvalidInput, "validation failed")+ }+ return nil+}++func (r *PostableRule) validateSchemaVersion() []error {+ switch r.SchemaVersion {+ case DefaultSchemaVersion:+ return r.validateV1()+ case SchemaVersionV2Alpha1:+ return r.validateV2Alpha1()+ default:+ return []error{errors.NewInvalidInputf(errors.CodeInvalidInput,+ "schemaVersion: unsupported value %q; must be one of %q, %q",+ r.SchemaVersion, DefaultSchemaVersion, SchemaVersionV2Alpha1)}+ }+}++func (r *PostableRule) validateV1() []error {+ var errs []error++ if r.RuleCondition.Target == nil {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,+ "condition.target: field is required for schemaVersion %q", DefaultSchemaVersion))+ }+ if r.RuleCondition.CompareOperator.IsZero() {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,+ "condition.op: field is required for schemaVersion %q", DefaultSchemaVersion))+ } else if err := r.RuleCondition.CompareOperator.Validate(); err != nil {+ errs = append(errs, err)+ }+ if r.RuleCondition.MatchType.IsZero() {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,+ "condition.matchType: field is required for schemaVersion %q", DefaultSchemaVersion))+ } else if err := r.RuleCondition.MatchType.Validate(); err != nil {+ errs = append(errs, err)+ }++ return errs+}++func (r *PostableRule) validateV2Alpha1() []error {+ var errs []error++ // TODO(srikanthccv): reject v1-only fields?+ // if r.RuleCondition.Target != nil {+ // errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,+ // "condition.target: field is not used in schemaVersion %q; set target in condition.thresholds entries instead",+ // SchemaVersionV2Alpha1))+ // }+ // if !r.RuleCondition.CompareOperator.IsZero() {+ // errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,+ // "condition.op: field is not used in schemaVersion %q; set op in condition.thresholds entries instead",+ // SchemaVersionV2Alpha1))+ // }+ // if !r.RuleCondition.MatchType.IsZero() {+ // errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,+ // "condition.matchType: field is not used in schemaVersion %q; set matchType in condition.thresholds entries instead",+ // SchemaVersionV2Alpha1))+ // }+ // if len(r.PreferredChannels) > 0 {+ // errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,+ // "preferredChannels: field is not used in schemaVersion %q; set channels in condition.thresholds entries instead",+ // SchemaVersionV2Alpha1))+ // }++ // Require v2alpha1-specific fields+ if r.RuleCondition.Thresholds == nil {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,+ "condition.thresholds: field is required for schemaVersion %q", SchemaVersionV2Alpha1))+ }++ if r.Evaluation == nil {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,+ "evaluation: field is required for schemaVersion %q", SchemaVersionV2Alpha1))+ }+ if r.NotificationSettings == nil {+ 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() {+ errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,+ "notificationSettings.renotify.interval: must be a positive duration when renotify is enabled"))+ }+ }++ return errs}func testTemplateParsing(rl *PostableRule) (errs []error) {@@ -393,6 +615,10 @@ func (g *GettableRule) MarshalJSON() ([]byte, error) {aux.SchemaVersion = ""aux.NotificationSettings = nilreturn json.Marshal(aux)+ case SchemaVersionV2Alpha1:+ copyStruct := *g+ aux := Alias(copyStruct)+ return json.Marshal(aux)default:copyStruct := *gaux := Alias(copyStruct)diff --git a/pkg/types/ruletypes/api_params_test.go b/pkg/types/ruletypes/api_params_test.goindex ea4aed6a94..cfea8aa266 100644--- a/pkg/types/ruletypes/api_params_test.go+++ b/pkg/types/ruletypes/api_params_test.go@@ -34,15 +34,15 @@ func TestParseIntoRule(t *testing.T) {"condition": {"compositeQuery": {"queryType": "builder",- "builderQueries": {- "A": {- "expression": "A",- "disabled": false,- "aggregateAttribute": {- "key": "test_metric"- }+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "test_metric", "spaceAggregation": "p50"}],+ "stepInterval": "5m"}- }+ }]},"target": 10.0,"matchType": "1",@@ -77,14 +77,15 @@ func TestParseIntoRule(t *testing.T) {"condition": {"compositeQuery": {"queryType": "builder",- "builderQueries": {- "A": {- "disabled": false,- "aggregateAttribute": {- "key": "test_metric"- }+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "test_metric", "spaceAggregation": "p50"}],+ "stepInterval": "5m"}- }+ }]},"target": 5.0,"matchType": "1",@@ -112,12 +113,14 @@ func TestParseIntoRule(t *testing.T) {"condition": {"compositeQuery": {"queryType": "promql",- "promQueries": {- "A": {+ "queries": [{+ "type": "promql",+ "spec": {+ "name": "A","query": "rate(http_requests_total[5m])","disabled": false}- }+ }]},"target": 10.0,"matchType": "1",@@ -165,12 +168,13 @@ func TestParseIntoRule(t *testing.T) {func TestParseIntoRuleSchemaVersioning(t *testing.T) {tests := []struct {- name string- initRule PostableRule- content []byte- kind RuleDataKind- expectError bool- validate func(*testing.T, *PostableRule)+ name string+ initRule PostableRule+ content []byte+ kind RuleDataKind+ expectError bool // unmarshal error (read path)+ expectValidateError bool // Validate() error (write path only)+ validate func(*testing.T, *PostableRule)}{{name: "schema v1 - threshold name from severity label",@@ -182,13 +186,15 @@ func TestParseIntoRuleSchemaVersioning(t *testing.T) {"condition": {"compositeQuery": {"queryType": "builder",- "builderQueries": {- "A": {- "aggregateAttribute": {- "key": "cpu_usage"- }+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "cpu_usage", "spaceAggregation": "p50"}],+ "stepInterval": "5m"}- },+ }],"unit": "percent"},"target": 85.0,@@ -271,13 +277,15 @@ func TestParseIntoRuleSchemaVersioning(t *testing.T) {"condition": {"compositeQuery": {"queryType": "builder",- "builderQueries": {- "A": {- "aggregateAttribute": {- "key": "memory_usage"- }+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "memory_usage", "spaceAggregation": "p50"}],+ "stepInterval": "5m"}- }+ }]},"target": 90.0,"matchType": "1",@@ -312,13 +320,15 @@ func TestParseIntoRuleSchemaVersioning(t *testing.T) {"condition": {"compositeQuery": {"queryType": "builder",- "builderQueries": {- "A": {- "aggregateAttribute": {- "key": "cpu_usage"- }+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "cpu_usage", "spaceAggregation": "p50"}],+ "stepInterval": "5m"}- },+ }],"unit": "percent"},"target": 80.0,@@ -394,50 +404,254 @@ func TestParseIntoRuleSchemaVersioning(t *testing.T) {},},{- name: "schema v2 - does not populate thresholds and evaluation",+ name: "schema v2alpha1 - uses explicit thresholds and evaluation",initRule: PostableRule{},content: []byte(`{- "alert": "V2Test",- "schemaVersion": "v2",+ "alert": "V2Alpha1Test",+ "schemaVersion": "v2alpha1","version": "v5",+ "ruleType": "threshold_rule","condition": {"compositeQuery": {"queryType": "builder",- "builderQueries": {- "A": {- "aggregateAttribute": {- "key": "test_metric"- }+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "test_metric", "spaceAggregation": "p50"}],+ "stepInterval": "5m"}- }+ }]},- "target": 100.0,- "matchType": "1",- "op": "1"+ "thresholds": {+ "kind": "basic",+ "spec": [{+ "name": "critical",+ "target": 100.0,+ "matchType": "1",+ "op": "1"+ }]+ }+ },+ "evaluation": {+ "kind": "rolling",+ "spec": {+ "evalWindow": "5m",+ "frequency": "1m"+ }+ },+ "notificationSettings": {+ "renotify": {+ "enabled": true,+ "interval": "4h",+ "alertStates": ["firing"]+ }}}`),kind: RuleDataKindJson,expectError: false,validate: func(t *testing.T, rule *PostableRule) {- if rule.SchemaVersion != "v2" {- t.Errorf("Expected schemaVersion 'v2', got '%s'", rule.SchemaVersion)+ if rule.SchemaVersion != SchemaVersionV2Alpha1 {+ t.Errorf("Expected schemaVersion %q, got %q", SchemaVersionV2Alpha1, rule.SchemaVersion)}- if rule.RuleCondition.Thresholds != nil {- t.Error("Expected Thresholds to be nil for v2")+ if rule.RuleCondition.Thresholds == nil {+ t.Error("Expected Thresholds to be present for v2alpha1")}- if rule.Evaluation != nil {- t.Error("Expected Evaluation to be nil for v2")+ if rule.Evaluation == nil {+ t.Error("Expected Evaluation to be present for v2alpha1")}-- if rule.EvalWindow.Duration() != 5*time.Minute {- t.Error("Expected default EvalWindow to be applied")+ if rule.NotificationSettings == nil {+ t.Error("Expected NotificationSettings to be present for v2alpha1")}if rule.RuleType != RuleTypeThreshold {t.Error("Expected RuleType to be auto-detected")}},},+ {+ name: "schema v2alpha1 - rejects v1-only fields with suggestions",+ initRule: PostableRule{},+ content: []byte(`{+ "alert": "MixedFieldsTest",+ "schemaVersion": "v2alpha1",+ "version": "v5",+ "ruleType": "threshold_rule",+ "preferredChannels": ["slack"],+ "condition": {+ "compositeQuery": {+ "queryType": "builder",+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "test_metric", "spaceAggregation": "p50"}],+ "stepInterval": "5m"+ }+ }]+ },+ "target": 100.0,+ "matchType": "1",+ "op": "1"+ }+ }`),+ kind: RuleDataKindJson,+ expectValidateError: true,+ },+ {+ name: "schema v2alpha1 - requires evaluation",+ initRule: PostableRule{},+ content: []byte(`{+ "alert": "MissingEvalTest",+ "schemaVersion": "v2alpha1",+ "version": "v5",+ "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {+ "queryType": "builder",+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "test_metric", "spaceAggregation": "p50"}],+ "stepInterval": "5m"+ }+ }]+ },+ "thresholds": {+ "kind": "basic",+ "spec": [{+ "name": "critical",+ "target": 100.0,+ "matchType": "1",+ "op": "1"+ }]+ }+ },+ "notificationSettings": {+ "renotify": {+ "enabled": true,+ "interval": "4h",+ "alertStates": ["firing"]+ }+ }+ }`),+ kind: RuleDataKindJson,+ expectValidateError: true,+ },+ {+ name: "schema v2alpha1 - requires notificationSettings",+ initRule: PostableRule{},+ content: []byte(`{+ "alert": "MissingNotifTest",+ "schemaVersion": "v2alpha1",+ "version": "v5",+ "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {+ "queryType": "builder",+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "test_metric", "spaceAggregation": "p50"}],+ "stepInterval": "5m"+ }+ }]+ },+ "thresholds": {+ "kind": "basic",+ "spec": [{+ "name": "critical",+ "target": 100.0,+ "matchType": "1",+ "op": "1"+ }]+ }+ },+ "evaluation": {+ "kind": "rolling",+ "spec": {+ "evalWindow": "5m",+ "frequency": "1m"+ }+ }+ }`),+ kind: RuleDataKindJson,+ expectValidateError: true,+ },+ {+ name: "schema v2alpha1 - requires thresholds for non-promql rules",+ initRule: PostableRule{},+ content: []byte(`{+ "alert": "MissingThresholdsTest",+ "schemaVersion": "v2alpha1",+ "version": "v5",+ "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {+ "queryType": "builder",+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "test_metric", "spaceAggregation": "p50"}],+ "stepInterval": "5m"+ }+ }]+ }+ },+ "evaluation": {+ "kind": "rolling",+ "spec": {+ "evalWindow": "5m",+ "frequency": "1m"+ }+ },+ "notificationSettings": {+ "renotify": {+ "enabled": true,+ "interval": "4h",+ "alertStates": ["firing"]+ }+ }+ }`),+ kind: RuleDataKindJson,+ expectValidateError: true,+ },+ {+ name: "unsupported schema version",+ initRule: PostableRule{},+ content: []byte(`{+ "alert": "BadSchemaTest",+ "schemaVersion": "v3",+ "version": "v5",+ "condition": {+ "compositeQuery": {+ "queryType": "builder",+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "test_metric", "spaceAggregation": "p50"}],+ "stepInterval": "5m"+ }+ }]+ },+ "target": 100.0,+ "matchType": "1",+ "op": "1"+ }+ }`),+ kind: RuleDataKindJson,+ expectValidateError: true,+ },{name: "default schema version - defaults to v1 behavior",initRule: PostableRule{},@@ -447,13 +661,15 @@ func TestParseIntoRuleSchemaVersioning(t *testing.T) {"condition": {"compositeQuery": {"queryType": "builder",- "builderQueries": {- "A": {- "aggregateAttribute": {- "key": "test_metric"- }+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "test_metric", "spaceAggregation": "p50"}],+ "stepInterval": "5m"}- }+ }]},"target": 75.0,"matchType": "1",@@ -480,13 +696,23 @@ func TestParseIntoRuleSchemaVersioning(t *testing.T) {t.Run(tt.name, func(t *testing.T) {rule := tt.initRuleerr := json.Unmarshal(tt.content, &rule)- if tt.expectError && err == nil {- t.Errorf("Expected error but got none")+ if tt.expectError {+ if err == nil {+ t.Errorf("Expected unmarshal error but got none")+ }+ return}- if !tt.expectError && err != nil {- t.Errorf("Unexpected error: %v", err)+ if err != nil {+ t.Errorf("Unexpected unmarshal error: %v", err)+ return}- if tt.validate != nil && err == nil {+ if tt.expectValidateError {+ if err := rule.Validate(); err == nil {+ t.Errorf("Expected Validate() error but got none")+ }+ return+ }+ if tt.validate != nil {tt.validate(t, &rule)}})@@ -500,15 +726,15 @@ func TestParseIntoRuleThresholdGeneration(t *testing.T) {"condition": {"compositeQuery": {"queryType": "builder",- "builderQueries": {- "A": {- "expression": "A",- "disabled": false,- "aggregateAttribute": {- "key": "response_time"- }+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "response_time", "spaceAggregation": "p50"}],+ "stepInterval": "5m"}- }+ }]},"target": 100.0,"matchType": "1",@@ -571,7 +797,7 @@ func TestParseIntoRuleThresholdGeneration(t *testing.T) {func TestParseIntoRuleMultipleThresholds(t *testing.T) {content := []byte(`{- "schemaVersion": "v2",+ "schemaVersion": "v2alpha1","alert": "MultiThresholdAlert","ruleType": "threshold_rule","version": "v5",@@ -579,19 +805,16 @@ func TestParseIntoRuleMultipleThresholds(t *testing.T) {"compositeQuery": {"queryType": "builder","unit": "%",- "builderQueries": {- "A": {- "expression": "A",- "disabled": false,- "aggregateAttribute": {- "key": "cpu_usage"- }+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "cpu_usage", "spaceAggregation": "p50"}],+ "stepInterval": "5m"}- }+ }]},- "target": 90.0,- "matchType": "1",- "op": "1","selectedQuery": "A","thresholds": {"kind": "basic",@@ -616,6 +839,20 @@ func TestParseIntoRuleMultipleThresholds(t *testing.T) {}]}+ },+ "evaluation": {+ "kind": "rolling",+ "spec": {+ "evalWindow": "5m",+ "frequency": "1m"+ }+ },+ "notificationSettings": {+ "renotify": {+ "enabled": true,+ "interval": "4h",+ "alertStates": ["firing"]+ }}}`)rule := PostableRule{}diff --git a/pkg/types/ruletypes/compare.go b/pkg/types/ruletypes/compare.goindex c677a1d8ba..187cf8e0e4 100644--- a/pkg/types/ruletypes/compare.go+++ b/pkg/types/ruletypes/compare.go@@ -54,6 +54,29 @@ func (CompareOperator) Enum() []any {}}+// Normalize returns the canonical (numeric) form of the operator.+// This ensures evaluation logic can use simple == checks against the canonical values.+func (c CompareOperator) Normalize() CompareOperator {+ switch c {+ case ValueIsAbove, ValueIsAboveLiteral, ValueIsAboveSymbol:+ return ValueIsAbove+ case ValueIsBelow, ValueIsBelowLiteral, ValueIsBelowSymbol:+ return ValueIsBelow+ case ValueIsEq, ValueIsEqLiteral, ValueIsEqLiteralShort, ValueIsEqSymbol:+ return ValueIsEq+ case ValueIsNotEq, ValueIsNotEqLiteral, ValueIsNotEqLiteralShort, ValueIsNotEqSymbol:+ return ValueIsNotEq+ case ValueAboveOrEq, ValueAboveOrEqLiteral, ValueAboveOrEqLiteralShort, ValueAboveOrEqSymbol:+ return ValueAboveOrEq+ case ValueBelowOrEq, ValueBelowOrEqLiteral, ValueBelowOrEqLiteralShort, ValueBelowOrEqSymbol:+ return ValueBelowOrEq+ case ValueOutsideBounds, ValueOutsideBoundsLiteral:+ return ValueOutsideBounds+ default:+ return c+ }+}+func (c CompareOperator) Validate() error {switch c {case ValueIsAbove,@@ -70,10 +93,18 @@ func (c CompareOperator) Validate() error {ValueIsNotEqLiteral,ValueIsNotEqLiteralShort,ValueIsNotEqSymbol,+ ValueAboveOrEq,+ ValueAboveOrEqLiteral,+ ValueAboveOrEqLiteralShort,+ ValueAboveOrEqSymbol,+ ValueBelowOrEq,+ ValueBelowOrEqLiteral,+ ValueBelowOrEqLiteralShort,+ ValueBelowOrEqSymbol,ValueOutsideBounds,ValueOutsideBoundsLiteral:return nildefault:- return errors.NewInvalidInputf(errors.CodeInvalidInput, "unknown comparison operator, known values are: ")+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "condition.op: unsupported value %q; must be one of above, below, equal, not_equal, above_or_equal, below_or_equal, outside_bounds", c.StringValue())}}diff --git a/pkg/types/ruletypes/match.go b/pkg/types/ruletypes/match.goindex d2b383af69..76f15aefbc 100644--- a/pkg/types/ruletypes/match.go+++ b/pkg/types/ruletypes/match.go@@ -11,7 +11,7 @@ type MatchType struct {var (AtleastOnce = MatchType{valuer.NewString("1")}- AtleastOnceLiteral = MatchType{valuer.NewString("atleast_once")}+ AtleastOnceLiteral = MatchType{valuer.NewString("at_least_once")}AllTheTimes = MatchType{valuer.NewString("2")}AllTheTimesLiteral = MatchType{valuer.NewString("all_the_times")}@@ -38,6 +38,24 @@ func (MatchType) Enum() []any {}}+// Normalize returns the canonical (numeric) form of the match type.+func (m MatchType) Normalize() MatchType {+ switch m {+ case AtleastOnce, AtleastOnceLiteral:+ return AtleastOnce+ case AllTheTimes, AllTheTimesLiteral:+ return AllTheTimes+ case OnAverage, OnAverageLiteral, OnAverageShort:+ return OnAverage+ case InTotal, InTotalLiteral, InTotalShort:+ return InTotal+ case Last, LastLiteral:+ return Last+ default:+ return m+ }+}+func (m MatchType) Validate() error {switch m {case@@ -55,6 +73,6 @@ func (m MatchType) Validate() error {LastLiteral:return nildefault:- return errors.NewInvalidInputf(errors.CodeInvalidInput, "unknown match type operator, known values are")+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "condition.matchType: unsupported value %q; must be one of at_least_once, all_the_times, on_average, in_total, last", m.StringValue())}}diff --git a/pkg/types/ruletypes/rule_type.go b/pkg/types/ruletypes/rule_type.goindex fa927ff0ec..dec8d66efb 100644--- a/pkg/types/ruletypes/rule_type.go+++ b/pkg/types/ruletypes/rule_type.go@@ -31,6 +31,6 @@ func (r RuleType) Validate() error {RuleTypeAnomaly:return nildefault:- return errors.NewInvalidInputf(errors.CodeInvalidInput, "unknown rule type, known values are")+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "ruleType: unsupported value %q; must be one of threshold_rule, promql_rule, anomaly_rule", r.StringValue())}}diff --git a/pkg/types/ruletypes/seasonality.go b/pkg/types/ruletypes/seasonality.gonew file mode 100644index 0000000000..08c7a898f8--- /dev/null+++ b/pkg/types/ruletypes/seasonality.go@@ -0,0 +1,35 @@+package ruletypes++import (+ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/valuer"+)++type Seasonality struct {+ valuer.String+}++var (+ SeasonalityHourly = Seasonality{valuer.NewString("hourly")}+ SeasonalityDaily = Seasonality{valuer.NewString("daily")}+ SeasonalityWeekly = Seasonality{valuer.NewString("weekly")}+)++func (Seasonality) Enum() []any {+ return []any{+ SeasonalityHourly,+ SeasonalityDaily,+ SeasonalityWeekly,+ }+}++func (s Seasonality) Validate() error {+ switch s {+ case SeasonalityHourly, SeasonalityDaily, SeasonalityWeekly:+ return nil+ default:+ return errors.NewInvalidInputf(errors.CodeInvalidInput,+ "condition.seasonality: unsupported value %q; must be one of hourly, daily, weekly",+ s.StringValue())+ }+}diff --git a/pkg/types/ruletypes/threshold.go b/pkg/types/ruletypes/threshold.goindex 80101b7f84..40bc77eb32 100644--- a/pkg/types/ruletypes/threshold.go+++ b/pkg/types/ruletypes/threshold.go@@ -113,6 +113,9 @@ func (r BasicRuleThresholds) GetRuleReceivers() []RuleReceivers {}func (r BasicRuleThresholds) Validate() error {+ if len(r) == 0 {+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "condition.thresholds.spec: must have at least one threshold")+ }var errs []errorfor _, basicThreshold := range r {if err := basicThreshold.Validate(); err != nil {@@ -189,7 +192,7 @@ func sortThresholds(thresholds []BasicRuleThreshold) {targetI := thresholds[i].target(thresholds[i].TargetUnit) //for sorting we dont need rule unittargetJ := thresholds[j].target(thresholds[j].TargetUnit)- switch thresholds[i].CompareOperator {+ switch thresholds[i].CompareOperator.Normalize() {case ValueIsAbove, ValueAboveOrEq, ValueOutsideBounds:// For "above" operations, sort descending (higher values first)return targetI > targetJ@@ -234,16 +237,11 @@ func (b BasicRuleThreshold) Validate() error {errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "target value cannot be nil"))}- switch b.CompareOperator {- case ValueIsAbove, ValueIsBelow, ValueIsEq, ValueIsNotEq, ValueAboveOrEq, ValueBelowOrEq, ValueOutsideBounds:- default:- errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid compare operation: %s", b.CompareOperator.StringValue()))+ if err := b.CompareOperator.Validate(); err != nil {+ errs = append(errs, err)}-- switch b.MatchType {- case AtleastOnce, AllTheTimes, OnAverage, InTotal, Last:- default:- errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid match type: %s", b.MatchType.StringValue()))+ if err := b.MatchType.Validate(); err != nil {+ errs = append(errs, err)}return errors.Join(errs...)@@ -268,6 +266,33 @@ func PrepareSampleLabelsForRule(seriesLabels []*qbtypes.Label, thresholdName strreturn lb.Labels()}+// matchesCompareOp checks if a value matches the compare operator against target.+func matchesCompareOp(op CompareOperator, value, target float64) bool {+ switch op {+ case ValueIsAbove:+ return value > target+ case ValueIsBelow:+ return value < target+ case ValueIsEq:+ return value == target+ case ValueIsNotEq:+ return value != target+ case ValueAboveOrEq:+ return value >= target+ case ValueBelowOrEq:+ return value <= target+ case ValueOutsideBounds:+ return math.Abs(value) >= target+ default:+ return false+ }+}++// negatesCompareOp checks if a value does NOT match the compare operator against target.+func negatesCompareOp(op CompareOperator, value, target float64) bool {+ return !matchesCompareOp(op, value, target)+}+func (b BasicRuleThreshold) shouldAlertWithTarget(series *qbtypes.TimeSeries, target float64) (Sample, bool) {var shouldAlert boolvar alertSmpl Sample@@ -278,63 +303,35 @@ func (b BasicRuleThreshold) shouldAlertWithTarget(series *qbtypes.TimeSeries, tareturn alertSmpl, false}- switch b.MatchType {+ // Normalize to canonical forms so evaluation uses simple == checks+ op := b.CompareOperator.Normalize()+ matchType := b.MatchType.Normalize()++ switch matchType {case AtleastOnce:// If any sample matches the condition, the rule is firing.- if b.CompareOperator == ValueIsAbove {- for _, smpl := range series.Values {- if smpl.Value > target {- alertSmpl = Sample{Point: Point{V: smpl.Value}, Metric: lbls}- shouldAlert = true- break- }- }- } else if b.CompareOperator == ValueIsBelow {- for _, smpl := range series.Values {- if smpl.Value < target {- alertSmpl = Sample{Point: Point{V: smpl.Value}, Metric: lbls}- shouldAlert = true- break- }- }- } else if b.CompareOperator == ValueIsEq {- for _, smpl := range series.Values {- if smpl.Value == target {- alertSmpl = Sample{Point: Point{V: smpl.Value}, Metric: lbls}- shouldAlert = true- break- }- }- } else if b.CompareOperator == ValueIsNotEq {- for _, smpl := range series.Values {- if smpl.Value != target {- alertSmpl = Sample{Point: Point{V: smpl.Value}, Metric: lbls}- shouldAlert = true- break- }- }- } else if b.CompareOperator == ValueOutsideBounds {- for _, smpl := range series.Values {- if math.Abs(smpl.Value) >= target {- alertSmpl = Sample{Point: Point{V: smpl.Value}, Metric: lbls}- shouldAlert = true- break- }+ for _, smpl := range series.Values {+ if matchesCompareOp(op, smpl.Value, target) {+ alertSmpl = Sample{Point: Point{V: smpl.Value}, Metric: lbls}+ shouldAlert = true+ break}}case AllTheTimes:// If all samples match the condition, the rule is firing.shouldAlert = truealertSmpl = Sample{Point: Point{V: target}, Metric: lbls}- if b.CompareOperator == ValueIsAbove {- for _, smpl := range series.Values {- if smpl.Value <= target {- shouldAlert = false- break- }+ for _, smpl := range series.Values {+ if negatesCompareOp(op, smpl.Value, target) {+ alertSmpl = Sample{Point: Point{V: smpl.Value}, Metric: lbls}+ shouldAlert = false+ break}- // use min value from the series- if shouldAlert {+ }+ if shouldAlert {+ switch op {+ case ValueIsAbove, ValueAboveOrEq, ValueOutsideBounds:+ // use min value from the seriesvar minValue = math.Inf(1)for _, smpl := range series.Values {if smpl.Value < minValue {@@ -342,15 +339,8 @@ func (b BasicRuleThreshold) shouldAlertWithTarget(series *qbtypes.TimeSeries, ta}}alertSmpl = Sample{Point: Point{V: minValue}, Metric: lbls}- }- } else if b.CompareOperator == ValueIsBelow {- for _, smpl := range series.Values {- if smpl.Value >= target {- shouldAlert = false- break- }- }- if shouldAlert {+ case ValueIsBelow, ValueBelowOrEq:+ // use max value from the seriesvar maxValue = math.Inf(-1)for _, smpl := range series.Values {if smpl.Value > maxValue {@@ -358,23 +348,8 @@ func (b BasicRuleThreshold) shouldAlertWithTarget(series *qbtypes.TimeSeries, ta}}alertSmpl = Sample{Point: Point{V: maxValue}, Metric: lbls}- }- } else if b.CompareOperator == ValueIsEq {- for _, smpl := range series.Values {- if smpl.Value != target {- shouldAlert = false- break- }- }- } else if b.CompareOperator == ValueIsNotEq {- for _, smpl := range series.Values {- if smpl.Value == target {- shouldAlert = false- break- }- }- // use any non-inf or nan value from the series- if shouldAlert {+ case ValueIsNotEq:+ // use any non-inf and non-nan value from the seriesfor _, smpl := range series.Values {if !math.IsInf(smpl.Value, 0) && !math.IsNaN(smpl.Value) {alertSmpl = Sample{Point: Point{V: smpl.Value}, Metric: lbls}@@ -382,14 +357,6 @@ func (b BasicRuleThreshold) shouldAlertWithTarget(series *qbtypes.TimeSeries, ta}}}- } else if b.CompareOperator == ValueOutsideBounds {- for _, smpl := range series.Values {- if math.Abs(smpl.Value) < target {- alertSmpl = Sample{Point: Point{V: smpl.Value}, Metric: lbls}- shouldAlert = false- break- }- }}case OnAverage:// If the average of all samples matches the condition, the rule is firing.@@ -403,32 +370,10 @@ func (b BasicRuleThreshold) shouldAlertWithTarget(series *qbtypes.TimeSeries, ta}avg := sum / countalertSmpl = Sample{Point: Point{V: avg}, Metric: lbls}- switch b.CompareOperator {- case ValueIsAbove:- if avg > target {- shouldAlert = true- }- case ValueIsBelow:- if avg < target {- shouldAlert = true- }- case ValueIsEq:- if avg == target {- shouldAlert = true- }- case ValueIsNotEq:- if avg != target {- shouldAlert = true- }- case ValueOutsideBounds:- if math.Abs(avg) >= target {- shouldAlert = true- }- }+ shouldAlert = matchesCompareOp(op, avg, target)case InTotal:// If the sum of all samples matches the condition, the rule is firing.var sum float64-for _, smpl := range series.Values {if math.IsNaN(smpl.Value) || math.IsInf(smpl.Value, 0) {continue@@ -436,50 +381,12 @@ func (b BasicRuleThreshold) shouldAlertWithTarget(series *qbtypes.TimeSeries, tasum += smpl.Value}alertSmpl = Sample{Point: Point{V: sum}, Metric: lbls}- switch b.CompareOperator {- case ValueIsAbove:- if sum > target {- shouldAlert = true- }- case ValueIsBelow:- if sum < target {- shouldAlert = true- }- case ValueIsEq:- if sum == target {- shouldAlert = true- }- case ValueIsNotEq:- if sum != target {- shouldAlert = true- }- case ValueOutsideBounds:- if math.Abs(sum) >= target {- shouldAlert = true- }- }+ shouldAlert = matchesCompareOp(op, sum, target)case Last:// If the last sample matches the condition, the rule is firing.- shouldAlert = false- alertSmpl = Sample{Point: Point{V: series.Values[len(series.Values)-1].Value}, Metric: lbls}- switch b.CompareOperator {- case ValueIsAbove:- if series.Values[len(series.Values)-1].Value > target {- shouldAlert = true- }- case ValueIsBelow:- if series.Values[len(series.Values)-1].Value < target {- shouldAlert = true- }- case ValueIsEq:- if series.Values[len(series.Values)-1].Value == target {- shouldAlert = true- }- case ValueIsNotEq:- if series.Values[len(series.Values)-1].Value != target {- shouldAlert = true- }- }+ lastValue := series.Values[len(series.Values)-1].Value+ alertSmpl = Sample{Point: Point{V: lastValue}, Metric: lbls}+ shouldAlert = matchesCompareOp(op, lastValue, target)}return alertSmpl, shouldAlert}diff --git a/pkg/types/ruletypes/validate_test.go b/pkg/types/ruletypes/validate_test.gonew file mode 100644index 0000000000..621a70c137--- /dev/null+++ b/pkg/types/ruletypes/validate_test.go@@ -0,0 +1,1720 @@+package ruletypes++import (+ "encoding/json"+ "strings"+ "testing"+)++// validV1Builder returns a minimal valid v1 builder rule JSON.+func validV1Builder() string {+ return `{+ "alert": "TestAlert",+ "version": "v5",+ "condition": {+ "compositeQuery": {+ "queryType": "builder",+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}],+ "stepInterval": "5m"+ }+ }]+ },+ "target": 10.0,+ "matchType": "1",+ "op": "1"+ }+ }`+}++// validV2Alpha1Builder returns a minimal valid v2alpha1 builder rule JSON.+func validV2Alpha1Builder() string {+ return `{+ "alert": "TestAlert",+ "version": "v5",+ "schemaVersion": "v2alpha1",+ "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {+ "queryType": "builder",+ "queries": [{+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "metrics",+ "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}],+ "stepInterval": "5m"+ }+ }]+ },+ "thresholds": {+ "kind": "basic",+ "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]+ }+ },+ "evaluation": {+ "kind": "rolling",+ "spec": {"evalWindow": "5m", "frequency": "1m"}+ },+ "notificationSettings": {+ "renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}+ }+ }`+}++// validV1Promql returns a minimal valid v1 promql rule JSON.+func validV1Promql() string {+ return `{+ "alert": "PromQLAlert",+ "version": "v5",+ "condition": {+ "compositeQuery": {+ "queryType": "promql",+ "queries": [{+ "type": "promql",+ "spec": {"name": "A", "query": "up == 0", "disabled": false}+ }]+ },+ "target": 1.0,+ "matchType": "1",+ "op": "1"+ }+ }`+}++// patchJSON takes base JSON and overlays fields from patch JSON.+func patchJSON(base, patch string) string {+ var baseMap, patchMap map[string]json.RawMessage+ _ = json.Unmarshal([]byte(base), &baseMap)+ _ = json.Unmarshal([]byte(patch), &patchMap)+ for k, v := range patchMap {+ baseMap[k] = v+ }+ out, _ := json.Marshal(baseMap)+ return string(out)+}++// removeField removes a top-level field from JSON.+func removeField(j, field string) string {+ var m map[string]json.RawMessage+ _ = json.Unmarshal([]byte(j), &m)+ delete(m, field)+ out, _ := json.Marshal(m)+ return string(out)+}++// unmarshalAndValidate unmarshals JSON into PostableRule, then calls Validate().+// Returns the unmarshal error and the Validate error separately.+func unmarshalAndValidate(j string) (unmarshalErr, validateErr error) {+ var rule PostableRule+ unmarshalErr = json.Unmarshal([]byte(j), &rule)+ if unmarshalErr != nil {+ return unmarshalErr, nil+ }+ validateErr = rule.Validate()+ return nil, validateErr+}++func TestValidate_PostableRule_Common(t *testing.T) {+ tests := []struct {+ name string+ json string+ wantErr bool+ errSubstr string // substring expected in error message+ }{+ // simple test+ {+ name: "valid v1 builder rule",+ json: validV1Builder(),+ },+ {+ name: "valid v1 promql rule",+ json: validV1Promql(),+ },+ {+ name: "valid v2alpha1 builder rule",+ json: validV2Alpha1Builder(),+ },++ // alert name+ {+ name: "missing alert name",+ json: removeField(validV1Builder(), "alert"),+ wantErr: true,+ errSubstr: "alert",+ },+ {+ name: "empty alert name",+ json: patchJSON(validV1Builder(), `{"alert": ""}`),+ wantErr: true,+ errSubstr: "alert",+ },++ // only "v5" is allowed+ {+ name: "missing version",+ json: removeField(validV1Builder(), "version"),+ wantErr: true,+ errSubstr: "version",+ },+ {+ name: "wrong version v4",+ json: patchJSON(validV1Builder(), `{"version": "v4"}`),+ wantErr: true,+ errSubstr: "version",+ },+ {+ name: "wrong version v3",+ json: patchJSON(validV1Builder(), `{"version": "v3"}`),+ wantErr: true,+ errSubstr: "version",+ },+ {+ name: "empty version",+ json: patchJSON(validV1Builder(), `{"version": ""}`),+ wantErr: true,+ errSubstr: "version",+ },++ // alert type, capital case to avoid breaking changes+ // no types.valuer for now+ {+ name: "valid alertType METRIC_BASED_ALERT",+ json: patchJSON(validV1Builder(), `{"alertType": "METRIC_BASED_ALERT"}`),+ },+ {+ name: "valid alertType LOGS_BASED_ALERT",+ json: patchJSON(validV1Builder(), `{"alertType": "LOGS_BASED_ALERT"}`),+ },+ {+ name: "valid alertType TRACES_BASED_ALERT",+ json: patchJSON(validV1Builder(), `{"alertType": "TRACES_BASED_ALERT"}`),+ },+ {+ name: "valid alertType EXCEPTIONS_BASED_ALERT",+ json: patchJSON(validV1Builder(), `{"alertType": "EXCEPTIONS_BASED_ALERT"}`),+ },+ {+ name: "empty alertType is ok (optional)",+ json: removeField(validV1Builder(), "alertType"),+ },+ {+ name: "invalid alertType",+ json: patchJSON(validV1Builder(), `{"alertType": "CUSTOM_ALERT"}`),+ wantErr: true,+ errSubstr: "alertType",+ },+ {+ name: "lowercase alertType",+ json: patchJSON(validV1Builder(), `{"alertType": "metric_based_alert"}`),+ wantErr: true,+ errSubstr: "alertType",+ },++ // rule_type, the matrix is bit confusing for now+ {+ name: "valid ruleType threshold_rule",+ json: patchJSON(validV1Builder(), `{"ruleType": "threshold_rule"}`),+ },+ {+ name: "valid ruleType promql_rule",+ json: patchJSON(validV1Promql(), `{"ruleType": "promql_rule"}`),+ },+ {+ name: "invalid ruleType",+ json: patchJSON(validV1Builder(), `{"ruleType": "custom_rule"}`),+ wantErr: true,+ errSubstr: "ruleType",+ },++ // rule condition should never be missing+ {+ name: "missing condition entirely",+ json: `{"alert": "Test", "version": "v5"}`,+ wantErr: true,+ errSubstr: "condition",+ },+ {+ name: "null condition",+ json: `{"alert": "Test", "version": "v5", "condition": null}`,+ wantErr: true,+ errSubstr: "condition",+ },++ // query should never be missing+ {+ name: "missing compositeQuery",+ json: `{"alert": "Test", "version": "v5", "condition": {"target": 10.0, "matchType": "1", "op": "1"}}`,+ wantErr: true,+ errSubstr: "compositeQuery",+ },+ {+ name: "empty queries array",+ json: `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": []},+ "target": 10.0, "matchType": "1", "op": "1"+ }+ }`,+ wantErr: true,+ errSubstr: "queries",+ },++ // selected query should be one of the query from queries+ {+ name: "selectedQueryName matches query",+ json: `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {+ "queryType": "builder",+ "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]+ },+ "target": 10.0, "matchType": "1", "op": "1",+ "selectedQueryName": "A"+ }+ }`,+ },+ {+ name: "selectedQueryName does not match any query",+ json: `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {+ "queryType": "builder",+ "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]+ },+ "target": 10.0, "matchType": "1", "op": "1",+ "selectedQueryName": "Z"+ }+ }`,+ wantErr: true,+ errSubstr: "selectedQueryName",+ },+ {+ name: "empty selectedQueryName is ok (optional)",+ json: validV1Builder(),+ },++ // min points enforcement+ {+ name: "requireMinPoints false with zero points is ok",+ json: `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 10.0, "matchType": "1", "op": "1",+ "requireMinPoints": false, "requiredNumPoints": 0+ }+ }`,+ },+ {+ name: "requireMinPoints true with positive points is ok",+ json: `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 10.0, "matchType": "1", "op": "1",+ "requireMinPoints": true, "requiredNumPoints": 5+ }+ }`,+ },+ {+ name: "requireMinPoints true with zero points",+ json: `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 10.0, "matchType": "1", "op": "1",+ "requireMinPoints": true, "requiredNumPoints": 0+ }+ }`,+ wantErr: true,+ errSubstr: "requiredNumPoints",+ },+ {+ name: "requireMinPoints true with negative points",+ json: `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 10.0, "matchType": "1", "op": "1",+ "requireMinPoints": true, "requiredNumPoints": -1+ }+ }`,+ wantErr: true,+ errSubstr: "requiredNumPoints",+ },++ // labels & annotations+ {+ name: "invalid label name starting with number",+ json: patchJSON(validV1Builder(), `{"labels": {"1bad": "value"}}`),+ wantErr: true,+ errSubstr: "label name",+ },+ {+ name: "invalid label name with special chars",+ json: patchJSON(validV1Builder(), `{"labels": {"bad-name": "value"}}`),+ wantErr: true,+ errSubstr: "label name",+ },+ {+ name: "valid label name with dots and underscores",+ json: patchJSON(validV1Builder(), `{"labels": {"valid.name_1": "value"}}`),+ },+ {+ name: "invalid annotation name",+ json: patchJSON(validV1Builder(), `{"annotations": {"bad-anno": "value"}}`),+ wantErr: true,+ errSubstr: "annotation name",+ },++ // templating+ {+ name: "invalid template in label value",+ json: patchJSON(validV1Builder(), `{"labels": {"severity": "{{.Invalid"}}`),+ wantErr: true,+ errSubstr: "template",+ },+ {+ name: "invalid template in annotation value",+ json: patchJSON(validV1Builder(), `{"annotations": {"description": "{{.Broken"}}`),+ wantErr: true,+ errSubstr: "template",+ },+ {+ name: "valid template in label",+ json: patchJSON(validV1Builder(), `{"labels": {"severity": "{{$labels.host}}"}}`),+ },++ // anomaly seasonality+ {+ name: "valid seasonality hourly for anomaly rule",+ json: `{+ "alert": "Test", "version": "v5", "ruleType": "anomaly_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 2.0, "matchType": "1", "op": "1",+ "seasonality": "hourly"+ }+ }`,+ },+ {+ name: "valid seasonality daily for anomaly rule",+ json: `{+ "alert": "Test", "version": "v5", "ruleType": "anomaly_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 2.0, "matchType": "1", "op": "1",+ "seasonality": "daily"+ }+ }`,+ },+ {+ name: "valid seasonality weekly for anomaly rule",+ json: `{+ "alert": "Test", "version": "v5", "ruleType": "anomaly_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 2.0, "matchType": "1", "op": "1",+ "seasonality": "weekly"+ }+ }`,+ },+ {+ name: "empty seasonality for anomaly rule is ok (defaults to daily)",+ json: `{+ "alert": "Test", "version": "v5", "ruleType": "anomaly_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 2.0, "matchType": "1", "op": "1"+ }+ }`,+ },+ {+ name: "invalid seasonality for anomaly rule",+ json: `{+ "alert": "Test", "version": "v5", "ruleType": "anomaly_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 2.0, "matchType": "1", "op": "1",+ "seasonality": "monthly"+ }+ }`,+ wantErr: true,+ errSubstr: "seasonality",+ },+ {+ name: "seasonality on non-anomaly rule is ignored",+ json: `{+ "alert": "Test", "version": "v5", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 2.0, "matchType": "1", "op": "1",+ "seasonality": "monthly"+ }+ }`,+ },++ // scheme version, v1, and v2alpha1+ {+ name: "unsupported schemaVersion v2",+ json: patchJSON(validV1Builder(), `{"schemaVersion": "v2"}`),+ wantErr: true,+ errSubstr: "schemaVersion",+ },+ {+ name: "unsupported schemaVersion v3",+ json: patchJSON(validV1Builder(), `{"schemaVersion": "v3"}`),+ wantErr: true,+ errSubstr: "schemaVersion",+ },+ {+ name: "unsupported schemaVersion random string",+ json: patchJSON(validV1Builder(), `{"schemaVersion": "foobar"}`),+ wantErr: true,+ errSubstr: "schemaVersion",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ unmarshalErr, validateErr := unmarshalAndValidate(tt.json)+ err := unmarshalErr+ if err == nil {+ err = validateErr+ }++ if tt.wantErr {+ if err == nil {+ t.Errorf("expected error containing %q, got nil", tt.errSubstr)+ } else if tt.errSubstr != "" && !strings.Contains(err.Error(), tt.errSubstr) {+ t.Errorf("expected error containing %q, got: %v", tt.errSubstr, err)+ }+ } else {+ if err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ }+ })+ }+}++func TestValidate_V1_ConditionFields(t *testing.T) {+ tests := []struct {+ name string+ json string+ wantErr bool+ errSubstr string+ }{+ // single target must always present for v1 alerts+ {+ name: "valid target",+ json: validV1Builder(),+ },+ {+ name: "missing target",+ json: `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "matchType": "1", "op": "1"+ }+ }`,+ wantErr: true,+ errSubstr: "condition.target",+ },++ // comparison operation can't be empty or invalid+ {+ name: "missing op",+ json: `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 10.0, "matchType": "1"+ }+ }`,+ wantErr: true,+ errSubstr: "condition.op",+ },+ {+ name: "invalid op value",+ json: `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 10.0, "matchType": "1", "op": "invalid"+ }+ }`,+ wantErr: true,+ errSubstr: "condition.op",+ },+ // numeric operators+ {name: "op numeric 1 (above)", json: patchJSON(validV1Builder(), `{}`)},+ {+ name: "op numeric 2 (below)",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":"2"}}`,+ },+ {+ name: "op numeric 3 (equal)",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":"3"}}`,+ },+ {+ name: "op numeric 4 (not_equal)",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":"4"}}`,+ },+ {+ name: "op numeric 5 (above_or_equal)",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":"5"}}`,+ },+ {+ name: "op numeric 6 (below_or_equal)",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":"6"}}`,+ },+ {+ name: "op numeric 7 (outside_bounds)",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":"7"}}`,+ },+ // literal operators+ {+ name: "op literal above",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":"above"}}`,+ },+ {+ name: "op literal below",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":"below"}}`,+ },+ {+ name: "op literal above_or_equal",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":"above_or_equal"}}`,+ },+ {+ name: "op literal below_or_equal",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":"below_or_equal"}}`,+ },+ {+ name: "op literal outside_bounds",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":"outside_bounds"}}`,+ },+ // symbol operators+ {+ name: "op symbol >",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":">"}}`,+ },+ {+ name: "op symbol >=",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":">="}}`,+ },+ {+ name: "op numeric 8 invalid",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":"8"}}`,+ wantErr: true,+ errSubstr: "condition.op",+ },++ // match type can't be empty or invalid for v1 alert payload+ {+ name: "missing matchType",+ json: `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 10.0, "op": "1"+ }+ }`,+ wantErr: true,+ errSubstr: "condition.matchType",+ },+ {+ name: "invalid matchType",+ json: `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 10.0, "op": "1", "matchType": "invalid"+ }+ }`,+ wantErr: true,+ errSubstr: "condition.matchType",+ },+ // literal matchTypes+ {+ name: "matchType literal at_least_once",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"op":"1","matchType":"at_least_once"}}`,+ },+ {+ name: "matchType literal all_the_times",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"op":"1","matchType":"all_the_times"}}`,+ },+ {+ name: "matchType literal on_average",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"op":"1","matchType":"on_average"}}`,+ },+ {+ name: "matchType short avg",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"op":"1","matchType":"avg"}}`,+ },+ {+ name: "matchType literal in_total",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"op":"1","matchType":"in_total"}}`,+ },+ {+ name: "matchType short sum",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"op":"1","matchType":"sum"}}`,+ },+ {+ name: "matchType literal last",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"op":"1","matchType":"last"}}`,+ },+ {+ name: "matchType numeric 6 invalid",+ json: `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"op":"1","matchType":"6"}}`,+ wantErr: true,+ errSubstr: "condition.matchType",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ _, validateErr := unmarshalAndValidate(tt.json)+ if tt.wantErr {+ if validateErr == nil {+ t.Errorf("expected Validate() error containing %q, got nil", tt.errSubstr)+ } else if tt.errSubstr != "" && !strings.Contains(validateErr.Error(), tt.errSubstr) {+ t.Errorf("expected error containing %q, got: %v", tt.errSubstr, validateErr)+ }+ } else {+ if validateErr != nil {+ t.Errorf("unexpected Validate() error: %v", validateErr)+ }+ }+ })+ }+}++func TestValidate_V2Alpha1(t *testing.T) {+ tests := []struct {+ name string+ json string+ wantErr bool+ errSubstr string+ }{+ // simple v2alpha1+ {+ name: "valid v2alpha1 rule",+ json: validV2Alpha1Builder(),+ },++ // missing required fields+ {+ name: "missing thresholds",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`,+ wantErr: true,+ errSubstr: "condition.thresholds",+ },+ {+ name: "missing evaluation",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]}+ },+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`,+ wantErr: true,+ errSubstr: "evaluation",+ },+ {+ name: "missing notificationSettings",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}}+ }`,+ wantErr: true,+ errSubstr: "notificationSettings",+ },++ // TODO(srikanthccv): should we throw here?+ // {+ // name: "v2alpha1 with condition.target",+ // json: `{+ // "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ // "condition": {+ // "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ // "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]},+ // "target": 10.0+ // },+ // "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ // "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ // }`,+ // wantErr: true,+ // errSubstr: "condition.target",+ // },+ // {+ // name: "v2alpha1 with condition.op",+ // json: `{+ // "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ // "condition": {+ // "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ // "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]},+ // "op": "1"+ // },+ // "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ // "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ // }`,+ // wantErr: true,+ // errSubstr: "condition.op",+ // },+ // {+ // name: "v2alpha1 with condition.matchType",+ // json: `{+ // "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ // "condition": {+ // "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ // "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]},+ // "matchType": "1"+ // },+ // "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ // "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ // }`,+ // wantErr: true,+ // errSubstr: "condition.matchType",+ // },+ // {+ // name: "v2alpha1 with preferredChannels",+ // json: patchJSON(validV2Alpha1Builder(), `{"preferredChannels": ["slack"]}`),+ // wantErr: true,+ // errSubstr: "preferredChannels",+ // },+ // {+ // name: "v2alpha1 with ALL v1 fields : multiple errors",+ // json: `{+ // "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ // "preferredChannels": ["slack"],+ // "condition": {+ // "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ // "target": 10.0, "op": "1", "matchType": "1"+ // }+ // }`,+ // wantErr: true,+ // errSubstr: "condition.target",+ // },++ {+ name: "v2alpha1 promql rule without thresholds is not ok",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "promql_rule",+ "condition": {+ "compositeQuery": {"queryType": "promql", "queries": [{"type": "promql", "spec": {"name": "A", "query": "up == 0", "disabled": false}}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`,+ wantErr: true,+ },++ // ensure notificationSettings is non empty for v2alpha1+ {+ name: "renotify enabled with zero interval",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "0s", "alertStates": ["firing"]}}+ }`,+ wantErr: true,+ errSubstr: "renotify",+ },+ {+ name: "renotify disabled with zero interval is ok",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": false}}+ }`,+ },+ {+ name: "invalid renotify alert state",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["invalid_state"]}}+ }`,+ wantErr: true,+ errSubstr: "alert state",+ },++ // threshold validation (happens on deser)+ {+ name: "threshold with empty name",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "", "target": 90.0, "matchType": "1", "op": "1"}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`,+ wantErr: true,+ errSubstr: "threshold name",+ },+ {+ name: "threshold with null target",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "matchType": "1", "op": "1"}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`,+ wantErr: true,+ errSubstr: "target",+ },+ {+ name: "threshold with invalid op",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "bad"}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`,+ wantErr: true,+ errSubstr: "condition.op",+ },+ {+ name: "threshold with invalid matchType",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName":"cpu","spaceAggregation":"p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "bad", "op": "1"}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`,+ wantErr: true,+ errSubstr: "condition.matchType",+ },+ {+ name: "threshold with literal op above is valid",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName":"cpu","spaceAggregation":"p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "at_least_once", "op": "above"}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`,+ },+ {+ name: "unknown threshold kind",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName":"cpu","spaceAggregation":"p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "advanced", "spec": []}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`,+ wantErr: true,+ errSubstr: "threshold",+ },++ // evaluation spec validation (happens on json unmarshal)+ {+ name: "rolling eval with zero window",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName":"cpu","spaceAggregation":"p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "0s", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`,+ wantErr: true,+ errSubstr: "evalWindow",+ },+ {+ name: "rolling eval with zero frequency",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName":"cpu","spaceAggregation":"p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "0s"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`,+ wantErr: true,+ errSubstr: "frequency",+ },+ {+ name: "unknown evaluation kind",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName":"cpu","spaceAggregation":"p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]}+ },+ "evaluation": {"kind": "custom", "spec": {}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`,+ wantErr: true,+ errSubstr: "evaluation",+ },++ // query-level validation+ {+ name: "promql query with empty query string",+ json: `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "promql_rule",+ "condition": {+ "compositeQuery": {"queryType": "promql", "queries": [{"type": "promql", "spec": {"name": "A", "query": "", "disabled": false}}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`,+ wantErr: true,+ errSubstr: "query",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ unmarshalErr, validateErr := unmarshalAndValidate(tt.json)+ err := unmarshalErr+ if err == nil {+ err = validateErr+ }++ if tt.wantErr {+ if err == nil {+ t.Errorf("expected error containing %q, got nil", tt.errSubstr)+ } else if tt.errSubstr != "" && !strings.Contains(err.Error(), tt.errSubstr) {+ t.Errorf("expected error containing %q, got: %v", tt.errSubstr, err)+ }+ } else {+ if err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ }+ })+ }+}++// ensure that truly malformed input doesn't panic.+func TestValidate_GarbagePayloads(t *testing.T) {+ payloads := []struct {+ name string+ json string+ }{+ {"empty object", `{}`},+ {"empty string", `""`},+ {"null", `null`},+ {"number", `42`},+ {"array", `[]`},+ {"just alert name", `{"alert": "x"}`},+ {"condition is a string", `{"alert": "x", "version": "v5", "condition": "not_an_object"}`},+ {"condition is a number", `{"alert": "x", "version": "v5", "condition": 42}`},+ {"condition is an array", `{"alert": "x", "version": "v5", "condition": []}`},+ {"queries is a string", `{"alert": "x", "version": "v5", "condition": {"compositeQuery": {"queries": "bad"}}}`},+ {"queries is a number", `{"alert": "x", "version": "v5", "condition": {"compositeQuery": {"queries": 42}}}`},+ {"thresholds is a string", `{"alert": "x", "version": "v5", "schemaVersion": "v2alpha1", "condition": {"compositeQuery": {"queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]}, "thresholds": "bad"}}`},+ {"evaluation is a string", `{"alert": "x", "version": "v5", "schemaVersion": "v2alpha1", "condition": {"compositeQuery": {"queries": []}}, "evaluation": "bad"}`},+ {"notificationSettings is a number", `{"alert": "x", "version": "v5", "schemaVersion": "v2alpha1", "condition": {"compositeQuery": {"queries": []}}, "notificationSettings": 42}`},+ {"deeply nested garbage", `{"alert": "x", "version": "v5", "condition": {"compositeQuery": {"queryType": "builder", "queries": [{"type": "unknown_type", "spec": {}}]}}}`},+ {"version is a number", `{"alert": "x", "version": 5, "condition": {}}`},+ {"labels is an array", `{"alert": "x", "version": "v5", "labels": [], "condition": {}}`},+ {"op is a number", `{"alert": "x", "version": "v5", "condition": {"compositeQuery": {"queries": []}, "op": 1}}`},+ }++ for _, tt := range payloads {+ t.Run(tt.name, func(t *testing.T) {+ // Must not panic, errors are expected+ var rule PostableRule+ err := json.Unmarshal([]byte(tt.json), &rule)+ if err == nil {+ // If unmarshal succeeded, Validate should also not panic+ _ = rule.Validate()+ }+ })+ }+}++// TestValidate_ReadPathVsWritePath verifies that UnmarshalJSON (read path)+// is lenient while Validate() (write path) is strict.+func TestValidate_ReadPathVsWritePath(t *testing.T) {+ tests := []struct {+ name string+ json string+ unmarshalOK bool // should UnmarshalJSON succeed?+ validateShouldErr bool // should Validate() fail?+ }{+ {+ name: "missing alert name : unmarshal ok, Validate fails",+ json: removeField(validV1Builder(), "alert"),+ unmarshalOK: true,+ validateShouldErr: true,+ },+ {+ name: "invalid alertType : unmarshal ok, Validate fails",+ json: patchJSON(validV1Builder(), `{"alertType": "GARBAGE"}`),+ unmarshalOK: true,+ validateShouldErr: true,+ },+ {+ name: "unsupported schemaVersion : unmarshal ok, Validate fails",+ json: patchJSON(validV1Builder(), `{"schemaVersion": "v99"}`),+ unmarshalOK: true,+ validateShouldErr: true,+ },+ {+ name: "valid v1 rule : both ok",+ json: validV1Builder(),+ unmarshalOK: true,+ validateShouldErr: false,+ },+ {+ name: "wrong version : unmarshal fails (pre-existing check)",+ json: patchJSON(validV1Builder(), `{"version": "v3"}`),+ unmarshalOK: false,+ validateShouldErr: false, // not reached+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ var rule PostableRule+ unmarshalErr := json.Unmarshal([]byte(tt.json), &rule)++ if tt.unmarshalOK && unmarshalErr != nil {+ t.Fatalf("expected unmarshal to succeed, got: %v", unmarshalErr)+ }+ if !tt.unmarshalOK && unmarshalErr == nil {+ t.Fatalf("expected unmarshal to fail, but it succeeded")+ }+ if unmarshalErr != nil {+ return+ }++ validateErr := rule.Validate()+ if tt.validateShouldErr && validateErr == nil {+ t.Errorf("expected Validate() to fail, but it succeeded")+ }+ if !tt.validateShouldErr && validateErr != nil {+ t.Errorf("expected Validate() to succeed, got: %v", validateErr)+ }+ })+ }+}++// TestValidate_ProcessRuleDefaults verifies that processRuleDefaults applies+// correct defaults during UnmarshalJSON.+func TestValidate_ProcessRuleDefaults(t *testing.T) {+ t.Run("v1 defaults schemaVersion when omitted", func(t *testing.T) {+ var rule PostableRule+ _ = json.Unmarshal([]byte(validV1Builder()), &rule)+ if rule.SchemaVersion != DefaultSchemaVersion {+ t.Errorf("expected schemaVersion %q, got %q", DefaultSchemaVersion, rule.SchemaVersion)+ }+ })++ t.Run("v1 explicit schemaVersion v1 same behavior", func(t *testing.T) {+ j := patchJSON(validV1Builder(), `{"schemaVersion": "v1"}`)+ var rule PostableRule+ _ = json.Unmarshal([]byte(j), &rule)+ if rule.SchemaVersion != DefaultSchemaVersion {+ t.Errorf("expected schemaVersion %q, got %q", DefaultSchemaVersion, rule.SchemaVersion)+ }+ if rule.RuleCondition.Thresholds == nil {+ t.Error("expected thresholds to be auto-populated for v1")+ }+ })++ t.Run("v1 auto-populates evalWindow and frequency", func(t *testing.T) {+ // validV1Builder does not set evalWindow/frequency+ j := removeField(validV1Builder(), "evalWindow")+ j = removeField(j, "frequency")+ var rule PostableRule+ _ = json.Unmarshal([]byte(j), &rule)+ if rule.EvalWindow.Duration().String() != "5m0s" {+ t.Errorf("expected default evalWindow 5m, got %v", rule.EvalWindow)+ }+ if rule.Frequency.Duration().String() != "1m0s" {+ t.Errorf("expected default frequency 1m, got %v", rule.Frequency)+ }+ })++ t.Run("v2alpha1 does NOT default evalWindow and frequency", func(t *testing.T) {+ var rule PostableRule+ _ = json.Unmarshal([]byte(validV2Alpha1Builder()), &rule)+ if !rule.EvalWindow.IsZero() {+ t.Errorf("expected evalWindow to be zero for v2alpha1, got %v", rule.EvalWindow)+ }+ if !rule.Frequency.IsZero() {+ t.Errorf("expected frequency to be zero for v2alpha1, got %v", rule.Frequency)+ }+ })++ t.Run("v1 auto-populates thresholds from condition fields", func(t *testing.T) {+ var rule PostableRule+ _ = json.Unmarshal([]byte(validV1Builder()), &rule)+ if rule.RuleCondition.Thresholds == nil {+ t.Fatal("expected thresholds to be populated")+ }+ if rule.RuleCondition.Thresholds.Kind != BasicThresholdKind {+ t.Errorf("expected BasicThresholdKind, got %v", rule.RuleCondition.Thresholds.Kind)+ }+ })++ t.Run("v1 auto-populates evaluation as rolling", func(t *testing.T) {+ var rule PostableRule+ _ = json.Unmarshal([]byte(validV1Builder()), &rule)+ if rule.Evaluation == nil {+ t.Fatal("expected evaluation to be populated")+ }+ if rule.Evaluation.Kind != RollingEvaluation {+ t.Errorf("expected RollingEvaluation, got %v", rule.Evaluation.Kind)+ }+ })++ t.Run("v1 auto-populates notificationSettings", func(t *testing.T) {+ var rule PostableRule+ _ = json.Unmarshal([]byte(validV1Builder()), &rule)+ if rule.NotificationSettings == nil {+ t.Fatal("expected notificationSettings to be populated")+ }+ if !rule.NotificationSettings.Renotify.Enabled {+ t.Error("expected renotify to be enabled by default")+ }+ })++ t.Run("v1 auto-detects ruleType from builder queryType", func(t *testing.T) {+ var rule PostableRule+ _ = json.Unmarshal([]byte(validV1Builder()), &rule)+ if rule.RuleType != RuleTypeThreshold {+ t.Errorf("expected threshold_rule, got %v", rule.RuleType)+ }+ })++ t.Run("v1 auto-detects ruleType from promql queryType", func(t *testing.T) {+ var rule PostableRule+ _ = json.Unmarshal([]byte(validV1Promql()), &rule)+ if rule.RuleType != RuleTypeProm {+ t.Errorf("expected promql_rule, got %v", rule.RuleType)+ }+ })+}++// TestValidate_MarshalRoundTrip verifies marshal to unmarshal produces equivalent rules.+func TestValidate_MarshalRoundTrip(t *testing.T) {+ t.Run("v1 round-trip strips computed fields and re-derives", func(t *testing.T) {+ var original PostableRule+ _ = json.Unmarshal([]byte(validV1Builder()), &original)++ // Marshal strips thresholds/evaluation/notificationSettings/schemaVersion+ marshaled, err := json.Marshal(&original)+ if err != nil {+ t.Fatalf("marshal error: %v", err)+ }++ // Verify stripped fields are absent from marshaled JSON+ var raw map[string]json.RawMessage+ _ = json.Unmarshal(marshaled, &raw)+ if _, ok := raw["schemaVersion"]; ok {+ t.Error("expected schemaVersion to be stripped from v1 marshal output")+ }+ if _, ok := raw["evaluation"]; ok {+ t.Error("expected evaluation to be stripped from v1 marshal output")+ }+ if _, ok := raw["notificationSettings"]; ok {+ t.Error("expected notificationSettings to be stripped from v1 marshal output")+ }++ // Unmarshal back : fields should be re-derived+ var roundTripped PostableRule+ if err := json.Unmarshal(marshaled, &roundTripped); err != nil {+ t.Fatalf("unmarshal error: %v", err)+ }+ if roundTripped.RuleCondition.Thresholds == nil {+ t.Error("expected thresholds to be re-derived after round-trip")+ }+ if roundTripped.Evaluation == nil {+ t.Error("expected evaluation to be re-derived after round-trip")+ }+ if roundTripped.NotificationSettings == nil {+ t.Error("expected notificationSettings to be re-derived after round-trip")+ }+ })++ t.Run("v2alpha1 round-trip preserves all fields", func(t *testing.T) {+ var original PostableRule+ _ = json.Unmarshal([]byte(validV2Alpha1Builder()), &original)++ marshaled, err := json.Marshal(&original)+ if err != nil {+ t.Fatalf("marshal error: %v", err)+ }++ var raw map[string]json.RawMessage+ _ = json.Unmarshal(marshaled, &raw)+ if _, ok := raw["schemaVersion"]; !ok {+ t.Error("expected schemaVersion to be preserved in v2alpha1 marshal output")+ }+ if _, ok := raw["evaluation"]; !ok {+ t.Error("expected evaluation to be preserved in v2alpha1 marshal output")+ }+ if _, ok := raw["notificationSettings"]; !ok {+ t.Error("expected notificationSettings to be preserved in v2alpha1 marshal output")+ }++ var roundTripped PostableRule+ if err := json.Unmarshal(marshaled, &roundTripped); err != nil {+ t.Fatalf("unmarshal error: %v", err)+ }+ if roundTripped.SchemaVersion != SchemaVersionV2Alpha1 {+ t.Errorf("expected schemaVersion %q, got %q", SchemaVersionV2Alpha1, roundTripped.SchemaVersion)+ }+ })+}++// TestValidate_MultipleErrors verifies that all errors are collected, not just the first.+func TestValidate_MultipleErrors(t *testing.T) {+ t.Run("multiple errors returned together", func(t *testing.T) {+ // Missing alert + wrong version + invalid alertType+ j := `{+ "version": "v3",+ "alertType": "GARBAGE",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 10.0, "matchType": "1", "op": "1"+ }+ }`+ // unmarshal will fail on version (read-path check), so test via Validate on a constructed rule+ var rule PostableRule+ err := json.Unmarshal([]byte(j), &rule)+ // version check is in validate() (read path), so unmarshal fails+ if err == nil {+ t.Fatal("expected unmarshal error for wrong version")+ }+ // The error should mention version+ if !strings.Contains(err.Error(), "version") {+ t.Errorf("expected error to mention version, got: %v", err)+ }+ })++ t.Run("v2alpha1 multiple suggestion errors returned together", func(t *testing.T) {+ j := `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "preferredChannels": ["slack"],+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 10.0, "op": "1", "matchType": "1"+ }+ }`+ _, validateErr := unmarshalAndValidate(j)+ if validateErr == nil {+ t.Fatal("expected Validate() error")+ }+ errStr := validateErr.Error()+ // Should contain errors for thresholds, evaluation, notificationSettings+ for _, substr := range []string{"evaluation", "notificationSettings"} {+ if !strings.Contains(errStr, substr) {+ t.Errorf("expected error to mention %q, got: %v", substr, validateErr)+ }+ }+ })+}++// TestValidate_V1_AllSymbolAndShortOperators tests symbol and short operator variants.+func TestValidate_V1_AllSymbolAndShortOperators(t *testing.T) {+ mkRule := func(op string) string {+ return `{"alert":"T","version":"v5","condition":{"compositeQuery":{"queryType":"builder","queries":[{"type":"builder_query","spec":{"name":"A","signal":"metrics","aggregations":[{"metricName":"cpu","spaceAggregation":"p50"}],"stepInterval":"5m"}}]},"target":10.0,"matchType":"1","op":"` + op + `"}}`+ }++ validOps := []string{+ // symbols+ ">", "<", "=", "!=", ">=", "<=",+ // short literals+ "eq", "not_eq", "above_or_eq", "below_or_eq",+ }+ for _, op := range validOps {+ t.Run("op "+op, func(t *testing.T) {+ _, validateErr := unmarshalAndValidate(mkRule(op))+ if validateErr != nil {+ t.Errorf("expected op %q to be valid, got: %v", op, validateErr)+ }+ })+ }++ invalidOps := []string{">>", "<>", "===", "~", "contains", "0", "8", "99"}+ for _, op := range invalidOps {+ t.Run("invalid op "+op, func(t *testing.T) {+ _, validateErr := unmarshalAndValidate(mkRule(op))+ if validateErr == nil {+ t.Errorf("expected op %q to be invalid", op)+ }+ })+ }+}++// TestValidate_V2Alpha1_CumulativeEvaluation tests cumulative evaluation schedules.+func TestValidate_V2Alpha1_CumulativeEvaluation(t *testing.T) {+ mkRule := func(evalJSON string) string {+ return `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]}+ },+ "evaluation": ` + evalJSON + `,+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`+ }++ tests := []struct {+ name string+ evalJSON string+ wantErr bool+ errSubstr string+ }{+ {+ name: "valid cumulative hourly",+ evalJSON: `{"kind": "cumulative", "spec": {"schedule": {"type": "hourly", "minute": 0}, "frequency": "5m", "timezone": "UTC"}}`,+ },+ {+ name: "valid cumulative daily",+ evalJSON: `{"kind": "cumulative", "spec": {"schedule": {"type": "daily", "hour": 9, "minute": 30}, "frequency": "5m", "timezone": "America/New_York"}}`,+ },+ {+ name: "valid cumulative weekly",+ evalJSON: `{"kind": "cumulative", "spec": {"schedule": {"type": "weekly", "weekday": 1, "hour": 14, "minute": 0}, "frequency": "5m", "timezone": "UTC"}}`,+ },+ {+ name: "valid cumulative monthly",+ evalJSON: `{"kind": "cumulative", "spec": {"schedule": {"type": "monthly", "day": 1, "hour": 0, "minute": 0}, "frequency": "5m", "timezone": "UTC"}}`,+ },+ {+ name: "cumulative missing minute for hourly",+ evalJSON: `{"kind": "cumulative", "spec": {"schedule": {"type": "hourly"}, "frequency": "5m", "timezone": "UTC"}}`,+ wantErr: true,+ errSubstr: "minute",+ },+ {+ name: "cumulative invalid timezone",+ evalJSON: `{"kind": "cumulative", "spec": {"schedule": {"type": "hourly", "minute": 0}, "frequency": "5m", "timezone": "Mars/Olympus"}}`,+ wantErr: true,+ errSubstr: "timezone",+ },+ {+ name: "cumulative zero frequency",+ evalJSON: `{"kind": "cumulative", "spec": {"schedule": {"type": "hourly", "minute": 0}, "frequency": "0s", "timezone": "UTC"}}`,+ wantErr: true,+ errSubstr: "frequency",+ },+ {+ name: "cumulative daily missing hour",+ evalJSON: `{"kind": "cumulative", "spec": {"schedule": {"type": "daily", "minute": 30}, "frequency": "5m", "timezone": "UTC"}}`,+ wantErr: true,+ errSubstr: "hour",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ unmarshalErr, validateErr := unmarshalAndValidate(mkRule(tt.evalJSON))+ err := unmarshalErr+ if err == nil {+ err = validateErr+ }+ if tt.wantErr {+ if err == nil {+ t.Errorf("expected error containing %q, got nil", tt.errSubstr)+ } else if !strings.Contains(err.Error(), tt.errSubstr) {+ t.Errorf("expected error containing %q, got: %v", tt.errSubstr, err)+ }+ } else if err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ })+ }+}++// TestValidate_V2Alpha1_MultipleThresholds tests multi-threshold and literal ops in thresholds.+func TestValidate_V2Alpha1_MultipleThresholds(t *testing.T) {+ t.Run("warning and critical thresholds", func(t *testing.T) {+ j := `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [+ {"name": "warning", "target": 70.0, "matchType": "1", "op": "1"},+ {"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}+ ]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`+ _, err := unmarshalAndValidate(j)+ if err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ })++ t.Run("thresholds with literal ops and matchTypes", func(t *testing.T) {+ j := `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [+ {"name": "warning", "target": 70.0, "matchType": "on_average", "op": "above_or_equal"},+ {"name": "critical", "target": 90.0, "matchType": "last", "op": "above"}+ ]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ["firing"]}}+ }`+ _, err := unmarshalAndValidate(j)+ if err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ })+}++// TestValidate_V2Alpha1_NotificationStates tests various renotify alert state combinations.+func TestValidate_V2Alpha1_NotificationStates(t *testing.T) {+ mkRule := func(states string) string {+ return `{+ "alert": "Test", "version": "v5", "schemaVersion": "v2alpha1", "ruleType": "threshold_rule",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "thresholds": {"kind": "basic", "spec": [{"name": "critical", "target": 90.0, "matchType": "1", "op": "1"}]}+ },+ "evaluation": {"kind": "rolling", "spec": {"evalWindow": "5m", "frequency": "1m"}},+ "notificationSettings": {"renotify": {"enabled": true, "interval": "4h", "alertStates": ` + states + `}}+ }`+ }++ tests := []struct {+ name string+ states string+ wantErr bool+ }{+ {"firing only", `["firing"]`, false},+ {"nodata only", `["nodata"]`, false},+ {"both firing and nodata", `["firing", "nodata"]`, false},+ {"empty states", `[]`, false},+ {"invalid state", `["pending"]`, true},+ {"mix valid and invalid", `["firing", "inactive"]`, true},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ unmarshalErr, validateErr := unmarshalAndValidate(mkRule(tt.states))+ err := unmarshalErr+ if err == nil {+ err = validateErr+ }+ if tt.wantErr && err == nil {+ t.Error("expected error, got nil")+ }+ if !tt.wantErr && err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ })+ }+}++// TestValidate_QueryTypes tests various query types in the composite query.+func TestValidate_QueryTypes(t *testing.T) {+ mkV1Rule := func(queryJSON string) string {+ return `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [` + queryJSON + `]},+ "target": 10.0, "matchType": "1", "op": "1"+ }+ }`+ }++ t.Run("logs signal query", func(t *testing.T) {+ j := mkV1Rule(`{"type": "builder_query", "spec": {"name": "A", "signal": "logs", "stepInterval": "5m", "aggregations": [{"spaceAggregation": "count"}], "filter": {"expression": "severity_text = 'ERROR'"}}}`)+ _, err := unmarshalAndValidate(j)+ if err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ })++ t.Run("traces signal query", func(t *testing.T) {+ j := mkV1Rule(`{"type": "builder_query", "spec": {"name": "A", "signal": "traces", "stepInterval": "5m", "aggregations": [{"spaceAggregation": "count"}]}}`)+ _, err := unmarshalAndValidate(j)+ if err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ })++ t.Run("clickhouse_sql query", func(t *testing.T) {+ j := `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "clickhouse_sql", "queries": [{"type": "clickhouse_sql", "spec": {"name": "A", "query": "SELECT count() FROM logs", "disabled": false}}]},+ "target": 10.0, "matchType": "1", "op": "1"+ }+ }`+ _, err := unmarshalAndValidate(j)+ if err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ })++ t.Run("clickhouse_sql with empty query string", func(t *testing.T) {+ j := `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "clickhouse_sql", "queries": [{"type": "clickhouse_sql", "spec": {"name": "A", "query": "", "disabled": false}}]},+ "target": 10.0, "matchType": "1", "op": "1"+ }+ }`+ _, err := unmarshalAndValidate(j)+ if err == nil {+ t.Error("expected error for empty clickhouse_sql query")+ }+ })++ t.Run("formula query", func(t *testing.T) {+ j := mkV1Rule(`+ {"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}},+ {"type": "builder_formula", "spec": {"name": "F1", "expression": "A * 100", "disabled": false}}+ `)+ _, err := unmarshalAndValidate(j)+ if err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ })++ t.Run("formula with empty expression", func(t *testing.T) {+ j := mkV1Rule(`+ {"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}},+ {"type": "builder_formula", "spec": {"name": "F1", "expression": "", "disabled": false}}+ `)+ _, err := unmarshalAndValidate(j)+ if err == nil {+ t.Error("expected error for empty formula expression")+ }+ })++ t.Run("duplicate query names", func(t *testing.T) {+ j := mkV1Rule(`+ {"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}},+ {"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "mem", "spaceAggregation": "p50"}], "stepInterval": "5m"}}+ `)+ _, err := unmarshalAndValidate(j)+ if err == nil {+ t.Error("expected error for duplicate query names")+ }+ })+}++// TestValidate_DisabledRule verifies that disabled rules are still validated.+func TestValidate_DisabledRule(t *testing.T) {+ t.Run("disabled rule with invalid alertType still fails Validate", func(t *testing.T) {+ j := patchJSON(validV1Builder(), `{"disabled": true, "alertType": "GARBAGE"}`)+ _, err := unmarshalAndValidate(j)+ if err == nil {+ t.Error("expected Validate() to fail even for disabled rule")+ }+ })++ t.Run("disabled rule with valid payload passes", func(t *testing.T) {+ j := patchJSON(validV1Builder(), `{"disabled": true}`)+ _, err := unmarshalAndValidate(j)+ if err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ })+}++// TestValidate_AlertOnAbsent documents current behavior for alertOnAbsent/absentFor fields.+func TestValidate_AlertOnAbsent(t *testing.T) {+ t.Run("alertOnAbsent true accepted", func(t *testing.T) {+ j := `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 10.0, "matchType": "1", "op": "1",+ "alertOnAbsent": true, "absentFor": 300+ }+ }`+ _, err := unmarshalAndValidate(j)+ if err != nil {+ t.Errorf("unexpected error: %v", err)+ }+ })++ t.Run("alertOnAbsent true adds nodata to renotify states in v1", func(t *testing.T) {+ j := `{+ "alert": "Test", "version": "v5",+ "condition": {+ "compositeQuery": {"queryType": "builder", "queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "cpu", "spaceAggregation": "p50"}], "stepInterval": "5m"}}]},+ "target": 10.0, "matchType": "1", "op": "1",+ "alertOnAbsent": true+ }+ }`+ var rule PostableRule+ if err := json.Unmarshal([]byte(j), &rule); err != nil {+ t.Fatalf("unmarshal error: %v", err)+ }+ if rule.NotificationSettings == nil {+ t.Fatal("expected notificationSettings to be populated")+ }+ states := rule.NotificationSettings.Renotify.AlertStates+ foundNoData := false+ for _, s := range states {+ if s == StateNoData {+ foundNoData = true+ }+ }+ if !foundNoData {+ t.Error("expected nodata state in renotify alertStates when alertOnAbsent is true")+ }+ })+}