MotoGP world champion Casey Stoner saw a ten-second lead vanish at Valencia, but re-passed Ben Spies for victory just centimetres from the finish line.
The last race of the 800cc era saw spots of rain falling throughout and began with a turn one accident that left four riders in the gravel.
Contact between Alvaro Bautista and Andrea Dovizioso resulted in Bautista losing the front of his Suzuki, then bringing down factory Ducati team-mates Valentino Rossi and Nicky Hayden, plus Pramac Ducati's Randy de Puniet.
The accident was especially frustrating for the Ducati riders, since their bike had performed well in damp conditions throughout the weekend.
Up front, pole sitter Stoner was soon disappearing, riding to a ten-second lead until the rain spots intensified with six of the 30 laps remaining. The Repsol Honda rider almost instantly lost all of his advantage as Ben Spies and Dovizioso homed-in on the #27.
With three laps to go Stoner's RCV got out of shape on the brakes, forcing him wide and allowing Spies into the lead.
The Factory Yamaha rider, who took his first win in similar damp conditions earlier this year at Assen, then looked to have contained Stoner.
But a fast exit from the very final turn allowed the double world champion to snatch victory back from Spies by just 0.015sec.
"I got fantastic drive out of the final turn... sorry to Ben!" smiled Stoner. It was Stoner's tenth victory of the year.
Joining them on the podium was Dovizioso, who needed to finish ahead of Repsol Honda team-mate Dani Pedrosa to secure third in the world championship, behind Stoner and the absent Jorge Lorenzo.
Dovizioso, who has been moved by the loss of great rival Marco Simoncelli, seemed to ride with a Simoncelli-like attitude on Sunday, attacking Pedrosa and Spies at every opportunity to hold second for most of the race.