When Sora used the power of waking to save his friends from Terra-Xehanort's fatal assault at the Keyblade Graveyard, the impact of forcing his friends' hearts back the way they were rewrote reality. This created a singularity, a tear in the fabric of time. The rewrite caused the first version of the battle in which they perished to have never happened. This allowed Sora to relive the battle a second time, where events took a more favorable turn for them.