I think that I may have found a bug in ResetBlockFailureFlags. The bug happens when there are two chains (say two blocks with blockheight 200) and a block before that fork will be invalidated (say blockheight 100). If you then use ResetBlockFailureFlags to remove the failure flags from one of the two blocks at block height 200. ResetBlockFailureFlags will remove the flags of all descendants and ancestors of the block 200 on one of the chains. But for the block number 200 on the other chain and the following blocks the flags will not be removed. The BLOCK_FAILED_CHILD flags remain for these blocks. But the BLOCK_FAILED_VALID flag of block 100 will be removed. This can then produce a problem in CheckBlockIndex on line
assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
My fix searches for a BLOCK_FAILED_VALID flag and remembers the block index. It will then call ResetBlockFailureFlags for this block index again to remove the flags all all descendants.