WIP: Backports migration fixes from #6650 to stable 6

(stable 6, not 5 despite branch name)

Still WIP