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.

Keep retained PVE archives bound to their guest kind

pulse-triage[bot]3413c2a80782
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 3bff4afc1f..36a4f0b71c 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -17,6 +17,36 @@
## Purpose
+### Retained local archives do not change kind when a VMID is reused
+
+A PVE VM archive cannot advance the backup date or protect a live LXC using
+the same connection and VMID, and an LXC archive cannot protect a replacement
+VM. Local guest-date selection groups explicit `qemu`/`vm` and `lxc`/`ct`
+subjects independently before comparing recency. Incomplete archives still
+supply no completion date. Existing best-effort matching of legacy/untyped
+rows, PBS matching, task state and provider observation policy are unchanged.
+
+Recovery mapping uses the explicit artifact kind. When it contradicts the
+live guest lookup, the archive retains its historical typed canonical subject
+without borrowing the new occupant's ID or display name. Collector placement
+lookup likewise ignores an opposite-kind occupant: its archive keeps the read
+node, while a same-kind migrated guest still supplies its actual placement.
+The independent local storage read origin and archive ID are unchanged.
+Same-kind metadata and legacy/untyped fallback retain their existing behaviour.
+The point ID, archive time, size and public JSON shape do not change. Ordinary
+collection updates existing point attribution; no deletion, schema migration,
+backup/restore or guest-agent operation is introduced.
+
+`TestSyncGuestBackupTimesLocalArchiveGuestKinds`,
+`TestFromPVEStorageBackupsRetainsExplicitGuestKind` and the normal-suite
+`TestPVEArchiveSubjectKindLifecycle` cover both replacement directions, aliases,
+connection isolation, migrated placement/read origin, recency, incomplete files,
+legacy controls, retained raw
+artifacts, canonical dates/subjects, partial reads, complete absence and ordinary
+recovery. Actual lifecycle frames drive production Coverage and backup-status
+browser proof at desktop and narrow widths. This is a source safety repair,
+not #3248 causal attribution, native recovery or verified restore availability.
+
### Archive guest kinds come from artifact discriminators
PVE archive type detection ignores the storage-name prefix and incidental
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index b96caf3ecc..1d36dc9c8e 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -21,6 +21,36 @@
## Purpose
+### Retained local archives do not change kind when a VMID is reused
+
+A PVE VM archive cannot advance the backup date or protect a live LXC using
+the same connection and VMID, and an LXC archive cannot protect a replacement
+VM. Local guest-date selection groups explicit `qemu`/`vm` and `lxc`/`ct`
+subjects independently before comparing recency. Incomplete archives still
+supply no completion date. Existing best-effort matching of legacy/untyped
+rows, PBS matching, task state and provider observation policy are unchanged.
+
+Recovery mapping uses the explicit artifact kind. When it contradicts the
+live guest lookup, the archive retains its historical typed canonical subject
+without borrowing the new occupant's ID or display name. Collector placement
+lookup likewise ignores an opposite-kind occupant: its archive keeps the read
+node, while a same-kind migrated guest still supplies its actual placement.
+The independent local storage read origin and archive ID are unchanged.
+Same-kind metadata and legacy/untyped fallback retain their existing behaviour.
+The point ID, archive time, size and public JSON shape do not change. Ordinary
+collection updates existing point attribution; no deletion, schema migration,
+backup/restore or guest-agent operation is introduced.
+
+`TestSyncGuestBackupTimesLocalArchiveGuestKinds`,
+`TestFromPVEStorageBackupsRetainsExplicitGuestKind` and the normal-suite
+`TestPVEArchiveSubjectKindLifecycle` cover both replacement directions, aliases,
+connection isolation, migrated placement/read origin, recency, incomplete files,
+legacy controls, retained raw
+artifacts, canonical dates/subjects, partial reads, complete absence and ordinary
+recovery. Actual lifecycle frames drive production Coverage and backup-status
+browser proof at desktop and narrow widths. This is a source safety repair,
+not #3248 causal attribution, native recovery or verified restore availability.
+
### Archive guest kinds come from artifact discriminators
PVE archive type detection ignores the storage-name prefix and incidental
diff --git a/internal/models/backup_in_progress_test.go b/internal/models/backup_in_progress_test.go
index 714af884b8..8b578e8eb4 100644
--- a/internal/models/backup_in_progress_test.go
+++ b/internal/models/backup_in_progress_test.go
@@ -275,3 +275,71 @@ func TestSyncGuestBackupTimesIgnoresAbandonedInFlightSnapshot(t *testing.T) {
t.Errorf("LastBackup = %v, want zero", snapshot.VMs[0].LastBackup)
}
}
+
+// Local archives retain their explicit guest kind after VMID reuse. PBS has
+// always used typed subjects; local files must not bypass that safety property.
+func TestSyncGuestBackupTimesLocalArchiveGuestKinds(t *testing.T) {
+ for _, kind := range []string{"qemu", "vm", " QEMU ", "lxc", "ct", " LXC "} {
+ t.Run(kind, func(t *testing.T) {
+ state := NewState()
+ now := time.Now().UTC().Truncate(time.Second)
+ matching, opposite := "qemu", "lxc"
+ isVM := kind == "qemu" || kind == "vm" || kind == " QEMU "
+ if !isVM {
+ matching, opposite = "lxc", "qemu"
+ }
+ state.UpdateVMs([]VM{{VMID: 100, Instance: "a"}, {VMID: 100, Instance: "b"}})
+ state.UpdateContainers([]Container{{VMID: 100, Instance: "a"}, {VMID: 100, Instance: "b"}})
+ state.UpdateStorageBackupsForInstance("a", []StorageBackup{{ID: "artifact", Instance: "a", VMID: 100, Type: kind, Time: now}})
+ state.SyncGuestBackupTimes()
+ snap := state.GetSnapshot()
+ right, wrong := snap.VMs[0].LastBackup, snap.Containers[0].LastBackup
+ if !isVM {
+ right, wrong = wrong, right
+ }
+ if !right.Equal(now) || !wrong.IsZero() {
+ t.Errorf("explicit %q archive right=%s wrong=%s", kind, right, wrong)
+ }
+ if !snap.VMs[1].LastBackup.IsZero() || !snap.Containers[1].LastBackup.IsZero() {
+ t.Fatal("another connection inherited backup time")
+ }
+ // Recency is considered within a kind, never before attribution.
+ older := now.Add(-time.Hour)
+ state.UpdateStorageBackupsForInstance("a", []StorageBackup{
+ {ID: "correct", Instance: "a", VMID: 100, Type: matching, Time: older},
+ {ID: "opposite", Instance: "a", VMID: 100, Type: opposite, Time: now},
+ {ID: "partial", Instance: "a", VMID: 100, Type: matching, Time: now.Add(time.Minute), InProgress: true},
+ })
+ state.SyncGuestBackupTimes()
+ snap = state.GetSnapshot()
+ right = snap.VMs[0].LastBackup
+ if !isVM {
+ right = snap.Containers[0].LastBackup
+ }
+ if !right.Equal(older) {
+ t.Errorf("newer opposite/partial file hid correct archive: %s want %s", right, older)
+ }
+ state.UpdateStorageBackupsForInstance("a", nil)
+ state.SyncGuestBackupTimes()
+ snap = state.GetSnapshot()
+ if !snap.VMs[0].LastBackup.IsZero() || !snap.Containers[0].LastBackup.IsZero() {
+ t.Error("accepted absence retained typed dates")
+ }
+ })
+ }
+}
+
+func TestSyncGuestBackupTimesUntypedLocalArchiveCompatibility(t *testing.T) {
+ for _, kind := range []string{"", "unknown", "legacy"} {
+ t.Run(kind, func(t *testing.T) {
+ state := NewState()
+ now := time.Now().UTC().Truncate(time.Second)
+ state.UpdateVMs([]VM{{VMID: 100, Instance: "a"}})
+ state.UpdateStorageBackupsForInstance("a", []StorageBackup{{ID: "legacy", Instance: "a", VMID: 100, Type: kind, Time: now}})
+ state.SyncGuestBackupTimes()
+ if got := state.GetSnapshot().VMs[0].LastBackup; !got.Equal(now) {
+ t.Errorf("untyped legacy behavior changed: %s", got)
+ }
+ })
+ }
+}
diff --git a/internal/models/models.go b/internal/models/models.go
index 3c97b24295..7c6b36f862 100644
--- a/internal/models/models.go
+++ b/internal/models/models.go
@@ -4710,9 +4710,14 @@ func (s *State) SyncGuestBackupTimes() {
vmid int
}
- // Build a map of instance+VMID -> latest backup time from all backup sources
- // Using composite key prevents cross-instance VMID collision issues
- latestBackup := make(map[string]time.Time)
+ // A retained archive may belong to the other guest kind after VMID reuse.
+ // Keep its kind as well as its connection; the live occupant cannot turn
+ // a removed VM's archive into an LXC backup (or the reverse).
+ type localSubjectKey struct {
+ instance, guestType string
+ vmid int
+ }
+ latestBackup := make(map[localSubjectKey]time.Time)
// Guests with a backup running right now: a live vzdump task is the
// authoritative PVE-side signal. Partial artifacts (an in-flight PBS
@@ -4753,11 +4758,27 @@ func (s *State) SyncGuestBackupTimes() {
// above already reports the guest as backing up.
continue
}
- key := backupKey(backup.Instance, backup.VMID)
+ guestType := ""
+ switch strings.ToLower(strings.TrimSpace(backup.Type)) {
+ case "qemu", "vm":
+ guestType = "vm"
+ case "lxc", "ct":
+ guestType = "ct"
+ }
+ key := localSubjectKey{backup.Instance, guestType, backup.VMID}
if existing, ok := latestBackup[key]; !ok || backup.Time.After(existing) {
latestBackup[key] = backup.Time
}
}
+ latestLocalBackup := func(instance string, vmid int, guestType string) time.Time {
+ latest := latestBackup[localSubjectKey{instance, guestType, vmid}]
+ // Preserve best-effort matching of older/untyped rows. Only an explicit
+ // artifact discriminator can establish a contradictory guest kind.
+ if untyped := latestBackup[localSubjectKey{instance, "", vmid}]; untyped.After(latest) {
+ latest = untyped
+ }
+ return latest
+ }
// Process PBS backups (VMID is string, BackupTime is the timestamp).
// Group by PBS subject type and VMID so VM and CT IDs do not cross-match.
@@ -5020,11 +5041,8 @@ func (s *State) SyncGuestBackupTimes() {
// Update VMs - recompute from current backup evidence instead of preserving stale values
for i := range s.VMs {
- var lastBackup time.Time
+ lastBackup := latestLocalBackup(s.VMs[i].Instance, s.VMs[i].VMID, "vm")
key := backupKey(s.VMs[i].Instance, s.VMs[i].VMID)
- if backupTime, ok := latestBackup[key]; ok {
- lastBackup = backupTime
- }
// Check if PBS has a more recent backup
pbsTime := findBestPBSBackup(pbsBackupsBySubject, s.VMs[i].VMID, "vm", s.VMs[i].Instance, s.VMs[i].Node, s.VMs[i].Name)
if !pbsTime.IsZero() {
@@ -5046,11 +5064,8 @@ func (s *State) SyncGuestBackupTimes() {
// Update Containers - recompute from current backup evidence instead of preserving stale values
for i := range s.Containers {
- var lastBackup time.Time
+ lastBackup := latestLocalBackup(s.Containers[i].Instance, s.Containers[i].VMID, "ct")
key := backupKey(s.Containers[i].Instance, s.Containers[i].VMID)
- if backupTime, ok := latestBackup[key]; ok {
- lastBackup = backupTime
- }
// Check if PBS has a more recent backup
pbsTime := findBestPBSBackup(pbsBackupsBySubject, s.Containers[i].VMID, "ct", s.Containers[i].Instance, s.Containers[i].Node, s.Containers[i].Name)
if !pbsTime.IsZero() {
diff --git a/internal/monitoring/monitor_backups.go b/internal/monitoring/monitor_backups.go
index ed71d0fdf0..d353c7c4b1 100644
--- a/internal/monitoring/monitor_backups.go
+++ b/internal/monitoring/monitor_backups.go
@@ -251,6 +251,7 @@ func (m *Monitor) pollStorageBackupsWithNodes(ctx context.Context, instanceName
// Build guest lookup map to find actual node for each VMID
snapshot := m.state.GetSnapshot()
+ guestInfo := buildProxmoxGuestInfoIndex(readState)
guestNodeMap := make(map[int]string) // VMID -> actual node name
populateGuestNodeMapFromReadState(readState, instanceName, guestNodeMap)
@@ -431,7 +432,14 @@ func (m *Monitor) pollStorageBackupsWithNodes(ctx context.Context, instanceName
backupNode := node.Node
if content.VMID > 0 {
if actualNode, found := guestNodeMap[content.VMID]; found {
- backupNode = actualNode
+ currentKind := guestInfo[proxmoxmapperKey(instanceName, actualNode, content.VMID)].ResourceType
+ // A reused VMID does not move a removed guest's archive
+ // to the opposite-kind occupant's current placement.
+ contradictoryKind := backupType == "qemu" && currentKind == unifiedresources.ResourceTypeSystemContainer ||
+ backupType == "lxc" && currentKind == unifiedresources.ResourceTypeVM
+ if !contradictoryKind {
+ backupNode = actualNode
+ }
}
// If not found in map, fall back to queried node (shouldn't happen normally)
}
@@ -651,7 +659,6 @@ func (m *Monitor) pollStorageBackupsWithNodes(ctx context.Context, instanceName
m.state.UpdatePBSGuestConfirmationsForInstance(instanceName, pbsConfirmations)
// Best-effort ingestion into recovery store (for rollups / unified backups UX).
- guestInfo := buildProxmoxGuestInfoIndex(readState)
points, evidenceErr := proxmoxrecoverymapper.FromPVEStorageBackupsWithEvidence(
observedBackups,
guestInfo,
diff --git a/internal/monitoring/monitor_backups_readstate_test.go b/internal/monitoring/monitor_backups_readstate_test.go
index a64405b742..8c143f7147 100644
--- a/internal/monitoring/monitor_backups_readstate_test.go
+++ b/internal/monitoring/monitor_backups_readstate_test.go
@@ -1113,3 +1113,27 @@ func TestPollPBSBackups_PreservesCacheOnTransientDatastoreError(t *testing.T) {
})
}
}
+
+func TestBackupArchivePlacementKeepsGuestKind(t *testing.T) {
+ for _, tc := range []struct {
+ archive string
+ current unifiedresources.ResourceType
+ want string
+ }{
+ {"qemu", unifiedresources.ResourceTypeVM, "migrated"},
+ {"lxc", unifiedresources.ResourceTypeSystemContainer, "migrated"},
+ {"qemu", unifiedresources.ResourceTypeSystemContainer, "read-node"},
+ {"lxc", unifiedresources.ResourceTypeVM, "read-node"},
+ {"unknown", unifiedresources.ResourceTypeVM, "migrated"},
+ } {
+ t.Run(tc.archive+"/"+string(tc.current), func(t *testing.T) {
+ m := &Monitor{state: models.NewState(), resourceStore: backupReadStateResourceStore([]unifiedresources.Resource{{ID: "current-guest", Type: tc.current, Name: "current", Status: unifiedresources.StatusOnline, Proxmox: &unifiedresources.ProxmoxData{Instance: "site", NodeName: "migrated", VMID: 100}}})}
+ client := &backupContentTypeClient{storage: "local", row: pveapi.StorageContent{Volid: "local:backup/vzdump-" + tc.archive + "-100.tar.zst", Content: "backup", VMID: 100, CTime: time.Now().Add(-time.Hour).Unix(), Size: 1024}}
+ m.pollStorageBackupsWithNodes(context.Background(), "site", client, []pveapi.Node{{Node: "read-node"}}, map[string]string{"read-node": "online"})
+ rows := m.state.GetSnapshot().PVEBackups.StorageBackups
+ if len(rows) != 1 || rows[0].Node != tc.want || rows[0].StorageNode != "read-node" {
+ t.Fatalf("archive kind borrowed wrong placement or lost read origin: %+v want=%s", rows, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/monitoring/pve_archive_subject_kind_test.go b/internal/monitoring/pve_archive_subject_kind_test.go
new file mode 100644
index 0000000000..b262d3c0a3
--- /dev/null
+++ b/internal/monitoring/pve_archive_subject_kind_test.go
@@ -0,0 +1,131 @@
+package monitoring
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "os"
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/recovery"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
+)
+
+// The provider may retain a removed VM's archives after its VMID is reused by
+// an LXC (or the reverse). The artifact kind, not the new occupant, owns them.
+// This drives ordinary read-only collection, ingest and posture APIs; no guest
+// agent or backup operation is involved.
+func TestPVEArchiveSubjectKindLifecycle(t *testing.T) {
+ f := newPVEReconciliationFixture(t)
+ f.nodes = f.nodes[:1]
+ ctID := unifiedresources.ProxmoxGuestCanonicalID(unifiedresources.ResourceTypeSystemContainer, "cluster", 101)
+ vmID := unifiedresources.ProxmoxGuestCanonicalID(unifiedresources.ResourceTypeVM, "cluster", 102)
+ f.ids = []string{ctID, vmID}
+ f.m.state.UpdateVMs([]models.VM{{ID: makeGuestID("cluster", "node-b", 102), VMID: 102, Instance: "cluster", Node: "node-b", Name: "current-vm", Status: "running"}})
+ f.m.state.UpdateContainers([]models.Container{{ID: makeGuestID("cluster", "node-b", 101), VMID: 101, Instance: "cluster", Node: "node-b", Name: "current-lxc", Status: "running"}})
+ oldAt := f.client.at
+ rightAt := oldAt.Add(-time.Hour)
+ rows := []proxmox.StorageContent{
+ {Volid: "local:backup/vzdump-qemu-101.vma.zst", VMID: 101, CTime: oldAt.Unix(), Size: 2048, Content: "backup", Format: "vma.zst"},
+ {Volid: "local:backup/vzdump-lxc-102.tar.zst", VMID: 102, CTime: oldAt.Unix(), Size: 1024, Content: "backup", Format: "tar.zst"},
+ }
+ client := &backupTypeLifecycleClient{backupContentTypeClient: backupContentTypeClient{storage: "local"}, rows: rows}
+ phases := []string{"mismatched", "matched", "partial", "recovered", "empty"}
+ frames := map[string]any{}
+ var accepted map[string]recovery.RecoveryPoint
+ for _, phase := range phases {
+ switch phase {
+ case "matched":
+ client.rows = append(client.rows,
+ proxmox.StorageContent{Volid: "local:backup/vzdump-lxc-101.tar.zst", VMID: 101, CTime: rightAt.Unix(), Size: 4096, Content: "backup", Format: "tar.zst"},
+ proxmox.StorageContent{Volid: "local:backup/vzdump-qemu-102.vma.zst", VMID: 102, CTime: rightAt.Unix(), Size: 8192, Content: "backup", Format: "vma.zst"})
+ case "partial":
+ client.err = fmt.Errorf("503 unavailable")
+ case "recovered":
+ client.err = nil
+ case "empty":
+ client.rows = nil
+ }
+ f.m.pollStorageBackupsWithNodes(context.Background(), "cluster", client, f.nodes, f.online)
+ f.wait(t)
+ snapshot := f.m.state.GetSnapshot()
+ points := f.points(t)
+ postures := f.postures(t)
+ want := rightAt
+ if phase == "mismatched" || phase == "empty" {
+ want = time.Time{}
+ }
+ for _, got := range []time.Time{snapshot.VMs[0].LastBackup, snapshot.Containers[0].LastBackup} {
+ if !got.Equal(want) {
+ t.Errorf("phase=%s guest LastBackup=%s want=%s: opposite-kind archive contaminated current occupant", phase, got, want)
+ }
+ }
+ for _, row := range snapshot.PVEBackups.StorageBackups {
+ point, ok := points["pve-backup:"+row.ID]
+ if !ok {
+ t.Fatalf("phase=%s missing archive point %s", phase, row.ID)
+ }
+ kind := unifiedresources.ResourceTypeVM
+ if row.Type == "lxc" {
+ kind = unifiedresources.ResourceTypeSystemContainer
+ }
+ expected := unifiedresources.ProxmoxGuestCanonicalID(kind, "cluster", row.VMID)
+ if point.SubjectResourceID != expected {
+ t.Errorf("phase=%s %s point subject=%s want=%s", phase, row.Type, point.SubjectResourceID, expected)
+ }
+ if point.CompletedAt == nil || !point.CompletedAt.Equal(row.Time) {
+ t.Errorf("phase=%s lost archive date: %+v", phase, point)
+ }
+ wrong := (row.VMID == 101 && row.Type == "qemu") || (row.VMID == 102 && row.Type == "lxc")
+ wantNode := "node-b"
+ if wrong {
+ wantNode = "node-a"
+ }
+ if row.Node != wantNode || row.StorageNode != "node-a" || point.SubjectRef == nil || point.SubjectRef.Class != wantNode {
+ t.Errorf("phase=%s archive borrowed an opposite-kind placement or lost read origin: row=%+v point=%+v", phase, row, point)
+ }
+ if wrong && point.SubjectRef != nil && (point.SubjectRef.Name == "current-lxc" || point.SubjectRef.Name == "current-vm") {
+ t.Errorf("phase=%s historical archive borrowed current occupant name: %+v", phase, point.SubjectRef)
+ }
+ }
+ for _, p := range postures {
+ if phase == "mismatched" || phase == "empty" || phase == "partial" {
+ if p.State == recovery.ProtectionStateProtected {
+ t.Errorf("phase=%s current occupant falsely protected: %+v", phase, p)
+ }
+ } else if p.State != recovery.ProtectionStateProtected || p.LastSuccessfulPointAt == nil || !p.LastSuccessfulPointAt.Equal(rightAt) {
+ t.Errorf("phase=%s actual same-kind archive not selected: %+v", phase, p)
+ }
+ }
+ if phase == "matched" {
+ accepted = points
+ }
+ if phase == "partial" && !reflect.DeepEqual(accepted, points) {
+ t.Error("unread inventory rewrote or renewed archive points")
+ }
+ if phase == "empty" && len(points) != 0 {
+ t.Errorf("accepted absence retains %d archive points", len(points))
+ }
+ frames[phase] = map[string]any{"pve": map[string]any{"data": snapshot.PVEBackups}, "postures": map[string]any{"data": postures, "policy": recovery.DefaultProtectionPosturePolicy.Payload()}, "points": points, "vms": snapshot.VMs, "containers": snapshot.Containers}
+ }
+ if os.Getenv("PULSE_ARCHIVE_SUBJECT_FRAMES") == "1" {
+ hashes := map[string]string{}
+ for _, p := range []string{"../models/models.go", "../recovery/mapper/proxmox/mapper.go", "monitor_backups.go"} {
+ b, err := os.ReadFile(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ hashes[p] = fmt.Sprintf("%x", sha256.Sum256(b))
+ }
+ data, err := json.Marshal(map[string]any{"runtime_sha256": hashes, "resource_ids": f.ids, "frames": frames})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Log("ARCHIVE_SUBJECT_FRAMES=" + string(data))
+ }
+}
diff --git a/internal/recovery/mapper/proxmox/mapper.go b/internal/recovery/mapper/proxmox/mapper.go
index d4fa29896c..836b0cb9ae 100644
--- a/internal/recovery/mapper/proxmox/mapper.go
+++ b/internal/recovery/mapper/proxmox/mapper.go
@@ -268,14 +268,20 @@ func FromPVEStorageBackups(backups []models.StorageBackup, guestInfoByKey map[st
if vmid > 0 && instanceName != "" && nodeName != "" {
key := guestLookupKey(instanceName, nodeName, vmid)
info := guestInfoByKey[key]
+ resourceType := resourceTypeFromGuestType(b.Type)
+ if resourceType == "" {
+ // Untyped legacy rows keep the existing best-effort lookup.
+ resourceType = info.ResourceType
+ } else if info.ResourceType != "" && info.ResourceType != resourceType {
+ // VMIDs can be reused across guest kinds. Keep the historical
+ // artifact's typed subject, without borrowing the new occupant's
+ // canonical ID, source ID or display name.
+ info = GuestInfo{}
+ }
sourceID := strings.TrimSpace(info.SourceID)
if sourceID == "" {
sourceID = guestSourceID(instanceName, nodeName, vmid)
}
- resourceType := info.ResourceType
- if resourceType == "" {
- resourceType = resourceTypeFromGuestType(b.Type)
- }
if resourceType != "" {
subjectRID = subjectResourceID(resourceType, info.ResourceID, sourceID)
subjectRef = proxmoxSubjectRef(resourceType, info, instanceName, nodeName, vmid, sourceID)
diff --git a/internal/recovery/mapper/proxmox/mapper_test.go b/internal/recovery/mapper/proxmox/mapper_test.go
index c4f6ab564a..1c2ae73293 100644
--- a/internal/recovery/mapper/proxmox/mapper_test.go
+++ b/internal/recovery/mapper/proxmox/mapper_test.go
@@ -865,3 +865,55 @@ func TestFromPVEStorageBackups_InProgressMapsToRunning(t *testing.T) {
t.Errorf("Verified = %v, want nil for a running backup", *p.Verified)
}
}
+
+func TestFromPVEStorageBackupsRetainsExplicitGuestKind(t *testing.T) {
+ for _, tc := range []struct {
+ name, kind string
+ artifactType, liveType unifiedresources.ResourceType
+ }{
+ {"removed-vm-now-lxc", "qemu", unifiedresources.ResourceTypeVM, unifiedresources.ResourceTypeSystemContainer},
+ {"removed-lxc-now-vm", "lxc", unifiedresources.ResourceTypeSystemContainer, unifiedresources.ResourceTypeVM},
+ {"vm-alias", " VM ", unifiedresources.ResourceTypeVM, unifiedresources.ResourceTypeSystemContainer},
+ {"ct-alias", " CT ", unifiedresources.ResourceTypeSystemContainer, unifiedresources.ResourceTypeVM},
+ {"matching-vm", "qemu", unifiedresources.ResourceTypeVM, unifiedresources.ResourceTypeVM},
+ {"matching-lxc", "lxc", unifiedresources.ResourceTypeSystemContainer, unifiedresources.ResourceTypeSystemContainer},
+ {"untyped-legacy", "", unifiedresources.ResourceTypeVM, unifiedresources.ResourceTypeVM},
+ {"unknown-legacy", "unknown", unifiedresources.ResourceTypeVM, unifiedresources.ResourceTypeVM},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ now := time.Now().UTC().Truncate(time.Second)
+ b := models.StorageBackup{ID: "retained-archive", Instance: "cluster", Node: "node", VMID: 100, Type: tc.kind, Time: now, Size: 2048, Storage: "local"}
+ info := map[string]GuestInfo{"cluster|node|100": {ResourceID: "current-canonical", SourceID: "current-source", ResourceType: tc.liveType, Name: "current-occupant"}}
+ points, err := FromPVEStorageBackupsWithEvidence([]models.StorageBackup{b}, info, now)
+ if err != nil || len(points) != 1 {
+ t.Fatalf("points=%+v err=%v", points, err)
+ }
+ p := points[0]
+ if tc.artifactType != tc.liveType {
+ want := unifiedresources.ProxmoxGuestCanonicalID(tc.artifactType, "cluster", 100)
+ if p.SubjectResourceID != want || p.SubjectRef == nil || p.SubjectRef.Name != "100" || p.SubjectRef.ID != "cluster:node:100" {
+ t.Errorf("opposite kind borrowed current occupant: %+v", p)
+ }
+ } else if p.SubjectResourceID != "current-canonical" || p.SubjectRef == nil || p.SubjectRef.Name != "current-occupant" || p.SubjectRef.ID != "current-source" {
+ t.Errorf("compatible metadata not preserved: %+v", p)
+ }
+ if p.ID != "pve-backup:retained-archive" || p.CompletedAt == nil || !p.CompletedAt.Equal(now) || p.Outcome != recovery.OutcomeSuccess || p.SizeBytes == nil || *p.SizeBytes != 2048 || p.ProviderScope != "cluster" {
+ t.Errorf("archive facts changed: %+v", p)
+ }
+ if p.SubjectRef != nil && tc.artifactType != tc.liveType {
+ wantType := "proxmox-vm"
+ if tc.artifactType == unifiedresources.ResourceTypeSystemContainer {
+ wantType = "proxmox-lxc"
+ }
+ if p.SubjectRef.Type != wantType {
+ t.Errorf("subject reference kind=%s want=%s", p.SubjectRef.Type, wantType)
+ }
+ }
+ b.InProgress = true
+ running := FromPVEStorageBackups([]models.StorageBackup{b}, info)[0]
+ if running.SubjectResourceID != p.SubjectResourceID || running.ID != p.ID || running.Outcome != recovery.OutcomeRunning || running.CompletedAt != nil {
+ t.Error("incomplete archive changed subject or claimed completion")
+ }
+ })
+ }
+}