Skip to content

Bounded sync steps, instance ids, close and worker poisoning - #18

Open
sqhell wants to merge 11 commits into
red-dev-inc:mainfrom
sqhell:feat/resumable-sync
Open

sqhell wants to merge 11 commits into
red-dev-inc:mainfrom
sqhell:feat/resumable-sync

Conversation

@sqhell

@sqhell sqhell commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What

  • Wallet::sync_step(first) refreshes the chain tip, scans at most one batch, releases the write lock and reports whether more work remains; Wallet::sync is a loop over it. Built on zcash_client_backend::sync::run_step from the pinned fork (sqhell/librustzcash branch snap/0a2c6d1-ironwood-step-sync: the pinned 0a2c6d1 plus the extraction fix plus run_step).
  • Every Wallet has an instance_id and a close() switch; a closed instance fails sync, persistence, proposal and signing with Error::InstanceClosed, so a loop driving a replaced instance stops at the next batch boundary.
  • WebWallet gains sync_step, instance_id, close, is_closed; the shared sync worker dispatches full syncs and steps. report_sync_worker_trap() lets the page's error handler poison a trapped worker so later calls reject with SyncWorkerUnavailable instead of queueing forever.
  • Batch size stays at 10000 blocks (a step also pays a chain-tip refresh, UTXO refresh and tree-state fetch).

Why

Wallet::sync took the write lock once and ran the whole scan, so a historic resync could not be persisted or stopped part way, and hours of scanning lived only in memory. The fork's run_step keeps the verification of the chain-tip view out of the step budget, so every step scans a full batch; an earlier draft charged the 10-block Verify lookahead to the budget and crawled at 10 blocks per step.

Stack

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

  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 (this PR)
  15. Resumable, checkpointed full resync driven by sync steps #19 feat/resync-resume

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

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

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.
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.
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.
@danielgorgonha

Copy link
Copy Markdown

One case #18 does not cover is a stall inside one batch. I reproduced it natively at #18's head (53a47ed) and at the head of #27 (9ad0a58).

How I ran it. A native harness calls the inner Rust Wallet methods that the wasm bindings wrap, over native tonic, against a public mainnet lightwalletd, with a throwaway view key that holds no funds. The bindings and the browser transport were not exercised. Note 3 is the run, except where it says read from the code. Notes 1, 2, 4 and 5 are read from the code. The program and its output are in https://github.com/deegalabs/WebZjs/tree/75cf34d5e2db2e602210b363a415364bb0f067a1/repro/stall at #18's head, and in https://github.com/deegalabs/WebZjs/tree/409ce5a294db0a196a24e446f7687621bc9f3677/repro/birthday-lock-stall at #27's head.

  1. sync_step takes the write lock and holds it across one run_step call (wallet.rs:400-414). Nothing bounds that call.
  2. The client is built with Client::new and no options (bindgen/wallet.rs:274). Bounded sync steps, instance ids, close and worker poisoning #18 builds against tonic-web-wasm-client 0.8.0 from crates.io (Cargo.toml:30). There timeout is an Option<Duration> with no default, and Client::new sets no options. The vendored copy in Feat/nu7 portable keys #27 has the same field and no default either (options/mod.rs:42-43), and fix(vendor): validate gRPC-web body trailers before completion #31 records it in VENDORED.md:73.
  3. If the server or its gRPC-web proxy stops answering during a batch, run_step has no deadline to end it. The lock stays held. I put a TCP proxy between the wallet and the server that stops forwarding after about 3,000,000 bytes from the server at Bounded sync steps, instance ids, close and worker poisoning #18's head and at Feat/nu7 portable keys #27's head, and keeps the connection open. The proxy counts bytes, not requests, so which request the stall falls in is not logged. It had passed 3,003,290 bytes at Bounded sync steps, instance ids, close and worker poisoning #18's head and 3,006,474 at Feat/nu7 portable keys #27's. sync() and get_wallet_summary did not return within 120 s, while a separate connection to the same server answered in 22 ms at both heads (an upper bound). Only get_wallet_summary was run during the stall. db_to_bytes, propose_transfer, pczt_shield, pczt_create and pczt_send take the same lock, read from the code (wallet.rs:183-186, :429-462, :591-639, :723-777, :892-943).
  4. The release between batches does not cover this. close() does not either, because a running step finishes its batch first (wallet.rs:150-156). report_sync_worker_trap answers a trap and not a stall.
  5. README.md:54 still says other methods are safe to use while a sync runs.

A deadline sized to one batch, inside the client or around run_step, would drop the lock when it fires. A FetchOptions::timeout on the client covers the whole fetch, including the body stream, so it has to be sized for a 10,000-block GetBlockRange and not for a single request. This can be a follow-up and does not need to block #18.

🤖 Generated with Claude Code

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.

2 participants