This 'self vs non-self' logic is very similar to how plants prevent self-pollination. They have a biological 'discrimination' system to recognize and reject their own genetic code.
Here is a breakdown - https://vectree.io/c/plant-self-incompatibility-logic