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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Give Proxmox guests node-independent canonical identity
rcourtmane74fea4bbc8f
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex dade07c570..8e46aa83b4 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -1082,7 +1082,21 @@ continues to emit its own `network-endpoint` supplemental record regardless ofthat correlation outcome; monitoring never substitutes a matched host orservice identity for the configured check. Monitoring does not perform thecorrelation decision itself; it only forwards the link hint for the registry-to resolve. Every completed probe also authors an operational-trust+to resolve.+Monitoring does own keeping that stored link hint current across canonical-ID+eras. On the same cadence as the alert-override migration,+`migrateAvailabilityLinksToCanonicalIDs`+(`internal/monitoring/availability_link_migration.go`) re-homes a+`LinkedResourceID` that references a retired canonical resource ID (declared+via `SupersededCanonicalIDs` by exactly one live resource) or a node-scoped+Proxmox guest source triple whose instance+VMID matches exactly one live+guest (#1669), rewriting it to the resource's current canonical ID and+persisting through `SaveAvailabilityTargets`. Only provider-declared+persistence keys migrate — never address, hostname, or display-alias+coincidences — ambiguous claims fail closed, and a link that resolves to a+live canonical ID is never touched, so the explicit link stays authoritative+and fail-closed. Regression coverage: `TestMigrateAvailabilityLinkedResources`+in `internal/monitoring/monitor_alert_override_migration_test.go`. Every completed probe also authors an operational-trust`EvidenceEnvelope` with provider `availability`, collector`availability-poller`, the saved target as its provider reference, the exactobservation/ingest times, and a validity window of twice the effective pollingdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 805f5e0767..42180bbb64 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -3330,6 +3330,20 @@ canonical linked guest identity for the same friendly label, guest type, andVMID/CTID, the store must relink later unresolved PBS points and backfill oldersplit rows onto that canonical protected item instead of leaving protectedinventory freshness to disagree with recovery events.+That same key boundary is node-independent for Proxmox guests (#1669).+Unified guest canonical IDs derive from instance+VMID+(`unifiedresources.ProxmoxGuestCanonicalID`), so recovery subject identity+must not embed the node a guest happened to run on: any subject resource ID+or external guest ref that still carries the node-scoped+`instance:node:vmid` source triple converges on the node-independent+derivation (`recovery.CanonicalSubjectResourceID`, the mapper's+registry-miss fallback in `subjectResourceID`, and the node-dropping arm of+`proxmoxGuestExternalKey`), and the store's startup `BackfillKeys` pass+rewrites historical `subject_resource_id` values and subject keys onto that+derivation — sweeping protection-posture rows stranded under retired+subject keys — so a live migration or a canonical-ID era change never forks+one guest's protected item into stale and fresh rows. Rows without a+recomputable guest identity keep their stored keys unchanged.That same hook-boundary normalization also owns the runtime recovery displaymodel. Canonical recovery points and rollups must expose `display.itemLabel`and `display.itemType` to recovery consumers, while legacy transport fieldsdiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex bf7c8441de..7e112a7cad 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -1678,6 +1678,49 @@ AI-only summary payloads, or page-local heuristics.`TestCloneResourceGivesRelationshipsTheirOwnBackingArray` in`internal/unifiedresources/clone_test.go`.+30. Keep Proxmox guest canonical IDs node-independent. VMIDs are unique+ within a cluster, so `ResourceTypeVM` / `ResourceTypeSystemContainer`+ resources ingested from `SourceProxmox` derive their canonical ID+ from `ResourceIdentity.ProxmoxGuestKey` (`instance:vmid`, hashed as+ `proxmox-guest:<instance>:<vmid>` in `canonicalIDFromIdentity`), not+ from the node-scoped source ID, so a live migration between cluster+ nodes never re-mints the guest (#1669). Guests without an+ instance+VMID identity — and VM resources from every other provider+ (TrueNAS, XCP-ng, libvirt, VMware) — keep the source-specific+ derivation. Ingest declares the retired node-scoped canonical IDs+ superseded for every node the instance currently knows (current+ names plus native aliases, `declareGuestSupersededEras`), so+ operator-owned rows orphaned by a pre-upgrade migration still re-key+ through record-declared succession, alert overrides migrate through+ `MigrateCanonicalOverrideKeys`, and explicit availability links and+ API reads keyed by a retired ID or a node-scoped guest source ID+ resolve through the registry's superseded index and+ `ParseProxmoxGuestSourceID` (persistence keys, never display+ aliases; ambiguity fails closed). Successions are durably recorded+ in the `canonical_id_successions` table, which memoizes the re-key+ (steady-state rebuilds re-declare the same eras every tick and must+ stay SQL-free) and lets change-journal reads merge retired guest+ eras without identity pins; pins remain host-only. The succession+ re-key also covers manual link/exclusion rows. Availability target+ configuration re-homes retired `LinkedResourceID` values through+ `migrateAvailabilityLinkedResources`+ (`internal/monitoring/availability_link_migration.go`), and recovery+ subjects converge on the same derivation through+ `CanonicalSubjectResourceID` plus the store's startup backfill.+ Metrics history and frontend row identity key off the node-scoped+ source ID and are deliberately unaffected. Regression coverage: the+ `TestProxmoxGuest*` cases in+ `internal/unifiedresources/registry_test.go`,+ `internal/unifiedresources/ids_test.go`,+ `internal/unifiedresources/adapters_test.go`, and+ `internal/unifiedresources/availability_link_test.go`;+ `TestSuccessionMergesGuestChangeJournalEras` in+ `internal/unifiedresources/store_test.go`; and the recovery-side pins+ in `internal/recovery/recovery_test.go`+ (`TestSubjectKey_CanonicalizesProxmoxLinkedGuestAliases`) and+ `internal/recovery/store/store_test.go`+ (`TestStore_OpenBackfillsLegacyUnresolvedProxmoxPBSGuestRows`).+## Current Statediff --git a/internal/ai/routing_test.go b/internal/ai/routing_test.goindex d3234a6954..c953feb9a9 100644--- a/internal/ai/routing_test.go+++ b/internal/ai/routing_test.go@@ -316,18 +316,19 @@ func TestRoutingError_ForAI(t *testing.T) {}func TestRouteToAgent_VMIDRoutingWithInstance(t *testing.T) {- // VMID 106 exists on two nodes within the same instance (cluster-b).- // The routing code calls lookupGuestsByVMID(106, "cluster-b") which returns- // both containers (multiple matches), then the collision resolution path- // picks the first match whose instance matches the request context.+ // VMID 106 briefly appears on two nodes of the same instance (cluster-b),+ // the transient dual report Proxmox emits mid live-migration. VMIDs are+ // unique within a cluster, so the registry's node-independent guest+ // identity (#1669) merges both reports into one resource and routing+ // resolves a single unambiguous guest instead of a phantom collision.snapshot := models.StateSnapshot{Nodes: []models.Node{{ID: "node/node-a", Name: "node-a", Instance: "cluster-b", Status: "online"},{ID: "node/node-b", Name: "node-b", Instance: "cluster-b", Status: "online"},},Containers: []models.Container{- {ID: "lxc/106-b", VMID: 106, Node: "node-b", Name: "ct-b", Instance: "cluster-b"},- {ID: "lxc/106-a", VMID: 106, Node: "node-a", Name: "ct-a", Instance: "cluster-b"},+ {ID: "cluster-b:node-b:106", VMID: 106, Node: "node-b", Name: "ct-migrating", Instance: "cluster-b"},+ {ID: "cluster-b:node-a:106", VMID: 106, Node: "node-a", Name: "ct-migrating", Instance: "cluster-b"},},}registry := unifiedresources.NewRegistry(nil)@@ -347,12 +348,11 @@ func TestRouteToAgent_VMIDRoutingWithInstance(t *testing.T) {if err != nil {t.Fatalf("unexpected error: %v", err)}- // Both containers match instance "cluster-b", so we get vmid_lookup_with_instance routing.- // The first matching container's node determines the agent.- if result.RoutingMethod != "vmid_lookup_with_instance" {- t.Errorf("RoutingMethod = %q, want %q", result.RoutingMethod, "vmid_lookup_with_instance")+ if result.RoutingMethod != "vmid_lookup" {+ t.Errorf("RoutingMethod = %q, want %q", result.RoutingMethod, "vmid_lookup")}- // The result should route to one of the agents that has a container with VMID 106+ // The merged guest lives on whichever node's report won the merge; either+ // agent is a correct owner-node target during the migration window.if result.AgentID != "agent-a" && result.AgentID != "agent-b" {t.Errorf("AgentID = %q, want agent-a or agent-b", result.AgentID)}diff --git a/internal/monitoring/availability_link_migration.go b/internal/monitoring/availability_link_migration.gonew file mode 100644index 0000000000..448f3d6998--- /dev/null+++ b/internal/monitoring/availability_link_migration.go@@ -0,0 +1,134 @@+package monitoring++import (+ "strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+ "github.com/rs/zerolog/log"+)++// migrateAvailabilityLinksToCanonicalIDs loads the availability target+// configuration, re-homes explicit links whose resource reference was retired+// by a canonical-ID succession or a guest live migration, and persists the+// result. Runs on the same cadence as the alert override migration; once+// every link references a live canonical ID it is a cheap no-op.+func (m *Monitor) migrateAvailabilityLinksToCanonicalIDs(resources []unifiedresources.Resource) {+ if m == nil || m.configPersist == nil || len(resources) == 0 {+ return+ }+ targets, err := m.configPersist.LoadAvailabilityTargets()+ if err != nil || len(targets) == 0 {+ return+ }+ migrated, changed := migrateAvailabilityLinkedResources(targets, resources)+ if !changed {+ return+ }+ if err := m.configPersist.SaveAvailabilityTargets(migrated); err != nil {+ log.Error().Err(err).Msg("failed to persist canonical availability link migration")+ return+ }+ log.Info().Msg("migrated availability links to current canonical resource IDs")+}++// migrateAvailabilityLinkedResources re-homes explicit availability links+// written under a retired canonical resource ID (or under a node-scoped guest+// source ID) onto the resource's current canonical ID. The explicit link is+// documented as authoritative and fail-closed, so only provider-declared+// persistence keys participate: a superseded canonical ID declared by exactly+// one live resource, or a Proxmox guest source reference whose instance+VMID+// matches exactly one live guest. Address or hostname coincidences never+// migrate a link.+//+// The returned slice shares unmodified entries with the input; the boolean+// reports whether any link changed.+func migrateAvailabilityLinkedResources(targets []config.AvailabilityTarget, resources []unifiedresources.Resource) ([]config.AvailabilityTarget, bool) {+ if len(targets) == 0 || len(resources) == 0 {+ return targets, false+ }++ hasLink := false+ for _, target := range targets {+ if strings.TrimSpace(target.LinkedResourceID) != "" {+ hasLink = true+ break+ }+ }+ if !hasLink {+ return targets, false+ }++ liveIDs := make(map[string]struct{}, len(resources))+ successors := make(map[string]string)+ ambiguous := make(map[string]struct{})+ guestIDsByKey := make(map[string][]string)++ for _, resource := range resources {+ currentID := unifiedresources.CanonicalResourceID(resource.ID)+ if currentID == "" {+ continue+ }+ liveIDs[currentID] = struct{}{}++ for _, supersededID := range resource.SupersededCanonicalIDs {+ oldID := unifiedresources.CanonicalResourceID(supersededID)+ if oldID == "" || oldID == currentID {+ continue+ }+ if existing, ok := successors[oldID]; ok && existing != currentID {+ delete(successors, oldID)+ ambiguous[oldID] = struct{}{}+ continue+ }+ if _, conflict := ambiguous[oldID]; conflict {+ continue+ }+ successors[oldID] = currentID+ }++ if resource.Proxmox != nil && resource.Proxmox.VMID > 0 {+ switch unifiedresources.CanonicalResourceType(resource.Type) {+ case unifiedresources.ResourceTypeVM, unifiedresources.ResourceTypeSystemContainer:+ key := unifiedresources.ProxmoxGuestIdentityKey(resource.Proxmox.Instance, resource.Proxmox.VMID)+ if key != "" {+ guestIDsByKey[key] = append(guestIDsByKey[key], currentID)+ }+ }+ }+ }++ changed := false+ out := targets+ for i, target := range targets {+ linkedID := strings.TrimSpace(target.LinkedResourceID)+ if linkedID == "" {+ continue+ }+ if _, live := liveIDs[linkedID]; live {+ continue+ }++ newID := successors[linkedID]+ if newID == "" {+ if instance, _, vmid, ok := unifiedresources.ParseProxmoxGuestSourceID(linkedID); ok {+ // Node segment deliberately ignored: the link must follow the+ // guest across live migrations. Ambiguity fails closed.+ if candidates := guestIDsByKey[unifiedresources.ProxmoxGuestIdentityKey(instance, vmid)]; len(candidates) == 1 {+ newID = candidates[0]+ }+ }+ }+ if newID == "" || newID == linkedID {+ continue+ }++ if !changed {+ out = make([]config.AvailabilityTarget, len(targets))+ copy(out, targets)+ changed = true+ }+ out[i].LinkedResourceID = newID+ }+ return out, changed+}diff --git a/internal/monitoring/monitor_alert_override_migration_test.go b/internal/monitoring/monitor_alert_override_migration_test.goindex 254767ee00..91be7ae53b 100644--- a/internal/monitoring/monitor_alert_override_migration_test.go+++ b/internal/monitoring/monitor_alert_override_migration_test.go@@ -205,3 +205,100 @@ func TestSyncUnifiedResourceAlertsPersistsAndEvaluatesTrueNASOverrideSuccession(t.Fatalf("restarted manager lost persisted TrueNAS hysteresis: %+v", override.Memory)}}++func TestMigrateAvailabilityLinkedResources(t *testing.T) {+ t.Parallel()++ guestID := unifiedresources.ProxmoxGuestCanonicalID(unifiedresources.ResourceTypeVM, "delly", 100)+ retiredID := unifiedresources.SourceSpecificID(unifiedresources.ResourceTypeVM, unifiedresources.SourceProxmox, "delly:pve1:100")+ resources := []unifiedresources.Resource{+ {+ ID: guestID,+ Type: unifiedresources.ResourceTypeVM,+ SupersededCanonicalIDs: []string{retiredID},+ Proxmox: &unifiedresources.ProxmoxData{+ Instance: "delly",+ VMID: 100,+ NodeName: "pve2",+ },+ },+ {+ ID: "agent-1234567890abcdef",+ Type: unifiedresources.ResourceTypeAgent,+ },+ }++ targets := []config.AvailabilityTarget{+ {ID: "t-live", LinkedResourceID: guestID},+ {ID: "t-retired", LinkedResourceID: retiredID},+ {ID: "t-old-node-source", LinkedResourceID: "delly:pve1:100"},+ {ID: "t-unrelated", LinkedResourceID: "agent-1234567890abcdef"},+ {ID: "t-unknown", LinkedResourceID: "delly:pve9:999"},+ {ID: "t-unlinked"},+ }++ migrated, changed := migrateAvailabilityLinkedResources(targets, resources)+ if !changed {+ t.Fatal("expected migration to report changes")+ }++ byID := make(map[string]config.AvailabilityTarget, len(migrated))+ for _, target := range migrated {+ byID[target.ID] = target+ }+ if got := byID["t-live"].LinkedResourceID; got != guestID {+ t.Fatalf("live link rewritten: %q", got)+ }+ if got := byID["t-retired"].LinkedResourceID; got != guestID {+ t.Fatalf("retired canonical link = %q, want %q", got, guestID)+ }+ if got := byID["t-old-node-source"].LinkedResourceID; got != guestID {+ t.Fatalf("old-node source link = %q, want %q", got, guestID)+ }+ if got := byID["t-unrelated"].LinkedResourceID; got != "agent-1234567890abcdef" {+ t.Fatalf("unrelated link rewritten: %q", got)+ }+ if got := byID["t-unknown"].LinkedResourceID; got != "delly:pve9:999" {+ t.Fatalf("unknown guest link rewritten: %q", got)+ }++ // Input slice must stay untouched: the migration returns a copy.+ if targets[1].LinkedResourceID != retiredID {+ t.Fatalf("input slice mutated: %q", targets[1].LinkedResourceID)+ }++ if _, changedAgain := migrateAvailabilityLinkedResources(migrated, resources); changedAgain {+ t.Fatal("second pass must be a no-op")+ }+}++// Two guests claiming the same retired ID (or the same instance+VMID) is+// ambiguous; the link must fail closed rather than re-home to either.+func TestMigrateAvailabilityLinkedResourcesFailsClosedOnAmbiguity(t *testing.T) {+ t.Parallel()++ retiredID := unifiedresources.SourceSpecificID(unifiedresources.ResourceTypeVM, unifiedresources.SourceProxmox, "delly:pve1:100")+ resources := []unifiedresources.Resource{+ {+ ID: "vm-aaaaaaaaaaaaaaaa",+ Type: unifiedresources.ResourceTypeVM,+ SupersededCanonicalIDs: []string{retiredID},+ Proxmox: &unifiedresources.ProxmoxData{Instance: "delly", VMID: 100},+ },+ {+ ID: "vm-bbbbbbbbbbbbbbbb",+ Type: unifiedresources.ResourceTypeVM,+ SupersededCanonicalIDs: []string{retiredID},+ Proxmox: &unifiedresources.ProxmoxData{Instance: "delly", VMID: 100},+ },+ }+ targets := []config.AvailabilityTarget{+ {ID: "t-ambiguous", LinkedResourceID: retiredID},+ {ID: "t-ambiguous-source", LinkedResourceID: "delly:pve1:100"},+ }++ migrated, changed := migrateAvailabilityLinkedResources(targets, resources)+ if changed {+ t.Fatalf("ambiguous claims must not migrate, got %+v", migrated)+ }+}diff --git a/internal/monitoring/monitor_alert_sync.go b/internal/monitoring/monitor_alert_sync.goindex b2415b3859..234310c3c1 100644--- a/internal/monitoring/monitor_alert_sync.go+++ b/internal/monitoring/monitor_alert_sync.go@@ -107,6 +107,8 @@ func (m *Monitor) syncUnifiedResourceAlertsToState(resources []unifiedresources.}}+ m.migrateAvailabilityLinksToCanonicalIDs(resources)+m.alertManager.CheckUnifiedResourceMetrics(resources)m.alertManager.SyncUnifiedResourceIncidents(resources)m.syncAlertsToState()diff --git a/internal/recovery/keys.go b/internal/recovery/keys.goindex 07cc3cb4a0..28fb31e4a0 100644--- a/internal/recovery/keys.go+++ b/internal/recovery/keys.go@@ -113,6 +113,16 @@ func normalizeProxmoxGuestSourceID(resourceType unifiedresources.ResourceType, sreturn normalized}+// CanonicalSubjectResourceID maps a stored proxmox guest subject resource ID+// to the guest's current canonical unified resource ID when the row carries+// enough identity to re-derive it. Non-guest rows and rows without a+// recognizable guest identity are returned unchanged. The store's startup+// backfill uses this to converge historical rows onto the node-independent+// guest derivation.+func CanonicalSubjectResourceID(provider Provider, subjectResourceID string, subjectRef *ExternalRef) string {+ return canonicalizeProxmoxLinkedSubjectResourceID(provider, subjectResourceID, subjectRef)+}+func canonicalizeProxmoxLinkedSubjectResourceID(provider Provider, subjectResourceID string, subjectRef *ExternalRef) string {rid := strings.TrimSpace(subjectResourceID)if rid == "" || !isProxmoxProvider(provider) {@@ -130,6 +140,29 @@ func canonicalizeProxmoxLinkedSubjectResourceID(provider Provider, subjectResourrefID = normalizeProxmoxGuestSourceID(resourceType, subjectRef.ID)}+ // Guest canonical IDs are node-independent (instance+VMID, #1669): a row+ // that still carries the node-scoped source triple re-derives through the+ // current ladder so a guest's rollup does not fork when it live-migrates.+ // The rid must plausibly refer to the ref's guest before it is adopted:+ // the current derivation, the retired node-scoped hash, or the raw triple+ // of the same instance+VMID on any node.+ if instance, _, vmid, ok := unifiedresources.ParseProxmoxGuestSourceID(refID); ok {+ nodeIndependentID := unifiedresources.ProxmoxGuestCanonicalID(resourceType, instance, vmid)+ legacyFromRef := unifiedresources.SourceSpecificID(resourceType, unifiedresources.SourceProxmox, refID)+ if rid == nodeIndependentID || normalizedRID == nodeIndependentID ||+ rid == legacyFromRef || normalizedRID == legacyFromRef ||+ normalizedRID == refID {+ return nodeIndependentID+ }+ if ridInstance, _, ridVMID, ridOK := unifiedresources.ParseProxmoxGuestSourceID(normalizedRID); ridOK &&+ ridInstance == instance && ridVMID == vmid {+ return nodeIndependentID+ }+ }+ if instance, _, vmid, ok := unifiedresources.ParseProxmoxGuestSourceID(normalizedRID); ok {+ return unifiedresources.ProxmoxGuestCanonicalID(resourceType, instance, vmid)+ }+if refID != "" {canonicalFromRef := unifiedresources.SourceSpecificID(resourceType, unifiedresources.SourceProxmox, refID)if rid == canonicalFromRef || normalizedRID == canonicalFromRef {@@ -177,13 +210,24 @@ func proxmoxGuestExternalKey(provider Provider, ref *ExternalRef) string {h.Write([]byte{0})}+ // A node-scoped source triple collapses to instance:vmid, and the node+ // label (Class) is excluded for those refs: guest identity is+ // node-independent (#1669), so an unlinked guest's backups do not split+ // into separate rollups when it live-migrates.+ externalID := normalizeProxmoxGuestSourceID(resourceType, ref.ID)+ nodeLabel := ref.Class+ if instance, _, vmid, ok := unifiedresources.ParseProxmoxGuestSourceID(externalID); ok {+ externalID = unifiedresources.ProxmoxGuestIdentityKey(instance, vmid)+ nodeLabel = ""+ }+write(subjectKeyExternalPrefix)write(string(provider))write(typeValue)write(ref.UID)- write(normalizeProxmoxGuestSourceID(resourceType, ref.ID))+ write(externalID)write(ref.Namespace)- write(ref.Class)+ write(nodeLabel)// Proxmox guest names are presentation data, not identity. Excluding Name prevents one guest// from splitting into multiple rollups when comments or display labels change.diff --git a/internal/recovery/mapper/proxmox/mapper.go b/internal/recovery/mapper/proxmox/mapper.goindex 2f7e6959d2..7c1cfef546 100644--- a/internal/recovery/mapper/proxmox/mapper.go+++ b/internal/recovery/mapper/proxmox/mapper.go@@ -44,6 +44,14 @@ func subjectResourceID(resourceType unifiedresources.ResourceType, resourceID, sreturn resourceID}if sourceID = strings.TrimSpace(sourceID); sourceID != "" {+ // Guests derive node-independently (instance+VMID, #1669) so a+ // registry miss during a boot window still mints the same subject ID+ // the live resource carries.+ if instance, _, vmid, ok := unifiedresources.ParseProxmoxGuestSourceID(sourceID); ok {+ if id := unifiedresources.ProxmoxGuestCanonicalID(resourceType, instance, vmid); id != "" {+ return id+ }+ }return unifiedresources.SourceSpecificID(resourceType, unifiedresources.SourceProxmox, sourceID)}return ""diff --git a/internal/recovery/mapper/proxmox/mapper_test.go b/internal/recovery/mapper/proxmox/mapper_test.goindex 419d491cdb..20da5d4953 100644--- a/internal/recovery/mapper/proxmox/mapper_test.go+++ b/internal/recovery/mapper/proxmox/mapper_test.go@@ -14,11 +14,9 @@ func TestSubjectResourceIDPrefersCanonicalIdentityAndFallsBackToSourceIdentity(tresourceType := unifiedresources.ResourceTypeVMsourceID := "pve-main:pve-a:100"- fallback := unifiedresources.SourceSpecificID(- resourceType,- unifiedresources.SourceProxmox,- sourceID,- )+ // A node-scoped source triple falls back to the node-independent guest+ // derivation so registry-miss rows key identically to the live resource.+ fallback := unifiedresources.ProxmoxGuestCanonicalID(resourceType, "pve-main", 100)tests := []struct {name stringdiff --git a/internal/recovery/recovery_test.go b/internal/recovery/recovery_test.goindex 78a3bd7a68..4c82821cc1 100644--- a/internal/recovery/recovery_test.go+++ b/internal/recovery/recovery_test.go@@ -571,6 +571,13 @@ func TestSubjectKey_CanonicalizesProxmoxLinkedGuestAliases(t *testing.T) {unifiedresources.SourceProxmox,"system-container-fb42a70d89bd20a6",)+ // Rows carrying the node-scoped source triple converge on the+ // node-independent guest derivation so rollups survive live migration.+ nodeIndependentRID := unifiedresources.ProxmoxGuestCanonicalID(+ unifiedresources.ResourceTypeSystemContainer,+ "delly",+ 112,+ )tests := []struct {name string@@ -591,7 +598,7 @@ func TestSubjectKey_CanonicalizesProxmoxLinkedGuestAliases(t *testing.T) {expected: "res:" + expectedContainerRID,},{- name: "legacy raw container source id is re-keyed to canonical hash",+ name: "legacy raw container source id is re-keyed to the node-independent id",subjectResourceID: "system-container-fb42a70d89bd20a6",subjectRef: &ExternalRef{Type: "proxmox-lxc",@@ -600,10 +607,10 @@ func TestSubjectKey_CanonicalizesProxmoxLinkedGuestAliases(t *testing.T) {ID: "delly:minipc:112",Class: "minipc",},- expected: "res:" + expectedContainerRID,+ expected: "res:" + nodeIndependentRID,},{- name: "legacy lxc-prefixed id is normalized before hashing",+ name: "legacy lxc-prefixed id is normalized before re-keying",subjectResourceID: "lxc-fb42a70d89bd20a6",subjectRef: &ExternalRef{Type: "proxmox-lxc",@@ -612,7 +619,7 @@ func TestSubjectKey_CanonicalizesProxmoxLinkedGuestAliases(t *testing.T) {ID: "delly:minipc:112",Class: "minipc",},- expected: "res:" + expectedContainerRID,+ expected: "res:" + nodeIndependentRID,},}diff --git a/internal/recovery/store/store.go b/internal/recovery/store/store.goindex dbcd125d9b..30e8645a54 100644--- a/internal/recovery/store/store.go+++ b/internal/recovery/store/store.go@@ -836,6 +836,12 @@ func (s *Store) BackfillKeys(ctx context.Context) error {}defer stmt.Close()+ ridStmt, err := tx.PrepareContext(ctx, "UPDATE recovery_points SET subject_resource_id = ? WHERE id = ?")+ if err != nil {+ return err+ }+ defer ridStmt.Close()+for _, item := range subjectItems {var ref recovery.ExternalRef_ = unmarshalJSON(item.refRaw, &ref) // best-effort@@ -844,11 +850,20 @@ func (s *Store) BackfillKeys(ctx context.Context) error {refPtr = &ref}- key := recovery.SubjectKey(- recovery.Provider(strings.TrimSpace(item.provider)),- strings.TrimSpace(item.rid),- refPtr,- )+ provider := recovery.Provider(strings.TrimSpace(item.provider))+ rid := strings.TrimSpace(item.rid)++ // Converge historical guest rows onto the node-independent+ // canonical derivation (#1669) so pre-migration history keeps+ // joining the live resource.+ if canonicalRID := recovery.CanonicalSubjectResourceID(provider, rid, refPtr); canonicalRID != "" && canonicalRID != rid {+ if _, err := ridStmt.ExecContext(ctx, canonicalRID, item.id); err != nil {+ return err+ }+ rid = canonicalRID+ }++ key := recovery.SubjectKey(provider, rid, refPtr)if strings.TrimSpace(key) == "" || strings.TrimSpace(item.subjectKey.String) == key {continue}@@ -860,6 +875,17 @@ func (s *Store) BackfillKeys(ctx context.Context) error {if err := tx.Commit(); err != nil {return err}++ // Subject re-keys can strand materialized posture rows under keys no+ // point references anymore; sweep them so retired-era subjects do not+ // linger as ghost protected items.+ _, _ = s.db.ExecContext(ctx, `+ DELETE FROM protection_postures+ WHERE subject_key NOT IN (+ SELECT DISTINCT subject_key FROM recovery_points+ WHERE subject_key IS NOT NULL AND TRIM(subject_key) != ''+ )+ `)}_, _ = s.db.ExecContext(ctx, `diff --git a/internal/recovery/store/store_test.go b/internal/recovery/store/store_test.goindex 977f667e2d..290c8596f5 100644--- a/internal/recovery/store/store_test.go+++ b/internal/recovery/store/store_test.go@@ -658,10 +658,12 @@ func TestStore_OpenBackfillsLegacyUnresolvedProxmoxPBSGuestRows(t *testing.T) {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(+ // Reopening runs the startup backfill, which converges guest rows onto+ // the node-independent canonical derivation (#1669).+ currentRID := unifiedresources.ProxmoxGuestCanonicalID(unifiedresources.ResourceTypeSystemContainer,- unifiedresources.SourceProxmox,- "pi:pi:140",+ "pi",+ 140,)linked := recovery.RecoveryPoint{diff --git a/internal/unifiedresources/adapters.go b/internal/unifiedresources/adapters.goindex 1f5391bb75..68c969ec72 100644--- a/internal/unifiedresources/adapters.go+++ b/internal/unifiedresources/adapters.go@@ -1791,8 +1791,9 @@ func resourceFromVM(vm models.VM) (Resource, ResourceIdentity) {}resource.Capabilities = proxmoxGuestLifecycleCapabilities("vm", "qemu", vm.Status, vm.Template, vm.Lock)identity := ResourceIdentity{- Hostnames: uniqueStrings([]string{vm.Name}),- IPAddresses: uniqueStrings(vm.IPAddresses),+ Hostnames: uniqueStrings([]string{vm.Name}),+ IPAddresses: uniqueStrings(vm.IPAddresses),+ ProxmoxGuestKey: ProxmoxGuestIdentityKey(vm.Instance, vm.VMID),}return resource, identity}@@ -1854,8 +1855,9 @@ func resourceFromContainer(ct models.Container) (Resource, ResourceIdentity) {}resource.Capabilities = proxmoxGuestLifecycleCapabilities("ct", "lxc", ct.Status, ct.Template, ct.Lock)identity := ResourceIdentity{- Hostnames: uniqueStrings([]string{ct.Name}),- IPAddresses: uniqueStrings(ct.IPAddresses),+ Hostnames: uniqueStrings([]string{ct.Name}),+ IPAddresses: uniqueStrings(ct.IPAddresses),+ ProxmoxGuestKey: ProxmoxGuestIdentityKey(ct.Instance, ct.VMID),}return resource, identity}diff --git a/internal/unifiedresources/adapters_test.go b/internal/unifiedresources/adapters_test.goindex 1fc6e28da0..1143cebf67 100644--- a/internal/unifiedresources/adapters_test.go+++ b/internal/unifiedresources/adapters_test.go@@ -1919,3 +1919,23 @@ func TestResourceAdaptersPreserveUnavailableMemoryAsRawEvidence(t *testing.T) {t.Fatalf("Docker raw memory = %+v, want explicit unavailable evidence", dockerResource.Docker)}}++// Proxmox guest adapters must publish the node-independent identity key so+// canonical ID derivation survives live migration (#1669); guests without an+// instance+VMID stay keyless and fall back to source-specific derivation.+func TestResourceFromGuestSetsProxmoxGuestKey(t *testing.T) {+ _, vmIdentity := resourceFromVM(models.VM{ID: "delly:pve1:100", VMID: 100, Name: "web-vm", Node: "pve1", Instance: "delly"})+ if want := ProxmoxGuestIdentityKey("delly", 100); vmIdentity.ProxmoxGuestKey != want {+ t.Fatalf("VM ProxmoxGuestKey = %q, want %q", vmIdentity.ProxmoxGuestKey, want)+ }++ _, ctIdentity := resourceFromContainer(models.Container{ID: "delly:pve1:112", VMID: 112, Name: "debian-ct", Node: "pve1", Instance: "delly"})+ if want := ProxmoxGuestIdentityKey("delly", 112); ctIdentity.ProxmoxGuestKey != want {+ t.Fatalf("container ProxmoxGuestKey = %q, want %q", ctIdentity.ProxmoxGuestKey, want)+ }++ _, keyless := resourceFromVM(models.VM{ID: "legacy-opaque-id", Name: "old-vm"})+ if keyless.ProxmoxGuestKey != "" {+ t.Fatalf("keyless VM must not carry a guest key, got %q", keyless.ProxmoxGuestKey)+ }+}diff --git a/internal/unifiedresources/availability_link_test.go b/internal/unifiedresources/availability_link_test.goindex 3db6e0c463..1daaa01432 100644--- a/internal/unifiedresources/availability_link_test.go+++ b/internal/unifiedresources/availability_link_test.go@@ -624,3 +624,44 @@ func TestAvailabilityRepeatedProjectionKeepsHostRelationshipsStable(t *testing.T}}}++// An explicit availability link saved under the guest's retired node-scoped+// canonical ID (or its raw node-scoped source ID) must keep resolving after+// the guest live-migrates (#1669). The link is fail-closed, so only+// provider-declared persistence keys resolve.+func TestProxmoxGuestAvailabilityLinkFollowsRetiredIDs(t *testing.T) {+ now := time.Now().UTC()++ refs := map[string]string{+ "retired canonical id": SourceSpecificID(ResourceTypeVM, SourceProxmox, "delly:pve1:100"),+ "old-node source id": "delly:pve1:100",+ }+ for name, ref := range refs {+ t.Run(name, func(t *testing.T) {+ rr := NewRegistry(nil)+ rr.IngestSnapshot(proxmoxGuestMigrationSnapshot(now, "pve2"))++ rr.IngestRecords(SourceAvailability, []IngestRecord{+ availabilityProbeRecord("probe-guest", "192.0.2.50", &AvailabilityData{+ LinkedResourceID: ref,+ Address: "192.0.2.50",+ Protocol: "icmp",+ Enabled: true,+ Available: true,+ LastChecked: &now,+ Evidence: availabilityProbeEvidence(t, "probe-guest", now),+ }),+ })++ guestID := ProxmoxGuestCanonicalID(ResourceTypeVM, "delly", 100)+ guest, ok := rr.Get(guestID)+ if !ok || guest == nil {+ t.Fatalf("guest %q missing", guestID)+ }+ if guest.Availability == nil || guest.Availability.CorrelationState != AvailabilityCorrelationAttached ||+ guest.Availability.CorrelationRule != "explicit_resource_link" {+ t.Fatalf("availability facet = %+v, want attached explicit link for ref %q", guest.Availability, ref)+ }+ })+ }+}diff --git a/internal/unifiedresources/canonical_id_succession.go b/internal/unifiedresources/canonical_id_succession.goindex 38fa002a7e..a6e4ce4044 100644--- a/internal/unifiedresources/canonical_id_succession.go+++ b/internal/unifiedresources/canonical_id_succession.go@@ -2,18 +2,19 @@ package unifiedresourcesimport "fmt"-// CanonicalIDSuccession records that the physical host durably pinned under+// CanonicalIDSuccession records that the resource durably pinned under// OldCanonicalID now mints NewCanonicalID. Canonical IDs hash the strongest-// identity key known at mint time, so a host's ID moves eras when a stronger-// key appears (a containerized agent gains /etc/machine-id) or when the-// derivation itself is corrected (cluster-scoped IDs switched from short to-// full hostnames so FQDN Swarm members stop collapsing). Succession re-keys-// the operator-owned rows, meaning operator state (never-auto-remediate,-// maintenance windows, criticality, notes) and action-audit history, onto-// the new canonical ID and drops the superseded identity pin row.-// Change-journal rows are intentionally left untouched: history is never-// rewritten, and ResourceIdentityPin.EraIDs merges old-era journal rows into-// reads keyed by the new ID.+// identity key known at mint time, so a resource's ID moves eras when a+// stronger key appears (a containerized agent gains /etc/machine-id), or when+// the derivation itself is corrected (cluster-scoped IDs switched from short+// to full hostnames; Proxmox guests switched from node-scoped source IDs to+// instance+VMID). Succession re-keys the operator-owned rows, meaning+// operator state (never-auto-remediate, maintenance windows, criticality,+// notes), action-audit history, and manual link/exclusion pairs, onto the new+// canonical ID and drops the superseded identity pin row. Change-journal rows+// are intentionally left untouched: history is never rewritten. Reads merge+// the eras instead, through ResourceIdentityPin.EraIDs for pinned hosts and+// through the durable canonical_id_successions record for everything else.type CanonicalIDSuccession struct {OldCanonicalID stringNewCanonicalID string@@ -22,21 +23,43 @@ type CanonicalIDSuccession struct {// canonicalIDSuccessor is an optional store capability, mirroring the// maintenance-lifecycle pattern in resource_operator_state.go. The durable// registry applies successions during PersistIdentityPins when it detects-// that a new pin supersedes an earlier era's pin for the same physical host.+// that a new pin supersedes an earlier era's pin for the same physical host,+// and during snapshot/record ingest for record-declared eras.type canonicalIDSuccessor interface {ApplyCanonicalIDSuccessions(successions []CanonicalIDSuccession) error}// ApplyCanonicalIDSuccessions re-keys operator-owned rows from each// superseded canonical ID to its successor and deletes the superseded-// identity pin row, in one transaction. Re-keys never clobber rows already-// present under the new ID (those are fresher); a shadowed old row is left-// behind, which matches the pre-succession orphaning behavior.+// identity pin row, in one transaction. Each (old, new) pair is applied once+// and durably recorded in canonical_id_successions; the record both memoizes+// re-runs (steady-state rebuilds re-declare the same retired eras every tick)+// and lets change-journal reads merge the old era without rewriting history.+// Re-keys never clobber rows already present under the new ID (those are+// fresher); a shadowed old row is left behind, which matches the+// pre-succession orphaning behavior.func (s *SQLiteResourceStore) ApplyCanonicalIDSuccessions(successions []CanonicalIDSuccession) error {if len(successions) == 0 {return nil}+ recorded := s.successionMap()+ pending := make([]CanonicalIDSuccession, 0, len(successions))+ for _, succession := range successions {+ oldID := CanonicalResourceID(succession.OldCanonicalID)+ newID := CanonicalResourceID(succession.NewCanonicalID)+ if oldID == "" || newID == "" || oldID == newID {+ continue+ }+ if successor, done := recorded[oldID]; done && successor == newID {+ continue+ }+ pending = append(pending, CanonicalIDSuccession{OldCanonicalID: oldID, NewCanonicalID: newID})+ }+ if len(pending) == 0 {+ return nil+ }+s.mu.Lock()defer s.mu.Unlock()@@ -51,25 +74,41 @@ func (s *SQLiteResourceStore) ApplyCanonicalIDSuccessions(successions []Canonica}}()- for _, succession := range successions {- oldID := CanonicalResourceID(succession.OldCanonicalID)- newID := CanonicalResourceID(succession.NewCanonicalID)- if oldID == "" || newID == "" || oldID == newID {+ applied := make([]CanonicalIDSuccession, 0, len(pending))+ for _, succession := range pending {+ oldID := succession.OldCanonicalID+ newID := succession.NewCanonicalID+ result, err := tx.Exec(+ `INSERT OR IGNORE INTO canonical_id_successions (old_canonical_id, new_canonical_id) VALUES (?, ?)`,+ oldID, newID,+ )+ if err != nil {+ return fmt.Errorf("record canonical ID succession %q -> %q: %w", oldID, newID, err)+ }+ if inserted, err := result.RowsAffected(); err == nil && inserted == 0 {+ // Recorded by an earlier boot; the re-key already ran.+ applied = append(applied, succession)continue}for _, stmt := range []string{`UPDATE OR IGNORE resource_operator_state SET canonical_id = ? WHERE canonical_id = ?`,`UPDATE action_audits SET canonical_id = ? WHERE canonical_id = ?`,+ `UPDATE OR IGNORE resource_links SET resource_a = ? WHERE resource_a = ?`,+ `UPDATE OR IGNORE resource_links SET resource_b = ? WHERE resource_b = ?`,+ `UPDATE resource_links SET primary_id = ? WHERE primary_id = ?`,+ `UPDATE OR IGNORE resource_exclusions SET resource_a = ? WHERE resource_a = ?`,+ `UPDATE OR IGNORE resource_exclusions SET resource_b = ? WHERE resource_b = ?`,} {if _, err := tx.Exec(stmt, newID, oldID); err != nil {return fmt.Errorf("re-key canonical rows %q -> %q: %w", oldID, newID, err)}}- // The successor pin's EraIDs keep the old era's journal rows+ // The successor's era record keeps the old era's journal rows// readable; the superseded pin row itself is stale bucket noise.if _, err := tx.Exec(`DELETE FROM resource_identities WHERE canonical_id = ?`, oldID); err != nil {return fmt.Errorf("delete superseded identity pin %q: %w", oldID, err)}+ applied = append(applied, succession)}if err := tx.Commit(); err != nil {@@ -80,9 +119,60 @@ func (s *SQLiteResourceStore) ApplyCanonicalIDSuccessions(successions []Canonicas.identityPinMu.Lock()s.identityPinFresh = falses.identityPinMu.Unlock()++ s.successionMu.Lock()+ if s.successionFresh {+ next := make(map[string]string, len(s.successionCache)+len(applied))+ for oldID, newID := range s.successionCache {+ next[oldID] = newID+ }+ for _, succession := range applied {+ if _, exists := next[succession.OldCanonicalID]; !exists {+ next[succession.OldCanonicalID] = succession.NewCanonicalID+ }+ }+ s.successionCache = next+ }+ s.successionMu.Unlock()return nil}+// successionMap returns the cached old→successor canonical ID record. The+// returned map is shared and must be treated as read-only.+func (s *SQLiteResourceStore) successionMap() map[string]string {+ s.successionMu.Lock()+ defer s.successionMu.Unlock()+ if !s.successionFresh {+ successors := make(map[string]string)+ rows, err := s.db.Query(`SELECT old_canonical_id, new_canonical_id FROM canonical_id_successions`)+ if err == nil {+ for rows.Next() {+ var oldID, newID string+ if err := rows.Scan(&oldID, &newID); err != nil {+ continue+ }+ oldID = CanonicalResourceID(oldID)+ newID = CanonicalResourceID(newID)+ if oldID == "" || newID == "" || oldID == newID {+ continue+ }+ successors[oldID] = newID+ }+ _ = rows.Close()+ if err := rows.Err(); err == nil {+ s.successionCache = successors+ s.successionFresh = true+ }+ }+ if !s.successionFresh {+ // Query failed; serve what we have without caching so the next+ // call retries.+ return successors+ }+ }+ return s.successionCache+}+// ApplyCanonicalIDSuccessions mirrors the SQLite semantics for the in-memory// test store. Action audits are not re-keyed here: MemoryStore filters them// by the audit record's embedded request resource ID rather than a separate@@ -104,7 +194,32 @@ func (m *MemoryStore) ApplyCanonicalIDSuccessions(successions []CanonicalIDSuccedelete(m.resourceOperatorState, oldID)}}+ for i := range m.links {+ if m.links[i].ResourceA == oldID {+ m.links[i].ResourceA = newID+ }+ if m.links[i].ResourceB == oldID {+ m.links[i].ResourceB = newID+ }+ if m.links[i].PrimaryID == oldID {+ m.links[i].PrimaryID = newID+ }+ }+ for i := range m.exclusions {+ if m.exclusions[i].ResourceA == oldID {+ m.exclusions[i].ResourceA = newID+ }+ if m.exclusions[i].ResourceB == oldID {+ m.exclusions[i].ResourceB = newID+ }+ }delete(m.identityPins, oldID)+ if m.canonicalSuccessions == nil {+ m.canonicalSuccessions = make(map[string]string)+ }+ if _, exists := m.canonicalSuccessions[oldID]; !exists {+ m.canonicalSuccessions[oldID] = newID+ }}return nil}diff --git a/internal/unifiedresources/ids.go b/internal/unifiedresources/ids.goindex c000acfb89..51975f8a05 100644--- a/internal/unifiedresources/ids.go+++ b/internal/unifiedresources/ids.go@@ -4,6 +4,7 @@ import ("crypto/sha256""encoding/hex""fmt"+ "strconv""strings")@@ -33,6 +34,58 @@ func MachineIdentityCanonicalID(resourceType ResourceType, machineID string) strreturn buildHashID(resourceType, "machine:"+strings.TrimSpace(machineID))}+// ProxmoxGuestIdentityKey returns the node-independent identity key for a+// Proxmox guest. VMIDs are unique within a cluster (and an instance maps to+// one cluster or one standalone node), so instance+VMID survives live+// migration between cluster nodes while the node-scoped source ID does not.+func ProxmoxGuestIdentityKey(instance string, vmid int) string {+ instance = strings.TrimSpace(instance)+ if instance == "" || vmid <= 0 {+ return ""+ }+ return fmt.Sprintf("%s:%d", instance, vmid)+}++// ProxmoxGuestCanonicalID returns the canonical ID the registry mints for a+// Proxmox guest keyed by its node-independent identity (see+// ProxmoxGuestIdentityKey). Consumers that persist guest resource IDs+// (recovery subjects, migrations) derive through this instead of hashing the+// node-scoped source ID.+func ProxmoxGuestCanonicalID(resourceType ResourceType, instance string, vmid int) string {+ key := ProxmoxGuestIdentityKey(instance, vmid)+ if key == "" {+ return ""+ }+ return buildHashID(resourceType, "proxmox-guest:"+key)+}++// ParseProxmoxGuestSourceID splits a node-scoped guest source ID+// ("instance:node:vmid", the makeGuestID format) into its components. The+// instance segment may itself contain colons, so the node and VMID are taken+// from the right.+func ParseProxmoxGuestSourceID(sourceID string) (instance, node string, vmid int, ok bool) {+ sourceID = strings.TrimSpace(sourceID)+ lastSep := strings.LastIndex(sourceID, ":")+ if lastSep <= 0 || lastSep == len(sourceID)-1 {+ return "", "", 0, false+ }+ parsedVMID, err := strconv.Atoi(sourceID[lastSep+1:])+ if err != nil || parsedVMID <= 0 {+ return "", "", 0, false+ }+ rest := sourceID[:lastSep]+ nodeSep := strings.LastIndex(rest, ":")+ if nodeSep <= 0 || nodeSep == len(rest)-1 {+ return "", "", 0, false+ }+ instance = strings.TrimSpace(rest[:nodeSep])+ node = strings.TrimSpace(rest[nodeSep+1:])+ if instance == "" || node == "" {+ return "", "", 0, false+ }+ return instance, node, parsedVMID, true+}+// CanonicalResourceID returns the canonical v6 resource identifier.func CanonicalResourceID(id string) string {trimmed := strings.TrimSpace(id)diff --git a/internal/unifiedresources/ids_test.go b/internal/unifiedresources/ids_test.goindex 139daa7374..1ce2f62c95 100644--- a/internal/unifiedresources/ids_test.go+++ b/internal/unifiedresources/ids_test.go@@ -112,3 +112,56 @@ func TestMachineIdentityCanonicalIDMatchesRegistryMachineArm(t *testing.T) {t.Fatalf("MachineIdentityCanonicalID = %q, want registry machine-arm ID %q", got, want)}}++func TestParseProxmoxGuestSourceID(t *testing.T) {+ cases := []struct {+ in string+ instance string+ node string+ vmid int+ ok bool+ }{+ {"delly:pve1:100", "delly", "pve1", 100, true},+ {"cluster:with:colons:pve2:112", "cluster:with:colons", "pve2", 112, true},+ {"delly:pve1:0", "", "", 0, false},+ {"delly:100", "delly", "", 0, false},+ {"just-a-name", "", "", 0, false},+ {"vm-1a2b3c4d5e6f7788", "", "", 0, false},+ {"", "", "", 0, false},+ {"delly:pve1:abc", "", "", 0, false},+ }+ for _, tc := range cases {+ instance, node, vmid, ok := ParseProxmoxGuestSourceID(tc.in)+ if ok != tc.ok {+ t.Fatalf("ParseProxmoxGuestSourceID(%q) ok = %v, want %v", tc.in, ok, tc.ok)+ }+ if !tc.ok {+ continue+ }+ if instance != tc.instance || node != tc.node || vmid != tc.vmid {+ t.Fatalf("ParseProxmoxGuestSourceID(%q) = (%q, %q, %d), want (%q, %q, %d)", tc.in, instance, node, vmid, tc.instance, tc.node, tc.vmid)+ }+ }+}++// ProxmoxGuestCanonicalID must mint exactly what the registry's guest+// identity arm mints, so external consumers (recovery subjects, migrations)+// derive the same node-independent ID as live ingest.+func TestProxmoxGuestCanonicalIDMatchesRegistryDerivation(t *testing.T) {+ registry := NewRegistry(nil)+ want := registry.canonicalIDFromIdentity(ResourceTypeVM, ResourceIdentity{ProxmoxGuestKey: ProxmoxGuestIdentityKey("delly", 100)})+ if got := ProxmoxGuestCanonicalID(ResourceTypeVM, "delly", 100); got != want {+ t.Fatalf("ProxmoxGuestCanonicalID = %q, want registry guest-arm ID %q", got, want)+ }+}++// A VM and a container never share a VMID inside one cluster, but a VMID can+// be destroyed and recreated as the other guest type; the type prefix keeps+// those identities distinct.+func TestProxmoxGuestCanonicalIDSeparatesTypes(t *testing.T) {+ vmID := ProxmoxGuestCanonicalID(ResourceTypeVM, "delly", 200)+ ctID := ProxmoxGuestCanonicalID(ResourceTypeSystemContainer, "delly", 200)+ if vmID == ctID {+ t.Fatalf("VM and container canonical IDs must differ, both %q", vmID)+ }+}diff --git a/internal/unifiedresources/registry.go b/internal/unifiedresources/registry.goindex 94acab9239..b73c1f327b 100644--- a/internal/unifiedresources/registry.go+++ b/internal/unifiedresources/registry.go@@ -94,6 +94,11 @@ type ResourceRegistry struct {exclusions map[string]struct{}identityPins *identityPinIndexpbsBackups []models.PBSBackup+ // supersededIndex maps record-declared retired canonical IDs to the live+ // resource that superseded them, so references persisted under a retired+ // ID (availability links, API reads) keep resolving. An empty value marks+ // an ambiguous claim and never resolves.+ supersededIndex map[string]string// Cached typed view indexes. Invalidated on ingest, rebuilt lazily on// first access. Protected by mu — callers hold RLock to read, and the@@ -188,10 +193,24 @@ func (rr *ResourceRegistry) ingestSnapshot(snapshot models.StateSnapshot, thresh// cluster names to VMs/Containers (their parent-ID lookup may fail// when the node ID uses clusterName instead of instanceName).clusterByInstance := make(map[string]string)+ // Instance→node-names lookup (current names plus native aliases) feeds+ // the guest superseded-era sweep: a guest's retired node-scoped canonical+ // IDs are recomputable for every node it could have lived on, so+ // operator-owned rows orphaned by a pre-upgrade migration still succeed+ // into the node-independent guest ID.+ nodeNamesByInstance := make(map[string][]string)for _, node := range snapshot.Nodes {if node.ClusterName != "" && node.Instance != "" {clusterByInstance[node.Instance] = node.ClusterName}+ if instance := strings.TrimSpace(node.Instance); instance != "" {+ names := append([]string{node.Name}, node.NativeNameAliases...)+ for _, name := range names {+ if name = strings.TrimSpace(name); name != "" {+ nodeNamesByInstance[instance] = append(nodeNamesByInstance[instance], name)+ }+ }+ }rr.ingestProxmoxNode(node, inferredLinkedHostByNodeID[strings.TrimSpace(node.ID)])}for _, host := range snapshot.Hosts {@@ -218,12 +237,14 @@ func (rr *ResourceRegistry) ingestSnapshot(snapshot models.StateSnapshot, threshfor _, instance := range snapshot.PMGInstances {rr.ingestPMGInstance(instance)}+ var guestSuccessions []CanonicalIDSuccessionfor _, vm := range snapshot.VMs {- rr.ingestVM(vm, clusterByInstance)+ guestSuccessions = append(guestSuccessions, rr.ingestVM(vm, clusterByInstance, nodeNamesByInstance)...)}for _, ct := range snapshot.Containers {- rr.ingestContainer(ct, clusterByInstance)+ guestSuccessions = append(guestSuccessions, rr.ingestContainer(ct, clusterByInstance, nodeNamesByInstance)...)}+ rr.applyRecordSuccessions(guestSuccessions)for _, storage := range snapshot.Storage {rr.ingestStorage(storage)}@@ -584,6 +605,59 @@ func (rr *ResourceRegistry) retainSupersededCanonicalIDs(resourceID string, supeids = append(ids, supersededID)}resource.SupersededCanonicalIDs = uniqueTrimmed(ids...)+ rr.indexSupersededCanonicalIDsLocked(resourceID, resource.SupersededCanonicalIDs)+}++func (rr *ResourceRegistry) indexSupersededCanonicalIDsLocked(resourceID string, supersededIDs []string) {+ if resourceID == "" || len(supersededIDs) == 0 {+ return+ }+ if rr.supersededIndex == nil {+ rr.supersededIndex = make(map[string]string)+ }+ for _, supersededID := range supersededIDs {+ if current, claimed := rr.supersededIndex[supersededID]; claimed && current != resourceID {+ // Two live resources claiming the same retired ID is ambiguous;+ // fail closed rather than resolving to either.+ rr.supersededIndex[supersededID] = ""+ continue+ }+ rr.supersededIndex[supersededID] = resourceID+ }+}++// supersededResourceIDLocked resolves a reference persisted under a retired+// canonical ID to the live resource that declared it superseded. Ambiguous+// claims and unknown references return "".+func (rr *ResourceRegistry) supersededResourceIDLocked(ref string) string {+ ref = CanonicalResourceID(ref)+ if ref == "" {+ return ""+ }+ return rr.supersededIndex[ref]+}++// proxmoxGuestResourceIDForSourceRefLocked resolves a node-scoped guest+// source reference ("instance:node:vmid") to the guest's node-independent+// canonical resource. The node segment is deliberately ignored: references+// written while the guest lived on another cluster node must still resolve+// after a live migration.+func (rr *ResourceRegistry) proxmoxGuestResourceIDForSourceRefLocked(ref string) string {+ instance, _, vmid, ok := ParseProxmoxGuestSourceID(ref)+ if !ok {+ return ""+ }+ matches := map[string]struct{}{}+ for _, resourceType := range []ResourceType{ResourceTypeVM, ResourceTypeSystemContainer} {+ candidateID := ProxmoxGuestCanonicalID(resourceType, instance, vmid)+ if candidateID == "" {+ continue+ }+ if rr.resources[candidateID] != nil {+ matches[candidateID] = struct{}{}+ }+ }+ return uniqueResourceIDMatch(matches)}// applyRecordSuccessions re-keys operator-owned store rows from canonical IDs@@ -669,6 +743,9 @@ func (rr *ResourceRegistry) ingestResources(resources []Resource, thresholds maprr.mu.Lock()for _, resourceID := range seededIDs {rr.seedSourceMappingsFromResourceLocked(rr.resources[resourceID])+ if resource := rr.resources[resourceID]; resource != nil {+ rr.indexSupersededCanonicalIDsLocked(resourceID, resource.SupersededCanonicalIDs)+ }}rr.applyManualLinks(thresholds)rr.refreshStorageConsumersLocked()@@ -1247,7 +1324,9 @@ func (rr *ResourceRegistry) GetByReference(ref string) (*Resource, string, bool)}for _, resolvedID := range []string{+ rr.supersededResourceIDLocked(ref),rr.uniqueSourceResourceIDLocked(ref),+ rr.proxmoxGuestResourceIDForSourceRefLocked(ref),rr.uniqueCanonicalIdentityResourceIDLocked(ref),} {if resolvedID == "" {@@ -1633,7 +1712,7 @@ func (rr *ResourceRegistry) ingestPMGInstance(instance models.PMGInstance) {rr.ingest(SourcePMG, sourceID, resource, identity)}-func (rr *ResourceRegistry) ingestVM(vm models.VM, clusterByInstance map[string]string) {+func (rr *ResourceRegistry) ingestVM(vm models.VM, clusterByInstance map[string]string, nodeNamesByInstance map[string][]string) []CanonicalIDSuccession {resource, identity := resourceFromVM(vm)sourceID := proxmoxVMSourceID(vm)clusterName := clusterByInstance[vm.Instance]@@ -1644,10 +1723,11 @@ func (rr *ResourceRegistry) ingestVM(vm models.VM, clusterByInstance map[string]if clusterName != "" && resource.Proxmox != nil {resource.Proxmox.ClusterName = clusterName}- rr.ingest(SourceProxmox, sourceID, resource, identity)+ newID := rr.ingest(SourceProxmox, sourceID, resource, identity)+ return rr.declareGuestSupersededEras(newID, ResourceTypeVM, sourceID, vm.Instance, vm.Node, vm.VMID, nodeNamesByInstance)}-func (rr *ResourceRegistry) ingestContainer(ct models.Container, clusterByInstance map[string]string) {+func (rr *ResourceRegistry) ingestContainer(ct models.Container, clusterByInstance map[string]string, nodeNamesByInstance map[string][]string) []CanonicalIDSuccession {resource, identity := resourceFromContainer(ct)sourceID := proxmoxContainerSourceID(ct)clusterName := clusterByInstance[ct.Instance]@@ -1658,7 +1738,70 @@ func (rr *ResourceRegistry) ingestContainer(ct models.Container, clusterByInstanif clusterName != "" && resource.Proxmox != nil {resource.Proxmox.ClusterName = clusterName}- rr.ingest(SourceProxmox, sourceID, resource, identity)+ newID := rr.ingest(SourceProxmox, sourceID, resource, identity)+ return rr.declareGuestSupersededEras(newID, ResourceTypeSystemContainer, sourceID, ct.Instance, ct.Node, ct.VMID, nodeNamesByInstance)+}++// declareGuestSupersededEras names the node-scoped canonical IDs a Proxmox+// guest was minted under before the node-independent instance+VMID derivation+// (#1669). The retired IDs are recomputable for every node currently known to+// the instance (plus prior native-name aliases), so operator-owned rows+// orphaned by a pre-upgrade live migration still succeed into the guest's+// current canonical ID. The IDs are retained on the resource for alert+// override migration and old-reference resolution, and returned as+// successions for the store re-key pass.+func (rr *ResourceRegistry) declareGuestSupersededEras(newID string, resourceType ResourceType, sourceID, instance, node string, vmid int, nodeNamesByInstance map[string][]string) []CanonicalIDSuccession {+ newID = CanonicalResourceID(newID)+ if newID == "" || ProxmoxGuestIdentityKey(instance, vmid) == "" {+ // Guests without an instance+VMID identity keep the source-specific+ // derivation; there is no retired era to succeed from.+ return nil+ }++ legacySourceIDs := []string{sourceID}+ seenNodes := map[string]struct{}{}+ for _, nodeName := range append([]string{node}, nodeNamesByInstance[strings.TrimSpace(instance)]...) {+ nodeName = strings.TrimSpace(nodeName)+ if nodeName == "" {+ continue+ }+ if _, dup := seenNodes[nodeName]; dup {+ continue+ }+ seenNodes[nodeName] = struct{}{}+ legacySourceIDs = append(legacySourceIDs, fmt.Sprintf("%s:%s:%d", strings.TrimSpace(instance), nodeName, vmid))+ }++ supersededIDs := make([]string, 0, len(legacySourceIDs))+ seenIDs := map[string]struct{}{}+ for _, legacySourceID := range legacySourceIDs {+ legacySourceID = normalizeSourceID(legacySourceID)+ if legacySourceID == "" {+ continue+ }+ legacyID := rr.sourceSpecificID(resourceType, SourceProxmox, legacySourceID)+ if legacyID == newID {+ continue+ }+ if _, dup := seenIDs[legacyID]; dup {+ continue+ }+ seenIDs[legacyID] = struct{}{}+ supersededIDs = append(supersededIDs, legacyID)+ }+ if len(supersededIDs) == 0 {+ return nil+ }++ rr.retainSupersededCanonicalIDs(newID, supersededIDs)+ successions := make([]CanonicalIDSuccession, 0, len(supersededIDs))+ for _, supersededID := range supersededIDs {+ successions = append(successions, CanonicalIDSuccession{+ OldCanonicalID: supersededID,+ NewCanonicalID: newID,+ })+ }+ return successions}func (rr *ResourceRegistry) linkedAgentIDForResource(resourceID string) string {@@ -2989,8 +3132,14 @@ func (rr *ResourceRegistry) resolveAvailabilityLinkedResource(ref string, incomireturn ""}+ // References persisted under a retired canonical ID or under a+ // node-scoped guest source ID follow the resource across identity eras+ // and live migrations. These arms resolve provider-declared persistence+ // keys, not display aliases, so the explicit link stays fail-closed.for _, candidateID := range uniqueTrimmed(+ rr.supersededResourceIDLocked(exactID),rr.uniqueSourceResourceIDLocked(ref),+ rr.proxmoxGuestResourceIDForSourceRefLocked(ref),rr.uniqueCanonicalIdentityResourceIDLocked(ref),) {existing := rr.resources[candidateID]@@ -4343,6 +4492,14 @@ func (rr *ResourceRegistry) chooseNewID(resourceType ResourceType, identity Resoif identity.MachineID != "" || identity.DMIUUID != "" {return rr.canonicalIDFromIdentity(resourceType, identity)}+ case ResourceTypeVM, ResourceTypeSystemContainer:+ // Proxmox guests key on instance+VMID so live migration between+ // cluster nodes keeps the canonical ID (#1669). Other VM providers+ // (TrueNAS, XCP-ng, libvirt, VMware) do not set the guest key and+ // keep their source-specific derivation.+ if identity.ProxmoxGuestKey != "" {+ return rr.canonicalIDFromIdentity(resourceType, identity)+ }}return rr.sourceSpecificID(resourceType, source, sourceID)}@@ -4361,6 +4518,8 @@ func (rr *ResourceRegistry) sourceResourceID(source DataSource, sourceID string)func (rr *ResourceRegistry) canonicalIDFromIdentity(resourceType ResourceType, identity ResourceIdentity) string {var stable stringswitch {+ case identity.ProxmoxGuestKey != "":+ stable = "proxmox-guest:" + identity.ProxmoxGuestKeycase identity.MachineID != "":stable = "machine:" + strings.TrimSpace(identity.MachineID)case identity.DMIUUID != "":@@ -4897,6 +5056,9 @@ func mergeIdentity(existing ResourceIdentity, incoming ResourceIdentity) Resourcif existing.ClusterName == "" {existing.ClusterName = incoming.ClusterName}+ if existing.ProxmoxGuestKey == "" {+ existing.ProxmoxGuestKey = incoming.ProxmoxGuestKey+ }existing.Hostnames = uniqueStrings(append(existing.Hostnames, incoming.Hostnames...))existing.IPAddresses = uniqueStrings(append(existing.IPAddresses, incoming.IPAddresses...))existing.MACAddresses = uniqueStrings(append(existing.MACAddresses, incoming.MACAddresses...))diff --git a/internal/unifiedresources/registry_test.go b/internal/unifiedresources/registry_test.goindex 6fc26cf50a..e2b53863a0 100644--- a/internal/unifiedresources/registry_test.go+++ b/internal/unifiedresources/registry_test.go@@ -5950,3 +5950,146 @@ func TestRegistryIngestsAgentLibvirtDomainUnderReportingHost(t *testing.T) {t.Fatalf("libvirt VM parent = %+v, found=%v", parent, ok)}}++func proxmoxGuestMigrationSnapshot(now time.Time, node string) models.StateSnapshot {+ return models.StateSnapshot{+ Nodes: []models.Node{+ {ID: "delly-pve1", Name: "pve1", Instance: "delly", ClusterName: "delly", Status: "online", LastSeen: now},+ {ID: "delly-pve2", Name: "pve2", Instance: "delly", ClusterName: "delly", Status: "online", LastSeen: now},+ },+ VMs: []models.VM{+ {+ ID: "delly:" + node + ":100",+ VMID: 100,+ Name: "web-vm",+ Node: node,+ Instance: "delly",+ Status: "running",+ LastSeen: now,+ },+ },+ Containers: []models.Container{+ {+ ID: "delly:" + node + ":112",+ VMID: 112,+ Name: "debian-ct",+ Node: node,+ Instance: "delly",+ Status: "running",+ LastSeen: now,+ },+ },+ }+}++// A live migration changes the guest's node and therefore its node-scoped+// source ID, but the canonical resource ID must stay put so operator-owned+// rows (availability links, overrides, operator state) keep following the+// guest (#1669).+func TestProxmoxGuestCanonicalIDSurvivesNodeMigration(t *testing.T) {+ now := time.Now().UTC()++ before := NewRegistry(nil)+ before.IngestSnapshot(proxmoxGuestMigrationSnapshot(now, "pve1"))+ after := NewRegistry(nil)+ after.IngestSnapshot(proxmoxGuestMigrationSnapshot(now, "pve2"))++ for _, resourceType := range []ResourceType{ResourceTypeVM, ResourceTypeSystemContainer} {+ beforeList := before.ListByType(resourceType)+ afterList := after.ListByType(resourceType)+ if len(beforeList) != 1 || len(afterList) != 1 {+ t.Fatalf("%s: expected exactly one guest before and after migration, got %d and %d", resourceType, len(beforeList), len(afterList))+ }+ if beforeList[0].ID != afterList[0].ID {+ t.Fatalf("%s: canonical ID changed across node migration: %q -> %q", resourceType, beforeList[0].ID, afterList[0].ID)+ }+ }++ vms := before.ListByType(ResourceTypeVM)+ if want := ProxmoxGuestCanonicalID(ResourceTypeVM, "delly", 100); vms[0].ID != want {+ t.Fatalf("VM canonical ID = %q, want node-independent %q", vms[0].ID, want)+ }+ cts := before.ListByType(ResourceTypeSystemContainer)+ if want := ProxmoxGuestCanonicalID(ResourceTypeSystemContainer, "delly", 112); cts[0].ID != want {+ t.Fatalf("container canonical ID = %q, want node-independent %q", cts[0].ID, want)+ }+}++// The retired node-scoped canonical IDs must be declared superseded for every+// node the instance knows, so rows orphaned by a migration that happened+// before the upgrade still succeed into the new ID.+func TestProxmoxGuestDeclaresNodeScopedSupersededEras(t *testing.T) {+ now := time.Now().UTC()+ rr := NewRegistry(nil)+ rr.IngestSnapshot(proxmoxGuestMigrationSnapshot(now, "pve2"))++ vms := rr.ListByType(ResourceTypeVM)+ if len(vms) != 1 {+ t.Fatalf("expected one VM, got %d", len(vms))+ }+ superseded := make(map[string]struct{}, len(vms[0].SupersededCanonicalIDs))+ for _, id := range vms[0].SupersededCanonicalIDs {+ superseded[id] = struct{}{}+ }+ for _, node := range []string{"pve1", "pve2"} {+ legacy := SourceSpecificID(ResourceTypeVM, SourceProxmox, "delly:"+node+":100")+ if _, ok := superseded[legacy]; !ok {+ t.Fatalf("superseded IDs %v missing legacy era for node %s (%s)", vms[0].SupersededCanonicalIDs, node, legacy)+ }+ }+}++// Operator-owned rows persisted under a retired node-scoped ID re-key to the+// node-independent ID during snapshot ingest.+func TestProxmoxGuestSuccessionRekeysOperatorState(t *testing.T) {+ now := time.Now().UTC()+ store := NewMemoryStore()+ legacyID := SourceSpecificID(ResourceTypeVM, SourceProxmox, "delly:pve1:100")+ if err := store.SetResourceOperatorState(ResourceOperatorState{+ CanonicalID: legacyID,+ NeverAutoRemediate: true,+ IntentionallyOffline: false,+ }); err != nil {+ t.Fatalf("seed operator state: %v", err)+ }++ rr := NewRegistry(store)+ // Guest already migrated to pve2 before the upgrade: the legacy row keyed+ // by its pve1-era ID must still follow it.+ rr.IngestSnapshot(proxmoxGuestMigrationSnapshot(now, "pve2"))++ newID := ProxmoxGuestCanonicalID(ResourceTypeVM, "delly", 100)+ state, ok, err := store.GetResourceOperatorState(newID)+ if err != nil || !ok {+ t.Fatalf("operator state missing under new canonical ID %q (ok=%v err=%v)", newID, ok, err)+ }+ if !state.NeverAutoRemediate {+ t.Fatalf("re-keyed operator state lost its fields: %+v", state)+ }+ if _, stale, _ := store.GetResourceOperatorState(legacyID); stale {+ t.Fatalf("operator state still present under retired ID %q", legacyID)+ }+}++// Guests that cannot derive an instance+VMID identity keep the+// source-specific derivation, as do VM resources from other providers.+func TestProxmoxGuestKeylessFallsBackToSourceSpecificID(t *testing.T) {+ now := time.Now().UTC()+ rr := NewRegistry(nil)+ rr.IngestSnapshot(models.StateSnapshot{+ VMs: []models.VM{+ {ID: "legacy-opaque-id", Name: "old-vm", Status: "running", LastSeen: now},+ },+ })++ vms := rr.ListByType(ResourceTypeVM)+ if len(vms) != 1 {+ t.Fatalf("expected one VM, got %d", len(vms))+ }+ if want := SourceSpecificID(ResourceTypeVM, SourceProxmox, "legacy-opaque-id"); vms[0].ID != want {+ t.Fatalf("keyless guest ID = %q, want source-specific %q", vms[0].ID, want)+ }+ if len(vms[0].SupersededCanonicalIDs) != 0 {+ t.Fatalf("keyless guest must not declare superseded eras, got %v", vms[0].SupersededCanonicalIDs)+ }+}diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.goindex e89496558b..b0dbbafe30 100644--- a/internal/unifiedresources/store.go+++ b/internal/unifiedresources/store.go@@ -153,6 +153,15 @@ type SQLiteResourceStore struct {identityPinCache []ResourceIdentityPinidentityPinFresh bool+ // successionCache caches the canonical_id_successions table (old ID →+ // successor ID). It memoizes ApplyCanonicalIDSuccessions so steady-state+ // rebuild ticks re-declaring the same retired eras cost no SQL, and it+ // feeds change-journal era expansion for resources without identity pins+ // (Proxmox guests, record-declared successions).+ successionMu sync.Mutex+ successionCache map[string]string+ successionFresh bool+retentionStop chan struct{}retentionDone chan struct{}retentionStopOnce sync.Once@@ -464,6 +473,13 @@ func (s *SQLiteResourceStore) initSchema() error {metadata_json TEXT);+ CREATE TABLE IF NOT EXISTS canonical_id_successions (+ old_canonical_id TEXT PRIMARY KEY,+ new_canonical_id TEXT NOT NULL,+ applied_at DATETIME DEFAULT CURRENT_TIMESTAMP+ );+ CREATE INDEX IF NOT EXISTS idx_canonical_id_successions_new ON canonical_id_successions(new_canonical_id);+CREATE TABLE IF NOT EXISTS action_audits (id TEXT PRIMARY KEY,action_id TEXT NOT NULL,@@ -1569,7 +1585,9 @@ func (s *SQLiteResourceStore) queryResourceIdentityPins() ([]ResourceIdentityPin// strongest identity key was known hash a weaker key (cluster+hostname during// a boot window vs machine ID in steady state); the pinned identity makes// every era's ID recomputable, so reads merge the eras without rewriting-// history. Unknown IDs expand to themselves.+// history. Resources without pins (Proxmox guests, record-declared eras)+// merge through the durable canonical_id_successions record instead. Unknown+// IDs expand to themselves.func (s *SQLiteResourceStore) resourceChangeIDSet(canonicalID string) []string {canonicalID = CanonicalResourceID(canonicalID)if canonicalID == "" {@@ -1587,19 +1605,55 @@ func (s *SQLiteResourceStore) resourceChangeIDSet(canonicalID string) []string {pins := s.identityPinCaches.identityPinMu.Unlock()- return expandResourceChangeIDs(canonicalID, pins)+ return expandResourceChangeIDs(canonicalID, pins, s.successionMap())}-func expandResourceChangeIDs(canonicalID string, pins []ResourceIdentityPin) []string {+func expandResourceChangeIDs(canonicalID string, pins []ResourceIdentityPin, successors map[string]string) []string {+ ids := []string{canonicalID}for _, pin := range pins {eraIDs := pin.EraIDs()for _, eraID := range eraIDs {if eraID == canonicalID {- return eraIDs+ ids = eraIDs+ break+ }+ }+ if len(ids) > 1 {+ break+ }+ }+ return appendSupersededChangeIDs(ids, successors)+}++// appendSupersededChangeIDs walks the succession record backwards from the+// requested IDs so journal rows written under any retired predecessor era+// stay readable, including chained eras (A succeeded into B, B into C).+func appendSupersededChangeIDs(ids []string, successors map[string]string) []string {+ if len(successors) == 0 || len(ids) == 0 {+ return ids+ }+ predecessors := make(map[string][]string, len(successors))+ for oldID, newID := range successors {+ predecessors[newID] = append(predecessors[newID], oldID)+ }+ seen := make(map[string]struct{}, len(ids))+ for _, id := range ids {+ seen[id] = struct{}{}+ }+ queue := append([]string(nil), ids...)+ for len(queue) > 0 {+ id := queue[0]+ queue = queue[1:]+ for _, oldID := range predecessors[id] {+ if _, dup := seen[oldID]; dup {+ continue}+ seen[oldID] = struct{}{}+ ids = append(ids, oldID)+ queue = append(queue, oldID)}}- return []string{canonicalID}+ return ids}func (s *SQLiteResourceStore) RecordChange(change ResourceChange) error {@@ -3182,6 +3236,7 @@ type MemoryStore struct {resourceOperatorState map[string]ResourceOperatorStateloopReports map[string]LoopReportidentityPins map[string]ResourceIdentityPin+ canonicalSuccessions map[string]string}func NewMemoryStore() *MemoryStore {@@ -3252,7 +3307,7 @@ func (m *MemoryStore) resourceChangeIDSetLocked(canonicalID string) []string {for _, pin := range m.identityPins {pins = append(pins, pin)}- return expandResourceChangeIDs(canonicalID, pins)+ return expandResourceChangeIDs(canonicalID, pins, m.canonicalSuccessions)}func (m *MemoryStore) AddLink(link ResourceLink) error {diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.goindex b6e03b2fe6..566a1ed45e 100644--- a/internal/unifiedresources/store_test.go+++ b/internal/unifiedresources/store_test.go@@ -3235,3 +3235,45 @@ func TestSQLiteResourceStoreCloseJoinsRetentionLoopAndIsIdempotent(t *testing.T)t.Fatalf("second Close: %v", err)}}++// Change-journal rows written under a retired guest era stay readable under+// the new canonical ID: the durable succession record merges eras at read+// time without rewriting history (#1669).+func TestSuccessionMergesGuestChangeJournalEras(t *testing.T) {+ now := time.Now().UTC()+ store, err := NewSQLiteResourceStore(t.TempDir(), "")+ if err != nil {+ t.Fatalf("open store: %v", err)+ }+ defer store.Close()++ legacyID := SourceSpecificID(ResourceTypeVM, SourceProxmox, "delly:pve1:100")+ newID := ProxmoxGuestCanonicalID(ResourceTypeVM, "delly", 100)+ if err := store.RecordChange(ResourceChange{+ ID: "chg-legacy-1",+ ResourceID: legacyID,+ ObservedAt: now.Add(-time.Hour),+ Kind: "status_transition",+ SourceType: "system",+ Confidence: "confirmed",+ }); err != nil {+ t.Fatalf("record legacy change: %v", err)+ }++ rr := NewRegistry(store)+ rr.IngestSnapshot(proxmoxGuestMigrationSnapshot(now, "pve2"))++ changes, err := store.GetRecentChanges(newID, now.Add(-2*time.Hour), 10)+ if err != nil {+ t.Fatalf("read changes: %v", err)+ }+ found := false+ for _, change := range changes {+ if change.ID == "chg-legacy-1" {+ found = true+ }+ }+ if !found {+ t.Fatalf("legacy-era journal row missing from new-ID read: %+v", changes)+ }+}diff --git a/internal/unifiedresources/types.go b/internal/unifiedresources/types.goindex c79de737cb..89cda5ca7d 100644--- a/internal/unifiedresources/types.go+++ b/internal/unifiedresources/types.go@@ -301,6 +301,11 @@ type ResourceIdentity struct {IPAddresses []string `json:"ipAddresses,omitempty"`MACAddresses []string `json:"macAddresses,omitempty"`ClusterName string `json:"clusterName,omitempty"`+ // ProxmoxGuestKey is the node-independent Proxmox guest identity+ // ("instance:vmid", see ProxmoxGuestIdentityKey). VMIDs are unique within+ // a cluster, so canonical IDs derived from this key survive live+ // migration between cluster nodes (#1669).+ ProxmoxGuestKey string `json:"proxmoxGuestKey,omitempty"`}// MatchResult describes a potential identity match.