The race for mayor took a surprise turn when first-time candidate C. Kenneth Gray outpaced incumbent Thatcher W. Kezer III in last Tuesday’s preliminary election. Gray, a technology executive, picked up 977 votes to 827 for Kezer, who is bidding for a fifth term. James Thivierge, a former selectman who has run previously for mayor, had 45 votes, and first-time candidate Jeff Hoover, got 39. According to the city clerk’s office, 1,892, or 17.1 percent, of the city’s 11,081 registered voters cast ballots. The outcome of the preliminary sets the stage for what now looks to be a competitive final election between Gray and Kezer Nov. 5. Gray is president of Northwave Technology in Haverhill, a manufacturer of semiconductor equipment, which he founded in 2011. He was previously an executive for other technology companies.