Skip to content

feat(platform-wallet-ffi): prefetch shielded spend anchors when a send screen opens - #6042

Draft
PastaPastaPasta wants to merge 28 commits into
v5.2-devfrom
feat/shielded-spend-anchor-prefetch
Draft

PastaPastaPasta wants to merge 28 commits into
v5.2-devfrom
feat/shielded-spend-anchor-prefetch

Conversation

@PastaPastaPasta

Copy link
Copy Markdown
Member

Issue being fixed or feature implemented

#5280 adds a 30-second cache of Platform's recorded shielded-anchor set, which only helps a send that follows another fetch. This PR lets an app fill that cache when a send screen opens, so the first send also skips the fetch. It was split out of #5280 and is stacked on it; retarget to v5.2-dev once #5280 merges.

What was done?

  • NetworkShieldedCoordinator::prefetch_recorded_anchors(): fills the cache unless it already holds a usable set; one prefetch at a time.
  • PlatformWalletManager::prefetch_shielded_spend_anchors(runtime): queues that as a background task on the given Tokio runtime.
  • FFI platform_wallet_manager_shielded_prefetch_spend_anchors(handle) and Swift PlatformWalletManager.prefetchShieldedSpendAnchors(). SwiftExampleApp's send screen calls it.
  • The FFI lookup uses a recursive registry read so the export can be called from an event callback (this is why parking_lot goes to 0.12 in the FFI crate).

Teardown contract

A borrowed SDK callback context must outlive all SDK work that can use it. Teardown of the prefetch is therefore seal-and-cancel:

  • manager shutdown() and drop stop admitting prefetches and abort a pending one;
  • they do not wait for it, so a context-provider callback that is already running may still finish after destroy returns.

The prefetch cannot be the thing that keeps a borrowed context safe: foreground operations such as unshield hold their own references past destroy, and a sync worker can outlive its shutdown budget. The earlier design in #5280 tried to join the prefetch in teardown, and each review round found another re-entrancy case (drop or destroy from inside the callback, a cancelled future dropped under its own lock). Those cases do not arise without a join.

platform_wallet_manager_destroy's documentation now states this, using the wording proposed in review on #5280, with one clause changed because nothing is joined: "any active prefetch callback has returned" became "a prefetch callback that is already running may still finish".

How Has This Been Tested?

  • Unit tests for coalescing, cancel-and-seal on shutdown, cancel on drop, and re-admission after a finished prefetch.
  • FFI tests: unknown handle, manager without shielded support, rejection after shutdown, a pending prefetch cancelled by destroy without entering the host callback, a call from inside a runtime context, and the registry lock cycle from a sync-completion callback (child process).
  • cargo test -p platform-wallet-ffi --features shielded --lib -- shielded_spend_prefetch manager:: spv::: 45 pass. cargo test -p platform-wallet --features shielded,test-utils --lib -- shielded_prefetch manager::tests: 35 pass. Clippy -D warnings and cargo fmt --check are clean for both crates.
  • Not done: the Swift build was not rerun on this branch (no Xcode on the build machine); CI covers it.

Breaking Changes

None. New FFI export and Swift method only.

Open review points carried from #5280

  • Calling platform_wallet_manager_destroy from inside an SDK callback still panics in block_on; that is not specific to the prefetch and is not changed here.
  • Review suggested try_read on parking_lot 0.13 instead of the downgrade, and warming the example app's send screen regardless of shielded balance. Neither is done yet.

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed
  • If I added or changed GroveDB structure, I described it in the area's structure.rs, regenerated grovedb-structure.json, and checked the structure viewer link posted on this pull request

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

PastaPastaPasta and others added 22 commits November 19, 2026 14:17
…lded spend path

Every shielded spend (transfer, unshield, withdraw, identity top-up and
create from the pool) fetched and proof-verified Platform's whole
recorded-anchor set before it could pick a checkpoint and start proving:
a serial round trip on every send.

Keep the most recently fetched set in a RecordedAnchorCache owned by the
NetworkShieldedCoordinator, and let the spend path select against it when
it is younger than 30 s (on both the monotonic and the wall clock, so
device sleep cannot stretch it) and the local commitment tree still has
the leaf count read before that fetch was sent. Platform records a
block's anchor in the same block-end transaction that appends its notes,
so at an unchanged tree size the cached set holds every checkpoint root a
fresh fetch could find, except anchors pruned since. The size pin
therefore keeps the selected anchor identical to a fresh fetch, and the
TTL bounds the extra pruning exposure to a few percent of the 1000-block
retention.

A cached set that covers no checkpoint triggers a fresh fetch, any failed
spend invalidates the cache so the retry selects afresh, and a contended
store lock skips the cache instead of queueing in front of the fetch.

Every existing fetch refreshes the cache: the send path, the
stranded-reservation release pass (which keeps judging against its own
pre-scan fetch), and a new NetworkShieldedCoordinator::prefetch_recorded_anchors
for hosts to call when a send screen opens. Clear drops the cache.

The spend free functions in shielded::operations take the cache as a new
parameter after the store; PlatformWallet passes the coordinator's.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…d screen opens

Expose NetworkShieldedCoordinator::prefetch_recorded_anchors over the C
ABI as platform_wallet_manager_shielded_prefetch_spend_anchors(handle),
which queues the fetch on the FFI runtime and returns immediately, and
wrap it in Swift as PlatformWalletManager.prefetchShieldedSpendAnchors().

SwiftExampleApp's send screen calls it on appear when the wallet holds
shielded funds, so the recorded-anchor round trip overlaps filling in the
form instead of delaying the send.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…rive after the send screen opens

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…as invalidated

A prefetch in flight while a spend failed could refill the cache with the
set holding the rejected anchor, so the retry would reuse it. Record when
the cache was last invalidated and drop results of requests sent before
that. Also trim the anchor-cache docs to the module's usual density.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Overlapping prefetch calls each downloaded and verified the full anchor
set. A prefetch now skips while another is in flight; spends and the
release pass are unaffected. Also note in the cache docs that the
same-anchor guarantee assumes an equally current node.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…vent callback

Event callbacks fire inside a runtime context, because the shielded sync
loop drives its passes with Handle::block_on. Calling the prefetch export
from one re-entered runtime().block_on to resolve the coordinator, so Tokio
panicked at the extern "C" boundary and aborted the host. When it is called
inside a runtime context, the lookup now runs on a thread outside it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ompletion callback

platform_wallet_manager_shielded_sync_sync_now holds the manager
registry's read guard until the pass returns, completion callback
included. When a registry writer (a manager create or destroy) queued
behind that guard, parking_lot parked the prefetch's plain registry read
behind the writer, so the callback waited on the writer, the writer on
the sync, and the sync on the callback.

The prefetch now looks the manager up with a recursive read, which only
waits for a writer that actually holds the registry. That is safe for the
manager registry, whose only writers are insert and remove.

The child-process deadlock harness from the SPV start tests moves to
test_fixtures, so the new regression test shares it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Teardown joined a Tokio task from Drop, which needed the caller's
runtime to allow blocking. Inside a LocalSet that panics before the
join, and a finished JoinHandle polled with no cooperative budget left
returned Pending and lost the task's panic.

The prefetch now keeps its future behind a lock. The runtime task only
polls it under that lock, so a host callback runs only while the lock
is held. Shutdown and Drop seal admission, take the lock and drop the
future themselves. Nothing is joined, so teardown no longer depends on
the runtime, the caller's budget or the thread it runs on. A panic is
recorded where it is caught.

Admission takes the runtime handle as an argument, so any Tokio runtime
works and the FFI export no longer enters the runtime on the caller's
thread. The only refusal left is a manager that is shut down.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A manager dropped from inside its own prefetch callback waited for the
lock its own thread held. Such a drop now only seals admission, and the
poll that is running the callback drops the future before it releases
the slot.

A destroy call that lost the race for a handle returned Success while
the winning call was still waiting for an active callback. It now
returns ErrorInvalidHandle, so only the call that ran the teardown
reports it complete.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…y changes

A recorded-anchor set stayed reusable after the SDK's context provider
was replaced, or after an adaptive provider switched quorum source in
place. A spend could then use a set, and persist its proved height,
that the policy now in force never verified.

The cache now records the installed provider and the quorum source it
reports. Readers check it before a lookup and fetches before storing,
so a change drops the cached set and any fetch that spanned it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… anchor cache change

The send-screen prefetch and its teardown go to a follow-up change. This
one keeps the recorded-anchor cache on the spend path, which sends and
the stranded-reservation release pass fill.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@thepastaclaw

thepastaclaw commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

🕓 Review not started yet because this PR is a draft.

  • Request normal review — click when the PR is ready for review.
  • Request priority review — click to move this review to the front of the queue.

Commit 7c75453. Normal review starts when eligible; priority review starts as soon as a slot is available.

PastaPastaPasta and others added 2 commits November 21, 2026 23:08
The cache read the provider's reported quorum source to notice a policy
change. That reading asks SPV whether it is ready, which can block and
panics inside a LocalSet, and it does not change when an Auto provider
that already uses SPV is switched to strict SPV.

ContextProvider::quorum_mode() returns the mode last set, without
asking any source. The cache compares that instead, so every explicit
switch drops the cached set and reading the policy never blocks.

A custom cache TTL is now capped at the 30-second default.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…nter

Comparing the quorum mode before and after a fetch missed a switch that
was switched back while the fetch was verifying, and reading it through
a Mutex-wrapped provider took the lock, which could deadlock or panic
during shielded configuration.

ContextProvider::policy_revision() replaces quorum_mode(). The adaptive
provider packs its mode and a change counter into one atomic, so every
real mode change advances the revision. The Mutex wrapper reads it with
try_lock and reports None when the lock is busy or poisoned; the cache
is then bypassed and any fetch in flight is dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PastaPastaPasta
PastaPastaPasta force-pushed the feat/shielded-spend-anchor-prefetch branch from 287436a to 269839a Compare November 22, 2026 05:22
…verified it

The cache compared the verification policy at separate observation
points, so a set could be returned after a change that landed between
the check and the read, and a release-pass fill verified under a new
policy could be discarded. A Mutex-wrapped provider could also swap its
inner provider without its revision changing.

A request's stamp now records the policy before it is sent. A set is
stored only if that policy still holds when it arrives, and returned
only while it still holds. The Mutex wrapper reports no revision, so it
is never cached against. The release pass skips the tree-size read when
it has nothing to release.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PastaPastaPasta
PastaPastaPasta force-pushed the feat/shielded-spend-anchor-prefetch branch from 269839a to 0bc68c2 Compare November 22, 2026 06:17
PastaPastaPasta and others added 3 commits November 22, 2026 06:43
…ates

policy_revision() defaulted to Some(0), so a provider that never reported
its policy, such as one asking the host for each key, claimed a policy
that never changes. An adaptive provider also reported only its own mode
changes, missing a change in the trusted provider it delegates to.

The default is now None, which the anchor cache never caches against.
Revisions never decrease, so the adaptive provider reports its own count
plus its trusted delegate's, and none when the delegate reports none.
The SPV, trusted HTTP and mock providers opt in with a fixed revision.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The anchor cache reuses a set only under a provider that reports its
policy revision. Assert that the trusted, SPV and adaptive SDKs the
native apps build still report one, so wrapping a provider cannot turn
the cache off unnoticed.

The adaptive provider's revision returns None instead of wrapping on
overflow, and the docs state that a published SPV client must serve only
SPV-verified keys, which no revision tracks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d screen opens

Adds the send-screen warm-up for the recorded-anchor cache: a
coordinator prefetch, the FFI export, the Swift wrapper and the example
app call.

Teardown is seal-and-cancel. Manager shutdown and drop stop admission
and abort a pending prefetch without waiting for it, so a context
provider callback that is already running may still finish. A borrowed
SDK callback context must outlive all SDK work that can use it; the
destroy export's documentation now says so.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@PastaPastaPasta
PastaPastaPasta force-pushed the feat/shielded-spend-anchor-prefetch branch from 0bc68c2 to 7c75453 Compare November 22, 2026 07:02
Base automatically changed from perf/shielded-anchor-cache to v5.2-dev November 24, 2026 23:45
@github-actions github-actions Bot added this to the v5.2.0 milestone Nov 24, 2026

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