Thanks Carl Meyer for the suggestion and Alex Gaynor and Carl for reviews.
Thanks to @dmyerscoug for the report and original patch and to @alasdairnicol for the added tests.