vercel/next.js · #101954

Turbopack: recover from an unreadable persistent cache at startup

lukesandberg · merged Nov 22, 20268 files · 564 + / 25 −
crates/next-napi-bindings/src/next_api/turbopack_ctx.rs4 + / 0 −
@@ -411,6 +411,10 @@ impl CompilationEvent for StartupCacheInvalidationEvent {                 " because we previously detected an internal error in Turbopack"             }             Some(invalidation_reasons::USER_REQUEST) => " as the result of a user request",+            Some(invalidation_reasons::UNREADABLE) => {+                " because it could not be read. Its files may have been modified or deleted by \+                 another process"+            }             _ => "", // ignore unknown reasons         };         format!(
turbopack/crates/turbo-persistence/README.md5 + / 0 −
@@ -16,6 +16,8 @@ There is a single `CURRENT` file, a small JSON object holding the latest committ  All other files have a sequence number as file name, e. g. `0000123.sst`. All files are immutable once their sequence number is <= the committed sequence number. But they might be deleted when they are superseded by other committed files. +Files whose name starts with `.` are ignored, such as `.DS_Store` or the `._<name>` AppleDouble files macOS writes next to every file on filesystems like exFAT. Any other unrecognized file fails opening the database, with an error that names it.+ There are four different file types:  - Static Sorted Table (SST, `*.sst`): These files contain key value pairs.@@ -457,6 +459,9 @@ Bottom merges are paced by the fresh (not yet compacted) files of the family: th - Read all `*.del` files and delete the files that are listed in there. - Open all remaining `*.meta` files (memory mapped with `AccessMode::Mmap`, read onto the heap with   `AccessMode::File`), parse their AMQFs and drop entries for SST files that are obsolete.+- Check that the SST file of every remaining entry exists. If one is missing (e.g. because it was+  deleted from outside), opening fails with an error that names it, rather than a later lookup+  failing on a key stored in it. - SST and blob files are not opened while the database opens. Once the meta files are loaded, the SST   files start opening eagerly in the background (see [Reading](#reading)); a lookup that needs one   first opens it itself. An SST file is memory mapped in mmap access mode, or read with positional
turbopack/crates/turbo-persistence/src/db.rs48 + / 17 −
@@ -738,8 +738,14 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>      /// Loads an existing database directory and performs cleanup if necessary (and non     /// `read_only`).+    ///+    /// Entries whose name starts with `.` are ignored. Fails if the directory contains any other+    /// file it doesn't recognize, or if a live meta file references an SST file that doesn't+    /// exist (e.g. because it was deleted from outside), so that a damaged database is detected+    /// when it is opened rather than when a key stored in a missing file is read.     fn load_directory(&mut self, entries: ReadDir, read_only: bool) -> Result<bool> {         let mut meta_files = Vec::new();+        let mut sst_files = FxHashSet::default();         let current = match read_current_version(&self.path)? {             Some(version) => version.max_sequence_number,             None if !read_only => return Ok(false),@@ -749,6 +755,12 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>         let mut deleted_files = HashSet::new();         for entry in entries {             let entry = entry?;+            // Not ours, e.g. `.DS_Store`, or the `._<name>` AppleDouble files macOS writes next to+            // every file on filesystems without native support for extended attributes (exFAT,+            // FAT32, network shares).+            if entry.file_name().as_encoded_bytes().starts_with(b".") {+                continue;+            }             let path = entry.path();             if let Some(ext) = path.extension().and_then(|s| s.to_str()) {                 // A leftover `CURRENT.next` means a crash interrupted a `commit_current` before@@ -762,10 +774,11 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>                 }                 let seq: u32 = path                     .file_stem()-                    .context("File has no file stem")?-                    .to_str()-                    .context("File stem is not valid utf-8")?-                    .parse()?;+                    .and_then(|s| s.to_str())+                    .and_then(|s| s.parse().ok())+                    .with_context(|| {+                        format!("Unexpected file in persistence directory: {path:?}")+                    })?;                 if deleted_files.contains(&seq) {                     continue;                 }@@ -801,17 +814,24 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>                                 fs::remove_file(&path)?;                             }                         }-                        "blob" | "sst" => {-                            // ignore blobs and sst, they are read when needed-                        }-                        _ => {-                            if !path+                        "sst" => {+                            // Read when needed. Meta files reference SST files by their canonical+                            // name, so a file with an equivalent number (e.g. `1.sst`) doesn't+                            // count.+                            if path                                 .file_name()-                                .is_some_and(|s| s.as_encoded_bytes().starts_with(b"."))+                                .and_then(|name| name.to_str())+                                .is_some_and(|name| name == format!("{seq:08}.sst"))                             {-                                bail!("Unexpected file in persistence directory: {:?}", path);+                                sst_files.insert(seq);                             }                         }+                        "blob" => {+                            // read when needed+                        }+                        _ => {+                            bail!("Unexpected file in persistence directory: {:?}", path);+                        }                     }                 }             } else {@@ -823,12 +843,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>                         // Ignored, write-only                     }                     _ => {-                        if !path-                            .file_name()-                            .is_some_and(|s| s.as_encoded_bytes().starts_with(b"."))-                        {-                            bail!("Unexpected file in persistence directory: {:?}", path);-                        }+                        bail!("Unexpected file in persistence directory: {:?}", path);                     }                 }             }@@ -853,6 +868,22 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>             sst_filter.apply_filter(meta_file);         } +        // After filtering, the meta files only reference the SST files that are still in use.+        // SST files are opened lazily, so without this check a missing one would only be noticed+        // when a key stored in it is read.+        for meta_file in &meta_files {+            for entry in meta_file.entries() {+                let seq = entry.sequence_number();+                if !sst_files.contains(&seq) || deleted_files.contains(&seq) {+                    bail!(+                        "{seq:08}.sst referenced from {:08}.meta is missing in {}",+                        meta_file.sequence_number(),+                        self.path.display()+                    );+                }+            }+        }+         let inner = self.inner.get_mut();         for meta_file in meta_files {             inner.push_meta_file(meta_file);
turbopack/crates/turbo-persistence/src/tests.rs159 + / 0 −
@@ -4245,3 +4245,162 @@ fn healthy_database_is_readable(#[case] mmap: bool) -> Result<()> {     assert!(db.get(0, &vec![3u8])?.is_none());     Ok(()) }++/// Commits two batches (and, with `compact`, fully compacts them, which retires the SSTs of both+/// commits) and returns the `.sst` files a fresh open would read keys from.+fn committed_db_with_live_ssts(path: &Path, compact: bool) -> Result<Vec<std::path::PathBuf>> {+    let db = SerialDb::open(path.to_path_buf())?;+    for (key, value) in [(1u8, 10u8), (2, 20)] {+        let batch = db.write_batch()?;+        batch.put(0, vec![key], vec![value].into())?;+        db.commit_write_batch(batch)?;+    }+    if compact {+        db.compact(&CompactConfig::full())?;+    }+    db.shutdown();+    drop(db);+    let mut ssts = Vec::new();+    for entry in fs::read_dir(path)? {+        let path = entry?.path();+        if path.extension().is_some_and(|ext| ext == "sst") {+            ssts.push(path);+        }+    }+    ssts.sort();+    Ok(ssts)+}++/// An SST that a live `.meta` file references but that was removed from outside fails the open+/// itself, naming the file, rather than failing a later read of a key that lives in it.+#[rstest]+#[case::writable(false)]+#[case::read_only(true)]+fn open_fails_when_a_referenced_sst_is_missing(#[case] read_only: bool) -> Result<()> {+    let tempdir = tempfile::tempdir()?;+    let path = tempdir.path();+    let ssts = committed_db_with_live_ssts(path, false)?;+    assert_eq!(ssts.len(), 2, "each commit writes one SST");+    fs::remove_file(&ssts[0])?;+    let before = dir_snapshot(path)?;++    let result = if read_only {+        open_read_only(path).map(drop)+    } else {+        SerialDb::open(path.to_path_buf()).map(|db| db.shutdown())+    };+    let error = format!("{:#}", result.expect_err("opening must fail"));+    let missing = ssts[0].file_name().unwrap().to_str().unwrap();+    assert!(+        error.contains(missing),+        "the error should name the missing file {missing}: {error}"+    );+    assert!(+        error.contains(".meta"),+        "the error should name the referencing meta file: {error}"+    );+    if read_only {+        assert_eq!(+            dir_snapshot(path)?,+            before,+            "a failed read-only open must not modify the directory"+        );+    }+    Ok(())+}++/// A file with the same number but not the canonical name of a referenced SST (e.g. `1.sst`+/// instead of `00000001.sst`) doesn't stand in for the missing file.+#[test]+fn open_fails_when_a_referenced_sst_is_renamed() -> Result<()> {+    let tempdir = tempfile::tempdir()?;+    let path = tempdir.path();+    let ssts = committed_db_with_live_ssts(path, false)?;+    let canonical = ssts[0].file_name().unwrap().to_str().unwrap().to_owned();+    let seq: u32 = canonical.trim_end_matches(".sst").parse()?;+    fs::rename(&ssts[0], path.join(format!("{seq}.sst")))?;++    let error = format!(+        "{:#}",+        SerialDb::open(path.to_path_buf())+            .map(|db| db.shutdown())+            .expect_err("opening must fail")+    );+    assert!(+        error.contains(&canonical),+        "the error should name the missing file {canonical}: {error}"+    );+    Ok(())+}++/// SST files retired by compaction aren't referenced anymore, so a healthy compacted database+/// keeps opening and reading normally.+#[test]+fn open_ignores_ssts_retired_by_compaction() -> Result<()> {+    let tempdir = tempfile::tempdir()?;+    let path = tempdir.path();+    committed_db_with_live_ssts(path, true)?;+    // Reopen twice: the first open finishes deleting retired files, the second sees the result.+    for _ in 0..2 {+        let db = SerialDb::open(path.to_path_buf())?;+        assert_eq!(db.get(0, &[1u8])?.as_deref(), Some(&[10u8][..]));+        assert_eq!(db.get(0, &[2u8])?.as_deref(), Some(&[20u8][..]));+        db.shutdown();+    }+    Ok(())+}++/// Files whose name starts with `.` (such as the `._<name>` AppleDouble files macOS writes next+/// to every file on exFAT and other non-Apple filesystems) are not database files and are ignored,+/// whatever their extension.+#[rstest]+#[case::writable(false)]+#[case::read_only(true)]+fn open_ignores_dot_files(#[case] read_only: bool) -> Result<()> {+    let tempdir = tempfile::tempdir()?;+    let path = tempdir.path();+    committed_db_with_live_ssts(path, false)?;+    let names: Vec<String> = fs::read_dir(path)?+        .map(|entry| Ok(entry?.file_name().into_string().expect("utf-8 file name")))+        .collect::<Result<_>>()?;+    for name in names {+        fs::write(path.join(format!("._{name}")), b"\x00\x05\x16\x07")?;+    }+    fs::write(path.join(".DS_Store"), b"")?;++    let check = |db: &SerialDb| -> Result<()> {+        assert_eq!(db.get(0, &[1u8])?.as_deref(), Some(&[10u8][..]));+        assert_eq!(db.get(0, &[2u8])?.as_deref(), Some(&[20u8][..]));+        Ok(())+    };+    if read_only {+        check(&open_read_only(path)?)?;+    } else {+        let db = SerialDb::open(path.to_path_buf())?;+        check(&db)?;+        db.shutdown();+    }+    assert!(path.join("._CURRENT").exists(), "dot files are left alone");+    Ok(())+}++/// A file that looks like a database file but whose name isn't a sequence number fails the open+/// with an error that names it.+#[test]+fn open_names_unparseable_files() -> Result<()> {+    let tempdir = tempfile::tempdir()?;+    let path = tempdir.path();+    committed_db_with_live_ssts(path, false)?;+    fs::write(path.join("copy-of-00000001.sst"), b"")?;+    let error = format!(+        "{:#}",+        SerialDb::open(path.to_path_buf())+            .map(|db| db.shutdown())+            .expect_err("opening must fail")+    );+    assert!(+        error.contains("copy-of-00000001.sst"),+        "the error should name the file: {error}"+    );+    Ok(())+}
turbopack/crates/turbo-tasks-backend/src/database/db_invalidation.rs4 + / 0 −
@@ -59,6 +59,10 @@ pub mod invalidation_reasons {     /// Indicates that the user explicitly clicked a button or ran a command that invalidates the     /// cache.     pub const USER_REQUEST: &str = concat!(module_path!(), "::USER_REQUEST");+    /// This invalidation reason is used by [`crate::turbo_backing_storage`] when the database+    /// could not be opened, e.g. because files were deleted or modified from outside, and was+    /// deleted and replaced by an empty one.+    pub const UNREADABLE: &str = concat!(module_path!(), "::UNREADABLE"); }  /// Atomically create an invalidation marker.
turbopack/crates/turbo-tasks-backend/src/database/db_versioning.rs103 + / 2 −
@@ -1,11 +1,11 @@ use std::{     env,     ffi::{OsStr, OsString},-    path::{Path, PathBuf},+    path::{Component, Path, PathBuf},     time::{Duration, SystemTime}, }; -use anyhow::Result;+use anyhow::{Result, bail}; use fs_err::{DirEntry, metadata, read_dir, remove_dir_all, rename}; use jiff::Timestamp; use turbo_persistence::read_current_version;@@ -168,6 +168,45 @@ pub fn handle_db_versioning(     Ok(path) } +/// Removes the database directory of a single version (a path returned by+/// [`handle_db_versioning`] for `base_path`), e.g. because it can't be opened anymore. Directories+/// of other versions are left alone.+///+/// Fails without touching anything unless `versioned_path` is a direct child of `base_path` (it+/// may not be, e.g. when `TURBO_ENGINE_VERSION` is set to something unusual), so that this can+/// never remove the base directory, one of its parents, or anything outside of it.+///+/// The directory is first atomically renamed out of the way (a failure to do so is returned), so+/// that an interrupted or failed deletion can't leave a partially deleted database behind at+/// `versioned_path`, which a later start could open and read stale entries from. The renamed+/// directory is then deleted on a best-effort basis: anything left behind is removed by+/// [`handle_db_versioning`] the next time it runs.+pub(crate) fn remove_db_version_dir(base_path: &Path, versioned_path: &Path) -> Result<()> {+    let mut components = versioned_path+        .strip_prefix(base_path)+        .ok()+        .map(|relative| relative.components());+    let name = match components.as_mut().map(|c| (c.next(), c.next())) {+        Some((Some(Component::Normal(name)), None)) => name,+        _ => bail!(+            "Refusing to remove {}: it is not a database version directory in {}",+            versioned_path.display(),+            base_path.display()+        ),+    };+    let mut stale_name = OsString::from(DELETION_PREFIX);+    stale_name.push(name);+    let stale_path = base_path.join(stale_name);+    // A leftover from an earlier, interrupted removal would make the rename fail.+    if stale_path.exists() {+        remove_dir_all(&stale_path)?;+    }+    rename(versioned_path, &stale_path)?;+    // It's okay if this fails, `handle_db_versioning` finishes the removal.+    let _ = remove_dir_all(&stale_path);+    Ok(())+}+ /// How long to retain a database whose version isn't the current one. Falls back to /// [`DEFAULT_OTHER_DB_VERSION_TTL_DAYS`] if `TURBO_ENGINE_VERSION_TTL_DAYS` is unset or unparsable. fn other_db_version_ttl() -> Duration {@@ -268,6 +307,68 @@ mod tests {         names     } +    /// Removing a version directory removes exactly that directory, including a leftover from an+    /// earlier interrupted removal of it, and leaves other versions alone.+    #[test]+    fn test_remove_db_version_dir_removes_only_that_version() {+        let tmp_dir = test_temp_dir().unwrap();+        let base_path = tmp_dir.path();+        create_version_dir(base_path, CURRENT_VERSION, Duration::ZERO);+        create_version_dir(base_path, "other-dir", Duration::ZERO);+        create_version_dir(+            base_path,+            &format!("{DELETION_PREFIX}{CURRENT_VERSION}"),+            Duration::ZERO,+        );++        remove_db_version_dir(base_path, &base_path.join(CURRENT_VERSION)).unwrap();+        assert_eq!(entry_names(base_path), ["other-dir"]);+    }++    /// If the directory can't be moved out of the way, the error is returned and the database is+    /// left intact at its path rather than partially deleted.+    #[test]+    fn test_remove_db_version_dir_fails_without_partial_deletion() {+        let tmp_dir = test_temp_dir().unwrap();+        let base_path = tmp_dir.path();+        create_version_dir(base_path, CURRENT_VERSION, Duration::ZERO);+        // A file can't be removed with `remove_dir_all`, so the rename target stays occupied.+        fs::write(+            base_path.join(format!("{DELETION_PREFIX}{CURRENT_VERSION}")),+            b"",+        )+        .unwrap();++        remove_db_version_dir(base_path, &base_path.join(CURRENT_VERSION)).unwrap_err();+        assert!(base_path.join(CURRENT_VERSION).join("CURRENT").is_file());+    }++    /// Paths that aren't a version directory directly inside of the base directory are never+    /// removed.+    #[rstest]+    #[case::base_itself("")]+    #[case::current_dir(".")]+    #[case::parent("..")]+    #[case::escaping("../outside")]+    #[case::nested("mock-version/nested")]+    fn test_remove_db_version_dir_refuses_other_paths(#[case] relative: &str) {+        let tmp_dir = test_temp_dir().unwrap();+        let parent = tmp_dir.path();+        let base_path = parent.join("base");+        fs::create_dir(&base_path).unwrap();+        fs::create_dir(parent.join("outside")).unwrap();+        fs::create_dir_all(base_path.join("mock-version").join("nested")).unwrap();++        let error = remove_db_version_dir(&base_path, &base_path.join(relative)).unwrap_err();+        assert!(+            format!("{error:#}").contains("Refusing to remove"),+            "unexpected error: {error:#}"+        );+        assert_eq!(entry_names(parent), ["base", "outside"]);+        assert_eq!(entry_names(&base_path), ["mock-version"]);+        assert_eq!(entry_names(&base_path.join("mock-version")), ["nested"]);+    }+     /// Only the most recently used other version survives, and the current version survives     /// regardless of how stale it is. On CI no other version survives at all.     #[rstest]
turbopack/crates/turbo-tasks-backend/src/kv_backing_storage.rs238 + / 6 −
@@ -23,7 +23,7 @@ use crate::{     backing_storage::{SnapshotItem, SnapshotMeta, compute_task_type_hash_from_components},     database::{         db_invalidation::{StartupCacheState, check_db_invalidation_and_cleanup, invalidate_db},-        db_versioning::handle_db_versioning,+        db_versioning::{handle_db_versioning, remove_db_version_dir},         key_value_database::KeySpace,         turbo::{TurboKeyValueDatabase, TurboWriteBatch},         write_batch::WriteBuffer,@@ -169,26 +169,72 @@ impl TurboBackingStorage {     /// - Creates a directory per version, with a maximum number of old versions and performs     ///   automatic cleanup of old versions.     /// - Checks for a database invalidation marker file, and cleans up the database as needed.+    /// - If the database can't be opened (e.g. because its files were deleted or modified from+    ///   outside), deletes the directory of this version and starts over with an empty database.+    ///   This is reported as [`StartupCacheState::Invalidated`] with+    ///   [`invalidation_reasons::UNREADABLE`].     /// - [Registers a dynamic panic hook][turbo_tasks::panic_hooks] to invalidate the database upon     ///   a panic. This invalidates the database using [`invalidation_reasons::PANIC`].     ///+    /// Like the panic hook, replacing an unreadable database is skipped when+    /// `TURBO_ENGINE_SKIP_INVALIDATE_ON_PANIC` or `__NEXT_TEST_MODE` is set: the error is returned+    /// instead.+    ///     /// Along with returning a [`TurboBackingStorage`], this returns a     /// [`StartupCacheState`], which can be used by the application for logging information to the     /// user or telemetry about the cache.     pub(crate) fn open_versioned_on_disk(         base_path: PathBuf,         version_info: &GitVersionInfo,         is_ci: bool,-        database: impl FnOnce(PathBuf) -> Result<TurboKeyValueDatabase>,+        database: impl Fn(PathBuf) -> Result<TurboKeyValueDatabase>,+    ) -> Result<(Self, StartupCacheState)> {+        Self::open_versioned_on_disk_with(+            base_path,+            version_info,+            is_ci,+            should_invalidate_on_panic(),+            database,+        )+    }++    /// [`Self::open_versioned_on_disk`], with `invalidate_on_failure` in place of+    /// [`should_invalidate_on_panic`]: whether to register the panic hook and to replace a+    /// database that can't be opened.+    fn open_versioned_on_disk_with(+        base_path: PathBuf,+        version_info: &GitVersionInfo,+        is_ci: bool,+        invalidate_on_failure: bool,+        database: impl Fn(PathBuf) -> Result<TurboKeyValueDatabase>,     ) -> Result<(Self, StartupCacheState)> {-        let startup_cache_state = check_db_invalidation_and_cleanup(&base_path)+        let mut startup_cache_state = check_db_invalidation_and_cleanup(&base_path)             .context("Failed to check database invalidation and cleanup")?;         let versioned_path = handle_db_versioning(&base_path, version_info, is_ci)             .context("Failed to handle database versioning")?;-        let database = (database)(versioned_path).context("Failed to open database")?;+        let database = match database(versioned_path.clone()) {+            Ok(database) => database,+            Err(open_error) if invalidate_on_failure => {+                // The cache is only an optimization, so rather than failing, pay for a cold start.+                // The failed open doesn't hold on to the directory, so it can be removed.+                let open_error = open_error.context("Failed to open database");+                let database = remove_db_version_dir(&base_path, &versioned_path)+                    .and_then(|()| database(versioned_path))+                    .with_context(|| {+                        format!(+                            "Failed to replace a database that could not be opened: {open_error:?}"+                        )+                    })?;+                startup_cache_state = StartupCacheState::Invalidated {+                    reason_code: Some(invalidation_reasons::UNREADABLE.to_string()),+                };+                database+            }+            Err(open_error) => return Err(open_error.context("Failed to open database")),+        };         let backing_storage = Self {             inner: Arc::new_cyclic(move |weak_inner: &Weak<TurboBackingStorageInner>| {-                let panic_hook_guard = if should_invalidate_on_panic() {+                let panic_hook_guard = if invalidate_on_failure {                     let weak_inner = weak_inner.clone();                     Some(register_panic_hook(Box::new(move |_| {                         let Some(inner) = weak_inner.upgrade() else {@@ -564,7 +610,7 @@ fn save_infra(  #[cfg(test)] mod tests {-    use std::borrow::Borrow;+    use std::{borrow::Borrow, path::Path};      use turbo_tasks::TaskId; @@ -1048,4 +1094,190 @@ mod tests {         assert_eq!(message, "Failed to restore: some bug");         Ok(())     }++    const TEST_VERSION: GitVersionInfo<'static> = GitVersionInfo {+        describe: "v-current",+        dirty: false,+    };++    /// Writes a cache entry into the current version's database under `base_path` and then removes+    /// one of its `.sst` files, the way something outside of Turbopack might. Also creates the+    /// database of another version next to it. Returns the removed file's name.+    fn unreadable_versioned_db(base_path: &Path) -> Result<String> {+        let versioned_path = base_path.join(TEST_VERSION.describe);+        let db = TurboKeyValueDatabase::new(versioned_path.clone(), TEST_STORAGE_OPTIONS)?;+        write_task_cache_entry(&db, 1, TaskId::try_from(1u32).unwrap())?;+        db.shutdown();+        drop(db);++        let other = base_path.join("v-other");+        fs_err::create_dir_all(&other)?;+        fs_err::write(other.join("CURRENT"), b"untouched")?;++        let sst = fs_err::read_dir(&versioned_path)?+            .map(|entry| entry.map(|entry| entry.path()))+            .collect::<std::io::Result<Vec<_>>>()?+            .into_iter()+            .find(|path| path.extension().is_some_and(|ext| ext == "sst"))+            .expect("the commit should have written an SST file");+        fs_err::remove_file(&sst)?;+        Ok(sst.file_name().unwrap().to_str().unwrap().to_owned())+    }++    /// A database that can't be opened is deleted and replaced by an empty one, and the deletion+    /// is reported, so that a damaged cache costs a cold start instead of failing the process.+    #[tokio::test(flavor = "multi_thread")]+    async fn test_open_versioned_on_disk_replaces_an_unreadable_database() -> Result<()> {+        let tempdir = test_temp_dir()?;+        let base_path = tempdir.path();+        unreadable_versioned_db(base_path)?;++        let (storage, state) = TurboBackingStorage::open_versioned_on_disk_with(+            base_path.to_path_buf(),+            &TEST_VERSION,+            false,+            true,+            |path| TurboKeyValueDatabase::new(path, TEST_STORAGE_OPTIONS),+        )?;+        assert!(+            matches!(+                &state,+                StartupCacheState::Invalidated { reason_code: Some(reason) }+                    if reason == invalidation_reasons::UNREADABLE+            ),+            "the deletion should be reported as UNREADABLE"+        );++        // The new database starts out empty and is writable.+        let db = &storage.inner.database;+        assert_eq!(task_cache_ids(db, 1)?, vec![]);+        write_task_cache_entry(db, 2, TaskId::try_from(2u32).unwrap())?;+        assert_eq!(+            task_cache_ids(db, 2)?,+            vec![TaskId::try_from(2u32).unwrap()]+        );+        db.shutdown();+        drop(storage);++        // Other versions are not touched.+        assert_eq!(+            fs_err::read(base_path.join("v-other").join("CURRENT"))?,+            b"untouched"+        );++        // The replacement is a normal database that is reused by the next start.+        let (storage, state) = TurboBackingStorage::open_versioned_on_disk_with(+            base_path.to_path_buf(),+            &TEST_VERSION,+            false,+            true,+            |path| TurboKeyValueDatabase::new(path, TEST_STORAGE_OPTIONS),+        )?;+        assert!(+            !matches!(state, StartupCacheState::Invalidated { .. }),+            "a replaced database must not be replaced again"+        );+        let db = &storage.inner.database;+        assert_eq!(+            task_cache_ids(db, 2)?,+            vec![TaskId::try_from(2u32).unwrap()]+        );+        db.shutdown();+        Ok(())+    }++    /// If the database that can't be opened can't be removed either, opening isn't retried and+    /// the error includes the original failure.+    #[tokio::test(flavor = "multi_thread")]+    async fn test_open_versioned_on_disk_returns_removal_failures() -> Result<()> {+        let tempdir = test_temp_dir()?;+        let base_path = tempdir.path();+        let attempts = std::sync::atomic::AtomicUsize::new(0);+        let stale_path = base_path.join(format!("__stale_{}", TEST_VERSION.describe));++        let error = TurboBackingStorage::open_versioned_on_disk_with(+            base_path.to_path_buf(),+            &TEST_VERSION,+            false,+            true,+            |path| {+                attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+                fs_err::create_dir_all(&path)?;+                // Occupy the path the database directory is moved to before it's deleted with a+                // file, which can't be removed as a directory, so that the removal fails. (Done+                // here because opening cleans up such leftovers before calling this.)+                fs_err::write(&stale_path, b"")?;+                anyhow::bail!("injected open failure")+            },+        )+        .map(|_| ())+        .expect_err("opening must fail");+        assert_eq!(attempts.into_inner(), 1, "no retry after a failed removal");+        assert!(+            format!("{error:#}").contains("injected open failure"),+            "the error should include the original failure: {error:#}"+        );+        assert!(base_path.join(TEST_VERSION.describe).is_dir());+        Ok(())+    }++    /// If the replacement database can't be opened either, opening is attempted only once more,+    /// and the error includes both the original failure and the failure of the retry.+    #[tokio::test(flavor = "multi_thread")]+    async fn test_open_versioned_on_disk_retries_once_and_keeps_both_errors() -> Result<()> {+        let tempdir = test_temp_dir()?;+        let base_path = tempdir.path();+        let attempts = std::sync::atomic::AtomicUsize::new(0);++        let error = TurboBackingStorage::open_versioned_on_disk_with(+            base_path.to_path_buf(),+            &TEST_VERSION,+            false,+            true,+            |path| {+                fs_err::create_dir_all(&path)?;+                let attempt = attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;+                anyhow::bail!("injected open failure {attempt}")+            },+        )+        .map(|_| ())+        .expect_err("opening must fail");+        assert_eq!(attempts.into_inner(), 2, "open once, then retry once");+        let error = format!("{error:#}");+        assert!(+            error.contains("injected open failure 1") && error.contains("injected open failure 2"),+            "the error should include both failures: {error}"+        );+        Ok(())+    }++    /// With recovery disabled (to surface such problems instead of hiding them), the open error is+    /// returned unchanged and nothing is deleted.+    #[tokio::test(flavor = "multi_thread")]+    async fn test_open_versioned_on_disk_without_recovery_returns_the_error() -> Result<()> {+        let tempdir = test_temp_dir()?;+        let base_path = tempdir.path();+        let missing = unreadable_versioned_db(base_path)?;++        let error = TurboBackingStorage::open_versioned_on_disk_with(+            base_path.to_path_buf(),+            &TEST_VERSION,+            false,+            false,+            |path| TurboKeyValueDatabase::new(path, TEST_STORAGE_OPTIONS),+        )+        .map(|_| ())+        .expect_err("opening must fail");+        assert!(+            format!("{error:#}").contains(&missing),+            "the error should name the missing file {missing}: {error:#}"+        );+        assert!(+            base_path+                .join(TEST_VERSION.describe)+                .join("CURRENT")+                .exists()+        );+        Ok(())+    } }
turbopack/crates/turbo-tasks-backend/src/lib.rs3 + / 0 −
@@ -45,6 +45,9 @@ pub struct BackingStorageOptions { /// Creates a `BackingStorage` to be passed to [`TurboTasksBackend::new`]. /// /// Information about the state of the on-disk cache is returned using [`StartupCacheState`].+/// A database that can't be opened is replaced by an empty one and reported as+/// [`StartupCacheState::Invalidated`], unless invalidation is disabled (see+/// `TURBO_ENGINE_SKIP_INVALIDATE_ON_PANIC`), in which case the error is returned. pub fn turbo_backing_storage(     base_path: &Path,     version_info: &GitVersionInfo,