Skip to content

fix(platform-wallet): close the asset-lock resume broadcast race - #4636

Open
shumkov wants to merge 4 commits into
v4.2-devfrom
fix/asset-lock-resume-broadcast-race
Open

fix(platform-wallet): close the asset-lock resume broadcast race#4636
shumkov wants to merge 4 commits into
v4.2-devfrom
fix/asset-lock-resume-broadcast-race

Conversation

@shumkov

@shumkov shumkov commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator

Issue being fixed or feature implemented

The asset-lock resume path broadcasts a Built row before advancing it to
Broadcast. For the whole in-flight broadcast the row still reads Built, so a
concurrent create-path definite Rejected untracks it — the untrack guard spares only
rows already past Built — and releases its funding reservation, while the resume's
broadcast of the same transaction may still deliver. A later build can then reselect
those inputs and produce a self-conflicting transaction.

This re-derives the fix from #4016 on the current module layout, per the rework
directive on that PR. #4016 has been dormant since 2026-08-07; its branch predates the
asset_lock/sync/ split and conflicts throughout, so this is a fresh implementation
rather than a rebase. Supersedes #4016.

What was done?

  • promote_built_to_broadcast CAS in the tracking module: promotes only while the
    row still reads Built, under the write lock, otherwise returns
    AlreadyAdvanced { status, proof }. The changeset is enqueued following the existing
    consume_asset_lock pattern.
  • The resume Built arm CAS-promotes before broadcasting and re-dispatches from
    the returned status/proof on AlreadyAdvanced. The MaybeSent bounded-wait mapping
    is unchanged. On a definite Rejected the row is left at Broadcast; the Broadcast
    arm's defensive re-broadcast preserves resumability. No rollback to Built — an
    earlier incarnation of this fix used one, and an unowned rollback can clobber a
    concurrent successful resume.
  • The create path routes its post-broadcast advance through the same CAS, so a
    concurrently finalized row cannot be downgraded.
  • The contested verdict is no longer one-shot. Promoting on the first resume used
    to route later resumes down the Broadcast arm, which returned
    TransactionBroadcastUnconfirmed and never consulted input_conflict. That arm now
    preserves a sighted conflict through the bounded proof wait, so an offline relaunch
    reproduces AssetLockInputContested on every pass rather than only the first.
  • Doc pass. Promoting before the send weakens Broadcast from "was broadcast once"
    to "a broadcast was attempted"; every comment that leaned on the old meaning is
    reworded, including the contested-verdict docs in the Rust error type and both mobile
    SDKs.

Tests

Test would have caught this in CI: ✖ before the fix, ✔ after.

  • rejected_create_while_resume_broadcasts_keeps_row_and_reservation — the forward
    interleaving, which had no coverage. Verified RED on the parent by applying only the
    test hunks: it fails at the ordering assertion, and with those assertions stripped it
    still fails on the symptom (TransactionBroadcast — row untracked, reservation
    released mid-flight).
  • create_broadcast_does_not_downgrade_a_concurrently_finalized_row — RED on the
    parent.
  • The pre-existing definite-rejection test asserting a Built resume "stays resumable at
    Built" is updated: that assertion is invalidated by design, and it now asserts
    the row stays tracked at Broadcast and resumable via the Broadcast arm.
  • The contested-verdict test now exercises a second resume with the row already at
    Broadcast.

cargo test -p platform-wallet and -p platform-wallet-ffi pass; clippy
-D warnings and fmt --check clean.

Explicitly out of scope, and deliberately not ported from #4016:
status_persist_serial, manager retirement, generation gates. That PR grew from a
two-commit fix into a wallet-lifecycle project whose own machinery kept generating
blockers; this keeps to the race.

Summary by CodeRabbit

  • Bug Fixes

    • Improved asset-lock recovery when broadcasts are retried, rejected, canceled, or processed concurrently.
    • Preserved asset-lock status and proof information during overlapping operations.
    • Improved handling of contested outcomes so conflicts can be reported accurately after retries.
    • Prevented premature cleanup while an asset-lock operation may still be active.
  • Documentation

    • Clarified asset-lock status descriptions and error messages across Kotlin, Rust, and Swift SDKs.

Promote Built rows before resume broadcasts through a shared compare-and-set.
Preserve concurrently advanced status and proof in both resume and create paths,
and keep rejected attempts tracked at Broadcast without releasing their inputs.

Test would have caught this in CI:
- rejected_create_while_resume_broadcasts_keeps_row_and_reservation: ✖ before
  the fix the rejected create removed the row and released its reservation;
  ✔ after the fix the row remains Broadcast and a rebuild cannot select its inputs.
- stale_built_resume_does_not_downgrade_a_concurrently_finalized_row: ✖ before
  the fix the stale resume timed out after replacing ChainLocked with Broadcast;
  ✔ after the fix it re-dispatches from the attached ChainLock proof.
- create_broadcast_does_not_downgrade_a_concurrently_finalized_row: ✖ before
  the fix the create completion replaced ChainLocked with Broadcast; ✔ after the
  fix it preserves the finalized status and proof.
- Built-resume rejection assertions: ✖ before the fix the row stayed Built;
  ✔ after the fix it stays tracked at Broadcast for defensive resume.
Keep definite rejections for Broadcast rows on the bounded proof-wait path when a standing input conflict exists, so later resumes reproduce AssetLockInputContested. Update status wording to reflect pre-send promotion.

Test would have caught this in CI:
- a_rejected_rebroadcast_of_a_conflicted_built_lock_reports_the_contested_verdict: ✖ before the fix the second resume returned TransactionBroadcastUnconfirmed; ✔ after the fix it returns AssetLockInputContested while the row remains Broadcast.
… send

A Broadcast row now means a broadcast was attempted, not that one reached the
network: two pre-dispatch rejections can leave a row at Broadcast having sent
nothing. The contested-verdict docs in the Rust error type and both mobile SDKs
still asserted an earlier call had sent the transaction.

Docs only; no behaviour change, so no test accompanies it.
@coderabbitai

coderabbitai Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: b743fe5a-3321-4add-bb1f-de271f44eb80

📥 Commits

Reviewing files that changed from the base of the PR and between e9ddb20 and 7907237.

📒 Files selected for processing (7)
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/deletion.rs
  • packages/rs-platform-wallet-ffi/src/error.rs
  • packages/rs-platform-wallet/src/wallet/asset_lock/build.rs
  • packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs
  • packages/rs-platform-wallet/src/wallet/asset_lock/sync/tracking.rs
  • packages/rs-platform-wallet/src/wallet/asset_lock/tracked.rs
  • packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift
💤 Files with no reviewable changes (1)
  • packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift
  • packages/rs-platform-wallet-ffi/src/error.rs
  • packages/rs-platform-wallet/src/wallet/asset_lock/tracked.rs

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

Asset-lock creation and recovery now use conditional status advancement and RAII dispatch claims. Concurrent finalization, rejection, cancellation, and contested-proof scenarios preserve tracked state and verdicts. Related SDK documentation and one test formatting change were updated.

Changes

Asset-lock race handling

Layer / File(s) Summary
Resume dispatch claim tracking
packages/rs-platform-wallet/src/wallet/asset_lock/sync/tracking.rs
Adds RAII dispatch claims. Cleanup keeps claimed Built rows tracked. Status transitions clear claims when rows leave Built.
Create broadcast state preservation
packages/rs-platform-wallet/src/wallet/asset_lock/build.rs
The create path advances only rows that remain Built. Tests verify that concurrent finalization does not lose status or proof.
Resume recovery state handling
packages/rs-platform-wallet/src/wallet/asset_lock/sync/recovery.rs
A conflicted rejected re-broadcast now enters bounded proof waiting. Repeated resumes can report the contested verdict again.
Status and error contract wording
packages/rs-platform-wallet/src/wallet/asset_lock/tracked.rs, packages/rs-platform-wallet/src/error.rs, packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt, packages/rs-platform-wallet-ffi/src/error.rs, packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift, packages/rs-drive-abci/execution/validation/state_transition/state_transitions/batch/tests/document/deletion.rs
Documentation now describes uncertain earlier attempts. The document deletion test was reformatted without behavior changes.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Merge Risk: ⚪ Minimal · up to 79072

Asset-lock create and resume flows now retain state during concurrent dispatch and finalization, preventing stale cleanup or status downgrades. The covered race and recovery behavior has no identified current-head merge-blocking risk.

Sequence Diagram(s)

sequenceDiagram
  participant CreateOrResume
  participant TransactionBroadcaster
  participant AssetLockManager
  participant ProofWait
  CreateOrResume->>TransactionBroadcaster: send or re-send asset-lock transaction
  TransactionBroadcaster-->>CreateOrResume: accepted or rejected
  CreateOrResume->>AssetLockManager: conditionally update tracked status
  AssetLockManager-->>CreateOrResume: preserve concurrent status and proof
  CreateOrResume->>ProofWait: wait when an input conflict is sighted
  ProofWait-->>CreateOrResume: contested or final proof verdict
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: fixing the asset-lock resume broadcast race.
Docstring Coverage ✅ Passed Docstring coverage is 93.75% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 11 files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/asset-lock-resume-broadcast-race

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

Comment @coderabbitai help to get the list of available commands.

@thepastaclaw

thepastaclaw commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator

✅ Final review complete — no blockers (commit 7907237) · triage: critical · Phase 2 only (queue backlog)

Keep #4355's resume dispatch-claim and transport-readiness flow, and conditionally advance the create path after broadcast.

Test would have caught this in CI: ✖ the unconditional merged-parent advance downgraded ChainLocked to Broadcast; ✔ the conditional advance preserves the finalized row and proof.
@codecov

codecov Bot commented Sep 9, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 84.51%. Comparing base (caf2b29) to head (7907237).
⚠️ Report is 1 commits behind head on v4.2-dev.

Additional details and impacted files
@@             Coverage Diff              @@
##           v4.2-dev    #4636      +/-   ##
============================================
- Coverage     85.34%   84.51%   -0.84%     
============================================
  Files          2795     2796       +1     
  Lines        373566   375112    +1546     
============================================
- Hits         318827   317025    -1802     
- Misses        54739    58087    +3348     
Components Coverage Δ
dpp 84.16% <ø> (-0.21%) ⬇️
drive 84.65% <ø> (-0.30%) ⬇️
drive-abci 86.39% <ø> (-2.56%) ⬇️
sdk ∅ <ø> (∅)
dapi-client ∅ <ø> (∅)
platform-version ∅ <ø> (∅)
platform-value 92.92% <ø> (ø)
platform-wallet ∅ <ø> (∅)
drive-proof-verifier 41.44% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@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 2 only (queue backlog)

Verified the changes at head 7907237; no actionable in-scope defects were found. The conditional create-path status update preserves concurrent finality, and rejected defensive re-broadcasts retain bounded conflict resolution without releasing reservations. Independent validation passed all 98 targeted asset-lock tests, the full platform-wallet and platform-wallet-ffi suites (1,361 passed, 5 ignored), and git diff --check; the worktree remains clean.

Source: reviewer 1: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 3: gpt-6-astra (agent: phase2-reviewer, role: rust-quality); reviewer 4: gpt-6-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6-astra (agent: astra-verifier, role: final-verifier)

Review provenance

  • Triage: critical by gpt-6-astra (effort low) — The change modifies concurrent asset-lock state transitions, broadcast recovery, and funding-reservation protection, where incorrect ordering or status handling could release committed inputs, create conflicting transactions, or compromise wallet fund recovery.
  • Phase 1 reviewers: not run (skipped for throughput: 21 PRs queued, above the 10 limit)
  • Fresh verifier: gpt-6-astra — final-verifier; agent astra-verifier
  • Phase 2 reviewers: gpt-6-astra — general (completed, effort xhigh); agent phase2-reviewer, gpt-6-astra — ffi-engineer (completed, effort xhigh); agent phase2-reviewer, gpt-6-astra — rust-quality (completed, effort xhigh); agent phase2-reviewer, gpt-6-astra — security-auditor (completed, effort xhigh); agent phase2-reviewer

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