This PR addresses the case where a wallet transaction fails to be accepted to the mempool when committed. This would keep the transaction in the wallet, to be rebroadcast at some undetermined time in the future, with the consequence that the change output would be cloaked. Even adding the mempool transactions into a new block will not immediately resolve the problem, due to the wallet not rebroadcasting the transaction immediately (even to itself) for (I think) privacy reasons.
Although there is a walletrejectlongchain option, the behavior when this is turned off is confusing and unpredictable, as noted above, and the CommitTransaction code will do the exact same thing for other mempool add failures, whichever those may be.
Edit: ~~~open question and currently investigating: will the coin selection algorithm inadvertently pick UTXOs that would result in a rejection of the transaction even if the user has other UTXOs available that wouldn't result in a too long chain? I have tried to trigger this case but the coin select is always picking the "right" UTXO that won't result in failure.~~~
Edit 2: In https://github.com/bitcoin/bitcoin/blame/master/src/wallet/wallet.cpp#L2457 the very last attempt to select coins increases the ancestor cap to num max, so above concern about coin select sometimes inadvertently picking an unspendable-due-to-chain-length tx is not a problem.