ONE BROAD test of whether a country is a democracy is whether the results of a national election are known before the votes are counted. For the first time since it became independent from Britain in 1957, Malaysia is poised to pass that test.

After half a century of maintaining itself in power through a mix of authoritarianism, corruption and ethnic favoritism, the ruling United Malays National Organization (UMNO) is in a dead heat with the opposition Pakatan Rakyat coalition, according to polls. Opposition leader Anwar Ibrahim, who has overcome imprisonment and exile during a 15-year campaign to democratize his country, has an even shot to become prime minister, in what would amount to a peaceful revolution in his country of 25 million.

That he has reached that point is due not only to his own courage but also to incumbent Prime Minister Najib Razak, who has done much to liberalize Malaysia’s political system since taking over in 2009. Mr. Najib has repealed some oppressive laws and pared down a legal system of discrimination that favored the ethnic Malay majority. Though his government prosecuted Mr. Anwar on questionable charges of sodomy — repeating the shameful maneuver that once before had been used to send him to prison — the opposition leader won a surprising acquittal early last year, setting up the electoral showdown.

Mr. Anwar is not a perfect partner for the West: A former deputy to strongman Mahathir Mohamad, he has demagogued against Israel in a predominately Muslim country and once alleged that a “Jewish-controlled” U.S. public relations firm was secretly pulling strings in the Malaysian government. But he has built a coalition of Malaysia’s young and rising middle class as well as the long-disempowered ethnic Chinese and Indian minorities. He has promised to abolish controls on the media and end the use of the courts for political purposes.

Mr. Najib, who has been a U.S. ally, is also appealing to moderate voters with promises to continue economic and political reforms. But as Sunday’s election approached, the most pressing question for outsiders was whether the government would stage a free and fair vote. Independent observers and media have chronicled worrying irregularities ranging from attacks on Internet sites supportive of Mr. Anwar to the chartering of planes to fly thousands of people from Malaysia’s provinces on the island of Borneo to closely contested districts on its peninsular territory.

By staging a clean election and vote count Sunday, Mr. Najib still has the opportunity to break ground as a democratizer — and, quite possibly, remain in power as well; the prime minister’s own approval rating of more than 60 percent may carry his party through. But if the election is stolen from Mr. Anwar, all of Malaysia’s progress in recent years could be lost. The prime minister should order his party and election officials to play it straight, and both he and Mr. Anwar should be prepared to accept a legitimate defeat.