A GitHub Action to restore and save (not only) Nix store paths using GitHub Actions cache.
This action is based on actions/cache.
Linux
and macOS
runners.Linux
, macOS
, and Windows
runners.The nix-quick-install-action installs Nix in single-user mode.
Restore
phase:
The cache-nix-action
tries to restore a cache whose key is the same as the primary key.
When it can't restore, the cache-nix-action
tries to restore a cache whose key matches a prefix in a given list of key prefixes.
The cache-nix-action
restores all caches whose keys match some of the prefixes in another given list of key prefixes.
Other job steps run.
Post Restore
phase:
The cache-nix-action
purges caches whose keys are the same as the primary key and that were created more than a given time ago.
When there's no cache whose key is the same as the primary key, the cache-nix-action
collects garbage in the Nix store and saves a new cache.
The cache-nix-action
purges caches whose keys match some of the given prefixes in a given list of key prefixes and that were created more than a given time ago relative to the start of the Post Restore
phase.
/nix
.
--store
flag (link)./nix/store
paths when restoring a cache./nix/var
except /nix/var/nix/db/db.sqlite
.nix-quick-install-action
.Linux
and macOS
runners for Nix store caching.GitHub
allows only 10GB
of caches and then removes the least recently used entries (see its eviction policy). Workarounds:
~30GB
of disk space in several minutes.actions: write
and the token
must have a repo
scope (link).See Caching Approaches.
- uses: nixbuild/nix-quick-install-action@v27
- name: Restore and cache Nix store
uses: nix-community/cache-nix-action@v5
with:
# restore and save a cache using this key
primary-key: nix-${{ runner.os }}-${{ hashFiles('**/*.nix') }}
# if there's no cache hit, restore a cache by this prefix
restore-prefixes-first-match: nix-${{ runner.os }}-
# collect garbage until Nix store size (in bytes) is at most this number
# before trying to save a new cache
gc-max-store-size-linux: 1073741824
# do purge caches
purge: true
# purge all versions of the cache
purge-prefixes: cache-${{ runner.os }}-
# created more than this number of seconds ago relative to the start of the `Post Restore` phase
purge-created: 0
# except the version with the `primary-key`, if it exists
purge-primary-key: never
nix-quick-install-action
loads nixConfig
from flake.nix
and writes to nix.conf (see action.yml in the nix-quick-install
repo).gc-max-store-size-linux: 1073741824
, on Linux
runners, garbage in the Nix store is collected until store size reaches 1GB
or until there's no garbage to collect.gc-max-store-size-macos
isn't set to a number, on macOS
runners, no garbage is collected in the Nix store.cache-nix-action
purges caches:
cache-${{ runner.os }}-
) AND (created more than 42
seconds ago OR last accessed more than 42
seconds ago).See action.yml.
name | description | required | default |
---|---|---|---|
primary-key |
|
true |
"" |
restore-prefixes-first-match |
|
false |
"" |
restore-prefixes-all-matches |
|
false |
"" |
skip-restore-on-hit-primary-key |
|
false |
false |
fail-on |
|
false |
"" |
nix |
|
false |
true |
save |
|
false |
true |
paths |
|
false |
"" |
paths-macos |
|
false |
"" |
paths-linux |
|
false |
"" |
backend |
Choose an implementation of the
|
false |
actions |
gc-max-store-size |
|
false |
"" |
gc-max-store-size-macos |
|
false |
"" |
gc-max-store-size-linux |
|
false |
"" |
purge |
|
false |
false |
purge-primary-key |
|
false |
"" |
purge-prefixes |
|
false |
"" |
purge-last-accessed |
|
false |
"" |
purge-created |
|
false |
"" |
upload-chunk-size |
|
false |
"" |
save-always |
Run the post step to save the cache even if another step before fails. |
false |
false |
token |
The action uses it to communicate with GitHub API. |
false |
${{ github.token }} |
name | description |
---|---|
primary-key |
|
hit |
|
hit-primary-key |
|
hit-first-match |
|
restored-key |
|
restored-keys |
|
On Linux
runners, when gc-max-store-size-linux
is set to a number, the cache-nix-action
will run nix store gc --max R
before saving a cache.
Here, R
is max(0, S - gc-max-store-size-linux)
, where S
is the current store size.
Respective conditions hold for macOS
runners.
There are alternative approaches to garbage collection (see Garbage collection).
The cache-nix-action
allows to delete old caches after saving a new cache (see purge-*
inputs in Inputs and the compare-run-times
job in the Example workflow).
The purge-cache action allows to remove caches based on their last accessed
or created
time without branch limitations.
Alternatively, you can use the GitHub Actions Cache API.
GitHub
evicts least recently used caches when their total size exceeds 10GB
(see Limitations).
If you have multiple similar caches produced on runners with the same OS (Linux
or macOS
), you can merge them into a single cache and store just it to save space.
In short:
See the make-similar-caches
and merge-similar-caches
jobs in the example workflow.
Pros: if N
individual caches are very similar, a common cache will take approximately N
times less space.
Cons: if caches aren't very similar, run time may increase due to a bigger common cache.
Discussed in more details here and here.
Caching approaches work at different "distances" from /nix/store
of GitHub Actions runner.
These distances affect the restore and save speed.
Pros:
GitHub Actions Cache
and works fast.Total duration
.Cons: see Limitations
Pros (link):
GitHub Actions Cache
and works fast.Cons:
Caches
.If used with nix-quick-install-action, it's similar to the cache-nix-action.
If used with install-nix-action and a chroot local store:
Pros:
/tmp/nix
.Cons:
/tmp/nix
to /nix/store
.If used with install-nix-action and this trick, it's similar to the cache-nix-action, but slower (link).
See binary cache, HTTP Binary Cache Store.
Pros:
Cons:
When restoring a Nix store from a cache, the store may contain old unnecessary paths. These paths should be removed sometimes to limit cache size and ensure the fastest restore/save steps.
Produce a cache once, use it multiple times. Don't collect garbage.
Advantages:
Disadvantages:
A
and saves a cache.B
, and saves a cache. The cache has both A
and B
.Collect garbage before saving a cache.
Advantages:
Disadvantages:
nix profile install
to save installables from garbage collection.
atime
.Clone the repository.
git clone --recurse-submodules https://github.com/nix-community/cache-nix-action
Improve README.
Report errors, suggest improvements in issues.
Improve code.
Improve docs.
action.yml
-s and README.md
-s:nix run .#write
Update deps:
actions-toolkit
branch that contains a patched version of actions/toolkit.buildjet-toolkit
branch that contains a patched version of BuildJet/toolkit synchronized with actions/toolkit.main
branch.See "Caching dependencies to speed up workflows".
save-always
flag to save the cache even if a prior step fails~/
home folder on ubuntu-latest
.SEGMENT_DOWNLOAD_TIMEOUT_MINS
. Default is 10 minutes.See the v2 README.md for older updates.
Create a workflow .yml
file in your repository's .github/workflows
directory. An example workflow is available below. For more information, see the GitHub Help Documentation for Creating a workflow file.
If you are using this inside a container, a POSIX-compliant tar
needs to be included and accessible from the execution path.
If you are using a self-hosted
Windows runner, GNU tar
and zstd
are required for Cross-OS caching to work. They are also recommended to be installed in general so the performance is on par with hosted
Windows runners.
SEGMENT_DOWNLOAD_TIMEOUT_MINS
- Segment download timeout (in minutes, default 10
) to abort download of the segment if not completed in the defined number of minutes. Read moreThe cache is scoped to the key, version, and branch. The default branch cache is available to other branches.
See Matching a cache key for more info.
name: Caching Primes
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Cache Primes
id: cache-primes
uses: actions/cache@v4
with:
primary-key: ${{ runner.os }}-primes
paths: prime-numbers
- name: Generate Prime Numbers
if: steps.cache-primes.outputs.cache-hit != 'true'
run: /generate-primes.sh -d prime-numbers
- name: Use Prime Numbers
run: /primes.sh -d prime-numbers
The cache
action provides a cache-hit
output which is set to true
when the cache is restored using the primary key
and false
when the cache is restored using restore-keys
or no cache is restored.
name: Caching Primes
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Restore cached Primes
id: cache-primes-restore
uses: nix-community/cache-nix-action/restore@v5
with:
primary-key: ${{ runner.os }}-primes
paths: |
path/to/dependencies
some/other/dependencies
# other steps
- name: Save Primes
id: cache-primes-save
uses: nix-community/cache-nix-action/save@v5
with:
primary-key: ${{ steps.cache-primes-restore.outputs.cache-primary-key }}
paths: |
path/to/dependencies
some/other/dependencies
Note You must use the
cache
orrestore
action in your workflow before you need to use the files that might be restored from the cache. If the providedkey
matches an existing cache, a new cache is not created and if the providedkey
doesn't match an existing cache, a new cache is automatically created provided the job completes successfully.
With the introduction of the restore
and save
actions, a lot of caching use cases can now be achieved. Please see the caching strategies document for understanding how you can use the actions strategically to achieve the desired goal.
Every programming language and framework has its own way of caching.
See Examples for a list of actions/cache
implementations for use with:
A cache key can include any of the contexts, functions, literals, and operators supported by GitHub Actions.
For example, using the hashFiles
function allows you to create a new cache when dependencies change.
- uses: nix-community/cache-nix-action@v5
with:
primary-key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
paths: |
path/to/dependencies
some/other/dependencies
Additionally, you can use arbitrary command output in a cache key, such as a date or software version:
# http://man7.org/linux/man-pages/man1/date.1.html
- name: Get Date
id: get-date
run: echo "date=$(/bin/date -u "+%Y%m%d")" >> $GITHUB_OUTPUT
shell: bash
- uses: nix-community/cache-nix-action@v5
with:
primary-key: ${{ runner.os }}-${{ steps.get-date.outputs.date }}-${{ hashFiles('**/lockfiles') }}
paths: path/to/dependencies
See Using contexts to create cache keys
A repository can have up to 10GB of caches. Once the 10GB limit is reached, older caches will be evicted based on when the cache was last accessed. Caches that are not accessed within the last week will also be evicted.
Using the hit-primary-key
output, subsequent steps (such as install or build) can be skipped when a cache hit occurs on the primary key. It is recommended to install missing/updated dependencies in case of a partial key match when the key is dependent on the hash
of the package file.
Example:
steps:
- uses: actions/checkout@v4
- uses: nix-community/cache-nix-action@v5
id: cache
with:
primary-key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
path: path/to/dependencies
- name: Install Dependencies
if: steps.cache.outputs.hit-primary-key != true
run: /install.sh
Note The
id
defined innix-community/cache-nix-action
must match the[id]
in theif
statement (i.e.steps.[id].outputs.hit-primary-key
)
Cache version is a hash generated for a combination of compression tool used (Gzip, Zstd, etc. based on the runner OS) and the path
of directories being cached. If two caches have different versions, they are identified as unique caches while matching. This, for example, means that a cache created on a windows-latest
runner can't be restored on ubuntu-latest
as cache Version
s are different.
Pro tip: The list caches API can be used to get the version of a cache. This can be helpful to troubleshoot cache miss due to version.
There are a number of community practices/workarounds to fulfill specific requirements. You may choose to use them if they suit your use case. Note these are not necessarily the only solution or even a recommended solution.
A cache gets downloaded in multiple segments of fixed sizes (1GB
for a 32-bit
runner and 2GB
for a 64-bit
runner). Sometimes, a segment download gets stuck which causes the workflow job to be stuck forever and fail. Version v3.0.8
of actions/cache
introduces a segment download timeout. The segment download timeout will allow the segment download to get aborted and hence allow the job to proceed with a cache miss.
Default value of this timeout is 10 minutes and can be customized by specifying an environment variable named SEGMENT_DOWNLOAD_TIMEOUT_MINS
with timeout value in minutes.
A cache today is immutable and cannot be updated. But some use cases require the cache to be saved even though there was a hit during the Restore phase
. To do so, always purge old versions of that cache:
- name: update cache on every commit
uses: actions/cache@v4
with:
primary-key: primes-${{ runner.os }}
paths: prime-numbers
purge: true
purge-primary-key: always
Please note that this will create a new cache on every run and hence will consume the cache quota.
Reusing cache across feature branches is not allowed today to provide cache isolation. However if both feature branches are from the default branch, a good way to achieve this is to ensure that the default branch has a cache. This cache will then be consumable by both feature branches.
Caches have branch scope restriction in place. This means that if caches for a specific branch are using a lot of storage quota, it may result into more frequently used caches from default
branch getting thrashed. For example, if there are many pull requests happening on a repo and are creating caches, these cannot be used in default branch scope but will still occupy a lot of space till they get cleaned up by eviction policy. But sometime we want to clean them up on a faster cadence so as to ensure default branch is not thrashing. In order to achieve this, gh-actions-cache cli can be used to delete caches for specific branches.
This workflow uses gh-actions-cache
to delete all the caches created by a branch.
The scripts and documentation in this project are released under the MIT License