Skip to content

Conversation

@ArnavBallinCode
Copy link
Member

@ArnavBallinCode ArnavBallinCode commented Dec 1, 2025

Fix: Voucher Redemption Race Condition

Fix voucher redemption race condition using pessimistic locking

Problem:

  • Voucher validation occurred before acquiring database lock
  • Multiple concurrent requests could all see voucher as 'available'
  • Led to over-redemption beyond max_usages limit

Solution:

  • Added select_for_update() to acquire row-level lock before validation
  • Added explicit availability check after lock acquisition
  • Ensures only one thread can validate voucher state at a time

Fixes #1398

  • Tested: 5 concurrent threads redeemed voucher with max_usages=3

Summary by Sourcery

Prevent race conditions during voucher redemption by validating availability under a database row lock.

Bug Fixes:

  • Ensure voucher availability is checked under a row-level lock to prevent over-redemption under concurrent requests.

Enhancements:

  • Use pessimistic locking on voucher rows when computing availability in the cart service.

marvel at flowers and others added 30 commits October 10, 2025 07:32
Currently translated at 0.1% (3 of 4121 strings)

Translation: eventyay/Eventyay Tickets
Translate-URL: https://hosted.weblate.org/projects/open-event/eventyay-tickets/zh_Hant/
Currently translated at 0.2% (9 of 4121 strings)

Translation: eventyay/Eventyay Tickets
Translate-URL: https://hosted.weblate.org/projects/open-event/eventyay-tickets/zh_Hant/
Currently translated at 0.4% (18 of 4121 strings)

Translation: eventyay/Eventyay Tickets
Translate-URL: https://hosted.weblate.org/projects/open-event/eventyay-tickets/pl_INFORMAL/
Currently translated at 2.9% (123 of 4121 strings)

Translation: eventyay/eventyay
Translate-URL: https://hosted.weblate.org/projects/eventyay/eventyay/zh_Hant/
Currently translated at 2.9% (123 of 4121 strings)

Translation: eventyay/eventyay
Translate-URL: https://hosted.weblate.org/projects/eventyay/eventyay/zh_Hant/
The issue was caused by unconditional access to test_form.cleaned_data
without checking if the form validation succeeded. When test_form.is_valid()
returned False, accessing cleaned_data could raise AttributeError or return
incomplete data, causing a 500 error.

Solution: Added conditional check to only access cleaned_data when form is
valid, otherwise use empty dict for initial values. This ensures the export
page loads properly even when no valid GET parameters are provided.

Changes:
- Modified ExportMixin.exporters property in control/views/orders.py
- Added validation check before accessing test_form.cleaned_data
- Fallback to empty dict when form is invalid
Applied the same fix from issueto the organizer-level export
functionality. The ExportMixin in organizer.py had the identical issue
where test_form.cleaned_data was accessed without checking if the form
validation succeeded first.

This prevents potential HTTP 500 errors when accessing:
- /control/organizer/{organizer}/export/

Changes:
- Modified ExportMixin.exporters in control/views/organizer.py
- Added validation check before accessing test_form.cleaned_data
- Fallback to empty dict when form is invalid
- Use f-strings instead of string concatenation for better readability
- Rename 'id' variable to 'identifier' to avoid shadowing builtin
- Apply improvements to both orders.py and organizer.py

Addresses Sourcery suggestions...
- Add JSON_FIELD_AVAILABLE setting based on database backend (postgresql = True)
- Fix checkinlists exporter using old Event.items instead of Event.products
- Resolves AttributeError when accessing export functionality
- Changed from if/else validation check to getattr() to preserve partial cleaned_data
- This allows useful defaults even when form is partially invalid
- Reverted unnecessary 'id' to 'identifier' rename in organizer.py
- Renamed 'items' field to 'products' in checkinlists exporter for consistency
- Updated form_data['items'] to form_data['products'] reference
…fossasia#1157)

* Fix navigation button border radius inconsistency

- Added border-radius: 0 to .header-nav class in orga/_layout.css
- Makes Talk component navigation buttons match Tickets component style
- Ensures consistent sharp corners across all navigation buttons
- Maintains visual consistency throughout the platform

Fixes fossasia#1156

* Add inset shadow on hover to match Tickets component

- Added hover and active states with inset box-shadow
- Matches the hover effect from btn-success in Tickets component
- Uses rgba(0, 128, 0, 0.25) for green inset shadow

* Fix navigation button active state to match Tickets component

- Added .header-nav.active state with proper inset shadow
- Fixed depth and consistency of hover, active, and current page states
- Current page button now has same darker border effect as Tickets
- All navigation buttons now have identical visual feedback

* Improve CSS: use variables and remove important declarations

* Fix CSS indentation formatting

* Update app/eventyay/static/orga/css/_layout.css

* Update app/eventyay/static/orga/css/_layout.css

* Fix navigation buttons: sharp corners and inset shadow to match Tickets component

---------

Co-authored-by: Mario Behling <[email protected]>
weblate and others added 8 commits November 30, 2025 18:50
Currently translated at 100.0% (1568 of 1568 strings)

Translation: eventyay/eventyay
Translate-URL: https://hosted.weblate.org/projects/eventyay/eventyay/de_FORMAL/
i18n(translations): update localized strings from Weblate
…speaker-acceptance-link-oof

Fix Speaker Acceptance Confirmation Link Returning 500 Error
* fix(translations): Add missing languages

* add(translation): Change language selection to drop down from check-box

* fix(translation): Add changes suggested by ai comments

* fix(translation): Updated Ukrainian to use the standard Django code `uk`

---------

Co-authored-by: Mario Behling <[email protected]>
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Dec 1, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Implements pessimistic row-level locking and post-lock availability validation for voucher redemption to prevent race-condition-based over-redemption in the cart service.

Sequence diagram for concurrent voucher redemption with pessimistic locking

sequenceDiagram
    actor User1
    actor User2
    participant CartService1
    participant CartService2
    participant DB

    User1->>CartService1: redeem_voucher(voucher_code)
    User2->>CartService2: redeem_voucher(voucher_code)

    CartService1->>DB: SELECT voucher FOR UPDATE
    activate DB
    DB-->>CartService1: locked Voucher row
    deactivate DB

    CartService2->>DB: SELECT voucher FOR UPDATE
    activate DB
    DB-->>CartService2: waits (row lock held)

    CartService1->>CartService1: compute cart_count, v_avail
    CartService1->>CartService1: if v_avail < requested_count: raise CartError
    CartService1->>DB: update voucher.redeemed
    DB-->>CartService1: commit transaction, release lock

    deactivate DB

    DB-->>CartService2: locked Voucher row (after lock released)
    CartService2->>CartService2: refresh redeemed, compute cart_count, v_avail
    CartService2->>CartService2: if v_avail < requested_count: raise CartError
    CartService2->>DB: update voucher.redeemed or abort
    DB-->>CartService2: commit/rollback

    CartService1-->>User1: success or CartError
    CartService2-->>User2: success or CartError
Loading

Flow diagram for updated _get_voucher_availability voucher locking and validation

flowchart TD
    A["Start _get_voucher_availability"] --> B["Iterate over voucher_use_diff (voucher, count)"]
    B --> C["Lock voucher row: select_for_update by pk"]
    C --> D{"voucher.valid_until is not None and voucher.valid_until < now_dt?"}
    D -- Yes --> E["Raise CartError voucher_expired"]
    D -- No --> F{"voucher.reusable or not voucher.is_valid_for_event(event)?"}
    F -- Yes --> G["Raise CartError voucher_invalid_for_event"]
    F -- No --> H["Compute redeemed_in_carts excluding ExtendOperation positions"]
    H --> I["cart_count = redeemed_in_carts.count"]
    I --> J["v_avail = voucher.max_usages - voucher.redeemed - cart_count"]
    J --> K{"v_avail < count?"}
    K -- Yes --> L["Raise CartError voucher_redeemed (over-redemption prevented)"]
    K -- No --> M{"cart_count > 0?"}
    M -- Yes --> N["Add voucher to _voucher_depend_on_cart"]
    M -- No --> O["Skip dependency tracking for this voucher"]
    N --> P["vouchers_ok[voucher] = v_avail"]
    O --> P
    P --> Q{"More vouchers to process?"}
    Q -- Yes --> B
    Q -- No --> R["Return vouchers_ok and finish"]
Loading

File-Level Changes

Change Details Files
Ensure voucher availability is validated under a database row-level lock to prevent race conditions in concurrent redemptions.
  • Replace non-locking voucher.refresh_from_db() call with a select_for_update() query to lock the voucher row before further checks.
  • Compute remaining voucher availability (max_usages - redeemed - in-cart count) under the acquired lock.
  • Add an explicit availability check comparing requested usage count against remaining availability and raise a voucher_redeemed error when insufficient.
app/eventyay/base/services/cart.py

Assessment against linked issues

Issue Objective Addressed Explanation
#1398 Move voucher availability validation so it is performed under a proper database lock to remove the race condition in concurrent voucher redemptions.
#1398 Ensure that the voucher max_usages limit is strictly enforced under concurrent usage (e.g., a voucher with max_usages=3 cannot be successfully redeemed more than 3 times).

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Sak1012 and others added 4 commits December 1, 2025 14:42
…4.* (fossasia#1401)

Updates the requirements on [beautifulsoup4](https://www.crummy.com/software/BeautifulSoup/bs4/) to permit the latest version.

---
updated-dependencies:
- dependency-name: beautifulsoup4
  dependency-version: 4.14.3
  dependency-type: direct:production
...

Signed-off-by: Mario Behling <[email protected]>
…sia#1400)

Updates the requirements on [celery](https://github.com/celery/celery) to permit the latest version.
- [Release notes](https://github.com/celery/celery/releases)
- [Changelog](https://github.com/celery/celery/blob/main/Changelog.rst)
- [Commits](celery/celery@v5.4.0rc1...v5.6.0)

---
updated-dependencies:
- dependency-name: celery
  dependency-version: 5.6.0
  dependency-type: direct:production
...

Signed-off-by: Mario Behling <[email protected]>
Copy link
Member

@mariobehling mariobehling left a comment

Choose a reason for hiding this comment

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

The docker build is failing. Please check.

Copilot finished reviewing on behalf of mariobehling December 1, 2025 13:54
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes a race condition in voucher redemption that allowed multiple concurrent requests to over-redeem vouchers beyond their max_usages limit. The fix implements pessimistic locking using Django's select_for_update() to ensure atomic validation and redemption of vouchers.

Key Changes:

  • Replaced refresh_from_db() with select_for_update().get() to acquire row-level locks before validation
  • Added explicit availability check after lock acquisition to prevent over-redemption
  • Ensures thread-safe voucher validation within database transactions

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@ArnavBallinCode
Copy link
Member Author

The docker build is failing. Please check.

It was due to some network issue...
working now...

@mariobehling mariobehling requested a review from norbusan December 1, 2025 14:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Backlog

Development

Successfully merging this pull request may close these issues.

Bug: Voucher Redemption Race Condition