WriteRef creates reference files even if the reference already exists with the correct value

Rails uses WriteRef to create keep-around references. Rails does not check the old value of the reference. This leads to WriteRef always writing reference files even if the reference already points to the correct value. This is wasteful, and leads to pile up of redundant loose reference files even though the reference already exists at the correct value in the pack.

This has led to real issues on production as well. There's a repository with 72016 loose keep-around references:

# ls -1 /var/opt/gitlab/git-data/repositories/@hashed/<ID>.git/refs/keep-around | wc -l
72016

packed-refs file contains already 71654 keep-around references.

# grep keep-around /var/opt/gitlab/git-data/repositories/@hashed/<ID>.git/packed-refs | wc -l
71654

Only 362 out of 72016 loose references are new, and don't exist in the packed-refs file with the exact same value.

# comm -13 <(grep keep-around /var/opt/gitlab/git-data/repositories/@hashed/<ID>.git/packed-refs | awk '{print $1}') <(ls -1 /var/opt/gitlab/git-data/repositories/@hashed/<ID>.git/refs/keep-around) | wc -l
362

This issue generalizes elsewhere as well since ultimately it's Git writing these redundant references.

Edited by Sami Hiltunen