Lake: concurrent restores rewrite cache entries in place, and artifact copies are not atomic
Maintainers usually reply within 1 day
Nobody has claimed this yet.
Assessment
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Newbie friendliness
- 48/100
- Issue type
- Bug
- Clarity
- Clearly specified
- Activity status
- Active
- Domain
- build-system
Research direction
Start with restoreArtifact in src/lake/Lake/Build/Common.lean, then compare its hard-link handling with saveArtifact and inspect the copy paths named in src/lake/Lake/Config/Cache.lean and src/lake/Lake/CLI/Main.lean. Reproduce both Linux cases from the issue and check how interrupted copies and concurrent restores behave. Done means concurrent builds succeed without rewriting existing cache entries, and an interrupted copy leaves no truncated file at the final path.
Written by the indexing model from the issue text.
Description
Prerequisites
- Check that your issue is not already filed:
https://github.com/leanprover/lean4/issues - Reduce the issue to a minimal, self-contained, reproducible test case.
Avoid dependencies to Mathlib or Batteries. - Test your test case against the latest nightly release, for example on
https://live.lean-lang.org/#project=lean-nightly
(You can also use the settings there to switch to “Lean nightly”) - When reporting a perceived soundness bug: Does it affect
lake check --paranoid?
If in doubt, please reach out on [email protected] for responsible disclosure.
Description
Lake copies artifacts with copyFile, which is readBinFile plus writeBinFile. writeBinFile opens the target with O_TRUNC (src/runtime/io.cpp:425) and writes into it in place. This causes two problems.
1. Two restores of the same file rewrite the cache entry.
restoreArtifact (src/lake/Lake/Build/Common.lean:662) restores only a missing target. It first tries a hard link to the cache entry. If another process made the link first, hardLink fails with "already exists". restoreArtifact accepts any error and copies instead (line 668). The target is now a hard link to the cache entry, so the copy truncates and rewrites the cache file itself.
- If the cache entry is read-only, the copy fails with "permission denied", and the build fails.
saveArtifactandresolveArtifactmake entries read-only. - If the cache entry is writable, the cache file is empty for a short time and then grows back. Entries from
lake cache get,createExtraPathsandlake cache unstageare writable, because these code paths do not set the mode. - During this copy, other workspaces that share the cache can read a short file. If the process stops during the copy, the entry stays truncated for all workspaces.
- As root (containers, CI), the read-only mode does not stop the copy.
saveArtifact already handles this race (src/lake/Lake/Build/Common.lean:504–507). The race is frequent. Lake has no build lock for a workspace, and each file worker of the server runs its own lake setup-file (src/Lean/Server/FileWorker/SetupFile.lean:32).
2. A copy that stops part-way leaves a truncated file that Lake keeps.
restoreArtifact copies when it cannot make a hard link, for example when the cache is on another file system. If the copy stops (Ctrl-C, kill, full disk, power loss), the truncated file stays at the final path.
Lake writes the fetch trace before the restore (src/lake/Lake/Build/Common.lean:716–720, src/lake/Lake/Build/Module.lean:1256). The next run thus sees a matching trace and an existing file, and does not restore the file again. Every importer then fails until the user deletes the file or runs lake clean.
Two writes into the cache have the same problem:
createExtraPathsinlake cache get(src/lake/Lake/Config/Cache.lean:1167).- The copy from the staging directory in
lake cache unstage(src/lake/Lake/CLI/Main.lean:921).
Lake reads cache entries without a hash check. resolveArtifact only reads the mtime (src/lake/Lake/Build/Common.lean:599). Thus a truncated entry stays until a run with --force or --overwrite. All other artifact writes into the cache are atomic, because they use a hard link or writeBinFileAtomicIfNew.
Both problems apply to all files that restoreArtifact handles: .olean, .olean.server, .olean.private, .ilean, .ir.sig, .ir, .c, .bc, .ltar, static and shared libraries, and executables. With the default read-only cache, a module restore copies all of its files (src/lake/Lake/Build/Module.lean:1313).
Context
Found during a review of how Lake writes into its cache while working on the new .ilean design. Since #16737, Lean reports a truncated .olean as "unexpected end of file". Before #16737, the reader could read past the end of its buffer.
Steps to Reproduce
The scripts need Linux and lake on PATH.
Problem 1: two builds at the same time, with the cache on the same file system.
cd "$(mktemp -d)" && mkdir -p proj/Proj && cd proj
export LAKE_CACHE_DIR="$PWD/../cache" # same file system as the project
printf 'name = "proj"\ndefaultTargets = ["Proj"]\n[[lean_lib]]\nname = "Proj"\n' > lakefile.toml
: > Proj.lean
for i in $(seq 0 299); do
echo "def m$i : Nat := $i" > Proj/M$i.lean
echo "import Proj.M$i" >> Proj.lean
done
LAKE_ARTIFACT_CACHE=true lake build > /dev/null # fill the cache
# (a) Read-only cache entries (as `saveArtifact` leaves them)
rm -rf .lake/build
lake build -v > ../a1.txt 2>&1 & lake build -v > ../a2.txt 2>&1 & wait
grep -h -m1 "could not hard link" ../a1.txt ../a2.txt
grep -h -m1 -A1 "permission denied" ../a1.txt ../a2.txt
tail -n1 ../a1.txt ../a2.txt
# (b) Writable cache entries (as `lake cache get` leaves them)
chmod u+w ../cache/artifacts/*
rm -rf .lake/build
touch ../marker
lake build -v > ../b1.txt 2>&1 & lake build -v > ../b2.txt 2>&1 & wait
tail -n1 ../b1.txt ../b2.txt
echo "cache entries rewritten in place: $(find ../cache/artifacts -type f -newer ../marker | wc -l)"
Problem 2: the cache is on another file system, and a copy stopped part-way (simulated).
cd "$(mktemp -d)" && mkdir -p Proj
export LAKE_CACHE_DIR=/dev/shm/lake-cache-repro # another file system: hard links fail
printf 'name = "proj"\ndefaultTargets = ["Proj"]\n[[lean_lib]]\nname = "Proj"\n' > lakefile.toml
echo 'import Proj.B' > Proj.lean
echo 'def a : Nat := 1' > Proj/A.lean
printf 'import Proj.A\ndef b : Nat := a + 1\n' > Proj/B.lean
LAKE_ARTIFACT_CACHE=true lake build > /dev/null # fill the cache
rm -rf .lake/build
lake build -v 2>&1 | grep -m1 "could not hard link" # the restore copies
# Simulate a copy that stopped part-way (Ctrl-C, kill, full disk).
# The copy writes the `.hash` file only at the end.
f=.lake/build/lib/lean/Proj/A.olean
chmod u+w $f && truncate -s 4096 $f && rm $f.hash
lake build
lake build
ls -l $f
Expected behavior:
- Two builds at the same time both succeed, and neither build writes into an existing cache entry.
- After a copy that stopped part-way, there is no file at the final path, or the next run restores the file again.
Actual behavior:
- Problem 1 (a): both builds fail. Each failure has this log:
In 10 runs, each run had 95–149 of these collisions.trace: could not hard link artifact, copying from cache instead; error: already exists (error code: 17, file already exists) file: <tmp>/cache/artifacts/8b138d844a320bd4.olean error: permission denied (error code: 13) file: <tmp>/proj/.lake/build/lib/lean/Proj/M3.olean - Problem 1 (b): both builds succeed, but each run rewrote 130–165 cache entries in place (same inode, new mtime). In a separate test with the same IO calls, a 256 MB cache file dropped to 0 bytes and then grew back during the copy.
- Problem 2: each later
lake buildfails with the error that follows, andA.oleanstays 4096 bytes:error: Proj/B.lean:1:0: failed to read '<tmp>/.lake/build/lib/lean/Proj/A.olean': unexpected end of file
Versions
Lean (version 4.38.0-pre, x86_64-unknown-linux-gnu, commit 80362eeeada9, Release), a master build of 2026-11-28.
Linux 7.3. The project and the cache are on xfs. The cache for problem 2 is on tmpfs.
Line numbers refer to master at 48fb9df5. This code did not change between the two commits.
Additional Information
Suggested fix:
- In
restoreArtifact, treatalreadyExistsfromhardLinkas success, assaveArtifactdoes. This change alone fixes problem 1. - Make the copies atomic: write a temporary file in the target directory, then rename it.
createExtraPathsandunstagecan usewriteBinFileAtomicIfNew, which already writes into the same directory.- For
restoreArtifact,writeBinFileAtomicIfNewhas a risk. It needsflockandIO.FS.renameIfNew, which isrenameat2(RENAME_NOREPLACE)with no fallback (src/runtime/io.cpp:1290,src/lake/Lake/Util/IO.lean:51). - The copy fallback mostly writes to other file systems. As far as I know, NFS and 9p reject
RENAME_NOREPLACEwithEINVAL. I did not test this. - A plain
IO.FS.renameis sufficient forrestoreArtifact, because the hash fixes the content. If the rename fails and the target exists, another process was first.
- With atomic copies, a stopped restore leaves a missing file. Lake already restores missing files, so the trace write can stay before the restore.
The fix does not repair files that are already truncated.
Related, with less effect: Lake also writes two kinds of metadata files in the cache in place. These are outputs/<scope>/<hash>.json (writeOutputsCore, src/lake/Lake/Config/Cache.lean:464) and revisions/<scope>/<rev>.jsonl (downloadRevisionOutputs?, src/lake/Lake/Config/Cache.lean:1312). A truncated file gives a cache miss or a parse error. CacheMap.load takes a shared lock, but downloadRevisionOutputs? writes without a lock.
Also related: #16407 (stale .olean.hash files after an .ltar restore).
Impact
Add 👍 to issues you consider important. If others are impacted by this issue, please ask them to add 👍 to it.
- Dominant language
- Lean
- Stars
- 10.5k
- Forks
- 1.2k
- Avg merge
- 19h 36m
- Merged PRs (30d)
- 323
Getting set up
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from leanprover/lean4
-
P-medium
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
leanprover/lean4#16958 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
leanprover/lean4#16897 ·
Maintainers usually reply within 1 day
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
leanprover/lean4#16892 ·
Maintainers usually reply within 1 day
-
Difficulty 1/5 1-3 hours Newbie friendliness 86/100
leanprover/lean4#16886 · 1 comment ·
Maintainers usually reply within 1 day
-
bug
Difficulty 1/5 Under an hour Newbie friendliness 78/100
leanprover/lean4#16820 ·
Maintainers usually reply within 1 day
All issues in leanprover/lean4
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
bazelbuild/apple_support#707 ·
Maintainers usually reply within 1 day
-
Difficulty 1/5 Under an hour Newbie friendliness 92/100
-
out-of-date
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
CachyOS/CachyOS-PKGBUILDS#2232 ·
Maintainers usually reply within 1 day
-
blast/large refactor risk/low spend-dem
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
chriskelly/MusicWall#87 · 2 comments ·
Maintainers usually reply within 1 day
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
neilotoole/sq#1503 ·
Maintainers usually reply within 1 day