Incremental Builds: Timestamps vs Hashes
An incremental build rebuilds only what changed since the last build. To do that, a build tool must answer one question for every step: is the output still up to date with its inputs? There are two classic answers:
- Timestamps (Make, and Ninja by default): the output is stale if any input's modification time (mtime) is newer than the output's.
- Content hashes (Bazel, Buck2, Gradle, Cargo for some inputs, ccache, SCons by default): the output is stale if the hash of any input differs from the hash recorded at the last build.
Both are right most of the time. Their failure modes are different, and knowing them explains a lot of strange rebuilds.
Timestamps in action
mkdir -p inc && cd inc
printf 'int value(void) { return 1; }\n' > lib.c
printf '#include <stdio.h>\nint value(void);\nint main(void) { printf("value %%d\\n", value()); return 0; }\n' > main.c
cat > Makefile <<'MK'
app: main.o lib.o
gcc main.o lib.o -o app
%.o: %.c
gcc -c lt; -o $@
MK
make -j1
echo "--- nothing changed"
make -j1
echo "--- touch lib.c (content unchanged)"
sleep 1 && touch lib.c
make -j1
echo "--- edit main.c"
sleep 1 && printf '#include <stdio.h>\nint value(void);\nint main(void) { printf("value is %%d\\n", value()); return 0; }\n' > main.c
make -j1 && ./appgcc -c main.c -o main.o
gcc -c lib.c -o lib.o
gcc main.o lib.o -o app
--- nothing changed
make: 'app' is up to date.
--- touch lib.c (content unchanged)
gcc -c lib.c -o lib.o
gcc main.o lib.o -o app
--- edit main.c
gcc -c main.c -o main.o
gcc main.o lib.o -o app
value is 1
Timestamps are cheap: one stat call per file, no reading. But touch lib.c rebuilt lib.o and relinked app even though nothing changed. That is a false positive: wasted work, but a correct result.
Where timestamps go wrong
The dangerous failures are false negatives: something changed, but the tool thinks it didn't.
- Restoring an older file.
cp -p,tar -x,rsync -tand some editors' "revert" keep the old mtime. The input really changed, but its mtime is older than the output's, so Make skips it. - Clock skew. Building on a network file system whose clock differs from your machine's. GNU Make warns
Clock skew detectedfor exactly this reason. - Coarse resolution. Some file systems store whole seconds (FAT has two-second resolution). An edit within the same second as the previous build can be missed; that's why the sessions in this course
sleep 1first. - Inputs that aren't files. Compiler flags, the compiler version and environment variables have no mtime at all.
Here is the first failure, for real. The output gets newer than the restored source, so Make keeps the wrong object:
mkdir -p inc && cd inc
printf 'int value(void) { return 1; }\n' > lib.c
printf '#include <stdio.h>\nint value(void);\nint main(void) { printf("value %%d\\n", value()); return 0; }\n' > main.c
printf 'app: main.o lib.o\n\tgcc main.o lib.o -o app\n%%.o: %%.c\n\tgcc -c lt; -o $@\n' > Makefile
cp -p lib.c lib.c.orig # a backup that keeps the original mtime
sleep 1
printf 'int value(void) { return 2; }\n' > lib.c
make -j1 -s && ./app
cp -p lib.c.orig lib.c # restore the backup, old mtime included
make -j1 && ./appvalue 2
make: 'app' is up to date.
value 2
The source now says return 1, the program still prints 2, and Make claims everything is up to date. (Git avoids this by giving every file it writes the current time on checkout, which is why switching branches often causes large rebuilds: a deliberate false positive.)
Hashes: correct, but you pay to read
A hash-based tool keeps a database of input hashes from the previous build. Here is the idea as a shell script: compute a fingerprint of everything that affects lib.o (the source and the command line) and rebuild only when the fingerprint differs from the stored one:
mkdir -p hashed && cd hashed
build_lib() {
local flags="$1"
local now; now=$( { cat lib.c; echo "gcc -c $flags"; } | sha256sum | cut -c1-64)
if [ -f lib.o ] && [ "$now" = "$(cat lib.o.stamp 2>/dev/null)" ]; then
echo "lib.o: up to date"
else
gcc -c $flags lib.c -o lib.o && echo "$now" > lib.o.stamp && echo "lib.o: compiled with '$flags'"
fi
}
printf 'int value(void) { return 1; }\n' > lib.c
build_lib "-O0"
sleep 1 && touch lib.c
build_lib "-O0" # touched, same content: no rebuild
build_lib "-O2" # same content, different flags: rebuild
printf 'int value(void) { return 1; }\n' > lib.c
build_lib "-O2" # rewritten with identical content: no rebuildlib.o: compiled with '-O0'
lib.o: up to date
lib.o: compiled with '-O2'
lib.o: up to date
The fingerprint covers what timestamps can't: the flags. Changing -O0 to -O2 rebuilds; touching or rewriting the file with identical bytes does not. The cost is that every input must be read and hashed on every build, which is slow for huge trees. Real tools combine both: Ninja records the command line of every output in .ninja_log and rebuilds when it changes; Bazel and Buck2 hash contents but trust file-system watchers to know which files to re-hash; ccache hashes the preprocessed source plus the compiler and flags.
Model: two strategies, one history
This model replays a sequence of events against both strategies and counts mistakes. "Wasted" means rebuilt for nothing; "WRONG" means a stale output was kept:
import hashlib
def h(text):
return hashlib.sha256(text.encode()).hexdigest()
events = [ # (description, new content or None, new mtime)
("edit", "return 2;", 110),
("touch only", None, 120),
("save without changes", "return 2;", 130),
("restore old backup", "return 1;", 95),
("clock-skewed edit", "return 3;", 99),
]
content, mtime = "return 1;", 100
out_mtime, out_hash, built_from = 105, h(content), content
def verdict(rebuild, changed):
if rebuild and not changed: return "wasted"
if not rebuild and changed: return "WRONG"
return "ok"
for desc, new, new_mtime in events:
if new is not None:
content = new
mtime = new_mtime
changed = content != built_from # the truth: does the output need rebuilding?
ts_rebuild = mtime > out_mtime
hash_rebuild = h(content) != out_hash
print(f"{desc:20} timestamps: {'rebuild' if ts_rebuild else 'skip '} {verdict(ts_rebuild, changed):6} "
f"hashes: {'rebuild' if hash_rebuild else 'skip '} {verdict(hash_rebuild, changed)}")
if ts_rebuild or hash_rebuild: # assume we rebuilt, so the output is current again
out_mtime, out_hash, built_from = max(mtime, out_mtime) + 1, h(content), contentedit timestamps: rebuild ok hashes: rebuild ok
touch only timestamps: rebuild wasted hashes: skip ok
save without changes timestamps: rebuild wasted hashes: skip ok
restore old backup timestamps: skip WRONG hashes: rebuild ok
clock-skewed edit timestamps: skip WRONG hashes: rebuild ok
Timestamps waste work twice and keep a stale output twice; hashes get all five right, paid for by reading every input. That trade-off is why large-scale build systems (and every build cache, see Content-Addressed Caches) are built on hashes.
Test yourself
After touch lib.c (no content change), what does a timestamp-based tool do?
- Nothing
- Rebuilds
lib.oand everything after it: a false positive - Deletes
lib.o - Reports an error
Which situation makes a timestamp-based build keep a stale output?
- Editing a file
- Restoring a file with an old mtime (e.g.
cp -pfrom a backup) - Running
make clean - Adding a new file
Why did the hash-based script rebuild when the flags changed from -O0 to -O2?
- Because the file was touched
- Because the command line is part of the fingerprint
- Because
-O2always rebuilds - It didn't rebuild