There are many, many reasons why this happens, some legitimate and some not.
Primary schools will have finalised budgets over the last couple of weeks and received their pupil numbers, so could have realised they don't need another member of staff; or can't afford your payscale.
I've known schools to interview on different days and they could have filled the post with a strong/preferred candidate yesterday or someone the agency sent along.
Their favourite supply teacher, or student teacher, could have been in the frame and decided yesterday that he or she wanted it. My first NQT job was in the school I was in teaching practice in, and they pulled the ad when I applied because they wanted me to stay.
People withdraw resignations - planned move out of the area with partner's job falls through, for example.
Recruitment is very difficult right now, and some schools are advertising when staff are applying elsewhere, to get ahead of the game. Maybe the person potentially leaving didn't get the job they went for.
Possibly you were always the "wild card" candidate in a strong field and others pulled out because they got jobs in the last few days (common for a field of 5 candidates to dwindle down to 1 or 2 at this time of year), in which case they'll readvertise.
I've rarely known another HT give a bad reference to keep someone. Possibly occasionally a bland reference which doesn't "sell" them. Unless there is history of this or of difficult relationships with your HT, it wouldn't be my first conclusion.
Ask for feedback, and whether you should reapply if it's readvertised.