A dog has had a lucky escape after jumping from a first-floor window and running half a mile before becoming wedged in a tiny space between two walls.