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(recovery): preserve canonical pbs guest continuity

rcourtmana9967c3e6961
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 66c8bf8b61..69265f4365 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -269,6 +269,19 @@ dependency order. When a persisted `recovery.db` predates columns such as
running query paths that reference them, so opening a legacy store backfills
cleanly instead of returning `500` from `/api/recovery/points` or
`/api/recovery/rollups` during schema initialization.
+That same recovery-store key boundary must keep `subject_key` genuinely stable
+across ingest generations. Protected rollups must not split one Proxmox guest
+into stale and fresh rows just because older points stored legacy linked IDs
+like `lxc-*` or raw source IDs while newer points carry hashed canonical
+resource IDs, and proxmox guest external keys must ignore display-name churn so
+renaming a backup comment does not fork the protected inventory from recent
+event history. That same store-owned continuity contract also applies when
+Proxmox PBS guest points temporarily lose unified-resource linkage or drift
+between historical PBS namespaces: if recovery history already proves one
+canonical linked guest identity for the same friendly label, guest type, and
+VMID/CTID, the store must relink later unresolved PBS points and backfill older
+split rows onto that canonical protected item instead of leaving protected
+inventory freshness to disagree with recovery events.
That same hook-boundary normalization also owns the runtime recovery display
model. Canonical recovery points and rollups must expose `display.itemLabel`
and `display.itemType` to recovery consumers, while legacy transport fields
diff --git a/internal/recovery/keys.go b/internal/recovery/keys.go
index 00a3346f25..07cc3cb4a0 100644
--- a/internal/recovery/keys.go
+++ b/internal/recovery/keys.go
@@ -4,6 +4,8 @@ import (
"crypto/sha256"
"encoding/hex"
"strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
const (
@@ -20,7 +22,7 @@ func SubjectKeyForPoint(p RecoveryPoint) string {
// SubjectKey builds a stable grouping key from the point provider + subject identifiers.
func SubjectKey(provider Provider, subjectResourceID string, subjectRef *ExternalRef) string {
- rid := strings.TrimSpace(subjectResourceID)
+ rid := canonicalizeProxmoxLinkedSubjectResourceID(provider, subjectResourceID, subjectRef)
if rid != "" {
return subjectKeyResourcePrefix + rid
}
@@ -47,6 +49,10 @@ func externalKey(provider Provider, ref *ExternalRef) string {
return ""
}
+ if key := proxmoxGuestExternalKey(provider, ref); key != "" {
+ return key
+ }
+
h := sha256.New()
write := func(s string) {
h.Write([]byte(strings.TrimSpace(s)))
@@ -66,6 +72,198 @@ func externalKey(provider Provider, ref *ExternalRef) string {
return subjectKeyExternalPrefix + hex.EncodeToString(h.Sum(nil))
}
+func isProxmoxProvider(provider Provider) bool {
+ switch provider {
+ case ProviderProxmoxPVE, ProviderProxmoxPBS:
+ return true
+ default:
+ return false
+ }
+}
+
+func proxmoxGuestResourceType(ref *ExternalRef, subjectResourceID string) unifiedresources.ResourceType {
+ if ref != nil {
+ switch strings.TrimSpace(ref.Type) {
+ case "proxmox-vm":
+ return unifiedresources.ResourceTypeVM
+ case "proxmox-lxc":
+ return unifiedresources.ResourceTypeSystemContainer
+ }
+ }
+
+ rid := strings.TrimSpace(subjectResourceID)
+ switch {
+ case strings.HasPrefix(rid, "vm-"):
+ return unifiedresources.ResourceTypeVM
+ case strings.HasPrefix(rid, "system-container-"), strings.HasPrefix(rid, "lxc-"):
+ return unifiedresources.ResourceTypeSystemContainer
+ default:
+ return ""
+ }
+}
+
+func normalizeProxmoxGuestSourceID(resourceType unifiedresources.ResourceType, sourceID string) string {
+ normalized := strings.TrimSpace(sourceID)
+ if normalized == "" {
+ return ""
+ }
+ if resourceType == unifiedresources.ResourceTypeSystemContainer && strings.HasPrefix(normalized, "lxc-") {
+ return "system-container-" + strings.TrimPrefix(normalized, "lxc-")
+ }
+ return normalized
+}
+
+func canonicalizeProxmoxLinkedSubjectResourceID(provider Provider, subjectResourceID string, subjectRef *ExternalRef) string {
+ rid := strings.TrimSpace(subjectResourceID)
+ if rid == "" || !isProxmoxProvider(provider) {
+ return rid
+ }
+
+ resourceType := proxmoxGuestResourceType(subjectRef, rid)
+ if resourceType == "" {
+ return rid
+ }
+
+ normalizedRID := normalizeProxmoxGuestSourceID(resourceType, rid)
+ refID := ""
+ if subjectRef != nil {
+ refID = normalizeProxmoxGuestSourceID(resourceType, subjectRef.ID)
+ }
+
+ if refID != "" {
+ canonicalFromRef := unifiedresources.SourceSpecificID(resourceType, unifiedresources.SourceProxmox, refID)
+ if rid == canonicalFromRef || normalizedRID == canonicalFromRef {
+ if strings.Contains(refID, ":") {
+ return unifiedresources.SourceSpecificID(resourceType, unifiedresources.SourceProxmox, normalizedRID)
+ }
+ return canonicalFromRef
+ }
+ if normalizedRID == refID {
+ return canonicalFromRef
+ }
+ }
+
+ if normalizedRID != rid {
+ return unifiedresources.SourceSpecificID(resourceType, unifiedresources.SourceProxmox, normalizedRID)
+ }
+
+ // Legacy linked guest rows sometimes kept a raw source-derived subject resource ID while the
+ // ref ID had already fallen back to the stable instance:node:vmid identity.
+ if refID != "" && strings.Contains(refID, ":") {
+ return unifiedresources.SourceSpecificID(resourceType, unifiedresources.SourceProxmox, normalizedRID)
+ }
+
+ return rid
+}
+
+func proxmoxGuestExternalKey(provider Provider, ref *ExternalRef) string {
+ if ref == nil || !isProxmoxProvider(provider) {
+ return ""
+ }
+
+ resourceType := proxmoxGuestResourceType(ref, "")
+ if resourceType == "" {
+ return ""
+ }
+
+ typeValue := strings.TrimSpace(ref.Type)
+ if typeValue == "" {
+ return ""
+ }
+
+ h := sha256.New()
+ write := func(s string) {
+ h.Write([]byte(strings.TrimSpace(s)))
+ h.Write([]byte{0})
+ }
+
+ write(subjectKeyExternalPrefix)
+ write(string(provider))
+ write(typeValue)
+ write(ref.UID)
+ write(normalizeProxmoxGuestSourceID(resourceType, ref.ID))
+ write(ref.Namespace)
+ write(ref.Class)
+
+ // Proxmox guest names are presentation data, not identity. Excluding Name prevents one guest
+ // from splitting into multiple rollups when comments or display labels change.
+ return subjectKeyExternalPrefix + hex.EncodeToString(h.Sum(nil))
+}
+
+func normalizeContinuityLabel(value string) string {
+ parts := strings.Fields(strings.ToLower(strings.TrimSpace(value)))
+ if len(parts) == 0 {
+ return ""
+ }
+ return strings.Join(parts, " ")
+}
+
+// ProxmoxPBSGuestContinuityKey returns a conservative continuity key for PBS guest backups.
+// It intentionally requires a friendly subject label plus guest type, namespace, and VMID so the
+// store can repair historically split rollups without guessing across unrelated reused VMIDs.
+func ProxmoxPBSGuestContinuityKey(subjectLabel, itemType, namespaceLabel, entityIDLabel string) string {
+ itemType = NormalizeRecoveryItemType(itemType)
+ switch itemType {
+ case "vm", "system-container":
+ default:
+ return ""
+ }
+
+ namespaceLabel = strings.ToLower(strings.TrimSpace(namespaceLabel))
+ entityIDLabel = strings.TrimSpace(entityIDLabel)
+ subjectLabel = normalizeContinuityLabel(subjectLabel)
+ if namespaceLabel == "" || entityIDLabel == "" || subjectLabel == "" || isNumericOnlyLabel(subjectLabel) {
+ return ""
+ }
+
+ return strings.Join([]string{
+ "proxmox-pbs-guest",
+ itemType,
+ namespaceLabel,
+ entityIDLabel,
+ subjectLabel,
+ }, ":")
+}
+
+// ProxmoxPBSGuestLooseContinuityKey deliberately omits namespace. It is only safe to use when the
+// caller has already proven there is a single linked historical candidate for the label/type/vmid.
+func ProxmoxPBSGuestLooseContinuityKey(subjectLabel, itemType, entityIDLabel string) string {
+ itemType = NormalizeRecoveryItemType(itemType)
+ switch itemType {
+ case "vm", "system-container":
+ default:
+ return ""
+ }
+
+ entityIDLabel = strings.TrimSpace(entityIDLabel)
+ subjectLabel = normalizeContinuityLabel(subjectLabel)
+ if entityIDLabel == "" || subjectLabel == "" || isNumericOnlyLabel(subjectLabel) {
+ return ""
+ }
+
+ return strings.Join([]string{
+ "proxmox-pbs-guest-loose",
+ itemType,
+ entityIDLabel,
+ subjectLabel,
+ }, ":")
+}
+
+// ProxmoxPBSGuestContinuityKeyForPoint derives the conservative PBS guest continuity key from a
+// normalized recovery point. It is used by the store to preserve historical identity continuity.
+func ProxmoxPBSGuestContinuityKeyForPoint(p RecoveryPoint) string {
+ if p.Provider != ProviderProxmoxPBS {
+ return ""
+ }
+ idx := DeriveIndex(p)
+ return ProxmoxPBSGuestContinuityKey(
+ idx.SubjectLabel,
+ idx.ItemType,
+ idx.NamespaceLabel,
+ idx.EntityIDLabel,
+ )
+}
+
// RollupResourceID returns the public-facing rollup ID:
// - linked resources return the raw unified resource ID
// - external refs return the external key
diff --git a/internal/recovery/mapper/proxmox/mapper.go b/internal/recovery/mapper/proxmox/mapper.go
index 9d2e74f27b..4f8ec2f5e1 100644
--- a/internal/recovery/mapper/proxmox/mapper.go
+++ b/internal/recovery/mapper/proxmox/mapper.go
@@ -36,6 +36,34 @@ func guestLookupKey(instanceName, nodeName string, vmid int) string {
return fmt.Sprintf("%s|%s|%d", strings.TrimSpace(instanceName), strings.TrimSpace(nodeName), vmid)
}
+func namespaceLikelyMatchesProxmoxLocation(namespace, value string) bool {
+ namespace = strings.TrimSpace(namespace)
+ value = strings.TrimSpace(value)
+ if namespace == "" || value == "" {
+ return false
+ }
+
+ normalize := func(s string) string {
+ var b strings.Builder
+ for _, r := range strings.ToLower(s) {
+ if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+ }
+
+ ns := normalize(namespace)
+ location := normalize(value)
+ if ns == "" || location == "" {
+ return false
+ }
+ if ns == location {
+ return true
+ }
+ return strings.HasSuffix(location, ns) || strings.HasSuffix(ns, location)
+}
+
func preferredPBSBackupSubjectName(comment, vmid string) string {
comment = strings.TrimSpace(comment)
vmid = strings.TrimSpace(vmid)
@@ -58,6 +86,52 @@ func preferredPBSBackupSubjectName(comment, vmid string) string {
return comment
}
+func selectPBSGuestCandidate(backup models.PBSBackup, candidates []GuestCandidate) (GuestCandidate, bool) {
+ if len(candidates) == 0 {
+ return GuestCandidate{}, false
+ }
+ if len(candidates) == 1 {
+ return candidates[0], true
+ }
+
+ matched := candidates
+ if namespace := strings.TrimSpace(backup.Namespace); namespace != "" {
+ filtered := make([]GuestCandidate, 0, len(matched))
+ for _, candidate := range matched {
+ if namespaceLikelyMatchesProxmoxLocation(namespace, candidate.InstanceName) ||
+ namespaceLikelyMatchesProxmoxLocation(namespace, candidate.NodeName) {
+ filtered = append(filtered, candidate)
+ }
+ }
+ if len(filtered) == 1 {
+ return filtered[0], true
+ }
+ if len(filtered) > 1 {
+ matched = filtered
+ }
+ }
+
+ if preferredName := strings.ToLower(strings.TrimSpace(preferredPBSBackupSubjectName(backup.Comment, backup.VMID))); preferredName != "" {
+ filtered := make([]GuestCandidate, 0, len(matched))
+ for _, candidate := range matched {
+ if strings.ToLower(strings.TrimSpace(candidate.DisplayName)) == preferredName {
+ filtered = append(filtered, candidate)
+ }
+ }
+ if len(filtered) == 1 {
+ return filtered[0], true
+ }
+ if len(filtered) > 1 {
+ matched = filtered
+ }
+ }
+
+ if len(matched) == 1 {
+ return matched[0], true
+ }
+ return GuestCandidate{}, false
+}
+
func proxmoxSubjectRef(resourceType unifiedresources.ResourceType, info GuestInfo, instanceName, nodeName string, vmid int, sourceID string) *recovery.ExternalRef {
name := strings.TrimSpace(info.Name)
if name == "" && vmid > 0 {
@@ -353,9 +427,9 @@ func FromPBSBackups(backups []models.PBSBackup, candidatesByKey map[string][]Gue
var subjectRID string
var subjectRef *recovery.ExternalRef
- // Link to a unified resource only when we have a single unambiguous guest match.
- if len(candidates) == 1 {
- c := candidates[0]
+ // Link to a unified resource when the candidate set is already singular or can be
+ // disambiguated by PBS namespace / guest label without guessing across guest collisions.
+ if c, ok := selectPBSGuestCandidate(b, candidates); ok {
subjectRID = unifiedresources.SourceSpecificID(c.ResourceType, unifiedresources.SourceProxmox, c.SourceID)
subjectRef = proxmoxSubjectRef(c.ResourceType, GuestInfo{Name: c.DisplayName, ResourceType: c.ResourceType, SourceID: c.SourceID}, c.InstanceName, c.NodeName, c.VMID, c.SourceID)
} else {
diff --git a/internal/recovery/mapper/proxmox/mapper_test.go b/internal/recovery/mapper/proxmox/mapper_test.go
index 7cb7b3f07f..c8a57008ab 100644
--- a/internal/recovery/mapper/proxmox/mapper_test.go
+++ b/internal/recovery/mapper/proxmox/mapper_test.go
@@ -317,3 +317,59 @@ func TestFromPBSBackups_WithCandidates(t *testing.T) {
t.Error("expected SubjectResourceID to be set when candidate matches")
}
}
+
+func TestFromPBSBackups_DisambiguatesCandidatesByNamespace(t *testing.T) {
+ backups := []models.PBSBackup{
+ {
+ ID: "pbs-backup-minipc-ct-112",
+ VMID: "112",
+ Instance: "pbs-docker",
+ Namespace: "minipc",
+ Datastore: "main",
+ BackupType: "ct",
+ BackupTime: time.Date(2026, 3, 29, 3, 3, 31, 0, time.UTC),
+ Comment: "debian-go",
+ },
+ }
+
+ candidatesByKey := map[string][]GuestCandidate{
+ "ct:112": {
+ {
+ SourceID: "system-container-fb42a70d89bd20a6",
+ ResourceType: unifiedresources.ResourceTypeSystemContainer,
+ DisplayName: "debian-go",
+ InstanceName: "delly",
+ NodeName: "minipc",
+ VMID: 112,
+ BackupTypeKey: "ct",
+ },
+ {
+ SourceID: "system-container-deadbeefdeadbeef",
+ ResourceType: unifiedresources.ResourceTypeSystemContainer,
+ DisplayName: "other-guest",
+ InstanceName: "other",
+ NodeName: "pve-b",
+ VMID: 112,
+ BackupTypeKey: "ct",
+ },
+ },
+ }
+
+ result := FromPBSBackups(backups, candidatesByKey)
+ if len(result) != 1 {
+ t.Fatalf("expected 1 point, got %d", len(result))
+ }
+
+ expectedRID := unifiedresources.SourceSpecificID(
+ unifiedresources.ResourceTypeSystemContainer,
+ unifiedresources.SourceProxmox,
+ "system-container-fb42a70d89bd20a6",
+ )
+
+ if got := result[0].SubjectResourceID; got != expectedRID {
+ t.Fatalf("SubjectResourceID = %q, want %q", got, expectedRID)
+ }
+ if result[0].SubjectRef == nil || result[0].SubjectRef.Name != "debian-go" {
+ t.Fatalf("SubjectRef = %#v, want linked debian-go guest", result[0].SubjectRef)
+ }
+}
diff --git a/internal/recovery/recovery_test.go b/internal/recovery/recovery_test.go
index 7eeab0b43d..f172bd279e 100644
--- a/internal/recovery/recovery_test.go
+++ b/internal/recovery/recovery_test.go
@@ -4,6 +4,8 @@ import (
"strings"
"testing"
"time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
func TestDeriveIndex(t *testing.T) {
@@ -561,6 +563,128 @@ func TestSubjectKey(t *testing.T) {
}
}
+func TestSubjectKey_CanonicalizesProxmoxLinkedGuestAliases(t *testing.T) {
+ t.Parallel()
+
+ expectedContainerRID := unifiedresources.SourceSpecificID(
+ unifiedresources.ResourceTypeSystemContainer,
+ unifiedresources.SourceProxmox,
+ "system-container-fb42a70d89bd20a6",
+ )
+
+ tests := []struct {
+ name string
+ subjectResourceID string
+ subjectRef *ExternalRef
+ expected string
+ }{
+ {
+ name: "current canonical hashed container id stays stable",
+ subjectResourceID: expectedContainerRID,
+ subjectRef: &ExternalRef{
+ Type: "proxmox-lxc",
+ Namespace: "delly",
+ Name: "debian-go",
+ ID: "system-container-fb42a70d89bd20a6",
+ Class: "minipc",
+ },
+ expected: "res:" + expectedContainerRID,
+ },
+ {
+ name: "legacy raw container source id is re-keyed to canonical hash",
+ subjectResourceID: "system-container-fb42a70d89bd20a6",
+ subjectRef: &ExternalRef{
+ Type: "proxmox-lxc",
+ Namespace: "delly",
+ Name: "debian-go",
+ ID: "delly:minipc:112",
+ Class: "minipc",
+ },
+ expected: "res:" + expectedContainerRID,
+ },
+ {
+ name: "legacy lxc-prefixed id is normalized before hashing",
+ subjectResourceID: "lxc-fb42a70d89bd20a6",
+ subjectRef: &ExternalRef{
+ Type: "proxmox-lxc",
+ Namespace: "delly",
+ Name: "debian-go",
+ ID: "delly:minipc:112",
+ Class: "minipc",
+ },
+ expected: "res:" + expectedContainerRID,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := SubjectKey(ProviderProxmoxPBS, tc.subjectResourceID, tc.subjectRef)
+ if got != tc.expected {
+ t.Fatalf("SubjectKey() = %q, want %q", got, tc.expected)
+ }
+ })
+ }
+}
+
+func TestSubjectKey_ProxmoxExternalGuestIgnoresNameDrift(t *testing.T) {
+ t.Parallel()
+
+ first := SubjectKey(ProviderProxmoxPBS, "", &ExternalRef{
+ Type: "proxmox-lxc",
+ Namespace: "pbs-docker",
+ Name: "socat",
+ ID: "900",
+ })
+ second := SubjectKey(ProviderProxmoxPBS, "", &ExternalRef{
+ Type: "proxmox-lxc",
+ Namespace: "pbs-docker",
+ Name: "900",
+ ID: "900",
+ })
+
+ if first == "" || second == "" {
+ t.Fatalf("expected proxmox external guest keys to be present, got %q and %q", first, second)
+ }
+ if first != second {
+ t.Fatalf("SubjectKey() should ignore proxmox external guest name drift, got %q vs %q", first, second)
+ }
+}
+
+func TestProxmoxPBSGuestContinuityKey(t *testing.T) {
+ t.Parallel()
+
+ got := ProxmoxPBSGuestContinuityKey("pulse-v4-prod", "system-container", "pimox", "140")
+ want := "proxmox-pbs-guest:system-container:pimox:140:pulse-v4-prod"
+ if got != want {
+ t.Fatalf("ProxmoxPBSGuestContinuityKey() = %q, want %q", got, want)
+ }
+
+ if got := ProxmoxPBSGuestContinuityKey("140", "system-container", "pimox", "140"); got != "" {
+ t.Fatalf("numeric-only label continuity key = %q, want empty", got)
+ }
+
+ point := RecoveryPoint{
+ ID: "pbs-backup-140",
+ Provider: ProviderProxmoxPBS,
+ SubjectRef: &ExternalRef{
+ Type: "proxmox-lxc",
+ Namespace: "pbs-docker",
+ Name: "pulse-v4-prod",
+ ID: "140",
+ },
+ Details: map[string]any{
+ "backupType": "ct",
+ "comment": "pulse-v4-prod, pi, 140",
+ "namespace": "pimox",
+ "vmid": "140",
+ },
+ }
+
+ if got := ProxmoxPBSGuestContinuityKeyForPoint(point); got != want {
+ t.Fatalf("ProxmoxPBSGuestContinuityKeyForPoint() = %q, want %q", got, want)
+ }
+}
+
func TestRepositoryKey(t *testing.T) {
tests := []struct {
name string
diff --git a/internal/recovery/store/store.go b/internal/recovery/store/store.go
index bb8716f499..d12de6b408 100644
--- a/internal/recovery/store/store.go
+++ b/internal/recovery/store/store.go
@@ -39,6 +39,241 @@ type Store struct {
lastPrune time.Time
}
+type historicalSubjectIdentity struct {
+ subjectResourceID string
+ subjectRef *recovery.ExternalRef
+ tsMs int64
+}
+
+func cloneExternalRef(ref *recovery.ExternalRef) *recovery.ExternalRef {
+ if ref == nil {
+ return nil
+ }
+ cloned := &recovery.ExternalRef{
+ Type: strings.TrimSpace(ref.Type),
+ Namespace: strings.TrimSpace(ref.Namespace),
+ Name: strings.TrimSpace(ref.Name),
+ UID: strings.TrimSpace(ref.UID),
+ ID: strings.TrimSpace(ref.ID),
+ Class: strings.TrimSpace(ref.Class),
+ }
+ if len(ref.Extra) > 0 {
+ cloned.Extra = make(map[string]string, len(ref.Extra))
+ for k, v := range ref.Extra {
+ cloned.Extra[strings.TrimSpace(k)] = strings.TrimSpace(v)
+ }
+ }
+ return cloned
+}
+
+func pointLatestMillis(p recovery.RecoveryPoint) int64 {
+ if p.CompletedAt != nil {
+ return p.CompletedAt.UTC().UnixMilli()
+ }
+ if p.StartedAt != nil {
+ return p.StartedAt.UTC().UnixMilli()
+ }
+ return 0
+}
+
+func isLikelyUnresolvedProxmoxPBSGuestRef(ref *recovery.ExternalRef) bool {
+ if ref == nil {
+ return true
+ }
+ if strings.TrimSpace(ref.Class) != "" {
+ return false
+ }
+
+ id := strings.TrimSpace(ref.ID)
+ if id == "" {
+ return true
+ }
+ if strings.Contains(id, ":") {
+ return false
+ }
+ if strings.HasPrefix(id, "vm-") || strings.HasPrefix(id, "system-container-") || strings.HasPrefix(id, "lxc-") {
+ return false
+ }
+ return true
+}
+
+func historicalSubjectIdentityFromPoint(p recovery.RecoveryPoint) (string, historicalSubjectIdentity) {
+ key := recovery.ProxmoxPBSGuestContinuityKeyForPoint(p)
+ if key == "" {
+ return "", historicalSubjectIdentity{}
+ }
+ rid := strings.TrimSpace(p.SubjectResourceID)
+ if rid == "" {
+ return "", historicalSubjectIdentity{}
+ }
+ return key, historicalSubjectIdentity{
+ subjectResourceID: rid,
+ subjectRef: cloneExternalRef(p.SubjectRef),
+ tsMs: pointLatestMillis(p),
+ }
+}
+
+func adoptHistoricalProxmoxPBSGuestIdentity(
+ p *recovery.RecoveryPoint,
+ identities map[string]historicalSubjectIdentity,
+ looseIdentities map[string]historicalSubjectIdentity,
+) {
+ if p == nil || (len(identities) == 0 && len(looseIdentities) == 0) {
+ return
+ }
+ if strings.TrimSpace(string(p.Provider)) != string(recovery.ProviderProxmoxPBS) {
+ return
+ }
+
+ key := recovery.ProxmoxPBSGuestContinuityKeyForPoint(*p)
+ identity, ok := identities[key]
+ if !ok {
+ idx := recovery.DeriveIndex(*p)
+ looseKey := recovery.ProxmoxPBSGuestLooseContinuityKey(
+ idx.SubjectLabel,
+ idx.ItemType,
+ idx.EntityIDLabel,
+ )
+ identity, ok = looseIdentities[looseKey]
+ }
+ if !ok || strings.TrimSpace(identity.subjectResourceID) == "" {
+ return
+ }
+ if strings.TrimSpace(p.SubjectResourceID) != "" && !isLikelyUnresolvedProxmoxPBSGuestRef(p.SubjectRef) {
+ return
+ }
+
+ p.SubjectResourceID = identity.subjectResourceID
+ if identity.subjectRef != nil {
+ p.SubjectRef = cloneExternalRef(identity.subjectRef)
+ }
+}
+
+func (s *Store) loadHistoricalProxmoxPBSGuestIdentities(ctx context.Context) (map[string]historicalSubjectIdentity, map[string]historicalSubjectIdentity, error) {
+ rows, err := s.db.QueryContext(ctx, `
+ SELECT
+ subject_resource_id,
+ subject_ref_json,
+ subject_label,
+ item_type,
+ namespace_label,
+ entity_id_label,
+ completed_at_ms,
+ started_at_ms,
+ updated_at_ms
+ FROM recovery_points
+ WHERE provider = 'proxmox-pbs'
+ AND subject_resource_id IS NOT NULL
+ AND TRIM(subject_resource_id) != ''
+ `)
+ if err != nil {
+ return nil, nil, err
+ }
+ defer rows.Close()
+
+ identities := make(map[string]historicalSubjectIdentity)
+ looseCandidates := make(map[string][]historicalSubjectIdentity)
+ for rows.Next() {
+ var (
+ subjectRID string
+ subjectRefRaw sql.NullString
+ subjectLabel sql.NullString
+ itemType sql.NullString
+ namespace sql.NullString
+ entityID sql.NullString
+ completedAtMs sql.NullInt64
+ startedAtMs sql.NullInt64
+ updatedAtMs sql.NullInt64
+ )
+ if err := rows.Scan(
+ &subjectRID,
+ &subjectRefRaw,
+ &subjectLabel,
+ &itemType,
+ &namespace,
+ &entityID,
+ &completedAtMs,
+ &startedAtMs,
+ &updatedAtMs,
+ ); err != nil {
+ return nil, nil, err
+ }
+
+ key := recovery.ProxmoxPBSGuestContinuityKey(
+ subjectLabel.String,
+ itemType.String,
+ namespace.String,
+ entityID.String,
+ )
+ if key == "" {
+ continue
+ }
+ looseKey := recovery.ProxmoxPBSGuestLooseContinuityKey(
+ subjectLabel.String,
+ itemType.String,
+ entityID.String,
+ )
+
+ var subjectRef recovery.ExternalRef
+ _ = unmarshalJSON(subjectRefRaw, &subjectRef)
+ var refPtr *recovery.ExternalRef
+ if strings.TrimSpace(subjectRef.Type) != "" {
+ refPtr = &subjectRef
+ }
+
+ tsMs := updatedAtMs.Int64
+ if completedAtMs.Valid && completedAtMs.Int64 > tsMs {
+ tsMs = completedAtMs.Int64
+ }
+ if startedAtMs.Valid && startedAtMs.Int64 > tsMs {
+ tsMs = startedAtMs.Int64
+ }
+
+ current, exists := identities[key]
+ if exists && current.tsMs > tsMs {
+ continue
+ }
+ identities[key] = historicalSubjectIdentity{
+ subjectResourceID: strings.TrimSpace(subjectRID),
+ subjectRef: cloneExternalRef(refPtr),
+ tsMs: tsMs,
+ }
+ if looseKey != "" {
+ looseCandidates[looseKey] = append(looseCandidates[looseKey], historicalSubjectIdentity{
+ subjectResourceID: strings.TrimSpace(subjectRID),
+ subjectRef: cloneExternalRef(refPtr),
+ tsMs: tsMs,
+ })
+ }
+ }
+ if err := rows.Err(); err != nil {
+ return nil, nil, err
+ }
+
+ looseIdentities := make(map[string]historicalSubjectIdentity)
+ for key, candidates := range looseCandidates {
+ seen := make(map[string]historicalSubjectIdentity)
+ for _, candidate := range candidates {
+ rid := strings.TrimSpace(candidate.subjectResourceID)
+ if rid == "" {
+ continue
+ }
+ current, exists := seen[rid]
+ if !exists || current.tsMs < candidate.tsMs {
+ seen[rid] = candidate
+ }
+ }
+ if len(seen) != 1 {
+ continue
+ }
+ for _, candidate := range seen {
+ looseIdentities[key] = candidate
+ }
+ }
+
+ return identities, looseIdentities, nil
+}
+
func ensureOwnerOnlyDir(dir string) error {
if err := os.MkdirAll(dir, privateDirPerm); err != nil {
return err
@@ -124,6 +359,9 @@ func Open(dbPath string) (*Store, error) {
// Best-effort backfill for deployments that wrote points before index columns existed.
// This should never block startup; missing backfills only affect filter UX.
_ = store.BackfillIndex(context.Background())
+ // Best-effort backfill for PBS guest rows that predate canonical historical continuity.
+ // This should never block startup; missing backfills only affect protected-item accuracy.
+ _ = store.BackfillHistoricalProxmoxPBSGuestIdentity(context.Background())
if err := hardenSQLiteArtifacts(dbPath); err != nil {
_ = db.Close()
return nil, fmt.Errorf("failed to secure recovery db files: %w", err)
@@ -334,14 +572,82 @@ func (s *Store) BackfillKeys(ctx context.Context) error {
ctx = context.Background()
}
- // Fast path: resource-linked keys can be derived directly in SQL.
- _, _ = s.db.ExecContext(ctx, `
- UPDATE recovery_points
- SET subject_key = 'res:' || subject_resource_id
- WHERE (subject_key IS NULL OR subject_key = '')
- AND subject_resource_id IS NOT NULL
- AND TRIM(subject_resource_id) != ''
+ // Subject keys own rollup truth, so proxmox guest rows need canonical Go-side normalization
+ // even when a subject key already exists in the DB.
+ const maxBackfillRows = 5000
+
+ rows, err := s.db.QueryContext(ctx, `
+ SELECT id, provider, subject_key, subject_resource_id, subject_ref_json
+ FROM recovery_points
+ WHERE
+ (subject_key IS NULL OR subject_key = '') OR
+ provider IN ('proxmox-pve', 'proxmox-pbs')
+ LIMIT `+fmt.Sprint(maxBackfillRows)+`
`)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ type subjectRow struct {
+ id string
+ provider string
+ subjectKey sql.NullString
+ rid string
+ refRaw sql.NullString
+ }
+
+ subjectItems := make([]subjectRow, 0, 256)
+ for rows.Next() {
+ var item subjectRow
+ if err := rows.Scan(&item.id, &item.provider, &item.subjectKey, &item.rid, &item.refRaw); err != nil {
+ return err
+ }
+ subjectItems = append(subjectItems, item)
+ }
+ if err := rows.Err(); err != nil {
+ return err
+ }
+
+ if len(subjectItems) > 0 {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback() }()
+
+ stmt, err := tx.PrepareContext(ctx, "UPDATE recovery_points SET subject_key = ? WHERE id = ?")
+ if err != nil {
+ return err
+ }
+ defer stmt.Close()
+
+ for _, item := range subjectItems {
+ var ref recovery.ExternalRef
+ _ = unmarshalJSON(item.refRaw, &ref) // best-effort
+ var refPtr *recovery.ExternalRef
+ if strings.TrimSpace(ref.Type) != "" {
+ refPtr = &ref
+ }
+
+ key := recovery.SubjectKey(
+ recovery.Provider(strings.TrimSpace(item.provider)),
+ strings.TrimSpace(item.rid),
+ refPtr,
+ )
+ if strings.TrimSpace(key) == "" || strings.TrimSpace(item.subjectKey.String) == key {
+ continue
+ }
+ if _, err := stmt.ExecContext(ctx, key, item.id); err != nil {
+ return err
+ }
+ }
+
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+ }
+
_, _ = s.db.ExecContext(ctx, `
UPDATE recovery_points
SET repository_key = 'res:' || repository_resource_id
@@ -350,8 +656,7 @@ func (s *Store) BackfillKeys(ctx context.Context) error {
AND TRIM(repository_resource_id) != ''
`)
- // External refs require JSON decode + hashing in Go. Keep it bounded.
- const maxBackfillRows = 2000
+ // External repository refs require JSON decode + hashing in Go. Keep it bounded.
backfillExternal := func(selectSQL string, targetCol string, keyFn func(provider recovery.Provider, rid string, ref *recovery.ExternalRef) string) error {
rows, err := s.db.QueryContext(ctx, selectSQL)
@@ -417,19 +722,6 @@ func (s *Store) BackfillKeys(ctx context.Context) error {
return nil
}
- _ = backfillExternal(
- `
- SELECT id, provider, subject_resource_id, subject_ref_json
- FROM recovery_points
- WHERE (subject_key IS NULL OR subject_key = '')
- LIMIT `+fmt.Sprint(maxBackfillRows)+`
- `,
- "subject_key",
- func(provider recovery.Provider, rid string, ref *recovery.ExternalRef) string {
- return recovery.SubjectKey(provider, rid, ref)
- },
- )
-
_ = backfillExternal(
`
SELECT id, provider, repository_resource_id, repository_ref_json
@@ -553,6 +845,11 @@ func (s *Store) UpsertPoints(ctx context.Context, points []recovery.RecoveryPoin
s.maybePrune(ctx)
+ proxmoxPBSIdentities, proxmoxPBSLooseIdentities, err := s.loadHistoricalProxmoxPBSGuestIdentities(ctx)
+ if err != nil {
+ return err
+ }
+
nowMs := time.Now().UTC().UnixMilli()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
@@ -613,6 +910,8 @@ func (s *Store) UpsertPoints(ctx context.Context, points []recovery.RecoveryPoin
defer stmt.Close()
for _, p := range points {
+ adoptHistoricalProxmoxPBSGuestIdentity(&p, proxmoxPBSIdentities, proxmoxPBSLooseIdentities)
+
id := strings.TrimSpace(p.ID)
if id == "" {
continue
@@ -645,7 +944,7 @@ func (s *Store) UpsertPoints(ctx context.Context, points []recovery.RecoveryPoin
subjectRID := strings.TrimSpace(p.SubjectResourceID)
repoRID := strings.TrimSpace(p.RepositoryResourceID)
- subjectKey := recovery.SubjectKey(p.Provider, subjectRID, p.SubjectRef)
+ subjectKey := recovery.SubjectKeyForPoint(p)
repoKey := recovery.RepositoryKey(p.Provider, repoRID, p.RepositoryRef)
idx := recovery.DeriveIndex(p)
@@ -690,6 +989,216 @@ func (s *Store) UpsertPoints(ctx context.Context, points []recovery.RecoveryPoin
); err != nil {
return err
}
+
+ if key, identity := historicalSubjectIdentityFromPoint(p); key != "" {
+ current, exists := proxmoxPBSIdentities[key]
+ if !exists || current.tsMs <= identity.tsMs {
+ proxmoxPBSIdentities[key] = identity
+ }
+ }
+ }
+
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// BackfillHistoricalProxmoxPBSGuestIdentity relinks older or unresolved PBS guest rows to the
+// strongest known linked identity when the same namespace/type/vmid/label has already been seen.
+func (s *Store) BackfillHistoricalProxmoxPBSGuestIdentity(ctx context.Context) error {
+ if err := s.ensureInitialized(); err != nil {
+ return err
+ }
+ if ctx == nil {
+ ctx = context.Background()
+ }
+
+ identities, looseIdentities, err := s.loadHistoricalProxmoxPBSGuestIdentities(ctx)
+ if err != nil {
+ return err
+ }
+ if len(identities) == 0 && len(looseIdentities) == 0 {
+ return nil
+ }
+
+ const maxBackfillRows = 5000
+ rows, err := s.db.QueryContext(ctx, `
+ SELECT
+ id, provider, kind, mode, outcome,
+ subject_resource_id, repository_resource_id,
+ subject_ref_json, repository_ref_json, details_json,
+ subject_label, item_type, namespace_label, entity_id_label
+ FROM recovery_points
+ WHERE provider = 'proxmox-pbs'
+ LIMIT `+fmt.Sprint(maxBackfillRows)+`
+ `)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+
+ type item struct {
+ id string
+ provider string
+ kind string
+ mode string
+ outcome string
+ subjectRID sql.NullString
+ repositoryRID sql.NullString
+ subjectRefRaw sql.NullString
+ repositoryRaw sql.NullString
+ detailsRaw sql.NullString
+ subjectLabel sql.NullString
+ itemType sql.NullString
+ namespaceLabel sql.NullString
+ entityIDLabel sql.NullString
+ }
+
+ items := make([]item, 0, 256)
+ for rows.Next() {
+ var r item
+ if err := rows.Scan(
+ &r.id,
+ &r.provider,
+ &r.kind,
+ &r.mode,
+ &r.outcome,
+ &r.subjectRID,
+ &r.repositoryRID,
+ &r.subjectRefRaw,
+ &r.repositoryRaw,
+ &r.detailsRaw,
+ &r.subjectLabel,
+ &r.itemType,
+ &r.namespaceLabel,
+ &r.entityIDLabel,
+ ); err != nil {
+ return err
+ }
+ items = append(items, r)
+ }
+ if err := rows.Err(); err != nil {
+ return err
+ }
+ if len(items) == 0 {
+ return nil
+ }
+
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback() }()
+
+ stmt, err := tx.PrepareContext(ctx, `
+ UPDATE recovery_points
+ SET
+ subject_key = ?,
+ subject_resource_id = ?,
+ subject_ref_json = ?,
+ subject_label = ?,
+ subject_type = ?,
+ item_type = ?,
+ is_workload = ?,
+ cluster_label = ?,
+ node_host_label = ?,
+ namespace_label = ?,
+ entity_id_label = ?,
+ repository_label = ?,
+ details_summary = ?
+ WHERE id = ?
+ `)
+ if err != nil {
+ return err
+ }
+ defer stmt.Close()
+
+ for _, item := range items {
+ key := recovery.ProxmoxPBSGuestContinuityKey(
+ item.subjectLabel.String,
+ item.itemType.String,
+ item.namespaceLabel.String,
+ item.entityIDLabel.String,
+ )
+ identity, ok := identities[key]
+ if !ok {
+ looseKey := recovery.ProxmoxPBSGuestLooseContinuityKey(
+ item.subjectLabel.String,
+ item.itemType.String,
+ item.entityIDLabel.String,
+ )
+ identity, ok = looseIdentities[looseKey]
+ }
+ if !ok || strings.TrimSpace(identity.subjectResourceID) == "" {
+ continue
+ }
+
+ var subjectRef recovery.ExternalRef
+ _ = unmarshalJSON(item.subjectRefRaw, &subjectRef)
+ var subjectRefPtr *recovery.ExternalRef
+ if strings.TrimSpace(subjectRef.Type) != "" {
+ subjectRefPtr = &subjectRef
+ }
+
+ currentRID := strings.TrimSpace(item.subjectRID.String)
+ if currentRID == identity.subjectResourceID && !isLikelyUnresolvedProxmoxPBSGuestRef(subjectRefPtr) {
+ continue
+ }
+
+ var repositoryRef recovery.ExternalRef
+ _ = unmarshalJSON(item.repositoryRaw, &repositoryRef)
+ var repositoryRefPtr *recovery.ExternalRef
+ if strings.TrimSpace(repositoryRef.Type) != "" {
+ repositoryRefPtr = &repositoryRef
+ }
+
+ var details map[string]any
+ _ = unmarshalJSON(item.detailsRaw, &details)
+
+ p := recovery.RecoveryPoint{
+ ID: strings.TrimSpace(item.id),
+ Provider: recovery.Provider(strings.TrimSpace(item.provider)),
+ Kind: recovery.Kind(strings.TrimSpace(item.kind)),
+ Mode: recovery.Mode(strings.TrimSpace(item.mode)),
+ Outcome: recovery.Outcome(strings.TrimSpace(item.outcome)),
+ SubjectResourceID: identity.subjectResourceID,
+ RepositoryResourceID: strings.TrimSpace(item.repositoryRID.String),
+ SubjectRef: cloneExternalRef(identity.subjectRef),
+ RepositoryRef: repositoryRefPtr,
+ Details: details,
+ }
+
+ idx := recovery.DeriveIndex(p)
+ isWorkload := 0
+ if idx.IsWorkload {
+ isWorkload = 1
+ }
+
+ subjectRefJSON, err := marshalJSON(p.SubjectRef)
+ if err != nil {
+ return err
+ }
+
+ if _, err := stmt.ExecContext(
+ ctx,
+ recovery.SubjectKeyForPoint(p),
+ p.SubjectResourceID,
+ nullStringToAny(subjectRefJSON),
+ strings.TrimSpace(idx.SubjectLabel),
+ strings.TrimSpace(idx.SubjectType),
+ strings.TrimSpace(idx.ItemType),
+ isWorkload,
+ strings.TrimSpace(idx.ClusterLabel),
+ strings.TrimSpace(idx.NodeHostLabel),
+ strings.TrimSpace(idx.NamespaceLabel),
+ strings.TrimSpace(idx.EntityIDLabel),
+ strings.TrimSpace(idx.RepositoryLabel),
+ strings.TrimSpace(idx.DetailsSummary),
+ p.ID,
+ ); err != nil {
+ return err
+ }
}
if err := tx.Commit(); err != nil {
diff --git a/internal/recovery/store/store_test.go b/internal/recovery/store/store_test.go
index 2538f99687..7f3bfc0ecb 100644
--- a/internal/recovery/store/store_test.go
+++ b/internal/recovery/store/store_test.go
@@ -9,6 +9,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/recovery"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
func TestStore_UpsertAndList(t *testing.T) {
@@ -287,6 +288,370 @@ func TestStore_OpenBackfillsLegacyNumericPBSSubjectLabels(t *testing.T) {
}
}
+func TestStore_OpenBackfillsLegacyProxmoxGuestSubjectKeys(t *testing.T) {
+ t.Parallel()
+
+ dir := t.TempDir()
+ dbPath := filepath.Join(dir, "recovery.db")
+
+ store, err := Open(dbPath)
+ if err != nil {
+ t.Fatalf("Open() error = %v", err)
+ }
+
+ legacyTime := time.Date(2026, 3, 4, 4, 3, 10, 0, time.UTC)
+ currentTime := time.Date(2026, 3, 29, 3, 3, 31, 0, time.UTC)
+ currentRID := unifiedresources.SourceSpecificID(
+ unifiedresources.ResourceTypeSystemContainer,
+ unifiedresources.SourceProxmox,
+ "system-container-fb42a70d89bd20a6",
+ )
+
+ points := []recovery.RecoveryPoint{
+ {
+ ID: "pbs-backup-legacy-lxc-id",
+ Provider: recovery.ProviderProxmoxPBS,
+ Kind: recovery.KindBackup,
+ Mode: recovery.ModeRemote,
+ Outcome: recovery.OutcomeSuccess,
+ StartedAt: &legacyTime,
+ CompletedAt: &legacyTime,
+ SubjectResourceID: "lxc-fb42a70d89bd20a6",
+ SubjectRef: &recovery.ExternalRef{
+ Type: "proxmox-lxc",
+ Namespace: "delly",
+ Name: "debian-go",
+ ID: "delly:minipc:112",
+ Class: "minipc",
+ },
+ Details: map[string]any{
+ "backupType": "ct",
+ "comment": "debian-go",
+ "vmid": "112",
+ },
+ },
+ {
+ ID: "pbs-backup-current-canonical-id",
+ Provider: recovery.ProviderProxmoxPBS,
+ Kind: recovery.KindBackup,
+ Mode: recovery.ModeRemote,
+ Outcome: recovery.OutcomeSuccess,
+ StartedAt: &currentTime,
+ CompletedAt: &currentTime,
+ SubjectResourceID: currentRID,
+ SubjectRef: &recovery.ExternalRef{
+ Type: "proxmox-lxc",
+ Namespace: "delly",
+ Name: "debian-go",
+ ID: "system-container-fb42a70d89bd20a6",
+ Class: "minipc",
+ },
+ Details: map[string]any{
+ "backupType": "ct",
+ "comment": "debian-go",
+ "vmid": "112",
+ },
+ },
+ }
+
+ if err := store.UpsertPoints(context.Background(), points); err != nil {
+ t.Fatalf("UpsertPoints() error = %v", err)
+ }
+
+ if _, err := store.db.ExecContext(
+ context.Background(),
+ `UPDATE recovery_points
+ SET subject_key = CASE
+ WHEN id = ? THEN ?
+ WHEN id = ? THEN ?
+ ELSE subject_key
+ END
+ WHERE id IN (?, ?)`,
+ points[0].ID,
+ "res:lxc-fb42a70d89bd20a6",
+ points[1].ID,
+ "res:system-container-fb42a70d89bd20a6",
+ points[0].ID,
+ points[1].ID,
+ ); err != nil {
+ t.Fatalf("degrade legacy proxmox subject keys: %v", err)
+ }
+
+ if err := store.Close(); err != nil {
+ t.Fatalf("Close() error = %v", err)
+ }
+
+ reopened, err := Open(dbPath)
+ if err != nil {
+ t.Fatalf("reopen Open() error = %v", err)
+ }
+ t.Cleanup(func() { _ = reopened.Close() })
+
+ rollups, total, err := reopened.ListRollups(context.Background(), recovery.ListPointsOptions{Page: 1, Limit: 50})
+ if err != nil {
+ t.Fatalf("ListRollups() error = %v", err)
+ }
+ if total != 1 || len(rollups) != 1 {
+ t.Fatalf("ListRollups() total=%d len=%d, want 1/1", total, len(rollups))
+ }
+ if rollups[0].LastSuccessAt == nil || !rollups[0].LastSuccessAt.Equal(currentTime) {
+ t.Fatalf("LastSuccessAt = %v, want %v", rollups[0].LastSuccessAt, currentTime)
+ }
+ if rollups[0].SubjectResourceID != currentRID {
+ t.Fatalf("SubjectResourceID = %q, want %q", rollups[0].SubjectResourceID, currentRID)
+ }
+ if rollups[0].Display == nil || rollups[0].Display.SubjectLabel != "debian-go" {
+ t.Fatalf("Display = %#v, want subject label debian-go", rollups[0].Display)
+ }
+}
+
+func TestStore_UpsertPointsRelinksHistoricalProxmoxPBSGuestIdentity(t *testing.T) {
+ t.Parallel()
+
+ dir := t.TempDir()
+ dbPath := filepath.Join(dir, "recovery.db")
+
+ store, err := Open(dbPath)
+ if err != nil {
+ t.Fatalf("Open() error = %v", err)
+ }
+ t.Cleanup(func() { _ = store.Close() })
+
+ linkedTime := time.Date(2026, 2, 23, 2, 30, 19, 0, time.UTC)
+ currentTime := time.Date(2026, 3, 29, 1, 30, 13, 0, time.UTC)
+ currentRID := unifiedresources.SourceSpecificID(
+ unifiedresources.ResourceTypeSystemContainer,
+ unifiedresources.SourceProxmox,
+ "pi:pi:140",
+ )
+
+ linked := recovery.RecoveryPoint{
+ ID: "pbs-linked-pulse-v4-prod",
+ Provider: recovery.ProviderProxmoxPBS,
+ Kind: recovery.KindBackup,
+ Mode: recovery.ModeRemote,
+ Outcome: recovery.OutcomeSuccess,
+ StartedAt: &linkedTime,
+ CompletedAt: &linkedTime,
+ SubjectResourceID: currentRID,
+ SubjectRef: &recovery.ExternalRef{
+ Type: "proxmox-lxc",
+ Namespace: "pi",
+ Name: "pulse-v4-prod",
+ ID: "pi:pi:140",
+ Class: "pi",
+ },
+ Details: map[string]any{
+ "backupType": "ct",
+ "comment": "pulse-v4-prod, pi, 140",
+ "namespace": "pimox",
+ "vmid": "140",
+ },
+ }
+ if err := store.UpsertPoints(context.Background(), []recovery.RecoveryPoint{linked}); err != nil {
+ t.Fatalf("UpsertPoints(linked) error = %v", err)
+ }
+
+ unresolved := recovery.RecoveryPoint{
+ ID: "pbs-unresolved-pulse-v4-prod",
+ Provider: recovery.ProviderProxmoxPBS,
+ Kind: recovery.KindBackup,
+ Mode: recovery.ModeRemote,
+ Outcome: recovery.OutcomeSuccess,
+ StartedAt: &currentTime,
+ CompletedAt: &currentTime,
+ SubjectRef: &recovery.ExternalRef{
+ Type: "proxmox-lxc",
+ Namespace: "pbs-docker",
+ Name: "pulse-v4-prod",
+ ID: "140",
+ },
+ Details: map[string]any{
+ "backupType": "ct",
+ "comment": "pulse-v4-prod, pi, 140",
+ "namespace": "pimox",
+ "vmid": "140",
+ },
+ }
+ if err := store.UpsertPoints(context.Background(), []recovery.RecoveryPoint{unresolved}); err != nil {
+ t.Fatalf("UpsertPoints(unresolved) error = %v", err)
+ }
+
+ points, total, err := store.ListPoints(context.Background(), recovery.ListPointsOptions{Page: 1, Limit: 50})
+ if err != nil {
+ t.Fatalf("ListPoints() error = %v", err)
+ }
+ if total != 2 || len(points) != 2 {
+ t.Fatalf("ListPoints() total=%d len=%d, want 2/2", total, len(points))
+ }
+
+ var newest recovery.RecoveryPoint
+ for _, point := range points {
+ if point.ID == unresolved.ID {
+ newest = point
+ break
+ }
+ }
+ if newest.ID == "" {
+ t.Fatalf("failed to find upserted unresolved point in ListPoints(): %#v", points)
+ }
+ if newest.SubjectResourceID != currentRID {
+ t.Fatalf("SubjectResourceID = %q, want %q", newest.SubjectResourceID, currentRID)
+ }
+ if newest.SubjectRef == nil || newest.SubjectRef.Class != "pi" || newest.SubjectRef.Namespace != "pi" {
+ t.Fatalf("SubjectRef = %#v, want linked pi guest ref", newest.SubjectRef)
+ }
+
+ rollups, rollupTotal, err := store.ListRollups(context.Background(), recovery.ListPointsOptions{Page: 1, Limit: 50})
+ if err != nil {
+ t.Fatalf("ListRollups() error = %v", err)
+ }
+ if rollupTotal != 1 || len(rollups) != 1 {
+ t.Fatalf("ListRollups() total=%d len=%d, want 1/1", rollupTotal, len(rollups))
+ }
+ if rollups[0].LastSuccessAt == nil || !rollups[0].LastSuccessAt.Equal(currentTime) {
+ t.Fatalf("LastSuccessAt = %v, want %v", rollups[0].LastSuccessAt, currentTime)
+ }
+ if rollups[0].SubjectResourceID != currentRID {
+ t.Fatalf("SubjectResourceID = %q, want %q", rollups[0].SubjectResourceID, currentRID)
+ }
+}
+
+func TestStore_OpenBackfillsLegacyUnresolvedProxmoxPBSGuestRows(t *testing.T) {
+ t.Parallel()
+
+ dir := t.TempDir()
+ dbPath := filepath.Join(dir, "recovery.db")
+
+ store, err := Open(dbPath)
+ if err != nil {
+ t.Fatalf("Open() error = %v", err)
+ }
+
+ linkedTime := time.Date(2026, 2, 23, 2, 30, 19, 0, time.UTC)
+ currentTime := time.Date(2026, 3, 29, 1, 30, 13, 0, time.UTC)
+ currentRID := unifiedresources.SourceSpecificID(
+ unifiedresources.ResourceTypeSystemContainer,
+ unifiedresources.SourceProxmox,
+ "pi:pi:140",
+ )
+
+ linked := recovery.RecoveryPoint{
+ ID: "pbs-linked-pulse-v4-prod",
+ Provider: recovery.ProviderProxmoxPBS,
+ Kind: recovery.KindBackup,
+ Mode: recovery.ModeRemote,
+ Outcome: recovery.OutcomeSuccess,
+ StartedAt: &linkedTime,
+ CompletedAt: &linkedTime,
+ SubjectResourceID: currentRID,
+ SubjectRef: &recovery.ExternalRef{
+ Type: "proxmox-lxc",
+ Namespace: "pi",
+ Name: "pulse-v4-prod",
+ ID: "pi:pi:140",
+ Class: "pi",
+ },
+ Details: map[string]any{
+ "backupType": "ct",
+ "comment": "pulse-v4-prod, pi, 140",
+ "namespace": "pimox",
+ "vmid": "140",
+ },
+ }
+ unresolved := recovery.RecoveryPoint{
+ ID: "pbs-unresolved-pulse-v4-prod",
+ Provider: recovery.ProviderProxmoxPBS,
+ Kind: recovery.KindBackup,
+ Mode: recovery.ModeRemote,
+ Outcome: recovery.OutcomeSuccess,
+ StartedAt: &currentTime,
+ CompletedAt: &currentTime,
+ SubjectResourceID: currentRID,
+ SubjectRef: &recovery.ExternalRef{
+ Type: "proxmox-lxc",
+ Namespace: "pi",
+ Name: "pulse-v4-prod",
+ ID: "pi:pi:140",
+ Class: "pi",
+ },
+ Details: map[string]any{
+ "backupType": "ct",
+ "comment": "pulse-v4-prod, pi, 140",
+ "namespace": "pimox",
+ "vmid": "140",
+ },
+ }
+ if err := store.UpsertPoints(context.Background(), []recovery.RecoveryPoint{linked, unresolved}); err != nil {
+ t.Fatalf("UpsertPoints() error = %v", err)
+ }
+
+ degradedRef := recovery.ExternalRef{
+ Type: "proxmox-lxc",
+ Namespace: "pbs-docker",
+ Name: "pulse-v4-prod",
+ ID: "140",
+ }
+ degradedRefJSON, err := json.Marshal(degradedRef)
+ if err != nil {
+ t.Fatalf("json.Marshal(degradedRef): %v", err)
+ }
+
+ if _, err := store.db.ExecContext(
+ context.Background(),
+ `UPDATE recovery_points
+ SET subject_key = ?,
+ subject_resource_id = '',
+ subject_ref_json = ?,
+ subject_label = ?,
+ subject_type = ?,
+ item_type = ?,
+ cluster_label = ?,
+ node_host_label = '',
+ namespace_label = ?,
+ entity_id_label = ?
+ WHERE id = ?`,
+ recovery.SubjectKey(recovery.ProviderProxmoxPBS, "", &degradedRef),
+ string(degradedRefJSON),
+ "pulse-v4-prod",
+ "proxmox-lxc",
+ "system-container",
+ "pbs-docker",
+ "pimox",
+ "140",
+ unresolved.ID,
+ ); err != nil {
+ t.Fatalf("degrade unresolved legacy pbs row: %v", err)
+ }
+
+ if err := store.Close(); err != nil {
+ t.Fatalf("Close() error = %v", err)
+ }
+
+ reopened, err := Open(dbPath)
+ if err != nil {
+ t.Fatalf("reopen Open() error = %v", err)
+ }
+ t.Cleanup(func() { _ = reopened.Close() })
+
+ rollups, total, err := reopened.ListRollups(context.Background(), recovery.ListPointsOptions{Page: 1, Limit: 50})
+ if err != nil {
+ t.Fatalf("ListRollups() error = %v", err)
+ }
+ if total != 1 || len(rollups) != 1 {
+ t.Fatalf("ListRollups() total=%d len=%d, want 1/1", total, len(rollups))
+ }
+ if rollups[0].LastSuccessAt == nil || !rollups[0].LastSuccessAt.Equal(currentTime) {
+ t.Fatalf("LastSuccessAt = %v, want %v", rollups[0].LastSuccessAt, currentTime)
+ }
+ if rollups[0].SubjectResourceID != currentRID {
+ t.Fatalf("SubjectResourceID = %q, want %q", rollups[0].SubjectResourceID, currentRID)
+ }
+ if rollups[0].Display == nil || rollups[0].Display.ClusterLabel != "pi" || rollups[0].Display.NodeHostLabel != "pi" {
+ t.Fatalf("Display = %#v, want linked pi identity after reopen backfill", rollups[0].Display)
+ }
+}
+
func TestStore_OpenBackfillsLegacyPVETaskSubjectLabels(t *testing.T) {
t.Parallel()