Canada to the US, on the Toronto to Chicago train, about 20 years ago.
The US/Canada rail border crossing has always been a bit odd, not least because it varies between every one of the regularly scheduled passenger trains that cross the border.
The
Amtrak Cascades (Vancouver, BC - Seattle, WA and Portland, OR) is the only one with juxtaposed border controls in Vancouver's Pacific Central Station. US-bound passengers pre-clear customs and immigration before boarding the train. Canada-bound passengers do it on arrival. The platform is fenced off. This is easily the smoothest and most passenger-friendly of the three current trains.
The
International (Chicago, IL - Port Huron, MI - Sarnia, ON - Toronto, ON) that
@endecotp refers to ran from c. 1982 to c. 2004, and the border controls took place on board. Today Amtrak and VIA Rail both have domestic trains on their portion of the route. It's difficult but not impossible to the Blue Water to Port Huron, stay in a hotel and then get a taxi over to Sarnia for the morning train. Miles in Transit did it recently.
The
Maple Leaf (New York, NY - Toronto, ON) is different from the Cascades and Adirondack in that Amtrak and VIA Rail share operation. It's an Amtrak train (with Amtrak staff and products in the café car, for example) in the USA and a VIA Rail train in Canada. It also makes additional stops between the border and Toronto. I haven't take it in almost 20 years, but my recollection from recent reports is that border controls are handled in the stations on either side of the border, so you need to detrain and bring luggage with you. (That may be incorrect - I welcome updates).
The
Adirondack (New York, NY - Montréal, QC) is more like the Cascades, in that it only makes one terminal stop in Canada. A juxtaposed customs and immigration facility on one of the underground platforms at Montréal Gare Centrale has been planned for years, but it still has not been inaugurated. Southbound, the train stops for a long time in Rouses Point, NY, during which time passengers must remain seated and not move about the train or use the toilet. Border control goes from one end of the train to the other and passengers who require additional processing or removal are taken to the café car. Northbound, the Canadian authorities drive over from the nearest border post and similarly check the train at an unmarked flag spot adjacent to a level crossing.
My first trip to the USA was by train, from Montréal in 2004. At that time, with a British passport, I was sent from my seat to the café car to pay the < $20 fee for a visa waiver. US dollars only, no change.