Skip to content

Importing projects triggers a duplicate key error in AuthorizedProjectsWorker

When importing a project the following error is triggered:

ERROR:  duplicate key value violates unique constraint \"index_project_authorizations_on_user_id_project_id_access_level\"\nDETAIL:  Key (user_id, project_id, access_level)=(209240, 500330, 40) already exists.\n: INSERT INTO project_authorizations (user_id, project_id, access_level)\nVALUES (209240, 500330, 40)\n","
error_class":"ActiveRecord::RecordNotUnique","failed_at":1482419898.7464676,"retry_count":0},"jobstr":"{\"class\":\"AuthorizedProjectsWorker\",\"args\":[209240],\"retry\":3,\"queue\":\"authorized_projects\",\"jid\":\"b64e10b3a8b652074bf5ebaa\",\"created_at\":1482419898.260817,\"enqueued_at\":1482419898.2610607}"}
2016-12-22T15:18:18.747Z 2958 TID-gqmnbsnds WARN: ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "index_project_authorizations_on_user_id_project_id_access_level"
DETAIL:  Key (user_id, project_id, access_level)=(209240, 500330, 40) already exists.
: INSERT INTO project_authorizations (user_id, project_id, access_level)
VALUES (209240, 500330, 40)

2016-12-22T15:18:18.747Z 2958 TID-gqmnbsnds WARN: /home/yorickpeterse/.gem/ruby/2.3.3/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `async_exec'

This is probably the result of the lease only being acquired during the update process, and not before we start diffing rows. We can solve this by acquiring the lease the moment you call Users::RefreshAuthorizedProjectsService#execute instead of when calling Users::RefreshAuthorizedProjectsService#update_with_lease