# The Physics of Build Caching: kache, Reflinks, and a Zombie Daemon

> Field notes from an ~800-crate Tauri 2 + Rust workspace: content-addressed keys, APFS reflink zero-copy restores, and a 4-day silent cache outage caused by a brew upgrade.

`kache` is not "just another `sccache`." It is a local-first build artifact manager built around **content-addressed storage and copy-on-write filesystems**. These field notes are grounded in measurements from our Tauri 2 + Rust workspace (~800 crates in the dependency graph).

## Why Rust Workspaces Need Artifact Governance

### Cargo's Append-Only Cache Philosophy

Cargo's `target/` directory behaves like an append-only log, not a managed database. Its freshness check (`fingerprint` + `dep-info`) accurately decides what can be reused, but it never deletes artifacts that *used to be* useful.

In our workspace (~100 `tests/*_contract.rs` integration binaries, multiple feature flags, and `--all-targets` runs), `target/debug/build/` grew to **19 GB across 570+ package directories**, with 371 historical unit hashes for a single crate (`dijiang-studio`), each dragging an `~400 MB` `libapp_lib.rlib` copy.

**`kache`'s first job is not raw compilation speed—it is making an append-only `target/` tree governable.**

### How kache Differs from sccache / ccache

| Dimension | sccache / ccache | kache |
|---|---|---|
| **Philosophy** | Transparent compiler proxy storing `.o` files locally or in S3 | Compiler wrapper + **filesystem-level** artifact governance |
| **Granularity** | Individual crate compilation outputs | Unit artifacts + build script execution + incremental graphs + `target/` lifecycle |
| **Local Disk Footprint** | Copies artifacts into `target/` | **APFS `reflink` sharing** (20 GB logical can be &lt; 1 GB physical) |
| **Governance** | None (cache hits only) | `clean --units` / `--stale` / `--orphans` / `disk-recovery` |
| **Daemon** | Stateless client | Stateful engine: periodic GC, quota eviction, target registry, liveness receipts |

## Four-Layer Architecture

1. **Access Layer (User-Level Wrapper):** Configured in `~/.cargo/config.toml` (`rustc-wrapper = "kache"`, `HOST_CC = "kache cc"`), *intentionally kept out of project-level `.cargo/config.toml`* so CI, sandboxes, and contributors without `kache` degrade gracefully to uncached builds.
2. **Key Layer (Content Addressing):** Hashes normalized inputs with `blake3`—source content, dependency metadata, `--cfg`, feature sets, profiles, `rustc` fingerprints, whitelisted env vars, and linker/SDK paths (with `-ffile-prefix-map` path normalization).
3. **Storage Layer (Store + APFS `FICLONE`):** Blobs live in `~/Library/Caches/kache/store/` alongside an SQLite WAL `index.db`. Restores use `clonefile` (`FICLONE`), sharing physical extents until written. Always check `df` and `kache clean -n` (`ON DISK` column) instead of `du`.
4. **Control Plane (`daemon`):** Handles periodic GC (`gc_max_age_hours`), quota eviction (`local_max_size`), `disk-recovery` (emergency eviction below a free-space floor), worktree `target/` registry, and liveness receipts (`KACHE_TARGET_LIVENESS=1`).

![kache four-layer architecture: data plane wrapper hashes inputs with blake3 to restore via FICLONE or compile back to store; control plane daemon manages GC, quotas, disk-recovery, target registry, and liveness receipts; physical layer shares APFS extents](./kache-architecture-en.svg)

**If the daemon dies, builds keep succeeding** (the wrapper reads and writes the store directly), **but all governance halts.**

## Practical Configuration & Pitfalls

```toml
# ~/.cargo/config.toml (user-level only)
[build]
rustc-wrapper = "kache"
[env]
HOST_CC = "kache cc"
HOST_CXX = "kache c++"
CC_KNOWN_WRAPPER_CUSTOM = "kache"
KACHE_TARGET_LIVENESS = "1"
```

```toml
# ~/.config/kache/config.toml
[cache]
local_max_size = "8 GiB"
target_liveness = true
auto_clean_unused_units_days = 7
auto_clean_idle_targets_days = 30
auto_clean_orphaned_targets = true
auto_recover_min_free_bytes = 10737418240   # 10 GiB safety floor
gc_max_age_hours = 168
```

Key operational rules we learned the hard way:

- **Read *time hit rate*, not just *count hit rate*:** Small crates inflate count hits, while a single `aws-lc-sys` hit outweighs a hundred `serde` hits.
- **Disable build-script execution caching when side effects matter:** Caching stdout without running the script broke our embedded git commit hash (`DIJIANG_GIT_COMMIT`) and skipped an `ffmpeg` check. Set `KACHE_BUILD_SCRIPT_CACHE=0`.
- **Keep free disk well above the recovery floor:** When free space hovers near the 10 GiB floor, `disk-recovery` evicts entries every 5 minutes (we watched our store shrink from 789 entries down to 20).

## Incident Postmortem: How a "Working" Cache Died Silently

On 2026-11-26, `kache` 2.3.1 was installed, builds were running daily, and zero errors appeared—yet `kache stats` reported a **1% hit rate (27 / 2,621 crates)** and only **10.6 seconds** saved over 24 hours.

Tracing the chain:

1. `brew upgrade kache` swapped the Cellar binary from `2.3.0` to `2.3.1`, but `launchd` `KeepAlive` only restarts exited processes.
2. The old `kache-engine` `2.3.0` stayed alive for 4+ days, holding `daemon.run.lock` while `ipc/d.sock` vanished.
3. Every `kache` CLI invocation failed to start the new daemon (`did not start after recovery`), leaving GC, quotas, and liveness receipts paralyzed.
4. Meanwhile, `disk-recovery` kept evicting the store down to ~20 entries (~945 MB / 8 GiB), collapsing the hit rate to 1%.

![Zombie daemon incident chain: brew upgrade replaces the binary while the old 2.3.0 engine holds daemon.run.lock, blocking the new daemon, paralyzing governance, triggering disk-recovery eviction, and dropping hit rate to 1%](./kache-incident-chain-en.svg)

**Immediate fix:** `kill` the zombie `kache-engine` process, run `kache daemon start`, and verify `Daemon v2.3.1`.
**Permanent fix:** We wired a lightweight version guard (`kache-daemon-guard.mjs`) into our build entrypoints (`_build-env.js` and `cargo-mem.sh`) with version normalization, an exclusive `wx` lock, readiness polling, and 60-second throttling.

> Caching systems rarely fail loudly—they fail silently by missing slowly. The final step of adopting any build cache is wiring a self-check guard at the entrypoint.