A store list sorts fine in every test. Then production logs show IllegalArgumentException: Comparison method violates its general contract! from sortedWith. The message means your comparator breaks a rule that the sort relies on. In the code below, two stacked causes produce it. First, the comparator answers -1 in both directions when both stores are pinned. It also never returns 0 for two stores at the same distance. Second, the JVM’s TimSort only notices this while it merges sorted runs. A list under 32 elements never merges, so small test lists sort quietly and never throw. In our repro, 10-item lists never crashed. With 200 items, 203 of 1,000 random lists crashed. The fix is to build the comparator from compareByDescending and thenBy. They produce the signs for you. Then test it with a list of at least 32 elements that includes ties.
A pinned-first store list that crashes only in production
The running example is a store picker. Pinned stores go first. Everything else is ordered by distance from the user. Distances come back rounded to 0.5 km, so ties are common. Here is the comparator.
data class Store(val id: Int, val pinned: Boolean, val distanceKm: Double)
val byPinnedThenDistance = Comparator<Store> { a, b ->
when {
a.pinned -> -1
b.pinned -> 1
else -> if (a.distanceKm < b.distanceKm) -1 else 1
}
}
fun sortStores(stores: List<Store>) = stores.sortedWith(byPinnedThenDistance)
We generated random lists with a fixed seed. One store in ten is pinned. Distances are multiples of 0.5 km from 0 to 9.5. Each list size ran 1,000 times on Kotlin 2.4.20 and OpenJDK 25.
size=10 crashes=0/1000
size=31 crashes=0/1000
size=32 crashes=6/1000
size=50 crashes=4/1000
size=200 crashes=203/1000
java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo
at java.util.TimSort.mergeAt
at java.util.TimSort.mergeCollapse
at java.util.TimSort.sort
at java.util.Arrays.sort
at kotlin.collections.ArraysKt___ArraysJvmKt.sortWith(_ArraysJvm.kt:2206)
at kotlin.collections.CollectionsKt___CollectionsKt.sortedWith(_Collections.kt:1260)
The size cliff is sharp. No list under 32 crashed. At 32 a few did. At 200 roughly one list in five did. A unit test with eight hand-picked stores passes every time. A user with 200 nearby stores sees a crash on some loads. Other loads work.
The trace also shows where the work happens. In the Kotlin 2.4.20 stdlib, sortedWith copies the list to an array. On the JVM, sortWith then calls java.util.Arrays.sort. So the exception comes from the JDK sort, not from Kotlin.
Comparison method violates its general contract when one pair gets two answers
The Comparator contract has three rules. Swapping the arguments must flip the sign. Ordering must be transitive. Two elements that compare equal must compare the same way against every third element. This is root cause one. Our comparator breaks the first rule in two places.
The pinned branch is the first. Take two pinned stores, a and b. compare(a, b) hits a.pinned and returns -1. compare(b, a) hits b.pinned first and also returns -1. Each store claims to come before the other. The when reads naturally from top to bottom. That hides the missing case where both flags are true.
The distance branch is the second. It has no path that returns 0. Two unpinned stores at 2.0 km return 1 in both directions. Even compare(c, c) on the same store returns 1. So every tie is a contradiction. With distances rounded to 0.5 km, a 200-store list has many ties.
two pinned stores: compare(a, b) = -1 compare(b, a) = -1 same store: compare(c, c) = 1 distance NaN vs 2.0: compare(n, c) = 1 compare(c, n) = 1
The last line shows a third trap in the same branch. A store with an unknown location often gets Double.NaN as its distance. Every < comparison with NaN is false. So the hand-written branch returns 1 both ways for that store too.
TimSort only checks the contract while it merges
Root cause two is in the sort itself. The JDK’s TimSort sets MIN_MERGE to 32. For a range smaller than that, it runs a binary insertion sort with no merges. The exception is thrown in only two places, mergeLo and mergeHi. Each fires when a merge runs out of elements in a way that a valid comparator can’t cause. A list of 31 stores never reaches either method. The broken comparator still runs. It just produces some order and returns.
Above 32 elements, detection still isn’t guaranteed. A merge throws only when the contradictions happen to empty one side early. That is why 200-store lists crashed about 20% of the time instead of always. The Arrays.sort docs say this outright. The IllegalArgumentException is marked optional, thrown “if the comparator is found to violate” the contract.
Android behaves the same way. Its libcore TimSort comes from OpenJDK. It has the same 32-element threshold and the same message in mergeLo and mergeHi. So on current Android, the crash also depends on list size and data.
The fix: let compareBy build the signs
Describe the ordering as keys and let the stdlib produce the signs. More branches in the when would leave the same risk in place.
val byPinnedThenDistance = compareByDescending<Store> { it.pinned }
.thenBy { it.distanceKm }
.thenBy { it.id }
fun sortStores(stores: List<Store>) = stores.sortedWith(byPinnedThenDistance)
compareByDescending { it.pinned } uses Boolean.compareTo, so true sorts first. Two pinned stores now compare equal on that key. thenBy only runs when the earlier keys are equal. So pinned stores fall through to distance as well.
thenBy { it.distanceKm } compares boxed doubles with compareTo. The Double docs define that as a total order. NaN equals itself and sorts above positive infinity. So stores with an unknown distance land at the end, consistently.
thenBy { it.id } isn’t needed for the contract. Ties already return 0. It makes the order deterministic when the input order changes. sortedWith is stable, so without it, tied stores keep their input order. A server that returns stores in a different order each time would reshuffle the list.
fixed size=10 crashes=0 wrongOrder=0 fixed size=200 crashes=0 wrongOrder=0 fixed, input [NaN (id 4), 2.0 km (id 3), pinned 1.0 km (id 2)] -> ids [2, 3, 4]
Zero crashes across the same 1,000 seeds at both sizes. Every result has pinned stores first and distances ascending. The test that guards this needs at least 32 stores, including two pinned and several ties. Otherwise it exercises the binary insertion path only and proves nothing about the merge.
How to answer it in a technical round
An interviewer may hand you the stack trace and the comparator. Work from the message back to the code.
- Name the message. It comes from TimSort and means the comparator broke its contract. The list isn’t being changed by another thread.
- Test antisymmetry by hand. Call
compare(a, b)andcompare(b, a)for two pinned stores. Both return -1. - Test ties and identity.
compare(c, c)returns 1, so the distance branch never says equal. Mention NaN as the same problem. - Explain why tests passed. TimSort runs no merges below 32 elements. Only merges throw. Above that, detection depends on the data.
- Fix it with
compareByDescending { it.pinned }.thenBy { it.distanceKm }. Add a tie-breaker if the order must be stable across loads. - Say which test you’d add. Use 32 or more stores with ties, two pinned stores and a NaN distance.
Step 4 explains why the bug reached production. The debugging round also scores the search past the first fix. Hass covers that in finding the bug and still not passing. Our HashSet contains() post covers a related contract, where hashCode broke after the object changed.
Wrong answers that keep the crash or hide it
“Return 0 when the distances are equal.” That fixes the tie branch and leaves the pinned branch alone. We ran that half fix on the same 1,000 seeds. Lists of 200 still crashed 11 times. The crash got rarer. That makes it harder to catch.
“Something is modifying the list while it sorts.” sortedWith sorts a private array copy, as the stdlib source shows. Nothing else can touch it. The message is about the comparator’s answers.
“Wrap the sort in try/catch and fall back to the unsorted list.” The crash goes away. Users who hit it now get the unsorted list, with pinned stores buried. The comparator stays broken. No one sees an error to fix.
“Subtract the values instead: (a.distanceKm - b.distanceKm).toInt().” Truncation turns a 0.5 km gap into 0. In our run, 1.0 equaled 1.5 and 1.5 equaled 2.0. Yet 1.0 came before 2.0. That breaks the third rule of the contract. With Int fields, subtraction can also overflow. Int.MIN_VALUE - 1 came out positive.