Minecraft wiki entry for Farming, associated text: Any mob that was created as part of a naturally-generated structure.
Any mob which is carrying an object (or, for enderman, a block) that it wasn't created with.
Any mob which has interacted with a player: Lured and/or bred with food by a player, tamed by a player, or created by player breeding. This is inherited if they get converted to another mob, thus Zombie villagers are protected if they were created from a villager which had been traded with.
Any mob which is riding something else -- another mob, a boat, or a minecart.
Any mob which has been named with a name tag, or has the NBT tag {PersistenceRequired: 1b} .
Villagers, iron golems and snow golems never despawn. Neither does any boss or miniboss (e.g., elder guardians)
In Java Edition, most passive mobs (the classic farm animals) never despawn (exceptions include untamed wolves, cats, etc).