Until Carey's rocket, St Johnstone looked to be sinking without a trace.
Josh Make had squandered two chances on the break, but Hearts looked the more threatening, Yan Dhanda striking the bar with a free-kick and Shankland unleashing a drive from just inside the St Johnstone half, which dipped wide.
St Johnstone play with laudable ambition under Valakari, and Carey's stunner, coupled with the magnitude of the night, imbued them with fresh confidence.
Stephen Duke-McKenna zipped a fabulous cross from the right which Taylor Steven lunged at but missed, then struck the side netting from an acute angle.
In the dying throes, they seared downfield in search of a leveller, and a seminal point in the relegation tussle. None came.
Valakari and his players were shaking hands at full-time, blissfully unaware of the events unfolding in Dundee.
They had trooped up the tunnel before Hale struck. Gone from the field, and the division.