Lake 4.36 build graph can stall behind compiler jobs while reading import headers and checking warm artifacts

Aperta
#16,873 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à
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
25/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
bash, c

Direzione di ricerca

Start with src/lake/Lake/Build/Module.lean, especially the input and elaboration artifact paths, and trace how they share the job queue with compiler work; then read the cited job scheduling code in src/lake/Lake/Build/Job/Monad.lean and src/runtime/object.cpp. Reproduce with the included reproduce.sh on Lean 4.36.0 and compare queue residence for source inputs and warm checks. Done means lightweight work can progress under compiler load while misses use ordinary build execution, with dependency, cancellation, cache, and failure behavior preserved.

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

Descrizione

In Lean and Lake 4.36.0, a build that mixes cold local modules with prebuilt dependencies can spend most of graph construction waiting for source-header jobs to get a worker. Warm artifact checks can face the same queue delay. Lake needs those small jobs to discover dependencies and publish results that unlock further work. They share the ordinary worker queue with jobs that run Lean compiler subprocesses. Lean 4.36.0 source revision

Where the build stalls

  1. The build CLI calls Workspace.runBuild (buildSpecs specs). Workspace.startBuild runs the graph-construction closure in one default-priority Job.async. buildSpecs fetches targets in order with specs.mapM. A library first collects its modules, then folds over them to fetch their irArts jobs. Previously fetched jobs can already be running while graph construction continues. CLI entry · Build/Run.lean · CLI/Build.lean · Build/Library.lean
  2. Library collection waits for root.imports at Library.lean:54. importInfoFacetConfig awaits mod.header at Module.lean:509. Both facets consume the memoized input job via synchronous continuations. Module.recFetchInput uses a default-priority Job.async to read and hash the source, parse its imports, and resolve module names. An already queued compiler job can therefore delay a later input job that the graph builder is waiting on. Library imports wait · Input, header and imports facets · Header wait
  3. recBuildElabArts uses a default-priority presetupJob.mapM. Its callback runs fetchCore, which checks traces and artifacts and can call buildLean on a miss. buildLean invokes compileLeanModule, whose rawProc call waits for the compiler's output. A cache hit and a full compilation therefore enter the same queue at the same priority. A warm irArts continuation can also queue before the result is available to metaExportInfo. Elaboration callback · Cache checks and rebuild branches · Compiler call · Compiler process · Process output · IR and export continuations · Meta export
  4. The default task priority is 0. The runtime takes the highest nonempty ordinary priority queue and consumes it FIFO within that priority. Job.wait goes through IO.wait to the task wait. When an ordinary task really blocks, wait_for temporarily increases the ordinary-worker limit. The extra worker still takes the next job under the same queue rules. Default priority · Job defaults and waits · Job.mapM · IO.wait · Queue rules · Task.get · Worker compensation

Measurements

I observed this while building the Physlib and QuantumInfo library targets in that order, on eight physical cores with Lean subprocesses using -j2. The checkout was Physlib 63250d48dc796f669f04043fcd5c2a1ce36e12e4 with Mathlib fc4f59e577feb1a4956671bc04ac18aaaf8cd842 and prebuilt external dependencies. The instrumented SDK was built from the 4.36.0 revision using the release Stage 2 recipe. The instrumentation recorded the requesting task, the task passed to wait_for, the source call site, queue insertion, worker pickup, and result publication.

The targeted capture closed 657,249 Lake events with zero unresolved task generations. The graph-construction job attached all 781 local module elaboration jobs. It blocked 5,212 times for 413.159518 s of its 415.095936 s lifetime (99.53%).

Await site Calls Blocking calls Blocked wall time Overlap with source input queue time Overlap with source input callback time
Module.lean:509, module header 5,238 4,429 341.680041 s 340.170826 s 0.771602 s
Library.lean:54, library member imports 781 780 71.478121 s 71.318134 s 0.127850 s

A further three waits on library extra dependencies account for about 1.36 ms. The two rows follow the awaited tasks back to their source input jobs. In total, graph-construction waits overlapped 411.488960 s of those jobs' queue residence and 0.899452 s of their callback execution. These are overlaps with the graph job's waiting intervals. The targeted build exited with code 1 after two compiler attempts encountered a PID-reuse filename collision in the trace collector. The graph scope and wait intervals closed. One failed attempt occurred during graph construction and may have changed queue contention. The earlier successful build supplies the warm-check timings below.

A separate successful build of the same targets captured 781 successful local compiler leaves. All 21,055 recorded ordinary-queue pickups obeyed priority-0 FIFO order. Five warm Mathlib elabArts callbacks waited 2.154–11.335 s between enqueue and worker pickup, then ran for 0.321–0.388 ms each, with no compiler fork for those modules. For Rpow.IntegralRepresentation and Rpow.Order, the delays were 10.141 s and 11.335 s. Seven local compiler callbacks took a worker ahead of each of them while it was queued. The targeted capture and the successful build are separate observations.

This is head-of-line blocking with a dependency-level priority inversion. A runnable input needed by the sole graph-construction job waits behind work that graph construction has already exposed. A ready cache check can likewise delay the release of a downstream compiler even though its own work takes less than a millisecond. Both effects follow from the execution queue and the dependency waits. They can occur with the existing target order and do not require a particular critical-path policy.

Expected behavior and suggested fix

Give lightweight source inputs and ready trace or artifact checks a bounded execution path that can make progress while ordinary workers are occupied by compiler jobs. Within recBuildElabArts, make the validation path hand a genuine miss off to ordinary build execution before calling buildLean. Raising the priority of the existing mapM callback as a whole would also promote cold compiles. Archive unpacking and other potentially long restore work need the same scrutiny when defining the lightweight path.

Keep the single graph builder, target visitation order, cycle checks, and BuildKey memoization. A facet should still publish only once its existing prerequisites and cache, restore, or build work have completed. Keep trace validation, failure propagation, and cancellation semantics. A candidate fix can be checked by measuring input and warm-check queue residence in the same workload, verifying zero external compiler launches for prebuilt dependencies, and comparing the generated artifacts and failure behavior.

Reproduction notes

At the revisions above, use the locked, prebuilt external dependencies and an empty local build output directory. Bind the build to eight physical cores and run LEAN_NUM_THREADS=8 LAKE_ARTIFACT_CACHE=false LAKE_NO_CACHE=true lake --offline --no-cache build Physlib QuantumInfo with -j2 in the local Lean compiler arguments. Check that the warm dependencies never invoke the compiler. A task trace that joins each real graph wait to the awaited task and its source input can distinguish worker-queue time from header parsing time. For warm checks, compare enqueue-to-worker time with time inside the callback.

The self-contained dependency-free reproduction below was verified on Linux against the unmodified official Lean 4.36.0 release. It builds four warm modules in a bundled path dependency, keeps the second library's root cold, and builds two local libraries in both target orders. Independent compilations in the first library each sleep during elaboration so that they occupy the two workers for long enough to see the queue delay. Run the script from the reproduction directory with Bash and a C compiler.

./reproduce.sh /absolute/path/to/lean-4.36.0-linux /tmp/lake-scheduling-repro

Both builds exited 0 with zero compiler forks for WarmDep. Times below are relative to the first source read of Mixed.lean in each build.

Target order First Slow compiler fork First Slow compiler reap First warm trace read
Slow Mixed −1776.096 ms −1.103 ms +8850.294 ms
Mixed Slow +6.439 ms +1778.699 ms +1.194 ms

With Slow first, two long compiler callbacks started before Lake read Mixed.lean. The first callback to finish and that source read were on the same worker thread, 1.103 ms apart. With Mixed first, Lake read the warm trace before it started the first Slow compiler. The source reads, trace reads, and parent-side fork and reap timestamps come from Linux libc calls in the official Lake process. Running ./reproduce.sh writes the raw timestamped .tsv records and .log files into the run directory.

Minimal dependency-free reproduction files (Linux, official Lean 4.36.0)

lean-toolchain:

leanprover/lean4:v4.36.0

lakefile.toml:

name = "scheduleRepro"
moreLeanArgs = ["-j1"]

[[lean_lib]]
name = "Slow"
globs = ["Slow.*"]

[[lean_lib]]
name = "Mixed"

[[require]]
name = "WarmDep"
path = "WarmDep"

WarmDep/lakefile.toml:

name = "WarmDep"
moreLeanArgs = ["-j1"]

[[lean_lib]]
name = "Warm"
globs = ["Warm.*"]

observe.c:

#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

static pid_t lake_pid;
static int (*open_file)(const char *, int, ...);
static pid_t (*spawn_child)(void);
static pid_t (*wait_child)(pid_t, int *, int);
static _Thread_local char setup[512];

__attribute__((constructor))
static void init(void) {
    const char *pid = getenv("REPRO_LAKE_PID");
    lake_pid = pid ? (pid_t)strtol(pid, NULL, 10) : 0;
    open_file = dlsym(RTLD_NEXT, "open");
    spawn_child = dlsym(RTLD_NEXT, "fork");
    wait_child = dlsym(RTLD_NEXT, "waitpid");
}

static int observing(void) { return getpid() == lake_pid; }

static void event(const char *kind, const char *path, pid_t child) {
    int saved = errno;
    struct timespec now;
    clock_gettime(CLOCK_MONOTONIC, &now);
    char line[1024];
    int n = snprintf(line, sizeof line, "%lld\t%ld\t%s\t%d\t%s\n",
        (long long)now.tv_sec * 1000000000 + now.tv_nsec,
        syscall(SYS_gettid), kind, child, path);
    if (n > 0 && n < (int)sizeof line) {
        ssize_t written = write(9, line, (size_t)n);
        (void)written;
    }
    errno = saved;
}

static void observe_path(const char *path, int flags) {
    if (!observing()) return;
    if ((flags & O_ACCMODE) == O_RDONLY) {
        if (strstr(path, "/Mixed.lean") || !strcmp(path, "Mixed.lean"))
            event("mixed-header", path, 0);
        if (strstr(path, "/Warm/") && strstr(path, ".trace") && !strstr(path, ".trace.nobuild"))
            event("warm-trace-read", path, 0);
    }
    if ((flags & O_ACCMODE) != O_RDONLY && strstr(path, ".setup.json"))
        snprintf(setup, sizeof setup, "%s", path);
}

int open(const char *path, int flags, ...) {
    observe_path(path, flags);
    if ((flags & O_CREAT) || (flags & O_TMPFILE) == O_TMPFILE) {
        va_list args;
        va_start(args, flags);
        mode_t mode = va_arg(args, mode_t);
        va_end(args);
        return open_file(path, flags, mode);
    }
    return open_file(path, flags);
}

pid_t fork(void) {
    pid_t pid = spawn_child();
    if (pid > 0 && observing()) event("fork", setup, pid);
    return pid;
}

pid_t waitpid(pid_t pid, int *status, int flags) {
    pid_t result = wait_child(pid, status, flags);
    if (result > 0 && observing()) event("reap", setup, result);
    return result;
}

reproduce.sh:

#!/usr/bin/env bash
set -euo pipefail
if [[ $# != 2 ]]; then
  echo 'usage: ./reproduce.sh /absolute/path/to/lean-4.36.0-linux /path/to/new-run' >&2
  exit 2
fi
fixture=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
sdk=$(cd -- "$1" && pwd)
mkdir -- "$2"
run=$(cd -- "$2" && pwd)
[[ $("$sdk/bin/lean" --githash) == 611c117bfaf7b7ae1cfcf246ce6fba31e8f509e9 ]]
unset LEAN_PATH LEAN_SRC_PATH LEAN_SYSROOT LAKE_HOME
export LEAN_NUM_THREADS=2 LAKE_ARTIFACT_CACHE=false LAKE_NO_CACHE=true LAKE_CACHE_DIR="$run/cache"
cp "$fixture/lakefile.toml" "$fixture/lean-toolchain" "$run/"
mkdir "$run/Slow" "$run/WarmDep" "$run/WarmDep/Warm"
cp "$fixture/WarmDep/lakefile.toml" "$run/WarmDep/"
cd -- "$run"
printf 'module\n\n#eval IO.sleep %s\n' "${REPRO_SLEEP_MS:-1500}" > Slow.lean
printf 'module\n' > WarmDep/Warm.lean
for i in {01..12}; do
  printf 'module\n\n#eval IO.sleep %s\n\npublic def slow%s : Nat := %d\n'     "${REPRO_SLEEP_MS:-1500}" "$i" "$((10#$i))" > "Slow/Leaf$i.lean"
done
previous=
for i in {01..04}; do
  {
    printf 'module\n'
    if [[ -n "$previous" ]]; then printf 'public import Warm.Step%s\n' "$previous"; fi
    printf '\npublic def warm%s : Nat := %d\n' "$i" "$((10#$i))"
  } > "WarmDep/Warm/Step$i.lean"
  previous=$i
done
cat > Mixed.lean <<'LEAN'
module
public import Warm.Step04

public def mixed : Nat := warm01 + warm02 + warm03 + warm04
LEAN
cc -O2 -std=c11 -Wall -Wextra -fPIC -shared "$fixture/observe.c" -ldl -o "$run/observe.so"
"$sdk/bin/lake" --offline --no-cache update > update.log 2>&1
"$sdk/bin/lake" --offline --no-cache build Warm > warm.log 2>&1
observe() {
  local label=$1
  shift
  (
    export REPRO_LAKE_PID="$BASHPID"
    export LD_PRELOAD="$run/observe.so"
    exec "$sdk/bin/lake" --offline --no-cache build "$@"
  ) 9>"$run/$label.tsv" >"$run/$label.log" 2>&1
}
observe slow-first Slow Mixed
mv .lake/build .lake/slow-first
observe mixed-first Mixed Slow

for arm in slow-first mixed-first; do
  awk -F '\t' '
    $3 == "fork" && $5 ~ /\/Slow(\/|\.setup\.json)/ && !first { first = $1 }
    $3 == "reap" && $5 ~ /\/Slow(\/|\.setup\.json)/ && !reap { reap = $1 }
    $3 == "mixed-header" && !header { header = $1 }
    $3 == "warm-trace-read" && !warm { warm = $1 }
    $3 == "fork" && $5 ~ /\/Warm\// { ++warmForks }
    END {
        if (!first || !header || !warm || !reap || warmForks) exit 1
        printf "%s | first Slow fork %+8.3f ms | first Slow reap %+8.3f ms | first Warm trace %+8.3f ms | Warm forks %d\n",
            FILENAME, (first-header)/1e6, (reap-header)/1e6, (warm-header)/1e6, warmForks
    }' "$arm.tsv"
done
Lingua principale
Lean
Stelle
10.3k
Fork
1.1k
Merge medio
16h 45m
PR unite (30g)
361

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.