From cc1e6e40f0c39f44e94f001d5f58ff975ce0b6ff Mon Sep 17 00:00:00 2001 From: Sahil Rasaikar Date: Sun, 5 Oct 2025 16:31:17 +0530 Subject: [PATCH] fix: Updates unknown state to -1,adds fix for failing test case Signed-off-by: Sahil Rasaikar --- rules/alerting.go | 13 +++++++------ rules/alerting_test.go | 2 ++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/rules/alerting.go b/rules/alerting.go index 6af3a46171..6e2dc3ffa7 100644 --- a/rules/alerting.go +++ b/rules/alerting.go @@ -50,6 +50,8 @@ const ( type AlertState int const ( + // StateUnknown is the state of an alert that has not yet been evaluated. + StateUnknown AlertState = -1 // StateInactive is the state of an alert that is neither firing nor pending. StateInactive AlertState = iota // StatePending is the state of an alert that has been active for less than @@ -58,8 +60,6 @@ const ( // StateFiring is the state of an alert that has been active for longer than // the configured threshold duration. StateFiring - // StateUnknown is the state of an alert that has not yet been evaluated. - StateUnknown ) func (s AlertState) String() string { @@ -536,13 +536,14 @@ func (r *AlertingRule) Eval(ctx context.Context, queryOffset time.Duration, ts t // State returns the maximum state of alert instances for this rule. // StateFiring > StatePending > StateInactive > StateUnknown. func (r *AlertingRule) State() AlertState { - // If the rule has never been evaluated, return StateUnknown - if r.GetEvaluationTimestamp().IsZero() { - return StateUnknown - } r.activeMtx.Lock() defer r.activeMtx.Unlock() + + // Check if the rule has been evaluated + if r.evaluationTimestamp.Load().IsZero() { + return StateUnknown + } maxState := StateInactive for _, a := range r.active { diff --git a/rules/alerting_test.go b/rules/alerting_test.go index 49817cc286..fff1d40048 100644 --- a/rules/alerting_test.go +++ b/rules/alerting_test.go @@ -85,6 +85,8 @@ func TestAlertingRuleState(t *testing.T) { for i, test := range tests { rule := NewAlertingRule(test.name, nil, 0, 0, labels.EmptyLabels(), labels.EmptyLabels(), labels.EmptyLabels(), "", true, nil) rule.active = test.active + // Set evaluation timestamp to simulate that the rule has been evaluated + rule.SetEvaluationTimestamp(time.Now()) got := rule.State() require.Equal(t, test.want, got, "test case %d unexpected AlertState, want:%d got:%d", i, test.want, got) }