Quad-Copter Changed Flight Modes Without Prompting

When testing a new build today, the UAV gained and lost altitude in 20ft increments at constant time intervals for about 10 minutes. Near the end of the flight, the UAV gained altitude indefinitely until it hit the geofence breach, when the QUAD issued and RTL and returned safely.

I have had this happen a few times. Most sources of this come from vibration in the Z and Yaw axes. Vibration was in fact high, but normally, in my experience not detrimental in nature.

Second thing I noticed was some EMI in the Norm Mag Field graph. It was not an ideal day to fly, as we were testing some, most literal, rainy day situations. It was a light rain and heavy low clouds, but no lightning or thunder. This was the first case of EMI this drone has had.

I also noticed that the UAV swapped into loiter mode shortly before these height variations had arose. No part of our offboard code calls a loiter or hold mode. After reading I realized that it can be automatically swapped in high vibration situations or large sensor offsets (I cannot remember where I read this, please correct me otherwise).

I should also bring to attention the countless baro and GPS resets at the time of the flight mode change. I am thinking that this probably had something to do with the change in flight mode. If so, is there another way to handle this? In the offboard control from the companion computer, if the flight mode is change to any other flight mode besides an RTL, it should change back to offboard. Is there a way to handle this or narrow down the problem?

My question is what causes this? How can this be avoided? Any insight on this would be helpful.

Log of flight: