dynamocomponentdeployment_controller_test.go 92.5 KB
Newer Older
1
2
/*
 * SPDX-FileCopyrightText: Copyright (c) 2022 Atalaya Tech. Inc
3
 * SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
5
6
7
8
9
10
11
12
13
14
15
16
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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.
17
 * Modifications Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES
18
19
20
21
22
 */

package controller

import (
23
	"context"
24
25
	"testing"

26
	configv1alpha1 "github.com/ai-dynamo/dynamo/deploy/operator/api/config/v1alpha1"
27
	"github.com/ai-dynamo/dynamo/deploy/operator/api/v1alpha1"
28
	"github.com/ai-dynamo/dynamo/deploy/operator/internal/checkpoint"
29
30
31
	commonconsts "github.com/ai-dynamo/dynamo/deploy/operator/internal/consts"
	"github.com/ai-dynamo/dynamo/deploy/operator/internal/controller_common"
	"github.com/ai-dynamo/dynamo/deploy/operator/internal/dynamo"
32
	gms "github.com/ai-dynamo/dynamo/deploy/operator/internal/gms"
33
	snapshotprotocol "github.com/ai-dynamo/dynamo/deploy/snapshot/protocol"
34
35
36
	"github.com/google/go-cmp/cmp"
	"github.com/onsi/gomega"
	"github.com/onsi/gomega/format"
37
	"github.com/stretchr/testify/require"
38
39
	istioNetworking "istio.io/api/networking/v1beta1"
	networkingv1beta1 "istio.io/client-go/pkg/apis/networking/v1beta1"
40
41
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
42
	networkingv1 "k8s.io/api/networking/v1"
43
	"k8s.io/apimachinery/pkg/api/resource"
44
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
45
	"k8s.io/apimachinery/pkg/util/intstr"
46
47
48
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/tools/record"
	"k8s.io/utils/ptr"
49
	ctrl "sigs.k8s.io/controller-runtime"
50
51
52
53
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/client/fake"
	leaderworkersetv1 "sigs.k8s.io/lws/api/leaderworkerset/v1"
	volcanov1beta1 "volcano.sh/apis/pkg/apis/scheduling/v1beta1"
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
)

func TestIsDeploymentReady(t *testing.T) {
	type args struct {
		deployment *appsv1.Deployment
	}
	tests := []struct {
		name string
		args args
		want bool
	}{
		{
			name: "deployment is nil",
			args: args{
				deployment: nil,
			},
			want: false,
		},
		{
			name: "not ready",
			args: args{
				deployment: &appsv1.Deployment{
					Spec: appsv1.DeploymentSpec{},
					Status: appsv1.DeploymentStatus{
						Conditions: []appsv1.DeploymentCondition{
							{
								Type:   appsv1.DeploymentAvailable,
								Status: corev1.ConditionFalse,
							},
						},
					},
				},
			},
			want: false,
		},
		{
			name: "not ready (paused)",
			args: args{
				deployment: &appsv1.Deployment{
					Spec: appsv1.DeploymentSpec{
						Paused: true,
					},
				},
			},
			want: false,
		},
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
		{
			name: "not ready (surging)",
			args: args{
				deployment: &appsv1.Deployment{
					ObjectMeta: metav1.ObjectMeta{
						Generation: 1,
					},
					Spec: appsv1.DeploymentSpec{
						Replicas: &[]int32{2}[0],
					},
					Status: appsv1.DeploymentStatus{
						ObservedGeneration: 1,
						UpdatedReplicas:    1,
						AvailableReplicas:  1,
						Replicas:           2,
					},
				},
			},
			want: false,
		},
120
121
122
123
124
125
126
127
128
129
130
131
132
133
		{
			name: "ready",
			args: args{
				deployment: &appsv1.Deployment{
					ObjectMeta: metav1.ObjectMeta{
						Generation: 1,
					},
					Spec: appsv1.DeploymentSpec{
						Replicas: &[]int32{1}[0],
					},
					Status: appsv1.DeploymentStatus{
						ObservedGeneration: 1,
						UpdatedReplicas:    1,
						AvailableReplicas:  1,
134
						Replicas:           1,
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
						Conditions: []appsv1.DeploymentCondition{
							{
								Type:   appsv1.DeploymentAvailable,
								Status: corev1.ConditionTrue,
							},
						},
					},
				},
			},
			want: true,
		},
		{
			name: "ready (no desired replicas)",
			args: args{
				deployment: &appsv1.Deployment{
					ObjectMeta: metav1.ObjectMeta{
						Generation: 1,
					},
					Spec: appsv1.DeploymentSpec{
						Replicas: &[]int32{0}[0],
					},
				},
			},
			want: true,
		},
		{
			name: "not ready (condition false)",
			args: args{
				deployment: &appsv1.Deployment{
					ObjectMeta: metav1.ObjectMeta{
						Generation: 1,
					},
					Spec: appsv1.DeploymentSpec{
						Replicas: &[]int32{1}[0],
					},
					Status: appsv1.DeploymentStatus{
						ObservedGeneration: 1,
						UpdatedReplicas:    1,
						AvailableReplicas:  1,
						Conditions: []appsv1.DeploymentCondition{
							{
								Type:   appsv1.DeploymentAvailable,
								Status: corev1.ConditionFalse,
							},
						},
					},
				},
			},
			want: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := IsDeploymentReady(tt.args.deployment); got != tt.want {
				t.Errorf("IsDeploymentReady() = %v, want %v", got, tt.want)
			}
		})
	}
}
194

195
func TestDynamoComponentDeploymentReconciler_generateIngress(t *testing.T) {
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
	type fields struct {
	}
	type args struct {
		ctx context.Context
		opt generateResourceOption
	}
	tests := []struct {
		name    string
		fields  fields
		args    args
		want    *networkingv1.Ingress
		want1   bool
		wantErr bool
	}{
		{
211
212
			name:   "generate ingress",
			fields: fields{},
213
214
215
			args: args{
				ctx: context.Background(),
				opt: generateResourceOption{
216
					dynamoComponentDeployment: &v1alpha1.DynamoComponentDeployment{
217
218
219
220
						ObjectMeta: metav1.ObjectMeta{
							Name:      "service1",
							Namespace: "default",
						},
221
222
						Spec: v1alpha1.DynamoComponentDeploymentSpec{
							DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
223
224
								ServiceName:     "service1",
								DynamoNamespace: &[]string{"default"}[0],
225
								Ingress: &v1alpha1.IngressSpec{
226
227
228
229
									Enabled:                    true,
									Host:                       "someservice",
									IngressControllerClassName: &[]string{"nginx"}[0],
									UseVirtualService:          false,
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
								},
							},
						},
					},
				},
			},
			want: &networkingv1.Ingress{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "service1",
					Namespace: "default",
				},
				Spec: networkingv1.IngressSpec{
					IngressClassName: &[]string{"nginx"}[0],
					Rules: []networkingv1.IngressRule{
						{
245
							Host: "someservice.local",
246
247
248
249
250
251
252
253
254
							IngressRuleValue: networkingv1.IngressRuleValue{
								HTTP: &networkingv1.HTTPIngressRuleValue{
									Paths: []networkingv1.HTTPIngressPath{
										{
											Path:     "/",
											PathType: &[]networkingv1.PathType{networkingv1.PathTypePrefix}[0],
											Backend: networkingv1.IngressBackend{
												Service: &networkingv1.IngressServiceBackend{
													Name: "service1",
255
													Port: networkingv1.ServiceBackendPort{Number: commonconsts.DynamoServicePort},
256
257
258
259
260
261
262
263
264
265
266
267
268
269
												},
											},
										},
									},
								},
							},
						},
					},
				},
			},
			want1:   false,
			wantErr: false,
		},
		{
270
271
			name:   "generate ingress, disabled",
			fields: fields{},
272
273
274
			args: args{
				ctx: context.Background(),
				opt: generateResourceOption{
275
					dynamoComponentDeployment: &v1alpha1.DynamoComponentDeployment{
276
277
278
279
						ObjectMeta: metav1.ObjectMeta{
							Name:      "service1",
							Namespace: "default",
						},
280
281
						Spec: v1alpha1.DynamoComponentDeploymentSpec{
							DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
282
283
								ServiceName:     "service1",
								DynamoNamespace: &[]string{"default"}[0],
284
								Ingress: &v1alpha1.IngressSpec{
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
									Enabled: false,
								},
							},
						},
					},
				},
			},
			want: &networkingv1.Ingress{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "service1",
					Namespace: "default",
				},
			},
			want1:   true,
			wantErr: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			g := gomega.NewGomegaWithT(t)
305
			r := &DynamoComponentDeploymentReconciler{}
306
307
			got, got1, err := r.generateIngress(tt.args.ctx, tt.args.opt)
			if (err != nil) != tt.wantErr {
308
				t.Errorf("DynamoComponentDeploymentReconciler.generateIngress() error = %v, wantErr %v", err, tt.wantErr)
309
310
311
312
313
314
315
316
				return
			}
			g.Expect(got).To(gomega.Equal(tt.want))
			g.Expect(got1).To(gomega.Equal(tt.want1))
		})
	}
}

317
func TestDynamoComponentDeploymentReconciler_generateVirtualService(t *testing.T) {
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
	type fields struct {
	}
	type args struct {
		ctx context.Context
		opt generateResourceOption
	}
	tests := []struct {
		name    string
		fields  fields
		args    args
		want    *networkingv1beta1.VirtualService
		want1   bool
		wantErr bool
	}{
		{
333
334
			name:   "generate virtual service, disabled in operator config",
			fields: fields{},
335
336
337
			args: args{
				ctx: context.Background(),
				opt: generateResourceOption{
338
					dynamoComponentDeployment: &v1alpha1.DynamoComponentDeployment{
339
340
341
342
						ObjectMeta: metav1.ObjectMeta{
							Name:      "service1",
							Namespace: "default",
						},
343
344
						Spec: v1alpha1.DynamoComponentDeploymentSpec{
							DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
345
346
								ServiceName:     "service1",
								DynamoNamespace: &[]string{"default"}[0],
347
								Ingress: &v1alpha1.IngressSpec{
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
									Enabled: true,
								},
							},
						},
					},
				},
			},
			want: &networkingv1beta1.VirtualService{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "service1",
					Namespace: "default",
				},
			},
			want1:   true,
			wantErr: false,
		},
		{
365
366
			name:   "generate virtual service, enabled in operator config",
			fields: fields{},
367
368
369
			args: args{
				ctx: context.Background(),
				opt: generateResourceOption{
370
					dynamoComponentDeployment: &v1alpha1.DynamoComponentDeployment{
371
372
373
374
						ObjectMeta: metav1.ObjectMeta{
							Name:      "service1",
							Namespace: "default",
						},
375
376
						Spec: v1alpha1.DynamoComponentDeploymentSpec{
							DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
377
378
								ServiceName:     "service1",
								DynamoNamespace: &[]string{"default"}[0],
379
								Ingress: &v1alpha1.IngressSpec{
380
381
382
383
									Enabled:               true,
									Host:                  "someservice",
									UseVirtualService:     true,
									VirtualServiceGateway: &[]string{"istio-system/ingress-alb"}[0],
384
385
386
387
388
389
390
391
392
393
394
395
								},
							},
						},
					},
				},
			},
			want: &networkingv1beta1.VirtualService{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "service1",
					Namespace: "default",
				},
				Spec: istioNetworking.VirtualService{
396
					Hosts:    []string{"someservice.local"},
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
					Gateways: []string{"istio-system/ingress-alb"},
					Http: []*istioNetworking.HTTPRoute{
						{
							Match: []*istioNetworking.HTTPMatchRequest{
								{
									Uri: &istioNetworking.StringMatch{
										MatchType: &istioNetworking.StringMatch_Prefix{Prefix: "/"},
									},
								},
							},
							Route: []*istioNetworking.HTTPRouteDestination{
								{
									Destination: &istioNetworking.Destination{
										Host: "service1",
										Port: &istioNetworking.PortSelector{
412
											Number: commonconsts.DynamoServicePort,
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
										},
									},
								},
							},
						},
					},
				},
			},
			want1:   false,
			wantErr: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			g := gomega.NewGomegaWithT(t)
428
			r := &DynamoComponentDeploymentReconciler{}
429
430
			got, got1, err := r.generateVirtualService(tt.args.ctx, tt.args.opt)
			if (err != nil) != tt.wantErr {
431
				t.Errorf("DynamoComponentDeploymentReconciler.generateVirtualService() error = %v, wantErr %v", err, tt.wantErr)
432
433
434
435
436
437
438
				return
			}
			g.Expect(got).To(gomega.Equal(tt.want))
			g.Expect(got1).To(gomega.Equal(tt.want1))
		})
	}
}
439
440
441

func TestDynamoComponentDeploymentReconciler_generateVolcanoPodGroup(t *testing.T) {
	type fields struct {
442
443
		Client   client.Client
		Recorder record.EventRecorder
444
		Config   *configv1alpha1.OperatorConfiguration
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
	}
	type args struct {
		ctx context.Context
		opt generateResourceOption
	}
	tests := []struct {
		name    string
		fields  fields
		args    args
		want    *volcanov1beta1.PodGroup
		want1   bool
		wantErr bool
	}{
		{
			name: "generate volcano pod group",
			args: args{
				ctx: context.Background(),
				opt: generateResourceOption{
					dynamoComponentDeployment: &v1alpha1.DynamoComponentDeployment{
						ObjectMeta: metav1.ObjectMeta{
							Name:      "service1",
							Namespace: "default",
						},
						Spec: v1alpha1.DynamoComponentDeploymentSpec{
							DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
470
471
472
								Multinode: &v1alpha1.MultinodeSpec{
									NodeCount: 2,
								},
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
								ServiceName:     "service1",
								DynamoNamespace: &[]string{"default"}[0],
							},
						},
					},
					instanceID: ptr.To(5),
				},
			},
			want: &volcanov1beta1.PodGroup{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "service1-5",
					Namespace: "default",
					Labels: map[string]string{
						"instance-id": "5",
					},
				},
				Spec: volcanov1beta1.PodGroupSpec{
					MinMember: 2,
				},
			},
			want1:   false,
			wantErr: false,
		},
		{
			name: "nil instanceID",
			args: args{
				ctx: context.Background(),
				opt: generateResourceOption{
					dynamoComponentDeployment: &v1alpha1.DynamoComponentDeployment{
						ObjectMeta: metav1.ObjectMeta{
							Name:      "service-nil-instanceid",
							Namespace: "default",
						},
						Spec: v1alpha1.DynamoComponentDeploymentSpec{
							DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
								ServiceName:     "service-nil-instanceid",
								DynamoNamespace: &[]string{"default"}[0],
510
511
								Multinode: &v1alpha1.MultinodeSpec{
									NodeCount: 2,
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
								},
							},
						},
					},
					instanceID: nil,
				},
			},
			want:    nil,
			want1:   false,
			wantErr: true,
		},
		{
			name: "negative instanceID",
			args: args{
				ctx: context.Background(),
				opt: generateResourceOption{
					dynamoComponentDeployment: &v1alpha1.DynamoComponentDeployment{
						ObjectMeta: metav1.ObjectMeta{
							Name:      "service-negative-instanceid",
							Namespace: "default",
						},
						Spec: v1alpha1.DynamoComponentDeploymentSpec{
							DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
								ServiceName:     "service-negative-instanceid",
								DynamoNamespace: &[]string{"default"}[0],
537
538
								Multinode: &v1alpha1.MultinodeSpec{
									NodeCount: 2,
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
								},
							},
						},
					},
					instanceID: ptr.To(-1),
				},
			},
			want:    nil,
			want1:   false,
			wantErr: true,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			g := gomega.NewGomegaWithT(t)
			r := &DynamoComponentDeploymentReconciler{
555
556
557
				Client:   tt.fields.Client,
				Recorder: tt.fields.Recorder,
				Config:   tt.fields.Config,
558
559
560
561
562
563
			}
			got, got1, err := r.generateVolcanoPodGroup(tt.args.ctx, tt.args.opt)
			if (err != nil) != tt.wantErr {
				t.Errorf("DynamoComponentDeploymentReconciler.generateVolcanoPodGroup() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
564
565
566
			if diff := cmp.Diff(tt.want, got); diff != "" {
				t.Errorf("Mismatch (-expected +actual):\n%s", diff)
			}
567
568
569
570
571
572
			g.Expect(got).To(gomega.Equal(tt.want))
			g.Expect(got1).To(gomega.Equal(tt.want1))
		})
	}
}

573
574
575
576
577
578
579
580
type mockDockerSecretRetriever struct {
	GetSecretsFunc func(namespace, imageName string) ([]string, error)
}

func (m *mockDockerSecretRetriever) GetSecrets(namespace, imageName string) ([]string, error) {
	return m.GetSecretsFunc(namespace, imageName)
}

581
582
583
584
func TestDynamoComponentDeploymentReconciler_generateLeaderWorkerSet(t *testing.T) {
	var limit = ptr.To(resource.MustParse("250Mi"))
	limit.SetMilli(ptr.To(resource.MustParse("1Gi")).MilliValue() / 2)
	type fields struct {
585
586
		Client                client.Client
		Recorder              record.EventRecorder
587
588
		Config                *configv1alpha1.OperatorConfiguration
		RuntimeConfig         *controller_common.RuntimeConfig
589
		DockerSecretRetriever *mockDockerSecretRetriever
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
	}
	type args struct {
		ctx context.Context
		opt generateResourceOption
		// Add expected ServiceAccountName if you want to verify it's picked up
		// For now, we'll ensure a default one exists for the happy path
		mockServiceAccounts []client.Object
	}
	tests := []struct {
		name    string
		fields  fields
		args    args
		want    *leaderworkersetv1.LeaderWorkerSet
		want1   bool // toDelete
		wantErr bool
	}{
		{
			name: "generateLeaderWorkerSet - nominal case",
			fields: fields{
609
610
611
				Recorder:      record.NewFakeRecorder(100),
				Config:        &configv1alpha1.OperatorConfiguration{},
				RuntimeConfig: &controller_common.RuntimeConfig{},
612
613
614
615
616
				DockerSecretRetriever: &mockDockerSecretRetriever{
					GetSecretsFunc: func(namespace, imageName string) ([]string, error) {
						return []string{}, nil
					},
				},
617
618
619
620
621
622
623
624
			},
			args: args{
				ctx: context.Background(),
				opt: generateResourceOption{
					dynamoComponentDeployment: &v1alpha1.DynamoComponentDeployment{
						ObjectMeta: metav1.ObjectMeta{
							Name:      "test-lws-deploy",
							Namespace: "default",
625
626
627
628
629
630
							OwnerReferences: []metav1.OwnerReference{
								{
									Kind: "DynamoGraphDeployment",
									Name: "test-lws-deploy",
								},
							},
631
632
						},
						Spec: v1alpha1.DynamoComponentDeploymentSpec{
633
							BackendFramework: string(dynamo.BackendFrameworkVLLM),
634
							DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
635
636
637
638
639
640
								Envs: []corev1.EnvVar{
									{
										Name:  "TEST_ENV_FROM_DYNAMO_COMPONENT_DEPLOYMENT_SPEC",
										Value: "test_value_from_dynamo_component_deployment_spec",
									},
								},
641
642
643
								ComponentType:    string(commonconsts.ComponentTypeWorker),
								SubComponentType: "test-sub-component",
								ServiceName:      "test-lws-deploy-service",
644
								DynamoNamespace:  &[]string{"default-test-lws-deploy"}[0],
645
646
								Multinode: &v1alpha1.MultinodeSpec{
									NodeCount: 2,
647
								},
648
649
								Resources: &v1alpha1.Resources{
									Requests: &v1alpha1.ResourceItem{
650
651
652
										CPU:    "300m",
										Memory: "500Mi",
									},
653
									Limits: &v1alpha1.ResourceItem{
654
655
656
										GPU:    "1",
										Memory: "20Gi",
										CPU:    "10",
657
658
									},
								},
659
								ExtraPodMetadata: &v1alpha1.ExtraPodMetadata{
660
661
662
663
664
665
666
									Annotations: map[string]string{
										"nvidia.com/annotation1": "annotation1",
									},
									Labels: map[string]string{
										"nvidia.com/label1": "label1",
									},
								},
667
								ExtraPodSpec: &v1alpha1.ExtraPodSpec{
668
669
									PodSpec: &corev1.PodSpec{
										TerminationGracePeriodSeconds: ptr.To(int64(10)),
670
671
672
673
674
										Containers: []corev1.Container{
											{
												Image: "another-image:latest",
											},
										},
675
									},
676
677
									MainContainer: &corev1.Container{
										Image: "test-image:latest",
678
										Command: []string{
679
680
681
											"some",
											"dynamo",
											"command",
682
683
										},
										Args: []string{
684
685
686
687
											"--tensor-parallel-size",
											"4",
											"--pipeline-parallel-size",
											"1",
688
										},
689
690
691
692
693
694
										Env: []corev1.EnvVar{
											{
												Name:  "TEST_ENV_FROM_EXTRA_POD_SPEC",
												Value: "test_value_from_extra_pod_spec",
											},
										},
695
696
									},
								},
697
698
699
700
701
702
703
704
705
706
707
708
							},
						},
					},
					instanceID: ptr.To(0),
				},
				// Define a mock ServiceAccount that should be found by r.List
				mockServiceAccounts: []client.Object{
					&corev1.ServiceAccount{
						ObjectMeta: metav1.ObjectMeta{
							Name:      "default-test-sa", // Name it will be resolved to
							Namespace: "default",         // Must match dynamoComponentDeployment.Namespace
							Labels: map[string]string{
709
								commonconsts.KubeLabelDynamoComponentPod: commonconsts.KubeLabelValueTrue,
710
711
712
713
714
715
716
717
718
719
							},
						},
					},
				},
			},
			want: &leaderworkersetv1.LeaderWorkerSet{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "test-lws-deploy-0",
					Namespace: "default",
					Labels: map[string]string{
720
						"instance-id": "0",
721
722
723
724
725
726
727
728
729
730
					},
				},
				Spec: leaderworkersetv1.LeaderWorkerSetSpec{
					Replicas:      ptr.To(int32(1)),
					StartupPolicy: leaderworkersetv1.LeaderCreatedStartupPolicy,
					LeaderWorkerTemplate: leaderworkersetv1.LeaderWorkerTemplate{
						Size: ptr.To(int32(2)),
						LeaderTemplate: &corev1.PodTemplateSpec{
							ObjectMeta: metav1.ObjectMeta{
								Labels: map[string]string{
731
732
733
734
735
									"instance-id":                                   "0",
									commonconsts.KubeLabelMetricsEnabled:            commonconsts.KubeLabelValueTrue,
									"role":                                          "leader",
									"nvidia.com/label1":                             "label1",
									commonconsts.KubeLabelDynamoNamespace:           "default-test-lws-deploy",
736
									commonconsts.KubeLabelDynamoComponentType:       commonconsts.ComponentTypeWorker,
737
									commonconsts.KubeLabelDynamoSubComponentType:    "test-sub-component",
738
									commonconsts.KubeLabelDynamoGraphDeploymentName: "",
739
740
741
								},
								Annotations: map[string]string{
									"scheduling.k8s.io/group-name": "test-lws-deploy-0",
742
									"nvidia.com/annotation1":       "annotation1",
743
744
745
								},
							},
							Spec: corev1.PodSpec{
746
747
								SchedulerName:                 "volcano",
								TerminationGracePeriodSeconds: ptr.To(int64(10)),
748
749
750
								SecurityContext: &corev1.PodSecurityContext{
									FSGroup: ptr.To(int64(commonconsts.DefaultSecurityContextFSGroup)),
								},
751
752
753
754
755
756
								Volumes: []corev1.Volume{
									{
										Name: "shared-memory",
										VolumeSource: corev1.VolumeSource{
											EmptyDir: &corev1.EmptyDirVolumeSource{
												Medium:    corev1.StorageMediumMemory,
757
												SizeLimit: func() *resource.Quantity { q := resource.MustParse(commonconsts.DefaultSharedMemorySize); return &q }(),
758
759
760
761
											},
										},
									},
								},
762
								RestartPolicy: corev1.RestartPolicyAlways,
763
764
								Containers: []corev1.Container{
									{
765
766
767
768
										Image: "another-image:latest",
									},
									{
										Name:    commonconsts.MainContainerName,
769
										Image:   "test-image:latest",
770
										Command: []string{"/bin/sh", "-c"},
771
										Args:    []string{"ray start --head --port=6379 && some dynamo command --tensor-parallel-size 4 --pipeline-parallel-size 1 --distributed-executor-backend ray"},
772
										Env: []corev1.EnvVar{
773
											{Name: "CONTAINER_NAME", Value: commonconsts.MainContainerName},
774
											{Name: commonconsts.DynamoComponentEnvVar, Value: commonconsts.ComponentTypeWorker},
775
											{Name: commonconsts.DynamoDiscoveryBackendEnvVar, Value: "kubernetes"},
776
											{Name: "DYN_HEALTH_CHECK_ENABLED", Value: "false"},
777
											{Name: commonconsts.DynamoNamespaceEnvVar, Value: "default-test-lws-deploy"},
778
779
											{Name: "DYN_PARENT_DGD_K8S_NAME", Value: "test-lws-deploy"},
											{Name: "DYN_PARENT_DGD_K8S_NAMESPACE", Value: "default"},
780
											{Name: "DYN_SYSTEM_ENABLED", Value: "true"},
781
											{Name: "DYN_SYSTEM_PORT", Value: "9090"},
782
											{Name: "DYN_SYSTEM_USE_ENDPOINT_HEALTH_STATUS", Value: "[\"generate\"]"},
783
784
785
											{Name: "NIXL_TELEMETRY_ENABLE", Value: "n"},
											{Name: "NIXL_TELEMETRY_EXPORTER", Value: "prometheus"},
											{Name: "NIXL_TELEMETRY_PROMETHEUS_PORT", Value: "19090"},
786
787
788
789
790
791
792
793
794
795
											{Name: "POD_NAME", ValueFrom: &corev1.EnvVarSource{
												FieldRef: &corev1.ObjectFieldSelector{
													FieldPath: "metadata.name",
												},
											}},
											{Name: "POD_NAMESPACE", ValueFrom: &corev1.EnvVarSource{
												FieldRef: &corev1.ObjectFieldSelector{
													FieldPath: "metadata.namespace",
												},
											}},
796
797
798
799
800
											{Name: "POD_UID", ValueFrom: &corev1.EnvVarSource{
												FieldRef: &corev1.ObjectFieldSelector{
													FieldPath: "metadata.uid",
												},
											}},
801
802
803
											{Name: "TEST_ENV_FROM_DYNAMO_COMPONENT_DEPLOYMENT_SPEC", Value: "test_value_from_dynamo_component_deployment_spec"},
											{Name: "TEST_ENV_FROM_EXTRA_POD_SPEC", Value: "test_value_from_extra_pod_spec"},
										},
804
805
806
807
										Ports: []corev1.ContainerPort{
											{
												Protocol: corev1.ProtocolTCP, Name: commonconsts.DynamoSystemPortName, ContainerPort: commonconsts.DynamoSystemPort,
											},
808
809
810
											{
												Protocol: corev1.ProtocolTCP, Name: commonconsts.DynamoNixlPortName, ContainerPort: commonconsts.DynamoNixlPort,
											},
811
										},
812
										VolumeMounts: []corev1.VolumeMount{
813
											{
814
												Name:      "shared-memory",
815
												MountPath: commonconsts.DefaultSharedMemoryMountPath,
816
											},
817
818
819
820
821
822
823
										},
										Resources: corev1.ResourceRequirements{
											Requests: corev1.ResourceList{
												corev1.ResourceCPU:    resource.MustParse("300m"),
												corev1.ResourceMemory: resource.MustParse("500Mi"),
											},
											Limits: corev1.ResourceList{
824
825
												corev1.ResourceMemory: resource.MustParse("20Gi"),
												corev1.ResourceCPU:    resource.MustParse("10"),
826
												corev1.ResourceName(commonconsts.KubeResourceGPUNvidia): resource.MustParse("1"),
827
828
											},
										},
829
830
831
832
833
834
835
										LivenessProbe: &corev1.Probe{
											ProbeHandler: corev1.ProbeHandler{
												HTTPGet: &corev1.HTTPGetAction{
													Path: "/live",
													Port: intstr.FromString(commonconsts.DynamoSystemPortName),
												},
											},
836
											TimeoutSeconds:   4,
837
838
839
840
841
842
843
844
845
846
847
											PeriodSeconds:    5,
											SuccessThreshold: 0,
											FailureThreshold: 1,
										},
										ReadinessProbe: &corev1.Probe{
											ProbeHandler: corev1.ProbeHandler{
												HTTPGet: &corev1.HTTPGetAction{
													Path: "/health",
													Port: intstr.FromString(commonconsts.DynamoSystemPortName),
												},
											},
848
											TimeoutSeconds:   4,
849
850
											PeriodSeconds:    10,
											SuccessThreshold: 0,
851
											FailureThreshold: 3,
852
853
854
855
856
857
858
859
860
861
862
										},
										StartupProbe: &corev1.Probe{
											ProbeHandler: corev1.ProbeHandler{
												HTTPGet: &corev1.HTTPGetAction{
													Path: "/live",
													Port: intstr.FromString(commonconsts.DynamoSystemPortName),
												},
											},
											TimeoutSeconds:   5,
											PeriodSeconds:    10,
											SuccessThreshold: 0,
863
											FailureThreshold: 720,
864
										},
865
866
									},
								},
867
868
								ImagePullSecrets:   nil,               // Assuming default config gives empty secret name
								ServiceAccountName: "default-test-sa", // Updated to reflect mocked SA
869
870
871
872
873
							},
						},
						WorkerTemplate: corev1.PodTemplateSpec{
							ObjectMeta: metav1.ObjectMeta{
								Labels: map[string]string{
874
875
876
877
878
									"instance-id":                                   "0",
									commonconsts.KubeLabelMetricsEnabled:            commonconsts.KubeLabelValueTrue,
									"role":                                          "worker",
									"nvidia.com/label1":                             "label1",
									commonconsts.KubeLabelDynamoNamespace:           "default-test-lws-deploy",
879
									commonconsts.KubeLabelDynamoComponentType:       commonconsts.ComponentTypeWorker,
880
									commonconsts.KubeLabelDynamoSubComponentType:    "test-sub-component",
881
									commonconsts.KubeLabelDynamoGraphDeploymentName: "",
882
883
884
								},
								Annotations: map[string]string{
									"scheduling.k8s.io/group-name": "test-lws-deploy-0",
885
									"nvidia.com/annotation1":       "annotation1",
886
887
888
								},
							},
							Spec: corev1.PodSpec{
889
890
								TerminationGracePeriodSeconds: ptr.To(int64(10)),
								SchedulerName:                 "volcano",
891
892
893
								SecurityContext: &corev1.PodSecurityContext{
									FSGroup: ptr.To(int64(commonconsts.DefaultSecurityContextFSGroup)),
								},
894
895
896
897
898
899
								Volumes: []corev1.Volume{
									{
										Name: "shared-memory",
										VolumeSource: corev1.VolumeSource{
											EmptyDir: &corev1.EmptyDirVolumeSource{
												Medium:    corev1.StorageMediumMemory,
900
												SizeLimit: func() *resource.Quantity { q := resource.MustParse(commonconsts.DefaultSharedMemorySize); return &q }(),
901
902
903
904
											},
										},
									},
								},
905
								RestartPolicy: corev1.RestartPolicyAlways,
906
907
								Containers: []corev1.Container{
									{
908
909
910
911
										Image: "another-image:latest",
									},
									{
										Name:    commonconsts.MainContainerName,
912
										Image:   "test-image:latest",
913
										Command: []string{"/bin/sh", "-c"},
914
										Args:    []string{"ray start --address=$(LWS_LEADER_ADDRESS):6379 --block"},
915
										Env: []corev1.EnvVar{
916
											{Name: "CONTAINER_NAME", Value: commonconsts.MainContainerName},
917
											{Name: commonconsts.DynamoComponentEnvVar, Value: commonconsts.ComponentTypeWorker},
918
											{Name: commonconsts.DynamoDiscoveryBackendEnvVar, Value: "kubernetes"},
919
											{Name: "DYN_HEALTH_CHECK_ENABLED", Value: "false"},
920
											{Name: commonconsts.DynamoNamespaceEnvVar, Value: "default-test-lws-deploy"},
921
922
											{Name: "DYN_PARENT_DGD_K8S_NAME", Value: "test-lws-deploy"},
											{Name: "DYN_PARENT_DGD_K8S_NAMESPACE", Value: "default"},
923
											{Name: "DYN_SYSTEM_ENABLED", Value: "true"},
924
											{Name: "DYN_SYSTEM_PORT", Value: "9090"},
925
											{Name: "DYN_SYSTEM_USE_ENDPOINT_HEALTH_STATUS", Value: "[\"generate\"]"},
926
927
928
											{Name: "NIXL_TELEMETRY_ENABLE", Value: "n"},
											{Name: "NIXL_TELEMETRY_EXPORTER", Value: "prometheus"},
											{Name: "NIXL_TELEMETRY_PROMETHEUS_PORT", Value: "19090"},
929
930
931
932
933
934
935
936
937
938
											{Name: "POD_NAME", ValueFrom: &corev1.EnvVarSource{
												FieldRef: &corev1.ObjectFieldSelector{
													FieldPath: "metadata.name",
												},
											}},
											{Name: "POD_NAMESPACE", ValueFrom: &corev1.EnvVarSource{
												FieldRef: &corev1.ObjectFieldSelector{
													FieldPath: "metadata.namespace",
												},
											}},
939
940
941
942
943
											{Name: "POD_UID", ValueFrom: &corev1.EnvVarSource{
												FieldRef: &corev1.ObjectFieldSelector{
													FieldPath: "metadata.uid",
												},
											}},
944
945
946
											{Name: "TEST_ENV_FROM_DYNAMO_COMPONENT_DEPLOYMENT_SPEC", Value: "test_value_from_dynamo_component_deployment_spec"},
											{Name: "TEST_ENV_FROM_EXTRA_POD_SPEC", Value: "test_value_from_extra_pod_spec"},
										},
947
948
949
950
										Ports: []corev1.ContainerPort{
											{
												Protocol: corev1.ProtocolTCP, Name: commonconsts.DynamoSystemPortName, ContainerPort: commonconsts.DynamoSystemPort,
											},
951
952
953
											{
												Protocol: corev1.ProtocolTCP, Name: commonconsts.DynamoNixlPortName, ContainerPort: commonconsts.DynamoNixlPort,
											},
954
										},
955
										VolumeMounts: []corev1.VolumeMount{
956
											{
957
												Name:      "shared-memory",
958
												MountPath: commonconsts.DefaultSharedMemoryMountPath,
959
960
											},
										},
961
										Resources: corev1.ResourceRequirements{
962
963
964
965
966
											Limits: corev1.ResourceList{
												corev1.ResourceMemory: resource.MustParse("20Gi"),
												corev1.ResourceCPU:    resource.MustParse("10"),
												"nvidia.com/gpu":      resource.MustParse("1"),
											},
967
968
969
970
											Requests: corev1.ResourceList{
												corev1.ResourceCPU:    resource.MustParse("300m"),
												corev1.ResourceMemory: resource.MustParse("500Mi"),
											},
971
972
973
										},
									},
								},
974
								ImagePullSecrets:   nil,
975
976
977
978
979
980
981
982
983
984
985
986
								ServiceAccountName: "default-test-sa", // Updated to reflect mocked SA
							},
						},
					},
				},
			},
			want1:   false,
			wantErr: false,
		},
		{
			name: "nil instanceID", // This test should fail before r.List is called in generatePodTemplateSpec
			fields: fields{
987
988
989
990
991
992
993
994
				Recorder:      record.NewFakeRecorder(100),
				Config:        &configv1alpha1.OperatorConfiguration{},
				RuntimeConfig: &controller_common.RuntimeConfig{},
				DockerSecretRetriever: &mockDockerSecretRetriever{
					GetSecretsFunc: func(namespace, imageName string) ([]string, error) {
						return []string{}, nil
					},
				},
995
996
997
998
999
			},
			args: args{
				ctx: context.Background(),
				opt: generateResourceOption{
					dynamoComponentDeployment: &v1alpha1.DynamoComponentDeployment{
1000
						ObjectMeta: metav1.ObjectMeta{Name: "test-lws-nil-id", Namespace: "default"},
1001
1002
						Spec: v1alpha1.DynamoComponentDeploymentSpec{
							DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
1003
1004
1005
								Multinode: &v1alpha1.MultinodeSpec{
									NodeCount: 2,
								},
1006
1007
								Resources: &v1alpha1.Resources{
									Limits: &v1alpha1.ResourceItem{
1008
1009
1010
										GPU: "1",
									},
								},
1011
								ExtraPodSpec: &v1alpha1.ExtraPodSpec{
1012
1013
1014
1015
									MainContainer: &corev1.Container{
										Image: "test-image:latest",
									},
								},
1016
1017
1018
1019
1020
1021
1022
1023
1024
							},
						},
					},
					instanceID: nil,
				},
				mockServiceAccounts: []client.Object{ // Provide a default SA for consistency, though not strictly needed here
					&corev1.ServiceAccount{
						ObjectMeta: metav1.ObjectMeta{
							Name: "default-test-sa", Namespace: "default", // Match namespace
1025
							Labels: map[string]string{commonconsts.KubeLabelDynamoComponentPod: commonconsts.KubeLabelValueTrue},
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
						},
					},
				},
			},
			want:    nil,
			want1:   false,
			wantErr: true,
		},
		{
			name: "error from generateLeaderPodTemplateSpec", // This case involves an error from generatePodTemplateSpec
			fields: fields{
1037
1038
1039
1040
1041
1042
1043
1044
				Recorder:      record.NewFakeRecorder(100),
				Config:        &configv1alpha1.OperatorConfiguration{},
				RuntimeConfig: &controller_common.RuntimeConfig{},
				DockerSecretRetriever: &mockDockerSecretRetriever{
					GetSecretsFunc: func(namespace, imageName string) ([]string, error) {
						return []string{}, nil
					},
				},
1045
1046
1047
1048
1049
			},
			args: args{
				ctx: context.Background(),
				opt: generateResourceOption{
					dynamoComponentDeployment: &v1alpha1.DynamoComponentDeployment{
1050
						ObjectMeta: metav1.ObjectMeta{Name: "test-lws-leader-err", Namespace: "default"},
1051
1052
						Spec: v1alpha1.DynamoComponentDeploymentSpec{
							DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
1053
1054
1055
								Multinode: &v1alpha1.MultinodeSpec{
									NodeCount: 2,
								},
1056
1057
								Resources: &v1alpha1.Resources{
									Limits: &v1alpha1.ResourceItem{
1058
1059
1060
										GPU: "1",
									},
								},
1061
								ExtraPodSpec: &v1alpha1.ExtraPodSpec{
1062
1063
1064
1065
									MainContainer: &corev1.Container{
										Image: "", // Image is missing, will cause error in generatePodTemplateSpec
									},
								},
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
							},
						},
					},
					instanceID: ptr.To(0),
				},
				// No specific SA needed if error is before SA listing, but good to be consistent
				mockServiceAccounts: []client.Object{
					&corev1.ServiceAccount{
						ObjectMeta: metav1.ObjectMeta{
							Name: "default-test-sa", Namespace: "default", // Match namespace
1076
							Labels: map[string]string{commonconsts.KubeLabelDynamoComponentPod: commonconsts.KubeLabelValueTrue},
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
						},
					},
				},
			},
			want:    nil,
			want1:   false,
			wantErr: true,
		},
	}

	// Initialize scheme & add API types
	s := scheme.Scheme
	if err := v1alpha1.AddToScheme(s); err != nil {
		t.Fatalf("Failed to add v1alpha1 to scheme: %v", err)
	}
	if err := corev1.AddToScheme(s); err != nil {
		t.Fatalf("Failed to add corev1 to scheme: %v", err)
	}
	// Add LeaderWorkerSet to scheme if not already present globally for tests
	if err := leaderworkersetv1.AddToScheme(s); err != nil {
		t.Fatalf("Failed to add leaderworkersetv1 to scheme: %v", err)
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			format.MaxLength = 0
			g := gomega.NewGomegaWithT(t)

			// Build initial objects for fake client for this test case
			var initialClientObjects []client.Object
			if tt.args.opt.dynamoComponentDeployment != nil {
				initialClientObjects = append(initialClientObjects, tt.args.opt.dynamoComponentDeployment)
			}
			if len(tt.args.mockServiceAccounts) > 0 {
				initialClientObjects = append(initialClientObjects, tt.args.mockServiceAccounts...)
			}

			fakeKubeClient := fake.NewClientBuilder().
				WithScheme(s).
				WithObjects(initialClientObjects...).
				Build()

			r := &DynamoComponentDeploymentReconciler{
1120
1121
1122
				Client:                fakeKubeClient, // Use the fake client
				Recorder:              tt.fields.Recorder,
				Config:                tt.fields.Config,
1123
				RuntimeConfig:         tt.fields.RuntimeConfig,
1124
				DockerSecretRetriever: tt.fields.DockerSecretRetriever,
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
				// Scheme: s, // Pass scheme if reconciler uses it directly, often client uses it
			}
			got, got1, err := r.generateLeaderWorkerSet(tt.args.ctx, tt.args.opt)
			if (err != nil) != tt.wantErr {
				t.Errorf("DynamoComponentDeploymentReconciler.generateLeaderWorkerSet() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if diff := cmp.Diff(tt.want, got); diff != "" {
				t.Errorf("Mismatch (-expected +actual):\n%s", diff)
			}
			// Use gomega.Equal for deep comparison of complex structs
			g.Expect(got).To(gomega.BeEquivalentTo(tt.want))
			g.Expect(got1).To(gomega.BeEquivalentTo(tt.want1))
		})
	}
}
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187

func TestDynamoComponentDeploymentReconciler_createOrUpdateOrDeleteDeployments_ReplicaReconciliation(t *testing.T) {
	ctx := context.Background()
	g := gomega.NewGomegaWithT(t)

	// Create a scheme with necessary types
	s := scheme.Scheme
	err := v1alpha1.AddToScheme(s)
	if err != nil {
		t.Fatalf("Failed to add v1alpha1 to scheme: %v", err)
	}
	err = appsv1.AddToScheme(s)
	if err != nil {
		t.Fatalf("Failed to add appsv1 to scheme: %v", err)
	}
	err = corev1.AddToScheme(s)
	if err != nil {
		t.Fatalf("Failed to add corev1 to scheme: %v", err)
	}

	// Create DynamoComponentDeployment with 1 replica
	replicaCount := int32(1)
	dcd := &v1alpha1.DynamoComponentDeployment{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "test-component",
			Namespace: "default",
		},
		Spec: v1alpha1.DynamoComponentDeploymentSpec{
			BackendFramework: string(dynamo.BackendFrameworkVLLM),
			DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
				ServiceName:     "test-service",
				DynamoNamespace: ptr.To("default"),
				ComponentType:   string(commonconsts.ComponentTypeDecode),
				Replicas:        &replicaCount,
			},
		},
	}

	// Set up fake client with the DCD
	fakeKubeClient := fake.NewClientBuilder().
		WithScheme(s).
		WithObjects(dcd).
		Build()

	// Set up reconciler
	recorder := record.NewFakeRecorder(100)
	reconciler := &DynamoComponentDeploymentReconciler{
1188
1189
1190
1191
		Client:        fakeKubeClient,
		Recorder:      recorder,
		Config:        &configv1alpha1.OperatorConfiguration{},
		RuntimeConfig: &controller_common.RuntimeConfig{},
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
		DockerSecretRetriever: &mockDockerSecretRetriever{
			GetSecretsFunc: func(namespace, imageName string) ([]string, error) {
				return []string{}, nil
			},
		},
	}

	opt := generateResourceOption{
		dynamoComponentDeployment: dcd,
	}

	// Step 1: Create the deployment with 1 replica
	modified, deployment, err := reconciler.createOrUpdateOrDeleteDeployments(ctx, opt)
	g.Expect(err).NotTo(gomega.HaveOccurred())
	g.Expect(modified).To(gomega.BeTrue(), "Deployment should have been created")
	g.Expect(deployment).NotTo(gomega.BeNil())

	// Verify deployment was created with 1 replica
	deploymentName := "test-component"
	createdDeployment := &appsv1.Deployment{}
	err = fakeKubeClient.Get(ctx, client.ObjectKey{Name: deploymentName, Namespace: "default"}, createdDeployment)
	g.Expect(err).NotTo(gomega.HaveOccurred())
	g.Expect(createdDeployment.Spec.Replicas).NotTo(gomega.BeNil())
	g.Expect(*createdDeployment.Spec.Replicas).To(gomega.Equal(int32(1)), "Initial deployment should have 1 replica")

	// Step 2: Manually update the deployment to 2 replicas (simulating manual edit)
1218
1219
1220
1221
	// Note: Real Kubernetes API server increments generation on spec changes,
	// but the fake client doesn't, so we simulate it here.
	// The operator sets last-applied-generation=1 on create, so we need generation > 1
	// to trigger manual change detection.
1222
1223
	manualReplicaCount := int32(2)
	createdDeployment.Spec.Replicas = &manualReplicaCount
1224
	createdDeployment.Generation = 2 // Simulate K8s incrementing generation on spec change
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
	err = fakeKubeClient.Update(ctx, createdDeployment)
	g.Expect(err).NotTo(gomega.HaveOccurred())

	// Verify the manual update
	updatedDeployment := &appsv1.Deployment{}
	err = fakeKubeClient.Get(ctx, client.ObjectKey{Name: deploymentName, Namespace: "default"}, updatedDeployment)
	g.Expect(err).NotTo(gomega.HaveOccurred())
	g.Expect(updatedDeployment.Spec.Replicas).NotTo(gomega.BeNil())
	g.Expect(*updatedDeployment.Spec.Replicas).To(gomega.Equal(int32(2)), "Deployment should have been manually updated to 2 replicas")

	// Step 3: Call createOrUpdateOrDeleteDeployments again - it should reconcile back to 1 replica
	modified2, deployment2, err := reconciler.createOrUpdateOrDeleteDeployments(ctx, opt)
	g.Expect(err).NotTo(gomega.HaveOccurred())
	g.Expect(modified2).To(gomega.BeTrue(), "Deployment should have been updated to reconcile replica count")
	g.Expect(deployment2).NotTo(gomega.BeNil())

	// Step 4: Verify the deployment was reconciled back to 1 replica
	reconciledDeployment := &appsv1.Deployment{}
	err = fakeKubeClient.Get(ctx, client.ObjectKey{Name: deploymentName, Namespace: "default"}, reconciledDeployment)
	g.Expect(err).NotTo(gomega.HaveOccurred())
	g.Expect(reconciledDeployment.Spec.Replicas).NotTo(gomega.BeNil())
	g.Expect(*reconciledDeployment.Spec.Replicas).To(gomega.Equal(int32(1)), "Deployment should have been reconciled back to 1 replica")
1247
1248
1249
1250
1251
1252
1253
1254

	// Step 5: Call createOrUpdateOrDeleteDeployments again - it should not be modified
	modified3, deployment3, err := reconciler.createOrUpdateOrDeleteDeployments(ctx, opt)
	g.Expect(err).NotTo(gomega.HaveOccurred())
	g.Expect(modified3).To(gomega.BeFalse(), "Deployment should have been not modified")
	g.Expect(deployment3).NotTo(gomega.BeNil())
}

1255
func TestDynamoComponentDeploymentReconciler_generatePodTemplateSpec_RestoreLabels(t *testing.T) { //nolint:gocyclo
1256
1257
1258
1259
1260
1261
1262
	s := scheme.Scheme
	if err := v1alpha1.AddToScheme(s); err != nil {
		t.Fatalf("Failed to add v1alpha1 to scheme: %v", err)
	}
	if err := corev1.AddToScheme(s); err != nil {
		t.Fatalf("Failed to add corev1 to scheme: %v", err)
	}
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
	if err := appsv1.AddToScheme(s); err != nil {
		t.Fatalf("Failed to add appsv1 to scheme: %v", err)
	}

	snapshotAgentDaemonSet := &appsv1.DaemonSet{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "snapshot-agent",
			Namespace: "default",
			Labels: map[string]string{
				snapshotprotocol.SnapshotAgentLabelKey: snapshotprotocol.SnapshotAgentLabelValue,
			},
		},
		Spec: appsv1.DaemonSetSpec{
			Template: corev1.PodTemplateSpec{
				Spec: corev1.PodSpec{
					Containers: []corev1.Container{{
						Name: snapshotprotocol.SnapshotAgentContainerName,
						VolumeMounts: []corev1.VolumeMount{{
							Name:      "checkpoints",
							MountPath: "/checkpoints",
						}},
					}},
					Volumes: []corev1.Volume{{
						Name: "checkpoints",
						VolumeSource: corev1.VolumeSource{
							PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
								ClaimName: "snapshot-pvc",
							},
						},
					}},
				},
			},
		},
	}
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311

	makeDCD := func(checkpointRef string) *v1alpha1.DynamoComponentDeployment {
		return &v1alpha1.DynamoComponentDeployment{
			ObjectMeta: metav1.ObjectMeta{
				Name:      "test-worker",
				Namespace: "default",
			},
			Spec: v1alpha1.DynamoComponentDeploymentSpec{
				BackendFramework: string(dynamo.BackendFrameworkVLLM),
				DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
					ServiceName:     "worker",
					ComponentType:   commonconsts.ComponentTypeWorker,
					DynamoNamespace: ptr.To("default"),
					Labels: map[string]string{
						commonconsts.KubeLabelDynamoGraphDeploymentName: "test-dgd",
1312
						commonconsts.KubeLabelDynamoWorkerHash:          "workerhash",
1313
						snapshotprotocol.RestoreTargetLabel:             commonconsts.KubeLabelValueTrue,
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
					},
					Checkpoint: &v1alpha1.ServiceCheckpointConfig{
						Enabled:       true,
						CheckpointRef: &checkpointRef,
					},
					ExtraPodSpec: &v1alpha1.ExtraPodSpec{
						MainContainer: &corev1.Container{
							Name:    commonconsts.MainContainerName,
							Image:   "test-image:latest",
							Command: []string{"python3"},
							Args:    []string{"-m", "dynamo.vllm"},
						},
					},
				},
			},
		}
	}

	makeReconciler := func(objs ...client.Object) *DynamoComponentDeploymentReconciler {
1333
		objs = append(objs, snapshotAgentDaemonSet.DeepCopy())
1334
1335
1336
1337
1338
		return &DynamoComponentDeploymentReconciler{
			Client: fake.NewClientBuilder().
				WithScheme(s).
				WithObjects(objs...).
				Build(),
1339
1340
			Config: &configv1alpha1.OperatorConfiguration{
				Checkpoint: configv1alpha1.CheckpointConfiguration{
1341
1342
1343
1344
1345
1346
1347
					Enabled: true,
				},
			},
		}
	}

	t.Run("ready checkpoint adds explicit restore labels", func(t *testing.T) {
1348
1349
1350
1351
1352
		identity := v1alpha1.DynamoCheckpointIdentity{Model: "test-model", BackendFramework: "vllm"}
		checkpointName, err := checkpoint.ComputeIdentityHash(identity)
		if err != nil {
			t.Fatalf("ComputeIdentityHash failed: %v", err)
		}
1353
1354
1355
1356
1357
1358
		dcd := makeDCD(checkpointName)
		ckpt := &v1alpha1.DynamoCheckpoint{
			ObjectMeta: metav1.ObjectMeta{
				Name:      checkpointName,
				Namespace: "default",
			},
1359
			Spec: v1alpha1.DynamoCheckpointSpec{Identity: identity},
1360
			Status: v1alpha1.DynamoCheckpointStatus{
1361
				Phase: v1alpha1.DynamoCheckpointPhaseReady,
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
			},
		}

		r := makeReconciler(dcd, ckpt)
		podTemplateSpec, err := r.generatePodTemplateSpec(
			context.Background(),
			generateResourceOption{dynamoComponentDeployment: dcd},
			dynamo.RoleMain,
		)
		if err != nil {
			t.Fatalf("generatePodTemplateSpec failed: %v", err)
		}

1375
1376
		if got := podTemplateSpec.Labels[snapshotprotocol.RestoreTargetLabel]; got != commonconsts.KubeLabelValueTrue {
			t.Fatalf("expected %s label to be true, got %q", snapshotprotocol.RestoreTargetLabel, got)
1377
		}
1378
1379
		if got := podTemplateSpec.Labels[snapshotprotocol.CheckpointIDLabel]; got != checkpointName {
			t.Fatalf("expected %s to be checkpoint id, got %q", snapshotprotocol.CheckpointIDLabel, got)
1380
1381
1382
		}
	})

1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
	t.Run("ready gms checkpoint injects gms restore sidecars", func(t *testing.T) {
		identity := v1alpha1.DynamoCheckpointIdentity{Model: "test-model", BackendFramework: "vllm"}
		checkpointName, err := checkpoint.ComputeIdentityHash(identity)
		if err != nil {
			t.Fatalf("ComputeIdentityHash failed: %v", err)
		}
		dcd := makeDCD(checkpointName)
		dcd.Spec.ExtraPodSpec.MainContainer.Resources.Claims = []corev1.ResourceClaim{{Name: "gpu"}}
		ckpt := &v1alpha1.DynamoCheckpoint{
			ObjectMeta: metav1.ObjectMeta{
				Name:      checkpointName,
				Namespace: "default",
			},
			Spec: v1alpha1.DynamoCheckpointSpec{
				Identity:         identity,
				GPUMemoryService: &v1alpha1.GPUMemoryServiceSpec{Enabled: true},
			},
			Status: v1alpha1.DynamoCheckpointStatus{
				Phase: v1alpha1.DynamoCheckpointPhaseReady,
			},
		}

		r := makeReconciler(dcd, ckpt)
		podTemplateSpec, err := r.generatePodTemplateSpec(
			context.Background(),
			generateResourceOption{dynamoComponentDeployment: dcd},
			dynamo.RoleMain,
		)
		if err != nil {
			t.Fatalf("generatePodTemplateSpec failed: %v", err)
		}

		find := func(name string) *corev1.Container {
			for i := range podTemplateSpec.Spec.Containers {
				if podTemplateSpec.Spec.Containers[i].Name == name {
					return &podTemplateSpec.Spec.Containers[i]
				}
			}
			for i := range podTemplateSpec.Spec.InitContainers {
				if podTemplateSpec.Spec.InitContainers[i].Name == name {
					return &podTemplateSpec.Spec.InitContainers[i]
				}
			}
			return nil
		}

1429
		gmsServer := find(gms.ServerContainerName)
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
		require.NotNil(t, gmsServer)
		loader := find(checkpoint.GMSLoaderContainer)
		require.NotNil(t, loader)

		mounts := map[string]string{}
		for _, mount := range loader.VolumeMounts {
			mounts[mount.Name] = mount.MountPath
		}
		if got := mounts[snapshotprotocol.CheckpointVolumeName]; got != "/checkpoints" {
			t.Fatalf("expected gms loader checkpoint mount at /checkpoints, got %q", got)
		}
		if got := gmsServer.Command; len(got) != 3 || got[0] != "python3" || got[1] != "-m" || got[2] != "gpu_memory_service.cli.server" { //nolint:goconst
			t.Fatalf("expected weights server to run python module, got %#v", got)
		}
1444
1445
1446
		// Restore: gms-server and loader are init sidecars (restartPolicy=Always)
		if gmsServer.RestartPolicy == nil || *gmsServer.RestartPolicy != corev1.ContainerRestartPolicyAlways {
			t.Fatalf("expected restore gms-server to have RestartPolicy=Always, got %#v", gmsServer.RestartPolicy)
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
		}
		if gmsServer.StartupProbe != nil {
			t.Fatalf("expected restore gms-server to have no StartupProbe")
		}
		if got := loader.Command; len(got) != 3 || got[0] != "python3" || got[1] != "-m" || got[2] != "gpu_memory_service.cli.snapshot.loader" {
			t.Fatalf("expected loader to run python module, got %#v", got)
		}
	})

	t.Run("ready checkpoint rewrites only main when extra sidecars are present", func(t *testing.T) {
		identity := v1alpha1.DynamoCheckpointIdentity{Model: "test-model", BackendFramework: "vllm"}
		checkpointName, err := checkpoint.ComputeIdentityHash(identity)
		if err != nil {
			t.Fatalf("ComputeIdentityHash failed: %v", err)
		}
		dcd := makeDCD(checkpointName)
		dcd.Spec.ExtraPodSpec.PodSpec = &corev1.PodSpec{
			Containers: []corev1.Container{{
				Name:    "gms-loader",
				Image:   "sidecar:latest",
				Command: []string{"python3"},
				Args:    []string{"-m", "sidecar"},
			}},
		}
		ckpt := &v1alpha1.DynamoCheckpoint{
			ObjectMeta: metav1.ObjectMeta{
				Name:      checkpointName,
				Namespace: "default",
			},
			Spec: v1alpha1.DynamoCheckpointSpec{Identity: identity},
			Status: v1alpha1.DynamoCheckpointStatus{
				Phase: v1alpha1.DynamoCheckpointPhaseReady,
			},
		}

		r := makeReconciler(dcd, ckpt)
		podTemplateSpec, err := r.generatePodTemplateSpec(
			context.Background(),
			generateResourceOption{dynamoComponentDeployment: dcd},
			dynamo.RoleMain,
		)
		if err != nil {
			t.Fatalf("generatePodTemplateSpec failed: %v", err)
		}

1492
1493
1494
		// User's extra sidecar should remain in Containers, unchanged.
		// GMS loader is now an init sidecar, so the user's container stays
		// at Containers[0] and main at Containers[1].
1495
		if got := podTemplateSpec.Spec.Containers[0]; got.Name != "gms-loader" || len(got.Command) != 1 || got.Command[0] != "python3" {
1496
			t.Fatalf("expected user sidecar container to remain unchanged, got %#v", got)
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
		}
		if got := podTemplateSpec.Spec.Containers[1]; got.Name != commonconsts.MainContainerName || len(got.Command) != 2 || got.Command[0] != "sleep" || got.Command[1] != "infinity" {
			t.Fatalf("expected main container to be rewritten for restore, got %#v", got)
		}
		if podTemplateSpec.Spec.Containers[1].Args != nil {
			t.Fatalf("expected main container args to be cleared, got %#v", podTemplateSpec.Spec.Containers[1].Args)
		}
		if got := podTemplateSpec.Labels[snapshotprotocol.RestoreTargetLabel]; got != commonconsts.KubeLabelValueTrue {
			t.Fatalf("expected %s label to be true, got %q", snapshotprotocol.RestoreTargetLabel, got)
		}
	})

1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
	t.Run("operator reasserts restore identity labels after metadata merge", func(t *testing.T) {
		identity := v1alpha1.DynamoCheckpointIdentity{Model: "test-model", BackendFramework: "vllm"}
		checkpointName, err := checkpoint.ComputeIdentityHash(identity)
		if err != nil {
			t.Fatalf("ComputeIdentityHash failed: %v", err)
		}
		dcd := makeDCD(checkpointName)
		dcd.Spec.ExtraPodMetadata = &v1alpha1.ExtraPodMetadata{
			Labels: map[string]string{
				commonconsts.KubeLabelDynamoNamespace:           "wrong-namespace",
				commonconsts.KubeLabelDynamoComponentType:       commonconsts.ComponentTypeFrontend,
				commonconsts.KubeLabelDynamoGraphDeploymentName: "wrong-dgd",
				commonconsts.KubeLabelDynamoWorkerHash:          "wrong-hash",
			},
		}
		ckpt := &v1alpha1.DynamoCheckpoint{
			ObjectMeta: metav1.ObjectMeta{
				Name:      checkpointName,
				Namespace: "default",
			},
			Spec: v1alpha1.DynamoCheckpointSpec{Identity: identity},
			Status: v1alpha1.DynamoCheckpointStatus{
				Phase: v1alpha1.DynamoCheckpointPhaseReady,
			},
		}

		r := makeReconciler(dcd, ckpt)
		podTemplateSpec, err := r.generatePodTemplateSpec(
			context.Background(),
			generateResourceOption{dynamoComponentDeployment: dcd},
			dynamo.RoleMain,
		)
		if err != nil {
			t.Fatalf("generatePodTemplateSpec failed: %v", err)
		}

		if got := podTemplateSpec.Labels[commonconsts.KubeLabelDynamoNamespace]; got != defaultNamespace {
			t.Fatalf("expected %s label to be %q, got %q", commonconsts.KubeLabelDynamoNamespace, "default", got)
		}
		if got := podTemplateSpec.Labels[commonconsts.KubeLabelDynamoComponentType]; got != commonconsts.ComponentTypeWorker {
			t.Fatalf("expected %s label to be %q, got %q", commonconsts.KubeLabelDynamoComponentType, commonconsts.ComponentTypeWorker, got)
		}
		if got := podTemplateSpec.Labels[commonconsts.KubeLabelDynamoGraphDeploymentName]; got != "test-dgd" {
			t.Fatalf("expected %s label to be %q, got %q", commonconsts.KubeLabelDynamoGraphDeploymentName, "test-dgd", got)
		}
		if got := podTemplateSpec.Labels[commonconsts.KubeLabelDynamoWorkerHash]; got != "workerhash" {
			t.Fatalf("expected %s label to be %q, got %q", commonconsts.KubeLabelDynamoWorkerHash, "workerhash", got)
		}
	})

1559
	t.Run("non-ready checkpoint clears stale restore labels", func(t *testing.T) {
1560
1561
1562
1563
1564
		identity := v1alpha1.DynamoCheckpointIdentity{Model: "test-model", BackendFramework: "vllm"}
		checkpointName, err := checkpoint.ComputeIdentityHash(identity)
		if err != nil {
			t.Fatalf("ComputeIdentityHash failed: %v", err)
		}
1565
1566
1567
1568
1569
1570
		dcd := makeDCD(checkpointName)
		ckpt := &v1alpha1.DynamoCheckpoint{
			ObjectMeta: metav1.ObjectMeta{
				Name:      checkpointName,
				Namespace: "default",
			},
1571
			Spec: v1alpha1.DynamoCheckpointSpec{Identity: identity},
1572
			Status: v1alpha1.DynamoCheckpointStatus{
1573
				Phase: v1alpha1.DynamoCheckpointPhaseCreating,
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
			},
		}

		r := makeReconciler(dcd, ckpt)
		podTemplateSpec, err := r.generatePodTemplateSpec(
			context.Background(),
			generateResourceOption{dynamoComponentDeployment: dcd},
			dynamo.RoleMain,
		)
		if err != nil {
			t.Fatalf("generatePodTemplateSpec failed: %v", err)
		}

1587
1588
		if _, ok := podTemplateSpec.Labels[snapshotprotocol.RestoreTargetLabel]; ok {
			t.Fatalf("did not expect %s label when checkpoint is not ready", snapshotprotocol.RestoreTargetLabel)
1589
		}
1590
1591
		if _, ok := podTemplateSpec.Labels[snapshotprotocol.CheckpointIDLabel]; ok {
			t.Fatalf("did not expect %s label when checkpoint is not ready", snapshotprotocol.CheckpointIDLabel)
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
		}
	})
}

func TestDynamoComponentDeploymentReconciler_generateDeployment_RestoreStrategy(t *testing.T) {
	s := scheme.Scheme
	if err := v1alpha1.AddToScheme(s); err != nil {
		t.Fatalf("Failed to add v1alpha1 to scheme: %v", err)
	}
	if err := corev1.AddToScheme(s); err != nil {
		t.Fatalf("Failed to add corev1 to scheme: %v", err)
	}
	if err := appsv1.AddToScheme(s); err != nil {
		t.Fatalf("Failed to add appsv1 to scheme: %v", err)
	}

	replicas := int32(1)
	makeDCD := func(checkpointRef string) *v1alpha1.DynamoComponentDeployment {
		return &v1alpha1.DynamoComponentDeployment{
			ObjectMeta: metav1.ObjectMeta{
				Name:      "test-worker",
				Namespace: "default",
			},
			Spec: v1alpha1.DynamoComponentDeploymentSpec{
				BackendFramework: string(dynamo.BackendFrameworkVLLM),
				DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
					ServiceName:     "worker",
					ComponentType:   commonconsts.ComponentTypeWorker,
					DynamoNamespace: ptr.To("default"),
					Replicas:        &replicas,
					Labels: map[string]string{
						commonconsts.KubeLabelDynamoGraphDeploymentName: "test-dgd",
					},
					Checkpoint: &v1alpha1.ServiceCheckpointConfig{
						Enabled:       true,
						CheckpointRef: &checkpointRef,
					},
					ExtraPodSpec: &v1alpha1.ExtraPodSpec{
						MainContainer: &corev1.Container{
							Name:    commonconsts.MainContainerName,
							Image:   "test-image:latest",
							Command: []string{"python3"},
							Args:    []string{"-m", "dynamo.vllm"},
						},
					},
				},
			},
		}
	}

	makeReconciler := func(objs ...client.Object) *DynamoComponentDeploymentReconciler {
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
		objs = append(objs, &appsv1.DaemonSet{
			ObjectMeta: metav1.ObjectMeta{
				Name:      "snapshot-agent",
				Namespace: "default",
				Labels: map[string]string{
					snapshotprotocol.SnapshotAgentLabelKey: snapshotprotocol.SnapshotAgentLabelValue,
				},
			},
			Spec: appsv1.DaemonSetSpec{
				Template: corev1.PodTemplateSpec{
					Spec: corev1.PodSpec{
						Containers: []corev1.Container{{
							Name: snapshotprotocol.SnapshotAgentContainerName,
							VolumeMounts: []corev1.VolumeMount{{
								Name:      "checkpoints",
								MountPath: "/checkpoints",
							}},
						}},
						Volumes: []corev1.Volume{{
							Name: "checkpoints",
							VolumeSource: corev1.VolumeSource{
								PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
									ClaimName: "snapshot-pvc",
								},
							},
						}},
					},
				},
			},
		})
1673
1674
1675
1676
1677
		return &DynamoComponentDeploymentReconciler{
			Client: fake.NewClientBuilder().
				WithScheme(s).
				WithObjects(objs...).
				Build(),
1678
1679
			Config: &configv1alpha1.OperatorConfiguration{
				Checkpoint: configv1alpha1.CheckpointConfiguration{
1680
1681
1682
1683
1684
1685
					Enabled: true,
				},
			},
		}
	}

1686
1687
1688
1689
1690
	t.Run("ready checkpoint keeps RollingUpdate strategy", func(t *testing.T) {
		// Restore-target pods do not need a special Recreate override. The
		// default RollingUpdate strategy works for failure-replacement and
		// scale-up; users who specifically want Recreate on tight-GPU nodes
		// can still opt in via the nvidia.com/deployment-strategy annotation.
1691
1692
1693
1694
1695
		identity := v1alpha1.DynamoCheckpointIdentity{Model: "test-model", BackendFramework: "vllm"}
		checkpointName, err := checkpoint.ComputeIdentityHash(identity)
		if err != nil {
			t.Fatalf("ComputeIdentityHash failed: %v", err)
		}
1696
1697
1698
1699
1700
1701
		dcd := makeDCD(checkpointName)
		ckpt := &v1alpha1.DynamoCheckpoint{
			ObjectMeta: metav1.ObjectMeta{
				Name:      checkpointName,
				Namespace: "default",
			},
1702
			Spec: v1alpha1.DynamoCheckpointSpec{Identity: identity},
1703
			Status: v1alpha1.DynamoCheckpointStatus{
1704
				Phase: v1alpha1.DynamoCheckpointPhaseReady,
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
			},
		}

		r := makeReconciler(dcd, ckpt)
		deploy, toDelete, err := r.generateDeployment(context.Background(), generateResourceOption{
			dynamoComponentDeployment: dcd,
		})
		if err != nil {
			t.Fatalf("generateDeployment failed: %v", err)
		}
		if toDelete {
			t.Fatalf("expected deployment to be retained")
		}
1718
1719
		if deploy.Spec.Strategy.Type != appsv1.RollingUpdateDeploymentStrategyType {
			t.Fatalf("expected RollingUpdate strategy, got %s", deploy.Spec.Strategy.Type)
1720
1721
1722
1723
		}
	})

	t.Run("non-ready checkpoint keeps RollingUpdate strategy", func(t *testing.T) {
1724
1725
1726
1727
1728
		identity := v1alpha1.DynamoCheckpointIdentity{Model: "test-model", BackendFramework: "vllm"}
		checkpointName, err := checkpoint.ComputeIdentityHash(identity)
		if err != nil {
			t.Fatalf("ComputeIdentityHash failed: %v", err)
		}
1729
1730
1731
1732
1733
1734
		dcd := makeDCD(checkpointName)
		ckpt := &v1alpha1.DynamoCheckpoint{
			ObjectMeta: metav1.ObjectMeta{
				Name:      checkpointName,
				Namespace: "default",
			},
1735
			Spec: v1alpha1.DynamoCheckpointSpec{Identity: identity},
1736
			Status: v1alpha1.DynamoCheckpointStatus{
1737
				Phase: v1alpha1.DynamoCheckpointPhaseCreating,
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
			},
		}

		r := makeReconciler(dcd, ckpt)
		deploy, toDelete, err := r.generateDeployment(context.Background(), generateResourceOption{
			dynamoComponentDeployment: dcd,
		})
		if err != nil {
			t.Fatalf("generateDeployment failed: %v", err)
		}
		if toDelete {
			t.Fatalf("expected deployment to be retained")
		}
		if deploy.Spec.Strategy.Type != appsv1.RollingUpdateDeploymentStrategyType {
			t.Fatalf("expected RollingUpdate strategy, got %s", deploy.Spec.Strategy.Type)
		}
	})
}

1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
func Test_createOrUpdateOrDeleteDeployments_K8sAPIDefaults(t *testing.T) {
	g := gomega.NewGomegaWithT(t)
	ctx := context.Background()

	// Set up scheme
	s := scheme.Scheme
	err := v1alpha1.AddToScheme(s)
	g.Expect(err).NotTo(gomega.HaveOccurred())
	err = appsv1.AddToScheme(s)
	g.Expect(err).NotTo(gomega.HaveOccurred())
	err = corev1.AddToScheme(s)
	g.Expect(err).NotTo(gomega.HaveOccurred())

	name := "test-component"
	namespace := defaultNamespace

	// Create DynamoComponentDeployment
	replicaCount := int32(3)
	dcd := &v1alpha1.DynamoComponentDeployment{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: namespace,
		},
		Spec: v1alpha1.DynamoComponentDeploymentSpec{
			BackendFramework: string(dynamo.BackendFrameworkVLLM),
			DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
				ServiceName:     "test-service",
				DynamoNamespace: ptr.To("default"),
				ComponentType:   string(commonconsts.ComponentTypeDecode),
				Replicas:        &replicaCount,
			},
		},
	}

	fakeKubeClient := fake.NewClientBuilder().
		WithScheme(s).
		WithObjects(dcd).
		Build()

	recorder := record.NewFakeRecorder(100)
	reconciler := &DynamoComponentDeploymentReconciler{
1798
1799
1800
1801
		Client:        fakeKubeClient,
		Recorder:      recorder,
		Config:        &configv1alpha1.OperatorConfiguration{},
		RuntimeConfig: &controller_common.RuntimeConfig{},
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
		DockerSecretRetriever: &mockDockerSecretRetriever{
			GetSecretsFunc: func(namespace, imageName string) ([]string, error) {
				return []string{}, nil
			},
		},
	}

	opt := generateResourceOption{
		dynamoComponentDeployment: dcd,
	}

	t.Log("=== Step 1: Create deployment (operator's first apply) ===")

	modified1, deployment1, err := reconciler.createOrUpdateOrDeleteDeployments(ctx, opt)
	g.Expect(err).NotTo(gomega.HaveOccurred())
	g.Expect(modified1).To(gomega.BeTrue(), "First create should report as modified")
	g.Expect(deployment1).NotTo(gomega.BeNil())
	g.Expect(deployment1.Spec.RevisionHistoryLimit).To(gomega.BeNil())

	operatorCreatedDeployment := &appsv1.Deployment{}
	err = fakeKubeClient.Get(ctx, client.ObjectKey{Name: name, Namespace: namespace}, operatorCreatedDeployment)
	g.Expect(err).NotTo(gomega.HaveOccurred())
	g.Expect(*operatorCreatedDeployment.Spec.Replicas).To(gomega.Equal(replicaCount))

	annotations := operatorCreatedDeployment.GetAnnotations()
	g.Expect(annotations).NotTo(gomega.BeNil())
	originalHash, hasHash := annotations[controller_common.NvidiaAnnotationHashKey]
	g.Expect(hasHash).To(gomega.BeTrue(), "Hash annotation should be set")
	t.Logf("Hash annotation after create: %s", originalHash)

	t.Log("\n=== Step 2: Simulate K8s adding defaults ===")

	// Operator does not set RevisionHistoryLimit but the k8s API defaults to 10
	operatorCreatedDeployment.Spec.RevisionHistoryLimit = ptr.To(int32(10))
	err = fakeKubeClient.Update(ctx, operatorCreatedDeployment)
	g.Expect(err).NotTo(gomega.HaveOccurred())

	// The deployment should not be modified because the spec is the same
	modified2, deployment2, err := reconciler.createOrUpdateOrDeleteDeployments(ctx, opt)
	g.Expect(err).NotTo(gomega.HaveOccurred())
	g.Expect(modified2).To(gomega.BeFalse(), "Second create should report as not modified")
	g.Expect(deployment2).NotTo(gomega.BeNil())

	modified3, deployment3, err := reconciler.createOrUpdateOrDeleteDeployments(ctx, opt)
	g.Expect(err).NotTo(gomega.HaveOccurred())
	g.Expect(modified3).To(gomega.BeFalse(), "Third create should report as not modified")
	g.Expect(deployment3).NotTo(gomega.BeNil())
1849
}
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889

func Test_reconcileLeaderWorkerSetResources(t *testing.T) {
	ctx := context.Background()

	tests := []struct {
		name                         string
		replicas                     int32
		existingLeaderWorkerSets     []*leaderworkersetv1.LeaderWorkerSet
		wantComponentReconcileResult ComponentReconcileResult
	}{
		{
			name:     "singular LWS replica ready",
			replicas: 1,
			existingLeaderWorkerSets: []*leaderworkersetv1.LeaderWorkerSet{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name:      "test-component-0",
						Namespace: "default",
					},
					Spec: leaderworkersetv1.LeaderWorkerSetSpec{
						Replicas: ptr.To(int32(1)),
					},
					Status: leaderworkersetv1.LeaderWorkerSetStatus{
						ReadyReplicas:   1,
						UpdatedReplicas: 1,
						Replicas:        1,
						Conditions: []metav1.Condition{
							{
								Type:   string(leaderworkersetv1.LeaderWorkerSetAvailable),
								Status: metav1.ConditionTrue,
							},
						},
					},
				},
			},
			wantComponentReconcileResult: ComponentReconcileResult{
				modified: true,
				status:   metav1.ConditionTrue,
				reason:   "AllLeaderWorkerSetsReady",
				message:  "All LeaderWorkerSets are ready",
1890
				serviceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
1891
1892
					ComponentKind:   v1alpha1.ComponentKindLeaderWorkerSet,
					ComponentName:   "test-component-0",
1893
					ComponentNames:  []string{"test-component-0"},
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
					ReadyReplicas:   ptr.To(int32(1)),
					UpdatedReplicas: 1,
					Replicas:        1,
				},
			},
		},
		{
			name:     "multiple LWS replicas - at least one is unready",
			replicas: 3,
			existingLeaderWorkerSets: []*leaderworkersetv1.LeaderWorkerSet{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name:      "test-component-0",
						Namespace: "default",
					},
					Spec: leaderworkersetv1.LeaderWorkerSetSpec{
						Replicas: ptr.To(int32(1)),
					},
					Status: leaderworkersetv1.LeaderWorkerSetStatus{
						ReadyReplicas:   1,
						Replicas:        1,
						UpdatedReplicas: 1,
						Conditions: []metav1.Condition{
							{
								Type:   string(leaderworkersetv1.LeaderWorkerSetAvailable),
								Status: metav1.ConditionTrue,
							},
						},
					},
				},
				{
					ObjectMeta: metav1.ObjectMeta{
						Name:      "test-component-1",
						Namespace: "default",
					},
					Spec: leaderworkersetv1.LeaderWorkerSetSpec{
						Replicas: ptr.To(int32(1)),
					},
					Status: leaderworkersetv1.LeaderWorkerSetStatus{
						ReadyReplicas:   0, // Not ready
						Replicas:        1,
						UpdatedReplicas: 0,
						Conditions: []metav1.Condition{
							{
								Type:   string(leaderworkersetv1.LeaderWorkerSetAvailable),
								Status: metav1.ConditionFalse,
							},
						},
					},
				},
				{
					ObjectMeta: metav1.ObjectMeta{
						Name:      "test-component-2",
						Namespace: "default",
					},
					Spec: leaderworkersetv1.LeaderWorkerSetSpec{
						Replicas: ptr.To(int32(1)),
					},
					Status: leaderworkersetv1.LeaderWorkerSetStatus{
						ReadyReplicas:   1,
						Replicas:        1,
						UpdatedReplicas: 1,
						Conditions: []metav1.Condition{
							{
								Type:   string(leaderworkersetv1.LeaderWorkerSetAvailable),
								Status: metav1.ConditionTrue,
							},
						},
					},
				},
			},
			wantComponentReconcileResult: ComponentReconcileResult{
				modified: true,
				status:   metav1.ConditionFalse,
				reason:   "SomeLeaderWorkerSetsNotReady",
				message:  "Some LeaderWorkerSets are not ready",
1970
				serviceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
1971
1972
					ComponentKind:   v1alpha1.ComponentKindLeaderWorkerSet,
					ComponentName:   "test-component-0",
1973
					ComponentNames:  []string{"test-component-0", "test-component-1", "test-component-2"},
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
					ReadyReplicas:   ptr.To(int32(2)),
					UpdatedReplicas: 2,
					Replicas:        3,
				},
			},
		},
		{
			name:     "multiple LWS replicas - all ready",
			replicas: 3,
			existingLeaderWorkerSets: []*leaderworkersetv1.LeaderWorkerSet{
				{
					ObjectMeta: metav1.ObjectMeta{
						Name:      "test-component-0",
						Namespace: "default",
					},
					Spec: leaderworkersetv1.LeaderWorkerSetSpec{
						Replicas: ptr.To(int32(1)),
					},
					Status: leaderworkersetv1.LeaderWorkerSetStatus{
						ReadyReplicas:   1,
						Replicas:        1,
						UpdatedReplicas: 1,
						Conditions: []metav1.Condition{
							{
								Type:   string(leaderworkersetv1.LeaderWorkerSetAvailable),
								Status: metav1.ConditionTrue,
							},
						},
					},
				},
				{
					ObjectMeta: metav1.ObjectMeta{
						Name:      "test-component-1",
						Namespace: "default",
					},
					Spec: leaderworkersetv1.LeaderWorkerSetSpec{
						Replicas: ptr.To(int32(1)),
					},
					Status: leaderworkersetv1.LeaderWorkerSetStatus{
						ReadyReplicas:   1,
						Replicas:        1,
						UpdatedReplicas: 1,
						Conditions: []metav1.Condition{
							{
								Type:   string(leaderworkersetv1.LeaderWorkerSetAvailable),
								Status: metav1.ConditionTrue,
							},
						},
					},
				},
				{
					ObjectMeta: metav1.ObjectMeta{
						Name:      "test-component-2",
						Namespace: "default",
					},
					Spec: leaderworkersetv1.LeaderWorkerSetSpec{
						Replicas: ptr.To(int32(1)),
					},
					Status: leaderworkersetv1.LeaderWorkerSetStatus{
						ReadyReplicas:   1,
						Replicas:        1,
						UpdatedReplicas: 1,
						Conditions: []metav1.Condition{
							{
								Type:   string(leaderworkersetv1.LeaderWorkerSetAvailable),
								Status: metav1.ConditionTrue,
							},
						},
					},
				},
			},
			wantComponentReconcileResult: ComponentReconcileResult{
				modified: true,
				status:   metav1.ConditionTrue,
				reason:   "AllLeaderWorkerSetsReady",
				message:  "All LeaderWorkerSets are ready",
2050
				serviceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
2051
2052
					ComponentKind:   v1alpha1.ComponentKindLeaderWorkerSet,
					ComponentName:   "test-component-0",
2053
					ComponentNames:  []string{"test-component-0", "test-component-1", "test-component-2"},
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
					ReadyReplicas:   ptr.To(int32(3)),
					UpdatedReplicas: 3,
					Replicas:        3,
				},
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			g := gomega.NewGomegaWithT(t)

			// Create a scheme with necessary types
			s := scheme.Scheme
			err := v1alpha1.AddToScheme(s)
			g.Expect(err).NotTo(gomega.HaveOccurred())
			err = leaderworkersetv1.AddToScheme(s)
			g.Expect(err).NotTo(gomega.HaveOccurred())
			err = volcanov1beta1.AddToScheme(s)
			g.Expect(err).NotTo(gomega.HaveOccurred())

			// Create DynamoComponentDeployment
			dcd := &v1alpha1.DynamoComponentDeployment{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "test-component",
					Namespace: "default",
				},
				Spec: v1alpha1.DynamoComponentDeploymentSpec{
					BackendFramework: string(dynamo.BackendFrameworkVLLM),
					DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
						ServiceName:     "test-service",
						DynamoNamespace: ptr.To("default"),
						ComponentType:   string(commonconsts.ComponentTypeDecode),
						Replicas:        &tt.replicas,
						Multinode: &v1alpha1.MultinodeSpec{
							NodeCount: 2,
						},
						Resources: &v1alpha1.Resources{
							Limits: &v1alpha1.ResourceItem{
								GPU: "1",
							},
						},
						ExtraPodSpec: &v1alpha1.ExtraPodSpec{
							MainContainer: &corev1.Container{
								Image: "test-image:latest",
								Args: []string{
									"--test-arg",
								},
							},
						},
					},
				},
			}

			// Prepare objects for fake client
			var objects []client.Object
			objects = append(objects, dcd)
			for _, lws := range tt.existingLeaderWorkerSets {
				objects = append(objects, lws)
			}
			// Add a mock ServiceAccount that the generateLeaderWorkerSet function needs
			objects = append(objects, &corev1.ServiceAccount{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "default-test-sa",
					Namespace: "default",
					Labels: map[string]string{
						commonconsts.KubeLabelDynamoComponentPod: commonconsts.KubeLabelValueTrue,
					},
				},
			})

			// Set up fake client with the DCD and existing LWS objects
			fakeKubeClient := fake.NewClientBuilder().
				WithScheme(s).
				WithObjects(objects...).
				WithStatusSubresource(objects...).
				Build()

			// Set up reconciler
			recorder := record.NewFakeRecorder(100)
			reconciler := &DynamoComponentDeploymentReconciler{
2135
2136
2137
2138
				Client:        fakeKubeClient,
				Recorder:      recorder,
				Config:        &configv1alpha1.OperatorConfiguration{},
				RuntimeConfig: &controller_common.RuntimeConfig{},
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
				DockerSecretRetriever: &mockDockerSecretRetriever{
					GetSecretsFunc: func(namespace, imageName string) ([]string, error) {
						return []string{}, nil
					},
				},
			}

			// Call the function under test
			result, err := reconciler.reconcileLeaderWorkerSetResources(ctx, dcd)
			g.Expect(err).NotTo(gomega.HaveOccurred())

			// Assert the ComponentReconcileResult
			g.Expect(result).To(gomega.Equal(tt.wantComponentReconcileResult))
		})
	}
}

func Test_reconcileDeploymentResources(t *testing.T) {
	ctx := context.Background()

	tests := []struct {
		name                         string
		replicas                     int32
		existingDeployment           *appsv1.Deployment
		wantComponentReconcileResult ComponentReconcileResult
	}{
		{
			name:     "ready deployment",
			replicas: 2,
			existingDeployment: &appsv1.Deployment{
				ObjectMeta: metav1.ObjectMeta{
					Name:       "test-component",
					Namespace:  "default",
					Generation: 1,
				},
				Spec: appsv1.DeploymentSpec{
					Replicas: ptr.To(int32(2)),
				},
				Status: appsv1.DeploymentStatus{
					ObservedGeneration: 1,
					Replicas:           2,
					UpdatedReplicas:    2,
					ReadyReplicas:      2,
					AvailableReplicas:  2,
					Conditions: []appsv1.DeploymentCondition{
						{
							Type:   appsv1.DeploymentAvailable,
							Status: corev1.ConditionTrue,
						},
					},
				},
			},
			wantComponentReconcileResult: ComponentReconcileResult{
				modified: true,
				status:   metav1.ConditionTrue,
				reason:   "DeploymentReady",
				message:  "Deployment is ready",
2196
				serviceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
2197
2198
					ComponentKind:     v1alpha1.ComponentKindDeployment,
					ComponentName:     "test-component",
2199
					ComponentNames:    []string{"test-component"},
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
					Replicas:          2,
					UpdatedReplicas:   2,
					ReadyReplicas:     ptr.To(int32(2)),
					AvailableReplicas: ptr.To(int32(2)),
				},
			},
		},
		{
			name:     "unready deployment",
			replicas: 1,
			existingDeployment: &appsv1.Deployment{
				ObjectMeta: metav1.ObjectMeta{
					Name:       "test-component",
					Namespace:  "default",
					Generation: 1,
				},
				Spec: appsv1.DeploymentSpec{
					Replicas: ptr.To(int32(1)),
				},
				Status: appsv1.DeploymentStatus{
					ObservedGeneration: 1,
					Replicas:           1,
					UpdatedReplicas:    1,
					ReadyReplicas:      1,
					AvailableReplicas:  0, // Not available
					Conditions: []appsv1.DeploymentCondition{
						{
							Type:   appsv1.DeploymentAvailable,
							Status: corev1.ConditionFalse,
						},
					},
				},
			},
			wantComponentReconcileResult: ComponentReconcileResult{
				modified: true,
				status:   metav1.ConditionFalse,
				reason:   "DeploymentNotReady",
				message:  "Deployment is not ready",
2238
				serviceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
2239
2240
					ComponentKind:     v1alpha1.ComponentKindDeployment,
					ComponentName:     "test-component",
2241
					ComponentNames:    []string{"test-component"},
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
					Replicas:          1,
					UpdatedReplicas:   1,
					ReadyReplicas:     ptr.To(int32(1)),
					AvailableReplicas: ptr.To(int32(0)),
				},
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			g := gomega.NewGomegaWithT(t)

			// Create a scheme with necessary types
			s := scheme.Scheme
			err := v1alpha1.AddToScheme(s)
			g.Expect(err).NotTo(gomega.HaveOccurred())
			err = appsv1.AddToScheme(s)
			g.Expect(err).NotTo(gomega.HaveOccurred())
			err = corev1.AddToScheme(s)
			g.Expect(err).NotTo(gomega.HaveOccurred())

			// Create DynamoComponentDeployment
			dcd := &v1alpha1.DynamoComponentDeployment{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "test-component",
					Namespace: "default",
				},
				Spec: v1alpha1.DynamoComponentDeploymentSpec{
					BackendFramework: string(dynamo.BackendFrameworkVLLM),
					DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
						ServiceName:     "test-service",
						DynamoNamespace: ptr.To("default"),
						ComponentType:   string(commonconsts.ComponentTypeDecode),
						Replicas:        &tt.replicas,
						ExtraPodSpec: &v1alpha1.ExtraPodSpec{
							MainContainer: &corev1.Container{
								Image: "test-image:latest",
								Args: []string{
									"--test-arg",
								},
							},
						},
					},
				},
			}

			// Prepare objects for fake client
			var objects []client.Object
			objects = append(objects, dcd)
			if tt.existingDeployment != nil {
				objects = append(objects, tt.existingDeployment)
			}

			// Set up fake client with the DCD and existing Deployment
			fakeKubeClient := fake.NewClientBuilder().
				WithScheme(s).
				WithObjects(objects...).
				WithStatusSubresource(objects...).
				Build()

			// Set up reconciler
			recorder := record.NewFakeRecorder(100)
			reconciler := &DynamoComponentDeploymentReconciler{
2306
2307
2308
2309
				Client:        fakeKubeClient,
				Recorder:      recorder,
				Config:        &configv1alpha1.OperatorConfiguration{},
				RuntimeConfig: &controller_common.RuntimeConfig{},
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
				DockerSecretRetriever: &mockDockerSecretRetriever{
					GetSecretsFunc: func(namespace, imageName string) ([]string, error) {
						return []string{}, nil
					},
				},
			}

			// Call the function under test
			result, err := reconciler.reconcileDeploymentResources(ctx, dcd)
			g.Expect(err).NotTo(gomega.HaveOccurred())

			// Assert the ComponentReconcileResult
			g.Expect(result).To(gomega.Equal(tt.wantComponentReconcileResult))
		})
	}
}

2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
func Test_reconcileDeploymentResources_DoesNotRecycleFailedRestorePods(t *testing.T) {
	ctx := context.Background()
	g := gomega.NewGomegaWithT(t)

	s := scheme.Scheme
	g.Expect(v1alpha1.AddToScheme(s)).To(gomega.Succeed())
	g.Expect(appsv1.AddToScheme(s)).To(gomega.Succeed())
	g.Expect(corev1.AddToScheme(s)).To(gomega.Succeed())

	replicas := int32(1)
	dcd := &v1alpha1.DynamoComponentDeployment{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "test-component",
			Namespace: "default",
		},
		Spec: v1alpha1.DynamoComponentDeploymentSpec{
			BackendFramework: string(dynamo.BackendFrameworkVLLM),
			DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
				ServiceName:     "test-service",
				DynamoNamespace: ptr.To("default"),
				ComponentType:   string(commonconsts.ComponentTypeDecode),
				Replicas:        &replicas,
				ExtraPodSpec: &v1alpha1.ExtraPodSpec{
					MainContainer: &corev1.Container{
						Image: "test-image:latest",
						Args:  []string{"--test-arg"},
					},
				},
			},
		},
	}

	deployment := &appsv1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Name:       "test-component",
			Namespace:  "default",
			Generation: 1,
		},
		Spec: appsv1.DeploymentSpec{
			Replicas: ptr.To(int32(1)),
		},
		Status: appsv1.DeploymentStatus{
			ObservedGeneration: 1,
			Replicas:           1,
			UpdatedReplicas:    1,
			ReadyReplicas:      0,
			AvailableReplicas:  0,
			Conditions: []appsv1.DeploymentCondition{
				{
					Type:   appsv1.DeploymentAvailable,
					Status: corev1.ConditionFalse,
				},
			},
		},
	}

	fakeKubeClient := fake.NewClientBuilder().
		WithScheme(s).
		WithObjects(dcd, deployment).
		WithStatusSubresource(dcd, deployment).
		Build()

	reconciler := &DynamoComponentDeploymentReconciler{
		Client:        fakeKubeClient,
		Recorder:      record.NewFakeRecorder(100),
		Config:        &configv1alpha1.OperatorConfiguration{},
		RuntimeConfig: &controller_common.RuntimeConfig{},
		DockerSecretRetriever: &mockDockerSecretRetriever{
			GetSecretsFunc: func(namespace, imageName string) ([]string, error) {
				return []string{}, nil
			},
		},
	}

	result, err := reconciler.reconcileDeploymentResources(ctx, dcd)
	g.Expect(err).NotTo(gomega.HaveOccurred())
	g.Expect(result).To(gomega.Equal(ComponentReconcileResult{
		modified: true,
		status:   metav1.ConditionFalse,
		reason:   "DeploymentNotReady",
		message:  "Deployment is not ready",
		serviceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
			ComponentKind:     v1alpha1.ComponentKindDeployment,
			ComponentName:     "test-component",
			ComponentNames:    []string{"test-component"},
			Replicas:          1,
			UpdatedReplicas:   1,
			ReadyReplicas:     ptr.To(int32(0)),
			AvailableReplicas: ptr.To(int32(0)),
		},
	}))

}

2421
2422
2423
2424
2425
2426
func Test_setStatusConditionAndServiceReplicaStatus(t *testing.T) {
	ctx := context.Background()

	tests := []struct {
		name                     string
		componentReconcileResult ComponentReconcileResult
2427
		wantConditions           []metav1.Condition
2428
		wantServiceReplicaStatus *v1alpha1.ServiceReplicaStatus
2429
		wantObservedGeneration   int64
2430
2431
2432
2433
2434
2435
2436
2437
	}{
		{
			name: "deployment backed DCD that is unready",
			componentReconcileResult: ComponentReconcileResult{
				modified: true,
				status:   metav1.ConditionFalse,
				reason:   "DeploymentNotReady",
				message:  "Deployment is not ready",
2438
				serviceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
2439
2440
2441
2442
2443
2444
2445
2446
					ComponentKind:     v1alpha1.ComponentKindDeployment,
					ComponentName:     "test-component",
					Replicas:          1,
					UpdatedReplicas:   1,
					ReadyReplicas:     ptr.To(int32(1)),
					AvailableReplicas: ptr.To(int32(0)),
				},
			},
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
			wantConditions: []metav1.Condition{
				{
					Type:    v1alpha1.DynamoGraphDeploymentConditionTypeAvailable,
					Status:  metav1.ConditionFalse,
					Reason:  "DeploymentNotReady",
					Message: "Deployment is not ready",
				},
				{
					Type:    v1alpha1.DynamoGraphDeploymentConditionTypeDynamoComponentReady,
					Status:  metav1.ConditionFalse,
					Reason:  "ComponentNotReady",
					Message: "DynamoComponent is not ready",
				},
			},
2461
			wantServiceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
				ComponentKind:     v1alpha1.ComponentKindDeployment,
				ComponentName:     "test-component",
				Replicas:          1,
				UpdatedReplicas:   1,
				ReadyReplicas:     ptr.To(int32(1)),
				AvailableReplicas: ptr.To(int32(0)),
			},
		},
		{
			name: "deployment backed DCD that is ready",
			componentReconcileResult: ComponentReconcileResult{
				modified: true,
				status:   metav1.ConditionTrue,
				reason:   "DeploymentReady",
				message:  "Deployment is ready",
2477
				serviceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
2478
2479
2480
2481
2482
2483
2484
2485
					ComponentKind:     v1alpha1.ComponentKindDeployment,
					ComponentName:     "test-component",
					Replicas:          2,
					UpdatedReplicas:   2,
					ReadyReplicas:     ptr.To(int32(2)),
					AvailableReplicas: ptr.To(int32(2)),
				},
			},
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
			wantConditions: []metav1.Condition{
				{
					Type:    v1alpha1.DynamoGraphDeploymentConditionTypeAvailable,
					Status:  metav1.ConditionTrue,
					Reason:  "DeploymentReady",
					Message: "Deployment is ready",
				},
				{
					Type:    v1alpha1.DynamoGraphDeploymentConditionTypeDynamoComponentReady,
					Status:  metav1.ConditionTrue,
					Reason:  "ComponentReady",
					Message: "DynamoComponent is ready",
				},
			},
2500
			wantServiceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
				ComponentKind:     v1alpha1.ComponentKindDeployment,
				ComponentName:     "test-component",
				Replicas:          2,
				UpdatedReplicas:   2,
				ReadyReplicas:     ptr.To(int32(2)),
				AvailableReplicas: ptr.To(int32(2)),
			},
		},
		{
			name: "LWS backed DCD that is unready",
			componentReconcileResult: ComponentReconcileResult{
				modified: true,
				status:   metav1.ConditionFalse,
				reason:   "SomeLeaderWorkerSetsNotReady",
				message:  "Some LeaderWorkerSets are not ready",
2516
				serviceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
2517
2518
2519
2520
2521
2522
2523
					ComponentKind:   v1alpha1.ComponentKindLeaderWorkerSet,
					ComponentName:   "test-component-0",
					Replicas:        3,
					UpdatedReplicas: 2,
					ReadyReplicas:   ptr.To(int32(2)),
				},
			},
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
			wantConditions: []metav1.Condition{
				{
					Type:    v1alpha1.DynamoGraphDeploymentConditionTypeAvailable,
					Status:  metav1.ConditionFalse,
					Reason:  "SomeLeaderWorkerSetsNotReady",
					Message: "Some LeaderWorkerSets are not ready",
				},
				{
					Type:    v1alpha1.DynamoGraphDeploymentConditionTypeDynamoComponentReady,
					Status:  metav1.ConditionFalse,
					Reason:  "ComponentNotReady",
					Message: "DynamoComponent is not ready",
				},
			},
2538
			wantServiceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
				ComponentKind:   v1alpha1.ComponentKindLeaderWorkerSet,
				ComponentName:   "test-component-0",
				Replicas:        3,
				UpdatedReplicas: 2,
				ReadyReplicas:   ptr.To(int32(2)),
			},
		},
		{
			name: "LWS backed DCD that is ready",
			componentReconcileResult: ComponentReconcileResult{
				modified: true,
				status:   metav1.ConditionTrue,
				reason:   "AllLeaderWorkerSetsReady",
				message:  "All LeaderWorkerSets are ready",
2553
				serviceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
2554
2555
2556
2557
2558
2559
2560
					ComponentKind:   v1alpha1.ComponentKindLeaderWorkerSet,
					ComponentName:   "test-component-0",
					Replicas:        3,
					UpdatedReplicas: 3,
					ReadyReplicas:   ptr.To(int32(3)),
				},
			},
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
			wantConditions: []metav1.Condition{
				{
					Type:    v1alpha1.DynamoGraphDeploymentConditionTypeAvailable,
					Status:  metav1.ConditionTrue,
					Reason:  "AllLeaderWorkerSetsReady",
					Message: "All LeaderWorkerSets are ready",
				},
				{
					Type:    v1alpha1.DynamoGraphDeploymentConditionTypeDynamoComponentReady,
					Status:  metav1.ConditionTrue,
					Reason:  "ComponentReady",
					Message: "DynamoComponent is ready",
				},
			},
2575
			wantServiceReplicaStatus: &v1alpha1.ServiceReplicaStatus{
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
				ComponentKind:   v1alpha1.ComponentKindLeaderWorkerSet,
				ComponentName:   "test-component-0",
				Replicas:        3,
				UpdatedReplicas: 3,
				ReadyReplicas:   ptr.To(int32(3)),
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			g := gomega.NewGomegaWithT(t)

			// Create a scheme with necessary types
			s := scheme.Scheme
			err := v1alpha1.AddToScheme(s)
			g.Expect(err).NotTo(gomega.HaveOccurred())

			// Create DynamoComponentDeployment
2595
			generation := int64(5)
2596
2597
			dcd := &v1alpha1.DynamoComponentDeployment{
				ObjectMeta: metav1.ObjectMeta{
2598
2599
2600
					Name:       "test-component",
					Namespace:  "default",
					Generation: generation,
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
				},
				Spec: v1alpha1.DynamoComponentDeploymentSpec{
					BackendFramework: string(dynamo.BackendFrameworkVLLM),
					DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
						ServiceName:     "test-service",
						DynamoNamespace: ptr.To("default"),
						ComponentType:   string(commonconsts.ComponentTypeDecode),
					},
				},
			}

			// Set up fake client with the DCD
			fakeKubeClient := fake.NewClientBuilder().
				WithScheme(s).
				WithObjects(dcd).
				WithStatusSubresource(dcd).
				Build()

			// Set up reconciler
			recorder := record.NewFakeRecorder(100)
			reconciler := &DynamoComponentDeploymentReconciler{
				Client:   fakeKubeClient,
				Recorder: recorder,
			}

			// Create the request
			req := ctrl.Request{
				NamespacedName: client.ObjectKey{
					Name:      "test-component",
					Namespace: "default",
				},
			}

			err = reconciler.setStatusConditionAndServiceReplicaStatus(ctx, dcd, tt.componentReconcileResult)
			g.Expect(err).NotTo(gomega.HaveOccurred())

			// Fetch the updated DCD to verify status was set
			updatedDCD := &v1alpha1.DynamoComponentDeployment{}
			err = fakeKubeClient.Get(ctx, req.NamespacedName, updatedDCD)
			g.Expect(err).NotTo(gomega.HaveOccurred())

2642
2643
2644
2645
2646
2647
2648
2649
2650
			// Assert the status conditions
			g.Expect(updatedDCD.Status.Conditions).To(gomega.HaveLen(len(tt.wantConditions)))

			// Clear LastTransitionTime from actual conditions for comparison
			actualConditions := make([]metav1.Condition, len(updatedDCD.Status.Conditions))
			for i, cond := range updatedDCD.Status.Conditions {
				cond.LastTransitionTime = metav1.Time{}
				actualConditions[i] = cond
			}
2651

2652
			g.Expect(actualConditions).To(gomega.ConsistOf(tt.wantConditions))
2653
2654
			// Assert the service replica status
			g.Expect(updatedDCD.Status.Service).To(gomega.Equal(tt.wantServiceReplicaStatus))
2655
2656
2657

			// Assert the observed generation
			g.Expect(updatedDCD.Status.ObservedGeneration).To(gomega.Equal(generation))
2658
2659
2660
		})
	}
}
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820

func Test_generateDeployment_Strategy(t *testing.T) {
	type args struct {
		annotations map[string]string
	}
	tests := []struct {
		name         string
		args         args
		wantStrategy appsv1.DeploymentStrategy
	}{
		{
			name: "no annotations - default RollingUpdate with default maxSurge and maxUnavailable",
			args: args{
				annotations: nil,
			},
			wantStrategy: appsv1.DeploymentStrategy{
				Type: appsv1.RollingUpdateDeploymentStrategyType,
				RollingUpdate: &appsv1.RollingUpdateDeployment{
					MaxSurge:       ptr.To(intstr.FromString("25%")),
					MaxUnavailable: ptr.To(intstr.FromString("25%")),
				},
			},
		},
		{
			name: "deployment-strategy annotation with Recreate - strategy is Recreate",
			args: args{
				annotations: map[string]string{
					KubeAnnotationDeploymentStrategy: "Recreate",
				},
			},
			wantStrategy: appsv1.DeploymentStrategy{
				Type: appsv1.RecreateDeploymentStrategyType,
			},
		},
		{
			name: "deployment-strategy Recreate with maxSurge/maxUnavailable - maxSurge/maxUnavailable are ignored",
			args: args{
				annotations: map[string]string{
					KubeAnnotationDeploymentStrategy:                    "Recreate",
					KubeAnnotationDeploymentRollingUpdateMaxSurge:       "50%",
					KubeAnnotationDeploymentRollingUpdateMaxUnavailable: "30%",
				},
			},
			wantStrategy: appsv1.DeploymentStrategy{
				Type: appsv1.RecreateDeploymentStrategyType,
			},
		},
		{
			name: "deployment-strategy RollingUpdate with only maxSurge",
			args: args{
				annotations: map[string]string{
					KubeAnnotationDeploymentStrategy:              "RollingUpdate",
					KubeAnnotationDeploymentRollingUpdateMaxSurge: "50%",
				},
			},
			wantStrategy: appsv1.DeploymentStrategy{
				Type: appsv1.RollingUpdateDeploymentStrategyType,
				RollingUpdate: &appsv1.RollingUpdateDeployment{
					MaxSurge:       ptr.To(intstr.FromString("50%")),
					MaxUnavailable: ptr.To(intstr.FromString("25%")),
				},
			},
		},
		{
			name: "deployment-strategy RollingUpdate with only maxUnavailable",
			args: args{
				annotations: map[string]string{
					KubeAnnotationDeploymentStrategy:                    "RollingUpdate",
					KubeAnnotationDeploymentRollingUpdateMaxUnavailable: "10%",
				},
			},
			wantStrategy: appsv1.DeploymentStrategy{
				Type: appsv1.RollingUpdateDeploymentStrategyType,
				RollingUpdate: &appsv1.RollingUpdateDeployment{
					MaxSurge:       ptr.To(intstr.FromString("25%")),
					MaxUnavailable: ptr.To(intstr.FromString("10%")),
				},
			},
		},
		{
			name: "deployment-strategy RollingUpdate with both maxSurge and maxUnavailable",
			args: args{
				annotations: map[string]string{
					KubeAnnotationDeploymentStrategy:                    "RollingUpdate",
					KubeAnnotationDeploymentRollingUpdateMaxSurge:       "40%",
					KubeAnnotationDeploymentRollingUpdateMaxUnavailable: "20%",
				},
			},
			wantStrategy: appsv1.DeploymentStrategy{
				Type: appsv1.RollingUpdateDeploymentStrategyType,
				RollingUpdate: &appsv1.RollingUpdateDeployment{
					MaxSurge:       ptr.To(intstr.FromString("40%")),
					MaxUnavailable: ptr.To(intstr.FromString("20%")),
				},
			},
		},
		{
			name: "deployment-strategy RollingUpdate with integer maxSurge and maxUnavailable (not percentages)",
			args: args{
				annotations: map[string]string{
					KubeAnnotationDeploymentStrategy:                    "RollingUpdate",
					KubeAnnotationDeploymentRollingUpdateMaxSurge:       "1",
					KubeAnnotationDeploymentRollingUpdateMaxUnavailable: "0",
				},
			},
			wantStrategy: appsv1.DeploymentStrategy{
				Type: appsv1.RollingUpdateDeploymentStrategyType,
				RollingUpdate: &appsv1.RollingUpdateDeployment{
					MaxSurge:       ptr.To(intstr.FromInt(1)),
					MaxUnavailable: ptr.To(intstr.FromInt(0)),
				},
			},
		},
	}

	// Initialize scheme & add API types
	s := scheme.Scheme
	if err := v1alpha1.AddToScheme(s); err != nil {
		t.Fatalf("Failed to add v1alpha1 to scheme: %v", err)
	}
	if err := corev1.AddToScheme(s); err != nil {
		t.Fatalf("Failed to add corev1 to scheme: %v", err)
	}
	if err := appsv1.AddToScheme(s); err != nil {
		t.Fatalf("Failed to add appsv1 to scheme: %v", err)
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			g := gomega.NewGomegaWithT(t)

			dcd := &v1alpha1.DynamoComponentDeployment{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "test-deployment-strategy",
					Namespace: "default",
				},
				Spec: v1alpha1.DynamoComponentDeploymentSpec{
					BackendFramework: string(dynamo.BackendFrameworkVLLM),
					DynamoComponentDeploymentSharedSpec: v1alpha1.DynamoComponentDeploymentSharedSpec{
						ServiceName:     "test-service",
						DynamoNamespace: ptr.To("default"),
						ComponentType:   string(commonconsts.ComponentTypeDecode),
						Replicas:        ptr.To(int32(1)),
						Annotations:     tt.args.annotations,
						ExtraPodSpec: &v1alpha1.ExtraPodSpec{
							MainContainer: &corev1.Container{
								Image: "test-image:latest",
							},
						},
					},
				},
			}

			fakeKubeClient := fake.NewClientBuilder().
				WithScheme(s).
				WithObjects(dcd).
				Build()

			recorder := record.NewFakeRecorder(100)
			reconciler := &DynamoComponentDeploymentReconciler{
2821
2822
2823
2824
				Client:        fakeKubeClient,
				Recorder:      recorder,
				Config:        &configv1alpha1.OperatorConfiguration{},
				RuntimeConfig: &controller_common.RuntimeConfig{},
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
				DockerSecretRetriever: &mockDockerSecretRetriever{
					GetSecretsFunc: func(namespace, imageName string) ([]string, error) {
						return []string{}, nil
					},
				},
			}

			opt := generateResourceOption{
				dynamoComponentDeployment: dcd,
			}

			deployment, toDelete, err := reconciler.generateDeployment(context.Background(), opt)
			g.Expect(err).NotTo(gomega.HaveOccurred())
			g.Expect(toDelete).To(gomega.BeFalse())
			g.Expect(deployment).NotTo(gomega.BeNil())
			g.Expect(deployment.Spec.Strategy).To(gomega.Equal(tt.wantStrategy))
		})
	}
}