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.

33.7 KB
Raw Blame
package mock

import (
	"reflect"
	"sort"
	"strings"
	"testing"
	"time"

	"github.com/rcourtman/pulse-go-rewrite/internal/models"
	"github.com/rcourtman/pulse-go-rewrite/internal/operationaltrust"
	"github.com/rcourtman/pulse-go-rewrite/internal/recovery"
	"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)

func TestBuildFixtureGraphAppliesCuratedDemoScenarioAcrossEstate(t *testing.T) {
	cfg := DefaultConfig
	cfg.RandomMetrics = false

	now := time.Date(2026, time.April, 1, 12, 0, 0, 0, time.UTC)
	graph := buildFixtureGraph(cfg, now)

	for _, want := range []string{"checkout-web-01", "orders-api-01"} {
		if !vmNameExists(graph, want) {
			t.Fatalf("expected curated vm %q in canonical demo graph", want)
		}
	}
	for _, want := range []string{"auth-service-01", "backup-orchestrator-01"} {
		if !containerNameExists(graph, want) {
			t.Fatalf("expected curated system container %q in canonical demo graph", want)
		}
	}
	for _, want := range []string{"edge-apps-01", "ops-services-01"} {
		if !dockerHostNameExists(graph, want) {
			t.Fatalf("expected curated docker host %q in canonical demo graph", want)
		}
	}
	for _, want := range []string{"customer-portal", "backup-coordinator"} {
		if !dockerContainerNameExists(graph, want) {
			t.Fatalf("expected curated app container %q in canonical demo graph", want)
		}
	}
	for _, want := range []string{"client-files", "edge-dns"} {
		if !trueNASAppNameExists(graph, want) {
			t.Fatalf("expected curated TrueNAS app %q in canonical demo graph", want)
		}
	}
	for _, want := range []string{"warehouse-api-01", "etl-batch-01"} {
		if !vmwareVMNameExists(graph, want) {
			t.Fatalf("expected curated VMware VM %q in canonical demo graph", want)
		}
	}
	if !nodeDisplayNameExists(graph, "West Production A") {
		t.Fatal("expected curated infrastructure node display name in canonical demo graph")
	}
	if !kubernetesNodeExists(graph, "prod-euw1-k8s-01") {
		t.Fatal("expected curated kubernetes node in canonical demo graph")
	}
	for _, want := range []string{"checkout-web", "payments-worker"} {
		if !kubernetesDeploymentExists(graph, want) {
			t.Fatalf("expected curated kubernetes deployment %q in canonical demo graph", want)
		}
	}
	if !kubernetesNativeInventoryExists(graph) {
		t.Fatal("expected curated kubernetes native API inventory in canonical demo graph")
	}
	if duplicate := firstDuplicateKubernetesClusterDisplayName(graph); duplicate != "" {
		t.Fatalf("expected curated kubernetes clusters to have distinct display names, duplicate %q", duplicate)
	}
	for _, want := range []string{"platform-observability", "node-exporter", "nightly-backfill-28918234", "cron-nightly-backfill"} {
		if !kubernetesControllerExists(graph, want) {
			t.Fatalf("expected curated kubernetes controller %q in canonical demo graph", want)
		}
	}
	for _, want := range []string{"shared-backup-fabric", "west-a-service-pool"} {
		if !storageNameExists(graph, want) {
			t.Fatalf("expected curated storage name %q in canonical demo graph", want)
		}
	}
	if storageNameExists(graph, "service-pool") {
		t.Fatal("expected demo storage naming to remove generic service-pool alias")
	}
	if !pbsInstanceExists(graph, "backup-vault") {
		t.Fatal("expected curated PBS instance in canonical demo graph")
	}
	if !allPBSDatastoresOnline(graph) {
		t.Fatal("expected curated PBS datastores to normalize onto online status")
	}
	if !pmgInstanceExists(graph, "mail-gateway-eu") {
		t.Fatal("expected curated PMG instance in canonical demo graph")
	}
	if leak := firstLegacyMockClusterLeak(graph); leak != "" {
		t.Fatalf("expected demo scenario to replace legacy mock-cluster labels, found %s", leak)
	}
}

func TestDefaultDemoProxmoxEstateIsLargeMultiClusterAndBounded(t *testing.T) {
	cfg := DefaultConfig
	cfg.RandomMetrics = false

	now := time.Date(2026, time.April, 1, 12, 0, 0, 0, time.UTC)
	graph := buildFixtureGraph(cfg, now)

	if got, want := len(graph.State.Nodes), 50; got != want {
		t.Fatalf("default demo node count = %d, want %d", got, want)
	}

	clusterCounts := make(map[string]int)
	standaloneCount := 0
	for _, node := range graph.State.Nodes {
		if node.IsClusterMember {
			clusterCounts[node.ClusterName]++
			continue
		}
		standaloneCount++
	}
	wantClusters := []string{
		"Production West",
		"Production East",
		"Core Services",
		"Disaster Recovery",
		"Edge Sites",
	}
	for _, clusterName := range wantClusters {
		if got := clusterCounts[clusterName]; got != mockProxmoxClusterSize {
			t.Fatalf("cluster %q node count = %d, want %d", clusterName, got, mockProxmoxClusterSize)
		}
	}
	if standaloneCount != 2 {
		t.Fatalf("standalone Proxmox node count = %d, want 2", standaloneCount)
	}

	guestCount := len(graph.State.VMs) + len(graph.State.Containers)
	if guestCount <= 800 || guestCount > 1000 {
		t.Fatalf("default demo guest count = %d, want a windowed but bounded estate in (800, 1000]", guestCount)
	}

	// Local storage, two shared PBS definitions per clustered node, and a
	// bounded cluster-wide NFS/Ceph set must stay linear in the node count.
	if storageCount := len(graph.State.Storage); storageCount > len(graph.State.Nodes)*5 {
		t.Fatalf("default demo storage count = %d, exceeds linear fleet budget %d", storageCount, len(graph.State.Nodes)*5)
	}

	if !nodeDisplayNameExists(graph, "East Production A") ||
		!nodeDisplayNameExists(graph, "Edge Sites A") ||
		!nodeDisplayNameExists(graph, "London Edge Standalone") {
		t.Fatal("expected multi-site and standalone Proxmox display identities")
	}
	if !demoProxmoxNodeIsOffline(graph, demoOfflineProxmoxNode) {
		t.Fatalf("expected curated offline Proxmox node %q", demoOfflineProxmoxNode)
	}
	for _, storage := range graph.State.Storage {
		if !strings.EqualFold(strings.TrimSpace(storage.Node), demoOfflineProxmoxNode) {
			continue
		}
		if !strings.EqualFold(strings.TrimSpace(storage.Status), "offline") || storage.Active || storage.Enabled {
			t.Fatalf("offline node storage retained live posture: %+v", storage)
		}
	}
}

func TestCuratedDemoProtectionStoriesProduceRepresentativePostures(t *testing.T) {
	cfg := DefaultConfig
	cfg.RandomMetrics = false

	now := time.Date(2026, time.April, 1, 12, 0, 0, 0, time.UTC)
	graph := buildFixtureGraph(cfg, now)
	resources, _ := graph.UnifiedResourceSnapshot()
	resourceIDsByName := make(map[string]string)
	for _, resource := range resources {
		if resource.Type != unifiedresources.ResourceTypeVM &&
			resource.Type != unifiedresources.ResourceTypeSystemContainer {
			continue
		}
		resourceIDsByName[resource.Name] = resource.ID
	}

	points := graph.RecoveryPoints()
	pointsByResourceID := make(map[string][]recovery.RecoveryPoint)
	observationsByKey := make(map[string]recovery.ProtectionProviderObservation)
	for _, point := range points {
		resourceID := strings.TrimSpace(point.SubjectResourceID)
		if resourceID == "" {
			continue
		}
		pointsByResourceID[resourceID] = append(pointsByResourceID[resourceID], point)
		scope := recovery.ProviderScopeForPoint(point)
		key := string(point.Provider) + "\x00" + scope
		if _, exists := observationsByKey[key]; exists {
			continue
		}
		observation, err := recovery.NewProtectionProviderObservation(
			point.Provider,
			"mock-complete-recovery-fixture",
			scope,
			recovery.OutcomeUnknown,
			recovery.ProtectionHistoryComplete,
			operationaltrust.EvidencePermissionsSufficient,
			point.Provider == recovery.ProviderProxmoxPBS,
			now,
			now,
			nil,
		)
		if err != nil {
			t.Fatalf("build provider observation for %s: %v", key, err)
		}
		observationsByKey[key] = observation
	}
	observations := make([]recovery.ProtectionProviderObservation, 0, len(observationsByKey))
	for _, observation := range observationsByKey {
		observations = append(observations, observation)
	}

	assertPosture := func(name string, want recovery.ProtectionState) {
		t.Helper()
		resourceID := resourceIDsByName[name]
		if resourceID == "" {
			t.Fatalf("expected curated workload %q in unified resource graph", name)
		}
		posture := recovery.BuildProtectionPostureFromPointsAt(
			resourceID,
			pointsByResourceID[resourceID],
			observations,
			recovery.DefaultProtectionPosturePolicy,
			now,
		)
		if posture.State != want {
			t.Fatalf("posture for %q = %q, want %q: %s", name, posture.State, want, posture.Explanation)
		}
	}

	assertPosture("checkout-web-01", recovery.ProtectionStateProtected)
	assertPosture("checkout-web-02", recovery.ProtectionStateAttention)
	assertPosture("orders-api-02", recovery.ProtectionStateAttention)
	assertPosture("docs-portal-01", recovery.ProtectionStateUnprotected)
	assertPosture("smtp-relay-01", recovery.ProtectionStateUnprotected)

	unknownResourceID := resourceIDsByName["backup-orchestrator-01"]
	if unknownResourceID == "" {
		t.Fatal("expected curated unknown workload in unified resource graph")
	}
	if got := len(pointsByResourceID[unknownResourceID]); got != 0 {
		t.Fatalf("unknown workload has %d recovery points, want none", got)
	}
}

func TestFixtureGraphUpdateMetricsKeepsProtectionCadenceAnchoredToRefresh(t *testing.T) {
	cfg := DefaultConfig
	cfg.RandomMetrics = true

	start := time.Date(2026, time.April, 1, 12, 0, 0, 0, time.UTC)
	later := start.Add(45 * time.Minute)
	graph := buildFixtureGraph(cfg, start)
	graph.UpdateMetrics(cfg, later)

	var protectedVM *models.VM
	for i := range graph.State.VMs {
		if graph.State.VMs[i].Name == "checkout-web-01" {
			protectedVM = &graph.State.VMs[i]
			break
		}
	}
	if protectedVM == nil {
		t.Fatal("expected curated protected VM after metric refresh")
	}
	wantBackupAt := later.Add(-6 * time.Hour)
	if !protectedVM.LastBackup.Equal(wantBackupAt) {
		t.Fatalf("protected VM LastBackup = %s, want %s", protectedVM.LastBackup, wantBackupAt)
	}

	var newestBackup time.Time
	for _, backup := range graph.State.PVEBackups.StorageBackups {
		if backup.VMID != protectedVM.VMID || backup.Type != "qemu" {
			continue
		}
		if backup.Time.After(newestBackup) {
			newestBackup = backup.Time
		}
	}
	if !newestBackup.Equal(wantBackupAt) {
		t.Fatalf("protected VM newest backup = %s, want %s", newestBackup, wantBackupAt)
	}

	for _, container := range graph.State.Containers {
		if container.Name == "backup-orchestrator-01" && !container.LastBackup.IsZero() {
			t.Fatalf("unknown workload LastBackup = %s, want zero", container.LastBackup)
		}
	}
}

// TestKubernetesDemoClustersTellDistinctStories guards the slice-F goal:
// each curated cluster carries its own node naming and exactly one
// degraded scenario, so four cluster screenshots don't look like four
// copies of the same one.
func TestKubernetesDemoClustersTellDistinctStories(t *testing.T) {
	cfg := DefaultConfig
	graph := buildFixtureGraph(cfg, time.Date(2026, time.April, 10, 12, 0, 0, 0, time.UTC))

	clusters := graph.State.KubernetesClusters
	if len(clusters) < 3 {
		t.Fatalf("expected at least 3 curated Kubernetes clusters, got %d", len(clusters))
	}

	// Node-name prefixes per cluster must be distinct.
	prefixByCluster := map[string]string{
		"Production EU":  "prod-euw1-",
		"Staging EU":     "stage-euw1-",
		"Development EU": "dev-euw1-",
	}
	for _, cluster := range clusters {
		prefix, ok := prefixByCluster[cluster.DisplayName]
		if !ok {
			continue
		}
		if len(cluster.Nodes) == 0 {
			t.Fatalf("cluster %q has no nodes", cluster.DisplayName)
		}
		for _, node := range cluster.Nodes {
			if !strings.HasPrefix(node.Name, prefix) {
				t.Fatalf(
					"cluster %q node %q does not use the curated %q prefix",
					cluster.DisplayName, node.Name, prefix,
				)
			}
		}
	}

	// Exactly one cluster carries each degraded scenario.
	crashLoopClusters := 0
	imagePullClusters := 0
	notReadyClusters := 0
	for _, cluster := range clusters {
		if clusterHasCrashLoopPaymentsWorker(cluster) {
			crashLoopClusters++
		}
		if clusterHasImagePullBackOffPod(cluster) {
			imagePullClusters++
		}
		if clusterHasNotReadyNode(cluster) {
			notReadyClusters++
		}
	}
	if crashLoopClusters != 1 {
		t.Fatalf("expected exactly one cluster with CrashLoopBackOff payments-worker, got %d", crashLoopClusters)
	}
	if imagePullClusters != 1 {
		t.Fatalf("expected exactly one cluster with ImagePullBackOff pod, got %d", imagePullClusters)
	}
	if notReadyClusters != 1 {
		t.Fatalf("expected exactly one cluster with a NotReady worker, got %d", notReadyClusters)
	}

	// Cluster versions must be distinct so the operator sees real
	// version drift instead of three identical entries.
	seenVersions := make(map[string]string, len(clusters))
	for _, cluster := range clusters {
		if cluster.Version == "" {
			t.Fatalf("cluster %q has no curated version", cluster.DisplayName)
		}
		if other, ok := seenVersions[cluster.Version]; ok {
			t.Fatalf("cluster %q duplicates kubelet version %q already used by %q",
				cluster.DisplayName, cluster.Version, other)
		}
		seenVersions[cluster.Version] = cluster.DisplayName
	}
}

func clusterHasCrashLoopPaymentsWorker(cluster models.KubernetesCluster) bool {
	for _, pod := range cluster.Pods {
		if pod.OwnerName != "payments-worker" {
			continue
		}
		for _, container := range pod.Containers {
			if !container.Ready && container.Reason == "CrashLoopBackOff" {
				return true
			}
		}
	}
	return false
}

func clusterHasImagePullBackOffPod(cluster models.KubernetesCluster) bool {
	for _, pod := range cluster.Pods {
		for _, container := range pod.Containers {
			if container.Reason == "ImagePullBackOff" {
				return true
			}
		}
	}
	return false
}

func clusterHasNotReadyNode(cluster models.KubernetesCluster) bool {
	for _, node := range cluster.Nodes {
		if !node.Ready {
			return true
		}
	}
	return false
}

func TestDemoScenarioStorageNamingHandlesScaledNodeCount(t *testing.T) {
	cfg := DefaultConfig
	cfg.NodeCount = 6
	cfg.RandomMetrics = false

	graph := buildFixtureGraph(cfg, time.Date(2026, time.April, 1, 12, 0, 0, 0, time.UTC))

	if storageNameExists(graph, "service-pool") {
		t.Fatal("expected demo storage naming to keep the generic service-pool alias retired even when NodeCount > 5")
	}
	if storageNameExists(graph, "iso-library") {
		t.Fatal("expected demo storage naming to keep the generic iso-library alias retired even when NodeCount > 5")
	}
}

func TestFixtureGraphUpdateMetricsPreservesCuratedDemoScenario(t *testing.T) {
	cfg := DefaultConfig
	cfg.RandomMetrics = false

	start := time.Date(2026, time.April, 1, 12, 0, 0, 0, time.UTC)
	later := start.Add(45 * time.Minute)

	graph := buildFixtureGraph(cfg, start)
	graph.UpdateMetrics(cfg, later)

	if !vmNameExists(graph, "checkout-web-01") {
		t.Fatal("expected curated vm naming to survive metric refresh")
	}
	if !dockerContainerNameExists(graph, "customer-portal") {
		t.Fatal("expected curated docker container naming to survive metric refresh")
	}
	if !trueNASAppNameExists(graph, "client-files") {
		t.Fatal("expected curated TrueNAS app naming to survive metric refresh")
	}
	if !vmwareVMNameExists(graph, "warehouse-api-01") {
		t.Fatal("expected curated VMware naming to survive metric refresh")
	}
	if !kubernetesNodeExists(graph, "prod-euw1-k8s-01") {
		t.Fatal("expected curated kubernetes node naming to survive metric refresh")
	}
	if !storageNameExists(graph, "west-a-service-pool") {
		t.Fatal("expected curated storage naming to survive metric refresh")
	}
	if !allPBSDatastoresOnline(graph) {
		t.Fatal("expected curated PBS datastore status to survive metric refresh")
	}
	if leak := firstLegacyMockClusterLeak(graph); leak != "" {
		t.Fatalf("expected metric refresh to preserve cluster aliasing, found %s", leak)
	}
}

func TestFixtureGraphUpdateMetricsRestoresStableDemoInfrastructurePosture(t *testing.T) {
	cfg := DefaultConfig
	cfg.RandomMetrics = true

	start := time.Date(2026, time.April, 1, 12, 0, 0, 0, time.UTC)
	later := start.Add(45 * time.Minute)

	graph := buildFixtureGraph(cfg, start)

	for i := range graph.State.Hosts {
		graph.State.Hosts[i].Status = "offline"
		graph.State.Hosts[i].LastSeen = time.Time{}
	}
	for i := range graph.State.DockerHosts {
		graph.State.DockerHosts[i].Status = "offline"
	}
	for i := range graph.State.KubernetesClusters {
		graph.State.KubernetesClusters[i].Status = "offline"
		for j := range graph.State.KubernetesClusters[i].Nodes {
			graph.State.KubernetesClusters[i].Nodes[j].Ready = false
			graph.State.KubernetesClusters[i].Nodes[j].Unschedulable = true
		}
	}
	for i := range graph.State.PBSInstances {
		graph.State.PBSInstances[i].Status = "offline"
		graph.State.PBSInstances[i].ConnectionHealth = "error"
		graph.State.PBSInstances[i].LastSeen = time.Time{}
	}
	for i := range graph.State.PMGInstances {
		graph.State.PMGInstances[i].Status = "offline"
		graph.State.PMGInstances[i].ConnectionHealth = "error"
		graph.State.PMGInstances[i].LastSeen = time.Time{}
	}
	graph.State.ConnectionHealth = map[string]bool{
		"docker-stale":     false,
		"kubernetes-stale": false,
		"host-stale":       false,
		"pbs-stale":        false,
		"pmg-stale":        false,
		"pve-stale":        false,
	}

	graph.UpdateMetrics(cfg, later)

	if !hostsMatchCuratedPosture(graph) {
		t.Fatalf("expected demo host agents to restore curated posture (%s + prod-euw1-k8s-03 offline) after metric refresh", demoOfflineProxmoxNode)
	}
	if !dockerHostsMatchCuratedPosture(graph) {
		t.Fatal("expected curated docker hosts to restore posture (one offline) after metric refresh")
	}
	if !allKubernetesClustersOnline(graph) {
		t.Fatal("expected curated kubernetes clusters to restore online status after metric refresh")
	}
	if !kubernetesNodesMatchCuratedPosture(graph) {
		t.Fatal("expected curated kubernetes nodes to restore posture (prod-euw1-k8s-03 NotReady in offline cluster) after metric refresh")
	}
	if !pbsInstancesMatchCuratedPosture(graph) {
		t.Fatal("expected curated PBS posture (dr-vault degraded, backup-vault online) to restore after metric refresh")
	}
	if !pmgInstancesMatchCuratedPosture(graph) {
		t.Fatal("expected curated PMG posture (mail-gateway-us degraded, mail-gateway-eu online) to restore after metric refresh")
	}
	if !connectionHealthMatchesCuratedDemoState(graph) {
		t.Fatal("expected connection-health map to match the final curated demo state after metric refresh")
	}
	if _, ok := graph.State.ConnectionHealth["docker-stale"]; ok {
		t.Fatal("expected stale docker connection-health keys to be cleared")
	}
	if _, ok := graph.State.ConnectionHealth["kubernetes-stale"]; ok {
		t.Fatal("expected stale kubernetes connection-health keys to be cleared")
	}
	if _, ok := graph.State.ConnectionHealth["host-stale"]; ok {
		t.Fatal("expected stale host-agent connection-health keys to be cleared")
	}
	if _, ok := graph.State.ConnectionHealth["pbs-stale"]; ok {
		t.Fatal("expected stale PBS connection-health keys to be cleared")
	}
	if _, ok := graph.State.ConnectionHealth["pmg-stale"]; ok {
		t.Fatal("expected stale PMG connection-health keys to be cleared")
	}
	if _, ok := graph.State.ConnectionHealth["pve-stale"]; ok {
		t.Fatal("expected stale PVE connection-health keys to be cleared")
	}
}

func vmNameExists(graph FixtureGraph, want string) bool {
	for _, vm := range graph.State.VMs {
		if vm.Name == want {
			return true
		}
	}
	return false
}

func containerNameExists(graph FixtureGraph, want string) bool {
	for _, container := range graph.State.Containers {
		if container.Name == want {
			return true
		}
	}
	return false
}

func dockerHostNameExists(graph FixtureGraph, want string) bool {
	for _, host := range graph.State.DockerHosts {
		if host.Hostname == want || host.DisplayName == want {
			return true
		}
	}
	return false
}

func dockerContainerNameExists(graph FixtureGraph, want string) bool {
	for _, host := range graph.State.DockerHosts {
		for _, container := range host.Containers {
			if container.Name == want {
				return true
			}
		}
	}
	return false
}

func trueNASAppNameExists(graph FixtureGraph, want string) bool {
	for _, app := range graph.PlatformFixtures.TrueNAS.Apps {
		if app.Name == want {
			return true
		}
	}
	return false
}

func vmwareVMNameExists(graph FixtureGraph, want string) bool {
	for _, vm := range graph.PlatformFixtures.VMware.VMs {
		if vm.Name == want {
			return true
		}
	}
	return false
}

func nodeDisplayNameExists(graph FixtureGraph, want string) bool {
	for _, node := range graph.State.Nodes {
		if node.DisplayName == want {
			return true
		}
	}
	return false
}

func kubernetesNodeExists(graph FixtureGraph, want string) bool {
	for _, cluster := range graph.State.KubernetesClusters {
		for _, node := range cluster.Nodes {
			if node.Name == want {
				return true
			}
		}
	}
	return false
}

func kubernetesDeploymentExists(graph FixtureGraph, want string) bool {
	for _, cluster := range graph.State.KubernetesClusters {
		for _, deployment := range cluster.Deployments {
			if deployment.Name == want {
				return true
			}
		}
	}
	return false
}

func kubernetesControllerExists(graph FixtureGraph, want string) bool {
	for _, cluster := range graph.State.KubernetesClusters {
		for _, statefulSet := range cluster.StatefulSets {
			if statefulSet.Name == want {
				return true
			}
		}
		for _, daemonSet := range cluster.DaemonSets {
			if daemonSet.Name == want {
				return true
			}
		}
		for _, job := range cluster.Jobs {
			if job.Name == want {
				return true
			}
		}
		for _, cronJob := range cluster.CronJobs {
			if cronJob.Name == want {
				return true
			}
		}
	}
	return false
}

func kubernetesNativeInventoryExists(graph FixtureGraph) bool {
	if len(graph.State.KubernetesClusters) == 0 {
		return false
	}
	for _, cluster := range graph.State.KubernetesClusters {
		if len(cluster.Namespaces) == 0 ||
			len(cluster.StatefulSets) == 0 ||
			len(cluster.DaemonSets) == 0 ||
			len(cluster.Jobs) == 0 ||
			len(cluster.CronJobs) == 0 ||
			len(cluster.Services) == 0 ||
			len(cluster.EndpointSlices) == 0 ||
			len(cluster.NetworkPolicies) == 0 ||
			len(cluster.ConfigMaps) == 0 ||
			len(cluster.Secrets) == 0 ||
			len(cluster.ServiceAccounts) == 0 ||
			len(cluster.Roles) == 0 ||
			len(cluster.ClusterRoles) == 0 ||
			len(cluster.RoleBindings) == 0 ||
			len(cluster.ClusterRoleBindings) == 0 ||
			len(cluster.ResourceQuotas) == 0 ||
			len(cluster.LimitRanges) == 0 ||
			len(cluster.PodDisruptionBudgets) == 0 ||
			len(cluster.HorizontalPodAutoscalers) == 0 ||
			len(cluster.Events) == 0 {
			return false
		}
		if !cluster.ConfigMaps[0].MetadataOnly ||
			len(cluster.ConfigMaps[0].DataKeys) != 0 ||
			len(cluster.ConfigMaps[0].BinaryDataKeys) != 0 {
			return false
		}
		if !cluster.Secrets[0].MetadataOnly ||
			cluster.Secrets[0].Type != "" ||
			len(cluster.Secrets[0].DataKeys) != 0 {
			return false
		}
		if cluster.StatefulSets[0].ServiceName == "" ||
			cluster.DaemonSets[0].DesiredNumberScheduled == 0 ||
			cluster.Jobs[0].DesiredCompletions == 0 ||
			cluster.CronJobs[0].Schedule == "" {
			return false
		}
		if cluster.HorizontalPodAutoscalers[0].TargetKind == "" ||
			cluster.HorizontalPodAutoscalers[0].TargetName == "" ||
			len(cluster.HorizontalPodAutoscalers[0].MetricTypes) == 0 {
			return false
		}
	}
	return true
}

func firstDuplicateKubernetesClusterDisplayName(graph FixtureGraph) string {
	seen := map[string]struct{}{}
	for _, cluster := range graph.State.KubernetesClusters {
		name := firstNonEmptyTrimmed(cluster.DisplayName, cluster.CustomDisplayName, cluster.Name, cluster.ID)
		if name == "" {
			continue
		}
		if _, ok := seen[name]; ok {
			return name
		}
		seen[name] = struct{}{}
	}
	return ""
}

func storageNameExists(graph FixtureGraph, want string) bool {
	for _, storage := range graph.State.Storage {
		if storage.Name == want {
			return true
		}
	}
	return false
}

func pbsInstanceExists(graph FixtureGraph, want string) bool {
	for _, instance := range graph.State.PBSInstances {
		if instance.Name == want {
			return true
		}
	}
	return false
}

func allPBSDatastoresOnline(graph FixtureGraph) bool {
	for _, instance := range graph.State.PBSInstances {
		for _, datastore := range instance.Datastores {
			if datastore.Status != "online" {
				return false
			}
		}
	}
	return true
}

func pmgInstanceExists(graph FixtureGraph, want string) bool {
	for _, instance := range graph.State.PMGInstances {
		if instance.Name == want {
			return true
		}
	}
	return false
}

func hostsMatchCuratedPosture(graph FixtureGraph) bool {
	for _, host := range graph.State.Hosts {
		hostname := strings.ToLower(strings.TrimSpace(host.Hostname))
		if isDemoOfflineProxmoxNode(hostname) || hostname == "prod-euw1-k8s-03" {
			if host.Status != "offline" {
				return false
			}
			continue
		}
		if host.Status != "online" {
			return false
		}
	}
	return true
}

func dockerHostsMatchCuratedPosture(graph FixtureGraph) bool {
	const offlineDockerIndex = 2
	for i, host := range graph.State.DockerHosts {
		if i == offlineDockerIndex {
			if host.Status != "offline" {
				return false
			}
			continue
		}
		if host.Status != "online" && host.Status != "degraded" {
			return false
		}
	}
	return true
}

func allKubernetesClustersOnline(graph FixtureGraph) bool {
	for _, cluster := range graph.State.KubernetesClusters {
		if cluster.Status != "online" {
			return false
		}
	}
	return true
}

func kubernetesNodesMatchCuratedPosture(graph FixtureGraph) bool {
	for _, cluster := range graph.State.KubernetesClusters {
		for _, node := range cluster.Nodes {
			if node.Name == "prod-euw1-k8s-03" {
				// At least one cluster reports this profile as NotReady to
				// drive the demo Linux-host outage; others can be Ready.
				continue
			}
			if !node.Ready || node.Unschedulable {
				return false
			}
		}
	}
	return true
}

func pbsInstancesMatchCuratedPosture(graph FixtureGraph) bool {
	for i, instance := range graph.State.PBSInstances {
		if i == 1 {
			if instance.Status != "degraded" || instance.ConnectionHealth != "degraded" {
				return false
			}
			continue
		}
		if instance.Status != "online" || instance.ConnectionHealth != "healthy" {
			return false
		}
	}
	return true
}

func pmgInstancesMatchCuratedPosture(graph FixtureGraph) bool {
	for i, instance := range graph.State.PMGInstances {
		if i == 1 {
			if instance.Status != "degraded" || instance.ConnectionHealth != "degraded" {
				return false
			}
			continue
		}
		if instance.Status != "online" || instance.ConnectionHealth != "healthy" {
			return false
		}
	}
	return true
}

func connectionHealthMatchesCuratedDemoState(graph FixtureGraph) bool {
	for _, node := range graph.State.Nodes {
		key := "pve-" + strings.TrimSpace(node.Name)
		expected := !strings.EqualFold(strings.TrimSpace(node.Status), "offline")
		healthy, ok := graph.State.ConnectionHealth[key]
		if key == "pve-" || !ok || healthy != expected {
			return false
		}
	}
	for _, host := range graph.State.DockerHosts {
		key := "docker-" + strings.TrimSpace(host.ID)
		expected := !strings.EqualFold(strings.TrimSpace(host.Status), "offline")
		healthy, ok := graph.State.ConnectionHealth[key]
		if key == "docker-" || !ok || healthy != expected {
			return false
		}
	}
	for _, cluster := range graph.State.KubernetesClusters {
		key := "kubernetes-" + strings.TrimSpace(cluster.ID)
		expected := !strings.EqualFold(strings.TrimSpace(cluster.Status), "offline")
		healthy, ok := graph.State.ConnectionHealth[key]
		if key == "kubernetes-" || !ok || healthy != expected {
			return false
		}
	}
	for _, host := range graph.State.Hosts {
		key := "host-" + strings.TrimSpace(host.ID)
		expected := !strings.EqualFold(strings.TrimSpace(host.Status), "offline")
		healthy, ok := graph.State.ConnectionHealth[key]
		if key == "host-" || !ok || healthy != expected {
			return false
		}
	}
	for _, instance := range graph.State.PBSInstances {
		key := "pbs-" + strings.TrimSpace(instance.Name)
		expected := !strings.EqualFold(strings.TrimSpace(instance.Status), "offline")
		healthy, ok := graph.State.ConnectionHealth[key]
		if key == "pbs-" || !ok || healthy != expected {
			return false
		}
	}
	for _, instance := range graph.State.PMGInstances {
		key := "pmg-" + strings.TrimSpace(instance.Name)
		expected := !strings.EqualFold(strings.TrimSpace(instance.Status), "offline")
		healthy, ok := graph.State.ConnectionHealth[key]
		if key == "pmg-" || !ok || healthy != expected {
			return false
		}
	}
	return true
}

func firstLegacyMockClusterLeak(graph FixtureGraph) string {
	for _, node := range graph.State.Nodes {
		if isLegacyMockClusterName(node.Instance) || isLegacyMockClusterName(node.ClusterName) {
			return "node:" + firstNonEmptyTrimmed(node.DisplayName, node.Name, node.ID)
		}
	}
	for _, vm := range graph.State.VMs {
		if isLegacyMockClusterName(vm.Instance) {
			return "vm:" + firstNonEmptyTrimmed(vm.Name, vm.ID)
		}
	}
	for _, container := range graph.State.Containers {
		if isLegacyMockClusterName(container.Instance) {
			return "container:" + firstNonEmptyTrimmed(container.Name, container.ID)
		}
	}
	for _, storage := range graph.State.Storage {
		if isLegacyMockClusterName(storage.Instance) {
			return "storage:" + firstNonEmptyTrimmed(storage.Name, storage.ID)
		}
	}
	for _, disk := range graph.State.PhysicalDisks {
		if isLegacyMockClusterName(disk.Instance) {
			return "physical-disk:" + firstNonEmptyTrimmed(disk.Model, disk.ID)
		}
	}
	for _, cluster := range graph.State.CephClusters {
		if isLegacyMockClusterName(cluster.Instance) || isLegacyMockClusterName(cluster.Name) {
			return "ceph:" + firstNonEmptyTrimmed(cluster.Name, cluster.ID)
		}
	}
	return ""
}

func isLegacyMockClusterName(value string) bool {
	return strings.HasPrefix(strings.ToLower(strings.TrimSpace(value)), "mock-cluster")
}

func demoProxmoxNodeIsOffline(graph FixtureGraph, nodeName string) bool {
	for _, node := range graph.State.Nodes {
		if strings.EqualFold(strings.TrimSpace(node.Name), strings.TrimSpace(nodeName)) {
			return strings.EqualFold(strings.TrimSpace(node.Status), "offline")
		}
	}
	return false
}

func TestDemoDockerContainerNamesAreUniquePerHost(t *testing.T) {
	cfg := DefaultConfig
	cfg.DockerHostCount = 3
	cfg.DockerContainersPerHost = 8

	graph := buildFixtureGraph(cfg, time.Date(2026, time.April, 1, 12, 0, 0, 0, time.UTC))

	// Docker refuses two containers with one name on a host. The demo used to
	// reuse a curated profile for a second round and show two "customer-portal"
	// rows per host, which also doubled every image's "used by" list.
	for _, host := range graph.State.DockerHosts {
		seen := map[string]struct{}{}
		for _, container := range host.Containers {
			if _, dup := seen[container.Name]; dup {
				t.Fatalf("host %s names two containers %q", host.Hostname, container.Name)
			}
			seen[container.Name] = struct{}{}
		}
	}
	if !dockerContainerNameExists(graph, "customer-portal") {
		t.Fatal("expected the first round of curated names to stay unchanged")
	}
}

func TestDemoKubernetesWorkloadNamesAreUniquePerNamespace(t *testing.T) {
	curatedPods := map[string]struct{}{}
	for _, profile := range demoKubernetesPodProfiles {
		curatedPods[profile.Name] = struct{}{}
	}
	for _, tc := range []struct {
		name        string
		deployments int
		pods        int
	}{
		{name: "default", deployments: DefaultConfig.K8sDeploymentsPerCluster, pods: DefaultConfig.K8sPodsPerCluster},
		{name: "beyond curated profiles", deployments: 30, pods: 60},
		{name: "no deployments", deployments: 0, pods: 40},
		{name: "many replicas", deployments: 15, pods: 631},
	} {
		t.Run(tc.name, func(t *testing.T) {
			cfg := DefaultConfig
			cfg.RandomMetrics = false
			cfg.K8sDeploymentsPerCluster = tc.deployments
			cfg.K8sPodsPerCluster = tc.pods

			start := time.Date(2026, time.April, 1, 12, 0, 0, 0, time.UTC)
			graph := buildFixtureGraph(cfg, start)
			before := kubernetesWorkloadKeys(graph)

			// Kubernetes refuses two deployments or two pods with one name in
			// a namespace. The demo cycled four deployment names and ten pod
			// names, so the overview showed "checkout-api" four times and the
			// curated crash-looping pod more than once.
			totalCrashLooping := 0
			for _, cluster := range graph.State.KubernetesClusters {
				readyNodes := map[string]bool{}
				for _, node := range cluster.Nodes {
					readyNodes[node.Name] = node.Ready
				}
				deployments := map[string]struct{}{}
				for _, deployment := range cluster.Deployments {
					key := deployment.Namespace + "/" + deployment.Name
					if _, dup := deployments[key]; dup {
						t.Fatalf("cluster %s names two deployments %q", cluster.DisplayName, key)
					}
					deployments[key] = struct{}{}
					if deployment.ReadyReplicas < deployment.DesiredReplicas && deployment.Name != "payments-worker" {
						t.Fatalf("cluster %s repeats a degraded deployment as %q", cluster.DisplayName, key)
					}
				}
				pods := map[string]struct{}{}
				crashLooping := 0
				for _, pod := range cluster.Pods {
					key := pod.Namespace + "/" + pod.Name
					if _, dup := pods[key]; dup {
						t.Fatalf("cluster %s names two pods %q", cluster.DisplayName, key)
					}
					pods[key] = struct{}{}
					if _, curated := curatedPods[pod.Name]; !curated && pod.NodeName != "" && !readyNodes[pod.NodeName] {
						t.Fatalf("cluster %s placed replica %q on not-ready node %q", cluster.DisplayName, key, pod.NodeName)
					}
					if tc.deployments >= len(demoKubernetesDeploymentProfiles) && pod.OwnerKind == "Deployment" {
						if _, ok := deployments[pod.Namespace+"/"+pod.OwnerName]; !ok {
							t.Fatalf("cluster %s pod %q is owned by missing deployment %q", cluster.DisplayName, key, pod.OwnerName)
						}
					}
					for _, container := range pod.Containers {
						if container.Reason == "CrashLoopBackOff" {
							crashLooping++
							break
						}
					}
				}
				if crashLooping > 1 {
					t.Fatalf("cluster %s repeats the curated crash loop on %d pods", cluster.DisplayName, crashLooping)
				}
				totalCrashLooping += crashLooping
			}
			if totalCrashLooping != 1 {
				t.Fatalf("expected the curated crash loop exactly once across the estate, got %d", totalCrashLooping)
			}

			graph.UpdateMetrics(cfg, start.Add(45*time.Minute))
			if after := kubernetesWorkloadKeys(graph); !reflect.DeepEqual(before, after) {
				t.Fatal("expected Kubernetes workload names to survive a metric refresh unchanged")
			}
		})
	}
}

func kubernetesWorkloadKeys(graph FixtureGraph) []string {
	keys := []string{}
	for _, cluster := range graph.State.KubernetesClusters {
		for _, deployment := range cluster.Deployments {
			keys = append(keys, cluster.ID+"/deploy/"+deployment.Namespace+"/"+deployment.Name)
		}
		for _, pod := range cluster.Pods {
			keys = append(keys, cluster.ID+"/pod/"+pod.Namespace+"/"+pod.Name)
		}
	}
	sort.Strings(keys)
	return keys
}