Deus ex machina
Something or someone that comes in the nick of time to solve a difficulty, especially in works of fiction.
This Latin term is a translation from the original Greek and owes its origin to Greek drama. 'Deus ex machina', literally 'god from the machina’ refers to the machina - the device by which gods were suspended above the stage in the Greek theatre. This began being used in English texts from around the middle of the 17th century.
John Sergeant, in Solid philosophy asserted against the fancies of the Ideists, 1697:
"Nor is it at all allowable in Philosophy, to bring in a Deus è Machiná at every turn, when our selves are at a loss to give a Reason for our Thesis."
In the Greek dramas a common plot device was to lower the gods into the action to sort things out and bring about a tidy conclusion. The modern-day version would be the cavalry riding over the horizon, or some character awaking and realizing the previous action had all been a bad dream.
The term is used these days as an implied criticism of implausible happy endings when the intervention of some improbable fairy godmother-like figure is considered too easy or cliched.