Cherrypicked 9b7efa961f and 66ff347255, passes test4