# Cache CI Dependencies Without Hiding Lockfile Drift

> A cache keyed on an unchanged lockfile can keep CI green while package.json drifts away from it. Cache the package store instead of node_modules, run npm ci or a frozen pnpm install on every hit, limit writes to trusted runs, and schedule a cache-mode: none job to prove the cold build.

- Author: [Shashank Rawlani](https://shashank.rawlani.com)

- Published: 2026-11-16T13:30:00.000Z

- Updated: 2026-11-16T13:30:00.000Z

- Category: Automation Tutorials

- Canonical source: https://automationtester.in/blog/automation-tutorials/ci-cache-dependencies-without-hiding-drift

- Tags: github-actions, ci-cd, dependency-caching, npm, pnpm, lockfiles

**Quick answer:** Cache what the package manager downloads, never what it produces. Key the entry on the OS, architecture, runtime version and a hash of the lockfile, and run the frozen install (`npm ci`, `pnpm install --frozen-lockfile`) on every run, hit or miss, so the lockfile is checked even when the cache is warm. Let only trusted `push` runs on the default branch write entries. Then schedule one job with `cache-mode: none` so a cold build is proven regularly instead of discovered when an entry is evicted.

A pull request bumps a dependency in `package.json` and forgets to regenerate the lockfile. CI is green. It stays green for a week of merges, because the cache key hashes the lockfile, the lockfile did not change, and the workflow skips the install step whenever `cache-hit` is `true`. Then the entry goes unused for seven days, GitHub evicts it, the next run on `main` installs from scratch, and it fails on a change nobody has touched in a week.

The cache did what it was told. The fix is to make the key describe the right inputs and to stop a warm cache from standing in for the check a cold install performs.

**Versions checked on 2026-11-09.** `actions/cache` v6.1.0, `actions/setup-node` v7.1.0, `actions/setup-python` v7.1.0, `pnpm/setup` v3.1.2, npm 12.2.2, pnpm 12.18.0 and Playwright 1.65.0. The local labs below were run with Node.js 26.12.1, npm 11.20.0 and pnpm 10.32.1. The platform is GitHub Actions throughout.

## The key is a claim about inputs

Three properties of the GitHub Actions cache decide everything else, and each is easy to get wrong from memory.

**Entries are immutable.** The dependency caching reference says it plainly: "You cannot change the contents of an existing cache. Instead, you can create a new cache with a new key." The `actions/cache` README adds the consequence: if the key matches an existing entry, "a new cache is not created". Whatever was saved first under a key is what every later run restores, until eviction.

**Restore is a search, and it widens.** The action looks for an exact match on `key`, then for prefix matches of `key`, then walks `restore-keys` in order. Among several prefix matches it returns "the most recently created cache". If nothing matches on the current branch, it repeats the whole search on the default branch. A run on a feature branch can therefore restore an entry built from a different lockfile on `main`.

**`cache-hit` means exact match only.** The restore action documents that `cache-hit` "will be set to `true` only when cache hit occurs for the exact `key` match. For a partial key match via `restore-keys` or a cache miss, it will be set to `false`." The `cache-matched-key` output tells you which entry you actually got.

There is also a hidden fourth component. Each entry carries a *version*, a hash of the cached `path` list and the compression tool. Two jobs using the same key with different paths, or the same key on Linux and Windows, produce separate entries and never match each other.

So a key claims that everything shaping the cached directory is encoded in one string. Any input you leave out can change underneath an exact hit.

## Cache the download, not the install

The common shape that hides drift caches the result of an install and then trusts it:

```
# Hides drift: caches the install output and skips the check on a hit
- uses: actions/cache@v6
  id: deps
  with:
    path: node_modules
    key: deps-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
    restore-keys: deps-${{ runner.os }}-
- if: steps.deps.outputs.cache-hit != 'true'
  run: npm install
```

Four separate problems sit in those eight lines. `node_modules` is a product of the lockfile, the Node.js version (native addons compile against it) and the install flags, and only one of those is in the key. The prefix restore key will hand a run a `node_modules` built from some other lockfile. `npm install` is allowed to rewrite the lockfile, so a miss can quietly "repair" the very file under test. And on an exact hit nothing at all verifies that `package.json` and the lockfile agree.

The first-party setup actions avoid most of this by design. `actions/setup-node` states that it "does not cache `node_modules`"; it caches the package manager's global store, the directory `pnpm store path --silent` reports for pnpm. A store is a download cache. A stale or oversized store makes an install slower; it cannot make an install succeed that should fail, because the frozen install still resolves from the lockfile. The safer version keeps the cache and moves the trust:

```
# Caches downloads; the frozen install runs on every run
- uses: actions/checkout@v6
- uses: actions/setup-node@v7
  with:
    node-version-file: .nvmrc
    cache: npm
- run: npm ci
```

`npm ci` carries the guarantees that matter here: the project "must have an existing `package-lock.json`", it exits with an error if the lock and `package.json` disagree "instead of updating the package lock", it removes any existing `node_modules` first, and it "will never write to `package.json` or `package-lock.json`". For pnpm, the CI docs say that when pnpm "detects that it is running in CI, it switches to frozen-lockfile mode automatically", and that a lockfile written by a newer pnpm major makes the install error out rather than rewriting it. With `pnpm/setup`, which installs pnpm and a runtime in one step, the equivalent is:

```
- uses: actions/checkout@v6
- uses: pnpm/setup@fa36a5ef7dcdefc3a7cb25655c122e00cf6e636e # v3.1.2
  with:
    runtime: node@24
    cache: true
    save-cache: ${{ github.ref == 'refs/heads/main' }}
    require-lockfile: true
```

`require-lockfile: true` makes the action's install run `pnpm install --frozen-lockfile`, and restricting `save-cache` to `main` follows the README's pattern for jobs that "should not write to the cache, such as pull requests". The pnpm docs are candid about the payoff: "it is not guaranteed that caching the store will make installation faster." Measure it rather than assume it.

## What each setup action actually puts in the key

The built-in caches are convenient, and their keys are not identical. Read from the source at the tags above:

| Action | Primary key built from | Prefix fallback | `cache-hit` on fallback |
| --- | --- | --- | --- |
| `setup-node` v7.1.0 | `node-cache-${RUNNER_OS}-${arch}-${packageManager}-${hash(lockfile)}` | None, except Yarn Berry projects whose dependencies are managed locally, which fall back to the hashless prefix | `true` for that Yarn Berry fallback, because the output is set from whether any entry was restored |
| `setup-python` v7.1.0 (pip) | `setup-python-${RUNNER_OS}-${arch}-${osVersion}-${osName}-python-${version}-pip-${hash}` (the OS segment is Linux only) | The same string without the hash | `false` |

The setup-node key omits the Node.js version, which is fine for a download store and wrong for a hand-rolled `node_modules` cache copying its shape. setup-python's pip cache hashes `requirements.txt` by default, which is not a lockfile. Its README warns that with unpinned or range specifiers, `pip install -r requirements.txt` "will always try to install the latest available package version", so a perfect cache hit tells you nothing about which versions were installed. Pin the file, or hash a real lock (`poetry.lock`, `Pipfile.lock`) through `cache-dependency-path`.

For npm projects, setup-node v6 and later enable caching automatically when `package.json` declares npm in `packageManager` or `devEngines.packageManager`, even with no `cache` input. The README recommends `package-manager-cache: false` for "workflows with elevated privileges or access to sensitive information". Audit release and deploy workflows for this: a cache you did not ask for is still a cache someone else's run may have written.

## Watch a warm cache hide a broken lockfile

The failure in the opening paragraph reproduces locally in a few seconds, with no registry and no network. Two versions of a package are packed as tarballs and referenced with `file:` specifiers, and a directory keyed on the lockfile's SHA-256 stands in for `actions/cache`:

```
#!/usr/bin/env bash
# Local only: file: tarball dependencies, offline npm, no listener.
set -u
LAB=$(mktemp -d); cd "$LAB"
export npm_config_offline=true npm_config_audit=false npm_config_fund=false
for v in 1.0.0 2.0.0; do
  mkdir -p "src/lib-$v"
  printf '{"name":"lib","version":"%s","main":"index.js"}\n' "$v" > "src/lib-$v/package.json"
  printf 'module.exports = { version: "%s" };\n' "$v" > "src/lib-$v/index.js"
  (cd "src/lib-$v" && npm pack --silent --pack-destination ../.. >/dev/null)
done
mkdir app cache; cd app
printf '{"name":"app","version":"1.0.0","dependencies":{"lib":"file:../lib-1.0.0.tgz"}}\n' > package.json
npm install --silent
printf 'console.log("lib resolved to", require("lib").version)\n' > test.js

ci_job() {   # $1 = skip-on-hit | always-install
  local key="deps-$(sha256sum package-lock.json | cut -c1-12)" hit=false
  rm -rf node_modules
  [ -d "../cache/$key" ] && { cp -R "../cache/$key" node_modules; hit=true; }
  echo "[$1] cache entry $key, cache-hit=$hit"
  if [ "$1" = always-install ] || [ "$hit" != true ]; then
    npm ci --loglevel=error > ../ci.log 2>&1 \
      || { grep -m1 "in sync" ../ci.log; echo "[$1] install FAILED"; return 1; }
  else
    echo "[$1] install skipped"
  fi
  node test.js
  [ "$hit" = true ] || cp -R node_modules "../cache/$key"
}

ci_job skip-on-hit                              # run 1: cold, saves the entry
sed -i.bak 's/lib-1.0.0/lib-2.0.0/' package.json # bump without relocking
ci_job skip-on-hit                              # run 2: the pattern that hides it
ci_job always-install                           # run 2, frozen install every time
```

The output:

```
[skip-on-hit] cache entry deps-20a3196ae69f, cache-hit=false
lib resolved to 1.0.0
[skip-on-hit] cache entry deps-20a3196ae69f, cache-hit=true
[skip-on-hit] install skipped
lib resolved to 1.0.0
[always-install] cache entry deps-20a3196ae69f, cache-hit=true
npm error `npm ci` can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync. Please update your lock file with `npm install` before continuing.
[always-install] install FAILED
```

The key did not change, the hit was exact, and the skip-on-hit job ran the tests against version 1.0.0 while `package.json` asked for 2.0.0. The same restored entry, followed by an unconditional `npm ci`, fails on the first run after the bad commit. The equivalent pnpm check, run with `CI=true` against the same mismatch, stops with `ERR_PNPM_OUTDATED_LOCKFILE  Cannot install with "frozen-lockfile" because pnpm-lock.yaml is not up to date with <ROOT>/package.json`.

Hashing the lockfile is correct. Skipping verification because the hash matched is the bug.

## Restore keys and the state you did not choose

A prefix restore key trades a cold start for a warm directory of unknown provenance. Over a download store that is usually safe: the frozen install fetches whatever is missing and ignores the rest. The cost is growth. pnpm's store documentation notes that pnpm "does not automatically remove packages", so each save under a new key carries forward every package any earlier lockfile needed. `pnpm/setup` runs `pnpm store prune` before deciding whether to save; a hand-rolled `actions/cache` step does not, so add the prune yourself before the post step saves.

Over anything that is executed or trusted as-is (`node_modules`, a virtualenv, a build output directory, a test-result cache) a prefix restore is a correctness risk, because no later step re-derives the contents. Use exact keys only for those, accept the cold start on a lockfile change, and set `fail-on-cache-miss: true` on `actions/cache/restore` where a downstream job must refuse to build without the exact entry a producer job saved. Its documentation is explicit that this only works if you "leave `restore-keys` empty".

Playwright browsers fall in between. The Playwright CI guide does not recommend caching them, because restoring takes about as long as downloading, and the Linux system dependencies "are not cacheable" anyway. If you cache them regardless, the guide says to key "against a hash of the Playwright version", which means the version resolved from the lockfile, not the range in `package.json`, with no prefix fallback:

```
- run: npm ci
- id: pw
  run: echo "version=$(node -p "require('@playwright/test/package.json').version")" >> "$GITHUB_OUTPUT"
- uses: actions/cache@v6
  with:
    path: ~/.cache/ms-playwright
    key: playwright-${{ runner.os }}-${{ runner.arch }}-${{ steps.pw.outputs.version }}
- run: npx playwright install --with-deps chromium
```

The install step stays unconditional, because it is also what installs the system packages the cache cannot carry.

## Who may write the entry you restore

The reference is direct about integrity: "Cache contents are not signed or verified, and any workflow run that can read a cache may extract its contents." An entry restored into a privileged job is code that job will run.

Branch scope does part of the work: a run restores from its own branch, the default branch and, for pull requests, the base branch, never from siblings or children. The gap is events that resolve to the default branch but can be triggered by people without write access. GitHub limits writes to the default branch's scope to `push`, `workflow_dispatch`, `repository_dispatch`, `delete`, `registry_package`, `page_build` and `schedule`. Runs from `pull_request_target`, `issue_comment` or `workflow_run` get read-only access by default, and a blocked save is a warning, not a failure.

The `cache-mode` workflow key makes the intent explicit per job: `read`, `write`, `write-only` or `none`, enforced with scoped cache tokens. Declaring `write` on a low-trust trigger overrides the read-only default, and the docs warn that this "reintroduces the risk of cache-poisoning". Treat a `cache-mode: write` next to `pull_request_target` as a review finding: only trusted runs should write entries that privileged runs restore.

## Prove the cold path on a schedule

Every warm run proves less than it appears to. The direct defence is a job that cannot touch the cache at all:

```
name: cold-install
on:
  schedule:
    - cron: "17 3 * * 1-5"
  workflow_dispatch:

cache-mode: none

jobs:
  cold:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: actions/setup-node@v7
        with:
          node-version-file: .nvmrc
      - run: npm ci
      - run: npm test
```

With `none`, restore is skipped and "treated as a cache miss", and save is skipped, so the run neither benefits from nor contaminates the shared entries. It also exercises the path a warm store skips: fetching every package from the registry with the credentials, proxy and mirror settings the job really has. If a cold run fails while warm runs pass, compare the two runs' environments the way [environment evidence for CI-only failures](/blog/automation-tutorials/debug-ci-only-failures-environment-evidence) describes; the cache is one more difference between them. Where this job sits relative to pull-request checks is a stage decision, of the kind covered in [choosing tests per CI stage by feedback cost](/blog/automation-tutorials/ci-test-pyramid-feedback-cost).

## Count exact, partial and miss separately

"Cache hit rate" as one number blends two different events. A partial restore is a cold-ish install with extra download, and should be counted on its own. The restore outputs carry enough to classify every run:

```
- uses: actions/cache/restore@v6
  id: store
  with:
    path: ~/.npm
    key: npm-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('package-lock.json') }}
    restore-keys: npm-${{ runner.os }}-${{ runner.arch }}-
- name: Record cache outcome
  env:
    HIT: ${{ steps.store.outputs.cache-hit }}
    MATCHED: ${{ steps.store.outputs.cache-matched-key }}
  run: |
    if [ "$HIT" = "true" ]; then outcome=exact
    elif [ -n "$MATCHED" ]; then outcome=partial
    else outcome=miss; fi
    echo "cache_outcome=$outcome matched=${MATCHED:-none}" >> "$GITHUB_STEP_SUMMARY"
- run: npm ci
- uses: actions/cache/save@v6
  if: github.ref == 'refs/heads/main' && steps.store.outputs.cache-hit != 'true'
  with:
    path: ~/.npm
    key: ${{ steps.store.outputs.cache-primary-key }}
```

Pair the outcome with the install step's duration and you have the number that justifies the cache: minutes saved per exact hit against minutes spent restoring on a miss. If exact hits are rare while the lockfile is stable, check storage pressure. Entries unused for seven days are evicted, and past the repository limit (10 GB by default) the least recently accessed go first. Pull request caches can crowd out the default branch's entries; the cache management docs include a workflow that runs `gh cache delete` for a branch when its pull request closes.

## Symptoms that trace back to the cache

### A key that never changes

`hashFiles` "returns an empty string" when its pattern matches nothing. Copy an npm example into a pnpm repository and `hashFiles('package-lock.json')` collapses the key to a constant like `npm-Linux-`. Because entries are immutable, the first save under that key is restored forever and never updated. Look for a key ending in a separator in the restore log. The setup actions guard against this: setup-node throws when it cannot find a lockfile, and setup-python refuses a primary key ending in `-`. Hand-written keys get no such check.

### An entry is listed but never restored

The key matches by eye and the step still reports a miss. That is the version stamp: a different `path` list between saving and restoring jobs, or a different OS. The README points to the list-caches REST endpoint, which returns each entry's version, so you can compare it against what the restoring job would compute.

## Apply this now

Open every workflow and search for `cache-hit`. Any `if:` that skips an install, lockfile check or build step on a hit is the pattern that hid the drift in the lab; remove the condition and keep the cache. Then search for `path: node_modules`, `.venv` or build output directories paired with `restore-keys`, and either cache the package manager's store instead or drop the fallback. Add the scheduled `cache-mode: none` job, and add the outcome step to the main CI job.

Capture as evidence: the first cold run's install duration and result, a week of `cache_outcome` lines from the job summaries, and the repository's current cache usage from the Actions caches page.

## FAQ

### Is caching node_modules ever acceptable?

Only with an exact key that includes every input that shapes it (lockfile hash, Node.js version, OS, architecture, install flags), no restore keys, and the frozen install still running afterwards. Even then `npm ci` deletes an existing `node_modules` before it starts, so the restore buys nothing with npm.

### Do caches saved by pull requests help later runs on main?

No. A `pull_request` run saves under the merge ref, and only re-runs of that pull request can restore it. Pull requests benefit from entries saved on the default branch, so make sure a `push` to the default branch saves them.

### Should the runtime version be in the key?

For anything compiled or linked against the runtime, yes. setup-python already includes the Python version; setup-node does not include the Node.js version, which is acceptable for its download store. In a matrix across runtime versions, hand-rolled keys need `${{ matrix.node }}` or equivalent, or matrix legs will restore each other's entries.

### How do you force a fresh entry without changing dependencies?

Delete the entry with `gh cache delete` or from the Actions caches page, or add a manual version segment such as `v2-` to the key prefix. Because entries are immutable, re-running a job will never refresh an existing key.

## Primary references

- [GitHub Docs: Dependency caching reference](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching). Restore search order including default-branch fallback, immutability of entries, most-recent-created selection among prefix matches, branch and merge-ref scope, the trusted-trigger list for default-branch writes, `cache-mode` values and defaults, unsigned cache contents, and the 7-day and 10 GB eviction rules.

- [GitHub Docs: Workflow syntax, the cache-mode key](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax). Workflow-level and job-level `cache-mode`, enforcement through scoped cache tokens, and the warning about write modes on low-trust triggers.

- [GitHub Docs: Expressions, hashFiles](https://docs.github.com/en/actions/reference/workflows-and-actions/expressions). That `hashFiles` combines per-file SHA-256 hashes and returns an empty string when no file matches.

- [GitHub Docs: Managing caches](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manage-caches). Deleting entries from the web UI or `gh cache`, and the example workflow that clears a branch's caches when its pull request closes.

- [actions/cache v6.1.0 README](https://github.com/actions/cache/blob/v6.1.0/README.md). The `cache-hit` output semantics, no new entry on a matching key, cache version from path and compression, and read-only saves reported as warnings.

- [actions/cache v6.1.0 restore action README](https://github.com/actions/cache/blob/v6.1.0/restore/README.md). The `cache-primary-key` and `cache-matched-key` outputs, and `fail-on-cache-miss` requiring empty `restore-keys`.

- [actions/setup-node v7.1.0 cache-restore source](https://github.com/actions/setup-node/blob/v7.1.0/src/cache-restore.ts). The primary key format, the absence of restore keys outside Yarn Berry, and the error when no lockfile is found; the README at the same tag states that `node_modules` is not cached and documents `package-manager-cache`.

- [actions/setup-python v7.1.0 pip cache source](https://github.com/actions/setup-python/blob/v7.1.0/src/cache-distributions/pip-cache.ts). The pip key including OS, architecture, Linux distribution and Python version, and its hashless restore prefix; the README at the same tag warns about unpinned requirements.

- [pnpm/setup v3.1.2 README](https://github.com/pnpm/setup/blob/v3.1.2/README.md). The `cache`, `save-cache` and `require-lockfile` inputs, exact-match `cache-hit`, and the store prune before saving.

- [npm Docs: npm ci](https://docs.npmjs.com/cli/v12/commands/npm-ci). The lockfile requirement, failure on a mismatch, removal of an existing `node_modules`, and never writing either manifest.

- [pnpm: Continuous Integration](https://pnpm.io/continuous-integration). Automatic frozen-lockfile mode in CI, failure on a newer-major lockfile, the caveat that store caching is not guaranteed to be faster, and treating store and cache directories as trusted.

- [pnpm: pnpm store](https://pnpm.io/cli/store). That pnpm never removes packages from the store on its own, and what `pnpm store prune` removes.

- [Playwright: Continuous Integration, caching browsers](https://playwright.dev/docs/ci#caching-browsers). Why browser caching is not recommended, that Linux system dependencies are not cacheable, and keying on the Playwright version if you cache anyway.

## Continue reading on AutomationTester.in

- [Preview a GitHub Actions Matrix Before include Adds the Wrong Jobs](https://automationtester.in/blog/tools-reviews/preview-github-actions-matrix-include-exclude)
- [Gate an MCP Server and Client on the Official Conformance Suite](https://automationtester.in/blog/ai-in-testing/mcp-conformance-framework-ci)
- [Write k6 Thresholds That Fail CI for the Right Reasons](https://automationtester.in/blog/automation-tutorials/k6-thresholds-fail-ci-right-reasons)
- [Understand Appium 3 Drivers, Plugins, and Boundaries](https://automationtester.in/blog/automation-tutorials/appium-drivers-plugins-test-boundaries)
- [Make JUnit Failures Useful in CI](https://automationtester.in/blog/automation-tutorials/junit-failure-reports-useful-ci)

Source: [Cache CI Dependencies Without Hiding Lockfile Drift](https://automationtester.in/blog/automation-tutorials/ci-cache-dependencies-without-hiding-drift) by Shashank Rawlani.
