Pakistan bowled out Sri Lanka for 96 in their second innings to give itself a target of 317 to win and protect a run of undefeated Test series since 2009, when they made the United Arab Emirates its home away from home.
At the end of another twist-filled day, Pakistan was 198-5, needing 119 more runs for victory.
Projecting hope were the nightwatchmen. Asad Shafiq was 86 not out off 141 balls, and captain Sarfraz Ahmed was 57 off 113 balls.
They had combined for 146 runs but it was more valuable than that. Shafiq and Ahmed came together when Pakistan was reduced to 52-5 in the middle session and looked like losing the Test and series inside four days. Offspinner Dilruwan Perera took three wickets in 11 balls and had Pakistan on theur knees.
Twice, Perera thought he had Shafiq, too, on 26. But both times, the shot was dropped by Kusal Mendis.
Shafiq made Sri Lanka pay. He and his captain made it to dinner of the day-night Test, and carried their bats through the last session, Pakistan's best in the Test.
They even prevented Rangana Herath from adding to his 400 career wickets in this innings. Herath has figures of 19-2-53-0.
The day started just as brightly for Pakistan.
Sri Lanka, 34-5 overnight in their second innings, was all out for 96 after making 482 in the first innings.
Mendis and Niroshan Dickwella threatened to set back Pakistan's gains late Sunday, until Dickwella was out for 21. Perera followed for a duck.
Herath hit a quick 17 then was dismissed by left-arm spinner Haris Sohail. Drinks were taken and, when the same over resumed, Sohail removed Mendis for 29 and Nuwan Pradeep for a duck.
Sohail took 3-1 in his one and only over, Wahab Riaz had 4-41 off nine overs, and Yasir Shah 2-47.
Despite Sri Lanka's collapse, the target was still formidable, and looked out of reach as Sami Aslam was out for 1, two balls after he was caught off a no ball, and Azhar Ali out for 17 from a thick inside edge which ballooned to short square leg.
Sohail (10) and Shan Masood (21 off 100 balls) edged behind, and Babar Azam fell for a duck at 52-5.
Enter Ahmed alongside Shafiq, and a little luck.