@@ -26,7 +26,7 @@ import (
2626 "context"
2727 "fmt"
2828 "maps"
29- "sort "
29+ "slices "
3030 "time"
3131
3232 "github.com/robfig/cron"
@@ -373,11 +373,19 @@ func (r *CronJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct
373373 // NB: deleting these are "best effort" -- if we fail on a particular one,
374374 // we won't requeue just to finish the deleting.
375375 if cronJob .Spec .FailedJobsHistoryLimit != nil {
376- sort .Slice (failedJobs , func (i , j int ) bool {
377- if failedJobs [i ].Status .StartTime == nil {
378- return failedJobs [j ].Status .StartTime != nil
376+ slices .SortStableFunc (failedJobs , func (a , b * kbatch.Job ) int {
377+ aStartTime := a .Status .StartTime
378+ bStartTime := b .Status .StartTime
379+ if aStartTime == nil && bStartTime != nil {
380+ return 1
379381 }
380- return failedJobs [i ].Status .StartTime .Before (failedJobs [j ].Status .StartTime )
382+
383+ if aStartTime .Before (bStartTime ) {
384+ return - 1
385+ } else if bStartTime .Before (aStartTime ) {
386+ return 1
387+ }
388+ return 0
381389 })
382390 for i , job := range failedJobs {
383391 if int32 (i ) >= int32 (len (failedJobs ))- * cronJob .Spec .FailedJobsHistoryLimit {
@@ -392,11 +400,19 @@ func (r *CronJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct
392400 }
393401
394402 if cronJob .Spec .SuccessfulJobsHistoryLimit != nil {
395- sort .Slice (successfulJobs , func (i , j int ) bool {
396- if successfulJobs [i ].Status .StartTime == nil {
397- return successfulJobs [j ].Status .StartTime != nil
403+ slices .SortStableFunc (successfulJobs , func (a , b * kbatch.Job ) int {
404+ aStartTime := a .Status .StartTime
405+ bStartTime := b .Status .StartTime
406+ if aStartTime == nil && bStartTime != nil {
407+ return 1
408+ }
409+
410+ if aStartTime .Before (bStartTime ) {
411+ return - 1
412+ } else if bStartTime .Before (aStartTime ) {
413+ return 1
398414 }
399- return successfulJobs [ i ]. Status . StartTime . Before ( successfulJobs [ j ]. Status . StartTime )
415+ return 0
400416 })
401417 for i , job := range successfulJobs {
402418 if int32 (i ) >= int32 (len (successfulJobs ))- * cronJob .Spec .SuccessfulJobsHistoryLimit {
0 commit comments