Skip to content

Resumable, checkpointed full resync driven by sync steps - #19

Open
sqhell wants to merge 18 commits into
red-dev-inc:mainfrom
sqhell:feat/resync-resume
Open

sqhell wants to merge 18 commits into
red-dev-inc:mainfrom
sqhell:feat/resync-resume

Conversation

@sqhell

@sqhell sqhell commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What

  • Full Resync runs sync_step in a loop and writes the in-progress wallet to a wallet.staging checkpoint every four steps; on completion promoteStaging moves it to wallet in one IndexedDB transaction (keeping the previous wallet as a backup) before the fresh instance becomes visible.
  • A reload mid-resync offers Resume or Discard from the checkpoint; a trapped worker is reported through report_sync_worker_trap and surfaces as a clear error.
  • A storage write that throws (for example DataCloneError when the renderer is out of memory) rejects instead of leaving the checkpoint promise pending, so the resync fails loudly and the old wallet stays.
  • A doc comment fix keeps */ out of a generated d.ts.

Why

Before this, a reload or crash during a multi-hour resync lost all of it, and a hung checkpoint write looked like a stalled sync. Builds on the bounded steps (previous PR) and the epoch-checked store, which the checkpoint and promotion reuse.

Stack

Position 15 of 15 in the WebZjs release order, to be merged in this order into main. Builds on #18 (feat/resumable-sync), #14 (fix/wallet-store-epochs). GitHub shows the whole stack against main until those merge; the commits of this PR alone are here: sqhell/WebZjs@feat/resumable-sync...feat/resync-resume (that view also includes the merge of fix/wallet-store-epochs).

  1. Make rustfmt and clippy pass on main #20 chore/rust-checks
  2. Reuse one web worker for every sync instead of spawning per call #6 fix/reuse-sync-worker
  3. Accept Trailers-Only gRPC responses from lightwalletd #7 fix/grpc-web-trailers-only
  4. Keep the Full Resync form usable during background syncs #8 fix/resync-dialog
  5. Send again from the transaction history, with a caution for new recipients #9 feat/send-again
  6. Surface PCZT parse and signer errors instead of trapping; readable transfer errors #10 fix/pczt-parse-error
  7. Sign the change-paired Orchard spends NU6.3 bundles require #11 fix/sign-change-paired-spends
  8. Stop a full resync from an old birthday exhausting the wasm heap #12 fix/historic-sync-oom
  9. Point to Full Resync from the end of the transaction history #13 feat/history-resync-hint
  10. Make wallet persistence refuse stale and silent overwrites #14 fix/wallet-store-epochs
  11. Spend and count the Ironwood (NU6.3) pool #15 feat/ironwood-pool
  12. Classify history by what the wallet spent, not only by what it received #16 fix/history-from-spends
  13. Wallet stats card on the account summary #17 feat/wallet-stats
  14. Bounded sync steps, instance ids, close and worker poisoning #18 feat/resumable-sync
  15. Resumable, checkpointed full resync driven by sync steps #19 feat/resync-resume (this PR)

Rust pins reference sqhell/zcash_client_memory and sqhell/librustzcash by revision so CI builds exactly what was tested; once the zcash_client_memory stack (red-dev-inc/zcash_client_memory #16 to #21) merges, the memory pin goes back to red-dev-inc/zcash_client_memory feat/snap-nu63. The integration branch test/all-fixes on the fork merges all fourteen and is the build that was tested end to end.

Tests

cd packages/web-wallet && yarn test
just build

Rust-Checks has failed on main since the NU6.3 toolchain bump: rustfmt
differs in nine files, and clippy on nightly-2025-06-15 rejects ten
uninlined format arguments in webzjs-keys and one map iteration in
webzjs-requests under -D warnings. Apply rustfmt and clippy's own
suggestions; no behaviour changes.
Leaving the wallet open on Account Summary crashed after roughly 75
minutes with:

    panicked at sharded-slab-0.1.7/src/shard.rs:295:9:
    Thread count overflowed the configured max count.
    Thread index = 128, max threads = 128.

followed by `RuntimeError: unreachable`, after which the wallet hung.

`WebWallet::sync` spawned a fresh web worker for every call, and the
periodic rescan calls it every 35 seconds. The tracing registry stores
spans in a sharded slab that allows 128 thread slots on wasm32; a thread
takes a slot the first time it creates a span (block scanning does) and
gives it back only from its thread-local destructor. Those destructors
never run here: wasm_thread is built with `keep_worker_alive`, so
finished workers are not closed at all, and closing a worker skips Rust
thread-local drops anyway. So every sync consumed one slot for good, and
sync number 129 panicked. The idle workers also kept their stacks and
thread-local storage, so memory grew per sync as well.

Run all syncs on a single long-lived worker, created on first use and
fed through a channel. Requests run one at a time, which the JS caller
already enforces with its sync-in-progress guard.

A trap inside the worker (a Rust panic compiled to wasm) is not recovered
from: the trapped call never resolves and later syncs wait behind it until
the page is reloaded. That was already the case with a worker per call, which
held the wallet lock forever after a trap.
…yncs

The resync form was rendered only while no sync was running, and fullResync
refused with "Sync already in progress" if a periodic rescan happened to be in
flight. With a 35 s rescan interval that made the dialog vanish mid-typing and
reject Confirm at random.

Syncs are now serialised on the JS side instead of refused: a small
module-level scheduler owns `syncInProgress`, periodic rescans skip their turn
while a sync runs, and a full resync waits behind an in-flight rescan. This
also closes the race where a rescan that had passed its guard could clear
`syncInProgress` while a full resync was still running. (The wasm wallet runs
syncs on one serial worker in a separate change; this one stands alone.)

The form stays mounted during background syncs. While the resync waits for a
running sync it can still be cancelled, which drops it from the queue; once it
starts, Confirm and Cancel are disabled until it settles, and a card mounted
while a resync is in flight shows that instead of offering another. The
birthday is validated against the chain height inline instead of an alert.

A custom birthday is written to the snap only once the resync succeeds, and
before the fresh wallet is swapped into state, so a failed resync never leaves
a birthday the old wallet never used (a birthday above the tip previously broke
auto-recovery with "block is not in the main chain"), and a failed snap write
leaves state, the snap and IndexedDB describing the same wallet.
The shared sync worker uses tokio::sync::{mpsc, oneshot}, which only compiled
because another dependency happened to enable the feature.
A Full Resync from an early birthday (for example 2,600,000) crashed the
sync worker with `RuntimeError: unreachable` after a few 10,000-block
batches, and the wallet UI hung afterwards.

MemBlockCache::delete in zcash_client_memory was a lazy `async fn`, and
zcash_client_backend::sync::run only awaits the returned futures once
the whole sync has finished, so every downloaded compact block stayed in
the cache for the entire sync. The browser caps wasm memory at 1 GiB and
the allocation failure traps without a panic message.

Point zcash_client_memory at a revision that removes the blocks when
`delete` is called, and that also prunes the nullifier map below the
fully scanned height as zcash_client_sqlite does, so a historic sync no
longer keeps every on-chain nullifier in memory for the life of the
wallet. Measured natively, syncing 800k blocks (2.6M to tip, batch
10,000): peak heap 2,039 MiB before, 524 MiB with the eager delete,
383 MiB with the pruning as well.
…writes

Twice in one day a correct wallet was replaced in IndexedDB by a worse one.
A second tab kept saving its old copy over a completed Full Resync, because
every tab wrote the single `wallet` key unconditionally and the last writer
won. Earlier, stored bytes that failed to load were replaced by auto-recovery
with an account-only wallet built from the chain tip.

All wallet storage now goes through one module, src/storage/walletStore.ts,
which enforces one rule: a save lands only if the instance saving descends
from what is stored right now, or it is an explicit resync or recovery that
is allowed to win.

- The stored value is a versioned record with metadata; `epoch` increments on
  every write and is checked and written in one IndexedDB transaction. A
  legacy byte array counts as epoch 0 and is converted on its first save.
- The epoch is bound to the WebWallet instance through a registry, not to
  React state, so a stale closure, an old hook or another tab is rejected
  by construction. A superseded instance can never write again.
- Full Resync persists the fresh wallet as a forced write, with its birthday,
  before it becomes visible, then retires the old instance. Snap state is
  updated afterwards and repaired later if that fails.
- Stored bytes that fail to decode are backed up and left in place. The empty
  wallet built instead is never registered, so no save, including
  auto-recovery, can replace them. The home page offers an explicit
  "Discard unreadable wallet data and recover from MetaMask" action.
- A rejected writer reloads the wallet from storage instead of fighting;
  tabs learn of saves through a BroadcastChannel and reload when visible.
  One tab per origin holds a Web Locks writer lock and runs the periodic
  rescan; the others follow. Both are for freshness and efficiency only,
  the epoch check keeps every configuration safe.
- The blob's own account birthday, read straight from the stored bytes, is
  authoritative. The snap value is repaired downward when it is later, never
  raised.

Tests: the store module under fake-indexeddb (stale write rejected with
storage untouched, forced resync wins, superseded instance blocked, legacy
migration, unreadable bytes quarantined, concurrent saves serialized, and a
two-tab simulation), the hook ordering (persist before swap, birthday
precedence, reload on stale write, recovery guard) and the home page guard.
Since NU6.3, payments to shielded addresses and the shielded change of
shielding transactions are delivered through the Ironwood pool, and this is
where a wallet's shielded funds live from then on. zcash_client_memory did
not track that pool, so every such transaction failed at creation with
ProposalNotSupported, and Ironwood funds were invisible.

Move the zcash_client_memory pin to the fork revision that tracks the Ironwood
pool (its own commitment tree, notes, nullifiers, balances and
serialization), and make the two wallet-side changes that depend on it:

- pczt_prove proves the Ironwood bundle as well as the Orchard one. The two
  bundles share the circuit and proving key; without the second proof,
  extraction rejects every post-NU6.3 payment to a shielded address.
- The wallet summary reports the Ironwood balance, and the web wallet counts
  it as shielded funds in the balance hook and the snap balance cache.

Verified on mainnet: a payment from legacy Orchard notes to the wallet's own
unified address, which the backend routes through Ironwood, built, signed in
the snap, proved and broadcast, and the resulting Ironwood note was scanned.

Both pins move together with this commit: zcash_client_memory to the fork
revision that exposes spend records and change flags for history queries,
and every librustzcash crate to sqhell/librustzcash, which is the previous
pin (0a2c6d1) plus the upstream fix that records Ironwood outputs when a
transaction is extracted from a PCZT. Without the latter, a payment to a
shielded address signed through the snap left no sent record at all, and
the history later showed only its change as a receipt.
…uning

The pinned revision is the head of the zcash_client_memory PR stack: the
Ironwood pool on top of the nullifier-map pruning tests, then strict
decode, loud encode, the dirty flag, the rewind nullifier fix and block
pruning that the resync and persistence work was tested against.
`sync::run_step` lives on the fork's snap/0a2c6d1-ironwood-step-sync
branch, on top of the Ironwood PCZT extraction fix already pinned. The
pinned revision includes the follow-up that keeps Verify ranges out of
the step budget, so a step always scans a full batch.
Wallet::sync used to take the wallet write lock once and run
zcash_client_backend::sync::run over every batch, so a historic resync
held the lock for the whole scan and could not be persisted or stopped
part way. Build the sync out of sync::run_step instead:

- Wallet::sync_step(first) refreshes the chain tip, fetches and scans at
  most one batch, releases the write lock and reports whether more work
  remains. The first step refreshes the subtree roots; later steps skip
  that round trip.
- Wallet::sync is now a loop over sync_step, so existing callers keep
  working but the lock is released between batches.
- Every Wallet carries an instance_id (a process-local counter plus a
  random suffix) and a closed flag shared by its clones. close() makes
  sync, sync_step, db_to_bytes, account creation, proposal, signing and
  the pczt_* and send paths fail with the new Error::InstanceClosed, so
  a sync loop driving an instance the page has replaced stops at the next
  batch boundary instead of writing into a stale wallet.
- Error::SyncWorkerUnavailable is added for the bindings to report a sync
  worker that has trapped.

BATCH_SIZE drops from 10000 to 2500 so a single step takes minutes, not
up to an hour, on a historic resync. The trade-off is more round trips to
lightwalletd in exchange for smaller memory peaks and shorter lock holds.
…soning

The shared sync worker ran only Wallet::sync, with no way to tell one
wallet instance from another, stop an instance, or recover once the
worker trapped.

- SyncRequest carries a SyncKind (Full or Step { first }) and replies
  with the "more work remains" flag; the worker dispatches to
  Wallet::sync or Wallet::sync_step accordingly. A closed instance is
  reported back as Error::InstanceClosed rather than a flattened string.
- WebWallet gains sync_step(first): Promise<boolean>, the instance_id
  getter, close() and is_closed(). sync(): Promise<void> is unchanged
  for existing callers.
- A trap inside the worker is a wasm RuntimeError the library cannot
  observe. The new free function report_sync_worker_trap() lets the
  page's window error handler poison the worker: every in-flight call
  is released and every later sync / sync_step rejects with
  Error::SyncWorkerUnavailable at once instead of queueing behind the
  dead worker. The sync doc comment explains the handshake.
- Requests from a closed instance are refused before they are queued.
Each sync step pays for a chain tip refresh, a UTXO refresh and a tree
state fetch before scanning. At 2500 blocks per batch that overhead was
paid four times as often as before the step-wise sync, for no gain in
peak memory worth the cost. Back to the batch size the one-shot sync used.
…erated d.ts

The JavaScript example in the `is_closed` doc contained `/* reload */`. wasm-bindgen
copies doc comments into webzjs_wallet.d.ts as a block comment, where that `*/` ends the
comment early and leaves the rest of the example as code. tsc then fails to parse the
whole declaration file (TS1443, TS1109, an unterminated template literal at the end),
which breaks type-checking of every consumer.
…ically

A full resync that scans from an old birthday takes long enough that a reload, a
closed tab or a dropped connection used to throw all of its progress away. The store
gains a `wallet.staging` key for a checkpoint of a resync in progress, written with
`stageWallet` and read back with `readStaging`. It never replaces the stored wallet
by itself, so it needs no epoch check; `clearStaging` drops it.

`promoteStaging` makes the checkpoint the stored wallet in one IndexedDB transaction:
the previous `wallet` value is kept under `wallet.backup.previous`, the checkpoint
becomes `wallet` at the next epoch, `wallet.meta` and the birthday mirror follow, and
the checkpoint is deleted. A failure anywhere inside the transaction rolls all of it
back, which the tests check by making the metadata write throw. `stagingIsResumable`
tells whether a checkpoint is short of the tip it was heading for, and `writesSettled`
lets callers wait for queued saves before closing an instance.
…steps

A full resync now drives `sync_step` instead of calling `sync` in up to 20 rounds.
Every four steps (about 10k blocks), and once the wallet reports no more work, the
fresh wallet's bytes are checkpointed to `wallet.staging`. On completion the
checkpoint is promoted to the stored wallet in one transaction; only then is the old
instance closed, marked superseded and replaced in state. A failure keeps the old
wallet and leaves the checkpoint in place; an abort observed between steps drops the
checkpoint and closes the fresh instance. Consecutive failures back off 2/4/8 s and
give up after four, but there is no longer a maximum number of rounds.

At startup the context looks for a checkpoint that is short of its chain tip and
exposes it as `resumableResync`. The block height card then shows where the resync
stopped with Resume and Discard buttons; Resume calls `fullResync` with
`{ resume: true }`, which rebuilds the wallet from the checkpoint bytes, skips the
account import and continues stepping with `first = true` so the subtree roots are
refreshed. Discard clears the checkpoint.

Instance hygiene: the periodic rescan also steps, tagged with the instance id, and
stops without saving if the instance is closed or replaced under it. `reloadWallet`
closes the old instance once the replacement is in state and queued saves have
settled. `withRetry` no longer retries once an instance was closed or the sync worker
stopped. A trap in the wasm worker (RuntimeError: unreachable on the window's error
or unhandledrejection event) is reported to the module with
`report_sync_worker_trap`, so pending sync calls reject instead of hanging, and the
user is told to reload; `isWasmTrapEvent` recognizes those events.
IDBObjectStore.put throws synchronously when the record cannot be
cloned, for example DataCloneError when the renderer is out of memory.
In saveWallet and stageWallet that exception escaped the request
callback, so the write promise never settled and a resync sat at its
checkpoint forever instead of reporting an error. Both handlers now
catch, abort the transaction and reject, through the same helper
promoteStaging already used. Tests cover both paths with an uncloneable
record and check the stored wallet and checkpoint are untouched.

The checkpoint log line now includes the blob size, so growth across
checkpoints is visible in the console.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant