وَمَنْ اقْتَدَى بِإِمَامٍ، ثُمَّ عَلِمَ أَنَّهُ عَلَى غَيْرِ طَهَارَةٍ، أَعَادَ الصَّلَاةَ.
Meaning: Whoever followed an imam and later learned that the imam lacked ritual purity must repeat the prayer.
The timing of discovery is important. In the cited Hanafi ruling, the imam’s prayer was invalid due to lack of purification, so the follower repeats the prayer built upon that imamate.