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
Key TrueNAS systems by configured connection, not reported hostname
rcourtman5d4f51c0275a
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex ed9cf00718..6e4c5fda37 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -331,6 +331,21 @@ resource health.dataset, app, VM, share, and disk names from different appliances remaindistinct. Mock fixture metrics and seeded/live history must use the samescoped source keys as the TrueNAS provider metrics targets.+ The owning system source key itself is connection-scoped: the poller+ constructs live providers through `NewLiveProviderForConnection` so+ `systemSourceID` keys the system (and every child scoped under it) by the+ configured connection ID, never by the snapshot-reported hostname, and the+ system's ingest identity carries no machine key (DMI serials are shared by+ DR clones and can be vendor placeholders). Two appliances that report the+ same hostname must remain distinct resources (#1573, #1575). The hostname+ arm of `systemSourceID` exists only for fixture snapshots, which carry no+ connection; mock-mode identities stay hostname-scoped through that arm.+ Regression coverage: `TestTrueNASPollerKeysSystemsByConnection` in+ `internal/monitoring/truenas_poller_test.go` and+ `TestRegistryIngestRecordsKeepsSameHostnameSystemsDistinct` in+ `internal/truenas/contract_test.go`. The canonical-ID migration semantics+ for rows minted under the retired hostname-keyed derivation live in the+ unified-resources contract (record-declared succession, item 27).TrueNAS storage and alert inventory follow native query methods first:pools use `pool.query`, datasets use `pool.dataset.query`, disks use`disk.query` with pool join options, and alerts use `alert.list`, withdiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 661b65e3d6..8226f8b99b 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -1469,6 +1469,39 @@ AI-only summary payloads, or page-local heuristics.or apply it to the wrong tenant.Regression coverage: `TestSQLiteStoreActionAuditOriginRoundTrip` in`internal/unifiedresources/store_test.go`.+27. Keep API-added TrueNAS systems keyed by the configured connection,+ never by snapshot-reported identity. `systemSourceID` in+ `internal/truenas/provider.go` scopes the system source ID (and every+ child pool/dataset/app/VM/share/disk scoped under it) to the+ connection ID the poller passes through+ `NewLiveProviderForConnection`; the hostname arm exists only for+ fixture snapshots, which carry no connection. The system's ingest+ identity deliberately carries no machine key: the TrueNAS DMI serial+ is shared by DR clones and can be vendor placeholder garbage, and the+ retired client fallback minted machine keys from the reported+ hostname, fully merging same-hostname systems (#1573, #1575). For the+ same reason `ingest` skips `completeIdentityFromPins` for+ `SourceTrueNAS`: a hostname-bucket pin (stale pre-fix TrueNAS pin or+ a pulse-agent's pin on a same-named host) must not lend the system a+ machine key and re-merge what connection scoping keeps apart.+ `trueNASSystemMetricResourceID` must stay `systemSourceID` minus its+ `system:` prefix so `Agent.AgentID`, native history keys, and+ `canonicalAgentMetricID` in `BuildMetricsTarget` resolve one series.+ Rows minted under the retired hostname-keyed derivation re-key once+ through record-declared succession: records name their old canonical+ IDs in `IngestRecord.SupersededCanonicalIDs` and+ `ResourceRegistry.IngestRecords` applies the same+ `ApplyCanonicalIDSuccessions` semantics as pin-driven successions+ (operator state and action audits re-key, the superseded pin row+ drops, never while the old ID belongs to a live resource, journal+ rows never rewritten). Regression coverage:+ `TestRegistryIngestRecordsKeepsSameHostnameSystemsDistinct` /+ `TestIngestRecordsSucceedLegacyHostnameScopedCanonicalIDs` /+ `TestIngestRecordsDoNotCompleteTrueNASIdentityFromPins` in+ `internal/truenas/contract_test.go`, and+ `TestIngestRecordsRecordDeclaredSuccessions` /+ `TestIngestRecordsSkipRecordDeclaredSuccessionForLiveOldID` in+ `internal/unifiedresources/canonical_id_succession_test.go`.## Current Statediff --git a/internal/monitoring/truenas_poller.go b/internal/monitoring/truenas_poller.goindex 19d3c91733..1c537bf9a9 100644--- a/internal/monitoring/truenas_poller.go+++ b/internal/monitoring/truenas_poller.go@@ -296,7 +296,7 @@ func (p *TrueNASPoller) syncConnections() {if existingProvider != nil {existingProvider.Close()}- p.providersByOrg[orgID][connID] = truenas.NewLiveProvider(&truenas.APIFetcher{Client: client})+ p.providersByOrg[orgID][connID] = truenas.NewLiveProviderForConnection(&truenas.APIFetcher{Client: client}, connID)}}diff --git a/internal/monitoring/truenas_poller_test.go b/internal/monitoring/truenas_poller_test.goindex dc609a7e89..044e3b9e9f 100644--- a/internal/monitoring/truenas_poller_test.go+++ b/internal/monitoring/truenas_poller_test.go@@ -1820,3 +1820,45 @@ func TestTrueNASPollerDoubleStartKeepsSingleLoop(t *testing.T) {t.Fatal("expected restart to install a fresh poller loop")}}++func TestTrueNASPollerKeysSystemsByConnection(t *testing.T) {+ previous := truenas.IsFeatureEnabled()+ truenas.SetFeatureEnabled(true)+ t.Cleanup(func() { truenas.SetFeatureEnabled(previous) })++ // Both appliances report the same hostname (#1573, #1575); the configured+ // connections must keep them distinct instead of collapsing them into one+ // flapping resource.+ first := newTrueNASMockServer(t, "truenas")+ t.Cleanup(first.Close)+ second := newTrueNASMockServer(t, "truenas")+ t.Cleanup(second.Close)++ mtp, persistence := newTestTenantPersistence(t)+ if err := persistence.SaveTrueNASConfig([]config.TrueNASInstance{+ trueNASInstanceForServer(t, "conn-first", first.URL(), true),+ trueNASInstanceForServer(t, "conn-second", second.URL(), true),+ }); err != nil {+ t.Fatalf("SaveTrueNASConfig() error = %v", err)+ }++ poller := NewTrueNASPoller(mtp, 50*time.Millisecond, nil)+ poller.Start(context.Background())+ t.Cleanup(poller.Stop)++ systemSourceIDs := func() map[string]struct{} {+ ids := make(map[string]struct{})+ for _, record := range poller.GetCurrentRecordsForOrg("default") {+ if record.Resource.Type == unifiedresources.ResourceTypeAgent {+ ids[record.SourceID] = struct{}{}+ }+ }+ return ids+ }+ waitForCondition(t, 2*time.Second, func() bool {+ ids := systemSourceIDs()+ _, firstOK := ids["system:conn-first"]+ _, secondOK := ids["system:conn-second"]+ return firstOK && secondOK && len(ids) == 2+ }, "expected one connection-scoped system source ID per configured connection")+}diff --git a/internal/truenas/client.go b/internal/truenas/client.goindex a0e2f3c1c7..4acdebb2af 100644--- a/internal/truenas/client.go+++ b/internal/truenas/client.go@@ -153,10 +153,12 @@ func (c *Client) GetSystemInfo(ctx context.Context) (*SystemInfo, error) {return nil, err}+ // MachineID is the raw DMI serial only. It must never fall back to the+ // reported hostname: hostname is not a machine identity, and the old+ // fallback gave two serial-less systems that report the same hostname+ // identical machine keys, fully merging them in the resource registry+ // (#1573, #1575).machineID := strings.TrimSpace(response.SystemSerial)- if machineID == "" {- machineID = strings.TrimSpace(response.Hostname)- }build := strings.TrimSpace(response.BuildTime.String())if build == "" {diff --git a/internal/truenas/contract_test.go b/internal/truenas/contract_test.goindex f07759ba3c..ef0c668ff0 100644--- a/internal/truenas/contract_test.go+++ b/internal/truenas/contract_test.go@@ -1,6 +1,7 @@package truenasimport (+ "context""math""strings""testing"@@ -670,3 +671,202 @@ func identityToInput(identity unifiedresources.ResourceIdentity) *models.ResourcIPs: ips,}}++func newConnectionProvider(t *testing.T, fixtures FixtureSnapshot, connectionID string) *Provider {+ t.Helper()+ provider := NewLiveProviderForConnection(&FixtureFetcher{Snapshot: fixtures}, connectionID)+ if err := provider.Refresh(context.Background()); err != nil {+ t.Fatalf("refresh fixture-backed provider: %v", err)+ }+ return provider+}++func TestRegistryIngestRecordsKeepsSameHostnameSystemsDistinct(t *testing.T) {+ previous := IsFeatureEnabled()+ SetFeatureEnabled(true)+ t.Cleanup(func() {+ SetFeatureEnabled(previous)+ })++ // The #1573/#1575 shape: two systems report the same hostname and no DMI+ // serial. Only the configured connections tell them apart.+ first := DefaultFixtures()+ first.System.MachineID = ""+ second := DefaultFixtures()+ second.System.MachineID = ""+ for i := range second.Disks {+ second.Disks[i].Serial = strings.TrimSpace(second.Disks[i].Serial) + "-second"+ }++ records := append(+ newConnectionProvider(t, first, "conn-first").Records(),+ newConnectionProvider(t, second, "conn-second").Records()...,+ )+ registry := unifiedresources.NewRegistry(unifiedresources.NewMemoryStore())+ registry.IngestRecords(unifiedresources.SourceTrueNAS, records)++ resources := registry.List()+ systems := resourcesByNameAndType(resources, unifiedresources.ResourceTypeAgent, "truenas-main")+ if len(systems) != 2 {+ t.Fatalf("expected 2 TrueNAS systems for the shared hostname, got %d from %+v", len(systems), systems)+ }+ if systems[0].ID == systems[1].ID {+ t.Fatalf("expected distinct canonical IDs for same-hostname systems, both got %s", systems[0].ID)+ }+ agentIDs := map[string]struct{}{}+ systemIDs := map[string]struct{}{}+ for _, system := range systems {+ systemIDs[system.ID] = struct{}{}+ if system.Agent == nil {+ t.Fatalf("expected agent data on TrueNAS system %s", system.ID)+ }+ agentIDs[system.Agent.AgentID] = struct{}{}+ }+ for _, want := range []string{"conn-first", "conn-second"} {+ if _, ok := agentIDs[want]; !ok {+ t.Fatalf("expected connection-scoped agent metric IDs, got %v", agentIDs)+ }+ }++ poolParents := map[string]struct{}{}+ poolCount := 0+ for _, pool := range resourcesByNameAndType(resources, unifiedresources.ResourceTypeStorage, "tank") {+ if pool.Storage == nil || pool.Storage.Topology != "pool" {+ continue+ }+ poolCount+++ if pool.ParentID == nil {+ t.Fatalf("expected tank pool %s to have a parent system", pool.ID)+ }+ if _, ok := systemIDs[*pool.ParentID]; !ok {+ t.Fatalf("expected tank pool %s parented to one of the systems, got parent %s", pool.ID, *pool.ParentID)+ }+ poolParents[*pool.ParentID] = struct{}{}+ }+ if poolCount != 2 || len(poolParents) != 2 {+ t.Fatalf("expected one tank pool per system, got %d pools across %d parents", poolCount, len(poolParents))+ }+}++func TestIngestRecordsSucceedLegacyHostnameScopedCanonicalIDs(t *testing.T) {+ previous := IsFeatureEnabled()+ SetFeatureEnabled(true)+ t.Cleanup(func() {+ SetFeatureEnabled(previous)+ })++ fixtures := DefaultFixtures()+ // A serial-less box: the retired client fallback minted its machine key+ // from the reported hostname.+ fixtures.System.MachineID = ""+ hostname := fixtures.System.Hostname+ legacySystemSourceID := "system:" + hostname++ legacySystemID := unifiedresources.MachineIdentityCanonicalID(unifiedresources.ResourceTypeAgent, hostname)+ legacyPoolID := unifiedresources.SourceSpecificID(+ unifiedresources.ResourceTypeStorage,+ unifiedresources.SourceTrueNAS,+ scopedPoolSourceID(legacySystemSourceID, "tank"),+ )++ store := unifiedresources.NewMemoryStore()+ for _, canonicalID := range []string{legacySystemID, legacyPoolID} {+ if err := store.SetResourceOperatorState(unifiedresources.ResourceOperatorState{+ CanonicalID: canonicalID,+ IntentionallyOffline: true,+ }); err != nil {+ t.Fatalf("seed operator state for %s: %v", canonicalID, err)+ }+ }+ if err := store.UpsertResourceIdentityPins([]unifiedresources.ResourceIdentityPin{{+ CanonicalID: legacySystemID,+ ResourceType: unifiedresources.ResourceTypeAgent,+ MachineID: hostname,+ Hostname: hostname,+ }}); err != nil {+ t.Fatalf("seed legacy identity pin: %v", err)+ }++ registry := unifiedresources.NewRegistry(store)+ registry.IngestRecords(unifiedresources.SourceTrueNAS, newConnectionProvider(t, fixtures, "conn-a").Records())++ newSystemID := unifiedresources.SourceSpecificID(unifiedresources.ResourceTypeAgent, unifiedresources.SourceTrueNAS, "system:conn-a")+ newPoolID := unifiedresources.SourceSpecificID(+ unifiedresources.ResourceTypeStorage,+ unifiedresources.SourceTrueNAS,+ scopedPoolSourceID("system:conn-a", "tank"),+ )+ system := mustResourceByID(t, registry.List(), newSystemID)+ if system.Agent == nil || system.Agent.AgentID != "conn-a" {+ t.Fatalf("expected connection-scoped system record, got %+v", system.Agent)+ }++ for oldID, newID := range map[string]string{legacySystemID: newSystemID, legacyPoolID: newPoolID} {+ if _, found, err := store.GetResourceOperatorState(oldID); err != nil || found {+ t.Fatalf("expected operator state to leave superseded ID %s (found=%v err=%v)", oldID, found, err)+ }+ state, found, err := store.GetResourceOperatorState(newID)+ if err != nil || !found {+ t.Fatalf("expected operator state re-keyed to %s (found=%v err=%v)", newID, found, err)+ }+ if !state.IntentionallyOffline {+ t.Fatalf("expected re-keyed operator state to keep its fields, got %+v", state)+ }+ }++ pins, err := store.ListResourceIdentityPins()+ if err != nil {+ t.Fatalf("list identity pins: %v", err)+ }+ for _, pin := range pins {+ if pin.CanonicalID == legacySystemID {+ t.Fatalf("expected superseded hostname-derived pin to be deleted, still present: %+v", pin)+ }+ }+}++func TestIngestRecordsDoNotCompleteTrueNASIdentityFromPins(t *testing.T) {+ previous := IsFeatureEnabled()+ SetFeatureEnabled(true)+ t.Cleanup(func() {+ SetFeatureEnabled(previous)+ })++ fixtures := DefaultFixtures()+ fixtures.System.MachineID = ""+ hostname := fixtures.System.Hostname++ // A pulse-agent's pin for a host with the same name must not lend the+ // TrueNAS system its machine key: completion would merge every TrueNAS+ // connection sharing that hostname into the agent host.+ agentPinID := unifiedresources.MachineIdentityCanonicalID(unifiedresources.ResourceTypeAgent, "agent-machine-id")+ store := unifiedresources.NewMemoryStore()+ if err := store.UpsertResourceIdentityPins([]unifiedresources.ResourceIdentityPin{{+ CanonicalID: agentPinID,+ ResourceType: unifiedresources.ResourceTypeAgent,+ MachineID: "agent-machine-id",+ Hostname: hostname,+ }}); err != nil {+ t.Fatalf("seed agent identity pin: %v", err)+ }++ registry := unifiedresources.NewRegistry(store)+ registry.IngestRecords(unifiedresources.SourceTrueNAS, newConnectionProvider(t, fixtures, "conn-a").Records())++ expectedID := unifiedresources.SourceSpecificID(unifiedresources.ResourceTypeAgent, unifiedresources.SourceTrueNAS, "system:conn-a")+ system := mustResourceByID(t, registry.List(), expectedID)+ if system.Identity.MachineID != "" {+ t.Fatalf("expected TrueNAS system identity to stay machine-keyless, got %q", system.Identity.MachineID)+ }+}++func mustResourceByID(t *testing.T, resources []unifiedresources.Resource, id string) unifiedresources.Resource {+ t.Helper()+ for _, resource := range resources {+ if resource.ID == id {+ return resource+ }+ }+ t.Fatalf("missing resource with canonical ID %s", id)+ return unifiedresources.Resource{}+}diff --git a/internal/truenas/fixture_records_test.go b/internal/truenas/fixture_records_test.goindex 8e14622f97..bfc75d47ad 100644--- a/internal/truenas/fixture_records_test.go+++ b/internal/truenas/fixture_records_test.go@@ -12,7 +12,7 @@ func TestFixtureRecordsIgnoreFeatureFlag(t *testing.T) {t.Fatal("expected fixture records even when feature flag is disabled")}- systemID := systemSourceID("truenas-main")+ systemID := systemSourceID("", "truenas-main")for _, record := range records {if record.SourceID == systemID {returndiff --git a/internal/truenas/provider.go b/internal/truenas/provider.goindex 0a74418e5d..ce3ad1036d 100644--- a/internal/truenas/provider.go+++ b/internal/truenas/provider.go@@ -144,6 +144,7 @@ func (f *FixtureFetcher) Fetch(context.Context) (*FixtureSnapshot, error) {// Provider converts TrueNAS snapshot data into unified resources.type Provider struct {fetcher Fetcher+ connectionID stringlastSnapshot *FixtureSnapshotmu sync.Mutexnow func() time.Time@@ -159,6 +160,17 @@ func NewLiveProvider(fetcher Fetcher) *Provider {}}+// NewLiveProviderForConnection returns a live provider whose resources are+// keyed by the configured connection rather than the hostname the TrueNAS API+// reports. Two systems that report the same hostname (a DR box restored from+// the primary's config, the default "truenas" name) must stay distinct+// resources (#1573, #1575).+func NewLiveProviderForConnection(fetcher Fetcher, connectionID string) *Provider {+ provider := NewLiveProvider(fetcher)+ provider.connectionID = strings.TrimSpace(connectionID)+ return provider+}+// NewProvider returns a fixture-backed provider.func NewProvider(fixtures FixtureSnapshot) *Provider {if fixtures.CollectedAt.IsZero() {@@ -300,7 +312,7 @@ func (p *Provider) SystemMetricHistory(ctx context.Context, duration time.Duratiif snapshot == nil {return "", nil, fmt.Errorf("truenas provider has no cached snapshot")}- resourceID := trueNASSystemMetricResourceID(snapshot.System)+ resourceID := trueNASSystemMetricResourceID(p.connectionID, snapshot.System)if resourceID == "" {return "", nil, fmt.Errorf("truenas provider snapshot is missing system metric resource id")}@@ -423,8 +435,10 @@ func (p *Provider) Snapshot() *FixtureSnapshot {// FixtureRecords projects a TrueNAS fixture snapshot into canonical unified// resource ingest records without consulting the runtime feature flag.+// Fixture snapshots carry no connection, so they keep the hostname-scoped+// source IDs that mock mode and the mock metric identities derive.func FixtureRecords(snapshot FixtureSnapshot) []unifiedresources.IngestRecord {- return truenasRecordsFromSnapshot(&snapshot, nil)+ return truenasRecordsFromSnapshot(&snapshot, "", nil)}// Records returns unified records if the feature flag is enabled.@@ -433,10 +447,10 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {return nil}- return truenasRecordsFromSnapshot(p.Snapshot(), p.now)+ return truenasRecordsFromSnapshot(p.Snapshot(), p.connectionID, p.now)}-func truenasRecordsFromSnapshot(snapshot *FixtureSnapshot, now func() time.Time) []unifiedresources.IngestRecord {+func truenasRecordsFromSnapshot(snapshot *FixtureSnapshot, connectionID string, now func() time.Time) []unifiedresources.IngestRecord {if snapshot == nil {return nil}@@ -452,7 +466,37 @@ func truenasRecordsFromSnapshot(snapshot *FixtureSnapshot, now func() time.Time)collectedAt = time.Now().UTC()}}- systemSourceID := systemSourceID(snapshot.System.Hostname)+ systemSourceID := systemSourceID(connectionID, snapshot.System.Hostname)+ // legacySystemSourceID is the retired hostname-keyed derivation. It is+ // only used to compute superseded canonical IDs so operator-owned rows+ // (never-auto-remediate, maintenance windows, action audits) written+ // under the old keys follow the resource onto its connection-scoped ID.+ legacySystemSourceID := ""+ if hostname := strings.TrimSpace(snapshot.System.Hostname); hostname != "" {+ if legacy := "system:" + hostname; legacy != systemSourceID {+ legacySystemSourceID = legacy+ }+ }+ supersededChildIDs := func(resourceType unifiedresources.ResourceType, legacyChildSourceID string) []string {+ if legacySystemSourceID == "" {+ return nil+ }+ return []string{unifiedresources.SourceSpecificID(resourceType, unifiedresources.SourceTrueNAS, legacyChildSourceID)}+ }+ var systemSupersededIDs []string+ if legacySystemSourceID != "" {+ // The retired client fell back to the reported hostname when the DMI+ // serial was empty, and the registry minted the system's canonical ID+ // from that machine key. Reproduce that ladder to name the old ID.+ legacyMachineID := strings.TrimSpace(snapshot.System.MachineID)+ if legacyMachineID == "" {+ legacyMachineID = strings.TrimSpace(snapshot.System.Hostname)+ }+ systemSupersededIDs = []string{+ unifiedresources.MachineIdentityCanonicalID(unifiedresources.ResourceTypeAgent, legacyMachineID),+ unifiedresources.SourceSpecificID(unifiedresources.ResourceTypeAgent, unifiedresources.SourceTrueNAS, legacySystemSourceID),+ }+ }systemAssessment := assessSystemStorage(snapshot)systemRisk := unifiedresources.StorageRiskFromAssessment(systemAssessment)_, protectionReduced, rebuildInProgress, protectionSummary, rebuildSummary := unifiedresources.StorageRiskSemantics(systemRisk)@@ -460,9 +504,10 @@ func truenasRecordsFromSnapshot(snapshot *FixtureSnapshot, now func() time.Time)records := make([]unifiedresources.IngestRecord, 0, 1+len(snapshot.Pools)+len(snapshot.Datasets)+len(snapshot.Apps)+len(snapshot.VMs)+len(snapshot.Shares)+len(snapshot.Disks))totalCapacity, totalUsed := aggregatePoolUsage(snapshot.Pools)- systemAgent := agentDataFromTrueNASSystem(snapshot.System, systemRisk, protectionReduced, protectionSummary, rebuildInProgress, rebuildSummary)+ systemAgent := agentDataFromTrueNASSystem(connectionID, snapshot.System, systemRisk, protectionReduced, protectionSummary, rebuildInProgress, rebuildSummary)records = append(records, unifiedresources.IngestRecord{- SourceID: systemSourceID,+ SourceID: systemSourceID,+ SupersededCanonicalIDs: systemSupersededIDs,Resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypeAgent,Name: strings.TrimSpace(snapshot.System.Hostname),@@ -493,8 +538,12 @@ func truenasRecordsFromSnapshot(snapshot *FixtureSnapshot, now func() time.Time)},Incidents: systemIncidents,},+ // The system's identity deliberately carries no machine key: the+ // TrueNAS DMI serial is shared by DR clones and can be vendor+ // placeholder garbage, so the identity matcher would re-merge the+ // systems this record's connection-scoped source ID keeps apart+ // (#1573, #1575). The configured connection is the identity.Identity: unifiedresources.ResourceIdentity{- MachineID: snapshot.System.MachineID,Hostnames: []string{snapshot.System.Hostname},},})@@ -505,8 +554,9 @@ func truenasRecordsFromSnapshot(snapshot *FixtureSnapshot, now func() time.Time)incidents := poolIncidents[strings.TrimSpace(pool.Name)]poolSourceID := scopedPoolSourceID(systemSourceID, pool.Name)records = append(records, unifiedresources.IngestRecord{- SourceID: poolSourceID,- ParentSourceID: systemSourceID,+ SourceID: poolSourceID,+ ParentSourceID: systemSourceID,+ SupersededCanonicalIDs: supersededChildIDs(unifiedresources.ResourceTypeStorage, scopedPoolSourceID(legacySystemSourceID, pool.Name)),Resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypeStorage,Name: pool.Name,@@ -549,8 +599,9 @@ func truenasRecordsFromSnapshot(snapshot *FixtureSnapshot, now func() time.Time)}totalBytes := dataset.UsedBytes + dataset.AvailBytesrecords = append(records, unifiedresources.IngestRecord{- SourceID: scopedDatasetSourceID(systemSourceID, dataset.Name),- ParentSourceID: scopedPoolSourceID(systemSourceID, parentPool),+ SourceID: scopedDatasetSourceID(systemSourceID, dataset.Name),+ ParentSourceID: scopedPoolSourceID(systemSourceID, parentPool),+ SupersededCanonicalIDs: supersededChildIDs(unifiedresources.ResourceTypeStorage, scopedDatasetSourceID(legacySystemSourceID, dataset.Name)),Resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypeStorage,Name: dataset.Name,@@ -616,8 +667,9 @@ func truenasRecordsFromSnapshot(snapshot *FixtureSnapshot, now func() time.Time)}records = append(records, unifiedresources.IngestRecord{- SourceID: scopedAppSourceID(systemSourceID, app),- ParentSourceID: systemSourceID,+ SourceID: scopedAppSourceID(systemSourceID, app),+ ParentSourceID: systemSourceID,+ SupersededCanonicalIDs: supersededChildIDs(unifiedresources.ResourceTypeAppContainer, scopedAppSourceID(legacySystemSourceID, app)),Resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypeAppContainer,Technology: "docker",@@ -642,8 +694,9 @@ func truenasRecordsFromSnapshot(snapshot *FixtureSnapshot, now func() time.Time)for _, vm := range snapshot.VMs {records = append(records, unifiedresources.IngestRecord{- SourceID: scopedVirtualMachineSourceID(systemSourceID, vm),- ParentSourceID: systemSourceID,+ SourceID: scopedVirtualMachineSourceID(systemSourceID, vm),+ ParentSourceID: systemSourceID,+ SupersededCanonicalIDs: supersededChildIDs(unifiedresources.ResourceTypeVM, scopedVirtualMachineSourceID(legacySystemSourceID, vm)),Resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypeVM,Name: virtualMachineDisplayName(vm),@@ -674,8 +727,9 @@ func truenasRecordsFromSnapshot(snapshot *FixtureSnapshot, now func() time.Time)parentSourceID = scopedPoolSourceID(systemSourceID, pool)}records = append(records, unifiedresources.IngestRecord{- SourceID: scopedNetworkShareSourceID(systemSourceID, share),- ParentSourceID: parentSourceID,+ SourceID: scopedNetworkShareSourceID(systemSourceID, share),+ ParentSourceID: parentSourceID,+ SupersededCanonicalIDs: supersededChildIDs(unifiedresources.ResourceTypeNetworkShare, scopedNetworkShareSourceID(legacySystemSourceID, share)),Resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypeNetworkShare,Name: networkShareDisplayName(share),@@ -710,9 +764,17 @@ func truenasRecordsFromSnapshot(snapshot *FixtureSnapshot, now func() time.Time)if pool := strings.TrimSpace(disk.Pool); pool != "" {parentSourceID = scopedPoolSourceID(systemSourceID, pool)}+ // Disks with a serial mint identity-keyed canonical IDs that do not+ // depend on the source ID, so only serial-less disks re-key when the+ // system scope moves to the connection.+ var diskSupersededIDs []string+ if disk.Serial == "" {+ diskSupersededIDs = supersededChildIDs(unifiedresources.ResourceTypePhysicalDisk, scopedDiskSourceID(legacySystemSourceID, disk.Name))+ }records = append(records, unifiedresources.IngestRecord{- SourceID: scopedDiskSourceID(systemSourceID, disk.Name),- ParentSourceID: parentSourceID,+ SourceID: scopedDiskSourceID(systemSourceID, disk.Name),+ ParentSourceID: parentSourceID,+ SupersededCanonicalIDs: diskSupersededIDs,Resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypePhysicalDisk,Name: disk.Name,@@ -851,9 +913,9 @@ func metricsFromTrueNASSystem(system SystemInfo, totalCapacity, totalUsed int64)return metrics}-func agentDataFromTrueNASSystem(system SystemInfo, storageRisk *unifiedresources.StorageRisk, protectionReduced bool, protectionSummary string, rebuildInProgress bool, rebuildSummary string) *unifiedresources.AgentData {+func agentDataFromTrueNASSystem(connectionID string, system SystemInfo, storageRisk *unifiedresources.StorageRisk, protectionReduced bool, protectionSummary string, rebuildInProgress bool, rebuildSummary string) *unifiedresources.AgentData {agent := &unifiedresources.AgentData{- AgentID: trueNASSystemMetricResourceID(system),+ AgentID: trueNASSystemMetricResourceID(connectionID, system),Hostname: strings.TrimSpace(system.Hostname),MachineID: strings.TrimSpace(system.MachineID),Platform: "truenas",@@ -1314,7 +1376,16 @@ func aggregatePoolUsage(pools []Pool) (int64, int64) {return total, used}-func systemSourceID(hostname string) string {+// systemSourceID keys an API-added TrueNAS system by the configured+// connection. The reported hostname is not an identity: two systems that+// report the same hostname (a DR clone, the default "truenas" name) must not+// collapse into one resource and flap between each other's data every poll+// (#1573, #1575). The hostname arm survives only for fixture snapshots,+// which carry no connection.+func systemSourceID(connectionID, hostname string) string {+ if id := strings.TrimSpace(connectionID); id != "" {+ return "system:" + id+ }return "system:" + strings.TrimSpace(hostname)}@@ -2116,7 +2187,15 @@ func systemMemoryPercentHistory(history *SystemMetricHistory, fallbackTotalBytesreturn nil}-func trueNASSystemMetricResourceID(system SystemInfo) string {+// trueNASSystemMetricResourceID must stay systemSourceID minus its "system:"+// prefix: BuildMetricsTarget derives the agent metric target by stripping+// that prefix from the TrueNAS source ID (canonicalAgentMetricID), and the+// records' Agent.AgentID plus the native history keys returned by+// SystemMetricHistory have to resolve to the same series.+func trueNASSystemMetricResourceID(connectionID string, system SystemInfo) string {+ if id := strings.TrimSpace(connectionID); id != "" {+ return id+ }return strings.TrimSpace(system.Hostname)}diff --git a/internal/unifiedresources/ids.go b/internal/unifiedresources/ids.goindex 55b71801b1..c000acfb89 100644--- a/internal/unifiedresources/ids.go+++ b/internal/unifiedresources/ids.go@@ -24,6 +24,15 @@ func SourceSpecificID(resourceType ResourceType, source DataSource, sourceID strreturn fmt.Sprintf("%s-%s", resourceType, hex.EncodeToString(hash[:8]))}+// MachineIdentityCanonicalID returns the canonical ID the registry mints for+// a resource keyed by its machine identity, the strongest arm of the+// chooseNewID ladder. Providers use it to name superseded canonical IDs+// (IngestRecord.SupersededCanonicalIDs) when a derivation correction retires+// a machine key, so operator-owned rows follow the resource to its new ID.+func MachineIdentityCanonicalID(resourceType ResourceType, machineID string) string {+ return buildHashID(resourceType, "machine:"+strings.TrimSpace(machineID))+}+// 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 31c40072a8..139daa7374 100644--- a/internal/unifiedresources/ids_test.go+++ b/internal/unifiedresources/ids_test.go@@ -104,3 +104,11 @@ func TestResourceIdentityPinEraIDsSkipsWeakOnlyKeys(t *testing.T) {t.Fatalf("expected era IDs %v, got %v", want, got)}}++func TestMachineIdentityCanonicalIDMatchesRegistryMachineArm(t *testing.T) {+ registry := NewRegistry(NewMemoryStore())+ want := registry.canonicalIDFromIdentity(ResourceTypeAgent, ResourceIdentity{MachineID: "machine-123"})+ if got := MachineIdentityCanonicalID(ResourceTypeAgent, " machine-123 "); got != want {+ t.Fatalf("MachineIdentityCanonicalID = %q, want registry machine-arm ID %q", got, want)+ }+}diff --git a/internal/unifiedresources/registry.go b/internal/unifiedresources/registry.goindex 322a71ac33..7b392960ab 100644--- a/internal/unifiedresources/registry.go+++ b/internal/unifiedresources/registry.go@@ -70,6 +70,15 @@ type IngestRecord struct {ParentSourceID stringResource ResourceIdentity ResourceIdentity+ // SupersededCanonicalIDs names canonical IDs this record's resource was+ // minted under by a retired derivation era (e.g. TrueNAS systems keyed by+ // reported hostname before they were keyed by the configured connection).+ // After ingest, operator-owned rows (resource_operator_state,+ // action_audits) and the superseded identity pin re-key to the record's+ // current canonical ID via canonical-ID succession, with the same guards+ // as pin-driven successions: never while the old ID still belongs to a+ // live resource, and change-journal rows are never rewritten.+ SupersededCanonicalIDs []string}// ResourceRegistry merges resources from multiple sources.@@ -500,6 +509,8 @@ func (rr *ResourceRegistry) ingestSnapshot(snapshot models.StateSnapshot, thresh// IngestRecords ingests normalized records for a single source.func (rr *ResourceRegistry) IngestRecords(source DataSource, records []IngestRecord) {+ var successions []CanonicalIDSuccession+ supersededSeen := make(map[string]struct{})for _, record := range records {sourceID := normalizeSourceID(record.SourceID)if sourceID == "" {@@ -512,8 +523,23 @@ func (rr *ResourceRegistry) IngestRecords(source DataSource, records []IngestRecresource.ParentID = &parentID}}- rr.ingest(source, sourceID, resource, record.Identity)+ newID := rr.ingest(source, sourceID, resource, record.Identity)+ for _, superseded := range record.SupersededCanonicalIDs {+ superseded = CanonicalResourceID(superseded)+ if superseded == "" || newID == "" || superseded == newID {+ continue+ }+ if _, dup := supersededSeen[superseded]; dup {+ continue+ }+ supersededSeen[superseded] = struct{}{}+ successions = append(successions, CanonicalIDSuccession{+ OldCanonicalID: superseded,+ NewCanonicalID: newID,+ })+ }}+ rr.applyRecordSuccessions(successions)rr.mu.Lock()rr.refreshStorageConsumersLocked()@@ -525,6 +551,39 @@ func (rr *ResourceRegistry) IngestRecords(source DataSource, records []IngestRecrr.mu.Unlock()}+// applyRecordSuccessions re-keys operator-owned store rows from canonical IDs+// that ingested records declared superseded (IngestRecord.SupersededCanonicalIDs)+// onto the records' current canonical IDs. Mirrors the guards of pin-driven+// successions in PersistIdentityPins: a superseded ID still held by a live+// resource is skipped so a genuinely distinct sibling never has its rows+// stolen. Re-runs are cheap no-ops once the old rows are gone.+func (rr *ResourceRegistry) applyRecordSuccessions(successions []CanonicalIDSuccession) {+ if len(successions) == 0 || rr.store == nil {+ return+ }+ successor, ok := rr.store.(canonicalIDSuccessor)+ if !ok {+ return+ }++ rr.mu.RLock()+ kept := make([]CanonicalIDSuccession, 0, len(successions))+ for _, succession := range successions {+ if _, live := rr.resources[succession.OldCanonicalID]; live {+ continue+ }+ kept = append(kept, succession)+ }+ rr.mu.RUnlock()++ if len(kept) == 0 {+ return+ }+ if err := successor.ApplyCanonicalIDSuccessions(kept); err != nil {+ log.Printf("unifiedresources: failed to apply record-declared canonical ID successions: %v", err)+ }+}+// IngestResources seeds the registry from already-unified resources.// This is used when a caller already has a canonical unified read model and// only needs store-backed manual links/exclusions applied on top.@@ -2283,8 +2342,14 @@ func (rr *ResourceRegistry) ingest(source DataSource, sourceID string, resource// Complete weak host identities from the durable pins before matching and// ID derivation, so canonical IDs do not depend on which sources happen to// be present in this rebuild (boot windows ingest the Proxmox node record- // before the agent has checked in).- identity = rr.completeIdentityFromPins(resource.Type, identity)+ // before the agent has checked in). TrueNAS is exempt: its systems are+ // keyed by the configured connection and deliberately carry no machine+ // key, so a hostname-bucket pin (a stale pre-#1573 TrueNAS pin, or a+ // pulse-agent's pin on a same-named host) completing the identity would+ // re-merge systems the connection scoping keeps apart.+ if source != SourceTrueNAS {+ identity = rr.completeIdentityFromPins(resource.Type, identity)+ }resource.Identity = identityresource.Sources = []DataSource{source}resource.SourceStatus = map[DataSource]SourceStatus{diff --git a/internal/unifiedresources/registry_test.go b/internal/unifiedresources/registry_test.goindex 21914355eb..db422e1c9e 100644--- a/internal/unifiedresources/registry_test.go+++ b/internal/unifiedresources/registry_test.go@@ -5101,3 +5101,76 @@ func TestCanonicalIDSuccessionSkipsLiveShortNamedHost(t *testing.T) {t.Fatalf("FQDN sibling stole the live short-named host's operator state")}}++// Record-declared successions (IngestRecord.SupersededCanonicalIDs) must+// re-key operator rows to the record's minted canonical ID, but never while+// the superseded ID still belongs to a live resource in the registry: a+// distinct sibling's rows must not be stolen.+func TestIngestRecordsRecordDeclaredSuccessions(t *testing.T) {+ store := NewMemoryStore()+ oldID := SourceSpecificID(ResourceTypeStorage, SourceTrueNAS, "system:legacy-host/pool:tank")+ if err := store.SetResourceOperatorState(ResourceOperatorState{+ CanonicalID: oldID,+ NeverAutoRemediate: true,+ }); err != nil {+ t.Fatalf("seed operator state: %v", err)+ }++ registry := NewRegistry(store)+ registry.IngestRecords(SourceTrueNAS, []IngestRecord{{+ SourceID: "system:conn-a/pool:tank",+ Resource: Resource{+ Type: ResourceTypeStorage,+ Name: "tank",+ LastSeen: time.Now().UTC(),+ },+ SupersededCanonicalIDs: []string{oldID},+ }})++ newID := SourceSpecificID(ResourceTypeStorage, SourceTrueNAS, "system:conn-a/pool:tank")+ if _, found, err := store.GetResourceOperatorState(oldID); err != nil || found {+ t.Fatalf("expected operator state to leave superseded ID (found=%v err=%v)", found, err)+ }+ state, found, err := store.GetResourceOperatorState(newID)+ if err != nil || !found || !state.NeverAutoRemediate {+ t.Fatalf("expected operator state re-keyed to %s (found=%v err=%v state=%+v)", newID, found, err, state)+ }+}++func TestIngestRecordsSkipRecordDeclaredSuccessionForLiveOldID(t *testing.T) {+ store := NewMemoryStore()+ oldID := SourceSpecificID(ResourceTypeStorage, SourceTrueNAS, "system:legacy-host/pool:tank")+ if err := store.SetResourceOperatorState(ResourceOperatorState{+ CanonicalID: oldID,+ NeverAutoRemediate: true,+ }); err != nil {+ t.Fatalf("seed operator state: %v", err)+ }++ registry := NewRegistry(store)+ // The old derivation is still alive in this registry: another record+ // legitimately owns it, so the succession must not run.+ registry.IngestRecords(SourceTrueNAS, []IngestRecord{+ {+ SourceID: "system:legacy-host/pool:tank",+ Resource: Resource{+ Type: ResourceTypeStorage,+ Name: "tank",+ LastSeen: time.Now().UTC(),+ },+ },+ {+ SourceID: "system:conn-a/pool:tank",+ Resource: Resource{+ Type: ResourceTypeStorage,+ Name: "tank",+ LastSeen: time.Now().UTC(),+ },+ SupersededCanonicalIDs: []string{oldID},+ },+ })++ if _, found, err := store.GetResourceOperatorState(oldID); err != nil || !found {+ t.Fatalf("expected operator state to stay under live old ID (found=%v err=%v)", found, err)+ }+}