Core component of SQL Server for storing, processing, and securing data
I would guess the reason that you sometimes get a failover and sometimes not is due to some timing issue. Sometimes, the error triggers the monitoring, and sometimes not. Maybe because if the errors occur close enough to each other, the cluster thinks the replica is not healthy and decides to fail over. To address this, you could change the FAILURE_CONDITION_LEVEL for the AG. The default level is 3, for which the documentation says (emphasis mine):
Specifies that an automatic failover should be initiated on critical SQL Server internal errors, such as orphaned spinlocks, serious write-access violations, or too much dumping.
However, I would not recommend taking this step. Rather, you need to work with the root cause, which is the failing query. It is interesting that the procedure sometimes succeeds, and sometimes fails with this error. Normally, when you get this error, you get it constantly. However, if the problematic query has OPTION (RECOMPILE) or the procedure is constructing dynamic SQL, there is compilation every time and depending on the values, a plan may or may not be possible to construct. It is not uncommon that this due to that hints that have been added to the query.
So what you need to do is to track down exactly what query/queries that are failing. Once you know the query, you can try to get an understanding of why the compilation fails and from this make the required changes.