The 23-year Castrillo had already won Thursday's 12th stage but this was the biggest victory of his young career.
He set off three kilometres from the finish and soloed to victory in the fog, holding off the late challenge of Roglic's Bora-Hansgrohe teammate Aleksandr Vlasov.
"It's something I couldn't even dream of," said Castrillo, stunned by the victory.
"I didn't think it was possible to achieve this (two wins) in this Vuelta."
After a punishing 143 kilometres of road and mountain, which included the Alto de Santo Emiliano and a double ascent of the Alto de la Colladiella as well as that vicious final climb, Roglic followed the young Spaniard across the line in fifth, over a minute behind.
More significantly, the Slovenian clawed back another 38 seconds from O'Connor to reduce the Australian's overall lead to just 43 sec as the race heads into its final week.
O'Connor, however, who had a lead of nearly five minutes after winning stage six, remained upbeat about his chances of landing a first Grand Tour win.
"Yeah, it's optimistic today," O'Connor said.
"But I guess I've proven those people wrong (who) thought I'd lose the jersey. I had a pretty good day.
"It's a bit of a shame that I exploded a bit at the end but that's got to be probably one of the most horrible endings to a climb I've ever done. It was really disgusting.
"It was kind of only one attack, and that was Primoz, who was super impressive. Then it was very much man against man. You just felt like you were going nowhere, and you couldn't see anything with the fog as well. It was rough."
The riders have a rest day on Monday before setting off on stage 16, a 181 kilometre route from Luanco on the Asturian coast to the iconic ascent to the Lakes of Covadonga which takes in two intermediate climbs.