Add NOT NULL constraint on label_links.label_id

Everyone can contribute. Help move this issue forward while earning points, leveling up and collecting rewards.

We found that in https://gitlab.com/gitlab-org/gitlab/issues/197300, project imports can produce label_links with NULL label_id values. We have about 65,000 entries (out of 28+ million) in this state:

gitlabhq_production=# select count(*) from label_links where label_id IS NULL;
-[ RECORD 1 ]
count | 64845

Current situation, origin of invalid records

We seem to have disabled the Rails validation https://gitlab.com/gitlab-org/gitlab/blob/096ab61dd6b6dcb2304f0ba9cd92fa63906be434/app/models/label_link.rb#L10 during import, so it's possible this happens because we didn't properly export/map labels. This has been addressesd and we no longer skip validations during imports, but we still produce new records with a NULL label_id at the time of writing (2025-10-06). So we need to find where this is happening before destroying invalid records and adding the constraint. I suspect we delete_all somewhere in a way that sets null to label_id instead of actually deleting the records

In some migration, we should:

  1. Stop producing new offending records
  2. Add a NOT VALID NOT NULL constraint
  3. Drop these entries in a BBM
  4. VALIDATE the NOT NULL constraint
Edited by Mario Celi