Skip to content

fix(platform-wallet): stop reporting a shielded balance as known after a Clear that failed - #6186

Merged
QuantumExplorer merged 2 commits into
v5.1-devfrom
fix/shielded-failed-clear-forgets-scan-evidence
Nov 24, 2026
Merged

QuantumExplorer merged 2 commits into
v5.1-devfrom
fix/shielded-failed-clear-forgets-scan-evidence

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Basic explanation

What this does. A shielded "Clear" first empties the commitment tree and then deletes the wallet's notes and scan state. If the first step works and the second fails, the notes stay. Until now such a wallet could still report its old shielded balance as a known amount. After this change it reports "not known yet" until a scan completes again or the app restores it.

Value. After a Clear that failed half way, the app no longer shows the pre-Clear amount as if it were established, against a tree that was just emptied. The app is also told about the change: before, nothing was announced, so it kept showing the amount.

Risks. Small. Rust only, one crate, no FFI or host change. The only behaviour that changes is on the failure path of Clear, which needs a storage error.

Before and after

Wallet with 900 credits, its ledger established by a scan completed in this session (no host restore behind it). Clear resets the tree, then the purge fails.

Before After
local_balance_snapshot Ready, account 0: 900 credits, ScannedThisSession, last_scanned_index: Some(1) RestoreIncomplete
Balance emitter sends nothing (state unchanged) sends RestoreIncomplete
The account in the store ScannedThisSession, established NoHistory, last_scanned_index: None, not established; still 900 credits of notes
Notes, watermarks, pending spends kept kept
After the next completed scan Ready, 900, ScannedThisSession the same

Issue being fixed or feature implemented

Closes #5988.

Confirmed on v5.1-dev (3b4117c64d): with the fix switched off, both new tests fail with exactly the state the issue describes:

left: Ready(ShieldedLocalBalanceSnapshot { accounts: {0: ShieldedLocalAccountBalance {
        spendable_credits: 900, last_scanned_index: Some(1), source: ScannedThisSession }} })
right: RestoreIncomplete

NetworkShieldedCoordinator::clear resets the tree, then calls purge_all_subwallets. The file store's purge deletes its SQL rows before it touches memory, so a failed purge leaves every subwallet as it was. Clear then drops hydration and returns the error. local_balance_snapshot reports RestoreIncomplete for a wallet that is not hydrated, unless an account's source is ScannedThisSession: a completed scan stands in for hydration. So an account scanned in this session stayed Ready.

What was done?

  • FileBackedShieldedStore::forget_scan_evidence() (crate-internal): for every subwallet, last_scanned_index = None and balance_source = NoHistory. Notes, last_synced_index and pending spends are not touched. Both fields are session-only state; nothing durable changes.
  • clear() calls it when the Clear failed, under the same store write guard as the reset. It runs for any failure, not only a failed purge: a tree reset can also fail after it has changed part of its state, which is why hydration is already dropped "regardless of the outcome" there. The scan evidence now goes with the hydration.
  • The comment in local_balance_snapshot that lists who removes the source now names the failed Clear.

After that, the ledger is established again the usual ways: a completed scan sets ScannedThisSession, and a bind that restores from the host's rows sets Restored and marks the wallet hydrated.

Not changed, and worth knowing

A Clear that fails this way keeps the sync watermarks, as the issue asks. The next scan therefore resumes from the old watermark into the emptied tree. That is a separate problem with the tree's contents, not with what the balance reports, and is filed as #6184.

Public interface changes

None. No public Rust item is added or changed, and nothing changes in the FFI, JNI, Swift or Kotlin.

Behaviour a caller can observe, all on a Clear that returned an error:

  • NetworkShieldedCoordinator::local_balance_snapshot returns RestoreIncomplete for a wallet whose accounts were at ScannedThisSession (before: Ready with the pre-Clear amounts). Wallets that were hydrated, not scanned, already returned RestoreIncomplete.
  • The shielded balance emitter delivers that state change to on_shielded_balance_changed, so Swift and Kotlin hosts show the balance as unknown instead of keeping the old amount.

How Has This Been Tested?

  • cargo test -p platform-wallet --all-features --locked --lib -- wallet::shielded::balance wallet::shielded::coordinator::tests::clear: 35 passed.
  • New tests, both starting from an account with a completed scan and no hydration, with a real SQLite failure in the purge (the shielded_pending_spends table renamed away):
    • should_forget_scan_evidence_when_a_clear_resets_the_tree_but_fails_to_purge: the wallet reads RestoreIncomplete; the tree is empty; the note is kept; the account is NoHistory, last_scanned_index: None, not established, 900 credits; a scan completing afterwards makes it Ready again.
    • should_emit_restore_incomplete_after_a_failed_clear_of_a_scanned_wallet: the emitter delivers RestoreIncomplete.
  • Both fail with the fix switched off (output above).
  • The existing local_balance_recovers_after_failed_clear_and_completed_scan and should_emit_restore_incomplete_after_a_clear_that_fails still pass.
  • The other failure path is covered too: clear_failure_still_invalidates_hydration_and_snapshots, which breaks the tree reset itself, now starts from a scanned account and requires RestoreIncomplete afterwards.
  • The four tests that fail a Clear in the purge share clear_failing_at_the_purge, which also checks that the purge is the step that failed.
  • cargo clippy -p platform-wallet --all-targets --all-features --locked -- -D warnings: clean. cargo fmt --all -- --check: clean.

Not yet verified

  • No device or emulator run: the failure needs a storage error between the two steps of one Clear, which the tests inject and an app cannot.

Breaking Changes

None.

Checklist:

  • I have performed a self-review of my own code
  • My Rust, FFI, WASM, Swift or Kotlin changes follow the coding conventions
  • 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
  • If I added or changed a system contract's document schemas, I checked the contract 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

PR Hygiene · 931302b

  • Bots — thepastaclaw ✓
  • Self-review — post /self-reviewed
  • Reviewer requests paused — your 5 review slots are occupied; this PR is excluded from reviewers' queues. Required approvals still count without a slot.
  • Build green
  • Approvals
    • rs-platform-wallet (packages/rs-platform-wallet/src/wallet/shielded/balance_emitter_tests.rs, packages/rs-platform-wallet/src/wallet/shielded/balance_tests.rs, packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs and 1 more) — HashEngineering or ZocoLini or llbartekll or romchornyi

When every merge requirement is met, the PR Hygiene check passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.

…r a Clear that failed

A shielded Clear resets the commitment tree and then purges the ledger.
When the reset landed and the purge failed, the notes stayed, and so did
the evidence of a scan completed in this session. Hydration is dropped on
a failed Clear, but a completed scan stands in for it, so such an account
still read as `Ready` with its pre-Clear amount, against an emptied tree.
The balance emitter saw no change and sent nothing.

A failed Clear now forgets every subwallet's scan evidence (its scan
coverage and balance source), under the same store guard as the reset.
The wallet reads as `RestoreIncomplete` until a scan completes or a
restore from the host covers it. Notes, watermarks and pending spends are
kept.

Closes #5988

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

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 22 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 3b4117c and 931302b.

Files selected for processing: 4

  • packages/rs-platform-wallet/src/wallet/shielded/balance_emitter_tests.rs
  • packages/rs-platform-wallet/src/wallet/shielded/balance_tests.rs
  • packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs
  • packages/rs-platform-wallet/src/wallet/shielded/file_store.rs
  • 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

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Nov 23, 2026
@github-actions github-actions Bot added this to the v5.1.0 milestone Nov 23, 2026
@thepastaclaw

thepastaclaw commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Final review complete — no blockers (commit 931302b)

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final validation — Phase 1 + Phase 2

A failed shielded Clear now invalidates scan evidence alongside hydration, so balance reads and callbacks report RestoreIncomplete instead of treating the retained pre-Clear amount as known. Linux wallet tests and Kotlin emulator checks passed; the Swift SDK build and tests are still pending, and no code checks have failed.

🟡 1 suggestion(s) | 💬 1 nitpick(s)

Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.

Review provenance

Source: reviewer 1: glm-5.3-flash (agent: phase1-reviewer, role: general); reviewer 2: glm-5.3-flash (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: low by gpt-6.2-sol (effort low) — The fix is confined to invalidating in-memory balance evidence under the existing write guard when Clear fails, with regression tests for the snapshot and emitted update.
  • Phase 1 reviewers: glm-5.3-flash — general (completed, effort high); agent phase1-reviewer, glm-5.3-flash — rust-quality (completed, effort high); agent phase1-reviewer
  • Phase 1 model: glm-5.3-flash — zai quota: 5h 94% left, weekly 77% left; passed over gemini-3.8-flash-high (lane failed)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort medium); agent phase2-reviewer, gpt-6.2-sol — architecture-layering (completed, effort medium); agent phase2-reviewer, gpt-6.2-sol — rust-quality (completed, effort medium); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs:1691-1693: The tests miss stale known balances when the tree reset itself fails
  Impact: A regression limited to the tree-reset error path could pass the tests while a previously scanned wallet still reports its pre-Clear balance as known after a partial reset.
  A regression that forgets scan evidence only on purge errors would pass both new tests. Both rename the pending-spends table to fail the purge, but the new guard also covers errors from the tree reset itself, which can fail after changing tree tables. The existing `clear_failure_still_invalidates_hydration_and_snapshots` test forces a reset error but checks only hydration and snapshot generation. Extend it to establish `ScannedThisSession` with `set_last_synced_note_index` before breaking the reopen, then assert that `local_balance_snapshot` returns `RestoreIncomplete` after Clear fails.

In `packages/rs-platform-wallet/src/wallet/shielded/balance_emitter_tests.rs`:
- [NITPICK] packages/rs-platform-wallet/src/wallet/shielded/balance_emitter_tests.rs:638-644: The same SQLite purge-failure setup is repeated in four tests
  Impact: Maintainers changing how a purge failure is injected or checked must update four sites across two files to keep the tests exercising the same failure path.
  The two new tests repeat the existing sequence of renaming the pending-spends table, calling Clear, and restoring the table. The databases are isolated, so this is not a cleanup safety issue. A shared test helper could own both schema changes, restore the table before checking the result, and verify that Clear failed in the purge rather than merely returning an error from any step.
Out-of-scope follow-up suggestions (2)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • The next scan can skip commitments after a partial Clear — The scan starts at the retained watermark rounded down to a chunk boundary. If that boundary is past the end of the emptied tree, the scan can skip commitments needed to rebuild it and still mark the balance as known. This behavior predates the patch.
    • Follow-up: Use #6184 to fix the scan start and verify both tree reconstruction and balance state through the real scan path.
  • A token-pool purge error can leave durable spend guards deleted — purge_all_subwallets deletes pending-spend rows before running the separate token-pool transaction. If the latter fails, the in-memory guards remain, but reopening the store cannot recover the deleted rows. This ordering predates the patch.
    • Follow-up: Include a failed token-pool purge followed by a store reopen in the durable-guard work tracked by #6011.

@github-actions

Copy link
Copy Markdown
Contributor

Bots are done — your move: post /self-reviewed.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 24, 2026
…e-failure setup

A failed Clear forgets scan evidence whichever step failed, but the new
tests only failed the purge. The existing test that breaks the tree reset
now starts from a scanned account and checks the balance is not reported
as known afterwards.

The four tests that fail a Clear in the purge share one helper, which also
checks that the purge is the step that failed.

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

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 24, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review — Final validation — Phase 1 + Phase 2

New on this head: The latest commit changes only tests: it gives all four purge-failure tests a shared SQLite fixture and verifies that a failed tree reset leaves a previously scanned wallet’s balance unknown. The Kotlin SDK emulator build and tests and the policy checks passed; PR Hygiene and the review check are still pending, and no code checks are failing.

🔴 0 blocking | 🟡 0 suggestion(s) | 💬 0 nitpick(s)

Review provenance

Source: reviewer 1: glm-5.3-flash (agent: phase1-reviewer, role: general); reviewer 2: glm-5.3-flash (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: low by gpt-6.2-sol (effort low) — The fix is confined to invalidating session-only balance evidence after a failed Clear, with regression tests and no changes to durable state or funds movement.
  • Phase 1 reviewers: glm-5.3-flash — general (completed, effort high); agent phase1-reviewer, glm-5.3-flash — rust-quality (completed, effort high); agent phase1-reviewer
  • Phase 1 model: glm-5.3-flash — zai quota: 5h 91% left, weekly 76% left; passed over gemini-3.8-flash-high (lane failed)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort medium); agent phase2-reviewer, gpt-6.2-sol — architecture-layering (completed, effort medium); agent phase2-reviewer, gpt-6.2-sol — rust-quality (completed, effort medium); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify the current code and confirm that no unresolved issues remain.

No unresolved findings remain from the prior review on this head.

@github-actions

Copy link
Copy Markdown
Contributor

Bots are done — your move: post /self-reviewed.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 24, 2026
@QuantumExplorer
QuantumExplorer merged commit 3366418 into v5.1-dev Nov 24, 2026
14 of 15 checks passed
@QuantumExplorer
QuantumExplorer deleted the fix/shielded-failed-clear-forgets-scan-evidence branch November 24, 2026 00:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

waiting-self-review Waiting for the author to post /self-reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A shielded Clear that resets the tree but fails to purge leaves the balance reported as known

2 participants