Foreign key constraint violation when deleting projects with AI catalog item consumers
Problem
When deleting a project that has AI catalog item consumers configured, a foreign key constraint violation occurs:
ERROR: update or delete on table "ai_catalog_items" violates foreign key constraint "fk_bba1649fa5" on table "ai_catalog_item_consumers" (PG::ForeignKeyViolation)
DETAIL: Key (id)=(78) is still referenced from table "ai_catalog_item_consumers".
Root Cause
The issue occurs during project deletion when:
- Project deletion cascades to delete
ai_catalog_item_consumersrecords via theproject_idforeign key (which hasON DELETE CASCADE) - The
ai_catalog_item_consumerstable has a foreign key constraint onai_catalog_item_idwithON DELETE RESTRICT - This constraint prevents deletion of the
ai_catalog_itemif any consumers still reference it - The deletion order causes a conflict where the constraint is violated before the cascade completes
Related Issues
- MR !196764 (merged): Added
ai_catalog_item_consumerstable withON DELETE RESTRICTconstraint - Issue #554105 (closed): Soft-deletion of catalog items if a project/group is using it
Solution
Add dependent: :delete_all to the Project model's relationship with ai_catalog_item_consumers to ensure consumers are explicitly deleted before any cascade operations:
# In ee/app/models/ee/project.rb
has_many :configured_ai_catalog_items,
class_name: '::Ai::Catalog::ItemConsumer',
inverse_of: :project,
dependent: :delete_all
This approach:
- Ensures explicit deletion of consumers before project deletion completes
- Maintains the application-level soft-delete logic for catalog items
- Prevents the foreign key constraint violation
- Aligns with the existing soft-delete strategy implemented in issue #554105 (closed)
Alternative Approach
Change the foreign key constraint from ON DELETE RESTRICT to ON DELETE CASCADE in the migration. However, this is less preferred as it bypasses the application-level deletion logic that handles soft-deletion of catalog items.
Edited by 🤖 GitLab Bot 🤖