Kilmarnock will play Scottish Premiership football next season after a late double from Joe Hugill sealed victory over Dundee and consigned St Mirren to the relegation play-off.
Tom Lowery's second-half strike gave the Ayrshire side the lead, but a splendid strike from Dundee substitute Charlie Reilly levelled.
However, Dundee substitute Charley Oosenbrugh brought down Aaron Tshibola in the box in the 85th minute and Hugill showed nerves of steel to bury the spot kick, then added a stoppage-time third to ensure Neil McCann's side were safe.
When McCann was appointed in January, they were second bottom, winless in 14 matches and looking every inch a side destined for the drop.
But now they have secured their position in the top flight with a game to spare.
They knew a win here would be enough to do that and thought they had taken the lead midway through the first half.
An incisive passing move sliced Dundee open and allowed Findlay Curtis to slot home, but VAR intervened and the goal was ruled out for offside.
Bruce Anderson was denied and Curtis passed up a glorious opportunity, heading over from six yards after being left unmarked.
At that stage, it looked like the play-off battle could head to a final day until Lowery stepped up with a wonderful goal just after the hour mark.
The ball was popped around the edge of the box before dropping into the path of the midfielder, who let fly with a powerful drive that arrowed into the far corner.
The Rugby Park crowd erupted, but were silenced soon after when Reilly conjured an even better goal to equalise, taking one touch and then letting fly with a stunning strike that flew past Max Stryjek.
With St Mirren leading at Pittodrie, it looked like the battle at the bottom would extend until the final Sunday of the campaign, but Hugill had other ideas.
After Oosenbrugh upended Tshibola in the box, the striker was ice cold from the spot, dispatching the penalty to regain the lead.
Then in the dying seconds, Hugill was first to react to a loose ball to nod home into the net and send the Kilmarnock faithful into raptures with their club's top-flight status secured.