From 9d3047031650d8a19cde29ddf45dfd0942ef22bf Mon Sep 17 00:00:00 2001 From: Hauser Zhi Date: Thu, 3 Dec 2026 00:37:13 +0800 Subject: [PATCH] fix(ecstore): preserve background delete discovery progress (#9866) * fix(ecstore): preserve background delete discovery progress Keep the local scan and its in-flight result across scheduling windows. Run bounded native steps under per-disk background admission, and defer genuinely stalled pages so sweeps on healthy drives can proceed. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * perf(ecstore): walk delete discovery directories by descriptor Open the Linux scan root beneath the pinned mount and descend relative to each retained parent directory. Skip ordinary files using directory entry types and validate evidence at its canonical path. Acquire the bucket lease before admitting background disk I/O. Return the page and continuation when a running walk stops cooperatively. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * fix(ecstore): retain delete discovery work across sweeps Keep active discovery pages when hint pressure requests another sweep. Let unopened retries cover their original scopes without bypassing backoff, and finish older cursors before revisiting the same bucket. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu * fix(ecstore): yield discovery during bucket identity reads Resolve the bucket incarnation as part of the in-flight page. Drive the bounded metadata read independently so its guard can be released while discovery rotates across disks. Keep the resolved identity attached to the page before admitting any discovered recovery hints. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu --------- Co-authored-by: heihutu Co-authored-by: zhi22915 Co-authored-by: qunjiazhu --- crates/ecstore/src/disk/disk_store.rs | 32 ++ crates/ecstore/src/disk/local.rs | 1 + .../ecstore/src/disk/local/delete_recovery.rs | 458 ++++++++++----- crates/ecstore/src/disk/os.rs | 2 +- .../src/store/delete_recovery_runtime.rs | 543 ++++++++++++++---- 5 files changed, 783 insertions(+), 253 deletions(-) diff --git a/crates/ecstore/src/disk/disk_store.rs b/crates/ecstore/src/disk/disk_store.rs index 2ea57bf4b5..ca965197c4 100644 --- a/crates/ecstore/src/disk/disk_store.rs +++ b/crates/ecstore/src/disk/disk_store.rs @@ -1926,6 +1926,38 @@ impl LocalDiskWrapper { .map_err(DiskError::Io) } + pub(crate) async fn advance_background_delete_discovery( + &self, + volume: String, + session: Option, + limit: u32, + cancel: CancellationToken, + ) -> Result<(Vec, Option)> { + self.check_scanner_handle()?; + let retired = self.retirement_token(); + // A queued bucket lease must not occupy the only background disk slot. + let lease = self.disk.lock_delete_discovery_bucket(&volume).await?; + let disk = Arc::clone(&self.disk); + super::with_background_disk_io( + cancel.clone(), + self.track_disk_health_with_op_timeout_action_and_mutation_with_io_permit( + "discover_delete_transactions", + |permit| async move { + super::io_admission::spawn_blocking_with_disk_io_permit(permit, move || { + let _lease = lease; + disk.advance_background_delete_discovery(&volume, session, limit, &cancel, &retired) + }) + .await + .map_err(DiskError::other)? + }, + Duration::ZERO, + TimeoutHealthAction::IgnoreFailure, + DiskMetricMutation::None, + ), + ) + .await + } + pub fn get_object_path_if_local(&self, volume: &str, path: &str) -> crate::disk::error::Result { self.disk.get_object_path(volume, path) } diff --git a/crates/ecstore/src/disk/local.rs b/crates/ecstore/src/disk/local.rs index 8a6bba77e8..ad29f8516e 100644 --- a/crates/ecstore/src/disk/local.rs +++ b/crates/ecstore/src/disk/local.rs @@ -21,6 +21,7 @@ use self::commit::lock_rename_commit_directories; mod commit; pub(super) mod delete_recovery; +pub(crate) use delete_recovery::DiscoverySession; mod delete_reserve; #[cfg(all(unix, test))] #[path = "fd_cache_tests.rs"] diff --git a/crates/ecstore/src/disk/local/delete_recovery.rs b/crates/ecstore/src/disk/local/delete_recovery.rs index 6c159e92c8..0e8fd4a794 100644 --- a/crates/ecstore/src/disk/local/delete_recovery.rs +++ b/crates/ecstore/src/disk/local/delete_recovery.rs @@ -31,13 +31,26 @@ pub(super) const PREPARED: &str = "delete-prepared"; pub(super) const TARGET: &str = "delete-target"; pub(super) const FINISHED: &str = "delete-commit-finished"; const MAX_METADATA: u64 = 64 * 1024 * 1024; -struct DiscoverySession { +#[cfg(target_os = "linux")] +type DiscoveryEntries = rustix::fs::Dir; +#[cfg(not(target_os = "linux"))] +type DiscoveryEntries = std::fs::ReadDir; + +#[cfg(any(test, not(target_os = "linux")))] +fn open_discovery_entries(path: &Path) -> std::io::Result { + #[cfg(target_os = "linux")] + return rustix::fs::Dir::new(open_dir_fd(path)?).map_err(std::io::Error::from); + #[cfg(not(target_os = "linux"))] + std::fs::read_dir(path) +} + +pub(crate) struct DiscoverySession { disk_root: PathBuf, volume: String, object: Option, root: PathBuf, _mount: std::fs::File, - frames: Vec<(String, std::fs::ReadDir)>, + frames: Vec<(String, DiscoveryEntries)>, touched: Instant, #[cfg(test)] metadata_stats: Arc, @@ -52,6 +65,7 @@ const PLAIN_CHILDREN_PER_BUDGET_ENTRY: u32 = 64; /// Entries one step of the resumable (background) discovery may visit. The /// foreground bounded protocol has its own, larger per-call allowance. const DISCOVERY_STEP_ENTRIES: u32 = 4096; +const BACKGROUND_DISCOVERY_SLICE: Duration = Duration::from_millis(50); /// Wall-clock allowance of one bounded discovery call: a third of the drive /// timeout that wraps the call (including its wait for a lane worker), capped at @@ -90,8 +104,23 @@ impl DiscoverySession { max_entries: u32, should_stop: &dyn Fn() -> bool, ) -> std::io::Result<(Vec, Option, u32)> { + if should_stop() { + return Ok((Vec::new(), Some(self), 0)); + } if self.frames.is_empty() { - match std::fs::read_dir(&self.root) { + #[cfg(target_os = "linux")] + let entries = { + use rustix::fs::{Mode, OFlags}; + let mut relative = PathBuf::from(&self.volume); + if let Some(object) = &self.object { + relative.push(object); + } + os::open_linux_relative(&self._mount, &relative, OFlags::RDONLY | OFlags::DIRECTORY, Mode::empty()) + .and_then(|fd| rustix::fs::Dir::new(fd).map_err(std::io::Error::from)) + }; + #[cfg(not(target_os = "linux"))] + let entries = open_discovery_entries(&self.root); + match entries { Ok(entries) => self.frames.push((String::new(), entries)), Err(err) if err.kind() == ErrorKind::NotFound => { return Ok((Vec::new(), None, 0)); @@ -99,15 +128,14 @@ impl DiscoverySession { Err(err) => return Err(err), } } + let limit = usize::try_from(limit).map_err(|_| std::io::Error::from(ErrorKind::InvalidInput))?; let mut transactions = BTreeSet::new(); let mut seen_candidates = HashSet::new(); let mut visited = 0u32; let mut skipped_by_name = 0u32; - while !self.frames.is_empty() - && transactions.len() < usize::try_from(limit).map_err(|_| std::io::Error::from(ErrorKind::InvalidInput))? - && visited < max_entries - && !should_stop() - { + while !self.frames.is_empty() && transactions.len() < limit && visited < max_entries && !should_stop() { + // A valid 1024-byte key can exceed 256 one-byte components. + let can_descend = self.frames.len() < 1024; let (parent, entries) = self .frames .last_mut() @@ -119,11 +147,17 @@ impl DiscoverySession { continue; } }; - let name = entry - .file_name() - .into_string() - .map_err(|_| std::io::Error::from(ErrorKind::InvalidData))?; - if !safe_path(&name, false) || name.contains('/') { + let name = entry.file_name(); + #[cfg(target_os = "linux")] + if matches!(name.to_bytes(), b"." | b"..") { + continue; + } + #[cfg(target_os = "linux")] + let name = name.to_str().ok(); + #[cfg(not(target_os = "linux"))] + let name = name.to_str(); + let name = name.ok_or_else(|| std::io::Error::from(ErrorKind::InvalidData))?; + if !safe_path(name, false) || name.contains('/') { return Err(std::io::Error::from(ErrorKind::InvalidData)); } // An object-scoped scan only ever descends into transaction (UUID) @@ -136,9 +170,9 @@ impl DiscoverySession { // folder prefix with many children, UUID-named or not, can complete. if self.object.is_some() && if parent.is_empty() { - !canonical_uuid(&name).is_some_and(|id| !id.is_nil()) + !canonical_uuid(name).is_some_and(|id| !id.is_nil()) } else { - !may_be_delete_evidence(&name) + !may_be_delete_evidence(name) } { skipped_by_name += 1; @@ -148,115 +182,186 @@ impl DiscoverySession { continue; } visited += 1; - if self.object.is_none() && !may_be_delete_evidence(&name) { - let ft = match entry.file_type() { - Ok(ft) => ft, - Err(err) if err.kind() == ErrorKind::NotFound => continue, - Err(err) => return Err(err), + #[cfg(target_os = "linux")] + let is_dir = { + use rustix::fs::{AtFlags, FileType, statat}; + + let kind = entry.file_type(); + #[cfg(test)] + let kind = if FORCE_RAW_DIR_DT_UNKNOWN.with(std::cell::Cell::get) { + FileType::Unknown + } else { + kind }; - if ft.is_symlink() { - return Err(std::io::Error::from(DiskError::InvalidPath)); - } - if !ft.is_dir() && !ft.is_file() { - return Err(std::io::Error::from(ErrorKind::InvalidData)); - } - if ft.is_file() { - continue; - } - } - let relative = if parent.is_empty() { - name.clone() - } else { - format!("{parent}/{name}") - }; - let path = self.root.join(&relative); - #[cfg(test)] - self.metadata_stats.fetch_add(1, Ordering::Relaxed); - reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?; - let kind = match std::fs::symlink_metadata(&path) { - Ok(metadata) => metadata, - Err(err) if err.kind() == ErrorKind::NotFound => continue, - Err(err) => return Err(err), - }; - if !kind.is_dir() && !kind.is_file() { - return Err(std::io::Error::from(ErrorKind::InvalidData)); - } - if kind.is_file() { - let bound = match self.object.as_deref() { - Some(object) if !parent.is_empty() && !parent.contains('/') => Some((object, parent.as_str())), - Some(_) => None, - None => parent.rsplit_once('/'), + let kind = if kind == FileType::Unknown { + #[cfg(test)] + self.metadata_stats.fetch_add(1, Ordering::Relaxed); + match statat(entries.fd()?, entry.file_name(), AtFlags::SYMLINK_NOFOLLOW) { + Ok(stat) => FileType::from_raw_mode(stat.st_mode), + Err(rustix::io::Errno::NOENT) => continue, + Err(err) => return Err(err.into()), + } + } else { + kind }; - if let Some((object, id)) = bound { - let transaction = - if [PREPARED, STORAGE_FORMAT_FILE_BACKUP, DELETE_QUORUM_COMMITTED_FILE].contains(&name.as_str()) { - canonical_uuid(id).filter(|id| !id.is_nil()) - } else { - [ - DELETE_DATA_DIR_MARKER_PREFIX, - RESERVED_DELETE_DATA_DIR_MARKER_PREFIX, - RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX, - ] - .iter() - .find_map(|prefix| delete_transaction_marker_id(&name, prefix)) - }; - if let Some(transaction) = transaction { - if !seen_candidates.insert((object.to_owned(), transaction)) { - continue; - } - let physical = match self.object.as_ref() { - Some(_) => self.root.clone(), - None => self.root.join(object), - }; - if name == STORAGE_FORMAT_FILE_BACKUP - && live_write_backup(&physical, transaction).map_err(std::io::Error::from)? - { - continue; - } - let proof_root = physical.join(transaction.to_string()); - if self.object.is_some() { - regular_file_exists(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?; - regular_file_exists(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)).map_err(std::io::Error::from)?; - transactions.insert((object.to_owned(), transaction)); - continue; - } - let prepared = regular_bytes(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?; - // Only a fully bound journal can name a logical - // key. Other records remain discoverable by their - // physical key for canonical inspection to reject. - let record = match prepared { - Some(bytes) => serde_json::from_slice::(&bytes).ok(), - None => regular_bytes(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)) - .map_err(std::io::Error::from)? - .filter(|bytes| !bytes.is_empty()) - .and_then(|bytes| parse_commit_receipt(&bytes).ok()) - .map(|receipt| receipt.journal), - }; - let logical = record - .filter(|journal| { - journal.protocol_version == DELETE_RECOVERY_PROTOCOL_VERSION - && journal.volume == self.volume - && journal.transaction == transaction - && safe_path(&journal.object, false) - && match self.object.as_ref() { - Some(scope) => scope == &journal.object, - None => build_local_disk_object_path(&self.root, "", &journal.object).1 == physical, - } - }) - .map_or_else(|| object.to_owned(), |journal| journal.object); - transactions.insert((logical, transaction)); + match kind { + FileType::Directory => true, + FileType::RegularFile => false, + FileType::Symlink => return Err(std::io::Error::from(DiskError::InvalidPath)), + _ => return Err(std::io::Error::from(ErrorKind::InvalidData)), + } + }; + #[cfg(not(target_os = "linux"))] + let is_dir = { + if self.object.is_none() && !may_be_delete_evidence(name) { + let kind = match entry.file_type() { + Ok(kind) => kind, + Err(err) if err.kind() == ErrorKind::NotFound => continue, + Err(err) => return Err(err), + }; + if kind.is_file() { + continue; + } + if kind.is_symlink() { + return Err(std::io::Error::from(DiskError::InvalidPath)); + } + if !kind.is_dir() { + return Err(std::io::Error::from(ErrorKind::InvalidData)); } } - } else { - if self.object.is_some() && (!parent.is_empty() || !canonical_uuid(&name).is_some_and(|id| !id.is_nil())) { + + let path = self.root.join(parent.as_str()).join(name); + #[cfg(test)] + self.metadata_stats.fetch_add(1, Ordering::Relaxed); + reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?; + match std::fs::symlink_metadata(path) { + Ok(metadata) if metadata.is_dir() => true, + Ok(metadata) if metadata.is_file() => false, + Ok(_) => return Err(std::io::Error::from(ErrorKind::InvalidData)), + Err(err) if err.kind() == ErrorKind::NotFound => continue, + Err(err) => return Err(err), + } + }; + + if is_dir { + if self.object.is_some() && (!parent.is_empty() || !canonical_uuid(name).is_some_and(|id| !id.is_nil())) { continue; } - // A valid 1024-byte key can exceed 256 one-byte path - // components; allow its transaction/data directories too. - if self.frames.len() >= 1024 { + if !can_descend { return Err(std::io::Error::from(ErrorKind::InvalidData)); } - self.frames.push((relative, std::fs::read_dir(path)?)); + let relative = if parent.is_empty() { + name.to_owned() + } else { + format!("{parent}/{name}") + }; + #[cfg(target_os = "linux")] + let child = { + use rustix::fs::{Mode, OFlags, openat}; + match openat( + entries.fd()?, + entry.file_name(), + OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::empty(), + ) { + Ok(fd) => rustix::fs::Dir::new(fd).map_err(std::io::Error::from), + Err(rustix::io::Errno::NOTDIR | rustix::io::Errno::LOOP) => { + return Err(std::io::Error::from(DiskError::InvalidPath)); + } + Err(err) => Err(err.into()), + } + }; + #[cfg(not(target_os = "linux"))] + let child = open_discovery_entries(&self.root.join(&relative)); + match child { + Ok(entries) => self.frames.push((relative, entries)), + Err(err) if err.kind() == ErrorKind::NotFound => continue, + Err(err) => return Err(err), + } + continue; + } + + if !may_be_delete_evidence(name) { + // Ordinary data and metadata files cannot contribute a recovery hint. + continue; + } + #[cfg(target_os = "linux")] + { + // Keep canonical, live-path validation for the sparse proof candidates. + let path = self.root.join(parent.as_str()).join(name); + #[cfg(test)] + self.metadata_stats.fetch_add(1, Ordering::Relaxed); + reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?; + match std::fs::symlink_metadata(path) { + Ok(metadata) if metadata.is_file() => {} + Ok(_) => return Err(std::io::Error::from(ErrorKind::InvalidData)), + Err(err) if err.kind() == ErrorKind::NotFound => continue, + Err(err) => return Err(err), + } + } + let bound = match self.object.as_deref() { + Some(object) if !parent.is_empty() && !parent.contains('/') => Some((object, parent.as_str())), + Some(_) => None, + None => parent.rsplit_once('/'), + }; + if let Some((object, id)) = bound { + let transaction = if [PREPARED, STORAGE_FORMAT_FILE_BACKUP, DELETE_QUORUM_COMMITTED_FILE].contains(&name) { + canonical_uuid(id).filter(|id| !id.is_nil()) + } else { + [ + DELETE_DATA_DIR_MARKER_PREFIX, + RESERVED_DELETE_DATA_DIR_MARKER_PREFIX, + RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX, + ] + .iter() + .find_map(|prefix| delete_transaction_marker_id(name, prefix)) + }; + if let Some(transaction) = transaction { + if !seen_candidates.insert((object.to_owned(), transaction)) { + continue; + } + let physical = match self.object.as_ref() { + Some(_) => self.root.clone(), + None => self.root.join(object), + }; + if name == STORAGE_FORMAT_FILE_BACKUP + && live_write_backup(&physical, transaction).map_err(std::io::Error::from)? + { + continue; + } + let proof_root = physical.join(transaction.to_string()); + if self.object.is_some() { + regular_file_exists(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?; + regular_file_exists(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)).map_err(std::io::Error::from)?; + transactions.insert((object.to_owned(), transaction)); + continue; + } + let prepared = regular_bytes(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?; + // Only a fully bound journal can name a logical + // key. Other records remain discoverable by their + // physical key for canonical inspection to reject. + let record = match prepared { + Some(bytes) => serde_json::from_slice::(&bytes).ok(), + None => regular_bytes(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)) + .map_err(std::io::Error::from)? + .filter(|bytes| !bytes.is_empty()) + .and_then(|bytes| parse_commit_receipt(&bytes).ok()) + .map(|receipt| receipt.journal), + }; + let logical = record + .filter(|journal| { + journal.protocol_version == DELETE_RECOVERY_PROTOCOL_VERSION + && journal.volume == self.volume + && journal.transaction == transaction + && safe_path(&journal.object, false) + && match self.object.as_ref() { + Some(scope) => scope == &journal.object, + None => build_local_disk_object_path(&self.root, "", &journal.object).1 == physical, + } + }) + .map_or_else(|| object.to_owned(), |journal| journal.object); + transactions.insert((logical, transaction)); + } } } @@ -274,10 +379,9 @@ impl DiscoverySession { if !transactions.is_empty() { return Ok(true); } - let Some(mut next) = next else { + let Some(next) = next else { return Ok(false); }; - next.touched = Instant::now(); self = next; } } @@ -1926,23 +2030,40 @@ impl LocalDisk { .await .map_err(to_file_error)? } - /// Local maintenance may pause a page behind recovery backpressure. It - /// retains only its own bounded set of cursors; remote callers still have - /// the ordinary idle deadline and every resumed page rechecks mount identity. - pub(crate) fn renew_delete_recovery_cursor(&self, volume: &str, cursor: &DeleteRecoveryCursor) -> bool { - let mut sessions = DISCOVERY_SESSIONS.lock(); - let Some(session) = sessions.get_mut(&cursor.token) else { - return false; - }; - if session.disk_root != self.io_root() - || session.volume != volume - || session.object.is_some() - || session.touched.elapsed() > Duration::from_secs(300) - { - return false; + pub(crate) async fn lock_delete_discovery_bucket(&self, volume: &str) -> Result> { + if !safe_path(volume, false) || volume.contains('/') { + return Err(DiskError::InvalidPath); } - session.touched = Instant::now(); - true + let path = build_local_disk_bucket_path(self.io_root(), volume); + Ok(os::acquire_namespace_mutation_lease_with_owner(&path, None).await) + } + + pub(in crate::disk) fn advance_background_delete_discovery( + &self, + volume: &str, + session: Option, + limit: u32, + cancel: &tokio_util::sync::CancellationToken, + retired: &tokio_util::sync::CancellationToken, + ) -> Result<(Vec, Option)> { + if retired.is_cancelled() { + return Err(DiskError::DiskNotFound); + } + if cancel.is_cancelled() { + return Ok((Vec::new(), session)); + } + let path = self.delete_discovery_path(volume, None)?; + let session = match session { + Some(session) => session, + None => self.new_delete_discovery_session(volume, None, &path)?, + }; + self.validate_delete_discovery_owner(&session)?; + let deadline = Instant::now() + BACKGROUND_DISCOVERY_SLICE; + let should_stop = || cancel.is_cancelled() || retired.is_cancelled() || Instant::now() >= deadline; + let (transactions, next, _) = session + .advance_bounded(limit, DISCOVERY_STEP_ENTRIES, &should_stop) + .map_err(to_file_error)?; + Ok((transactions, next)) } fn delete_discovery_path(&self, volume: &str, object: Option<&str>) -> Result { @@ -1998,7 +2119,7 @@ impl LocalDisk { } fn validate_delete_discovery_owner(&self, session: &DiscoverySession) -> Result<()> { - if session.disk_root != self.io_root() || session.touched.elapsed() > Duration::from_secs(300) { + if session.disk_root != self.io_root() { return Err(DiskError::InvalidPath); } #[cfg(unix)] @@ -2092,7 +2213,10 @@ impl LocalDisk { .lock() .remove(&cursor.token) .ok_or(DiskError::FileNotFound)?; - if session.volume != volume || session.object.as_deref() != object { + if session.volume != volume + || session.object.as_deref() != object + || session.touched.elapsed() > Duration::from_secs(300) + { return Err(DiskError::InvalidPath); } (cursor.token, session) @@ -7740,10 +7864,6 @@ mod tests { .expect("bounded discovery continues"); found.extend(page.transactions.into_iter().map(|id| (id.object, id.transaction))); cursor = page.next; - if let Some(cursor) = cursor.as_ref() { - assert!(!disk.renew_delete_recovery_cursor("different-bucket", cursor)); - assert!(disk.renew_delete_recovery_cursor("recovery", cursor)); - } if cursor.is_none() { break; } @@ -8324,8 +8444,8 @@ mod tests { // Seed a valid DFS continuation so this assertion is independent of // filesystem directory ordering: the large empty frame runs first. session.frames = vec![ - (transaction.to_string(), std::fs::read_dir(&proof).expect("later evidence frame")), - (filler_id, std::fs::read_dir(&filler).expect("empty intermediate frame")), + (transaction.to_string(), open_discovery_entries(&proof).expect("later evidence frame")), + (filler_id, open_discovery_entries(&filler).expect("empty intermediate frame")), ]; assert!( session @@ -8932,6 +9052,23 @@ mod tests { .await .is_err() ); + #[cfg(target_os = "linux")] + { + let prefix = temp.path().join("recovery/prefix"); + fs::create_dir_all(prefix.join("key")).await.expect("object directory"); + fs::create_dir(outside.path().join("key")) + .await + .expect("outside object directory"); + let path = disk + .delete_discovery_path("recovery", Some("prefix/key")) + .expect("validated key path"); + let session = disk + .new_delete_discovery_session("recovery", Some("prefix/key"), &path) + .expect("unopened key session"); + fs::remove_dir_all(&prefix).await.expect("remove original prefix"); + symlink(outside.path(), &prefix).expect("replace a parent after validation"); + assert!(session.advance(16).is_err(), "the real root open must reject a replaced ancestor"); + } assert_eq!( fs::read(outside.path().join("sentinel")) .await @@ -8965,13 +9102,36 @@ mod tests { assert!(transactions.is_empty()); assert!(next.is_none()); let stats = stats_counter.load(Ordering::Relaxed); - // fixture() pre-creates recovery/object (1 directory + 1 xl.meta); with 32 obj-XX + 32 data_dir directories, - // only the 65 directories reach symlink_metadata, while all 65 regular files (xl.meta and part.1) are skipped - // via DirEntry::file_type() with 0 stats. - assert_eq!( - stats, 65, - "bucket-wide discovery must skip inert regular files without symlink_metadata stats" - ); + // The fixture has 65 directories and 65 regular files. An ordinary + // Linux walk uses d_type and opens directories relative to the parent FD. + #[cfg(target_os = "linux")] + { + let expected = match open_discovery_entries(&bucket_root).expect("read dirents").find_map(|entry| { + let entry = entry.expect("dirent"); + (!matches!(entry.file_name().to_bytes(), b"." | b"..")).then(|| entry.file_type()) + }) { + Some(rustix::fs::FileType::Unknown) => 130, + Some(_) => 0, + None => panic!("the fixture contains directories"), + }; + assert_eq!(stats, expected, "known directory types must skip path-based metadata checks"); + + let session = disk + .new_delete_discovery_session("recovery", None, &disc_path) + .expect("discovery session with unknown dirent types"); + let fallback_stats = Arc::clone(&session.metadata_stats); + let result = FORCE_RAW_DIR_DT_UNKNOWN.with(|flag| { + let previous = flag.replace(true); + let result = session.advance(16); + flag.set(previous); + result + }); + let (transactions, next) = result.expect("unknown directory types use no-follow statat"); + assert!(transactions.is_empty() && next.is_none()); + assert_eq!(fallback_stats.load(Ordering::Relaxed), 130, "one parent-relative stat per unknown entry"); + } + #[cfg(not(target_os = "linux"))] + assert_eq!(stats, 65, "the portable walk skips metadata checks for ordinary files"); // A symlink with an inert file name ("part.1") inside a bucket-wide walk must still fail closed with InvalidPath. let outside = tempfile::tempdir().expect("outside dir"); diff --git a/crates/ecstore/src/disk/os.rs b/crates/ecstore/src/disk/os.rs index e93abb3117..c0c7d944d2 100644 --- a/crates/ecstore/src/disk/os.rs +++ b/crates/ecstore/src/disk/os.rs @@ -6583,7 +6583,7 @@ fn linux_relative_path_has_invalid_component(relative: &Path) -> bool { /// Open the actual IO handle with the same containment policy as path validation. /// Older kernels retain fd-relative traversal; only ENOSYS enables the fallback. #[cfg(target_os = "linux")] -fn open_linux_relative( +pub(in crate::disk) fn open_linux_relative( directory: &std::fs::File, relative: &Path, flags: rustix::fs::OFlags, diff --git a/crates/ecstore/src/store/delete_recovery_runtime.rs b/crates/ecstore/src/store/delete_recovery_runtime.rs index eca5f98ba0..8f7376fa23 100644 --- a/crates/ecstore/src/store/delete_recovery_runtime.rs +++ b/crates/ecstore/src/store/delete_recovery_runtime.rs @@ -18,7 +18,7 @@ use super::ECStore; use crate::bucket::utils::is_meta_bucketname; -use crate::disk::{DeleteRecoveryCursor, DiskAPI, DiskStore}; +use crate::disk::{DeleteTransactionId, Disk, DiskAPI, DiskStore, error::DiskError, local::DiscoverySession}; use futures::{StreamExt, future::BoxFuture, stream::FuturesUnordered}; use rand::RngExt as _; use rustfs_heal_contracts::heal_channel::HealOpts; @@ -29,13 +29,15 @@ use std::sync::{ }; use std::time::Duration; use tokio::time::{Instant, MissedTickBehavior}; -use tokio_util::sync::CancellationToken; +use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle}; use uuid::Uuid; const HINT_CAPACITY: usize = 1_024; const DISCOVERY_PAGE_SIZE: u32 = 128; const PAGES_PER_PASS: usize = 8; const MAX_ACTIVE_DISCOVERY_CURSORS: usize = 32; +const DISCOVERY_PAGE_WAIT: Duration = Duration::from_millis(100); +const DISCOVERY_PAGE_STALL: Duration = Duration::from_secs(30); const LOG_COMPONENT_ECSTORE: &str = "ecstore"; const LOG_SUBSYSTEM_DELETE_RECOVERY: &str = "delete_recovery"; const EVENT_DELETE_RECOVERY_STATUS: &str = "delete_recovery_status"; @@ -468,18 +470,50 @@ struct LocalSource { available: bool, } +impl LocalSource { + fn same_disk(&self, other: &Self) -> bool { + self.pool == other.pool && self.set == other.set && Arc::ptr_eq(&self.disk, &other.disk) + } +} + +struct DiscoveryPage { + incarnation: Uuid, + transactions: Vec, + next: Option, +} + +#[derive(Default)] +enum BucketDiscovery { + #[default] + Unstarted, + Paused(DiscoverySession), + InFlight(BoxFuture<'static, crate::disk::error::Result>), +} + struct BucketScan { bucket: String, incarnation: Option, - cursor: Option, + discovery: BucketDiscovery, pending: VecDeque, } +impl BucketScan { + fn has_progress(&self) -> bool { + !matches!(self.discovery, BucketDiscovery::Unstarted) || !self.pending.is_empty() + } +} + struct DiskScan { source: LocalSource, buckets: Option>, } +impl DiskScan { + fn front_bucket(&self) -> Option<&BucketScan> { + self.buckets.as_ref()?.front() + } +} + fn admit_discovered_keys(hints: &DeleteRecoveryHints, source: &LocalSource, bucket: &mut BucketScan) { while let Some(object) = bucket.pending.front() { if !hints.register_discovered(DeleteRecoveryKey { @@ -531,11 +565,8 @@ impl RecoveryPass { } } } - let contains_source = |inventory: &[LocalSource], source: &LocalSource| { - inventory.iter().any(|current| { - current.pool == source.pool && current.set == source.set && Arc::ptr_eq(¤t.disk, &source.disk) - }) - }; + let contains_source = + |inventory: &[LocalSource], source: &LocalSource| inventory.iter().any(|current| current.same_disk(source)); if sources.len() != self.sources.len() || self.sources.iter().any(|source| !contains_source(&sources, source)) { let hints = store.ctx.delete_recovery_hints(); hints.request_rescan(); @@ -547,12 +578,10 @@ impl RecoveryPass { .iter() .filter(|source| { source.available - && !self.sources.iter().any(|previous| { - previous.available - && Arc::ptr_eq(&previous.disk, &source.disk) - && previous.pool == source.pool - && previous.set == source.set - }) + && !self + .sources + .iter() + .any(|previous| previous.available && previous.same_disk(source)) }) .map(|source| (source.pool, source.set)) .collect(); @@ -567,42 +596,39 @@ impl RecoveryPass { fn defer(&mut self, mut scan: DiskScan) { if let Some(buckets) = scan.buckets.as_mut() { for bucket in buckets { - bucket.cursor = None; + bucket.discovery = BucketDiscovery::Unstarted; bucket.incarnation = None; } } let same_scope = |other: &DiskScan| { - scan.source.pool == other.source.pool - && scan.source.set == other.source.set - && scan.source.disk.to_string() == other.source.disk.to_string() - && scan - .buckets - .as_ref() - .and_then(|buckets| buckets.front()) - .map(|bucket| &bucket.bucket) - == other - .buckets - .as_ref() - .and_then(|buckets| buckets.front()) - .map(|bucket| &bucket.bucket) + scan.source.same_disk(&other.source) + && scan.front_bucket().map(|bucket| &bucket.bucket) == other.front_bucket().map(|bucket| &bucket.bucket) }; + if let Some(failed) = scan.front_bucket() { + // A full sweep may have listed this bucket before the retry failed. + // Keep the failed scope's backoff for all still-unopened copies. + self.scans.retain_mut(|queued| { + if queued.source.same_disk(&scan.source) + && let Some(buckets) = queued.buckets.as_mut() + { + buckets.retain(|bucket| bucket.bucket != failed.bucket || bucket.has_progress()); + !buckets.is_empty() + } else { + true + } + }); + } if !self.deferred.iter().any(|(_, pending)| same_scope(pending)) { self.deferred.push_back((Instant::now() + INVENTORY_INTERVAL, scan)); } } - async fn discover_page(&mut self, store: &Arc, deadline: Instant) { + async fn discover_page(&mut self, store: &Arc, deadline: Instant, cancel: &CancellationToken) { let hints = store.ctx.delete_recovery_hints(); - let active_cursor = |scan: &DiskScan| { - scan.buckets - .as_ref() - .and_then(|buckets| buckets.front()) - .is_some_and(|bucket| bucket.cursor.is_some() || !bucket.pending.is_empty()) - }; + let active_cursor = |scan: &DiskScan| scan.front_bucket().is_some_and(BucketScan::has_progress); if self.scans.iter().filter(|scan| active_cursor(scan)).count() >= MAX_ACTIVE_DISCOVERY_CURSORS { - // Keep room for exact-key recovery and other discovery callers in - // the disk API's bounded session table. Finish existing cursors - // before starting another bucket; queued sources retain their place. + // Bound the number of directory stacks we keep open while rotating + // across disks. Finish existing walks before opening another bucket. if let Some(index) = self.scans.iter().position(active_cursor) { self.scans.rotate_left(index); } @@ -611,14 +637,28 @@ impl RecoveryPass { if scan.buckets.is_none() { match tokio::time::timeout_at(deadline, scan.source.disk.list_volumes()).await { Ok(Ok(volumes)) => { + // A retry that has yet to open its bucket can cover the full + // scope for this generation, without bypassing its backoff. + let unopened_retries: HashSet<_> = self + .scans + .iter() + .chain(self.deferred.iter().map(|(_, retry)| retry)) + .filter(|retry| retry.source.same_disk(&scan.source)) + .filter_map(|retry| retry.buckets.as_ref()) + .flatten() + .filter(|bucket| !bucket.has_progress()) + .map(|bucket| bucket.bucket.as_str()) + .collect(); scan.buckets = Some( volumes .into_iter() - .filter(|volume| !is_meta_bucketname(&volume.name)) + .filter(|volume| { + !is_meta_bucketname(&volume.name) && !unopened_retries.contains(volume.name.as_str()) + }) .map(|volume| BucketScan { bucket: volume.name, incarnation: None, - cursor: None, + discovery: BucketDiscovery::Unstarted, pending: VecDeque::new(), }) .collect(), @@ -634,7 +674,7 @@ impl RecoveryPass { { let had_pending = !bucket.pending.is_empty(); admit_discovered_keys(hints, &scan.source, &mut bucket); - if !bucket.pending.is_empty() || (had_pending && bucket.cursor.is_none()) { + if !bucket.pending.is_empty() || (had_pending && matches!(bucket.discovery, BucketDiscovery::Unstarted)) { if !bucket.pending.is_empty() { buckets.push_front(bucket); } @@ -643,47 +683,104 @@ impl RecoveryPass { } return; } - if bucket.incarnation.is_none() { - match tokio::time::timeout_at(deadline, store.bucket_incarnation_id_from_disk(&bucket.bucket)).await { - Ok(Ok(incarnation)) => bucket.incarnation = Some(incarnation), - _ => { + // Finish an older cursor before the new sweep revisits that + // bucket. A different bucket may proceed once the disk is idle. + if !matches!(bucket.discovery, BucketDiscovery::InFlight(_)) + && self + .scans + .iter() + .filter(|other| other.source.same_disk(&scan.source)) + .filter_map(DiskScan::front_bucket) + .any(|other| { + matches!(other.discovery, BucketDiscovery::InFlight(_)) + || (!bucket.has_progress() && other.bucket == bucket.bucket && other.has_progress()) + }) + { + buckets.push_front(bucket); + self.scans.push_back(scan); + return; + } + if !matches!(bucket.discovery, BucketDiscovery::InFlight(_)) { + let store = Arc::clone(store); + let incarnation = bucket.incarnation; + let disk = Arc::clone(&scan.source.disk); + let volume = bucket.bucket.clone(); + let cancel = cancel.child_token(); + let session = match std::mem::take(&mut bucket.discovery) { + BucketDiscovery::Paused(session) => Some(session), + _ => None, + }; + bucket.discovery = BucketDiscovery::InFlight(Box::pin(async move { + let _cancel_on_drop = cancel.clone().drop_guard(); + let (volume, incarnation) = match incarnation { + Some(incarnation) => (volume, incarnation), + None => { + // Finish the quorum read and release its metadata guard even + // while the discovery scheduler is polling other disks. + let lookup = AbortOnDropHandle::new(tokio::spawn(async move { + let incarnation = + tokio::time::timeout(DISCOVERY_BUDGET, store.bucket_incarnation_id_from_disk(&volume)) + .await + .map_err(|_| DiskError::Timeout)? + .map_err(DiskError::other)?; + Ok::<_, DiskError>((volume, incarnation)) + })); + lookup.await.map_err(DiskError::other)?? + } + }; + // A stalled disk must not prevent later sweeps on healthy disks. + let (transactions, next) = tokio::time::timeout(DISCOVERY_PAGE_STALL, async move { + match disk.as_ref() { + Disk::Local(local) => { + local + .advance_background_delete_discovery(volume, session, DISCOVERY_PAGE_SIZE, cancel) + .await + } + #[cfg(feature = "dst")] + Disk::Sim(sim) => sim + .discover_delete_transactions(&volume, None, None, DISCOVERY_PAGE_SIZE) + .await + .map(|page| (page.transactions, None)), + Disk::Remote(_) => Err(DiskError::DiskNotFound), + } + }) + .await + .map_err(|_| DiskError::Timeout)??; + Ok(DiscoveryPage { + incarnation, + transactions, + next, + }) + })); + } + if let BucketDiscovery::InFlight(page) = &mut bucket.discovery { + let wait_until = deadline.min(Instant::now() + DISCOVERY_PAGE_WAIT); + match tokio::time::timeout_at(wait_until, page.as_mut()).await { + Ok(Ok(DiscoveryPage { + incarnation, + transactions, + next, + })) => { + bucket.incarnation = Some(incarnation); + bucket.pending = transactions.into_iter().map(|transaction| transaction.object).collect(); + bucket.discovery = next.map_or(BucketDiscovery::Unstarted, BucketDiscovery::Paused); + admit_discovered_keys(hints, &scan.source, &mut bucket); + if !matches!(bucket.discovery, BucketDiscovery::Unstarted) || !bucket.pending.is_empty() { + buckets.push_front(bucket); + } + } + Ok(Err(_)) => { self.defer(DiskScan { source: scan.source.clone(), buckets: Some(VecDeque::from([bucket])), }); - if !buckets.is_empty() { - self.scans.push_back(scan); - } - return; } - } - } - match tokio::time::timeout_at( - deadline, - scan.source - .disk - .discover_delete_transactions(&bucket.bucket, None, bucket.cursor.take(), DISCOVERY_PAGE_SIZE), - ) - .await - { - Ok(Ok(page)) => { - bucket.pending = page.transactions.into_iter().map(|transaction| transaction.object).collect(); - bucket.cursor = page.next; - admit_discovered_keys(hints, &scan.source, &mut bucket); - if bucket.cursor.is_some() || !bucket.pending.is_empty() { - // Keep one bounded page until its keys are admitted; - // unopened buckets cannot displace its continuation. + Err(_) => { + // Native calls can run past a scheduling window. Poll the + // same page next time, including any evidence it has found. buckets.push_front(bucket); } } - _ => { - // Retry only this source, never a full healthy tree - // because another disk is offline or a cursor expired. - self.defer(DiskScan { - source: scan.source.clone(), - buckets: Some(VecDeque::from([bucket])), - }); - } } } if scan.buckets.as_ref().is_some_and(|buckets| !buckets.is_empty()) { @@ -699,24 +796,6 @@ impl RecoveryPass { } let hints = store.ctx.delete_recovery_hints(); - // Renew only this worker's bounded local cursors before any await. - // Backpressure and a slow canonical rollback must not erase progress. - for scan in &mut self.scans { - if let Some(bucket) = scan.buckets.as_mut().and_then(|buckets| buckets.front_mut()) - && let Some(cursor) = bucket.cursor.as_ref() - { - let renewed = match scan.source.disk.as_ref() { - crate::disk::Disk::Local(local) => local.get_disk().renew_delete_recovery_cursor(&bucket.bucket, cursor), - crate::disk::Disk::Remote(_) => false, - #[cfg(feature = "dst")] - crate::disk::Disk::Sim(_) => false, - }; - if !renewed { - bucket.cursor = None; - hints.request_rescan(); - } - } - } let discovery_deadline = Instant::now() + DISCOVERY_BUDGET; tokio::select! { _ = cancel.cancelled() => return, @@ -731,12 +810,21 @@ impl RecoveryPass { } if let Some(generation) = hints.rescan() { self.scan_generation = Some(generation); - self.scans = self - .sources - .iter() - .cloned() - .map(|source| DiskScan { source, buckets: None }) - .collect(); + // A due retry may already have a live page even though the + // previous full sweep completed. Keep it ahead of fresh work. + for source in &self.sources { + let inventory_queued = self + .scans + .iter() + .chain(self.deferred.iter().map(|(_, retry)| retry)) + .any(|scan| scan.buckets.is_none() && scan.source.same_disk(source)); + if !inventory_queued { + self.scans.push_back(DiskScan { + source: source.clone(), + buckets: None, + }); + } + } } } for _ in 0..self.deferred.len() { @@ -753,7 +841,7 @@ impl RecoveryPass { } tokio::select! { _ = cancel.cancelled() => return, - _ = self.discover_page(store, discovery_deadline) => {} + _ = self.discover_page(store, discovery_deadline, cancel) => {} } } if self.scans.is_empty() @@ -1538,6 +1626,180 @@ mod tests { assert!(pass.scans.is_empty()); assert!(store.ctx.delete_recovery_hints().rescan().is_none()); } + #[tokio::test] + async fn delete_recovery_slow_bucket_identity_does_not_block_other_disks() { + let healthy = "runtime-healthy-identity"; + let blocked = "runtime-blocked-identity"; + let (_dirs, store, disks) = fixture(healthy).await; + store + .make_bucket(blocked, &MakeBucketOptions::default()) + .await + .expect("create second bucket"); + prepare(&store, &disks, healthy).await; + let incarnation = store + .bucket_incarnation_id_from_disk(healthy) + .await + .expect("healthy bucket incarnation"); + let writer = crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, blocked) + .await + .expect("hold the blocked bucket's metadata write lock"); + let key = DeleteRecoveryKey { + pool: 0, + set: 0, + bucket: healthy.to_owned(), + object: "object".to_owned(), + incarnation: Some(incarnation), + }; + let mut pass = hint_only_pass(&store); + pass.scans + .extend([blocked, healthy].into_iter().enumerate().map(|(index, bucket)| DiskScan { + source: LocalSource { + pool: 0, + set: 0, + disk: disks[index].clone(), + available: true, + }, + buckets: Some(VecDeque::from([BucketScan { + bucket: bucket.to_owned(), + incarnation: None, + discovery: BucketDiscovery::Unstarted, + pending: VecDeque::new(), + }])), + })); + let cancel = CancellationToken::new(); + let hints = store.ctx.delete_recovery_hints(); + assert!(!hints.is_pending(&key), "the key must be discovered by the healthy scan"); + tokio::time::timeout(Duration::from_secs(2), pass.discover(&store, &cancel)) + .await + .expect("identity lookup yields to independent disk work"); + + assert!(hints.is_pending(&key), "the healthy disk discovers its journal while metadata is locked"); + assert!(pass.deferred.is_empty(), "the scheduler keeps the waiting page"); + assert!(matches!( + pass.scans.front().and_then(DiskScan::front_bucket), + Some(BucketScan { bucket, discovery: BucketDiscovery::InFlight(_), .. }) if bucket == blocked + )); + + drop(writer); + let writer = tokio::time::timeout( + Duration::from_secs(2), + crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, blocked), + ) + .await + .expect("the parked discovery page must not keep the metadata guard held") + .expect("reacquire the bucket's metadata write lock"); + drop(writer); + pass.discover(&store, &cancel).await; + assert!(pass.scans.is_empty(), "the original identity lookup resumes through the native page"); + } + + #[tokio::test] + async fn delete_recovery_rescan_keeps_an_inflight_retry_page() { + let bucket = "runtime-rescan-retry"; + let (_dirs, store, disks) = fixture(bucket).await; + let source = LocalSource { + pool: 0, + set: 0, + disk: disks[0].clone(), + available: true, + }; + let incarnation = store + .bucket_incarnation_id_from_disk(bucket) + .await + .expect("bucket incarnation"); + let discovered = DeleteRecoveryKey { + pool: source.pool, + set: source.set, + bucket: bucket.to_owned(), + object: "found-in-retry".to_owned(), + incarnation: Some(incarnation), + }; + let mut pass = hint_only_pass(&store); + pass.sources.push(source.clone()); + pass.scans.push_back(DiskScan { + source, + buckets: Some(VecDeque::from([BucketScan { + bucket: bucket.to_owned(), + incarnation: Some(incarnation), + discovery: BucketDiscovery::InFlight(Box::pin(std::future::ready(Ok(DiscoveryPage { + incarnation, + transactions: vec![DeleteTransactionId { + object: discovered.object.clone(), + transaction: Uuid::new_v4(), + }], + next: None, + })))), + pending: VecDeque::new(), + }])), + }); + + let hints = store.ctx.delete_recovery_hints(); + hints.request_rescan(); + pass.discover(&store, &CancellationToken::new()).await; + + assert!(hints.is_pending(&discovered), "a fresh sweep must admit the in-flight retry result"); + assert!(pass.scans.is_empty(), "the fresh sweep also completes"); + assert!(hints.rescan().is_none(), "the new generation is acknowledged"); + } + + #[tokio::test] + async fn delete_recovery_rescan_respects_the_retry_backoff() { + let bucket = "runtime-rescan-backoff"; + let (_dirs, store, disks) = fixture(bucket).await; + prepare(&store, &disks, bucket).await; + let source = LocalSource { + pool: 0, + set: 0, + disk: disks[0].clone(), + available: true, + }; + let incarnation = store + .bucket_incarnation_id_from_disk(bucket) + .await + .expect("bucket incarnation"); + let discovered = DeleteRecoveryKey { + pool: source.pool, + set: source.set, + bucket: bucket.to_owned(), + object: "object".to_owned(), + incarnation: Some(incarnation), + }; + let mut pass = hint_only_pass(&store); + pass.sources.push(source.clone()); + pass.scans.push_back(DiskScan { + source: source.clone(), + buckets: Some(VecDeque::from([BucketScan { + bucket: bucket.to_owned(), + incarnation: None, + discovery: BucketDiscovery::Unstarted, + pending: VecDeque::new(), + }])), + }); + pass.defer(DiskScan { + source, + buckets: Some(VecDeque::from([BucketScan { + bucket: bucket.to_owned(), + incarnation: None, + discovery: BucketDiscovery::Unstarted, + pending: VecDeque::new(), + }])), + }); + + let hints = store.ctx.delete_recovery_hints(); + hints.request_rescan(); + let cancel = CancellationToken::new(); + pass.discover(&store, &cancel).await; + + assert!(!hints.is_pending(&discovered), "the full sweep must not bypass the bucket retry"); + assert!(hints.rescan().is_none(), "the deferred bucket does not block the full sweep"); + let (ready, _) = pass.deferred.front_mut().expect("pending bucket retry"); + *ready = Instant::now(); + pass.discover(&store, &cancel).await; + + assert!(hints.is_pending(&discovered), "the due retry still reads the hidden preparation"); + assert!(pass.deferred.is_empty(), "the retry settled its discovery obligation"); + } + #[tokio::test] async fn delete_recovery_blocked_capacity_yields_until_periodic_sweep() { let (_dirs, store, _disks) = fixture("runtime-blocked-sweep").await; @@ -1962,6 +2224,24 @@ mod tests { #[tokio::test] async fn delete_recovery_continues_current_bucket_before_opening_later_buckets() { + async fn finish_page(pass: &mut RecoveryPass, store: &Arc, cancel: &CancellationToken) { + let deadline = Instant::now() + Duration::from_secs(30); + loop { + assert!(Instant::now() < deadline, "discovery page did not return"); + pass.discover_page(store, deadline, cancel).await; + if !matches!( + pass.scans + .front() + .and_then(|scan| scan.buckets.as_ref()) + .and_then(|buckets| buckets.front()) + .map(|bucket| &bucket.discovery), + Some(BucketDiscovery::InFlight(_)) + ) { + break; + } + } + } + let bucket = "runtime-cursor-progress"; let (dirs, store, disks) = fixture(bucket).await; let other = "runtime-after-large"; @@ -1983,11 +2263,12 @@ mod tests { buckets: Some(VecDeque::from([bucket, other].map(|bucket| BucketScan { bucket: bucket.to_owned(), incarnation: None, - cursor: None, + discovery: BucketDiscovery::Unstarted, pending: VecDeque::new(), }))), }); - pass.discover_page(&store, Instant::now() + Duration::from_secs(30)).await; + let cancel = CancellationToken::new(); + finish_page(&mut pass, &store, &cancel).await; let first = pass.scans[0] .buckets .as_ref() @@ -1995,8 +2276,44 @@ mod tests { .front() .expect("current bucket"); assert_eq!(first.bucket, bucket); - assert!(first.cursor.is_some(), "raw entry budget must leave a continuation"); - pass.discover_page(&store, Instant::now() + Duration::from_secs(30)).await; + assert!( + matches!(first.discovery, BucketDiscovery::Paused(_)), + "raw entry budget must leave a continuation" + ); + let Disk::Local(local) = disks[0].as_ref() else { + panic!("expected a local drive"); + }; + let lease = local + .get_disk() + .lock_delete_discovery_bucket(bucket) + .await + .expect("hold bucket lease"); + pass.discover_page(&store, Instant::now(), &cancel).await; + assert!( + pass.deferred.is_empty(), + "the scheduling deadline must not discard a page waiting on the disk" + ); + assert!( + matches!( + pass.scans[0] + .buckets + .as_ref() + .and_then(|buckets| buckets.front()) + .map(|bucket| &bucket.discovery), + Some(BucketDiscovery::InFlight(_)) + ), + "the original page and its continuation stay owned across the deadline" + ); + let volumes = tokio::time::timeout( + Duration::from_secs(5), + crate::disk::with_background_disk_io(cancel.clone(), local.list_volumes()), + ) + .await + .expect("another background operation can use the disk while discovery waits for its bucket lease") + .expect("list volumes under background admission"); + assert!(volumes.iter().any(|volume| volume.name == other)); + drop(lease); + finish_page(&mut pass, &store, &cancel).await; assert_eq!( pass.scans[0] .buckets @@ -2008,5 +2325,25 @@ mod tests { other, "the second page completes instead of cycling through unopened buckets" ); + let hints = store.ctx.delete_recovery_hints(); + hints.request_rescan(); + pass.scan_generation = Some(hints.rescan().expect("scan obligation before the stall")); + let incarnation = store + .bucket_incarnation_id_from_disk(other) + .await + .expect("source incarnation"); + pass.scans[0].buckets.as_mut().expect("open inventory")[0].incarnation = Some(incarnation); + let _lease = local + .get_disk() + .lock_delete_discovery_bucket(other) + .await + .expect("hold bucket lease"); + tokio::time::pause(); + pass.discover_page(&store, Instant::now(), &cancel).await; + tokio::time::advance(DISCOVERY_PAGE_STALL).await; + pass.next_inventory = Some(Instant::now() + INVENTORY_INTERVAL); + pass.discover(&store, &cancel).await; + assert_eq!(pass.deferred.len(), 1, "a genuinely stalled source is deferred"); + assert!(pass.scan_generation.is_none(), "the stall cannot pin subsequent sweeps"); } }