13. Troubleshooting & Debugging
A systematic way to read Nix errors, tell eval failures from build failures, and reach for the right tool
Everyone who runs NixOS long enough hits the wall of red text. You add one option, run
nixos-rebuild switch, and instead of a new generation you get a stack trace forty lines
tall, or a build that grinds for two minutes and then dies with a compiler error you've
never seen. The reflex — copy the last line into a search engine and hope — works often
enough to be a habit and fails often enough to be miserable.
This article is the antidote: a systematic way to diagnose Nix and NixOS failures. It's the capstone of the series, so it leans on everything before it — the store, the module system, overlays, the REPL. The single most valuable idea is also the simplest, and it's the one most people never make explicit. Before you read a single word of the error, ask one question: did this fail while Nix was still figuring out what to build, or did it fail while actually building something? Those are two completely different worlds, with two different sets of tools. Get that split right and half your debugging is already done.
The one distinction that organizes everything
A Nix run has two phases. First it evaluates the Nix language — reads your flake, merges your modules, resolves every option — to compute a set of derivations (build recipes). Only then does it build those derivations, running real compilers and scripts in a sandbox. An evaluation-time error means the language itself blew up before anything was built — a typo, a type mismatch, an infinite loop in your config. A build-time error means evaluation succeeded, a derivation was handed to a builder, and that build failed — a bad hash, a missing library, a failing test. The tools for the two are almost entirely disjoint.
Which kind of failure is it?
You can usually tell within the first two lines. Evaluation errors talk about the language
and point at a .nix file with a line and column. Build errors talk about a derivation
(a .drv path) and usually scroll a wall of build output past you first. Here are the two
shapes side by side:
Evaluation-time error
Fails fast, before any building. Mentions the Nix language, an attribute, a function, or a type, and points at a source location:
error: attribute 'openssh' missing
at /etc/nixos/hosts/bluewhale.nix:14:3:
13| services.openssh = {
14| enabl = true;
| ^
Build-time error
Evaluation already succeeded. Names a specific derivation by its store path and fails inside a build phase, often after lots of scrolling output:
error: builder for '/nix/store/xxxx-mytool-1.2.drv'
failed with exit code 1;
last 10 log lines:
> gcc: error: cannot find -lssl
The tell is right there: "attribute missing … at file:line" is the language complaining, so it's an eval problem. "builder for /nix/store/….drv failed" means a build problem. Keep that fork in mind and the rest of your response follows from it:
Reading a Nix error
Every Nix error has the same skeleton, and learning to parse it at a glance saves enormous time. The shape is a headline, then a location, then (often) a source snippet:
Anatomy of an error message
error: attribute 'openssh' missing
at /etc/nixos/hosts/bluewhale.nix:14:3:
13| services.openssh = {
14| enabl = true;
| ^
… (a trace of nested "while …" frames may follow)
Line 1 is what went wrong. Line 2 is where —
file:line:column. The caret points at the exact token. Everything after
that, if present, is the trace: the chain of expressions Nix was in the middle
of evaluating when it hit the problem.
The location is the fastest lead you have, so read it before anything else. A huge fraction
of eval errors are a typo one or two lines from where the caret lands — here, enabl
instead of enable.
--show-trace and why traces are enormous. By default Nix shows a compact error. When
the location alone isn't enough, add --show-trace (it works on nix build, nix repl,
and nixos-rebuild ... --show-trace) to get the full chain of "while evaluating …" frames
that led to the failure:
A trace, abbreviated
$ nixos-rebuild switch --show-trace
error:
… while evaluating the attribute 'config.system.build.toplevel'
… while evaluating the module argument 'config'
… while evaluating 'services.openssh.enable'
… while calling the 'foldl'' builtin
(many more frames)
error: attribute 'openssh' missing
at /etc/nixos/hosts/bluewhale.nix:14:3
Two things make traces feel overwhelming. First, they can run to hundreds of frames,
because the NixOS module system is one giant lazy fixpoint: evaluating any option can pull
in the merge of every module. Second, Nix prints the trace outermost-first — the frame
at the very top is the high-level thing it was trying to compute (usually
system.build.toplevel, the whole system), and the frames get more specific as you scroll
down. So the useful reading order is top for context, bottom for the actual cause: skim
the top to see what was being built, then jump to the very bottom, where the real error:
line and its file location live. The middle is almost always noise. (This top-versus-bottom
rule is specific to a --show-trace dump; a plain error printed without a trace is just its
own single headline line, so there's nothing to scroll past.)
How to read a scary trace
Read the bottom first — the last error: line and its
at file:line:col are the concrete cause. Then glance at the
top frame for context (what was Nix ultimately trying to evaluate?).
Ignore the middle. If there's no file location at all, the failure is deep inside library
code, and --show-trace plus that top frame is how you find the option or
package that dragged you there.
Common evaluation-time errors
These all happen before a single derivation is built. Fixing them is a matter of reading the language, not the build log — the REPL from Exploring nixpkgs with the REPL is your best friend here, because you can reproduce most of them at the prompt in a second.
attribute 'X' missing. You asked for a key that isn't in a set. Nearly always a typo
(enabl), a wrong attribute path (pkgs.pyton3), or a package that simply doesn't exist
under that name. Fix: check the spelling at the caret; verify package names with tab
completion in nix repl, and options with nixos-option or search.nixos.org.
called without required argument 'Y'. A function was invoked but a parameter it
requires wasn't supplied. The classic version reads:
A missing function argument
error: function 'anonymous lambda' called without required argument 'pkgs'
at /etc/nixos/modules/mytool.nix:1:1
A module written as { config, lib, ... }: … that then references
pkgs in its body will trip this — the argument set needs pkgs
too, or the catch-all ... to accept it. Add the missing name to the header:
{ config, lib, pkgs, ... }:.
value is a X while a Y was expected. A type mismatch. You wrote a function where a set
was wanted, a list where a string was wanted, null where an attribute set was wanted. Very
common when you forget to call a function (leaving a bare lambda), or when an option
expects a list and you gave it one value. The message tells you both the type you supplied
and the type expected — reconcile them at the caret.
cannot coerce a X to a string. You interpolated something into a string that Nix
doesn't know how to stringify — a set, a list, or a function inside "...${thing}...".
Packages and paths coerce fine (a derivation coerces to its store path); a raw attribute set
does not. Fix: interpolate a concrete leaf ("${pkgs.hello}/bin/hello"), not the container.
infinite recursion encountered. The scariest-looking, but it comes from a small number
of patterns. The recurring causes:
-
Overlay
finalvsprevconfusion. An overlay isfinal: prev: { … }. If you define a package in terms offinal.thatSamePackageinstead ofprev.thatSamePackage, you've asked the finished set to define itself — a loop. Base your override onprev; reach forfinalonly to pull in other packages. This is covered in depth in Overlays & Overrides. -
The module fixpoint referring to itself. Setting an option in terms of
its own final value — e.g.
services.foo.package = config.services.foo.package.override …written so it feeds back on itself — makes the fixpoint chase its tail. Break the cycle by basing the definition onpkgs.foorather than the already-mergedconfigvalue. -
Misused
rec. Arec { a = b; b = a; }where two attributes are defined in terms of each other loops immediately. Remove the mutual reference or don't userec.
Option collisions. Two modules define the same option with different values and the module system can't pick a winner:
A conflicting definition
error: The option 'networking.hostName' has conflicting definition
values:
- In '/etc/nixos/a.nix': "bluewhale"
- In '/etc/nixos/b.nix': "seahorse"
Use 'lib.mkForce value' or 'lib.mkDefault value' to change the
priority on any of these definitions.
The message even names both files. Decide which should win: wrap the authoritative one in
lib.mkForce to override the other, or make the loser a lib.mkDefault
so it only applies when nothing else sets the option. Priorities and merge rules are the
subject of Modules & Options.
A related eval failure is an assertion: a module can declare assertions = [ { assertion = …; message = "…"; } ], and a failed one aborts evaluation with your own message. Those are the friendly errors — a module author anticipated a bad combination and told you exactly what's wrong. Read the message; it usually names the fix.
Common build-time errors
Now evaluation has succeeded, a derivation is being realized in the sandbox, and that
failed. The universal move here is to read the build log, which is where the real cause
lives — the error: from Nix itself is often just "builder … failed with exit code 1."
Fixed-output hash mismatch. A fetcher (fetchurl, fetchFromGitHub, fetchpatch) is a
fixed-output derivation: you tell it the hash of what it will download, and Nix
verifies the download matches. When it doesn't, you get:
Read the got: line
error: hash mismatch in fixed-output derivation
'/nix/store/xxxx-source.drv':
specified: sha256-AAAA…AAAA=
got: sha256-BBBB…BBBB=
The fix is almost mechanical: the got: line is the correct hash —
copy it into your derivation's hash/sha256 field. This happens
when you bump a version and forget to update the hash, or when an upstream tarball or git
tag was changed under you. If the source changed unexpectedly and you didn't bump a
version, be suspicious before trusting the new hash — the content genuinely changed.
A build phase failed. A compiler error, a failing test, a missing header. Nix prints the last few log lines inline, but the full log is what you want. If a rebuild scrolled the failure off-screen, retrieve the complete log by its derivation path:
Getting the full build log
$ nix log /nix/store/xxxx-mytool-1.2.drv
… every line the builder printed …
# or, if you only have the output path, ask Nix for the drv it came from:
$ nix log /nix/store/yyyy-mytool-1.2
nix log replays the stored log for a derivation or its output. When you
can't even name the derivation, re-run the build with --print-build-logs
(short flag -L) so Nix streams every builder's output live instead of only
the last ten lines: nixos-rebuild switch -L.
Missing dependencies. A build can't find a header, a library, or a tool. The distinction
that trips people is buildInputs versus nativeBuildInputs: nativeBuildInputs are tools
that run on the build machine during the build (compilers, pkg-config, code generators),
while buildInputs are libraries that get linked into the result and run on the target.
Put a build tool in buildInputs and it won't be on PATH during the build; put a runtime
library in nativeBuildInputs and it won't be linked. When a build says it can't find cc,
pkg-config, or a generator, it belongs in nativeBuildInputs; a missing -lssl or a
missing header for a linked library belongs in buildInputs. The full treatment is in
Packaging & Derivations.
The sandbox has no network. This surprises everyone once. As we saw all the way back in
The NixOS Mental Model, a normal build runs in a sandbox with no network
access — that purity is exactly what makes builds reproducible. So a build step that tries
to curl a file, or a language build tool that wants to fetch dependencies from the internet
(npm, pip, cargo, go modules), fails with a connection error even though the network is fine:
Why a plain fetch fails mid-build
Ordinary derivations can't touch the network — Nix blocks it so a build depends only on
its declared inputs. The only derivations allowed online are fixed-output ones,
because their hash is declared up front and verified afterward. So the fix for
"connection refused" during a build is never "give the sandbox network"; it's to fetch
the network content in a fixed-output step (a fetcher, a vendored dependency hash like
cargoHash/npmDepsHash) and hand the result to the build as a
normal input.
A binary can't find its libraries at runtime. The build succeeded, but running the
program fails with something like error while loading shared libraries: libfoo.so or a
bad interpreter path. This is because the store has no global /usr/lib: a binary must be
told exactly where its libraries live. For prebuilt binaries you didn't compile (downloaded
releases, proprietary tools), the fix is to rewrite the binary's interpreter and RPATH with
patchelf (or autoPatchelfHook), or to wrap the executable with makeWrapper /
wrapProgram so it launches with the right LD_LIBRARY_PATH and PATH. Again, the
mechanics live in Packaging & Derivations.
The debugging toolkit
A handful of commands cover almost every investigation. Here's the working set, grouped by what you're trying to learn.
Inspect the evaluated config without a rebuild. The single most powerful move for
eval-side questions: load your flake in the REPL and read the fully-merged value of any
option, exactly as nixos-rebuild would compute it.
Ask the config what it actually resolved to
$ cd /etc/nixos
$ nix repl
nix-repl> :lf .
nix-repl> nixosConfigurations.bluewhale.config.services.openssh.enable
true
nix-repl> :a nixosConfigurations.bluewhale
nix-repl> config.networking.hostName
"bluewhale"
This is ground truth after every module merges — the answer to "is this option really
set?" in one line instead of a rebuild. The full workflow, including :a to
lift a host's config into scope, is in
Exploring nixpkgs with the REPL.
Evaluate and build without switching. nixos-rebuild build runs the whole
evaluate-and-build pipeline and leaves the result in a ./result symlink, but does not
activate it or touch your bootloader. It's the safe way to find out whether a change even
compiles. To go further and try it in isolation, nixos-rebuild build-vm builds a bootable
QEMU virtual machine of your configuration and gives you a script to launch it — you can log
into the new config without risking the host at all:
Test a config safely
# evaluate + build, but do not activate:
$ nixos-rebuild build
# build a throwaway VM of this config and run it:
$ nixos-rebuild build-vm
$ ./result/bin/run-*-vm
build answers "does it build?"; build-vm answers "does it boot
and behave?" — both without endangering the running machine. There's also
nixos-rebuild test, which activates a config for the current boot only
(no bootloader entry), so a reboot returns you to the previous generation.
Recover a broken switch. If a switch succeeds at eval and build but the resulting
system misbehaves — a service won't start, or worse, it won't boot — you're never stuck. As
covered in Generations, the Store & Rollbacks: if it still boots,
nixos-rebuild switch --rollback returns you to the previous generation; if it doesn't boot,
reboot and pick the previous generation from the boot menu, which lists every generation
you've ever built. Your old system's store paths were never deleted, so recovery is one
reboot away.
Diagnose a failed service. When the system built and booted fine but a service is down, the problem has left Nix's world entirely and is now an ordinary systemd matter. Use the same tools you would on any Linux box:
When a unit fails
$ systemctl status nginx.service # state, recent lines, exit code
$ journalctl -u nginx.service -e # full log, jump to the end
$ journalctl -u nginx -b # only this boot
$ journalctl -xe # everything recent, with hints
A NixOS service usually fails because of the config it was generated with, so once the journal tells you what's wrong (a bad path, a missing directory, a port clash), the fix is back in your Nix config, not in an edited unit file.
Trace dependencies and disk usage. Two nix subcommands answer "why is this here?" and
"how big is this?" — invaluable when a closure is unexpectedly huge or pulls in something it
shouldn't:
Follow the dependency chain
# WHY does my system depend on this package at all?
$ nix why-depends /run/current-system /nix/store/xxxx-somelib
# how big is a closure (self + all runtime deps), human-readable?
$ nix path-info -Sh /run/current-system
why-depends prints the shortest dependency path from the first store path to
the second — the chain of packages that dragged the second one in.
path-info -S reports the closure size (the package plus every
runtime dependency); add -h for human-readable units.
Find options and functions. When you don't know what an option is called or what it does,
nixos-option services.openssh.enable prints an option's value, type, default, and
description from the current system. For discovery, search.nixos.org
searches every option and package, and Noogle searches the lib and
builtins functions by name or signature — the fastest way to answer "what's the function
that does X?"
NixOS-specific gotchas
Some failures aren't really Nix language or build problems at all — they're rough edges of how flakes and NixOS fit together. These are worth committing to memory because the error messages rarely spell out the real cause.
Flakes ignore files git doesn't track. This is the number-one confusing flake behavior,
and it produces the misleading attribute 'X' missing or "file not found" from a file you
can clearly see on disk. A flake's source is the git tree, so any file you haven't
git add-ed is invisible to the build — a new module you created but didn't stage simply
doesn't exist as far as the flake is concerned. Fix: git add the file (staging is enough;
you don't have to commit) and rebuild. This trap is introduced in
Your First Flake.
The "dirty git tree" warning. Running a flake command with uncommitted changes prints:
Not an error — a warning
warning: Git tree '/etc/nixos' is dirty
This is purely informational: it's telling you the build includes uncommitted changes, so the result isn't tied to a clean commit and isn't perfectly reproducible yet. The build still proceeds. Commit your changes to make it go away — and to make the generation traceable to an exact revision.
system.stateVersion. This option pins the release whose stateful defaults your system
was first installed under — things like default database versions or data layouts that
mustn't silently change when you upgrade. It is deliberately not meant to track your
current NixOS version: you set it once at install and leave it alone forever. If you see
warnings about a missing stateVersion, set it to the release you installed on; don't bump
it to the latest to "fix" it.
Renamed or removed options. NixOS occasionally renames or drops options between releases.
After a big nixpkgs bump you may hit The option 'X' does not exist or a deprecation
warning pointing at a new name. Read the message — it usually names the replacement — and
check the release notes for that version. nixos-option and search.nixos.org confirm the
current spelling.
/boot or the disk fills up. Every generation keeps a kernel and initrd in /boot, and
every build keeps its store paths on disk. Left unmanaged, both grow without bound, and a
full /boot can make a rebuild fail partway or leave you unable to boot. The cure is garbage
collection and generation limits — nix-collect-garbage -d, boot.loader generation caps,
and automatic GC — all covered in
Generations, the Store & Rollbacks. If a rebuild dies with "no
space left on device," this is almost always why.
Try it: decode a Nix error
Pick one of the errors below — the eval-time and build-time ones from this article — and the panel will show what the message actually means, the usual root cause, and the concrete fix. It's a way to build the pattern-matching reflex: see the shape, know the world it belongs to, reach for the right tool.
Key Takeaways
- Ask "eval or build?" first. Evaluation errors mention the language and point at a
file:line:col; build errors name a/nix/store/….drvand fail inside a build phase. The two have almost entirely separate toolkits. - Read the trace bottom-up. The last
error:line and its file location are the real cause; the top frame gives context; the middle is noise. Reach for--show-tracewhen the plain error lacks a location. - Eval fixes are language fixes. Missing attributes (typos), missing function arguments (add it to the
{ … }:header), type mismatches,cannot coerce, infinite recursion (overlayfinal/prev, self-referential fixpoints, misusedrec), and option collisions (mkForce/mkDefault). - Build fixes start with the log. On a hash mismatch, copy the
got:value. Otherwisenix log(or rebuild with-L) shows the real failure — missing deps (buildInputsvsnativeBuildInputs), the sandbox's lack of network, or a binary that can't find its libraries (patchelf/wrapProgram). - Know the toolkit:
nix repl+:lf .for the merged config,nixos-rebuild build/build-vmto test safely,--rollbackand the boot menu to recover,journalctl -u/systemctl statusfor services,nix why-depends/path-info -Sfor the closure, andnixos-option/search.nixos.org/Noogle to find things. - Remember the NixOS gotchas: flakes ignore untracked files (
git add), the "dirty tree" warning is harmless, setsystem.stateVersiononce, watch for renamed options after upgrades, and garbage-collect before/bootor the disk fills.
Debugging on NixOS is less about memorizing fixes and more about routing: the moment you know whether you're looking at an evaluation failure or a build failure, the set of possible causes collapses and the right tool is obvious. Everything above is just filling in that routing table. The last article ties off the series with the flake-specific quality-of-life knowledge that keeps these problems from happening in the first place — pinning, updating inputs, and the conventions that make a configuration pleasant to live with long-term. On to Flake Tips & Gotchas.