recent PRs like #31405, #30666 mark all m_block_index descendants as invalid immediately whenever an invalid block is encountered in SetBlockFailureFlags. so by the time we reach FindMostWorkChain, the block in setBlockIndexCandidates already has BLOCK_FAILED_VALID set on it - not just on its ancestor. this means pindexTest = pindexFailed whenever fFailedChain fires, and the inner while (pindexTest != pindexFailed) loop body is never reached!
I think we can remove it but I’ve just replaced it with Assume in this PR for safety + good to document this invariant in case the code changes in future. (noticed by @ stickies-v in #32950 (review))
the second commit is unrelated and adds a unit test for the situation in https://github.com/bitcoin/bitcoin/issues/32173