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.

fix(monitoring): make Unraid task state freshness-safe

rcourtmanb8ea840f11c7
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 98585e6113..53a5908087 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -348,6 +348,15 @@ update, profile rollout, command reachability, or fleet-control authority.
22. `internal/api/unified_agent.go` shared with `api-contracts`: unified agent download and installer handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.
23. `internal/kubernetesagent/agent.go` shared with `monitoring`: the Kubernetes native agent runtime is both a monitoring inventory source and an agent lifecycle Pulse control-plane transport client.
24. `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.
+ Every current agent process authors a process-unique report stream and a
+ monotonic sequence within that stream. Reconnect delivery must preserve
+ collection order by draining each destination's persisted FIFO before
+ sending a newly collected report, so buffered running-task snapshots cannot
+ overwrite a later cancellation or completion. Authentication/scope
+ rejection may discard an undeliverable FIFO; transient transport failures
+ retain it. Unraid collection treats positive `mdResyncPos` / `mdResync` as
+ authoritative active-operation evidence and emits zero progress whenever
+ no active sync action exists, even if terminal percentage fields linger.
25. `scripts/install.ps1` shared with `deployment-installability`: the Windows installer is both a deployment installability entry point and a canonical agent lifecycle runtime continuity boundary.
The Windows installer must support a non-mutating download preflight that
can run before Administrator-only install work, must accept token-file
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index f1cbeb1c6c..0c3cd36979 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -540,6 +540,17 @@ health handling, host cleanup, and host offline lifecycle handling; future host
agent alert behavior should extend that resource checker owner while shared
health-assessment evaluation remains package-level until all storage-health
callers can be separated behind a narrower owner.
+Host long-running storage-operation alerts require fresh operation evidence.
+An accepted Unraid cancellation/completion or terminal Linux RAID report
+resolves the corresponding operation alert immediately. A normal polling gap
+does not imply completion; after the monitoring-owned reporting lease expires,
+alerts must re-evaluate with only transient operation/progress fields cleared,
+retain alerts backed by static degraded/topology evidence when that last-known
+topology remains available, and progress the separate confirmed
+host-connectivity alert. Persisted operation alerts also obey the durable
+accepted-telemetry lease after server restart, so restart cannot make a stale
+parity or rebuild alert immortal and missing telemetry is never represented as
+healthy reporting.
Snapshot and backup-age alert evaluation now lives in
`internal/alerts/backup_snapshot.go`. That file owns snapshot age/size
evaluation, backup rollup age evaluation, backup inventory readiness, PVE
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index eea1b9b020..2501500b85 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -32,6 +32,29 @@ Host-agent report liveness is server-observed, not agent-clock-observed:
freshness, and host-agent cluster sensor freshness from Pulse receipt time, so
a reporting machine with a slow or fast local clock cannot be ingested as stale
or keep offline/recovery alerts flapping while reports are still arriving.
+Report ordering is a separate, source-authored contract. Current agents publish
+a process-unique stream plus monotonic sequence, and monitoring must serialize
+each host's complete accept-and-apply transition, reject duplicate/older or
+retired-stream reports without replacing state or writing metrics/history/
+alerts, and still advance receipt-time liveness for every authenticated
+arrival. Transport activity must not extend `Host.LastSeen`, the accepted
+telemetry lease, or alert recovery when the payload itself is rejected. The
+accepted ordering watermark, reporting interval, accepted receipt time,
+transport receipt time, and observation time are durable host continuity so a
+server restart cannot let a delayed buffered report resurrect an operation
+that a newer report already stopped.
+Legacy reports without a sequence retain timestamp-based reconnect-burst
+protection, but a clock correction after a normal report interval must be
+admitted rather than freezing telemetry indefinitely.
+Host telemetry also has a reporting lease derived from the agent cadence.
+Monitoring must not clear a genuinely active Unraid parity operation or Linux
+RAID rebuild during an ordinary polling gap. Once the lease expires, it must
+clear transient operation/progress fields from host and canonical resource
+projections while retaining static topology/health evidence that remains in
+the live last-known host snapshot. After a server restart, durable continuity
+must still expire persisted operation alerts on the same accepted-telemetry
+lease; missing telemetry then remains visible through the separate confirmed
+connectivity lifecycle.
PBS backup snapshot refresh is a bounded monitoring hot path: group-level
snapshot fetches must run through the fixed worker pool in
`internal/monitoring/monitor_backups.go`, reuse cached snapshots on per-group
@@ -187,6 +210,7 @@ data cannot wrap into a fabricated healthy value.
57. `internal/monitoring/multi_tenant_monitor.go`
58. `internal/monitoring/proxmox_action_observer.go`
59. `internal/monitoring/agent_fleet_doctor.go`
+60. `internal/config/host_continuity.go`
## Shared Boundaries
@@ -741,6 +765,16 @@ legacy Unraid raw-status normalization at host-agent ingest: when older agents s
must derive the canonical disk status before storage-risk assessment runs so
v5 aggregate counters do not override clearly healthy per-disk state during v6
compatibility operation.
+Unraid long-running operation state uses the same authoritative transition
+boundary. A non-empty active sync action may carry progress; cancellation,
+completion, or idle state is represented by an empty action and normalized
+zero progress even when an older collector or buffered payload retains a
+terminal percentage. Accepted terminal reports must immediately remove
+`unraid_sync_active` from host state, canonical storage resources, alerts, and
+UI-facing risk projections. Older reports must never restore it after that
+transition, while a mere loss of reports waits for the reporting lease and then
+clears only the transient operation evidence alongside an explicit connectivity
+signal.
The same monitoring compatibility boundary owns Unraid slot filtering and
operator health posture after host-agent ingest. Empty no-present Unraid slots
must be removed before storage-risk assessment so unassigned array capacity is
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 663c7e08a8..9c5af5928e 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -1367,6 +1367,7 @@
"test_prefixes": [],
"exact_files": [
"internal/agentupdate/coverage_test.go",
+ "internal/hostagent/agent_flushbuffer_test.go",
"internal/hostagent/agent_metrics_test.go",
"internal/hostagent/agent_new_test.go",
"internal/hostagent/command_client_test.go",
@@ -1379,7 +1380,9 @@
"internal/hostagent/package_updates_test.go",
"internal/hostagent/send_report_test.go",
"internal/hostagent/smartctl_standby_guard_test.go",
- "internal/hostagent/storage_cleanup_test.go"
+ "internal/hostagent/storage_cleanup_test.go",
+ "internal/hostagent/unraid_test.go",
+ "pkg/agents/host/report_test.go"
]
},
{
@@ -2317,6 +2320,7 @@
"internal/alerts/guest_snapshot_test.go",
"internal/alerts/history_concurrency_test.go",
"internal/alerts/history_test.go",
+ "internal/alerts/host_unraid_lifecycle_test.go",
"internal/alerts/intent_policy_test.go",
"internal/alerts/operational_contract_test.go",
"internal/alerts/resolved_lock_discipline_test.go",
@@ -5059,6 +5063,7 @@
],
"owned_files": [
"docker-entrypoint.sh",
+ "internal/config/host_continuity.go",
"internal/dockeragent/collect.go",
"internal/dockeragent/docker_client.go",
"internal/dockeragent/swarm.go",
@@ -5116,12 +5121,15 @@
"label": "monitoring host-agent ingest proof",
"match_prefixes": [],
"match_files": [
+ "internal/config/host_continuity.go",
"internal/monitoring/monitor_agents.go",
"pkg/agents/host/report.go"
],
"allow_same_subsystem_tests": false,
"test_prefixes": [],
"exact_files": [
+ "internal/config/host_continuity_test.go",
+ "internal/monitoring/issue1485_unraid_lifecycle_test.go",
"internal/monitoring/issue1595_collection_trust_test.go",
"internal/monitoring/monitor_host_agents_test.go",
"internal/monitoring/monitor_package_updates_test.go",
@@ -5285,6 +5293,7 @@
"exact_files": [
"internal/dockeragent/swarm_coverage_test.go",
"internal/models/deepcopy_test.go",
+ "internal/models/host_transient_expiry_test.go",
"internal/models/state_host_test.go",
"internal/monitoring/issue1595_collection_trust_test.go",
"internal/monitoring/monitor_full_coverage_test.go",
@@ -5455,6 +5464,7 @@
"internal/monitoring/availability_poller_test.go",
"internal/monitoring/availability_udp_test.go",
"internal/monitoring/canonical_guardrails_test.go",
+ "internal/monitoring/issue1485_unraid_lifecycle_test.go",
"internal/monitoring/issue1595_collection_trust_test.go",
"internal/monitoring/monitor_alert_intent_test.go",
"internal/monitoring/monitor_alert_override_migration_test.go",
diff --git a/internal/alerts/host.go b/internal/alerts/host.go
index b190b36afe..e8b8d7a60f 100644
--- a/internal/alerts/host.go
+++ b/internal/alerts/host.go
@@ -615,6 +615,88 @@ func (m *Manager) HandleHostRemoved(host models.Host) {
m.clearHostUnraidAlerts(host.ID)
}
+// HandleHostTelemetryExpired re-evaluates transient storage-operation evidence
+// after the host reporting lease ends. Connectivity remains a separate signal
+// evaluated by HandleHostOffline; non-transient metric and disk alerts retain
+// their existing confirmation policy until that connectivity transition.
+func (m *Manager) HandleHostTelemetryExpired(host models.Host) {
+ if host.ID == "" {
+ return
+ }
+
+ if host.Unraid != nil {
+ unraid := *host.Unraid
+ unraid.SyncAction = ""
+ unraid.SyncProgress = 0
+ host.Unraid = &unraid
+ }
+ host.RAID = append([]models.HostRAIDArray(nil), host.RAID...)
+ for i := range host.RAID {
+ host.RAID[i].Operation = ""
+ host.RAID[i].RebuildPercent = 0
+ host.RAID[i].RebuildSpeed = ""
+ }
+
+ m.mu.RLock()
+ alertsEnabled := m.config.Enabled
+ disableAllAgents := m.config.DisableAllAgents
+ thresholds := m.resolveHostThresholdsNoLock(host.ID, host.LinkedNodeID, host.LinkedVMID, host.LinkedContainerID)
+ m.mu.RUnlock()
+ if !alertsEnabled || disableAllAgents || thresholds.Disabled {
+ m.clearHostRAIDAlerts(host.ID)
+ m.clearHostUnraidAlerts(host.ID)
+ return
+ }
+
+ if host.Unraid == nil {
+ m.clearHostUnraidAlerts(host.ID)
+ } else {
+ baseMetadata := map[string]interface{}{
+ "resourceType": "agent",
+ "hostId": host.ID,
+ "hostname": host.Hostname,
+ "displayName": host.DisplayName,
+ "platform": host.Platform,
+ "osName": host.OSName,
+ "osVersion": host.OSVersion,
+ "agentVersion": host.AgentVersion,
+ "architecture": host.Architecture,
+ }
+ if linkedNodeID := strings.TrimSpace(host.LinkedNodeID); linkedNodeID != "" {
+ baseMetadata["linkedNodeId"] = linkedNodeID
+ }
+ if linkedVMID := strings.TrimSpace(host.LinkedVMID); linkedVMID != "" {
+ baseMetadata["linkedVmId"] = linkedVMID
+ }
+ if linkedContainerID := strings.TrimSpace(host.LinkedContainerID); linkedContainerID != "" {
+ baseMetadata["linkedContainerId"] = linkedContainerID
+ }
+ if len(host.Tags) > 0 {
+ baseMetadata["tags"] = append([]string(nil), host.Tags...)
+ }
+ m.syncHostUnraidStorageAlert(
+ host,
+ strings.TrimSpace(host.Hostname),
+ hostInstanceName(host),
+ hostDisplayName(host),
+ baseMetadata,
+ )
+ }
+
+ if len(host.RAID) == 0 {
+ m.clearHostRAIDAlerts(host.ID)
+ return
+ }
+ for _, array := range host.RAID {
+ assessment := storagehealth.AssessHostRAIDArray(array)
+ if assessment.Level != storagehealth.RiskHealthy {
+ continue
+ }
+ resourceID := fmt.Sprintf("%s/raid:%s", hostResourceID(host.ID), sanitizeRAIDDevice(array.Device))
+ m.clearAlert(buildCanonicalStateID(resourceID, resourceID+"-health"))
+ }
+}
+
// HandleHostOffline raises an alert when a host agent stops reporting.
func (m *Manager) HandleHostOffline(host models.Host) {
if host.ID == "" {
@@ -626,6 +708,7 @@ func (m *Manager) HandleHostOffline(host models.Host) {
if host.Hostname != "" {
m.UnregisterHostAgentHostname(host.Hostname)
}
+ m.HandleHostTelemetryExpired(host)
m.mu.RLock()
if !m.config.Enabled {
@@ -750,6 +833,8 @@ func (m *Manager) HandleHostOffline(host models.Host) {
m.clearAlertNoLock(staleAlertID)
}
m.mu.Unlock()
+ m.clearHostRAIDAlerts(host.ID)
+ m.clearHostUnraidAlerts(host.ID)
log.Error().
Str("host", resourceName).
diff --git a/internal/alerts/host_unraid_lifecycle_test.go b/internal/alerts/host_unraid_lifecycle_test.go
new file mode 100644
index 0000000000..1d074c6f49
--- /dev/null
+++ b/internal/alerts/host_unraid_lifecycle_test.go
@@ -0,0 +1,122 @@
+package alerts
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+func TestHandleHostOfflineExpiresUnraidOperationAlertBeforeConnectivityConfirmation(t *testing.T) {
+ manager := newTestManager(t)
+ manager.ClearActiveAlerts()
+ host := models.Host{
+ ID: "unraid-host",
+ Hostname: "tower",
+ DisplayName: "Tower",
+ Platform: "unraid",
+ Unraid: &models.HostUnraidStorage{
+ ArrayStarted: true,
+ ArrayState: "STARTED",
+ SyncAction: "check",
+ SyncProgress: 40,
+ Disks: []models.HostUnraidDisk{
+ {Name: "parity", Role: "parity", Status: "online", Device: "/dev/sda"},
+ {Name: "disk1", Role: "data", Status: "online", Device: "/dev/sdb"},
+ },
+ },
+ }
+
+ manager.CheckHost(host)
+ if !hasAlertType(manager.GetActiveAlerts(), "storage-topology") {
+ t.Fatal("expected active Unraid operation alert")
+ }
+
+ manager.HandleHostOffline(host)
+ alerts := manager.GetActiveAlerts()
+ if hasAlertType(alerts, "storage-topology") {
+ t.Fatal("expired Unraid operation alert remained active")
+ }
+ if hasAlertType(alerts, "host-offline") {
+ t.Fatal("connectivity alert should still require its confirmation window")
+ }
+}
+
+func TestHandleHostTelemetryExpiredPreservesStaticStorageRisk(t *testing.T) {
+ t.Run("Unraid no-parity risk survives transient check expiry", func(t *testing.T) {
+ manager := newTestManager(t)
+ manager.ClearActiveAlerts()
+ host := models.Host{
+ ID: "unraid-no-parity",
+ Hostname: "tower",
+ DisplayName: "Tower",
+ Platform: "unraid",
+ Unraid: &models.HostUnraidStorage{
+ ArrayStarted: true,
+ ArrayState: "STARTED",
+ SyncAction: "check",
+ SyncProgress: 40,
+ Disks: []models.HostUnraidDisk{
+ {Name: "disk1", Role: "data", Status: "online", Device: "/dev/sdb"},
+ },
+ },
+ }
+
+ manager.CheckHost(host)
+ manager.HandleHostTelemetryExpired(host)
+
+ var storageAlert *Alert
+ activeAlerts := manager.GetActiveAlerts()
+ for i := range activeAlerts {
+ alert := activeAlerts[i]
+ if alert.Type == "storage-topology" {
+ storageAlert = &alert
+ break
+ }
+ }
+ if storageAlert == nil {
+ t.Fatal("static no-parity risk was cleared with transient operation state")
+ }
+ if strings.Contains(strings.ToLower(storageAlert.Message), "check") {
+ t.Fatalf("expired operation remained in static alert: %q", storageAlert.Message)
+ }
+ })
+
+ t.Run("degraded RAID risk survives transient rebuild expiry", func(t *testing.T) {
+ manager := newTestManager(t)
+ manager.ClearActiveAlerts()
+ host := models.Host{
+ ID: "raid-degraded",
+ Hostname: "storage-host",
+ DisplayName: "Storage Host",
+ Platform: "linux",
+ RAID: []models.HostRAIDArray{{
+ Device: "/dev/md0",
+ Level: "raid1",
+ State: "degraded",
+ TotalDevices: 2,
+ ActiveDevices: 1,
+ WorkingDevices: 1,
+ FailedDevices: 1,
+ Operation: "recovery",
+ RebuildPercent: 40,
+ RebuildSpeed: "100M/sec",
+ }},
+ }
+
+ manager.CheckHost(host)
+ manager.HandleHostTelemetryExpired(host)
+ if !hasAlertType(manager.GetActiveAlerts(), "raid") {
+ t.Fatal("static degraded RAID risk was cleared with transient rebuild state")
+ }
+ })
+}
+
+func hasAlertType(alerts []Alert, alertType string) bool {
+ for _, alert := range alerts {
+ if alert.Type == alertType {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/config/host_continuity.go b/internal/config/host_continuity.go
index e74a2e4234..b52c661582 100644
--- a/internal/config/host_continuity.go
+++ b/internal/config/host_continuity.go
@@ -14,9 +14,9 @@ import (
"github.com/rs/zerolog/log"
)
-// HostContinuityEntry stores the minimum durable identity needed to recognise
-// an existing standalone host across restart and upgrade boundaries before the
-// next live report arrives.
+// HostContinuityEntry stores the minimum durable identity and report watermark
+// needed to recognise an existing standalone host and reject older telemetry
+// across restart and upgrade boundaries before the next live report arrives.
type HostContinuityEntry struct {
HostID string `json:"hostId"`
ReportHostID string `json:"reportHostId,omitempty"`
@@ -32,10 +32,21 @@ type HostContinuityEntry struct {
LinkedContainerID string `json:"linkedContainerId,omitempty"`
IsLegacy bool `json:"isLegacy,omitempty"`
LastSeen time.Time `json:"lastSeen,omitempty"`
+ IntervalSeconds int `json:"intervalSeconds,omitempty"`
+ // Report ordering and transport activity are persisted independently from
+ // accepted telemetry freshness. LastSeen is the server receipt time of the
+ // last accepted report; ReportLastReceivedAt includes rejected stale or
+ // duplicate arrivals, while ReportObservedAt is the agent-authored clock.
+ ReportObservedAt time.Time `json:"reportObservedAt,omitempty"`
+ ReportLastReceivedAt time.Time `json:"reportLastReceivedAt,omitempty"`
+ ReportStreamID string `json:"reportStreamId,omitempty"`
+ ReportSequence uint64 `json:"reportSequence,omitempty"`
+ RetiredReportStreamIDs []string `json:"retiredReportStreamIds,omitempty"`
}
-// HostContinuityStore persists recent standalone host identities so licensing
-// and grandfather-floor continuity survive process restarts.
+// HostContinuityStore persists recent standalone host identity and report
+// ordering so licensing, grandfather-floor, and telemetry-transition
+// continuity survive process restarts.
type HostContinuityStore struct {
mu sync.RWMutex
entries map[string]HostContinuityEntry
@@ -75,6 +86,14 @@ func normalizeHostContinuityEntry(entry HostContinuityEntry) (HostContinuityEntr
entry.LinkedNodeID = strings.TrimSpace(entry.LinkedNodeID)
entry.LinkedVMID = strings.TrimSpace(entry.LinkedVMID)
entry.LinkedContainerID = strings.TrimSpace(entry.LinkedContainerID)
+ entry.ReportStreamID = strings.TrimSpace(entry.ReportStreamID)
+ entry.RetiredReportStreamIDs = uniqueTrimmedStrings(entry.RetiredReportStreamIDs...)
+ if len(entry.RetiredReportStreamIDs) > 8 {
+ entry.RetiredReportStreamIDs = append([]string(nil), entry.RetiredReportStreamIDs[len(entry.RetiredReportStreamIDs)-8:]...)
+ }
+ if entry.ReportStreamID == "" {
+ entry.ReportSequence = 0
+ }
return entry, true
}
diff --git a/internal/config/host_continuity_test.go b/internal/config/host_continuity_test.go
index 85cb893123..2503d89dcd 100644
--- a/internal/config/host_continuity_test.go
+++ b/internal/config/host_continuity_test.go
@@ -11,13 +11,22 @@ func TestHostContinuityStoreRoundTripAndMatch(t *testing.T) {
now := time.Now().UTC().Truncate(time.Second)
if err := store.Upsert(HostContinuityEntry{
- HostID: "host-1",
- ReportHostID: "machine-1",
- AgentReportedID: "agent-1",
- Hostname: "host-1.local",
- MachineID: "machine-1",
- TokenID: "token-1",
- LastSeen: now,
+ HostID: "host-1",
+ ReportHostID: "machine-1",
+ AgentReportedID: "agent-1",
+ Hostname: "host-1.local",
+ MachineID: "machine-1",
+ TokenID: "token-1",
+ LastSeen: now,
+ IntervalSeconds: 30,
+ ReportObservedAt: now.Add(-time.Second),
+ ReportLastReceivedAt: now.Add(time.Second),
+ ReportStreamID: "stream-current",
+ ReportSequence: 14,
+ RetiredReportStreamIDs: []string{
+ "stream-old",
+ "stream-old",
+ },
}); err != nil {
t.Fatalf("Upsert: %v", err)
}
@@ -25,7 +34,15 @@ func TestHostContinuityStoreRoundTripAndMatch(t *testing.T) {
reloaded := NewHostContinuityStore(dir, nil)
if entry, ok := reloaded.Get("host-1"); !ok {
t.Fatal("expected reloaded entry")
- } else if entry.TokenID != "token-1" || entry.Hostname != "host-1.local" {
+ } else if entry.TokenID != "token-1" ||
+ entry.Hostname != "host-1.local" ||
+ entry.IntervalSeconds != 30 ||
+ entry.ReportObservedAt != now.Add(-time.Second) ||
+ entry.ReportLastReceivedAt != now.Add(time.Second) ||
+ entry.ReportStreamID != "stream-current" ||
+ entry.ReportSequence != 14 ||
+ len(entry.RetiredReportStreamIDs) != 1 ||
+ entry.RetiredReportStreamIDs[0] != "stream-old" {
t.Fatalf("unexpected reloaded entry: %+v", entry)
}
diff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.go
index 7633f00300..bcceccf11f 100644
--- a/internal/hostagent/agent.go
+++ b/internal/hostagent/agent.go
@@ -3,6 +3,8 @@ package hostagent
import (
"bytes"
"context"
+ "crypto/rand"
+ "encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -18,6 +20,7 @@ import (
"strconv"
"strings"
"sync"
+ "sync/atomic"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/agenttarget"
@@ -153,6 +156,8 @@ type Agent struct {
runCommandClient func(*CommandClient, context.Context) error
packageUpdates *packageUpdateManager
storageCleanup *storageCleanupManager
+ reportStreamID string
+ reportSequence atomic.Uint64
// lastAuthFailureLog throttles the actionable 401 error so a permanently
// rejected token does not spam the log every report interval. Only touched
@@ -332,6 +337,11 @@ func New(cfg Config) (*Agent, error) {
agentVersion = Version
}
+ reportStreamID, err := newReportStreamID()
+ if err != nil {
+ return nil, fmt.Errorf("create report stream ID: %w", err)
+ }
+
const bufferCapacity = 60
// Check if agent was recently auto-updated (only reported once per restart)
@@ -377,6 +387,7 @@ func New(cfg Config) (*Agent, error) {
runCommandClient: runCommandClientFn,
packageUpdates: packageUpdates,
storageCleanup: storageCleanup,
+ reportStreamID: reportStreamID,
}
// Create command client for AI command execution (only if enabled)
@@ -390,6 +401,21 @@ func New(cfg Config) (*Agent, error) {
return agent, nil
}
+func newReportStreamID() (string, error) {
+ var raw [16]byte
+ if _, err := rand.Read(raw[:]); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(raw[:]), nil
+}
+
+func (a *Agent) nextReportSequenceID() string {
+ if a == nil || strings.TrimSpace(a.reportStreamID) == "" {
+ return ""
+ }
+ return agentshost.FormatReportSequenceID(a.reportStreamID, a.reportSequence.Add(1))
+}
+
func newAgentHTTPClient(caCertPath string, insecureSkipVerify bool, serverFingerprint string) (*http.Client, error) {
tlsConfig, err := agenttls.NewClientTLSConfig(caCertPath, insecureSkipVerify, serverFingerprint)
if err != nil {
@@ -704,6 +730,17 @@ func (a *Agent) process(ctx context.Context) error {
}
func (a *Agent) deliverPrimaryReport(ctx context.Context, report agentshost.Report) error {
+ // Preserve collection order across reconnects. Sending the newest report
+ // before the buffered FIFO can let an older long-running-task snapshot
+ // overwrite a newer cancellation or completion on the server.
+ if !a.reportBuffer.IsEmpty() {
+ a.flushBuffer(ctx)
+ if !a.reportBuffer.IsEmpty() {
+ a.reportBuffer.Push(report)
+ return nil
+ }
+ }
+
if err := a.sendReport(ctx, report); err != nil {
agenttarget.MarkDelivery("host", "primary", "primary", false)
var statusErr *reportHTTPStatusError
@@ -755,6 +792,14 @@ func (a *Agent) deliverPrimaryReport(ctx context.Context, report agentshost.Repo
}
func (a *Agent) deliverObserverReport(ctx context.Context, observer *observerReporter, report agentshost.Report) {
+ if !observer.reportBuffer.IsEmpty() {
+ a.flushObserverBuffer(ctx, observer)
+ if !observer.reportBuffer.IsEmpty() {
+ observer.reportBuffer.Push(report)
+ return
+ }
+ }
+
if err := a.sendReportToDestination(ctx, report, observer.target.PulseURL, observer.target.APIToken, observer.httpClient, false); err != nil {
agenttarget.MarkDelivery("host", observer.target.Name, "observer", false)
var statusErr *reportHTTPStatusError
@@ -805,8 +850,8 @@ func (a *Agent) flushObserverBuffer(ctx context.Context, observer *observerRepor
}
// logAuthFailure emits an actionable, throttled error when the server rejects
-// the agent's API token with 401. It is only called from the single-threaded
-// report loop, so lastAuthFailureLog needs no additional synchronisation.
+// the agent's API token. It is only called from the single-threaded report
+// loop, so lastAuthFailureLog needs no additional synchronisation.
func (a *Agent) logAuthFailure(statusErr *reportHTTPStatusError) {
if time.Since(a.lastAuthFailureLog) < authFailureLogInterval {
return
@@ -822,11 +867,15 @@ func (a *Agent) logAuthFailure(statusErr *reportHTTPStatusError) {
statusCode = statusErr.StatusCode
}
- a.logger.Error().
+ event := a.logger.Error().
Str("endpoint", endpoint).
Int("status_code", statusCode).
- Str("pulse_url", a.trimmedPulseURL).
- Msg("Pulse rejected this agent's API token (401 Unauthorized). The token is no longer valid on the server, which usually means Pulse was restored/reinstalled or upgraded (for example v5 -> v6) without carrying the token across. Re-run the agent install command from the Pulse UI to mint a fresh token. Reports are dropped until the token is replaced.")
+ Str("pulse_url", a.trimmedPulseURL)
+ if statusCode == http.StatusForbidden {
+ event.Msg("Pulse rejected this agent's API token (403 Forbidden). The token may lack the Unified Agent reporting scope. Re-run the agent install command from the Pulse UI to mint a correctly scoped token. Reports are dropped until the token is replaced.")
+ return
+ }
+ event.Msg("Pulse rejected this agent's API token (401 Unauthorized). The token is no longer valid on the server, which usually means Pulse was restored/reinstalled or upgraded (for example v5 -> v6) without carrying the token across. Re-run the agent install command from the Pulse UI to mint a fresh token. Reports are dropped until the token is replaced.")
}
func (a *Agent) flushBuffer(ctx context.Context) {
@@ -845,7 +894,8 @@ func (a *Agent) flushBuffer(ctx context.Context) {
if err := a.sendReport(ctx, report); err != nil {
var statusErr *reportHTTPStatusError
- if errors.As(err, &statusErr) && statusErr.StatusCode == http.StatusUnauthorized {
+ if errors.As(err, &statusErr) &&
+ (statusErr.StatusCode == http.StatusUnauthorized || statusErr.StatusCode == http.StatusForbidden) {
// The token is rejected; buffered reports will never be
// accepted with it. Drop them so the buffer cannot grow
// unbounded across restarts, and surface the actionable error.
@@ -1080,6 +1130,7 @@ func (a *Agent) buildReport(ctx context.Context) (agentshost.Report, error) {
ClusterSensors: clusterSensors,
Tags: append([]string(nil), runtimeConfig.tags...),
Timestamp: a.collector.Now(),
+ SequenceID: a.nextReportSequenceID(),
}
return report, nil
diff --git a/internal/hostagent/agent_flushbuffer_test.go b/internal/hostagent/agent_flushbuffer_test.go
index 790c9ef50c..131c37630d 100644
--- a/internal/hostagent/agent_flushbuffer_test.go
+++ b/internal/hostagent/agent_flushbuffer_test.go
@@ -1,9 +1,13 @@
package hostagent
import (
+ "compress/gzip"
"context"
+ "encoding/json"
+ "io"
"net/http"
"net/http/httptest"
+ "sync"
"sync/atomic"
"testing"
@@ -12,6 +16,61 @@ import (
"github.com/rs/zerolog"
)
+func TestAgent_deliverPrimaryReport_DrainsBufferedReportsBeforeCurrent(t *testing.T) {
+ var (
+ mu sync.Mutex
+ received []string
+ )
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body io.Reader = r.Body
+ if r.Header.Get("Content-Encoding") == "gzip" {
+ reader, err := gzip.NewReader(r.Body)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ defer reader.Close()
+ body = reader
+ }
+ var report agentshost.Report
+ if err := json.NewDecoder(body).Decode(&report); err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ mu.Lock()
+ received = append(received, report.SequenceID)
+ mu.Unlock()
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer server.Close()
+
+ a := &Agent{
+ cfg: Config{APIToken: "token"},
+ logger: zerolog.Nop(),
+ httpClient: server.Client(),
+ trimmedPulseURL: server.URL,
+ reportBuffer: utils.New[agentshost.Report](10),
+ }
+ a.reportBuffer.Push(agentshost.Report{SequenceID: "oldest"})
+ a.reportBuffer.Push(agentshost.Report{SequenceID: "older"})
+
+ if err := a.deliverPrimaryReport(context.Background(), agentshost.Report{SequenceID: "current"}); err != nil {
+ t.Fatalf("deliverPrimaryReport: %v", err)
+ }
+
+ mu.Lock()
+ defer mu.Unlock()
+ want := []string{"oldest", "older", "current"}
+ if len(received) != len(want) {
+ t.Fatalf("received = %v, want %v", received, want)
+ }
+ for i := range want {
+ if received[i] != want[i] {
+ t.Fatalf("received = %v, want %v", received, want)
+ }
+ }
+}
+
func TestAgent_flushBuffer_StopsOnFailureAndDoesNotDropReport(t *testing.T) {
var requestCount int32
@@ -87,3 +146,25 @@ func TestAgent_flushBuffer_RetryAfterTransientFailure(t *testing.T) {
t.Fatalf("expected buffer to be empty, has %d items", a.reportBuffer.Len())
}
}
+
+func TestAgent_flushBuffer_ForbiddenDropsBuffer(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusForbidden)
+ }))
+ defer server.Close()
+
+ a := &Agent{
+ cfg: Config{APIToken: "wrong-scope"},
+ logger: zerolog.Nop(),
+ httpClient: server.Client(),
+ trimmedPulseURL: server.URL,
+ reportBuffer: utils.New[agentshost.Report](10),
+ }
+ a.reportBuffer.Push(agentshost.Report{Agent: agentshost.AgentInfo{ID: "r1"}})
+ a.reportBuffer.Push(agentshost.Report{Agent: agentshost.AgentInfo{ID: "r2"}})
+
+ a.flushBuffer(context.Background())
+ if !a.reportBuffer.IsEmpty() {
+ t.Fatalf("buffer should be drained after forbidden flush, len=%d", a.reportBuffer.Len())
+ }
+}
diff --git a/internal/hostagent/agent_new_test.go b/internal/hostagent/agent_new_test.go
index dc1a81c61e..00f619d262 100644
--- a/internal/hostagent/agent_new_test.go
+++ b/internal/hostagent/agent_new_test.go
@@ -954,6 +954,10 @@ func TestNew_CarriesUpdatedFromIntoFirstV6Report(t *testing.T) {
if report.Agent.UpdatedFrom != "5.1.14" {
t.Fatalf("report updated_from = %q, want %q", report.Agent.UpdatedFrom, "5.1.14")
}
+ reportStreamID, reportSequence, ok := agentshost.ParseReportSequenceID(report.SequenceID)
+ if !ok || reportStreamID == "" || reportSequence != 1 {
+ t.Fatalf("first report sequence ID = %q, parsed (%q, %d, %v)", report.SequenceID, reportStreamID, reportSequence, ok)
+ }
if agent.updatedFrom != "" {
t.Fatalf("agent.updatedFrom after first build = %q, want empty string", agent.updatedFrom)
}
@@ -965,6 +969,10 @@ func TestNew_CarriesUpdatedFromIntoFirstV6Report(t *testing.T) {
if secondReport.Agent.UpdatedFrom != "" {
t.Fatalf("second report updated_from = %q, want empty string", secondReport.Agent.UpdatedFrom)
}
+ secondStreamID, secondSequence, ok := agentshost.ParseReportSequenceID(secondReport.SequenceID)
+ if !ok || secondStreamID != reportStreamID || secondSequence != 2 {
+ t.Fatalf("second report sequence ID = %q, parsed (%q, %d, %v), first stream %q", secondReport.SequenceID, secondStreamID, secondSequence, ok, reportStreamID)
+ }
}
func TestNew_RejectsInvalidPulseURL(t *testing.T) {
diff --git a/internal/hostagent/unraid.go b/internal/hostagent/unraid.go
index 8fd5d42cc5..f4daec413c 100644
--- a/internal/hostagent/unraid.go
+++ b/internal/hostagent/unraid.go
@@ -88,11 +88,12 @@ func parseUnraidStatusOutput(output string) (*agentshost.UnraidStorage, error) {
return nil, fmt.Errorf("mdcmd status returned no key=value fields")
}
+ syncAction := unraidSyncAction(fields)
storage := &agentshost.UnraidStorage{
ArrayState: strings.ToUpper(strings.TrimSpace(fields["mdState"])),
ArrayStarted: strings.EqualFold(strings.TrimSpace(fields["mdState"]), "STARTED"),
- SyncAction: unraidSyncAction(fields),
- SyncProgress: unraidSyncProgress(fields),
+ SyncAction: syncAction,
+ SyncProgress: unraidSyncProgress(fields, syncAction),
SyncErrors: parseUnraidInt64Field(fields, "mdResyncCorr"),
NumProtected: parseUnraidIntField(fields, "mdNumProtected"),
NumDisabled: parseUnraidIntField(fields, "mdNumDisabled"),
@@ -485,7 +486,10 @@ func unraidSyncAction(fields map[string]string) string {
return normalizeUnraidSyncAction(fields["mdResyncAction"])
}
-func unraidSyncProgress(fields map[string]string) float64 {
+func unraidSyncProgress(fields map[string]string, syncAction string) float64 {
+ if strings.TrimSpace(syncAction) == "" {
+ return 0
+ }
pos := parseFirstInt64(fields["mdResyncPos"], fields["mdResync"])
size := parseFirstInt64(fields["mdResyncSize"], fields["mdSize"])
if pos > 0 && size > 0 {
diff --git a/internal/hostagent/unraid_test.go b/internal/hostagent/unraid_test.go
index 659dedfb53..db34659c39 100644
--- a/internal/hostagent/unraid_test.go
+++ b/internal/hostagent/unraid_test.go
@@ -68,6 +68,7 @@ func TestParseUnraidStatusOutputStaleSyncAction(t *testing.T) {
name string
output string
wantSyncAction string
+ wantProgress float64
}{
{
name: "sync active reports action",
@@ -78,6 +79,7 @@ mdResyncPos=500
mdResyncSize=1000
`,
wantSyncAction: "check",
+ wantProgress: 50,
},
{
name: "stale action cleared when position is zero",
@@ -86,8 +88,10 @@ mdState=STARTED
mdResyncAction=check
mdResyncPos=0
mdResyncSize=0
+mdResyncPct=100
`,
wantSyncAction: "",
+ wantProgress: 0,
},
{
name: "stale action cleared when position fields absent",
@@ -96,6 +100,7 @@ mdState=STARTED
mdResyncAction=check
`,
wantSyncAction: "",
+ wantProgress: 0,
},
{
name: "idle action always empty",
@@ -105,6 +110,7 @@ mdResyncAction=idle
mdResyncPos=500
`,
wantSyncAction: "",
+ wantProgress: 0,
},
}
@@ -117,6 +123,9 @@ mdResyncPos=500
if storage.SyncAction != tt.wantSyncAction {
t.Errorf("SyncAction = %q, want %q", storage.SyncAction, tt.wantSyncAction)
}
+ if storage.SyncProgress != tt.wantProgress {
+ t.Errorf("SyncProgress = %v, want %v", storage.SyncProgress, tt.wantProgress)
+ }
})
}
}
diff --git a/internal/models/host_transient_expiry_test.go b/internal/models/host_transient_expiry_test.go
new file mode 100644
index 0000000000..4aab4e2d9e
--- /dev/null
+++ b/internal/models/host_transient_expiry_test.go
@@ -0,0 +1,49 @@
+package models
+
+import "testing"
+
+func TestExpireHostTelemetryClearsTransientStorageOperationsOnly(t *testing.T) {
+ state := NewState()
+ state.UpsertHost(Host{
+ ID: "storage-host",
+ Status: "online",
+ RAID: []HostRAIDArray{{
+ Device: "/dev/md127",
+ State: "degraded",
+ FailedDevices: 1,
+ Operation: "recovery",
+ RebuildPercent: 45,
+ RebuildSpeed: "90M/sec",
+ }},
+ Unraid: &HostUnraidStorage{
+ ArrayStarted: true,
+ ArrayState: "STARTED",
+ SyncAction: "check",
+ SyncProgress: 72,
+ NumDisabled: 1,
+ },
+ })
+
+ host, changed := state.ExpireHostTelemetry("storage-host")
+ if !changed {
+ t.Fatal("expected host telemetry to change")
+ }
+ if host.Status != "offline" {
+ t.Fatalf("status = %q, want offline", host.Status)
+ }
+ if host.Unraid == nil || host.Unraid.SyncAction != "" || host.Unraid.SyncProgress != 0 {
+ t.Fatalf("Unraid transient state not cleared: %+v", host.Unraid)
+ }
+ if host.Unraid.NumDisabled != 1 || host.Unraid.ArrayState != "STARTED" {
+ t.Fatalf("Unraid last-known topology was lost: %+v", host.Unraid)
+ }
+ if len(host.RAID) != 1 ||
+ host.RAID[0].Operation != "" ||
+ host.RAID[0].RebuildPercent != 0 ||
+ host.RAID[0].RebuildSpeed != "" {
+ t.Fatalf("RAID transient state not cleared: %+v", host.RAID)
+ }
+ if host.RAID[0].FailedDevices != 1 || host.RAID[0].State != "degraded" {
+ t.Fatalf("RAID last-known health was lost: %+v", host.RAID[0])
+ }
+}
diff --git a/internal/models/models.go b/internal/models/models.go
index 8eaafd956b..81a592befc 100644
--- a/internal/models/models.go
+++ b/internal/models/models.go
@@ -4763,6 +4763,42 @@ func (s *State) SetHostStatus(hostID, status string) bool {
return false
}
+// ExpireHostTelemetry marks a host offline and clears transient operation
+// claims that cannot remain authoritative after the reporting lease expires.
+// Static topology and health counters remain available as last-known context.
+func (s *State) ExpireHostTelemetry(hostID string) (Host, bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ for i, host := range s.Hosts {
+ if host.ID != hostID {
+ continue
+ }
+ changed := host.Status != "offline"
+ host.Status = "offline"
+ for idx := range host.RAID {
+ array := &host.RAID[idx]
+ if array.Operation != "" || array.RebuildPercent != 0 || array.RebuildSpeed != "" {
+ array.Operation = ""
+ array.RebuildPercent = 0
+ array.RebuildSpeed = ""
+ changed = true
+ }
+ }
+ if host.Unraid != nil && (host.Unraid.SyncAction != "" || host.Unraid.SyncProgress != 0) {
+ host.Unraid.SyncAction = ""
+ host.Unraid.SyncProgress = 0
+ changed = true
+ }
+ s.Hosts[i] = host
+ if changed {
+ s.LastUpdate = time.Now()
+ }
+ return cloneHost(host), changed
+ }
+ return Host{}, false
+}
+
// TouchHost updates the last seen timestamp for a host.
func (s *State) TouchHost(hostID string, ts time.Time) bool {
s.mu.Lock()
diff --git a/internal/monitoring/issue1485_unraid_lifecycle_test.go b/internal/monitoring/issue1485_unraid_lifecycle_test.go
new file mode 100644
index 0000000000..9ccf6e179d
--- /dev/null
+++ b/internal/monitoring/issue1485_unraid_lifecycle_test.go
@@ -0,0 +1,417 @@
+package monitoring
+
+import (
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
+)
+
+func newIssue1485Monitor(t *testing.T, dataDir string) *Monitor {
+ t.Helper()
+ manager := alerts.NewManagerWithDataDir(dataDir)
+ monitor := &Monitor{
+ config: &config.Config{DataPath: dataDir},
+ state: models.NewState(),
+ alertManager: manager,
+ hostContinuityStore: config.NewHostContinuityStore(dataDir, nil),
+ rateTracker: NewRateTracker(),
+ metricsHistory: NewMetricsHistory(100, time.Hour),
+ hostTokenBindings: make(map[string]string),
+ hostReportOrders: make(map[string]hostReportOrder),
+ removedHostAgents: make(map[string]time.Time),
+ clusterSensorsCache: make(map[string]clusterSensorsCacheEntry),
+ resourceStore: unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(nil)),
+ guestMetadataStore: config.NewGuestMetadataStore(dataDir, nil),
+ dockerMetadataStore: config.NewDockerMetadataStore(dataDir, nil),
+ hostMetadataStore: config.NewHostMetadataStore(dataDir, nil),
+ removedDockerHosts: make(map[string]time.Time),
+ dockerTokenBindings: make(map[string]string),
+ }
+ t.Cleanup(manager.Stop)
+ return monitor
+}
+
+func issue1485Report(observedAt time.Time, streamID string, sequence uint64, action string, progress float64) agentshost.Report {
+ return agentshost.Report{
+ Agent: agentshost.AgentInfo{
+ ID: "unraid-agent",
+ Version: "6.1.1",
+ Type: "unified",
+ IntervalSeconds: 10,
+ },
+ Host: agentshost.HostInfo{
+ ID: "unraid-machine",
+ Hostname: "tower",
+ DisplayName: "Tower",
+ MachineID: "unraid-machine",
+ Platform: "unraid",
+ OSName: "Unraid",
+ UptimeSeconds: 3600,
+ },
+ Metrics: agentshost.Metrics{
+ CPUUsagePercent: float64(sequence),
+ Memory: agentshost.MemoryMetric{
+ TotalBytes: 16 << 30,
+ UsedBytes: 4 << 30,
+ Usage: 25,
+ },
+ },
+ Unraid: &agentshost.UnraidStorage{
+ ArrayStarted: true,
+ ArrayState: "STARTED",
+ SyncAction: action,
+ SyncProgress: progress,
+ NumProtected: 1,
+ Disks: []agentshost.UnraidDisk{
+ {Name: "parity", Role: "parity", Status: "online", Device: "/dev/sda"},
+ {Name: "disk1", Role: "data", Status: "online", Device: "/dev/sdb"},
+ },
+ },
+ Timestamp: observedAt.UTC(),
+ SequenceID: agentshost.FormatReportSequenceID(streamID, sequence),
+ }
+}
+
+func issue1485HasAlertType(manager *alerts.Manager, alertType string) bool {
+ for _, alert := range manager.GetActiveAlerts() {
+ if alert.Type == alertType {
+ return true
+ }
+ }
+ return false
+}
+
+func issue1485UnraidResource(t *testing.T, monitor *Monitor) unifiedresources.Resource {
+ t.Helper()
+ for _, resource := range monitor.resourceStore.GetAll() {
+ if resource.Type == unifiedresources.ResourceTypeStorage &&
+ resource.Technology == "unraid" &&
+ resource.Storage != nil &&
+ resource.Storage.Type == "unraid-array" {
+ return resource
+ }
+ }
+ t.Fatal("Unraid array resource not found")
+ return unifiedresources.Resource{}
+}
+
+func assertIssue1485Idle(t *testing.T, monitor *Monitor, host models.Host) {
+ t.Helper()
+ if host.Unraid == nil {
+ t.Fatal("Unraid state missing")
+ }
+ if host.Unraid.SyncAction != "" || host.Unraid.SyncProgress != 0 {
+ t.Fatalf("transient sync state = (%q, %.1f), want idle", host.Unraid.SyncAction, host.Unraid.SyncProgress)
+ }
+ if issue1485HasAlertType(monitor.alertManager, "storage-topology") {
+ t.Fatal("Unraid operation alert remained active")
+ }
+ resource := issue1485UnraidResource(t, monitor)
+ if resource.Storage.SyncAction != "" || resource.Storage.SyncProgress != 0 {
+ t.Fatalf("resource sync state = (%q, %.1f), want idle", resource.Storage.SyncAction, resource.Storage.SyncProgress)
+ }
+ if resource.Storage.Risk != nil {
+ for _, reason := range resource.Storage.Risk.Reasons {
+ if reason.Code == "unraid_sync_active" {
+ t.Fatalf("resource retained active-sync risk: %+v", reason)
+ }
+ }
+ }
+}
+
+func TestIssue1485UnraidParityLifecycle(t *testing.T) {
+ base := time.Now().UTC().Add(-time.Minute)
+
+ t.Run("cancelled and normally completed checks resolve every projection", func(t *testing.T) {
+ for _, terminal := range []struct {
+ name string
+ progress float64
+ }{
+ {name: "cancelled", progress: 0},
+ {name: "completed", progress: 100},
+ } {
+ t.Run(terminal.name, func(t *testing.T) {
+ monitor := newIssue1485Monitor(t, t.TempDir())
+ running, err := monitor.ApplyHostReport(issue1485Report(base, "stream-a", 1, "check", 40), nil)
+ if err != nil {
+ t.Fatalf("apply running report: %v", err)
+ }
+ if running.Unraid == nil || running.Unraid.SyncAction != "check" {
+ t.Fatalf("running state = %+v", running.Unraid)
+ }
+ if !issue1485HasAlertType(monitor.alertManager, "storage-topology") {
+ t.Fatal("running parity check did not create an alert")
+ }
+
+ terminalReport := issue1485Report(base.Add(time.Second), "stream-a", 2, "", terminal.progress)
+ idle, err := monitor.ApplyHostReport(terminalReport, nil)
+ if err != nil {
+ t.Fatalf("apply terminal report: %v", err)
+ }
+ assertIssue1485Idle(t, monitor, idle)
+ })
+ }
+ })
+
+ t.Run("stale and retired reports cannot resurrect a cancelled check or append metrics", func(t *testing.T) {
+ monitor := newIssue1485Monitor(t, t.TempDir())
+ if _, err := monitor.ApplyHostReport(issue1485Report(base, "stream-a", 1, "check", 20), nil); err != nil {
+ t.Fatal(err)
+ }
+ idle, err := monitor.ApplyHostReport(issue1485Report(base.Add(time.Second), "stream-a", 2, "", 0), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertIssue1485Idle(t, monitor, idle)
+ metricKey := "agent:" + idle.ID
+ before := len(monitor.metricsHistory.GetGuestMetrics(metricKey, "cpu", time.Hour))
+
+ stale, err := monitor.ApplyHostReport(issue1485Report(base, "stream-a", 1, "check", 20), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertIssue1485Idle(t, monitor, stale)
+ if !stale.LastSeen.Equal(idle.LastSeen) {
+ t.Fatalf("stale report extended accepted telemetry lease: got %v want %v", stale.LastSeen, idle.LastSeen)
+ }
+ if after := len(monitor.metricsHistory.GetGuestMetrics(metricKey, "cpu", time.Hour)); after != before {
+ t.Fatalf("stale report appended metrics: before=%d after=%d", before, after)
+ }
+
+ reconnected, err := monitor.ApplyHostReport(issue1485Report(base.Add(-time.Hour), "stream-b", 1, "", 0), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertIssue1485Idle(t, monitor, reconnected)
+
+ retired, err := monitor.ApplyHostReport(issue1485Report(base.Add(2*time.Second), "stream-a", 3, "check", 60), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertIssue1485Idle(t, monitor, retired)
+ })
+
+ t.Run("polling gap expires transient operations without hiding telemetry loss", func(t *testing.T) {
+ monitor := newIssue1485Monitor(t, t.TempDir())
+ running, err := monitor.ApplyHostReport(issue1485Report(base, "stream-a", 1, "check", 30), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ monitor.evaluateHostAgents(running.LastSeen.Add(hostAgentHealthWindow(running.IntervalSeconds) - time.Second))
+ stillRunning, ok := monitor.hostByID(running.ID)
+ if !ok {
+ t.Fatal("host missing during ordinary polling gap")
+ }
+ if stillRunning.Unraid == nil || stillRunning.Unraid.SyncAction != "check" {
+ t.Fatalf("active check cleared before reporting lease expired: %+v", stillRunning.Unraid)
+ }
+ if !issue1485HasAlertType(monitor.alertManager, "storage-topology") {
+ t.Fatal("active check alert cleared before reporting lease expired")
+ }
+
+ expiredAt := running.LastSeen.Add(hostAgentHealthWindow(running.IntervalSeconds) + time.Second)
+ monitor.evaluateHostAgents(expiredAt)
+
+ expired, ok := monitor.hostByID(running.ID)
+ if !ok {
+ t.Fatal("expired host missing")
+ }
+ if expired.Status != "offline" {
+ t.Fatalf("status = %q, want offline", expired.Status)
+ }
+ assertIssue1485Idle(t, monitor, expired)
+ if issue1485HasAlertType(monitor.alertManager, "host-offline") {
+ t.Fatal("connectivity alert activated before confirmation window")
+ }
+ monitor.evaluateHostAgents(expiredAt.Add(time.Second))
+ monitor.evaluateHostAgents(expiredAt.Add(2 * time.Second))
+ if !issue1485HasAlertType(monitor.alertManager, "host-offline") {
+ t.Fatal("telemetry loss was hidden instead of becoming a connectivity alert")
+ }
+ })
+
+ t.Run("server restart preserves order and expires persisted state", func(t *testing.T) {
+ dataDir := t.TempDir()
+ first := newIssue1485Monitor(t, dataDir)
+ runningBeforeRestart, err := first.ApplyHostReport(issue1485Report(base, "stream-a", 1, "check", 25), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !issue1485HasAlertType(first.alertManager, "storage-topology") {
+ t.Fatal("running alert missing before restart")
+ }
+ first.alertManager.Stop()
+
+ restarted := newIssue1485Monitor(t, dataDir)
+ if !issue1485HasAlertType(restarted.alertManager, "storage-topology") {
+ t.Fatal("active alert was not restored for restart proof")
+ }
+ staleBeforeFresh, err := restarted.ApplyHostReport(issue1485Report(base.Add(-time.Second), "stream-a", 1, "check", 10), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !staleBeforeFresh.LastSeen.Equal(runningBeforeRestart.LastSeen) {
+ t.Fatalf("stale restart report extended accepted telemetry lease: got %v want %v", staleBeforeFresh.LastSeen, runningBeforeRestart.LastSeen)
+ }
+ if !issue1485HasAlertType(restarted.alertManager, "storage-topology") {
+ t.Fatal("stale restart report prematurely cleared a genuinely active check")
+ }
+ idle, err := restarted.ApplyHostReport(issue1485Report(base.Add(time.Second), "stream-a", 2, "", 0), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertIssue1485Idle(t, restarted, idle)
+ stale, err := restarted.ApplyHostReport(issue1485Report(base, "stream-a", 1, "check", 25), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertIssue1485Idle(t, restarted, stale)
+
+ // A separate restart with no reconnect must wait for the reporting
+ // lease, then retire persisted task evidence and raise connectivity.
+ gapDir := t.TempDir()
+ beforeGap := newIssue1485Monitor(t, gapDir)
+ gapRunning, err := beforeGap.ApplyHostReport(issue1485Report(base, "stream-gap", 1, "check", 25), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ beforeGap.alertManager.Stop()
+ afterGap := newIssue1485Monitor(t, gapDir)
+ expiredAt := gapRunning.LastSeen.Add(hostAgentHealthWindow(gapRunning.IntervalSeconds) + time.Second)
+ afterGap.evaluateHostAgents(expiredAt)
+ if issue1485HasAlertType(afterGap.alertManager, "storage-topology") {
+ t.Fatal("persisted Unraid alert survived the reporting lease")
+ }
+ afterGap.evaluateHostAgents(expiredAt.Add(time.Second))
+ afterGap.evaluateHostAgents(expiredAt.Add(2 * time.Second))
+ if !issue1485HasAlertType(afterGap.alertManager, "host-offline") {
+ t.Fatal("restart continuity did not surface telemetry loss")
+ }
+ })
+}
+
+func TestIssue1485LegacyReportOrderingAllowsClockEpochReset(t *testing.T) {
+ monitor := newIssue1485Monitor(t, t.TempDir())
+ base := time.Date(2026, 7, 23, 12, 0, 0, 0, time.UTC)
+ report := issue1485Report(base, "", 0, "check", 10)
+ report.SequenceID = ""
+ report.Agent.IntervalSeconds = 30
+
+ order, accepted := monitor.reserveHostReportOrder("legacy-host", report, base.Add(time.Second))
+ if !accepted {
+ t.Fatal("first legacy report rejected")
+ }
+
+ report.Timestamp = base.Add(time.Second)
+ order, accepted = monitor.reserveHostReportOrder("legacy-host", report, base.Add(30*time.Second))
+ if !accepted {
+ t.Fatal("newer legacy report rejected")
+ }
+
+ report.Timestamp = base
+ if _, accepted = monitor.reserveHostReportOrder("legacy-host", report, base.Add(31*time.Second)); accepted {
+ t.Fatal("reconnect-burst legacy report was accepted out of order")
+ }
+
+ report.Timestamp = base.Add(-time.Hour)
+ order, accepted = monitor.reserveHostReportOrder("legacy-host", report, base.Add(time.Minute))
+ if !accepted {
+ t.Fatal("legacy clock epoch reset was rejected after a normal report interval")
+ }
+ if !order.ObservedAt.Equal(report.Timestamp) {
+ t.Fatalf("clock-reset watermark = %v, want %v", order.ObservedAt, report.Timestamp)
+ }
+}
+
+func TestIssue1485RejectedReportCannotRegressReceiptLiveness(t *testing.T) {
+ monitor := newIssue1485Monitor(t, t.TempDir())
+ base := time.Date(2026, 7, 23, 12, 0, 0, 0, time.UTC)
+
+ newer := issue1485Report(base.Add(2*time.Second), "stream-a", 2, "", 0)
+ order, accepted := monitor.reserveHostReportOrder("unraid-host", newer, base.Add(20*time.Second))
+ if !accepted {
+ t.Fatal("newer report rejected")
+ }
+
+ older := issue1485Report(base.Add(time.Second), "stream-a", 1, "check", 20)
+ order, accepted = monitor.reserveHostReportOrder("unraid-host", older, base.Add(10*time.Second))
+ if accepted {
+ t.Fatal("older report accepted")
+ }
+ if want := base.Add(20 * time.Second); !order.LastReceivedAt.Equal(want) {
+ t.Fatalf("receipt liveness regressed to %v, want %v", order.LastReceivedAt, want)
+ }
+}
+
+func TestIssue1485HostReportApplicationIsSerializedPerHost(t *testing.T) {
+ monitor := newIssue1485Monitor(t, t.TempDir())
+ unlockFirst := monitor.lockHostReportApplication("unraid-host")
+
+ attempting := make(chan struct{})
+ acquired := make(chan struct{})
+ released := make(chan struct{})
+ go func() {
+ close(attempting)
+ unlockSecond := monitor.lockHostReportApplication("unraid-host")
+ close(acquired)
+ unlockSecond()
+ close(released)
+ }()
+ <-attempting
+
+ select {
+ case <-acquired:
+ t.Fatal("second report application acquired the same-host lock early")
+ case <-time.After(50 * time.Millisecond):
+ }
+
+ unlockFirst()
+ select {
+ case <-released:
+ case <-time.After(time.Second):
+ t.Fatal("second report application did not proceed after the first completed")
+ }
+
+ monitor.hostReportApplyLocksMu.Lock()
+ remaining := len(monitor.hostReportApplyLocks)
+ monitor.hostReportApplyLocksMu.Unlock()
+ if remaining != 0 {
+ t.Fatalf("per-host report locks retained after release: %d", remaining)
+ }
+}
+
+func TestIssue1485NormalizesTerminalMDRAIDProgress(t *testing.T) {
+ monitor := newIssue1485Monitor(t, t.TempDir())
+ report := issue1485Report(time.Now().UTC(), "raid-stream", 1, "", 0)
+ report.Host.Platform = "linux"
+ report.Host.OSName = "Debian"
+ report.Unraid = nil
+ report.RAID = []agentshost.RAIDArray{{
+ Device: "/dev/md127",
+ Level: "raid1",
+ State: "active",
+ TotalDevices: 2,
+ ActiveDevices: 2,
+ WorkingDevices: 2,
+ Operation: "",
+ RebuildPercent: 100,
+ RebuildSpeed: "100M/sec",
+ }}
+
+ host, err := monitor.ApplyHostReport(report, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(host.RAID) != 1 {
+ t.Fatalf("RAID arrays = %d, want 1", len(host.RAID))
+ }
+ array := host.RAID[0]
+ if array.Operation != "" || array.RebuildPercent != 0 || array.RebuildSpeed != "" {
+ t.Fatalf("terminal RAID operation retained transient state: %+v", array)
+ }
+}
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 4df5f96b67..4de81e74a4 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -1139,6 +1139,10 @@ type Monitor struct {
kubernetesTokenBindings map[string]string // Track token ID -> agent ID bindings to enforce uniqueness
removedHostAgents map[string]time.Time // Track deliberately removed host agents (ID -> removal time)
hostTokenBindings map[string]string // Track tokenID:hostname -> host identity bindings
+ hostReportApplyLocksMu sync.Mutex
+ hostReportApplyLocks map[string]*hostReportApplyLock
+ hostReportOrderMu sync.Mutex
+ hostReportOrders map[string]hostReportOrder
dockerCommands map[string]*dockerHostCommand
dockerCommandIndex map[string]string
guestMetadataMu sync.RWMutex
@@ -1700,6 +1704,8 @@ func New(cfg *config.Config) (*Monitor, error) {
kubernetesTokenBindings: make(map[string]string),
removedHostAgents: make(map[string]time.Time),
hostTokenBindings: make(map[string]string),
+ hostReportApplyLocks: make(map[string]*hostReportApplyLock),
+ hostReportOrders: make(map[string]hostReportOrder),
clusterSensorsCache: make(map[string]clusterSensorsCacheEntry),
dockerCommands: make(map[string]*dockerHostCommand),
dockerCommandIndex: make(map[string]string),
diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.go
index aa0cbc23eb..a5857748ed 100644
--- a/internal/monitoring/monitor_agents.go
+++ b/internal/monitoring/monitor_agents.go
@@ -5,6 +5,7 @@ import (
"encoding/hex"
"fmt"
"strings"
+ "sync"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/agentupdate"
@@ -25,6 +26,163 @@ import (
const hostContinuityRetention = 72 * time.Hour
+const maxRetiredHostReportStreams = 8
+
+type hostReportOrder struct {
+ ObservedAt time.Time
+ LastReceivedAt time.Time
+ StreamID string
+ Sequence uint64
+ RetiredStreamIDs []string
+}
+
+type hostReportApplyLock struct {
+ mu sync.Mutex
+ refs int
+}
+
+func hostReportOrderFromContinuity(entry config.HostContinuityEntry) hostReportOrder {
+ lastReceivedAt := entry.ReportLastReceivedAt.UTC()
+ if lastReceivedAt.IsZero() {
+ lastReceivedAt = entry.LastSeen.UTC()
+ }
+ return hostReportOrder{
+ ObservedAt: entry.ReportObservedAt.UTC(),
+ LastReceivedAt: lastReceivedAt,
+ StreamID: strings.TrimSpace(entry.ReportStreamID),
+ Sequence: entry.ReportSequence,
+ RetiredStreamIDs: append([]string(nil), entry.RetiredReportStreamIDs...),
+ }
+}
+
+func containsHostReportStream(streams []string, target string) bool {
+ target = strings.TrimSpace(target)
+ for _, stream := range streams {
+ if strings.TrimSpace(stream) == target {
+ return true
+ }
+ }
+ return false
+}
+
+func retireHostReportStream(streams []string, streamID string) []string {
+ streamID = strings.TrimSpace(streamID)
+ if streamID == "" || containsHostReportStream(streams, streamID) {
+ return streams
+ }
+ streams = append(streams, streamID)
+ if len(streams) > maxRetiredHostReportStreams {
+ streams = append([]string(nil), streams[len(streams)-maxRetiredHostReportStreams:]...)
+ }
+ return streams
+}
+
+func legacyHostReportReorderWindow(intervalSeconds int) time.Duration {
+ window := time.Duration(intervalSeconds) * time.Second / 2
+ if window < 2*time.Second {
+ return 2 * time.Second
+ }
+ if window > 15*time.Second {
+ return 15 * time.Second
+ }
+ return window
+}
+
+// lockHostReportApplication serializes the complete state transition for one
+// host while allowing different hosts to ingest concurrently. Reserving a
+// sequence number without holding this lock through the subsequent state write
+// would still allow two HTTP handlers to commit reports in reverse order.
+func (m *Monitor) lockHostReportApplication(hostID string) func() {
+ hostID = strings.TrimSpace(hostID)
+
+ m.hostReportApplyLocksMu.Lock()
+ if m.hostReportApplyLocks == nil {
+ m.hostReportApplyLocks = make(map[string]*hostReportApplyLock)
+ }
+ applyLock := m.hostReportApplyLocks[hostID]
+ if applyLock == nil {
+ applyLock = &hostReportApplyLock{}
+ m.hostReportApplyLocks[hostID] = applyLock
+ }
+ applyLock.refs++
+ m.hostReportApplyLocksMu.Unlock()
+
+ applyLock.mu.Lock()
+ return func() {
+ applyLock.mu.Unlock()
+ m.hostReportApplyLocksMu.Lock()
+ applyLock.refs--
+ if applyLock.refs == 0 && m.hostReportApplyLocks[hostID] == applyLock {
+ delete(m.hostReportApplyLocks, hostID)
+ }
+ m.hostReportApplyLocksMu.Unlock()
+ }
+}
+
+// reserveHostReportOrder separates source-authored ordering from transport
+// activity. Receipt time always records authenticated contact, while only a
+// non-retired, increasing report stream may replace telemetry and generate
+// metrics, history, or alerts.
+func (m *Monitor) reserveHostReportOrder(hostID string, report agentshost.Report, receivedAt time.Time) (hostReportOrder, bool) {
+ hostID = strings.TrimSpace(hostID)
+ authoredAt := report.Timestamp.UTC()
+ if authoredAt.IsZero() {
+ authoredAt = receivedAt.UTC()
+ }
+
+ m.hostReportOrderMu.Lock()
+ defer m.hostReportOrderMu.Unlock()
+
+ if m.hostReportOrders == nil {
+ m.hostReportOrders = make(map[string]hostReportOrder)
+ }
+ order, exists := m.hostReportOrders[hostID]
+ if !exists && m.hostContinuityStore != nil {
+ if entry, ok := m.hostContinuityStore.Get(hostID); ok {
+ order = hostReportOrderFromContinuity(entry)
+ }
+ }
+
+ streamID, sequence, sequenced := agentshost.ParseReportSequenceID(report.SequenceID)
+ accepted := true
+ switch {
+ case sequenced && containsHostReportStream(order.RetiredStreamIDs, streamID):
+ accepted = false
+ case sequenced && order.StreamID == streamID && sequence <= order.Sequence:
+ accepted = false
+ case sequenced && order.StreamID == streamID:
+ order.Sequence = sequence
+ order.ObservedAt = authoredAt
+ case sequenced:
+ order.RetiredStreamIDs = retireHostReportStream(order.RetiredStreamIDs, order.StreamID)
+ order.StreamID = streamID
+ order.Sequence = sequence
+ order.ObservedAt = authoredAt
+ default:
+ // Older agents have no process stream. Reject backwards timestamps only
+ // when they arrive in the reconnect burst; after a normal report
+ // interval, accept a clock epoch reset so a corrected host clock cannot
+ // freeze telemetry indefinitely.
+ if !order.ObservedAt.IsZero() &&
+ authoredAt.Before(order.ObservedAt) &&
+ !order.LastReceivedAt.IsZero() &&
+ receivedAt.Sub(order.LastReceivedAt) <= legacyHostReportReorderWindow(report.Agent.IntervalSeconds) {
+ accepted = false
+ } else {
+ order.RetiredStreamIDs = retireHostReportStream(order.RetiredStreamIDs, order.StreamID)
+ order.StreamID = ""
+ order.Sequence = 0
+ order.ObservedAt = authoredAt
+ }
+ }
+
+ if receivedAt.After(order.LastReceivedAt) {
+ order.LastReceivedAt = receivedAt.UTC()
+ }
+ m.hostReportOrders[hostID] = order
+ return order, accepted
+}
+
func (m *Monitor) RemoveDockerHost(hostID string) (models.DockerHost, error) {
hostID = strings.TrimSpace(hostID)
if hostID == "" {
@@ -252,6 +410,9 @@ func (m *Monitor) RemoveHostAgent(hostID string) (models.Host, error) {
m.alertManager.HandleHostRemoved(host)
}
m.removeHostContinuity(hostID)
+ m.hostReportOrderMu.Lock()
+ delete(m.hostReportOrders, hostID)
+ m.hostReportOrderMu.Unlock()
return host, nil
}
@@ -892,26 +1053,35 @@ func (m *Monitor) MatchHostConfigContinuity(agentID, tokenID string) (models.Hos
return models.Host{}, false
}
-func (m *Monitor) persistHostContinuity(host models.Host, report agentshost.Report) {
+func (m *Monitor) persistHostContinuity(host models.Host, report agentshost.Report, order hostReportOrder) {
if m == nil || m.hostContinuityStore == nil {
return
}
entry := config.HostContinuityEntry{
- HostID: strings.TrimSpace(host.ID),
- ReportHostID: strings.TrimSpace(report.Host.ID),
- AgentReportedID: strings.TrimSpace(report.Agent.ID),
- Hostname: strings.TrimSpace(host.Hostname),
- DisplayName: strings.TrimSpace(host.DisplayName),
- MachineID: strings.TrimSpace(host.MachineID),
- TokenID: strings.TrimSpace(host.TokenID),
- AgentVersion: strings.TrimSpace(host.AgentVersion),
- Platform: strings.TrimSpace(host.Platform),
- LinkedNodeID: strings.TrimSpace(host.LinkedNodeID),
- LinkedVMID: strings.TrimSpace(host.LinkedVMID),
- LinkedContainerID: strings.TrimSpace(host.LinkedContainerID),
- IsLegacy: host.IsLegacy,
- LastSeen: host.LastSeen.UTC(),
+ HostID: strings.TrimSpace(host.ID),
+ ReportHostID: strings.TrimSpace(report.Host.ID),
+ AgentReportedID: strings.TrimSpace(report.Agent.ID),
+ Hostname: strings.TrimSpace(host.Hostname),
+ DisplayName: strings.TrimSpace(host.DisplayName),
+ MachineID: strings.TrimSpace(host.MachineID),
+ TokenID: strings.TrimSpace(host.TokenID),
+ AgentVersion: strings.TrimSpace(host.AgentVersion),
+ Platform: strings.TrimSpace(host.Platform),
+ LinkedNodeID: strings.TrimSpace(host.LinkedNodeID),
+ LinkedVMID: strings.TrimSpace(host.LinkedVMID),
+ LinkedContainerID: strings.TrimSpace(host.LinkedContainerID),
+ IsLegacy: host.IsLegacy,
+ LastSeen: host.LastSeen.UTC(),
+ IntervalSeconds: host.IntervalSeconds,
+ ReportObservedAt: order.ObservedAt.UTC(),
+ ReportLastReceivedAt: order.LastReceivedAt.UTC(),
+ ReportStreamID: strings.TrimSpace(order.StreamID),
+ ReportSequence: order.Sequence,
+ RetiredReportStreamIDs: append(
+ []string(nil),
+ order.RetiredStreamIDs...,
+ ),
}
if err := m.hostContinuityStore.Upsert(entry); err != nil {
log.Warn().
@@ -921,6 +1091,63 @@ func (m *Monitor) persistHostContinuity(host models.Host, report agentshost.Repo
}
}
+func (m *Monitor) hostByID(hostID string) (models.Host, bool) {
+ for _, host := range m.state.GetHosts() {
+ if host.ID == hostID {
+ return host, true
+ }
+ }
+ return models.Host{}, false
+}
+
+func (m *Monitor) applyRejectedHostReportLiveness(
+ hostID string,
+ report agentshost.Report,
+ receivedAt time.Time,
+ order hostReportOrder,
+) models.Host {
+ host, exists := m.hostByID(hostID)
+ if !exists {
+ if m.hostContinuityStore != nil {
+ if entry, ok := m.hostContinuityStore.Get(hostID); ok {
+ host = hostFromContinuityEntry(entry)
+ }
+ }
+ if host.ID == "" {
+ host = models.Host{
+ ID: hostID,
+ Hostname: strings.TrimSpace(report.Host.Hostname),
+ DisplayName: strings.TrimSpace(report.Host.DisplayName),
+ Platform: platformsupport.NormalizeAgentReportedPlatform(report.Host.Platform),
+ AgentVersion: strings.TrimSpace(report.Agent.Version),
+ MachineID: strings.TrimSpace(report.Host.MachineID),
+ }
+ }
+ if host.IntervalSeconds <= 0 {
+ host.IntervalSeconds = report.Agent.IntervalSeconds
+ }
+ if host.LastSeen.IsZero() ||
+ receivedAt.Sub(host.LastSeen) > hostAgentHealthWindow(host.IntervalSeconds) {
+ host.Status = "offline"
+ }
+ m.state.UpsertHost(host)
+ }
+
+ // An authenticated arrival proves the transport is reachable, but a report
+ // rejected by the authored-state watermark must not extend Host.LastSeen,
+ // clear an offline alert, or renew the accepted telemetry lease.
+ m.state.SetConnectionHealth(hostConnectionPrefix+host.ID, true)
+ m.persistHostContinuity(host, report, order)
+ m.refreshUnifiedResourceStoreAfterAgentReport()
+
+ log.Debug().
+ Str("hostID", host.ID).
+ Str("sequenceId", report.SequenceID).
+ Time("reportTimestamp", report.Timestamp).
+ Msg("Ignored stale or duplicate host report state while refreshing receipt-time liveness")
+ return host
+}
+
func (m *Monitor) removeHostContinuity(hostID string) {
if m == nil || m.hostContinuityStore == nil {
return
@@ -967,6 +1194,7 @@ func hostFromContinuityEntry(entry config.HostContinuityEntry) models.Host {
TokenID: strings.TrimSpace(entry.TokenID),
Platform: platformsupport.NormalizeAgentReportedPlatform(entry.Platform),
IsLegacy: entry.IsLegacy,
+ IntervalSeconds: entry.IntervalSeconds,
LinkedNodeID: strings.TrimSpace(entry.LinkedNodeID),
LinkedVMID: strings.TrimSpace(entry.LinkedVMID),
LinkedContainerID: strings.TrimSpace(entry.LinkedContainerID),
@@ -1931,6 +2159,23 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
return models.Host{}, fmt.Errorf("host agent %q had monitoring stopped at %v and cannot report again. Re-enroll by reinstalling the agent with a newly generated API token, or wait for the block to clear 24 hours after removal", identifier, removedAt.Format(time.RFC3339))
}
+ unlockHostReport := m.lockHostReportApplication(identifier)
+ defer unlockHostReport()
+
+ // Identity resolution happens before taking the per-host lock. Refresh the
+ // shared read model after waiting so token inheritance and previous-state
+ // comparisons use the latest accepted report, not the pre-wait snapshot.
+ readState = m.snapshotBackedUnifiedReadState()
+ existingHosts = nil
+ if readState != nil {
+ existingHosts = readState.Hosts()
+ }
+
+ reportOrder, accepted := m.reserveHostReportOrder(identifier, report, receivedAt)
+ if !accepted {
+ return m.applyRejectedHostReportLiveness(identifier, report, receivedAt, reportOrder), nil
+ }
+
var previous *unifiedresources.HostView
var hasPrevious bool
for _, candidate := range existingHosts {
@@ -2036,6 +2281,13 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
Slot: dev.Slot,
})
}
+ operation := strings.TrimSpace(array.Operation)
+ rebuildPercent := safeFloat(array.RebuildPercent)
+ rebuildSpeed := strings.TrimSpace(array.RebuildSpeed)
+ if operation == "" {
+ rebuildPercent = 0
+ rebuildSpeed = ""
+ }
raid = append(raid, models.HostRAIDArray{
Device: array.Device,
Name: array.Name,
@@ -2048,9 +2300,9 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
SpareDevices: array.SpareDevices,
UUID: array.UUID,
Devices: devices,
- RebuildPercent: array.RebuildPercent,
- RebuildSpeed: array.RebuildSpeed,
- Operation: array.Operation,
+ RebuildPercent: rebuildPercent,
+ RebuildSpeed: rebuildSpeed,
+ Operation: operation,
})
}
@@ -2094,11 +2346,16 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
Slot: disk.Slot,
})
}
+ syncAction := strings.TrimSpace(report.Unraid.SyncAction)
+ syncProgress := safeFloat(report.Unraid.SyncProgress)
+ if syncAction == "" {
+ syncProgress = 0
+ }
unraidData = &models.HostUnraidStorage{
ArrayStarted: report.Unraid.ArrayStarted,
ArrayState: strings.TrimSpace(report.Unraid.ArrayState),
- SyncAction: strings.TrimSpace(report.Unraid.SyncAction),
- SyncProgress: report.Unraid.SyncProgress,
+ SyncAction: syncAction,
+ SyncProgress: syncProgress,
SyncErrors: report.Unraid.SyncErrors,
NumProtected: report.Unraid.NumProtected,
NumDisabled: report.Unraid.NumDisabled,
@@ -2368,7 +2625,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
// Store cluster peer sensor data if present and evict stale entries
m.applyClusterSensors(report.ClusterSensors, observedAt)
- m.persistHostContinuity(host, report)
+ m.persistHostContinuity(host, report, reportOrder)
m.refreshUnifiedResourceStoreAfterAgentReport()
return host, nil
@@ -3364,22 +3621,28 @@ func (m *Monitor) evaluateDockerAgents(now time.Time) {
}
}
+func hostAgentHealthWindow(interval int) time.Duration {
+ if interval <= 0 {
+ interval = int(hostMinimumHealthWindow / time.Second)
+ }
+ window := time.Duration(interval) * time.Second * hostOfflineGraceMultiplier
+ if window < hostMinimumHealthWindow {
+ return hostMinimumHealthWindow
+ }
+ if window > hostMaximumHealthWindow {
+ return hostMaximumHealthWindow
+ }
+ return window
+}
+
// evaluateHostAgents updates health for host agents based on last report time.
func (m *Monitor) evaluateHostAgents(now time.Time) {
hosts := m.state.GetHosts()
+ liveHostIDs := make(map[string]struct{}, len(hosts))
+ resourceRefreshNeeded := false
for _, host := range hosts {
- interval := host.IntervalSeconds
- if interval <= 0 {
- interval = int(hostMinimumHealthWindow / time.Second)
- }
-
- window := time.Duration(interval) * time.Second * hostOfflineGraceMultiplier
- if window < hostMinimumHealthWindow {
- window = hostMinimumHealthWindow
- } else if window > hostMaximumHealthWindow {
- window = hostMaximumHealthWindow
- }
-
+ liveHostIDs[host.ID] = struct{}{}
+ window := hostAgentHealthWindow(host.IntervalSeconds)
age := now.Sub(host.LastSeen)
healthy := !host.LastSeen.IsZero() && age <= window
key := hostConnectionPrefix + host.ID
@@ -3397,12 +3660,14 @@ func (m *Monitor) evaluateHostAgents(now time.Time) {
Dur("window", window).
Msg("Host agent back online")
}
- m.state.SetHostStatus(host.ID, "online")
+ if host.Status != "online" {
+ m.state.SetHostStatus(host.ID, "online")
+ resourceRefreshNeeded = true
+ }
if m.alertManager != nil {
m.alertManager.HandleHostOnline(hostCopy)
}
} else {
- hostCopy.Status = "offline"
// Log status transition from online to offline with diagnostic info
if host.Status == "online" || host.Status == "" {
log.Debug().
@@ -3415,12 +3680,42 @@ func (m *Monitor) evaluateHostAgents(now time.Time) {
Bool("lastSeenZero", host.LastSeen.IsZero()).
Msg("Host agent appears offline")
}
- m.state.SetHostStatus(host.ID, "offline")
+ if expiredHost, changed := m.state.ExpireHostTelemetry(host.ID); expiredHost.ID != "" {
+ hostCopy = expiredHost
+ resourceRefreshNeeded = resourceRefreshNeeded || changed
+ } else {
+ hostCopy.Status = "offline"
+ }
if m.alertManager != nil {
m.alertManager.HandleHostOffline(hostCopy)
}
}
}
+
+ // Active alerts survive process restarts, while the live host snapshot does
+ // not. Continuity entries provide the durable receipt timestamp needed to
+ // expire those alerts after the same reporting lease, even if the agent
+ // never reconnects.
+ for _, entry := range m.recentStandaloneHostContinuityEntries() {
+ if _, live := liveHostIDs[entry.HostID]; live {
+ continue
+ }
+ window := hostAgentHealthWindow(entry.IntervalSeconds)
+ healthy := !entry.LastSeen.IsZero() && now.Sub(entry.LastSeen) <= window
+ m.state.SetConnectionHealth(hostConnectionPrefix+entry.HostID, healthy)
+ if healthy {
+ continue
+ }
+ host := hostFromContinuityEntry(entry)
+ host.Status = "offline"
+ if m.alertManager != nil {
+ m.alertManager.HandleHostOffline(host)
+ }
+ }
+
+ if resourceRefreshNeeded {
+ m.refreshUnifiedResourceStoreAfterAgentReport()
+ }
}
// sortContent sorts comma-separated content values for consistent display
diff --git a/pkg/agents/host/report.go b/pkg/agents/host/report.go
index 2cc81f50a7..c2b3ef98e7 100644
--- a/pkg/agents/host/report.go
+++ b/pkg/agents/host/report.go
@@ -1,11 +1,46 @@
package host
import (
+ "fmt"
+ "strconv"
+ "strings"
"time"
"github.com/rcourtman/pulse-go-rewrite/pkg/diskinventory"
)
+const reportSequenceVersion = "v1"
+
+// FormatReportSequenceID returns the opaque report-ordering token carried by a
+// single agent process. The stream ID changes when the agent restarts and the
+// sequence increases for every report collected by that process.
+func FormatReportSequenceID(streamID string, sequence uint64) string {
+ streamID = strings.TrimSpace(streamID)
+ if streamID == "" || sequence == 0 || strings.Contains(streamID, ":") {
+ return ""
+ }
+ return fmt.Sprintf("%s:%s:%d", reportSequenceVersion, streamID, sequence)
+}
+
+// ParseReportSequenceID decodes sequence IDs produced by
+// FormatReportSequenceID. Unknown formats remain valid opaque wire values but
+// are not used for ordering by current servers.
+func ParseReportSequenceID(value string) (streamID string, sequence uint64, ok bool) {
+ parts := strings.Split(strings.TrimSpace(value), ":")
+ if len(parts) != 3 || parts[0] != reportSequenceVersion {
+ return "", 0, false
+ }
+ streamID = strings.TrimSpace(parts[1])
+ if streamID == "" {
+ return "", 0, false
+ }
+ sequence, err := strconv.ParseUint(parts[2], 10, 64)
+ if err != nil || sequence == 0 {
+ return "", 0, false
+ }
+ return streamID, sequence, true
+}
+
// Report represents the payload sent by the host module of pulse-agent.
type Report struct {
Agent AgentInfo `json:"agent"`
diff --git a/pkg/agents/host/report_test.go b/pkg/agents/host/report_test.go
index 9e48287684..139f665e89 100644
--- a/pkg/agents/host/report_test.go
+++ b/pkg/agents/host/report_test.go
@@ -16,6 +16,23 @@ func TestLegacyReportJSONDefaultsOperationReceiptProtocolUnsupported(t *testing.
}
}
+func TestReportSequenceIDRoundTrip(t *testing.T) {
+ value := FormatReportSequenceID("0123456789abcdef", 42)
+ if value != "v1:0123456789abcdef:42" {
+ t.Fatalf("FormatReportSequenceID() = %q", value)
+ }
+ streamID, sequence, ok := ParseReportSequenceID(value)
+ if !ok || streamID != "0123456789abcdef" || sequence != 42 {
+ t.Fatalf("ParseReportSequenceID() = (%q, %d, %v)", streamID, sequence, ok)
+ }
+
+ for _, invalid := range []string{"", "legacy", "v2:stream:1", "v1::1", "v1:stream:0", "v1:stream:not-a-number"} {
+ if _, _, ok := ParseReportSequenceID(invalid); ok {
+ t.Fatalf("ParseReportSequenceID(%q) unexpectedly succeeded", invalid)
+ }
+ }
+}
+
func float64Ptr(value float64) *float64 {
return &value
}