“Going down to 10 men changed the game,” Vilanova said. “I told Gerard that he would be sent off with the next foul.”
The Basque side pushed short-handed Barcelona into their area and the effort paid off when Castro’s strike took a deflection off substitute Javier Mascherano to catch Valdes out of position.
Barcelona did not seriously threaten again and the slow-footed Mascherano let Agirretxe slip behind him to reach Martinez’s cross and end Barcelona’s 15-game unbeaten streak in all competitions.
Ninth-placed Sociedad stayed undefeated in six consecutive home games.
“There is no recipe for beating Barcelona,” Sociedad coach Philippe Montanier said. “We won because we have a compact team that works hard and we had a little bit of luck.”
The defeat was Barcelona’s first in La Liga since they lost to Real Madrid last season on April 21.