While the bug fixed in 3.1.x (gh-39942) has already been addressed as a side-effect of the changes made in dbb24286, the change is merged forwards here to improve the consistency of the code between branches.
dbb24286