Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ jobs:
run: go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12
- name: Rebuild packaged binaries
env:
VERSION: v0.2.2
VERSION: v0.3.0
run: scripts/build-dist.sh
- name: Verify packaged binaries are reproducible
run: git diff --exit-code -- dist
6 changes: 4 additions & 2 deletions .github/workflows/smoke.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ on:

permissions:
contents: read
actions: read

jobs:
smoke:
Expand All @@ -27,7 +28,8 @@ jobs:
uses: ./
with:
write: ${{ github.event_name == 'push' || inputs.mode == 'seed' }}
key-prefix: bazel-http-smoke-v1
key-prefix: bazel-http-smoke-car-v1
storage-mode: packs
- name: Prepare stable object
id: object
shell: bash
Expand Down Expand Up @@ -57,4 +59,4 @@ jobs:
STATS_URL: ${{ steps.cache.outputs.stats-url }}
run: |
curl --fail-with-body --silent --show-error "$STATS_URL" --output "$RUNNER_TEMP/stats.json"
jq --exit-status '.backend_downloads == 1 and .hits == 1' "$RUNNER_TEMP/stats.json"
jq --exit-status '.backend_downloads == 2 and .pack_downloads == 1 and .hits == 1' "$RUNNER_TEMP/stats.json"
2 changes: 1 addition & 1 deletion .go-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.26.5
1.26.6
87 changes: 66 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,50 @@ For a trusted release or scheduled workflow, set `write: true`. For all
untrusted code, keep `write: false` and pass the emitted `writable` value to
Bazel.

### CARv2 packs and manifest DAGs

`storage-mode: packs` is the v0.3 storage format. Instead of creating one
GitHub cache entry for every CAS or Action Cache object, it writes many values
to a modest CARv2 archive (8 MiB by default) and publishes one immutable
DAG-CBOR manifest after that archive is available. A large output is placed in
its own archive. The result is normally two Actions-cache creations per pack
(one pack and one manifest), rather than one per Bazel object.

```yaml
permissions:
contents: read
actions: read # manifest discovery for storage-mode: packs

steps:
- id: bazel-cache
uses: cre4ture/bazel-github-actions-cache-v2@<FULL_COMMIT_SHA>
with:
write: auto
key-prefix: ironmesh-bazel-car-v1
storage-mode: packs
pack-size-mb: "8"
```

The `github-token` input defaults to `${{ github.token }}` and is used only to
list immutable manifest keys through GitHub's documented Actions-cache REST
endpoint. It must have `actions: read`; no external service, secret, or write
token is needed. Keep the packed mode in a new `key-prefix`: it deliberately
does not reinterpret or mix v0.2 object keys.

Writers discover all current manifest heads at startup and make each new
manifest a child of every head they observed. Parallel writers can therefore
publish siblings without overwriting each other. Readers discover and merge all
heads. If two manifests contain different Action Results for the same action
digest, that digest is treated as a cache miss rather than picking one result.
Manifest discovery is eventually consistent by design: an unseen manifest is
only a temporary miss.

The server flushes a pending pack when it reaches `pack-size-mb`, at least once
per `pack-flush-seconds`, and unconditionally during the action post step. It
uploads the CARv2 file first and the manifest second; the manifest is the
commit point. Thus cancellation, eviction, a corrupt pack, or a missing output
closure can only lose a cache hit and cannot supply incomplete build output.

### IronMesh example

The action can replace the external-cache URL and token in the Bazel job:
Expand Down Expand Up @@ -84,6 +128,11 @@ Do not enable Bazel remote-cache compression with this release.
| `write` | `auto` | `auto`, `true`, or `false`; forks are always read-only |
| `fail-on-cache-error` | `false` | Strict mode; by default backend failures degrade to misses/soft upload success |
| `key-prefix` | `bazel-http-v1` | Immutable namespace; change to invalidate entries |
| `storage-mode` | `objects` | `objects` (v0.2) or `packs` (CARv2 and manifest DAG) |
| `pack-size-mb` | `8` | Target size for a CARv2 archive; only for `packs`, 1–32 MiB |
| `pack-flush-seconds` | `30` | Maximum local staging interval; only for `packs` |
| `max-manifests` | `2048` | Bound on REST-discovered immutable manifests; only for `packs` |
| `github-token` | `${{ github.token }}` | `actions: read` token for packed-manifest discovery |
| `max-blob-size-mb` | `512` | Maximum spooled upload/download size |
| `max-concurrent-operations` | `4` | Backend-operation backpressure |
| `max-uploads-per-minute` | `180` | Evenly spaced uploads; must be below 200 |
Expand All @@ -110,6 +159,8 @@ Supported:
- implicit handling of the standard SHA-256 zero-byte CAS digest
- immutable cache keys
- per-job coalescing of duplicate immutable `PUT`s before rate limiting and backend publication
- opt-in CARv2 archives with footer indexes, DAG-CBOR manifests, concurrent
writer head merging, and action-result conflict detection

Not currently supported:

Expand All @@ -121,18 +172,13 @@ Not currently supported:

## Limits and operational model

Every Bazel AC or CAS object is one GitHub Actions cache entry. This is the
simplest correct mapping, but large build graphs can create thousands of small
entries. GitHub documents a limit of 200 cache creations per minute; the action
defaults to 180 evenly spaced uploads and exposes throttle statistics. Duplicate
immutable `PUT`s received by the same server are coalesced before they consume
an upload slot; `deduplicated_uploads` reports those avoided backend saves. If
the remaining unique entries become a bottleneck, object segmentation should be
designed from measurements rather than silently bypassing the limit.

The proposed next-generation design is documented in
[CARv2 packs and a manifest DAG](docs/carv2-manifest-dag-concept.md). It is not
implemented by this release.
The `objects` format maps every Bazel AC or CAS object to one GitHub Actions
cache entry. It remains the default rollback path. GitHub documents a limit of
200 cache creations per minute; the action defaults to 180 evenly spaced
uploads. In `packs` mode a successful flush consumes one creation for the CARv2
pack and one for its manifest, so a large build graph is governed by pack count
instead of object count. `pack_uploads`, `manifest_uploads`, and
`pack_downloads` make that distinction explicit in the final statistics.

GitHub's repository cache quota, eviction policy, and branch restrictions all
apply. At the time of writing, the default repository quota is 10 GB and caches
Expand All @@ -144,11 +190,10 @@ correctness.
Because GitHub evicts entries independently, an AC entry can outlive one of its
referenced CAS entries. The adapter checks the complete output closure before
serving or publishing an action result and degrades an incomplete closure to an
ordinary cache miss. Direct output blobs use cache-entry existence checks
without downloading their contents; `Tree` and recursive `Directory` metadata
must be downloaded so their file references can be checked. One action result
is limited to 100,000 distinct validation operations to bound amplification
from a malformed cache entry.
ordinary cache miss. In packed mode this restores and verifies each referenced
CARv2 pack and CAS block before serving the Action Result. One action result is
limited to 100,000 distinct validation operations to bound amplification from a
malformed cache entry.

- [GitHub dependency cache reference](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching)
- [GitHub cache limits](https://docs.github.com/en/actions/reference/limits#cache-limits)
Expand Down Expand Up @@ -201,7 +246,7 @@ go vet ./...
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./...
go run golang.org/x/vuln/cmd/govulncheck@v1.6.0 ./...
node --test action/*.test.js
VERSION=v0.2.2 scripts/build-dist.sh
VERSION=v0.3.0 scripts/build-dist.sh
git diff --exit-code -- dist
(cd dist && sha256sum --check SHA256SUMS)
```
Expand All @@ -210,9 +255,9 @@ Release binaries are built with `CGO_ENABLED=0`, `-trimpath`, and an empty Go
build ID, with VCS stamping disabled, for deterministic Linux amd64/arm64 output. CI rebuilds them and
requires a byte-for-byte match.

The smoke workflow has two modes. A default-branch push seeds a stable object.
A separate `workflow_dispatch` restore run is required to download that object
on a new runner and asserts `backend_downloads == 1`.
The smoke workflow has two modes. A default-branch push seeds a stable packed
object. A separate `workflow_dispatch` restore run downloads the manifest and
one CARv2 pack on a new runner and asserts the persistent hit statistics.

## License

Expand Down
20 changes: 20 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,26 @@ inputs:
description: "Immutable GitHub cache-key namespace; change it to invalidate all entries"
required: false
default: bazel-http-v1
storage-mode:
description: "objects keeps the v0.2 object-per-entry format; packs enables CARv2 packs and manifest DAGs"
required: false
default: objects
pack-size-mb:
description: "Target CARv2 pack size in MiB when storage-mode is packs (1-32)"
required: false
default: "8"
pack-flush-seconds:
description: "Maximum seconds that staged CARv2 objects wait before publication"
required: false
default: "30"
max-manifests:
description: "Maximum immutable manifest entries to discover through the GitHub Actions REST API"
required: false
default: "2048"
github-token:
description: "GitHub token with actions: read, used only by storage-mode=packs to discover manifest cache keys"
required: false
default: ${{ github.token }}
max-blob-size-mb:
description: "Maximum accepted or downloaded AC/CAS object size"
required: false
Expand Down
29 changes: 27 additions & 2 deletions action/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,18 @@ async function main() {
const maxConcurrent = positiveInteger("max-concurrent-operations", 4, 32);
const uploadsPerMinute = positiveInteger("max-uploads-per-minute", 180, 199);
const backendTimeoutSeconds = positiveInteger("backend-timeout-seconds", 300, 3600);
const storageMode = input("storage-mode", "objects").trim().toLowerCase();
if (!["objects", "packs"].includes(storageMode)) {
throw new Error("storage-mode must be objects or packs");
}
const packSizeMB = positiveInteger("pack-size-mb", 8, 32);
const packFlushSeconds = positiveInteger("pack-flush-seconds", 30, 3600);
const maxManifests = positiveInteger("max-manifests", 2048, 10_000);
const githubToken = input("github-token", "");
if (storageMode === "packs" && !githubToken) {
throw new Error("storage-mode=packs requires github-token with actions: read");
}
if (githubToken) mask(githubToken);
const portText = input("port", "0");
const port = Number.parseInt(portText, 10);
if (!Number.isSafeInteger(port) || port < 0 || port > 65535) {
Expand All @@ -77,6 +89,14 @@ async function main() {
spoolDir,
"--key-prefix",
input("key-prefix", "bazel-http-v1"),
"--storage-mode",
storageMode,
"--pack-size",
String(packSizeMB * 1024 * 1024),
"--pack-flush-interval",
`${packFlushSeconds}s`,
"--max-manifests",
String(maxManifests),
booleanFlag("write-enabled", writeEnabled),
booleanFlag("fail-open", failOpen),
"--max-blob-size",
Expand All @@ -95,7 +115,11 @@ async function main() {
const logDescriptor = fs.openSync(logFile, "a", 0o600);
const child = spawn(binary, args, {
detached: true,
env: { ...process.env, BAZEL_GHA_CACHE_SHUTDOWN_TOKEN: shutdownToken },
env: {
...process.env,
BAZEL_GHA_CACHE_SHUTDOWN_TOKEN: shutdownToken,
GITHUB_TOKEN: githubToken || process.env.GITHUB_TOKEN || "",
},
stdio: ["ignore", logDescriptor, logDescriptor],
});
fs.closeSync(logDescriptor);
Expand Down Expand Up @@ -125,6 +149,7 @@ async function main() {
saveState("stats_file", statsFile);
saveState("log_file", logFile);
saveState("temp_dir", tempDir);
saveState("shutdown_wait_seconds", String(Math.max(60, backendTimeoutSeconds + 30)));
setOutput("url", ready.url);
setOutput("stats-url", ready.stats_url);
setOutput("writable", String(writeEnabled));
Expand All @@ -134,7 +159,7 @@ async function main() {
);
setOutput("initial-stats", '{"requests":0,"hits":0,"misses":0,"uploads":0}');
process.stdout.write(
`Bazel cache adapter ready at ${ready.url} (write=${writeEnabled}, fail_open=${failOpen}, pid=${ready.pid})${os.EOL}`,
`Bazel cache adapter ready at ${ready.url} (write=${writeEnabled}, mode=${storageMode}, fail_open=${failOpen}, pid=${ready.pid})${os.EOL}`,
);
}

Expand Down
11 changes: 10 additions & 1 deletion action/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ async function post() {
const statsFile = process.env.STATE_stats_file;
const logFile = process.env.STATE_log_file;
const tempDir = process.env.STATE_temp_dir;
const shutdownWaitSeconds = Number.parseInt(process.env.STATE_shutdown_wait_seconds || "330", 10);
if (!url || !token || !Number.isSafeInteger(pid)) {
process.stdout.write("Cache server state is absent; no cleanup is needed.\n");
return;
Expand All @@ -39,7 +40,10 @@ async function post() {
process.stderr.write(`::warning::cache shutdown request failed: ${error.message}\n`);
}

for (let attempt = 0; attempt < 100 && processExists(pid); attempt += 1) {
const shutdownAttempts = Number.isSafeInteger(shutdownWaitSeconds) && shutdownWaitSeconds > 0
? shutdownWaitSeconds * 10
: 3300;
for (let attempt = 0; attempt < shutdownAttempts && processExists(pid); attempt += 1) {
await sleep(100);
}
if (processExists(pid)) {
Expand Down Expand Up @@ -67,6 +71,11 @@ async function post() {
`| Hits | ${stats.hits ?? 0} |`,
`| Misses | ${stats.misses ?? 0} |`,
`| Published uploads | ${stats.uploads ?? 0} |`,
`| CARv2 pack uploads | ${stats.pack_uploads ?? 0} |`,
`| Manifest uploads | ${stats.manifest_uploads ?? 0} |`,
`| CARv2 pack downloads | ${stats.pack_downloads ?? 0} |`,
`| Manifests discovered | ${stats.manifests_discovered ?? 0} |`,
`| Action-digest conflicts | ${stats.action_digest_conflicts ?? 0} |`,
`| Read-only discarded uploads | ${stats.discarded_uploads ?? 0} |`,
`| Backend downloads | ${stats.backend_downloads ?? 0} |`,
`| Backend existence checks | ${stats.backend_existence_checks ?? 0} |`,
Expand Down
45 changes: 33 additions & 12 deletions cmd/cache-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ func run() error {
port = flag.Int("port", 0, "loopback TCP port; zero selects a dynamic port")
cacheDir = flag.String("cache-dir", "", "local spool directory")
keyPrefix = flag.String("key-prefix", "bazel-http-v1", "GitHub cache key prefix")
storageMode = flag.String("storage-mode", "objects", "storage mode: objects or packs")
packSize = flag.Int64("pack-size", 8*1024*1024, "target CARv2 pack size in bytes")
packFlush = flag.Duration("pack-flush-interval", 30*time.Second, "maximum delay before flushing pending CARv2 data")
maxManifests = flag.Int("max-manifests", 2048, "maximum manifest cache entries to discover")
writeEnabled = flag.Bool("write-enabled", false, "publish validated uploads")
failOpen = flag.Bool("fail-open", true, "degrade backend errors to misses/success")
maxBlobSize = flag.Int64("max-blob-size", 512*1024*1024, "maximum object size in bytes")
Expand Down Expand Up @@ -85,19 +89,31 @@ func run() error {
}
}
logger := log.New(os.Stderr, "bazel-gha-cache: ", log.LstdFlags|log.LUTC)
var catalog cache.Catalog
if *storageMode == "packs" {
catalog, err = cache.NewActionsCatalog(*backendTimeout)
if err != nil {
return err
}
}
srv, err := cacheserver.New(cacheserver.Config{
Backend: backend,
CacheDir: dir,
KeyPrefix: *keyPrefix,
WriteEnabled: *writeEnabled,
FailOpen: *failOpen,
MaxBlobSize: *maxBlobSize,
MaxConcurrent: *maxConcurrent,
UploadsPerMinute: *uploadsPerMinute,
BackendTimeout: *backendTimeout,
ShutdownToken: os.Getenv("BAZEL_GHA_CACHE_SHUTDOWN_TOKEN"),
Shutdown: requestShutdown,
Logger: logger,
Backend: backend,
Catalog: catalog,
CacheDir: dir,
KeyPrefix: *keyPrefix,
StorageMode: *storageMode,
PackSize: *packSize,
PackFlushInterval: *packFlush,
MaxManifests: *maxManifests,
WriteEnabled: *writeEnabled,
FailOpen: *failOpen,
MaxBlobSize: *maxBlobSize,
MaxConcurrent: *maxConcurrent,
UploadsPerMinute: *uploadsPerMinute,
BackendTimeout: *backendTimeout,
ShutdownToken: os.Getenv("BAZEL_GHA_CACHE_SHUTDOWN_TOKEN"),
Shutdown: requestShutdown,
Logger: logger,
})
if err != nil {
return err
Expand Down Expand Up @@ -156,6 +172,11 @@ func run() error {
logger.Printf("graceful shutdown failed: %v", err)
_ = httpServer.Close()
}
flushContext, flushCancel := context.WithTimeout(context.Background(), *backendTimeout)
if err := srv.Close(flushContext); err != nil {
logger.Printf("flush packed cache: %v", err)
}
flushCancel()
stats := srv.Snapshot()
if err := cacheserver.WriteStatsFile(*statsFile, stats); err != nil {
logger.Printf("write stats: %v", err)
Expand Down
4 changes: 2 additions & 2 deletions dist/SHA256SUMS
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
2e25107fd39830c2f617cb9401cea50071d2f901d88f8e1fff3bde14fde71b44 cache-server-linux-amd64
5896195b6347e049aa93c64e5010c7019fb93e2b7377af06f8e36fd14a0d34db cache-server-linux-arm64
100dfdbf3729558bd6953d0e836f6d22a6d7f4e53e67bae289008de2e971e96b cache-server-linux-amd64
5de1b5db9ffa1350bdda5ef1affcabad59be3527df3b7a2abd332d3a6c3e2bcd cache-server-linux-arm64
Binary file modified dist/cache-server-linux-amd64
Binary file not shown.
Binary file modified dist/cache-server-linux-arm64
Binary file not shown.
13 changes: 7 additions & 6 deletions docs/carv2-manifest-dag-concept.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Concept: CARv2 packs and a manifest DAG

Status: proposed for a future v0.3 release. This document does not change the
v0.2 object-per-entry format or its wire compatibility.
Status: implemented in v0.3 as the opt-in `storage-mode: packs` format. It does
not change the v0.2 object-per-entry format or its wire compatibility.

## Problem

Expand Down Expand Up @@ -66,8 +66,7 @@ A manifest is a small immutable DAG-CBOR block encoded with
`go-ipld-prime`. Its CID is the manifest identifier and its Actions-cache key
is derived from that CID.

The final generated schema is a design-time decision, but its logical contents
are:
The implemented DAG-CBOR schema has this logical content:

```text
Manifest {
Expand Down Expand Up @@ -168,8 +167,10 @@ Required tests include:
- An end-to-end cold seed followed by a fresh-runner warm restore, measuring
cache-entry creations, transfer volume, and hit rate.

Before implementation, validate the chosen manifest schema and pack-size targets
with a prototype against a representative large Bazel build.
The initial implementation uses an 8 MiB target and a 32 MiB normal-pack limit;
an individual oversized CAS output receives its own pack. It is released
opt-in so representative cold-seed and warm-read runs can tune those defaults
without altering the v0.2 rollback path.

[go-car]: https://github.com/ipld/go-car
[go-ipld]: https://github.com/ipld/go-ipld-prime
Loading
Loading