On Linux, this problem is extremely hard to reproduce by running Kleopatra. The easiest way to reproduce this on Linux is to run libkleo's keyresolvercoretest (which consists of 58 tests where each one uses a separate temporary GNUPGHOME and each of those tests initializes the KeyCache by doing keylistings with gpg and gpgsm) in a loop until it fails (see also https://invent.kde.org/pim/libkleo/-/issues/2), e.g. by running the following in the build folder of libkleo:
while ctest --output-on-failure -R keyresolvercore; do echo; done
I ran the tests with GPGME_DEBUG=8:$(pwd)/gpgme-$(date +"%Y-%m-%d-%H%M%S").log to get gpgme logs.
It took 109 tries and 25 tries until the test failed. Additionally, in the first iteration 2 out of the 109 runs took ~10 seconds instead of ~3 seconds and in the second iteration 3 out of the 25 tries took ~10 seconds instead of ~3 seconds.
The gpgme logs of the first failure indicate that gpgsm failed to start gpg-agent. The gpgme logs of the second failure seem to indicate that gpg tried a few times to start gpg-agent before it could connect to gpg-agent. I'll attach the logs.
In any case, the logging suggests that performing concurrent keylistings with gpg and gpgsm without already running gpg-agent, so that gpg and gpgsm race to start gpg-agent, sometimes (on Linux very rarely) results in a failure of one of the keylistings.
To avoid this problem I will serialize the two keylistings done by KeyCache.