Understanding Cache Action keys

Can someone please help me understand how the cache keys work in the Cache Action?

Here are the things I do not fully understand.

  1. In some places, I see people using the “github.sha” as part of the cache key. For example:

    key: ${{ runner.os }}-docker-${{ github.sha }}
    restore-keys: |
    ${{ runner.os }}-docker-

So, as I understand it, the cache key will change with every commit, and therefore, not be a “cache hit”. What reason is there to use the commit sha in the cache key?

  1. What are restore keys

The documentation on restore-keys states that there are “fallback keys” if no cache hit occurred. So does it mean that when caching is done, it will be cached using two keys, and the topmost key will be selected on restore? Or, is the “restore-keys” option actually listing prefixes of keys, so its meaning is more like “${{ runner.os }}-docker- *”?

If the answer is the latter, then it explains the first question as well, at least to some extent.

If these are not prefixes, then why is everybody using a trailing hyphen in the restore key names?

  1. Restore key documentation

A quote from the restore key documentaiton:

  • restore-keys - An ordered list of keys to use for restoring the cache if no cache hit occurred for key

But the syntax everywhere, is actually used like this:

restore-keys: |
  ${{ runner.os }}-docker-

which is not an ordered list, but rather a newline delimited string. I expected the syntax to match the definition (and actually be an oordered list), which makes more sense to me here:

restore-keys:
  - ${{ runner.os }}-docker-
  - ${{ runner.os }}-

What is the reason for this variable typed as a newline delimited string, instead of a proper YAML array?

Sorry for the long post, hoping someone has the patience to elaborate, and if this is you - thanks in advance!

1 Like

Caches not only can be shared between workflow runs, you also can share caches between jobs in the same workflow run. So when using github.sha in the key is feasible. The key can be any combination of variables, context values, static strings, and functions.
An ordered list of alternative keys to use for finding the cache if no cache hit occurred for key. If you provide restore-keys, the cache action sequentially searches for any caches that match the list of restore-keys.

  1. When there is an exact match, the action restores the files in the cache to the path directory.
  2. If there are no exact matches, the action searches for partial matches of the restore keys. When the action finds a partial match, the most recent cache is restored to the path directory.

More details, you can reference the documentation about Caching dependencies to speed up workflows.

1 Like