Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Make alert incident timelines complete

rcourtman1878245cdb1c
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index e331fee70b..8a483f9a85 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -1132,12 +1132,29 @@ that canonical stream. It runs for lifecycle transitions regardless of
activation, quiet hours, grouping, rate limits, or destination state; delivery
callbacks remain policy-controlled consumers. Monitoring uses this seam to
materialize canonical resource-history breadcrumbs and incident shells. On
-startup it replays durable lifecycle transitions oldest first, then
-idempotently reconciles restored active alerts that predate the event store.
-This repairs resolved as well as active incident timelines without replaying
-any delivery side effect, and ensures an alert already visible in Overview
-cannot keep returning an unavailable timeline merely because its notification
-was held.
+startup it replays durable lifecycle transitions and migrated legacy-history
+snapshots oldest first, then idempotently reconciles restored active alerts
+that predate the event store. Because monitor construction precedes attachment
+of the API-owned durable unified-resource store, that attachment repeats the
+same idempotent replay so canonical resource history is repaired as well as the
+incident fallback cache. A migrated final snapshot expands only facts it
+actually carries: the occurrence start, saved acknowledgement, and known end;
+it does not invent delivery, escalation, analysis, or remediation events.
+The incident store retains those snapshot events as a fallback only when the
+canonical resource timeline lacks the equivalent event, so a partial durable
+projection cannot erase the occurrence start while complete canonical history
+still wins. The occurrence-qualified incident API performs the same repair
+from the active/history read model when retention or an older migration left a
+shell absent or empty. This repairs resolved as well as active incident
+timelines without replaying any delivery side effect, and ensures an alert
+already visible in Overview or History cannot keep returning an unavailable
+timeline merely because its notification was held or it predates the event
+store. Occurrence lookup allows only one second of start-time precision drift;
+it must not merge recurring or flapping incidents merely because they share an
+alert identifier and started within the same former ten-minute window.
+Snapshot events stored at equal timestamp precision order by lifecycle meaning,
+with detection first and resolution last, rather than by generated event ID;
+a malformed legacy end before its own start clamps to the start boundary.
The same dispatch policy owns firing-notification evidence on active alerts:
any alert that passes notification suppression and enters the fired callback
fan-out must carry `LastNotified` before the callback clone is emitted. Resolved
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 1588b61dea..18bb8a6f59 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -4476,6 +4476,19 @@ window as its delivery-attempt log, with an explicit bounded limit. That event
request runs independently of `GET /api/notifications/delivery-log`; failure
of either API must not recast the other response as empty or unavailable.
+`GET /api/alerts/incidents` with both `alertIdentifier` and `started_at` is an
+occurrence-qualified timeline read. The incident/resource-history projection
+remains authoritative. If that projection is absent or empty for an alert
+occurrence still present in the active or history read model, the handler
+materializes the minimum snapshot-backed timeline and returns it in the same
+request: detected at the saved start, acknowledged only when the snapshot says
+so, and resolved only for a non-active occurrence with a known end. This is an
+idempotent projection repair, not a delivery or lifecycle mutation, and it must
+not manufacture escalation, notification, analysis, command, or runbook
+events. Richer canonical events replace equivalent snapshot fallbacks when
+available. A genuinely unknown identifier/occurrence may still return `null`;
+an Alerts-page row with its canonical identifier and start time must not.
+
Per-alert snooze is a monitoring-write mutation over canonical alert identity.
`POST /api/alerts/snooze` accepts `alertIdentifier` and an RFC 3339 `until`,
rejects missing, past, or more-than-30-day expiries, and returns the normalized
diff --git a/internal/ai/memory/incidents.go b/internal/ai/memory/incidents.go
index 5902061bfc..9c3a268fd6 100644
--- a/internal/ai/memory/incidents.go
+++ b/internal/ai/memory/incidents.go
@@ -286,8 +286,9 @@ const (
defaultIncidentMaxEvents = 120
defaultIncidentMaxAgeDays = 90
maxIncidentFileSize = 20 * 1024 * 1024 // 20MB
- incidentStartMatchTolerance = 10 * time.Minute
+ incidentStartMatchTolerance = time.Second
projectedIncidentChangeLimit = 256
+ incidentSnapshotSource = "alert_history_snapshot"
)
// IncidentTimelineStore exposes the canonical resource timeline used to derive
@@ -450,6 +451,70 @@ func (s *IncidentStore) RecordAlertResolved(alert *alerts.Alert, resolvedAt time
s.saveAsync()
}
+// EnsureAlertOccurrence materializes the minimum honest timeline carried by
+// an alert snapshot. It is the read-repair boundary for active alerts and
+// legacy history entries that predate the canonical resource timeline. When
+// canonical events exist, projectIncident replaces these snapshot-derived
+// lifecycle breadcrumbs with the durable projection.
+func (s *IncidentStore) EnsureAlertOccurrence(alert *alerts.Alert, resolvedAt *time.Time) *Incident {
+ if s == nil || alert == nil || strings.TrimSpace(alert.ID) == "" {
+ return nil
+ }
+
+ s.mu.Lock()
+ shell := s.findIncidentByAlertAtLocked(alert.ID, alert.StartTime)
+ changed := false
+ if shell == nil {
+ shell = newIncidentShellFromAlert(alert)
+ s.incidents = append(s.incidents, shell)
+ changed = true
+ } else {
+ updateIncidentShellFromAlert(shell, alert)
+ }
+
+ if !hasIncidentEventType(shell.Events, IncidentEventAlertFired) {
+ s.addEventAtLocked(shell, IncidentEventAlertFired, shell.OpenedAt, formatAlertSummary(alert), map[string]interface{}{
+ "type": alert.Type,
+ "level": string(alert.Level),
+ "value": alert.Value,
+ "threshold": alert.Threshold,
+ "projection_source": incidentSnapshotSource,
+ })
+ changed = true
+ }
+
+ if alert.Acknowledged && !hasIncidentEventType(shell.Events, IncidentEventAlertAcknowledged) {
+ ackAt := shell.OpenedAt
+ if alert.AckTime != nil && !alert.AckTime.IsZero() {
+ ackAt = *alert.AckTime
+ }
+ s.addEventAtLocked(shell, IncidentEventAlertAcknowledged, ackAt, "Alert acknowledged", map[string]interface{}{
+ "user": strings.TrimSpace(alert.AckUser),
+ "projection_source": incidentSnapshotSource,
+ })
+ changed = true
+ }
+
+ if resolvedAt != nil && !resolvedAt.IsZero() {
+ shell.OccurrenceClosedAt = cloneTime(*resolvedAt)
+ if !hasIncidentEventType(shell.Events, IncidentEventAlertResolved) {
+ s.addEventAtLocked(shell, IncidentEventAlertResolved, *resolvedAt, "Alert resolved", map[string]interface{}{
+ "resolved_at": resolvedAt.Format(time.RFC3339),
+ "projection_source": incidentSnapshotSource,
+ })
+ changed = true
+ }
+ }
+
+ if changed {
+ s.trimLockedPreserving(shell)
+ s.saveAsync()
+ }
+ s.mu.Unlock()
+
+ return s.GetTimelineByAlertAt(alert.ID, alert.StartTime)
+}
+
// RecordAnalysis adds an AI analysis event to the incident for an alert.
func (s *IncidentStore) RecordAnalysis(alertIdentifier, summary string, details map[string]interface{}) {
if alertIdentifier == "" {
@@ -623,6 +688,30 @@ func (s *IncidentStore) GetTimelineByAlertAt(alertIdentifier string, startedAt t
}
s.mu.RLock()
+ best, bestDelta := s.findClosestIncidentByAlertAtLocked(alertIdentifier, startedAt)
+ best = cloneIncidentShell(best)
+ timelineStore := s.resourceTimelineStore
+ maxAge := s.maxAge
+ s.mu.RUnlock()
+
+ if best == nil || bestDelta > incidentStartMatchTolerance {
+ return s.projectIncidentFromCanonical(alertIdentifier, startedAt, timelineStore, maxAge)
+ }
+ return s.projectIncident(incidentFromShell(best), timelineStore)
+}
+
+func (s *IncidentStore) findIncidentByAlertAtLocked(alertIdentifier string, startedAt time.Time) *incidentShell {
+ if startedAt.IsZero() {
+ return s.findLatestIncidentByAlertIdentifierLocked(alertIdentifier)
+ }
+ best, delta := s.findClosestIncidentByAlertAtLocked(alertIdentifier, startedAt)
+ if best == nil || delta > incidentStartMatchTolerance {
+ return nil
+ }
+ return best
+}
+
+func (s *IncidentStore) findClosestIncidentByAlertAtLocked(alertIdentifier string, startedAt time.Time) (*incidentShell, time.Duration) {
var best *incidentShell
var bestDelta time.Duration
for _, incident := range s.incidents {
@@ -638,14 +727,7 @@ func (s *IncidentStore) GetTimelineByAlertAt(alertIdentifier string, startedAt t
bestDelta = delta
}
}
- timelineStore := s.resourceTimelineStore
- maxAge := s.maxAge
- s.mu.RUnlock()
-
- if best == nil || bestDelta > incidentStartMatchTolerance {
- return s.projectIncidentFromCanonical(alertIdentifier, startedAt, timelineStore, maxAge)
- }
- return s.projectIncident(incidentFromShell(cloneIncidentShell(best)), timelineStore)
+ return best, bestDelta
}
// ListIncidentsByResource returns recent incidents for a resource.
@@ -826,14 +908,16 @@ func (s *IncidentStore) projectIncident(incident *Incident, timelineStore Incide
filtered := make([]IncidentEvent, 0, len(projected.Events)+len(projectedEvents))
for _, event := range projected.Events {
if isCanonicalProjectedIncidentEventType(event.Type) {
- continue
+ if !isSnapshotProjectionEvent(event) || hasIncidentEventType(projectedEvents, event.Type) {
+ continue
+ }
}
filtered = append(filtered, cloneIncidentEvent(event))
}
filtered = append(filtered, projectedEvents...)
sortIncidentEvents(filtered)
projected.Events = filtered
- applyProjectedIncidentState(projected, projectedEvents)
+ applyProjectedIncidentState(projected, filtered)
return projected
}
@@ -1146,15 +1230,39 @@ func isCanonicalProjectedIncidentEventType(eventType IncidentEventType) bool {
}
}
+func isSnapshotProjectionEvent(event IncidentEvent) bool {
+ if event.Details == nil {
+ return false
+ }
+ source, ok := event.Details["projection_source"].(string)
+ return ok && source == incidentSnapshotSource
+}
+
func sortIncidentEvents(events []IncidentEvent) {
sort.Slice(events, func(i, j int) bool {
if events[i].Timestamp.Equal(events[j].Timestamp) {
+ iRank := incidentEventTimestampRank(events[i].Type)
+ jRank := incidentEventTimestampRank(events[j].Type)
+ if iRank != jRank {
+ return iRank < jRank
+ }
return events[i].ID < events[j].ID
}
return events[i].Timestamp.Before(events[j].Timestamp)
})
}
+func incidentEventTimestampRank(eventType IncidentEventType) int {
+ switch eventType {
+ case IncidentEventAlertFired:
+ return 0
+ case IncidentEventAlertResolved:
+ return 2
+ default:
+ return 1
+ }
+}
+
func cloneIncidentEvent(event IncidentEvent) IncidentEvent {
cloned := event
cloned.Details = cloneIncidentEventDetails(event.Details)
@@ -1323,6 +1431,53 @@ func (s *IncidentStore) trimLocked() {
}
}
+// trimLockedPreserving applies the ordinary retention policy while keeping the
+// occurrence currently being read-repaired. This lets a user open an older
+// retained alert-history row even when the bounded incident cache is already
+// full; another least-recent occurrence becomes repairable on demand instead.
+func (s *IncidentStore) trimLockedPreserving(protected *incidentShell) {
+ s.trimLocked()
+ if protected == nil {
+ return
+ }
+ for _, shell := range s.incidents {
+ if shell == protected {
+ return
+ }
+ }
+
+ if s.maxAge > 0 {
+ compareTime := protected.OpenedAt
+ if closedAt := incidentOccurrenceClosedAt(protected); closedAt != nil {
+ compareTime = *closedAt
+ }
+ if compareTime.Before(time.Now().Add(-s.maxAge)) {
+ return
+ }
+ }
+
+ s.incidents = append(s.incidents, protected)
+ if s.maxIncidents <= 0 || len(s.incidents) <= s.maxIncidents {
+ return
+ }
+ sort.Slice(s.incidents, func(i, j int) bool {
+ return s.incidents[i].OpenedAt.Before(s.incidents[j].OpenedAt)
+ })
+ for len(s.incidents) > s.maxIncidents {
+ removeAt := -1
+ for index, shell := range s.incidents {
+ if shell != protected {
+ removeAt = index
+ break
+ }
+ }
+ if removeAt < 0 {
+ break
+ }
+ s.incidents = append(s.incidents[:removeAt], s.incidents[removeAt+1:]...)
+ }
+}
+
func (s *IncidentStore) saveAsync() {
if s.dataDir == "" || s.filePath == "" {
return
diff --git a/internal/ai/memory/incidents_test.go b/internal/ai/memory/incidents_test.go
index 2acf20d137..e271d21337 100644
--- a/internal/ai/memory/incidents_test.go
+++ b/internal/ai/memory/incidents_test.go
@@ -104,6 +104,141 @@ func TestIncidentStore_RecordTimeline(t *testing.T) {
}
}
+func TestIncidentStore_EnsureAlertOccurrenceBuildsSnapshotFallback(t *testing.T) {
+ store := NewIncidentStore(IncidentStoreConfig{
+ MaxIncidents: 10,
+ MaxEventsPerIncident: 10,
+ MaxAgeDays: 30,
+ })
+ // An attached canonical store with no matching history reproduces the
+ // migration gap that previously returned an empty timeline.
+ store.SetResourceTimelineStore(unifiedresources.NewMemoryStore())
+
+ startedAt := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Second)
+ ackAt := startedAt.Add(2 * time.Minute)
+ resolvedAt := startedAt.Add(7 * time.Minute)
+ alert := &alerts.Alert{
+ ID: "legacy-alert-1",
+ Type: "cpu",
+ Level: alerts.AlertLevelWarning,
+ ResourceID: "legacy-resource-1",
+ ResourceName: "Legacy VM",
+ StartTime: startedAt,
+ LastSeen: resolvedAt,
+ Acknowledged: true,
+ AckTime: &ackAt,
+ AckUser: "operator",
+ }
+
+ first := store.EnsureAlertOccurrence(alert, &resolvedAt)
+ second := store.EnsureAlertOccurrence(alert, &resolvedAt)
+ if first == nil || second == nil {
+ t.Fatal("snapshot repair returned no incident")
+ }
+ if second.Status != IncidentStatusResolved || !second.Acknowledged {
+ t.Fatalf("snapshot state = status %q acknowledged %v", second.Status, second.Acknowledged)
+ }
+ if len(second.Events) != 3 {
+ t.Fatalf("snapshot events = %d, want fired, acknowledged, and resolved", len(second.Events))
+ }
+ for index, want := range []IncidentEventType{
+ IncidentEventAlertFired,
+ IncidentEventAlertAcknowledged,
+ IncidentEventAlertResolved,
+ } {
+ if second.Events[index].Type != want {
+ t.Fatalf("event[%d] = %q, want %q", index, second.Events[index].Type, want)
+ }
+ }
+}
+
+func TestIncidentStore_SnapshotFallbackCompletesPartialCanonicalTimeline(t *testing.T) {
+ store := NewIncidentStore(IncidentStoreConfig{MaxIncidents: 10, MaxEventsPerIncident: 10, MaxAgeDays: 30})
+ canonicalStore := unifiedresources.NewMemoryStore()
+ store.SetResourceTimelineStore(canonicalStore)
+
+ startedAt := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Second)
+ alert := &alerts.Alert{
+ ID: "partial-alert-1",
+ Type: "memory",
+ Level: alerts.AlertLevelWarning,
+ ResourceID: "partial-resource-1",
+ ResourceName: "Partial VM",
+ StartTime: startedAt,
+ }
+ store.EnsureAlertOccurrence(alert, nil)
+ ackChange := unifiedresources.BuildAlertTimelineChange(alert.ResourceID, unifiedresources.ChangeAlertAcknowledged, startedAt.Add(time.Minute), "operator", unifiedresources.AlertTimelineChange{
+ AlertIdentifier: alert.ID,
+ AlertType: alert.Type,
+ AlertLevel: string(alert.Level),
+ })
+ if ackChange == nil {
+ t.Fatal("expected acknowledgement change")
+ }
+ if err := canonicalStore.RecordChange(*ackChange); err != nil {
+ t.Fatalf("record canonical acknowledgement: %v", err)
+ }
+
+ timeline := store.GetTimelineByAlertAt(alert.ID, startedAt)
+ if timeline == nil || len(timeline.Events) != 2 {
+ t.Fatalf("partial canonical timeline = %#v, want snapshot fired plus canonical acknowledgement", timeline)
+ }
+ if timeline.Events[0].Type != IncidentEventAlertFired || timeline.Events[1].Type != IncidentEventAlertAcknowledged {
+ t.Fatalf("partial canonical event types = %#v", timeline.Events)
+ }
+}
+
+func TestIncidentStore_EnsureAlertOccurrencePreservesRequestedHistoryBeyondCountCache(t *testing.T) {
+ store := NewIncidentStore(IncidentStoreConfig{MaxIncidents: 1, MaxEventsPerIncident: 10, MaxAgeDays: 30})
+ store.SetResourceTimelineStore(unifiedresources.NewMemoryStore())
+
+ newer := &alerts.Alert{
+ ID: "newer-alert",
+ Type: "cpu",
+ ResourceID: "newer-resource",
+ ResourceName: "Newer VM",
+ StartTime: time.Now().UTC().Add(-time.Hour),
+ }
+ store.EnsureAlertOccurrence(newer, nil)
+
+ olderResolvedAt := time.Now().UTC().Add(-24 * time.Hour)
+ older := &alerts.Alert{
+ ID: "older-alert",
+ Type: "memory",
+ ResourceID: "older-resource",
+ ResourceName: "Older VM",
+ StartTime: olderResolvedAt.Add(-time.Hour),
+ LastSeen: olderResolvedAt,
+ }
+ timeline := store.EnsureAlertOccurrence(older, &olderResolvedAt)
+ if timeline == nil || timeline.AlertIdentifier != older.ID {
+ t.Fatalf("requested history occurrence was evicted during repair: %#v", timeline)
+ }
+ if len(store.incidents) != 1 || store.incidents[0].AlertIdentifier != older.ID {
+ t.Fatalf("bounded cache did not preserve requested occurrence: %#v", store.incidents)
+ }
+}
+
+func TestIncidentStore_EqualTimestampLifecycleKeepsResolvedState(t *testing.T) {
+ store := NewIncidentStore(IncidentStoreConfig{MaxIncidents: 10, MaxEventsPerIncident: 10, MaxAgeDays: 30})
+ startedAt := time.Now().UTC().Truncate(time.Second)
+ alert := &alerts.Alert{
+ ID: "same-time-alert",
+ Type: "connection",
+ ResourceID: "same-time-resource",
+ ResourceName: "Same-time resource",
+ StartTime: startedAt,
+ LastSeen: startedAt,
+ }
+ timeline := store.EnsureAlertOccurrence(alert, &startedAt)
+ if timeline == nil || timeline.Status != IncidentStatusResolved {
+ t.Fatalf("equal-timestamp lifecycle state = %#v, want resolved", timeline)
+ }
+ if len(timeline.Events) != 2 || timeline.Events[0].Type != IncidentEventAlertFired || timeline.Events[1].Type != IncidentEventAlertResolved {
+ t.Fatalf("equal-timestamp event order = %#v", timeline.Events)
+ }
+}
+
func TestIncidentStore_ProjectsCanonicalTimelineWhenAttached(t *testing.T) {
store := NewIncidentStore(IncidentStoreConfig{
MaxIncidents: 10,
diff --git a/internal/ai/memory/memory_coverage_test.go b/internal/ai/memory/memory_coverage_test.go
index 93140f5fd4..2e354e4f88 100644
--- a/internal/ai/memory/memory_coverage_test.go
+++ b/internal/ai/memory/memory_coverage_test.go
@@ -448,22 +448,26 @@ func TestIncidentStore_Timelines_EmptyAndZeroTime(t *testing.T) {
if timeline == nil || timeline.AlertIdentifier != alert.ID {
t.Fatalf("expected timeline for zero start time")
}
- timeline = store.GetTimelineByAlertAt(alert.ID, alert.StartTime.Add(5*time.Minute))
+ timeline = store.GetTimelineByAlertAt(alert.ID, alert.StartTime.Add(500*time.Millisecond))
if timeline == nil || timeline.AlertIdentifier != alert.ID {
- t.Fatalf("expected timeline for later start time")
+ t.Fatalf("expected timeline within timestamp precision tolerance")
+ }
+ if timeline = store.GetTimelineByAlertAt(alert.ID, alert.StartTime.Add(5*time.Minute)); timeline != nil {
+ t.Fatalf("expected no timeline for a distinct nearby occurrence")
}
}
func TestIncidentStore_GetTimelineByAlertAt_SkipsMismatched(t *testing.T) {
+ openedAt := time.Now().Add(-5 * time.Minute)
store := &IncidentStore{
incidents: []*incidentShell{
nil,
{ID: "inc-a", AlertIdentifier: "alert-a", OpenedAt: time.Now().Add(-10 * time.Minute)},
- {ID: "inc-b", AlertIdentifier: "alert-b", OpenedAt: time.Now().Add(-5 * time.Minute)},
+ {ID: "inc-b", AlertIdentifier: "alert-b", OpenedAt: openedAt},
},
}
- timeline := store.GetTimelineByAlertAt("alert-b", time.Now())
+ timeline := store.GetTimelineByAlertAt("alert-b", openedAt)
if timeline == nil || timeline.AlertIdentifier != "alert-b" {
t.Fatalf("expected timeline for alert-b")
}
diff --git a/internal/alerts/event_emission.go b/internal/alerts/event_emission.go
index 2b9238bab0..fceb2eda8d 100644
--- a/internal/alerts/event_emission.go
+++ b/internal/alerts/event_emission.go
@@ -73,9 +73,12 @@ func (m *Manager) AlertEvents(filter eventlog.Filter) ([]eventlog.Event, error)
return store.Query(filter)
}
-// ReplayLifecycleEvents visits every durable lifecycle transition oldest
-// first. It is the projection-repair seam for consumers such as incident and
-// resource timelines: delivery callbacks are deliberately not involved.
+// ReplayLifecycleEvents visits every durable lifecycle transition and migrated
+// history snapshot oldest first. It is the projection-repair seam for
+// consumers such as incident and resource timelines: delivery callbacks are
+// deliberately not involved. Migrated snapshots carry a final occurrence
+// state rather than a transition; consumers must expand only the facts present
+// in that snapshot.
func (m *Manager) ReplayLifecycleEvents(visit func(LifecycleEvent) error) error {
if m == nil || visit == nil {
return nil
@@ -92,6 +95,7 @@ func (m *Manager) ReplayLifecycleEvents(visit func(LifecycleEvent) error) error
eventlog.TypeUnacknowledged,
eventlog.TypeSnoozed,
eventlog.TypeUnsnoozed,
+ eventlog.TypeHistoryImported,
}}, func(event eventlog.Event) error {
if len(event.Snapshot) == 0 {
return nil
diff --git a/internal/api/alerting/alerts.go b/internal/api/alerting/alerts.go
index 2b4aea8c72..e6d1cb79e0 100644
--- a/internal/api/alerting/alerts.go
+++ b/internal/api/alerting/alerts.go
@@ -834,6 +834,11 @@ func (h *AlertHandlers) GetAlertIncidentTimeline(w http.ResponseWriter, r *http.
} else {
incident = store.GetTimelineByAlertIdentifier(alertID)
}
+ if !startedAt.IsZero() && (incident == nil || len(incident.Events) == 0) {
+ if alert, resolvedAt := findAlertOccurrenceForTimeline(h.getMonitor(r.Context()).GetAlertManager(), alertID, startedAt); alert != nil {
+ incident = store.EnsureAlertOccurrence(alert, resolvedAt)
+ }
+ }
if err := utils.WriteJSONResponse(w, exportIncident(incident)); err != nil {
log.Error().Err(err).Msg("Failed to write incident timeline response")
}
@@ -855,6 +860,51 @@ func (h *AlertHandlers) GetAlertIncidentTimeline(w http.ResponseWriter, r *http.
http.Error(w, "Missing alertIdentifier or resource_id", http.StatusBadRequest)
}
+func findAlertOccurrenceForTimeline(manager AlertManager, alertID string, startedAt time.Time) (*alerts.Alert, *time.Time) {
+ if manager == nil || strings.TrimSpace(alertID) == "" {
+ return nil, nil
+ }
+
+ for _, active := range manager.GetActiveAlerts() {
+ if alertOccurrenceMatches(&active, alertID, startedAt) {
+ return active.Clone(), nil
+ }
+ }
+
+ for _, historical := range manager.GetAlertHistory(0) {
+ if !alertOccurrenceMatches(&historical, alertID, startedAt) {
+ continue
+ }
+ resolvedAt := historical.LastSeen
+ if historical.OperationalRecord != nil && historical.OperationalRecord.ResolvedAt != nil && !historical.OperationalRecord.ResolvedAt.IsZero() {
+ resolvedAt = *historical.OperationalRecord.ResolvedAt
+ }
+ if resolvedAt.IsZero() {
+ return historical.Clone(), nil
+ }
+ if !historical.StartTime.IsZero() && resolvedAt.Before(historical.StartTime) {
+ resolvedAt = historical.StartTime
+ }
+ return historical.Clone(), &resolvedAt
+ }
+
+ return nil, nil
+}
+
+func alertOccurrenceMatches(alert *alerts.Alert, alertID string, startedAt time.Time) bool {
+ if alert == nil || strings.TrimSpace(alert.ID) != strings.TrimSpace(alertID) {
+ return false
+ }
+ if startedAt.IsZero() || alert.StartTime.IsZero() {
+ return true
+ }
+ delta := alert.StartTime.Sub(startedAt)
+ if delta < 0 {
+ delta = -delta
+ }
+ return delta <= time.Second
+}
+
// SaveAlertIncidentNote stores a user note in the incident timeline.
func (h *AlertHandlers) SaveAlertIncidentNote(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
diff --git a/internal/api/alerting/alerts_test.go b/internal/api/alerting/alerts_test.go
index 9c609061d2..3054bbee6d 100644
--- a/internal/api/alerting/alerts_test.go
+++ b/internal/api/alerting/alerts_test.go
@@ -669,6 +669,73 @@ func TestGetAlertIncidentTimeline_AcceptsCamelCaseAlertIdentifierQuery(t *testin
assert.Equal(t, "canonical:a1", incident["alertIdentifier"])
}
+func TestGetAlertIncidentTimeline_RepairsActiveAlertWithoutIncidentShell(t *testing.T) {
+ mockMonitor := new(MockAlertMonitor)
+ mockManager := new(MockAlertManager)
+ incidentStore := memory.NewIncidentStore(memory.IncidentStoreConfig{})
+ incidentStore.SetResourceTimelineStore(unifiedresources.NewMemoryStore())
+ startedAt := time.Now().UTC().Add(-5 * time.Minute).Truncate(time.Second)
+ alert := alerts.Alert{
+ ID: "active-without-timeline",
+ Type: "cpu",
+ Level: alerts.AlertLevelWarning,
+ ResourceID: "resource-active",
+ ResourceName: "Active VM",
+ StartTime: startedAt,
+ LastSeen: startedAt.Add(4 * time.Minute),
+ }
+ mockMonitor.On("GetIncidentStore").Return(incidentStore)
+ mockMonitor.On("GetAlertManager").Return(mockManager)
+ mockManager.On("GetActiveAlerts").Return([]alerts.Alert{alert})
+ h := NewAlertHandlers(nil, mockMonitor, nil)
+
+ req := httptest.NewRequest("GET", "/api/alerts/incidents?alertIdentifier=active-without-timeline&started_at="+startedAt.Format(time.RFC3339), nil)
+ w := httptest.NewRecorder()
+ h.GetAlertIncidentTimeline(w, req)
+
+ assert.Equal(t, http.StatusOK, w.Code)
+ var incident incidentView
+ assert.NoError(t, json.NewDecoder(w.Body).Decode(&incident))
+ assert.Equal(t, memory.IncidentStatusOpen, incident.Status)
+ assert.Len(t, incident.Events, 1)
+ assert.Equal(t, memory.IncidentEventAlertFired, incident.Events[0].Type)
+}
+
+func TestGetAlertIncidentTimeline_RepairsResolvedHistoryOccurrence(t *testing.T) {
+ mockMonitor := new(MockAlertMonitor)
+ mockManager := new(MockAlertManager)
+ incidentStore := memory.NewIncidentStore(memory.IncidentStoreConfig{})
+ incidentStore.SetResourceTimelineStore(unifiedresources.NewMemoryStore())
+ startedAt := time.Now().UTC().Add(-20 * time.Minute).Truncate(time.Second)
+ resolvedAt := startedAt.Add(10 * time.Minute)
+ alert := alerts.Alert{
+ ID: "history-without-timeline",
+ Type: "memory",
+ Level: alerts.AlertLevelCritical,
+ ResourceID: "resource-history",
+ ResourceName: "Historical VM",
+ StartTime: startedAt,
+ LastSeen: resolvedAt,
+ }
+ mockMonitor.On("GetIncidentStore").Return(incidentStore)
+ mockMonitor.On("GetAlertManager").Return(mockManager)
+ mockManager.On("GetActiveAlerts").Return([]alerts.Alert{})
+ mockManager.On("GetAlertHistory", 0).Return([]alerts.Alert{alert})
+ h := NewAlertHandlers(nil, mockMonitor, nil)
+
+ req := httptest.NewRequest("GET", "/api/alerts/incidents?alertIdentifier=history-without-timeline&started_at="+startedAt.Format(time.RFC3339), nil)
+ w := httptest.NewRecorder()
+ h.GetAlertIncidentTimeline(w, req)
+
+ assert.Equal(t, http.StatusOK, w.Code)
+ var incident incidentView
+ assert.NoError(t, json.NewDecoder(w.Body).Decode(&incident))
+ assert.Equal(t, memory.IncidentStatusResolved, incident.Status)
+ assert.Len(t, incident.Events, 2)
+ assert.Equal(t, memory.IncidentEventAlertFired, incident.Events[0].Type)
+ assert.Equal(t, memory.IncidentEventAlertResolved, incident.Events[1].Type)
+}
+
func TestGetAlertIncidentTimeline_ListExportsCanonicalAlertIdentifier(t *testing.T) {
mockMonitor := new(MockAlertMonitor)
mockStore := memory.NewIncidentStore(memory.IncidentStoreConfig{})
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index bd335410af..b5f06d4f18 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -4531,13 +4531,22 @@ func (m *Monitor) SetResourceStore(store ResourceStoreInterface) {
m.installOperatorIntentResolver(store)
log.Info().Msg("resource store set for polling optimization")
+ timelineAttached := false
if incidentStore != nil {
if timelineStore, ok := store.(memory.IncidentTimelineStore); ok {
incidentStore.SetResourceTimelineStore(timelineStore)
+ timelineAttached = true
} else {
incidentStore.SetResourceTimelineStore(nil)
}
}
+ if timelineAttached {
+ // NewMonitor replays before the API-owned durable resource store is
+ // attached. Replay again at the canonical boundary so restart repair
+ // reaches resource history as well as the incident fallback cache.
+ m.replayAlertLifecycleProjections()
+ m.reconcileActiveAlertTimelines()
+ }
// Immediately backfill the store from current state so ReadState
// consumers have data as soon as the store is wired.
diff --git a/internal/monitoring/monitor_alert_handling_test.go b/internal/monitoring/monitor_alert_handling_test.go
index b7ed5de654..d28046c492 100644
--- a/internal/monitoring/monitor_alert_handling_test.go
+++ b/internal/monitoring/monitor_alert_handling_test.go
@@ -301,6 +301,67 @@ func TestLifecycleReplayRepairsResolvedIncidentTimeline(t *testing.T) {
}
}
+func TestLifecycleReplayMaterializesImportedHistoryTimeline(t *testing.T) {
+ manager := alerts.NewManagerWithDataDir(t.TempDir(), alerts.WithoutPersistedAlertRestore())
+ t.Cleanup(manager.Stop)
+ store, err := eventlog.Open(t.TempDir())
+ if err != nil {
+ t.Fatalf("open event log: %v", err)
+ }
+ manager.SetEventLog(store)
+
+ startedAt := time.Now().UTC().Add(-30 * time.Minute).Truncate(time.Second)
+ ackAt := startedAt.Add(5 * time.Minute)
+ resolvedAt := startedAt.Add(20 * time.Minute)
+ snapshot := alerts.Alert{
+ ID: "imported-alert-1",
+ Type: "cpu",
+ Level: alerts.AlertLevelWarning,
+ ResourceID: "imported-resource-1",
+ ResourceName: "Imported VM",
+ StartTime: startedAt,
+ LastSeen: resolvedAt,
+ Acknowledged: true,
+ AckTime: &ackAt,
+ AckUser: "operator",
+ }
+ payload, err := json.Marshal(snapshot)
+ if err != nil {
+ t.Fatalf("marshal imported snapshot: %v", err)
+ }
+ if err := store.ImportEvents([]eventlog.Event{{
+ OccurredAt: resolvedAt,
+ Type: eventlog.TypeHistoryImported,
+ AlertID: snapshot.ID,
+ ResourceID: snapshot.ResourceID,
+ Snapshot: payload,
+ }}); err != nil {
+ t.Fatalf("import history event: %v", err)
+ }
+
+ incidentStore := memory.NewIncidentStore(memory.IncidentStoreConfig{})
+ monitor := &Monitor{alertManager: manager, incidentStore: incidentStore}
+ resourceStore := unifiedresources.NewMemoryStore()
+ adapter := unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(resourceStore))
+ monitor.SetResourceStore(adapter)
+ monitor.SetResourceStore(adapter)
+
+ timeline := incidentStore.GetTimelineByAlertAt(snapshot.ID, snapshot.StartTime)
+ if timeline == nil || timeline.Status != memory.IncidentStatusResolved || !timeline.Acknowledged {
+ t.Fatalf("imported timeline state = %#v", timeline)
+ }
+ if len(timeline.Events) != 3 {
+ t.Fatalf("imported timeline events = %d, want three idempotent snapshot events", len(timeline.Events))
+ }
+ changes, err := resourceStore.GetRecentChanges(snapshot.ResourceID, time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("read imported canonical changes: %v", err)
+ }
+ if len(changes) != 3 {
+ t.Fatalf("imported canonical changes = %d, want fired, acknowledged, and resolved", len(changes))
+ }
+}
+
func TestSystemAlertTimelineUsesCanonicalPulseResource(t *testing.T) {
resourceStore := unifiedresources.NewMemoryStore()
incidentStore := memory.NewIncidentStore(memory.IncidentStoreConfig{})
diff --git a/internal/monitoring/monitor_alerts.go b/internal/monitoring/monitor_alerts.go
index 2000eea3e1..ecda885caf 100644
--- a/internal/monitoring/monitor_alerts.go
+++ b/internal/monitoring/monitor_alerts.go
@@ -370,9 +370,68 @@ func (m *Monitor) handleAlertLifecycleEvent(event alerts.LifecycleEvent) {
m.incidentStore.RecordAlertResolved(timelineAlert, event.OccurredAt)
}
m.recordAlertTimelineChange(timelineAlert, unifiedresources.ChangeAlertResolved, event.OccurredAt, "")
+ case eventlog.TypeHistoryImported:
+ m.materializeImportedAlertTimeline(timelineAlert, event.OccurredAt)
}
}
+func (m *Monitor) materializeImportedAlertTimeline(alert *alerts.Alert, importedAt time.Time) {
+ if m == nil || alert == nil || m.incidentStore == nil {
+ return
+ }
+
+ var resolvedAt *time.Time
+ if !m.isActiveAlertOccurrence(alert) {
+ endedAt := importedAt
+ if alert.OperationalRecord != nil && alert.OperationalRecord.ResolvedAt != nil && !alert.OperationalRecord.ResolvedAt.IsZero() {
+ endedAt = *alert.OperationalRecord.ResolvedAt
+ } else if alert.LastSeen.After(endedAt) {
+ endedAt = alert.LastSeen
+ }
+ if endedAt.IsZero() {
+ endedAt = alert.LastSeen
+ }
+ if !endedAt.IsZero() {
+ if !alert.StartTime.IsZero() && endedAt.Before(alert.StartTime) {
+ endedAt = alert.StartTime
+ }
+ resolvedAt = &endedAt
+ }
+ }
+
+ m.incidentStore.EnsureAlertOccurrence(alert, resolvedAt)
+ firedAt := alert.StartTime
+ if firedAt.IsZero() {
+ firedAt = importedAt
+ }
+ m.recordAlertTimelineChange(alert, unifiedresources.ChangeAlertFired, firedAt, "")
+ if alert.Acknowledged {
+ ackAt := alert.AckTime
+ if ackAt == nil || ackAt.IsZero() {
+ ackAt = &firedAt
+ }
+ m.recordAlertTimelineChange(alert, unifiedresources.ChangeAlertAcknowledged, *ackAt, alert.AckUser)
+ }
+ if resolvedAt != nil {
+ m.recordAlertTimelineChange(alert, unifiedresources.ChangeAlertResolved, *resolvedAt, "")
+ }
+}
+
+func (m *Monitor) isActiveAlertOccurrence(candidate *alerts.Alert) bool {
+ if m == nil || m.alertManager == nil || candidate == nil {
+ return false
+ }
+ for _, active := range m.alertManager.GetActiveAlerts() {
+ if active.ID != candidate.ID {
+ continue
+ }
+ if candidate.StartTime.IsZero() || active.StartTime.IsZero() || active.StartTime.Equal(candidate.StartTime) {
+ return true
+ }
+ }
+ return false
+}
+
func (m *Monitor) replayAlertLifecycleProjections() {
if m == nil || m.alertManager == nil {
return