This is a work in progress, do not review yet please
PR#18618 was divided in 2 when it got too complicated. This PR solves the new bug I found while working on the previous PR (see here).
For the moment I have just created a test that fails.