Williams has announced it is releasing Valtteri Bottas to join Mercedes with Felipe Massa reversing his decision to retire from Formula 1 to replace the Finn.
It brings to an end a saga that has run since Nico Rosberg announced his shock retirement just days after winning the 2016 world championship.
Bottas quickly emerged as Mercedes' leading candidate to partner Lewis Hamilton but the discussions ran for several weeks before an agreement was reached.
With teenager Lance Stroll signed up for 2017, Williams wanted an experienced driver if it was to release Bottas, especially given the dramatic regulation changes for this year.
The Grove-based team also could not field a second young driver as that would cause problems with key sponsor Martini.
It is believed Williams was initially uncertain whether Massa would accept an invitation to return.
But after making contact and holding an initial meeting, an agreement for a one-year deal was swiftly reached.
"I am very happy to have an opportunity to return to Williams," said Massa.
"I always intended to race somewhere in 2017, but Williams is a team close to my heart and I have respect for everything it is trying to achieve.
"Valtteri has a great opportunity, given the turn of events over the winter, and I wish him all the best at Mercedes.
"In turn, when I was offered the chance to help Williams with their 2017 campaign, it felt like the right thing to do.
"I certainly have not lost any of my enthusiasm for racing and I'm extremely motivated to be coming back to drive the FW40."
Deputy team principal Claire Williams said: "I'm delighted that Felipe has agreed to come out of retirement to be a part of our 2017 campaign.
"With Valtteri having a unique opportunity to join the current constructors' champions, we have been working hard to ensure that an agreement could be made with Mercedes to give Valtteri this fantastic opportunity.
"Valtteri has been part of the Williams family since 2010 and in that time has proved a huge talent, securing nine podium finishes.
"I would like to take this opportunity to thank him on behalf of the whole team, and wish him a successful season as he joins Mercedes.
"Felipe has always been a much-loved member of the Williams family, and having the opportunity to work with him again is something we all look forward to.
"Felipe re-joining us provides stability, experience and talent to help lead us forward. He is a great asset for us."
Bottas joins Mercedes having scored nine podiums but he has yet to reach the top step in 77 starts.
Meanwhile, Massa returns to Williams to compete in what will be his 15th F1 season as a race driver.
During that period, he scored 11 wins, 41 podiums, 16 pole positions and narrowly missed out on the world title in 2008.