# Compilation caching: incremental and clean builds produce different .swiftmodule bytes, so cache keys depend on build history

**URL:** <https://forums.swift.org/t/compilation-caching-incremental-and-clean-builds-produce-different-swiftmodule-bytes-so-cache-keys-depend-on-build-history/91358>\
**Category:** Compiler\
**Tags:** swift-driver\
**Created:** [December 3, 2026, 4:43pm UTC](https://forums.swift.org/t/compilation-caching-incremental-and-clean-builds-produce-different-swiftmodule-bytes-so-cache-keys-depend-on-build-history/91358 "2026-12-03T16:43:54Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![arobinson-cricut](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/arobinson-cricut/32/47717_2.png) [@arobinson-cricut](https://forums.swift.org/u/arobinson-cricut)\
**Post date:** [December 3, 2026, 4:43pm UTC](https://forums.swift.org/t/compilation-caching-incremental-and-clean-builds-produce-different-swiftmodule-bytes-so-cache-keys-depend-on-build-history/91358/1 "2026-12-03T16:43:54Z")

</div>

With Xcode compilation caching on, an incremental build and a clean build of the same source produce different `.swiftmodule` bytes. Everything that imports the affected module then gets a different cache key, so machines with different build histories can't share cache entries. Reproduced on Xcode 27.2 (Swift 6.4.2, swift-driver 1.168.6), Xcode 27.1 (Swift 6.4) and Xcode 26.4.1 (Swift 6.3.1, swift-driver 1.148.6).

**Setup.** Four package targets, `Base ‚Üê Middle ‚Üê Top ‚Üê App`. `Middle` uses `Base.Used`. `Top` calls a function in `Middle` and never names anything from `Base`. Build with `xcodebuild`, explicit modules, `COMPILATION_CACHE_ENABLE_CACHING=YES`, and fixed DerivedData and CAS paths.

1. Clean-build. Then append `public struct Unused { public init() {} }` to `Base` and build incrementally.
2. Separately, clean-build the same state-2 source at the same paths with a fresh CAS.

**Result.**

- In the incremental build, `Base` and `Middle` are recompiled and re-emitted. `Top`'s driver logs `Skipping input: {compile: Top.o <= Top.swift}` and runs no emit-module job.
- `Base.swiftmodule` and `Middle.swiftmodule` are byte-identical between the two builds. `Top.swiftmodule` is not: 117‚Äì118 bytes differ on 27.2 and 27.1, and 60 bytes on 26.4.1, with the same file size.
- The differing fields are the `llvmcas://` IDs that `Top.swiftmodule` records for its dependencies: `Middle` (both Xcodes) and transitive `Base` (27.x). The incremental build still holds the CAS IDs of the _state-1_ `Middle` and `Base` module bytes. I checked this with `llvm-cas --make-blob` on the saved modules. The clean build holds the state-2 IDs.
- After the same edit to `App`, App's compile and emit-module cache keys differ between the two histories.
- With `-disable-incremental-imports`: same result. With caching off: all modules are byte-identical.

**Likely cause.** `computeCanSkipEmitModuleTasks` in `FirstWaveComputer.swift` skips emit-module when no compile jobs are scheduled and the module's own `.swift` files are older than its outputs. It doesn't consider explicit module inputs. Without caching that is fine. With caching, the emit-module output embeds those inputs' CAS IDs, so skipping leaves them stale. Running the job, or comparing its cache key with the previous build's, would fix it, and a cache hit would keep the cost low.

**Impact.** In a large modular app, about 16% of modules differed between CI runners building the same commit with persistent DerivedData. The cross-runner cache hit rate was about 10%. Workarounds tested on Xcode 27.2: turning off incremental compilation, whole-module mode, or touching every source file before each build all fix it, at the cost of rebuilding everything. The cheapest fix is touching every source file _and_ passing `-enable-incremental-file-hashing`. Emit-module then runs for every module, but only the modules whose sources really changed recompile. It works only because the hash fallback in `computeCanSkipEmitModuleTasks` gives up on explicit module inputs, which swift-driver#2242 would change. `-driver-always-rebuild-dependents` and `-disable-incremental-imports` don't help.

**Related.** swift-driver#2214 is about the same function with the opposite symptom (emit-module re-runs too often). swift-driver#2242 says explicit module dependency changes needn't be detected in this function, and this repro shows that doesn't hold under caching. swift#94797 fixes incremental-scanner CAS validation, a different layer. swift-driver#2235 and #2236 are caching bugs that cause too much recompilation.

Filed as FB25840618.

## Reproduction

Create these five files, put `run-repro.sh` next to `Package.swift`, and run `./run-repro.sh`. It prints `REPRODUCED` or `NOT REPRODUCED` with the evidence. Set `XCODE=/path/to/Xcode.app` to pick another Xcode, and `CACHING=NO` for the control run.

`Package.swift`

```swift
// swift-tools-version: 5.9
import PackageDescription

// Base <- Middle <- Top <- App
// Middle uses a type from Base. Top uses Middle only and never names anything from Base.
let package = Package(
    name: "Repro",
    platforms: [.macOS(.v14)],
    products: [
        .library(name: "App", targets: ["App"]),
    ],
    targets: [
        .target(name: "Base"),
        .target(name: "Middle", dependencies: ["Base"]),
        .target(name: "Top", dependencies: ["Middle"]),
        .target(name: "App", dependencies: ["Top"]),
    ]
)

```

`Sources/Base/Base.swift`

```swift
public struct Used {
    public var value: Int
    public init(value: Int) { self.value = value }
}

```

`Sources/Middle/Middle.swift`

```swift
import Base

public func makeUsed() -> Int {
    Used(value: 1).value
}

```

`Sources/Top/Top.swift`

```swift
import Middle

public func topValue() -> Int {
    makeUsed() + 1
}

```

`Sources/App/App.swift`

```swift
import Top

public func appValue() -> Int {
    topValue() + 1
}

```

> **run-repro.sh**
>
> ```bash
> #!/bin/bash
> # Reproduces: with Xcode compilation caching on, each .swiftmodule records the
> # CAS ID of every module in its explicit dependency graph, including transitive
> # ones. After a public declaration is added to Base, an incremental build skips
> # re-emitting Top (which reaches Base only through Middle), so Top.swiftmodule
> # keeps the OLD Base CAS ID. A clean build of the same source records the NEW
> # ID. Every cache key that hashes Top.swiftmodule (here: App's jobs) then
> # depends on build history.
> #
> # Graph: Base <- Middle <- Top <- App
> #
> # Usage:
> # ./run-repro.sh # /Applications/Xcode.app, caching on
> # XCODE=/Applications/Xcode-26.4.1.app ./run-repro.sh
> # CACHING=NO ./run-repro.sh # control run
> # EXTRA_SWIFT_FLAGS=-disable-incremental-imports ./run-repro.sh
> # EXTRA_SETTINGS=SWIFT_COMPILATION_MODE=wholemodule ./run-repro.sh # extra build settings
> # PRE_BUILD='find Sources -name "*.swift" -exec touch {} +' \
> # EXTRA_SWIFT_FLAGS=-enable-incremental-file-hashing ./run-repro.sh # shell command run in the
> # # source folder before every build ($DD is set)
> # BUILD_LOCK=/path/to/lockfile ./run-repro.sh # serialize with other builds (lockf -k)
> set -euo pipefail
> 
> HERE=$(cd "$(dirname "$0")" && pwd)
> XCODE=${XCODE:-/Applications/Xcode.app}
> CACHING=${CACHING:-YES}
> export DEVELOPER_DIR="$XCODE/Contents/Developer"
> TOOLBIN="$DEVELOPER_DIR/Toolchains/XcodeDefault.xctoolchain/usr/bin"
> TAG="${TAG:-$(basename "$XCODE" .app)-caching-$CACHING}"
> 
> # Fixed paths: cache keys embed absolute paths, so both scenarios build the
> # same source folder with the same DerivedData and CAS locations.
> WORK="$HERE/work"
> SRC="$WORK/src"
> DD="$WORK/dd"
> CAS="$WORK/cas"
> OUT="$HERE/results/$TAG"
> PRODUCTS="$DD/Build/Products/Debug"
> ARCH_FILE="arm64-apple-macos.swiftmodule"
> MODULES=(Base Middle Top App)
> 
> say() { printf '\n=== %s\n' "$*"; }
> scrub() { sed -e "s#$HOME#\$HOME#g"; }
> 
> reset_tree() {
> rm -rf "$SRC" "$DD" "$CAS" "$WORK/blob-cas"
> mkdir -p "$SRC"
> cp -R "$HERE/Package.swift" "$HERE/Sources" "$SRC/"
> }
> 
> # State 2: Base gains a public declaration nobody uses.
> add_unused_to_base() {
> printf '\npublic struct Unused { public init() {} }\n' >> "$SRC/Sources/Base/Base.swift"
> }
> 
> # State 3: an edit to App, so App's jobs run and log their cache keys.
> edit_app() {
> printf '\npublic func appValue2() -> Int { appValue() + 1 }\n' >> "$SRC/Sources/App/App.swift"
> }
> 
> build() {
> local log="$OUT/$1.log"
> local cmd=(xcodebuild build
> -scheme Repro
> -destination 'generic/platform=macOS'
> -configuration Debug
> -derivedDataPath "$DD"
> ARCHS=arm64 ONLY_ACTIVE_ARCH=YES
> SWIFT_ENABLE_EXPLICIT_MODULES=YES
> COMPILATION_CACHE_ENABLE_CACHING="$CACHING"
> COMPILATION_CACHE_CAS_PATH="$CAS"
> COMPILATION_CACHE_ENABLE_DIAGNOSTIC_REMARKS=YES
> "OTHER_SWIFT_FLAGS=\$(inherited) -driver-show-incremental ${EXTRA_SWIFT_FLAGS:-}"
> ${EXTRA_SETTINGS:-})
> if [[-n "${PRE_BUILD:-}"]]; then (cd "$SRC" && DD="$DD" eval "$PRE_BUILD"); fi
> if [[-n "${BUILD_LOCK:-}"]]; then cmd=(lockf -k "$BUILD_LOCK" "${cmd[@]}"); fi
> (cd "$SRC" && "${cmd[@]}") > "$log" 2>&1 || { echo "build $1 failed, see $log"; tail -30 "$log" | scrub; exit 1; }
> echo "build $1 ok"
> }
> 
> save() {
> for m in "${MODULES[@]}"; do
> cp "$PRODUCTS/$m.swiftmodule/$ARCH_FILE" "$OUT/$1-$m.swiftmodule"
> done
> }
> 
> # "<target> <emit-module|compile> <hit|miss> <key>" for each arm64 Swift job that ran.
> tasks_ran() {
> awk '
> /^Swift(EmitModule|Compile) normal arm64 (Emitting|Compiling)/ {
> match($0, /in target .[A-Za-z]+./); tgt = substr($0, RSTART + 11, RLENGTH - 12)
> kind = ($0 ~ /EmitModule/) ? "emit-module" : "compile"
> pending = tgt " " kind; next
> }
> pending != "" && /[Cc]ache (hit|miss) for key:/ {
> res = ($0 ~ /[Cc]ache hit/) ? "hit" : "miss"
> match($0, /llvmcas:\/\/[0-9a-f]+/)
> print pending, res, substr($0, RSTART, RLENGTH); pending = ""; next
> }
> pending != "" && /^$/ { print pending, "-", "(no-key)"; pending = "" }
> ' "$OUT/$1.log"
> }
> 
> ran() { tasks_ran "$1" | awk -v t="$2" -v k="$3" '$1==t && $2==k {f=1} END {exit !f}'; }
> keys_for() { tasks_ran "$1" | awk -v t="$2" '$1==t {print $2, $4}' | sort; }
> 
> # Whether a .swiftmodule's printable strings contain a given llvmcas:// ID.
> has_id() { if strings -n 8 "$1" | grep -qxF "$2"; then echo yes; else echo no; fi; }
> 
> # CAS ID of a file's bytes, computed the way the build stores module outputs.
> blob_id() { "$TOOLBIN/llvm-cas" --cas "$WORK/blob-cas" --make-blob --data "$1"; }
> 
> compare_bytes() { # $1 $2 = step names, $3 = module
> local a="$OUT/$1-$3.swiftmodule" b="$OUT/$2-$3.swiftmodule"
> if cmp -s "$a" "$b"; then
> echo " $3.swiftmodule: identical ($(stat -f %z "$a") bytes)"
> return
> fi
> cmp -l "$a" "$b" > "$OUT/$3-cmp-l.txt" 2>/dev/null || true
> local n first last
> n=$(grep -cE '^ *[0-9]' "$OUT/$3-cmp-l.txt")
> first=$(( $(head -1 "$OUT/$3-cmp-l.txt" | awk '{print $1}') - 1 ))
> last=$(( $(grep -E '^ *[0-9]' "$OUT/$3-cmp-l.txt" | tail -1 | awk '{print $1}') - 1 ))
> echo " $3.swiftmodule: DIFFERENT, sizes $(stat -f %z "$a") / $(stat -f %z "$b"), $n bytes differ at offsets $first-$last"
> local from=$(( first > 160 ? first - 160 : 0 ))
> for f in "$a" "$b"; do
> echo " strings from offset $from in $(basename "$f"):"
> tail -c +$((from + 1)) "$f" | head -c $(( last - from + 1 )) | strings -n 8 | scrub | grep -E '^(/|\$HOME|llvmcas://|[a-z0-9_]+-apple-)' | sed 's/^/ /'
> done
> }
> 
> rm -rf "$OUT"; mkdir -p "$OUT"
> {
> say "Toolchain"
> xcodebuild -version
> xcrun swiftc --version 2>&1 | head -1
> echo "COMPILATION_CACHE_ENABLE_CACHING=$CACHING EXTRA_SWIFT_FLAGS=${EXTRA_SWIFT_FLAGS:-}"
> } | tee "$OUT/versions.txt"
> 
> say "Scenario A: incremental history (same DerivedData and CAS throughout)"
> reset_tree
> build A1-state1-clean; save A1
> add_unused_to_base
> build A2-state2-incr; save A2
> edit_app
> build A3-state3-incr; save A3
> 
> say "Scenario B: clean build of state 2 (fresh DerivedData and CAS, same paths), then the same App edit"
> reset_tree
> add_unused_to_base
> build B2-state2-clean; save B2
> edit_app
> build B3-state3-incr; save B3
> 
> say "Swift jobs that ran in A2 (Base gained 'public struct Unused')"
> tasks_ran A2-state2-incr | sed 's/^/ /'
> for m in Middle Top; do
> if ran A2-state2-incr $m emit-module; then echo " $m emit-module re-ran: yes"; else echo " $m emit-module re-ran: no"; fi
> done
> top_reemitted=no; ran A2-state2-incr Top emit-module && top_reemitted=yes
> 
> say "State 2 module bytes: A2 (incremental) vs B2 (clean), identical source and paths"
> for m in Base Middle Top; do compare_bytes A2 B2 $m; done
> top_differs=yes; cmp -s "$OUT/A2-Top.swiftmodule" "$OUT/B2-Top.swiftmodule" && top_differs=no
> 
> stale=no; app_same=n/a; stale_fields=""
> if [["$CACHING" == YES]]; then
> say "Dependency CAS IDs recorded inside Top.swiftmodule (state 2)"
> echo " (CAS ID = llvm-cas --make-blob of the dependency's .swiftmodule bytes)"
> for dep in Middle Base; do
> old=$(blob_id "$OUT/A1-$dep.swiftmodule")
> new=$(blob_id "$OUT/B2-$dep.swiftmodule")
> a_old=$(has_id "$OUT/A2-Top.swiftmodule" "$old"); a_new=$(has_id "$OUT/A2-Top.swiftmodule" "$new")
> b_old=$(has_id "$OUT/B2-Top.swiftmodule" "$old"); b_new=$(has_id "$OUT/B2-Top.swiftmodule" "$new")
> echo " $dep.swiftmodule state 1: $old"
> echo " $dep.swiftmodule state 2: $new"
> echo " A2 Top (incremental) contains state-1 ID: $a_old, state-2 ID: $a_new"
> echo " B2 Top (clean) contains state-1 ID: $b_old, state-2 ID: $b_new"
> if [["$old" != "$new" && "$a_old" == yes && "$a_new" == no && "$b_new" == yes]]; then
> stale=yes; stale_fields="$stale_fields $dep"
> fi
> done
> 
> say "App cache keys after the same App edit (A3 vs B3)"
> echo " A3:"; keys_for A3-state3-incr App | sed 's/^/ /'
> echo " B3:"; keys_for B3-state3-incr App | sed 's/^/ /'
> if [["$(keys_for A3-state3-incr App)" == "$(keys_for B3-state3-incr App)"]]; then app_same=yes; else app_same=no; fi
> echo " App keys identical: $app_same"
> fi
> 
> say "Result ($TAG)"
> if [["$CACHING" == YES]]; then
> if [["$stale" == yes && "$top_reemitted" == no]]; then
> echo "REPRODUCED: Top's emit-module was skipped after Base changed. Top.swiftmodule still records the"
> echo " state-1 CAS ID of:$stale_fields. A clean build of the same source records the state-2 ID."
> echo " Top.swiftmodule bytes differ: $top_differs. App cache keys identical across histories: $app_same."
> else
> echo "NOT REPRODUCED: Top re-emitted=$top_reemitted, stale dependency ID in Top=$stale"
> fi
> else
> echo "CONTROL (caching off): Top re-emitted in A2=$top_reemitted; Top.swiftmodule differs between incremental and clean: $top_differs"
> fi
> echo "Logs and module copies: $(echo "$OUT" | scrub)"
> 
> ```

---

<div class="post-metadata">

**Author:** ![wes1](https://avatars.discourse-cdn.com/v4/letter/w/848f3c/32.png) [@wes1](https://forums.swift.org/u/wes1)\
**Post date:** [December 3, 2026, 8:50pm UTC](https://forums.swift.org/t/compilation-caching-incremental-and-clean-builds-produce-different-swiftmodule-bytes-so-cache-keys-depend-on-build-history/91358/2 "2026-12-03T20:50:49Z")

</div>

> [@arobinson-cricut](#):
>
> machines with different build histories can't share cache entries

I didn't realize that sharing was supported.

More generally, what's your goal in this post? To clarify something before submitting a bug? Is this reproducible in the open-source toolchain without Xcode, or traceable thereto? Are you looking for a better workaround? Or to coordinate fixes with swift-driver#2242 and swift-driver#2214?

---

<div class="post-metadata">

**Author:** ![cachemeifyoucan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/cachemeifyoucan/32/6833_2.png) [@cachemeifyoucan](https://forums.swift.org/u/cachemeifyoucan)\
**Post date:** [December 4, 2026, 4:45pm UTC](https://forums.swift.org/t/compilation-caching-incremental-and-clean-builds-produce-different-swiftmodule-bytes-so-cache-keys-depend-on-build-history/91358/3 "2026-12-04T16:45:19Z")

</div>

This is a known issue of the current swift incremental build. The current incremental build focuses on minimal builds, but it is not a stable build state. That means doing an incremental build will not equal to the clean build of the same source, but it will achieve many other alternative buildable states.

To fix this, we need to enforce much stricter dependency invalidations, which will result in much more jobs getting invalidated. It is a trade off we need to make between fastest incremental build vs. stable build state. I don't think this can be addressed without going through a deeper conversation.
