I borked my nix profiles

I “accidentally” ran this command after hitting tab too many times:

sudo nixos-rebuild switch --rollback --profile-name /nix/var/nix/profiles/system-83-link/

And I cancelled out, but now my NixOS is borked. I can’t create new profiles or switch profiles.

Example command:

switching profile from version 89 to 88
error: filesystem error: read_symlink: Invalid argument [/nix/var/nix/profiles/system-profiles/nix]
Traceback (most recent call last):
  File "/nix/store/3xjqx4dazji7lgch62ysrkfycywjvg8g-systemd-boot/bin/systemd-boot", line 435, in <module>
    main()
  File "/nix/store/3xjqx4dazji7lgch62ysrkfycywjvg8g-systemd-boot/bin/systemd-boot", line 418, in main
    install_bootloader(args)
  File "/nix/store/3xjqx4dazji7lgch62ysrkfycywjvg8g-systemd-boot/bin/systemd-boot", line 363, in install_bootloader
    gens += get_generations(profile)
            ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/nix/store/3xjqx4dazji7lgch62ysrkfycywjvg8g-systemd-boot/bin/systemd-boot", line 213, in get_generations
    gen_list = run(
               ^^^^
  File "/nix/store/3xjqx4dazji7lgch62ysrkfycywjvg8g-systemd-boot/bin/systemd-boot", line 58, in run
    return subprocess.run(cmd, check=True, text=True, stdout=stdout)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/nix/store/dzi9r3xn0ny4l4gwnyqpncljq40pdk6f-python3-3.12.8/lib/python3.12/subprocess.py", line 571, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['/nix/store/sgdyr2a16rkppbdly1clbcqjqw57dg6g-nix-2.24.14/bin/nix-env', '--list-generations', '-p', '/nix/var/nix/profiles/system-profiles/nix']' returned non-zero exit status 1.
Failed to install bootloader
warning: error(s) occurred while switching to the new configuration

running nixos-rebuild switch --rollback does appear to decrement the profile number, but it doesn’t actually switch to the new profile.

How would I repair /nix/var so my system actually works again?

I fixed my system, just wanted to list out how I did it

  • create/use a nixos installation medium
  • boot into the installation medium
  • mount all devices in /mnt as if you were manually installing nixos for the first time
  • install the channels you had in the system, with the same names, and update
  • run sudo rm -rf /mnt/nix/var (The store doesn’t need to be deleted)
  • run sudo nixos-install (This won’t delete files in /home)
  • reboot, after re-setting your root password
  • run sudo nix-channel --update to fix the channels
  • optionally run sudo nix-collect-garbage to delete all the old system files that can’t be accessed anymore
  • You should have a working nixos system again!