fix(vcs): stop retrying stale git worktrees (#6794)

A failed reopen of a repository never updated the cache stamp, so every gix() call reopened it again and logged a warning, and status fell back to running git in a worktree folder that no longer existed (os error 267 on Windows). The stamp is now updated on failure too, and a repository whose worktree or git directory is missing is skipped by status, ignored-files and path status, logged once, and picked up again when both directories are back.

Fixes #5514

Co-authored-by: arookieofc <[email protected]>
Цей коміт міститься в:
arookieofcтаarookieofc authored and GitHub committed 2026-11-29 21:56:58 +08:00
1 джерело 13cd8ba006
коміт bd0455bda5
4 files changed
+147 -10

No files matched your search

+6
Переглянути файл
@@ -1143,6 +1143,8 @@ pub struct Repo {
ignored: std::sync::RwLock<IgnoredNames>,
/// Working-tree status from `git status` instead of gitoxide.
cli_status: std::sync::atomic::AtomicBool,
/// Set once the worktree or its git directory is no longer valid so callers stop retrying it.
stale: std::sync::atomic::AtomicBool,
automatic_shelf: std::sync::RwLock<Option<shelf::AutomaticShelf>>,
log_index: std::sync::Mutex<log_index::LogIndex>,
ref_decorations: std::sync::Mutex<ref_decorations::RefDecorations>,
@@ -1175,6 +1177,10 @@ impl Repo {
let _scope = self.execution_scope();
&self.root
}
/// Whether this repository's worktree or git directory has been detected as missing/invalid.
pub fn is_stale(&self) -> bool {
self.stale.load(std::sync::atomic::Ordering::Acquire)
}
/// git's own folders for this worktree: its git dir and the common one (they differ for a
/// linked worktree, whose `.git` file points into the main repository).
pub fn metadata_dirs(&self) -> IdeResult<[PathBuf; 2]> {
+34 -1
Переглянути файл
@@ -86,6 +86,7 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
inner: std::sync::Mutex::new(cache),
ignored: Default::default(),
cli_status: Default::default(),
stale: std::sync::atomic::AtomicBool::new(false),
automatic_shelf: Default::default(),
log_index: Default::default(),
ref_decorations: Default::default(),
@@ -113,10 +114,36 @@ pub(crate) fn absolute(p: &Path) -> IdeResult<PathBuf> {
}
impl Repo {
pub(crate) fn stale_error(&self) -> IdeError {
IdeError::unavailable(format!("git repository is no longer valid: {}", self.root.display()))
}
/// Verifies that the worktree root and its git directory exist on disk. A missing one marks
/// the repository stale and is logged once; when both are back (a drive reconnected, `git
/// worktree repair`), the mark is cleared, so a stale repository costs two `stat`s per check.
pub(crate) fn check_valid(&self) -> IdeResult<()> {
use std::sync::atomic::Ordering;
if self.root.is_dir() && self.git_dir.is_dir() {
if self.stale.swap(false, Ordering::AcqRel) {
tracing::info!("git repository is valid again: {}", self.root.display());
}
return Ok(());
}
if !self.stale.swap(true, Ordering::AcqRel) {
tracing::warn!(
"git repository is no longer valid, skipping it until it is back: worktree {}, git dir {}",
self.root.display(),
self.git_dir.display()
);
}
Err(self.stale_error())
}
/// A thread-local gitoxide handle; reopened when configuration or packed refs change.
/// gitoxide's packed-ref snapshot only reloads for a newer mtime, which a replacement may preserve.
pub(crate) fn gix(&self) -> IdeResult<gix::Repository> {
let _scope = self.execution_scope();
self.check_valid()?;
if !self.execution_allowed.load(std::sync::atomic::Ordering::Acquire) {
return gix::open_opts(&self.git_dir, gix::open::Options::default().filter_config_section(|_| false))
.map_err(gx);
@@ -131,7 +158,13 @@ impl Repo {
cache.stamp = now;
cache.pack_stamp = pack_now;
}
Err(e) => tracing::warn!("reopening repository failed: {e}"),
Err(e) => {
// Retried on the next change, not on every call (which flooded the log).
cache.stamp = now;
cache.pack_stamp = pack_now;
self.check_valid()?;
tracing::warn!("reopening repository failed: {e}");
}
}
}
let mut repo = cache.repo.to_thread_local();
+101 -9
Переглянути файл
@@ -277,6 +277,10 @@ impl Repos {
let mut first_error = None;
let mut read = 0;
for (repo, mine) in groups {
// A worktree deleted under the project: skipped (logged once) until it is back.
if repo.check_valid().is_err() {
continue;
}
let nested: Vec<&Path> = self
.repos
.iter()
@@ -336,6 +340,16 @@ mod tests {
assert!(ok, "git init in {}", dir.display());
}
fn git(dir: &Path, args: &[&str]) {
let ok = Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
.args(args)
.current_dir(dir)
.status()
.is_ok_and(|s| s.success());
assert!(ok, "git {args:?}");
}
#[test]
fn ignored_files_use_git_rules_without_listing_other_repositories_twice() {
let tmp = tempfile::tempdir().unwrap();
@@ -493,15 +507,6 @@ mod tests {
git_init(&root);
std::fs::create_dir_all(root.join("web")).unwrap();
std::fs::write(root.join("web/page.html"), "v1").unwrap();
let git = |dir: &Path, args: &[&str]| {
let ok = Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
.args(args)
.current_dir(dir)
.status()
.is_ok_and(|s| s.success());
assert!(ok, "git {args:?}");
};
git(&root, &["add", "."]);
git(&root, &["commit", "-qm", "init"]);
git_init(&root.join("web"));
@@ -528,4 +533,91 @@ mod tests {
assert_eq!(repos.primary().unwrap().root(), root.join("a"), "the first when none contains the project root");
assert!(repos.for_path(&root.join("c.txt")).is_none());
}
#[test]
fn stale_worktree_is_marked_stale_and_skipped_on_subsequent_refreshes() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
git_init(&root);
std::fs::write(root.join("README.md"), "hello\n").unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-qm", "init"]);
let wt = root.join("wt").join("mod").join("stale-wt");
git(&root, &["worktree", "add", "-q", "-b", "stale-wt", wt.to_str().unwrap()]);
let repos = Repos::discover(&root, &|_| false).unwrap();
assert_eq!(repos.all().len(), 2);
for r in repos.all() {
r.set_execution_allowed(true);
assert!(!r.is_stale());
}
let wt_repo = repos.at_root(&wt).unwrap().clone();
let main_repo = repos.at_root(&root).unwrap().clone();
// Move the worktree's git metadata dir away (a stale worktree, #5514).
let wt_git_dir = wt_repo.metadata_dirs().unwrap()[0].clone();
let moved = wt_git_dir.with_extension("moved");
std::fs::rename(&wt_git_dir, &moved).unwrap();
std::fs::write(root.join("dirty.txt"), "changed\n").unwrap();
// First status refresh detects the stale worktree, marks it stale, and still returns healthy repo changes.
let status = repos.status().unwrap();
assert!(wt_repo.is_stale(), "stale worktree must be marked stale after first failed refresh");
assert!(!main_repo.is_stale(), "healthy enclosing repo must stay active");
assert!(status.iter().any(|f| f.rel_path == "dirty.txt"), "{status:?}");
// Subsequent refreshes must skip the stale worktree without invoking its status callback again.
let called_roots = std::cell::RefCell::new(Vec::new());
let second = repos
.read_status(repos.all_status_groups(), |r, _| {
called_roots.borrow_mut().push(r.root().to_path_buf());
(r as &dyn Backend).status()
})
.unwrap();
assert_eq!(called_roots.into_inner(), vec![root.clone()], "stale worktree must not be retried");
assert!(second.iter().any(|f| f.rel_path == "dirty.txt"), "{second:?}");
// Querying paths solely inside the stale worktree also degrades cleanly without erroring or retrying.
let wt_paths = repos.status_paths(&[wt.join("README.md")]).unwrap();
assert!(wt_paths.is_empty());
// Once the metadata is back (`git worktree repair`, a drive reconnected), the worktree is read again.
std::fs::rename(&moved, &wt_git_dir).unwrap();
std::fs::write(wt.join("wt-dirty.txt"), "changed\n").unwrap();
let called_roots = std::cell::RefCell::new(Vec::new());
let third = repos
.read_status(repos.all_status_groups(), |r, _| {
called_roots.borrow_mut().push(r.root().to_path_buf());
(r as &dyn Backend).status()
})
.unwrap();
assert!(!wt_repo.is_stale(), "a restored worktree is no longer stale");
assert_eq!(called_roots.into_inner(), vec![root.clone(), wt.clone()]);
assert!(third.iter().any(|f| f.rel_path.ends_with("wt-dirty.txt")), "{third:?}");
}
#[test]
fn stale_worktree_directory_deletion_stops_reopening() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
git_init(&root);
std::fs::write(root.join("a.txt"), "1\n").unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-qm", "init"]);
let wt = root.join("wt-gone");
git(&root, &["worktree", "add", "-q", "-b", "wt-gone", wt.to_str().unwrap()]);
let wt_repo = Repo::discover(&wt).unwrap().unwrap();
wt_repo.set_execution_allowed(true);
assert!(wt_repo.head().is_ok());
assert!(!wt_repo.is_stale());
// Delete the worktree directory itself (triggers Windows os error 267 if git CLI is spawned there).
std::fs::remove_dir_all(&wt).unwrap();
assert!(wt_repo.head().is_err());
assert!(wt_repo.is_stale());
assert!(wt_repo.status().is_err());
assert!(wt_repo.ignored_files().is_err());
}
}
+6
Переглянути файл
@@ -17,6 +17,7 @@ struct Entry {
}
pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
r.check_valid()?;
let ignored = r.ignored.read().unwrap_or_else(|p| p.into_inner()).clone();
// gitoxide stops at the first IO error (a directory it may not read), where git warns
// and lists the rest: git answers then.
@@ -24,6 +25,9 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
cli_status(r, &ignored)?
} else {
gix_status(r, &ignored).or_else(|e| {
if r.is_stale() {
return Err(e);
}
tracing::debug!("status via gitoxide failed, asking git: {}", e.message);
cli_status(r, &ignored)
})?
@@ -33,6 +37,7 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
/// Git-ignored working-tree entries, with ignored directories reported as one entry each.
pub(crate) fn ignored_files(r: &Repo) -> IdeResult<Vec<FileStatus>> {
r.check_valid()?;
let ignored = r.ignored.read().unwrap_or_else(|p| p.into_inner()).clone();
let overrides = crate::cli::filter_overrides(r.root(), &ide_core::CancellationToken::new())?;
let mut args: Vec<&str> = overrides.iter().map(String::as_str).collect();
@@ -67,6 +72,7 @@ pub(crate) fn ignored_files(r: &Repo) -> IdeResult<Vec<FileStatus>> {
/// pathspec filtering keeps that batch proportional to what changed. An empty list is the
/// full status, so a caller that lost the paths still gets a correct answer.
pub(crate) fn status_paths(r: &Repo, paths: &[String]) -> IdeResult<Vec<FileStatus>> {
r.check_valid()?;
// Pathspecs always take `/`, and a path that *is* the repository root names everything: both
// matter, because `Repo::status_paths` hands over paths as the platform spells them.
let patterns: Vec<String> =