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 mock alert history lifecycle-consistent

Pulse Testff6c6a7fe7a1
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 6525d9fabd..c0c2d693e1 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -624,6 +624,10 @@ update, profile rollout, command reachability, or fleet-control authority.
can carry it forward across a failed storage query; that accessor is
likewise monitoring-internal and never becomes an agent- or API-facing
surface.
+ The optional `models.Alert.LastSeen` field is likewise monitoring-owned
+ lifecycle presentation evidence. It keeps mock active-alert and history
+ payloads aligned with the canonical alert contract, but it cannot enroll,
+ identify, link, command, remove, or otherwise grant authority to an agent.
27. `internal/monitoring/monitor.go` shared with `monitoring`: monitor construction owns both monitoring runtime initialization and fail-closed agent lifecycle journal hydration before report admission.
28. `internal/monitoring/monitor_agents.go` shared with `monitoring`: server-side Unified Agent report, removal, token binding, tombstone expiry, and re-enrollment semantics are jointly owned by agent lifecycle authority and monitoring ingest.
29. `pkg/agents/host/report.go` shared with `monitoring`: the Unified Agent host report is both an agent lifecycle authored-state contract and a monitoring ingest contract for host maintenance posture.
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 817ba30330..f9fe1571f1 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -516,6 +516,7 @@ cleanup so readers cannot retain orphaned runtime or alert projections.
35c. `internal/mock/recovery_points.go`
35d. `internal/mock/integration.go`
35e. `internal/mock/alert_incidents.go`
+35f. `internal/mock/alert_history.go`
36. `internal/dockeragent/docker_client.go`
37. `pkg/agents/docker/report.go`
38. `internal/models/models.go`
@@ -1941,6 +1942,12 @@ representative investigation and runbook events exercise the richer timeline
surface. Alert-level reads, resource-level incident lists, and graph-lifetime
notes must all query or mutate that same fixture instance; a mock history row
must never expose a Timeline control backed by a missing incident.
+`internal/mock/alert_history.go` is the canonical history fixture generator and
+must mirror the live history read contract: rows are newest-first, closed rows
+carry the same resolution timestamp as their incident in `lastSeen`, and live
+alerts come from the active-alert snapshot rather than unrelated synthetic open
+history rows. History duration, status, and Timeline therefore remain three
+projections of one occurrence instead of contradicting each other in demo mode.
Mock fixture defaults in `internal/mock/generator.go` (the `DefaultConfig`
constant) are also part of that mock-runtime contract. The Proxmox default is
an intentionally large public-demo estate so platform-first pages exercise
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 5a6439feff..bdc9dc6a39 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -201,6 +201,12 @@ start a goroutine, timer, or notification lifecycle per target.
21. `internal/mock/fixture_graph.go` shared with `monitoring`: the canonical mock fixture graph is both monitoring-owned runtime data and a protected large-estate demo transport hot path.
22. `internal/mock/generator.go` shared with `monitoring`: mock metric generation is both monitoring-owned runtime data and a protected large-estate demo update hot path.
23. `internal/mock/integration.go` shared with `monitoring`: the mock runtime scheduler is both monitoring-owned sampling infrastructure and a protected large-estate demo cadence boundary.
+ Alert-history lifecycle enrichment remains graph-build work, not sampler-tick
+ work. History access must apply its requested limit before cloning rows, and
+ cloning optional lifecycle timestamps must stay linear in the returned
+ slice rather than rebuilding or walking the full mock estate. This keeps
+ history/timeline consistency from adding cost to the protected realtime
+ update path.
Large-estate realtime updates must be sparse end to end. The public 50-node,
900-guest demo advances node-scoped metrics through ten bounded cohorts on the
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 2175367a9d..ad48344bb7 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -5555,6 +5555,7 @@
"internal/dockeragent/swarm.go",
"internal/kubernetesagent/agent.go",
"internal/mock/action_fixtures.go",
+ "internal/mock/alert_history.go",
"internal/mock/alert_incidents.go",
"internal/mock/availability_fixtures.go",
"internal/mock/demo_scenarios.go",
@@ -5943,6 +5944,7 @@
"match_prefixes": [],
"match_files": [
"internal/mock/action_fixtures.go",
+ "internal/mock/alert_history.go",
"internal/mock/alert_incidents.go",
"internal/mock/availability_fixtures.go",
"internal/mock/demo_scenarios.go",
diff --git a/internal/api/alerting/alerts_test.go b/internal/api/alerting/alerts_test.go
index 5d3c6d96f1..856859d2e3 100644
--- a/internal/api/alerting/alerts_test.go
+++ b/internal/api/alerting/alerts_test.go
@@ -782,6 +782,9 @@ func TestMockAlertIncidentTimelineSupportsAlertResourceAndNoteWorkflows(t *testi
t.Fatalf("mock alert history returned %d rows, want 1", len(history))
}
alert := history[0]
+ if alert.LastSeen == nil {
+ t.Fatalf("mock history row %q has no resolution timestamp", alert.ID)
+ }
mockMonitor := new(MockAlertMonitor)
h := NewAlertHandlers(nil, mockMonitor, nil)
@@ -795,6 +798,9 @@ func TestMockAlertIncidentTimelineSupportsAlertResourceAndNoteWorkflows(t *testi
assert.NoError(t, json.NewDecoder(w.Body).Decode(&timeline))
assert.Equal(t, alert.ID, timeline.AlertIdentifier)
assert.NotEmpty(t, timeline.Events)
+ if timeline.Status != memory.IncidentStatusResolved || timeline.ClosedAt == nil || !timeline.ClosedAt.Equal(*alert.LastSeen) {
+ t.Fatalf("mock timeline status = %q, closedAt = %v, history lastSeen = %v", timeline.Status, timeline.ClosedAt, alert.LastSeen)
+ }
resourceURL := "/api/alerts/incidents?resource_id=" + url.QueryEscape(alert.ResourceID) + "&limit=5"
w = httptest.NewRecorder()
diff --git a/internal/mock/alert_history.go b/internal/mock/alert_history.go
index c19fa39715..1303b0142e 100644
--- a/internal/mock/alert_history.go
+++ b/internal/mock/alert_history.go
@@ -3,6 +3,7 @@ package mock
import (
"fmt"
"math/rand"
+ "sort"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
@@ -153,50 +154,13 @@ func buildAlertHistory(nodes []models.Node, vms []models.VM, containers []models
}
}
- // Add some recent unresolved alerts (last 2 hours)
- for i := 0; i < 3; i++ {
- alertType := alertTypes[rand.Intn(len(alertTypes))]
-
- var resourceName, resourceID, node string
- if len(nodes) > 0 {
- selectedNode := nodes[rand.Intn(len(nodes))]
- resourceName = selectedNode.Name
- resourceID = selectedNode.ID
- node = selectedNode.Name
- }
-
- startTime := now.Add(-time.Duration(rand.Intn(120)) * time.Minute)
-
- msg := alertType.messages[rand.Intn(len(alertType.messages))]
- if alertType.alertType == "threshold" {
- value := rand.Intn(30) + 70
- msg = fmt.Sprintf(msg, value)
- }
-
- alert := models.Alert{
- ID: fmt.Sprintf("active-%d-%d", i, rand.Intn(10000)),
- Type: alertType.alertType,
- Level: alertType.level,
- ResourceID: resourceID,
- ResourceName: resourceName,
- Node: node,
- Message: msg,
- StartTime: startTime,
- Acknowledged: false,
- }
- if resourceName != "" {
- alert.Metadata = map[string]interface{}{"resourceType": "node"}
- }
-
- if alertType.alertType == "threshold" {
- value := float64(rand.Intn(30) + 70)
- threshold := float64(rand.Intn(20) + 60)
- alert.Value = value
- alert.Threshold = threshold
- }
-
- history = append(history, alert)
- }
+ // The live history endpoint is newest-first. Active alerts are supplied by
+ // the live alert snapshot and merged by the UI, so this fixture contains
+ // only closed occurrences; inventing unrelated open rows makes their
+ // history status contradict the active-alert source of truth.
+ sort.SliceStable(history, func(i, j int) bool {
+ return history[i].StartTime.After(history[j].StartTime)
+ })
return history
}
diff --git a/internal/mock/alert_incidents.go b/internal/mock/alert_incidents.go
index 693584c8c9..a7de7f365d 100644
--- a/internal/mock/alert_incidents.go
+++ b/internal/mock/alert_incidents.go
@@ -18,7 +18,7 @@ const mockIncidentStartTolerance = time.Second
// mode exercises acknowledgement, investigation, remediation, and resolution
// rather than presenting timeline controls backed by no data.
func buildAlertIncidentFixtures(history []models.Alert, now time.Time) ([]models.Alert, []*memory.Incident) {
- enriched := append([]models.Alert(nil), history...)
+ enriched := cloneMockAlerts(history)
incidents := make([]*memory.Incident, 0, len(enriched))
for index := range enriched {
alert := &enriched[index]
@@ -49,6 +49,11 @@ func buildAlertIncidentFixtures(history []models.Alert, now time.Time) ([]models
alert.AckTime = cloneMockTime(ackAt)
alert.AckUser = "demo-operator"
}
+ if active {
+ alert.LastSeen = cloneMockTime(now)
+ } else {
+ alert.LastSeen = cloneMockTime(resolvedAt)
+ }
incident := &memory.Incident{
ID: "mock-incident-" + alert.ID,
@@ -204,6 +209,22 @@ func cloneMockIncidents(incidents []*memory.Incident) []*memory.Incident {
return cloned
}
+func cloneMockAlerts(alerts []models.Alert) []models.Alert {
+ cloned := make([]models.Alert, len(alerts))
+ for index, alert := range alerts {
+ cloned[index] = alert
+ cloned[index].LastSeen = cloneMockTimePtr(alert.LastSeen)
+ cloned[index].AckTime = cloneMockTimePtr(alert.AckTime)
+ if alert.Metadata != nil {
+ cloned[index].Metadata = make(map[string]interface{}, len(alert.Metadata))
+ for key, value := range alert.Metadata {
+ cloned[index].Metadata[key] = value
+ }
+ }
+ }
+ return cloned
+}
+
func cloneMockTime(value time.Time) *time.Time {
if value.IsZero() {
return nil
diff --git a/internal/mock/alert_incidents_test.go b/internal/mock/alert_incidents_test.go
index 2c1e7bbaca..1e718088e0 100644
--- a/internal/mock/alert_incidents_test.go
+++ b/internal/mock/alert_incidents_test.go
@@ -51,11 +51,17 @@ func TestBuildAlertIncidentFixturesCreatesCompleteLifecycleData(t *testing.T) {
if resolved.ResourceType != "vm" {
t.Fatalf("resource type = %q, want vm", resolved.ResourceType)
}
+ if enriched[0].LastSeen == nil || resolved.ClosedAt == nil || !enriched[0].LastSeen.Equal(*resolved.ClosedAt) {
+ t.Fatalf("historical row lastSeen = %v, closedAt = %v; want one resolution time", enriched[0].LastSeen, resolved.ClosedAt)
+ }
active := incidents[1]
if active.Status != memory.IncidentStatusOpen || active.ClosedAt != nil {
t.Fatalf("active incident status = %q, closedAt = %v; want open lifecycle", active.Status, active.ClosedAt)
}
+ if enriched[1].LastSeen == nil || !enriched[1].LastSeen.Equal(now) {
+ t.Fatalf("active row lastSeen = %v, want fixture observation time %v", enriched[1].LastSeen, now)
+ }
for _, event := range active.Events {
if event.Timestamp.After(now) {
t.Fatalf("active incident event %q is in the future: %s", event.Type, event.Timestamp)
diff --git a/internal/mock/fixture_graph.go b/internal/mock/fixture_graph.go
index bf3a8f84eb..087d64ff94 100644
--- a/internal/mock/fixture_graph.go
+++ b/internal/mock/fixture_graph.go
@@ -50,7 +50,7 @@ func buildFixtureGraph(cfg MockConfig, now time.Time) FixtureGraph {
func cloneFixtureGraph(in FixtureGraph) FixtureGraph {
return FixtureGraph{
State: cloneState(in.State),
- AlertHistory: append([]models.Alert(nil), in.AlertHistory...),
+ AlertHistory: cloneMockAlerts(in.AlertHistory),
AlertIncidents: cloneMockIncidents(in.AlertIncidents),
PlatformFixtures: clonePlatformFixtures(in.PlatformFixtures),
AvailabilityFixtures: cloneAvailabilityFixtures(in.AvailabilityFixtures),
@@ -141,6 +141,7 @@ func (g *FixtureGraph) UpdateAlertSnapshots(active []alerts.Alert, resolved []mo
Value: alert.Value,
Threshold: alert.Threshold,
StartTime: alert.StartTime,
+ LastSeen: cloneMockTime(alert.LastSeen),
Acknowledged: alert.Acknowledged,
// GetActiveAlerts returns deep clones, so the map is already private.
Metadata: alert.Metadata,
diff --git a/internal/mock/integration.go b/internal/mock/integration.go
index 2103ec3f46..e8fd097c65 100644
--- a/internal/mock/integration.go
+++ b/internal/mock/integration.go
@@ -558,9 +558,9 @@ func GetMockAlertHistory(limit int) []models.Alert {
defer dataMu.RUnlock()
if limit > 0 && limit < len(mockGraph.AlertHistory) {
- return append([]models.Alert(nil), mockGraph.AlertHistory[:limit]...)
+ return cloneMockAlerts(mockGraph.AlertHistory[:limit])
}
- return append([]models.Alert(nil), mockGraph.AlertHistory...)
+ return cloneMockAlerts(mockGraph.AlertHistory)
}
// GetMockAlertIncidentTimeline returns the occurrence-qualified incident
diff --git a/internal/mock/integration_coverage_test.go b/internal/mock/integration_coverage_test.go
index dd7ec0a58b..e810f59316 100644
--- a/internal/mock/integration_coverage_test.go
+++ b/internal/mock/integration_coverage_test.go
@@ -2,6 +2,7 @@ package mock
import (
"os"
+ "strings"
"testing"
"time"
@@ -446,6 +447,7 @@ func TestUpdateAlertSnapshotsAndHistoryAccessors(t *testing.T) {
resetMockIntegrationState(t)
start := time.Now().Add(-2 * time.Minute).Truncate(time.Second)
+ activeLastSeen := start.Add(time.Minute)
resolvedTime := time.Now().Add(-1 * time.Minute).Truncate(time.Second)
active := []alerts.Alert{
{
@@ -460,6 +462,7 @@ func TestUpdateAlertSnapshotsAndHistoryAccessors(t *testing.T) {
Value: 97,
Threshold: 90,
StartTime: start,
+ LastSeen: activeLastSeen,
Acknowledged: true,
},
}
@@ -486,6 +489,10 @@ func TestUpdateAlertSnapshotsAndHistoryAccessors(t *testing.T) {
dataMu.RUnlock()
t.Fatalf("unexpected converted active alert snapshot: %+v", snapshot)
}
+ if snapshot.LastSeen == nil || !snapshot.LastSeen.Equal(activeLastSeen) {
+ dataMu.RUnlock()
+ t.Fatalf("active alert lastSeen = %v, want %v", snapshot.LastSeen, activeLastSeen)
+ }
if len(mockGraph.State.RecentlyResolved) != 1 || mockGraph.State.RecentlyResolved[0].ID != "r-1" {
dataMu.RUnlock()
t.Fatalf("unexpected resolved snapshot data: %+v", mockGraph.State.RecentlyResolved)
@@ -507,7 +514,8 @@ func TestUpdateAlertSnapshotsAndHistoryAccessors(t *testing.T) {
dataMu.RUnlock()
dataMu.Lock()
- mockGraph.AlertHistory = []models.Alert{{ID: "h-1"}, {ID: "h-2"}, {ID: "h-3"}}
+ lastSeen := time.Date(2026, time.August, 27, 12, 0, 0, 0, time.UTC)
+ mockGraph.AlertHistory = []models.Alert{{ID: "h-1", LastSeen: &lastSeen}, {ID: "h-2"}, {ID: "h-3"}}
dataMu.Unlock()
enabled.Store(false)
@@ -524,10 +532,47 @@ func TestUpdateAlertSnapshotsAndHistoryAccessors(t *testing.T) {
t.Fatalf("expected full history result, got %d", len(all))
}
all[0].ID = "changed"
+ *all[0].LastSeen = all[0].LastSeen.Add(time.Hour)
dataMu.RLock()
defer dataMu.RUnlock()
if mockGraph.AlertHistory[0].ID != "h-1" {
t.Fatalf("expected history accessor to return defensive copies")
}
+ if !mockGraph.AlertHistory[0].LastSeen.Equal(lastSeen) {
+ t.Fatalf("history accessor exposed lastSeen pointer: %v", mockGraph.AlertHistory[0].LastSeen)
+ }
+}
+
+func TestMockAlertHistoryMatchesProductionLifecycleContract(t *testing.T) {
+ history := buildAlertHistory(
+ []models.Node{{ID: "node-1", Name: "pve-1"}},
+ []models.VM{{ID: "vm-1", Name: "database", Node: "pve-1"}},
+ []models.Container{{ID: "ct-1", Name: "worker", Node: "pve-1"}},
+ )
+ if len(history) == 0 {
+ t.Fatal("mock history is empty")
+ }
+ for index, alert := range history {
+ if strings.HasPrefix(alert.ID, "active-") {
+ t.Fatalf("mock history contains synthetic open row %q", alert.ID)
+ }
+ if index > 0 && alert.StartTime.After(history[index-1].StartTime) {
+ t.Fatalf("mock history is not newest-first at %d: %v after %v", index, alert.StartTime, history[index-1].StartTime)
+ }
+ }
+
+ now := time.Now()
+ enriched, incidents := buildAlertIncidentFixtures(history, now)
+ if len(enriched) != len(incidents) {
+ t.Fatalf("enriched history rows = %d, incidents = %d", len(enriched), len(incidents))
+ }
+ for index, incident := range incidents {
+ if incident.Status != "resolved" || incident.ClosedAt == nil {
+ t.Fatalf("history incident %q status = %q, closedAt = %v", incident.ID, incident.Status, incident.ClosedAt)
+ }
+ if enriched[index].LastSeen == nil || !enriched[index].LastSeen.Equal(*incident.ClosedAt) {
+ t.Fatalf("history row %q lastSeen = %v, closedAt = %v", enriched[index].ID, enriched[index].LastSeen, incident.ClosedAt)
+ }
+ }
}
diff --git a/internal/models/metrics_types_test.go b/internal/models/metrics_types_test.go
index c098fe8ecd..a57670dc90 100644
--- a/internal/models/metrics_types_test.go
+++ b/internal/models/metrics_types_test.go
@@ -19,6 +19,25 @@ func TestMetricPoint_ZeroValue(t *testing.T) {
}
}
+func TestAlertLastSeenWireContract(t *testing.T) {
+ withoutLastSeen, err := json.Marshal(Alert{ID: "alert-1"})
+ if err != nil {
+ t.Fatalf("marshal alert without lastSeen: %v", err)
+ }
+ if strings.Contains(string(withoutLastSeen), "lastSeen") {
+ t.Fatalf("payload = %s, absent lastSeen must be omitted", withoutLastSeen)
+ }
+
+ resolvedAt := time.Date(2026, time.August, 27, 12, 15, 0, 0, time.UTC)
+ withLastSeen, err := json.Marshal(Alert{ID: "alert-1", LastSeen: &resolvedAt})
+ if err != nil {
+ t.Fatalf("marshal alert with lastSeen: %v", err)
+ }
+ if !strings.Contains(string(withLastSeen), `"lastSeen":"2026-08-27T12:15:00Z"`) {
+ t.Fatalf("payload = %s, want canonical RFC3339 lastSeen", withLastSeen)
+ }
+}
+
func TestNodeNetworkInterfacesNormalizeCollections(t *testing.T) {
node := Node{NetworkInterfaces: []HostNetworkInterface{{Name: "vmbr0"}}}.NormalizeCollections()
if node.NetworkInterfaces == nil || node.NetworkInterfaces[0].Addresses == nil {
diff --git a/internal/models/models.go b/internal/models/models.go
index a7f94be6a7..d515b4f2c3 100644
--- a/internal/models/models.go
+++ b/internal/models/models.go
@@ -102,6 +102,7 @@ type Alert struct {
Value float64 `json:"value"`
Threshold float64 `json:"threshold"`
StartTime time.Time `json:"startTime"`
+ LastSeen *time.Time `json:"lastSeen,omitempty"`
Acknowledged bool `json:"acknowledged"`
AckTime *time.Time `json:"ackTime,omitempty"`
AckUser string `json:"ackUser,omitempty"`