Conor Lamb, a Democrat and former Marine, scored a razor-thin but extraordinary upset in a special House election in southwestern Pennsylvania after a few thousand absentee ballots cemented a Democratic victory in the heart of President Trump’s Rust Belt base.

The Republican candidate, Rick Saccone, may still contest the outcome. But Mr. Lamb’s 627-vote lead Wednesday afternoon appeared insurmountable, given that the four counties in Pennsylvania’s 18th district have about 500 provisional, military and other absentee ballots left to count, election officials said.

That slim margin — out of almost 230,000 ballots cast in a district that Mr. Trump carried by nearly 20 percentage points in 2016 — nonetheless upended the political landscape ahead of November’s midterm elections. It also emboldened Democrats to run maverick campaigns even in deep-red areas where Republicans remain bedeviled by Mr. Trump’s unpopularity.

Republican officials in Washington said they were likely to demand a recount through litigation, and the National Republican Congressional Committee put out a call for voters to report any irregularities in the balloting. Matt Gorman, a spokesman for the committee, said the party was “not conceding anything.”