Jess Fishlock inspired Wales as they ended Scotland's Pinatar Cup defence at the first hurdle.
Lana Clelland headed the Scots in front in first-half added time but Wales quickly hit back through Fishlock's penalty.
Sloppy defending led to Fishlock's second early in the second period and Natasha Harding's strike ensured a semi-final against Slovakia or Belgium.
Scotland will now compete in the 5th-8th place section of the tournament.
Slovakia face Belgium later and Russia, Poland, Republic of Ireland and Hungary are in the other half of the draw. All eight teams in the Murcia-based event are guaranteed three matches.
Under Pedro Martinez Losa's predecessor Shelley Kerr, the Scots won the inaugural four-team Pinatar Cup in 2020 and Erin Cuthbert's goal for Scotland had defeated Wales in last year's friendly between the sides.
The defending champions set about getting ahead when Jane Ross threatened before Wales lost defender Hayley Ladd to a thigh injury with Anna Filbey coming on.
Claire Emslie's run and cross ended with Clelland's shot deflected wide and, from the corner, Caroline Weir's delivery was flicked on by Clelland and knocked into goalkeeper Laura O'Sullivan's arms by captain Jen Beattie.
Jane Ross released Christy Grimshaw to cross for Clelland to powerful head Scotland in front in the third minute of added time.
However, Wales were level three minutes later. Jenna Clark fouled Kayleigh Green as the latter ran in on goal and Fishlock's emphatic penalty beat Jenna Fife to the keeper's right.
Emslie should have put Scotland back in front at the end of a neat passing move involving another set-up by Grimshaw, the winger shooting too high. And substitute Abi Harrison struck across the face of O'Sullivan's goal moments later.
Wales punished that profligacy when Harding robbed Lisa Robertson in the box and backheeled for Fishlock to turn home.
Fishlock could have had her hat-trick after being set up by Green, but she could not keep her effort down.
However, the third goal was not long in coming as Green crossed for Harding to sneak in a shot at Fife's near post.
Fife avoided conceding a fourth goal as Wales mounted another slick counter attack, but time Green was to be denied.
Wales coach Gemma Grainger and Scotland boss Martinez Losa both made a raft of substitutions as time wound down in the Spanish heat.
Kelly Clark was given her Scotland debut off the bench before Harrison flashed an effort wide and, at the other end, Ffion Morgan shot over.