Lake: concurrent restores rewrite cache entries in place, and artifact copies are not atomic

Aperta
#16,924 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
48/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Ambito
build-system

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

bug P-high
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. saveArtifact and resolveArtifact make 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, createExtraPaths and lake cache unstage are 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:

  • createExtraPaths in lake 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:
    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
    
    In 10 runs, each run had 95–149 of these collisions.
  • 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 build fails with the error that follows, and A.olean stays 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:

  1. In restoreArtifact, treat alreadyExists from hardLink as success, as saveArtifact does. This change alone fixes problem 1.
  2. Make the copies atomic: write a temporary file in the target directory, then rename it.
    • createExtraPaths and unstage can use writeBinFileAtomicIfNew, which already writes into the same directory.
    • For restoreArtifact, writeBinFileAtomicIfNew has a risk. It needs flock and IO.FS.renameIfNew, which is renameat2(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_NOREPLACE with EINVAL. I did not test this.
    • A plain IO.FS.rename is sufficient for restoreArtifact, because the hash fixes the content. If the rename fails and the target exists, another process was first.
  3. 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.

Lingua principale
Lean
Stelle
10.5k
Fork
1.2k
Merge medio
19h 36m
PR unite (30g)
323

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di leanprover/lean4

Tutte le issue di leanprover/lean4

Issue simili

Altre issue su Build System

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.