A recent bout of incompetence was no grounds for firing a veteran city public school teacher, an appeals court ruled.

In a 3-2 decision, Appellate Division judges overturned the Department of Education’s firing of PS/IS 377 special education teacher Anthony Russo, citing a 21-year record that had been spotless until the his last three school years — when he lost total control of his class.

Russo’s students at the Bushwick, Brooklyn school roamed in and out of class, ate in class, were generally disruptive and even viewed pornography on school computers in his classroom, the Education Dept. found.

The tenured teacher was canned for poor performance following the 2010-11 school year, the end of a three-year period when he had the same class of under-performing fourth-through-sixth graders.

The appeals panel didn’t dispute most of the charges of incompetence cited by the Education Dept. for Russo’s termination — but said his previous 18 years of at least satisfactory reviews should have trumped any desire to fire the teacher.

“We find that under the circumstances presented here the penalty of termination shocks our sense of fairness,” according to the majority ruling.

The court was remarkably sympathetic to Russo and even let him off the hook for the porn. That incident happened “because respondent’s [the school’s] filters did not block the sites as petitioner had a right to expect.”

But in a dissenting opinion, judges said their colleagues completely undersold Russo’s incompetence.

“The majority minimizes the nature and extent of petitioner’s shortcomings,” those judges wrote.

The Education Department has not yet decided what it’ll do with Russo.

“We are not sure what’s going to happen regarding his placement,” a rep said on Monday. “Nothing has been decided yet since the decision just came out last week.”

The Education Dept. is also awaiting word from the city Law Department, which is weighing appeal options.

“We are disappointed by the court’s decision and are evaluating our options for further review,” a Law Department spokeswoman said.