Migration to fix drifted project namespace parent_id and traversal_ids

Summary

After investigating #614002 (closed), we found that the parent_id drift on project namespaces is not isolated to a single project. A scan of the production database revealed multiple projects where namespaces.parent_id on the project namespace does not match projects.namespace_id.

These project namespaces have stale parent_id values (pointing at a previous parent), and their traversal_ids are internally consistent with the wrong parent_id. This means:

  • Work item list views are broken for affected projects (the NamespaceResolver full path lookup fails silently)
  • The WorkItems::TraversalIdsHealingCronWorker cannot fix this because it trusts namespaces.traversal_ids as the source of truth

Detection query

The affected rows can be identified with:

SELECT p.id AS project_id,
       p.namespace_id AS expected_parent,
       n.id AS project_namespace_id,
       n.parent_id AS actual_parent
FROM projects p
JOIN namespaces n ON n.id = p.project_namespace_id
WHERE n.parent_id IS DISTINCT FROM p.namespace_id;

Proposed fix

Create a batched background migration that:

  1. Finds all project namespaces where parent_id != projects.namespace_id
  2. Updates namespaces.parent_id to match projects.namespace_id
  3. Recomputes traversal_ids for the affected namespaces (this should happen automatically via the after_update :sync_traversal_ids callback when parent_id changes, but the migration should verify)

Considerations

  • The Namespace::TraversalHierarchy.sync_traversal_ids! method acquires locks on the root of the hierarchy. The migration should handle lock timeouts gracefully.
  • Project namespaces have no children, so traversal_ids recomputation is scoped to the single row.
  • The migration should be idempotent and safe to re-run.

References

Edited by 🤖 GitLab Bot 🤖