Backport of core PR14588.
This refactor repairs the invariant, [...]. It also simplifies some other code, and removes redundant parameters from some related functions.
Note that the bug fixed in the PR is not affecting us, but I kept the
test as it can't hurt.
Also the IsSane() method is kept for easier backports, despite it does
nothing and will be optimized out by the compiler.