Fix concurrent role creation race condition #325
Draft
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix concurrent role creation race condition with advisory locks
Summary
Fixes the intermittent CI error:
ERROR: duplicate key value violates unique constraint "pg_authid_rolname_index"that occurs when multiple processes try to create the same PostgreSQL role concurrently.Root Cause: Under concurrent execution,
CREATE ROLEcan hit thepg_authid_rolname_indexunique constraint before PostgreSQL's duplicate object detection runs, resulting inunique_violation(error code 23505) instead ofduplicate_object(error code 42710).Solution:
pg_advisory_xact_lock(42, hashtext(rolname))to serialize role creation per role nameduplicate_objectORunique_violationbootstrap-roles.sql(anonymous, authenticated, administrator)bootstrap-test-roles.sql(app_user, app_admin)LaunchQLInit.bootstrapDbRoles()(custom users)DbAdmin.createUserRole()(pgsql-test users)The advisory lock prevents the race entirely, while catching both exceptions provides defense in depth.
Review & Testing Checklist for Human
CREATE ROLEstatements that might need the same fix42doesn't collide with other advisory locks used elsewhere in the systemRecommended Test Plan
lql admin-users add --test --yesin multiple parallel shellsNotes
pg_advisory_xact_lock) and will be automatically released at transaction endhashtext()function provides good distribution of lock keys based on role namesLink to Devin run: https://app.devin.ai/sessions/2c33cab4511f4a7897e29001895487df
Requested by: Dan Lynch (@pyramation)