I'm planning on catching the Caledonian sleeper from London to Perth which arrives at 5:39am. How late can I stay on the train once it has pulled into the station?
For London-Perth it looks like you'll have little more than around 5 minutes, from looking at the details. [Update: a link in Andrew's comment seems to confirm 3 minutes].
The excellent Seat61 gives heaps of info on the practicalities of train travel, and has a detailed guide to the Caledonian Sleeper. It confirms:
That's a journey time of 21 minutes compared to a normal journey time of 17 minutes, so unless the Sleeper is somehow faster than a normal train, it looks like the maximum extra time they might allow you to get up and get ready is an extra 4 minutes on top of the usual stopping time.
Best plan to be ready or almost ready to disembark at 5:39am.
If you were hoping to sleep in on the train until a more reasonable hour, unfortunately that's only possible on trains arriving in to Edinburgh and Glasgow:
Source: I've been on the sleeper myself a number of times, usually between London and Dundee, which is on the Perth/Aberdeen route.
It very much depends where you're getting off. If you're getting off at an intermediate station, then you will need to be prepared to get off as soon as the train arrives. It stays at each station no longer than any normal train does - usually under a minute. However, you may well be asked by the train's hospitality crew when you get on where you're getting off, and they will come round to rouse people ~30 minutes before their station.
If you're getting off at the terminus, you have slightly longer to get moving as the train is turning round. However, the cleaning crews will want to get on and get through the train quickly so that it can be prepared for the next run, and will not appreciate long stayers!