Skip to content

proposal: slices, sort: randomize sort order of equal elements in tests #70182

@znkr

Description

@znkr

Proposal Details

Go's (non-stable) sort functions don't guarantee a particular ordering for equal elements. However, since the order of equal elements is always the same for a number of releases, tests tend to accumulate dependencies on the ordering of equal elements by accident.

In Google codebase we noticed that a large number of tests depended on the order of equal elements when the sorting algorithm was changed to pdqsort in April 2022 (http://go.dev/cl/371574). We needed to fix all of these to be able to release pdqsort internally. Recently http://go.dev/cl/624295 changed how equal elements are ordered. In the 2½ years since pdqsort was introduced a few tests have already started to depend on the order of equal elements again.

This is a classic example of Hyrum's Law

With a sufficient number of users of an API,
it does not matter what you promise in the contract:
all observable behaviors of your system
will be depended on by somebody.

Fixing tests when the order of equal elements changes is a lot of work and makes upgrading to a new Go version harder. It's also surprisingly hard to understand if the order of equal elements actually matters (i.e. if stable sort should have been used) or if the order of equal elements was depended upon accidentally. Both problems can be mitigated sufficiently by randomizing the order of equal elements on each test run. That way, tests that depend on the order of equal elements provide a very early signal of problem.

Google already did this for C++ some time ago and it's working very well:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions