There's a bug in BlockPlacementPolicyDefault#chooseTarget with stale node avoidance enabled (
HDFS-3912). If a NotEnoughReplicasException is thrown in the call to chooseRandom(), numOfReplicas is not updated together with the partial result in result since it is pass by value. The retry call to chooseTarget then uses this incorrect value.
This can be seen if you enable stale node detection for TestReplicationPolicy#testChooseTargetWithMoreThanAvaiableNodes().