Refactor of fix for Ticket 22232

This is a refactor of NathanRSmith's fix for ticket #22232
please use slightly longer lines such as here (move `EXTENDS_HISTORY_CONTEXT_KEY)` up) when it improves readability