There are two solutions and you are close to being able to use either. Add an intermediate point that makes the arm rotate in the direction you want and then that won’t happen. That’s pretty common when you have roughly 180 degrees of rotation on a joint during the move. The robot can rotate it either way and get to the final solution in roughly the same time. So by adding an intermediate point it stops this behavior.
When running a program it sometimes selects one joint angle then occasionally it flipped to another make the joint hit the part