Castrillo (Kern-Pharma) was part of a leading trio on the gruelling Cuitu Negru climb to the finish and made his move with three kilometres to the end of the 143-km ride from Infiesto to Valgrane-Pajares.
In the final kilometre, he glanced over his shoulder to see Aleksandr Vlasov (Red Bull-Bora-Hansgrohe) appear through the fog, but Castrillo found another burst of energy to hold off the Russian, with Pavel Sivakov of France coming in third.
Three-times former champion Roglic finished fifth, coming in 38 seconds ahead of the red jersey, Australia's O'Connor, who now holds a slender 43-second lead going into the final week.