Rollup merge of #162240 - charliermarsh:charlie/incremental-session-gc, r=bjorn3

Garbage-collect old incremental compilation sessions

## Summary

rustc cleans up old incremental-cache snapshots twice during a compilation: once at startup (after loading the previous cache), and then again after finishing and finalizing the new cache.

In rust-lang/rust#147821, we started skipping the current session during cleanup. But that means we're also skipping cleanup _after_ the session has finished, so we're keeping _both_ the previous and the completed snapshot on disk. (The snapshots don't accumulate indefinitely -- the "extra" snapshot gets removed when the next compilation starts, but that compilation then leaves another snapshot behind when it finishes.)

This PR modifies the logic to skip the current session while it is still active, but remove it once finalized.

Testing it locally for [Ruff](https://github.com/astral-sh/ruff) and [uv](https://github.com/astral-sh/uv), the target directory shrinks significantly... The query caches are almost exactly 50% smaller, and `target` as a whole is 27.3% smaller in Ruff and 31.1% smaller in uv.
This commit is contained in:
Jonathan Brouwer
2026-09-14 15:15:56 +02:00
committed by GitHub
3 changed files with 81 additions and 23 deletions

View File

@@ -702,29 +702,6 @@ pub(crate) fn garbage_collect_session_directories(
lock_file_to_session_dir.items().filter_map(|(lock_file_name, directory_name)| {
debug!("garbage_collect_session_directories() - inspecting: {}", directory_name);
if directory_name.as_str() == current_session_directory_name {
// Skipping our own directory is, unfortunately, important for correctness.
//
// To summarize #147821: we will try to lock directories before deciding they can be
// garbage collected, but the ability of `flock::Lock` to detect a lock held *by the
// same process* varies across file locking APIs. Then, if our own session directory
// has become old enough to be eligible for GC, we are beholden to platform-specific
// details about detecting the our own lock on the session directory.
//
// POSIX `fcntl(F_SETLK)`-style file locks are maintained across a process. On
// systems where this is the mechanism for `flock::Lock`, there is no way to
// discover if an `flock::Lock` has been created in the same process on the same
// file. Attempting to set a lock on the lockfile again will succeed, even if the
// lock was set by another thread, on another file descriptor. Then we would
// garbage collect our own live directory, unable to tell it was locked perhaps by
// this same thread.
//
// It's not clear that `flock::Lock` can be fixed for this in general, and our own
// incremental session directory is the only one which this process may own, so skip
// it here and avoid the problem. We know it's not garbage anyway: we're using it.
return None;
}
let Ok(timestamp) = extract_timestamp_from_session_dir(directory_name) else {
debug!(
"found session-dir with malformed timestamp: {}",
@@ -768,6 +745,31 @@ pub(crate) fn garbage_collect_session_directories(
}
}
} else if is_old_enough_to_be_collected(timestamp) {
if directory_name.as_str() == current_session_directory_name {
// Skipping our own active directory is important for correctness.
//
// To summarize #147821: we will try to lock directories before deciding they can be
// garbage collected, but the ability of `flock::Lock` to detect a lock held *by the
// same process* varies across file locking APIs. Then, if our own session directory
// has become old enough to be eligible for GC, we are beholden to platform-specific
// details about detecting the our own lock on the session directory.
//
// POSIX `fcntl(F_SETLK)`-style file locks are maintained across a process. On
// systems where this is the mechanism for `flock::Lock`, there is no way to
// discover if an `flock::Lock` has been created in the same process on the same
// file. Attempting to set a lock on the lockfile again will succeed, even if the
// lock was set by another thread, on another file descriptor. Then we would
// garbage collect our own live directory, unable to tell it was locked perhaps by
// this same thread.
//
// It's not clear that `flock::Lock` can be fixed for this in general, and our own
// incremental session directory is the only one which this process may own, so skip
// it here and avoid the problem. We know it's not garbage anyway: we're using it.
// Once finalized, its lock is released. Include it in collection so we keep
// the newest completed session.
return None;
}
// When cleaning out "-working" session directories, i.e.
// session directories that might still be in use by another
// compiler instance, we only look a directories that are
@@ -818,6 +820,10 @@ pub(crate) fn garbage_collect_session_directories(
// Delete all but the most recent of the candidates
all_except_most_recent(deletion_candidates).into_items().all(|(path, lock)| {
if path.file_name() == Some(current_session_directory_name) {
return true;
}
debug!("garbage_collect_session_directories() - deleting `{}`", path.display());
if let Err(err) = std_fs::remove_dir_all(&path) {

View File

@@ -0,0 +1,2 @@
#![feature(no_core)]
#![no_core]

View File

@@ -0,0 +1,50 @@
//! Successful sequential builds should retain only the newest incremental session.
//! The current session must participate in garbage collection once it is finalized.
use std::path::PathBuf;
use run_make_support::{rfs, rustc, shallow_find_directories};
fn main() {
let compile = || {
rustc().input("empty.rs").crate_type("rlib").emit("metadata").incremental("incr").run();
};
compile();
let mut previous = session_dir();
rfs::write(previous.join("sentinel"), "previous session");
for _ in 0..2 {
compile();
let current = session_dir();
assert_ne!(previous, current);
assert!(!previous.exists(), "superseded session was not collected: {previous:?}");
assert_eq!(rfs::read_to_string(current.join("sentinel")), "previous session");
previous = current;
}
let crate_dir = previous.parent().unwrap();
let (prefix, hash) = previous.file_name().unwrap().to_str().unwrap().rsplit_once('-').unwrap();
let newer = crate_dir.join(format!("s-zzzzzzzzzz-0000000-{hash}"));
rfs::rename(&previous, &newer);
rfs::rename(
crate_dir.join(format!("{prefix}.lock")),
crate_dir.join("s-zzzzzzzzzz-0000000.lock"),
);
compile();
let sessions = shallow_find_directories(crate_dir, |_| true);
assert_eq!(sessions.len(), 2, "{sessions:?}");
assert!(sessions.contains(&newer));
let current = sessions.into_iter().find(|session| *session != newer).unwrap();
assert!(!current.file_name().unwrap().to_str().unwrap().ends_with("-working"));
assert_eq!(rfs::read_to_string(current.join("sentinel")), "previous session");
}
fn session_dir() -> PathBuf {
let crate_dirs = shallow_find_directories("incr", |_| true);
assert_eq!(crate_dirs.len(), 1);
let sessions = shallow_find_directories(&crate_dirs[0], |_| true);
assert_eq!(sessions.len(), 1, "expected only the newest completed session: {sessions:?}");
sessions.into_iter().next().unwrap()
}