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#[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
81fn 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
100fn 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 base_path: Option<PathBuf>,
136 invalidated: Mutex<bool>,
138 _panic_hook_guard: Option<PanicHookGuard>,
141}
142
143pub struct TurboBackingStorage {
151 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 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 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 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 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 if let Some(base_path) = &self.base_path {
268 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_db(base_path, reason_code)?;
281 self.database.prevent_writes();
282 *invalidated_guard = true;
284 }
285 Ok(())
286 }
287
288 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 pub(crate) fn invalidate(&self, reason_code: &str) -> Result<()> {
306 self.inner.invalidate(reason_code)
307 }
308
309 #[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 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 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 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 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 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 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 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 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 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 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 const TEST_STORAGE_OPTIONS: BackingStorageOptions = BackingStorageOptions {
627 is_ci: false,
628 is_short_session: true,
629 skip_compaction: false,
630 };
631
632 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 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 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 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 #[tokio::test(flavor = "multi_thread")]
738 async fn test_batch_lookup_data_roundtrip_at_parallel_threshold() -> Result<()> {
739 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 #[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 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_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 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 #[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 {
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 unsafe { batch.flush(KeySpace::TaskCache) }?;
896 batch.commit()?;
897
898 db.shutdown();
899 }
900
901 {
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 #[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 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 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 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 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 assert!(message.contains("No such file or directory"), "{message}");
1037 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 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 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 #[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 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 assert_eq!(
1164 fs_err::read(base_path.join("v-other").join("CURRENT"))?,
1165 b"untouched"
1166 );
1167
1168 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 #[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 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 #[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 #[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}