Keep firing cooldown and owed recovery through queue reopen (#3948)

**Keep firing cooldown and owed recovery through queue reopen**

Restore occurrence delivery high-water marks from durable receipts under
manager admission. Retain unsettled recoveries through cleanup, and
retire explicitly ended or removed obligations only after grace and
pending work settle. Preserve legacy uncertainty, new severity,
recurrence, routing and shutdown controls.

**Keep restored cooldown scoped across occurrence and destination
rotation**

Do not let old destination completions or older durable occurrence reads
replace current delivery evidence. Retain regression controls for both
ordering cases.

**Publish notification policy before awaiting receipt retirement
storage**

The full race suite exposed a deadlock when email disable held the
manager mutex behind an admitted queue serialization. Serialize
destination changes separately, retain their shutdown leases, and
release the policy mutex before receipt writes. Keep the failed result
and extend blocked-enqueue controls to webhook changes and Apprise
disable.

---
Fleet candidate `20261105T065651Z-core-runtime` from the `core-runtime`
lane. Reviewed tip `d20487e5ada78a68fd34658456b1d70646f32495` on `main`.

[How Pulse handles
triage](https://github.com/rcourtman/Pulse/blob/main/docs/AI_TRANSPARENCY.md)
This commit is contained in:
pulse-triage[bot]
2026-11-05 08:19:52 +00:00
committed by GitHub
7 changed files with 1231 additions and 58 deletions

View File

@@ -1688,3 +1688,54 @@ destinations: pending work remains delayed with no attempt or audit. These are
source/native process proofs, not installed-service, external provider, stable
release or reporter recovery. A crash before graceful checkpointing can still
lose volatile firing buffers; this repair makes no crash-durability promise.
### Firing cooldown and owed recovery survive reopen and cleanup (5 November 2026)
The repeat-delivery map is a cache of successful occurrence-bound delivery.
On a cache miss, under the existing manager admission lease, current destination
receipts restore the highest delivered severity and latest completion instant.
Both high-water marks only advance, including out-of-order completions. A
legacy receipt without severity still establishes recovery eligibility, but
cannot suppress potentially new severity information. A genuinely new occurrence,
higher severity, expired cooldown and scheduled escalation retain their existing
admission. Unreadable delivery evidence must not silence a wanted firing.
Firing age alone never expires an owed recovery. Active or uncertain receipts
remain until successful recovery, explicit resolution or explicit destination
retirement. The existing occurrence-aware cancellation boundary records positive
resolution, even when recovery notifications are disabled. Recovery dispatch also
records it. Missing callbacks, an unavailable/stopped lifecycle owner and an empty
startup configuration are not evidence that an occurrence ended. Historic orphan
receipts with no positive resolution/removal evidence remain uncertain.
Explicit destination removal, disable or endpoint/recipient/target rotation starts
a durable 30-day retirement grace; it neither retargets nor authorises delivery.
An exact configuration revert during grace restores the old obligation; after
retirement cleanup it does not recreate one. New completion timestamps, resolution
and removal must all be at least 30 days old before their applicable receipt can
be deleted. Pending/sending/retryable work pins its exact occurrence/destination,
including a recovery waiting beyond the grace. Unreadable queued work prevents
receipt cleanup, not age-only fallback. Retirement markers cover late completions
and are themselves removed when no receipt or retryable job needs them. Future
rotations therefore do not accumulate permanent receipt/marker state. This does
not infer resolution for old unobserved orphans or guarantee provider inbox receipt.
`receipt_continuity_test.go` covers migration, severity/completion monotonicity,
legacy uncertainty, cache eviction, destination separation, expiry, exact revert,
all three transport retirement paths, pending/retryable/unreadable work and shutdown
admission. `receipt_retention_continuity_test.go` promotes the independent real-HTTP
one-day/31-day retention experiment; `notification_restart_continuity_test.go` in
monitoring promotes its graceful reopen and two-native-process receiver controls,
including owed recovery and a new occurrence. The old negative experiments remain
unaltered evidence. These are synthetic queue/receiver controls, not original-estate,
crash, signal-driven shutdown, installed-service or external-provider recovery.
A late completion for a removed endpoint keeps its own receipt without publishing
a cooldown for the replacement. A durable read of an older occurrence cannot
evict the newer occurrence's cache entry. Explicit configuration changes invalidate
the cache's destination scope; they do not permit recovery for a different endpoint.
Configuration retirement is serialized separately from the manager's policy lock.
Live policy and its shutdown lease are published first, then storage is updated
without that lock; a blocked accepted enqueue cannot hide a channel-disable or
destination change from its observers. Existing email-disable drain controls and
`TestReceiptRetirementPublishesPolicyBeforeWaitingForQueue` pin this ordering and
require the retirement write to survive shutdown. No read/retention gate is waived.

View File

@@ -0,0 +1,298 @@
package monitoring
// Regression controls promoted from the independently retained 5 November
// receiver experiment. Both reopens are graceful, not crash/signal/service
// qualification. The parent owns the HTTP receiver across native subprocesses.
import (
"database/sql"
"encoding/json"
"fmt"
"io/fs"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"sync"
"testing"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/notifications"
_ "modernc.org/sqlite"
)
const (
proofCooldownMinutes = 30
proofRestoredWait = 15 * time.Second // restored criticals re-dispatch after 10s
)
type proofReceipt struct {
Event string `json:"event"`
Identifier string `json:"alertIdentifier"`
Alerts []alerts.Alert `json:"alerts"`
}
type proofReceiver struct {
server *httptest.Server
mu sync.Mutex
got []proofReceipt
}
func newProofReceiver(t *testing.T) *proofReceiver {
r := &proofReceiver{}
r.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
var got proofReceipt
if err := json.NewDecoder(req.Body).Decode(&got); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
r.mu.Lock()
r.got = append(r.got, got)
r.mu.Unlock()
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(r.server.Close)
return r
}
func (r *proofReceiver) snapshot() []proofReceipt {
r.mu.Lock()
defer r.mu.Unlock()
return append([]proofReceipt(nil), r.got...)
}
func (r *proofReceiver) count(event, alertID string, start time.Time) int {
n := 0
for _, got := range r.snapshot() {
if got.Event != event {
continue
}
for _, a := range got.Alerts {
if a.ID == alertID && a.StartTime.Equal(start) {
n++
}
}
}
return n
}
func (r *proofReceiver) waitFor(t *testing.T, event, alertID string, start time.Time, want int, within time.Duration) bool {
t.Helper()
deadline := time.Now().Add(within)
for time.Now().Before(deadline) {
if r.count(event, alertID, start) >= want {
return true
}
time.Sleep(20 * time.Millisecond)
}
return r.count(event, alertID, start) >= want
}
func startProofMonitor(t *testing.T, alertDir, notificationDir, receiverURL string) *Monitor {
t.Helper()
a := alerts.NewManagerWithDataDir(alertDir)
n := notifications.NewNotificationManagerWithDataDir("http://pulse.example", notificationDir)
if err := n.UpdateAllowedPrivateCIDRs("127.0.0.1/32,::1/128"); err != nil {
t.Fatal(err)
}
n.AddWebhook(notifications.WebhookConfig{ID: "restart-proof", URL: receiverURL, Enabled: true, Service: "generic"})
n.SetNotifyOnResolve(true)
n.SetGroupingWindow(0)
n.SetCooldown(proofCooldownMinutes)
a.UpdateConfig(alerts.AlertConfig{Enabled: true, ActivationState: alerts.ActivationActive,
TimeThresholds: map[string]int{"storage": 0},
StorageDefault: alerts.HysteresisThreshold{Trigger: 80, Clear: 70}})
m := &Monitor{alertManager: a, notificationMgr: n}
a.SetAlertCallback(m.handleAlertFired)
a.SetResolvedCallback(m.handleAlertResolved)
return m
}
func stopProofMonitor(m *Monitor) { m.alertManager.Stop(); m.notificationMgr.Stop() }
func observeProofStorage(m *Monitor, usage float64) {
s := models.Storage{ID: "pbs-primary-backups", Name: "backups", Instance: "pbs-primary", Type: "pbs", Status: "online",
Total: 1000, Used: int64(usage * 10), Free: 1000 - int64(usage*10), Usage: usage}
for range 5 {
m.alertManager.CheckStorage(s)
}
}
func drainProofQueue(t *testing.T, m *Monitor) {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for {
stats, err := m.notificationMgr.GetQueueStats()
if err != nil {
t.Fatal(err)
}
if stats["pending"]+stats["sending"] == 0 {
return
}
if time.Now().After(deadline) {
t.Fatalf("queue did not drain: %v", stats)
}
time.Sleep(5 * time.Millisecond)
}
}
// durableFiringReceipts reads the persisted receipt rows for one occurrence
// through an independent read-only SQLite handle.
func durableFiringReceipts(t *testing.T, notificationDir, alertID string, start time.Time) int {
t.Helper()
var dbPath string
_ = filepath.WalkDir(notificationDir, func(path string, d fs.DirEntry, err error) error {
if err == nil && !d.IsDir() && d.Name() == "notification_queue.db" {
dbPath = path
}
return nil
})
if dbPath == "" {
t.Fatal("notification queue database not found")
}
db, err := sql.Open("sqlite", "file:"+dbPath+"?mode=ro")
if err != nil {
t.Fatal(err)
}
defer db.Close()
var n int
if err := db.QueryRow(`SELECT COUNT(*) FROM notification_delivery_receipts WHERE alert_id = ? AND alert_start_nanos = ?`,
alertID, start.UnixNano()).Scan(&n); err != nil {
t.Fatal(err)
}
return n
}
func firstCriticalFiring(t *testing.T, r *proofReceiver) alerts.Alert {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
for _, got := range r.snapshot() {
if got.Event == "" && len(got.Alerts) == 1 && got.Alerts[0].Level == alerts.AlertLevelCritical {
return got.Alerts[0]
}
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("no critical firing received: %+v", r.snapshot())
return alerts.Alert{}
}
func TestRestartWithinCooldownPreservesDeliveredCriticalFiring(t *testing.T) {
receiver := newProofReceiver(t)
alertDir, notificationDir := t.TempDir(), t.TempDir()
m := startProofMonitor(t, alertDir, notificationDir, receiver.server.URL)
observeProofStorage(m, 95) // trigger 80 -> critical at 90
original := firstCriticalFiring(t, receiver)
drainProofQueue(t, m)
receipts := durableFiringReceipts(t, notificationDir, original.ID, original.StartTime)
t.Logf("before restart: firing deliveries for occurrence = %d, durable receipts = %d",
receiver.count("", original.ID, original.StartTime), receipts)
if receipts != 1 {
t.Fatalf("expected one durable firing receipt before restart, got %d", receipts)
}
stopProofMonitor(m)
stoppedAt := time.Now()
m = startProofMonitor(t, alertDir, notificationDir, receiver.server.URL)
t.Cleanup(func() { stopProofMonitor(m) })
active := m.alertManager.GetActiveAlerts()
if len(active) != 1 || active[0].ID != original.ID || !active[0].StartTime.Equal(original.StartTime) || active[0].Acknowledged {
t.Fatalf("restart did not restore the same unacknowledged occurrence: %+v", active)
}
time.Sleep(proofRestoredWait)
drainProofQueue(t, m)
firings := receiver.count("", original.ID, original.StartTime)
t.Logf("after restart (%.1fs later, cooldown %dm): firing deliveries for the same occurrence = %d",
time.Since(stoppedAt).Seconds(), proofCooldownMinutes, firings)
if firings != 1 {
t.Errorf("FINDING: restart inside cooldown re-delivered the already-delivered firing (%d deliveries of one occurrence)", firings)
}
// Controls a fix must preserve: the recovery still reaches the destination
// that received the firing, and a genuinely new occurrence still delivers.
observeProofStorage(m, 10)
if !receiver.waitFor(t, "resolved", original.ID, original.StartTime, 1, 10*time.Second) {
t.Fatalf("recovery for the delivered occurrence was not delivered: %+v", receiver.snapshot())
}
drainProofQueue(t, m)
time.Sleep(10 * time.Millisecond) // occurrence start times must differ
observeProofStorage(m, 95)
next := m.alertManager.GetActiveAlerts()
if len(next) != 1 || next[0].StartTime.Equal(original.StartTime) {
t.Fatalf("expected a new occurrence: %+v", next)
}
if !receiver.waitFor(t, "", next[0].ID, next[0].StartTime, 1, 10*time.Second) {
t.Fatalf("new occurrence was not delivered: %+v", receiver.snapshot())
}
}
// Native subprocess form. Phases run in child processes of this test binary.
func TestNativeSubprocessRestartPreservesDeliveredCriticalFiring(t *testing.T) {
if phase := os.Getenv("PULSE_RESTART_PROOF_PHASE"); phase != "" {
runRestartProofPhase(t, phase)
return
}
receiver := newProofReceiver(t)
alertDir, notificationDir := t.TempDir(), t.TempDir()
run := func(phase string) {
cmd := exec.Command(os.Args[0], "-test.run=^TestNativeSubprocessRestartPreservesDeliveredCriticalFiring$", "-test.v", "-test.count=1")
cmd.Env = append(os.Environ(),
"PULSE_RESTART_PROOF_PHASE="+phase,
"PULSE_RESTART_PROOF_ALERT_DIR="+alertDir,
"PULSE_RESTART_PROOF_NOTIFICATION_DIR="+notificationDir,
"PULSE_RESTART_PROOF_RECEIVER="+receiver.server.URL,
)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("phase %s process failed: %v\n%s", phase, err, out)
}
t.Logf("phase %s process pid exited cleanly", phase)
}
run("first-process")
original := firstCriticalFiring(t, receiver)
t.Logf("first process: firing deliveries = %d, durable receipts = %d",
receiver.count("", original.ID, original.StartTime),
durableFiringReceipts(t, notificationDir, original.ID, original.StartTime))
run("second-process")
firings := receiver.count("", original.ID, original.StartTime)
t.Logf("after second process (cooldown %dm): firing deliveries for the same occurrence = %d", proofCooldownMinutes, firings)
if firings != 1 {
t.Errorf("FINDING: a new process inside cooldown re-delivered the already-delivered firing (%d deliveries of one occurrence)", firings)
}
}
func runRestartProofPhase(t *testing.T, phase string) {
alertDir := os.Getenv("PULSE_RESTART_PROOF_ALERT_DIR")
notificationDir := os.Getenv("PULSE_RESTART_PROOF_NOTIFICATION_DIR")
receiverURL := os.Getenv("PULSE_RESTART_PROOF_RECEIVER")
m := startProofMonitor(t, alertDir, notificationDir, receiverURL)
switch phase {
case "first-process":
observeProofStorage(m, 95)
deadline := time.Now().Add(10 * time.Second)
for {
active := m.alertManager.GetActiveAlerts()
if len(active) == 1 && durableFiringReceipts(t, notificationDir, active[0].ID, active[0].StartTime) == 1 {
break
}
if time.Now().After(deadline) {
t.Fatal("first process did not record the firing receipt")
}
time.Sleep(20 * time.Millisecond)
}
case "second-process":
time.Sleep(proofRestoredWait)
default:
t.Fatalf("unknown phase %q", phase)
}
drainProofQueue(t, m)
stopProofMonitor(m)
fmt.Printf("phase %s pid %d finished\n", phase, os.Getpid())
}

View File

@@ -304,6 +304,7 @@ func (l *notificationLifecycle) close() {
// NotificationManager handles sending notifications
type NotificationManager struct {
mu sync.RWMutex
receiptConfigMu sync.Mutex // Orders configuration/retirement publication without holding mu across storage.
stopOnce sync.Once
cleanupWG sync.WaitGroup
lifecycle notificationLifecycle // Admission and shutdown ownership of queue and direct delivery work
@@ -686,9 +687,10 @@ func defaultAppriseExec(ctx context.Context, args []string) ([]byte, error) {
}
type notificationRecord struct {
lastSent time.Time
alertStart time.Time
level alerts.AlertLevel // Highest delivered severity for this occurrence.
lastSent time.Time
alertStart time.Time
level alerts.AlertLevel // Highest delivered severity for this occurrence.
destinationScope string // Config identity used by the durable cache read.
}
// Alert represents an alert (interface to avoid circular dependency)
@@ -1001,9 +1003,13 @@ func (n *NotificationManager) GetPublicURL() string {
// SetEmailConfig updates email configuration
func (n *NotificationManager) SetEmailConfig(config EmailConfig) {
n.receiptConfigMu.Lock()
defer n.receiptConfigMu.Unlock()
n.mu.Lock()
config = normalizeEmailConfig(copyEmailConfig(config))
previousDestinations := n.receiptDestinationKeysLocked()
n.emailConfig = config
retireReceipts := n.prepareReceiptDestinationUpdateLocked(previousDestinations)
// Recreate email manager with new config to preserve rate limiting state
rateLimit := effectiveEmailRateLimit(config.RateLimit)
@@ -1023,6 +1029,7 @@ func (n *NotificationManager) SetEmailConfig(config EmailConfig) {
queue = n.queue
}
n.mu.Unlock()
retireReceipts()
if queue != nil {
defer n.lifecycle.release()
@@ -1034,13 +1041,18 @@ func (n *NotificationManager) SetEmailConfig(config EmailConfig) {
// SetAppriseConfig updates Apprise configuration.
func (n *NotificationManager) SetAppriseConfig(config AppriseConfig) {
n.receiptConfigMu.Lock()
defer n.receiptConfigMu.Unlock()
n.mu.Lock()
previousDestinations := n.receiptDestinationKeysLocked()
n.appriseConfig = NormalizeAppriseConfig(config)
retireReceipts := n.prepareReceiptDestinationUpdateLocked(previousDestinations)
var queue *NotificationQueue
if !n.appriseConfig.Enabled && n.queue != nil && n.lifecycle.join() {
queue = n.queue
}
n.mu.Unlock()
retireReceipts()
if queue != nil {
defer n.lifecycle.release()
@@ -1197,36 +1209,51 @@ func (n *NotificationManager) SetGroupingOptions(byNode, byGuest bool) {
// AddWebhook adds a webhook configuration
func (n *NotificationManager) AddWebhook(webhook WebhookConfig) {
n.receiptConfigMu.Lock()
defer n.receiptConfigMu.Unlock()
n.mu.Lock()
defer n.mu.Unlock()
previousDestinations := n.receiptDestinationKeysLocked()
n.webhooks = append(n.webhooks, copyWebhookConfig(NormalizeWebhookConfig(webhook)))
retireReceipts := n.prepareReceiptDestinationUpdateLocked(previousDestinations)
n.mu.Unlock()
retireReceipts()
}
// UpdateWebhook updates an existing webhook
func (n *NotificationManager) UpdateWebhook(webhookID string, webhook WebhookConfig) error {
n.receiptConfigMu.Lock()
defer n.receiptConfigMu.Unlock()
n.mu.Lock()
defer n.mu.Unlock()
for i, w := range n.webhooks {
if w.ID == webhookID {
previousDestinations := n.receiptDestinationKeysLocked()
n.webhooks[i] = copyWebhookConfig(NormalizeWebhookConfig(webhook))
retireReceipts := n.prepareReceiptDestinationUpdateLocked(previousDestinations)
n.mu.Unlock()
retireReceipts()
return nil
}
}
n.mu.Unlock()
return fmt.Errorf("webhook not found: %s", webhookID)
}
// DeleteWebhook removes a webhook
func (n *NotificationManager) DeleteWebhook(webhookID string) error {
n.receiptConfigMu.Lock()
defer n.receiptConfigMu.Unlock()
n.mu.Lock()
defer n.mu.Unlock()
for i, w := range n.webhooks {
if w.ID == webhookID {
previousDestinations := n.receiptDestinationKeysLocked()
n.webhooks = append(n.webhooks[:i], n.webhooks[i+1:]...)
retireReceipts := n.prepareReceiptDestinationUpdateLocked(previousDestinations)
n.mu.Unlock()
retireReceipts()
return nil
}
}
n.mu.Unlock()
return fmt.Errorf("webhook not found: %s", webhookID)
}
@@ -1373,6 +1400,28 @@ func (n *NotificationManager) sendAlert(alert *alerts.Alert, options alertSendOp
// new information, not a repeat. Scheduled escalation retains its explicit
// bypass because its cadence is owned by the alert schedule.
record, exists := n.lastNotified[alert.ID]
cached := record
destinations := n.receiptDestinationKeysLocked()
scope := receiptDestinationScope(destinations)
if exists && record.destinationScope != "" && record.destinationScope != scope {
exists = false
}
if (!exists || !record.alertStart.Equal(alert.StartTime)) && n.queue != nil {
var err error
record, exists, err = n.queue.deliveryCooldown(alert.ID, alert.StartTime, destinations)
if err != nil {
// Unknown evidence must not silence a wanted firing.
log.Error().Err(err).Str("alertID", alert.ID).Msg("Could not restore notification cooldown")
} else if exists {
record.destinationScope = scope
if !cached.alertStart.After(record.alertStart) {
if n.lastNotified == nil {
n.lastNotified = make(map[string]notificationRecord)
}
n.lastNotified[alert.ID] = record
}
}
}
severityIncreased := notificationSeverityRank(record.level) > 0 && notificationSeverityRank(alert.Level) > notificationSeverityRank(record.level)
if !options.bypassCooldown && !severityIncreased && exists && record.alertStart.Equal(alert.StartTime) && (n.cooldown <= 0 || time.Since(record.lastSent) < n.cooldown) {
elapsed := time.Since(record.lastSent)
@@ -1490,8 +1539,16 @@ func notificationSeverityRank(level alerts.AlertLevel) int {
}
}
func (n *NotificationManager) markAlertsNotified(alertsToSend []*alerts.Alert, sentAt time.Time) {
func (n *NotificationManager) markAlertsNotified(alertsToSend []*alerts.Alert, sentAt time.Time, deliveredDestination ...string) {
n.mu.Lock()
defer n.mu.Unlock()
destinations := n.receiptDestinationKeysLocked()
if len(deliveredDestination) > 0 && !destinations[deliveredDestination[0]] {
// An admitted old snapshot can complete after configuration rotates.
// Keep its receipt, but never lend its cooldown to the replacement.
return
}
scope := receiptDestinationScope(destinations)
if n.lastNotified == nil {
n.lastNotified = make(map[string]notificationRecord)
}
@@ -1509,7 +1566,7 @@ func (n *NotificationManager) markAlertsNotified(alertsToSend []*alerts.Alert, s
if previous.alertStart.After(alert.StartTime) {
continue
}
if previous.alertStart.Equal(alert.StartTime) {
if previous.alertStart.Equal(alert.StartTime) && (previous.destinationScope == "" || previous.destinationScope == scope) {
// A late warning cannot re-enable critical delivery, and an
// earlier completion cannot shorten the same occurrence's hold.
if notificationSeverityRank(previous.level) > notificationSeverityRank(level) {
@@ -1521,12 +1578,12 @@ func (n *NotificationManager) markAlertsNotified(alertsToSend []*alerts.Alert, s
}
}
n.lastNotified[alert.ID] = notificationRecord{
level: level,
lastSent: lastSent,
alertStart: alert.StartTime,
level: level,
lastSent: lastSent,
alertStart: alert.StartTime,
destinationScope: scope,
}
}
n.mu.Unlock()
}
func (n *NotificationManager) dispatchFiringAlerts(
@@ -1637,7 +1694,7 @@ func (n *NotificationManager) recordSuccessfulDelivery(job notificationDeliveryJ
if job.Event == eventResolved {
err = queue.DeleteDeliveryReceipt(alert.ID, alert.StartTime, destinationKey)
} else {
err = queue.RecordDeliveryReceipt(alert.ID, alert.StartTime, destinationKey, deliveredAt)
err = queue.recordDeliveryReceipt(alert.ID, alert.StartTime, destinationKey, deliveredAt, alert.Level)
}
if err != nil {
log.Error().Err(err).Str("alertID", alert.ID).Str("destination", destinationKey).Msg("Failed to update notification delivery receipt")
@@ -1664,7 +1721,7 @@ func (n *NotificationManager) recordSuccessfulDelivery(job notificationDeliveryJ
// Publish the cooldown/delivered marker only after the per-destination
// receipts are durable. Resolution can race the delivery goroutine and
// uses this marker as proof that receipt recording has completed.
n.markAlertsNotified(job.Alerts, deliveredAt)
n.markAlertsNotified(job.Alerts, deliveredAt, destinationKey)
}
}
@@ -1790,6 +1847,16 @@ func (n *NotificationManager) dispatchResolvedAlerts(alertList []*alerts.Alert)
return
}
defer n.lifecycle.release()
if queue != nil {
for _, alert := range alertList {
if alert == nil {
continue
}
if err := queue.resolveDeliveryReceipts(alert.ID, &alert.StartTime, time.Now()); err != nil {
log.Error().Err(err).Msg("Could not retain notification resolution; receipts remain unsettled")
}
}
}
jobs := buildNotificationDeliveryJobs(emailConfig, webhooks, appriseConfig, alertList, eventResolved, resolvedTimeFromAlerts(alertList))
// Filter each destination independently at dispatch, not merely when the
// alert enters the window. Never announce a recovery for an undelivered firing.
@@ -1882,6 +1949,8 @@ func (n *NotificationManager) cancelAlert(alertID string, start *time.Time) bool
}
if err != nil {
log.Error().Err(err).Str("alertID", alertID).Msg("failed to cancel queued notifications")
} else if err := queue.resolveDeliveryReceipts(alertID, start, time.Now()); err != nil {
log.Error().Err(err).Str("alertID", alertID).Msg("failed to retain notification resolution; receipts remain unsettled")
}
}

View File

@@ -481,32 +481,16 @@ func (nq *NotificationQueue) initSchema() error {
); err != nil {
return err
}
return nq.ensureTextColumn(
"notification_audit",
notificationAuditDestinationColumn,
)
if err := nq.ensureTextColumn("notification_audit", notificationAuditDestinationColumn); err != nil {
return err
}
return nq.migrateDeliveryReceiptContinuity()
}
// RecordDeliveryReceipt retains the legacy receipt API. Without a delivered
// severity it proves recovery eligibility, not a restart cooldown.
func (nq *NotificationQueue) RecordDeliveryReceipt(alertID string, alertStart time.Time, destinationKey string, deliveredAt time.Time) error {
if nq == nil || strings.TrimSpace(alertID) == "" || strings.TrimSpace(destinationKey) == "" || alertStart.IsZero() {
return fmt.Errorf("alert occurrence and destination are required for a delivery receipt")
}
if deliveredAt.IsZero() {
deliveredAt = time.Now()
}
nq.mu.Lock()
defer nq.mu.Unlock()
_, err := nq.db.Exec(`
INSERT INTO notification_delivery_receipts
(alert_id, alert_start_nanos, destination_key, delivered_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(alert_id, alert_start_nanos, destination_key)
DO UPDATE SET delivered_at = excluded.delivered_at
`, alertID, alertStart.UnixNano(), destinationKey, deliveredAt.Unix())
if err != nil {
return fmt.Errorf("record notification delivery receipt: %w", err)
}
return nil
return nq.recordDeliveryReceipt(alertID, alertStart, destinationKey, deliveredAt, "")
}
func (nq *NotificationQueue) HasDeliveryReceipt(alertID string, alertStart time.Time, destinationKey string) (bool, error) {
@@ -2016,25 +2000,10 @@ func (nq *NotificationQueue) performCleanup() {
// Keep completed/failed for 7 days, DLQ for 30 days
completedCutoff := time.Now().Add(-7 * 24 * time.Hour).Unix()
dlqCutoff := time.Now().Add(-30 * 24 * time.Hour).Unix()
receiptCutoff := dlqCutoff
// Receipts are only needed to correlate a later recovery with a firing
// occurrence. Bound their lifetime so installations with recovery delivery
// disabled do not grow this side table indefinitely.
if result, err := nq.db.Exec(`DELETE FROM notification_delivery_receipts WHERE delivered_at < ?`, receiptCutoff); err != nil {
log.Error().
Err(err).
Str("component", "notification_queue").
Str("action", "cleanup_delivery_receipts").
Int64("receiptCutoff", receiptCutoff).
Msg("Failed to cleanup old notification delivery receipts")
} else if rows, _ := result.RowsAffected(); rows > 0 {
log.Debug().
Str("component", "notification_queue").
Str("action", "cleanup_delivery_receipts").
Int64("count", rows).
Int64("receiptCutoff", receiptCutoff).
Msg("Cleaned up old notification delivery receipts")
// Firing age alone cannot settle an owed recovery. Only positive
// resolution or explicit destination retirement starts its grace period.
if err := nq.cleanupDeliveryReceiptsNoLock(dlqCutoff); err != nil {
log.Error().Err(err).Msg("Failed to cleanup settled notification receipts; obligations retained")
}
// Delete audit records for notifications about to be cleaned up (FK constraint)

View File

@@ -0,0 +1,317 @@
package notifications
import (
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rs/zerolog/log"
)
// Receipt lifecycle is positive evidence: absence from a snapshot (including a
// missing/unreadable/stopped alert owner) never establishes resolution. The
// existing occurrence cancellation callback records resolution explicitly.
func (nq *NotificationQueue) migrateDeliveryReceiptContinuity() error {
columns, err := nq.tableColumns("notification_delivery_receipts")
if err != nil {
return err
}
for _, column := range []string{"highest_severity", "delivered_nanos", "resolved_at"} {
if !columns[column] {
if _, err := nq.db.Exec(`ALTER TABLE notification_delivery_receipts ADD COLUMN ` + column + ` INTEGER NOT NULL DEFAULT 0`); err != nil {
return fmt.Errorf("add receipt %s: %w", column, err)
}
}
}
_, err = nq.db.Exec(`CREATE TABLE IF NOT EXISTS notification_receipt_retirements (
destination_key TEXT PRIMARY KEY, retired_at INTEGER NOT NULL
)`)
return err
}
func (nq *NotificationQueue) recordDeliveryReceipt(alertID string, start time.Time, destination string, completed time.Time, level alerts.AlertLevel) error {
if nq == nil || strings.TrimSpace(alertID) == "" || start.IsZero() || strings.TrimSpace(destination) == "" {
return fmt.Errorf("alert occurrence and destination are required for a delivery receipt")
}
if completed.IsZero() {
completed = time.Now()
}
nq.mu.Lock()
defer nq.mu.Unlock()
_, err := nq.db.Exec(`INSERT INTO notification_delivery_receipts
(alert_id, alert_start_nanos, destination_key, delivered_at, delivered_nanos, highest_severity)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(alert_id, alert_start_nanos, destination_key) DO UPDATE SET
delivered_at = MAX(delivered_at, excluded.delivered_at),
delivered_nanos = MAX(delivered_nanos, excluded.delivered_nanos),
highest_severity = MAX(highest_severity, excluded.highest_severity)`,
alertID, start.UnixNano(), destination, completed.Unix(), completed.UnixNano(), notificationSeverityRank(level))
return err
}
// Called under the manager's admission lease and mutex, before storage can be
// closed by Stop. Only current destinations may contribute restart cooldown.
func (nq *NotificationQueue) deliveryCooldown(id string, start time.Time, destinations map[string]bool) (notificationRecord, bool, error) {
record := notificationRecord{alertStart: start}
if id == "" || start.IsZero() || len(destinations) == 0 {
return record, false, nil
}
nq.mu.RLock()
defer nq.mu.RUnlock()
rows, err := nq.db.Query(`SELECT destination_key, delivered_at, delivered_nanos, highest_severity
FROM notification_delivery_receipts WHERE alert_id = ? AND alert_start_nanos = ?`, id, start.UnixNano())
if err != nil {
return record, false, err
}
defer rows.Close()
var highest int
for rows.Next() {
var destination string
var seconds, nanos int64
var severity int
if err := rows.Scan(&destination, &seconds, &nanos, &severity); err != nil {
return notificationRecord{}, false, err
}
// Legacy receipts have no severity history. They still authorise
// recovery, but cannot suppress potentially new severity information.
if !destinations[destination] || severity < 1 || severity > 3 {
continue
}
if nanos == 0 {
nanos = seconds * int64(time.Second)
}
completed := time.Unix(0, nanos)
if completed.After(record.lastSent) {
record.lastSent = completed
}
if severity > highest {
highest = severity
}
}
if err := rows.Err(); err != nil {
return notificationRecord{}, false, err
}
switch highest {
case 1:
record.level = alerts.AlertLevelInfo
case 2:
record.level = alerts.AlertLevelWarning
case 3:
record.level = alerts.AlertLevelCritical
}
return record, highest > 0, nil
}
func (nq *NotificationQueue) resolveDeliveryReceipts(id string, start *time.Time, at time.Time) error {
nq.mu.Lock()
defer nq.mu.Unlock()
query := `UPDATE notification_delivery_receipts SET resolved_at = ? WHERE alert_id = ? AND resolved_at = 0`
args := []any{at.Unix(), id}
if start != nil {
query += ` AND alert_start_nanos = ?`
args = append(args, start.UnixNano())
}
_, err := nq.db.Exec(query, args...)
return err
}
func (n *NotificationManager) receiptDestinationKeysLocked() map[string]bool {
keys := make(map[string]bool)
add := func(job notificationDeliveryJob, enabled bool) {
if key := notificationDeliveryDestinationKey(job); enabled && key != "" {
keys[key] = true
}
}
add(notificationDeliveryJob{Type: "email", EmailConfig: &n.emailConfig}, n.emailConfig.Enabled)
add(notificationDeliveryJob{Type: "apprise", AppriseConfig: &n.appriseConfig}, n.appriseConfig.Enabled)
for _, webhook := range n.webhooks {
add(notificationDeliveryJob{Type: "webhook", WebhookConfig: &webhook}, webhook.Enabled)
}
return keys
}
func receiptDestinationScope(keys map[string]bool) string {
ordered := make([]string, 0, len(keys))
for key := range keys {
ordered = append(ordered, key)
}
sort.Strings(ordered)
if len(ordered) == 0 {
return "-"
}
return strings.Join(ordered, ",")
}
// Explicit removal/disable/rotation starts a 30-day grace. An exact revert
// during grace restores old obligations. Merely booting with no configuration
// is not removal evidence. Historic orphans without removal evidence remain
// uncertain, rather than being silently expired. Late in-flight receipts use
// the same durable retirement marker as receipts already present at removal.
// Call under receiptConfigMu and mu. The returned write must run after mu is
// released: an accepted enqueue can be blocked in payload serialization with
// the queue lock held, while a policy observer needs mu to release that enqueue.
// receiptConfigMu preserves configuration order; the lease preserves storage.
func (n *NotificationManager) prepareReceiptDestinationUpdateLocked(previous map[string]bool) func() {
current := n.receiptDestinationKeysLocked()
if n.queue == nil || receiptDestinationScope(previous) == receiptDestinationScope(current) || !n.lifecycle.join() {
return func() {}
}
queue := n.queue
return func() {
defer n.lifecycle.release()
if err := queue.updateReceiptDestinations(previous, current, time.Now()); err != nil {
log.Error().Err(err).Msg("Could not retain destination receipt retirement; obligations preserved")
}
}
}
func (nq *NotificationQueue) updateReceiptDestinations(previous, current map[string]bool, at time.Time) error {
nq.mu.Lock()
defer nq.mu.Unlock()
tx, err := nq.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
for key := range previous {
if !current[key] {
if _, err := tx.Exec(`INSERT INTO notification_receipt_retirements(destination_key, retired_at) VALUES (?, ?)
ON CONFLICT(destination_key) DO NOTHING`, key, at.Unix()); err != nil {
return err
}
}
}
for key := range current {
if !previous[key] {
if _, err := tx.Exec(`DELETE FROM notification_receipt_retirements WHERE destination_key = ?`, key); err != nil {
return err
}
}
}
return tx.Commit()
}
// Pending/retryable work pins only its exact destination/occurrences. Failure
// to read or decode it is uncertainty, never permission for age-only deletion.
func (nq *NotificationQueue) pendingReceiptKeysNoLock() (map[string]bool, map[string]bool, error) {
rows, err := nq.db.Query(`SELECT type, alerts, config FROM notification_queue WHERE status IN ('pending', 'sending', 'failed', 'dlq')`)
if err != nil {
return nil, nil, err
}
defer rows.Close()
keys, destinations := make(map[string]bool), make(map[string]bool)
for rows.Next() {
var kind string
var payload, config []byte
if err := rows.Scan(&kind, &payload, &config); err != nil {
return nil, nil, err
}
base, _ := normalizeQueueType(kind)
job := notificationDeliveryJob{Type: base}
var decodeErr error
switch base {
case "email":
job.EmailConfig = &EmailConfig{}
decodeErr = json.Unmarshal(config, job.EmailConfig)
case "webhook":
job.WebhookConfig = &WebhookConfig{}
decodeErr = json.Unmarshal(config, job.WebhookConfig)
case "apprise":
job.AppriseConfig = &AppriseConfig{}
decodeErr = json.Unmarshal(config, job.AppriseConfig)
default:
return nil, nil, fmt.Errorf("unknown pending notification type")
}
if decodeErr != nil {
return nil, nil, fmt.Errorf("unreadable pending notification destination")
}
if err := json.Unmarshal(payload, &job.Alerts); err != nil {
return nil, nil, fmt.Errorf("unreadable pending notification occurrences")
}
destination := notificationDeliveryDestinationKey(job)
if destination == "" {
return nil, nil, fmt.Errorf("unknown pending notification destination")
}
destinations[destination] = true
for _, alert := range job.Alerts {
if key := notificationDeliveryReceiptKey(alert, destination); key != "" {
keys[key] = true
} else {
return nil, nil, fmt.Errorf("unknown pending notification occurrence")
}
}
}
return keys, destinations, rows.Err()
}
func (nq *NotificationQueue) cleanupDeliveryReceiptsNoLock(cutoff int64) error {
pinned, pendingDestinations, err := nq.pendingReceiptKeysNoLock()
if err != nil {
return err
}
rows, err := nq.db.Query(`SELECT r.alert_id, r.alert_start_nanos, r.destination_key
FROM notification_delivery_receipts r
LEFT JOIN notification_receipt_retirements d ON d.destination_key = r.destination_key
WHERE r.delivered_at < ? AND ((r.resolved_at > 0 AND r.resolved_at < ?) OR (d.retired_at > 0 AND d.retired_at < ?))`, cutoff, cutoff, cutoff)
if err != nil {
return err
}
type receipt struct {
id, destination string
start int64
}
var removable []receipt
for rows.Next() {
var r receipt
if err := rows.Scan(&r.id, &r.start, &r.destination); err != nil {
rows.Close()
return err
}
key := notificationDeliveryReceiptKey(&alerts.Alert{ID: r.id, StartTime: time.Unix(0, r.start)}, r.destination)
if !pinned[key] {
removable = append(removable, r)
}
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
for _, r := range removable {
if _, err := nq.db.Exec(`DELETE FROM notification_delivery_receipts WHERE alert_id = ? AND alert_start_nanos = ? AND destination_key = ?`, r.id, r.start, r.destination); err != nil {
return err
}
}
// Prune retirement markers too, unless a late queued attempt can still
// produce a receipt for this destination.
rows, err = nq.db.Query(`SELECT destination_key FROM notification_receipt_retirements d WHERE retired_at < ?
AND NOT EXISTS (SELECT 1 FROM notification_delivery_receipts r WHERE r.destination_key = d.destination_key)`, cutoff)
if err != nil {
return err
}
var retired []string
for rows.Next() {
var key string
if err := rows.Scan(&key); err != nil {
rows.Close()
return err
}
if !pendingDestinations[key] {
retired = append(retired, key)
}
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
for _, key := range retired {
if _, err := nq.db.Exec(`DELETE FROM notification_receipt_retirements WHERE destination_key = ?`, key); err != nil {
return err
}
}
return nil
}

View File

@@ -0,0 +1,329 @@
package notifications
import (
"database/sql"
"path/filepath"
"testing"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/stretchr/testify/require"
)
func TestDurableCooldownKeepsSeverityTimeAndDestination(t *testing.T) {
for _, cooldown := range []int{0, 30} {
t.Run(time.Duration(cooldown).String(), func(t *testing.T) {
dir := t.TempDir()
hook := WebhookConfig{ID: "ops", URL: "https://ops.example.test", Enabled: true}
other := WebhookConfig{ID: "other", URL: "https://other.example.test", Enabled: true}
a := &alerts.Alert{ID: "repeat", StartTime: time.Now().Add(-time.Hour), Level: alerts.AlertLevelCritical}
open := func() *NotificationManager {
m := NewNotificationManagerWithDeferredQueue("", dir)
t.Cleanup(m.Stop)
m.SetCooldown(cooldown)
m.SetGroupingWindow(3600)
m.AddWebhook(hook)
return m
}
m := open()
key := notificationDeliveryDestinationKey(notificationDeliveryJob{Type: "webhook", WebhookConfig: &hook})
latest := time.Now().Add(-time.Minute).Round(0)
require.NoError(t, m.queue.recordDeliveryReceipt(a.ID, a.StartTime, key, latest, a.Level))
require.NoError(t, m.queue.recordDeliveryReceipt(a.ID, a.StartTime, key, latest.Add(-time.Hour), alerts.AlertLevelWarning))
m.Stop()
m = open()
m.SendAlert(a)
require.Empty(t, m.pendingAlerts, "restart/cache miss repeated critical")
record := m.lastNotified[a.ID]
require.Equal(t, latest, record.lastSent)
require.Equal(t, alerts.AlertLevelCritical, record.level)
// A cache eviction is not a new notification entitlement.
delete(m.lastNotified, a.ID)
m.SendAlert(a)
require.Empty(t, m.pendingAlerts)
// An unrelated endpoint cannot lend cooldown to a replacement.
require.NoError(t, m.UpdateWebhook(hook.ID, other))
m.SendAlert(a)
require.Len(t, m.pendingAlerts, 1)
m.pendingAlerts = nil
m.pendingAlertIndex = nil
// Nor can a different occurrence inherit the prior severity history.
a.StartTime = a.StartTime.Add(time.Nanosecond)
m.SendAlert(a)
require.Len(t, m.pendingAlerts, 1)
})
}
}
func TestDurableCooldownAllowsIncreasesExpiryAndLegacy(t *testing.T) {
for _, tc := range []struct {
name string
level alerts.AlertLevel
age time.Duration
legacy bool
want int
}{
{"critical increase", alerts.AlertLevelWarning, time.Minute, false, 1},
{"same critical", alerts.AlertLevelCritical, time.Minute, false, 0},
{"expired critical", alerts.AlertLevelCritical, time.Hour, false, 1},
{"unknown legacy severity", "", time.Minute, true, 1},
} {
t.Run(tc.name, func(t *testing.T) {
m := NewNotificationManagerWithDeferredQueue("", t.TempDir())
defer m.Stop()
m.SetCooldown(30)
m.SetGroupingWindow(3600)
hook := WebhookConfig{ID: "ops", URL: "https://ops.example.test", Enabled: true}
m.AddWebhook(hook)
a := &alerts.Alert{ID: "same", StartTime: time.Now().Add(-2 * time.Hour), Level: alerts.AlertLevelCritical}
key := notificationDeliveryDestinationKey(notificationDeliveryJob{Type: "webhook", WebhookConfig: &hook})
if tc.legacy {
require.NoError(t, m.queue.RecordDeliveryReceipt(a.ID, a.StartTime, key, time.Now().Add(-tc.age)))
} else {
require.NoError(t, m.queue.recordDeliveryReceipt(a.ID, a.StartTime, key, time.Now().Add(-tc.age), tc.level))
}
m.SendAlert(a)
require.Len(t, m.pendingAlerts, tc.want)
has, err := m.queue.HasDeliveryReceipt(a.ID, a.StartTime, key)
require.NoError(t, err)
require.True(t, has, "legacy delivery must still authorise recovery")
})
}
}
func TestReceiptContinuityMigratesOriginalSchema(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, notificationQueueFileName)
db, err := sql.Open("sqlite", path)
require.NoError(t, err)
_, err = db.Exec(`CREATE TABLE notification_delivery_receipts(alert_id TEXT NOT NULL, alert_start_nanos INTEGER NOT NULL, destination_key TEXT NOT NULL, delivered_at INTEGER NOT NULL, PRIMARY KEY(alert_id,alert_start_nanos,destination_key));
INSERT INTO notification_delivery_receipts VALUES ('legacy',123,'webhook:ops',123)`)
require.NoError(t, err)
require.NoError(t, db.Close())
for range 2 {
q, err := NewNotificationQueue(dir)
require.NoError(t, err)
has, err := q.HasDeliveryReceipt("legacy", time.Unix(0, 123), "webhook:ops")
require.NoError(t, err)
require.True(t, has)
record, known, err := q.deliveryCooldown("legacy", time.Unix(0, 123), map[string]bool{"webhook:ops": true})
require.NoError(t, err)
require.False(t, known, "migration cannot guess a delivered severity")
require.Empty(t, record.level)
require.NoError(t, q.Stop())
}
}
func TestReceiptRetirementIsPositiveBoundedAndPinned(t *testing.T) {
for _, policy := range []string{"active", "unknown", "resolved", "rotated", "pending-recovery", "retryable-recovery", "unreadable-pending", "revert", "recent-resolution"} {
t.Run(policy, func(t *testing.T) {
m := NewNotificationManagerWithDeferredQueue("", t.TempDir())
defer m.Stop()
m.SetGroupingConfig(false, 0, false, false)
hook := WebhookConfig{ID: "ops", URL: "https://old.example.test", Enabled: true}
m.AddWebhook(hook)
q := m.GetQueue()
old := time.Now().Add(-31 * 24 * time.Hour)
a := &alerts.Alert{ID: "owed", StartTime: old.Add(-time.Hour), Level: alerts.AlertLevelCritical}
job := notificationDeliveryJob{Type: "webhook", Event: eventAlert, Alerts: []*alerts.Alert{a}, WebhookConfig: &hook}
key := notificationDeliveryDestinationKey(job)
require.NoError(t, q.recordDeliveryReceipt(a.ID, a.StartTime, key, old, a.Level))
if policy == "resolved" || policy == "pending-recovery" || policy == "retryable-recovery" || policy == "unreadable-pending" {
require.NoError(t, q.resolveDeliveryReceipts(a.ID, &a.StartTime, old))
}
if policy == "recent-resolution" {
m.CancelResolvedAlert(a)
}
if policy == "rotated" || policy == "revert" {
replacement := hook
replacement.URL = "https://new.example.test"
require.NoError(t, m.UpdateWebhook(hook.ID, replacement))
_, err := q.db.Exec(`UPDATE notification_receipt_retirements SET retired_at=?`, old.Unix())
require.NoError(t, err)
if policy == "revert" {
require.NoError(t, m.UpdateWebhook(hook.ID, hook))
}
}
if policy == "pending-recovery" || policy == "retryable-recovery" || policy == "unreadable-pending" {
job.Event = eventResolved
config, err := configJSONForNotificationDeliveryJob(job)
require.NoError(t, err)
require.NoError(t, q.Enqueue(&QueuedNotification{ID: "owed-recovery", Type: queueTypeForNotificationDeliveryJob(job), Alerts: job.Alerts, Config: config}))
if policy == "retryable-recovery" {
_, err = q.db.Exec(`UPDATE notification_queue SET status='dlq'`)
require.NoError(t, err)
}
if policy == "unreadable-pending" {
_, err = q.db.Exec(`UPDATE notification_queue SET config='{'`)
require.NoError(t, err)
}
}
q.performCleanup()
has, err := q.HasDeliveryReceipt(a.ID, a.StartTime, key)
require.NoError(t, err)
require.Equal(t, policy != "resolved" && policy != "rotated", has)
if policy == "rotated" {
var markers int
require.NoError(t, q.db.QueryRow(`SELECT COUNT(*) FROM notification_receipt_retirements`).Scan(&markers))
require.Zero(t, markers, "rotation markers must retire along with their receipts")
}
})
}
}
func TestDestinationRetirementTracksLateReceiptsAndAllTransports(t *testing.T) {
for _, kind := range []string{"webhook", "email", "apprise"} {
t.Run(kind, func(t *testing.T) {
m := NewNotificationManagerWithDeferredQueue("", t.TempDir())
defer m.Stop()
var key string
var remove func()
switch kind {
case "webhook":
c := WebhookConfig{ID: "ops", URL: "https://ops.example.test", Enabled: true}
m.AddWebhook(c)
key = notificationDeliveryDestinationKey(notificationDeliveryJob{Type: kind, WebhookConfig: &c})
remove = func() { require.NoError(t, m.DeleteWebhook(c.ID)) }
case "email":
c := EmailConfig{Enabled: true, From: "pulse@example.test", To: []string{"ops@example.test"}}
m.SetEmailConfig(c)
key = notificationDeliveryDestinationKey(notificationDeliveryJob{Type: kind, EmailConfig: &c})
remove = func() { c.Enabled = false; m.SetEmailConfig(c) }
case "apprise":
c := AppriseConfig{Enabled: true, Mode: AppriseModeCLI, Targets: []string{"json://ops.example.test"}}
m.SetAppriseConfig(c)
key = notificationDeliveryDestinationKey(notificationDeliveryJob{Type: kind, AppriseConfig: &c})
remove = func() { c.Enabled = false; m.SetAppriseConfig(c) }
}
remove()
q := m.GetQueue()
old := time.Now().Add(-31 * 24 * time.Hour)
_, err := q.db.Exec(`UPDATE notification_receipt_retirements SET retired_at=?`, old.Unix())
require.NoError(t, err)
// An already-in-flight request may finish after removal. Its receipt
// must not evade the recorded retirement just by arriving late.
a := &alerts.Alert{ID: "late", StartTime: old.Add(-time.Hour)}
require.NoError(t, q.RecordDeliveryReceipt(a.ID, a.StartTime, key, old))
q.performCleanup()
has, err := q.HasDeliveryReceipt(a.ID, a.StartTime, key)
require.NoError(t, err)
require.False(t, has)
})
}
}
func TestCooldownCacheMissIsOwnedByShutdownAdmission(t *testing.T) {
f := newShutdownAdmissionFixture(t)
m := f.open(nil)
q := m.GetQueue()
a := quietReplayAlert("restored", alerts.AlertLevelCritical, time.Now().Add(-time.Hour))
key := notificationDeliveryDestinationKey(notificationDeliveryJob{Type: "webhook", WebhookConfig: &f.hook})
require.NoError(t, q.recordDeliveryReceipt(a.ID, a.StartTime, key, time.Now(), a.Level))
q.mu.Lock()
sent := make(chan struct{})
go func() { m.SendAlert(a); close(sent) }()
// Admission takes the lease before waiting for this blocked storage read.
awaitShutdownCondition(t, "cooldown read admission", func() bool { m.lifecycle.mu.Lock(); defer m.lifecycle.mu.Unlock(); return m.lifecycle.leases > 0 })
stopped := make(chan struct{})
go func() { m.Stop(); close(stopped) }()
select {
case <-stopped:
t.Fatal("Stop closed an admitted cooldown read")
default:
}
q.mu.Unlock()
awaitShutdownSignal(t, "restored cooldown", sent)
awaitShutdownSignal(t, "manager stop", stopped)
require.Empty(t, m.pendingAlerts)
}
func TestLateDestinationCompletionDoesNotLendCooldown(t *testing.T) {
m := NewNotificationManagerWithDeferredQueue("", t.TempDir())
defer m.Stop()
m.SetGroupingWindow(3600)
original := WebhookConfig{ID: "ops", URL: "https://old.example.test", Enabled: true}
m.AddWebhook(original)
replacement := original
replacement.URL = "https://new.example.test"
require.NoError(t, m.UpdateWebhook(original.ID, replacement))
a := &alerts.Alert{ID: "late-rotation", StartTime: time.Now(), Level: alerts.AlertLevelCritical}
m.recordSuccessfulDelivery(notificationDeliveryJob{Type: "webhook", Event: eventAlert, Alerts: []*alerts.Alert{a}, WebhookConfig: &original}, time.Now())
m.SendAlert(a)
require.Len(t, m.pendingAlerts, 1, "old URL completion muted the new destination")
}
func TestOldCooldownRestoreCannotEvictNewOccurrence(t *testing.T) {
m := NewNotificationManagerWithDeferredQueue("", t.TempDir())
defer m.Stop()
m.SetGroupingWindow(3600)
m.SetCooldown(0)
hook := WebhookConfig{ID: "ops", URL: "https://ops.example.test", Enabled: true}
m.AddWebhook(hook)
old := &alerts.Alert{ID: "restored-old", StartTime: time.Now().Add(-time.Hour), Level: alerts.AlertLevelCritical}
current := old.Clone()
current.StartTime = current.StartTime.Add(time.Minute)
key := notificationDeliveryDestinationKey(notificationDeliveryJob{Type: "webhook", WebhookConfig: &hook})
require.NoError(t, m.queue.recordDeliveryReceipt(old.ID, old.StartTime, key, time.Now(), old.Level))
m.markAlertsNotified([]*alerts.Alert{current}, time.Now())
m.SendAlert(old)
require.Equal(t, current.StartTime, m.lastNotified[current.ID].alertStart)
require.Empty(t, m.pendingAlerts)
}
func TestReceiptRetirementPublishesPolicyBeforeWaitingForQueue(t *testing.T) {
for _, action := range []string{"webhook-delete", "webhook-rotate", "apprise-disable"} {
t.Run(action, func(t *testing.T) {
f := newShutdownAdmissionFixture(t)
m := f.open(func(m *NotificationManager) {
if action == "apprise-disable" {
m.SetAppriseConfig(AppriseConfig{Enabled: true, Mode: AppriseModeCLI, Targets: []string{"json://ops.example.test"}})
}
})
barrier := newAdmissionBarrier()
a := quietReplayAlert("retirement-"+action, alerts.AlertLevelWarning, time.Now().Add(-time.Hour))
a.Metadata = map[string]interface{}{"barrier": barrier}
admitted := make(chan struct{})
go func() { defer close(admitted); m.SendAlert(a) }()
awaitShutdownSignal(t, "accepted enqueue holding the queue lock", barrier.entered)
acted := make(chan struct{})
go func() {
defer close(acted)
switch action {
case "webhook-delete":
if err := m.DeleteWebhook(f.hook.ID); err != nil {
t.Error(err)
}
case "webhook-rotate":
updated := f.hook
updated.URL = "https://new.example.test"
if err := m.UpdateWebhook(f.hook.ID, updated); err != nil {
t.Error(err)
}
case "apprise-disable":
config := m.GetAppriseConfig()
config.Enabled = false
m.SetAppriseConfig(config)
}
}()
awaitShutdownCondition(t, "new policy visible without taking the blocked queue lock", func() bool {
if action == "apprise-disable" {
return !m.GetAppriseConfig().Enabled
}
hooks := m.GetWebhooks()
return len(hooks) == 0 || hooks[0].URL == "https://new.example.test"
})
stopped := make(chan struct{})
go func() { m.Stop(); close(stopped) }()
close(barrier.release)
awaitShutdownSignal(t, "accepted enqueue", admitted)
awaitShutdownSignal(t, "retirement write", acted)
awaitShutdownSignal(t, "stop owns retirement write", stopped)
q, err := NewNotificationQueue(f.dir)
require.NoError(t, err)
defer q.Stop()
var retired int
require.NoError(t, q.db.QueryRow(`SELECT COUNT(*) FROM notification_receipt_retirements`).Scan(&retired))
require.Equal(t, 1, retired, "published retirement lost across shutdown")
})
}
}

View File

@@ -0,0 +1,140 @@
package notifications
// Regression from the independent retention experiment. Only delivered_at is
// backdated; real cleanup, persistent reopen and actual HTTP delivery decide
// whether the owed recovery survives. This is age simulation, not a 31-day run.
import (
"encoding/json"
"net/http"
"sync"
"testing"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
)
type retentionProofReceipt struct {
Event string `json:"event"`
Alerts []alerts.Alert `json:"alerts"`
}
func TestReceiptCleanupPreservesRecoveryOfLongActiveFiring(t *testing.T) {
for _, tc := range []struct {
name string
receiptAgeDays int
}{
{name: "control receipt one day old", receiptAgeDays: 1},
{name: "receipt older than thirty days while occurrence still active", receiptAgeDays: 31},
} {
t.Run(tc.name, func(t *testing.T) {
var mu sync.Mutex
var got []retentionProofReceipt
server := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var receipt retentionProofReceipt
if err := json.NewDecoder(r.Body).Decode(&receipt); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
mu.Lock()
got = append(got, receipt)
mu.Unlock()
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
count := func(event string) int {
mu.Lock()
defer mu.Unlock()
n := 0
for _, receipt := range got {
if receipt.Event == event {
n++
}
}
return n
}
dataDir := t.TempDir()
webhook := WebhookConfig{ID: "ops", Name: "ops", URL: server.URL, Enabled: true, Service: "generic"}
open := func() *NotificationManager {
m := NewNotificationManagerWithDataDir("", dataDir)
m.webhookClient = server.Client()
if err := m.UpdateAllowedPrivateCIDRs("127.0.0.1/32"); err != nil {
t.Fatal(err)
}
m.SetGroupingConfig(false, 0, false, false)
m.SetCooldown(30)
m.SetNotifyOnResolve(true)
m.AddWebhook(webhook)
return m
}
drain := func(m *NotificationManager) {
deadline := time.Now().Add(10 * time.Second)
for {
stats, err := m.GetQueueStats()
if err != nil {
t.Fatal(err)
}
if stats["pending"]+stats["sending"] == 0 {
return
}
if time.Now().After(deadline) {
t.Fatalf("queue did not drain: %v", stats)
}
time.Sleep(5 * time.Millisecond)
}
}
alert := &alerts.Alert{
ID: "storage-pbs-primary-backups-usage", Type: "usage", Level: alerts.AlertLevelCritical,
ResourceID: "pbs-primary-backups", ResourceName: "backups", Node: "pbs-primary",
Message: "Storage usage 95%", Value: 95, Threshold: 80,
StartTime: time.Now().Add(-time.Duration(tc.receiptAgeDays) * 24 * time.Hour).Truncate(time.Second),
}
m := open()
m.SendAlert(alert.Clone())
deadline := time.Now().Add(10 * time.Second)
for count("") < 1 {
if time.Now().After(deadline) {
t.Fatal("firing not received")
}
time.Sleep(5 * time.Millisecond)
}
drain(m)
q := m.GetQueue()
if ok, err := q.HasDeliveryReceipt(alert.ID, alert.StartTime, notificationDeliveryDestinationKey(notificationDeliveryJob{Type: "webhook", WebhookConfig: &webhook})); err != nil || !ok {
t.Fatalf("firing receipt missing after delivery: ok=%v err=%v", ok, err)
}
// Elapsed-time simulation: only the receipt's delivered_at is aged.
deliveredAt := time.Now().Add(-time.Duration(tc.receiptAgeDays) * 24 * time.Hour).Unix()
q.mu.Lock()
_, err := q.db.Exec(`UPDATE notification_delivery_receipts SET delivered_at = ? WHERE alert_id = ?`, deliveredAt, alert.ID)
q.mu.Unlock()
if err != nil {
t.Fatal(err)
}
q.performCleanup() // the real hourly cleanup routine
var remaining int
q.mu.RLock()
_ = q.db.QueryRow(`SELECT COUNT(*) FROM notification_delivery_receipts WHERE alert_id = ?`, alert.ID).Scan(&remaining)
q.mu.RUnlock()
t.Logf("receipt age %dd: receipts remaining after cleanup = %d (occurrence still active, no repeat sent)", tc.receiptAgeDays, remaining)
// The occurrence stays active across a graceful reopen, then recovers.
m.Stop()
m = open()
t.Cleanup(m.Stop)
m.SendResolvedAlert(&alerts.ResolvedAlert{Alert: alert.Clone(), ResolvedTime: time.Now()})
drain(m)
deadline = time.Now().Add(3 * time.Second)
for count("resolved") < 1 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
t.Logf("receipt age %dd: firing deliveries = %d, recovery deliveries = %d", tc.receiptAgeDays, count(""), count("resolved"))
if count("resolved") != 1 {
t.Errorf("FINDING: destination that received the firing did not receive its recovery (receipt age %dd)", tc.receiptAgeDays)
}
})
}
}