wallet may silently skip to sync history #36828

issue maflcko opened this issue on November 10, 2026
  1. maflcko commented at 4:35 PM on November 10, 2026: member

    This is from a ci failure, but I think it can happen in reality as well. It would be trivial to fix the test, but maybe this should be fixed in the wallet?

    The basic idea is that some block connection events on the scheduler thread may be processed while the wallet is failing to load due to a pre-prune locator. Thus, on the next load, the corrupt locator is used and the rescan is silently skipped.

    From https://github.com/bitcoin/bitcoin/actions/runs/42834240037/job/129901508274?pr=36827#step:11:23736 shows that the balance is wrong:

                                         File "D:\a\bitcoin\bitcoin/test/functional/wallet_assumeutxo.py", line 271, in run_test
                                           assert_equal(w.getbalance(), 34)
                                           ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
                                         File "D:\a\bitcoin\bitcoin\test\functional\test_framework\util.py", line 95, in assert_equal
                                           raise AssertionError("not(%s)" % " == ".join(str(arg) for arg in (thing1, thing2) + args))
                                       AssertionError: not(15.00000000 == 34)
    

    <details><summary>LLM summary of the bug (experimental)</summary>

    Timeline:

    1. dumb_sync_blocks() submits blocks through height 359.
    2. Their BlockConnected callbacks are queued on the scheduler.
    3. At 15:06:17.180791, the test performs the deliberately failing loadwallet("w").
    4. Loading w registers it for validation callbacks before it discovers that the required pre-snapshot blocks are unavailable.
    5. The scheduler then delivers already-queued notifications for blocks 357–359 to this newly registered wallet:

    15:06:17.184199 BlockConnected height=357 15:06:17.184613 [w] AddToWallet ... height=357 15:06:17.184868 BlockConnected height=359 15:06:17.184911 [w] Releasing wallet w..

    1. The callback at height 357 finds a wallet transaction, so CWallet::blockConnected() persists the wallet’s best-block locator at 357.
    2. The load still fails as expected because blocks needed before the snapshot are unavailable. But the failed load has now mutated w on disk.
    3. After snapshot validation completes, the final loadwallet("w") trusts that poisoned locator and rescans only 357–399:

    [w] Rescanning last 42 blocks (from block 357) [w] mapWallet.size() = 15

    That produces exactly the observed 15 payments: heights 357, 360, …, 399.

    So the problem is not getbalance, and not snapshot validation completing too early. It is a race between wallet-load failure and queued validation callbacks. The callback registration in AttachChain() happens before the availability preflight; its failing path disconnects and drains notifications, but draining allows the already-queued callbacks to update and persist the wallet.

    A robust fix belongs in wallet loading: perform the “are all rescan blocks available?” preflight before registering the wallet for validation notifications, or otherwise ensure callbacks delivered during a failed attach cannot write wallet state. A test-only synchronization barrier before the expected-failing loadwallet would avoid the flake, but would mask the underlying persistence bug.

    </details>

  2. maflcko added the label Wallet on Nov 10, 2026
  3. maflcko added the label Tests on Nov 10, 2026
  4. maflcko added the label CI failed on Nov 10, 2026
  5. maflcko added the label Bug on Nov 10, 2026
  6. achow101 commented at 7:37 PM on November 10, 2026: member

    Can you reliably reproduce the race?

  7. Yudis-bit commented at 3:31 AM on November 14, 2026: none

    Since the availability preflight runs before any blocks are rescanned, early notification registration can be dropped.

    The race reproduces when blocks submitted prior to loadwallet are still being processed on the validation queue. In AttachChain(), handleNotifications() registers the wallet at line 3080 before checking block availability on disk. While AttachChain() holds cs_wallet during the haveBlockOnDisk backward scan, the scheduler picks up the in-flight block (height 357 in wallet_assumeutxo.py) and blocks on cs_wallet. Once AttachChain() fails and releases cs_wallet, the scheduler acquires the lock and CWallet::blockConnected() writes the height 357 locator to disk before DisconnectChainNotifications() finishes draining.

    On subsequent load, the wallet trusts that locator and skips blocks 300–356. Deferring handleNotifications() until after the availability check passes prevents the failing load from registering:

    --- a/src/wallet/wallet.cpp
    +++ b/src/wallet/wallet.cpp
    @@ -3080,2 +3080,0 @@ bool CWallet::AttachChain(...)
    -    walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
    -
    @@ -3147,0 +3148,2 @@ bool CWallet::AttachChain(...)
    +        walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
    +
    @@ -3168,0 +3171,2 @@ bool CWallet::AttachChain(...)
    +    } else {
    +        walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
    
  8. achow101 commented at 9:05 PM on November 14, 2026: member

    Deferring handleNotifications() until after the availability check passes prevents the failing load from registering:

    This introduces a different race. A block that arrives after the tip height is retrieved but before notifications are registered results in that block being missed. Early registration is to prevent this race.

  9. Yudis-bit commented at 2:26 AM on November 15, 2026: none

    Could we keep early registration to prevent the tip race, and gate the notification callbacks on an m_is_attached flag set under cs_wallet on attach success? A failing load then drops drained notifications without touching disk.

  10. bitcoin deleted a comment on Nov 17, 2026
  11. bitcoin blocked a user on Nov 17, 2026
  12. bitcoin deleted a comment on Nov 17, 2026
  13. maflcko commented at 5:22 PM on November 17, 2026: member

    Can you reliably reproduce the race?

    Sure, to repro the test issue:

    diff --git a/src/validationinterface.cpp b/src/validationinterface.cpp
    index 128f14a..06dd069 100644
    --- a/src/validationinterface.cpp
    +++ b/src/validationinterface.cpp
    @@ -17,2 +17,3 @@
     #include <util/task_runner.h>
    +#include <util/time.h>
     
    @@ -227,2 +228,7 @@ void ValidationSignals::BlockConnected(const ChainstateRole& role, std::shared_p
         auto event = [role, pblock = std::move(pblock), pindex, this] {
    +        // TEST-ONLY RACE REPRODUCTION for wallet_assumeutxo.py. Keep the
    +        // height-357 callback queued while loadwallet("w") registers its
    +        // validation handler. AttachChain() has a matching delay after the
    +        // handler is registered.
    +        if (pindex->nHeight == 357) UninterruptibleSleep(1s);
             m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockConnected(role, pblock, pindex); });
    diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp
    index f509915..b2ca102 100644
    --- a/src/wallet/wallet.cpp
    +++ b/src/wallet/wallet.cpp
    @@ -3069,2 +3069,6 @@ bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interf
         walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
    +    // TEST-ONLY RACE REPRODUCTION for wallet_assumeutxo.py. cs_wallet remains
    +    // held here, so the queued height-357 callback retains this handler then
    +    // blocks trying to enter CWallet::blockConnected().
    +    UninterruptibleSleep(1s);
     
    

    Not sure how often it would happen in reality during IBD catch-up. Maybe just the test can be fixed for now and then this issue can be closed or revisited later?

    <!-- A standalone setup would be: 1. Start one regtest node with pruning enabled. 2. Create victim, obtain an address, and unload it while its saved locator is still old. 3. Mine far enough ahead to permit pruning, then prune past victim’s locator. 4. Keep the victim address, and make a payment to it in a new tip block, H. 5. Arrange for BlockConnected(H) to remain queued. 6. Call loadwallet("victim"). Its availability preflight fails because its rescan range crosses pruned data. 7. During that failed attach, dispatch the queued BlockConnected(H). It sees the newly registered victim, finds the payment, and persists its locator at H. 8. A later loadwallet("victim") no longer needs the pruned range, so it succeeds but silently omits historic transactions. The two test sleeps make steps 5–7 deterministic. The exact critical ordering is narrower than “a block arrives while wallet loading”: queued BlockConnected(H) ↓ AttachChain registers wallet, holding cs_wallet ↓ validation thread enters Iterate() and retains the callback, then blocks acquiring cs_wallet ↓ availability preflight fails; AttachChain releases cs_wallet ↓ callback acquires cs_wallet, updates a wallet tx, calls WriteBestBlock() ↓ DisconnectChainNotifications() cannot cancel that already-in-flight callback The validation iterator holds its internal mutex while invoking the callback, so teardown’s unregister blocks behind it; that makes the post-unlock handoff reliably favor the callback with the instrumentation. It is naturally uncommon, but not exceptionally contrived: • Failed load requires a pruned node, an assumeutxo background sync, or another missing-rescan-data condition. • The relevant block must already be queued—not merely connected—when the handler is registered. • That block must update the wallet (or be a periodic locator-write height).

  14. Yudis-bit commented at 10:28 PM on November 17, 2026: none

    A failed wallet load must not persist locator state to disk.

    Fixing only the test leaves on-disk corruption reachable in production: whenever AttachChain aborts on pruned data or in-progress assumeutxo sync, drained callbacks from concurrent blocks can write a locator at tip. The write does not even require a relevant payment, since blockConnected triggers WriteBestBlock() periodically every 144 blocks regardless. On subsequent load, the wallet skips the missing historical range, silently omitting confirmed transactions.

    Gating blockConnected and blockDisconnected on m_is_attached (set under cs_wallet upon successful return of AttachChain) ensures failed loads drop in-flight notifications without mutating disk.


github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-12-01 02:51 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me