This patch only cherry-picks the parts that actually fix the issue, but not the numerous NFC refactorings around it.