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.

Remove ChangeDetector's unjoined legacy history writer

rcourtman7f6ac2f27e9a
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 005efb5512..31a32302e4 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -6633,6 +6633,15 @@ The patrol-local `memory.ChangeDetector.GetChangesSummary` path now also
delegates to the shared memory recent-change presentation helper, so any
future fallback summary entry point inherits the same heading, resource
prefixing, and change-type labels without re-implementing the markdown shape.
+That detector's on-disk history (`ai_changes.json`) is legacy and read-only.
+Nothing in the runtime has called `DetectChanges` since patrol moved to
+agentic execution, so the detector only loads that file at construction and
+never writes it. Detected changes stay in memory, and there is no background
+save to join before a data directory is removed. The unjoined save goroutine
+that `DetectChanges` used to launch was reachable only from tests, and could
+outlive a `t.TempDir` cleanup; it was removed rather than hardened.
+`TestChangeDetector_LegacyHistoryIsReadOnly` proves detection leaves the file
+and directory untouched.
Those unified-resource action and export audit records are now also exposed
through the enterprise audit read surface so operators can inspect the
execution trail without reaching into storage internals.
diff --git a/internal/ai/memory/changes.go b/internal/ai/memory/changes.go
index 4896eaae79..17627d3d22 100644
--- a/internal/ai/memory/changes.go
+++ b/internal/ai/memory/changes.go
@@ -4,8 +4,6 @@
package memory
import (
- "encoding/json"
- "os"
"sync"
"sync/atomic"
"time"
@@ -53,20 +51,20 @@ type ResourceSnapshot struct {
SnapshotTime time.Time `json:"snapshot_time"`
}
-// ChangeDetector tracks infrastructure changes over time
+// ChangeDetector tracks infrastructure changes over time.
+//
+// Recent-change context comes from the unified-resource timeline; the detector
+// is only its fallback. Its on-disk history (ai_changes.json) is legacy data
+// from before patrol stopped calling DetectChanges: it is loaded once at
+// construction and never written, so changes detected now stay in memory.
type ChangeDetector struct {
mu sync.RWMutex
previousState map[string]ResourceSnapshot // resourceID -> snapshot
changes []Change
maxChanges int
- // Persistence
+ // dataDir holds the legacy history read by loadFromDisk.
dataDir string
-
- // saveStateMu guards asynchronous save scheduling state.
- saveStateMu sync.Mutex
- saveRunning bool
- saveRequested bool
}
// ChangeDetectorConfig configures the change detector
@@ -156,17 +154,10 @@ func (d *ChangeDetector) DetectChanges(currentSnapshots []ResourceSnapshot) []Ch
}
}
- // Store new changes
+ // Store new changes in memory only; the legacy history is read-only.
if len(newChanges) > 0 {
d.changes = append(d.changes, newChanges...)
d.trimChanges()
-
- // Persist asynchronously
- go func() {
- if err := d.saveToDisk(); err != nil {
- log.Warn().Err(err).Msg("failed to save change history")
- }
- }()
}
return newChanges
@@ -306,35 +297,7 @@ func (d *ChangeDetector) trimChanges() {
}
}
-// saveToDisk persists changes to JSON file
-func (d *ChangeDetector) saveToDisk() error {
- if d.dataDir == "" {
- return nil
- }
-
- d.mu.RLock()
- changes := make([]Change, len(d.changes))
- copy(changes, d.changes)
- d.mu.RUnlock()
-
- path, err := memoryPersistencePath(d.dataDir, changeHistoryFileName)
- if err != nil {
- return err
- }
- data, err := json.MarshalIndent(changes, "", " ")
- if err != nil {
- return err
- }
-
- tmpPath := path + ".tmp"
- if err := os.WriteFile(tmpPath, data, 0600); err != nil {
- return err
- }
-
- return os.Rename(tmpPath, path)
-}
-
-// loadFromDisk loads changes from JSON file
+// loadFromDisk loads the legacy change history from its JSON file
func (d *ChangeDetector) loadFromDisk() error {
changes, ok, err := loadMemoryHistory(d.dataDir, changeHistoryFileName, "change history", func(a, b Change) bool {
return a.DetectedAt.Before(b.DetectedAt)
diff --git a/internal/ai/memory/memory_coverage_test.go b/internal/ai/memory/memory_coverage_test.go
index e96eb817af..50b9cba439 100644
--- a/internal/ai/memory/memory_coverage_test.go
+++ b/internal/ai/memory/memory_coverage_test.go
@@ -79,67 +79,6 @@ func TestNewChangeDetector_LoadError(t *testing.T) {
}
}
-func TestChangeDetector_SaveToDisk_Scenarios(t *testing.T) {
- t.Run("NoDataDir", func(t *testing.T) {
- d := &ChangeDetector{}
- if err := d.saveToDisk(); err != nil {
- t.Fatalf("expected nil error, got %v", err)
- }
- })
-
- t.Run("MissingDir", func(t *testing.T) {
- tmpDir := t.TempDir()
- missing := filepath.Join(tmpDir, "missing")
- d := &ChangeDetector{
- dataDir: missing,
- changes: []Change{{ID: "c1"}},
- }
- if err := d.saveToDisk(); err == nil {
- t.Fatal("expected error for missing directory")
- }
- })
-
- t.Run("MarshalError", func(t *testing.T) {
- tmpDir := t.TempDir()
- d := &ChangeDetector{
- dataDir: tmpDir,
- changes: []Change{{ID: "c1", Before: func() {}}},
- }
- if err := d.saveToDisk(); err == nil {
- t.Fatal("expected marshal error")
- }
- })
-
- t.Run("RenameError", func(t *testing.T) {
- tmpDir := t.TempDir()
- destDir := filepath.Join(tmpDir, "ai_changes.json")
- if err := os.MkdirAll(destDir, 0755); err != nil {
- t.Fatalf("mkdir: %v", err)
- }
- d := &ChangeDetector{
- dataDir: tmpDir,
- changes: []Change{{ID: "c1"}},
- }
- if err := d.saveToDisk(); err == nil {
- t.Fatal("expected rename error")
- }
- })
-
- t.Run("Success", func(t *testing.T) {
- tmpDir := t.TempDir()
- d := &ChangeDetector{
- dataDir: tmpDir,
- changes: []Change{{ID: "c1"}},
- }
- if err := d.saveToDisk(); err != nil {
- t.Fatalf("saveToDisk error: %v", err)
- }
- if _, err := os.Stat(filepath.Join(tmpDir, "ai_changes.json")); err != nil {
- t.Fatalf("expected file to exist: %v", err)
- }
- })
-}
-
func TestChangeDetector_LoadFromDisk_Scenarios(t *testing.T) {
t.Run("NoFile", func(t *testing.T) {
d := &ChangeDetector{dataDir: t.TempDir()}
@@ -232,20 +171,6 @@ func TestChangeDetector_LoadFromDisk_Scenarios(t *testing.T) {
})
}
-func TestChangeDetector_DetectChanges_SaveError(t *testing.T) {
- tmpDir := t.TempDir()
- badDir := filepath.Join(tmpDir, "not-dir")
- if err := os.WriteFile(badDir, []byte("x"), 0600); err != nil {
- t.Fatalf("write file: %v", err)
- }
-
- detector := NewChangeDetector(ChangeDetectorConfig{DataDir: badDir})
- detector.DetectChanges([]ResourceSnapshot{
- {ID: "vm-1", Name: "vm-1", Type: "vm", Status: "running"},
- })
- time.Sleep(20 * time.Millisecond)
-}
-
func TestIncidentStore_DefaultsAndSummary(t *testing.T) {
store := NewIncidentStore(IncidentStoreConfig{})
if store.maxIncidents != defaultIncidentMaxIncidents {
@@ -913,10 +838,10 @@ func TestRemediationLog_Log_SaveError(t *testing.T) {
dataDir: badDir,
maxRecords: 1,
}
+ // Log persists before returning, so the failed save has already run here.
if err := log.Log(RemediationRecord{Problem: "p", Action: "a"}); err != nil {
t.Fatalf("log error: %v", err)
}
- time.Sleep(20 * time.Millisecond)
}
func TestNewRemediationLog_LoadsFromDisk(t *testing.T) {
diff --git a/internal/ai/memory/memory_extended_test.go b/internal/ai/memory/memory_extended_test.go
index 4e16ad8bfc..fcaafede8e 100644
--- a/internal/ai/memory/memory_extended_test.go
+++ b/internal/ai/memory/memory_extended_test.go
@@ -1,6 +1,7 @@
package memory
import (
+ "bytes"
"os"
"path/filepath"
"testing"
@@ -143,31 +144,42 @@ func TestChangeDetector_MultipleChangesAtOnce(t *testing.T) {
}
}
-func TestChangeDetector_Persistence(t *testing.T) {
- tmpDir, err := os.MkdirTemp("", "changes-test")
- if err != nil {
- t.Fatalf("Failed to create temp dir: %v", err)
+func TestChangeDetector_LegacyHistoryIsReadOnly(t *testing.T) {
+ tmpDir := t.TempDir()
+ path := filepath.Join(tmpDir, "ai_changes.json")
+ legacy := []byte(`[{"id":"legacy-1","resource_id":"vm-100","resource_type":"vm","change_type":"created","detected_at":"2026-01-01T00:00:00Z"}]`)
+ if err := os.WriteFile(path, legacy, 0600); err != nil {
+ t.Fatalf("write legacy history: %v", err)
}
- defer os.RemoveAll(tmpDir)
- // Create detector with persistence
d := NewChangeDetector(ChangeDetectorConfig{
MaxChanges: 100,
DataDir: tmpDir,
})
-
- // Create some changes
d.DetectChanges([]ResourceSnapshot{
{ID: "vm-100", Name: "web-server", Type: "vm", Status: "running", Node: "node1"},
})
- // Wait a bit for async save
- time.Sleep(100 * time.Millisecond)
+ // Detected changes join the loaded legacy history in memory.
+ if got := d.GetChangesForResource("vm-100", 10); len(got) != 2 {
+ t.Fatalf("expected legacy and detected change, got %d", len(got))
+ }
- // Check if file was created (persistence is async, might not exist)
- filePath := filepath.Join(tmpDir, "ai_changes.json")
- if _, err := os.Stat(filePath); os.IsNotExist(err) {
- t.Log("Changes file not created - persistence may be async")
+ // Nothing writes the data directory, so no background save can outlive
+ // the test and race TempDir cleanup.
+ entries, err := os.ReadDir(tmpDir)
+ if err != nil {
+ t.Fatalf("read data dir: %v", err)
+ }
+ if len(entries) != 1 || entries[0].Name() != "ai_changes.json" {
+ t.Fatalf("data dir must hold only the legacy history, got %v", entries)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read legacy history: %v", err)
+ }
+ if !bytes.Equal(data, legacy) {
+ t.Fatalf("legacy history was rewritten: %s", data)
}
}
@@ -304,11 +316,7 @@ func TestRemediationLog_FormatForContext_NoRecords(t *testing.T) {
}
func TestRemediationLog_Persistence(t *testing.T) {
- tmpDir, err := os.MkdirTemp("", "remediation-test")
- if err != nil {
- t.Fatalf("Failed to create temp dir: %v", err)
- }
- defer os.RemoveAll(tmpDir)
+ tmpDir := t.TempDir()
// Create log with persistence
r := NewRemediationLog(RemediationLogConfig{
@@ -316,20 +324,19 @@ func TestRemediationLog_Persistence(t *testing.T) {
DataDir: tmpDir,
})
- _ = r.Log(RemediationRecord{
+ if err := r.Log(RemediationRecord{
ResourceID: "vm-100",
Problem: "Test problem",
Action: "Test action",
Outcome: OutcomeResolved,
- })
-
- // Wait a bit for async save
- time.Sleep(100 * time.Millisecond)
+ }); err != nil {
+ t.Fatalf("Log: %v", err)
+ }
- // Check if file was created (persistence may be async)
+ // Log persists before returning.
filePath := filepath.Join(tmpDir, "ai_remediations.json")
- if _, err := os.Stat(filePath); os.IsNotExist(err) {
- t.Log("Remediation file not created - persistence may be async")
+ if _, err := os.Stat(filePath); err != nil {
+ t.Fatalf("expected remediation file after Log: %v", err)
}
}