When running walletpassphrase on a large wallet.dat (ie about 300,000 segwit P2SH addresses) the command sometimes takes a very long time, and if command is run multiple times at once (while running slow) it causes bitcoin core to freeze (stops syncing and requires kill -9 to stop/restart)

During the locked up walletpassphrase commands being run the following messages start to appear in the debug.log:

`018-01-24 01:01:04 socket sending timeout: 1201s`

Note that this problem is intermittent, so sometimes the command runs instantly, other times it takes a few minutes, and other times it completely freezes the node.
{
    
    LearnRelatedScripts(key, OutputType::P2SH_SEGWIT);
}
void LegacyScriptPubKeyMan::MarkReserveKeysAsUsed(int64_t keypool_id)
{
    AssertLockHeld(cs_KeyStore);
    bool internal = setInternalKeyPool.count(keypool_id);
    if (!internal) assert(setExternalKeyPool.count(keypool_id) || set_pre_split_keypool.count(keypool_id));
    std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : (set_pre_split_keypool.empty() ? &setExternalKeyPool : &set_pre_split_keypool);
    auto it = setKeyPool->begin();
    WalletBatch batch(m_storage.GetDatabase());
    while (it != std::end(*setKeyPool)) {
        const int64_t& index = *(it);
        if (index > keypool_id) break; 
        CKeyPool keypool;
        if (batch.ReadPool(index, keypool)) { 
            m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
        }
        LearnAllRelatedScripts(keypool.vchPubKey);
        batch.ErasePool(index);
        WalletLogPrintf("keypool index %d removed\n", index);
        it = setKeyPool->erase(it);
    }
}
std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider)