fix: Updates unknown state to -1,adds fix for failing test case

Signed-off-by: Sahil Rasaikar <sahil.rasaikar@gmail.com>
This commit is contained in:
Sahil Rasaikar 2025-10-05 16:31:17 +05:30
parent 516afbea67
commit cc1e6e40f0
2 changed files with 9 additions and 6 deletions

View File

@ -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 {

View File

@ -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)
}