Pr/6136 test

This fixes #6143, adds tests for #6136 and rebases original PR on top of it.