@@ -138,6 +138,13 @@ func (r *ScheduledScalingReconciler) applyScheduledScaling(ctx context.Context,
138138 return fmt .Errorf ("failed to get target tortoise: %w" , err )
139139 }
140140
141+ // Preserve existing HPA reference if present and not already specified in spec
142+ if t .Spec .TargetRefs .HorizontalPodAutoscalerName == nil && t .Status .Targets .HorizontalPodAutoscaler != "" {
143+ // If tortoise created an HPA but spec doesn't reference it explicitly,
144+ // add the reference to prevent HPA recreation during scheduled scaling
145+ t .Spec .TargetRefs .HorizontalPodAutoscalerName = & t .Status .Targets .HorizontalPodAutoscaler
146+ }
147+
141148 const annOriginal = "autoscaling.mercari.com/scheduledscaling-original-spec"
142149 const annMinReplicas = "autoscaling.mercari.com/scheduledscaling-min-replicas"
143150 if t .Annotations == nil {
@@ -235,6 +242,14 @@ func (r *ScheduledScalingReconciler) applyNormalScaling(ctx context.Context, sch
235242 if err := json .Unmarshal ([]byte (orig ), & spec ); err != nil {
236243 return fmt .Errorf ("unmarshal original tortoise spec: %w" , err )
237244 }
245+
246+ // Preserve HPA reference if it was added during scheduled scaling to prevent HPA recreation
247+ if spec .TargetRefs .HorizontalPodAutoscalerName == nil && t .Spec .TargetRefs .HorizontalPodAutoscalerName != nil && t .Status .Targets .HorizontalPodAutoscaler != "" {
248+ // If original spec didn't have HPA reference but current spec does (added during scheduled scaling),
249+ // preserve it to avoid HPA recreation when restoring
250+ spec .TargetRefs .HorizontalPodAutoscalerName = t .Spec .TargetRefs .HorizontalPodAutoscalerName
251+ }
252+
238253 t .Spec = spec
239254 delete (t .Annotations , annOriginal )
240255 delete (t .Annotations , annMinReplicas )
0 commit comments