Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 17 additions & 15 deletions backend/internal/models/alert.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,21 +137,23 @@ func (j *JSONBArray) Scan(value interface{}) error {

// Alert represents an alert from a monitoring system
type Alert struct {
ID uuid.UUID `gorm:"type:uuid;primaryKey;default:gen_random_uuid()" json:"id"`
ExternalID string `gorm:"type:varchar(255);not null" json:"external_id"`
Source string `gorm:"type:varchar(100);not null" json:"source"`
Fingerprint string `gorm:"type:varchar(255);index" json:"fingerprint"`
Status AlertStatus `gorm:"type:varchar(50);not null;default:'firing'" json:"status"`
Severity AlertSeverity `gorm:"type:varchar(50);not null;default:'info'" json:"severity"`
Title string `gorm:"type:varchar(500);not null" json:"title"`
Description string `gorm:"type:text" json:"description"`
Labels JSONB `gorm:"type:jsonb;default:'{}'" json:"labels"`
Annotations JSONB `gorm:"type:jsonb;default:'{}'" json:"annotations"`
RawPayload JSONB `gorm:"type:jsonb" json:"raw_payload"`
StartedAt time.Time `gorm:"type:timestamptz;not null" json:"started_at"`
EndedAt *time.Time `gorm:"type:timestamptz" json:"ended_at"`
ReceivedAt time.Time `gorm:"type:timestamptz;not null;default:now()" json:"received_at"`
CreatedAt time.Time `gorm:"type:timestamptz;not null;default:now()" json:"created_at"`
// IncidentSeverity is a transient request used only when creating an incident.
IncidentSeverity IncidentSeverity `gorm:"-" json:"-"`
ID uuid.UUID `gorm:"type:uuid;primaryKey;default:gen_random_uuid()" json:"id"`
ExternalID string `gorm:"type:varchar(255);not null" json:"external_id"`
Source string `gorm:"type:varchar(100);not null" json:"source"`
Fingerprint string `gorm:"type:varchar(255);index" json:"fingerprint"`
Status AlertStatus `gorm:"type:varchar(50);not null;default:'firing'" json:"status"`
Severity AlertSeverity `gorm:"type:varchar(50);not null;default:'info'" json:"severity"`
Title string `gorm:"type:varchar(500);not null" json:"title"`
Description string `gorm:"type:text" json:"description"`
Labels JSONB `gorm:"type:jsonb;default:'{}'" json:"labels"`
Annotations JSONB `gorm:"type:jsonb;default:'{}'" json:"annotations"`
RawPayload JSONB `gorm:"type:jsonb" json:"raw_payload"`
StartedAt time.Time `gorm:"type:timestamptz;not null" json:"started_at"`
EndedAt *time.Time `gorm:"type:timestamptz" json:"ended_at"`
ReceivedAt time.Time `gorm:"type:timestamptz;not null;default:now()" json:"received_at"`
CreatedAt time.Time `gorm:"type:timestamptz;not null;default:now()" json:"created_at"`

// EscalationPolicyID links this alert to the escalation policy assigned by
// the routing engine. Nil means no escalation is configured for this alert.
Expand Down
2 changes: 1 addition & 1 deletion backend/internal/models/routing_rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ import (
// {
// "create_incident": true, // default action
// "suppress": true, // alert stored, no incident created
// "severity_override": "critical", // override alert severity
// "severity_override": "critical", // incident level (critical/high/medium/low), or legacy warning/info
// "channel_override": "db-oncall" // override Slack channel name suffix
// "notify_email_label": "owner" // DM the Regen user at labels[owner]
// }
Expand Down
35 changes: 24 additions & 11 deletions backend/internal/models/webhooks/generic.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ type GenericAlert struct {
// Severity must be "critical", "warning", or "info" (defaults to "warning")
Severity string `json:"severity" binding:"omitempty,oneof=critical warning info"`

// IncidentSeverity explicitly requests an incident at this level, including for info alerts.
IncidentSeverity string `json:"incident_severity,omitempty" binding:"omitempty,oneof=critical high medium low"`

// Status must be "firing" or "resolved" (defaults to "firing")
Status string `json:"status" binding:"omitempty,oneof=firing resolved"`

Expand Down Expand Up @@ -202,6 +205,10 @@ func (g *GenericProvider) normalizeGenericAlert(genericAlert *GenericAlert) (*No
}
}

if v := genericAlert.IncidentSeverity; v != "" && v != "critical" && v != "high" && v != "medium" && v != "low" {
return nil, fmt.Errorf("invalid incident_severity %q: must be critical, high, medium, or low", v)
}

// Apply status default and validate
status := genericAlert.Status
if status == "" {
Expand Down Expand Up @@ -248,17 +255,18 @@ func (g *GenericProvider) normalizeGenericAlert(genericAlert *GenericAlert) (*No
}

return &NormalizedAlert{
ExternalID: externalID,
Source: "generic",
Status: status,
Severity: severity,
Title: genericAlert.Title,
Description: genericAlert.Description,
Labels: labels,
Annotations: annotations,
RawPayload: json.RawMessage(rawPayloadBytes),
StartedAt: startedAt,
EndedAt: genericAlert.EndedAt,
ExternalID: externalID,
Source: "generic",
Status: status,
Severity: severity,
IncidentSeverity: genericAlert.IncidentSeverity,
Title: genericAlert.Title,
Description: genericAlert.Description,
Labels: labels,
Annotations: annotations,
RawPayload: json.RawMessage(rawPayloadBytes),
StartedAt: startedAt,
EndedAt: genericAlert.EndedAt,
}, nil
}

Expand Down Expand Up @@ -308,6 +316,11 @@ func GetJSONSchema() map[string]interface{} {
"enum": []string{"critical", "warning", "info"},
"default": "warning",
},
"incident_severity": map[string]interface{}{
"type": "string",
"description": "Explicit incident severity; creates an incident even for info alerts. Routing suppression and severity overrides take precedence. Omit for legacy severity mapping.",
"enum": []string{"critical", "high", "medium", "low"},
},
"status": map[string]interface{}{
"type": "string",
"description": "Alert status (defaults to 'firing')",
Expand Down
40 changes: 40 additions & 0 deletions backend/internal/models/webhooks/generic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"net/http"
"os"
"testing"
Expand Down Expand Up @@ -353,3 +354,42 @@ func TestGenericProviderRFC3339Timestamps(t *testing.T) {
})
}
}

func TestGenericIncidentSeverityValidation(t *testing.T) {
for _, body := range []string{
`{"title":"Test","incident_severity":"invalid"}`,
`{"alerts":[{"title":"Test","incident_severity":"warning"}]}`,
} {
_, err := (&GenericProvider{}).ParsePayload([]byte(body))
require.Error(t, err)
}
}

func TestGenericProviderIncidentSeverity(t *testing.T) {
for _, level := range []string{"", "critical", "high", "medium", "low"} {
for _, batch := range []bool{false, true} {
name := fmt.Sprintf("level=%s/batch=%t", level, batch)
t.Run(name, func(t *testing.T) {
payload := fmt.Sprintf(`{"title":"Test", "severity":"info", "incident_severity":%q}`, level)
if batch {
payload = `{"alerts":[` + payload + `]}`
}
alerts, err := (&GenericProvider{}).ParsePayload([]byte(payload))
require.NoError(t, err)
require.Len(t, alerts, 1)
require.Equal(t, level, alerts[0].IncidentSeverity)
require.Equal(t, "info", alerts[0].Severity)
})
}
}
}

func TestGenericIncidentSeveritySchema(t *testing.T) {
properties := GetJSONSchema()["properties"].(map[string]interface{})
items := properties["alerts"].(map[string]interface{})["items"].(map[string]interface{})
fields := items["properties"].(map[string]interface{})
field := fields["incident_severity"].(map[string]interface{})
require.Equal(t, []string{"critical", "high", "medium", "low"}, field["enum"])
require.NotContains(t, items["required"], "incident_severity")
require.NotContains(t, field, "default")
}
5 changes: 4 additions & 1 deletion backend/internal/models/webhooks/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ type NormalizedAlert struct {
// Severity represents the urgency level of the alert.
// MUST be one of: "critical", "warning", or "info"
//
// Severity affects incident auto-creation:
// Without an explicit IncidentSeverity, severity affects incident auto-creation:
// - "critical" → Always creates incident
// - "warning" → Always creates incident
// - "info" → Alert stored but no incident created
Expand All @@ -131,6 +131,9 @@ type NormalizedAlert struct {
// - Default to "warning" if source doesn't specify severity
Severity string `json:"severity"`

// IncidentSeverity requests an incident independently of monitoring severity.
IncidentSeverity string `json:"incident_severity,omitempty"`

// Title is a short, human-readable summary of the alert.
// Displayed in incident lists and Slack notifications.
//
Expand Down
90 changes: 90 additions & 0 deletions backend/internal/services/alert_lifecycle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -414,3 +414,93 @@ func TestAlertLifecycleConcurrentSharedIncidentResolutions(t *testing.T) {
assertStatus(t, db, first.ID, models.IncidentStatusResolved)
assertStatus(t, db, second.ID, models.IncidentStatusResolved)
}

func TestAlertLifecycleExplicitIncidentSeverity(t *testing.T) {
db := lifecycleDB(t)
require.NoError(t, db.Exec("DELETE FROM grouping_rules").Error)
rule := &models.GroupingRule{ID: uuid.New(), Name: "severity test", Enabled: true, Priority: 1, MatchLabels: models.JSONB{}, CrossSourceLabels: models.JSONBArray{"service"}, TimeWindowSeconds: 300}
require.NoError(t, db.Create(rule).Error)
for _, grouped := range []bool{false, true} {
for _, level := range []string{"critical", "high", "medium", "low"} {
t.Run(fmt.Sprintf("%s/grouped=%t", level, grouped), func(t *testing.T) {
svc := lifecycleService(db)
if grouped {
svc.SetGroupingEngine(NewGroupingEngine(repository.NewGroupingRuleRepository(db), repository.NewIncidentRepository(db), db))
}
alert := makeNormalizedAlert("generic", "info")
alert.Labels = map[string]string{"service": alert.ExternalID}
// Exercise an existing info alert as well as a fresh explicit request.
require.Zero(t, deliver(t, svc, alert, "firing").IncidentsCreated)
alert.IncidentSeverity = level
require.Equal(t, 1, deliver(t, svc, alert, "firing").IncidentsCreated)
inc := incidentFor(t, db, alert)
require.Equal(t, models.IncidentSeverity(level), inc.Severity)
require.Zero(t, deliver(t, svc, alert, "firing").IncidentsCreated)
if grouped {
other := makeNormalizedAlert("generic", "info")
other.Labels = alert.Labels
other.IncidentSeverity = "high"
require.Zero(t, deliver(t, svc, other, "firing").IncidentsCreated)
linked := incidentFor(t, db, other)
require.Equal(t, inc.ID, linked.ID)
require.Equal(t, models.IncidentSeverity(level), linked.Severity)
deliver(t, svc, other, "resolved")
}
deliver(t, svc, alert, "resolved")
assertStatus(t, db, inc.ID, models.IncidentStatusResolved)
resolved := makeNormalizedAlert("generic", "info")
resolved.IncidentSeverity = level
require.Zero(t, deliver(t, svc, resolved, "resolved").IncidentsCreated)
})
}
}
}

func TestAlertLifecycleIncidentSeveritySuppressed(t *testing.T) {
db := lifecycleDB(t)
svc := lifecycleService(db)
svc.SetRoutingEngine(severityRoutingEngine{RoutingDecision{Suppress: true}})
for _, level := range []string{"critical", "high", "medium", "low"} {
alert := makeNormalizedAlert("generic", "warning")
alert.IncidentSeverity = level
require.Zero(t, deliver(t, svc, alert, "firing").IncidentsCreated)
stored, err := repository.NewAlertRepository(db).GetByExternalID(context.Background(), alert.Source, alert.ExternalID)
require.NoError(t, err)
require.Equal(t, models.AlertSeverityWarning, stored.Severity)
}
var count int64
require.NoError(t, db.Model(&models.Incident{}).Count(&count).Error)
require.Zero(t, count)
}

func TestAlertLifecycleRoutingIncidentSeverity(t *testing.T) {
db := lifecycleDB(t)
require.NoError(t, db.Exec("DELETE FROM grouping_rules").Error)
groupRule := &models.GroupingRule{ID: uuid.New(), Name: "routing severity test", Enabled: true, Priority: 1, MatchLabels: models.JSONB{}, CrossSourceLabels: models.JSONBArray{"service"}, TimeWindowSeconds: 300}
require.NoError(t, db.Create(groupRule).Error)
for _, source := range []string{"prometheus", "grafana", "cloudwatch"} {
for _, level := range []string{"critical", "high", "medium", "low"} {
for _, grouped := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/%s/grouped=%t", source, level, grouped), func(t *testing.T) {
svc := lifecycleService(db)
rule := makeRoutingRule(1, models.JSONB{"source": []interface{}{source}}, models.JSONB{"severity_override": level})
svc.SetRoutingEngine(NewRoutingEngine(&mockRoutingRuleRepo{rules: []models.RoutingRule{rule}}))
if grouped {
svc.SetGroupingEngine(NewGroupingEngine(repository.NewGroupingRuleRepository(db), repository.NewIncidentRepository(db), db))
}
alert := makeNormalizedAlert(source, "info")
alert.Labels = map[string]string{"service": alert.ExternalID}
require.Equal(t, 1, deliver(t, svc, alert, "firing").IncidentsCreated)
inc := incidentFor(t, db, alert)
require.Equal(t, models.IncidentSeverity(level), inc.Severity)
stored, err := repository.NewAlertRepository(db).GetByExternalID(context.Background(), source, alert.ExternalID)
require.NoError(t, err)
require.Equal(t, models.AlertSeverityInfo, stored.Severity)
require.Zero(t, deliver(t, svc, alert, "firing").IncidentsCreated)
deliver(t, svc, alert, "resolved")
assertStatus(t, db, inc.ID, models.IncidentStatusResolved)
})
}
}
}
}
39 changes: 24 additions & 15 deletions backend/internal/services/alert_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ func (s *alertService) createOrUpdateAlert(ctx context.Context, alert *models.Al

// Alert exists, update mutable fields
previousStatus := existing.Status
existing.IncidentSeverity = alert.IncidentSeverity
existing.Status = alert.Status
existing.Title = alert.Title
existing.Description = alert.Description
Expand Down Expand Up @@ -296,11 +297,18 @@ func (s *alertService) processNormalizedAlerts(ctx context.Context, alerts []web
// severity (intentional — preserves the raw audit record). The override
// only affects which severity the resulting incident is created at.
if routingDecision.SeverityOverride != "" {
alert.Severity = parseSeverity(routingDecision.SeverityOverride)
switch routingDecision.SeverityOverride {
case "critical", "high", "medium", "low":
alert.IncidentSeverity = models.IncidentSeverity(routingDecision.SeverityOverride)
default:
// Preserve legacy warning/info overrides and their incident-creation behavior.
alert.Severity = parseSeverity(routingDecision.SeverityOverride)
alert.IncidentSeverity = ""
}
}

// Check if this alert should trigger an incident (uses possibly-overridden severity)
if s.incidentSvc.ShouldCreateIncident(alert.Severity) {
if alert.IncidentSeverity != "" || s.incidentSvc.ShouldCreateIncident(alert.Severity) {
// v0.3+: Use grouping engine if configured
if s.groupingEngine != nil {
decision, err := s.groupingEngine.EvaluateAlert(alert)
Expand Down Expand Up @@ -381,19 +389,20 @@ func (s *alertService) normalizedAlertToModel(normalized *webhooks.NormalizedAle
}

return &models.Alert{
ID: uuid.New(),
ExternalID: normalized.ExternalID,
Source: normalized.Source,
Fingerprint: normalized.ExternalID, // Use external_id as fingerprint (for Prometheus, this IS the fingerprint)
Status: status,
Severity: severity,
Title: normalized.Title,
Description: normalized.Description,
Labels: labels,
Annotations: annotations,
RawPayload: rawPayload,
StartedAt: normalized.StartedAt,
EndedAt: normalized.EndedAt,
ID: uuid.New(),
ExternalID: normalized.ExternalID,
Source: normalized.Source,
Fingerprint: normalized.ExternalID, // Use external_id as fingerprint (for Prometheus, this IS the fingerprint)
Status: status,
Severity: severity,
IncidentSeverity: models.IncidentSeverity(normalized.IncidentSeverity),
Title: normalized.Title,
Description: normalized.Description,
Labels: labels,
Annotations: annotations,
RawPayload: rawPayload,
StartedAt: normalized.StartedAt,
EndedAt: normalized.EndedAt,
}
}

Expand Down
11 changes: 9 additions & 2 deletions backend/internal/services/incident_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ func (s *incidentService) ShouldCreateIncident(severity models.AlertSeverity) bo
// CreateIncidentFromAlert creates an incident from an alert with full transaction support
func (s *incidentService) CreateIncidentFromAlert(ctx context.Context, alert *models.Alert, aiEnabled bool) (*models.Incident, error) {
// Map alert severity to incident severity
incidentSeverity := mapAlertSeverityToIncident(alert.Severity)
incidentSeverity := incidentSeverityForAlert(alert)

// Generate slug from title
slug := generateSlug(alert.Title)
Expand Down Expand Up @@ -440,7 +440,7 @@ func (s *incidentService) finishAlertIncident(ctx context.Context, alert *models
// with the same group_key try to create incidents.
func (s *incidentService) CreateIncidentFromAlertWithGrouping(ctx context.Context, alert *models.Alert, groupKey string, aiEnabled bool) (*models.Incident, error) {
// Map alert severity to incident severity
incidentSeverity := mapAlertSeverityToIncident(alert.Severity)
incidentSeverity := incidentSeverityForAlert(alert)

// Generate slug from title
slug := generateSlug(alert.Title)
Expand Down Expand Up @@ -806,6 +806,13 @@ func (s *incidentService) createTimelineEntry(incidentID uuid.UUID, entryType st
}
}

func incidentSeverityForAlert(alert *models.Alert) models.IncidentSeverity {
if alert.IncidentSeverity != "" {
return alert.IncidentSeverity
}
return mapAlertSeverityToIncident(alert.Severity)
}

// mapAlertSeverityToIncident maps alert severity to incident severity
func mapAlertSeverityToIncident(alertSeverity models.AlertSeverity) models.IncidentSeverity {
switch alertSeverity {
Expand Down
Loading
Loading