I've attached a draft patch. To fix it, I think we can reset InitialRunningXacts and NInitialRunningXacts at FreeSnapshotBuilder() and add an assertion in AllocateSnapshotBuilder() to make sure both are reset.
Thanks for the patch. It works fine. I've tested this patch for 15 and 11 versions on x86_64 and ARM
and see no fails. But the function pg_current_xact_id added by 4c04be9b05ad doesn't exist in PG11.
Regarding the tests, the patch includes a new scenario to reproduce this issue. However, since the issue can be reproduced also by the existing scenario (with low probability, though), I'm not sure it's worth adding the new scenario.
AFAICS, the test added doesn't 100% reproduce this issue, so, maybe, it does not worth it. But, I do not have a strong opinion here.
Let's add tests in a separate commit and let the actual committer to decide what to do, should we?