From 9c19c1b56df1235b4e69563ef485f4438d764622 Mon Sep 17 00:00:00 2001 From: "pulse-triage[bot]" <249995291+pulse-triage[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:56:59 +0000 Subject: [PATCH] Discard superseded watchdog alerts before manager admission Fence standing raises at the alert manager lock so queued alerts cannot record an obsolete firing or dispatch after watchdog recovery or saved removal. Keep restart history, independent external signals and ownership through teardown. Contract-Neutral: Restores the existing watchdog latest-standing-condition rule at internal alert admission; public status, alert identity, restart history and delivery policy are unchanged. Change-source: pulse-maintainer --- .../v6/internal/subsystems/monitoring.md | 10 +- internal/alerts/system_alert.go | 16 +- internal/monitoring/deadman.go | 38 +-- .../monitoring/deadman_alert_projection.go | 48 +++- .../monitoring/deadman_projection_test.go | 231 ++++++++++++++++++ internal/monitoring/deadman_test.go | 22 ++ 6 files changed, 338 insertions(+), 27 deletions(-) create mode 100644 internal/monitoring/deadman_projection_test.go diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md index bd920ee180..54c5118e2a 100644 --- a/docs/release-control/v6/internal/subsystems/monitoring.md +++ b/docs/release-control/v6/internal/subsystems/monitoring.md @@ -9282,7 +9282,9 @@ agent intake, or per-provider success. Ordinary idle time and provider backoff do not stop the loop's marker. HTTP liveness remains independent. The external sender never waits for the alert manager to raise, refresh, or clear a local watchdog alert. A single, bounded projection worker reconciles -the latest standing condition and retains the restart observation for local +the latest standing condition. Recovery or a saved destination change makes +an obsolete raise ineligible even if it has left the queue and is waiting +for alert-manager admission. A real restart observation still goes to local history, even when the same signal reports recovery. Tenant shutdown cancels the sender and joins this projection before releasing the alert store. Every DNS answer is compared with all Pulse host interface addresses before @@ -9307,7 +9309,11 @@ manager lock while a fixture receiver accepts the first and later failure signals and the recovery report. It verifies the durable restart gap, local history and final alert state after release. Configuration tests verify that a saved removal cancels an active request under the same lock pressure, and -that a superseded snapshot cannot start a request. +that a superseded snapshot cannot start a request or queue a new stall. +`TestDeadManStandingAlertAdmission` waits for the stall raise to leave the +queue while holding the real alert-manager lock. Recovery and saved removal +each prevent obsolete history, firing and delivery callbacks, and a webhook +attempt. The same path still records and delivers a current stall. ### Agent removal keeps credential truth continuous across restart diff --git a/internal/alerts/system_alert.go b/internal/alerts/system_alert.go index 5bd11fffa3..4e1d7055c0 100644 --- a/internal/alerts/system_alert.go +++ b/internal/alerts/system_alert.go @@ -1,10 +1,10 @@ package alerts import ( - "github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog" "strings" "time" + "github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog" "github.com/rs/zerolog/log" ) @@ -91,6 +91,14 @@ func IsSystemAlert(alert *Alert) bool { // // It reports whether this call raised the alert or changed it. func (m *Manager) RaiseSystemAlert(input SystemAlertInput) bool { + return m.RaiseSystemAlertUnlessSuperseded(input, nil) +} + +// RaiseSystemAlertUnlessSuperseded is for standing conditions that may be +// replaced while waiting for the manager. A closed superseded channel vetoes +// admission before any mutation, history or dispatch. A nil channel never +// vetoes. After admission, the normal alert lifecycle owns the occurrence. +func (m *Manager) RaiseSystemAlertUnlessSuperseded(input SystemAlertInput, superseded <-chan struct{}) bool { alertType := strings.TrimSpace(input.Type) if alertType == "" { return false @@ -99,6 +107,12 @@ func (m *Manager) RaiseSystemAlert(input SystemAlertInput) bool { level := NormalizeAlertLevel(input.Level) m.mu.Lock() + select { + case <-superseded: + m.mu.Unlock() + return false + default: + } now := time.Now() existing, exists := m.getActiveAlertNoLock(alertID) diff --git a/internal/monitoring/deadman.go b/internal/monitoring/deadman.go index af2854704e..4f8d1dc748 100644 --- a/internal/monitoring/deadman.go +++ b/internal/monitoring/deadman.go @@ -227,7 +227,7 @@ func (d *deadManRuntime) runCycle( } if err := notifications.ValidateDeadManPingURL(endpoint); err != nil { - d.setMisconfigured(err.Error()) + d.setMisconfigured(ctx, err.Error()) return } fingerprint := deadManEndpointFingerprint(endpoint) @@ -240,11 +240,10 @@ func (d *deadManRuntime) runCycle( fresh := !progress.IsZero() && !progress.After(now.Add(5*time.Second)) && now.Sub(progress) <= d.progressFreshness d.setMonitoringProgress(progress) if fresh { - d.recordHealthyProgress(progress) d.alertProjection.clear(alerts.DeadManMonitoringStalledAlertType) + d.recordHealthyProgress(progress) } else { - d.setState("monitor_stalled", "Pulse monitoring loop has stopped making progress") - d.raiseMonitoringStalled(progress) + d.raiseMonitoringStalled(ctx, progress) } message := "" @@ -459,26 +458,22 @@ func (d *deadManRuntime) setAttempt(at time.Time) { d.mu.Unlock() } -func (d *deadManRuntime) setState(state, message string) { - d.mu.Lock() - d.status.State = state - d.status.LastError = message - d.mu.Unlock() -} - func (d *deadManRuntime) pendingInterruption() *DeadManInterruption { d.mu.RLock() defer d.mu.RUnlock() return cloneDeadManInterruption(d.pendingGap) } -func (d *deadManRuntime) setMisconfigured(message string) { +func (d *deadManRuntime) setMisconfigured(ctx context.Context, message string) { d.mu.Lock() + defer d.mu.Unlock() + if d.stopping || ctx.Err() != nil { + return + } d.status.Configured = true d.status.State = "misconfigured" d.status.LastError = message d.status.ConsecutiveFailures = 0 - d.mu.Unlock() d.alertProjection.raise(alerts.SystemAlertInput{ Type: alerts.DeadManDeliveryAlertType, Level: alerts.AlertLevelWarning, @@ -489,8 +484,8 @@ func (d *deadManRuntime) setMisconfigured(message string) { func (d *deadManRuntime) recordSignalFailure(ctx context.Context, message string) { d.mu.Lock() + defer d.mu.Unlock() if d.stopping || ctx.Err() != nil { - d.mu.Unlock() return } d.consecutiveFail++ @@ -500,8 +495,6 @@ func (d *deadManRuntime) recordSignalFailure(ctx context.Context, message string } d.status.LastError = message failures := d.consecutiveFail - d.mu.Unlock() - if failures >= deadManDeliveryAlertThreshold { d.alertProjection.raise(alerts.SystemAlertInput{ Type: alerts.DeadManDeliveryAlertType, @@ -553,6 +546,10 @@ func (d *deadManRuntime) notifyConfigChanged() { d.activeSignalCancel() d.activeSignalCancel = nil } + // Destination-derived raises check their cycle's cancellation under this + // same lock before enqueueing. An old cycle cannot restore a raise we + // just revoked, even if it was computing progress when the save landed. + d.alertProjection.discardStandingRaises(alerts.DeadManMonitoringStalledAlertType, alerts.DeadManDeliveryAlertType) d.mu.Unlock() select { case d.wake <- struct{}{}: @@ -600,7 +597,14 @@ func (d *deadManRuntime) persistCurrentState() error { return persistDeadManState(d.statePath, state) } -func (d *deadManRuntime) raiseMonitoringStalled(progress time.Time) { +func (d *deadManRuntime) raiseMonitoringStalled(ctx context.Context, progress time.Time) { + d.mu.Lock() + defer d.mu.Unlock() + if d.stopping || ctx.Err() != nil { + return + } + d.status.State = "monitor_stalled" + d.status.LastError = "Pulse monitoring loop has stopped making progress" message := "Pulse's external watchdog is running, but the monitoring loop has stopped making progress." metadata := map[string]interface{}{} if !progress.IsZero() { diff --git a/internal/monitoring/deadman_alert_projection.go b/internal/monitoring/deadman_alert_projection.go index 23dbcb1bd3..984ca0fe71 100644 --- a/internal/monitoring/deadman_alert_projection.go +++ b/internal/monitoring/deadman_alert_projection.go @@ -12,13 +12,19 @@ import ( // There is at most one pending standing update per watchdog alert type, plus // a history observation for restart gaps and unreadable restart state. Those // observations must be recorded even if a later success has already cleared -// the condition. An update already in the manager finishes before its newer -// replacement, so delayed work cannot leave an old condition standing. +// the condition. A newer update can also revoke the one standing raise that +// has left the queue but has not yet been admitted by the manager. type deadManAlertProjection struct { - mu sync.Mutex - pending []deadManAlertUpdate - wake chan struct{} - closed bool + mu sync.Mutex + pending []deadManAlertUpdate + inFlight *deadManStandingRaise + wake chan struct{} + closed bool +} + +type deadManStandingRaise struct { + alertType string + superseded chan struct{} } type deadManAlertUpdate struct { @@ -45,6 +51,7 @@ func (p *deadManAlertProjection) submit(update deadManAlertUpdate) { if p.closed { return } + p.revokeInFlightLocked(update.alertType) p.pending = slices.DeleteFunc(p.pending, func(pending deadManAlertUpdate) bool { return pending.alertType == update.alertType && (!pending.history || update.history) }) @@ -55,6 +62,27 @@ func (p *deadManAlertProjection) submit(update deadManAlertUpdate) { } } +func (p *deadManAlertProjection) revokeInFlightLocked(alertType string) { + if p.inFlight != nil && p.inFlight.alertType == alertType { + close(p.inFlight.superseded) + p.inFlight = nil + } +} + +// discardStandingRaises invalidates old destination-dependent raises on a +// saved configuration change, without waiting for the next watchdog cycle. +// Clears and actual historical observations still belong to the worker. +func (p *deadManAlertProjection) discardStandingRaises(alertTypes ...string) { + p.mu.Lock() + defer p.mu.Unlock() + for _, alertType := range alertTypes { + p.revokeInFlightLocked(alertType) + } + p.pending = slices.DeleteFunc(p.pending, func(update deadManAlertUpdate) bool { + return update.raise != nil && !update.history && slices.Contains(alertTypes, update.alertType) + }) +} + // close stops admission and lets the worker finish the already accepted // projection before Monitor.Start releases ownership of the alert store. func (p *deadManAlertProjection) close() { @@ -75,15 +103,21 @@ func (p *deadManAlertProjection) run(manager *alerts.Manager) { func (p *deadManAlertProjection) drain(manager *alerts.Manager) { for { p.mu.Lock() + p.inFlight = nil // the sole worker has finished the preceding manager call if len(p.pending) == 0 { p.mu.Unlock() return } update := p.pending[0] p.pending = slices.Delete(p.pending, 0, 1) + var superseded <-chan struct{} + if update.raise != nil && !update.history { + p.inFlight = &deadManStandingRaise{alertType: update.alertType, superseded: make(chan struct{})} + superseded = p.inFlight.superseded + } p.mu.Unlock() if update.raise != nil { - manager.RaiseSystemAlert(*update.raise) + manager.RaiseSystemAlertUnlessSuperseded(*update.raise, superseded) } else { manager.ClearSystemAlert(update.alertType) } diff --git a/internal/monitoring/deadman_projection_test.go b/internal/monitoring/deadman_projection_test.go new file mode 100644 index 0000000000..22be7b740b --- /dev/null +++ b/internal/monitoring/deadman_projection_test.go @@ -0,0 +1,231 @@ +package monitoring + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/url" + "slices" + "sync/atomic" + "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/notifications" + "github.com/stretchr/testify/require" +) + +type deadManStandingFixtureResult struct { + Status DeadManStatus `json:"status"` + History []alerts.Alert `json:"history"` + Active []alerts.Alert `json:"active"` + FiringCallbacks int64 `json:"firingCallbacks"` + DeliveryCallbacks int64 `json:"deliveryCallbacks"` + WebhookDeliveries int64 `json:"webhookDeliveries"` +} + +func TestDeadManStandingAlertAdmission(t *testing.T) { + for _, tc := range []struct { + name, state string + wantStallCount int + }{ + {"recovered", "healthy", 0}, + {"removed", "disabled", 0}, + {"still-stalled", "monitor_stalled", 1}, + } { + t.Run(tc.name, func(t *testing.T) { + got := exerciseDeadManStandingAlert(t, tc.name) + const stall = alerts.DeadManMonitoringStalledAlertType + stallCount, restartCount := 0, 0 + for _, entry := range got.History { + switch entry.Type { + case stall: + stallCount++ + case alerts.DeadManInterruptionAlertType: + restartCount++ + } + } + require.NotNil(t, got.Status.LastInterruption) + require.EqualValues(t, 300, got.Status.LastInterruption.DurationSecs) + require.Equal(t, 1, restartCount, "real restart history") + require.Equal(t, tc.state, got.Status.State) + t.Logf("state=%s stall_history=%d restart_history=%d firing_callbacks=%d delivery_callbacks=%d webhook_receipts=%d", + got.Status.State, stallCount, restartCount, got.FiringCallbacks, got.DeliveryCallbacks, got.WebhookDeliveries) + // Stop() has joined both callback types. Final active state alone + // would miss the obsolete occurrence and its notification. + asserted := []int64{int64(stallCount), got.FiringCallbacks, got.DeliveryCallbacks, got.WebhookDeliveries} + require.Equal(t, []int64{int64(tc.wantStallCount), int64(tc.wantStallCount), int64(tc.wantStallCount), int64(tc.wantStallCount)}, + asserted, "stall history, firing callback, delivery callback, webhook receipt") + require.Len(t, got.Active, tc.wantStallCount) + }) + } +} + +func exerciseDeadManStandingAlert(t *testing.T, settle string) deadManStandingFixtureResult { + t.Helper() + start := time.Now().UTC().Truncate(time.Second) + const endpoint = "https://watchdog.example.com/ping/fixture" + const stall = alerts.DeadManMonitoringStalledAlertType + + type signal struct{ method, path, body string } + signals := make(chan signal, 4) + receiver := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + } + signals <- signal{r.Method, r.URL.Path, string(body)} + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(receiver.Close) + fixtureURL, err := url.Parse(receiver.URL) + require.NoError(t, err) + + var webhookDeliveries, firingCallbacks, deliveryCallbacks atomic.Int64 + webhook := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var payload struct{ Type string } + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil || payload.Type != stall { + t.Errorf("ordinary webhook must carry the stalled alert, type=%q err=%v", payload.Type, err) + } + webhookDeliveries.Add(1) + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(webhook.Close) + nm := notifications.NewNotificationManagerWithDeferredQueue("", t.TempDir()) + t.Cleanup(nm.Stop) + require.NoError(t, nm.UpdateAllowedPrivateCIDRs("127.0.0.1/32")) + nm.SetGroupingConfig(false, 0, false, false) + nm.AddWebhook(notifications.WebhookConfig{ID: "fixture", Name: "Fixture", Enabled: true, URL: webhook.URL, + Service: "generic", Template: `{"type":"{{.Type}}"}`}) + + am := alerts.NewManagerWithDataDir(t.TempDir(), alerts.WithoutPersistedAlertRestore()) + t.Cleanup(am.Stop) + am.UpdateConfig(alerts.AlertConfig{Enabled: true, ActivationState: alerts.ActivationActive}) + am.SubscribeAlertFiringCallback(func(a *alerts.Alert) { + if a.Type == stall { + firingCallbacks.Add(1) + } + }) + am.SetAlertCallback(func(a *alerts.Alert) { + if a.Type == stall { + deliveryCallbacks.Add(1) + nm.SendAlert(a) + } + }) + dir := t.TempDir() + require.NoError(t, persistDeadManState(dir+"/alerts/deadman-state.json", deadManPersistedState{ + SchemaVersion: deadManStateSchemaVersion, EndpointFingerprint: deadManEndpointFingerprint(endpoint), + Enabled: true, StartedAt: start.Add(-time.Hour), LastHealthyAt: start.Add(-5 * time.Minute), + })) + d := newDeadManRuntime(dir) + d.startupAt = start + d.retryDelays = nil + d.client = &http.Client{Timeout: time.Second, Transport: deadManRoundTripFunc(func(r *http.Request) (*http.Response, error) { + // Map only the synthetic authority to the test receiver. Production + // URL validation, host separation and transport settings are untouched. + if r.URL.Host != "watchdog.example.com" || r.URL.Scheme != "https" { + t.Errorf("unexpected authority: %s", r.URL.Host) + return deadManResponse(http.StatusBadRequest, ""), nil + } + request := r.Clone(r.Context()) + request.Host, request.URL.Host = "", fixtureURL.Host + return receiver.Client().Transport.RoundTrip(request) + })} + persistence := config.NewConfigPersistence(t.TempDir()) + initialConfig := notifications.DeadManConfig{PingURL: endpoint} + require.NoError(t, persistence.SaveDeadManConfig(initialConfig)) + m := &Monitor{deadMan: d, alertManager: am, configPersist: persistence, deadManConfig: initialConfig} + cycle := func(at, progress time.Time, path, body string) { + t.Helper() + d.now = func() time.Time { return at } + cycleDone := make(chan struct{}) + go func() { + defer close(cycleDone) + d.runCycle(context.Background(), func() string { return m.deadManConfigSnapshot().PingURL }, func() time.Time { return progress }) + }() + select { + case <-cycleDone: + case <-time.After(5 * time.Second): + t.Fatal("watchdog cycle did not settle independently of alert projection") + } + select { + case got := <-signals: + require.Equal(t, path, got.path) + if body == "" { + require.Equal(t, http.MethodGet, got.method) + require.Empty(t, got.body) + } else { + require.Equal(t, http.MethodPost, got.method) + require.Contains(t, got.body, body) + } + default: + t.Fatalf("watchdog signal not received: %s", path) + } + } + cycle(start, start, "/ping/fixture", "previous unexpected shutdown") + // Finish startup, so the next item to enter the manager is the stall, + // not a restart observation or an initial clear. + d.alertProjection.drain(am) + + unblock := holdDeadManAlertManager(t, am) + projected := make(chan struct{}) + go func() { + defer close(projected) + d.alertProjection.run(am) + }() + finish := func() { + d.alertProjection.close() + unblock() + <-projected + } + t.Cleanup(finish) + cycle(start.Add(time.Minute), start.Add(-2*time.Minute), "/ping/fixture/fail", "monitoring loop has stopped") + // No superseding updates have happened. Since the stall was queued + // before the fixture got /fail, its absence proves dequeue, while the + // real manager lock prevents any manager-side admission. + require.Eventually(t, func() bool { + p := &d.alertProjection + p.mu.Lock() + defer p.mu.Unlock() + return !slices.ContainsFunc(p.pending, func(update deadManAlertUpdate) bool { + return update.alertType == stall && update.raise != nil + }) + }, 3*time.Second, time.Millisecond, "standing raise did not leave the projection queue") + switch settle { + case "recovered": + recovered := start.Add(2 * time.Minute) + cycle(recovered, recovered, "/ping/fixture", "") + require.Equal(t, "healthy", m.DeadManStatus().State) + case "removed": + saved := make(chan error, 1) + go func() { saved <- m.UpdateDeadManConfig(notifications.DeadManConfig{}) }() + select { + case err := <-saved: + require.NoError(t, err) + case <-time.After(5 * time.Second): + t.Fatal("saved removal waited for the alert manager") + } + cfg, err := persistence.LoadDeadManConfig() + require.NoError(t, err) + require.Empty(t, cfg.PingURL) + require.Equal(t, "disabled", m.DeadManStatus().State) + // Deliberately don't start the next watchdog cycle. The completed + // save, rather than a later disabled tick, must revoke the raise. + } + finish() + am.Stop() + + queue := nm.GetQueue() + require.NotNil(t, queue) + rows, err := queue.GetPending(10) + require.NoError(t, err) + require.Len(t, rows, int(deliveryCallbacks.Load()), "ordinary notification queue") + for _, row := range rows { + require.NoError(t, nm.ProcessQueuedNotification(row)) + } + return deadManStandingFixtureResult{m.DeadManStatus(), am.GetAlertHistory(0), am.GetActiveAlerts(), + firingCallbacks.Load(), deliveryCallbacks.Load(), webhookDeliveries.Load()} +} diff --git a/internal/monitoring/deadman_test.go b/internal/monitoring/deadman_test.go index 8e4f09203c..103f05b047 100644 --- a/internal/monitoring/deadman_test.go +++ b/internal/monitoring/deadman_test.go @@ -660,3 +660,25 @@ func TestDeadManSupersededSnapshotDoesNotSend(t *testing.T) { }, func() time.Time { return now }) require.Nil(t, d.statusSnapshot().LastAttemptAt) } + +func TestDeadManSupersededProgressCannotQueueAStall(t *testing.T) { + now := time.Date(2026, 11, 24, 12, 0, 0, 0, time.UTC) + d := newDeadManTestRuntime(t, now, deadManRoundTripFunc(func(*http.Request) (*http.Response, error) { + t.Error("a removed destination must not receive a request") + return deadManResponse(http.StatusOK, ""), nil + })) + endpoint := "https://watchdog.example.com/ping/fixture" + m := &Monitor{deadMan: d, configPersist: config.NewConfigPersistence(t.TempDir()), + deadManConfig: notifications.DeadManConfig{PingURL: endpoint}} + d.runCycle(context.Background(), func() string { return m.deadManConfigSnapshot().PingURL }, func() time.Time { + // The old cycle already has a destination and is still reading + // progress when the operator completes removal. + require.NoError(t, m.UpdateDeadManConfig(notifications.DeadManConfig{})) + return now.Add(-2 * time.Minute) + }) + require.Equal(t, "disabled", m.DeadManStatus().State) + for _, update := range d.alertProjection.pending { + require.False(t, update.alertType == alerts.DeadManMonitoringStalledAlertType && update.raise != nil, + "cancelled cycle queued an obsolete stall after saved removal") + } +}