Add fail-safe code for key migration