Forward port of #3927 and #3957