Impermanence
Platforms: NixOS only.
The root filesystem is wiped on every boot. Only explicitly declared state persists.
Importing
The feature has two halves. The othrys.system.impermanence options and the
root wipe are part of nixosModules.default. The bind mounts that carry state
across the wipe come from the
impermanence module, and
nixosModules.default neither imports it nor writes into its options. A host
with a persistent root imports nothing for this page.
A host with an ephemeral root imports the othrys adapter together with the impermanence module:
modules = [
inputs.othrys.nixosModules.default
inputs.othrys.nixosModules.impermanence
inputs.impermanence.nixosModules.impermanence
];
with impermanence.follows = "othrys/impermanence"; among the flake inputs.
nixosModules.full holds both imports already, so a host built from it adds
neither.
nixosModules.impermanence is modules/system/impermanence.nix, the only file
in the tree that writes environment.persistence. Enabling
othrys.system.impermanence without it fails an assertion that names the
export, since the root would be wiped on every boot and nothing bound back. The
adapter without the impermanence module fails at evaluation, because the option
it writes does not exist.
How It Works
- BTRFS root subvolume is mounted as
/ - On boot, a systemd stage-1 unit moves the old root to
old_roots/with a timestamp - A fresh empty root subvolume is created
- Old roots older than
retentionDaysare deleted, and a delete that fails is reported and the entry kept
The unit waits for the device named by othrys.system.impermanence.device and
runs after a resume from hibernation would have taken over, so a resumed system
never meets a wiped root.
The device
The wipe needs one fact about the disk, which is the block device holding the
btrfs filesystem with the root and persist subvolumes. That is
othrys.system.impermanence.device, and the module names no partitioning tool.
A host that uses the disko layout sets nothing. The
nixosModules.disko export fills the option with its LUKS mapping,
/dev/mapper/<luks.name>, as a default.
A host that partitions another way names the device itself, and needs neither the disko module nor the export:
othrys.system.impermanence = {
enable = true;
device = "/dev/disk/by-partlabel/root";
};
That host also declares the filesystems the layout would have. The root
subvolume is mounted at /, the persist subvolume at
othrys.system.impermanence.persistRoot, and /nix on a volume the wipe does
not touch. The module marks the last two as needed for boot. For an encrypted
root the device is the opened mapping, such as /dev/mapper/cryptroot, and not
the partition under it.
Enabling impermanence with no device and no layout fails an assertion that names the option.
Options
options.othrys.system.impermanence = {
enable = lib.mkEnableOption "Impermanence (ephemeral root with opt-in persistence)";
persistRoot = lib.mkOption {
type = lib.types.str;
default = "/persist";
description = ''
Mountpoint of the persistent volume. `nixosModules.impermanence`
binds everything the othrys modules declare as persistent from this
path, and the disko layout mounts the persist subvolume here, so one
option moves the whole persistence surface. The btrfs subvolume
itself is still named `persist` (the boot-wipe script addresses
subvolumes, not mounts).
'';
};
retentionDays = lib.mkOption {
type = lib.types.ints.unsigned;
default = 30;
description = "Days to keep old root snapshots in /btrfs_tmp/old_roots before deletion.";
};
device = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = ''
Block device holding the btrfs filesystem with the `root` and
`persist` subvolumes. The wipe unit waits for this device in the initrd
and mounts its top-level subvolume.
The option has to be set on a host that enables impermanence. With
`nixosModules.disko` imported and `othrys.system.disko.enable` on, the
layout fills it with its LUKS mapping, `/dev/mapper/<luks.name>`, as a
default. A host that partitions any other way names the device here,
which is the LUKS mapping for an encrypted root and the partition
itself for a plain one.
'';
example = "/dev/disk/by-partlabel/root";
};
};
Boot Wipe Script
Runs during early boot (initrd), after resume from hibernation but before root is mounted:
boot.initrd.systemd.services.root-wipe = {
description = "Wipe root BTRFS subvolume for impermanence.";
wantedBy = ["initrd.target"];
requires = [deviceUnit];
# A resume from hibernation never returns from the resume unit, so this
# only runs on a boot that is not a resume. Without the ordering the
# wipe could run first and the resumed image would see a root that is no
# longer the one it had mounted.
after = [deviceUnit "systemd-hibernate-resume.service"];
before = ["sysroot.mount"];
unitConfig.DefaultDependencies = "no";
serviceConfig.Type = "oneshot";
script = ''
mkdir -p /btrfs_tmp
# subvolid=5 names the top-level subvolume. A host whose default
# subvolume was changed with `btrfs subvolume set-default` would
# otherwise mount that one and find no `root` to move.
mount -o subvolid=5 ${lib.escapeShellArg cfg.device} /btrfs_tmp
if [[ -e /btrfs_tmp/root ]]; then
mkdir -p /btrfs_tmp/old_roots
timestamp=$(date --date="@$(stat -c %Y /btrfs_tmp/root)" "+%Y-%m-%d_%H:%M:%S")
mv /btrfs_tmp/root "/btrfs_tmp/old_roots/$timestamp"
fi
# The new root exists before anything that can fail below runs. A
# prune that aborted between the move and this line left the host
# with no root subvolume, and sysroot.mount dropped it into the
# emergency shell.
btrfs subvolume create /btrfs_tmp/root
${lib.optionalString usersEnabled "mkdir -p ${lib.escapeShellArg "/btrfs_tmp/persist${config.users.users.${username}.home}"}"}
# `local IFS` keeps the split scoped to this function. Assigned
# globally it survived the first call and silently changed how every
# later word split behaved, including the retention loop below.
delete_subvolume_recursively() {
local IFS=$'\n'
for i in $(btrfs subvolume list -o "$1" | cut -f 9- -d ' '); do
delete_subvolume_recursively "/btrfs_tmp/$i"
done
btrfs subvolume delete "$1"
}
# Retention pruning, best-effort. Data-safety invariants:
# - The glob lists the entries of old_roots and never old_roots
# itself, so an archive directory whose own mtime has aged past the
# window (a host up longer than retentionDays) is not a candidate.
# With `find` and no `-mindepth 1` it was, and the ENTIRE archive
# would be deleted at once.
# - Only delete entries that are actually btrfs subvolumes, and a stray
# file or directory in old_roots is skipped (deleting the unknown is
# never the right move in a boot script) and must not fail the boot.
# - A delete that fails is reported and the entry kept. The root above
# already exists, so nothing here can keep the host from booting.
#
# A glob with nullglob handles an empty archive and an entry name with
# whitespace. The names are generated timestamps today, and a boot
# script that deletes subvolumes should not depend on that staying
# true. `find` is not on the stage-1 PATH, which is why the loop uses
# `stat` instead; see initrdBin above.
shopt -s nullglob
cutoff=$(( $(date +%s) - ${toString cfg.retentionDays} * 86400 ))
for i in /btrfs_tmp/old_roots/*; do
if [ "$(stat -c %Y "$i")" -ge "$cutoff" ]; then
continue
fi
if btrfs subvolume show "$i" > /dev/null 2>&1; then
delete_subvolume_recursively "$i" \
|| echo "impermanence: could not delete '$i', keeping it" >&2
else
echo "impermanence: skipping non-subvolume '$i' in old_roots" >&2
fi
done
shopt -u nullglob
umount /btrfs_tmp
'';
};
The Persistence Registry
A module declares what it keeps across the wipe in othrys.internal.persist,
under a key that is its own option path. It does not write
environment.persistence.
# Every othrys module that keeps state across the root wipe writes here,
# keyed by its own option path, and nixosModules.impermanence is the only
# file that writes the option the impermanence module declares.
#
# That option exists only on a host that imports the impermanence module,
# and a write into an option nothing declares fails whatever condition
# guards it. A module that wrote there directly made every host import the
# impermanence module, a host with a persistent root included. This option
# is declared by othrys itself, so a write to it evaluates everywhere and
# is read only where the export is imported and impermanence is on.
#
# The export also applies the two guards, once. System paths are bound when
# impermanence is on, and the paths under `user` only when
# othrys.system.users.enable is on as well, since the impermanence module
# resolves them against the home of an account that has to exist. No module
# spells either guard, so none can spell it wrongly.
#
# A module with a second condition wraps its own value in lib.mkIf. The key
# then disappears when the condition is false. lib.mkIf on a single list
# works as well.
#
# The value is a typed submodule, unlike othrys.internal.homeConfig, which
# is raw. A home-manager contribution carries lib.mkForce and lib.mkDefault
# that have to reach home-manager unprocessed. A persistence entry is a
# plain path with an optional owner and mode and carries no priority, so
# the lists are merged here. That lets two blocks of one module share a
# key, lets lib.mkIf sit on one list, and reports a misspelt attribute at
# the module that wrote it.
#
# An entry keeps the forms the impermanence module accepts. It is a string,
# or an attribute set with `directory` or `file` and any of `user`, `group`
# and `mode`. The export passes each entry on unchanged, and the
# impermanence module checks the attribute names.
options.othrys.internal.persist = let
entries = description:
lib.mkOption {
type = lib.types.listOf (lib.types.either lib.types.str (lib.types.attrsOf lib.types.anything));
default = [];
inherit description;
};
in
lib.mkOption {
type = lib.types.attrsOf (lib.types.submodule {
options = {
directories = entries "System directories to keep, as absolute paths.";
files = entries "System files to keep, as absolute paths.";
user = {
directories = entries "Directories to keep in the primary user's home, relative to it.";
files = entries "Files to keep in the primary user's home, relative to it.";
};
};
});
default = {};
internal = true;
# The sub-options would otherwise be listed in the options reference
# under a parent that is not.
visible = false;
example = lib.literalExpression ''{ "services.tailscale".directories = [ "/var/lib/tailscale" ]; }'';
description = "Per-module persistent paths, keyed by option path, handed to the impermanence module by nixosModules.impermanence.";
};
Each value holds directories and files for system paths, and
user.directories and user.files for paths in the primary user’s home. An
entry is a string, or an attribute set with directory or file and any of
user, group and mode, which are the forms the impermanence module accepts.
The adapter reads the whole registry and writes it under
othrys.system.impermanence.persistRoot:
# Both guards are applied here, once, and at the attribute-set level.
# With impermanence off the persist root is not declared at all. With
# no managed account the `users` set stays empty, since the
# impermanence module reads users.users.<name>.home for every entry
# under it and that account does not exist. A guard on a leaf would
# still declare the user and fail there.
#
# The root is declared once any module has a key in the registry, and
# the user once any module names a path in the home. A host on which
# no module persists anything therefore keeps an empty
# environment.persistence.
environment.persistence = lib.mkIf (cfg.enable && registry != {}) {
${persistRoot} = {
# Part of the system-critical set, so it follows that switch.
hideMounts = lib.mkIf persistenceEnabled true;
directories = collect (entry: entry.directories);
files = collect (entry: entry.files);
users = lib.mkIf (usersEnabled && (userDirectories != [] || userFiles != [])) {
${username} = {
directories = userDirectories;
files = userFiles;
};
};
};
};
Both guards live there. With impermanence off nothing is declared. With no
managed account the paths under user are left out, since the impermanence
module reads users.users.<name>.home to place each bind mount and that
account does not exist. A host of that shape, with every app and desktop module
on, is what the eval-persistence check evaluates. contract-guards rejects
any other file that names environment.persistence, and eval-contract reads
the writers back from two evaluated hosts.
A host adds paths of its own either way. It writes a key of its own in
othrys.internal.persist, or it writes environment.persistence directly,
which merges with what the adapter declares.
System Persistence
System-critical directories persisted in persistence.nixos.nix:
othrys.internal.persist."system.persistence" = {
directories = [
{
directory = "/var/lib/systemd";
user = "root";
group = "root";
mode = "0755";
}
{
directory = "/var/lib/nixos";
user = "root";
group = "root";
mode = "0755";
}
{
directory = "/var/log";
user = "root";
group = "root";
mode = "0755";
}
{
directory = "/var/db/sudo/lectured";
user = "root";
group = "root";
mode = "0700";
}
];
# /etc/machine-id keys the journal directory, the systemd-networkd DHCP
# identity and anything else that tracks the host by id. Left on the
# wiped root it is regenerated on every boot.
files = [
"/etc/adjtime"
"/etc/machine-id"
];
/etc/machine-id is in the set because the journal directory and the
systemd-networkd DHCP identity are both derived from it. Without it every boot
produces a new id.
A host that was already running when it first switches onto this gets its
current id kept. impermanence refuses to mount over a machine-id file that
already holds an id, so an activation step in the adapter copies the running id
into the persist root and bind-mounts it before impermanence looks. A persisted file that
is missing, empty or a leftover symlink is replaced, and one holding a different
id is kept beside it as machine-id.replaced. At boot the step does nothing.
/nix/var is not in the set. The nix subvolume survives the wipe on its own,
so the database, the profiles and the GC roots stay where the installer put
them. Releases before v0.9.0 persisted it, and v0.9.0 to v0.16.0 carried an
activation step that moved such a host onto the subvolume at its first switch.
The step is gone, so a host that still bind-mounts <persistRoot>/nix/var
switches to one of those releases first.
The SSH host keys are not bind-mounted. services.openssh.hostKeys points at
<persistRoot>/etc/ssh/ directly, which is also where sops-nix reads the
ed25519 key. A bind mount over /etc/ssh would cover the sshd_config that
activation writes, and sshd on a freshly installed host would not start until
the first switch.
User Persistence
Cross-cutting user directories (XDG, SSH, Projects):
# Bound only on a host where othrys manages the user account. A
# headless host persists system state without a primary user.
user = {
directories =
(lib.attrNames xdgUserDirs)
++ [
"Projects"
{
directory = ".ssh";
mode = "0700";
}
".cache/nix"
".local/state/home-manager"
".local/share/applications"
];
files = [
".bash_history"
];
};
Every entry under user is bound only when othrys.system.users.enable is on
as well as impermanence, here and for each app module. The adapter applies
that guard, as described above, and no module spells it.
Directories that hold a token, a key or a session are persisted at mode
0700. A file a program saves by renaming a temporary over it, such as zsh
history, is persisted through its directory, since a rename onto a
bind-mounted file fails.
App-Specific Persistence
Each module declares its own persistence:
# App-specific persistence lives in each app's module:
# - Steam → modules/apps/gui/gaming/steam.nix
# - Floorp → modules/apps/gui/floorp/floorp.nixos.nix
# - Signal → modules/apps/gui/signal.nix
# - Plexamp → modules/apps/gui/plexamp.nix
# - Audio → modules/hardware/audio.nix
# - Printing → modules/services/printing.nix
# - Tailscale → modules/services/tailscale.nixos.nix
# - Zsh/Zoxide → modules/system/shell/zsh.nixos.nix
# - Direnv → modules/apps/cli/development.nixos.nix
# - Bluetooth → modules/hardware/wireless/bluetooth.nix
# - WiFi → modules/hardware/wireless/wifi.nix
# - GPG/YubiKey → modules/services/security/yubikey.nixos.nix
Recovering files from a previous boot
The wipe archives each replaced root under old_roots for
retentionDays. The old-roots tool (installed with this module) browses
that archive, since every mount is read-only and restore only copies out:
old-roots list # archived snapshots (timestamps)
old-roots restore <snapshot> home/alice/notes.txt ./notes.txt
old-roots mount # browse under /run/old-roots/old_roots
old-roots umount
The recovery path is exercised by the impermanence VM test alongside the wipe behavior itself. A second VM test boots the unit itself from a btrfs root across three boots, so the initrd rendering, the device dependency and the stage-1 PATH are covered as well as the script.