Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GitHub actions: why 'Cache restored successfully' but 'cache-hit' got 'false' problem

I'm experiencing CI using GitHub action.

I had a problem with installing dependencies on every CI and found that I could solve this with actions/cache.

Here is my part of action.yaml

- name: Cache npm dependency
  uses: actions/cache@v3
  id: npm-cache
  with:
    path: ~/.npm
    key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
    restore-keys: |
      ${{ runner.os }}-npm-

- if: steps.npm-cache.outputs.cache-hit != true
  name: Install Dependency
  run: |
    echo 'npm cache missed'
    npm ci

And restore the cache in Cache npm dependency step.

Cache restored successfully
Cache restored from key: Linux-npm-...

But it always reinstalls dependencies in 'Install Dependency' step.

Run echo 'npm cache missed'
  echo 'npm cache missed'
  npm ci
  shell: /usr/bin/bash -e {0}
npm cache missed
> [email protected] ...
> node bin/postinstall || exit 0
added 661 packages in 19.862s

As a result, caching becomes meaningless. What am i missing or doing wrong?

like image 221
aryang Avatar asked Oct 28 '25 10:10

aryang


2 Answers

I solved it by modifying it like this: != true -> != 'true'

like image 69
aryang Avatar answered Oct 30 '25 10:10

aryang


I am using action cache/restore for getting data from the cache, but the mechanic is similar to the general action.

So in my case, I run into the same frustrating situation, until finally noticed a message in the documentation:

Note 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

That means that if your cache name did not find an exact match and instead was loaded another cache by a relative key, cache-hit will be false despite it saying the opposite in the log!

For example:

key: dev-npm-v5
restore-keys: dev-npm

But actual log will say:

Cache restored successfully
Cache restored from key: dev-npm-v4

In that case your cache-hit output is false, but cache-matched-key is dev-npm-v4

So carefully check the requested name vs actually retrieved cache name. I ended up adding a bash script to determine if at least some cache was loaded using cache-matched-key variable.

Hope it helps anyone. Wasted hours trying to debug this behaviour by myself: 3

like image 20
StasGrin Avatar answered Oct 30 '25 11:10

StasGrin