Sorry I don't have an opinion on which of these is the best (I can try to find some time to form an opionion on this later!), but:
Fixing the flakiness sounds great, but I would suggest decoupling that from the refactoring. If it's practical, focus on removing the globals first, while leaving the fundamental logic the same, even if it's bad. Then as a separate series, fix the logic.
Thanks, much appreciated. I'll send a patch with the refactoring + a comment regarding this variable left-in and follow-up with a fix.