Skip to content

feat: split Go module and build caches - #797

Open
qmuntal wants to merge 6 commits into
mainfrom
feat/split-go-caches
Open

qmuntal wants to merge 6 commits into
mainfrom
feat/split-go-caches

Conversation

@qmuntal

@qmuntal qmuntal commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Description:

Cache downloaded Go modules (GOMODCACHE) separately from compiled build outputs (GOCACHE). The current combined archive stores another copy of the module sources for every Go version, runner architecture, and Linux runner image. Separating the entries lets those variants reuse one module archive on the same OS, subject to compatible cache paths, archive versions, and cache access scope. Build outputs keep their existing partitioning dimensions.

Restore the entries sequentially and save them in parallel, so an exact module hit is not uploaded again when the build cache misses. Sequential restores avoid concurrent extraction into overlapping or aliased custom cache directories without path-overlap detection or filesystem-resolution helpers. Each operation still handles failures independently. Parallel saves use the Windows archive-read isolation fix already included by #794. No new inputs or automatic GOOS/GOARCH key dimensions are introduced.

Implementation and test restructuring

  • Replace the single combined cache state with per-entry paths, keys, and restore results. The post step uses the paths captured during restore, even if a later workflow step changes the Go environment.
  • Restore entries sequentially with independent error handling. Remove the path-overlap, symlink-resolution, and case-normalization machinery that was needed only to decide whether concurrent extraction was safe.
  • Keep saves parallel, but move each entry's error handling into the save helper so orchestration is a direct map over the entries. One failed save does not prevent the other, and the post step waits for both before exiting.
  • Test restructuring: fixtures model separate module/build entries and exercise all four hit/miss combinations through restore and post-save, including skipping uploads for exact hits. Invalid dependency-path and missing dependency-file cases are retained, alongside per-entry failure and key-reuse/isolation coverage. Typed mock references and per-test resets keep the setup isolated.
  • Intentional cache-hit change: the old hit test accepted any nonempty returned key. The replacement tests require exact matches for both cache entries; a single matching entry remains usable but does not make the overall output true.
  • Async test helpers: deferred promises verify sequential restores, concurrent saves, and completion before publishing state/output or exiting the post step, without sleep-based timing assertions. Tests specific to the removed overlap-detection helpers are no longer needed.

Use cases that benefit

These reuse cases require an unchanged dependency-file hash and compatible cache paths/archive versions within an accessible cache scope:

  • Testing the two latest Go versions: many modules test against at least the two latest Go release lines. Those jobs can share one module archive while retaining separate build entries, rather than storing and uploading the same dependencies for each Go version. Updating either toolchain also reuses the existing module entry when dependencies are unchanged.
  • Runner-architecture matrices on the same OS: workflows building on both x64 and ARM64 runners can share module sources while retaining architecture-specific build entries. This avoids keeping another copy of the dependencies for each runner architecture; it does not share compiled artifacts between architectures.
  • Different Linux runner images: workflows using multiple Linux images, or moving to a newer image, can reuse the module entry while populating image-specific build entries. Dependency sources do not need another archive just because the runner image changes.
  • Independent hits, misses, and eviction: when one entry is missing or evicted, the other can still be reused. Only the missing entry needs uploading again, rather than re-uploading both modules and build outputs together. A failure in one cache operation also does not prevent processing the other entry.

Measured storage and upload savings

The seven-project hosted benchmark compared the combined action with an earlier revision of this PR on Windows using pinned project sources, go mod download, and go build. The two toolchains were Go 1.26.7 and 1.26.8, with automatic toolchain downloads disabled. All sizes below are compressed archives actually persisted by the GitHub cache service, not unpacked disk sizes. Hugo and Prometheus used bounded build-package selections; these are workload-specific results, not full release-build cache sizes.

These measurements predate the sequential-restore simplification and have not been rerun for this revision. They describe the measured storage/upload savings of split archives, not the latency of the latest implementation.

Project Combined storage, two Go versions Split storage, two Go versions Storage reduction Combined upload, second version Split upload, second version Upload reduction
Cobra 28.13 MiB 27.51 MiB 2.2% 14.06 MiB 13.45 MiB 4.3%
Viper 98.84 MiB 77.28 MiB 21.8% 49.47 MiB 27.86 MiB 43.7%
Prometheus client 247.23 MiB 154.30 MiB 37.6% 123.65 MiB 30.71 MiB 75.2%
Gin 196.82 MiB 142.30 MiB 27.7% 98.46 MiB 43.92 MiB 55.4%
gRPC-Go 344.51 MiB 225.58 MiB 34.5% 172.32 MiB 53.49 MiB 69.0%
Hugo 708.41 MiB 437.10 MiB 38.3% 354.35 MiB 82.83 MiB 76.6%
Prometheus 1,764.08 MiB 938.27 MiB 46.8% 881.93 MiB 55.86 MiB 93.7%
Total 3,388.02 MiB 2,002.33 MiB 40.9% 1,694.25 MiB 308.11 MiB 81.8%

Across these workloads, sharing modules avoided 1,385.69 MiB of retained storage across two Go versions and 1,386.13 MiB of upload traffic when populating the second version. The aggregate is weighted toward the dependency-heavy projects; sharing is repository/cache-scope-local, not global deduplication.

For N compatible variants, compressed module size M, and similarly sized compressed build archives B, the expected footprint changes from approximately N × (M + B) to M + N × B. Each additional variant therefore avoids another M bytes of module storage and, on an existing module hit, approximately M bytes of upload. Workflows with large dependency caches relative to their build caches benefit most. The measurements above cover a patch upgrade; architecture matrices, Linux-image changes, and matrices across different Go release lines were not measured.

Scope and trade-offs

  • Sequential restores: removing concurrency and path-overlap detection simplifies correctness for custom cache layouts, but restoring two hits may take longer than extracting both at once. The storage/upload benefits do not depend on concurrent restores; saves remain parallel.

  • One variant or both entries missing: there is essentially no compression-size gain. The combined and split totals differed by less than 0.11% in magnitude for each measured workload. Splitting reduces duplication across entries, not the size of their underlying contents.

  • Source-only changes with unchanged Go version and dependency hash: neither key changes, so both designs upload zero bytes on exact hits. This PR does not refresh the immutable remote build snapshot with newly compiled artifacts.

  • Source files or target settings included in cache-dependency-path: both entries still use that same hash. A source/settings change invalidates the module entry too, so it does not retain module sharing across those revisions. Separate invalidation inputs and automatic cross-compilation target dimensions remain outside this PR.

  • Two entries add cache lookups and metadata. There is no demonstrated reduction in download bytes for full hits, and module reuse on an otherwise cold key can increase GitHub cache egress while avoiding module-proxy downloads. Hosted latency was mixed; the storage/write savings do not imply universally faster workflows.

  • A shared immutable module snapshot may lack dependencies downloaded only by another variant; Go downloads missing modules, but exact hits do not merge later additions. Cold competing module writers still prepare archives before reservation.

Compatibility

  • New setup-go-modules- and setup-go-build- namespaces deliberately do not restore the old combined archives. Existing workflows need an initial refill; old and new entries can coexist until eviction.
  • Workflows using only setup-go need no input changes. Manual actions/cache/restore integrations must use two entries and the new keys; the documentation is updated accordingly.
  • cache-hit is true only when both entries are restored with exact matches for their cache keys. One exact hit plus one miss reports false, while the exact-hit entry remains usable and is not uploaded again.

Validation

Local validation on Windows with the original dependency lockfile:

  • npm test - passed: 6 suites, 160 tests, including sequential restores, per-entry failure isolation, and concurrent saves.
  • npm run build - passed: TypeScript compilation and both action bundles rebuilt.
  • npm run lint - passed.
  • npm run format-check - passed.
  • git --no-pager diff HEAD --check - passed before committing.
  • npm audit --audit-level=high --json - failed on pre-existing dependency findings in the branch's original lockfile. Dependency maintenance is intentionally outside this PR's scope.

No dependency-manifest or license-record changes are included in this PR. Hosted CI results for the latest revision are not yet verified.

Related issue:
Related to #630.

Check list:

  • Mark if documentation changes are required.
  • Mark if tests were added or updated to cover the changes.

Reuse downloaded modules across Go versions, runner architectures, and
runner images on the same OS instead of duplicating them in each build
cache archive.

Restore and save each entry independently, running operations in parallel
when safe. Serialize restores for overlapping or aliased paths, preserve
the original paths for the post step, and report cache-hit only when both
entries match their primary keys.

Update the documented manual restore keys and generated action bundles.
@qmuntal
qmuntal marked this pull request as ready for review October 5, 2026 18:00
@qmuntal
qmuntal requested a review from a team as a code owner October 5, 2026 18:00
Copilot AI balanced review requested due to automatic review settings October 5, 2026 18:00

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟢 Approval recommended

The split-cache behavior is consistently implemented, documented, bundled, and covered across success, failure, and concurrency scenarios.

Review effort: Balanced
Findings: None

What changed in this PR

Splits Go module and build caches to improve reuse while preserving build-cache isolation.

Changes:

  • Adds independent cache keys, restore/save operations, and hit tracking.
  • Safely parallelizes non-overlapping cache operations.
  • Updates documentation, bundles, and comprehensive tests.
File Description
src/​package-managers.ts Associates cache paths with module/build kinds.
src/​constants.ts Stores cache entries in action state.
src/​cache-utils.ts Resolves paths and detects safe parallel restores.
src/​cache-save.ts Saves cache entries independently.
src/​cache-restore.ts Restores split caches and computes combined hit status.
README.md Documents split-cache behavior.
docs/​advanced-usage.md Updates caching guidance and examples.
action.yml Clarifies cache-hit semantics.
dist/​setup/​index.js Updates the setup runtime bundle.
dist/​cache-save/​index.js Updates the post-action runtime bundle.
__tests__/​cache-utils.test.ts Tests cache path identity and overlap detection.
__tests__/​cache-save.test.ts Tests independent and concurrent saves.
__tests__/​cache-restore.test.ts Tests split keys, restores, failures, and reuse.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@dagood dagood left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mainly doc comments. Looked through the src/ changes and only one thing jumped out at me.

Comment thread __tests__/cache-restore.test.ts Resolved
Comment thread docs/advanced-usage.md Resolved
Comment thread docs/advanced-usage.md Resolved
Comment thread docs/advanced-usage.md Resolved
Comment thread docs/advanced-usage.md Outdated

Both entries use the hash of `cache-dependency-path`, or the root `go.mod` by default. Adding source files or build settings to that input invalidates both entries when those files change. Custom cache locations and the cache service's normal access restrictions still apply.

Each entry is restored and saved independently, with concurrent transfers where safe. An exact hit is not uploaded again, even when the other entry misses. A failure for one entry does not prevent caching the other. The `cache-hit` output is `true` only when both entries are restored on their primary keys.

@dagood dagood Oct 7, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doc only mentioned "primary" key once before this PR. (And it may have been a mistake to use that terminology, an implementation detail leaking into the doc?)

Now it's a bit more confusing, because "primary key" has been added a few more times, like this prominent case. I don't see anything about what a secondary key would potentially be, or any other reason to call it "primary".

This term was added to docs/advanced-usage.md, but also action.yml and README.md.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed: "primary" is cache-library terminology here, not a useful new user-facing concept. It means the key computed for the current run, as distinct from the key returned by the restore call. It does not mean that modules are the primary cache and build outputs are secondary, and setup-go does not supply a list of fallback restore keys.

The public contract is clearer as:

cache-hit is true only when both the module cache and the build cache are restored with exact matches for their cache keys. If only one matches, the output is false; that entry is still used and is not uploaded again.

That wording should be consistent across the README, action output description, and advanced usage. The sentence about a "non-primary key" can also be removed from the user documentation; it exposes the implementation rather than helping explain this feature. This wording cleanup is still outstanding in the current revision.

Comment thread src/cache-utils.ts Outdated
Comment on lines +103 to +104
return paths.every((parent, index) =>
paths.every((child, otherIndex) => {

@dagood dagood Oct 7, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what the intent of this is, and it seems like it deserves justification in part because it appears to be N^2 on the number of paths involved....

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the pairwise check is O(N^2) in the number of cache roots. In the current Go configuration N is at most two: one module directory and one build directory, or just one if discovery of the other fails. There are therefore at most two non-self path comparisons; this does not walk the files inside either cache.

The purpose is to make the new concurrent restores safe when users customize GOMODCACHE and GOCACHE. They can point to the same directory or to ancestor/descendant directories, in which case two archive extractions could write to the same locations. Disjoint roots restore concurrently; overlapping roots restore sequentially.

The alias handling is deliberately conservative too: one archive can replace a symlink traversed by the other extraction, so checking only the final canonical destinations is insufficient. Missing cache directories are resolved through their existing ancestors, and aliases or unresolved paths fall back to sequential restores. The tests cover equal/nested paths in either order, case-insensitive paths, missing directories, symlink aliases, and resolution failures.

So this is a bounded safety check for splitting one restore into two, rather than a general-purpose many-path algorithm. If more cache roots were introduced, the pairwise approach would be worth revisiting.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems worth documenting this intent in the code, so future revisions are more likely to in fact revisit this.

qmuntal and others added 4 commits November 9, 2026 11:57
Co-authored-by: Davis Goodin <dagood@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Restore cache entries sequentially, keep saves parallel with per-entry error handling, and simplify the cache test setup.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This reverts commit aa2cac0. The split-cache implementation and sequential-restore simplifications are retained.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@qmuntal
qmuntal requested a review from dagood November 25, 2026 11:11
@qmuntal

qmuntal commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

@copilot rebase with main

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

Copilot AI commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

@copilot rebase with main

Merged main in 9c6167d rather than rebasing, since a rebase requires a force push. Tests, build, lint, formatting, and CodeQL passed. npm still reports one high-severity dependency audit finding.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants