Skip to content

fix: prevent OrgFeatureFlag IntegrityError on creation#1407

Open
sentry[bot] wants to merge 1 commit into
mainfrom
seer/fix/orgfeatureflag-pk-integrity
Open

fix: prevent OrgFeatureFlag IntegrityError on creation#1407
sentry[bot] wants to merge 1 commit into
mainfrom
seer/fix/orgfeatureflag-pk-integrity

Conversation

@sentry

@sentry sentry Bot commented Jun 10, 2026

Copy link
Copy Markdown

This PR addresses an IntegrityError: duplicate key value violates unique constraint "ddpui_orgfeatureflag_pkey" that occurred when creating OrgFeatureFlag entries. The root cause was identified as the PostgreSQL primary key sequence (ddpui_orgfeatureflag_id_seq) being out of sync with the actual MAX(id) in the ddpui_orgfeatureflag table, leading to get_or_create attempting to insert records with already existing primary keys.

Changes Implemented:

  1. Data Migration (ddpui/migrations/0164_reset_orgfeatureflag_pk_sequence.py):

    • A new data migration has been added to reset the ddpui_orgfeatureflag_id_seq sequence. This migration executes SELECT setval('ddpui_orgfeatureflag_id_seq', COALESCE((SELECT MAX(id) FROM ddpui_orgfeatureflag), 1)) to synchronize the sequence with the highest existing id in the table. This resolves the immediate data inconsistency.
  2. Code Refactoring (ddpui/utils/feature_flags.py):

    • The enable_feature_flag and disable_feature_flag functions have been refactored to use a new internal helper function, _safe_update_or_create.
    • _safe_update_or_create utilizes OrgFeatureFlag.objects.update_or_create for cleaner and more robust handling of existing or new feature flags.
    • Crucially, the first attempt within _safe_update_or_create is wrapped in with transaction.atomic(). This creates a savepoint, allowing the code to catch IntegrityError (specifically for primary key collisions) without aborting the entire transaction. If an IntegrityError occurs, the operation is retried. This retry mechanism is effective because the database sequence advances past the conflicting ID on the first failed attempt, allowing the second attempt to succeed.

This solution addresses both the existing data problem (via migration) and provides a resilient, self-healing mechanism for future primary key collisions, improving the robustness of feature flag management.

Fixes DALGO-BACKEND-2AK

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.

0 participants