Once there was a mediaeval torture device called a rack. It, to put it mildly, stretched and tore the limbs of its victims. So the word "rack" became an adjective for pain. Over time it evolved into how we use it today. It was found in print in 1680 as a figure of speech. (source)
When we use it today we are saying that one has to think very hard or with strain.