The Gemara distinguishes between a צדיק and a צדיק גמור with respect to whether or not they can be harmed by a Rasha.
This fits in with the classical view of hashgocha pratis as found in the Rishonim and Acharonim.
Both the Rambam and the Ramban based hashgacha pratis on a person's closeness to hashem. The closer a person is to Hashem the higher the level of their hashgocha.
When the brothers are planning on killing Yosef, Reuven saves him by suggesting throwing him into the pit. The mefarshim ask what did Reuven accomplish, the pit was very dangerous (full of snakes, etc.), even life threatening. The Netziv answers as follows. A person has בחירה חפשית and therefore the brothers could kill Yosef even if he was not supposed to die. However, animals since they have no בחירה חפשית cannot kill someone if he is not supposed to die. However the Netziv qualifies this by saying that this only applies to someone who is not a צדיק גמור, but a צדיק גמור cannot be harmed even through בחירה חפשית, exactly like our Gemara (see also the אלשיך and אור החיים there).