"vscode:/vscode.git/clone" did not exist on "8bbb7c7f200ea791eb4ccd15e77433e29e13ec95"
dynamographdeploymentrequest_controller_test.go 56.8 KB
Newer Older
1
/*
2
 * SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 * 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.
 */

package controller

import (
	"context"
22
	"encoding/json"
23
24
	"time"

25
26
	nvidiacomv1alpha1 "github.com/ai-dynamo/dynamo/deploy/operator/api/v1alpha1"
	commonController "github.com/ai-dynamo/dynamo/deploy/operator/internal/controller_common"
27
28
29
30
	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	batchv1 "k8s.io/api/batch/v1"
	corev1 "k8s.io/api/core/v1"
31
	apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
32
	"k8s.io/apimachinery/pkg/api/meta"
33
34
35
36
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/client-go/tools/record"
	"sigs.k8s.io/controller-runtime/pkg/reconcile"
37
	"sigs.k8s.io/yaml"
38
39
)

40
41
42
43
const (
	defaultNamespace = "default"
)

44
45
46
47
48
49
50
51
52
53
54
55
// MockRBACManager implements RBACManager for testing
type MockRBACManager struct {
	EnsureServiceAccountWithRBACFunc func(ctx context.Context, targetNamespace, serviceAccountName, clusterRoleName string) error
}

func (m *MockRBACManager) EnsureServiceAccountWithRBAC(ctx context.Context, targetNamespace, serviceAccountName, clusterRoleName string) error {
	if m.EnsureServiceAccountWithRBACFunc != nil {
		return m.EnsureServiceAccountWithRBACFunc(ctx, targetNamespace, serviceAccountName, clusterRoleName)
	}
	return nil
}

56
57
// Helper function to create JSON config for tests
func createTestConfig(config map[string]interface{}) *apiextensionsv1.JSON {
58
59
60
61
62
63
64
65
	// Add default hardware config if not present to satisfy validation
	if _, hasHardware := config["hardware"]; !hasHardware {
		config["hardware"] = map[string]interface{}{
			"numGpusPerNode": 8,
			"gpuModel":       "H100-SXM5-80GB",
			"gpuVramMib":     81920,
		}
	}
66
67
68
69
70
71
72
	jsonBytes, err := json.Marshal(config)
	if err != nil {
		panic(err)
	}
	return &apiextensionsv1.JSON{Raw: jsonBytes}
}

73
74
75
76
77
78
79
80
81
82
83
84
85
86
var _ = Describe("DynamoGraphDeploymentRequest Controller", func() {
	const (
		timeout  = time.Second * 10
		interval = time.Millisecond * 250
	)

	var (
		reconciler *DynamoGraphDeploymentRequestReconciler
		recorder   *record.FakeRecorder
	)

	BeforeEach(func() {
		recorder = record.NewFakeRecorder(100)
		reconciler = &DynamoGraphDeploymentRequestReconciler{
87
88
			Client:   k8sClient,
			Recorder: recorder,
89
90
91
92
93
94
95
96
97
98
99
100
101
102
			Config: commonController.Config{
				RestrictedNamespace: "",
				RBAC: commonController.RBACConfig{
					DGDRProfilingClusterRoleName: "test-cluster-role",
				},
			},
			RBACManager: &MockRBACManager{},
		}
	})

	Context("When reconciling initial DGDR", func() {
		It("Should validate spec and transition to Pending", func() {
			ctx := context.Background()
			dgdrName := "test-dgdr-initial"
103
			namespace := defaultNamespace
104
105
106
107
108
109
110

			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
111
112
					Model:   "test-model",
					Backend: "vllm",
113
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
114
						ProfilerImage: "test-profiler:latest",
115
116
						Config: createTestConfig(map[string]interface{}{
							"engine": map[string]interface{}{
117
								"config": "/tmp/test-config.yaml",
118
119
120
121
122
123
124
125
							},
							"sla": map[string]interface{}{
								"ttft": 100.0,
								"itl":  1500.0,
								"isl":  3000,
								"osl":  5,
							},
						}),
126
127
128
129
130
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
131
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()
132
133
134
135
136
137
138
139
140
141
142

			// First reconcile: Empty -> Pending
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{
					Name:      dgdrName,
					Namespace: namespace,
				},
			})
			Expect(err).NotTo(HaveOccurred())

			// Check status
143
			Eventually(func() nvidiacomv1alpha1.DGDRState {
144
				var updated nvidiacomv1alpha1.DynamoGraphDeploymentRequest
145
				_ = k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &updated)
146
				return updated.Status.State
147
			}, timeout, interval).Should(Equal(nvidiacomv1alpha1.DGDRStatePending))
148
149
150

			// Verify observedGeneration is set
			var updated nvidiacomv1alpha1.DynamoGraphDeploymentRequest
151
			_ = k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &updated)
152
153
154
			Expect(updated.Status.ObservedGeneration).Should(Equal(updated.Generation))
		})

155
		It("Should pass validation with minimal config", func() {
156
			ctx := context.Background()
157
			dgdrName := "test-dgdr-minimal"
158
			namespace := defaultNamespace
159
160
161
162
163
164
165

			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
166
167
					Model:   "test-model",
					Backend: "vllm",
168
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
169
						ProfilerImage: "test-profiler:latest",
170
171
172
173
174
175
						Config: createTestConfig(map[string]interface{}{
							"sla": map[string]interface{}{
								"ttft": 100.0,
								"itl":  1500.0,
							},
						}),
176
177
178
179
180
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
181
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()
182

183
			// Reconcile - should succeed with minimal config
184
185
186
187
188
189
190
191
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{
					Name:      dgdrName,
					Namespace: namespace,
				},
			})
			Expect(err).NotTo(HaveOccurred())

192
			// Check status transitions to Pending (not Failed)
193
			Eventually(func() nvidiacomv1alpha1.DGDRState {
194
				var updated nvidiacomv1alpha1.DynamoGraphDeploymentRequest
195
				_ = k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &updated)
196
				return updated.Status.State
197
			}, timeout, interval).Should(Equal(nvidiacomv1alpha1.DGDRStatePending))
198
199
200
201
202
203
204
		})
	})

	Context("When creating profiling job", func() {
		It("Should create online profiling job", func() {
			ctx := context.Background()
			dgdrName := "test-dgdr-profiling-online"
205
			namespace := defaultNamespace
206

207
			// Create ConfigMap for DGD base config
208
209
210
211
212
213
214
215
216
217
			configMap := &corev1.ConfigMap{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "test-config",
					Namespace: namespace,
				},
				Data: map[string]string{
					"disagg.yaml": "test: config",
				},
			}
			Expect(k8sClient.Create(ctx, configMap)).Should(Succeed())
218
			defer func() { _ = k8sClient.Delete(ctx, configMap) }()
219
220
221
222
223
224
225
226
227

			// Create ServiceAccount
			sa := &corev1.ServiceAccount{
				ObjectMeta: metav1.ObjectMeta{
					Name:      ServiceAccountProfilingJob,
					Namespace: namespace,
				},
			}
			Expect(k8sClient.Create(ctx, sa)).Should(Succeed())
228
			defer func() { _ = k8sClient.Delete(ctx, sa) }()
229
230
231
232
233
234
235

			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
236
237
					Model:   "test-model",
					Backend: "vllm",
238
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
239
						ProfilerImage: "test-profiler:latest",
240
241
242
243
244
245
246
247
248
249
250
						Config: createTestConfig(map[string]interface{}{
							"engine": map[string]interface{}{
								"profiler_image": "test-profiler:latest",
							},
							"sla": map[string]interface{}{
								"ttft": 100.0,
								"itl":  1500.0,
								"isl":  3000,
								"osl":  5,
							},
						}),
251
252
253
254
255
256
257
258
259
						ConfigMapRef: &nvidiacomv1alpha1.ConfigMapKeySelector{
							Name: "test-config",
							Key:  "disagg.yaml",
						},
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
260
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284

			// Reconcile multiple times to move through states
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{Name: dgdrName, Namespace: namespace},
			})
			Expect(err).NotTo(HaveOccurred())

			// Second reconcile: Pending -> Profiling
			_, err = reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{Name: dgdrName, Namespace: namespace},
			})
			Expect(err).NotTo(HaveOccurred())

			// Verify profiling job was created
			Eventually(func() bool {
				jobName := getProfilingJobName(dgdr)
				job := &batchv1.Job{}
				err := k8sClient.Get(ctx, types.NamespacedName{Name: jobName, Namespace: namespace}, job)
				return err == nil
			}, timeout, interval).Should(BeTrue())

			// Verify job has correct labels
			jobName := getProfilingJobName(dgdr)
			job := &batchv1.Job{}
285
			_ = k8sClient.Get(ctx, types.NamespacedName{Name: jobName, Namespace: namespace}, job)
286
287
288
289
290
291
292
293
			Expect(job.Labels[LabelApp]).Should(Equal(LabelValueDynamoProfiler))
			Expect(job.Labels[LabelDGDR]).Should(Equal(dgdrName))

			// Verify job has profiler container
			Expect(job.Spec.Template.Spec.Containers).Should(HaveLen(2))
			Expect(job.Spec.Template.Spec.Containers[0].Name).Should(Equal(ContainerNameProfiler))
			Expect(job.Spec.Template.Spec.Containers[1].Name).Should(Equal(ContainerNameOutputCopier))

294
			// Verify emptyDir volume (not PVC)
295
296
297
298
			Expect(job.Spec.Template.Spec.Volumes).Should(ContainElement(
				corev1.Volume{
					Name: VolumeNameProfilingOutput,
					VolumeSource: corev1.VolumeSource{
299
						EmptyDir: &corev1.EmptyDirVolumeSource{},
300
301
302
303
304
					},
				},
			))

			// Clean up job
305
			_ = k8sClient.Delete(ctx, job)
306
307
308
309
310
		})

		It("Should create offline (AIC) profiling job", func() {
			ctx := context.Background()
			dgdrName := "test-dgdr-profiling-aic"
311
			namespace := defaultNamespace
312
313
314
315
316
317
318
319

			// Create ServiceAccount
			sa := &corev1.ServiceAccount{
				ObjectMeta: metav1.ObjectMeta{
					Name:      ServiceAccountProfilingJob,
					Namespace: namespace,
				},
			}
320
321
			Expect(k8sClient.Create(ctx, sa)).Should(Succeed())
			defer func() { _ = k8sClient.Delete(ctx, sa) }()
322
323
324
325
326
327
328

			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
329
330
					Model:   "test-model",
					Backend: "trtllm",
331
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
332
						ProfilerImage: "test-profiler:latest",
333
334
335
336
337
338
339
340
341
342
343
344
345
346
						Config: createTestConfig(map[string]interface{}{
							"engine": map[string]interface{}{
								"config":         "/tmp/test-config.yaml",
								"profiler_image": "test-profiler:latest",
							},
							"sla": map[string]interface{}{
								"ttft": 100.0,
								"itl":  1500.0,
								"isl":  3000,
								"osl":  5,
							},
							"sweep": map[string]interface{}{
								"use_ai_configurator": true,
								"aic_system":          "h200_sxm",
347
								"aic_hf_id":           "Qwen/Qwen3-32B",
348
349
350
								"aic_backend_version": "0.20.0",
							},
						}),
351
352
353
354
355
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
356
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382

			// Reconcile
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{Name: dgdrName, Namespace: namespace},
			})
			Expect(err).NotTo(HaveOccurred())

			_, err = reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{Name: dgdrName, Namespace: namespace},
			})
			Expect(err).NotTo(HaveOccurred())

			// Verify job was created with AIC label
			Eventually(func() string {
				jobName := getProfilingJobName(dgdr)
				job := &batchv1.Job{}
				if err := k8sClient.Get(ctx, types.NamespacedName{Name: jobName, Namespace: namespace}, job); err != nil {
					return ""
				}
				return job.Labels[LabelApp]
			}, timeout, interval).Should(Equal(LabelValueAICProfiler))

			// Clean up
			jobName := getProfilingJobName(dgdr)
			job := &batchv1.Job{}
			if err := k8sClient.Get(ctx, types.NamespacedName{Name: jobName, Namespace: namespace}, job); err == nil {
383
				_ = k8sClient.Delete(ctx, job)
384
385
386
387
388
389
390
391
			}
		})
	})

	Context("When profiling completes", func() {
		It("Should generate DGD spec from ConfigMap", func() {
			ctx := context.Background()
			dgdrName := "test-dgdr-profiling-complete"
392
			namespace := defaultNamespace
393
394
395
396
397
398
399

			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
400
401
					Model:   "test-model",
					Backend: "vllm",
402
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
403
						ProfilerImage: "test-profiler:latest",
404
405
						Config: createTestConfig(map[string]interface{}{
							"engine": map[string]interface{}{
406
								"config": "/tmp/test-config.yaml",
407
408
409
410
411
412
413
414
							},
							"sla": map[string]interface{}{
								"ttft": 100.0,
								"itl":  1500.0,
								"isl":  3000,
								"osl":  5,
							},
						}),
415
416
417
418
419
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
420
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()
421
422

			// Update status to Profiling using Status subresource
423
			dgdr.Status.State = nvidiacomv1alpha1.DGDRStateProfiling
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
			Expect(k8sClient.Status().Update(ctx, dgdr)).Should(Succeed())

			// Create completed profiling job
			jobName := getProfilingJobName(dgdr)
			job := &batchv1.Job{
				ObjectMeta: metav1.ObjectMeta{
					Name:      jobName,
					Namespace: namespace,
				},
				Spec: batchv1.JobSpec{
					Template: corev1.PodTemplateSpec{
						Spec: corev1.PodSpec{
							Containers: []corev1.Container{{
								Name:  "test",
								Image: "test",
							}},
							RestartPolicy: corev1.RestartPolicyNever,
						},
					},
				},
				Status: batchv1.JobStatus{
					Conditions: []batchv1.JobCondition{{
						Type:   batchv1.JobComplete,
						Status: corev1.ConditionTrue,
					}},
				},
			}
			Expect(k8sClient.Create(ctx, job)).Should(Succeed())
452
			defer func() { _ = k8sClient.Delete(ctx, job) }()
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481

			// Update job status to completed using Status subresource
			job.Status.Conditions = []batchv1.JobCondition{{
				Type:   batchv1.JobComplete,
				Status: corev1.ConditionTrue,
			}}
			Expect(k8sClient.Status().Update(ctx, job)).Should(Succeed())

			// Create output ConfigMap with DGD spec
			dgdYAML := `apiVersion: nvidia.com/v1alpha1
kind: DynamoGraphDeployment
metadata:
  name: test-dgd
spec:
  services:
    Frontend:
      replicas: 1`

			outputConfigMapName := getOutputConfigMapName(dgdr)
			cm := &corev1.ConfigMap{
				ObjectMeta: metav1.ObjectMeta{
					Name:      outputConfigMapName,
					Namespace: namespace,
				},
				Data: map[string]string{
					ProfilingOutputFile: dgdYAML,
				},
			}
			Expect(k8sClient.Create(ctx, cm)).Should(Succeed())
482
			defer func() { _ = k8sClient.Delete(ctx, cm) }()
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497

			// Reconcile to process the profiling completion
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{Name: dgdrName, Namespace: namespace},
			})
			Expect(err).NotTo(HaveOccurred())

			// Get the updated DGDR
			var updated nvidiacomv1alpha1.DynamoGraphDeploymentRequest
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &updated)).Should(Succeed())

			// Check that DGD spec was generated
			Expect(updated.Status.GeneratedDeployment).NotTo(BeNil())

			// Verify state transitioned to Ready (since autoApply is false by default)
498
			Expect(updated.Status.State).Should(Equal(nvidiacomv1alpha1.DGDRStateReady))
499
500
501
502
503
504
505
		})
	})

	Context("When autoApply is enabled", func() {
		It("Should create DGD after profiling", func() {
			ctx := context.Background()
			dgdrName := "test-dgdr-autoapply"
506
			namespace := defaultNamespace
507
508
509
510
511
512
513

			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
514
515
					Model:   "test-model",
					Backend: "vllm",
516
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
517
						ProfilerImage: "test-profiler:latest",
518
519
						Config: createTestConfig(map[string]interface{}{
							"engine": map[string]interface{}{
520
								"config": "/tmp/test-config.yaml",
521
522
523
524
525
526
527
528
							},
							"sla": map[string]interface{}{
								"ttft": 100.0,
								"itl":  1500.0,
								"isl":  3000,
								"osl":  5,
							},
						}),
529
530
531
532
533
534
					},
					AutoApply: true,
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
535
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()
536
537

			// Update status to Profiling using Status subresource
538
			dgdr.Status.State = nvidiacomv1alpha1.DGDRStateProfiling
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
			Expect(k8sClient.Status().Update(ctx, dgdr)).Should(Succeed())

			// Create completed profiling job
			jobName := getProfilingJobName(dgdr)
			job := &batchv1.Job{
				ObjectMeta: metav1.ObjectMeta{
					Name:      jobName,
					Namespace: namespace,
				},
				Spec: batchv1.JobSpec{
					Template: corev1.PodTemplateSpec{
						Spec: corev1.PodSpec{
							Containers: []corev1.Container{{
								Name:  "test",
								Image: "test",
							}},
							RestartPolicy: corev1.RestartPolicyNever,
						},
					},
				},
				Status: batchv1.JobStatus{
					Conditions: []batchv1.JobCondition{{
						Type:   batchv1.JobComplete,
						Status: corev1.ConditionTrue,
					}},
				},
			}
			Expect(k8sClient.Create(ctx, job)).Should(Succeed())
567
			defer func() { _ = k8sClient.Delete(ctx, job) }()
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596

			// Update job status to completed using Status subresource
			job.Status.Conditions = []batchv1.JobCondition{{
				Type:   batchv1.JobComplete,
				Status: corev1.ConditionTrue,
			}}
			Expect(k8sClient.Status().Update(ctx, job)).Should(Succeed())

			// Create output ConfigMap
			dgdYAML := `apiVersion: nvidia.com/v1alpha1
kind: DynamoGraphDeployment
metadata:
  name: test-dgd-auto
spec:
  services:
    Frontend:
      replicas: 1`

			outputConfigMapName := getOutputConfigMapName(dgdr)
			cm := &corev1.ConfigMap{
				ObjectMeta: metav1.ObjectMeta{
					Name:      outputConfigMapName,
					Namespace: namespace,
				},
				Data: map[string]string{
					ProfilingOutputFile: dgdYAML,
				},
			}
			Expect(k8sClient.Create(ctx, cm)).Should(Succeed())
597
			defer func() { _ = k8sClient.Delete(ctx, cm) }()
598
599
600
601
602
603
604
605
606
607

			// Reconcile to generate spec (transitions to Deploying because autoApply=true)
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{Name: dgdrName, Namespace: namespace},
			})
			Expect(err).NotTo(HaveOccurred())

			// Get updated DGDR and check state is Deploying
			var updated nvidiacomv1alpha1.DynamoGraphDeploymentRequest
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &updated)).Should(Succeed())
608
			Expect(updated.Status.State).Should(Equal(nvidiacomv1alpha1.DGDRStateDeploying))
609
610
611
612
613
614
615
616
617
618
619
620

			// Reconcile again to create DGD
			_, err = reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{Name: dgdrName, Namespace: namespace},
			})
			Expect(err).NotTo(HaveOccurred())

			// Verify DGD was created
			dgd := &nvidiacomv1alpha1.DynamoGraphDeployment{}
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: "test-dgd-auto", Namespace: namespace}, dgd)).Should(Succeed())

			// Get final DGDR status
621
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &updated)).Should(Succeed())
622
623
624
625
626
			Expect(updated.Status.Deployment).NotTo(BeNil())
			Expect(updated.Status.Deployment.Created).Should(BeTrue())
			Expect(updated.Status.Deployment.Name).Should(Equal("test-dgd-auto"))

			// Clean up DGD
627
628
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: "test-dgd-auto", Namespace: namespace}, dgd)).Should(Succeed())
			_ = k8sClient.Delete(ctx, dgd)
629
630
631
632
633
634
635
		})
	})

	Context("When enforcing spec immutability", func() {
		It("Should reject spec changes after profiling starts", func() {
			ctx := context.Background()
			dgdrName := "test-dgdr-immutable"
636
			namespace := defaultNamespace
637
638
639
640
641
642
643

			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
644
645
					Model:   "test-model",
					Backend: "vllm",
646
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
647
						ProfilerImage: "test-profiler:latest",
648
649
						Config: createTestConfig(map[string]interface{}{
							"engine": map[string]interface{}{
650
								"config": "/tmp/test-config.yaml",
651
652
653
654
655
656
657
658
							},
							"sla": map[string]interface{}{
								"ttft": 100.0,
								"itl":  1500.0,
								"isl":  3000,
								"osl":  5,
							},
						}),
659
660
661
662
663
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
664
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()
665
666
667
668
669
670
671
672
673

			// Reconcile to initialize
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{Name: dgdrName, Namespace: namespace},
			})
			Expect(err).NotTo(HaveOccurred())

			// Get current generation
			var current nvidiacomv1alpha1.DynamoGraphDeploymentRequest
674
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &current)).Should(Succeed())
675
676
677
678
			initialGeneration := current.Generation
			observedGeneration := current.Status.ObservedGeneration

			// Manually set state to Profiling to simulate in-progress profiling
679
			current.Status.State = nvidiacomv1alpha1.DGDRStateProfiling
680
			Expect(k8sClient.Status().Update(ctx, &current)).Should(Succeed())
681
682

			// Try to modify spec
683
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &current)).Should(Succeed())
684
685
			// Unmarshal config, modify it, and marshal back
			var config map[string]interface{}
686
			Expect(yaml.Unmarshal(current.Spec.ProfilingConfig.Config.Raw, &config)).Should(Succeed())
687
688
			config["sla"].(map[string]interface{})["ttft"] = 200.0
			current.Spec.ProfilingConfig.Config = createTestConfig(config)
689
			Expect(k8sClient.Update(ctx, &current)).Should(Succeed())
690
691
692
693
694
695
696
697

			// Reconcile
			_, err = reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{Name: dgdrName, Namespace: namespace},
			})
			Expect(err).NotTo(HaveOccurred())

			// Verify generation changed but observedGeneration stayed the same
698
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &current)).Should(Succeed())
699
700
			Expect(current.Generation).Should(BeNumerically(">", initialGeneration))
			Expect(current.Status.ObservedGeneration).Should(Equal(observedGeneration))
701
			Expect(current.Status.State).Should(Equal(nvidiacomv1alpha1.DGDRStateProfiling)) // State unchanged
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718

			// Verify event was recorded
			Eventually(func() bool {
				select {
				case event := <-recorder.Events:
					return event == "Warning SpecChangeRejected Cannot modify spec in state 'Profiling'. DynamoGraphDeploymentRequest is immutable once profiling starts. Create a new resource with a different name instead."
				default:
					return false
				}
			}, timeout, interval).Should(BeTrue())
		})
	})

	Context("When handling DGD deletion", func() {
		It("Should transition to DeploymentDeleted state", func() {
			ctx := context.Background()
			dgdrName := "test-dgdr-dgd-deleted"
719
			namespace := defaultNamespace
720
721
722
723
724
725
726

			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
727
728
					Model:   "test-model",
					Backend: "vllm",
729
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
730
						ProfilerImage: "test-profiler:latest",
731
732
						Config: createTestConfig(map[string]interface{}{
							"engine": map[string]interface{}{
733
								"config": "/tmp/test-config.yaml",
734
735
736
737
738
739
740
741
							},
							"sla": map[string]interface{}{
								"ttft": 100.0,
								"itl":  1500.0,
								"isl":  3000,
								"osl":  5,
							},
						}),
742
743
744
745
746
747
					},
					AutoApply: true,
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
748
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()
749
750

			// Update status to Ready with Deployment info using Status subresource
751
			dgdr.Status.State = nvidiacomv1alpha1.DGDRStateReady
752
753
754
755
			dgdr.Status.Deployment = &nvidiacomv1alpha1.DeploymentStatus{
				Name:      "test-dgd-to-delete",
				Namespace: namespace,
				Created:   true,
756
				State:     nvidiacomv1alpha1.DGDStateSuccessful,
757
758
759
760
761
762
763
764
765
766
767
768
			}
			Expect(k8sClient.Status().Update(ctx, dgdr)).Should(Succeed())

			// Reconcile when DGD doesn't exist (simulating deletion)
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{Name: dgdrName, Namespace: namespace},
			})
			Expect(err).NotTo(HaveOccurred())

			// Get updated DGDR and check state transitioned to DeploymentDeleted
			var updated nvidiacomv1alpha1.DynamoGraphDeploymentRequest
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &updated)).Should(Succeed())
769
			Expect(updated.Status.State).Should(Equal(nvidiacomv1alpha1.DGDRStateDeploymentDeleted))
770
771
772
773
774
775
		})
	})
})

var _ = Describe("DGDR Helper Functions", func() {
	Context("getProfilingJobName", func() {
776
		It("Should return correct job name", func() {
777
778
779
780
781
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name: "test-dgdr",
				},
			}
782
			Expect(getProfilingJobName(dgdr)).Should(Equal("profile-test-dgdr"))
783
784
785
786
787
788
789
790
791
792
793
794
795
796
		})
	})

	Context("getOutputConfigMapName", func() {
		It("Should return correct ConfigMap name", func() {
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name: "test-dgdr",
				},
			}
			Expect(getOutputConfigMapName(dgdr)).Should(Equal("dgdr-output-test-dgdr"))
		})
	})

797
798
	Context("isOnlineProfiling", func() {
		It("Should return true for online profiling (use_ai_configurator=false)", func() {
799
800
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
801
802
803
804
805
806
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
						Config: createTestConfig(map[string]interface{}{
							"sweep": map[string]interface{}{
								"use_ai_configurator": false,
							},
						}),
807
808
809
					},
				},
			}
810
			Expect(isOnlineProfiling(dgdr)).Should(BeTrue())
811
812
		})

813
		It("Should return false for AI Configurator profiling (use_ai_configurator=true)", func() {
814
815
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
816
817
818
819
820
821
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
						Config: createTestConfig(map[string]interface{}{
							"sweep": map[string]interface{}{
								"use_ai_configurator": true,
							},
						}),
822
823
824
					},
				},
			}
825
			Expect(isOnlineProfiling(dgdr)).Should(BeFalse())
826
827
		})

828
		It("Should return true by default when sweep section is missing", func() {
829
830
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
831
832
833
834
835
836
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
						Config: createTestConfig(map[string]interface{}{
							"engine": map[string]interface{}{
								"backend": "vllm",
							},
						}),
837
838
839
					},
				},
			}
840
841
			Expect(isOnlineProfiling(dgdr)).Should(BeTrue())
		})
842

843
844
845
846
847
848
		It("Should return true by default when use_ai_configurator is not specified", func() {
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
						Config: createTestConfig(map[string]interface{}{
							"sweep": map[string]interface{}{
849
								"prefill_interpolation_granularity": 16,
850
851
852
853
854
855
							},
						}),
					},
				},
			}
			Expect(isOnlineProfiling(dgdr)).Should(BeTrue())
856
		})
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886

		It("Should return false for AI Configurator profiling (useAiConfigurator=true camelCase)", func() {
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
						Config: createTestConfig(map[string]interface{}{
							"sweep": map[string]interface{}{
								"useAiConfigurator": true,
							},
						}),
					},
				},
			}
			Expect(isOnlineProfiling(dgdr)).Should(BeFalse())
		})

		It("Should return true for online profiling (useAiConfigurator=false camelCase)", func() {
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
						Config: createTestConfig(map[string]interface{}{
							"sweep": map[string]interface{}{
								"useAiConfigurator": false,
							},
						}),
					},
				},
			}
			Expect(isOnlineProfiling(dgdr)).Should(BeTrue())
		})
887
888
	})
})
889

890
891
892
893
894
895
896
897
898
899
900
var _ = Describe("DGDR Validation", func() {
	var reconciler *DynamoGraphDeploymentRequestReconciler

	BeforeEach(func() {
		reconciler = &DynamoGraphDeploymentRequestReconciler{
			Client: k8sClient,
		}
	})

	Context("validateSpec", func() {
		It("Should pass validation for valid spec", func() {
901
902
903
			ctx := context.Background()
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
904
905
					Model:   "test-model",
					Backend: "vllm",
906
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
907
						ProfilerImage: "test-profiler:latest",
908
909
						Config: createTestConfig(map[string]interface{}{
							"engine": map[string]interface{}{
910
								"config": "/tmp/test-config.yaml",
911
912
913
914
915
916
917
918
							},
							"sla": map[string]interface{}{
								"ttft": 100.0,
								"itl":  1500.0,
								"isl":  3000,
								"osl":  5,
							},
						}),
919
920
921
922
923
					},
				},
			}

			err := reconciler.validateSpec(ctx, dgdr)
924
			Expect(err).NotTo(HaveOccurred())
925
926
		})

927
		It("Should pass validation with minimal config", func() {
928
929
930
			ctx := context.Background()
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
931
932
					Model:   "test-model",
					Backend: "vllm",
933
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
934
						ProfilerImage: "test-profiler:latest",
935
936
937
938
939
940
						Config: createTestConfig(map[string]interface{}{
							"sla": map[string]interface{}{
								"ttft": 100.0,
								"itl":  1500.0,
							},
						}),
941
942
943
944
					},
				},
			}

945
			// Validation should pass - profiler will auto-generate missing config
946
			err := reconciler.validateSpec(ctx, dgdr)
947
			Expect(err).NotTo(HaveOccurred())
948
949
950
		})
	})
})
951
952
953
954
955
956

var _ = Describe("DGDR Profiler Arguments", func() {
	var reconciler *DynamoGraphDeploymentRequestReconciler

	BeforeEach(func() {
		reconciler = &DynamoGraphDeploymentRequestReconciler{
957
958
			Client:   k8sClient,
			Recorder: record.NewFakeRecorder(100),
959
960
961
962
963
964
965
			Config: commonController.Config{
				RestrictedNamespace: "",
			},
			RBACManager: &MockRBACManager{},
		}
	})

966
967
	Context("When creating profiling job with inline config", func() {
		It("Should pass config as --profile-config argument for online profiling", func() {
968
969
970
971
972
973
974
975
976
977
978
			ctx := context.Background()
			namespace := "default"
			dgdrName := "test-args-online"

			// Create ServiceAccount
			sa := &corev1.ServiceAccount{
				ObjectMeta: metav1.ObjectMeta{
					Name:      ServiceAccountProfilingJob,
					Namespace: namespace,
				},
			}
979
980
			Expect(k8sClient.Create(ctx, sa)).Should(Succeed())
			defer func() { _ = k8sClient.Delete(ctx, sa) }()
981
982
983
984
985
986
987

			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
988
989
					Model:   "test-model",
					Backend: "trtllm",
990
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
991
						ProfilerImage: "test-profiler:latest",
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
						Config: createTestConfig(map[string]interface{}{
							"engine": map[string]interface{}{
								"config":         "/tmp/test-config.yaml",
								"profiler_image": "test-profiler:latest",
							},
							"sla": map[string]interface{}{
								"ttft": 50.0,
								"itl":  10.0,
								"isl":  3000,
								"osl":  500,
							},
							"hardware": map[string]interface{}{
								"gpu_type":                "h200_sxm",
								"min_num_gpus_per_engine": 2,
								"max_num_gpus_per_engine": 4,
							},
							"sweep": map[string]interface{}{
								"use_ai_configurator": false,
							},
						}),
1012
1013
1014
1015
1016
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
1017
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031

			// Re-fetch DGDR to get proper metadata from API server
			var fetchedDGDR nvidiacomv1alpha1.DynamoGraphDeploymentRequest
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &fetchedDGDR)).Should(Succeed())

			// Create profiling job with properly initialized DGDR
			err := reconciler.createProfilingJob(ctx, &fetchedDGDR)
			Expect(err).NotTo(HaveOccurred())

			// Verify job was created
			jobName := getProfilingJobName(&fetchedDGDR)
			job := &batchv1.Job{}
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: jobName, Namespace: namespace}, job)).Should(Succeed())

1032
			// Verify profiler container has --profile-config argument
1033
1034
1035
			profilerContainer := job.Spec.Template.Spec.Containers[0]
			args := profilerContainer.Args

1036
1037
			// Check that --profile-config argument is present
			Expect(args).Should(ContainElement("--profile-config"))
1038
1039

			// Clean up
1040
			_ = k8sClient.Delete(ctx, job)
1041
1042
		})

1043
		It("Should pass config with AI Configurator settings for offline profiling", func() {
1044
			ctx := context.Background()
1045
			namespace := defaultNamespace
1046
1047
1048
1049
1050
1051
1052
1053
1054
			dgdrName := "test-args-offline"

			// Create ServiceAccount
			sa := &corev1.ServiceAccount{
				ObjectMeta: metav1.ObjectMeta{
					Name:      ServiceAccountProfilingJob,
					Namespace: namespace,
				},
			}
1055
1056
			Expect(k8sClient.Create(ctx, sa)).Should(Succeed())
			defer func() { _ = k8sClient.Delete(ctx, sa) }()
1057
1058
1059
1060
1061
1062
1063

			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
1064
1065
					Model:   "test-model",
					Backend: "trtllm",
1066
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
1067
						ProfilerImage: "test-profiler:latest",
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
						Config: createTestConfig(map[string]interface{}{
							"engine": map[string]interface{}{
								"config":         "/tmp/test-config.yaml",
								"profiler_image": "test-profiler:latest",
							},
							"sla": map[string]interface{}{
								"ttft": 50.0,
								"itl":  10.0,
								"isl":  3000,
								"osl":  500,
							},
							"hardware": map[string]interface{}{
								"gpu_type":                "h200_sxm",
								"min_num_gpus_per_engine": 1,
								"max_num_gpus_per_engine": 8,
							},
							"sweep": map[string]interface{}{
								"use_ai_configurator": true,
								"aic_system":          "h200_sxm",
1087
								"aic_hf_id":           "Qwen/Qwen3-32B",
1088
1089
1090
								"aic_backend_version": "0.20.0",
							},
						}),
1091
1092
1093
1094
1095
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
1096
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110

			// Re-fetch DGDR to get proper metadata from API server
			var fetchedDGDR nvidiacomv1alpha1.DynamoGraphDeploymentRequest
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &fetchedDGDR)).Should(Succeed())

			// Create profiling job with properly initialized DGDR
			err := reconciler.createProfilingJob(ctx, &fetchedDGDR)
			Expect(err).NotTo(HaveOccurred())

			// Verify job was created
			jobName := getProfilingJobName(&fetchedDGDR)
			job := &batchv1.Job{}
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: jobName, Namespace: namespace}, job)).Should(Succeed())

1111
			// Verify profiler container has --profile-config argument
1112
1113
1114
			profilerContainer := job.Spec.Template.Spec.Containers[0]
			args := profilerContainer.Args

1115
1116
			// Check that --profile-config argument is present
			Expect(args).Should(ContainElement("--profile-config"))
1117
1118

			// Clean up
1119
			_ = k8sClient.Delete(ctx, job)
1120
		})
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
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
1188
1189

		It("Should set fsGroup in pod security context for volume permissions", func() {
			ctx := context.Background()
			namespace := "default"
			dgdrName := "test-fsgroup"

			// Create ServiceAccount
			sa := &corev1.ServiceAccount{
				ObjectMeta: metav1.ObjectMeta{
					Name:      ServiceAccountProfilingJob,
					Namespace: namespace,
				},
			}
			Expect(k8sClient.Create(ctx, sa)).Should(Succeed())
			defer func() { _ = k8sClient.Delete(ctx, sa) }()

			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
					Model:   "test-model",
					Backend: "trtllm",
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
						ProfilerImage: "test-profiler:latest",
						Config: createTestConfig(map[string]interface{}{
							"sla": map[string]interface{}{
								"ttft": 50.0,
								"itl":  10.0,
								"isl":  3000,
								"osl":  500,
							},
						}),
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()

			// Re-fetch DGDR to get proper metadata from API server
			var fetchedDGDR nvidiacomv1alpha1.DynamoGraphDeploymentRequest
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &fetchedDGDR)).Should(Succeed())

			// Create profiling job with properly initialized DGDR
			err := reconciler.createProfilingJob(ctx, &fetchedDGDR)
			Expect(err).NotTo(HaveOccurred())

			// Verify job was created
			jobName := getProfilingJobName(&fetchedDGDR)
			job := &batchv1.Job{}
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: jobName, Namespace: namespace}, job)).Should(Succeed())

			// Verify security context has all security fields set correctly
			podSecurityContext := job.Spec.Template.Spec.SecurityContext
			Expect(podSecurityContext).NotTo(BeNil())
			Expect(podSecurityContext.RunAsNonRoot).NotTo(BeNil())
			Expect(*podSecurityContext.RunAsNonRoot).To(BeTrue())
			Expect(podSecurityContext.RunAsUser).NotTo(BeNil())
			Expect(*podSecurityContext.RunAsUser).To(Equal(int64(1000)))
			Expect(podSecurityContext.RunAsGroup).NotTo(BeNil())
			Expect(*podSecurityContext.RunAsGroup).To(Equal(int64(1000)))
			Expect(podSecurityContext.FSGroup).NotTo(BeNil())
			Expect(*podSecurityContext.FSGroup).To(Equal(int64(1000)))

			// Clean up
			_ = k8sClient.Delete(ctx, job)
		})
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
	})
})

var _ = Describe("DGDR Error Handling", func() {
	var reconciler *DynamoGraphDeploymentRequestReconciler
	var recorder *record.FakeRecorder

	BeforeEach(func() {
		recorder = record.NewFakeRecorder(100)
		reconciler = &DynamoGraphDeploymentRequestReconciler{
1200
1201
			Client:   k8sClient,
			Recorder: recorder,
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
			Config: commonController.Config{
				RestrictedNamespace: "",
			},
			RBACManager: &MockRBACManager{},
		}
	})

	Context("When profiling job fails", func() {
		It("Should capture detailed error from pod termination state", func() {
			ctx := context.Background()
1212
			namespace := defaultNamespace
1213
1214
1215
1216
1217
1218
1219
1220
			dgdrName := "test-error-capture"

			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
1221
1222
					Model:   "test-model",
					Backend: "vllm",
1223
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
1224
						ProfilerImage: "test-profiler:latest",
1225
1226
						Config: createTestConfig(map[string]interface{}{
							"engine": map[string]interface{}{
1227
								"config": "/tmp/test-config.yaml",
1228
1229
1230
1231
1232
1233
1234
1235
							},
							"sla": map[string]interface{}{
								"ttft": 100.0,
								"itl":  1500.0,
								"isl":  3000,
								"osl":  5,
							},
						}),
1236
1237
1238
1239
1240
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
1241
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()
1242
1243

			// Set status to Profiling
1244
			dgdr.Status.State = nvidiacomv1alpha1.DGDRStateProfiling
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
			Expect(k8sClient.Status().Update(ctx, dgdr)).Should(Succeed())

			// Create failed job
			jobName := getProfilingJobName(dgdr)
			job := &batchv1.Job{
				ObjectMeta: metav1.ObjectMeta{
					Name:      jobName,
					Namespace: namespace,
				},
				Spec: batchv1.JobSpec{
					Template: corev1.PodTemplateSpec{
						Spec: corev1.PodSpec{
							Containers: []corev1.Container{{
								Name:  ContainerNameProfiler,
								Image: "test",
							}},
							RestartPolicy: corev1.RestartPolicyNever,
						},
					},
				},
				Status: batchv1.JobStatus{
					Conditions: []batchv1.JobCondition{{
						Type:    batchv1.JobFailed,
						Status:  corev1.ConditionTrue,
						Message: "BackoffLimitExceeded",
					}},
				},
			}
			Expect(k8sClient.Create(ctx, job)).Should(Succeed())
1274
			defer func() { _ = k8sClient.Delete(ctx, job) }()
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314

			// Update job status
			job.Status.Conditions = []batchv1.JobCondition{{
				Type:    batchv1.JobFailed,
				Status:  corev1.ConditionTrue,
				Message: "BackoffLimitExceeded",
			}}
			Expect(k8sClient.Status().Update(ctx, job)).Should(Succeed())

			// Create failed pod with termination details
			pod := &corev1.Pod{
				ObjectMeta: metav1.ObjectMeta{
					Name:      jobName + "-pod",
					Namespace: namespace,
					Labels: map[string]string{
						"job-name": jobName,
					},
				},
				Spec: corev1.PodSpec{
					Containers: []corev1.Container{{
						Name:  ContainerNameProfiler,
						Image: "test",
					}},
					RestartPolicy: corev1.RestartPolicyNever,
				},
				Status: corev1.PodStatus{
					Phase: corev1.PodFailed,
					ContainerStatuses: []corev1.ContainerStatus{{
						Name: ContainerNameProfiler,
						State: corev1.ContainerState{
							Terminated: &corev1.ContainerStateTerminated{
								ExitCode: 1,
								Reason:   "Error",
								Message:  "ValueError: Invalid model name for AI Configurator",
							},
						},
					}},
				},
			}
			Expect(k8sClient.Create(ctx, pod)).Should(Succeed())
1315
			defer func() { _ = k8sClient.Delete(ctx, pod) }()
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325

			// Reconcile - should capture error details
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{Name: dgdrName, Namespace: namespace},
			})
			Expect(err).NotTo(HaveOccurred())

			// Verify DGDR transitioned to Failed state
			var updated nvidiacomv1alpha1.DynamoGraphDeploymentRequest
			Expect(k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &updated)).Should(Succeed())
1326
			Expect(updated.Status.State).Should(Equal(nvidiacomv1alpha1.DGDRStateFailed))
1327
1328
1329
1330
1331
1332
1333
1334

			// Verify error condition contains detailed error
			condition := meta.FindStatusCondition(updated.Status.Conditions, ConditionTypeProfiling)
			Expect(condition).NotTo(BeNil())
			Expect(condition.Status).Should(Equal(metav1.ConditionFalse))
			Expect(condition.Message).Should(ContainSubstring("profiling job failed"))
		})
	})
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
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
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
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
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505

	Context("When parsing multi-document YAML", func() {
		It("Should extract DGD from ConfigMap + DGD YAML", func() {
			// Multi-document YAML with ConfigMap first, then DGD
			multiDocYAML := `---
apiVersion: v1
kind: ConfigMap
metadata:
  name: test-config
  namespace: default
data:
  some-data: "value"
---
apiVersion: nvidia.com/v1alpha1
kind: DynamoGraphDeployment
metadata:
  name: test-dgd
  namespace: default
spec:
  backendFramework: vllm
  services: {}`

			dgd, err := reconciler.extractDGDFromYAML([]byte(multiDocYAML))
			Expect(err).NotTo(HaveOccurred())
			Expect(dgd).NotTo(BeNil())
			Expect(dgd.Kind).Should(Equal("DynamoGraphDeployment"))
			Expect(dgd.Name).Should(Equal("test-dgd"))
			Expect(dgd.Spec.BackendFramework).Should(Equal("vllm"))
		})

		It("Should extract DGD from single-document YAML", func() {
			// Single document YAML without separator
			singleDocYAML := `apiVersion: nvidia.com/v1alpha1
kind: DynamoGraphDeployment
metadata:
  name: test-dgd-single
  namespace: default
spec:
  backendFramework: vllm
  services: {}`

			dgd, err := reconciler.extractDGDFromYAML([]byte(singleDocYAML))
			Expect(err).NotTo(HaveOccurred())
			Expect(dgd).NotTo(BeNil())
			Expect(dgd.Kind).Should(Equal("DynamoGraphDeployment"))
			Expect(dgd.Name).Should(Equal("test-dgd-single"))
		})

		It("Should handle DGD + ConfigMap order (DGD first)", func() {
			// Multi-document YAML with DGD first, then ConfigMap
			multiDocYAML := `---
apiVersion: nvidia.com/v1alpha1
kind: DynamoGraphDeployment
metadata:
  name: test-dgd-first
  namespace: default
spec:
  backendFramework: vllm
  services: {}
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: test-config
  namespace: default
data:
  some-data: "value"`

			dgd, err := reconciler.extractDGDFromYAML([]byte(multiDocYAML))
			Expect(err).NotTo(HaveOccurred())
			Expect(dgd).NotTo(BeNil())
			Expect(dgd.Kind).Should(Equal("DynamoGraphDeployment"))
			Expect(dgd.Name).Should(Equal("test-dgd-first"))
		})

		It("Should return error when no DGD found", func() {
			// YAML with only ConfigMap
			configMapOnlyYAML := `---
apiVersion: v1
kind: ConfigMap
metadata:
  name: test-config
  namespace: default
data:
  some-data: "value"`

			_, err := reconciler.extractDGDFromYAML([]byte(configMapOnlyYAML))
			Expect(err).To(HaveOccurred())
			Expect(err.Error()).Should(ContainSubstring("no DynamoGraphDeployment found"))
		})

		It("Should handle YAML with leading separator", func() {
			// YAML starting with --- separator
			yamlWithLeadingSeparator := `---
apiVersion: nvidia.com/v1alpha1
kind: DynamoGraphDeployment
metadata:
  name: test-dgd-leading
  namespace: default
spec:
  backendFramework: vllm
  services: {}`

			dgd, err := reconciler.extractDGDFromYAML([]byte(yamlWithLeadingSeparator))
			Expect(err).NotTo(HaveOccurred())
			Expect(dgd).NotTo(BeNil())
			Expect(dgd.Name).Should(Equal("test-dgd-leading"))
		})

		It("Should extract DGD and additional resources correctly", func() {
			// Multi-document YAML with ConfigMap and DGD
			multiDocYAML := `---
apiVersion: v1
kind: ConfigMap
metadata:
  name: model-config
  namespace: default
data:
  model.json: '{"name": "test-model"}'
---
apiVersion: nvidia.com/v1alpha1
kind: DynamoGraphDeployment
metadata:
  name: test-dgd
  namespace: default
spec:
  backendFramework: vllm
  services: {}`

			dgd, additionalResources, err := reconciler.extractResourcesFromYAML([]byte(multiDocYAML))
			Expect(err).NotTo(HaveOccurred())
			Expect(dgd).NotTo(BeNil())
			Expect(dgd.Name).Should(Equal("test-dgd"))
			Expect(additionalResources).To(HaveLen(1))
			Expect(additionalResources[0].GetKind()).Should(Equal("ConfigMap"))
			Expect(additionalResources[0].GetName()).Should(Equal("model-config"))
		})

		It("Should handle multiple additional resources", func() {
			// Multi-document YAML with multiple ConfigMaps and DGD
			multiDocYAML := `---
apiVersion: v1
kind: ConfigMap
metadata:
  name: config1
data:
  key1: value1
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: config2
data:
  key2: value2
---
apiVersion: nvidia.com/v1alpha1
kind: DynamoGraphDeployment
metadata:
  name: test-dgd
spec:
  backendFramework: vllm
  services: {}`

			dgd, additionalResources, err := reconciler.extractResourcesFromYAML([]byte(multiDocYAML))
			Expect(err).NotTo(HaveOccurred())
			Expect(dgd).NotTo(BeNil())
			Expect(additionalResources).To(HaveLen(2))
			Expect(additionalResources[0].GetName()).Should(Equal("config1"))
			Expect(additionalResources[1].GetName()).Should(Equal("config2"))
		})
	})
1506
1507
1508
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
1559
1560
1561
1562

	Context("GPU Discovery Integration Tests", func() {
		It("Should use GPU discovery when nodes have GPU labels", func() {
			ctx := context.Background()
			dgdrName := "test-dgdr-gpu-discovery"
			namespace := defaultNamespace

			// Create a node with GPU labels (simulating GFD labels)
			gpuNode := &corev1.Node{
				ObjectMeta: metav1.ObjectMeta{
					Name: "gpu-worker-1",
					Labels: map[string]string{
						"nvidia.com/gpu.count":   "8",
						"nvidia.com/gpu.product": "H100-SXM5-80GB",
						"nvidia.com/gpu.memory":  "81920",
					},
				},
			}
			Expect(k8sClient.Create(ctx, gpuNode)).Should(Succeed())
			defer func() { _ = k8sClient.Delete(ctx, gpuNode) }()

			// Create DGDR WITHOUT hardware config (should use GPU discovery)
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
					Model:   "test-model",
					Backend: "vllm",
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
						ProfilerImage: "test-profiler:latest",
						Config: &apiextensionsv1.JSON{
							Raw: []byte(`{
								"sla": {"ttft": 100.0, "itl": 1500.0},
								"engine": {"minNumGpusPerEngine": 1, "maxNumGpusPerEngine": 8}
							}`),
						},
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()

			// Reconcile - should succeed with GPU discovery
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{
					Name:      dgdrName,
					Namespace: namespace,
				},
			})
			Expect(err).NotTo(HaveOccurred())

			// Should transition to Pending (validation passed)
			var updated nvidiacomv1alpha1.DynamoGraphDeploymentRequest
			_ = k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &updated)
1563
			Expect(updated.Status.State).Should(Equal(nvidiacomv1alpha1.DGDRStatePending))
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
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
		})

		It("Should respect manual hardware config over GPU discovery", func() {
			ctx := context.Background()
			dgdrName := "test-dgdr-manual-override"
			namespace := defaultNamespace

			// Create a node with H100 GPUs
			gpuNode := &corev1.Node{
				ObjectMeta: metav1.ObjectMeta{
					Name: "gpu-worker-h100",
					Labels: map[string]string{
						"nvidia.com/gpu.count":   "8",
						"nvidia.com/gpu.product": "H100-SXM5-80GB",
						"nvidia.com/gpu.memory":  "81920",
					},
				},
			}
			Expect(k8sClient.Create(ctx, gpuNode)).Should(Succeed())
			defer func() { _ = k8sClient.Delete(ctx, gpuNode) }()

			// Create DGDR WITH manual hardware config (A100, not H100)
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
					Model:   "test-model",
					Backend: "vllm",
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
						ProfilerImage: "test-profiler:latest",
						Config: &apiextensionsv1.JSON{
							Raw: []byte(`{
								"sla": {"ttft": 100.0, "itl": 1500.0},
								"hardware": {
									"numGpusPerNode": 4,
									"gpuModel": "A100-SXM4-40GB",
									"gpuVramMib": 40960,
									"system": "a100_sxm"
								}
							}`),
						},
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()

			// Reconcile - should succeed and use manual config
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{
					Name:      dgdrName,
					Namespace: namespace,
				},
			})
			Expect(err).NotTo(HaveOccurred())

			// Should transition to Pending (validation passed with manual config)
			var updated nvidiacomv1alpha1.DynamoGraphDeploymentRequest
			_ = k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &updated)
1626
			Expect(updated.Status.State).Should(Equal(nvidiacomv1alpha1.DGDRStatePending))
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
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
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
		})

		It("Should succeed with GPU discovery when cluster has GPU nodes", func() {
			ctx := context.Background()
			dgdrName := "test-dgdr-with-autodiscovery"
			namespace := defaultNamespace

			// Create a GPU node so GPU discovery can succeed
			node := &corev1.Node{
				ObjectMeta: metav1.ObjectMeta{
					Name: "gpu-worker-autodiscovery",
					Labels: map[string]string{
						"nvidia.com/gpu.count":   "8",
						"nvidia.com/gpu.product": "H100-SXM5-80GB",
						"nvidia.com/gpu.memory":  "81920",
					},
				},
			}
			Expect(k8sClient.Create(ctx, node)).Should(Succeed())
			defer func() { _ = k8sClient.Delete(ctx, node) }()

			// Create DGDR WITHOUT hardware config - should use GPU discovery
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
					Model:   "test-model",
					Backend: "vllm",
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
						ProfilerImage: "test-profiler:latest",
						Config: &apiextensionsv1.JSON{
							Raw: []byte(`{
								"sla": {"ttft": 100.0, "itl": 1500.0}
							}`),
						},
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()

			// Reconcile - should succeed with GPU discovery
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{
					Name:      dgdrName,
					Namespace: namespace,
				},
			})
			Expect(err).NotTo(HaveOccurred())

			// Should transition to Pending
			var updated nvidiacomv1alpha1.DynamoGraphDeploymentRequest
			_ = k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &updated)
1683
			Expect(updated.Status.State).Should(Equal(nvidiacomv1alpha1.DGDRStatePending))
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
		})

		It("Should pass validation with explicit GPU ranges without GPU discovery", func() {
			ctx := context.Background()
			dgdrName := "test-dgdr-explicit-ranges"
			namespace := defaultNamespace

			// Intentionally don't create GPU nodes to test that explicit ranges work without GPU discovery
			// Create DGDR with explicit minNumGpusPerEngine/maxNumGpusPerEngine
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
					Model:   "test-model",
					Backend: "vllm",
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
						ProfilerImage: "test-profiler:latest",
						Config: &apiextensionsv1.JSON{
							Raw: []byte(`{
								"sla": {"ttft": 100.0, "itl": 1500.0},
								"engine": {
									"minNumGpusPerEngine": 2,
									"maxNumGpusPerEngine": 4
								},
								"hardware": {
									"numGpusPerNode": 8
								}
							}`),
						},
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()

			// Reconcile - should succeed (explicit ranges + minimal hardware bypass GPU discovery requirement)
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{
					Name:      dgdrName,
					Namespace: namespace,
				},
			})
			Expect(err).NotTo(HaveOccurred())

			// Should transition to Pending
			var updated nvidiacomv1alpha1.DynamoGraphDeploymentRequest
			_ = k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &updated)
1734
			Expect(updated.Status.State).Should(Equal(nvidiacomv1alpha1.DGDRStatePending))
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
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
1798
1799
1800
1801
1802
1803
1804
1805
		})

		It("Should use GPU discovery with heterogeneous nodes (picks best)", func() {
			ctx := context.Background()
			dgdrName := "test-dgdr-heterogeneous"
			namespace := defaultNamespace

			// Create nodes with different GPU configs
			nodeA100 := &corev1.Node{
				ObjectMeta: metav1.ObjectMeta{
					Name: "gpu-worker-a100",
					Labels: map[string]string{
						"nvidia.com/gpu.count":   "4",
						"nvidia.com/gpu.product": "A100-SXM4-40GB",
						"nvidia.com/gpu.memory":  "40960",
					},
				},
			}
			nodeH100 := &corev1.Node{
				ObjectMeta: metav1.ObjectMeta{
					Name: "gpu-worker-h100",
					Labels: map[string]string{
						"nvidia.com/gpu.count":   "8",
						"nvidia.com/gpu.product": "H100-SXM5-80GB",
						"nvidia.com/gpu.memory":  "81920",
					},
				},
			}
			Expect(k8sClient.Create(ctx, nodeA100)).Should(Succeed())
			Expect(k8sClient.Create(ctx, nodeH100)).Should(Succeed())
			defer func() {
				_ = k8sClient.Delete(ctx, nodeA100)
				_ = k8sClient.Delete(ctx, nodeH100)
			}()

			// Create DGDR without hardware config
			dgdr := &nvidiacomv1alpha1.DynamoGraphDeploymentRequest{
				ObjectMeta: metav1.ObjectMeta{
					Name:      dgdrName,
					Namespace: namespace,
				},
				Spec: nvidiacomv1alpha1.DynamoGraphDeploymentRequestSpec{
					Model:   "test-model",
					Backend: "vllm",
					ProfilingConfig: nvidiacomv1alpha1.ProfilingConfigSpec{
						ProfilerImage: "test-profiler:latest",
						Config: &apiextensionsv1.JSON{
							Raw: []byte(`{
								"sla": {"ttft": 100.0, "itl": 1500.0},
								"engine": {"minNumGpusPerEngine": 1, "maxNumGpusPerEngine": 8}
							}`),
						},
					},
				},
			}

			Expect(k8sClient.Create(ctx, dgdr)).Should(Succeed())
			defer func() { _ = k8sClient.Delete(ctx, dgdr) }()

			// Reconcile - should pick H100 (8 GPUs > 4 GPUs)
			_, err := reconciler.Reconcile(ctx, reconcile.Request{
				NamespacedName: types.NamespacedName{
					Name:      dgdrName,
					Namespace: namespace,
				},
			})
			Expect(err).NotTo(HaveOccurred())

			// Should transition to Pending (using H100 config)
			var updated nvidiacomv1alpha1.DynamoGraphDeploymentRequest
			_ = k8sClient.Get(ctx, types.NamespacedName{Name: dgdrName, Namespace: namespace}, &updated)
1806
			Expect(updated.Status.State).Should(Equal(nvidiacomv1alpha1.DGDRStatePending))
1807
1808
		})
	})
1809
})