At the end of the First Age, after the fall of Angband, Sauron was said to have truly repented. He was ordered to return to Valinor to suffer judgement, but his pride quailed. He would not endure a long imprisonment, and so turned away.
Many of Morgoth’s servants were given the same choice and some returned. Balrogs of Morgoth came back to Valinor, and their fire and shadow was burned away in the light of heaven. They were imprisoned for an Age and spend a thousand years learning new lore and new power. At the end of that time, their new masters sent them to Middle Earth to serve again, and wreak the destruction of their new master.
But since pride was their weakness, they were not to fight him themselves. They had to work through the free peoples.
Five there were, and with the lore of Valinor, they returned as wizards.
Two went east and lost themselves.
One strayed into Mirkwood and became a friend of the small creatures.
One recalled much of ancient Morgoth’s lore, but the Valar had burned away his aptitude for the dark powers. So he set about finding new forms of power and fell again into arrogance.
The last did not. He remembered Morgoth’s powers of illusion but made them gentle. He created fireworks instead of fireballs, and he served the free peoples. Only once did he unfurl his true power when he was tested against on such as he had been, a Balrog of Morgoth in Moria. In humility, he triumphed as in pride, he had once fallen.
Gandalf defeated his own history, and when he was given a chance to remain in Middle Earth as a power, he returned to Valinor as he had once before.