"docs/pages/design-docs/event-plane.md" did not exist on "f9050aae852b2f4985f8194cd775be432d8312e7"
graph.go 55.1 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
 * 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.
 */

18
package dynamo
19
20
21

import (
	"context"
22
	"encoding/json"
23
	"fmt"
24
	"maps"
25
	"regexp"
26
	"sort"
27
28
	"strings"

29
30
	istioNetworking "istio.io/api/networking/v1beta1"

31
	"k8s.io/apimachinery/pkg/api/resource"
32
33
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
34
	"k8s.io/utils/ptr"
35
36

	grovev1alpha1 "github.com/NVIDIA/grove/operator/api/core/v1alpha1"
37
38
39
40
	"github.com/ai-dynamo/dynamo/deploy/operator/api/v1alpha1"
	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/discovery"
41
42
	"github.com/imdario/mergo"
	networkingv1beta1 "istio.io/client-go/pkg/apis/networking/v1beta1"
43
	corev1 "k8s.io/api/core/v1"
44
	networkingv1 "k8s.io/api/networking/v1"
45
46
)

47
48
49
50
51
52
53
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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
// RestartState holds the restart state for DGD services.
type RestartState struct {
	// Timestamp is the restart timestamp to apply as the annotation value.
	// Format: RFC3339
	Timestamp string
	// ServicesToAnnotate is the set of service names that should have the restart annotation.
	ServicesToAnnotate map[string]bool
}

// ShouldAnnotateService returns true if the given service should have a restart annotation.
func (s *RestartState) ShouldAnnotateService(serviceName string) bool {
	if s == nil || s.ServicesToAnnotate == nil {
		return false
	}
	return s.ServicesToAnnotate[serviceName]
}

// DetermineRestartState computes the restart state for DGD services.
func DetermineRestartState(dgd *v1alpha1.DynamoGraphDeployment, restartStatus *v1alpha1.RestartStatus) *RestartState {
	if restartStatus == nil {
		return nil
	}

	if dgd.Spec.Restart == nil || dgd.Spec.Restart.ID == "" {
		// Check if there's a completed restart we need to preserve
		if restartStatus.ObservedID != "" {
			return &RestartState{
				Timestamp:          restartStatus.ObservedID,
				ServicesToAnnotate: getAllServiceNames(dgd),
			}
		}
		return nil
	}

	specID := dgd.Spec.Restart.ID

	isNewRestart := restartStatus.ObservedID == "" ||
		dgd.Spec.Restart.ID != restartStatus.ObservedID

	if !isNewRestart && restartStatus.Phase == v1alpha1.RestartPhaseCompleted {
		return &RestartState{
			Timestamp:          specID,
			ServicesToAnnotate: getAllServiceNames(dgd),
		}
	}

	if IsParallelRestart(dgd) {
		return &RestartState{
			Timestamp:          specID,
			ServicesToAnnotate: getAllServiceNames(dgd),
		}
	}

	// Sequential restart (default or specified)
	return &RestartState{
		Timestamp:          specID,
		ServicesToAnnotate: getServicesToAnnotateForSequentialRestart(dgd, restartStatus),
	}
}

// getAllServiceNames returns a map of all service names in the DGD.
func getAllServiceNames(dgd *v1alpha1.DynamoGraphDeployment) map[string]bool {
	services := make(map[string]bool, len(dgd.Spec.Services))
	for serviceName := range dgd.Spec.Services {
		services[serviceName] = true
	}
	return services
}

// IsParallelRestart returns true if the restart strategy is parallel.
func IsParallelRestart(dgd *v1alpha1.DynamoGraphDeployment) bool {
	if dgd.Spec.Restart == nil || dgd.Spec.Restart.Strategy == nil {
		return false // Default is sequential
	}
	return dgd.Spec.Restart.Strategy.Type == v1alpha1.RestartStrategyTypeParallel
}

// getServicesToAnnotateForSequentialRestart determines which services should be annotated
// for a sequential restart in progress.
func getServicesToAnnotateForSequentialRestart(dgd *v1alpha1.DynamoGraphDeployment, status *v1alpha1.RestartStatus) map[string]bool {
	services := make(map[string]bool)

	order := GetRestartOrder(dgd)
	if len(order) == 0 {
		return services
	}

	// New restart or Pending phase - only first service needs to be annotated
	if status == nil ||
		status.Phase == v1alpha1.RestartPhasePending ||
		len(status.InProgress) == 0 {
		services[order[0]] = true
		return services
	}

	// Find the max index among in-progress services
	inProgress := make(map[string]bool)
	for _, svc := range status.InProgress {
		inProgress[svc] = true
	}

	maxIndex := -1
	for i, svc := range order {
		if inProgress[svc] {
			if i > maxIndex {
				maxIndex = i
			}
		}
	}

	// Add all services up to and including maxIndex
	// Services before the in-progress one have completed and need their annotation preserved
	if maxIndex >= 0 {
		for i := 0; i <= maxIndex; i++ {
			services[order[i]] = true
		}
	}

	return services
}

// GetRestartOrder returns the order of services for sequential restart.
// If not specified, returns a deterministic alphabetical order.
func GetRestartOrder(dgd *v1alpha1.DynamoGraphDeployment) []string {
	if dgd.Spec.Restart != nil && dgd.Spec.Restart.Strategy != nil && len(dgd.Spec.Restart.Strategy.Order) > 0 {
		return dgd.Spec.Restart.Strategy.Order
	}

	order := make([]string, 0, len(dgd.Spec.Services))
	for serviceName := range dgd.Spec.Services {
		order = append(order, serviceName)
	}
	sort.Strings(order)
	return order
}

183
// ServiceConfig represents the YAML configuration structure for a service
184
type DynamoConfig struct {
185
186
187
188
	Enabled       bool   `yaml:"enabled"`
	Namespace     string `yaml:"namespace"`
	Name          string `yaml:"name"`
	ComponentType string `yaml:"component_type,omitempty"`
189
190
191
192
193
194
195
196
197
198
199
200
}

type Traffic struct {
	Timeout int `yaml:"timeout"`
}

type Autoscaling struct {
	MinReplicas int `yaml:"min_replicas"`
	MaxReplicas int `yaml:"max_replicas"`
}

type Config struct {
201
202
203
204
205
206
207
208
209
	Dynamo       *DynamoConfig          `yaml:"dynamo,omitempty"`
	Resources    *Resources             `yaml:"resources,omitempty"`
	Traffic      *Traffic               `yaml:"traffic,omitempty"`
	Autoscaling  *Autoscaling           `yaml:"autoscaling,omitempty"`
	HttpExposed  bool                   `yaml:"http_exposed,omitempty"`
	ApiEndpoints []string               `yaml:"api_endpoints,omitempty"`
	Workers      *int32                 `yaml:"workers,omitempty"`
	TotalGpus    *int32                 `yaml:"total_gpus,omitempty"`
	ExtraPodSpec *v1alpha1.ExtraPodSpec `yaml:"extraPodSpec,omitempty"`
210
211
212
213
214
215
216
217
}

type ServiceConfig struct {
	Name         string              `yaml:"name"`
	Dependencies []map[string]string `yaml:"dependencies,omitempty"`
	Config       Config              `yaml:"config"`
}

218
219
220
221
222
223
224
type Resources struct {
	CPU    *string           `yaml:"cpu,omitempty" json:"cpu,omitempty"`
	Memory *string           `yaml:"memory,omitempty" json:"memory,omitempty"`
	GPU    *string           `yaml:"gpu,omitempty" json:"gpu,omitempty"`
	Custom map[string]string `yaml:"custom,omitempty" json:"custom,omitempty"`
}

225
226
227
228
229
230
231
232
233
234
235
236
237
type DynDeploymentConfig = map[string]*DynDeploymentServiceConfig

// ServiceConfig represents the configuration for a specific service
type DynDeploymentServiceConfig struct {
	ServiceArgs *ServiceArgs `json:"ServiceArgs,omitempty"`
}

// ServiceArgs represents the arguments that can be passed to any service
type ServiceArgs struct {
	Workers   *int32     `json:"workers,omitempty"`
	Resources *Resources `json:"resources,omitempty"`
}

238
239
240
241
242
243
244
func (s ServiceConfig) GetNamespace() *string {
	if s.Config.Dynamo == nil || s.Config.Dynamo.Namespace == "" {
		return nil
	}
	return &s.Config.Dynamo.Namespace
}

245
246
247
248
249
250
func ParseDynDeploymentConfig(ctx context.Context, jsonContent []byte) (DynDeploymentConfig, error) {
	var config DynDeploymentConfig
	err := json.Unmarshal(jsonContent, &config)
	return config, err
}

251
// GenerateDynamoComponentsDeployments generates a map of DynamoComponentDeployments from a DynamoGraphConfig
252
func GenerateDynamoComponentsDeployments(ctx context.Context, parentDynamoGraphDeployment *v1alpha1.DynamoGraphDeployment, defaultIngressSpec *v1alpha1.IngressSpec, restartState *RestartState, existingRestartAnnotations map[string]string) (map[string]*v1alpha1.DynamoComponentDeployment, error) {
253
	deployments := make(map[string]*v1alpha1.DynamoComponentDeployment)
254
	for componentName, component := range parentDynamoGraphDeployment.Spec.Services {
255
		dynamoNamespace := getDynamoNamespace(parentDynamoGraphDeployment, component)
256
		deployment := &v1alpha1.DynamoComponentDeployment{}
257
		deployment.Spec.DynamoComponentDeploymentSharedSpec = *component
258
		deployment.Name = GetDynamoComponentName(parentDynamoGraphDeployment, componentName)
259
		deployment.Spec.BackendFramework = parentDynamoGraphDeployment.Spec.BackendFramework
260
		deployment.Namespace = parentDynamoGraphDeployment.Namespace
261
		deployment.Spec.ServiceName = componentName
262
		deployment.Spec.DynamoNamespace = &dynamoNamespace
263
264
265
266
267
		labels := make(map[string]string)
		// add the labels in the spec in order to label all sub-resources
		deployment.Spec.Labels = labels
		// and add the labels to the deployment itself
		deployment.Labels = labels
268
		labels[commonconsts.KubeLabelDynamoComponent] = componentName
269
		labels[commonconsts.KubeLabelDynamoNamespace] = dynamoNamespace
270
		labels[commonconsts.KubeLabelDynamoGraphDeploymentName] = parentDynamoGraphDeployment.Name
271
272
273

		// Propagate metrics annotation from parent deployment if present
		if parentDynamoGraphDeployment.Annotations != nil {
274
275
276
			if deployment.Spec.Annotations == nil {
				deployment.Spec.Annotations = make(map[string]string)
			}
277
278
279
			if val, exists := parentDynamoGraphDeployment.Annotations[commonconsts.KubeAnnotationEnableMetrics]; exists {
				deployment.Spec.Annotations[commonconsts.KubeAnnotationEnableMetrics] = val
			}
280
281
282
			if val, exists := parentDynamoGraphDeployment.Annotations[commonconsts.KubeAnnotationDynamoDiscoveryBackend]; exists {
				deployment.Spec.Annotations[commonconsts.KubeAnnotationDynamoDiscoveryBackend] = val
			}
283
284
		}

285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
		// Apply restart annotation if this service should be restarted.
		// For services not in the current restart order, preserve their existing annotation
		// to avoid triggering unwanted rollouts when a new restart begins.
		if restartState.ShouldAnnotateService(componentName) {
			if deployment.Spec.Annotations == nil {
				deployment.Spec.Annotations = make(map[string]string)
			}
			deployment.Spec.Annotations[commonconsts.RestartAnnotation] = restartState.Timestamp
		} else if existingRestartAnnotations != nil {
			if existingRestartAt, ok := existingRestartAnnotations[componentName]; ok && existingRestartAt != "" {
				if deployment.Spec.Annotations == nil {
					deployment.Spec.Annotations = make(map[string]string)
				}
				deployment.Spec.Annotations[commonconsts.RestartAnnotation] = existingRestartAt
			}
		}

302
		if component.ComponentType == commonconsts.ComponentTypePlanner {
303
			// ensure that the extraPodSpec is not nil
304
			if deployment.Spec.ExtraPodSpec == nil {
305
				deployment.Spec.ExtraPodSpec = &v1alpha1.ExtraPodSpec{}
306
			}
307
308
309
310
311
312
			// ensure that the embedded PodSpec struct is not nil
			if deployment.Spec.ExtraPodSpec.PodSpec == nil {
				deployment.Spec.ExtraPodSpec.PodSpec = &corev1.PodSpec{}
			}
			// finally set the service account name
			deployment.Spec.ExtraPodSpec.PodSpec.ServiceAccountName = commonconsts.PlannerServiceAccountName
313
		}
314
		if deployment.IsFrontendComponent() && defaultIngressSpec != nil && deployment.Spec.Ingress == nil {
315
			deployment.Spec.Ingress = defaultIngressSpec
316
317
318
		}
		// merge the envs from the parent deployment with the envs from the service
		if len(parentDynamoGraphDeployment.Spec.Envs) > 0 {
319
			deployment.Spec.Envs = MergeEnvs(parentDynamoGraphDeployment.Spec.Envs, deployment.Spec.Envs)
320
321
322
323
324
325
326
327
328
329
330
		}
		err := updateDynDeploymentConfig(deployment, commonconsts.DynamoServicePort)
		if err != nil {
			return nil, err
		}
		err = overrideWithDynDeploymentConfig(ctx, deployment)
		if err != nil {
			return nil, err
		}
		// we only override the replicas if it is not set in the CRD.
		// replicas, if set in the CRD must always be the source of truth.
331
332
		if component.Replicas != nil {
			deployment.Spec.Replicas = component.Replicas
333
		}
334
		deployments[componentName] = deployment
335
336
337
	}
	return deployments, nil
}
338

339
340
341
func getDynamoNamespace(object metav1.Object, service *v1alpha1.DynamoComponentDeploymentSharedSpec) string {
	if service.GlobalDynamoNamespace {
		return commonconsts.GlobalDynamoNamespace
342
	}
343
	return fmt.Sprintf("%s-%s", object.GetNamespace(), object.GetName())
344
345
}

346
347
348
// updateDynDeploymentConfig updates the runtime config object for the given dynamoDeploymentComponent
// It updates the port for the given service (if it is the main component)
func updateDynDeploymentConfig(dynamoDeploymentComponent *v1alpha1.DynamoComponentDeployment, newPort int) error {
349
	if dynamoDeploymentComponent.IsFrontendComponent() {
350
351
352
353
354
355
356
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
383
384
385
		dynamoDeploymentConfig := dynamoDeploymentComponent.GetDynamoDeploymentConfig()
		if dynamoDeploymentConfig != nil {
			var config map[string]any
			if err := json.Unmarshal(dynamoDeploymentConfig, &config); err != nil {
				return fmt.Errorf("failed to unmarshal %v: %w", commonconsts.DynamoDeploymentConfigEnvVar, err)
			}
			// Safely navigate and update the config
			if serviceConfig, ok := config[dynamoDeploymentComponent.Spec.ServiceName].(map[string]any); ok {
				serviceConfig["port"] = newPort
			}
			// Marshal back to JSON string
			updated, err := json.Marshal(config)
			if err != nil {
				return fmt.Errorf("failed to marshal updated config: %w", err)
			}
			dynamoDeploymentComponent.SetDynamoDeploymentConfig(updated)
		}
	}
	return nil
}

func overrideWithDynDeploymentConfig(ctx context.Context, dynamoDeploymentComponent *v1alpha1.DynamoComponentDeployment) error {
	dynamoDeploymentConfig := dynamoDeploymentComponent.GetDynamoDeploymentConfig()
	if dynamoDeploymentConfig == nil {
		return nil
	}
	dynDeploymentConfig, err := ParseDynDeploymentConfig(ctx, dynamoDeploymentConfig)
	if err != nil {
		return fmt.Errorf("failed to parse %v: %w", commonconsts.DynamoDeploymentConfigEnvVar, err)
	}
	componentDynConfig := dynDeploymentConfig[dynamoDeploymentComponent.Spec.ServiceName]
	if componentDynConfig != nil {
		if componentDynConfig.ServiceArgs != nil && componentDynConfig.ServiceArgs.Workers != nil {
			dynamoDeploymentComponent.Spec.Replicas = componentDynConfig.ServiceArgs.Workers
		}
		if componentDynConfig.ServiceArgs != nil && componentDynConfig.ServiceArgs.Resources != nil {
386
387
			requests := &v1alpha1.ResourceItem{}
			limits := &v1alpha1.ResourceItem{}
388
			if dynamoDeploymentComponent.Spec.Resources == nil {
389
				dynamoDeploymentComponent.Spec.Resources = &v1alpha1.Resources{
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
					Requests: requests,
					Limits:   limits,
				}
			} else {
				if dynamoDeploymentComponent.Spec.Resources.Requests != nil {
					requests = dynamoDeploymentComponent.Spec.Resources.Requests
				} else {
					dynamoDeploymentComponent.Spec.Resources.Requests = requests
				}
				if dynamoDeploymentComponent.Spec.Resources.Limits != nil {
					limits = dynamoDeploymentComponent.Spec.Resources.Limits
				} else {
					dynamoDeploymentComponent.Spec.Resources.Limits = limits
				}
			}
			if componentDynConfig.ServiceArgs.Resources.GPU != nil {
				requests.GPU = *componentDynConfig.ServiceArgs.Resources.GPU
				limits.GPU = *componentDynConfig.ServiceArgs.Resources.GPU
			}
			if componentDynConfig.ServiceArgs.Resources.CPU != nil {
				requests.CPU = *componentDynConfig.ServiceArgs.Resources.CPU
				limits.CPU = *componentDynConfig.ServiceArgs.Resources.CPU
			}
			if componentDynConfig.ServiceArgs.Resources.Memory != nil {
				requests.Memory = *componentDynConfig.ServiceArgs.Resources.Memory
				limits.Memory = *componentDynConfig.ServiceArgs.Resources.Memory
			}
			if componentDynConfig.ServiceArgs.Resources.Custom != nil {
				requests.Custom = componentDynConfig.ServiceArgs.Resources.Custom
				limits.Custom = componentDynConfig.ServiceArgs.Resources.Custom
			}
		}
	}
	return nil
}

426
func MergeEnvs(common, specific []corev1.EnvVar) []corev1.EnvVar {
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
	envMap := make(map[string]corev1.EnvVar)

	// Add all common environment variables.
	for _, env := range common {
		envMap[env.Name] = env
	}

	// Override or add with service-specific environment variables.
	for _, env := range specific {
		envMap[env.Name] = env
	}

	// Convert the map back to a slice.
	merged := make([]corev1.EnvVar, 0, len(envMap))
	for _, env := range envMap {
		merged = append(merged, env)
	}
444
445
446
	sort.Slice(merged, func(i, j int) bool {
		return merged[i].Name < merged[j].Name
	})
447
448
	return merged
}
449

450
func GetDynamoComponentName(dynamoDeployment *v1alpha1.DynamoGraphDeployment, component string) string {
451
	return fmt.Sprintf("%s-%s", dynamoDeployment.Name, strings.ToLower(component))
452
}
453
454
455
456
457

type SecretsRetriever interface {
	GetSecrets(namespace, registry string) ([]string, error)
}

458
// applyCliqueStartupDependencies configures StartsAfter dependencies for cliques in a PodCliqueSet
459
460
461
462
463
464
// based on the backend framework and multinode deployment patterns.
//
// Rules:
// - For VLLM and SGLang: worker cliques start after leader clique
// - For TRTLLM: leader clique starts after worker cliques
// - Only applies to multinode deployments (numberOfNodes > 1)
465
// - Sets the PodCliqueSet StartupType to Explicit if any dependencies are configured
466
func applyCliqueStartupDependencies(
467
	gangSet *grovev1alpha1.PodCliqueSet,
468
469
470
471
	roles []ServiceRole,
	backendFramework BackendFramework,
	numberOfNodes int32,
) {
472
473
474
	// enabled for TRTLLM multinode deployments only
	// TODO: reactivate for all backends when we have a better way to handle the readiness probe for the leader.
	enabled := backendFramework == BackendFrameworkTRTLLM && numberOfNodes > 1
475

476
	if !enabled {
477
478
		return // No dependencies for single-node deployments
	}
479

480
481
482
	// Build maps of leader and worker clique names
	var leaderCliqueName string
	var workerCliqueNames []string
483

484
485
486
487
488
489
490
	for _, r := range roles {
		cliqueName := strings.ToLower(r.Name)
		switch r.Role {
		case RoleLeader:
			leaderCliqueName = cliqueName
		case RoleWorker:
			workerCliqueNames = append(workerCliqueNames, cliqueName)
491
		}
492
493
494
495
496
497
498
499
500
501
502
503
	}

	// Apply dependencies to cliques
	hasDependencies := false
	for _, clique := range gangSet.Spec.Template.Cliques {
		// Find the corresponding role for this clique
		var cliqueRole Role
		for _, r := range roles {
			if strings.ToLower(r.Name) == clique.Name {
				cliqueRole = r.Role
				break
			}
504
505
		}

506
507
508
509
510
		// Determine dependencies for this clique
		startsAfter := getCliqueStartupDependencies(cliqueRole, backendFramework, leaderCliqueName, workerCliqueNames)
		if len(startsAfter) > 0 {
			clique.Spec.StartsAfter = startsAfter
			hasDependencies = true
511
		}
512
	}
513

514
515
516
517
518
519
	// Set explicit startup type if we have any dependencies
	if hasDependencies {
		explicitStartupType := grovev1alpha1.CliqueStartupTypeExplicit
		gangSet.Spec.Template.StartupType = &explicitStartupType
	}
}
520

521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
// getCliqueStartupDependencies determines the StartsAfter dependencies for a clique
// based on its role, backend framework, and available leader/worker clique names.
//
// Rules:
// - For VLLM and SGLang: worker cliques start after leader clique
// - For TRTLLM: leader clique starts after worker cliques
// - For other backends or single-node deployments: no dependencies
func getCliqueStartupDependencies(
	role Role,
	backendFramework BackendFramework,
	leaderCliqueName string,
	workerCliqueNames []string,
) []string {
	switch backendFramework {
	case BackendFrameworkVLLM, BackendFrameworkSGLang:
		// For vllm and sglang: worker cliques start after leader clique
		if role == RoleWorker && leaderCliqueName != "" {
			return []string{leaderCliqueName}
		}
	case BackendFrameworkTRTLLM:
		// For trtllm: leader clique starts after worker cliques
		if role == RoleLeader && len(workerCliqueNames) > 0 {
			return workerCliqueNames
544
545
		}
	}
546
547
548

	// No dependencies for other cases
	return nil
549
550
}

551
func GenerateComponentService(ctx context.Context, dynamoDeployment *v1alpha1.DynamoGraphDeployment, component *v1alpha1.DynamoComponentDeploymentSharedSpec, componentName string, isK8sDiscoveryEnabled bool) (*corev1.Service, error) {
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
	if component.DynamoNamespace == nil {
		return nil, fmt.Errorf("expected DynamoComponentDeployment %s to have a dynamoNamespace", componentName)
	}
	componentName = GetDynamoComponentName(dynamoDeployment, componentName)

	var servicePort corev1.ServicePort
	if component.ComponentType == commonconsts.ComponentTypeFrontend {
		servicePort = corev1.ServicePort{
			Name:       commonconsts.DynamoServicePortName,
			Port:       commonconsts.DynamoServicePort,
			TargetPort: intstr.FromString(commonconsts.DynamoContainerPortName),
			Protocol:   corev1.ProtocolTCP,
		}
	} else {
		servicePort = corev1.ServicePort{
			Name:       commonconsts.DynamoSystemPortName,
			Port:       commonconsts.DynamoSystemPort,
			TargetPort: intstr.FromString(commonconsts.DynamoSystemPortName),
			Protocol:   corev1.ProtocolTCP,
		}
	}
573
574
575
	service := &corev1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Name:      componentName,
576
			Namespace: dynamoDeployment.Namespace,
577
578
579
		},
		Spec: corev1.ServiceSpec{
			Selector: map[string]string{
580
581
				commonconsts.KubeLabelDynamoComponentType: component.ComponentType,
				commonconsts.KubeLabelDynamoNamespace:     *component.DynamoNamespace,
582
			},
583
			Ports: []corev1.ServicePort{servicePort},
584
585
		},
	}
586
587
588
	if isK8sDiscoveryEnabled {
		service.Labels = map[string]string{
			commonconsts.KubeLabelDynamoDiscoveryBackend: "kubernetes",
589
			commonconsts.KubeLabelDynamoDiscoveryEnabled: commonconsts.KubeLabelValueTrue,
590
591
		}
	}
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
	return service, nil
}

func GenerateComponentIngress(ctx context.Context, componentName, componentNamespace string, ingressSpec v1alpha1.IngressSpec) *networkingv1.Ingress {
	resourceName := componentName
	ingress := &networkingv1.Ingress{
		ObjectMeta: metav1.ObjectMeta{
			Name:      resourceName,
			Namespace: componentNamespace,
		},
	}
	host := getIngressHost(ingressSpec)
	ingress.Spec = networkingv1.IngressSpec{
		IngressClassName: ingressSpec.IngressControllerClassName,
		Rules: []networkingv1.IngressRule{
			{
				Host: host,
				IngressRuleValue: networkingv1.IngressRuleValue{
					HTTP: &networkingv1.HTTPIngressRuleValue{
						Paths: []networkingv1.HTTPIngressPath{
							{
								Path:     "/",
								PathType: &[]networkingv1.PathType{networkingv1.PathTypePrefix}[0],
								Backend: networkingv1.IngressBackend{
									Service: &networkingv1.IngressServiceBackend{
										Name: resourceName,
										Port: networkingv1.ServiceBackendPort{
											Number: commonconsts.DynamoServicePort,
										},
									},
								},
							},
						},
					},
				},
			},
		},
	}
	if ingressSpec.TLS != nil {
		ingress.Spec.TLS = []networkingv1.IngressTLS{
			{
				Hosts:      []string{host},
				SecretName: ingressSpec.TLS.SecretName,
			},
		}
	}
	return ingress
}

func getIngressHost(ingressSpec v1alpha1.IngressSpec) string {
	host := ingressSpec.Host
	if ingressSpec.HostPrefix != nil {
		host = *ingressSpec.HostPrefix + host
	}
	ingressSuffix := commonconsts.DefaultIngressSuffix
	if ingressSpec.HostSuffix != nil {
		ingressSuffix = *ingressSpec.HostSuffix
	}
	return fmt.Sprintf("%s.%s", host, ingressSuffix)
}

func GenerateComponentVirtualService(ctx context.Context, componentName, componentNamespace string, ingressSpec v1alpha1.IngressSpec) *networkingv1beta1.VirtualService {
	vs := &networkingv1beta1.VirtualService{
		ObjectMeta: metav1.ObjectMeta{
			Name:      componentName,
			Namespace: componentNamespace,
		},
	}
660
661
662
663
664
665
666
667
668
669
670
671
672
	if ingressSpec.IsVirtualServiceEnabled() {
		vs.Spec = istioNetworking.VirtualService{
			Hosts: []string{
				getIngressHost(ingressSpec),
			},
			Gateways: []string{*ingressSpec.VirtualServiceGateway},
			Http: []*istioNetworking.HTTPRoute{
				{
					Match: []*istioNetworking.HTTPMatchRequest{
						{
							Uri: &istioNetworking.StringMatch{
								MatchType: &istioNetworking.StringMatch_Prefix{Prefix: "/"},
							},
673
674
						},
					},
675
676
677
678
679
680
681
					Route: []*istioNetworking.HTTPRouteDestination{
						{
							Destination: &istioNetworking.Destination{
								Host: componentName,
								Port: &istioNetworking.PortSelector{
									Number: commonconsts.DynamoServicePort,
								},
682
683
684
685
686
							},
						},
					},
				},
			},
687
		}
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
	}
	return vs
}

func GenerateDefaultIngressSpec(dynamoDeployment *v1alpha1.DynamoGraphDeployment, ingressConfig controller_common.IngressConfig) v1alpha1.IngressSpec {
	res := v1alpha1.IngressSpec{
		Enabled:           ingressConfig.VirtualServiceGateway != "" || ingressConfig.IngressControllerClassName != "",
		Host:              dynamoDeployment.Name,
		UseVirtualService: ingressConfig.VirtualServiceGateway != "",
	}
	if ingressConfig.IngressControllerClassName != "" {
		res.IngressControllerClassName = &ingressConfig.IngressControllerClassName
	}
	if ingressConfig.IngressControllerTLSSecret != "" {
		res.TLS = &v1alpha1.IngressTLSSpec{
			SecretName: ingressConfig.IngressControllerTLSSecret,
		}
	}
	if ingressConfig.IngressHostSuffix != "" {
		res.HostSuffix = &ingressConfig.IngressHostSuffix
	}
	if ingressConfig.VirtualServiceGateway != "" {
		res.VirtualServiceGateway = &ingressConfig.VirtualServiceGateway
	}
	return res
}
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758

// Define Role enum for leader/worker/main
// Use this type everywhere instead of string for role

type Role string

const (
	RoleLeader Role = "leader"
	RoleWorker Role = "worker"
	RoleMain   Role = "main"
)

// Update ServiceRole struct for expandRolesForService

type ServiceRole struct {
	Name     string
	Role     Role
	Replicas int32
}

// Update expandRolesForService to use Role
func expandRolesForService(serviceName string, serviceReplicas *int32, numberOfNodes int32) []ServiceRole {
	var roles []ServiceRole
	if numberOfNodes > 1 {
		roles = append(roles, ServiceRole{Name: serviceName + "-" + commonconsts.GroveRoleSuffixLeader, Role: RoleLeader, Replicas: 1})
		roles = append(roles, ServiceRole{Name: serviceName + "-" + commonconsts.GroveRoleSuffixWorker, Role: RoleWorker, Replicas: numberOfNodes - 1})
	} else {
		roles = append(roles, ServiceRole{Name: serviceName, Role: RoleMain, Replicas: *serviceReplicas})
	}
	return roles
}

// Define BackendFramework enum for sglang, vllm, trtllm

type BackendFramework string

const (
	BackendFrameworkSGLang BackendFramework = "sglang"
	BackendFrameworkVLLM   BackendFramework = "vllm"
	BackendFrameworkTRTLLM BackendFramework = "trtllm"
)

// Backend interface for modular backend logic
// Each backend (SGLang, VLLM, etc.) implements this interface
type Backend interface {
759
760
	UpdateContainer(container *corev1.Container, numberOfNodes int32, role Role, component *v1alpha1.DynamoComponentDeploymentSharedSpec, serviceName string, multinodeDeployer MultinodeDeployer)
	UpdatePodSpec(podSpec *corev1.PodSpec, numberOfNodes int32, role Role, component *v1alpha1.DynamoComponentDeploymentSharedSpec, serviceName string)
761
762
763
764
765
}

// NoopBackend does no processing - used for non-worker components like frontend, planner, router
type NoopBackend struct{}

766
func (b *NoopBackend) UpdateContainer(container *corev1.Container, numberOfNodes int32, role Role, component *v1alpha1.DynamoComponentDeploymentSharedSpec, serviceName string, multinodeDeployer MultinodeDeployer) {
767
768
769
	// No-op: frontend, planner, router, etc. don't need backend-specific processing
}

770
func (b *NoopBackend) UpdatePodSpec(podSpec *corev1.PodSpec, numberOfNodes int32, role Role, component *v1alpha1.DynamoComponentDeploymentSharedSpec, serviceName string) {
771
772
773
	// No-op: frontend, planner, router, etc. don't need backend-specific processing
}

774
775
776
type MultinodeDeployer interface {
	GetLeaderHostname(serviceName string) string
	GetHostNames(serviceName string, numberOfNodes int32) []string
777
	GetNodeRank() (string, bool) // returns (rank, needsShellInterpretation)
778
	NeedsDNSWait() bool          // returns true if DNS wait is needed to launch multinode components
779
780
}

781
// BackendFactory creates backend instances based on the framework type
782
func BackendFactory(backendFramework BackendFramework, controllerConfig controller_common.Config) Backend {
783
784
785
786
787
788
	switch backendFramework {
	case BackendFrameworkSGLang:
		return &SGLangBackend{}
	case BackendFrameworkVLLM:
		return &VLLMBackend{}
	case BackendFrameworkTRTLLM:
789
790
791
		return &TRTLLMBackend{
			MpiRunSecretName: controllerConfig.MpiRun.SecretName,
		}
792
793
794
795
796
797
798
	case BackendFrameworkNoop:
		return &NoopBackend{}
	default:
		return nil
	}
}

799
800
801
802
803
804
805
806
807
808
809
func MultinodeDeployerFactory(multinodeDeploymentType commonconsts.MultinodeDeploymentType) MultinodeDeployer {
	switch multinodeDeploymentType {
	case commonconsts.MultinodeDeploymentTypeGrove:
		return &GroveMultinodeDeployer{}
	case commonconsts.MultinodeDeploymentTypeLWS:
		return &LWSMultinodeDeployer{}
	default:
		return nil
	}
}

810
811
// isWorkerComponent checks if a component is a worker that needs backend framework detection
func isWorkerComponent(componentType string) bool {
812
813
814
	return componentType == commonconsts.ComponentTypeWorker ||
		componentType == commonconsts.ComponentTypePrefill ||
		componentType == commonconsts.ComponentTypeDecode
815
816
817
818
}

// addStandardEnvVars adds the standard environment variables that are common to both Grove and Controller
func addStandardEnvVars(container *corev1.Container, controllerConfig controller_common.Config) {
819
	standardEnvVars := []corev1.EnvVar{}
820
	if controllerConfig.NatsAddress != "" {
821
		standardEnvVars = append(standardEnvVars, corev1.EnvVar{
822
823
824
825
826
827
			Name:  "NATS_SERVER",
			Value: controllerConfig.NatsAddress,
		})
	}

	if controllerConfig.EtcdAddress != "" {
828
		standardEnvVars = append(standardEnvVars, corev1.EnvVar{
829
830
831
832
			Name:  "ETCD_ENDPOINTS",
			Value: controllerConfig.EtcdAddress,
		})
	}
833
834

	if controllerConfig.ModelExpressURL != "" {
835
		standardEnvVars = append(standardEnvVars, corev1.EnvVar{
836
837
838
839
			Name:  "MODEL_EXPRESS_URL",
			Value: controllerConfig.ModelExpressURL,
		})
	}
840
841
842
843
844
845
846
847
	if controllerConfig.PrometheusEndpoint != "" {
		standardEnvVars = append(standardEnvVars, corev1.EnvVar{
			Name:  "PROMETHEUS_ENDPOINT",
			Value: controllerConfig.PrometheusEndpoint,
		})
	}
	// merge the env vars to allow users to override the standard env vars
	container.Env = MergeEnvs(standardEnvVars, container.Env)
848
849
}

850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
// applyDefaultSecurityContext sets secure defaults for pod security context.
// Currently only sets fsGroup to solve volume permission issues.
// Does NOT set runAsUser/runAsGroup/runAsNonRoot to maintain backward compatibility
// with images that may expect to run as root.
// User-provided security context values (via extraPodSpec) will override these defaults.
func applyDefaultSecurityContext(podSpec *corev1.PodSpec) {
	// Initialize SecurityContext if not present
	if podSpec.SecurityContext == nil {
		podSpec.SecurityContext = &corev1.PodSecurityContext{}
	}

	// Only set fsGroup by default
	// This fixes volume permission issues without forcing a specific UID/GID
	// which maintains compatibility with both root and non-root images
	if podSpec.SecurityContext.FSGroup == nil {
		podSpec.SecurityContext.FSGroup = ptr.To(int64(commonconsts.DefaultSecurityContextFSGroup))
	}
}

869
870
871
// GenerateBasePodSpec creates a basic PodSpec with common logic shared between controller and grove
// Includes standard environment variables (DYNAMO_PORT, NATS_SERVER, ETCD_ENDPOINTS)
// Deployment-specific environment merging should be handled by the caller
872
873
//
//nolint:gocyclo
874
func GenerateBasePodSpec(
875
	component *v1alpha1.DynamoComponentDeploymentSharedSpec,
876
877
	backendFramework BackendFramework,
	secretsRetriever SecretsRetriever,
878
	parentGraphDeploymentName string,
879
880
881
882
883
884
	namespace string,
	role Role,
	numberOfNodes int32,
	controllerConfig controller_common.Config,
	multinodeDeploymentType commonconsts.MultinodeDeploymentType,
	serviceName string,
885
) (*corev1.PodSpec, error) {
886
	// Start with base container generated per component type
887
	componentContext := generateComponentContext(component, parentGraphDeploymentName, namespace, numberOfNodes, controllerConfig.GetDiscoveryBackend(component.Annotations))
888
889
	componentDefaults := ComponentDefaultsFactory(component.ComponentType)
	container, err := componentDefaults.GetBaseContainer(componentContext)
890
	if err != nil {
891
		return nil, fmt.Errorf("failed to get base container: %w", err)
892
	}
893

894
895
896
897
	if component.ExtraPodSpec != nil && component.ExtraPodSpec.MainContainer != nil {
		main := component.ExtraPodSpec.MainContainer.DeepCopy()
		if main != nil {
			// merge the extraPodSpec from the parent deployment with the extraPodSpec from the service
898
			containerEnvs := container.Env
899
			err = mergo.Merge(&container, *main, mergo.WithOverride)
900
			if err != nil {
901
				return nil, fmt.Errorf("failed to merge extraPodSpec: %w", err)
902
			}
903
904

			// main container fields that require special handling
905
			container.Env = MergeEnvs(containerEnvs, container.Env)
906
907
908
909
910
			// Note: startup probe does not have its own top level field so it must be passed in extraPodSpec.MainContainer
			// We want to overwrite entirely if provided rather than merge
			if main.StartupProbe != nil {
				container.StartupProbe = main.StartupProbe
			}
911
912
		}
	}
913
	container.Env = MergeEnvs(container.Env, component.Envs)
914

915
916
917
918
919
920
921
922
923
	// Merge probes entirely if they are passed (no partial merge)
	if component.LivenessProbe != nil {
		container.LivenessProbe = component.LivenessProbe.DeepCopy()
	}
	if component.ReadinessProbe != nil {
		container.ReadinessProbe = component.ReadinessProbe.DeepCopy()
	}

	overrideResources, err := controller_common.GetResourcesConfig(component.Resources)
924
	if err != nil {
925
		return nil, fmt.Errorf("failed to get resources config: %w", err)
926
	}
927
928
929
930
931
932
	// Requests
	if overrideResources != nil && len(overrideResources.Requests) > 0 {
		if container.Resources.Requests == nil {
			container.Resources.Requests = corev1.ResourceList{}
		}
		maps.Copy(container.Resources.Requests, overrideResources.Requests)
933
	}
934
935
936
937
938
939
940
941
942

	// Limits
	if overrideResources != nil && len(overrideResources.Limits) > 0 {
		if container.Resources.Limits == nil {
			container.Resources.Limits = corev1.ResourceList{}
		}
		maps.Copy(container.Resources.Limits, overrideResources.Limits)
	}

943
944
945
946
947
948
949
950
	// Claims
	if overrideResources != nil && len(overrideResources.Claims) > 0 {
		if container.Resources.Claims == nil {
			container.Resources.Claims = []corev1.ResourceClaim{}
		}
		container.Resources.Claims = append(container.Resources.Claims, overrideResources.Claims...)
	}

951
952
	shouldDisableImagePullSecret := component.Annotations[commonconsts.KubeAnnotationDisableImagePullSecretDiscovery] == commonconsts.KubeLabelValueTrue

953
	imagePullSecrets := []corev1.LocalObjectReference{}
954
	if !shouldDisableImagePullSecret && secretsRetriever != nil && component.ExtraPodSpec != nil && component.ExtraPodSpec.MainContainer != nil && component.ExtraPodSpec.MainContainer.Image != "" {
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
		secretsName, err := secretsRetriever.GetSecrets(namespace, component.ExtraPodSpec.MainContainer.Image)
		if err == nil {
			for _, secretName := range secretsName {
				imagePullSecrets = append(imagePullSecrets, corev1.LocalObjectReference{Name: secretName})
			}
		}
	}
	if component.EnvFromSecret != nil {
		container.EnvFrom = append(container.EnvFrom, corev1.EnvFromSource{
			SecretRef: &corev1.SecretEnvSource{
				LocalObjectReference: corev1.LocalObjectReference{Name: *component.EnvFromSecret},
			},
		})
	}

	addStandardEnvVars(&container, controllerConfig)

972
	volumes := make([]corev1.Volume, 0, len(component.VolumeMounts)+1) // +1 for shared memory volume
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991

	for _, volumeMount := range component.VolumeMounts {
		if volumeMount.Name == "" {
			return nil, fmt.Errorf("volumeMount.name is required when volumeMounts is set")
		}

		// Determine mount point
		mountPoint := volumeMount.MountPoint
		if volumeMount.UseAsCompilationCache && mountPoint == "" {
			// Use backend-specific default for compilation cache
			defaultMountPoint := getDefaultCompilationCacheMountPoint(backendFramework)
			if defaultMountPoint == "" {
				return nil, fmt.Errorf("volumeMount with useAsCompilationCache=true requires an explicit mountPoint for backend framework %s (no default available)", backendFramework)
			}
			mountPoint = defaultMountPoint
		} else if !volumeMount.UseAsCompilationCache && mountPoint == "" {
			return nil, fmt.Errorf("volumeMount.mountPoint is required when useAsCompilationCache is false")
		}

992
		volumes = append(volumes, corev1.Volume{
993
			Name: volumeMount.Name,
994
995
			VolumeSource: corev1.VolumeSource{
				PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
996
					ClaimName: volumeMount.Name,
997
998
999
				},
			},
		})
1000

1001
		container.VolumeMounts = append(container.VolumeMounts, corev1.VolumeMount{
1002
1003
			Name:      volumeMount.Name,
			MountPath: mountPoint,
1004
1005
		})
	}
1006
1007
1008
1009
	if shmVol, shmMount := generateSharedMemoryVolumeAndMount(component.SharedMemory); shmVol != nil && shmMount != nil {
		volumes = append(volumes, *shmVol)
		container.VolumeMounts = append(container.VolumeMounts, *shmMount)
	}
1010

1011
	// Apply backend-specific container modifications
1012
1013
	multinodeDeployer := MultinodeDeployerFactory(multinodeDeploymentType)
	if multinodeDeployer == nil {
1014
		return nil, fmt.Errorf("unsupported multinode deployment type: %s", multinodeDeploymentType)
1015
	}
1016
	backend := BackendFactory(backendFramework, controllerConfig)
1017
	if backend == nil {
1018
		return nil, fmt.Errorf("unsupported backend framework: %s", backendFramework)
1019
	}
1020
	backend.UpdateContainer(&container, numberOfNodes, role, component, serviceName, multinodeDeployer)
1021
1022

	// get base podspec from component
1023
	podSpec, err := componentDefaults.GetBasePodSpec(componentContext)
1024
	if err != nil {
1025
		return nil, fmt.Errorf("failed to get base podspec: %w", err)
1026
1027
	}

1028
1029
1030
1031
1032
	// Check if user provided their own security context before merging
	userProvidedSecurityContext := component.ExtraPodSpec != nil &&
		component.ExtraPodSpec.PodSpec != nil &&
		component.ExtraPodSpec.PodSpec.SecurityContext != nil

1033
	if component.ExtraPodSpec != nil && component.ExtraPodSpec.PodSpec != nil {
1034
1035
1036
		// merge extraPodSpec PodSpec with base podspec
		err := mergo.Merge(&podSpec, component.ExtraPodSpec.PodSpec.DeepCopy(), mergo.WithOverride)
		if err != nil {
1037
			return nil, fmt.Errorf("failed to merge extraPodSpec: %w", err)
1038
		}
1039
	}
1040

1041
1042
1043
1044
1045
1046
1047
	// Apply default security context ONLY if user didn't provide any security context
	// If user provides ANY securityContext (even partial), they get full control with no defaults injected
	// This allows users to intentionally set fields to nil (e.g., to run as root)
	if !userProvidedSecurityContext {
		applyDefaultSecurityContext(&podSpec)
	}

1048
	if controllerConfig.IsK8sDiscoveryEnabled(component.Annotations) {
1049
1050
1051
		if podSpec.ServiceAccountName == "" {
			podSpec.ServiceAccountName = discovery.GetK8sDiscoveryServiceAccountName(parentGraphDeploymentName)
		}
1052
1053
	}

1054
1055
	podSpec.Containers = append(podSpec.Containers, container)
	podSpec.Volumes = append(podSpec.Volumes, volumes...)
1056
	podSpec.ImagePullSecrets = controller_common.AppendUniqueImagePullSecrets(podSpec.ImagePullSecrets, imagePullSecrets)
1057

1058
	backend.UpdatePodSpec(&podSpec, numberOfNodes, role, component, serviceName)
1059
	return &podSpec, nil
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
}

func setMetricsLabels(labels map[string]string, dynamoGraphDeployment *v1alpha1.DynamoGraphDeployment) {
	// Convert user-provided metrics annotation into controller-managed label
	// By default (no annotation), metrics are enabled
	if metricsAnnotationValue, ok := dynamoGraphDeployment.Annotations[commonconsts.KubeAnnotationEnableMetrics]; ok && metricsAnnotationValue == commonconsts.KubeLabelValueFalse {
		// Explicitly disabled, don't add the label
		return
	}
	// Any other value (including empty) enables metrics
	labels[commonconsts.KubeLabelMetricsEnabled] = commonconsts.KubeLabelValueTrue
}

1073
func generateComponentContext(component *v1alpha1.DynamoComponentDeploymentSharedSpec, parentGraphDeploymentName string, namespace string, numberOfNodes int32, discoveryBackend string) ComponentContext {
1074
1075
	componentContext := ComponentContext{
		numberOfNodes:                  numberOfNodes,
1076
		ComponentType:                  component.ComponentType,
1077
1078
		ParentGraphDeploymentName:      parentGraphDeploymentName,
		ParentGraphDeploymentNamespace: namespace,
1079
		DiscoveryBackend:               discoveryBackend,
1080
1081
1082
1083
1084
1085
1086
	}
	if component.DynamoNamespace != nil {
		componentContext.DynamoNamespace = *component.DynamoNamespace
	}
	return componentContext
}

1087
1088
// GeneratePodSpecForComponent creates a PodSpec for Grove deployments (simplified wrapper)
func GeneratePodSpecForComponent(
1089
	component *v1alpha1.DynamoComponentDeploymentSharedSpec,
1090
1091
1092
1093
1094
1095
1096
1097
	backendFramework BackendFramework,
	secretsRetriever SecretsRetriever,
	dynamoDeployment *v1alpha1.DynamoGraphDeployment,
	role Role,
	numberOfNodes int32,
	controllerConfig controller_common.Config,
	multinodeDeploymentType commonconsts.MultinodeDeploymentType,
	serviceName string,
1098
) (*corev1.PodSpec, error) {
1099
1100
1101
	if len(dynamoDeployment.Spec.Envs) > 0 {
		component.Envs = MergeEnvs(dynamoDeployment.Spec.Envs, component.Envs)
	}
1102
	podSpec, err := GenerateBasePodSpec(component, backendFramework, secretsRetriever, dynamoDeployment.Name, dynamoDeployment.Namespace, role, numberOfNodes, controllerConfig, multinodeDeploymentType, serviceName)
1103
	if err != nil {
1104
		return nil, err
1105
1106
1107
1108
	}
	return podSpec, nil
}

1109
1110
// GenerateGrovePodCliqueSet generates a Grove PodCliqueSet for the given deployment, supporting both single-node and multinode cases.
func GenerateGrovePodCliqueSet(
1111
1112
1113
1114
	ctx context.Context,
	dynamoDeployment *v1alpha1.DynamoGraphDeployment,
	controllerConfig controller_common.Config,
	secretsRetriever SecretsRetriever,
1115
1116
	restartState *RestartState,
	existingRestartAnnotations map[string]string,
1117
1118
) (*grovev1alpha1.PodCliqueSet, error) {
	gangSet := &grovev1alpha1.PodCliqueSet{}
1119
1120
1121
1122
1123
1124
	gangSet.Name = dynamoDeployment.Name
	gangSet.Namespace = dynamoDeployment.Namespace
	gangSet.Spec.Replicas = 1
	gangSet.Spec.Template.HeadlessServiceConfig = &grovev1alpha1.HeadlessServiceConfig{
		PublishNotReadyAddresses: true,
	}
1125
	gangSet.Spec.Template.StartupType = ptr.To(grovev1alpha1.CliqueStartupTypeAnyOrder)
1126
1127
1128
	if controllerConfig.Grove.TerminationDelay > 0 {
		gangSet.Spec.Template.TerminationDelay = &metav1.Duration{Duration: controllerConfig.Grove.TerminationDelay}
	}
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139

	// Validate kai-scheduler queue once if kai-scheduler is enabled
	var validatedQueueName string
	if controllerConfig.Grove.Enabled && controllerConfig.KaiScheduler.Enabled {
		var err error
		validatedQueueName, err = DetermineKaiSchedulerQueue(ctx, dynamoDeployment.Annotations)
		if err != nil {
			return nil, fmt.Errorf("failed to determine kai-scheduler queue: %w", err)
		}
	}

1140
1141
	discoveryBackend := controllerConfig.GetDiscoveryBackend(dynamoDeployment.Annotations)

1142
1143
	var scalingGroups []grovev1alpha1.PodCliqueScalingGroupConfig
	for serviceName, component := range dynamoDeployment.Spec.Services {
1144
		dynamoNamespace := getDynamoNamespace(dynamoDeployment, component)
1145
		component.DynamoNamespace = &dynamoNamespace
1146
1147
1148
1149
1150
1151
		// Determine backend framework using hybrid approach
		backendFramework, err := getBackendFrameworkFromComponent(component, dynamoDeployment)
		if err != nil {
			return nil, fmt.Errorf("failed to determine backend framework for service %s: %w", serviceName, err)
		}

1152
1153
1154
1155
1156
1157
1158
		if discoveryBackend != "" {
			if component.Annotations == nil {
				component.Annotations = make(map[string]string)
			}
			component.Annotations[commonconsts.KubeAnnotationDynamoDiscoveryBackend] = discoveryBackend
		}

1159
		numberOfNodes := component.GetNumberOfNodes()
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
		isMultinode := numberOfNodes > 1
		roles := expandRolesForService(serviceName, component.Replicas, numberOfNodes)
		var cliqueNames []string

		for _, r := range roles {
			podSpec, err := GeneratePodSpecForComponent(
				component,
				backendFramework,
				secretsRetriever,
				dynamoDeployment,
				r.Role,
				numberOfNodes,
				controllerConfig,
				commonconsts.MultinodeDeploymentTypeGrove,
				serviceName,
			)
			if err != nil {
				return nil, fmt.Errorf("failed to generate podSpec for role %s: %w", r.Name, err)
			}

			clique := &grovev1alpha1.PodCliqueTemplateSpec{
				Name: strings.ToLower(r.Name),
				Spec: grovev1alpha1.PodCliqueSpec{
1183
1184
1185
1186
					RoleName:     strings.ToLower(r.Name),
					Replicas:     r.Replicas,
					MinAvailable: ptr.To(int32(1)),
					PodSpec:      *podSpec,
1187
1188
				},
			}
1189
			labels, err := generateLabels(component, dynamoDeployment, serviceName)
1190
1191
1192
1193
1194
1195
1196
1197
			if err != nil {
				return nil, fmt.Errorf("failed to generate labels: %w", err)
			}
			clique.Labels = labels
			annotations, err := generateAnnotations(component)
			if err != nil {
				return nil, fmt.Errorf("failed to generate annotations: %w", err)
			}
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214

			// Apply restart annotation if this service should be restarted.
			// For services not in the current restart order, preserve their existing annotation
			// to avoid triggering unwanted rollouts when a new restart begins.
			if restartState.ShouldAnnotateService(serviceName) {
				if annotations == nil {
					annotations = make(map[string]string)
				}
				annotations[commonconsts.RestartAnnotation] = restartState.Timestamp
			} else if existingRestartAnnotations != nil {
				if existingTimestamp, ok := existingRestartAnnotations[serviceName]; ok {
					if annotations == nil {
						annotations = make(map[string]string)
					}
					annotations[commonconsts.RestartAnnotation] = existingTimestamp
				}
			}
1215
			clique.Annotations = annotations
1216
1217
1218
1219

			// Inject kai-scheduler settings if enabled
			injectKaiSchedulerIfEnabled(clique, controllerConfig, validatedQueueName)

1220
1221
1222
1223
1224
1225
1226
1227
1228
			gangSet.Spec.Template.Cliques = append(gangSet.Spec.Template.Cliques, clique)
			cliqueNames = append(cliqueNames, strings.ToLower(r.Name))
		}

		// Apply startup dependencies for this service
		applyCliqueStartupDependencies(gangSet, roles, backendFramework, numberOfNodes)

		if isMultinode {
			scalingGroups = append(scalingGroups, grovev1alpha1.PodCliqueScalingGroupConfig{
1229
1230
1231
1232
				Name:         strings.ToLower(serviceName),
				CliqueNames:  cliqueNames,
				Replicas:     component.Replicas,
				MinAvailable: ptr.To(int32(1)),
1233
1234
1235
1236
1237
1238
1239
			})
		}
	}
	if len(scalingGroups) > 0 {
		gangSet.Spec.Template.PodCliqueScalingGroupConfigs = scalingGroups
	}

1240
	return gangSet, nil
1241
1242
}

1243
func generateLabels(component *v1alpha1.DynamoComponentDeploymentSharedSpec, dynamoDeployment *v1alpha1.DynamoGraphDeployment, componentName string) (map[string]string, error) {
1244
1245
	labels := make(map[string]string)
	labels[commonconsts.KubeLabelDynamoSelector] = GetDynamoComponentName(dynamoDeployment, componentName)
1246
	labels[commonconsts.KubeLabelDynamoGraphDeploymentName] = dynamoDeployment.Name
1247
	labels[commonconsts.KubeLabelDynamoComponent] = componentName
1248
1249
1250
	if component.DynamoNamespace != nil {
		labels[commonconsts.KubeLabelDynamoNamespace] = *component.DynamoNamespace
	}
1251
1252
1253
	if component.ComponentType != "" {
		labels[commonconsts.KubeLabelDynamoComponentType] = component.ComponentType
	}
1254
1255
1256
	if component.SubComponentType != "" {
		labels[commonconsts.KubeLabelDynamoSubComponentType] = component.SubComponentType
	}
1257
1258
	// Add base model label if modelRef is specified
	AddBaseModelLabel(labels, component.ModelRef)
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
	setMetricsLabels(labels, dynamoDeployment)
	if component.Labels != nil {
		err := mergo.Merge(&labels, component.Labels, mergo.WithOverride)
		if err != nil {
			return nil, fmt.Errorf("failed to merge labels: %w", err)
		}
	}
	if component.ExtraPodMetadata != nil {
		err := mergo.Merge(&labels, component.ExtraPodMetadata.Labels, mergo.WithOverride)
		if err != nil {
			return nil, fmt.Errorf("failed to merge extraPodMetadata labels: %w", err)
		}
	}
	return labels, nil
}

1275
func generateAnnotations(component *v1alpha1.DynamoComponentDeploymentSharedSpec) (map[string]string, error) {
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
	annotations := make(map[string]string)
	if component.Annotations != nil {
		err := mergo.Merge(&annotations, component.Annotations, mergo.WithOverride)
		if err != nil {
			return nil, fmt.Errorf("failed to merge annotations: %w", err)
		}
	}
	if component.ExtraPodMetadata != nil {
		err := mergo.Merge(&annotations, component.ExtraPodMetadata.Annotations, mergo.WithOverride)
		if err != nil {
			return nil, fmt.Errorf("failed to merge extraPodMetadata annotations: %w", err)
		}
	}
	return annotations, nil
}

// detectBackendFrameworkFromArgs detects the backend framework from command/args
func detectBackendFrameworkFromArgs(command []string, args []string) (BackendFramework, error) {
	// Combine command and args to search through all parts
	allParts := append(command, args...)
	fullCommand := strings.Join(allParts, " ")

	// Pattern to match python -m dynamo.{backend}.something
	patterns := map[BackendFramework]*regexp.Regexp{
		BackendFrameworkVLLM:   regexp.MustCompile(`python[0-9.]*\s+[^|&;]*-m\s+[^|&;]*dynamo\.vllm[^|&;]*`),
		BackendFrameworkSGLang: regexp.MustCompile(`python[0-9.]*\s+[^|&;]*-m\s+[^|&;]*dynamo\.sglang[^|&;]*`),
		BackendFrameworkTRTLLM: regexp.MustCompile(`python[0-9.]*\s+[^|&;]*-m\s+[^|&;]*dynamo\.trtllm[^|&;]*`),
	}

	var detected []BackendFramework
	for framework, pattern := range patterns {
		if pattern.MatchString(fullCommand) {
			detected = append(detected, framework)
		}
	}

	if len(detected) == 0 {
1313
		return BackendFrameworkNoop, nil
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
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
	}

	if len(detected) > 1 {
		return "", fmt.Errorf("multiple backend frameworks detected from command: %v in %q", detected, fullCommand)
	}

	return detected[0], nil
}

// BackendFrameworkNoop represents no backend processing needed
const BackendFrameworkNoop BackendFramework = "noop"

// determineBackendFramework is the core logic for hybrid backend framework detection
// Takes extracted parameters and applies the detection logic
func determineBackendFramework(
	componentType string,
	command []string,
	args []string,
	explicitBackendFramework string,
) (BackendFramework, error) {
	// Check if this is a worker component - if not, use noop backend
	if !isWorkerComponent(componentType) {
		return BackendFrameworkNoop, nil
	}

	// Worker component - apply backend framework detection
	var detectedFramework BackendFramework
	var detectionError error

	// Try to detect from command/args
	if len(command) > 0 || len(args) > 0 {
		detected, err := detectBackendFrameworkFromArgs(command, args)
		if err == nil {
			detectedFramework = detected
		} else {
			detectionError = err
		}
	}

	// Get explicit framework
	var explicitFramework BackendFramework
	if explicitBackendFramework != "" {
		explicitFramework = BackendFramework(explicitBackendFramework)
	}

	// Validate consistency if both detected and explicit exist
1360
	if detectedFramework != "" && detectedFramework != BackendFrameworkNoop && explicitFramework != "" && detectedFramework != explicitFramework {
1361
1362
1363
1364
1365
		return "", fmt.Errorf("backend framework mismatch: detected %q from command but explicitly configured as %q",
			detectedFramework, explicitFramework)
	}

	// Return in order of preference: detected > explicit > error
1366
	if detectedFramework != "" && detectedFramework != BackendFrameworkNoop {
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
		return detectedFramework, nil
	}

	if explicitFramework != "" {
		return explicitFramework, nil
	}

	// If we couldn't detect and no explicit config, return error
	if detectionError != nil {
		return "", fmt.Errorf("could not determine backend framework: %w", detectionError)
	}

	// No command/args to detect from and no explicit config
1380
	return BackendFrameworkNoop, nil
1381
1382
1383
1384
1385
1386
1387
1388
}

// getBackendFrameworkFromComponent attempts to determine backend framework using hybrid approach:
// 1. Check if component is a worker - if not, return noop
// 2. For workers: try to detect from command/args, fall back to explicit config
// 3. Return error if worker has neither detection nor explicit config
// Also validates consistency between detected and explicit if both exist
func getBackendFrameworkFromComponent(
1389
	component *v1alpha1.DynamoComponentDeploymentSharedSpec,
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
	dynamoDeployment *v1alpha1.DynamoGraphDeployment,
) (BackendFramework, error) {
	// Extract command/args from component
	var command, args []string
	if component.ExtraPodSpec != nil && component.ExtraPodSpec.MainContainer != nil {
		command = component.ExtraPodSpec.MainContainer.Command
		args = component.ExtraPodSpec.MainContainer.Args
	}

	// Extract explicit backend framework from deployment
	explicitBackendFramework := dynamoDeployment.Spec.BackendFramework

	return determineBackendFramework(
		component.ComponentType,
		command,
		args,
		explicitBackendFramework,
	)
}

// ConvertDynamoComponentDeploymentToSpec converts a DynamoComponentDeployment to our component spec interface
// This is a helper for the controller to use our backend logic
1412
1413
func ConvertDynamoComponentDeploymentToSpec(dynComponent *v1alpha1.DynamoComponentDeployment) *v1alpha1.DynamoComponentDeploymentSharedSpec {
	return dynComponent.Spec.DynamoComponentDeploymentSharedSpec.DeepCopy()
1414
1415
}

1416
1417
// GetBackendFrameworkFromDynamoComponent determines backend framework for a DynamoComponentDeployment
func GetBackendFrameworkFromDynamoComponent(dynComponent *v1alpha1.DynamoComponentDeployment) (BackendFramework, error) {
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
	// Extract command/args from component
	var command, args []string
	if dynComponent.Spec.ExtraPodSpec != nil && dynComponent.Spec.ExtraPodSpec.MainContainer != nil {
		command = dynComponent.Spec.ExtraPodSpec.MainContainer.Command
		args = dynComponent.Spec.ExtraPodSpec.MainContainer.Args
	}

	// Extract explicit backend framework
	explicitBackendFramework := dynComponent.Spec.BackendFramework

	return determineBackendFramework(
		dynComponent.Spec.ComponentType,
		command,
		args,
		explicitBackendFramework,
	)
}

// GenerateBasePodSpecForController generates a PodSpec using backend logic for controller usage
// This preserves the base pod generation while allowing controller-specific enhancements
func GenerateBasePodSpecForController(
	dynComponent *v1alpha1.DynamoComponentDeployment,
	secretsRetriever SecretsRetriever,
	controllerConfig controller_common.Config,
	role Role,
	multinodeDeploymentType commonconsts.MultinodeDeploymentType,
1444
) (*corev1.PodSpec, error) {
1445
1446
1447
	// Convert to our interface
	componentSpec := ConvertDynamoComponentDeploymentToSpec(dynComponent)

1448
	numberOfNodes := componentSpec.GetNumberOfNodes()
1449
1450

	// Determine backend framework using hybrid approach
1451
	backendFramework, err := GetBackendFrameworkFromDynamoComponent(dynComponent)
1452
	if err != nil {
1453
		return nil, fmt.Errorf("failed to determine backend framework: %w", err)
1454
1455
1456
1457
1458
1459
1460
1461
1462
	}

	// Generate base PodSpec with standard env vars using merged component envs
	// For controller usage, we may not have serviceName, so use the component name as fallback
	serviceName := dynComponent.Name
	podSpec, err := GenerateBasePodSpec(
		componentSpec,
		backendFramework,
		secretsRetriever,
1463
		dynComponent.GetParentGraphDeploymentName(),
1464
1465
1466
1467
1468
1469
1470
1471
		dynComponent.Namespace,
		role,
		numberOfNodes,
		controllerConfig,
		multinodeDeploymentType,
		serviceName,
	)
	if err != nil {
1472
		return nil, err
1473
1474
1475
1476
1477
	}

	return podSpec, nil
}

1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
// getDefaultCompilationCacheMountPoint returns the default mount point for compilation cache based on backend framework
func getDefaultCompilationCacheMountPoint(backendFramework BackendFramework) string {
	switch backendFramework {
	case BackendFrameworkVLLM:
		return commonconsts.DefaultVLLMCacheMountPoint
	case BackendFrameworkSGLang, BackendFrameworkTRTLLM:
		// SGLang and TensorRT-LLM don't currently support compilation caches
		// Return empty string as these should not be used
		return ""
	default:
		// For unknown backends, don't assume compilation cache support
		return ""
	}
}

1493
1494
1495
1496
1497
1498
1499
1500
1501
func generateSharedMemoryVolumeAndMount(spec *v1alpha1.SharedMemorySpec) (*corev1.Volume, *corev1.VolumeMount) {
	// default: enabled=true, size=8Gi
	size := resource.MustParse(commonconsts.DefaultSharedMemorySize)
	if spec != nil {
		if spec.Disabled {
			return nil, nil
		}
		if !spec.Size.IsZero() {
			size = spec.Size
1502
1503
1504
1505
1506
1507
1508
		}
	}
	volume := corev1.Volume{
		Name: commonconsts.KubeValueNameSharedMemory,
		VolumeSource: corev1.VolumeSource{
			EmptyDir: &corev1.EmptyDirVolumeSource{
				Medium:    corev1.StorageMediumMemory,
1509
				SizeLimit: &size,
1510
1511
1512
1513
1514
			},
		},
	}
	volumeMount := corev1.VolumeMount{
		Name:      commonconsts.KubeValueNameSharedMemory,
1515
		MountPath: commonconsts.DefaultSharedMemoryMountPath,
1516
	}
1517
	return &volume, &volumeMount
1518
}