Backport #1341 fix and tests