The anyhit programs are called as often as there are successful intersection tests with a geometric primitive.
The acceleration structures in OptiX are built with a splitting BVH algorithm by default which means that the same geometric primitive can appear in multiple BVH nodes and can be intersected multiple times along a single ray!
Algorithms which do counting inside anyhit programs are not going to work with that default.
To prevent that, the acceleration structure must be built with the OptixGeometryFlags OPTIX_GEOMETRY_FLAG_REQUIRE_SINGLE_ANYHIT_CALL
Note that intersection program and therefore anyhit program invocations are not happening in ray direction order but in BVH traversal order (which is view and implementation dependent), but in your case of ignoring all hits, all primitives along the tested ray interval should reach the anyhit program and then would finally call into the miss program or return to the raygen program when there is no miss program assigned to that ray type.
(There is no need for that ternary operator and the modulo in this line: int result = (payload.hitCount % 2 == 1) ? 1 : 0;
That’s identical to int result = payload.hitCount & 1; which is faster.)