Here is an updated function which accounts for gimbal lock. Can you let me know if this works correctly?
float3x3 WtoL = LWCToFloat(GetPrimitiveData(Parameters.PrimitiveId).WorldToLocal);
float sy = sqrt(WtoL[0][0] * WtoL[0][0] + WtoL[1][0] * WtoL[1][0]);
bool singular = sy < 1e-6; // If true, gimbal lock is likely
float x, y, z;
if (!singular) {
x = atan2(WtoL[2][1], WtoL[2][2]);
y = atan2(-WtoL[2][0], sy);
z = atan2(WtoL[1][0], WtoL[0][0]);
} else {
x = atan2(-WtoL[1][2], WtoL[1][1]);
y = atan2(-WtoL[2][0], sy);
z = 0;
}
float3 R = float3(x, y, z);
return R < 0 ? 2 * pi - abs(R) : R;