Track used to be separate pieces (seemingly before 1950), but they are now continuous welded rail [1][3]. This was done to allow trains to go faster, and lowers maintenance on the trains. This confused me because trains go "clack clack clack" - I guess that's foley now.
However, it means track is more prone to buckling, since there aren't any expansion joints, like we have on bridges.
Slack is added/removed from the rails by stressing the track during installation [2].
They heat (or mechanically stretch) the track to the length at a chosen "neutral" temperature. Then they install the track. This allows them to calculate the max expansion and contraction the track will see and offset those forces with the sleepers (horizontal forces?) and the ballast (vertical forces?).
The rail can still buckle - this is engineering. If the ballast fails, or the temperatures exceed the maximum allowed for, then it will buckle. It also looks like it must be continually destressed by going along the rail, cutting it and re-welding it? [4]
[1] https://en.wikipedia.org/wiki/Railway_track#Continuous_welde...
[2] https://en.wikipedia.org/wiki/Rail_stressing
[3] Thermite track welding: https://www.youtube.com/watch?v=5uxsFglz2ig
[4] https://www.nzherald.co.nz/nz/peter-calder-old-methods-keep-...