Repository navigation
fix(platform-wallet): stop a shielded note scan at a gap between fetched ranges - #6172
Conversation
…hed ranges The note scan fetches adjacent ranges concurrently, each proved at its own height. A range answered a block earlier can end short of the next range's start while the next one, answered after the tree grew, holds notes. The scan used that later range anyway: its commitments were appended at shifted positions, its nullifiers replayed, and the watermark moved past positions that were never read, so notes there were never decrypted. The pass now ends at the first range that starts past the positions read so far and holds notes. Nothing past the gap is appended, replayed or counted, and the watermark is the end of the run read without a gap. The next pass reads on from there. Closes #6109 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Warning Review limit reachedYou'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 39 minutes. View limit details
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. |
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
|
🔍 Review in progress (commit 4b444f5) · live progress |
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 1 + Phase 2
Changes requested: 1 blocker
- A scan stopped at a gap can show spent funds and leave restored history incomplete —
packages/rs-platform-wallet/src/wallet/shielded/sync.rs:580-587(new)
Impact: When a restore scan hits a gap, users can see an already-spent note as available or recover a payment into their balance that never appears in activity.
This patch stops the shielded wallet scan at the first nonempty range beyond a gap and advances the watermark only through positions read contiguously. For head 6788e85, Linux Rust wallet tests and the Swift and Kotlin SDK checks passed; PR Hygiene remains pending. No tests were run locally.
🔴 1 blocking | 🟡 1 suggestion(s) | 💬 1 nitpick(s)
1 finding(s) not shown inline (the lines are not part of this PR's diff)
💬 Nitpick: The scan counter documentation includes notes fetched but discarded at a gap
Impact: Host integrators reading the field documentation can mistake the Scanned counter for download volume when a pass discards a fetched range.
packages/rs-platform-wallet/src/wallet/shielded/sync.rs:174-180
total_scanned can be lower than the amount downloaded: the gap check runs before total_notes_scanned is incremented, and the final formula excludes the already-covered overlap. The formula in the field doc remains correct, but the description of the input as notes pulled from Platform now includes batches the wallet discarded. Describe it as the scan volume from the contiguous prefix the wallet accepted, after subtracting overlap.
source: glm-5.3-flash (phase1-reviewer: general, rust-quality)
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); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
lowbygpt-6.2-sol(effort low) — The production change is confined to stopping the shielded wallet scan at a gap and deriving its watermark from the contiguous prefix, with regression tests covering recovery on the next pass. - Phase 1 reviewers:
glm-5.3-flash— general (completed, effort high); agentphase1-reviewer,glm-5.3-flash— rust-quality (completed, effort high); agentphase1-reviewer - Phase 1 model:
glm-5.3-flash— zai quota: 5h 95% left, weekly 77% left; passed overgemini-3.8-flash-high(lane failed) - Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-sol— general (completed, effort medium); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort medium); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort medium); agentphase2-reviewer,gpt-6.2-sol— security-auditor (completed, effort medium); agentphase2-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/sync.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/shielded/sync.rs:580-587: A scan stopped at a gap can show spent funds and leave restored history incomplete
Impact: When a restore scan hits a gap, users can see an already-spent note as available or recover a payment into their balance that never appears in activity.
A newly bound subwallet can report funds it cannot spend. Its zero watermark makes the coordinator scan from the beginning even if another wallet has already synced the shared tree through the tip. If the accepted prefix contains a receipt and the newer batch beyond the gap contains its spend, `break false` discards the spend but still saves the receipt as unspent and stamps the balance `ScannedThisSession`. Send selection reads those unspent notes, and a witness against the already-caught-up tree can pass the recorded-anchor check: that check proves the note exists, not that it is unspent. Before this change, the later batch's nullifier was replayed even when its commitments were already in the shared tree.
The same completion path can permanently undercount restored activity. A full range proved at H can contribute a receipt before a short range proved at H−1 stops the scan. If the retry recovers another receipt also proved at H, activity derivation groups both receipts together, then treats the existing entry's overlapping commitment as confirmation only. It never adds the recovered value. The coordinator can also stamp its 30-second caught-up cooldown if the prefix only reread known positions and no other activity was detected, delaying a retry for hosts that poll within that window.
Keep the contiguous tree checkpoint, but fill the known gap before finalizing the ledger, or return a distinct incomplete result that defers balance and activity publication and clears the cooldown. If receipt writes are deferred, keep their wallet watermarks available for replay. Add regressions for a restored subwallet on a caught-up shared tree and for activity recovered at the same proof height on retry.
- [NITPICK] packages/rs-platform-wallet/src/wallet/shielded/sync.rs:174-180: The scan counter documentation includes notes fetched but discarded at a gap
Impact: Host integrators reading the field documentation can mistake the Scanned counter for download volume when a pass discards a fetched range.
`total_scanned` can be lower than the amount downloaded: the gap check runs before `total_notes_scanned` is incremented, and the final formula excludes the already-covered overlap. The formula in the field doc remains correct, but the description of the input as notes pulled from Platform now includes batches the wallet discarded. Describe it as the scan volume from the contiguous prefix the wallet accepted, after subtracting overlap.
In `packages/rs-platform-wallet/src/wallet/shielded/sync/range_gap_tests.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/sync/range_gap_tests.rs:156-174: The gap test misses the coverage result when the newer fetch finishes first
Impact: When the newer response finishes first, a wallet can safely save the prefix but defer pending-spend reconciliation because the pass reports no covered height.
The gap regression only tests the completion order that reports `Some(EARLIER)`. The SDK emits batches in position order, but `StreamState::pop_ready` supplies the largest count seen across completed fetches, not the count from the emitted batch's own proof. If the newer fetch finishes first, the short batch has `total_count == 6`; the wallet compares its end position of 2 against 6 and leaves `covered_height` unset. This is conservative. Add a case with that metadata and assert that the scan still stops at position 2, claims no covered height, and recovers the skipped notes on retry.
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 one-shot SDK scan still combines notes across gaps — The unchanged public
sync_shielded_notescollector concatenates raw notes from both sides of a gap and can return a resume index beyond unread positions. External SDK callers can misplace leaves and miss receipts; the wallet uses the streaming API.- Follow-up: Use #6181 to fix the one-shot collector and test that resuming recovers the missing range.
- Previously corrupted wallet trees still need a rebuild — Stopping at new gaps does not replace commitments already appended at incorrect positions or recover notes behind an incorrect persisted watermark.
- Follow-up: Keep detection and explicit rebuild in #5565.
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them. |
…stops at a gap A pass that met a gap between two fetched ranges published the run of positions it had read: notes, spent marks, a watermark at the gap and a scanned balance. It knew the pool held more than it read, so that ledger was incomplete: a receipt in it could already be spent by an action past the gap (notably for an account bound late and scanned from position 0), the activity derived from it could be frozen short of a note the next pass finds at the same proved height, and a pass that read nothing new stamped the caught-up cooldown and delayed the retry. The pass now ends as a cut-short pass does: the commitments it read up to the gap stay appended and checkpointed, nothing else is published, and MultiSyncNotesResult::stopped_at_gap is set. The coordinator returns the empty summary for it and clears the caught-up stamp, so the next pass reads the pool again at once. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Your move: thepastaclaw left review threads unresolved; resolve them. |
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
…et-shielded-scan-watermark-gap Conflict in coordinator.rs: both sides added a test at the same place; both are kept. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
New on this head: The follow-up checkpoints the contiguous tree prefix without publishing ledger changes or advancing wallet watermarks, and clears the caught-up cooldown so the next pass can retry. The regression tests now cover both fetch completion orders and a late-bound account on a caught-up shared tree. CI shows the Rust workspace tests and Swift SDK build and tests passed; Kotlin SDK build and emulator tests are still pending.
🟡 2 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.
1 finding(s) not shown inline (the lines are not part of this PR's diff)
💬 Nitpick: The scan counter documentation includes notes fetched but discarded at a gap
Impact: Rust callers can read a zero scan count as zero notes downloaded even when the pass processed and checkpointed a prefix.
packages/rs-platform-wallet/src/wallet/shielded/sync.rs:174-180
The new stopped_at_gap documentation explains why the result is empty, but total_scanned itself still describes wire volume for the pass. The gap return bypasses the calculation and leaves the field at zero even after processing a prefix. On a completed pass, the formula subtracts positions before the previous watermark, so it is not a count of every note downloaded. Describe it as the published scan count for a completed pass and state what a cut-short pass returns.
/// On a completed pass, the host-visible "Scanned" count: notes
/// processed (decrypted or skipped) beyond the previous watermark.
/// Computed as `(aligned_start + total_notes_scanned).saturating_sub(already_have)`.
/// This counts neither all downloads nor just newly appended leaves.
/// A cut-short pass reports zero even if it checkpointed new leaves.
/// See [`SyncNotesResult::total_scanned`] for the rationale.
source: glm-5.3-flash (phase1-reviewer: rust-quality); gpt-6.2-sol (phase2-reviewer: general, architecture-layering, rust-quality)
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); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
lowbygpt-6.2-sol(effort low) — The production change is a contained control-flow fix that reuses the existing cancellation path and clears the coordinator cooldown, with most of the diff devoted to regression tests. - Phase 1 reviewers:
glm-5.3-flash— general (completed, effort high); agentphase1-reviewer,glm-5.3-flash— rust-quality (completed, effort high); agentphase1-reviewer - Phase 1 model:
glm-5.3-flash— zai quota: 5h 90% left, weekly 76% left; passed overgemini-3.8-flash-high(lane failed) - Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-sol— general (completed, effort medium); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort medium); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort medium); agentphase2-reviewer,gpt-6.2-sol— security-auditor (completed, effort medium); agentphase2-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:1950-1964: A shielded scan stopped at a gap still reports completion and refreshes the last-sync timestamp
Impact: Hosts that use the completion event or last-sync timestamp to check freshness can treat an unchanged shielded ledger as freshly scanned after a manual or background pass hits a gap.
Hosts receive a new completion timestamp even though the pass did not reconcile any wallet's shielded ledger. The new gap branch returns a default summary without cancelling the pass token. In `manager/shielded_sync.rs:483–519`, `sync_now` suppresses completion for an empty summary only when the token is cancelled. It otherwise supplies a timestamp, stores it in `last_sync_unix`, and dispatches `on_shielded_sync_completed`. The FFI callback forwards that timestamp even with zero wallet results. Carry the incomplete outcome to the Rust manager and return before stamping or dispatching it, while preserving the behavior of other empty passes. Extend the regression through `sync_now` to check both the timestamp and the callback; the coordinator test cannot observe either.
In `packages/rs-platform-wallet/src/wallet/shielded/sync.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/sync.rs:195-200: Adding the gap flag breaks existing Rust literals and exhaustive patterns for the scan result
Impact: Downstream Rust code that constructs `MultiSyncNotesResult` with a full literal or destructures it without `..` no longer compiles.
`MultiSyncNotesResult` is reachable through the public `wallet::shielded::sync` module and previously had only public fields, with no `#[non_exhaustive]` restriction. Adding `stopped_at_gap` therefore breaks full literals and exhaustive patterns; deriving `Default` only helps callers already using struct update syntax. The PR's interface notes acknowledge the literal break, but its Breaking Changes section says none. Carry the stop reason in an internal scan outcome and leave the public result shape unchanged, or record the Rust source break in the Breaking Changes section if it is intentional.
- [NITPICK] packages/rs-platform-wallet/src/wallet/shielded/sync.rs:174-180: The scan counter documentation includes notes fetched but discarded at a gap
Impact: Rust callers can read a zero scan count as zero notes downloaded even when the pass processed and checkpointed a prefix.
The new `stopped_at_gap` documentation explains why the result is empty, but `total_scanned` itself still describes wire volume for the pass. The gap return bypasses the calculation and leaves the field at zero even after processing a prefix. On a completed pass, the formula subtracts positions before the previous watermark, so it is not a count of every note downloaded. Describe it as the published scan count for a completed pass and state what a cut-short pass returns.
Out-of-scope follow-up suggestions (1)
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 SDK's one-shot shielded sync still combines ranges across a gap — The one-shot collector concatenates raw notes from both sides of a gap, so later notes can appear at the wrong offsets and the resume index can skip unread positions. This predates the PR, and the wallet uses the stream directly rather than this collector.
- Follow-up: Fix the one-shot SDK collector separately under #6181.
|
Bots are done — your move: post |
…scan stops at a gap The sync manager suppressed the last-sync time and the completion event for an empty pass only when the pass token was cancelled. A pass whose scan stopped at a gap returned the same empty summary with no stop requested, so the manager stamped the last-sync time and dispatched a completion for a pass that reconciled no wallet's ledger. It now returns before both when the coordinator hands back a summary with no wallet results and no timestamp, which only a cut-short pass does. The gap is now carried by an internal scan outcome (NoteScan) instead of a new public field on MultiSyncNotesResult, whose shape is unchanged. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
Basic explanation
What this does: the shielded note scan downloads the pool in ranges, several at a time, and each range is proved at its own block height. If the pool grows between two of those answers, an earlier range can end short of where the next range starts, while the next range already holds notes. The positions in between were never read. The scan used the later range anyway. It now stops at that gap, keeps the tree progress it made, publishes nothing else, and reads the pool again in the next pass.
Value: before this, a wallet that hit the gap could permanently miss notes sent to it (a balance that is too low and never corrects), and its local commitment tree stopped matching Platform's, so later spends could fail with an anchor Platform never recorded. After it, the scan never claims to have read a position it did not read, and never shows a ledger it knows to be incomplete.
Risks: low. One early exit in the scan loop, which then takes the path a cancelled pass already takes, one branch in the coordinator and one condition in the sync manager. The cost is that a pass that meets a gap is read again. That needs the pool's end to cross a fetch range boundary between two answers, so it is rare. No consensus, SDK, FFI, JNI, Swift or Kotlin code changes.
Issue being fixed or feature implemented
Closes #6109.
No other open PR or issue covers it (searched open PRs and issues on 2026-11-24). Related, not changed here: #5565 (detect an inconsistent commitment tree and rebuild it), #4999 (the scan starts 16 range fetches, most past the end of the tree).
What was done?
packages/rs-platform-wallet/src/wallet/shielded/sync.rs, insync_notes_from_stream:scanned_to, the end of the run of positions read without a gap from the pass's start, but used it only for the height the pass covers. The loop now ends when a range starts pastscanned_toand holds notes.NoteScan::StoppedAtGap, instead of a result.scanned_toinstead of the start position plus the number of notes received. The two are equal whenever the ranges are contiguous, which a completed pass now guarantees.packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs, insync:packages/rs-platform-wallet/src/manager/shielded_sync.rs, insync_now:Where this departs from the issue, and why
The issue proposed publishing the contiguous prefix and moving the watermark to the gap. The first version of this PR did that. Review showed the prefix is not safe to publish, because the pass knows the pool holds more than it read:
The code already has a rule for a scan that did not read the whole pool (a cancelled one): keep the tree progress, publish nothing. A gap now follows the same rule.
I did not make the pass fill the gap itself by fetching again from the gap. That restarts the range stream in the middle of a pass with the append gate and the progress counters carried across, for a rare event.
Token pool scan (
token_pool.rs): checked, no change needed.scan_poolreads one chunk at a time, applies it, and ends the pass at the first short chunk, so it cannot use a chunk past a gap.token_pool_tests::should_not_scan_past_a_short_chunk_and_recover_its_notes_next_passalready covers exactly this case.How Has This Been Tested?
New tests, no network.
wallet::shielded::sync::range_gap_testsfeedssync_notes_from_streamsynthetic ranges with real encrypted notes for the wallet's key:should_publish_nothing_at_a_gap_between_ranges_and_find_every_note_next_pass: the case in the example above, in both orders the two answers can arrive in (the short range carrying a pool count of 2, or of 6). After the first pass: 2 leaves, watermark unmoved, no note in the ledger, and the scan reports that it stopped at a gap. After the second pass: both notes found, the spend applied, the note at position 2 has a witness, and the tree root equals the root of a second store that scanned the same pool without a gap.should_show_a_late_bound_account_nothing_from_a_pass_that_stops_at_a_gap: one account has scanned the whole pool, a second is bound and scanned from position 0. The gap pass reads the second account's receipt before the gap and its spend after. The account is shown nothing; after the next pass the receipt reads spent.should_use_nothing_past_an_empty_range_a_later_range_follows: the first range comes back empty and a later one does not.wallet::shielded::coordinator::tests::should_report_no_completion_and_clear_the_cooldown_when_the_scan_stops_at_a_gap: a whole coordinator pass against a mock pool whose first range is short and whose second holds a note. The pass returns the empty summary and clears a caught-up stamp left by an earlier pass. With the coordinator handling removed, this test fails (the pass reports a completed sync for the wallet).manager::shielded_sync::tests::should_report_no_completion_for_a_pass_whose_scan_stops_at_a_gap:sync_nowover the same kind of mock pool. The pass sets no last-sync time and dispatches no completion callback, andsync_walletreports nothing; the same manager over a pool without the gap sets and dispatches both. It fails with the manager's new check removed.The first version's tests failed on
v5.1-devbefore the fix (4 positions scanned instead of 2, and 2 leaves appended past an empty range).Run locally:
Not yet verified
Not covered
sync_shielded_notes(rs-sdk) assembles the same ranges into one result and has the same hole in itsall_notesandnext_start_index. Nothing in this repository calls it (the wallet uses the stream). Filed as rs-sdk: sync_shielded_notes returns notes past a gap between fetched ranges #6181.Public interface changes
No public type or signature changes in Rust, FFI, JNI, Swift or Kotlin.
MultiSyncNotesResultkeeps its shape: the gap is carried byNoteScan, an enum private to the shielded module.Behaviour hosts can observe, in the rare pass that meets a gap:
ShieldedSyncManager::sync_nowreturns an empty summary withsync_unix_seconds0, sets no last-sync time, and dispatches noon_shielded_sync_completed.sync_walletreturnsOk(None). This is what a pass cut short by a stop already does.Breaking Changes
None.
Checklist:
structure.rs, regeneratedgrovedb-structure.json, and checked the structure viewer link posted on this pull requestFor repository code-owners and collaborators only
🤖 Generated with Claude Code
PR Hygiene ·
4b444f5/skip-botsproceeds without the ones not yet reported/self-reviewedrs-platform-wallet(packages/rs-platform-wallet/src/manager/shielded_sync.rs,packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs,packages/rs-platform-wallet/src/wallet/shielded/sync.rsand 3 more) — HashEngineering or ZocoLini or llbartekll or romchornyiWhen every merge requirement is met, the
PR Hygienecheck passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.