Re-apply 7f215b13, which was reverted in a9e3d232. The orginal commit uncovered a bug that was fixed by 4701f776. Fixes #58680