Skip to content

fix: serialize order release under per-order mutex with state recheck - #836

Merged
grunch merged 3 commits into
mainfrom
fix/release-mutex-state-check
Jun 14, 2026
Merged

fix: serialize order release under per-order mutex with state recheck#836
grunch merged 3 commits into
mainfrom
fix/release-mutex-state-check

Conversation

@grunch

@grunch grunch commented Jun 13, 2026

Copy link
Copy Markdown
Member

Summary

Hardens the order release flow against a race condition that could allow a hold invoice to be settled after the order had already moved on (e.g. been canceled), by serializing the settle under the per-order mutex and re-checking the order state under the lock.

Previously, validateReleaseOrder ran without holding any lock, and the settle proceeded based on that earlier read. Between validation and the actual settle, the order could be canceled, settled or otherwise advanced by a concurrent action or background job, leaving room for a release-vs-cancel race over the same hold invoice.

Changes

  • bot/commands.ts — Wrap the settle in PerOrderIdMutex.instance.runExclusive(orderId, ...), the same per-order lock used by payHoldInvoice and the cancel/expiry jobs. Inside the lock, re-read the order and only settle when it is still in a releasable state (ACTIVE, FIAT_SENT, DISPUTE); otherwise log and skip. The dispute status update and the settleHoldInvoice call now happen against the order re-read under the lock.

Testing

  • npx tsc --noEmit passes.

Summary by CodeRabbit

  • Bug Fixes
    • Improved order settlement reliability with enhanced concurrency safety measures. Order state is now consistently validated during settlement operations, ensuring reliable handling of concurrent requests and preventing potential consistency issues.

Run the hold-invoice settle in the release flow under the same
per-order mutex used by payHoldInvoice and the cancel/expiry jobs, and
re-read the order under the lock before settling. The order is only
settled when it is still in a releasable state (ACTIVE, FIAT_SENT or
DISPUTE).

Order validation runs before the lock is acquired, so the order could
be canceled, settled or otherwise advanced in between. Rechecking the
state under the lock closes the release-vs-cancel race over the same
hold invoice.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@grunch, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 10 minutes. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: abce0254-fa11-4bc9-997e-094939d51109

📥 Commits

Reviewing files that changed from the base of the PR and between 43dffe5 and ab3f3aa.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • bot/commands.ts

Walkthrough

The release command's settlement flow is refactored to serialize execution under a per-order mutex. The command now re-fetches and validates the current order state inside the lock before settling the hold invoice, ensuring atomic verification that the order remains releasable and that dispute updates occur safely under concurrency control.

Changes

Release Settlement Concurrency Control

Layer / File(s) Summary
Per-order mutex settlement in release command
bot/commands.ts
PerOrderIdMutex is imported and used to wrap the release settlement flow. Inside the lock, the current order is re-fetched and validated to be in a releasable status (ACTIVE, FIAT_SENT, or DISPUTE), secret is verified non-null, any related Dispute is marked RELEASED, and then settleHoldInvoice is called using the current order's secret.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • lnp2pBot/bot#823: Refactors PerOrderIdMutex implementation and moves it to util/index.ts, directly supporting the mutex import and usage in this PR's release settlement flow.
  • lnp2pBot/bot#705: Uses PerOrderIdMutex to serialize order state–dependent logic by re-fetching and verifying order status inside the lock, following the same pattern as this PR's release settlement.
  • lnp2pBot/bot#765: Modifies the same /release settlement path in bot/commands.ts around settleHoldInvoice, potentially conflicting with or building upon this PR's concurrency control changes.

Suggested reviewers

  • Luquitasjeffrey
  • mostronatorcoder

Poem

🐰 A mutex guards each order's fate,
Re-fetching state before too late.
Disputes dissolve to RELEASED bliss,
While invoices settle—nothing miss! ✨

🚥 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 specifically describes the main change: serializing order release under a per-order mutex with state recheck, which directly matches the PR's objective of fixing a race condition in the order release flow.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/release-mutex-state-check

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 and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@bot/commands.ts`:
- Around line 917-924: The code updates and saves dispute.status = 'RELEASED'
(Dispute.findOne result) before calling settleHoldInvoice, risking a stale
released state if settle fails; move the mutation and await dispute.save() to
after the successful await settleHoldInvoice({ secret: currentOrder.secret }) so
the database is only updated once the Lightning settle completes, or
alternatively add a compensating retry/write on settle failure to revert/repair
the dispute state; locate the dispute handling in this function (the dispute
variable from Dispute.findOne) and ensure bot/modules/dispute/actions.ts logic
(lines cited) will only observe the released state after a confirmed settle.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: d5d95917-ec22-47dc-bbf2-64671ac5ca5e

📥 Commits

Reviewing files that changed from the base of the PR and between 056284a and 43dffe5.

📒 Files selected for processing (1)
  • bot/commands.ts

Comment thread bot/commands.ts Outdated
grunch and others added 2 commits June 13, 2026 08:42
Move the dispute RELEASED status update to after settleHoldInvoice
succeeds. Previously the dispute was saved as RELEASED before the
Lightning settle, so a failed settle left a stale RELEASED dispute that
makes solvers believe the seller already released
(bot/modules/dispute/actions.ts short-circuits on that status).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
package.json was bumped to 0.15.2 (commit 056284a) but package-lock.json
still declared 0.15.1. The CI 'Run prettier' step runs 'npm install'
followed by 'git diff --exit-code', and npm rewrites the lockfile
version to match package.json, producing an uncommitted diff that fails
the check. Sync the lockfile version so the working tree stays clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@grunch
grunch requested a review from Luquitasjeffrey June 13, 2026 11:51
@grunch

grunch commented Jun 13, 2026

Copy link
Copy Markdown
Member Author

@codex review

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

tACK

@grunch
grunch merged commit a1045a2 into main Jun 14, 2026
7 checks passed
@grunch
grunch deleted the fix/release-mutex-state-check branch June 14, 2026 01:22
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