Skip to content

kubectl sort-by uses an inconsistent comparison for two missing field values #1875

Description

@DevaanshPathak

What happened?

kubectl get --sort-by uses RuntimeSort.Less and TableSorter.Less to order objects. When both compared objects are missing the selected JSONPath field, both comparators return true in both directions:

Less(i, j) == true
Less(j, i) == true

This violates the sort.Interface contract, which requires Less(i, j) and Less(j, i) to both be false when elements compare equal. The inconsistent comparator can produce unpredictable ordering when multiple resources omit the selected field.

The problem is present in both missing-value branches in staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go.

What did you expect to happen?

Two objects that both lack the selected sort field should compare equal. Objects with missing fields should still sort before objects with present fields, preserving the existing behavior.

How can we reproduce it?

Construct two runtime objects without the selected field and compare them through RuntimeSort:

objects := []runtime.Object{
    &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: first}},
    &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: second}},
}
sorter := NewRuntimeSort({.metadata.labels.missing}, objects)

// Both currently return true.
sorter.Less(0, 1)
sorter.Less(1, 0)

The same behavior is reachable through TableSorter when two rows are missing the selected JSONPath value.

Proposed fix

Compute whether each side is missing first, return false when both are missing, otherwise keep missing values ordered before present values. Add focused unit coverage for both RuntimeSort and TableSorter.

Kubernetes version

Current master (35d4fd6c8148587b5186f50a7e376f1a6c70ce3a).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

kind/bugCategorizes issue or PR as related to a bug.needs-triageIndicates an issue or PR lacks a `triage/foo` label and requires one.sig/cliCategorizes an issue or PR as relevant to SIG CLI.

Type

No type

Projects

  • Status
    Needs Triage

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions