Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

85.4 KB
Raw Blame
package monitoring

import (
	"encoding/json"
	"fmt"
	"math"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"testing"
	"time"

	"github.com/rcourtman/pulse-go-rewrite/internal/ai/memory"
	"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
	"github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog"
	"github.com/rcourtman/pulse-go-rewrite/internal/config"
	"github.com/rcourtman/pulse-go-rewrite/internal/mock"
	"github.com/rcourtman/pulse-go-rewrite/internal/models"
	unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
	"github.com/rcourtman/pulse-go-rewrite/internal/vmware"
	agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker"
	"github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
)

var bannedSnapshotResourceAccessPatterns = []struct {
	re      *regexp.Regexp
	message string
}{
	{
		re:      regexp.MustCompile(`GetState\(\)\.(VMs|Containers|Nodes|Hosts|DockerHosts|PBSInstances|Storage|PhysicalDisks)\b`),
		message: "derive canonical monitoring resource views through ReadState-backed helpers instead of GetState() resource arrays",
	},
}

func TestAvailabilityTLSUsesSharedCertificateCaptureBoundary(t *testing.T) {
	// The probe execution core moved to internal/availabilityprobe so the host
	// agent can share it; the TLS boundary guardrail follows the code and still
	// covers the monitoring poller that schedules the probes.
	const probeCore = "../availabilityprobe/probe.go"
	sources := make(map[string]string, 2)
	for _, path := range []string{"availability_poller.go", probeCore} {
		data, err := os.ReadFile(path)
		if err != nil {
			t.Fatalf("read %s: %v", path, err)
		}
		text := string(data)
		sources[path] = text
		if strings.Contains(text, "InsecureSkipVerify: true") {
			t.Fatalf("%s must not define a local skip-verification TLS config", path)
		}
	}
	if !strings.Contains(sources[probeCore], "tlsutil.UnverifiedPeerCertificateCaptureTLSConfig()") {
		t.Fatal("availability probes must use the shared peer-certificate capture boundary")
	}
}

type guardrailSupplementalProvider struct {
	records []unifiedresources.IngestRecord
}

func (p guardrailSupplementalProvider) SupplementalRecords(*Monitor, string) []unifiedresources.IngestRecord {
	out := make([]unifiedresources.IngestRecord, len(p.records))
	copy(out, p.records)
	return out
}

func readMonitoringRuntimeFiles(t *testing.T) map[string]string {
	t.Helper()

	files := make(map[string]string)
	entries, err := os.ReadDir(".")
	if err != nil {
		t.Fatalf("failed to read monitoring directory: %v", err)
	}

	for _, entry := range entries {
		name := entry.Name()
		if entry.IsDir() || filepath.Ext(name) != ".go" || strings.HasSuffix(name, "_test.go") {
			continue
		}
		data, err := os.ReadFile(name)
		if err != nil {
			t.Fatalf("failed to read %s: %v", name, err)
		}
		files[name] = string(data)
	}

	return files
}

func TestNoGetStateResourceArrayRegression(t *testing.T) {
	for name, content := range readMonitoringRuntimeFiles(t) {
		for _, pattern := range bannedSnapshotResourceAccessPatterns {
			if matches := pattern.re.FindAllStringIndex(content, -1); len(matches) > 0 {
				for _, match := range matches {
					line := 1 + strings.Count(content[:match[0]], "\n")
					t.Errorf("%s:%d: %s", name, line, pattern.message)
				}
			}
		}
	}
}

func TestPBSClientConstructionCannotPublishConnectedHealth(t *testing.T) {
	for _, name := range []string{"monitor_client_init.go", "monitor_client_reconnect.go"} {
		data, err := os.ReadFile(name)
		if err != nil {
			t.Fatalf("read %s: %v", name, err)
		}
		source := string(data)
		if strings.Contains(source, "setProviderConnectionHealth(InstanceTypePBS") {
			t.Fatalf("%s must wait for a completed PBS poll before publishing connection health", name)
		}
		if !strings.Contains(source, "awaiting") {
			t.Fatalf("%s must make the first-poll boundary explicit", name)
		}
	}
}

// Keep the registered monitoring proof connected to executable lifecycle,
// trust and actual producer controls, not a source-text expiry assertion.
func TestStartupConnectionRecoveryCanonicalContract(t *testing.T) {
	t.Run("late-recovery", TestConnectionRetrySurvivesLongStartupOutage)
	t.Run("cancel-capped-wait", TestConnectionRetryLongOutageStopsOnCancellation)
	t.Run("paused-exclusions", TestConnectionRetryDoesNotResumePausedConnections)
	t.Run("pbs-trust-and-first-poll", TestPBSStartupRecoveryKeepsTrustAndFirstPollBoundary)
}

func TestMultiTenantMonitorListOrganizationIDsFallsBackToDefault(t *testing.T) {
	got, err := (&MultiTenantMonitor{}).ListOrganizationIDs()
	if err != nil {
		t.Fatalf("ListOrganizationIDs() error = %v", err)
	}
	if len(got) != 1 || got[0] != "default" {
		t.Fatalf("ListOrganizationIDs() = %v, want [default]", got)
	}
}

func TestVMwareManualConnectionTestPreservesDegradedDiagnostics(t *testing.T) {
	poller := NewVMwarePoller(nil, time.Minute)
	connection := config.NewVMwareVCenterInstance()
	connection.ID = "vc-degraded"
	connection.Host = "vc.lab.local"
	connection.Username = "[email protected]"
	connection.Password = "secret"

	recordedAt := time.Date(2026, 7, 23, 19, 0, 0, 0, time.UTC)
	poller.RecordConnectionTestSuccess("default", connection.ID, &vmware.InventorySummary{
		Hosts:      2,
		VMs:        14,
		Datastores: 3,
		Networks:   5,
		VIRelease:  "8.0.2.0",
		Degraded:   true,
		Issues: []vmware.InventoryEnrichmentIssue{
			{
				Stage:      "signals",
				EntityType: "host",
				EntityID:   "host-101",
				Category:   "endpoint",
				Message:    "VMware HostSystem recent events request failed with HTTP 500",
			},
		},
	}, recordedAt)

	summary := poller.ConnectionSummaries("default", []config.VMwareVCenterInstance{connection})[connection.ID]
	if summary.Poll == nil || summary.Poll.LastSuccessAt == nil || !summary.Poll.LastSuccessAt.Equal(recordedAt) {
		t.Fatalf("expected degraded test to remain a successful connection attempt, got %+v", summary.Poll)
	}
	if summary.Observed == nil || !summary.Observed.Degraded || summary.Observed.IssueCount != 1 {
		t.Fatalf("expected degraded observed summary, got %+v", summary.Observed)
	}
	if len(summary.Observed.Issues) != 1 ||
		summary.Observed.Issues[0].Stage != "signals" ||
		summary.Observed.Issues[0].Category != "endpoint" ||
		summary.Observed.Issues[0].Message != "VMware HostSystem recent events request failed with HTTP 500" ||
		summary.Observed.Issues[0].Occurrences != 1 {
		t.Fatalf("expected preserved summarized diagnostic, got %+v", summary.Observed.Issues)
	}
}

func TestProxmoxActionObserverUsesDirectControlPlaneClient(t *testing.T) {
	data, err := os.ReadFile("proxmox_action_observer.go")
	if err != nil {
		t.Fatalf("read proxmox_action_observer.go: %v", err)
	}
	source := string(data)
	for _, snippet := range []string{"m.getPVEClient(instance)", "client.GetVMStatus(ctx, node, vmid)", "client.GetContainerStatus(ctx, node, vmid)"} {
		if !strings.Contains(source, snippet) {
			t.Fatalf("Proxmox action observer must use direct control-plane read %q", snippet)
		}
	}
	for _, forbidden := range []string{"m.GetState(", "m.ReadState(", "m.resourceStore", "m.state."} {
		if strings.Contains(source, forbidden) {
			t.Fatalf("Proxmox action observer must not derive independent evidence through cached monitoring state %q", forbidden)
		}
	}
}

func TestBroadcastResourceDiskIOUsesUnifiedResourceMetrics(t *testing.T) {
	readRate, writeRate := monitorDiskIOMetricInput(&unifiedresources.ResourceMetrics{
		DiskRead:  &unifiedresources.MetricValue{Value: 4096.4, Unit: "bytes/s", Source: unifiedresources.SourceAgent},
		DiskWrite: &unifiedresources.MetricValue{Value: 8191.6, Unit: "bytes/s", Source: unifiedresources.SourceAgent},
	})
	if readRate == nil || writeRate == nil {
		t.Fatal("expected disk I/O metrics to be projected")
	}
	if *readRate != 4096 || *writeRate != 8192 {
		t.Fatalf("unexpected projected disk I/O rates: read=%d write=%d", *readRate, *writeRate)
	}
}

func TestProxmoxReadStateCPUPercentRehydratesLegacyRatios(t *testing.T) {
	const (
		canonicalPercent = 0.6
		legacyRatio      = 0.006
	)

	t.Run("node", func(t *testing.T) {
		view := unifiedresources.NewNodeView(&unifiedresources.Resource{
			ID:     "node-pve1",
			Name:   "pve1",
			Type:   unifiedresources.ResourceTypeAgent,
			Status: unifiedresources.StatusOnline,
			Metrics: &unifiedresources.ResourceMetrics{
				CPU: &unifiedresources.MetricValue{Percent: canonicalPercent},
			},
			Proxmox: &unifiedresources.ProxmoxData{
				SourceID: "node/pve1",
				NodeName: "pve1",
				Instance: "lab",
			},
		})

		got := nodeFromReadStateView(&view)
		assertFloatClose(t, got.CPU, legacyRatio)
	})

	t.Run("vm", func(t *testing.T) {
		view := unifiedresources.NewVMView(&unifiedresources.Resource{
			ID:     "vm-101",
			Name:   "debian",
			Type:   unifiedresources.ResourceTypeVM,
			Status: unifiedresources.StatusOnline,
			Metrics: &unifiedresources.ResourceMetrics{
				CPU: &unifiedresources.MetricValue{Percent: canonicalPercent},
			},
			Proxmox: &unifiedresources.ProxmoxData{
				SourceID: "qemu/101",
				NodeName: "pve1",
				Instance: "lab",
				VMID:     101,
			},
		})

		got := vmFromReadStateView(&view)
		assertFloatClose(t, got.CPU, legacyRatio)
	})

	t.Run("container", func(t *testing.T) {
		view := unifiedresources.NewContainerView(&unifiedresources.Resource{
			ID:     "ct-201",
			Name:   "nginx",
			Type:   unifiedresources.ResourceTypeSystemContainer,
			Status: unifiedresources.StatusOnline,
			Metrics: &unifiedresources.ResourceMetrics{
				CPU: &unifiedresources.MetricValue{Percent: canonicalPercent},
			},
			Proxmox: &unifiedresources.ProxmoxData{
				SourceID:      "lxc/201",
				NodeName:      "pve1",
				Instance:      "lab",
				VMID:          201,
				ContainerType: "lxc",
			},
		})

		got := containerFromReadStateView(&view)
		assertFloatClose(t, got.CPU, legacyRatio)
	})
}

func assertFloatClose(t *testing.T, got float64, want float64) {
	t.Helper()

	if math.Abs(got-want) > 0.000001 {
		t.Fatalf("got %v, want %v", got, want)
	}
}

func TestStandaloneInactiveDockerSwarmMetadataIsNotCapabilityEvidence(t *testing.T) {
	got := convertDockerSwarmInfo(&agentsdocker.SwarmInfo{
		NodeRole:   "worker",
		LocalState: "inactive",
		Scope:      "node",
	})
	if got != nil {
		t.Fatalf("expected inactive standalone Docker Swarm metadata to be omitted, got %+v", got)
	}
}

func TestDockerInventoryConvertersPreserveNativeRuntimeFields(t *testing.T) {
	createdAt := time.Date(2026, 5, 24, 8, 0, 0, 0, time.UTC)

	images := convertDockerImages([]agentsdocker.Image{{
		ID:          " sha256:image1 ",
		RepoTags:    []string{"repo/app:latest"},
		RepoDigests: []string{"repo/app@sha256:abc"},
		SizeBytes:   1024,
		CreatedAt:   createdAt,
		Labels:      map[string]string{"tier": "web"},
	}})
	if len(images) != 1 || images[0].ID != "sha256:image1" || images[0].Labels["tier"] != "web" {
		t.Fatalf("unexpected image conversion: %+v", images)
	}

	volumes := convertDockerVolumes([]agentsdocker.Volume{{
		Name: " app-data ", Driver: " local ", SizeBytes: 2048, RefCount: 3, Labels: map[string]string{"backup": "true"},
	}})
	if len(volumes) != 1 || volumes[0].Name != "app-data" || volumes[0].SizeBytes != 2048 || volumes[0].Labels["backup"] != "true" {
		t.Fatalf("unexpected volume conversion: %+v", volumes)
	}

	networks := convertDockerNetworks([]agentsdocker.Network{{
		ID: " net1 ", Name: " app-net ", Driver: " bridge ", EnableIPv4: true, Subnets: []agentsdocker.NetworkSubnet{{Subnet: " 10.88.0.0/24 ", Gateway: " 10.88.0.1 "}},
	}})
	if len(networks) != 1 || networks[0].Name != "app-net" || networks[0].Subnets[0].Subnet != "10.88.0.0/24" {
		t.Fatalf("unexpected network conversion: %+v", networks)
	}

	usage := convertDockerStorageUsage(&agentsdocker.StorageUsage{
		Images: agentsdocker.StorageUsageBucket{TotalCount: 3, ActiveCount: 2, TotalSizeBytes: 4096, ReclaimableBytes: 512},
	})
	if usage == nil || usage.Images.TotalCount != 3 || usage.Images.ReclaimableBytes != 512 {
		t.Fatalf("unexpected storage usage conversion: %+v", usage)
	}

	nodes := convertDockerNodes([]agentsdocker.Node{{
		ID:                  " node-manager ",
		Hostname:            " manager-1 ",
		Role:                " manager ",
		Availability:        " active ",
		State:               " ready ",
		Address:             " 192.0.2.10 ",
		ManagerReachability: " reachable ",
		ManagerAddress:      " 192.0.2.10:2377 ",
		Leader:              true,
		EngineVersion:       " 27.5.1 ",
		OS:                  " linux ",
		Architecture:        " amd64 ",
		NanoCPUs:            8_000_000_000,
		MemoryBytes:         32 * 1024 * 1024 * 1024,
		Labels:              map[string]string{"zone": "rack-a"},
		EngineLabels:        map[string]string{"engine": "primary"},
		CreatedAt:           createdAt,
	}})
	if len(nodes) != 1 || nodes[0].ID != "node-manager" || nodes[0].ManagerReachability != "reachable" || nodes[0].EngineLabels["engine"] != "primary" {
		t.Fatalf("unexpected swarm node conversion: %+v", nodes)
	}
}

func TestPVEBackupPermissionWarningsPreserveNonDestructiveGuidance(t *testing.T) {
	warning := pveBackupPermissionWarning(&config.PVEInstance{TokenName: "different-reader@pve!manual"})
	if !strings.Contains(warning, "saved PVE connection") || !strings.Contains(warning, "privilege separation") || !strings.Contains(warning, "rejected endpoint") {
		t.Fatalf("missing identity/scope guidance: %q", warning)
	}
	if strings.Contains(warning, "pveum") || strings.Contains(warning, "PVEDatastoreAdmin") || strings.Contains(warning, "pulse-monitor@pve") {
		t.Fatalf("unconditional ACL recipe survived: %q", warning)
	}
}

func TestLegacySSHTemperatureUsesPulseSensorWrapperContract(t *testing.T) {
	if !strings.Contains(pulseSensorsSSHCommand, "/usr/local/sbin/pulse-sensors") {
		t.Fatalf("legacy SSH temperature command must prefer Pulse sensor wrapper, got %q", pulseSensorsSSHCommand)
	}
	if !strings.Contains(pulseSensorsSSHCommand, "sensors -j") {
		t.Fatalf("legacy SSH temperature command must preserve sensors -j fallback for old forced keys, got %q", pulseSensorsSSHCommand)
	}
	if strings.Contains(pulseSensorsSSHCommand, "smartctl") {
		t.Fatalf("SMART collection belongs inside the remote wrapper, not the local SSH command: %q", pulseSensorsSSHCommand)
	}
}

func TestPBSBackupsSnapshotPreservesSourceArtifactFields(t *testing.T) {
	state := models.NewState()
	backupTime := time.Date(2026, 5, 25, 1, 34, 25, 0, time.UTC)
	state.UpdatePBSBackups("pbs-main", []models.PBSBackup{{
		ID:         "pbs-main/main/minipc/ct/112/2026-05-25T01:34:25Z",
		Instance:   "pbs-main",
		Datastore:  "main",
		Namespace:  "minipc",
		BackupType: "ct",
		VMID:       "112",
		BackupTime: backupTime,
		Size:       8_589_934_592,
		Protected:  true,
		Verified:   true,
		Comment:    "debian-go",
		Files:      []string{"index.json.blob", "root.pxar.didx"},
		Owner:      "backup@pbs",
	}})
	monitor := &Monitor{state: state}

	got := monitor.PBSBackupsSnapshot()
	if len(got) != 1 {
		t.Fatalf("expected one PBS backup, got %d", len(got))
	}
	if got[0].Datastore != "main" || got[0].Namespace != "minipc" || got[0].VMID != "112" {
		t.Fatalf("unexpected PBS artifact identity: %+v", got[0])
	}
	if got[0].Size != 8_589_934_592 || !got[0].Protected || !got[0].Verified {
		t.Fatalf("PBS artifact source fields were not preserved: %+v", got[0])
	}
	if got[0].Owner != "backup@pbs" || len(got[0].Files) != 2 {
		t.Fatalf("PBS artifact owner/files were not preserved: %+v", got[0])
	}
}

func TestGuestSnapshotPollingStaysBoundedConcurrent(t *testing.T) {
	// Guard real concurrency, waiting work and complete membership, rather
	// than requiring a semaphore that still spawns a goroutine per guest.
	testSnapshotPollWorkersBoundWaitingAndActiveWork(t)
}

// Monitor state and live snapshots switch to the fixture graph in mock mode,
// so a store refresh must take its mock-mode scope before it reads them.
// Go evaluates call arguments left to right: a scope begun in the argument
// after the read belongs to the epoch the snapshot may already have left.
func TestStoreRefreshTakesItsMockModeScopeBeforeReadingState(t *testing.T) {
	files, err := filepath.Glob("*.go")
	if err != nil {
		t.Fatalf("glob monitoring sources: %v", err)
	}
	for _, file := range files {
		if strings.HasSuffix(file, "_test.go") {
			continue
		}
		data, err := os.ReadFile(file)
		if err != nil {
			t.Fatalf("read %s: %v", file, err)
		}
		source := string(data)
		for _, forbidden := range []string{
			"GetState(), m.mockModeFence.begin()",
			"GetSnapshot(), m.mockModeFence.begin()",
		} {
			if strings.Contains(source, forbidden) {
				t.Errorf("%s reads state before taking its mock-mode scope (%q); use currentStateWithScope or begin the scope first", file, forbidden)
			}
		}
	}

	data, err := os.ReadFile("monitor.go")
	if err != nil {
		t.Fatalf("failed to read monitor.go: %v", err)
	}
	source := string(data)
	if got := strings.Count(source, "m.mockModeFence.advance()\n\tm.alertManager.ClearActiveAlerts()"); got != 1 {
		t.Fatalf("endMockModeEpoch must end the mock-mode epoch immediately before clearing alerts, found %d", got)
	}
	if !strings.Contains(source, "for _, monitor := range monitors {\n\t\tmonitor.endMockModeEpoch(enable)\n\t}") {
		t.Fatal("SetMockMode must end the epoch of every monitor the switch reaches")
	}
}

func TestHostUnraidReadStateProjectionPreservesNativeDiskFields(t *testing.T) {
	projected := hostUnraidFromReadStateView(&unifiedresources.HostUnraidMeta{
		ArrayStarted: true,
		ArrayState:   "STARTED",
		Disks: []unifiedresources.HostUnraidDiskMeta{
			{
				Name:        "disk1",
				Device:      "/dev/sdc",
				Role:        "data",
				Status:      "online",
				RawStatus:   "DISK_OK",
				Model:       "WDC WD60EFRX",
				Serial:      "SERIAL-DATA",
				Filesystem:  "xfs",
				Transport:   "sata",
				SizeBytes:   6_000_000_000_000,
				UsedBytes:   4_000,
				FreeBytes:   2_000,
				Temperature: 31,
				SpunDown:    true,
				ReadCount:   11,
				WriteCount:  12,
				ErrorCount:  16,
				Slot:        1,
			},
		},
	})

	if projected == nil || len(projected.Disks) != 1 {
		t.Fatalf("expected projected Unraid disk metadata, got %+v", projected)
	}
	disk := projected.Disks[0]
	if disk.Model != "WDC WD60EFRX" || disk.Transport != "sata" || disk.SizeBytes != 6_000_000_000_000 {
		t.Fatalf("expected native metadata to survive read-state projection, got %+v", disk)
	}
	if disk.UsedBytes != 4_000 || disk.FreeBytes != 2_000 || disk.Temperature != 31 || !disk.SpunDown {
		t.Fatalf("expected native capacity and state fields to survive projection, got %+v", disk)
	}
	if disk.ReadCount != 11 || disk.WriteCount != 12 || disk.ErrorCount != 16 {
		t.Fatalf("expected native counters to survive projection, got %+v", disk)
	}
}

func TestBroadcastResourceProjectionCoalescesSplitHostIdentities(t *testing.T) {
	data, err := os.ReadFile("monitor.go")
	if err != nil {
		t.Fatalf("failed to read monitor.go: %v", err)
	}
	source := string(data)

	for _, snippet := range []string{
		"metricsTargetResolver := unifiedView.metricsTargets",
		"metricsTargetResolver = broadcastMetricsTargetResolver(unifiedView.readState)",
		"broadcastResources := m.coalesceResourcesForPresentation(unifiedView.readState, unifiedView.resources, unifiedView.staleThresholds)",
		"if coalesced, ok := coalescer.CoalesceForPresentation(resources, staleThresholds); ok {",
		"return unifiedresources.CoalescePresentationHostResourcesWithStaleThresholds(resources, staleThresholds)",
		"broadcastFrontendResources, broadcastCatalogs := convertPresentationResourcesForBroadcast(broadcastResources)",
		"attachBroadcastMetricsTargetsInPlace(broadcastResources, metricsTargetResolver)",
		"frontendState.CapabilityCatalog = broadcastCatalogs.capabilities",
		"frontendState.PolicyCatalog = broadcastCatalogs.policies",
		"frontendState.AISafeSummaryCatalog = broadcastCatalogs.aiSafeSummaries",
		"frontendState.ConnectedInfrastructure = buildConnectedInfrastructure(broadcastResources, snapshot)",
		"func attachBroadcastMetricsTargets(",
		"allResources = unifiedresources.CoalescePresentationHostResources(allResources)",
	} {
		if !strings.Contains(source, snippet) {
			t.Fatalf("monitor.go must contain %q", snippet)
		}
	}
}

func TestMetricsStoreRuntimeOverridesStayOnMonitorBoundary(t *testing.T) {
	data, err := os.ReadFile("monitor.go")
	if err != nil {
		t.Fatalf("failed to read monitor.go: %v", err)
	}
	source := string(data)

	for _, snippet := range []string{
		"metricsStoreConfig := metrics.DefaultConfig(cfg.DataPath)",
		"if strings.TrimSpace(cfg.MetricsDBPath) != \"\" {",
		"metricsStoreConfig.DBPath = cfg.MetricsDBPath",
		"if cfg.MetricsRollupInterval > 0 {",
		"metricsStoreConfig.RollupInterval = cfg.MetricsRollupInterval",
	} {
		if !strings.Contains(source, snippet) {
			t.Fatalf("monitor.go must contain %q", snippet)
		}
	}

	// Non-default tenants use the same scoped loader on startup and import.
	// Check that wiring before New, then exercise the loader's storage boundary
	// rather than requiring its implementation to remain inline in GetMonitor.
	data, err = os.ReadFile("multi_tenant_monitor.go")
	if err != nil {
		t.Fatalf("failed to read multi_tenant_monitor.go: %v", err)
	}
	tenantSource := string(data)
	loadIdx := strings.Index(tenantSource, "if orgID != \"default\" {\n\t\ttenantConfig, err = loadTenantRuntimeConfig(mtm.baseConfig, tenantPersistence)")
	newIdx := strings.Index(tenantSource, "monitor, err = New(tenantConfig)")
	if loadIdx < 0 || newIdx < 0 || loadIdx >= newIdx {
		t.Fatal("multi_tenant_monitor.go must load non-default tenant configuration before New")
	}

	for _, override := range []string{"", filepath.Join(t.TempDir(), "default-metrics.db")} {
		name := "without_override"
		if override != "" {
			name = "with_override"
		}
		t.Run(name, func(t *testing.T) {
			base := &config.Config{
				DataPath: t.TempDir(), ConfigPath: t.TempDir(),
				MetricsDBPath: override, MetricsRollupInterval: 17 * time.Second,
			}
			defaultDataPath, defaultConfigPath := base.DataPath, base.ConfigPath
			for _, orgID := range []string{"org-a", "org-b"} {
				t.Run(orgID, func(t *testing.T) {
					persistence := config.NewConfigPersistence(t.TempDir())
					tenant, err := loadTenantRuntimeConfig(base, persistence)
					if err != nil {
						t.Fatalf("load tenant configuration: %v", err)
					}
					if tenant == base || tenant.DataPath != persistence.GetConfigDir() || tenant.ConfigPath != persistence.GetConfigDir() || tenant.MetricsDBPath != "" {
						t.Fatal("non-default tenant must use its own paths without the process metrics override")
					}
					if tenant.MetricsRollupInterval != base.MetricsRollupInterval {
						t.Fatal("tenant lost the instance-wide metrics rollup interval")
					}
					if base.DataPath != defaultDataPath || base.ConfigPath != defaultConfigPath || base.MetricsDBPath != override {
						t.Fatal("loading tenant configuration changed default-org storage paths")
					}
				})
			}
		})
	}
}

func TestDockerTokenBindingUsesCanonicalHostIdentity(t *testing.T) {
	requiredSnippets := map[string][]string{
		"docker_host_identity.go": {
			"func resolveDockerTokenBindingIdentity(",
			"preferred = dockerHostStableID(previous)",
			"previous.AgentID()",
			"func dockerTokenBindingMatches(",
		},
		"monitor_agents.go": {
			"resolveDockerTokenBindingIdentity(identifier, report, previous, hasPrevious)",
			"dockerTokenBindingMatches(boundAgentID, tokenBindingAliases)",
			"Bound Docker / Podman module token to host identity",
		},
		"monitor.go": {
			"Docker host identity bindings",
		},
	}

	for file, snippets := range requiredSnippets {
		data, err := os.ReadFile(file)
		if err != nil {
			t.Fatalf("failed to read %s: %v", file, err)
		}
		source := string(data)
		for _, snippet := range snippets {
			if !strings.Contains(source, snippet) {
				t.Fatalf("%s must contain %q", file, snippet)
			}
		}
	}
}

func TestDockerMutatingCommandsRespectCanonicalSecurityPosture(t *testing.T) {
	monitor := newTestMonitorForCommands(t)
	host := models.DockerHost{
		ID:       "docker-secure-host",
		Hostname: "docker-secure-host",
		Status:   "online",
		Containers: []models.DockerContainer{
			{
				ID:   "container-a",
				Name: "container-a",
				UpdateStatus: &models.DockerContainerUpdateStatus{
					UpdateAvailable: true,
					LastChecked:     time.Now().UTC(),
				},
			},
		},
		Security: &models.DockerHostSecurity{
			AuthorizationPlugins:          []string{"opa"},
			MutatingCommandsBlocked:       true,
			MutatingCommandsBlockedReason: "blocked for test",
		},
	}
	monitor.state.UpsertDockerHost(host)

	if _, err := monitor.QueueDockerContainerUpdateCommand(host.ID, "container-a", "container-a"); err == nil || !strings.Contains(err.Error(), "blocked for test") {
		t.Fatalf("expected container update to be blocked by canonical security posture, got %v", err)
	}

	if _, err := monitor.QueueDockerUpdateAllCommand(host.ID); err == nil || !strings.Contains(err.Error(), "blocked for test") {
		t.Fatalf("expected update-all to be blocked by canonical security posture, got %v", err)
	}

	status, err := monitor.QueueDockerCheckUpdatesCommand(host.ID)
	if err != nil {
		t.Fatalf("expected check-updates to remain allowed, got %v", err)
	}
	if status.Type != DockerCommandTypeCheckUpdates {
		t.Fatalf("expected check-updates command, got %q", status.Type)
	}
}

func TestGuestDiskObservationContract(t *testing.T) {
	t.Run("legacy-origin-admission", testGuestDiskLegacyObservationAge)
	t.Run("original-source-age", testGuestDiskOriginalObservationAge)
	t.Run("repeated-canonical-polls", testGuestDiskRepeatedPollsAndCanonicalOrigin)
	t.Run("ordinary-deferral-expiry-recovery", testGuestDiskOrdinaryDeferralExpiryAndRecovery)
}

func TestGuestAgentAdmissionEvidenceContract(t *testing.T) {
	t.Run("retained-identity-cannot-renew", testGuestAgentRetainedIdentityCannotRenewAdmission)
	t.Run("original-age", testGuestAgentEvidenceOriginalAge)
	t.Run("canonical-continuity", testGuestAgentEvidenceCanonicalContinuity)
	t.Run("accepted-read-origins", testGuestAgentEvidenceAcceptedReadOrigins)
	t.Run("config-flag-cannot-renew", testGuestAgentConfigFlagCannotRenewAdmission)
}

func TestProxmoxGuestDockerInventoryUsesCanonicalReportIngestPath(t *testing.T) {
	requiredSnippets := map[string][]string{
		"docker_detection.go": {
			"type DockerInventoryCollector interface {",
			"proxmoxGuestDockerSocketMarker",
			"proxmoxGuestDockerNegativeRecheckAfter",
			"dockerCheckerConfiguredAt",
			"checker_reconfigured",
			"func (m *Monitor) CollectProxmoxGuestDockerInventory(ctx context.Context, containers []models.Container) {",
			"m.hasOnlineHostAgentForContainer(ct.ID)",
			"m.ApplyDockerReport(report, nil)",
			"pct exec %d -- sh -c",
			"container docker socket probe failed",
			`docker ps -a --no-trunc --format 'CONTAINER\\t{{json .ID}}`,
			`docker stats --no-stream --no-trunc --format 'STAT\\t{{json .ID}}`,
			"ParseProxmoxGuestDockerInventoryVMIDs",
		},
		"monitor_pve_guest_poll.go": {
			"m.CollectProxmoxGuestDockerInventory(enrichmentCtx, allContainers)",
			"m.publishPVEGuests(ctx, instanceName, allVMs, allContainers)",
		},
		"monitor_polling_containers.go": {
			"m.CollectProxmoxGuestDockerInventory(ctx, allContainers)",
			"return allContainers",
		},
		"monitor_pve.go": {
			"m.publishPVEGuests(ctx, instanceName, vms, containers)",
		},
		"guest_poll_publication.go": {
			"func (m *Monitor) publishPVEGuests(",
			"m.state.UpdateGuestsForInstance(instance, vms, containers)",
		},
	}

	for file, snippets := range requiredSnippets {
		data, err := os.ReadFile(file)
		if err != nil {
			t.Fatalf("failed to read %s: %v", file, err)
		}
		source := string(data)
		for _, snippet := range snippets {
			if !strings.Contains(source, snippet) {
				t.Fatalf("%s must contain %q", file, snippet)
			}
		}
		if file == "docker_detection.go" && strings.Contains(source, "&& echo yes || echo no") {
			t.Fatalf("%s must not mask host-side pct exec failures with a host-shell echo fallback", file)
		}
	}
}

func TestProxmoxGuestDockerDetectionRechecksNegativeCacheAfterCheckerSetup(t *testing.T) {
	configuredAt := time.Now()
	monitor := &Monitor{}
	container := models.Container{
		ID:     "pve-a:node-a:101",
		VMID:   101,
		Name:   "docker-lxc",
		Node:   "node-a",
		Status: "running",
		Uptime: 7200,
	}

	reason := monitor.containerNeedsDockerCheck(container, map[string]models.Container{
		container.ID: {
			ID:              container.ID,
			Status:          "running",
			Uptime:          3600,
			HasDocker:       false,
			DockerCheckedAt: configuredAt.Add(-time.Minute),
		},
	}, configuredAt)
	if reason != "checker_reconfigured" {
		t.Fatalf("reason = %q, want checker_reconfigured", reason)
	}

	reason = monitor.containerNeedsDockerCheck(container, map[string]models.Container{
		container.ID: {
			ID:              container.ID,
			Status:          "running",
			Uptime:          3600,
			HasDocker:       false,
			DockerCheckedAt: configuredAt.Add(time.Minute),
		},
	}, configuredAt)
	if reason != "" {
		t.Fatalf("fresh negative cache reason = %q, want empty", reason)
	}
}

func TestProxmoxGuestDockerLXCProbingRequiresExplicitOptIn(t *testing.T) {
	requiredSnippets := map[string][]string{
		"../config/config.go": {
			"EnableProxmoxGuestDockerDetection bool",
			`envconfig:"PULSE_ENABLE_PROXMOX_GUEST_DOCKER_DETECTION" default:"false"`,
			"EnableProxmoxGuestDockerInventory bool",
			`envconfig:"PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY" default:"false"`,
		},
		"../api/router.go": {
			"inventoryEnabled := r.config != nil && r.config.EnableProxmoxGuestDockerInventory",
			"detectionEnabled := r.config != nil && (r.config.EnableProxmoxGuestDockerDetection || inventoryEnabled)",
			"m.SetDockerChecker(nil)",
			"m.SetDockerInventoryCollector(nil)",
			"if inventoryEnabled {",
		},
		// The runtime Settings toggle is the same explicit opt-in, admin-gated
		// through the system settings endpoint; the environment variable stays
		// authoritative and locks the toggle out of the API when set.
		"../api/system_settings.go": {
			`rawRequest["enableProxmoxGuestDockerInventory"]`,
			`h.config.EnvOverrides["PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY"]`,
			"guestDockerInventoryToggleFunc",
		},
		"../config/persistence.go": {
			"EnableProxmoxGuestDockerInventory bool `json:\"enableProxmoxGuestDockerInventory\"`",
		},
		"../../docs/UNIFIED_AGENT.md": {
			"Pulse does not use a Proxmox node agent to look inside LXCs by default.",
			"`PULSE_ENABLE_PROXMOX_GUEST_DOCKER_DETECTION=true`",
			"`PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY=true`",
		},
	}

	for file, snippets := range requiredSnippets {
		data, err := os.ReadFile(file)
		if err != nil {
			t.Fatalf("failed to read %s: %v", file, err)
		}
		source := string(data)
		for _, snippet := range snippets {
			if !strings.Contains(source, snippet) {
				t.Fatalf("%s must contain %q", file, snippet)
			}
		}
	}
}

func TestBackupOrphanDetectionUsesCanonicalInventoryReadinessScope(t *testing.T) {
	// Inventory-readiness scope still owns orphan detection. The old spelling
	// check also required an unbounded PBS alert read; exercise its actual
	// expiry/ordinary-recovery behaviour instead of preserving that choice.
	exercisePBSBudgetExpiredAlertEvaluation(t)
}

func TestMonitoringRuntimeAvoidsLegacyMockPartialHelpers(t *testing.T) {
	forbiddenSnippets := []string{
		"mock.GetMockState(",
		"mock.GetPlatformFixtures(",
		"mock.GetMockRecoveryPoints(",
	}

	for name, content := range readMonitoringRuntimeFiles(t) {
		for _, snippet := range forbiddenSnippets {
			if strings.Contains(content, snippet) {
				t.Fatalf("%s must not depend on legacy mock partial helper %q", name, snippet)
			}
		}
	}
}

func TestMockOwnedUnifiedMetricSyncDefersToCanonicalSamplerInMockMode(t *testing.T) {
	previous := mock.IsMockEnabled()
	mustSetMockEnabled(t, true)
	t.Cleanup(func() { mustSetMockEnabled(t, previous) })

	if !shouldSkipMockOwnedUnifiedMetricSync(unifiedresources.Resource{
		Sources: []unifiedresources.DataSource{unifiedresources.SourceTrueNAS},
	}) {
		t.Fatal("expected TrueNAS mock-owned resources to skip generic unified metric sync")
	}
	if !shouldSkipMockOwnedUnifiedMetricSync(unifiedresources.Resource{
		Sources: []unifiedresources.DataSource{unifiedresources.SourceVMware},
	}) {
		t.Fatal("expected VMware mock-owned resources to skip generic unified metric sync")
	}
	if !shouldSkipMockOwnedUnifiedMetricSync(unifiedresources.Resource{
		Sources: []unifiedresources.DataSource{unifiedresources.SourceDocker},
	}) {
		t.Fatal("expected all mock-owned resources to defer to the canonical mock sampler")
	}

	mustSetMockEnabled(t, false)
	if shouldSkipMockOwnedUnifiedMetricSync(unifiedresources.Resource{
		Sources: []unifiedresources.DataSource{unifiedresources.SourceDocker},
	}) {
		t.Fatal("expected unified metric sync to remain available outside mock mode")
	}
}

func TestMonitoringBroadcastCarriesCanonicalSourceAndStoragePlatformIdentity(t *testing.T) {
	input := monitorResourceToConvertInput(unifiedresources.Resource{
		ID:      "storage-tower-array",
		Type:    unifiedresources.ResourceTypeStorage,
		Name:    "Tower Array",
		Status:  unifiedresources.StatusWarning,
		Sources: []unifiedresources.DataSource{unifiedresources.SourceAgent},
		Storage: &unifiedresources.StorageMeta{
			Type:     "unraid-array",
			Platform: "unraid",
			Topology: "array",
			Enabled:  true,
			Active:   true,
		},
	})

	if input.PlatformType != "agent" {
		t.Fatalf("PlatformType = %q, want agent for Unraid agent-backed storage", input.PlatformType)
	}
	if input.SourceType != "agent" {
		t.Fatalf("SourceType = %q, want agent", input.SourceType)
	}
	if len(input.Sources) != 1 || input.Sources[0] != string(unifiedresources.SourceAgent) {
		t.Fatalf("Sources = %#v, want [agent]", input.Sources)
	}

	payload := string(input.PlatformData)
	for _, snippet := range []string{
		`"platform":"unraid"`,
		`"type":"unraid-array"`,
		`"sources":["agent"]`,
	} {
		if !strings.Contains(payload, snippet) {
			t.Fatalf("PlatformData must contain %s, got %s", snippet, payload)
		}
	}
}

// TestMonitoringBroadcastDualSourceProxmoxAgentNodeKeepsProxmoxPlatformIdentity
// pins the Pi case: a Proxmox VE node with a linked Pulse host agent must
// resolve to platformType="proxmox-pve" and surface both sources in
// platformData. Regression guard for any future change that lets the agent
// facet override the Proxmox identity.
func TestMonitoringBroadcastDualSourceProxmoxAgentNodeKeepsProxmoxPlatformIdentity(t *testing.T) {
	input := monitorResourceToConvertInput(unifiedresources.Resource{
		ID:      "agent-pi-host",
		Type:    unifiedresources.ResourceTypeAgent,
		Name:    "pi",
		Status:  unifiedresources.StatusOnline,
		Sources: []unifiedresources.DataSource{unifiedresources.SourceProxmox, unifiedresources.SourceAgent},
		Proxmox: &unifiedresources.ProxmoxData{
			NodeName:   "pi",
			Instance:   "pi",
			PVEVersion: "8.3.1",
		},
		Agent: &unifiedresources.AgentData{
			AgentID:  "agent-pi",
			Hostname: "pi",
			OSName:   "Proxmox VE",
		},
	})

	if input.PlatformType != "proxmox-pve" {
		t.Fatalf("PlatformType = %q, want proxmox-pve for Proxmox node linked to host agent", input.PlatformType)
	}
	if input.SourceType != "hybrid" {
		t.Fatalf("SourceType = %q, want hybrid", input.SourceType)
	}
	wantSources := []string{"proxmox", "agent"}
	if len(input.Sources) != len(wantSources) {
		t.Fatalf("Sources = %#v, want %#v", input.Sources, wantSources)
	}
	for i, want := range wantSources {
		if input.Sources[i] != want {
			t.Fatalf("Sources[%d] = %q, want %q (full = %#v)", i, input.Sources[i], want, input.Sources)
		}
	}

	payload := string(input.PlatformData)
	for _, snippet := range []string{
		`"pveVersion":"8.3.1"`,
		`"sources":["proxmox","agent"]`,
	} {
		if !strings.Contains(payload, snippet) {
			t.Fatalf("PlatformData must contain %s, got %s", snippet, payload)
		}
	}
}

// TestMonitoringBroadcastDualSourceTrueNASAgentKeepsTrueNASPlatformIdentity
// pins the TrueNAS appliance + linked host agent case to platformType="truenas"
// so a future code path cannot quietly demote the appliance identity to
// "agent" once the agent facet is also populated.
func TestMonitoringBroadcastDualSourceTrueNASAgentKeepsTrueNASPlatformIdentity(t *testing.T) {
	input := monitorResourceToConvertInput(unifiedresources.Resource{
		ID:      "agent-truenas-host",
		Type:    unifiedresources.ResourceTypeAgent,
		Name:    "truenas-1",
		Status:  unifiedresources.StatusOnline,
		Sources: []unifiedresources.DataSource{unifiedresources.SourceTrueNAS, unifiedresources.SourceAgent},
		TrueNAS: &unifiedresources.TrueNASData{
			Hostname: "truenas-1",
			Version:  "TrueNAS-SCALE-24.10.0",
		},
		Agent: &unifiedresources.AgentData{
			AgentID:  "agent-truenas",
			Hostname: "truenas-1",
			OSName:   "TrueNAS SCALE",
		},
	})

	if input.PlatformType != "truenas" {
		t.Fatalf("PlatformType = %q, want truenas for TrueNAS appliance linked to host agent", input.PlatformType)
	}
	if input.SourceType != "hybrid" {
		t.Fatalf("SourceType = %q, want hybrid", input.SourceType)
	}
	wantSources := []string{"truenas", "agent"}
	if len(input.Sources) != len(wantSources) {
		t.Fatalf("Sources = %#v, want %#v", input.Sources, wantSources)
	}
	for i, want := range wantSources {
		if input.Sources[i] != want {
			t.Fatalf("Sources[%d] = %q, want %q (full = %#v)", i, input.Sources[i], want, input.Sources)
		}
	}

	payload := string(input.PlatformData)
	if !strings.Contains(payload, `"sources":["truenas","agent"]`) {
		t.Fatalf("PlatformData must contain hybrid source list, got %s", payload)
	}
}

// TestMonitoringBroadcastUnraidAgentHostKeepsAgentPlatformType pins the Tower
// case: an Unraid host whose only data source is the Pulse agent stays on
// platformType="agent". The frontend resolves the "Unraid" identity badge via
// host profile / OSName; the contract platformType must not promote OSName
// strings to platform identifiers.
func TestMonitoringBroadcastUnraidAgentHostKeepsAgentPlatformType(t *testing.T) {
	input := monitorResourceToConvertInput(unifiedresources.Resource{
		ID:      "agent-tower-host",
		Type:    unifiedresources.ResourceTypeAgent,
		Name:    "tower",
		Status:  unifiedresources.StatusOnline,
		Sources: []unifiedresources.DataSource{unifiedresources.SourceAgent},
		Agent: &unifiedresources.AgentData{
			AgentID:  "agent-tower",
			Hostname: "tower",
			OSName:   "Unraid OS 7.2.2",
		},
	})

	if input.PlatformType != "agent" {
		t.Fatalf("PlatformType = %q, want agent for single-source Unraid host agent", input.PlatformType)
	}
	if input.SourceType != "agent" {
		t.Fatalf("SourceType = %q, want agent", input.SourceType)
	}
	if len(input.Sources) != 1 || input.Sources[0] != "agent" {
		t.Fatalf("Sources = %#v, want [agent]", input.Sources)
	}

	payload := string(input.PlatformData)
	for _, snippet := range []string{
		`"osName":"Unraid OS 7.2.2"`,
		`"sources":["agent"]`,
	} {
		if !strings.Contains(payload, snippet) {
			t.Fatalf("PlatformData must contain %s, got %s", snippet, payload)
		}
	}
}

func TestMonitorSetMockModeAuthorizesBeforeResettingRuntimeState(t *testing.T) {
	data, err := os.ReadFile("monitor.go")
	if err != nil {
		t.Fatalf("failed to read monitor.go: %v", err)
	}
	source := strings.Join(strings.Fields(string(data)), " ")
	authorize := strings.Index(source, "if err := mock.SetEnabled(enable); err != nil { return err }")
	reset := strings.Index(source, "monitor.endMockModeEpoch(enable)")
	if authorize < 0 || reset < 0 || authorize > reset {
		t.Fatal("SetMockMode must return the mock.SetEnabled error before it ends any monitor's epoch or resets its state")
	}
}

func TestMonitorAlertTimelineWritesCanonicalAlertMetadata(t *testing.T) {
	data, err := os.ReadFile("monitor_alerts.go")
	if err != nil {
		t.Fatalf("failed to read monitor_alerts.go: %v", err)
	}
	source := string(data)
	requiredSnippets := []string{
		"change := unifiedresources.BuildAlertTimelineChange(",
		"AlertMetadata:   alert.Metadata,",
	}
	for _, snippet := range requiredSnippets {
		if !strings.Contains(source, snippet) {
			t.Fatalf("monitor_alerts.go must contain %q", snippet)
		}
	}
}

func TestLegacyMemorySourceAliasesRemainCanonicalized(t *testing.T) {
	t.Parallel()

	tests := []struct {
		source    string
		canonical string
	}{
		{source: "avail-field", canonical: "available-field"},
		{source: "meminfo-available", canonical: "available-field"},
		{source: "guest-agent-meminfo", canonical: "guest-agent-meminfo"},
		{source: "node-status-available", canonical: "available-field"},
		{source: "meminfo-derived", canonical: "derived-free-buffers-cached"},
		{source: "calculated", canonical: "derived-free-buffers-cached"},
		{source: "meminfo-total-minus-used", canonical: "derived-total-minus-used"},
		{source: "rrd-available", canonical: "rrd-memavailable"},
		{source: "rrd-data", canonical: "rrd-memused"},
		{source: "listing-mem", canonical: "cluster-resources"},
		{source: "listing", canonical: "cluster-resources"},
	}

	for _, tt := range tests {
		tt := tt
		t.Run(tt.source, func(t *testing.T) {
			t.Parallel()
			if got := CanonicalMemorySource(tt.source); got != tt.canonical {
				t.Fatalf("CanonicalMemorySource(%q) = %q, want %q", tt.source, got, tt.canonical)
			}
		})
	}
}

func TestDockerReportPreservesMetadataAcrossObservedContainerRecreation(t *testing.T) {
	migrationData, err := os.ReadFile("docker_metadata_migration.go")
	if err != nil {
		t.Fatalf("failed to read docker_metadata_migration.go: %v", err)
	}
	migrationSource := string(migrationData)
	requiredMigrationSnippets := []string{
		"func (m *Monitor) migrateDockerContainerMetadataForRecreatedContainers(",
		"normalizeDockerContainerMetadataIdentity(container.Name)",
		`strings.TrimLeft(strings.TrimSpace(name), "/")`,
		"m.CopyDockerContainerMetadata(hostID, previousContainer.ID, container.ID)",
	}
	for _, snippet := range requiredMigrationSnippets {
		if !strings.Contains(migrationSource, snippet) {
			t.Fatalf("docker_metadata_migration.go must contain %q", snippet)
		}
	}

	agentsData, err := os.ReadFile("monitor_agents.go")
	if err != nil {
		t.Fatalf("failed to read monitor_agents.go: %v", err)
	}
	agentsSource := string(agentsData)
	requiredAgentsSnippet := "m.migrateDockerContainerMetadataForRecreatedContainers(identifier, previous.Containers(), host.Containers)"
	if !strings.Contains(agentsSource, requiredAgentsSnippet) {
		t.Fatalf("monitor_agents.go must contain %q", requiredAgentsSnippet)
	}
}

func TestMockUnifiedStateViewUsesCanonicalMockFixtureGraph(t *testing.T) {
	data, err := os.ReadFile("monitor.go")
	if err != nil {
		t.Fatalf("failed to read monitor.go: %v", err)
	}
	source := string(data)
	requiredSnippets := []string{
		"version := mock.FixtureDataVersion()",
		"m.mockUnifiedViewValid && m.mockUnifiedViewVersion == version",
		"resources, freshness := mock.UnifiedResourceSnapshotWithLinks(links)",
		"view := monitorUnifiedStateViewFromResources(resources, freshness)",
		"m.mockUnifiedView = view",
		"m.mockUnifiedViewVersion = version",
		"return view",
	}
	for _, snippet := range requiredSnippets {
		if !strings.Contains(source, snippet) {
			t.Fatalf("monitor.go must contain %q", snippet)
		}
	}
}

func TestProxmoxDiskAlertsRunOnMergedDiskState(t *testing.T) {
	cases := []struct {
		file     string
		snippets []string
	}{
		{
			file: "monitor.go",
			snippets: []string{
				"func mergeHostAgentSMARTIntoDisks(disks []models.PhysicalDisk, nodes []models.Node, hosts []models.Host, splits diskAgentSplitStore) []models.PhysicalDisk {",
				"deriveWearoutFromSMARTAttributes(matched.Attributes)",
				"storagehealth.RemainingLifeFromPercentageUsed(*attrs.PercentageUsed)",
				"shouldUseHostAgentPhysicalDiskHealth(updated[i].Health, matched.Health)",
				`if incoming == "FAILED"`,
			},
		},
		{
			file: "monitor_pve.go",
			snippets: []string{
				"allDisks = mergeHostAgentSMARTIntoDisks(allDisks, nodesFromState, hosts, splits)",
				"m.checkPhysicalDiskAlerts(inst, disk, diskExcludeByNode[disk.Node])",
				"m.alertManager.CheckDiskHealth(instance, disk.Node, proxmoxDiskFromPhysicalDisk(disk))",
				"func proxmoxDiskFromPhysicalDisk(disk models.PhysicalDisk) proxmox.Disk {",
			},
		},
	}

	for _, tc := range cases {
		data, err := os.ReadFile(tc.file)
		if err != nil {
			t.Fatalf("failed to read %s: %v", tc.file, err)
		}
		source := string(data)
		for _, snippet := range tc.snippets {
			if !strings.Contains(source, snippet) {
				t.Fatalf("%s must contain %q", tc.file, snippet)
			}
		}
	}
}

func TestHostAgentRemovalGuardUsesResolvedIdentifier(t *testing.T) {
	data, err := os.ReadFile("monitor_agents.go")
	if err != nil {
		t.Fatalf("failed to read monitor_agents.go: %v", err)
	}
	source := string(data)
	requiredSnippets := []string{
		"blocked, wasRemoved := m.lookupRemovedHostAgent(identifier, hostname, report.Host.MachineID, tokenID)",
		"removedHostAgentAllowsFreshReenroll(blocked, identifier, report, tokenRecord)",
		"func removedHostAgentMatchesReport(entry models.RemovedHostAgent, identifier, hostname, machineID, tokenID string) bool {",
		"entryTokenID == \"\" || tokenID == \"\" || entryTokenID != tokenID",
		`Str("hostID", identifier)`,
		`fmt.Errorf("host agent %q had monitoring stopped at %v and cannot report again.`,
	}
	for _, snippet := range requiredSnippets {
		if !strings.Contains(source, snippet) {
			t.Fatalf("monitor_agents.go must contain %q", snippet)
		}
	}
	if strings.Contains(source, "m.lookupRemovedHostAgent(baseIdentifier, hostname)") {
		t.Fatal("monitor_agents.go must not check removed host-agent state against pre-resolution baseIdentifier")
	}
	if strings.Contains(source, "if hostAgentHostnamesMatch(entry.Hostname, hostname) {") {
		t.Fatal("monitor_agents.go must not block host-agent re-enroll solely by removed hostname")
	}
}

func TestAlertLifecycleCanonicalChangesRemainWritable(t *testing.T) {
	store := unifiedresources.NewMemoryStore()
	incidentStore := memory.NewIncidentStore(memory.IncidentStoreConfig{})
	monitor := &Monitor{
		incidentStore: incidentStore,
	}
	monitor.SetResourceStore(unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(store)))

	startedAt := time.Now().UTC().Add(-1 * time.Hour)
	alert := &alerts.Alert{
		ID:         "alert-guardrail-1",
		Type:       "cpu",
		Level:      alerts.AlertLevelCritical,
		ResourceID: "vm-guardrail",
		Message:    "CPU threshold exceeded",
		StartTime:  startedAt,
	}

	monitor.handleAlertLifecycleEvent(alerts.LifecycleEvent{
		Type:       eventlog.TypeFired,
		OccurredAt: startedAt,
		Alert:      alert,
	})

	changes, err := store.GetRecentChanges("vm-guardrail", time.Time{}, 10)
	if err != nil {
		t.Fatalf("GetRecentChanges: %v", err)
	}
	if len(changes) != 1 {
		t.Fatalf("expected 1 canonical alert change, got %d", len(changes))
	}
	if changes[0].Kind != unifiedresources.ChangeAlertFired {
		t.Fatalf("Kind = %q, want %q", changes[0].Kind, unifiedresources.ChangeAlertFired)
	}

	timeline := incidentStore.GetTimelineByAlertIdentifier(alert.ID)
	if timeline == nil {
		t.Fatal("expected incident timeline")
	}
	if len(timeline.Events) != 1 || timeline.Events[0].Type != memory.IncidentEventAlertFired {
		t.Fatalf("expected projected alert-fired event, got %#v", timeline.Events)
	}
}

func TestSupplementalProviderChangesRefreshCanonicalReadState(t *testing.T) {
	now := time.Now().UTC()
	state := models.NewState()
	state.UpsertHost(models.Host{
		ID:       "host-1",
		Hostname: "seed-host",
		Status:   "online",
		LastSeen: now,
	})

	store := unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(nil))
	monitor := &Monitor{state: state}
	monitor.SetResourceStore(store)
	monitor.SetSupplementalRecordsProvider(unifiedresources.SourceVMware, guardrailSupplementalProvider{
		records: []unifiedresources.IngestRecord{
			{
				SourceID: "vmware:esxi-01",
				Resource: unifiedresources.Resource{
					Type:      unifiedresources.ResourceTypeAgent,
					Name:      "esxi-01.lab.local",
					Status:    unifiedresources.StatusOnline,
					LastSeen:  now,
					UpdatedAt: now,
				},
				Identity: unifiedresources.ResourceIdentity{
					Hostnames: []string{"esxi-01.lab.local"},
				},
			},
		},
	})

	resources := store.GetAll()
	for _, resource := range resources {
		for _, source := range resource.Sources {
			if source == unifiedresources.SourceVMware {
				return
			}
		}
	}
	t.Fatalf("expected resource store refresh to surface vmware supplemental records, got %#v", resources)
}

func TestTelemetrySnapshotAggregationUsesProvisionedTenantSet(t *testing.T) {
	baseDir := t.TempDir()
	persistence := config.NewMultiTenantPersistence(baseDir)
	for _, orgID := range []string{"default", "org-a"} {
		if _, err := persistence.GetPersistence(orgID); err != nil {
			t.Fatalf("GetPersistence(%s): %v", orgID, err)
		}
	}

	rm, err := NewReloadableMonitor(&config.Config{DataPath: baseDir}, persistence, nil)
	if err != nil {
		t.Fatalf("NewReloadableMonitor: %v", err)
	}

	mtm := rm.GetMultiTenantMonitor()
	if mtm == nil {
		t.Fatal("expected multi-tenant monitor")
	}
	mtm.monitors["default"] = testTelemetryMonitor(
		nil,
		[]models.VM{{ID: "vm-default", VMID: 101, Name: "vm-default", Instance: "pve-default"}},
		nil,
		nil,
		nil,
		nil,
		nil,
		1,
	)
	mtm.monitors["org-a"] = testTelemetryMonitor(
		nil,
		[]models.VM{{ID: "vm-a", VMID: 201, Name: "vm-a", Instance: "pve-a"}},
		nil,
		nil,
		nil,
		nil,
		nil,
		2,
	)

	counts := rm.AggregateInstallSnapshotCounts()
	if counts.VMs != 2 {
		t.Fatalf("VMs = %d, want 2 across provisioned tenants", counts.VMs)
	}
	if counts.ActiveAlerts != 3 {
		t.Fatalf("ActiveAlerts = %d, want 3 across provisioned tenants", counts.ActiveAlerts)
	}
}

func TestUnifiedStorageMetricsFallbackToResourceIDWhenResolverTargetMissing(t *testing.T) {
	data, err := os.ReadFile("monitor.go")
	if err != nil {
		t.Fatalf("failed to read monitor.go: %v", err)
	}
	source := string(data)
	for _, snippet := range []string{
		"target := resolver.MetricsTargetForResource(resource.ID)",
		"if target != nil && target.ResourceType == \"storage\" && strings.TrimSpace(target.ResourceID) != \"\" {",
		"targetID = strings.TrimSpace(target.ResourceID)",
		"} else {\n\t\t\ttargetID = resource.ID\n\t\t}",
	} {
		if !strings.Contains(source, snippet) {
			t.Fatalf("monitor.go must contain %q", snippet)
		}
	}
}

// TestPollersHonorDisabledInstanceFlag asserts that the PVE, PBS, and PMG
// pollers skip instances whose `Disabled` flag is set, both at client
// initialization/reconnect time and on every per-instance iteration of the
// poll loop. The unified connections ledger surfaces `Disabled` as a
// `paused` state, so the monitoring runtime must not drive API calls or
// mark a disabled instance reachable; that behavior is what keeps the
// ledger's pause semantics honest across restarts.
func TestPollersHonorDisabledInstanceFlag(t *testing.T) {
	expectations := map[string][]string{
		"monitor_client_init.go": {
			"if pve.Disabled {",
			"if pbsInst.Disabled {",
			"if pmgInst.Disabled {",
		},
		"monitor_client_reconnect.go": {
			"if pve.Disabled {",
			"if pbsInst.Disabled {",
		},
		"monitor_pve.go": {
			"if instanceCfg.Disabled {",
		},
		"monitor_pbs_pmg.go": {
			"if instanceCfg.Disabled {",
		},
	}

	for file, snippets := range expectations {
		data, err := os.ReadFile(file)
		if err != nil {
			t.Fatalf("failed to read %s: %v", file, err)
		}
		source := string(data)
		for _, snippet := range snippets {
			if !strings.Contains(source, snippet) {
				t.Fatalf("%s must contain %q so disabled instances stay off the monitoring hot path", file, snippet)
			}
		}
	}
}

// TestMonitorUptimeFallsBackToCanonicalResourceUptime locks the contract
// that the websocket broadcast converter must surface canonical
// Resource.Uptime when no platform-specific carve-out is populated. The
// vSphere adapter writes uptime onto Resource.Uptime only (no
// vmware-specific UptimeSeconds), so without this fallback WS broadcasts
// would silently drop uptime for VMware-backed rows even though the
// canonical REST `/api/resources` payload exposes it.
func TestMonitorUptimeFallsBackToCanonicalResourceUptime(t *testing.T) {
	t.Run("falls through to Resource.Uptime when no source carve-out is set", func(t *testing.T) {
		resource := unifiedresources.Resource{Uptime: 123456}
		got := monitorUptime(&resource)
		if got == nil || *got != 123456 {
			t.Fatalf("monitorUptime() = %v, want 123456 from canonical Resource.Uptime", got)
		}
	})

	t.Run("agent / proxmox / docker / k8s carve-outs keep precedence", func(t *testing.T) {
		resource := unifiedresources.Resource{
			Uptime: 999999,
			Agent:  &unifiedresources.AgentData{UptimeSeconds: 100},
		}
		got := monitorUptime(&resource)
		if got == nil || *got != 100 {
			t.Fatalf("monitorUptime() = %v, want 100 from agent (precedence over canonical Uptime)", got)
		}

		resource.Agent = nil
		resource.Proxmox = &unifiedresources.ProxmoxData{Uptime: 200}
		got = monitorUptime(&resource)
		if got == nil || *got != 200 {
			t.Fatalf("monitorUptime() = %v, want 200 from proxmox (precedence over canonical Uptime)", got)
		}
	})

	t.Run("returns nil when nothing populates", func(t *testing.T) {
		if got := monitorUptime(&unifiedresources.Resource{}); got != nil {
			t.Fatalf("monitorUptime() = %v, want nil when all sources empty", got)
		}
	})
}

// Tenant monitors must stamp their org's identity into notification webhook
// payloads via an org-backed resolver, so PSA/ticket-bridge receivers get
// tenant routing identity from the payload boundary and display-name renames
// propagate without a monitor restart.
func TestTenantMonitorWiresOrgIdentityIntoNotifications(t *testing.T) {
	mtp, _ := newTestTenantPersistence(t)
	baseCfg := &config.Config{DataPath: t.TempDir()}
	mtm := NewMultiTenantMonitor(baseCfg, mtp, nil)
	t.Cleanup(mtm.Stop)

	if err := mtp.SaveOrganization(&models.Organization{
		ID:          "org-acme",
		DisplayName: "Acme Corp",
	}); err != nil {
		t.Fatalf("SaveOrganization(org-acme) error = %v", err)
	}

	monitor, err := mtm.GetMonitor("org-acme")
	if err != nil {
		t.Fatalf("GetMonitor(org-acme) error = %v", err)
	}

	nm := monitor.GetNotificationManager()
	if nm == nil {
		t.Fatal("expected tenant monitor to have a notification manager")
	}

	tenantID, tenantName := nm.TenantIdentity()
	if tenantID != "org-acme" {
		t.Fatalf("TenantIdentity() id = %q, want %q", tenantID, "org-acme")
	}
	if tenantName != "Acme Corp" {
		t.Fatalf("TenantIdentity() name = %q, want %q", tenantName, "Acme Corp")
	}

	// Display-name renames must propagate lazily without monitor restarts.
	if err := mtp.SaveOrganization(&models.Organization{
		ID:          "org-acme",
		DisplayName: "Acme Corp Renamed",
	}); err != nil {
		t.Fatalf("SaveOrganization(rename) error = %v", err)
	}
	if _, tenantName = nm.TenantIdentity(); tenantName != "Acme Corp Renamed" {
		t.Fatalf("TenantIdentity() name after rename = %q, want %q", tenantName, "Acme Corp Renamed")
	}
}

func TestDefaultOrgMonitorSharesCanonicalRuntimeTokenInventory(t *testing.T) {
	dataDir := t.TempDir()
	baseCfg := &config.Config{DataPath: dataDir, ConfigPath: dataDir}
	mtm := NewMultiTenantMonitor(baseCfg, config.NewMultiTenantPersistence(dataDir), nil)
	t.Cleanup(mtm.Stop)

	monitor, err := mtm.GetMonitor("default")
	if err != nil {
		t.Fatalf("GetMonitor(default) error = %v", err)
	}
	if monitor.GetConfig() != baseCfg {
		t.Fatal("default monitor must retain the canonical server config pointer")
	}

	now := time.Now().UTC()
	config.Mu.Lock()
	baseCfg.APITokens = []config.APITokenRecord{{
		ID:        "fresh-agent-token",
		Name:      "Fresh agent token",
		CreatedAt: now,
		Scopes:    []string{config.ScopeAgentExec},
	}}
	config.Mu.Unlock()
	// GetMonitor starts polling concurrently; host fixtures must use the
	// state-owned lock, not monitor.mu, to synchronise with snapshots.
	monitor.state.UpsertHost(models.Host{
		ID:              "agent-fresh-token",
		Hostname:        "fresh-token-host",
		Status:          "online",
		LastSeen:        now,
		AgentVersion:    "6.2.2",
		TokenID:         "fresh-agent-token",
		CommandsEnabled: true,
	})

	diagnostics := monitor.GetAgentFleetDiagnostics("6.2.2", now)
	agent := requireAgentDiagnostic(t, diagnostics, "agent-agent-fresh-token")
	if diagnosticHasAnyReason(agent.Reasons, AgentFleetReasonCredentialMissing, AgentFleetReasonExecScopeMissing) {
		t.Fatalf("fresh canonical token was diagnosed as unavailable: %+v", agent.Reasons)
	}
}

// Instance-wide notification settings (webhook security allowlist, public
// URL) propagate through ForEachMonitor; it must visit every live tenant
// monitor so no org's manager is left observing stale security settings.
func TestForEachMonitorVisitsAllTenantMonitors(t *testing.T) {
	mtm := &MultiTenantMonitor{
		monitors: map[string]*Monitor{
			"default": {},
			"org-a":   {},
			"org-b":   {},
			"nil-org": nil,
		},
	}

	visited := 0
	mtm.ForEachMonitor(func(m *Monitor) {
		if m == nil {
			t.Fatal("ForEachMonitor must skip nil monitors")
		}
		visited++
	})
	if visited != 3 {
		t.Fatalf("ForEachMonitor visited %d monitors, want 3", visited)
	}

	// Nil receiver and nil callback are safe no-ops.
	var nilMTM *MultiTenantMonitor
	nilMTM.ForEachMonitor(func(*Monitor) { t.Fatal("nil receiver must not invoke callback") })
	mtm.ForEachMonitor(nil)
}

func TestAgentFleetDoctorStaysReadOnlyProjection(t *testing.T) {
	source, err := os.ReadFile("agent_fleet_doctor.go")
	if err != nil {
		t.Fatalf("read agent_fleet_doctor.go: %v", err)
	}
	src := string(source)
	for _, required := range []string{
		"GetAgentFleetDiagnostics",
		"buildAgentFleetSubjects(state)",
		"agentFleetProfileState()",
		"LoadProfileDeploymentStatus()",
	} {
		if !strings.Contains(src, required) {
			t.Fatalf("agent fleet doctor must keep read-only projection primitive %q", required)
		}
	}
	for _, forbidden := range []string{
		"SaveAgentProfiles(",
		"SaveAgentProfileAssignments(",
		"SaveProfileDeploymentStatus(",
		"UpdateHostAgentConfig(",
		"HandleCommandAck",
		"Execute",
	} {
		if strings.Contains(src, forbidden) {
			t.Fatalf("agent fleet doctor must stay read-only; found forbidden mutation/execution primitive %q", forbidden)
		}
	}
}

func TestStateBroadcastSignalsUseLazyCurrentState(t *testing.T) {
	monitorSourceBytes, err := os.ReadFile("monitor.go")
	if err != nil {
		t.Fatalf("read monitor.go: %v", err)
	}
	monitorSource := string(monitorSourceBytes)
	for _, required := range []string{
		"m.broadcastCurrentState(wsHub)",
		"m.broadcastCurrentState(hub)",
		"hub.BroadcastCurrentStateToTenant(orgID)",
		"hub.BroadcastCurrentState()",
	} {
		if !strings.Contains(monitorSource, required) {
			t.Fatalf("monitor.go must contain lazy state broadcast primitive %q", required)
		}
	}
	for _, forbidden := range []string{
		"m.buildBroadcastFrontendStateFromSnapshot(state)\n\t\t\tm.broadcastState(wsHub",
		"frontendState := m.buildBroadcastFrontendStateFromSnapshot(m.GetState())",
	} {
		if strings.Contains(monitorSource, forbidden) {
			t.Fatalf("monitor.go must not build full frontend state at high-frequency broadcast callsite %q", forbidden)
		}
	}

	alertSourceBytes, err := os.ReadFile("monitor_alerts.go")
	if err != nil {
		t.Fatalf("read monitor_alerts.go: %v", err)
	}
	alertSource := string(alertSourceBytes)
	if !strings.Contains(alertSource, "m.broadcastCurrentState(hub)") {
		t.Fatal("monitor_alerts.go must signal lazy current-state broadcasts")
	}
	if strings.Contains(alertSource, "m.BuildBroadcastFrontendState()") {
		t.Fatal("monitor_alerts.go must not build full frontend state for alert-driven broadcast signals")
	}
}

func TestResourceStaleThresholdsFollowPollingCadence(t *testing.T) {
	thresholds := ResourceStaleThresholdsForConfig(&config.Config{
		PVEPollingInterval: 5 * time.Minute,
		PBSPollingInterval: 45 * time.Second,
		PMGPollingInterval: 3 * time.Minute,
	})

	if got := thresholds[unifiedresources.SourceProxmox]; got != 10*time.Minute {
		t.Fatalf("Proxmox threshold = %v, want %v", got, 10*time.Minute)
	}
	if got := thresholds[unifiedresources.SourcePBS]; got != 120*time.Second {
		t.Fatalf("PBS threshold = %v, want %v", got, 120*time.Second)
	}
	if got := thresholds[unifiedresources.SourcePMG]; got != 6*time.Minute {
		t.Fatalf("PMG threshold = %v, want %v", got, 6*time.Minute)
	}
}

func TestResourceStaleThresholdsPreserveDefaultFloors(t *testing.T) {
	thresholds := ResourceStaleThresholdsForConfig(nil)

	if got := thresholds[unifiedresources.SourceProxmox]; got != 60*time.Second {
		t.Fatalf("default Proxmox threshold = %v, want %v", got, 60*time.Second)
	}
	if got := thresholds[unifiedresources.SourcePBS]; got != 120*time.Second {
		t.Fatalf("default PBS threshold = %v, want %v", got, 120*time.Second)
	}
	if got := thresholds[unifiedresources.SourcePMG]; got != 120*time.Second {
		t.Fatalf("default PMG threshold = %v, want %v", got, 120*time.Second)
	}
}

// Consumers outside the monitor, such as the connections list, judge poll
// freshness by Monitor.BasePollInterval. It must report the base cadence the
// scheduler polls each platform at, including runtime polling overrides on a
// detached tenant config copy (#1619), and must not take m.mu, which the
// scheduler's poll-provider lookup takes.
func TestMonitorBasePollIntervalReportsSchedulerBaseCadence(t *testing.T) {
	newTenantMonitor := func(override time.Duration) *Monitor {
		base := &config.Config{
			PVEPollingInterval: 30 * time.Second,
			PBSPollingInterval: time.Minute,
			PMGPollingInterval: time.Minute,
		}
		monitor := &Monitor{config: base.DeepCopy()}
		monitor.SetPBSPollingInterval(override)
		monitor.SetPMGPollingInterval(override)
		return monitor
	}

	t.Run("runtime overrides on a detached copy, clamped like the scheduler", func(t *testing.T) {
		for override, want := range map[time.Duration]time.Duration{
			5 * time.Second:  10 * time.Second,
			90 * time.Second: 90 * time.Second,
			5 * time.Minute:  5 * time.Minute,
			2 * time.Hour:    time.Hour,
		} {
			monitor := newTenantMonitor(override)
			for _, instanceType := range []InstanceType{InstanceTypePBS, InstanceTypePMG} {
				if got := monitor.BasePollInterval(instanceType); got != want {
					t.Errorf("%s base interval = %v for override %v, want %v", instanceType, got, override, want)
				}
			}
			for _, instanceType := range []InstanceType{InstanceTypePVE, InstanceTypePBS, InstanceTypePMG} {
				if got, scheduled := monitor.BasePollInterval(instanceType), monitor.baseIntervalForInstanceType(instanceType); got != scheduled {
					t.Errorf("%s base interval = %v for override %v, want the scheduler's %v", instanceType, got, override, scheduled)
				}
			}
		}
	})

	t.Run("adaptive scheduling keeps the same base", func(t *testing.T) {
		monitor := newTenantMonitor(5 * time.Minute)
		monitor.scheduler = NewAdaptiveScheduler(SchedulerConfig{}, nil, nil, nil)
		if got := monitor.BasePollInterval(InstanceTypePBS); got != 5*time.Minute {
			t.Fatalf("PBS base interval = %v under adaptive scheduling, want the saved %v", got, 5*time.Minute)
		}
	})

	t.Run("does not take the monitor lock", func(t *testing.T) {
		monitor := newTenantMonitor(5 * time.Minute)
		monitor.mu.Lock()
		defer monitor.mu.Unlock()
		done := make(chan time.Duration, 1)
		go func() { done <- monitor.BasePollInterval(InstanceTypePBS) }()
		select {
		case got := <-done:
			if got != 5*time.Minute {
				t.Fatalf("PBS base interval = %v, want %v", got, 5*time.Minute)
			}
		case <-time.After(2 * time.Second):
			t.Fatal("BasePollInterval blocked while m.mu was held")
		}
	})

	t.Run("unknown cadence reads zero", func(t *testing.T) {
		var nilMonitor *Monitor
		for name, got := range map[string]time.Duration{
			"nil monitor":       nilMonitor.BasePollInterval(InstanceTypePBS),
			"monitor no config": (&Monitor{}).BasePollInterval(InstanceTypePVE),
			"availability":      newTenantMonitor(time.Minute).BasePollInterval(InstanceTypeAvailability),
		} {
			if got != 0 {
				t.Errorf("%s base interval = %v, want 0", name, got)
			}
		}
	})
}

// Non-default tenant monitors poll against a detached config copy (#1619), so
// a saved PBS or PMG interval reaches them only as a runtime override. The
// freshness thresholds the monitor publishes must follow the cadence its
// scheduler polls at, or PBS and PMG rows read stale between real polls.
func TestMonitorResourceStaleThresholdsFollowRuntimePollingOverrides(t *testing.T) {
	cases := []struct {
		name          string
		configured    time.Duration
		override      time.Duration
		wantThreshold time.Duration
		wantStatus    unifiedresources.ResourceStatus
	}{
		{
			name:          "raised interval keeps a sighting inside the new cadence online",
			configured:    time.Minute,
			override:      5 * time.Minute,
			wantThreshold: 10 * time.Minute,
			wantStatus:    unifiedresources.StatusOnline,
		},
		{
			name:          "lowered interval judges the same sighting stale",
			configured:    5 * time.Minute,
			override:      time.Minute,
			wantThreshold: 2 * time.Minute,
			wantStatus:    unifiedresources.StatusWarning,
		},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			sighting := time.Now().UTC().Add(-3 * time.Minute)
			state := models.NewState()
			state.UpdatePBSInstances([]models.PBSInstance{{
				ID:               "pbs-main",
				Name:             "pbs-main",
				Host:             "https://pbs.lab.local:8007",
				Status:           "online",
				ConnectionHealth: "healthy",
				LastSeen:         sighting,
			}})
			state.UpdatePMGInstances([]models.PMGInstance{{
				ID:               "pmg-main",
				Name:             "pmg-main",
				Host:             "https://pmg.lab.local:8006",
				Status:           "online",
				ConnectionHealth: "healthy",
				LastSeen:         sighting,
				LastUpdated:      sighting,
			}})

			base := &config.Config{
				PVEPollingInterval: 10 * time.Second,
				PBSPollingInterval: tc.configured,
				PMGPollingInterval: tc.configured,
			}
			monitor := &Monitor{state: state, config: base.DeepCopy()}
			adapter := unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(nil))
			monitor.SetResourceStore(adapter)
			monitor.SetPBSPollingInterval(tc.override)
			monitor.SetPMGPollingInterval(tc.override)

			if got := monitor.baseIntervalForInstanceType(InstanceTypePBS); got != tc.override {
				t.Fatalf("PBS scheduler interval = %v, want override %v", got, tc.override)
			}
			thresholds := monitor.resourceStaleThresholds()
			for _, source := range []unifiedresources.DataSource{unifiedresources.SourcePBS, unifiedresources.SourcePMG} {
				if got := thresholds[source]; got != tc.wantThreshold {
					t.Errorf("%s threshold = %v, want %v from the %v runtime interval", source, got, tc.wantThreshold, tc.override)
				}
			}
			if got := thresholds[unifiedresources.SourceProxmox]; got != 60*time.Second {
				t.Errorf("Proxmox threshold = %v, want the unchanged %v floor", got, 60*time.Second)
			}

			monitor.updateResourceStore(state.GetSnapshot(), monitor.mockModeFence.begin())

			pbs := adapter.PBSInstances()
			if len(pbs) != 1 {
				t.Fatalf("PBS instances = %d, want 1", len(pbs))
			}
			if got := pbs[0].Status(); got != tc.wantStatus {
				t.Fatalf("PBS status = %q, want %q for a 3m-old sighting on a %v cadence", got, tc.wantStatus, tc.override)
			}
			pmg := adapter.PMGInstances()
			if len(pmg) != 1 {
				t.Fatalf("PMG instances = %d, want 1", len(pmg))
			}
			if got := pmg[0].Status(); got != tc.wantStatus {
				t.Fatalf("PMG status = %q, want %q for a 3m-old sighting on a %v cadence", got, tc.wantStatus, tc.override)
			}
		})
	}

	t.Run("freshness reads the scheduler's clamped interval", func(t *testing.T) {
		for _, override := range []time.Duration{5 * time.Second, 90 * time.Second, 2 * time.Hour} {
			base := &config.Config{PBSPollingInterval: time.Minute, PMGPollingInterval: time.Minute}
			monitor := &Monitor{config: base.DeepCopy()}
			monitor.SetPBSPollingInterval(override)
			monitor.SetPMGPollingInterval(override)
			thresholds := monitor.resourceStaleThresholds()
			for instanceType, source := range map[InstanceType]unifiedresources.DataSource{
				InstanceTypePBS: unifiedresources.SourcePBS,
				InstanceTypePMG: unifiedresources.SourcePMG,
			} {
				scheduled := monitor.baseIntervalForInstanceType(instanceType)
				want := resourceStaleThresholdForPollInterval(scheduled, defaultPlatformResourceStaleThreshold)
				if got := thresholds[source]; got != want {
					t.Errorf("%s threshold = %v for override %v, want %v from the scheduler's %v", source, got, override, want, scheduled)
				}
			}
		}
	})

	// The adaptive scheduler picks intervals from its own bounds and never
	// reads the per-platform intervals or overrides, so a save must not move
	// freshness there: it follows the scheduler's maximum interval, which the
	// 5-minute per-platform interval below would not give (10 minutes).
	// TestMonitorResourceFreshnessFollowsAdaptiveCadence covers the cadence
	// itself.
	t.Run("adaptive scheduling ignores per-platform overrides", func(t *testing.T) {
		base := &config.Config{PBSPollingInterval: 5 * time.Minute, PMGPollingInterval: 5 * time.Minute}
		monitor := &Monitor{
			config:    base.DeepCopy(),
			scheduler: NewAdaptiveScheduler(SchedulerConfig{MaxInterval: 15 * time.Minute}, nil, nil, nil),
		}
		const want = 30 * time.Minute
		before := monitor.resourceStaleThresholds()
		monitor.SetPBSPollingInterval(time.Minute)
		monitor.SetPMGPollingInterval(time.Minute)
		after := monitor.resourceStaleThresholds()
		for _, source := range []unifiedresources.DataSource{unifiedresources.SourcePBS, unifiedresources.SourcePMG, unifiedresources.SourceProxmox} {
			if before[source] != want || after[source] != want {
				t.Errorf("%s threshold = %v -> %v across an override the adaptive scheduler ignores, want %v from its 15m maximum throughout",
					source, before[source], after[source], want)
			}
		}
	})
}

// Mock history is seeded for a bounded window, so chart ranges longer than the
// seed fall through to the synthetic generator. That generator must still carry
// the host-relative `memoryused` byte series, or the workloads memory column in
// host-capacity mode has nothing to draw at 7d while every other series renders.
func TestMockGuestChartHistoryCarriesMemoryUsedBeyondSeededWindow(t *testing.T) {
	previous := mock.IsMockEnabled()
	mustSetMockEnabled(t, true)
	defer mustSetMockEnabled(t, previous)

	graph := mock.CurrentFixtureGraph()
	var (
		guestID string
		total   float64
	)
	for _, vm := range graph.State.VMs {
		if vm.ID != "" && vm.Memory.Total > 0 {
			guestID = vm.ID
			total = float64(vm.Memory.Total)
			break
		}
	}
	if guestID == "" {
		t.Fatal("mock fixture graph has no VM with a memory total")
	}

	series := mockGuestMetricsForChart("vm", guestID, 7*24*time.Hour)
	memoryUsed := series["memoryused"]
	memoryPercent := series["memory"]

	if len(memoryUsed) == 0 {
		t.Fatalf("expected a memoryused series for %s over 7d, got none", guestID)
	}
	if len(memoryUsed) != len(memoryPercent) {
		t.Fatalf(
			"expected memoryused to track the memory series length, got %d vs %d",
			len(memoryUsed),
			len(memoryPercent),
		)
	}

	for i, point := range memoryUsed {
		if !point.Timestamp.Equal(memoryPercent[i].Timestamp) {
			t.Fatalf("memoryused timestamp %d diverged from the memory series", i)
		}
		want := total * (math.Max(0, math.Min(100, memoryPercent[i].Value)) / 100)
		if math.Abs(point.Value-want) > 1 {
			t.Fatalf("memoryused[%d] = %f, want %f bytes", i, point.Value, want)
		}
	}
}

// Docker containers and pods are outside the Proxmox host-capacity memory
// contract, so the synthetic generator must not start emitting bytes for them.
func TestMockGuestChartHistorySkipsMemoryUsedForNonProxmoxGuests(t *testing.T) {
	previous := mock.IsMockEnabled()
	mustSetMockEnabled(t, true)
	defer mustSetMockEnabled(t, previous)

	for _, resourceType := range []string{"dockerContainer", "k8s"} {
		series := mockGuestMetricsForChart(resourceType, "any-guest-id", 7*24*time.Hour)
		if len(series["memoryused"]) != 0 {
			t.Fatalf(
				"expected no memoryused series for %s, got %d points",
				resourceType,
				len(series["memoryused"]),
			)
		}
	}
}

func TestBroadcastProjectionMatchesPreviousPipeline(t *testing.T) {
	now := time.Now().UTC()
	resources := []unifiedresources.Resource{
		{ID: "agent-api", Type: unifiedresources.ResourceTypeAgent, Name: "tower", Status: unifiedresources.StatusOnline, LastSeen: now,
			Identity: unifiedresources.ResourceIdentity{Hostnames: []string{"tower.local"}},
			Sources:  []unifiedresources.DataSource{unifiedresources.SourceProxmox},
			Proxmox:  &unifiedresources.ProxmoxData{NodeName: "tower.local", ClusterName: "lab", PVEVersion: "9"}},
		{ID: "agent-runtime", Type: unifiedresources.ResourceTypeAgent, Name: "tower", Status: unifiedresources.StatusOnline, LastSeen: now,
			Identity: unifiedresources.ResourceIdentity{MachineID: "tower-machine", Hostnames: []string{"tower.local"}},
			Sources:  []unifiedresources.DataSource{unifiedresources.SourceAgent},
			Agent:    &unifiedresources.AgentData{AgentID: "tower-machine", Hostname: "tower.local", Platform: "linux", AgentVersion: "6.4.5"},
			Metrics:  &unifiedresources.ResourceMetrics{CPU: &unifiedresources.MetricValue{Value: 25, Unit: "percent"}}},
	}
	for i, name := range []string{"zebra", "Alpha", "alpha", "", "尾"} {
		parent := "agent-api"
		resources = append(resources, unifiedresources.Resource{
			ID: fmt.Sprintf("vm-%d", i), Type: unifiedresources.ResourceTypeVM, Name: name,
			ParentID: &parent, Status: unifiedresources.StatusOnline, LastSeen: now,
			Proxmox: &unifiedresources.ProxmoxData{NodeName: "tower.local", VMID: i + 100},
			Sources: []unifiedresources.DataSource{unifiedresources.SourceProxmox},
			Metrics: &unifiedresources.ResourceMetrics{CPU: &unifiedresources.MetricValue{Value: 10, Unit: "percent"}},
		})
	}
	registry := unifiedresources.NewRegistry(nil)
	registry.IngestResources(resources)
	store := &broadcastProjectionCountingStore{MonitorAdapter: unifiedresources.NewMonitorAdapter(registry)}
	m := &Monitor{resourceStore: store}
	snapshot := models.EmptyStateSnapshot()
	snapshot.ActiveAlerts = []models.Alert{{ID: "warning", ResourceID: "agent-runtime", Level: "warning", Type: "cpu"}}
	snapshot.RemovedHostAgents = []models.RemovedHostAgent{{ID: "ignored-host", Hostname: "ignored.local", RemovedAt: now}}
	snapshot.RemovedDockerHosts = []models.RemovedDockerHost{{ID: "ignored-docker", Hostname: "docker.local", RemovedAt: now}}
	sourceBefore, _ := json.Marshal(store.GetAll())
	view := m.currentUnifiedStateView()
	previousResources := unifiedresources.CoalescePresentationHostResources(view.resources)
	previousResources = m.applyPersistedMetadataToUnifiedResources(previousResources)
	previousResources = unifiedresources.AttachResourceHealth(previousResources, resourceHealthAlerts(snapshot.ActiveAlerts), now)
	want := snapshot.ToFrontend()
	projected, catalogs := convertResourcesForBroadcastReference(previousResources, broadcastMetricsTargetResolver(view.readState))
	want.Resources = projected
	want.CapabilityCatalog = catalogs.capabilities
	want.PolicyCatalog = catalogs.policies
	want.AISafeSummaryCatalog = catalogs.aiSafeSummaries
	want.ConnectedInfrastructure = buildConnectedInfrastructure(previousResources, snapshot)
	if !view.freshness.IsZero() {
		want.LastUpdate = view.freshness.UnixMilli()
	}
	got := m.buildBroadcastFrontendStateFromSnapshotWithClock(snapshot, m.mockModeFence.begin(), func() time.Time { return now })
	wantJSON, err := json.Marshal(want)
	if err != nil {
		t.Fatal(err)
	}
	gotJSON, err := json.Marshal(got)
	if err != nil {
		t.Fatal(err)
	}
	if string(gotJSON) != string(wantJSON) {
		t.Fatalf("projection differs from previous pipeline\nwant=%s\ngot=%s", wantJSON, gotJSON)
	}
	sourceAfter, _ := json.Marshal(store.GetAll())
	if string(sourceAfter) != string(sourceBefore) {
		t.Fatal("broadcast decoration mutated registry")
	}
}

// The runtime contract includes both poll builders, protocol admission and truthful History.
func TestGuestAgentBackupMonitoringContract(t *testing.T) {
	testGuestAgentBackupMonitoringLifecycle(t)
}

func TestGuestAgentOptionalReadOrderingContract(t *testing.T) {
	t.Run("current-status", func(t *testing.T) { testGuestAgentOptionalReadOrdering(t, false) })
	t.Run("recent-evidence-without-status", func(t *testing.T) { testGuestAgentOptionalReadOrdering(t, true) })
}

func TestGuestWindowsMeminfoPollingContract(t *testing.T) {
	testGuestWindowsMeminfoPolling(t)
}

func TestGuestWindowsRestartPollingContract(t *testing.T) {
	t.Run("cold-and-expired", testGuestWindowsBootstrapPolling)
	t.Run("process-restart", testGuestWindowsBootstrapProcessRestart)
	t.Run("admission-and-identity", testGuestWindowsBootstrapSafety)
}

func TestGuestMetadataRejectionRecoveryContract(t *testing.T) {
	t.Run("typed-rejection", testGuestMetadataRejectedOSInfo)
	t.Run("ordinary-stopped-agent-recovery", testGuestMetadataStoppedAgentPollingRecovery)
}

func TestGuestMemoryObservationContract(t *testing.T) {
	t.Run("poll-to-served-observation", testGuestMemoryObservationLifecycle)
	t.Run("identity-and-origin-boundaries", testGuestMemoryObservationKeepsOriginsSeparate)
	t.Run("independent-linked-agent", testGuestMemoryObservationPreservesIndependentLinkedAgent)
}

// Same-target, unambiguous lock evidence is required even with warm caches.
func TestGuestAgentBackupLockEvidenceContract(t *testing.T) {
	for _, test := range []struct{ name, config string }{
		{"redirected config", "redirect"},
		{"overwritten backup lock", `{"data":{"lock":"backup","lock":""}}`},
		{"overwritten config envelope", `{"data":{"lock":"backup"},"data":{}}`},
		{"case-conflicting envelope", `{"data":{"lock":"backup"},"DATA":{}}`},
	} {
		t.Run(test.name, func(t *testing.T) {
			testGuestAgentBackupMonitoringLifecycleWithUnverifiedConfig(t, test.config)
		})
	}
}

func TestDeferredVMGuestMemoryRequiresOriginalEvidence(t *testing.T) {
	now := time.Now()
	tests := []struct {
		name   string
		change func(*agentMemCacheEntry, *GuestMemorySnapshot)
		key    string
		want   bool
	}{
		{name: "expired read TTL still supports last-known memory", want: true},
		{name: "derived meminfo", want: true, change: func(e *agentMemCacheEntry, _ *GuestMemorySnapshot) { e.info.Source = "meminfo-derived" }},
		{name: "last-known age boundary", want: true, change: func(e *agentMemCacheEntry, _ *GuestMemorySnapshot) { e.fetchedAt = now.Add(-vmAgentMemCleanupMaxAge) }},
		{name: "expired original observation", change: func(e *agentMemCacheEntry, _ *GuestMemorySnapshot) {
			e.fetchedAt = now.Add(-vmAgentMemCleanupMaxAge - time.Nanosecond)
		}},
		{name: "missing observation time", change: func(e *agentMemCacheEntry, _ *GuestMemorySnapshot) { e.fetchedAt = time.Time{} }},
		{name: "future observation time", change: func(e *agentMemCacheEntry, _ *GuestMemorySnapshot) { e.fetchedAt = now.Add(time.Second) }},
		{name: "failed guest read", change: func(e *agentMemCacheEntry, _ *GuestMemorySnapshot) { e.negative = true }},
		{name: "missing source", change: func(e *agentMemCacheEntry, _ *GuestMemorySnapshot) { e.info.Source = "" }},
		{name: "unsupported source", change: func(e *agentMemCacheEntry, _ *GuestMemorySnapshot) { e.info.Source = "unavailable" }},
		{name: "different instance cache", key: "other/node/105"},
		{name: "different node cache", key: "fixture/other/105"},
		{name: "different VM cache", key: "fixture/node/106"},
		{name: "different previous identity", change: func(_ *agentMemCacheEntry, v *GuestMemorySnapshot) { v.VMID++ }},
		{name: "different guest type", change: func(_ *agentMemCacheEntry, v *GuestMemorySnapshot) { v.GuestType = "lxc" }},
		{name: "stopped guest", change: func(_ *agentMemCacheEntry, v *GuestMemorySnapshot) { v.Status = "stopped" }},
		{name: "unrelated memory source", change: func(_ *agentMemCacheEntry, v *GuestMemorySnapshot) { v.MemorySource = "agent" }},
		{name: "previous-snapshot remains bound to original read", want: true, change: func(_ *agentMemCacheEntry, v *GuestMemorySnapshot) { v.MemorySource = "previous-snapshot" }},
		{name: "unknown previous memory", change: func(_ *agentMemCacheEntry, v *GuestMemorySnapshot) { v.Memory = models.UnavailableMemory(100) }},
		{name: "changed capacity", change: func(_ *agentMemCacheEntry, v *GuestMemorySnapshot) { v.Memory.Total++ }},
		{name: "different observation", change: func(_ *agentMemCacheEntry, v *GuestMemorySnapshot) { v.Memory.Used++ }},
		{name: "different free memory observation", change: func(_ *agentMemCacheEntry, v *GuestMemorySnapshot) { v.Memory.Free++ }},
		{name: "different reclaimable cache observation", change: func(_ *agentMemCacheEntry, v *GuestMemorySnapshot) { v.Memory.Cache++ }},
		{name: "impossible availability", change: func(e *agentMemCacheEntry, _ *GuestMemorySnapshot) { e.info.EffectiveAvailable = 101 }},
		{name: "observed zero usage", want: true, change: func(e *agentMemCacheEntry, v *GuestMemorySnapshot) {
			e.info.EffectiveAvailable = 100
			e.info.Free = 20
			v.Memory = models.Memory{Total: 100, Free: 20, Cache: 80}
		}},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			entry := agentMemCacheEntry{info: proxmox.LinuxMemoryAvailability{Source: "meminfo-available", EffectiveAvailable: 60, Free: 10}, fetchedAt: now.Add(-2 * vmAgentMemCacheTTL)}
			previous := GuestMemorySnapshot{GuestType: "qemu", Status: "running", MemorySource: "guest-agent-meminfo", Instance: "fixture", Node: "node", VMID: 105, Memory: models.Memory{Total: 100, Used: 40, Free: 10, Cache: 50, Usage: 40}}
			if tt.change != nil {
				tt.change(&entry, &previous)
			}
			key := tt.key
			if key == "" {
				key = guestMemoryCacheKey("fixture", "node", 105)
			}
			m := &Monitor{vmAgentMemCache: map[string]agentMemCacheEntry{key: entry}}
			memory, ok := m.deferredVMGuestMemory("fixture", "node", 105, 100, &previous, now)
			if ok != tt.want || (ok && memory != previous.Memory) {
				t.Fatalf("retention = %#v, %t; want previous memory, %t", memory, ok, tt.want)
			}
			if m.vmAgentMemCache[key] != entry {
				t.Fatal("last-known evidence was renewed or changed")
			}
		})
	}
	if _, ok := (&Monitor{}).deferredVMGuestMemory("fixture", "node", 105, 100, nil, now); ok {
		t.Fatal("invented memory without a previous observation")
	}
}

func TestGuestAgentUnrecognisedHTTPStatusContract(t *testing.T) {
	testGuestAgentTransportDeferralKeepsLastKnownHistory(t, "conflict response", "too early response", "client closed response")
}

func TestGuestAgentTransportMonitoringContract(t *testing.T) {
	for _, reason := range []string{"agent-redirect", "agent-transport-unverified", "agent-completion-unverified"} {
		for _, prefix := range []string{"", "prev-"} {
			if !guestAgentDiskDeferred(prefix + reason) {
				t.Errorf("transport uncertainty %q is not labelled deferred", prefix+reason)
			}
		}
	}
	for _, reason := range []string{"", "permission-denied", "agent-not-running", "agent-error"} {
		if guestAgentDiskDeferred(reason) {
			t.Errorf("completed/ordinary error %q became transport uncertainty", reason)
		}
	}
	testGuestAgentTransportDeferralKeepsLastKnownHistory(t, "lost reply", "redirect", "server error", "gateway error")
}

func TestGuestAgentSuccessEnvelopeMonitoringContract(t *testing.T) {
	// A complete HTTP 200 is not enough to renew guest caches or History when
	// it only supplies a malformed, ambiguous or prefix-only reply. These
	// real client/builder controls also keep independent CPU progressing.
	testGuestAgentTransportDeferralKeepsLastKnownHistory(t, "malformed success", "ambiguous success", "trailing success")
}

func TestGuestAgentTypedReplyMonitoringContract(t *testing.T) {
	// Valid JSON with impossible result/file field types is still unreadable
	// command evidence, not an empty current inventory or a completion fence.
	testGuestAgentTransportDeferralKeepsLastKnownHistory(t, "typed result", "typed content", "typed truncated")
}

func TestGuestAgentCommandReplyMonitoringContract(t *testing.T) {
	// A complete but recognizably foreign command reply cannot clear a
	// filesystem request or renew its capacity/History. Keep actual warm
	// observation origins and live CPU across both deferral polls.
	testGuestAgentTransportDeferralKeepsLastKnownHistory(t, "foreign file", "foreign network", "foreign version")
}

func TestBackupAlertEvaluationCallersShareFailureVisibility(t *testing.T) {
	for path, want := range map[string]int{"monitor_backups.go": 2, "monitor_alerts.go": 1} {
		raw, err := os.ReadFile(path)
		if err != nil {
			t.Fatal(err)
		}
		source := string(raw)
		if strings.Contains(source, "listBackupRollupsForAlerts(") || strings.Contains(source, "CheckBackupsWithInventory(") {
			t.Errorf("%s bypasses shared failure-preserving evaluation", path)
		}
		if got := strings.Count(source, "m.checkBackupAlerts("); got != want {
			t.Errorf("%s has %d shared backup evaluations, want %d", path, got, want)
		}
	}
}

func TestGuestMemorySampleCapacityCanonicalProjection(t *testing.T) {
	testGuestMemorySampleCapacityPolling(t)
}

// The configurable vCenter refresh budget must retain the default, caller
// cancellation, last complete inventory and serial multi-connection dispatch.
func TestVMwareInventoryRefreshBudgetContract(t *testing.T) {
	t.Run("configuration", testVMwarePollTimeoutConfiguration)
	t.Run("refresh-and-projection", testVMwarePollRefreshBudgetAndProjection)
}

// The REST seed must preserve the same resolved coordinates as the broadcast
// generation, without consulting a later registry or editing a shared view.
func TestUnifiedSnapshotPreservesCapturedHistoryTargets(t *testing.T) {
	oldTarget := &unifiedresources.MetricsTarget{ResourceType: "agent", ResourceID: "old-connection"}
	rows := []unifiedresources.Resource{
		{ID: "canonical-row", Type: unifiedresources.ResourceTypeAgent, MetricsTarget: oldTarget},
		{ID: "unknown-row", Type: unifiedresources.ResourceTypeAgent, MetricsTarget: oldTarget},
	}
	targets := projectionMetricsTargets{"canonical-row": {ResourceType: "agent", ResourceID: "native-connection"}}
	view := monitorUnifiedStateView{resources: rows, metricsTargets: targets}
	got := unifiedSnapshotResources(view)
	if got[0].MetricsTarget == nil || got[0].MetricsTarget.ResourceID != "native-connection" || got[1].MetricsTarget != nil {
		t.Fatalf("captured known/unknown targets lost: %+v", got)
	}
	if rows[0].MetricsTarget != oldTarget || rows[1].MetricsTarget != oldTarget || oldTarget.ResourceID != "old-connection" {
		t.Fatal("snapshot decorated the shared read-state rows")
	}
	got[0].MetricsTarget.ResourceID = "caller-change"
	got[0].Name = "caller-change"
	again := unifiedSnapshotResources(view)
	if again[0].Name != "" || again[0].MetricsTarget.ResourceID != "native-connection" || targets["canonical-row"].ResourceID != "native-connection" {
		t.Fatal("returned snapshot changed the captured generation")
	}
	// A store without a captured target projection retains its existing
	// source row; the snapshot does not invent a coordinate from its name.
	fallback := unifiedSnapshotResources(monitorUnifiedStateView{resources: rows})
	if fallback[0].MetricsTarget != oldTarget {
		t.Fatal("projection-less fallback lost its supplied coordinate")
	}
}