Skip to content

Fix: Prevent duplicate active alerts with unique index - #2144

Closed
sentry[bot] wants to merge 1 commit into
mainfrom
seer/fix/duplicate-alerts-unique-index
Closed

Fix: Prevent duplicate active alerts with unique index#2144
sentry[bot] wants to merge 1 commit into
mainfrom
seer/fix/duplicate-alerts-unique-index

Conversation

@sentry

@sentry sentry Bot commented Aug 13, 2026

Copy link
Copy Markdown

This PR addresses the ActiveRecord::RecordInvalid: Validation failed: Address You already have an alert for that address error occurring in CuttlefishController#event.

Root Cause:
The issue stemmed from a race condition during alert creation, which allowed multiple active alerts for the same user and address to be saved. The Rails-level uniqueness validation (validates :address, uniqueness: { scope: %i[user_id unsubscribed] }) was insufficient to prevent this under concurrent requests, as there was no corresponding database-level unique index.

When Cuttlefish attempted to update an alert (e.g., last_delivered_at), the alert.update! call would trigger the Rails validation, find the other duplicate active alert, and raise ActiveRecord::RecordInvalid.

Solution:

  1. Add Partial Unique Database Index: A new migration (20260813000000_add_unique_index_to_alerts.rb) has been added to create a partial unique index on alerts(address, user_id) where unsubscribed = false. This enforces uniqueness at the database level, preventing new duplicate active alerts from being created.
  2. Clean Up Existing Duplicates: The migration includes a step to delete any existing duplicate active alerts, ensuring that only the oldest alert for a given (address, user_id) pair (where unsubscribed = false) remains before the index is added.
  3. Update Rails Uniqueness Validation: The Alert model's validates :address, uniqueness: scope has been adjusted to { scope: :user_id } to align with the new partial database index. The unless: :unsubscribed? condition already handles the partial nature of the validation.
  4. Graceful Error Handling in CuttlefishController: A rescue block has been added around alert.update! in CuttlefishController#event to catch ActiveRecord::RecordNotUnique and ActiveRecord::RecordInvalid exceptions. This ensures that if any residual duplicate active alerts cause a validation error during an update, the webhook call will still return a 200 OK, preventing Cuttlefish from retrying and potentially exacerbating the issue.

Fixes PLANNING-ALERTS-2

@sentry
sentry Bot requested a review from a team as a code owner August 13, 2026 06:33
@sonarqubecloud

Copy link
Copy Markdown

@benrfairless
benrfairless deleted the seer/fix/duplicate-alerts-unique-index branch August 13, 2026 06:38
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.

1 participant