Cycle detection to avoid infinite stack growth.