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.

feat(alerts): intent gate in the reducer with parity harness

rcourtman9ddfc69ec71d
diff --git a/docs/release-control/v6/internal/records/alert-lifecycle-contract-coverage-2026-08-26.md b/docs/release-control/v6/internal/records/alert-lifecycle-contract-coverage-2026-08-26.md
index c824595d43..4ea7e70b61 100644
--- a/docs/release-control/v6/internal/records/alert-lifecycle-contract-coverage-2026-08-26.md
+++ b/docs/release-control/v6/internal/records/alert-lifecycle-contract-coverage-2026-08-26.md
@@ -80,5 +80,18 @@ and the parity expiry scenario exercises the manager's real Cleanup pass.
Applies to both families (checkMetric shares preserveAlertState). Second
consecutive slice with no manager defect found.
-Remaining for later slices: intent-policy interaction and a shadow-mode
-runtime feed.
+Sixth slice (2026-08-26): the intent gate — operator suppression
+(expected offline, muted, retired, active maintenance windows) and
+explicit grace policies hold ACTIVATION only, while confirmations keep
+counting; release activates with the run's first active observation as
+the alert start; an already-firing incident is never suppressed by
+intent. The manager accrues grace on monotonic process runtime while the
+reducer measures the signal clock — coincident under continuous
+operation, recorded as a nuance that disappears at cutover. Third
+consecutive parity slice with no manager defect; the operator scenarios'
+StartTime parity additionally exercises the lifecycleFirstMatched fix in
+composition. Deferred: the backup-offline deferral sub-policy
+(MaxDeferralSeconds / PostGraceSeconds).
+
+Remaining for later slices: the backup-offline deferral sub-policy and a
+shadow-mode runtime feed.
diff --git a/internal/alerts/reducer/discrete.go b/internal/alerts/reducer/discrete.go
index a5bd18492d..8c3d2511d9 100644
--- a/internal/alerts/reducer/discrete.go
+++ b/internal/alerts/reducer/discrete.go
@@ -43,6 +43,52 @@ type DiscreteRule struct {
// bypassing recovery confirmations, exactly as the manager's disable
// paths call clearAlert directly.
Disabled bool
+ // Intent is the resolved intent-policy context for this observation;
+ // nil means no gate. See DiscreteIntent.
+ Intent *DiscreteIntent
+}
+
+// DiscreteIntent characterizes the manager's intent gate
+// (evaluateIntentNoLock as composed by evaluateCanonicalLifecycleAlert):
+// it holds ACTIVATION only — an already-firing incident is never
+// suppressed by intent — and while held, the incident stays pending with
+// the condition's first active observation preserved as the eventual
+// start time. Operator context and policy are resolved by the caller per
+// observation; the reducer only applies the gate. The backup-offline
+// deferral sub-policy is not characterized yet (deferred slice).
+type DiscreteIntent struct {
+ // Explicit reports whether any intent rule applies to this
+ // resource+signal; only explicit policies impose the grace gate.
+ Explicit bool
+ // GraceSeconds is how long the condition must have been active before
+ // activation (explicit policies only). The manager accrues this on
+ // monotonic process runtime; the reducer measures it on the signal
+ // clock, which coincides under continuous operation.
+ GraceSeconds int
+ // OperatorSuppressed holds activation for operator context: an active
+ // maintenance window, muted or retired monitoring, or expected-offline
+ // for offline-family signals. The caller resolves it, honoring the
+ // policy's HonorOperatorState (default true).
+ OperatorSuppressed bool
+ // OperatorReason names the suppression, e.g. "operator_maintenance".
+ OperatorReason string
+}
+
+// intentHoldsActivation reports whether the gate keeps a would-be
+// activation pending. Grace accrues from the condition run's first active
+// observation, concurrently with any operator suppression — exactly as the
+// manager accrues elapsed time while suppressed.
+func intentHoldsActivation(intent *DiscreteIntent, activeSince, observedAt time.Time) bool {
+ if intent == nil {
+ return false
+ }
+ if intent.OperatorSuppressed {
+ return true
+ }
+ if !intent.Explicit {
+ return false
+ }
+ return observedAt.Sub(activeSince) < time.Duration(intent.GraceSeconds)*time.Second
}
// recordResolved remembers a resolved occurrence for re-fire restoration.
@@ -160,8 +206,14 @@ func (s *State) ApplyDiscrete(signal DiscreteSignal, rule DiscreteRule) []Event
if incident.Confirmations < required {
return nil
}
- incident.State = StateFiring
incident.Confirmations = required
+ // The intent gate holds activation only: the incident stays
+ // pending, counts clamped at the requirement, and the run's first
+ // active observation remains the eventual start time.
+ if intentHoldsActivation(rule.Intent, incident.PendingSince, signal.ObservedAt) {
+ return nil
+ }
+ incident.State = StateFiring
incident.StartedAt = incident.PendingSince
s.restoreAck(key, incident, signal.ObservedAt)
if restored, ok := s.consumeRefire(key, signal.ObservedAt); ok {
@@ -173,6 +225,21 @@ func (s *State) ApplyDiscrete(signal DiscreteSignal, rule DiscreteRule) []Event
// First matching observation.
if required <= 1 {
+ // With the intent gate holding, even a single-confirmation
+ // condition enters pending: the manager's wrapper forces the
+ // evaluator's would-be activation back to pending state.
+ if intentHoldsActivation(rule.Intent, signal.ObservedAt, signal.ObservedAt) {
+ s.incidents[key] = &Incident{
+ ResourceID: signal.ResourceID,
+ Key: signal.Key,
+ State: StatePending,
+ Severity: signal.Severity,
+ PendingSince: signal.ObservedAt,
+ Confirmations: 1,
+ LastObservedAt: signal.ObservedAt,
+ }
+ return []Event{event(EventPending, "")}
+ }
created := &Incident{
ResourceID: signal.ResourceID,
Key: signal.Key,
diff --git a/internal/alerts/reducer/intent_test.go b/internal/alerts/reducer/intent_test.go
new file mode 100644
index 0000000000..6cf9cf0dcc
--- /dev/null
+++ b/internal/alerts/reducer/intent_test.go
@@ -0,0 +1,115 @@
+package reducer
+
+import (
+ "testing"
+ "time"
+)
+
+func TestIntentOperatorSuppressionHoldsActivation(t *testing.T) {
+ state := NewState()
+ suppressed := DiscreteRule{Confirmations: 1, Intent: &DiscreteIntent{
+ OperatorSuppressed: true, OperatorReason: "operator_expected_offline",
+ }}
+
+ events := state.ApplyDiscrete(discreteSignalAt(true, SeverityCritical, 0), suppressed)
+ if len(events) != 1 || events[0].Type != EventPending {
+ t.Fatalf("events = %+v, want pending while operator-suppressed", events)
+ }
+ if events := state.ApplyDiscrete(discreteSignalAt(true, SeverityCritical, time.Minute), suppressed); len(events) != 0 {
+ t.Fatalf("held observation emitted %+v", events)
+ }
+
+ // Suppression lifts: next observation activates with the run's first
+ // active observation as the start.
+ released := DiscreteRule{Confirmations: 1, Intent: &DiscreteIntent{}}
+ events = state.ApplyDiscrete(discreteSignalAt(true, SeverityCritical, 2*time.Minute), released)
+ if len(events) != 1 || events[0].Type != EventFired {
+ t.Fatalf("events = %+v, want fired after suppression lifts", events)
+ }
+ incident, _ := state.Incident("node-1", "connectivity")
+ if !incident.StartedAt.Equal(t0) {
+ t.Fatalf("StartedAt = %v, want first active observation %v", incident.StartedAt, t0)
+ }
+}
+
+func TestIntentGraceHoldsUntilElapsed(t *testing.T) {
+ state := NewState()
+ rule := DiscreteRule{Confirmations: 1, Intent: &DiscreteIntent{Explicit: true, GraceSeconds: 120}}
+
+ state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 0), rule)
+ if events := state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, time.Minute), rule); len(events) != 0 {
+ t.Fatalf("inside grace emitted %+v", events)
+ }
+ events := state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 2*time.Minute), rule)
+ if len(events) != 1 || events[0].Type != EventFired {
+ t.Fatalf("events = %+v, want fired at grace boundary", events)
+ }
+ incident, _ := state.Incident("node-1", "connectivity")
+ if !incident.StartedAt.Equal(t0) {
+ t.Fatalf("StartedAt = %v, want grace-run start %v", incident.StartedAt, t0)
+ }
+}
+
+func TestIntentDipDuringGraceResetsRun(t *testing.T) {
+ state := NewState()
+ rule := DiscreteRule{Confirmations: 1, Intent: &DiscreteIntent{Explicit: true, GraceSeconds: 120}}
+
+ state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 0), rule)
+ events := state.ApplyDiscrete(discreteSignalAt(false, "", time.Minute), rule)
+ if len(events) != 1 || events[0].Type != EventPendingCleared {
+ t.Fatalf("events = %+v, want pending cleared on dip", events)
+ }
+
+ // Grace restarts from the re-entry.
+ state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 2*time.Minute), rule)
+ if events := state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 3*time.Minute), rule); len(events) != 0 {
+ t.Fatalf("restarted grace emitted %+v", events)
+ }
+ events = state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 4*time.Minute), rule)
+ if len(events) != 1 || events[0].Type != EventFired {
+ t.Fatalf("events = %+v, want fired after restarted grace", events)
+ }
+ incident, _ := state.Incident("node-1", "connectivity")
+ if !incident.StartedAt.Equal(t0.Add(2 * time.Minute)) {
+ t.Fatalf("StartedAt = %v, want restarted run start", incident.StartedAt)
+ }
+}
+
+func TestIntentDoesNotSuppressFiringIncident(t *testing.T) {
+ state := NewState()
+ state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 0), DiscreteRule{Confirmations: 1})
+
+ // Maintenance starting after activation does not clear or hold the
+ // already-firing incident.
+ held := DiscreteRule{Confirmations: 1, Intent: &DiscreteIntent{
+ OperatorSuppressed: true, OperatorReason: "operator_maintenance",
+ }}
+ if events := state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, time.Minute), held); len(events) != 0 {
+ t.Fatalf("firing incident emitted %+v under maintenance", events)
+ }
+ incident, _ := state.Incident("node-1", "connectivity")
+ if incident.State != StateFiring {
+ t.Fatalf("incident = %+v, want still firing", incident)
+ }
+}
+
+func TestIntentGraceComposesWithConfirmations(t *testing.T) {
+ state := NewState()
+ // Three confirmations AND a 5-minute grace: activation needs both.
+ rule := DiscreteRule{Confirmations: 3, Intent: &DiscreteIntent{Explicit: true, GraceSeconds: 300}}
+
+ state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 0), rule)
+ state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, time.Minute), rule)
+ // Third confirmation reached at 2m, but grace holds until 5m.
+ if events := state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 2*time.Minute), rule); len(events) != 0 {
+ t.Fatalf("confirmed-but-in-grace emitted %+v", events)
+ }
+ events := state.ApplyDiscrete(discreteSignalAt(true, SeverityWarning, 5*time.Minute), rule)
+ if len(events) != 1 || events[0].Type != EventFired {
+ t.Fatalf("events = %+v, want fired once grace also elapses", events)
+ }
+ incident, _ := state.Incident("node-1", "connectivity")
+ if !incident.StartedAt.Equal(t0) {
+ t.Fatalf("StartedAt = %v, want run start %v", incident.StartedAt, t0)
+ }
+}
diff --git a/internal/alerts/reducer_parity_intent_test.go b/internal/alerts/reducer_parity_intent_test.go
new file mode 100644
index 0000000000..984f8456d2
--- /dev/null
+++ b/internal/alerts/reducer_parity_intent_test.go
@@ -0,0 +1,198 @@
+package alerts
+
+import (
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/reducer"
+ alertspecs "github.com/rcourtman/pulse-go-rewrite/internal/alerts/specs"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// Intent-gate parity: operator suppression (expected offline, maintenance
+// windows) and explicit grace policies hold ACTIVATION while the condition
+// keeps confirming, then release with the run's first active observation
+// as the alert start. The manager side runs the real composition —
+// evaluateIntentNoLock inside evaluateCanonicalLifecycleAlert — with its
+// wall-clock and runtime-tick seams (m.now, m.intentClock) driven by the
+// simulated clock, a scenario-controlled operator resolver, and policies
+// loaded through LoadIntentPolicies. StartTime parity on the operator
+// scenarios exercises the lifecycleFirstMatched preservation landed in
+// earlier slices; on the grace scenario it exercises intentPending's
+// FirstMatchedAt restoration. The backup-offline deferral sub-policy is
+// deferred.
+
+type intentParityStep struct {
+ matched bool
+ advance time.Duration
+
+ operatorSuppressed bool
+ operatorReason string
+ maintenance bool // active maintenance window at this observation
+
+ wantFiring bool
+ wantStartOffset time.Duration // -1 skips
+}
+
+type intentParityScenario struct {
+ name string
+ graceSeconds int // loaded as an explicit state.offline default when > 0
+ steps []intentParityStep
+}
+
+const intentParityResourceID = "parity-intent-1"
+
+func intentParityScenarios() []intentParityScenario {
+ skip := time.Duration(-1)
+ return []intentParityScenario{
+ {
+ name: "expected-offline suppression releases with original start",
+ steps: []intentParityStep{
+ {matched: true, operatorSuppressed: true, operatorReason: "operator_expected_offline", wantFiring: false, wantStartOffset: skip},
+ {matched: true, advance: time.Minute, operatorSuppressed: true, operatorReason: "operator_expected_offline", wantFiring: false, wantStartOffset: skip},
+ {matched: true, advance: time.Minute, wantFiring: true, wantStartOffset: 0},
+ },
+ },
+ {
+ name: "maintenance window suppresses until it ends",
+ steps: []intentParityStep{
+ {matched: true, maintenance: true, wantFiring: false, wantStartOffset: skip},
+ {matched: true, advance: time.Minute, maintenance: true, wantFiring: false, wantStartOffset: skip},
+ {matched: true, advance: time.Minute, wantFiring: true, wantStartOffset: 0},
+ },
+ },
+ {
+ name: "explicit grace holds activation until elapsed",
+ graceSeconds: 120,
+ steps: []intentParityStep{
+ {matched: true, wantFiring: false, wantStartOffset: skip},
+ {matched: true, advance: time.Minute, wantFiring: false, wantStartOffset: skip},
+ {matched: true, advance: time.Minute, wantFiring: true, wantStartOffset: 0},
+ },
+ },
+ {
+ name: "maintenance starting mid-firing does not clear the alert",
+ steps: []intentParityStep{
+ {matched: true, wantFiring: true, wantStartOffset: 0},
+ {matched: true, advance: time.Minute, maintenance: true, wantFiring: true, wantStartOffset: 0},
+ },
+ },
+ }
+}
+
+func TestReducerParityWithManagerIntentGate(t *testing.T) {
+ for _, scenario := range intentParityScenarios() {
+ scenario := scenario
+ t.Run(scenario.name, func(t *testing.T) {
+ epoch := time.Date(2026, 8, 26, 12, 0, 0, 0, time.UTC)
+ simClock := epoch
+
+ manager := NewManagerWithDataDir(t.TempDir(), WithoutPersistedAlertRestore())
+ t.Cleanup(manager.Stop)
+
+ var currentStep intentParityStep
+ manager.mu.Lock()
+ manager.config.Enabled = true
+ manager.config.FlappingEnabled = false
+ manager.now = func() time.Time { return simClock }
+ manager.intentClock = func() time.Duration { return simClock.Sub(epoch) }
+ manager.mu.Unlock()
+ manager.SetOperatorIntentContextResolver(func(resourceID string, now time.Time) (OperatorIntentContext, bool) {
+ if currentStep.maintenance {
+ start := epoch.Add(-time.Hour)
+ end := simClock.Add(30 * time.Second)
+ return OperatorIntentContext{MaintenanceStartAt: &start, MaintenanceEndAt: &end}, true
+ }
+ if currentStep.operatorSuppressed {
+ return OperatorIntentContext{MonitoringMode: "expected_offline"}, true
+ }
+ return OperatorIntentContext{}, true
+ })
+ if scenario.graceSeconds > 0 {
+ grace := scenario.graceSeconds
+ document := NewAlertIntentPolicyDocument()
+ document.Defaults[string(AlertIntentSignalOffline)] = AlertIntentRule{GraceSeconds: &grace}
+ if err := manager.LoadIntentPolicies(document); err != nil {
+ t.Fatalf("LoadIntentPolicies: %v", err)
+ }
+ }
+
+ reducerState := reducer.NewState()
+
+ alertID := canonicalConnectivityStateID(intentParityResourceID)
+ for i, step := range scenario.steps {
+ simClock = simClock.Add(step.advance)
+ currentStep = step
+
+ spec, err := buildCanonicalConnectivitySpec(
+ intentParityResourceID, "parity-intent", unifiedresources.ResourceTypeAgent,
+ AlertLevelCritical, 1, false,
+ )
+ if err != nil {
+ t.Fatalf("build spec: %v", err)
+ }
+ if _, ok := manager.evaluateCanonicalLifecycleAlert(canonicalLifecycleAlertParams{
+ Spec: spec,
+ Evidence: alertspecs.AlertEvidence{
+ ObservedAt: simClock,
+ Connectivity: &alertspecs.ConnectivityEvidence{Signal: "status", Connected: !step.matched},
+ },
+ Tracking: manager.offlineConfirmations,
+ TrackingKey: "parity:" + intentParityResourceID,
+ AlertID: alertID,
+ AlertType: "offline",
+ ResourceID: intentParityResourceID,
+ ResourceName: "parity-intent",
+ Message: "parity intent condition",
+ }); !ok {
+ t.Fatal("evaluateCanonicalLifecycleAlert rejected the parity spec")
+ }
+
+ intent := &reducer.DiscreteIntent{
+ Explicit: scenario.graceSeconds > 0,
+ GraceSeconds: scenario.graceSeconds,
+ OperatorSuppressed: step.operatorSuppressed || step.maintenance,
+ OperatorReason: step.operatorReason,
+ }
+ reducerState.ApplyDiscrete(reducer.DiscreteSignal{
+ ResourceID: intentParityResourceID,
+ Key: "connectivity",
+ Matched: step.matched,
+ Severity: reducer.SeverityCritical,
+ ObservedAt: simClock,
+ }, reducer.DiscreteRule{Confirmations: 1, Intent: intent})
+
+ manager.mu.Lock()
+ alert, exists := manager.getActiveAlertNoLock(alertID)
+ manager.mu.Unlock()
+ managerFiring := exists && alert != nil
+ incident, ok := reducerState.Incident(intentParityResourceID, "connectivity")
+ reducerFiring := ok && incident.State == reducer.StateFiring
+
+ label := fmt.Sprintf("step %d (matched=%v suppressed=%v maint=%v advance=%s)",
+ i, step.matched, step.operatorSuppressed, step.maintenance, step.advance)
+
+ if managerFiring != step.wantFiring {
+ t.Fatalf("%s: manager firing = %v, scenario expects %v (characterization drift)",
+ label, managerFiring, step.wantFiring)
+ }
+ if managerFiring && step.wantStartOffset >= 0 {
+ wantStart := epoch.Add(step.wantStartOffset)
+ if !alert.StartTime.Equal(wantStart) {
+ t.Fatalf("%s: manager start = %v, scenario expects %v", label, alert.StartTime, wantStart)
+ }
+ }
+
+ if reducerFiring != managerFiring {
+ t.Fatalf("%s: PARITY DIVERGENCE — reducer firing = %v, manager = %v",
+ label, reducerFiring, managerFiring)
+ }
+ if managerFiring && step.wantStartOffset >= 0 && !incident.StartedAt.Equal(alert.StartTime) {
+ t.Fatalf("%s: PARITY DIVERGENCE — reducer start = %v, manager = %v",
+ label, incident.StartedAt, alert.StartTime)
+ }
+ }
+ })
+ }
+}