I am writing a large document and recently had a weird bug crop up regarding the order of my references. I've now resolved it, but I'm not sure how it was able to occur, or why my solution even worked. I'd like to understand this so I can find other similar bugs if they exist, or at least be confident my references are ordered correctly without having to go through 200+ pages with a fine-toothed comb.
My document is in roughly this form:
\documentclass{book}
\usepackage{cleveref}
\usepackage{cite}
\usepackage[nottoc]{tocbibind}
\begin{document}
\frontmatter
\tableofcontents
\mainmatter
\include{Chapter1}
\include{Chapter2}
\include{Chapter3}
\backmatter
\bibliographystyle{unsrt}
\bibliography{bibfile}
\end{document}
And the output looked something like this:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.[1] Duis cursus dictum purus,[2] sit amet malesuada diam viverra vel.[3] Donec et velit sit amet lorem lobortis vulputate.[20] Aenean vel leo tempor,[4] fringilla nisl eget, mollis arcu.[5]
Bibliography
Dummy reference A, Journal of Foo Bar, vol 1, 1999.
Dummy reference B, Journal of Bar Foo, vol 12, 2000.
etc"
For some reason I was never able to determine, reference 20 was not numbered correctly. It was the 4th reference cited in the document (including in captions, TOC, etc), but it was assigned the number 20 instead of 4. Out of the references that I explicitly checked, there were no other similar issues. Compiling the document multiple times didn't correct the order. At some point I opened up the .bib file and moved the offending reference to a different random point in the .bib file and suddenly everything was fine. There is no difference in the code in the main document, and in theory the .bib file should give the same result regardless of the order of the references, yet this seemingly irrelevant change has made it go from not working to working. As a side note, at no point was there a problem compiling the document, and there were never any error messages, either before or after the fix.
Can anyone explain what happened here? Or how I might avoid similar issues in the future?