Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix(ai): skip unchanged incident JSON checkpoints

pulse-triage[bot]e41381681adc
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index b5b39aa607..c893477583 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -25,6 +25,17 @@ that same result. Successful reads retain their content and execution provenance
## Purpose
+### Unchanged incident JSON checkpoints
+
+Incident-memory checkpoints compare the serialized snapshot with bounded bytes
+from the existing recovery file before replacing it. Byte-identical snapshots
+do not rewrite the file, including after restart. Changed snapshots retain the
+atomic replacement path; missing files and failed writes must remain retryable.
+This does not change occurrence identity, retention or notification timing, nor
+does it eliminate snapshot serialization. Proof:
+`internal/ai/memory/incidents_unchanged_test.go` covers unchanged evaluations,
+metadata, restart, resolution/recurrence, file loss and failed-write retry.
+
### Canonical Patrol and Assistant continuation, 2026-09-07
Canonical investigation planning runs inside the model's tool call. The model
diff --git a/internal/ai/memory/incidents.go b/internal/ai/memory/incidents.go
index d8fbd4ea4a..fa02ff75e5 100644
--- a/internal/ai/memory/incidents.go
+++ b/internal/ai/memory/incidents.go
@@ -1,8 +1,10 @@
package memory
import (
+ "bytes"
"encoding/json"
"fmt"
+ "io"
"os"
"sort"
"strings"
@@ -274,7 +276,7 @@ type IncidentStore struct {
mu sync.RWMutex
saveMu sync.Mutex
savePending atomic.Bool // a queued save will capture the latest state; further requests coalesce
- savesCompleted atomic.Int64 // completed saveToDisk passes, observable by tests
+ savesCompleted atomic.Int64 // completed JSON replacements, observable by tests
incidents []*incidentShell
maxIncidents int
maxEvents int
@@ -1529,6 +1531,19 @@ func (s *IncidentStore) saveToDisk() error {
return err
}
+ // Coalescing handles concurrent bursts, but sequential lifecycle replays
+ // can also produce identical snapshots. Compare the actual recovery file
+ // rather than caching a hash: restarts, failed writes and missing files
+ // must not prevent the next checkpoint from restoring durable state.
+ if file, err := os.Open(s.filePath); err == nil {
+ // One extra byte detects a longer file without an unbounded read.
+ existing, readErr := io.ReadAll(io.LimitReader(file, int64(len(data))+1))
+ file.Close()
+ if readErr == nil && bytes.Equal(existing, data) {
+ return nil
+ }
+ }
+
tmpFile := s.filePath + ".tmp"
if err := os.WriteFile(tmpFile, data, 0600); err != nil {
return err
diff --git a/internal/ai/memory/incidents_unchanged_test.go b/internal/ai/memory/incidents_unchanged_test.go
new file mode 100644
index 0000000000..e6089403d2
--- /dev/null
+++ b/internal/ai/memory/incidents_unchanged_test.go
@@ -0,0 +1,114 @@
+package memory
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+)
+
+// Drive the real incident mutation entrypoints without background saves, then
+// checkpoint synchronously to distinguish sequential evaluations from bursts.
+func TestIncidentStoreUnchangedCheckpoint(t *testing.T) {
+ dir := t.TempDir()
+ store := NewIncidentStore(IncidentStoreConfig{})
+ alert := &alerts.Alert{ID: "pbs::connectivity", ResourceID: "pbs", Message: "offline", StartTime: time.Now().UTC()}
+ checkpoint := func() {
+ t.Helper()
+ store.dataDir = dir
+ store.filePath = filepath.Join(dir, "ai_incidents.json")
+ defer func() { store.dataDir = "" }()
+ if err := store.saveToDisk(); err != nil {
+ t.Fatal(err)
+ }
+ }
+ store.RecordAlertFired(alert)
+ checkpoint()
+ first, err := os.Stat(store.filePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ id := store.GetTimelineByAlertIdentifier(alert.ID).ID
+ for i := 0; i < 20; i++ {
+ store.RecordAlertFired(alert)
+ checkpoint()
+ }
+ after, err := os.Stat(store.filePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !os.SameFile(first, after) || store.savesCompleted.Load() != 1 {
+ t.Errorf("unchanged evaluations rewrote JSON: writes=%d", store.savesCompleted.Load())
+ }
+ if len(store.incidents) != 1 || store.incidents[0].ID != id {
+ t.Fatal("unchanged occurrence duplicated")
+ }
+ alert.Message = "still offline; new evidence"
+ store.RecordAlertFired(alert)
+ checkpoint()
+ if store.savesCompleted.Load() != 2 {
+ t.Fatal("changed metadata was not persisted")
+ }
+ reloaded := NewIncidentStore(IncidentStoreConfig{DataDir: dir})
+ if got := reloaded.GetTimelineByAlertIdentifier(alert.ID); got == nil || got.ID != id || got.Message != alert.Message {
+ t.Fatalf("restart lost occurrence or metadata: %+v", got)
+ }
+ // A newly loaded store also recognises an unchanged checkpoint.
+ if err := reloaded.saveToDisk(); err != nil {
+ t.Fatal(err)
+ }
+ if reloaded.savesCompleted.Load() != 0 {
+ t.Error("restart rewrote unchanged JSON")
+ }
+ store.RecordAlertResolved(alert, alert.StartTime.Add(time.Minute))
+ checkpoint()
+ alert.StartTime = alert.StartTime.Add(2 * time.Minute)
+ store.RecordAlertFired(alert)
+ checkpoint()
+ reloaded = NewIncidentStore(IncidentStoreConfig{DataDir: dir})
+ if len(reloaded.incidents) != 2 || reloaded.incidents[0].OccurrenceClosedAt == nil || reloaded.incidents[1].ID == id {
+ t.Fatal("resolution/recurrence did not survive restart")
+ }
+ // Missing files must still be restored, even when in-memory state is unchanged.
+ if err := os.Rename(store.filePath, store.filePath+".previous"); err != nil {
+ t.Fatal(err)
+ }
+ checkpoint()
+ if _, err := os.Stat(store.filePath); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestIncidentStoreCheckpointRetriesFailedWrite(t *testing.T) {
+ dir := t.TempDir()
+ store := NewIncidentStore(IncidentStoreConfig{})
+ alert := &alerts.Alert{ID: "pbs::connectivity", StartTime: time.Now().UTC()}
+ store.RecordAlertFired(alert)
+ store.dataDir = dir
+ store.filePath = filepath.Join(dir, "ai_incidents.json")
+ // A directory at the temporary-file path deterministically rejects writing.
+ if err := os.Mkdir(store.filePath+".tmp", 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := store.saveToDisk(); err == nil {
+ t.Fatal("expected checkpoint failure")
+ }
+ if store.savesCompleted.Load() != 0 {
+ t.Fatal("failed write counted as successful")
+ }
+ if err := os.Rename(store.filePath+".tmp", store.filePath+".obstruction"); err != nil {
+ t.Fatal(err)
+ }
+ if err := store.saveToDisk(); err != nil {
+ t.Fatal(err)
+ }
+ if store.savesCompleted.Load() != 1 {
+ t.Fatal("unchanged state was not retried")
+ }
+ reloaded := NewIncidentStore(IncidentStoreConfig{DataDir: dir})
+ if got := reloaded.GetTimelineByAlertIdentifier(alert.ID); got == nil || got.ID != store.incidents[0].ID {
+ t.Fatalf("retried occurrence not durable: %+v", got)
+ }
+}