Hi,
I was looking at the code in ri_PlanCheck
of src/backend/utils/adt/ri_triggers.c starting at line 2289.
When qplan is NULL, we log an error. This would skip
calling SetUserIdAndSecContext().
I think the intention of the code should be restoring user id
and SecContext regardless of the outcome from SPI_prepare().
If my understanding is correct, please take a look at the patch.
Thanks