Is there any way to tell what's keeping a store path alive after garbage collection?

After I call sudo nix-collect-garbage, there are a couple of store paths that remain and that have names unrelated to any package I’ve declared. Is there a way to tell what’s linking to them, or what’s keeping them from getting garbage collected?

I don’t think there is any automated way, but you can try looking in the /nix/var/nix/gcroots folder.

If the path is used by the current or booted system, this isn’t really very useful. However, if you suspect that it might be caused by a result symlink hanging around, it will be in /nix/var/nix/gcroots/auto. If you do something like ls -la /nix/var/nix/gcroots/auto that should give you an idea.

If it may be somewhere in the graph under one of the GC roots, you could try looking at trees, e.g. nix-store -q --tree /nix/var/nix/gcroots/current-system.

There is probably a better way to get an answer here, if anyone happens to know, I’d love to know, too. If all else fails I bet you could tie together find, nix-store and grep together somehow to get a duck-tape solution.

edit: As it turns out, after doing a bit of searching, there might actually be a solution:

Apparently, you can use nix-store -q --roots to find the GC root for a given store path, e.g. nix-store -q --roots $(which systemctl). The output seems a bit confusing to me but I think this does actually wind up showing the right stuff.

There’s also nix-store -q --referrers ... which seems to show dependents of a given nix store path.

Because the output is a little unclear I’m not 100% sure I’m interpreting this right, but it seems promising.

fantastic, thank you very much for the extensive answer! will begin testing these out

nix-du can also help a bit here IIRC.