/*
Copyright 2014 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package scheduler

import (
	"context"
	"errors"
	"fmt"
	"slices"
	"sort"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	"github.com/onsi/gomega"
	"github.com/stretchr/testify/require"

	v1 "k8s.io/api/core/v1"
	eventsv1 "k8s.io/api/events/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/apimachinery/pkg/util/version"
	"k8s.io/apiserver/pkg/util/feature"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/kubernetes/fake"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/events"
	featuregatetesting "k8s.io/component-base/featuregate/testing"
	"k8s.io/klog/v2"
	"k8s.io/klog/v2/ktesting"
	fwk "k8s.io/kube-scheduler/framework"
	"k8s.io/kubernetes/pkg/features"
	schedulerapi "k8s.io/kubernetes/pkg/scheduler/apis/config"
	"k8s.io/kubernetes/pkg/scheduler/apis/config/testing/defaults"
	apicache "k8s.io/kubernetes/pkg/scheduler/backend/api_cache"
	apidispatcher "k8s.io/kubernetes/pkg/scheduler/backend/api_dispatcher"
	internalcache "k8s.io/kubernetes/pkg/scheduler/backend/cache"
	internalqueue "k8s.io/kubernetes/pkg/scheduler/backend/queue"
	"k8s.io/kubernetes/pkg/scheduler/framework"
	apicalls "k8s.io/kubernetes/pkg/scheduler/framework/api_calls"
	"k8s.io/kubernetes/pkg/scheduler/framework/plugins"
	"k8s.io/kubernetes/pkg/scheduler/framework/plugins/defaultbinder"
	"k8s.io/kubernetes/pkg/scheduler/framework/plugins/names"
	"k8s.io/kubernetes/pkg/scheduler/framework/plugins/queuesort"
	frameworkruntime "k8s.io/kubernetes/pkg/scheduler/framework/runtime"
	"k8s.io/kubernetes/pkg/scheduler/metrics"
	"k8s.io/kubernetes/pkg/scheduler/profile"
	st "k8s.io/kubernetes/pkg/scheduler/testing"
	tf "k8s.io/kubernetes/pkg/scheduler/testing/framework"
	utiltesting "k8s.io/kubernetes/test/utils/ktesting"
	testingclock "k8s.io/utils/clock/testing"
	"k8s.io/utils/ptr"
)

func init() {
	metrics.Register()
}

func TestSchedulerCreation(t *testing.T) {
	invalidRegistry := map[string]frameworkruntime.PluginFactory{
		defaultbinder.Name: defaultbinder.New,
	}
	validRegistry := map[string]frameworkruntime.PluginFactory{
		"Foo": defaultbinder.New,
	}
	cases := []struct {
		name          string
		opts          []Option
		wantErr       string
		wantProfiles  []string
		wantExtenders []string
	}{
		{
			name: "valid out-of-tree registry",
			opts: []Option{
				WithFrameworkOutOfTreeRegistry(validRegistry),
				WithProfiles(
					schedulerapi.KubeSchedulerProfile{
						SchedulerName: "default-scheduler",
						Plugins: &schedulerapi.Plugins{
							QueueSort: schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "PrioritySort"}}},
							Bind:      schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "DefaultBinder"}}},
						},
					},
				)},
			wantProfiles: []string{"default-scheduler"},
		},
		{
			name: "repeated plugin name in out-of-tree plugin",
			opts: []Option{
				WithFrameworkOutOfTreeRegistry(invalidRegistry),
				WithProfiles(
					schedulerapi.KubeSchedulerProfile{
						SchedulerName: "default-scheduler",
						Plugins: &schedulerapi.Plugins{
							QueueSort: schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "PrioritySort"}}},
							Bind:      schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "DefaultBinder"}}},
						},
					},
				)},
			wantProfiles: []string{"default-scheduler"},
			wantErr:      "a plugin named DefaultBinder already exists",
		},
		{
			name: "multiple profiles",
			opts: []Option{
				WithProfiles(
					schedulerapi.KubeSchedulerProfile{
						SchedulerName: "foo",
						Plugins: &schedulerapi.Plugins{
							QueueSort: schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "PrioritySort"}}},
							Bind:      schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "DefaultBinder"}}},
						},
					},
					schedulerapi.KubeSchedulerProfile{
						SchedulerName: "bar",
						Plugins: &schedulerapi.Plugins{
							QueueSort: schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "PrioritySort"}}},
							Bind:      schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "DefaultBinder"}}},
						},
					},
				)},
			wantProfiles: []string{"bar", "foo"},
		},
		{
			name: "Repeated profiles",
			opts: []Option{
				WithProfiles(
					schedulerapi.KubeSchedulerProfile{
						SchedulerName: "foo",
						Plugins: &schedulerapi.Plugins{
							QueueSort: schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "PrioritySort"}}},
							Bind:      schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "DefaultBinder"}}},
						},
					},
					schedulerapi.KubeSchedulerProfile{
						SchedulerName: "bar",
						Plugins: &schedulerapi.Plugins{
							QueueSort: schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "PrioritySort"}}},
							Bind:      schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "DefaultBinder"}}},
						},
					},
					schedulerapi.KubeSchedulerProfile{
						SchedulerName: "foo",
						Plugins: &schedulerapi.Plugins{
							QueueSort: schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "PrioritySort"}}},
							Bind:      schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "DefaultBinder"}}},
						},
					},
				)},
			wantErr: "duplicate profile with scheduler name \"foo\"",
		},
		{
			name: "With extenders",
			opts: []Option{
				WithProfiles(
					schedulerapi.KubeSchedulerProfile{
						SchedulerName: "default-scheduler",
						Plugins: &schedulerapi.Plugins{
							QueueSort: schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "PrioritySort"}}},
							Bind:      schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "DefaultBinder"}}},
						},
					},
				),
				WithExtenders(
					schedulerapi.Extender{
						URLPrefix: "http://extender.kube-system/",
					},
				),
			},
			wantProfiles:  []string{"default-scheduler"},
			wantExtenders: []string{"http://extender.kube-system/"},
		},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			client := fake.NewClientset()
			informerFactory := informers.NewSharedInformerFactory(client, 0)

			eventBroadcaster := events.NewBroadcaster(&events.EventSinkImpl{Interface: client.EventsV1()})

			_, ctx := ktesting.NewTestContext(t)
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()
			s, err := New(
				ctx,
				client,
				informerFactory,
				nil,
				profile.NewRecorderFactory(eventBroadcaster),
				tc.opts...,
			)

			// Errors
			if len(tc.wantErr) != 0 {
				if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
					t.Errorf("got error %q, want %q", err, tc.wantErr)
				}
				return
			}
			if err != nil {
				t.Fatalf("Failed to create scheduler: %v", err)
			}

			// Profiles
			profiles := make([]string, 0, len(s.Profiles))
			for name := range s.Profiles {
				profiles = append(profiles, name)
			}
			sort.Strings(profiles)
			if diff := cmp.Diff(tc.wantProfiles, profiles); diff != "" {
				t.Errorf("unexpected profiles (-want, +got):\n%s", diff)
			}

			// Extenders
			if len(tc.wantExtenders) != 0 {
				// Scheduler.Extenders
				extenders := make([]string, 0, len(s.Extenders))
				for _, e := range s.Extenders {
					extenders = append(extenders, e.Name())
				}
				if diff := cmp.Diff(tc.wantExtenders, extenders); diff != "" {
					t.Errorf("unexpected extenders (-want, +got):\n%s", diff)
				}

				// fwk.Handle.Extenders()
				for _, p := range s.Profiles {
					extenders := make([]string, 0, len(p.Extenders()))
					for _, e := range p.Extenders() {
						extenders = append(extenders, e.Name())
					}
					if diff := cmp.Diff(tc.wantExtenders, extenders); diff != "" {
						t.Errorf("unexpected extenders (-want, +got):\n%s", diff)
					}
				}
			}
		})
	}
}

func TestFailureHandler(t *testing.T) {
	metrics.Register()
	testPod := st.MakePod().Name("test-pod").Namespace(v1.NamespaceDefault).Obj()
	testPodUpdated := testPod.DeepCopy()
	testPodUpdated.Labels = map[string]string{"foo": ""}

	tests := []struct {
		name                       string
		podUpdatedDuringScheduling bool // pod is updated during a scheduling cycle
		podDeletedDuringScheduling bool // pod is deleted during a scheduling cycle
		expect                     *v1.Pod
	}{
		{
			name:                       "pod is updated during a scheduling cycle",
			podUpdatedDuringScheduling: true,
			expect:                     testPodUpdated,
		},
		{
			name:   "pod is not updated during a scheduling cycle",
			expect: testPod,
		},
		{
			name:                       "pod is deleted during a scheduling cycle",
			podDeletedDuringScheduling: true,
			expect:                     nil,
		},
	}

	for _, asyncAPICallsEnabled := range []bool{true, false} {
		for _, tt := range tests {
			t.Run(fmt.Sprintf("%s (Async API calls enabled: %v)", tt.name, asyncAPICallsEnabled), func(t *testing.T) {
				logger, ctx := ktesting.NewTestContext(t)
				ctx, cancel := context.WithCancel(ctx)
				defer cancel()

				client := fake.NewClientset(&v1.PodList{Items: []v1.Pod{*testPod}})
				informerFactory := informers.NewSharedInformerFactory(client, 0)
				podInformer := informerFactory.Core().V1().Pods()
				// Need to add/update/delete testPod to the store.
				if err := podInformer.Informer().GetStore().Add(testPod); err != nil {
					t.Fatal(err)
				}

				var apiDispatcher *apidispatcher.APIDispatcher
				if asyncAPICallsEnabled {
					apiDispatcher = apidispatcher.New(client, 16, apicalls.Relevances)
					apiDispatcher.Run(logger)
					defer apiDispatcher.Close()
				}

				recorder := metrics.NewMetricsAsyncRecorder(3, 20*time.Microsecond, ctx.Done())
				queue := internalqueue.NewPriorityQueue(nil, informerFactory, internalqueue.WithClock(testingclock.NewFakeClock(time.Now())), internalqueue.WithMetricsRecorder(recorder), internalqueue.WithAPIDispatcher(apiDispatcher))
				schedulerCache := internalcache.New(ctx, apiDispatcher, false)

				queue.Add(ctx, testPod)

				if _, err := queue.Pop(logger); err != nil {
					t.Fatalf("Pop failed: %v", err)
				}

				if tt.podUpdatedDuringScheduling {
					if err := podInformer.Informer().GetStore().Update(testPodUpdated); err != nil {
						t.Fatal(err)
					}
					queue.Update(ctx, testPod, testPodUpdated)
				}
				if tt.podDeletedDuringScheduling {
					if err := podInformer.Informer().GetStore().Delete(testPod); err != nil {
						t.Fatal(err)
					}
					queue.Delete(testPod)
				}

				s, schedFramework, err := initScheduler(ctx, schedulerCache, queue, apiDispatcher, client, informerFactory)
				if err != nil {
					t.Fatal(err)
				}

				testPodInfo := &framework.QueuedPodInfo{PodInfo: mustNewPodInfo(t, testPod)}
				s.FailureHandler(ctx, schedFramework, testPodInfo, fwk.NewStatus(fwk.Unschedulable), nil, time.Now())

				var got *v1.Pod
				if tt.podUpdatedDuringScheduling {
					pInfo, ok := queue.GetPod(testPod.Name, testPod.Namespace)
					if !ok {
						t.Fatalf("Failed to get pod %s/%s from queue", testPod.Namespace, testPod.Name)
					}
					got = pInfo.Pod
				} else {
					got = getPodFromPriorityQueue(queue, testPod)
				}

				if diff := cmp.Diff(tt.expect, got); diff != "" {
					t.Errorf("Unexpected pod (-want, +got): %s", diff)
				}
			})
		}
	}
}

func TestFailureHandler_PodAlreadyBound(t *testing.T) {
	for _, asyncAPICallsEnabled := range []bool{true, false} {
		t.Run(fmt.Sprintf("Async API calls enabled: %v", asyncAPICallsEnabled), func(t *testing.T) {
			logger, ctx := ktesting.NewTestContext(t)
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()

			nodeFoo := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}
			testPod := st.MakePod().Name("test-pod").Namespace(v1.NamespaceDefault).Node("foo").Obj()

			client := fake.NewClientset(&v1.PodList{Items: []v1.Pod{*testPod}}, &v1.NodeList{Items: []v1.Node{nodeFoo}})
			informerFactory := informers.NewSharedInformerFactory(client, 0)
			podInformer := informerFactory.Core().V1().Pods()
			// Need to add testPod to the store.
			if err := podInformer.Informer().GetStore().Add(testPod); err != nil {
				t.Fatal(err)
			}

			var apiDispatcher *apidispatcher.APIDispatcher
			if asyncAPICallsEnabled {
				apiDispatcher = apidispatcher.New(client, 16, apicalls.Relevances)
				apiDispatcher.Run(logger)
				defer apiDispatcher.Close()
			}

			queue := internalqueue.NewPriorityQueue(nil, informerFactory, internalqueue.WithClock(testingclock.NewFakeClock(time.Now())), internalqueue.WithAPIDispatcher(apiDispatcher))
			schedulerCache := internalcache.New(ctx, apiDispatcher, false)

			// Add node to schedulerCache no matter it's deleted in API server or not.
			schedulerCache.AddNode(logger, &nodeFoo)

			s, schedFramework, err := initScheduler(ctx, schedulerCache, queue, apiDispatcher, client, informerFactory)
			if err != nil {
				t.Fatal(err)
			}

			testPodInfo := &framework.QueuedPodInfo{PodInfo: mustNewPodInfo(t, testPod)}
			s.FailureHandler(ctx, schedFramework, testPodInfo, fwk.NewStatus(fwk.Unschedulable).WithError(fmt.Errorf("binding rejected: timeout")), nil, time.Now())

			pod := getPodFromPriorityQueue(queue, testPod)
			if pod != nil {
				t.Fatalf("Unexpected pod: %v should not be in PriorityQueue when the NodeName of pod is not empty", pod.Name)
			}
		})
	}
}

// TestWithPercentageOfNodesToScore tests scheduler's PercentageOfNodesToScore is set correctly.
func TestWithPercentageOfNodesToScore(t *testing.T) {
	tests := []struct {
		name                           string
		percentageOfNodesToScoreConfig *int32
		wantedPercentageOfNodesToScore int32
	}{
		{
			name:                           "percentageOfNodesScore is nil",
			percentageOfNodesToScoreConfig: nil,
			wantedPercentageOfNodesToScore: schedulerapi.DefaultPercentageOfNodesToScore,
		},
		{
			name:                           "percentageOfNodesScore is not nil",
			percentageOfNodesToScoreConfig: ptr.To[int32](10),
			wantedPercentageOfNodesToScore: 10,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			client := fake.NewClientset()
			informerFactory := informers.NewSharedInformerFactory(client, 0)
			eventBroadcaster := events.NewBroadcaster(&events.EventSinkImpl{Interface: client.EventsV1()})
			_, ctx := ktesting.NewTestContext(t)
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()
			sched, err := New(
				ctx,
				client,
				informerFactory,
				nil,
				profile.NewRecorderFactory(eventBroadcaster),
				WithPercentageOfNodesToScore(tt.percentageOfNodesToScoreConfig),
			)
			if err != nil {
				t.Fatalf("Failed to create scheduler: %v", err)
			}
			if sched.percentageOfNodesToScore != tt.wantedPercentageOfNodesToScore {
				t.Errorf("scheduler.percercentageOfNodesToScore = %v, want %v", sched.percentageOfNodesToScore, tt.wantedPercentageOfNodesToScore)
			}
		})
	}
}

// getPodFromPriorityQueue is the function used in the TestDefaultErrorFunc test to get
// the specific pod from the given priority queue. It returns the found pod in the priority queue.
func getPodFromPriorityQueue(queue *internalqueue.PriorityQueue, pod *v1.Pod) *v1.Pod {
	podList, _ := queue.PendingPods()
	if len(podList) == 0 {
		return nil
	}

	queryPodKey, err := cache.MetaNamespaceKeyFunc(pod)
	if err != nil {
		return nil
	}

	for _, foundPod := range podList {
		foundPodKey, err := cache.MetaNamespaceKeyFunc(foundPod)
		if err != nil {
			return nil
		}

		if foundPodKey == queryPodKey {
			return foundPod
		}
	}

	return nil
}

func initScheduler(ctx context.Context, cache internalcache.Cache, queue internalqueue.SchedulingQueue, apiDispatcher *apidispatcher.APIDispatcher,
	client kubernetes.Interface, informerFactory informers.SharedInformerFactory) (*Scheduler, framework.Framework, error) {
	logger := klog.FromContext(ctx)
	registerPluginFuncs := []tf.RegisterPluginFunc{
		tf.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
		tf.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
	}
	eventBroadcaster := events.NewBroadcaster(&events.EventSinkImpl{Interface: client.EventsV1()})
	waitingPods := frameworkruntime.NewWaitingPodsMap()
	fwk, err := tf.NewFramework(ctx,
		registerPluginFuncs,
		testSchedulerName,
		frameworkruntime.WithClientSet(client),
		frameworkruntime.WithAPIDispatcher(apiDispatcher),
		frameworkruntime.WithInformerFactory(informerFactory),
		frameworkruntime.WithEventRecorder(eventBroadcaster.NewRecorder(scheme.Scheme, testSchedulerName)),
		frameworkruntime.WithWaitingPods(waitingPods),
	)
	if err != nil {
		return nil, nil, err
	}
	if apiDispatcher != nil {
		fwk.SetAPICacher(apicache.New(queue, cache))
	}

	s := &Scheduler{
		Cache:           cache,
		client:          client,
		StopEverything:  ctx.Done(),
		SchedulingQueue: queue,
		APIDispatcher:   apiDispatcher,
		Profiles:        profile.Map{testSchedulerName: fwk},
		logger:          logger,
	}
	s.applyDefaultHandlers()

	return s, fwk, nil
}

func TestInitPluginsWithIndexers(t *testing.T) {
	tests := []struct {
		name string
		// the plugin registration ordering must not matter, being map traversal random
		entrypoints map[string]frameworkruntime.PluginFactory
		wantErr     string
	}{
		{
			name: "register indexer, no conflicts",
			entrypoints: map[string]frameworkruntime.PluginFactory{
				"AddIndexer": func(ctx context.Context, obj runtime.Object, handle fwk.Handle) (fwk.Plugin, error) {
					podInformer := handle.SharedInformerFactory().Core().V1().Pods()
					err := podInformer.Informer().AddIndexers(cache.Indexers{
						"nodeName": indexByPodSpecNodeName,
					})
					return &TestPlugin{name: "AddIndexer"}, err
				},
			},
		},
		{
			name: "register the same indexer name multiple times, conflict",
			// order of registration doesn't matter
			entrypoints: map[string]frameworkruntime.PluginFactory{
				"AddIndexer1": func(ctx context.Context, obj runtime.Object, handle fwk.Handle) (fwk.Plugin, error) {
					podInformer := handle.SharedInformerFactory().Core().V1().Pods()
					err := podInformer.Informer().AddIndexers(cache.Indexers{
						"nodeName": indexByPodSpecNodeName,
					})
					return &TestPlugin{name: "AddIndexer1"}, err
				},
				"AddIndexer2": func(ctx context.Context, obj runtime.Object, handle fwk.Handle) (fwk.Plugin, error) {
					podInformer := handle.SharedInformerFactory().Core().V1().Pods()
					err := podInformer.Informer().AddIndexers(cache.Indexers{
						"nodeName": indexByPodAnnotationNodeName,
					})
					return &TestPlugin{name: "AddIndexer1"}, err
				},
			},
			wantErr: "indexer conflict",
		},
		{
			name: "register the same indexer body with different names, no conflicts",
			// order of registration doesn't matter
			entrypoints: map[string]frameworkruntime.PluginFactory{
				"AddIndexer1": func(ctx context.Context, obj runtime.Object, handle fwk.Handle) (fwk.Plugin, error) {
					podInformer := handle.SharedInformerFactory().Core().V1().Pods()
					err := podInformer.Informer().AddIndexers(cache.Indexers{
						"nodeName1": indexByPodSpecNodeName,
					})
					return &TestPlugin{name: "AddIndexer1"}, err
				},
				"AddIndexer2": func(ctx context.Context, obj runtime.Object, handle fwk.Handle) (fwk.Plugin, error) {
					podInformer := handle.SharedInformerFactory().Core().V1().Pods()
					err := podInformer.Informer().AddIndexers(cache.Indexers{
						"nodeName2": indexByPodAnnotationNodeName,
					})
					return &TestPlugin{name: "AddIndexer2"}, err
				},
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			fakeInformerFactory := NewInformerFactory(&fake.Clientset{}, 0*time.Second)

			var registerPluginFuncs []tf.RegisterPluginFunc
			for name, entrypoint := range tt.entrypoints {
				registerPluginFuncs = append(registerPluginFuncs,
					// anything supported by TestPlugin is fine
					tf.RegisterFilterPlugin(name, entrypoint),
				)
			}
			// we always need this
			registerPluginFuncs = append(registerPluginFuncs,
				tf.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
				tf.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
			)
			_, ctx := ktesting.NewTestContext(t)
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()
			_, err := tf.NewFramework(ctx, registerPluginFuncs, "test", frameworkruntime.WithInformerFactory(fakeInformerFactory))

			if len(tt.wantErr) > 0 {
				if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
					t.Errorf("got error %q, want %q", err, tt.wantErr)
				}
				return
			}
			if err != nil {
				t.Fatalf("Failed to create scheduler: %v", err)
			}
		})
	}
}

func indexByPodSpecNodeName(obj interface{}) ([]string, error) {
	pod, ok := obj.(*v1.Pod)
	if !ok {
		return []string{}, nil
	}
	if len(pod.Spec.NodeName) == 0 {
		return []string{}, nil
	}
	return []string{pod.Spec.NodeName}, nil
}

func indexByPodAnnotationNodeName(obj interface{}) ([]string, error) {
	pod, ok := obj.(*v1.Pod)
	if !ok {
		return []string{}, nil
	}
	if len(pod.Annotations) == 0 {
		return []string{}, nil
	}
	nodeName, ok := pod.Annotations["node-name"]
	if !ok {
		return []string{}, nil
	}
	return []string{nodeName}, nil
}

const (
	filterWithoutEnqueueExtensions = "filterWithoutEnqueueExtensions"
	fakeNode                       = "fakeNode"
	fakePod                        = "fakePod"
	emptyEventsToRegister          = "emptyEventsToRegister"
	errorEventsToRegister          = "errorEventsToRegister"
	queueSort                      = "no-op-queue-sort-plugin"
	fakeBind                       = "bind-plugin"
	emptyEventExtensions           = "emptyEventExtensions"
	fakePermit                     = "fakePermit"
)

func Test_buildQueueingHintMap(t *testing.T) {
	tests := []struct {
		name                string
		plugins             []fwk.Plugin
		want                map[fwk.ClusterEvent][]*internalqueue.QueueingHintFunction
		featuregateDisabled bool
		wantErr             error
	}{
		{
			name:    "filter without EnqueueExtensions plugin",
			plugins: []fwk.Plugin{&filterWithoutEnqueueExtensionsPlugin{}},
			want: map[fwk.ClusterEvent][]*internalqueue.QueueingHintFunction{
				{Resource: fwk.Pod, ActionType: fwk.All}: {
					{PluginName: filterWithoutEnqueueExtensions, QueueingHintFn: defaultQueueingHintFn},
				},
				{Resource: fwk.Node, ActionType: fwk.All}: {
					{PluginName: filterWithoutEnqueueExtensions, QueueingHintFn: defaultQueueingHintFn},
				},
				{Resource: fwk.CSINode, ActionType: fwk.All}: {
					{PluginName: filterWithoutEnqueueExtensions, QueueingHintFn: defaultQueueingHintFn},
				},
				{Resource: fwk.CSIDriver, ActionType: fwk.All}: {
					{PluginName: filterWithoutEnqueueExtensions, QueueingHintFn: defaultQueueingHintFn},
				},
				{Resource: fwk.CSIStorageCapacity, ActionType: fwk.All}: {
					{PluginName: filterWithoutEnqueueExtensions, QueueingHintFn: defaultQueueingHintFn},
				},
				{Resource: fwk.PersistentVolume, ActionType: fwk.All}: {
					{PluginName: filterWithoutEnqueueExtensions, QueueingHintFn: defaultQueueingHintFn},
				},
				{Resource: fwk.StorageClass, ActionType: fwk.All}: {
					{PluginName: filterWithoutEnqueueExtensions, QueueingHintFn: defaultQueueingHintFn},
				},
				{Resource: fwk.PersistentVolumeClaim, ActionType: fwk.All}: {
					{PluginName: filterWithoutEnqueueExtensions, QueueingHintFn: defaultQueueingHintFn},
				},
				{Resource: fwk.ResourceClaim, ActionType: fwk.All}: {
					{PluginName: filterWithoutEnqueueExtensions, QueueingHintFn: defaultQueueingHintFn},
				},
				{Resource: fwk.DeviceClass, ActionType: fwk.All}: {
					{PluginName: filterWithoutEnqueueExtensions, QueueingHintFn: defaultQueueingHintFn},
				},
				{Resource: fwk.PodGroup, ActionType: fwk.All}: {
					{PluginName: filterWithoutEnqueueExtensions, QueueingHintFn: defaultQueueingHintFn},
				},
			},
		},
		{
			name:    "node and pod plugin",
			plugins: []fwk.Plugin{&fakeNodePlugin{}, &fakePodPlugin{}},
			want: map[fwk.ClusterEvent][]*internalqueue.QueueingHintFunction{
				{Resource: fwk.Pod, ActionType: fwk.Add}: {
					{PluginName: fakePod, QueueingHintFn: fakePodPluginQueueingFn},
				},
				{Resource: fwk.Node, ActionType: fwk.Add}: {
					{PluginName: fakeNode, QueueingHintFn: fakeNodePluginQueueingFn},
				},
				{Resource: fwk.Node, ActionType: fwk.UpdateNodeTaint}: {
					{PluginName: fakeNode, QueueingHintFn: defaultQueueingHintFn}, // When Node/Add is registered, Node/UpdateNodeTaint is automatically registered.
				},
			},
		},
		{
			name:                "node and pod plugin (featuregate is disabled)",
			plugins:             []fwk.Plugin{&fakeNodePlugin{}, &fakePodPlugin{}},
			featuregateDisabled: true,
			want: map[fwk.ClusterEvent][]*internalqueue.QueueingHintFunction{
				{Resource: fwk.Pod, ActionType: fwk.Add}: {
					{PluginName: fakePod, QueueingHintFn: defaultQueueingHintFn}, // default queueing hint due to disabled feature gate.
				},
				{Resource: fwk.Node, ActionType: fwk.Add}: {
					{PluginName: fakeNode, QueueingHintFn: defaultQueueingHintFn}, // default queueing hint due to disabled feature gate.
				},
				{Resource: fwk.Node, ActionType: fwk.UpdateNodeTaint}: {
					{PluginName: fakeNode, QueueingHintFn: defaultQueueingHintFn}, // When Node/Add is registered, Node/UpdateNodeTaint is automatically registered.
				},
			},
		},
		{
			name:    "register plugin with empty event",
			plugins: []fwk.Plugin{&emptyEventPlugin{}},
			want:    map[fwk.ClusterEvent][]*internalqueue.QueueingHintFunction{},
		},
		{
			name:    "register plugins including emptyEventPlugin",
			plugins: []fwk.Plugin{&emptyEventPlugin{}, &fakeNodePlugin{}},
			want: map[fwk.ClusterEvent][]*internalqueue.QueueingHintFunction{
				{Resource: fwk.Pod, ActionType: fwk.Add}: {
					{PluginName: fakePod, QueueingHintFn: fakePodPluginQueueingFn},
				},
				{Resource: fwk.Node, ActionType: fwk.Add}: {
					{PluginName: fakeNode, QueueingHintFn: fakeNodePluginQueueingFn},
				},
				{Resource: fwk.Node, ActionType: fwk.UpdateNodeTaint}: {
					{PluginName: fakeNode, QueueingHintFn: defaultQueueingHintFn}, // When Node/Add is registered, Node/UpdateNodeTaint is automatically registered.
				},
			},
		},
		{
			name:    "one EventsToRegister returns an error",
			plugins: []fwk.Plugin{&errorEventsToRegisterPlugin{}},
			want:    map[fwk.ClusterEvent][]*internalqueue.QueueingHintFunction{},
			wantErr: errors.New("mock error"),
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if tt.featuregateDisabled {
				featuregatetesting.SetFeatureGateEmulationVersionDuringTest(t, feature.DefaultFeatureGate, version.MustParse("1.33"))
				featuregatetesting.SetFeatureGateDuringTest(t, feature.DefaultFeatureGate, features.SchedulerQueueingHints, false)
			}

			logger, ctx := ktesting.NewTestContext(t)
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()
			registry := frameworkruntime.Registry{}
			cfgPls := &schedulerapi.Plugins{}
			plugins := append(tt.plugins, &fakebindPlugin{}, &fakeQueueSortPlugin{})
			for _, pl := range plugins {
				tmpPl := pl
				if err := registry.Register(pl.Name(), func(_ context.Context, _ runtime.Object, _ fwk.Handle) (fwk.Plugin, error) {
					return tmpPl, nil
				}); err != nil {
					t.Fatalf("fail to register filter plugin (%s)", pl.Name())
				}
				cfgPls.MultiPoint.Enabled = append(cfgPls.MultiPoint.Enabled, schedulerapi.Plugin{Name: pl.Name()})
			}

			profile := schedulerapi.KubeSchedulerProfile{Plugins: cfgPls}
			fwk, err := newFramework(ctx, registry, profile)
			if err != nil {
				t.Fatal(err)
			}

			exts := fwk.EnqueueExtensions()
			// need to sort to make the test result stable.
			sort.Slice(exts, func(i, j int) bool {
				return exts[i].Name() < exts[j].Name()
			})

			got, err := buildQueueingHintMap(ctx, exts)
			if err != nil {
				if tt.wantErr != nil && tt.wantErr.Error() != err.Error() {
					t.Fatalf("unexpected error from buildQueueingHintMap: expected: %v, actual: %v", tt.wantErr, err)
				}

				if tt.wantErr == nil {
					t.Fatalf("unexpected error from buildQueueingHintMap: %v", err)
				}
			}

			for e, fns := range got {
				wantfns, ok := tt.want[e]
				if !ok {
					t.Errorf("got unexpected event %v", e)
					continue
				}
				if len(fns) != len(wantfns) {
					t.Errorf("got %v queueing hint functions, want %v", len(fns), len(wantfns))
					continue
				}
				for i, fn := range fns {
					if fn.PluginName != wantfns[i].PluginName {
						t.Errorf("got plugin name %v, want %v", fn.PluginName, wantfns[i].PluginName)
						continue
					}
					got, gotErr := fn.QueueingHintFn(logger, nil, nil, nil)
					want, wantErr := wantfns[i].QueueingHintFn(logger, nil, nil, nil)
					if got != want || gotErr != wantErr {
						t.Errorf("got queueing hint function (%v) returning (%v, %v), expect it to return (%v, %v)", fn.PluginName, got, gotErr, want, wantErr)
						continue
					}
				}
			}
		})
	}
}

// Test_UnionedGVKs tests UnionedGVKs worked with buildQueueingHintMap.
func Test_UnionedGVKs(t *testing.T) {
	tests := []struct {
		name                            string
		plugins                         schedulerapi.PluginSet
		want                            map[fwk.EventResource]fwk.ActionType
		enableInPlacePodVerticalScaling bool
		enableSchedulerQueueingHints    bool
		enableDynamicResourceAllocation bool
		enableNodeDeclaredFeatures      bool
		enableGangScheduling            bool
	}{
		{
			name: "filter without EnqueueExtensions plugin",
			plugins: schedulerapi.PluginSet{
				Enabled: []schedulerapi.Plugin{
					{Name: filterWithoutEnqueueExtensions},
					{Name: queueSort},
					{Name: fakeBind},
				},
				Disabled: []schedulerapi.Plugin{{Name: "*"}}, // disable default plugins
			},
			want: map[fwk.EventResource]fwk.ActionType{
				fwk.Pod:                   fwk.All,
				fwk.Node:                  fwk.All,
				fwk.CSINode:               fwk.All,
				fwk.CSIDriver:             fwk.All,
				fwk.CSIStorageCapacity:    fwk.All,
				fwk.PersistentVolume:      fwk.All,
				fwk.PersistentVolumeClaim: fwk.All,
				fwk.StorageClass:          fwk.All,
				fwk.ResourceClaim:         fwk.All,
				fwk.DeviceClass:           fwk.All,
			},
		},
		{
			name: "filter without EnqueueExtensions plugin (GenericWorkload enabled)",
			plugins: schedulerapi.PluginSet{
				Enabled: []schedulerapi.Plugin{
					{Name: filterWithoutEnqueueExtensions},
					{Name: queueSort},
					{Name: fakeBind},
				},
				Disabled: []schedulerapi.Plugin{{Name: "*"}}, // disable default plugins
			},
			want: map[fwk.EventResource]fwk.ActionType{
				fwk.Pod:                   fwk.All,
				fwk.Node:                  fwk.All,
				fwk.CSINode:               fwk.All,
				fwk.CSIDriver:             fwk.All,
				fwk.CSIStorageCapacity:    fwk.All,
				fwk.PersistentVolume:      fwk.All,
				fwk.PersistentVolumeClaim: fwk.All,
				fwk.StorageClass:          fwk.All,
				fwk.ResourceClaim:         fwk.All,
				fwk.DeviceClass:           fwk.All,
				fwk.PodGroup:              fwk.All,
			},
			enableGangScheduling:            true,
			enableInPlacePodVerticalScaling: true,
			enableDynamicResourceAllocation: true,
			enableSchedulerQueueingHints:    true,
		},
		{
			name: "node plugin",
			plugins: schedulerapi.PluginSet{
				Enabled: []schedulerapi.Plugin{
					{Name: fakeNode},
					{Name: queueSort},
					{Name: fakeBind},
				},
				Disabled: []schedulerapi.Plugin{{Name: "*"}}, // disable default plugins
			},
			want: map[fwk.EventResource]fwk.ActionType{
				fwk.Node: fwk.Add | fwk.UpdateNodeTaint, // When Node/Add is registered, Node/UpdateNodeTaint is automatically registered.
			},
		},
		{
			name: "pod plugin",
			plugins: schedulerapi.PluginSet{
				Enabled: []schedulerapi.Plugin{
					{Name: fakePod},
					{Name: queueSort},
					{Name: fakeBind},
				},
				Disabled: []schedulerapi.Plugin{{Name: "*"}}, // disable default plugins
			},
			want: map[fwk.EventResource]fwk.ActionType{
				fwk.Pod: fwk.Add,
			},
		},
		{
			name: "node and pod plugin",
			plugins: schedulerapi.PluginSet{
				Enabled: []schedulerapi.Plugin{
					{Name: fakePod},
					{Name: fakeNode},
					{Name: queueSort},
					{Name: fakeBind},
				},
				Disabled: []schedulerapi.Plugin{{Name: "*"}}, // disable default plugins
			},
			want: map[fwk.EventResource]fwk.ActionType{
				fwk.Pod:  fwk.Add,
				fwk.Node: fwk.Add | fwk.UpdateNodeTaint, // When Node/Add is registered, Node/UpdateNodeTaint is automatically registered.
			},
		},
		{
			name: "empty EventsToRegister plugin",
			plugins: schedulerapi.PluginSet{
				Enabled: []schedulerapi.Plugin{
					{Name: emptyEventsToRegister},
					{Name: queueSort},
					{Name: fakeBind},
				},
				Disabled: []schedulerapi.Plugin{{Name: "*"}}, // disable default plugins
			},
			want: map[fwk.EventResource]fwk.ActionType{},
		},
		{
			name:    "plugins with default profile (No feature gate enabled)",
			plugins: schedulerapi.PluginSet{Enabled: defaults.PluginsV1.MultiPoint.Enabled},
			want: map[fwk.EventResource]fwk.ActionType{
				fwk.Pod:                   fwk.Add | fwk.UpdatePodLabel | fwk.Delete,
				fwk.Node:                  fwk.Add | fwk.UpdateNodeAllocatable | fwk.UpdateNodeLabel | fwk.UpdateNodeTaint | fwk.Delete,
				fwk.CSINode:               fwk.All - fwk.Delete,
				fwk.CSIDriver:             fwk.Update,
				fwk.CSIStorageCapacity:    fwk.All - fwk.Delete,
				fwk.PersistentVolume:      fwk.All - fwk.Delete,
				fwk.PersistentVolumeClaim: fwk.All - fwk.Delete,
				fwk.StorageClass:          fwk.All - fwk.Delete,
				fwk.VolumeAttachment:      fwk.Delete,
			},
		},
		{
			name:    "plugins with default profile (InPlacePodVerticalScaling: enabled)",
			plugins: schedulerapi.PluginSet{Enabled: defaults.PluginsV1.MultiPoint.Enabled},
			want: map[fwk.EventResource]fwk.ActionType{
				fwk.Pod:                   fwk.Add | fwk.UpdatePodLabel | fwk.UpdatePodScaleDown | fwk.Delete,
				fwk.Node:                  fwk.Add | fwk.UpdateNodeAllocatable | fwk.UpdateNodeLabel | fwk.UpdateNodeTaint | fwk.Delete,
				fwk.CSINode:               fwk.All - fwk.Delete,
				fwk.CSIDriver:             fwk.Update,
				fwk.CSIStorageCapacity:    fwk.All - fwk.Delete,
				fwk.PersistentVolume:      fwk.All - fwk.Delete,
				fwk.PersistentVolumeClaim: fwk.All - fwk.Delete,
				fwk.StorageClass:          fwk.All - fwk.Delete,
				fwk.VolumeAttachment:      fwk.Delete,
			},
			enableInPlacePodVerticalScaling: true,
		},
		{
			name:    "plugins with default profile (queueingHint/InPlacePodVerticalScaling: enabled)",
			plugins: schedulerapi.PluginSet{Enabled: defaults.PluginsV1.MultiPoint.Enabled},
			want: map[fwk.EventResource]fwk.ActionType{
				fwk.Pod:                   fwk.Add | fwk.UpdatePodLabel | fwk.UpdatePodScaleDown | fwk.UpdatePodToleration | fwk.UpdatePodSchedulingGatesEliminated | fwk.Delete,
				fwk.Node:                  fwk.Add | fwk.UpdateNodeAllocatable | fwk.UpdateNodeLabel | fwk.UpdateNodeTaint | fwk.Delete,
				fwk.CSINode:               fwk.All - fwk.Delete,
				fwk.CSIDriver:             fwk.Update,
				fwk.CSIStorageCapacity:    fwk.All - fwk.Delete,
				fwk.PersistentVolume:      fwk.All - fwk.Delete,
				fwk.PersistentVolumeClaim: fwk.All - fwk.Delete,
				fwk.StorageClass:          fwk.All - fwk.Delete,
				fwk.VolumeAttachment:      fwk.Delete,
			},
			enableInPlacePodVerticalScaling: true,
			enableSchedulerQueueingHints:    true,
		},
		{
			name:    "plugins with default profile (DynamicResourceAllocation: enabled)",
			plugins: schedulerapi.PluginSet{Enabled: defaults.PluginsV1.MultiPoint.Enabled},
			want: map[fwk.EventResource]fwk.ActionType{
				fwk.Pod:                   fwk.Add | fwk.UpdatePodLabel | fwk.UpdatePodGeneratedResourceClaim | fwk.Delete,
				fwk.Node:                  fwk.Add | fwk.UpdateNodeAllocatable | fwk.UpdateNodeLabel | fwk.UpdateNodeTaint | fwk.Delete,
				fwk.CSINode:               fwk.All - fwk.Delete,
				fwk.CSIDriver:             fwk.Update,
				fwk.CSIStorageCapacity:    fwk.All - fwk.Delete,
				fwk.PersistentVolume:      fwk.All - fwk.Delete,
				fwk.PersistentVolumeClaim: fwk.All - fwk.Delete,
				fwk.StorageClass:          fwk.All - fwk.Delete,
				fwk.VolumeAttachment:      fwk.Delete,
				fwk.DeviceClass:           fwk.All - fwk.Delete,
				fwk.ResourceClaim:         fwk.All - fwk.Delete,
				fwk.ResourceSlice:         fwk.All - fwk.Delete,
			},
			enableDynamicResourceAllocation: true,
		},
		{
			name:    "plugins with default profile (queueingHint/DynamicResourceAllocation: enabled)",
			plugins: schedulerapi.PluginSet{Enabled: defaults.PluginsV1.MultiPoint.Enabled},
			want: map[fwk.EventResource]fwk.ActionType{
				fwk.Pod:                   fwk.Add | fwk.UpdatePodLabel | fwk.UpdatePodGeneratedResourceClaim | fwk.UpdatePodToleration | fwk.UpdatePodSchedulingGatesEliminated | fwk.Delete,
				fwk.Node:                  fwk.Add | fwk.UpdateNodeAllocatable | fwk.UpdateNodeLabel | fwk.UpdateNodeTaint | fwk.Delete,
				fwk.CSINode:               fwk.All - fwk.Delete,
				fwk.CSIDriver:             fwk.Update,
				fwk.CSIStorageCapacity:    fwk.All - fwk.Delete,
				fwk.PersistentVolume:      fwk.All - fwk.Delete,
				fwk.PersistentVolumeClaim: fwk.All - fwk.Delete,
				fwk.StorageClass:          fwk.All - fwk.Delete,
				fwk.VolumeAttachment:      fwk.Delete,
				fwk.DeviceClass:           fwk.All - fwk.Delete,
				fwk.ResourceClaim:         fwk.All - fwk.Delete,
				fwk.ResourceSlice:         fwk.All - fwk.Delete,
			},
			enableDynamicResourceAllocation: true,
			enableSchedulerQueueingHints:    true,
		},
		{
			name:    "plugins with default profile (NodeDeclaredFeatures: enabled)",
			plugins: defaults.PluginsV1.MultiPoint,
			want: map[fwk.EventResource]fwk.ActionType{
				// NodeDeclaredFeatures adds fwk.Update
				fwk.Pod: fwk.Add | fwk.UpdatePodLabel | fwk.UpdatePodGeneratedResourceClaim | fwk.UpdatePodToleration | fwk.UpdatePodSchedulingGatesEliminated | fwk.Delete | fwk.Update,
				// NodeDeclaredFeatures adds fwk.UpdateNodeDeclaredFeature
				fwk.Node:                  fwk.Add | fwk.UpdateNodeAllocatable | fwk.UpdateNodeLabel | fwk.UpdateNodeTaint | fwk.Delete | fwk.UpdateNodeDeclaredFeature,
				fwk.CSINode:               fwk.All - fwk.Delete,
				fwk.CSIDriver:             fwk.Update,
				fwk.CSIStorageCapacity:    fwk.All - fwk.Delete,
				fwk.PersistentVolume:      fwk.All - fwk.Delete,
				fwk.PersistentVolumeClaim: fwk.All - fwk.Delete,
				fwk.StorageClass:          fwk.All - fwk.Delete,
				fwk.VolumeAttachment:      fwk.Delete,
				fwk.DeviceClass:           fwk.All - fwk.Delete,
				fwk.ResourceClaim:         fwk.All - fwk.Delete,
				fwk.ResourceSlice:         fwk.All - fwk.Delete,
			},
			enableDynamicResourceAllocation: true,
			enableSchedulerQueueingHints:    true,
			enableNodeDeclaredFeatures:      true,
			enableInPlacePodVerticalScaling: true,
		},
		{
			name:    "plugins with default profile and GangScheduling",
			plugins: schedulerapi.PluginSet{Enabled: append(defaults.PluginsV1.MultiPoint.Enabled, schedulerapi.Plugin{Name: names.GangScheduling})},
			want: map[fwk.EventResource]fwk.ActionType{
				fwk.Pod:                   fwk.Add | fwk.UpdatePodLabel | fwk.UpdatePodScaleDown | fwk.UpdatePodGeneratedResourceClaim | fwk.UpdatePodToleration | fwk.UpdatePodSchedulingGatesEliminated | fwk.Delete,
				fwk.Node:                  fwk.Add | fwk.UpdateNodeAllocatable | fwk.UpdateNodeLabel | fwk.UpdateNodeTaint | fwk.Delete,
				fwk.CSINode:               fwk.All - fwk.Delete,
				fwk.CSIDriver:             fwk.Update,
				fwk.CSIStorageCapacity:    fwk.All - fwk.Delete,
				fwk.PersistentVolume:      fwk.All - fwk.Delete,
				fwk.PersistentVolumeClaim: fwk.All - fwk.Delete,
				fwk.StorageClass:          fwk.All - fwk.Delete,
				fwk.VolumeAttachment:      fwk.Delete,
				fwk.DeviceClass:           fwk.All - fwk.Delete,
				fwk.ResourceClaim:         fwk.All - fwk.Delete,
				fwk.ResourceSlice:         fwk.All - fwk.Delete,
				fwk.PodGroup:              fwk.Add,
			},
			enableGangScheduling:            true,
			enableInPlacePodVerticalScaling: true,
			enableDynamicResourceAllocation: true,
			enableSchedulerQueueingHints:    true,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			pluginConfig := defaults.PluginConfigsV1

			if !tt.enableSchedulerQueueingHints || !tt.enableDynamicResourceAllocation {
				// Set emulated version before setting other feature gates, since it can impact feature dependencies.
				featuregatetesting.SetFeatureGateEmulationVersionDuringTest(t, feature.DefaultFeatureGate, version.MustParse("1.33"))
			} else if !tt.enableInPlacePodVerticalScaling {
				// In place pod resize GA'd in 1.35. Set emulation version to 1.34 for tests that do not have the flag set
				featuregatetesting.SetFeatureGateEmulationVersionDuringTest(t, feature.DefaultFeatureGate, version.MustParse("1.34"))
				// DRADeviceBindingConditions is alpha in 1.34 (disabled by default).
				// Strip BindingTimeout from DynamicResources args to avoid validation failure.
				pluginConfig = slices.Clone(pluginConfig)
				for i := range pluginConfig {
					if pluginConfig[i].Name == "DynamicResources" {
						pluginConfig[i].Args = &schedulerapi.DynamicResourcesArgs{}
						break
					}
				}
			} else {
				featuregatetesting.SetFeatureGateDuringTest(t, feature.DefaultFeatureGate, features.NodeDeclaredFeatures, tt.enableNodeDeclaredFeatures)
				featuregatetesting.SetFeatureGatesDuringTest(t, feature.DefaultFeatureGate, featuregatetesting.FeatureOverrides{
					features.NodeDeclaredFeatures: tt.enableNodeDeclaredFeatures,
					features.GenericWorkload:      tt.enableGangScheduling,
					features.GangScheduling:       tt.enableGangScheduling,
				})
			}
			featuregatetesting.SetFeatureGatesDuringTest(t, feature.DefaultFeatureGate, featuregatetesting.FeatureOverrides{
				features.InPlacePodVerticalScaling: tt.enableInPlacePodVerticalScaling,
				features.DynamicResourceAllocation: tt.enableDynamicResourceAllocation,
			})
			if !tt.enableSchedulerQueueingHints {
				featuregatetesting.SetFeatureGateDuringTest(t, feature.DefaultFeatureGate, features.SchedulerQueueingHints, false)
				// The test uses defaults.PluginConfigsV1, which contains the filter timeout.
				// With emulation of 1.33, the DRASchedulerFilterTimeout feature gets disabled
				// and also cannot be enabled ("pre-alpha"), which makes the config invalid.
				// To avoid this, we have to patch the config.
				pluginConfig = slices.Clone(pluginConfig)
				for i := range pluginConfig {
					if pluginConfig[i].Name == "DynamicResources" {
						pluginConfig[i].Args = &schedulerapi.DynamicResourcesArgs{}
						break
					}
				}
			}

			_, ctx := ktesting.NewTestContext(t)
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()
			registry := plugins.NewInTreeRegistry()

			cfgPls := &schedulerapi.Plugins{MultiPoint: tt.plugins}
			plugins := []fwk.Plugin{&fakeNodePlugin{}, &fakePodPlugin{}, &filterWithoutEnqueueExtensionsPlugin{}, &emptyEventsToRegisterPlugin{}, &fakeQueueSortPlugin{}, &fakebindPlugin{}}
			for _, pl := range plugins {
				tmpPl := pl
				if err := registry.Register(pl.Name(), func(_ context.Context, _ runtime.Object, _ fwk.Handle) (fwk.Plugin, error) {
					return tmpPl, nil
				}); err != nil {
					t.Fatalf("fail to register filter plugin (%s)", pl.Name())
				}
			}

			profile := schedulerapi.KubeSchedulerProfile{Plugins: cfgPls, PluginConfig: pluginConfig}
			fwk, err := newFramework(ctx, registry, profile)
			if err != nil {
				t.Fatal(err)
			}
			queueingHintMap, err := buildQueueingHintMap(ctx, fwk.EnqueueExtensions())
			if err != nil {
				t.Fatal(err)
			}
			queueingHintsPerProfile := internalqueue.QueueingHintMapPerProfile{
				"default": queueingHintMap,
			}
			got := unionedGVKs(queueingHintsPerProfile)

			if diff := cmp.Diff(tt.want, got); diff != "" {
				t.Errorf("Unexpected eventToPlugin map (-want,+got):%s", diff)
			}
		})
	}
}

func newFramework(ctx context.Context, r frameworkruntime.Registry, profile schedulerapi.KubeSchedulerProfile) (framework.Framework, error) {
	return frameworkruntime.NewFramework(ctx, r, &profile,
		frameworkruntime.WithSnapshotSharedLister(internalcache.NewSnapshot(nil, nil)),
		frameworkruntime.WithInformerFactory(informers.NewSharedInformerFactory(fake.NewClientset(), 0)),
	)
}

func TestFrameworkHandler_IterateOverWaitingPods(t *testing.T) {
	const (
		testSchedulerProfile1 = "test-scheduler-profile-1"
		testSchedulerProfile2 = "test-scheduler-profile-2"
		testSchedulerProfile3 = "test-scheduler-profile-3"
	)

	nodes := []runtime.Object{
		st.MakeNode().Name("node1").UID("node1").Obj(),
		st.MakeNode().Name("node2").UID("node2").Obj(),
		st.MakeNode().Name("node3").UID("node3").Obj(),
	}

	cases := []struct {
		name                        string
		profiles                    []schedulerapi.KubeSchedulerProfile
		waitSchedulingPods          []*v1.Pod
		expectPodNamesInWaitingPods []string
	}{
		{
			name: "pods with same profile are waiting on permit stage",
			profiles: []schedulerapi.KubeSchedulerProfile{
				{
					SchedulerName: testSchedulerProfile1,
					Plugins: &schedulerapi.Plugins{
						QueueSort: schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "PrioritySort"}}},
						Permit:    schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: fakePermit}}},
						Bind:      schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "DefaultBinder"}}},
					},
				},
			},
			waitSchedulingPods: []*v1.Pod{
				st.MakePod().Name("pod1").UID("pod1").SchedulerName(testSchedulerProfile1).Obj(),
				st.MakePod().Name("pod2").UID("pod2").SchedulerName(testSchedulerProfile1).Obj(),
				st.MakePod().Name("pod3").UID("pod3").SchedulerName(testSchedulerProfile1).Obj(),
			},
			expectPodNamesInWaitingPods: []string{"pod1", "pod2", "pod3"},
		},
		{
			name: "pods with different profiles are waiting on permit stage",
			profiles: []schedulerapi.KubeSchedulerProfile{
				{
					SchedulerName: testSchedulerProfile1,
					Plugins: &schedulerapi.Plugins{
						QueueSort: schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "PrioritySort"}}},
						Permit:    schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: fakePermit}}},
						Bind:      schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "DefaultBinder"}}},
					},
				},
				{
					SchedulerName: testSchedulerProfile2,
					Plugins: &schedulerapi.Plugins{
						QueueSort: schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "PrioritySort"}}},
						Permit:    schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: fakePermit}}},
						Bind:      schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "DefaultBinder"}}},
					},
				},
				{
					SchedulerName: testSchedulerProfile3,
					Plugins: &schedulerapi.Plugins{
						QueueSort: schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "PrioritySort"}}},
						Permit:    schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: fakePermit}}},
						Bind:      schedulerapi.PluginSet{Enabled: []schedulerapi.Plugin{{Name: "DefaultBinder"}}},
					},
				},
			},
			waitSchedulingPods: []*v1.Pod{
				st.MakePod().Name("pod1").UID("pod1").SchedulerName(testSchedulerProfile1).Obj(),
				st.MakePod().Name("pod2").UID("pod2").SchedulerName(testSchedulerProfile1).Obj(),
				st.MakePod().Name("pod3").UID("pod3").SchedulerName(testSchedulerProfile2).Obj(),
				st.MakePod().Name("pod4").UID("pod4").SchedulerName(testSchedulerProfile3).Obj(),
			},
			expectPodNamesInWaitingPods: []string{"pod1", "pod2", "pod3", "pod4"},
		},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			// Set up scheduler for the 3 nodes.
			objs := append([]runtime.Object{&v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ""}}}, nodes...)
			fakeClient := fake.NewClientset(objs...)
			informerFactory := informers.NewSharedInformerFactory(fakeClient, 0)
			eventBroadcaster := events.NewBroadcaster(&events.EventSinkImpl{Interface: fakeClient.EventsV1()})
			defer eventBroadcaster.Shutdown()

			eventRecorder := eventBroadcaster.NewRecorder(scheme.Scheme, fakePermit)

			outOfTreeRegistry := frameworkruntime.Registry{
				fakePermit: newFakePermitPlugin(eventRecorder),
			}

			tCtx := utiltesting.Init(t)

			scheduler, err := New(
				tCtx,
				fakeClient,
				informerFactory,
				nil,
				profile.NewRecorderFactory(eventBroadcaster),
				WithProfiles(tc.profiles...),
				WithFrameworkOutOfTreeRegistry(outOfTreeRegistry),
			)

			if err != nil {
				t.Fatalf("Failed to create scheduler: %v", err)
			}

			var wg sync.WaitGroup
			waitSchedulingPodNumber := len(tc.waitSchedulingPods)
			wg.Add(waitSchedulingPodNumber)
			stopFn, err := eventBroadcaster.StartEventWatcher(func(obj runtime.Object) {
				e, ok := obj.(*eventsv1.Event)
				if !ok || (e.Reason != podWaitingReason) {
					return
				}
				wg.Done()
			})
			if err != nil {
				t.Fatal(err)
			}
			defer stopFn()

			// Run scheduler.
			informerFactory.Start(tCtx.Done())
			informerFactory.WaitForCacheSync(tCtx.Done())
			go scheduler.Run(tCtx)

			// Send pods to be scheduled.
			for _, p := range tc.waitSchedulingPods {
				_, err = fakeClient.CoreV1().Pods("").Create(tCtx, p, metav1.CreateOptions{})
				if err != nil {
					t.Fatal(err)
				}
			}

			// Wait all pods in waitSchedulingPods to be scheduled.
			wg.Wait()

			tCtx.Eventually(func(utiltesting.TContext) sets.Set[string] {
				// Ensure that all waitingPods in scheduler can be obtained from any profiles.
				actualPodNamesInWaitingPods := sets.New[string]()
				for _, schedFramework := range scheduler.Profiles {
					schedFramework.IterateOverWaitingPods(func(pod fwk.WaitingPod) {
						actualPodNamesInWaitingPods.Insert(pod.GetPod().Name)
					})
				}
				return actualPodNamesInWaitingPods
			}).WithTimeout(permitTimeout).Should(gomega.Equal(sets.New(tc.expectPodNamesInWaitingPods...)), "unexpected waitingPods in scheduler profile")
		})
	}
}

var _ fwk.QueueSortPlugin = &fakeQueueSortPlugin{}

// fakeQueueSortPlugin is a no-op implementation for QueueSort extension point.
type fakeQueueSortPlugin struct{}

func (pl *fakeQueueSortPlugin) Name() string {
	return queueSort
}

func (pl *fakeQueueSortPlugin) Less(_, _ fwk.QueuedPodInfo) bool {
	return false
}

var _ fwk.BindPlugin = &fakebindPlugin{}

// fakebindPlugin is a no-op implementation for Bind extension point.
type fakebindPlugin struct{}

func (t *fakebindPlugin) Name() string {
	return fakeBind
}

func (t *fakebindPlugin) Bind(ctx context.Context, state fwk.CycleState, p *v1.Pod, nodeName string) *fwk.Status {
	return nil
}

// filterWithoutEnqueueExtensionsPlugin implements Filter, but doesn't implement EnqueueExtensions.
type filterWithoutEnqueueExtensionsPlugin struct{}

func (*filterWithoutEnqueueExtensionsPlugin) Name() string { return filterWithoutEnqueueExtensions }

func (*filterWithoutEnqueueExtensionsPlugin) Filter(_ context.Context, _ fwk.CycleState, _ *v1.Pod, _ fwk.NodeInfo) *fwk.Status {
	return nil
}

var hintFromFakeNode = fwk.QueueingHint(100)

type fakeNodePlugin struct{}

var fakeNodePluginQueueingFn = func(_ klog.Logger, _ *v1.Pod, _, _ interface{}) (fwk.QueueingHint, error) {
	return hintFromFakeNode, nil
}

func (*fakeNodePlugin) Name() string { return fakeNode }

func (*fakeNodePlugin) Filter(_ context.Context, _ fwk.CycleState, _ *v1.Pod, _ fwk.NodeInfo) *fwk.Status {
	return nil
}

func (pl *fakeNodePlugin) EventsToRegister(_ context.Context) ([]fwk.ClusterEventWithHint, error) {
	return []fwk.ClusterEventWithHint{
		{Event: fwk.ClusterEvent{Resource: fwk.Node, ActionType: fwk.Add}, QueueingHintFn: fakeNodePluginQueueingFn},
	}, nil
}

var hintFromFakePod = fwk.QueueingHint(101)

type fakePodPlugin struct{}

var fakePodPluginQueueingFn = func(_ klog.Logger, _ *v1.Pod, _, _ interface{}) (fwk.QueueingHint, error) {
	return hintFromFakePod, nil
}

func (*fakePodPlugin) Name() string { return fakePod }

func (*fakePodPlugin) Filter(_ context.Context, _ fwk.CycleState, _ *v1.Pod, _ fwk.NodeInfo) *fwk.Status {
	return nil
}

func (pl *fakePodPlugin) EventsToRegister(_ context.Context) ([]fwk.ClusterEventWithHint, error) {
	return []fwk.ClusterEventWithHint{
		{Event: fwk.ClusterEvent{Resource: fwk.Pod, ActionType: fwk.Add}, QueueingHintFn: fakePodPluginQueueingFn},
	}, nil
}

type emptyEventPlugin struct{}

func (*emptyEventPlugin) Name() string { return emptyEventExtensions }

func (*emptyEventPlugin) Filter(_ context.Context, _ fwk.CycleState, _ *v1.Pod, _ fwk.NodeInfo) *fwk.Status {
	return nil
}

func (pl *emptyEventPlugin) EventsToRegister(_ context.Context) ([]fwk.ClusterEventWithHint, error) {
	return nil, nil
}

// errorEventsToRegisterPlugin is a mock plugin that returns an error for EventsToRegister method
type errorEventsToRegisterPlugin struct{}

func (*errorEventsToRegisterPlugin) Name() string { return errorEventsToRegister }

func (*errorEventsToRegisterPlugin) Filter(_ context.Context, _ fwk.CycleState, _ *v1.Pod, _ fwk.NodeInfo) *fwk.Status {
	return nil
}

func (*errorEventsToRegisterPlugin) EventsToRegister(_ context.Context) ([]fwk.ClusterEventWithHint, error) {
	return nil, errors.New("mock error")
}

// emptyEventsToRegisterPlugin implement interface fwk.EnqueueExtensions, but returns nil from EventsToRegister.
// This can simulate a plugin registered at scheduler setup, but does nothing
// due to some disabled feature gate.
type emptyEventsToRegisterPlugin struct{}

func (*emptyEventsToRegisterPlugin) Name() string { return emptyEventsToRegister }

func (*emptyEventsToRegisterPlugin) Filter(_ context.Context, _ fwk.CycleState, _ *v1.Pod, _ fwk.NodeInfo) *fwk.Status {
	return nil
}

func (*emptyEventsToRegisterPlugin) EventsToRegister(_ context.Context) ([]fwk.ClusterEventWithHint, error) {
	return nil, nil
}

// fakePermitPlugin only implements PermitPlugin interface.
type fakePermitPlugin struct {
	eventRecorder events.EventRecorderLogger
}

func newFakePermitPlugin(eventRecorder events.EventRecorderLogger) frameworkruntime.PluginFactory {
	return func(ctx context.Context, configuration runtime.Object, f fwk.Handle) (fwk.Plugin, error) {
		pl := &fakePermitPlugin{
			eventRecorder: eventRecorder,
		}
		return pl, nil
	}
}

func (f fakePermitPlugin) Name() string {
	return fakePermit
}

const (
	podWaitingReason = "podWaiting"
	permitTimeout    = 10 * time.Second
)

func (f fakePermitPlugin) Permit(ctx context.Context, state fwk.CycleState, p *v1.Pod, nodeName string) (*fwk.Status, time.Duration) {
	defer func() {
		// Send event with podWaiting reason to broadcast this pod is already waiting in the permit stage.
		f.eventRecorder.WithLogger(klog.FromContext(ctx)).Eventf(p, nil, v1.EventTypeWarning, podWaitingReason, "", "")
	}()

	return fwk.NewStatus(fwk.Wait), permitTimeout
}

var _ fwk.PermitPlugin = &fakePermitPlugin{}

func TestNewInformerFactoryTrim(t *testing.T) {
	cs := fake.NewClientset()

	pd := &v1.Pod{ObjectMeta: metav1.ObjectMeta{
		Name:      "test",
		Namespace: "default",
		ManagedFields: []metav1.ManagedFieldsEntry{
			{
				Manager:    "update",
				Operation:  metav1.ManagedFieldsOperationApply,
				APIVersion: "apps/v1",
			},
		},
	}}
	require.NoError(t, cs.Tracker().Add(pd))

	informerFactory := NewInformerFactory(cs, 0)
	lister := informerFactory.Core().V1().Pods().Lister()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	informerFactory.Start(ctx.Done())
	informerFactory.WaitForCacheSync(ctx.Done())

	p, err := lister.Pods("default").Get("test")
	require.NoError(t, err)
	require.Empty(t, p.GetManagedFields(), "expected managedFields to be trimmed by the transform")
}
