At https://ctan.org/pkg/lastpage the manual for the lastpage package is available.
The version at the time of this post is v2.0a, its manual reads:
Subsection 3.1 \AtEndDocument
\AtEndDocument is not used by the lastpagemodern.sty version of the lastpage package, requiring LaTeX-format 2022-11-01 or newer. Instead \AddToHook{enddocument/afterlastpage} is used and the problem does not arise.
lastpageclassic.sty uses \AtEndDocument and lastpage209.sty redefines
\enddocument. The last two cases are problematic: The output of a
LaTeX2e run is not independent of the order in which the packages are
loaded. It is often the case that the same formats for which one must
put tables and figure at the end, are the ones in which endnotes are
also required. If one wants to use \AtEndDocument here as well (as
done for \pageref{LastPage}), then it is easy to get to three separate
uses of \AtEndDocument (assuming one uses this for the endnotes as
well). Clearly it is not safe for any package writer or user to assume
that no material will follow what they put into \AtEndDocument.
Therefore a message, which begins with AED, is included in every usage
of \AtEndDocument. lastpage uses \AtEndDocument{...\clearpage...},
thus \usepackage{lastpage}...\AtEndDocument{something} will place
something after the \clearpage. To place it earlier, use
\AtEndDocument{something}...\usepackage{lastpage}. If the something is
not known before \usepackage{lastpage}, you can use for example
...
\def\beforeLastpageClearpage{\relax}
\AtEndDocument{\beforeLastpageClearpage}
\usepackage{lastpage}
\begin{document}
...
\def\beforeLastpageClearpage{\textit{something}}%
...
\end{document}
(might need a protected and/or expanded \def). When
\clearpage leads to some output, \clearpage\textit{something} instead
of \textit{something} might be wanted.
tl;dr
Either use LaTeX-format 2022-11-01 or newer (\usepackage{lastpage} automatically loads the modern style which does not even use \AtEndDocument but \AddToHook{enddocument/afterlastpage})
or pay attention where/when to \AtEndDocument your stuff.
atveryendwhich provides a host of hooks for the end-of-document area. – Werner Nov 15 '14 at 02:50