Test Failing: Computer Too Fast
A peculiar bug
Today I fixed a very interesting bug. The code reads
//Segment lineage entries are sorted in chronological order by
lineageEntries.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(
Comparator.comparingLong(LineageEntry::getTimestamp)
));
The test creates two LineageEntry, then prints them, and ensures they are sorted by time of creation — that is to say the first one created is printed before the second one.
It works fine most of the time.... Except on a computer that is just too fast. Two consecutive LineageEntry can be created within a millisecond and therefore have the same timestamp!
And here's the problem... the ordering of LineageEntry with identical timestamps is undefined. The test fails 50% of the time.
The fix is trivial: Add a secondary sort order. The ordering didn't even matter all that much: it is just how the log statement is ordering entries. We want it to be sorted by time, though, and then, I think it is better that entries within a timestamp are also consistently sorted, and not randomly shuffled each time we print the logs.
It may be the first time I see a bug that only manifests only for fast computers.