Skip to main content

turbo_tasks_backend/
kv_backing_storage.rs

1use std::{
2    borrow::Borrow,
3    env,
4    fmt::Display,
5    path::{Path, PathBuf},
6    sync::{Arc, LazyLock, Mutex, PoisonError, Weak},
7};
8
9use anyhow::{Context, Result};
10use smallvec::SmallVec;
11use turbo_bincode::{new_turbo_bincode_decoder, turbo_bincode_decode, turbo_bincode_encode};
12use turbo_persistence::{CacheFileUnreadable, CommitStats};
13use turbo_tasks::{
14    DynTaskInputs, PersistentCacheUnreadablePanic, RawVc, TaskId,
15    macro_helpers::NativeFunction,
16    panic_hooks::{PanicHookGuard, register_panic_hook},
17    parallel,
18};
19
20use crate::{
21    GitVersionInfo,
22    backend::{SpecificTaskDataCategory, TtlCounter, storage_schema::TaskStorage},
23    backing_storage::{SnapshotItem, SnapshotMeta, compute_task_type_hash_from_components},
24    database::{
25        db_invalidation::{StartupCacheState, check_db_invalidation_and_cleanup, invalidate_db},
26        db_versioning::{handle_db_versioning, remove_db_version_dir},
27        key_value_database::KeySpace,
28        turbo::{TurboKeyValueDatabase, TurboWriteBatch},
29        write_batch::WriteBuffer,
30    },
31    db_invalidation::invalidation_reasons,
32};
33
34/// The fixed keys in the [`KeySpace::Infra`] keyspace.
35#[derive(Clone, Copy)]
36#[repr(u8)]
37enum InfraKey {
38    NextFreeTaskId = 0,
39    GcRoots = 1,
40}
41
42impl InfraKey {
43    fn key(self) -> ByteKey {
44        ByteKey::new(self as u8)
45    }
46}
47
48struct ByteKey([u8; 1]);
49
50impl ByteKey {
51    fn new(value: u8) -> Self {
52        Self([value])
53    }
54}
55
56impl AsRef<[u8]> for ByteKey {
57    fn as_ref(&self) -> &[u8] {
58        &self.0
59    }
60}
61
62struct IntKey([u8; 4]);
63
64impl IntKey {
65    fn new(value: u32) -> Self {
66        Self(value.to_le_bytes())
67    }
68}
69
70impl AsRef<[u8]> for IntKey {
71    fn as_ref(&self) -> &[u8] {
72        &self.0
73    }
74}
75
76fn as_u32(bytes: impl Borrow<[u8]>) -> Result<u32> {
77    let n = u32::from_le_bytes(bytes.borrow().try_into()?);
78    Ok(n)
79}
80
81// We want to invalidate the cache on panic for most users, but this is a band-aid to underlying
82// problems in turbo-tasks.
83//
84// If we invalidate the cache upon panic and it "fixes" the issue upon restart, users typically
85// won't report bugs to us, and we'll never find root-causes for these problems.
86//
87// These overrides let us avoid the cache invalidation / error suppression within Vercel so that we
88// feel these pain points and fix the root causes of bugs.
89fn should_invalidate_on_panic() -> bool {
90    fn env_is_falsy(key: &str) -> bool {
91        env::var_os(key)
92            .is_none_or(|value| ["".as_ref(), "0".as_ref(), "false".as_ref()].contains(&&*value))
93    }
94    static SHOULD_INVALIDATE: LazyLock<bool> = LazyLock::new(|| {
95        env_is_falsy("TURBO_ENGINE_SKIP_INVALIDATE_ON_PANIC") && env_is_falsy("__NEXT_TEST_MODE")
96    });
97    *SHOULD_INVALIDATE
98}
99
100/// Builds the message of a [`PersistentCacheUnreadablePanic`] if `error` was caused by a database
101/// file that couldn't be read (see [`CacheFileUnreadable`]), otherwise returns `None`.
102///
103/// `base_path` is the directory of the filesystem cache (`None` for in-memory storage), and
104/// `invalidates_on_panic` whether the panic hook registered by
105/// [`TurboBackingStorage::open_versioned_on_disk`] invalidates the cache (see
106/// [`should_invalidate_on_panic`]). That invalidation is best-effort, so the message doesn't claim
107/// that it succeeded.
108fn unreadable_cache_message(
109    error: &anyhow::Error,
110    base_path: Option<&Path>,
111    invalidates_on_panic: bool,
112) -> Option<String> {
113    let unreadable = CacheFileUnreadable::find(error)?;
114    let what_to_do = match base_path {
115        Some(base_path) if invalidates_on_panic => format!(
116            "Turbopack will try to invalidate the filesystem cache, so that it is rebuilt on the \
117             next start. Restart to continue. If this error comes back, delete {} manually.",
118            base_path.display()
119        ),
120        Some(base_path) => format!("Delete {} and restart to continue.", base_path.display()),
121        None => "Restart to continue.".to_string(),
122    };
123    Some(format!(
124        "Turbopack's filesystem cache could not be read: the cache file {} is missing or \
125         corrupted. It may have been deleted or modified outside of Turbopack while Turbopack was \
126         running.\n{what_to_do}\n\nDetails: {error:?}",
127        unreadable.file_name()
128    ))
129}
130
131struct TurboBackingStorageInner {
132    database: TurboKeyValueDatabase,
133    /// Used when calling [`TurboBackingStorage::invalidate`]. Can be `None` in the
134    /// memory-only/no-op storage case.
135    base_path: Option<PathBuf>,
136    /// Used to skip calling [`invalidate_db`] when the database has already been invalidated.
137    invalidated: Mutex<bool>,
138    /// We configure a panic hook to invalidate the cache. This guard cleans up our panic hook upon
139    /// drop.
140    _panic_hook_guard: Option<PanicHookGuard>,
141}
142
143/// The higher-level backing storage passed to [`TurboTasksBackend::new`], used by
144/// [`crate::turbo_backing_storage`] and [`crate::noop_backing_storage`].
145///
146/// Wraps a low-level `TurboKeyValueDatabase` and adapts it into the persistence operations the
147/// backend needs (snapshots, task-candidate lookups, etc.).
148///
149/// [`TurboTasksBackend::new`]: crate::TurboTasksBackend::new
150pub struct TurboBackingStorage {
151    // wrapped so that `register_panic_hook` can hold a weak reference to `inner`.
152    inner: Arc<TurboBackingStorageInner>,
153}
154
155impl TurboBackingStorage {
156    pub(crate) fn new_in_memory(database: TurboKeyValueDatabase) -> Self {
157        Self {
158            inner: Arc::new(TurboBackingStorageInner {
159                database,
160                base_path: None,
161                invalidated: Mutex::new(false),
162                _panic_hook_guard: None,
163            }),
164        }
165    }
166
167    /// Handles boilerplate logic for an on-disk persisted database with versioning.
168    ///
169    /// - Creates a directory per version, with a maximum number of old versions and performs
170    ///   automatic cleanup of old versions.
171    /// - Checks for a database invalidation marker file, and cleans up the database as needed.
172    /// - If the database can't be opened (e.g. because its files were deleted or modified from
173    ///   outside), deletes the directory of this version and starts over with an empty database.
174    ///   This is reported as [`StartupCacheState::Invalidated`] with
175    ///   [`invalidation_reasons::UNREADABLE`].
176    /// - [Registers a dynamic panic hook][turbo_tasks::panic_hooks] to invalidate the database upon
177    ///   a panic. This invalidates the database using [`invalidation_reasons::PANIC`].
178    ///
179    /// Like the panic hook, replacing an unreadable database is skipped when
180    /// `TURBO_ENGINE_SKIP_INVALIDATE_ON_PANIC` or `__NEXT_TEST_MODE` is set: the error is returned
181    /// instead.
182    ///
183    /// Along with returning a [`TurboBackingStorage`], this returns a
184    /// [`StartupCacheState`], which can be used by the application for logging information to the
185    /// user or telemetry about the cache.
186    pub(crate) fn open_versioned_on_disk(
187        base_path: PathBuf,
188        version_info: &GitVersionInfo,
189        is_ci: bool,
190        database: impl Fn(PathBuf) -> Result<TurboKeyValueDatabase>,
191    ) -> Result<(Self, StartupCacheState)> {
192        Self::open_versioned_on_disk_with(
193            base_path,
194            version_info,
195            is_ci,
196            should_invalidate_on_panic(),
197            database,
198        )
199    }
200
201    /// [`Self::open_versioned_on_disk`], with `invalidate_on_failure` in place of
202    /// [`should_invalidate_on_panic`]: whether to register the panic hook and to replace a
203    /// database that can't be opened.
204    fn open_versioned_on_disk_with(
205        base_path: PathBuf,
206        version_info: &GitVersionInfo,
207        is_ci: bool,
208        invalidate_on_failure: bool,
209        database: impl Fn(PathBuf) -> Result<TurboKeyValueDatabase>,
210    ) -> Result<(Self, StartupCacheState)> {
211        let mut startup_cache_state = check_db_invalidation_and_cleanup(&base_path)
212            .context("Failed to check database invalidation and cleanup")?;
213        let versioned_path = handle_db_versioning(&base_path, version_info, is_ci)
214            .context("Failed to handle database versioning")?;
215        let database = match database(versioned_path.clone()) {
216            Ok(database) => database,
217            Err(open_error) if invalidate_on_failure => {
218                // The cache is only an optimization, so rather than failing, pay for a cold start.
219                // The failed open doesn't hold on to the directory, so it can be removed.
220                let open_error = open_error.context("Failed to open database");
221                let database = remove_db_version_dir(&base_path, &versioned_path)
222                    .and_then(|()| database(versioned_path))
223                    .with_context(|| {
224                        format!(
225                            "Failed to replace a database that could not be opened: {open_error:?}"
226                        )
227                    })?;
228                startup_cache_state = StartupCacheState::Invalidated {
229                    reason_code: Some(invalidation_reasons::UNREADABLE.to_string()),
230                };
231                database
232            }
233            Err(open_error) => return Err(open_error.context("Failed to open database")),
234        };
235        let backing_storage = Self {
236            inner: Arc::new_cyclic(move |weak_inner: &Weak<TurboBackingStorageInner>| {
237                let panic_hook_guard = if invalidate_on_failure {
238                    let weak_inner = weak_inner.clone();
239                    Some(register_panic_hook(Box::new(move |_| {
240                        let Some(inner) = weak_inner.upgrade() else {
241                            return;
242                        };
243                        // If a panic happened that must mean something deep inside of turbopack
244                        // or turbo-tasks failed, and it may be hard to recover. We don't want
245                        // the cache to stick around, as that may persist bugs. Make a
246                        // best-effort attempt to invalidate the database (ignoring failures).
247                        let _ = inner.invalidate(invalidation_reasons::PANIC);
248                    })))
249                } else {
250                    None
251                };
252                TurboBackingStorageInner {
253                    database,
254                    base_path: Some(base_path),
255                    invalidated: Mutex::new(false),
256                    _panic_hook_guard: panic_hook_guard,
257                }
258            }),
259        };
260        Ok((backing_storage, startup_cache_state))
261    }
262}
263
264impl TurboBackingStorageInner {
265    fn invalidate(&self, reason_code: &str) -> Result<()> {
266        // `base_path` is `None` for in-memory backing storage (see `noop_backing_storage`).
267        if let Some(base_path) = &self.base_path {
268            // Invalidation could happen frequently if there's a bunch of panics. We only need to
269            // invalidate once, so grab a lock.
270            let mut invalidated_guard = self
271                .invalidated
272                .lock()
273                .unwrap_or_else(PoisonError::into_inner);
274            if *invalidated_guard {
275                return Ok(());
276            }
277            // Invalidate first, as it's a very fast atomic operation. `prevent_writes` is allowed
278            // to be slower (e.g. wait for a lock) and is allowed to corrupt the database with
279            // partial writes.
280            invalidate_db(base_path, reason_code)?;
281            self.database.prevent_writes();
282            // Avoid redundant invalidations from future panics
283            *invalidated_guard = true;
284        }
285        Ok(())
286    }
287
288    /// Used to read the next free task ID from the database.
289    fn get_infra_u32(&self, key: InfraKey) -> Result<Option<u32>> {
290        self.database
291            .get(KeySpace::Infra, key.key().as_ref())?
292            .map(as_u32)
293            .transpose()
294    }
295}
296
297impl TurboBackingStorage {
298    /// Called when the database should be invalidated upon re-initialization.
299    ///
300    /// This typically means that we'll restart the process or `turbo-tasks` soon with a fresh
301    /// database. If this happens, there's no point in writing anything else to disk, or flushing
302    /// during [`TurboTasksBackend::stop`].
303    ///
304    /// [`TurboTasksBackend::stop`]: turbo_tasks::backend::Backend::stop
305    pub(crate) fn invalidate(&self, reason_code: &str) -> Result<()> {
306        self.inner.invalidate(reason_code)
307    }
308
309    /// Panics because reading from the database failed with `error`, which can't be recovered
310    /// from: the task graph can't be restored without that data.
311    ///
312    /// If a database file couldn't be read (see [`CacheFileUnreadable`]), e.g. because it was
313    /// deleted or modified by another process while it was in use, the panic payload is a
314    /// [`PersistentCacheUnreadablePanic`] with a message explaining that and what to do about it.
315    /// Otherwise this panics with `description` and `error` as before.
316    #[cold]
317    #[track_caller]
318    pub(crate) fn panic_on_read_error(&self, description: impl Display, error: anyhow::Error) -> ! {
319        if let Some(message) = unreadable_cache_message(
320            &error,
321            self.inner.base_path.as_deref(),
322            should_invalidate_on_panic(),
323        ) {
324            std::panic::panic_any(PersistentCacheUnreadablePanic { message });
325        }
326        panic!("{description}: {error:?}");
327    }
328
329    pub(crate) fn next_free_task_id(&self) -> Result<TaskId> {
330        Ok(self
331            .inner
332            .get_infra_u32(InfraKey::NextFreeTaskId)
333            .context("Unable to read next free task id from database")?
334            .map_or(Ok(TaskId::MIN), TaskId::try_from)?)
335    }
336
337    /// Reads the persisted GC roots set (see [`InfraKey::GcRoots`]). Empty on a fresh database.
338    pub(crate) fn roots(&self) -> Result<Vec<(TaskId, TtlCounter)>> {
339        fn get(database: &TurboKeyValueDatabase) -> Result<Vec<(TaskId, TtlCounter)>> {
340            let Some(roots) = database.get(KeySpace::Infra, InfraKey::GcRoots.key().as_ref())?
341            else {
342                return Ok(Vec::new());
343            };
344            let roots = turbo_bincode_decode(roots.borrow())?;
345            Ok(roots)
346        }
347        get(&self.inner.database).context("Unable to read GC roots from database")
348    }
349
350    pub(crate) fn save_snapshot<I>(
351        &self,
352        roots: Option<Vec<(TaskId, TtlCounter)>>,
353        snapshots: Vec<I>,
354    ) -> Result<SnapshotMeta>
355    where
356        I: IntoIterator<Item = SnapshotItem> + Send + Sync,
357    {
358        let _span = tracing::info_span!("save snapshot").entered();
359        let batch = self.inner.database.write_batch()?;
360
361        {
362            let span = tracing::trace_span!("update task data");
363            let mut snapshot_meta =
364                parallel::map_collect_owned::<_, _, Result<Vec<_>>>(snapshots, |shard: I| {
365                    let _span = span.clone().entered();
366                    let mut max_new_task_id = 0;
367                    let mut data_items = 0;
368                    let mut meta_items = 0;
369                    let mut task_cache_items = 0;
370                    for item in shard {
371                        match item {
372                            SnapshotItem::Put {
373                                task_id,
374                                meta,
375                                data,
376                                task_type_hash,
377                                ..
378                            } => {
379                                let key = IntKey::new(*task_id);
380                                let key = key.as_ref();
381                                if let Some(meta) = meta {
382                                    batch.put(
383                                        KeySpace::TaskMeta,
384                                        WriteBuffer::Borrowed(key),
385                                        WriteBuffer::Owned(meta),
386                                    )?;
387                                    meta_items += 1;
388                                }
389                                if let Some(data) = data {
390                                    batch.put(
391                                        KeySpace::TaskData,
392                                        WriteBuffer::Borrowed(key),
393                                        WriteBuffer::Owned(data),
394                                    )?;
395                                    data_items += 1;
396                                }
397                                // Register the task type only for new tasks.
398                                if let Some(task_type_hash) = task_type_hash {
399                                    batch.put(
400                                        KeySpace::TaskCache,
401                                        WriteBuffer::Borrowed(&task_type_hash),
402                                        WriteBuffer::Borrowed(key),
403                                    )?;
404                                    task_cache_items += 1;
405                                    max_new_task_id = max_new_task_id.max(*task_id);
406                                }
407                            }
408                            SnapshotItem::Delete {
409                                task_id,
410                                task_type_hash,
411                            } => {
412                                let key = IntKey::new(*task_id);
413                                let key = key.as_ref();
414                                batch.delete(KeySpace::TaskMeta, WriteBuffer::Borrowed(key))?;
415                                batch.delete(KeySpace::TaskData, WriteBuffer::Borrowed(key))?;
416                                // TaskCache is MultiValue, delete just this id from the bucket.
417                                batch.delete_value(
418                                    KeySpace::TaskCache,
419                                    WriteBuffer::Borrowed(&task_type_hash[..]),
420                                    WriteBuffer::Borrowed(key),
421                                )?;
422                            }
423                        }
424                    }
425                    Ok(SnapshotMeta {
426                        data_items,
427                        meta_items,
428                        task_cache_items,
429                        // The on-disk byte totals aren't known until the batch is committed
430                        // below; they're filled in from `CommitStats` after `batch.commit()`.
431                        bytes_written: 0,
432                        bytes_deleted: 0,
433                        max_next_task_id: max_new_task_id,
434                    })
435                })?
436                .into_iter()
437                .reduce(|t1, t2| t1.merge(t2))
438                .unwrap_or_default();
439
440            let span = tracing::trace_span!("flush task data");
441            parallel::try_for_each(
442                &[KeySpace::TaskMeta, KeySpace::TaskData, KeySpace::TaskCache],
443                |&key_space| {
444                    let _span = span.clone().entered();
445                    // Safety: `map_collect_owned` has returned, so no concurrent `put` or `delete`
446                    // on these key spaces are in-flight.
447                    unsafe { batch.flush(key_space) }
448                },
449            )?;
450
451            let mut next_task_id = get_next_free_task_id(&batch)?;
452            next_task_id = next_task_id.max(snapshot_meta.max_next_task_id + 1);
453
454            save_infra(&batch, next_task_id, roots)?;
455            {
456                let _span = tracing::trace_span!("commit").entered();
457                // Byte totals are the physical on-disk bytes (post-compression, including .sst /
458                // .blob / .meta files) produced and removed by the commit.
459                let stats = batch.commit().context("Unable to commit snapshot")?;
460                snapshot_meta.bytes_written = stats.bytes_written;
461                snapshot_meta.bytes_deleted = stats.bytes_deleted;
462            }
463            Ok(snapshot_meta)
464        }
465    }
466
467    pub(crate) fn lookup_task_candidates(
468        &self,
469        native_fn: &'static NativeFunction,
470        this: Option<RawVc>,
471        arg: &dyn DynTaskInputs,
472    ) -> Result<SmallVec<[TaskId; 1]>> {
473        let inner = &*self.inner;
474        if inner.database.is_empty() {
475            // Checking if the database is empty is a performance optimization
476            // to avoid computing the hash.
477            return Ok(SmallVec::new());
478        }
479        let hash = compute_task_type_hash_from_components(native_fn, this, arg);
480        let buffers = inner
481            .database
482            .get_multiple(KeySpace::TaskCache, &hash)
483            .with_context(|| {
484                format!("Looking up task id for {native_fn:?}(this={this:?}) from database failed")
485            })?;
486
487        let mut task_ids = SmallVec::with_capacity(buffers.len());
488        for bytes in buffers {
489            let bytes = Borrow::<[u8]>::borrow(&bytes).try_into()?;
490            let id = TaskId::try_from(u32::from_le_bytes(bytes)).unwrap();
491            task_ids.push(id);
492        }
493        Ok(task_ids)
494    }
495
496    /// Reads the stored `category` for `task_id`.
497    ///
498    /// `None` means the database had no key for this category. That is distinct from `Some`
499    /// of an empty [`TaskStorage`] (a key that decoded to nothing): `MustExist` treats a missing
500    /// requested category as a missing task, regardless of the other category.
501    pub(crate) fn lookup_data(
502        &self,
503        task_id: TaskId,
504        category: SpecificTaskDataCategory,
505    ) -> Result<Option<TaskStorage>> {
506        let inner = &*self.inner;
507        let Some(bytes) = inner
508            .database
509            .get(category.key_space(), IntKey::new(*task_id).as_ref())
510            .with_context(|| {
511                format!("Looking up task storage for {task_id} from database failed")
512            })?
513        else {
514            return Ok(None);
515        };
516        let mut storage = TaskStorage::default();
517        let mut decoder = new_turbo_bincode_decoder(bytes.borrow());
518        storage
519            .decode(category, &mut decoder)
520            .with_context(|| format!("Failed to decode {category:?}"))?;
521        Ok(Some(storage))
522    }
523
524    /// Looks up and decodes the `category` of many tasks. Calls `on_result` with the index of the
525    /// task in `task_ids` and its decoded storage, or `None` if the category has no key on disk.
526    ///
527    /// When this returns `Ok`, `on_result` was called exactly once for every index. The calls
528    /// happen in no particular order and may run concurrently on other threads, so decoding
529    /// runs in parallel for large batches. A read, decode or `on_result` error aborts the
530    /// batch.
531    pub(crate) fn batch_lookup_data(
532        &self,
533        task_ids: &[TaskId],
534        category: SpecificTaskDataCategory,
535        on_result: impl Fn(usize, Option<TaskStorage>) -> Result<()> + Sync,
536    ) -> Result<()> {
537        let inner = &*self.inner;
538        let int_keys: Vec<_> = task_ids.iter().map(|&id| IntKey::new(*id)).collect();
539        let keys = int_keys.iter().map(|k| k.as_ref()).collect::<Vec<_>>();
540        inner
541            .database
542            .batch_get(category.key_space(), &keys, |index, opt_bytes| {
543                let Some(bytes) = opt_bytes else {
544                    return on_result(index, None);
545                };
546                let mut storage = TaskStorage::new();
547                let mut decoder = new_turbo_bincode_decoder(bytes.borrow());
548                storage
549                    .decode(category, &mut decoder)
550                    .map_err(|e| anyhow::anyhow!("Failed to decode {category:?}: {e:?}"))?;
551                on_result(index, Some(storage))
552            })
553            .with_context(|| {
554                format!(
555                    "Looking up typed data for {} tasks from database failed",
556                    task_ids.len()
557                )
558            })
559    }
560
561    pub(crate) fn compact(&self) -> Result<Option<CommitStats>> {
562        self.inner.database.compact()
563    }
564
565    pub(crate) fn shutdown(&self) {
566        self.inner.database.shutdown()
567    }
568
569    pub(crate) fn has_unrecoverable_write_error(&self) -> bool {
570        self.inner.database.has_unrecoverable_write_error()
571    }
572}
573
574fn get_next_free_task_id(batch: &TurboWriteBatch<'_>) -> Result<u32, anyhow::Error> {
575    Ok(
576        match batch.get(KeySpace::Infra, InfraKey::NextFreeTaskId.key().as_ref())? {
577            Some(bytes) => u32::from_le_bytes(Borrow::<[u8]>::borrow(&bytes).try_into()?),
578            None => 1,
579        },
580    )
581}
582
583fn save_infra(
584    batch: &TurboWriteBatch<'_>,
585    next_task_id: u32,
586    roots: Option<Vec<(TaskId, TtlCounter)>>,
587) -> Result<(), anyhow::Error> {
588    batch
589        .put(
590            KeySpace::Infra,
591            WriteBuffer::Borrowed(InfraKey::NextFreeTaskId.key().as_ref()),
592            WriteBuffer::Borrowed(&next_task_id.to_le_bytes()),
593        )
594        .context("Unable to write next free task id")?;
595    if let Some(roots) = roots {
596        let _span = tracing::trace_span!("update roots", roots = roots.len()).entered();
597        let roots = turbo_bincode_encode(&roots).context("Unable to serialize GC roots")?;
598        batch
599            .put(
600                KeySpace::Infra,
601                WriteBuffer::Borrowed(InfraKey::GcRoots.key().as_ref()),
602                WriteBuffer::Owned(roots.into_boxed_slice()),
603            )
604            .context("Unable to write GC roots")?;
605    }
606    // Safety: save_infra is called after all concurrent writes to Infra are done.
607    unsafe { batch.flush(KeySpace::Infra)? };
608    Ok(())
609}
610
611#[cfg(test)]
612mod tests {
613    use std::{borrow::Borrow, path::Path};
614
615    use turbo_tasks::TaskId;
616
617    use super::*;
618    use crate::{
619        BackingStorageOptions,
620        database::{turbo::TurboKeyValueDatabase, write_batch::WriteBuffer},
621        utils::test_temp_dir::test_temp_dir,
622    };
623
624    /// Options used by these tests. `is_short_session` disables background compaction, which
625    /// requires a turbo-tasks context that these tests don't set up.
626    const TEST_STORAGE_OPTIONS: BackingStorageOptions = BackingStorageOptions {
627        is_ci: false,
628        is_short_session: true,
629        skip_compaction: false,
630    };
631
632    /// Helper to write to the database using the concurrent batch API.
633    fn write_task_cache_entry(
634        db: &TurboKeyValueDatabase,
635        hash: u64,
636        task_id: TaskId,
637    ) -> Result<()> {
638        let batch = db.write_batch()?;
639        batch.put(
640            KeySpace::TaskCache,
641            WriteBuffer::Borrowed(&hash.to_le_bytes()),
642            WriteBuffer::Borrowed(&(*task_id).to_le_bytes()),
643        )?;
644        batch.commit()?;
645        Ok(())
646    }
647
648    /// Reads the TaskIds stored under `hash` in `TaskCache`, sorted for stable comparison.
649    fn task_cache_ids(db: &TurboKeyValueDatabase, hash: u64) -> Result<Vec<TaskId>> {
650        let mut ids: Vec<TaskId> = db
651            .get_multiple(KeySpace::TaskCache, &hash.to_le_bytes())?
652            .iter()
653            .map(|bytes| {
654                let bytes: [u8; 4] = Borrow::<[u8]>::borrow(bytes).try_into().unwrap();
655                TaskId::try_from(u32::from_le_bytes(bytes)).unwrap()
656            })
657            .collect();
658        ids.sort_by_key(|id| **id);
659        Ok(ids)
660    }
661
662    /// Encodes a distinct [`TaskStorage`] for `seed`, with both meta and data fields populated.
663    fn encoded_task_storage(seed: u32, category: SpecificTaskDataCategory) -> Vec<u8> {
664        use crate::{
665            backend::{TrackOutcome, storage_schema::TaskStorageAccessors},
666            data::{AggregationNumber, OutputValue},
667        };
668
669        /// Accessors over a bare [`TaskStorage`], without modification tracking.
670        struct Untracked(TaskStorage);
671        impl TaskStorageAccessors for Untracked {
672            fn typed(&self) -> &TaskStorage {
673                &self.0
674            }
675            fn typed_mut(&mut self) -> &mut TaskStorage {
676                &mut self.0
677            }
678            fn track_modification(
679                &mut self,
680                _category: SpecificTaskDataCategory,
681                _name: &str,
682            ) -> TrackOutcome {
683                TrackOutcome::NoChange
684            }
685            fn undo_track_modification(&mut self, _outcome: TrackOutcome) {}
686            fn check_access(&self, _category: SpecificTaskDataCategory) {}
687        }
688
689        let id = |n: u32| TaskId::try_from(n).unwrap();
690        let mut task = Untracked(TaskStorage::new());
691        task.set_output(OutputValue::Output(id(seed + 1)));
692        task.set_aggregation_number(AggregationNumber {
693            base: seed,
694            distance: 1,
695            effective: seed + 1,
696        });
697        task.add_upper(id(seed + 2), 1);
698        assert!(task.add_output_dependencies(id(seed + 3)));
699        assert!(task.add_children(id(seed + 4)));
700        let storage = task.0;
701        let mut buffer = turbo_bincode::TurboBincodeBuffer::new();
702        storage
703            .encode(
704                category,
705                &mut turbo_bincode::new_turbo_bincode_encoder(&mut buffer),
706            )
707            .unwrap();
708        buffer.to_vec()
709    }
710
711    fn reencode(
712        storages: &[Option<TaskStorage>],
713        category: SpecificTaskDataCategory,
714    ) -> Vec<Option<Vec<u8>>> {
715        storages
716            .iter()
717            .map(|storage| {
718                storage.as_ref().map(|storage| {
719                    let mut buffer = turbo_bincode::TurboBincodeBuffer::new();
720                    storage
721                        .encode(
722                            category,
723                            &mut turbo_bincode::new_turbo_bincode_encoder(&mut buffer),
724                        )
725                        .unwrap();
726                    buffer.to_vec()
727                })
728            })
729            .collect()
730    }
731
732    /// Reports every requested index exactly once, with request order, duplicates and missing
733    /// entries resolved correctly, on both sides of turbo-persistence's parallel `batch_get`
734    /// cutoff. A value that fails to decode fails the whole lookup.
735    // Default worker count like the other database tests here: under the WASI test host, file
736    // descriptors are per thread, so committing SST files from extra runtime workers fails.
737    #[tokio::test(flavor = "multi_thread")]
738    async fn test_batch_lookup_data_roundtrip_at_parallel_threshold() -> Result<()> {
739        /// turbo-persistence's `batch_get` runs in parallel above this many keys.
740        const PARALLEL_BATCH_GET_THRESHOLD: usize = 2048;
741        const MALFORMED_ID: u32 = 999_997;
742
743        let tempdir = test_temp_dir()?;
744        let db = TurboKeyValueDatabase::new(tempdir.path().to_path_buf(), TEST_STORAGE_OPTIONS)?;
745        let stored_ids: Vec<TaskId> = (1..=(PARALLEL_BATCH_GET_THRESHOLD as u32 + 64))
746            .map(|id| TaskId::try_from(id).unwrap())
747            .collect();
748        let batch = db.write_batch()?;
749        for category in [
750            SpecificTaskDataCategory::Meta,
751            SpecificTaskDataCategory::Data,
752        ] {
753            for &task_id in &stored_ids {
754                let key = IntKey::new(*task_id);
755                let value = encoded_task_storage(*task_id * 10, category);
756                batch.put(
757                    category.key_space(),
758                    WriteBuffer::Borrowed(key.as_ref()),
759                    WriteBuffer::Borrowed(&value),
760                )?;
761            }
762            batch.put(
763                category.key_space(),
764                WriteBuffer::Borrowed(IntKey::new(MALFORMED_ID).as_ref()),
765                WriteBuffer::Borrowed(&[0xff; 3]),
766            )?;
767        }
768        batch.commit()?;
769        let storage = TurboBackingStorage::new_in_memory(db);
770
771        for category in [
772            SpecificTaskDataCategory::Meta,
773            SpecificTaskDataCategory::Data,
774        ] {
775            for len in [
776                PARALLEL_BATCH_GET_THRESHOLD,
777                PARALLEL_BATCH_GET_THRESHOLD + 1,
778            ] {
779                let mut requested = stored_ids[..len - 3].to_vec();
780                requested.reverse();
781                requested.insert(len / 2, TaskId::try_from(999_999).unwrap());
782                requested.push(stored_ids[7]);
783                requested.push(TaskId::try_from(999_998).unwrap());
784                assert_eq!(requested.len(), len);
785
786                let expected: Vec<Option<Vec<u8>>> = requested
787                    .iter()
788                    .map(|task_id| {
789                        (**task_id <= stored_ids.len() as u32)
790                            .then(|| encoded_task_storage(**task_id * 10, category))
791                    })
792                    .collect();
793                let slots: Vec<std::sync::OnceLock<Option<TaskStorage>>> =
794                    (0..len).map(|_| std::sync::OnceLock::new()).collect();
795                storage.batch_lookup_data(&requested, category, |index, storage| {
796                    assert!(
797                        slots[index].set(storage).is_ok(),
798                        "{category:?} len={len}: index {index} reported twice"
799                    );
800                    Ok(())
801                })?;
802                let decoded: Vec<Option<TaskStorage>> = slots
803                    .into_iter()
804                    .enumerate()
805                    .map(|(index, slot)| {
806                        slot.into_inner().unwrap_or_else(|| {
807                            panic!("{category:?} len={len}: index {index} never reported")
808                        })
809                    })
810                    .collect();
811                assert_eq!(
812                    reencode(&decoded, category),
813                    expected,
814                    "{category:?} len={len}"
815                );
816
817                let mut malformed = requested.clone();
818                malformed[len / 3] = TaskId::try_from(MALFORMED_ID).unwrap();
819                assert!(
820                    storage
821                        .batch_lookup_data(&malformed, category, |_, _| Ok(()))
822                        .is_err(),
823                    "{category:?} len={len} must fail on malformed bytes"
824                );
825            }
826        }
827
828        storage.inner.database.shutdown();
829        Ok(())
830    }
831
832    /// Tests that `get_multiple` correctly returns multiple TaskIds when the same hash key
833    /// is used (simulating a hash collision scenario).
834    ///
835    /// This is a lower-level test that verifies the database layer correctly handles
836    /// the case where multiple task IDs are stored under the same hash key.
837    #[tokio::test(flavor = "multi_thread")]
838    async fn test_hash_collision_returns_multiple_candidates() -> Result<()> {
839        let tempdir = test_temp_dir()?;
840        let path = tempdir.path();
841
842        let db = TurboKeyValueDatabase::new(path.to_path_buf(), TEST_STORAGE_OPTIONS)?;
843
844        // Simulate a hash collision by writing multiple TaskIds with the same hash key
845        let collision_hash: u64 = 0xDEADBEEF;
846        let task_id_1 = TaskId::try_from(100u32).unwrap();
847        let task_id_2 = TaskId::try_from(200u32).unwrap();
848        let task_id_3 = TaskId::try_from(300u32).unwrap();
849
850        // Write three task IDs under the same hash key (simulating collision)
851        // Each write creates a new SST file, so all three will be returned by get_multiple
852        write_task_cache_entry(&db, collision_hash, task_id_1)?;
853        write_task_cache_entry(&db, collision_hash, task_id_2)?;
854        write_task_cache_entry(&db, collision_hash, task_id_3)?;
855
856        // Now query using get_multiple - should return all three TaskIds
857        assert_eq!(
858            task_cache_ids(&db, collision_hash)?,
859            vec![task_id_1, task_id_2, task_id_3],
860            "Should return all 3 task IDs for the colliding hash"
861        );
862
863        db.shutdown();
864        Ok(())
865    }
866
867    /// Tests that multiple distinct keys written in a single batch with flush can be read back.
868    /// This mirrors the actual save_snapshot pattern: write many TaskCache entries, flush, commit.
869    // This test is too slow to run under Miri.
870    #[cfg(not(miri))]
871    #[tokio::test(flavor = "multi_thread")]
872    async fn test_batch_write_with_flush_and_reopen() -> Result<()> {
873        let tempdir = test_temp_dir()?;
874        let path = tempdir.path();
875
876        let n = 100_000;
877        let hashes: Vec<u64> = (0..n).map(|i| 0x1000 + i as u64).collect();
878        let task_ids: Vec<TaskId> = (1..=n as u32)
879            .map(|i| TaskId::try_from(i).unwrap())
880            .collect();
881
882        // Write all entries in a single batch with flush (like save_snapshot does)
883        {
884            let db = TurboKeyValueDatabase::new(path.to_path_buf(), TEST_STORAGE_OPTIONS)?;
885            let batch = db.write_batch()?;
886
887            for (hash, task_id) in hashes.iter().zip(task_ids.iter()) {
888                batch.put(
889                    KeySpace::TaskCache,
890                    WriteBuffer::Borrowed(&hash.to_le_bytes()),
891                    WriteBuffer::Borrowed(&(**task_id).to_le_bytes()),
892                )?;
893            }
894            // Flush TaskCache (like the new code does)
895            unsafe { batch.flush(KeySpace::TaskCache) }?;
896            batch.commit()?;
897
898            db.shutdown();
899        }
900
901        // Reopen and verify all entries are readable
902        {
903            let db = TurboKeyValueDatabase::new(path.to_path_buf(), TEST_STORAGE_OPTIONS)?;
904            let mut found = 0;
905            let mut missing = 0;
906            for (hash, expected_id) in hashes.iter().zip(task_ids.iter()) {
907                let results = db.get_multiple(KeySpace::TaskCache, &hash.to_le_bytes())?;
908                if results.is_empty() {
909                    missing += 1;
910                } else {
911                    found += 1;
912                    let bytes: [u8; 4] = Borrow::<[u8]>::borrow(&results[0]).try_into().unwrap();
913                    let id = TaskId::try_from(u32::from_le_bytes(bytes)).unwrap();
914                    assert_eq!(id, *expected_id, "Task ID mismatch for hash {hash:#x}");
915                }
916            }
917            assert_eq!(missing, 0, "Found {found}/{n} entries, missing {missing}");
918            db.shutdown();
919        }
920
921        Ok(())
922    }
923
924    /// `save_snapshot` delete path: a `Delete` item must erase the task's `TaskMeta` and
925    /// `TaskData` (`SingleValue`) entries and remove *only* that id from its `TaskCache`
926    /// (`MultiValue`) bucket.
927    ///
928    /// The colliding survivor is never read or rewritten — the key-value tombstone names the
929    /// single id it deletes, so anything else in the bucket is untouched whether or not this
930    /// commit knows about it.
931    #[tokio::test(flavor = "multi_thread")]
932    async fn test_save_snapshot_delete_tombstones_task() -> Result<()> {
933        let tempdir = test_temp_dir()?;
934        let path = tempdir.path();
935
936        let collision_hash: u64 = 0xC0FFEE;
937        let deleted_id = TaskId::try_from(111u32).unwrap();
938        let survivor_id = TaskId::try_from(222u32).unwrap();
939        let deleted_key = (*deleted_id).to_le_bytes();
940
941        let db = TurboKeyValueDatabase::new(
942            path.to_path_buf(),
943            BackingStorageOptions {
944                is_ci: false,
945                is_short_session: true,
946                skip_compaction: false,
947            },
948        )?;
949
950        // Both ids collide in one TaskCache bucket, purely on disk; the deleted task also has
951        // meta and data entries.
952        write_task_cache_entry(&db, collision_hash, deleted_id)?;
953        write_task_cache_entry(&db, collision_hash, survivor_id)?;
954        let batch = db.write_batch()?;
955        batch.put(
956            KeySpace::TaskMeta,
957            WriteBuffer::Borrowed(&deleted_key),
958            WriteBuffer::Borrowed(b"meta-bytes"),
959        )?;
960        batch.put(
961            KeySpace::TaskData,
962            WriteBuffer::Borrowed(&deleted_key),
963            WriteBuffer::Borrowed(b"data-bytes"),
964        )?;
965        batch.commit()?;
966
967        // Sanity: everything is present before the delete.
968        assert!(db.get(KeySpace::TaskMeta, &deleted_key)?.is_some());
969        assert!(db.get(KeySpace::TaskData, &deleted_key)?.is_some());
970        assert_eq!(
971            task_cache_ids(&db, collision_hash)?,
972            vec![deleted_id, survivor_id],
973        );
974
975        let storage = TurboBackingStorage::new_in_memory(db);
976
977        // Snapshot with no task data, just the one deletion.
978        storage.save_snapshot(
979            None,
980            vec![vec![SnapshotItem::Delete {
981                task_id: deleted_id,
982                task_type_hash: collision_hash.to_le_bytes(),
983            }]],
984        )?;
985
986        let db = &storage.inner.database;
987        assert!(
988            db.get(KeySpace::TaskMeta, &deleted_key)?.is_none(),
989            "TaskMeta should be tombstoned"
990        );
991        assert!(
992            db.get(KeySpace::TaskData, &deleted_key)?.is_none(),
993            "TaskData should be tombstoned"
994        );
995        assert_eq!(
996            task_cache_ids(db, collision_hash)?,
997            vec![survivor_id],
998            "save_snapshot should delete only the named id from the bucket"
999        );
1000
1001        db.shutdown();
1002        Ok(())
1003    }
1004
1005    /// An error caused by an unreadable database file, wrapped in further context like the errors
1006    /// of restoring a task.
1007    fn unreadable_error() -> anyhow::Error {
1008        anyhow::Error::new(CacheFileUnreadable::new(
1009            "00000007.sst",
1010            anyhow::anyhow!("failed to open file `00000007.sst`: No such file or directory"),
1011        ))
1012        .context("Looking up task storage for TaskId 4 from database failed")
1013        .context("Failed to restore Data for TaskId 4")
1014    }
1015
1016    #[test]
1017    fn test_unreadable_cache_message() {
1018        let base_path = Path::new("/project/.cache/turbopack");
1019        let error = unreadable_error();
1020
1021        let with_invalidation = unreadable_cache_message(&error, Some(base_path), true).unwrap();
1022        let without_invalidation =
1023            unreadable_cache_message(&error, Some(base_path), false).unwrap();
1024        let in_memory = unreadable_cache_message(&error, None, true).unwrap();
1025        for message in [&with_invalidation, &without_invalidation, &in_memory] {
1026            assert!(
1027                message.contains("Turbopack's filesystem cache could not be read"),
1028                "{message}"
1029            );
1030            assert!(message.contains("00000007.sst"), "{message}");
1031            assert!(
1032                message.contains("deleted or modified outside of Turbopack"),
1033                "{message}"
1034            );
1035            // The details of the error follow.
1036            assert!(message.contains("No such file or directory"), "{message}");
1037            // Invalidating is best-effort, so it's never claimed to have happened.
1038            assert!(!message.contains("has been deleted"), "{message}");
1039            assert!(!message.contains("was deleted"), "{message}");
1040        }
1041        assert!(
1042            with_invalidation.contains("will try to invalidate"),
1043            "{with_invalidation}"
1044        );
1045        assert!(
1046            with_invalidation
1047                .contains("If this error comes back, delete /project/.cache/turbopack"),
1048            "{with_invalidation}"
1049        );
1050        assert!(
1051            without_invalidation.contains("Delete /project/.cache/turbopack and restart"),
1052            "{without_invalidation}"
1053        );
1054        assert!(
1055            !without_invalidation.contains("will try to invalidate"),
1056            "{without_invalidation}"
1057        );
1058
1059        assert_eq!(
1060            unreadable_cache_message(&anyhow::anyhow!("some bug"), Some(base_path), true),
1061            None
1062        );
1063    }
1064
1065    #[test]
1066    #[cfg_attr(target_family = "wasm", ignore = "no unwinding on wasm")]
1067    fn test_panic_on_read_error() -> Result<()> {
1068        let tempdir = test_temp_dir()?;
1069        let db = TurboKeyValueDatabase::new(tempdir.path().to_path_buf(), TEST_STORAGE_OPTIONS)?;
1070        let storage = TurboBackingStorage::new_in_memory(db);
1071
1072        let payload = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1073            storage.panic_on_read_error("Failed to restore", unreadable_error())
1074        }))
1075        .expect_err("must panic");
1076        let panic = payload
1077            .downcast_ref::<PersistentCacheUnreadablePanic>()
1078            .expect("the payload must be a PersistentCacheUnreadablePanic");
1079        assert!(panic.message.contains("00000007.sst"), "{}", panic.message);
1080
1081        // Other errors panic as before. (Without the error's backtrace, which is included if
1082        // `RUST_BACKTRACE` is set.)
1083        let payload = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1084            storage.panic_on_read_error("Failed to restore", anyhow::anyhow!("some bug"))
1085        }))
1086        .expect_err("must panic");
1087        let message = payload
1088            .downcast_ref::<String>()
1089            .expect("the payload must be a String");
1090        let message = message
1091            .split("\n\nStack backtrace:")
1092            .next()
1093            .unwrap_or_default();
1094        assert_eq!(message, "Failed to restore: some bug");
1095        Ok(())
1096    }
1097
1098    const TEST_VERSION: GitVersionInfo<'static> = GitVersionInfo {
1099        describe: "v-current",
1100        dirty: false,
1101    };
1102
1103    /// Writes a cache entry into the current version's database under `base_path` and then removes
1104    /// one of its `.sst` files, the way something outside of Turbopack might. Also creates the
1105    /// database of another version next to it. Returns the removed file's name.
1106    fn unreadable_versioned_db(base_path: &Path) -> Result<String> {
1107        let versioned_path = base_path.join(TEST_VERSION.describe);
1108        let db = TurboKeyValueDatabase::new(versioned_path.clone(), TEST_STORAGE_OPTIONS)?;
1109        write_task_cache_entry(&db, 1, TaskId::try_from(1u32).unwrap())?;
1110        db.shutdown();
1111        drop(db);
1112
1113        let other = base_path.join("v-other");
1114        fs_err::create_dir_all(&other)?;
1115        fs_err::write(other.join("CURRENT"), b"untouched")?;
1116
1117        let sst = fs_err::read_dir(&versioned_path)?
1118            .map(|entry| entry.map(|entry| entry.path()))
1119            .collect::<std::io::Result<Vec<_>>>()?
1120            .into_iter()
1121            .find(|path| path.extension().is_some_and(|ext| ext == "sst"))
1122            .expect("the commit should have written an SST file");
1123        fs_err::remove_file(&sst)?;
1124        Ok(sst.file_name().unwrap().to_str().unwrap().to_owned())
1125    }
1126
1127    /// A database that can't be opened is deleted and replaced by an empty one, and the deletion
1128    /// is reported, so that a damaged cache costs a cold start instead of failing the process.
1129    #[tokio::test(flavor = "multi_thread")]
1130    async fn test_open_versioned_on_disk_replaces_an_unreadable_database() -> Result<()> {
1131        let tempdir = test_temp_dir()?;
1132        let base_path = tempdir.path();
1133        unreadable_versioned_db(base_path)?;
1134
1135        let (storage, state) = TurboBackingStorage::open_versioned_on_disk_with(
1136            base_path.to_path_buf(),
1137            &TEST_VERSION,
1138            false,
1139            true,
1140            |path| TurboKeyValueDatabase::new(path, TEST_STORAGE_OPTIONS),
1141        )?;
1142        assert!(
1143            matches!(
1144                &state,
1145                StartupCacheState::Invalidated { reason_code: Some(reason) }
1146                    if reason == invalidation_reasons::UNREADABLE
1147            ),
1148            "the deletion should be reported as UNREADABLE"
1149        );
1150
1151        // The new database starts out empty and is writable.
1152        let db = &storage.inner.database;
1153        assert_eq!(task_cache_ids(db, 1)?, vec![]);
1154        write_task_cache_entry(db, 2, TaskId::try_from(2u32).unwrap())?;
1155        assert_eq!(
1156            task_cache_ids(db, 2)?,
1157            vec![TaskId::try_from(2u32).unwrap()]
1158        );
1159        db.shutdown();
1160        drop(storage);
1161
1162        // Other versions are not touched.
1163        assert_eq!(
1164            fs_err::read(base_path.join("v-other").join("CURRENT"))?,
1165            b"untouched"
1166        );
1167
1168        // The replacement is a normal database that is reused by the next start.
1169        let (storage, state) = TurboBackingStorage::open_versioned_on_disk_with(
1170            base_path.to_path_buf(),
1171            &TEST_VERSION,
1172            false,
1173            true,
1174            |path| TurboKeyValueDatabase::new(path, TEST_STORAGE_OPTIONS),
1175        )?;
1176        assert!(
1177            !matches!(state, StartupCacheState::Invalidated { .. }),
1178            "a replaced database must not be replaced again"
1179        );
1180        let db = &storage.inner.database;
1181        assert_eq!(
1182            task_cache_ids(db, 2)?,
1183            vec![TaskId::try_from(2u32).unwrap()]
1184        );
1185        db.shutdown();
1186        Ok(())
1187    }
1188
1189    /// If the database that can't be opened can't be removed either, opening isn't retried and
1190    /// the error includes the original failure.
1191    #[tokio::test(flavor = "multi_thread")]
1192    async fn test_open_versioned_on_disk_returns_removal_failures() -> Result<()> {
1193        let tempdir = test_temp_dir()?;
1194        let base_path = tempdir.path();
1195        let attempts = std::sync::atomic::AtomicUsize::new(0);
1196        let stale_path = base_path.join(format!("__stale_{}", TEST_VERSION.describe));
1197
1198        let error = TurboBackingStorage::open_versioned_on_disk_with(
1199            base_path.to_path_buf(),
1200            &TEST_VERSION,
1201            false,
1202            true,
1203            |path| {
1204                attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1205                fs_err::create_dir_all(&path)?;
1206                // Occupy the path the database directory is moved to before it's deleted with a
1207                // file, which can't be removed as a directory, so that the removal fails. (Done
1208                // here because opening cleans up such leftovers before calling this.)
1209                fs_err::write(&stale_path, b"")?;
1210                anyhow::bail!("injected open failure")
1211            },
1212        )
1213        .map(|_| ())
1214        .expect_err("opening must fail");
1215        assert_eq!(attempts.into_inner(), 1, "no retry after a failed removal");
1216        assert!(
1217            format!("{error:#}").contains("injected open failure"),
1218            "the error should include the original failure: {error:#}"
1219        );
1220        assert!(base_path.join(TEST_VERSION.describe).is_dir());
1221        Ok(())
1222    }
1223
1224    /// If the replacement database can't be opened either, opening is attempted only once more,
1225    /// and the error includes both the original failure and the failure of the retry.
1226    #[tokio::test(flavor = "multi_thread")]
1227    async fn test_open_versioned_on_disk_retries_once_and_keeps_both_errors() -> Result<()> {
1228        let tempdir = test_temp_dir()?;
1229        let base_path = tempdir.path();
1230        let attempts = std::sync::atomic::AtomicUsize::new(0);
1231
1232        let error = TurboBackingStorage::open_versioned_on_disk_with(
1233            base_path.to_path_buf(),
1234            &TEST_VERSION,
1235            false,
1236            true,
1237            |path| {
1238                fs_err::create_dir_all(&path)?;
1239                let attempt = attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
1240                anyhow::bail!("injected open failure {attempt}")
1241            },
1242        )
1243        .map(|_| ())
1244        .expect_err("opening must fail");
1245        assert_eq!(attempts.into_inner(), 2, "open once, then retry once");
1246        let error = format!("{error:#}");
1247        assert!(
1248            error.contains("injected open failure 1") && error.contains("injected open failure 2"),
1249            "the error should include both failures: {error}"
1250        );
1251        Ok(())
1252    }
1253
1254    /// With recovery disabled (to surface such problems instead of hiding them), the open error is
1255    /// returned unchanged and nothing is deleted.
1256    #[tokio::test(flavor = "multi_thread")]
1257    async fn test_open_versioned_on_disk_without_recovery_returns_the_error() -> Result<()> {
1258        let tempdir = test_temp_dir()?;
1259        let base_path = tempdir.path();
1260        let missing = unreadable_versioned_db(base_path)?;
1261
1262        let error = TurboBackingStorage::open_versioned_on_disk_with(
1263            base_path.to_path_buf(),
1264            &TEST_VERSION,
1265            false,
1266            false,
1267            |path| TurboKeyValueDatabase::new(path, TEST_STORAGE_OPTIONS),
1268        )
1269        .map(|_| ())
1270        .expect_err("opening must fail");
1271        assert!(
1272            format!("{error:#}").contains(&missing),
1273            "the error should name the missing file {missing}: {error:#}"
1274        );
1275        assert!(
1276            base_path
1277                .join(TEST_VERSION.describe)
1278                .join("CURRENT")
1279                .exists()
1280        );
1281        Ok(())
1282    }
1283}