All perfect praise be to Allah, The Lord of the Worlds. I testify that there is none worthy of worship except Allah, and that Muhammad is His Slave and Messenger.
One of the fundamental principles in Islamic jurisprudence is that certainty cannot be removed except with certainty. For example, whoever performs ablution, remains in that state of ablution until he becomes certain that his ablution is invalidated by one of the nullifiers of ablution. Likewise, if one is certain that he invalidated his ablution, then he remains in the state of impurity until he performs ablution, because the state of having no ablution became the default state.
Therefore, what is established with certainty cannot be overruled by doubt.
Based on this, whoever prayed while doubting his purity, then his prayer is not valid and he has to make that prayer up. Ibn Nujaym mentioned in Al-Ashbaah wa An-Nathaa'ir: “Whoever is certain of his purity and doubts that he had invalidated his purity, then remains in the state of purity, and whoever is certain of invalidating the state of purity and is not certain that he had become pure (performed ablution), then he remains in the state of impurity.”
Allah Knows best.