Considering hashing inputs
I'm thinking about hashing inputs, including elements like the command line, environment variables, execution platform, tool versions, and input digests. I'll also need to think about how to output hashing and verify those outputs. It's essential to ensure accuracy throughout. I want to maintain a focus on clarity and not use any emojis or generic acknowledgments during the process. Let's get started on crafting this!
1) What “hermetic build” and “cache correctness” actually mean
Hermetic build (action): an action’s outputs are a pure function of its declared inputs (files + parameters) and a well-defined execution environment. No undeclared reads, no dependence on machine state (time, network, /usr/bin drift, locale), and deterministic outputs.
Cache correctness: when the cache returns an output for a given action key, that output must be exactly what a fresh, correct execution would have produced under the same inputs/environment. Correctness requires:
- Sound keys (they change whenever the result could change),
- Trustworthy cache content (not corrupted/poisoned),
- Deterministic execution (or explicit nondeterminism handling).
2) Hashing: designing action keys that don’t lie
2.1 Action key = hash of “everything that matters”
Most modern systems use an action digest over a canonical encoding of:
- Declared input file digests
- Use a content hash (e.g., SHA-256) of each file.
- For directories, use a Merkle tree digest (hash of names + child digests), so tree identity is stable and order-independent.
- Command line
- Full argv, properly quoted/structured (avoid stringly “join with spaces”; use an array).
- Include response files’ contents if they are used.
- Environment
- Only allow a whitelisted environment set; hash exactly those variables.
- Include working directory if relevant (prefer fixed workdir inside sandbox).
- Toolchain/runtime identity
- Compiler/interpreter binaries’ digests (or immutable IDs).
- Versioned SDKs, sysroots, platform images, container digests.
- For remote execution: include execution platform properties (OS/arch, image digest, kernel ABI if relevant).
- Declared auxiliary inputs
- Param files, link scripts, codegen templates, configuration fragments, etc.
- Build system semantics
- Relevant rule implementation version, feature flags, or “action schema version”.
- Otherwise you’ll get “valid” cache hits across incompatible rule logic.
A common structure is:
ActionKey = H(
CanonicalSerialize({
inputRootDigest,
argv,
envWhitelistMap,
execPlatformID,
toolchainDigests,
ruleVersion,
declaredOutputs, // sometimes included to prevent path mismatches
})
)
2.2 Canonicalization pitfalls (sources of false hits / misses)
- Path normalization: absolute paths must not leak in; use stable sandbox paths.
- File metadata: typically don’t hash mtime/uid/gid (causes misses) unless you truly depend on them.
- Symlinks: decide and be consistent—hash link target vs dereferenced content. For toolchains, prefer content or immutable image digests.
- Locale/timezone/encoding: either fix them in the sandbox or include them in the key.
- Non-deterministic archives: zip/jar/tar often embed timestamps/order; either normalize during creation or accept misses/incorrectness.
2.3 Hash algorithm choices
- Prefer SHA-256 (widely supported, strong). BLAKE3 is faster but requires careful ecosystem support.
- Avoid MD5/SHA1 (collision risks can become cache-poisoning vectors).
2.4 Two-level caching
Many systems split:
- CAS (Content Addressable Storage): stores blobs by digest.
- Action cache: maps
ActionKey -> (output digests + metadata).
Correctness relies on both:
- CAS enforces “digest matches bytes.”
- Action cache enforces “key matches semantics.”
3) Sandboxing: preventing undeclared dependencies
Hashing only works if the action can’t read “random stuff” that isn’t in the key. Sandboxing makes undeclared reads fail loudly.
3.1 Filesystem isolation
Common strategies:
- Linux namespaces + mount: mount only declared inputs + toolchain, plus an empty writable workspace.
- chroot (weaker without namespaces/caps drop).
- Container image pinned by digest (good for toolchain hermeticity).
- macOS sandbox-exec / EndpointSecurity-based controls (harder; often best-effort).
Make writes go only to:
- declared output paths
- a designated temp directory (and preferably its contents are treated as outputs only if declared)
3.2 Block the classic leaks
- Network: disable by default. If allowed, treat as an explicit capability and include it in the key (and ideally pin endpoints/artifacts).
- Time: set fixed
SOURCE_DATE_EPOCH and/or use a “frozen time” facility if available; at minimum include time inputs if used (but better: remove dependency).
- Randomness: seed RNG deterministically for tools that support it.
- Host /proc and /sys: either hide or mount minimal views; these often encode machine-specific info.
- User environment: fixed
HOME, TMPDIR, USER, PATH (or use absolute tool paths).
- Locale: set
LANG, LC_ALL to stable values.
3.3 Sandboxing enforcement & observability
- Fail the action on any read outside the allowlist.
- Log the first N violations with paths to drive cleanup.
- Optional “learning mode” in CI to collect undeclared accesses, but treat it as transitional.
4) Poisoning defenses (remote cache / multi-tenant correctness)
Remote caches introduce adversarial and accidental corruption risks. Defenses should assume:
- caches can serve stale/wrong bytes,
- action cache entries can be forged,
- different tenants/projects may collide if keys aren’t namespaced.
4.1 Integrity: trust, but verify
- CAS digest verification on download: always recompute hash; never trust server-provided digest.
- Authenticated transport: mTLS or signed requests; avoid anonymous write access.
- Immutable blobs: CAS should be write-once per digest; reject “overwrite digest with different bytes.”
4.2 Namespacing and access control
- Separate caches by project/org and often by trust domain (PRs from forks vs mainline).
- Restrict who can write to shared caches. Common pattern:
- PR builds: read-only from trusted cache, write to a quarantine namespace.
- Mainline builds: read-write to canonical cache.
4.3 Output validation strategies
If you need stronger guarantees than “hash matches”:
- Deterministic replay sampling: re-execute a small percentage of cache hits and compare output digests.
- Two-source agreement: accept cached output only if it’s been produced by ≥2 independent builders (expensive but strong).
- Signed provenance / attestation: store “who produced this artifact” metadata signed by CI identity (SLSA-style). Validate signature before use.
4.4 Preventing semantic cache poisoning
Poisoning often exploits missing key inputs:
- Ensure the key includes toolchain + rule version + platform.
- Include linker scripts, codegen templates, implicit config.
- For language ecosystems: include lockfiles and resolved dependency artifacts by digest, not by version string alone.
4.5 Handling nondeterministic tools
If outputs vary between runs, the cache can look “poisoned” even when it isn’t.
- Normalize outputs (stable ordering, timestamps stripped).
- Configure tool flags for determinism (e.g.,
-Wl,--build-id=..., deterministic archives).
- If unavoidable, mark actions “no-remote-cache” or “local-only” or include nondeterminism source in the key (last resort).
5) Metrics that actually tell you correctness is holding
5.1 Cache effectiveness (but not correctness)
- Action cache hit rate:
hits / (hits + misses)
- CAS hit rate: reused blobs vs uploaded blobs
- Saved CPU time: estimated via historic action runtimes
- P95/P99 remote cache latency and download volume
These are necessary but can hide correctness issues.
5.2 Hermeticity / sandbox health metrics
- Sandbox violation rate: count of blocked reads/writes/network attempts per build
- Top undeclared paths (e.g.,
/usr/include, $HOME/.cache, /etc/ssl/certs)
- Network attempt count (should be near zero unless explicitly allowed)
- Env var access (if you instrument/trace it) outside allowlist
5.3 Correctness validation metrics
- Replay mismatch rate: among sampled cache hits, fraction where re-execution produces different output digests
- Non-determinism rate: repeated executions of the same action key yielding different outputs
- “Cache hit but test failed” correlation: track flakiness and whether it spikes with cache hits
- Cross-machine reproducibility: same commit built on two workers → output digests match
5.4 Key quality metrics (catch missing inputs)
- Action key churn: unexpected key changes for “no-op” commits
- Over-sharing detection: if outputs differ but keys match (found via replay), you have missing key inputs
- Under-sharing detection: keys differ but outputs identical (wasted cache); often due to unstable paths, timestamps, env noise
6) Practical rollout checklist
- Make actions explicit: declared inputs/outputs, argv array, env allowlist.
- Sandbox locally first: enforce no undeclared reads; fix violations.
- Pin toolchains: container digest or content-hashed toolchain directories.
- Determinize outputs: normalize archives, set
SOURCE_DATE_EPOCH, fixed locale.
- Enable remote CAS + action cache with digest verification and auth.
- Add poisoning controls: namespaces, write restrictions, optional attestations.
- Run correctness sampling: periodic re-exec of cache hits; alert on mismatches.
- Track metrics above; set SLOs (e.g., replay mismatch < 1e-6, sandbox violations = 0 on main).
If you share your build system/tooling (e.g., Bazel/Buck/Nix/custom), target platforms, and whether you use remote execution, I can map the above into concrete configuration and an incremental adoption plan (including what to hash, how to sandbox on macOS/Windows, and what metrics to wire into CI).