Backport some fixes for release-0.2 branch

This backports fixes for #4763 and #6036.