Detect cyclic references to prevent infinite recursion.

Prevents panics from stack overflow with a heuristic to detect cycles.