1use std::{
2 borrow::{Borrow, Cow},
3 cell::Cell,
4 cmp::Reverse,
5 fmt::{Debug, Display},
6 future::Future,
7 hash::{BuildHasher, BuildHasherDefault, Hash},
8 mem::take,
9 ops::Deref,
10 panic::AssertUnwindSafe,
11 pin::Pin,
12 process::abort,
13 sync::{
14 Arc, Mutex, RwLock, Weak,
15 atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering},
16 },
17 task::{Context, Poll, Waker},
18 time::{Duration, Instant},
19};
20
21use anyhow::{Result, anyhow};
22use auto_hash_map::AutoMap;
23use bincode::{Decode, Encode};
24use either::Either;
25use futures::FutureExt;
26use rustc_hash::{FxBuildHasher, FxHashSet, FxHasher};
27use serde::{Deserialize, Serialize};
28use smallvec::SmallVec;
29use tokio::{select, sync::mpsc::Receiver, task_local};
30use tracing::{Instrument, Span, instrument};
31use turbo_tasks_hash::{DeterministicHash, hash_xxh3_hash128};
32
33use crate::{
34 CellId, Completion, InvalidationReason, InvalidationReasonSet, NonLocalValue, OperationValue,
35 OperationVc, OutputContent, RawVc, ReadCellOptions, ReadOutcome, ReadOutputOptions, ResolvedVc,
36 SharedReference, TaskId, TraitMethod, ValueTypeId, Vc, VcRead, VcValueTrait, VcValueType,
37 backend::{
38 Backend, CellContent, CellHash, TaskCollectiblesMap, TaskExecutionSpec, TransientTaskType,
39 TurboTasksExecutionError, TypedCellContent, VerificationMode,
40 },
41 capture_future::CaptureFuture,
42 dyn_task_inputs::DynTaskInputsStorage,
43 event::{Event, EventDescriptor, EventListener},
44 id::{ExecutionId, LocalTaskId, TraitTypeId},
45 keyed::KeyedEq,
46 local_task_tracker::LocalTaskTracker,
47 macro_helpers::NativeFunction,
48 message_queue::{CompilationEvent, CompilationEventQueue},
49 priority_runner::{Claimable, Executor, PriorityRunner},
50 registry,
51 serialization_invalidation::SerializationInvalidator,
52 spawn::JoinHandle,
53 task::local_task::{LocalTask, LocalTaskSpec, LocalTaskType},
54 task_statistics::TaskStatisticsApi,
55 util::{IdFactory, StaticOrArc},
56};
57
58pub trait TurboTasksCallApi: Sync + Send {
61 fn dynamic_call(
68 &self,
69 native_fn: &'static NativeFunction,
70 this: Option<RawVc>,
71 arg: &mut dyn DynTaskInputsStorage,
72 inputs_resolved: InputResolution,
73 persistence: TaskPersistence,
74 ) -> RawVc;
75 fn native_call(
78 &self,
79 native_fn: &'static NativeFunction,
80 this: Option<RawVc>,
81 arg: &mut dyn DynTaskInputsStorage,
82 persistence: TaskPersistence,
83 ) -> RawVc;
84 fn trait_call(
91 &self,
92 trait_method: &'static TraitMethod,
93 this: RawVc,
94 arg: &mut dyn DynTaskInputsStorage,
95 inputs_resolved: InputResolution,
96 persistence: TaskPersistence,
97 ) -> RawVc;
98
99 fn run(
100 &self,
101 future: Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>,
102 ) -> Pin<Box<dyn Future<Output = Result<(), TurboTasksExecutionError>> + Send>>;
103 fn run_once(
104 &self,
105 future: Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>,
106 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
107 fn run_once_with_reason(
108 &self,
109 reason: StaticOrArc<dyn InvalidationReason>,
110 future: Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>,
111 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
112 fn start_once_process(&self, future: Pin<Box<dyn Future<Output = ()> + Send + 'static>>);
113
114 fn send_compilation_event(&self, event: Arc<dyn CompilationEvent>);
116
117 fn get_task_name(&self, task: TaskId) -> String;
119}
120
121pub trait TurboTasksApi: TurboTasksCallApi + Sync + Send {
127 fn invalidate(&self, task: TaskId);
128 fn invalidate_with_reason(&self, task: TaskId, reason: StaticOrArc<dyn InvalidationReason>);
129 fn invalidate_many(&self, tasks: &[TaskId]);
132 fn invalidate_many_with_reasons(
134 &self,
135 tasks: &[TaskId],
136 reasons: Vec<StaticOrArc<dyn InvalidationReason>>,
137 );
138
139 fn invalidate_serialization(&self, task: TaskId);
140
141 fn try_read_task_output(
142 &self,
143 task: TaskId,
144 options: ReadOutputOptions,
145 ) -> Result<ReadOutcome<RawVc>>;
146
147 fn try_read_task_cell(
148 &self,
149 task: TaskId,
150 index: CellId,
151 options: ReadCellOptions,
152 ) -> Result<ReadOutcome<TypedCellContent>>;
153
154 fn refine_provisional_cell_dependency(
158 &self,
159 task: TaskId,
160 index: CellId,
161 reader: TaskId,
162 id: u32,
163 key_hashes: &FxHashSet<u64>,
164 ) -> Result<()>;
165
166 fn try_read_local_output(
182 &self,
183 execution_id: ExecutionId,
184 local_task_id: LocalTaskId,
185 ) -> Result<Result<RawVc, EventListener>>;
186
187 fn read_task_collectibles(&self, task: TaskId, trait_id: TraitTypeId) -> TaskCollectiblesMap;
188
189 fn try_execute_scheduled_task_inline(&self, key: ScheduleKey) -> bool;
195
196 #[cfg(feature = "inline_execution_stats")]
199 fn note_waited_for_in_progress_task(&self);
200
201 fn emit_collectible(&self, trait_type: TraitTypeId, collectible: RawVc);
202 fn unemit_collectible(&self, trait_type: TraitTypeId, collectible: RawVc, count: u32);
203 fn unemit_collectibles(&self, trait_type: TraitTypeId, collectibles: &TaskCollectiblesMap);
204
205 fn try_read_own_task_cell(
208 &self,
209 current_task: TaskId,
210 index: CellId,
211 ) -> Result<TypedCellContent>;
212
213 fn drop_task_cell_content_hint(&self, task: TaskId, index: CellId) -> Result<()>;
215
216 fn read_own_task_cell(&self, task: TaskId, index: CellId) -> Result<TypedCellContent>;
217 fn update_own_task_cell(
218 &self,
219 task: TaskId,
220 index: CellId,
221 content: CellContent,
222 updated_key_hashes: Option<SmallVec<[u64; 2]>>,
223 content_hash: Option<CellHash>,
224 verification_mode: VerificationMode,
225 );
226 fn mark_own_task_as_finished(&self, task: TaskId);
227
228 fn pin_task_for_gc(&self, task: TaskId);
231
232 fn unpin_task_for_gc(&self, task: TaskId);
234
235 fn connect_task(&self, task: TaskId);
236
237 fn spawn_detached_for_testing(&self, f: Pin<Box<dyn Future<Output = ()> + Send + 'static>>);
242
243 fn task_statistics(&self) -> &TaskStatisticsApi;
244
245 fn stop_and_wait(&self) -> Pin<Box<dyn Future<Output = ()> + Send>>;
246
247 fn subscribe_to_compilation_events(
248 &self,
249 event_types: Option<Vec<String>>,
250 ) -> Receiver<Arc<dyn CompilationEvent>>;
251
252 fn is_tracking_dependencies(&self) -> bool;
254}
255
256pub struct Unused<T> {
258 inner: T,
259}
260
261impl<T> Unused<T> {
262 pub unsafe fn new_unchecked(inner: T) -> Self {
268 Self { inner }
269 }
270
271 pub unsafe fn get_unchecked(&self) -> &T {
277 &self.inner
278 }
279
280 pub fn into(self) -> T {
282 self.inner
283 }
284}
285
286#[allow(clippy::manual_non_exhaustive)]
287pub struct UpdateInfo {
288 pub duration: Duration,
289 pub tasks: usize,
290 pub reasons: InvalidationReasonSet,
291 #[allow(dead_code)]
292 placeholder_for_future_fields: (),
293}
294
295#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize, Encode, Decode)]
296pub enum TaskPersistence {
297 Persistent,
299
300 Transient,
307}
308
309impl Display for TaskPersistence {
310 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311 match self {
312 TaskPersistence::Persistent => write!(f, "persistent"),
313 TaskPersistence::Transient => write!(f, "transient"),
314 }
315 }
316}
317
318#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
321pub enum InputResolution {
322 Resolved,
325 Unresolved,
327}
328
329impl InputResolution {
330 #[inline]
331 pub fn from_is_resolved(is_resolved: bool) -> Self {
332 if is_resolved {
333 Self::Resolved
334 } else {
335 Self::Unresolved
336 }
337 }
338
339 #[inline]
340 pub fn is_resolved(self) -> bool {
341 matches!(self, Self::Resolved)
342 }
343}
344
345#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
346pub enum ReadConsistency {
347 #[default]
350 Eventual,
351 Strong,
356}
357
358#[derive(Clone, Copy, Eq, PartialEq, Hash, Encode, Decode)]
366#[repr(transparent)]
367pub struct CellKey(#[bincode(fixint)] u64);
368
369#[derive(Clone, Copy, Debug, Eq, PartialEq)]
371pub enum CellKeyKind {
372 Hash(u64),
377 Provisional(u32),
390}
391
392impl CellKey {
393 const PROVISIONAL: u64 = 1 << 63;
394
395 pub const fn hash(hash: u64) -> Self {
398 Self(hash & !Self::PROVISIONAL)
399 }
400
401 pub const fn provisional(id: u32) -> Self {
403 Self(Self::PROVISIONAL | id as u64)
404 }
405
406 pub const fn kind(self) -> CellKeyKind {
407 if self.is_provisional() {
408 CellKeyKind::Provisional(self.0 as u32)
409 } else {
410 CellKeyKind::Hash(self.0)
411 }
412 }
413
414 pub const fn is_provisional(self) -> bool {
415 self.0 & Self::PROVISIONAL != 0
416 }
417}
418
419impl Debug for CellKey {
420 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
421 Debug::fmt(&self.kind(), f)
422 }
423}
424
425#[cfg(test)]
426mod cell_key_tests {
427 use super::{CellKey, CellKeyKind};
428
429 #[test]
430 fn packs_into_one_word() {
431 assert_eq!(size_of::<CellKey>(), 8);
432 }
433
434 #[test]
435 fn hashes_keep_their_low_63_bits() {
436 assert_eq!(CellKey::hash(0x1234).kind(), CellKeyKind::Hash(0x1234));
437 let key = CellKey::hash(u64::MAX);
439 assert!(!key.is_provisional());
440 assert_eq!(key.kind(), CellKeyKind::Hash(u64::MAX >> 1));
441 assert_eq!(key, CellKey::hash(u64::MAX >> 1));
442 }
443
444 #[test]
445 fn encodes_at_fixed_width() {
446 let key = CellKey::hash(0x1234);
447 let mut buf = turbo_bincode::TurboBincodeBuffer::new();
448 let mut encoder = turbo_bincode::new_turbo_bincode_encoder(&mut buf);
449 bincode::Encode::encode(&key, &mut encoder).unwrap();
450 assert_eq!(buf.len(), 8);
451 let mut decoder = turbo_bincode::new_turbo_bincode_decoder(&buf);
452 let decoded: CellKey = bincode::Decode::decode(&mut decoder).unwrap();
453 assert_eq!(decoded, key);
454 }
455
456 #[test]
457 fn provisional_ids_round_trip() {
458 for id in [0, 1, u32::MAX] {
459 let key = CellKey::provisional(id);
460 assert!(key.is_provisional());
461 assert_eq!(key.kind(), CellKeyKind::Provisional(id));
462 assert_ne!(key, CellKey::hash(id as u64));
463 }
464 }
465}
466
467#[derive(Clone, Copy, Debug, Eq, PartialEq)]
468pub enum ReadCellTracking {
469 Tracked {
471 key: Option<CellKey>,
473 },
474 TrackOnlyError,
479 Untracked,
484}
485
486impl ReadCellTracking {
487 pub fn should_track(&self, is_err: bool) -> bool {
488 match self {
489 ReadCellTracking::Tracked { .. } => true,
490 ReadCellTracking::TrackOnlyError => is_err,
491 ReadCellTracking::Untracked => false,
492 }
493 }
494
495 pub fn key(&self) -> Option<CellKey> {
496 match self {
497 ReadCellTracking::Tracked { key } => *key,
498 ReadCellTracking::TrackOnlyError => None,
499 ReadCellTracking::Untracked => None,
500 }
501 }
502}
503
504impl Default for ReadCellTracking {
505 fn default() -> Self {
506 ReadCellTracking::Tracked { key: None }
507 }
508}
509
510impl Display for ReadCellTracking {
511 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512 match self {
513 ReadCellTracking::Tracked { key: None } => write!(f, "tracked"),
514 ReadCellTracking::Tracked { key: Some(key) } => match key.kind() {
515 CellKeyKind::Hash(key) => write!(f, "tracked with key {key}"),
516 CellKeyKind::Provisional(id) => write!(f, "tracked as provisional read {id}"),
517 },
518 ReadCellTracking::TrackOnlyError => write!(f, "track only error"),
519 ReadCellTracking::Untracked => write!(f, "untracked"),
520 }
521 }
522}
523
524#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
525pub enum ReadTracking {
526 #[default]
528 Tracked,
529 TrackOnlyError,
534 Untracked,
539}
540
541impl ReadTracking {
542 pub fn should_track(&self, is_err: bool) -> bool {
543 match self {
544 ReadTracking::Tracked => true,
545 ReadTracking::TrackOnlyError => is_err,
546 ReadTracking::Untracked => false,
547 }
548 }
549}
550
551impl Display for ReadTracking {
552 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
553 match self {
554 ReadTracking::Tracked => write!(f, "tracked"),
555 ReadTracking::TrackOnlyError => write!(f, "track only error"),
556 ReadTracking::Untracked => write!(f, "untracked"),
557 }
558 }
559}
560
561#[derive(Encode, Decode, Default, Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
562pub enum TaskPriority {
563 #[default]
564 Initial,
565 Invalidation {
566 priority: Reverse<u32>,
567 },
568 Recomputation,
569}
570
571impl TaskPriority {
572 pub fn invalidation(priority: u32) -> Self {
573 Self::Invalidation {
574 priority: Reverse(priority),
575 }
576 }
577
578 pub fn initial() -> Self {
579 Self::Initial
580 }
581
582 pub fn leaf() -> Self {
583 Self::Invalidation {
584 priority: Reverse(0),
585 }
586 }
587
588 pub fn in_parent(&self, parent_priority: TaskPriority) -> Self {
589 match self {
590 TaskPriority::Initial => parent_priority,
591 TaskPriority::Invalidation { priority } => {
592 if let TaskPriority::Invalidation {
593 priority: parent_priority,
594 } = parent_priority
595 && priority.0 < parent_priority.0
596 {
597 Self::Invalidation {
598 priority: Reverse(parent_priority.0.saturating_add(1)),
599 }
600 } else {
601 *self
602 }
603 }
604 TaskPriority::Recomputation => TaskPriority::Recomputation,
605 }
606 }
607}
608
609impl Display for TaskPriority {
610 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
611 match self {
612 TaskPriority::Initial => write!(f, "initial"),
613 TaskPriority::Invalidation { priority } => write!(f, "invalidation({})", priority.0),
614 TaskPriority::Recomputation => write!(f, "recomputation"),
615 }
616 }
617}
618
619enum ScheduledTask {
620 Task {
621 task_id: TaskId,
622 span: Span,
623 },
624 LocalTask {
625 ty: LocalTaskSpec,
626 persistence: TaskPersistence,
627 parent_task: Option<TaskId>,
630 execution_id: ExecutionId,
631 local_task_id: LocalTaskId,
632 global_task_state: CurrentTaskStateHandle,
633 span: Span,
634 },
635}
636
637#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
641pub enum ScheduleKey {
642 Task(TaskId),
644 LocalTask(Option<TaskId>, ExecutionId, LocalTaskId),
653}
654
655impl ScheduleKey {
656 pub(crate) fn current_local_task(
658 execution_id: ExecutionId,
659 local_task_id: LocalTaskId,
660 ) -> Self {
661 let parent_task = CURRENT_TASK_STATE.with(|ts| ts.current_task_id());
662 Self::LocalTask(parent_task, execution_id, local_task_id)
663 }
664}
665
666impl Claimable for ScheduledTask {
667 type Key = ScheduleKey;
668
669 fn claim_key(&self) -> ScheduleKey {
670 match self {
671 ScheduledTask::Task { task_id, .. } => ScheduleKey::Task(*task_id),
672 ScheduledTask::LocalTask {
673 parent_task,
674 execution_id,
675 local_task_id,
676 ..
677 } => ScheduleKey::LocalTask(*parent_task, *execution_id, *local_task_id),
678 }
679 }
680}
681
682#[cfg(feature = "inline_execution_stats")]
683use std::sync::atomic::AtomicU64;
684
685#[cfg(feature = "inline_execution_stats")]
688#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
689pub struct InlineExecutionStats {
690 pub queued: u64,
692 pub claim_attempted: u64,
694 pub claim_completed: u64,
696 pub claim_yielded: u64,
698 pub claim_failed: u64,
700 pub waited_in_progress: u64,
702}
703
704#[derive(Default)]
710struct InlineExecutionCounters {
711 #[cfg(feature = "inline_execution_stats")]
712 claim_attempted: AtomicU64,
713 #[cfg(feature = "inline_execution_stats")]
714 claim_completed: AtomicU64,
715 #[cfg(feature = "inline_execution_stats")]
716 claim_yielded: AtomicU64,
717 #[cfg(feature = "inline_execution_stats")]
718 claim_failed: AtomicU64,
719 #[cfg(feature = "inline_execution_stats")]
720 waited_in_progress: AtomicU64,
721}
722
723impl InlineExecutionCounters {
724 #[inline]
726 fn claim_attempted(&self) {
727 #[cfg(feature = "inline_execution_stats")]
728 self.claim_attempted.fetch_add(1, Ordering::Relaxed);
729 }
730
731 #[inline]
733 fn claim_completed(&self) {
734 #[cfg(feature = "inline_execution_stats")]
735 self.claim_completed.fetch_add(1, Ordering::Relaxed);
736 }
737
738 #[inline]
740 fn claim_yielded(&self) {
741 #[cfg(feature = "inline_execution_stats")]
742 self.claim_yielded.fetch_add(1, Ordering::Relaxed);
743 }
744
745 #[inline]
747 fn claim_failed(&self) {
748 #[cfg(feature = "inline_execution_stats")]
749 self.claim_failed.fetch_add(1, Ordering::Relaxed);
750 }
751
752 #[cfg(feature = "inline_execution_stats")]
754 #[inline]
755 fn waited_in_progress(&self) {
756 self.waited_in_progress.fetch_add(1, Ordering::Relaxed);
757 }
758}
759
760#[cfg(feature = "inline_execution_stats")]
762pub(crate) fn inline_stats_requested() -> bool {
763 static REQUESTED: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
764 std::env::var("TURBO_ENGINE_INLINE_STATS").is_ok_and(|value| value != "0")
765 });
766 *REQUESTED
767}
768
769const MAX_INLINE_EXECUTION_DEPTH: usize = 16;
772
773thread_local! {
774 static INLINE_EXECUTION_DEPTH: Cell<usize> = const { Cell::new(0) };
776}
777
778fn inline_execution_allowed() -> bool {
780 INLINE_EXECUTION_DEPTH.get() < MAX_INLINE_EXECUTION_DEPTH
781}
782
783struct InlineExecutionDepthGuard;
785
786impl InlineExecutionDepthGuard {
787 fn enter() -> Self {
788 INLINE_EXECUTION_DEPTH.set(INLINE_EXECUTION_DEPTH.get() + 1);
789 Self
790 }
791}
792
793impl Drop for InlineExecutionDepthGuard {
794 fn drop(&mut self) {
795 INLINE_EXECUTION_DEPTH.set(INLINE_EXECUTION_DEPTH.get() - 1);
796 }
797}
798
799async fn wait_until_zero(counter: &AtomicUsize, event: &Event, note: impl EventDescriptor + Copy) {
806 loop {
807 let listener = event.listen_with_note(note);
808 if counter.load(Ordering::Acquire) == 0 {
809 return;
810 }
811 listener.await;
812 }
813}
814
815fn poll_once_or_spawn(future: impl Future<Output = ()> + Send + 'static) -> bool {
818 let _depth_guard = InlineExecutionDepthGuard::enter();
819 let span_slot = InlineExecutionSpanSlot::default();
820 let mut future = Box::pin(INLINE_EXECUTION_SPAN.scope(span_slot.clone(), future));
821 match future
825 .as_mut()
826 .poll(&mut Context::from_waker(Waker::noop()))
827 {
828 Poll::Ready(()) => {
829 span_slot.record("complete");
830 true
831 }
832 Poll::Pending => {
833 span_slot.record("partial");
834 tokio::task::spawn(future);
835 false
836 }
837 }
838}
839
840pub(crate) fn execute_read_target_inline(
842 turbo_tasks: &dyn TurboTasksApi,
843 key: ScheduleKey,
844) -> bool {
845 if !inline_execution_allowed() {
846 return false;
848 }
849 turbo_tasks.try_execute_scheduled_task_inline(key)
850}
851
852pub struct TurboTasks<B: Backend + 'static> {
853 this: Weak<Self>,
854 backend: B,
855 execution_id_factory: IdFactory<ExecutionId>,
856 stopped: AtomicBool,
857 currently_scheduled_foreground_jobs: AtomicUsize,
858 currently_scheduled_background_jobs: AtomicUsize,
859 scheduled_tasks: AtomicUsize,
860 inline_counters: InlineExecutionCounters,
863 priority_runner:
864 Arc<PriorityRunner<TurboTasks<B>, ScheduledTask, TaskPriority, TurboTasksExecutor>>,
865 start: Mutex<Option<Instant>>,
866 aggregated_update: Mutex<(Option<(Duration, usize)>, InvalidationReasonSet)>,
867 event_foreground_start: Event,
869 event_foreground_done: Event,
872 event_background_done: Event,
874 compilation_events: CompilationEventQueue,
875}
876
877struct CurrentTaskState {
886 task_id: Option<TaskId>,
887 execution_id: ExecutionId,
888 priority: TaskPriority,
889
890 #[cfg(feature = "verify_determinism")]
893 stateful: bool,
894
895 has_invalidator: bool,
897
898 in_top_level_task: bool,
901
902 cell_counters: Option<AutoMap<ValueTypeId, u32, BuildHasherDefault<FxHasher>, 8>>,
907
908 local_tasks: LocalTaskTracker,
911}
912
913impl CurrentTaskState {
914 fn new(
915 task_id: TaskId,
916 execution_id: ExecutionId,
917 priority: TaskPriority,
918 in_top_level_task: bool,
919 ) -> Self {
920 Self {
921 task_id: Some(task_id),
922 execution_id,
923 priority,
924 #[cfg(feature = "verify_determinism")]
925 stateful: false,
926 has_invalidator: false,
927 in_top_level_task,
928 cell_counters: Some(AutoMap::default()),
929 local_tasks: LocalTaskTracker::new(),
930 }
931 }
932
933 fn new_temporary(
934 execution_id: ExecutionId,
935 priority: TaskPriority,
936 in_top_level_task: bool,
937 ) -> Self {
938 Self {
939 task_id: None,
940 execution_id,
941 priority,
942 #[cfg(feature = "verify_determinism")]
943 stateful: false,
944 has_invalidator: false,
945 in_top_level_task,
946 cell_counters: None,
947 local_tasks: LocalTaskTracker::new(),
948 }
949 }
950
951 fn assert_execution_id(&self, expected_execution_id: ExecutionId) {
952 if self.execution_id != expected_execution_id {
953 panic!(
954 "Local tasks can only be scheduled/awaited within the same execution of the \
955 parent task that created them"
956 );
957 }
958 }
959}
960
961#[derive(Clone)]
965struct CurrentTaskStateHandle {
966 inner: Arc<CurrentTaskStateInner>,
967}
968
969struct CurrentTaskStateInner {
970 current_task_id: Option<TaskId>,
971 provisional_read_counter: AtomicU32,
975 alive_provisional_read_refs: AtomicU32,
980 deferred_error: Mutex<Option<anyhow::Error>>,
985 state: RwLock<CurrentTaskState>,
986}
987
988const PROVISIONAL_READ_REF_LEAKED: &str =
993 "A `KeyedReadRef` or `LazyReadRef` was not dropped within the task execution that created it. \
994 It (and the `keyed_reader` / `lazy_reader` future) must be dropped before the task function \
995 returns, and must not be moved to other threads or tasks.";
996
997impl CurrentTaskStateHandle {
998 fn new(state: CurrentTaskState) -> Self {
999 Self {
1000 inner: Arc::new(CurrentTaskStateInner {
1001 current_task_id: state.task_id,
1002 provisional_read_counter: AtomicU32::new(0),
1003 alive_provisional_read_refs: AtomicU32::new(0),
1004 deferred_error: Mutex::new(None),
1005 state: RwLock::new(state),
1006 }),
1007 }
1008 }
1009
1010 fn current_task_id(&self) -> Option<TaskId> {
1011 self.inner.current_task_id
1012 }
1013}
1014
1015pub(crate) struct ProvisionalReadDependency {
1019 execution: Weak<CurrentTaskStateInner>,
1022 pub(crate) reader: TaskId,
1023 pub(crate) id: u32,
1024}
1025
1026impl ProvisionalReadDependency {
1027 pub(crate) fn new_for_current_task() -> Option<Self> {
1035 CURRENT_TASK_STATE
1036 .try_with(|ts| {
1037 let reader = ts.current_task_id()?;
1038 let id = ts
1039 .inner
1040 .provisional_read_counter
1041 .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
1042 .expect(
1043 "too many `keyed_reader` / `lazy_reader` reads in a single task execution",
1044 );
1045 Some(Self {
1046 execution: Arc::downgrade(&ts.inner),
1047 reader,
1048 id,
1049 })
1050 })
1051 .ok()
1052 .flatten()
1053 }
1054
1055 pub(crate) fn register_alive_ref(&self) {
1061 if let Some(execution) = self.execution.upgrade() {
1062 execution
1063 .alive_provisional_read_refs
1064 .fetch_add(1, Ordering::Relaxed);
1065 }
1066 }
1067
1068 pub(crate) fn fail_execution(&self, error: anyhow::Error) {
1073 if let Some(execution) = self.execution.upgrade() {
1074 execution
1075 .deferred_error
1076 .lock()
1077 .unwrap()
1078 .get_or_insert(error);
1079 }
1080 }
1081
1082 pub(crate) fn release_alive_ref(&self) {
1086 if let Some(execution) = self.execution.upgrade() {
1087 execution
1088 .alive_provisional_read_refs
1089 .fetch_sub(1, Ordering::Relaxed);
1090 }
1091 }
1092
1093 pub(crate) fn is_current_execution(&self) -> bool {
1096 CURRENT_TASK_STATE
1097 .try_with(|ts| {
1098 std::ptr::eq(self.execution.as_ptr(), Arc::as_ptr(&ts.inner))
1099 && ts.read().unwrap().cell_counters.is_some()
1100 })
1101 .unwrap_or(false)
1102 }
1103}
1104
1105impl Deref for CurrentTaskStateHandle {
1106 type Target = RwLock<CurrentTaskState>;
1107
1108 fn deref(&self) -> &Self::Target {
1109 &self.inner.state
1110 }
1111}
1112
1113task_local! {
1115 static TURBO_TASKS: Arc<dyn TurboTasksApi>;
1117
1118 static CURRENT_TASK_STATE: CurrentTaskStateHandle;
1119
1120 pub(crate) static SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK: bool;
1125
1126 static INLINE_EXECUTION_SPAN: InlineExecutionSpanSlot;
1129}
1130
1131#[derive(Clone, Default)]
1142struct InlineExecutionSpanSlot(Arc<Mutex<Option<Span>>>);
1143
1144impl InlineExecutionSpanSlot {
1145 fn set(span: &Span) {
1147 let _ = INLINE_EXECUTION_SPAN.try_with(|slot| {
1148 *slot.0.lock().unwrap() = Some(span.clone());
1149 });
1150 }
1151
1152 fn record(&self, outcome: &'static str) {
1156 if let Some(span) = self.0.lock().unwrap().as_ref() {
1157 span.record("inline_execution", outcome);
1158 }
1159 }
1160}
1161
1162impl<B: Backend + 'static> TurboTasks<B> {
1163 pub fn new(backend: B) -> Arc<Self> {
1169 let execution_id_factory = IdFactory::new(ExecutionId::MIN, ExecutionId::MAX);
1170 let this = Arc::new_cyclic(|this| Self {
1171 this: this.clone(),
1172 backend,
1173 execution_id_factory,
1174 stopped: AtomicBool::new(false),
1175 currently_scheduled_foreground_jobs: AtomicUsize::new(0),
1176 currently_scheduled_background_jobs: AtomicUsize::new(0),
1177 scheduled_tasks: AtomicUsize::new(0),
1178 inline_counters: InlineExecutionCounters::default(),
1179 priority_runner: Arc::new(PriorityRunner::new(TurboTasksExecutor)),
1180 start: Default::default(),
1181 aggregated_update: Default::default(),
1182 event_foreground_done: Event::new(|| {
1183 || "TurboTasks::event_foreground_done".to_string()
1184 }),
1185 event_foreground_start: Event::new(|| {
1186 || "TurboTasks::event_foreground_start".to_string()
1187 }),
1188 event_background_done: Event::new(|| {
1189 || "TurboTasks::event_background_done".to_string()
1190 }),
1191 compilation_events: CompilationEventQueue::default(),
1192 });
1193 this.backend.startup(&*this);
1194 this
1195 }
1196
1197 pub fn pin(&self) -> Arc<Self> {
1198 self.this.upgrade().unwrap()
1199 }
1200
1201 pub fn spawn_root_task<T, F, Fut>(&self, functor: F) -> TaskId
1203 where
1204 T: ?Sized,
1205 F: Fn() -> Fut + Send + Sync + Clone + 'static,
1206 Fut: Future<Output = Result<Vc<T>>> + Send,
1207 {
1208 let id = self.backend.create_transient_task(
1209 TransientTaskType::Root(Box::new(move || {
1210 let functor = functor.clone();
1211 Box::pin(async move {
1212 mark_top_level_task();
1213 let raw_vc = functor().await?.node;
1214 raw_vc.to_non_local().await
1215 })
1216 })),
1217 self,
1218 );
1219 self.schedule(id, TaskPriority::initial());
1220 id
1221 }
1222
1223 pub fn dispose_root_task(&self, task_id: TaskId) {
1224 self.backend.dispose_root_task(task_id, self);
1225 }
1226
1227 pub fn pin_task_for_gc(&self, task_id: TaskId) {
1231 self.backend.pin_task_for_gc(task_id, self);
1232 }
1233
1234 pub fn unpin_task_for_gc(&self, task_id: TaskId) {
1236 self.backend.unpin_task_for_gc(task_id, self);
1237 }
1238
1239 #[track_caller]
1243 fn spawn_once_task<T, Fut>(&self, future: Fut)
1244 where
1245 T: ?Sized,
1246 Fut: Future<Output = Result<Vc<T>>> + Send + 'static,
1247 {
1248 let id = self.backend.create_transient_task(
1249 TransientTaskType::Once(Box::pin(async move {
1250 mark_top_level_task();
1251 let raw_vc = future.await?.node;
1252 raw_vc.to_non_local().await
1253 })),
1254 self,
1255 );
1256 self.schedule(id, TaskPriority::initial());
1257 }
1258
1259 pub async fn run_once<T: Send + 'static>(
1282 &self,
1283 future: impl Future<Output = Result<T>> + Send + 'static,
1284 ) -> Result<T> {
1285 let (tx, rx) = tokio::sync::oneshot::channel();
1286 self.spawn_once_task(async move {
1287 mark_top_level_task();
1288 let result = future.await;
1289 tx.send(result)
1290 .map_err(|_| anyhow!("unable to send result"))?;
1291 Ok(Completion::new())
1292 });
1293
1294 rx.await?
1295 }
1296
1297 #[tracing::instrument(level = "trace", skip_all, name = "turbo_tasks::run")]
1303 pub async fn run<T: Send + 'static>(
1304 &self,
1305 future: impl Future<Output = Result<T>> + Send + 'static,
1306 ) -> Result<T, TurboTasksExecutionError> {
1307 self.begin_foreground_job();
1308 let execution_id = self.execution_id_factory.wrapping_get();
1310 let current_task_state = CurrentTaskStateHandle::new(CurrentTaskState::new_temporary(
1311 execution_id,
1312 TaskPriority::initial(),
1313 true, ));
1315
1316 let result = TURBO_TASKS
1317 .scope(
1318 self.pin(),
1319 CURRENT_TASK_STATE.scope(current_task_state, async {
1320 let result = CaptureFuture::new(future).await;
1321
1322 wait_for_local_tasks().await;
1324
1325 match result {
1326 Ok(Ok(value)) => Ok(value),
1327 Ok(Err(err)) => Err(err.into()),
1328 Err(err) => Err(TurboTasksExecutionError::Panic(Arc::new(err))),
1329 }
1330 }),
1331 )
1332 .await;
1333 self.finish_foreground_job();
1334 result
1335 }
1336
1337 pub fn start_once_process(&self, future: impl Future<Output = ()> + Send + 'static) {
1338 let this = self.pin();
1339 tokio::spawn(async move {
1340 this.pin()
1341 .run_once(async move {
1342 this.finish_foreground_job();
1343 future.await;
1344 this.begin_foreground_job();
1345 Ok(())
1346 })
1347 .await
1348 .unwrap()
1349 });
1350 }
1351
1352 pub(crate) fn native_call(
1353 &self,
1354 native_fn: &'static NativeFunction,
1355 this: Option<RawVc>,
1356 arg: &mut dyn DynTaskInputsStorage,
1357 persistence: TaskPersistence,
1358 ) -> RawVc {
1359 RawVc::task_output(self.backend.get_or_create_task(
1360 native_fn,
1361 this,
1362 arg,
1363 current_task_if_available("turbo_function calls"),
1364 persistence,
1365 self,
1366 ))
1367 }
1368
1369 pub fn dynamic_call(
1370 &self,
1371 native_fn: &'static NativeFunction,
1372 this: Option<RawVc>,
1373 arg: &mut dyn DynTaskInputsStorage,
1374 inputs_resolved: InputResolution,
1375 persistence: TaskPersistence,
1376 ) -> RawVc {
1377 if inputs_resolved.is_resolved() && this.is_none_or(|this| this.is_resolved()) {
1378 return self.native_call(native_fn, this, arg, persistence);
1379 }
1380 let arg = arg.take_box();
1382 let task_type = LocalTaskSpec {
1383 task_type: LocalTaskType::ResolveNative { native_fn },
1384 this,
1385 arg,
1386 };
1387 self.schedule_local_task(task_type, persistence)
1388 }
1389
1390 pub fn trait_call(
1391 &self,
1392 trait_method: &'static TraitMethod,
1393 this: RawVc,
1394 arg: &mut dyn DynTaskInputsStorage,
1395 inputs_resolved: InputResolution,
1396 persistence: TaskPersistence,
1397 ) -> RawVc {
1398 if let Some((_, cell_id)) = this.as_task_cell() {
1402 match registry::get_value_type(cell_id.type_id()).get_trait_method(trait_method) {
1403 Some(native_fn) => {
1404 if let Some(filter) = native_fn.arg_meta.filter_owned {
1405 return (filter)(arg, &mut |resolved, arg| {
1406 self.dynamic_call(native_fn, Some(this), arg, resolved, persistence)
1407 });
1408 } else {
1409 return self.dynamic_call(
1410 native_fn,
1411 Some(this),
1412 arg,
1413 inputs_resolved,
1414 persistence,
1415 );
1416 }
1417 }
1418 None => {
1419 }
1423 }
1424 }
1425
1426 let task_type = LocalTaskSpec {
1428 task_type: LocalTaskType::ResolveTrait { trait_method },
1429 this: Some(this),
1430 arg: arg.take_box(),
1431 };
1432
1433 self.schedule_local_task(task_type, persistence)
1434 }
1435
1436 #[track_caller]
1437 pub fn schedule(&self, task_id: TaskId, priority: TaskPriority) {
1438 self.begin_foreground_job();
1439 self.scheduled_tasks.fetch_add(1, Ordering::AcqRel);
1440
1441 let task = ScheduledTask::Task {
1442 task_id,
1443 span: Span::current(),
1444 };
1445 self.priority_runner.schedule(&self.pin(), task, priority);
1446 }
1447
1448 #[track_caller]
1451 pub fn schedule_many(&self, tasks: &[(TaskId, TaskPriority)]) {
1452 if tasks.is_empty() {
1453 return;
1454 }
1455 self.begin_foreground_jobs(tasks.len());
1456 self.scheduled_tasks
1457 .fetch_add(tasks.len(), Ordering::AcqRel);
1458
1459 let span = Span::current();
1460 self.priority_runner.schedule_many(
1461 &self.pin(),
1462 tasks.iter().map(|&(task_id, priority)| {
1463 (
1464 ScheduledTask::Task {
1465 task_id,
1466 span: span.clone(),
1467 },
1468 priority,
1469 )
1470 }),
1471 );
1472 }
1473
1474 fn schedule_local_task(
1475 &self,
1476 ty: LocalTaskSpec,
1477 persistence: TaskPersistence,
1479 ) -> RawVc {
1480 let task_type = ty.task_type;
1481 let (global_task_state, parent_task, execution_id, priority, local_task_id) =
1482 CURRENT_TASK_STATE.with(|gts| {
1483 let mut gts_write = gts.write().unwrap();
1484 let local_task_id = gts_write.local_tasks.create(task_type);
1485 (
1486 gts.clone(),
1487 gts_write.task_id,
1488 gts_write.execution_id,
1489 gts_write.priority,
1490 local_task_id,
1491 )
1492 });
1493
1494 let task = ScheduledTask::LocalTask {
1495 ty,
1496 persistence,
1497 parent_task,
1498 execution_id,
1499 local_task_id,
1500 global_task_state,
1501 span: Span::current(),
1502 };
1503 self.priority_runner.schedule(&self.pin(), task, priority);
1504
1505 RawVc::local_output(execution_id, local_task_id, persistence)
1506 }
1507
1508 fn try_execute_scheduled_task_inline(&self, key: ScheduleKey) -> bool {
1510 let this = self.pin();
1511 self.inline_counters.claim_attempted();
1512 if let Some(future) = self.priority_runner.claim(&this, &key) {
1513 let completed = poll_once_or_spawn(future);
1514 if completed {
1515 self.inline_counters.claim_completed();
1516 } else {
1517 self.inline_counters.claim_yielded();
1518 }
1519 return completed;
1520 }
1521 self.inline_counters.claim_failed();
1522 false
1523 }
1524
1525 #[cfg(feature = "inline_execution_stats")]
1526 fn note_waited_for_in_progress_task(&self) {
1527 self.inline_counters.waited_in_progress();
1528 }
1529
1530 fn begin_foreground_job(&self) {
1531 self.begin_foreground_jobs(1);
1532 }
1533
1534 fn begin_foreground_jobs(&self, count: usize) {
1536 debug_assert!(count > 0);
1537 if self
1538 .currently_scheduled_foreground_jobs
1539 .fetch_add(count, Ordering::AcqRel)
1540 == 0
1541 {
1542 *self.start.lock().unwrap() = Some(Instant::now());
1543 self.event_foreground_start.notify(usize::MAX);
1544 self.backend.idle_end(self);
1545 }
1546 }
1547
1548 fn finish_foreground_job(&self) {
1549 if self
1550 .currently_scheduled_foreground_jobs
1551 .fetch_sub(1, Ordering::AcqRel)
1552 == 1
1553 {
1554 self.backend.idle_start(self);
1555 let total = self.scheduled_tasks.load(Ordering::Acquire);
1558 self.scheduled_tasks.store(0, Ordering::Release);
1559 if let Some(start) = *self.start.lock().unwrap() {
1560 let (update, _) = &mut *self.aggregated_update.lock().unwrap();
1561 if let Some(update) = update.as_mut() {
1562 update.0 += start.elapsed();
1563 update.1 += total;
1564 } else {
1565 *update = Some((start.elapsed(), total));
1566 }
1567 }
1568 self.event_foreground_done.notify(usize::MAX);
1569 }
1570 }
1571
1572 fn begin_background_job(&self) {
1573 self.currently_scheduled_background_jobs
1574 .fetch_add(1, Ordering::Relaxed);
1575 }
1576
1577 fn finish_background_job(&self) {
1578 if self
1579 .currently_scheduled_background_jobs
1580 .fetch_sub(1, Ordering::Relaxed)
1581 == 1
1582 {
1583 self.event_background_done.notify(usize::MAX);
1584 }
1585 }
1586
1587 pub fn get_in_progress_count(&self) -> usize {
1588 self.currently_scheduled_foreground_jobs
1589 .load(Ordering::Acquire)
1590 }
1591
1592 #[cfg(feature = "inline_execution_stats")]
1595 #[doc(hidden)]
1596 pub fn inline_execution_stats(&self) -> InlineExecutionStats {
1597 let counters = &self.inline_counters;
1598 InlineExecutionStats {
1599 queued: self.priority_runner.total_queued(),
1600 claim_attempted: counters.claim_attempted.load(Ordering::Relaxed),
1601 claim_completed: counters.claim_completed.load(Ordering::Relaxed),
1602 claim_yielded: counters.claim_yielded.load(Ordering::Relaxed),
1603 claim_failed: counters.claim_failed.load(Ordering::Relaxed),
1604 waited_in_progress: counters.waited_in_progress.load(Ordering::Relaxed),
1605 }
1606 }
1607
1608 pub async fn wait_task_completion(
1620 &self,
1621 id: TaskId,
1622 consistency: ReadConsistency,
1623 ) -> Result<()> {
1624 read_task_output(
1625 self,
1626 id,
1627 ReadOutputOptions {
1628 tracking: ReadTracking::Untracked,
1630 consistency,
1631 },
1632 )
1633 .await?;
1634 Ok(())
1635 }
1636
1637 pub async fn get_or_wait_aggregated_update_info(&self, aggregation: Duration) -> UpdateInfo {
1640 self.aggregated_update_info(aggregation, Duration::MAX)
1641 .await
1642 .unwrap()
1643 }
1644
1645 pub async fn aggregated_update_info(
1650 &self,
1651 aggregation: Duration,
1652 timeout: Duration,
1653 ) -> Option<UpdateInfo> {
1654 let listener = self
1655 .event_foreground_done
1656 .listen_with_note(|| || "wait for update info".to_string());
1657 let wait_for_finish = {
1658 let (update, reason_set) = &mut *self.aggregated_update.lock().unwrap();
1659 if aggregation.is_zero() {
1660 if let Some((duration, tasks)) = update.take() {
1661 return Some(UpdateInfo {
1662 duration,
1663 tasks,
1664 reasons: take(reason_set),
1665 placeholder_for_future_fields: (),
1666 });
1667 } else {
1668 true
1669 }
1670 } else {
1671 update.is_none()
1672 }
1673 };
1674 if wait_for_finish {
1675 if timeout == Duration::MAX {
1676 listener.await;
1678 } else {
1679 let start_listener = self
1681 .event_foreground_start
1682 .listen_with_note(|| || "wait for update info".to_string());
1683 if self
1684 .currently_scheduled_foreground_jobs
1685 .load(Ordering::Acquire)
1686 == 0
1687 {
1688 start_listener.await;
1689 } else {
1690 drop(start_listener);
1691 }
1692 if timeout.is_zero() || tokio::time::timeout(timeout, listener).await.is_err() {
1693 return None;
1695 }
1696 }
1697 }
1698 if !aggregation.is_zero() {
1699 loop {
1700 select! {
1701 () = tokio::time::sleep(aggregation) => {
1702 let listener = self
1706 .event_foreground_done
1707 .listen_with_note(|| || "wait for update info".to_string());
1708 if self
1709 .currently_scheduled_foreground_jobs
1710 .load(Ordering::Acquire)
1711 == 0
1712 {
1713 break;
1714 }
1715 listener.await;
1716 }
1718 () = self.event_foreground_done.listen_with_note(|| || "wait for update info".to_string()) => {
1719 }
1721 }
1722 }
1723 }
1724 let (update, reason_set) = &mut *self.aggregated_update.lock().unwrap();
1725 if let Some((duration, tasks)) = update.take() {
1726 Some(UpdateInfo {
1727 duration,
1728 tasks,
1729 reasons: take(reason_set),
1730 placeholder_for_future_fields: (),
1731 })
1732 } else {
1733 panic!("aggregated_update_info must not called concurrently")
1734 }
1735 }
1736
1737 pub async fn wait_background_done(&self) {
1738 wait_until_zero(
1739 &self.currently_scheduled_background_jobs,
1740 &self.event_background_done,
1741 || || "wait for background jobs".to_string(),
1742 )
1743 .await;
1744 }
1745
1746 pub async fn stop_and_wait(&self) {
1747 #[cfg(feature = "inline_execution_stats")]
1748 if inline_stats_requested() {
1749 eprintln!(
1752 "turbo-tasks inline execution stats: {:#?}",
1753 self.inline_execution_stats()
1754 );
1755 }
1756 turbo_tasks_future_scope(self.pin(), async move {
1757 self.backend.stopping(self);
1758 self.stopped.store(true, Ordering::Release);
1759 wait_until_zero(
1762 &self.currently_scheduled_foreground_jobs,
1763 &self.event_foreground_done,
1764 || || "wait for stop".to_string(),
1765 )
1766 .await;
1767 self.wait_background_done().await;
1768 self.backend.stop(self);
1769 self.compilation_events.flush_and_close().await;
1773 })
1774 .await;
1775 }
1776
1777 #[track_caller]
1778 pub(crate) fn schedule_background_job<T>(&self, func: T)
1779 where
1780 T: AsyncFnOnce(Arc<TurboTasks<B>>) -> Arc<TurboTasks<B>> + Send + 'static,
1781 T::CallOnceFuture: Send,
1782 {
1783 let mut this = self.pin();
1784 self.begin_background_job();
1785 tokio::spawn(
1786 TURBO_TASKS
1787 .scope(this.clone(), async move {
1788 if !this.stopped.load(Ordering::Acquire) {
1789 this = func(this).await;
1790 }
1791 this.finish_background_job();
1792 })
1793 .in_current_span(),
1794 );
1795 }
1796
1797 fn finish_current_task_state(&self) -> FinishedTaskState {
1798 CURRENT_TASK_STATE.with(|cell| {
1799 let current_task_state = &*cell.write().unwrap();
1800 FinishedTaskState {
1801 #[cfg(feature = "verify_determinism")]
1802 stateful: current_task_state.stateful,
1803 has_invalidator: current_task_state.has_invalidator,
1804 }
1805 })
1806 }
1807
1808 pub fn backend(&self) -> &B {
1809 &self.backend
1810 }
1811
1812 pub fn get_current_task_priority(&self) -> TaskPriority {
1813 CURRENT_TASK_STATE
1814 .try_with(|task_state| task_state.read().unwrap().priority)
1815 .unwrap_or(TaskPriority::initial())
1816 }
1817
1818 pub fn is_idle(&self) -> bool {
1819 self.currently_scheduled_foreground_jobs
1820 .load(Ordering::Acquire)
1821 == 0
1822 }
1823
1824 #[track_caller]
1825 pub fn schedule_backend_background_job(&self, job: B::BackendJob) {
1826 self.schedule_background_job(async move |this| {
1827 this.backend.run_backend_job(job, &*this).await;
1828 this
1829 })
1830 }
1831}
1832
1833struct TurboTasksExecutor;
1834
1835fn abort_on_panic<F: Future>(f: F) -> impl Future<Output = F::Output> {
1849 AssertUnwindSafe(f)
1850 .catch_unwind()
1851 .map(|result| match result {
1852 Ok(r) => r,
1853 Err(payload) => {
1854 eprintln!("\n{}\n\nAborting.", abort_on_panic_message(&*payload));
1855 abort();
1856 }
1857 })
1858}
1859
1860fn abort_on_panic_message(payload: &(dyn std::any::Any + Send)) -> Cow<'static, str> {
1868 if let Some(panic) = payload.downcast_ref::<crate::PersistentCacheUnreadablePanic>() {
1869 format!(
1870 "turbo-tasks: the persistent cache could not be read:\n\n{}",
1871 panic.message
1872 )
1873 .into()
1874 } else {
1875 "turbo-tasks: an internal panic occurred outside the per-task panic boundary. This is a \
1876 bug in turbo-tasks/Turbopack — please report it at \
1877 https://github.com/vercel/next.js/discussions and include the panic message and stack \
1878 trace above."
1879 .into()
1880 }
1881}
1882
1883impl<B: Backend> Executor<TurboTasks<B>, ScheduledTask, TaskPriority> for TurboTasksExecutor {
1884 const LOWEST_PRIORITY: TaskPriority = TaskPriority::Initial;
1885
1886 type Future = impl Future<Output = ()> + Send + 'static;
1887
1888 fn execute(
1889 &self,
1890 this: &Arc<TurboTasks<B>>,
1891 scheduled_task: ScheduledTask,
1892 priority: TaskPriority,
1893 ) -> Self::Future {
1894 match scheduled_task {
1895 ScheduledTask::Task { task_id, span } => {
1896 let this2 = this.clone();
1897 let this = this.clone();
1898 let future = async move {
1899 abort_on_panic(async {
1900 let execution_id = this.execution_id_factory.wrapping_get();
1903 let current_task_state =
1904 CurrentTaskStateHandle::new(CurrentTaskState::new(
1905 task_id,
1906 execution_id,
1907 priority,
1908 false, ));
1910 let single_execution_future = async {
1911 if this.stopped.load(Ordering::Acquire) {
1912 this.backend.task_execution_canceled(task_id, &*this);
1913 return None;
1914 }
1915
1916 let TaskExecutionSpec { future, span } = this
1917 .backend
1918 .try_start_task_execution(task_id, priority, &*this)?;
1919
1920 InlineExecutionSpanSlot::set(&span);
1923
1924 async {
1925 let result = CaptureFuture::new(future).await;
1926
1927 wait_for_local_tasks().await;
1929
1930 let result = match result {
1931 Ok(Ok(raw_vc)) => {
1932 raw_vc
1935 .to_non_local_unchecked_sync(&*this)
1936 .map_err(|err| err.into())
1937 }
1938 Ok(Err(err)) => Err(err.into()),
1939 Err(err) => Err(TurboTasksExecutionError::Panic(Arc::new(err))),
1940 };
1941 let deferred_error = CURRENT_TASK_STATE
1946 .with(|ts| ts.inner.deferred_error.lock().unwrap().take());
1947 let result = match (result, deferred_error) {
1948 (Ok(_), Some(error)) => Err(error.into()),
1949 (result, _) => result,
1950 };
1951
1952 let finished_state = this.finish_current_task_state();
1953 let (
1954 cell_counters,
1955 has_provisional_reads,
1956 leaked_provisional_read_refs,
1957 ) = CURRENT_TASK_STATE.with(|ts| {
1958 let cell_counters =
1962 ts.write().unwrap().cell_counters.take().unwrap();
1963 let has_provisional_reads =
1969 ts.inner.provisional_read_counter.load(Ordering::Relaxed)
1970 > 0;
1971 let leaked_provisional_read_refs = has_provisional_reads
1972 && ts
1973 .inner
1974 .alive_provisional_read_refs
1975 .load(Ordering::Relaxed)
1976 > 0;
1977 (
1978 cell_counters,
1979 has_provisional_reads,
1980 leaked_provisional_read_refs,
1981 )
1982 });
1983 let stale_priority = this.backend.task_execution_completed(
1990 task_id,
1991 result,
1992 &cell_counters,
1993 has_provisional_reads,
1994 #[cfg(feature = "verify_determinism")]
1995 finished_state.stateful,
1996 finished_state.has_invalidator,
1997 &*this,
1998 );
1999 if leaked_provisional_read_refs {
2000 panic!(
2001 "{PROVISIONAL_READ_REF_LEAKED} Task: {}",
2002 this.backend.get_task_name(task_id, &*this)
2003 );
2004 }
2005 stale_priority
2006 }
2007 .instrument(span)
2008 .await
2009 };
2010 if let Some(stale_priority) = CURRENT_TASK_STATE
2011 .scope(current_task_state, single_execution_future)
2012 .await
2013 {
2014 this.schedule(task_id, stale_priority);
2017 }
2018 this.finish_foreground_job();
2019 })
2020 .await
2021 };
2022
2023 Either::Left(TURBO_TASKS.scope(this2, future).instrument(span))
2024 }
2025 ScheduledTask::LocalTask {
2026 ty,
2027 persistence,
2028 parent_task: _,
2029 execution_id: _,
2030 local_task_id,
2031 global_task_state,
2032 span,
2033 } => {
2034 let this2 = this.clone();
2035 let this = this.clone();
2036 let task_type = ty.task_type;
2037 let future = async move {
2038 let span = match &ty.task_type {
2039 LocalTaskType::ResolveNative { native_fn } => {
2040 native_fn.resolve_span(priority)
2041 }
2042 LocalTaskType::ResolveTrait { trait_method } => {
2043 trait_method.resolve_span(priority)
2044 }
2045 };
2046 InlineExecutionSpanSlot::set(&span);
2049 abort_on_panic(
2050 async move {
2051 let result = match ty.task_type {
2052 LocalTaskType::ResolveNative { native_fn } => {
2053 LocalTaskType::run_resolve_native(
2054 native_fn,
2055 ty.this,
2056 &*ty.arg,
2057 persistence,
2058 this,
2059 )
2060 .await
2061 }
2062 LocalTaskType::ResolveTrait { trait_method } => {
2063 LocalTaskType::run_resolve_trait(
2064 trait_method,
2065 ty.this.unwrap(),
2066 &*ty.arg,
2067 persistence,
2068 this,
2069 )
2070 .await
2071 }
2072 };
2073
2074 let output = match result {
2075 Ok(raw_vc) => OutputContent::Link(raw_vc),
2076 Err(err) => OutputContent::Error(
2077 TurboTasksExecutionError::from(err)
2078 .with_local_task_context(task_type.to_string()),
2079 ),
2080 };
2081
2082 CURRENT_TASK_STATE.with(move |gts| {
2083 gts.write()
2084 .unwrap()
2085 .local_tasks
2086 .complete(local_task_id, output);
2087 });
2088 }
2089 .instrument(span),
2090 )
2091 .await
2092 };
2093 let future = CURRENT_TASK_STATE.scope(global_task_state, future);
2094
2095 Either::Right(TURBO_TASKS.scope(this2, future).instrument(span))
2096 }
2097 }
2098 }
2099
2100 fn discard(
2101 &self,
2102 this: &Arc<TurboTasks<B>>,
2103 scheduled_task: ScheduledTask,
2104 _priority: TaskPriority,
2105 ) {
2106 match scheduled_task {
2107 ScheduledTask::Task { .. } => this.finish_foreground_job(),
2110 ScheduledTask::LocalTask { .. } => {}
2113 }
2114 }
2115}
2116
2117struct FinishedTaskState {
2118 #[cfg(feature = "verify_determinism")]
2121 stateful: bool,
2122
2123 has_invalidator: bool,
2125}
2126
2127impl<B: Backend + 'static> TurboTasksCallApi for TurboTasks<B> {
2128 fn dynamic_call(
2129 &self,
2130 native_fn: &'static NativeFunction,
2131 this: Option<RawVc>,
2132 arg: &mut dyn DynTaskInputsStorage,
2133 inputs_resolved: InputResolution,
2134 persistence: TaskPersistence,
2135 ) -> RawVc {
2136 self.dynamic_call(native_fn, this, arg, inputs_resolved, persistence)
2137 }
2138 fn native_call(
2139 &self,
2140 native_fn: &'static NativeFunction,
2141 this: Option<RawVc>,
2142 arg: &mut dyn DynTaskInputsStorage,
2143 persistence: TaskPersistence,
2144 ) -> RawVc {
2145 self.native_call(native_fn, this, arg, persistence)
2146 }
2147 fn trait_call(
2148 &self,
2149 trait_method: &'static TraitMethod,
2150 this: RawVc,
2151 arg: &mut dyn DynTaskInputsStorage,
2152 inputs_resolved: InputResolution,
2153 persistence: TaskPersistence,
2154 ) -> RawVc {
2155 self.trait_call(trait_method, this, arg, inputs_resolved, persistence)
2156 }
2157
2158 #[track_caller]
2159 fn run(
2160 &self,
2161 future: Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>,
2162 ) -> Pin<Box<dyn Future<Output = Result<(), TurboTasksExecutionError>> + Send>> {
2163 let this = self.pin();
2164 Box::pin(async move { this.run(future).await })
2165 }
2166
2167 #[track_caller]
2168 fn run_once(
2169 &self,
2170 future: Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>,
2171 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
2172 let this = self.pin();
2173 Box::pin(async move { this.run_once(future).await })
2174 }
2175
2176 #[track_caller]
2177 fn run_once_with_reason(
2178 &self,
2179 reason: StaticOrArc<dyn InvalidationReason>,
2180 future: Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>,
2181 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
2182 {
2183 let (_, reason_set) = &mut *self.aggregated_update.lock().unwrap();
2184 reason_set.insert(reason);
2185 }
2186 let this = self.pin();
2187 Box::pin(async move { this.run_once(future).await })
2188 }
2189
2190 #[track_caller]
2191 fn start_once_process(&self, future: Pin<Box<dyn Future<Output = ()> + Send + 'static>>) {
2192 self.start_once_process(future)
2193 }
2194
2195 fn send_compilation_event(&self, event: Arc<dyn CompilationEvent>) {
2196 if let Err(e) = self.compilation_events.send(event) {
2197 tracing::warn!("Failed to send compilation event: {e}");
2198 }
2199 }
2200
2201 fn get_task_name(&self, task: TaskId) -> String {
2202 self.backend.get_task_name(task, self)
2203 }
2204}
2205
2206impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
2207 #[instrument(level = "info", skip_all, name = "invalidate")]
2208 fn invalidate(&self, task: TaskId) {
2209 self.backend.invalidate_task(task, self);
2210 }
2211
2212 #[instrument(level = "info", skip_all, name = "invalidate", fields(name = display(&reason)))]
2213 fn invalidate_with_reason(&self, task: TaskId, reason: StaticOrArc<dyn InvalidationReason>) {
2214 {
2215 let (_, reason_set) = &mut *self.aggregated_update.lock().unwrap();
2216 reason_set.insert(reason);
2217 }
2218 self.backend.invalidate_task(task, self);
2219 }
2220
2221 #[instrument(level = "info", skip_all, name = "invalidate many", fields(count = tasks.len()))]
2222 fn invalidate_many(&self, tasks: &[TaskId]) {
2223 if tasks.is_empty() {
2224 return;
2225 }
2226 self.backend.invalidate_tasks(tasks, self);
2227 }
2228
2229 #[instrument(level = "info", skip_all, name = "invalidate many", fields(count = tasks.len()))]
2230 fn invalidate_many_with_reasons(
2231 &self,
2232 tasks: &[TaskId],
2233 reasons: Vec<StaticOrArc<dyn InvalidationReason>>,
2234 ) {
2235 if tasks.is_empty() {
2236 return;
2237 }
2238 {
2240 let (_, reason_set) = &mut *self.aggregated_update.lock().unwrap();
2241 for reason in reasons {
2242 reason_set.insert(reason);
2243 }
2244 }
2245 self.backend.invalidate_tasks(tasks, self);
2246 }
2247
2248 fn invalidate_serialization(&self, task: TaskId) {
2249 self.backend.invalidate_serialization(task, self);
2250 }
2251
2252 #[track_caller]
2253 fn try_read_task_output(
2254 &self,
2255 task: TaskId,
2256 options: ReadOutputOptions,
2257 ) -> Result<ReadOutcome<RawVc>> {
2258 if options.consistency == ReadConsistency::Eventual {
2259 debug_assert_not_in_top_level_task("read_task_output");
2260 }
2261 self.backend.try_read_task_output(
2262 task,
2263 current_task_if_available("reading Vcs"),
2264 options,
2265 self,
2266 )
2267 }
2268
2269 #[track_caller]
2270 fn try_read_task_cell(
2271 &self,
2272 task: TaskId,
2273 index: CellId,
2274 options: ReadCellOptions,
2275 ) -> Result<ReadOutcome<TypedCellContent>> {
2276 let reader = current_task_if_available("reading Vcs");
2277 self.backend
2278 .try_read_task_cell(task, index, reader, options, self)
2279 }
2280
2281 fn refine_provisional_cell_dependency(
2282 &self,
2283 task: TaskId,
2284 index: CellId,
2285 reader: TaskId,
2286 id: u32,
2287 key_hashes: &FxHashSet<u64>,
2288 ) -> Result<()> {
2289 self.backend.refine_provisional_cell_dependency(
2290 task,
2291 index,
2292 reader,
2293 id,
2294 key_hashes.iter().copied(),
2295 self,
2296 )
2297 }
2298
2299 fn try_read_own_task_cell(
2300 &self,
2301 current_task: TaskId,
2302 index: CellId,
2303 ) -> Result<TypedCellContent> {
2304 self.backend
2305 .try_read_own_task_cell(current_task, index, self)
2306 }
2307
2308 fn drop_task_cell_content_hint(&self, task: TaskId, index: CellId) -> Result<()> {
2309 self.backend.drop_task_cell_content_hint(task, index, self)
2310 }
2311
2312 #[track_caller]
2313 fn try_read_local_output(
2314 &self,
2315 execution_id: ExecutionId,
2316 local_task_id: LocalTaskId,
2317 ) -> Result<Result<RawVc, EventListener>> {
2318 debug_assert_not_in_top_level_task("read_local_output");
2319 CURRENT_TASK_STATE.with(|gts| {
2320 let gts_read = gts.read().unwrap();
2321
2322 gts_read.assert_execution_id(execution_id);
2327
2328 match gts_read.local_tasks.get(local_task_id) {
2329 LocalTask::Scheduled { done_event } => Ok(Err(done_event.listen())),
2330 LocalTask::Done { output } => Ok(Ok(output.as_read_result()?)),
2331 }
2332 })
2333 }
2334
2335 fn read_task_collectibles(&self, task: TaskId, trait_id: TraitTypeId) -> TaskCollectiblesMap {
2336 self.backend.read_task_collectibles(
2339 task,
2340 trait_id,
2341 current_task_if_available("reading collectibles"),
2342 self,
2343 )
2344 }
2345
2346 fn try_execute_scheduled_task_inline(&self, key: ScheduleKey) -> bool {
2347 self.try_execute_scheduled_task_inline(key)
2348 }
2349
2350 #[cfg(feature = "inline_execution_stats")]
2351 fn note_waited_for_in_progress_task(&self) {
2352 self.note_waited_for_in_progress_task()
2353 }
2354
2355 fn emit_collectible(&self, trait_type: TraitTypeId, collectible: RawVc) {
2356 self.backend.emit_collectible(
2357 trait_type,
2358 collectible,
2359 current_task("emitting collectible"),
2360 self,
2361 );
2362 }
2363
2364 fn unemit_collectible(&self, trait_type: TraitTypeId, collectible: RawVc, count: u32) {
2365 self.backend.unemit_collectible(
2366 trait_type,
2367 collectible,
2368 count,
2369 current_task("emitting collectible"),
2370 self,
2371 );
2372 }
2373
2374 fn unemit_collectibles(&self, trait_type: TraitTypeId, collectibles: &TaskCollectiblesMap) {
2375 if !collectibles.values().any(|&count| count > 0) {
2376 return;
2377 }
2378 self.backend.unemit_collectibles(
2379 trait_type,
2380 collectibles,
2381 current_task("unemitting collectibles"),
2382 self,
2383 );
2384 }
2385
2386 fn read_own_task_cell(&self, task: TaskId, index: CellId) -> Result<TypedCellContent> {
2387 self.try_read_own_task_cell(task, index)
2388 }
2389
2390 fn update_own_task_cell(
2391 &self,
2392 task: TaskId,
2393 index: CellId,
2394 content: CellContent,
2395 updated_key_hashes: Option<SmallVec<[u64; 2]>>,
2396 content_hash: Option<CellHash>,
2397 verification_mode: VerificationMode,
2398 ) {
2399 self.backend.update_task_cell(
2400 task,
2401 index,
2402 content,
2403 updated_key_hashes,
2404 content_hash,
2405 verification_mode,
2406 self,
2407 );
2408 }
2409
2410 fn connect_task(&self, task: TaskId) {
2411 self.backend
2412 .connect_task(task, current_task_if_available("connecting task"), self);
2413 }
2414
2415 fn mark_own_task_as_finished(&self, task: TaskId) {
2416 self.backend.mark_own_task_as_finished(task, self);
2417 }
2418
2419 fn pin_task_for_gc(&self, task: TaskId) {
2420 self.backend.pin_task_for_gc(task, self);
2421 }
2422
2423 fn unpin_task_for_gc(&self, task: TaskId) {
2424 self.backend.unpin_task_for_gc(task, self);
2425 }
2426
2427 fn spawn_detached_for_testing(&self, fut: Pin<Box<dyn Future<Output = ()> + Send + 'static>>) {
2430 let global_task_state = CURRENT_TASK_STATE.with(|ts| ts.clone());
2433 global_task_state
2434 .write()
2435 .unwrap()
2436 .local_tasks
2437 .register_detached();
2438 let wrapped = async move {
2439 struct DropGuard;
2441 impl Drop for DropGuard {
2442 fn drop(&mut self) {
2443 CURRENT_TASK_STATE
2444 .with(|ts| ts.write().unwrap().local_tasks.decrement_in_flight());
2445 }
2446 }
2447 let _guard = DropGuard;
2448 fut.await;
2449 };
2450 tokio::spawn(TURBO_TASKS.scope(
2451 turbo_tasks(),
2452 CURRENT_TASK_STATE.scope(global_task_state, wrapped),
2453 ));
2454 }
2455
2456 fn task_statistics(&self) -> &TaskStatisticsApi {
2457 self.backend.task_statistics()
2458 }
2459
2460 fn stop_and_wait(&self) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> {
2461 let this = self.pin();
2462 Box::pin(async move {
2463 this.stop_and_wait().await;
2464 })
2465 }
2466
2467 fn subscribe_to_compilation_events(
2468 &self,
2469 event_types: Option<Vec<String>>,
2470 ) -> Receiver<Arc<dyn CompilationEvent>> {
2471 self.compilation_events.subscribe(event_types)
2472 }
2473
2474 fn is_tracking_dependencies(&self) -> bool {
2475 self.backend.is_tracking_dependencies()
2476 }
2477}
2478
2479async fn wait_for_local_tasks() {
2480 let listener =
2481 CURRENT_TASK_STATE.with(|ts| ts.read().unwrap().local_tasks.listen_for_in_flight());
2482 let Some(listener) = listener else {
2483 return;
2484 };
2485 listener.await;
2486}
2487
2488pub(crate) fn current_task_if_available(from: &str) -> Option<TaskId> {
2489 match CURRENT_TASK_STATE.try_with(|ts| ts.current_task_id()) {
2490 Ok(id) => id,
2491 Err(_) => panic!(
2492 "{from} can only be used in the context of a turbo_tasks task execution or \
2493 turbo_tasks run"
2494 ),
2495 }
2496}
2497
2498pub(crate) fn current_task(from: &str) -> TaskId {
2499 match CURRENT_TASK_STATE.try_with(|ts| ts.current_task_id()) {
2500 Ok(Some(id)) => id,
2501 Ok(None) | Err(_) => {
2502 panic!("{from} can only be used in the context of a turbo_tasks task execution")
2503 }
2504 }
2505}
2506
2507#[track_caller]
2510pub(crate) fn debug_assert_in_top_level_task(message: &str) {
2511 if !cfg!(debug_assertions) {
2512 return;
2513 }
2514
2515 let in_top_level = CURRENT_TASK_STATE
2516 .try_with(|ts| ts.read().unwrap().in_top_level_task)
2517 .unwrap_or(true);
2518 if !in_top_level {
2519 panic!("{message}");
2520 }
2521}
2522
2523#[track_caller]
2524pub(crate) fn debug_assert_not_in_top_level_task(operation: &str) {
2525 if !cfg!(debug_assertions) {
2526 return;
2527 }
2528
2529 let suppressed = SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK
2532 .try_with(|&suppressed| suppressed)
2533 .unwrap_or(false);
2534 if suppressed {
2535 return;
2536 }
2537
2538 let in_top_level = CURRENT_TASK_STATE
2539 .try_with(|ts| ts.read().unwrap().in_top_level_task)
2540 .unwrap_or(false);
2541 if in_top_level {
2542 panic!(
2543 "Eventually consistent read ({operation}) cannot be performed from a top-level task. \
2544 Top-level tasks (e.g. code inside `.run_once(...)`) must use strongly consistent \
2545 reads to avoid leaking inconsistent return values."
2546 );
2547 }
2548}
2549
2550pub async fn run<T: Send + 'static>(
2551 tt: Arc<dyn TurboTasksApi>,
2552 future: impl Future<Output = Result<T>> + Send + 'static,
2553) -> Result<T> {
2554 let (tx, rx) = tokio::sync::oneshot::channel();
2555
2556 tt.run(Box::pin(async move {
2557 let result = future.await?;
2558 tx.send(result)
2559 .map_err(|_| anyhow!("unable to send result"))?;
2560 Ok(())
2561 }))
2562 .await?;
2563
2564 Ok(rx.await?)
2565}
2566
2567pub async fn run_once<T: Send + 'static>(
2568 tt: Arc<dyn TurboTasksApi>,
2569 future: impl Future<Output = Result<T>> + Send + 'static,
2570) -> Result<T> {
2571 let (tx, rx) = tokio::sync::oneshot::channel();
2572
2573 tt.run_once(Box::pin(async move {
2574 let result = future.await?;
2575 tx.send(result)
2576 .map_err(|_| anyhow!("unable to send result"))?;
2577 Ok(())
2578 }))
2579 .await?;
2580
2581 Ok(rx.await?)
2582}
2583
2584pub async fn run_once_with_reason<T: Send + 'static>(
2585 tt: Arc<dyn TurboTasksApi>,
2586 reason: impl InvalidationReason,
2587 future: impl Future<Output = Result<T>> + Send + 'static,
2588) -> Result<T> {
2589 let (tx, rx) = tokio::sync::oneshot::channel();
2590
2591 tt.run_once_with_reason(
2592 (Arc::new(reason) as Arc<dyn InvalidationReason>).into(),
2593 Box::pin(async move {
2594 let result = future.await?;
2595 tx.send(result)
2596 .map_err(|_| anyhow!("unable to send result"))?;
2597 Ok(())
2598 }),
2599 )
2600 .await?;
2601
2602 Ok(rx.await?)
2603}
2604
2605pub fn dynamic_call(
2607 func: &'static NativeFunction,
2608 this: Option<RawVc>,
2609 arg: &mut dyn DynTaskInputsStorage,
2610 inputs_resolved: InputResolution,
2611 persistence: TaskPersistence,
2612) -> RawVc {
2613 with_turbo_tasks(|tt| tt.dynamic_call(func, this, arg, inputs_resolved, persistence))
2614}
2615
2616pub fn trait_call(
2618 trait_method: &'static TraitMethod,
2619 this: RawVc,
2620 arg: &mut dyn DynTaskInputsStorage,
2621 inputs_resolved: InputResolution,
2622 persistence: TaskPersistence,
2623) -> RawVc {
2624 with_turbo_tasks(|tt| tt.trait_call(trait_method, this, arg, inputs_resolved, persistence))
2625}
2626
2627pub fn turbo_tasks() -> Arc<dyn TurboTasksApi> {
2628 TURBO_TASKS.with(|arc| arc.clone())
2629}
2630
2631pub fn turbo_tasks_weak() -> Weak<dyn TurboTasksApi> {
2632 TURBO_TASKS.with(Arc::downgrade)
2633}
2634
2635pub fn try_turbo_tasks() -> Option<Arc<dyn TurboTasksApi>> {
2636 TURBO_TASKS.try_with(|arc| arc.clone()).ok()
2637}
2638
2639pub fn with_turbo_tasks<T>(func: impl FnOnce(&Arc<dyn TurboTasksApi>) -> T) -> T {
2640 TURBO_TASKS.with(|arc| func(arc))
2641}
2642
2643pub fn turbo_tasks_scope<T>(tt: Arc<dyn TurboTasksApi>, f: impl FnOnce() -> T) -> T {
2644 TURBO_TASKS.sync_scope(tt, f)
2645}
2646
2647pub fn turbo_tasks_future_scope<T>(
2648 tt: Arc<dyn TurboTasksApi>,
2649 f: impl Future<Output = T>,
2650) -> impl Future<Output = T> {
2651 TURBO_TASKS.scope(tt, f)
2652}
2653
2654pub(crate) fn spawn_in_current_task<T: Send + 'static>(
2667 future: impl Future<Output = T> + Send + 'static,
2668) -> JoinHandle<T> {
2669 struct InFlightGuard(CurrentTaskStateHandle);
2672 impl Drop for InFlightGuard {
2673 fn drop(&mut self) {
2674 self.0.write().unwrap().local_tasks.decrement_in_flight();
2675 }
2676 }
2677
2678 let task_state = CURRENT_TASK_STATE.with(|ts| ts.clone());
2679 task_state.write().unwrap().local_tasks.register_detached();
2680 let guard = InFlightGuard(task_state.clone());
2681 let future = async move {
2682 let result = CaptureFuture::new(future).await;
2683 drop(guard);
2685 result
2686 };
2687 JoinHandle::new(tokio::task::spawn(
2688 TURBO_TASKS
2689 .scope(turbo_tasks(), CURRENT_TASK_STATE.scope(task_state, future))
2690 .instrument(Span::current()),
2691 ))
2692}
2693
2694pub fn spawn_detached_for_testing(f: impl Future<Output = ()> + Send + 'static) {
2699 turbo_tasks().spawn_detached_for_testing(Box::pin(f));
2700}
2701
2702pub fn mark_finished() {
2705 with_turbo_tasks(|tt| {
2706 tt.mark_own_task_as_finished(current_task("turbo_tasks::mark_finished()"))
2707 });
2708}
2709
2710pub fn get_serialization_invalidator() -> SerializationInvalidator {
2716 CURRENT_TASK_STATE.with(|cell| {
2717 let CurrentTaskState {
2718 task_id,
2719 #[cfg(feature = "verify_determinism")]
2720 stateful,
2721 ..
2722 } = &mut *cell.write().unwrap();
2723 #[cfg(feature = "verify_determinism")]
2724 {
2725 *stateful = true;
2726 }
2727 let Some(task_id) = *task_id else {
2728 panic!(
2729 "get_serialization_invalidator() can only be used in the context of a turbo_tasks \
2730 task execution"
2731 );
2732 };
2733 SerializationInvalidator::new(task_id)
2734 })
2735}
2736
2737pub fn mark_invalidator() {
2738 CURRENT_TASK_STATE.with(|cell| {
2739 let CurrentTaskState {
2740 has_invalidator, ..
2741 } = &mut *cell.write().unwrap();
2742 *has_invalidator = true;
2743 })
2744}
2745
2746pub fn mark_stateful() {
2752 #[cfg(feature = "verify_determinism")]
2753 {
2754 CURRENT_TASK_STATE.with(|cell| {
2755 let CurrentTaskState { stateful, .. } = &mut *cell.write().unwrap();
2756 *stateful = true;
2757 })
2758 }
2759 }
2761
2762pub fn mark_top_level_task() {
2766 if cfg!(debug_assertions) {
2767 CURRENT_TASK_STATE.with(|cell| {
2768 cell.write().unwrap().in_top_level_task = true;
2769 })
2770 }
2771}
2772
2773pub fn unmark_top_level_task_may_leak_eventually_consistent_state() {
2784 if cfg!(debug_assertions) {
2785 CURRENT_TASK_STATE.with(|cell| {
2786 cell.write().unwrap().in_top_level_task = false;
2787 })
2788 }
2789}
2790
2791pub fn prevent_gc() {
2799 if let Some(task) = current_task_if_available("prevent_gc") {
2800 with_turbo_tasks(|tt| tt.pin_task_for_gc(task));
2801 }
2802}
2803
2804pub struct GcRoot<T: ?Sized> {
2806 tt: Arc<dyn TurboTasksApi>,
2807 vc: OperationVc<T>,
2808}
2809
2810impl<T: ?Sized> GcRoot<T> {
2811 pub fn pin(tt: Arc<dyn TurboTasksApi>, vc: OperationVc<T>) -> Self {
2813 tt.pin_task_for_gc(vc.task_id());
2814 Self { tt, vc }
2815 }
2816}
2817
2818impl<T: ?Sized> Deref for GcRoot<T> {
2821 type Target = OperationVc<T>;
2822
2823 fn deref(&self) -> &Self::Target {
2824 &self.vc
2825 }
2826}
2827
2828impl<T: ?Sized> Clone for GcRoot<T> {
2829 fn clone(&self) -> Self {
2830 Self::pin(self.tt.clone(), self.vc)
2831 }
2832}
2833
2834impl<T: ?Sized> Drop for GcRoot<T> {
2835 fn drop(&mut self) {
2836 self.tt.unpin_task_for_gc(self.vc.task_id());
2837 }
2838}
2839
2840impl<T: ?Sized> Debug for GcRoot<T> {
2841 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2842 f.debug_struct("GcRoot").field("vc", &self.vc).finish()
2843 }
2844}
2845
2846impl<T: ?Sized> PartialEq for GcRoot<T> {
2847 fn eq(&self, other: &Self) -> bool {
2850 self.vc == other.vc
2851 }
2852}
2853
2854impl<T: ?Sized> Eq for GcRoot<T> {}
2855
2856impl<T: ?Sized> Hash for GcRoot<T> {
2857 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2860 self.vc.hash(state);
2861 }
2862}
2863
2864impl<T: ?Sized> Borrow<OperationVc<T>> for GcRoot<T> {
2868 fn borrow(&self) -> &OperationVc<T> {
2869 &self.vc
2870 }
2871}
2872
2873unsafe impl<T: ?Sized + Send> OperationValue for GcRoot<T> {}
2876
2877unsafe impl<T: NonLocalValue + ?Sized> NonLocalValue for GcRoot<T> {}
2880
2881pub fn emit<T: VcValueTrait + ?Sized>(collectible: ResolvedVc<T>) {
2882 with_turbo_tasks(|tt| {
2883 let raw_vc = collectible.node.node;
2884 tt.emit_collectible(T::get_trait_type_id(), raw_vc)
2885 })
2886}
2887
2888pub(crate) async fn read_task_output(
2889 this: &dyn TurboTasksApi,
2890 id: TaskId,
2891 options: ReadOutputOptions,
2892) -> Result<RawVc> {
2893 loop {
2894 match this.try_read_task_output(id, options)? {
2895 ReadOutcome::Value(result) => return Ok(result),
2896 ReadOutcome::Scheduled(listener) => {
2897 if execute_read_target_inline(this, ScheduleKey::Task(id)) {
2899 continue;
2900 }
2901 listener.await
2902 }
2903 ReadOutcome::InProgress(listener) => {
2904 #[cfg(feature = "inline_execution_stats")]
2906 this.note_waited_for_in_progress_task();
2907 listener.await
2908 }
2909 }
2910 }
2911}
2912
2913#[derive(Clone, Copy)]
2919pub struct CurrentCellRef {
2920 current_task: TaskId,
2921 index: CellId,
2922}
2923
2924type VcReadTarget<T> = <<T as VcValueType>::Read as VcRead<T>>::Target;
2925
2926type CellUpdate = (
2929 SharedReference,
2930 Option<SmallVec<[u64; 2]>>,
2931 Option<CellHash>,
2932);
2933
2934type CellUpdateFn<'l> = dyn FnMut(Option<&SharedReference>) -> Option<CellUpdate> + 'l;
2937
2938impl CurrentCellRef {
2939 fn conditional_update<T>(
2941 &self,
2942 functor: impl FnOnce(Option<&T>) -> Option<(T, Option<SmallVec<[u64; 2]>>, Option<CellHash>)>,
2943 ) where
2944 T: VcValueType,
2945 {
2946 let mut functor = Some(functor);
2949 self.conditional_update_with_shared_reference(&mut |old_shared_reference| {
2950 let functor = functor.take().expect("functor is called at most once");
2951 let old_ref = old_shared_reference.and_then(|sr| sr.0.downcast_ref::<T>());
2952 let (new_value, updated_key_hashes, content_hash) = functor(old_ref)?;
2953 Some((
2954 SharedReference::new(triomphe::Arc::new(new_value)),
2955 updated_key_hashes,
2956 content_hash,
2957 ))
2958 })
2959 }
2960
2961 fn conditional_update_with_shared_reference(&self, functor: &mut CellUpdateFn<'_>) {
2968 let tt = turbo_tasks();
2969 let cell_content = tt.read_own_task_cell(self.current_task, self.index).ok();
2970 let update = functor(cell_content.as_ref().and_then(|cc| cc.1.0.as_ref()));
2971 if let Some((update, updated_key_hashes, content_hash)) = update {
2972 tt.update_own_task_cell(
2973 self.current_task,
2974 self.index,
2975 CellContent(Some(update)),
2976 updated_key_hashes,
2977 content_hash,
2978 VerificationMode::EqualityCheck,
2979 )
2980 }
2981 }
2982
2983 pub fn compare_and_update<T>(&self, new_value: T)
3018 where
3019 T: PartialEq + VcValueType,
3020 {
3021 self.conditional_update(|old_value| {
3022 if let Some(old_value) = old_value
3023 && old_value == &new_value
3024 {
3025 return None;
3026 }
3027 Some((new_value, None, None))
3028 });
3029 }
3030
3031 pub fn compare_and_update_with_shared_reference<T>(&self, new_shared_reference: SharedReference)
3039 where
3040 T: VcValueType + PartialEq,
3041 {
3042 let mut new_shared_reference = Some(new_shared_reference);
3043 self.conditional_update_with_shared_reference(&mut |old_sr| {
3044 let new_shared_reference = new_shared_reference
3045 .take()
3046 .expect("functor is called at most once");
3047 if let Some(old_sr) = old_sr {
3048 let old_value = extract_sr_value::<T>(old_sr);
3049 let new_value = extract_sr_value::<T>(&new_shared_reference);
3050 if old_value == new_value {
3051 return None;
3052 }
3053 }
3054 Some((new_shared_reference, None, None))
3055 });
3056 }
3057
3058 pub fn hashed_compare_and_update<T>(&self, new_value: T)
3067 where
3068 T: PartialEq + DeterministicHash + VcValueType,
3069 {
3070 self.conditional_update(|old_value| {
3071 if let Some(old_value) = old_value
3072 && old_value == &new_value
3073 {
3074 return None;
3075 }
3076 let content_hash = hash_xxh3_hash128(&new_value).to_le_bytes();
3077
3078 Some((new_value, None, Some(content_hash)))
3079 });
3080 }
3081
3082 pub fn hashed_compare_and_update_with_shared_reference<T>(
3088 &self,
3089 new_shared_reference: SharedReference,
3090 ) where
3091 T: VcValueType + PartialEq + DeterministicHash,
3092 {
3093 let mut new_shared_reference = Some(new_shared_reference);
3094 self.conditional_update_with_shared_reference(&mut move |old_sr| {
3095 let new_shared_reference = new_shared_reference
3096 .take()
3097 .expect("functor is called at most once");
3098 if let Some(old_sr) = old_sr {
3099 let old_value = extract_sr_value::<T>(old_sr);
3100 let new_value = extract_sr_value::<T>(&new_shared_reference);
3101 if old_value == new_value {
3102 return None;
3103 }
3104 }
3105 let content_hash =
3106 hash_xxh3_hash128(extract_sr_value::<T>(&new_shared_reference)).to_le_bytes();
3107 Some((new_shared_reference, None, Some(content_hash)))
3108 });
3109 }
3110
3111 pub fn keyed_compare_and_update<T>(&self, new_value: T)
3113 where
3114 T: PartialEq + VcValueType,
3115 VcReadTarget<T>: KeyedEq,
3116 {
3117 self.conditional_update(|old_value| {
3118 let Some(old_value) = old_value else {
3119 return Some((new_value, None, None));
3120 };
3121 let old_value = <T as VcValueType>::Read::value_to_target_ref(old_value);
3122 let new_value_ref = <T as VcValueType>::Read::value_to_target_ref(&new_value);
3123 let updated_keys = old_value.different_keys(new_value_ref)?;
3126 let updated_key_hashes = updated_keys
3128 .into_iter()
3129 .map(|key| FxBuildHasher.hash_one(key))
3130 .collect();
3131 Some((new_value, Some(updated_key_hashes), None))
3132 });
3133 }
3134
3135 pub fn keyed_compare_and_update_with_shared_reference<T>(
3138 &self,
3139 new_shared_reference: SharedReference,
3140 ) where
3141 T: VcValueType + PartialEq,
3142 VcReadTarget<T>: KeyedEq,
3143 {
3144 let mut new_shared_reference = Some(new_shared_reference);
3145 self.conditional_update_with_shared_reference(&mut |old_sr| {
3146 let new_shared_reference = new_shared_reference
3147 .take()
3148 .expect("functor is called at most once");
3149 let Some(old_sr) = old_sr else {
3150 return Some((new_shared_reference, None, None));
3151 };
3152 let old_value = extract_sr_value::<T>(old_sr);
3153 let old_value = <T as VcValueType>::Read::value_to_target_ref(old_value);
3154 let new_value = extract_sr_value::<T>(&new_shared_reference);
3155 let new_value = <T as VcValueType>::Read::value_to_target_ref(new_value);
3156 let updated_keys = old_value.different_keys(new_value)?;
3159 let updated_key_hashes = updated_keys
3161 .into_iter()
3162 .map(|key| FxBuildHasher.hash_one(key))
3163 .collect();
3164 Some((new_shared_reference, Some(updated_key_hashes), None))
3165 });
3166 }
3167
3168 pub fn update<T>(&self, new_value: T, verification_mode: VerificationMode)
3170 where
3171 T: VcValueType,
3172 {
3173 let tt = turbo_tasks();
3174 tt.update_own_task_cell(
3175 self.current_task,
3176 self.index,
3177 CellContent(Some(SharedReference::new(triomphe::Arc::new(new_value)))),
3178 None,
3179 None,
3180 verification_mode,
3181 )
3182 }
3183
3184 pub fn update_with_shared_reference(
3192 &self,
3193 shared_ref: SharedReference,
3194 verification_mode: VerificationMode,
3195 ) {
3196 let tt = turbo_tasks();
3197 let update = if matches!(verification_mode, VerificationMode::EqualityCheck) {
3198 let content = tt.read_own_task_cell(self.current_task, self.index).ok();
3199 if let Some(TypedCellContent(_, CellContent(Some(shared_ref_exp)))) = content {
3200 shared_ref_exp != shared_ref
3202 } else {
3203 true
3204 }
3205 } else {
3206 true
3207 };
3208 if update {
3209 tt.update_own_task_cell(
3210 self.current_task,
3211 self.index,
3212 CellContent(Some(shared_ref)),
3213 None,
3214 None,
3215 verification_mode,
3216 )
3217 }
3218 }
3219}
3220
3221impl From<CurrentCellRef> for RawVc {
3222 fn from(cell: CurrentCellRef) -> Self {
3223 RawVc::task_cell(cell.current_task, cell.index)
3224 }
3225}
3226
3227fn extract_sr_value<T: VcValueType>(sr: &SharedReference) -> &T {
3228 sr.0.downcast_ref::<T>()
3229 .expect("cannot update SharedReference of different type")
3230}
3231
3232pub fn find_cell_by_type<T: VcValueType>() -> CurrentCellRef {
3233 find_cell_by_id(T::get_value_type_id())
3234}
3235
3236pub fn find_cell_by_id(ty: ValueTypeId) -> CurrentCellRef {
3237 CURRENT_TASK_STATE.with(|ts| {
3238 let current_task = current_task("celling turbo_tasks values");
3239 let mut ts = ts.write().unwrap();
3240 let map = ts.cell_counters.as_mut().unwrap();
3241 let current_index = map.entry(ty).or_default();
3242 let index = *current_index;
3243 assert!(
3244 index <= CellId::MAX_CELL_INDEX,
3245 "task allocated more than {} cells of a single type",
3246 CellId::MAX_CELL_INDEX as u64 + 1,
3247 );
3248 *current_index += 1;
3249 CurrentCellRef {
3250 current_task,
3251 index: CellId::new(ty, index),
3252 }
3253 })
3254}
3255
3256pub(crate) async fn read_local_output(
3257 this: &dyn TurboTasksApi,
3258 execution_id: ExecutionId,
3259 local_task_id: LocalTaskId,
3260) -> Result<RawVc> {
3261 loop {
3262 match this.try_read_local_output(execution_id, local_task_id)? {
3263 Ok(raw_vc) => return Ok(raw_vc),
3264 Err(event_listener) => {
3265 if execute_read_target_inline(
3268 this,
3269 ScheduleKey::current_local_task(execution_id, local_task_id),
3270 ) {
3271 continue;
3272 }
3273 event_listener.await
3274 }
3275 }
3276 }
3277}
3278
3279#[cfg(test)]
3280mod tests {
3281 use super::*;
3282
3283 #[test]
3284 fn test_abort_on_panic_message() {
3285 let unreadable: Box<dyn std::any::Any + Send> =
3286 Box::new(crate::PersistentCacheUnreadablePanic {
3287 message: "cache file 00000001.sst is missing".to_string(),
3288 });
3289 let message = abort_on_panic_message(&*unreadable);
3290 assert!(message.contains("could not be read"), "{message}");
3291 assert!(
3292 message.contains("cache file 00000001.sst is missing"),
3293 "{message}"
3294 );
3295 assert!(!message.contains("report"), "{message}");
3296 assert!(!message.contains("bug"), "{message}");
3297
3298 let other: Box<dyn std::any::Any + Send> = Box::new("some bug".to_string());
3299 let message = abort_on_panic_message(&*other);
3300 assert!(message.contains("please report it"), "{message}");
3301 }
3302
3303 #[test]
3304 fn test_inline_execution_depth_guard_restores_depth() {
3305 assert_eq!(INLINE_EXECUTION_DEPTH.get(), 0);
3306 {
3307 let _outer = InlineExecutionDepthGuard::enter();
3308 {
3309 let _inner = InlineExecutionDepthGuard::enter();
3310 assert_eq!(INLINE_EXECUTION_DEPTH.get(), 2);
3311 }
3312 assert_eq!(INLINE_EXECUTION_DEPTH.get(), 1);
3313 }
3314 assert_eq!(INLINE_EXECUTION_DEPTH.get(), 0);
3315 }
3316
3317 #[test]
3318 fn test_inline_depth_cap() {
3319 assert!(inline_execution_allowed(), "nothing is nested yet");
3320 let mut guards = (0..MAX_INLINE_EXECUTION_DEPTH)
3321 .map(|_| InlineExecutionDepthGuard::enter())
3322 .collect::<Vec<_>>();
3323 assert_eq!(INLINE_EXECUTION_DEPTH.get(), MAX_INLINE_EXECUTION_DEPTH);
3324 assert!(
3325 !inline_execution_allowed(),
3326 "at the nesting cap reads wait for a worker instead of executing inline"
3327 );
3328
3329 guards.pop();
3331 assert!(inline_execution_allowed());
3332 }
3333
3334 #[tokio::test]
3335 async fn test_poll_once_or_spawn_completed_execution() {
3336 assert!(
3337 poll_once_or_spawn(async {}),
3338 "a future that completes on the first poll is executed inline"
3339 );
3340 assert_eq!(INLINE_EXECUTION_DEPTH.get(), 0);
3341 }
3342
3343 #[tokio::test]
3344 async fn test_poll_once_or_spawn_pending_execution() {
3345 let (tx, rx) = tokio::sync::oneshot::channel();
3346 let done = Arc::new(AtomicBool::new(false));
3347 let done_in_task = done.clone();
3348 assert!(
3349 !poll_once_or_spawn(async move {
3350 tokio::task::yield_now().await;
3352 done_in_task.store(true, Ordering::SeqCst);
3353 let _ = tx.send(());
3354 }),
3355 "a future that yields is not completed inline"
3356 );
3357 assert_eq!(INLINE_EXECUTION_DEPTH.get(), 0);
3358
3359 rx.await.unwrap();
3361 assert!(done.load(Ordering::SeqCst));
3362 }
3363
3364 #[tokio::test]
3365 async fn test_wait_until_zero_returns_immediately_at_zero() {
3366 let counter = AtomicUsize::new(0);
3367 let event = Event::new(|| || "test event".to_string());
3368 let wait = std::pin::pin!(wait_until_zero(&counter, &event, || || "test".to_string()));
3369 assert!(futures::poll!(wait).is_ready());
3370 }
3371
3372 #[tokio::test]
3376 async fn test_wait_until_zero_ignores_stale_notification() {
3377 let counter = AtomicUsize::new(1);
3378 let event = Event::new(|| || "test event".to_string());
3379 let mut wait = std::pin::pin!(wait_until_zero(&counter, &event, || || "test".to_string()));
3380 assert!(futures::poll!(wait.as_mut()).is_pending());
3381
3382 event.notify(usize::MAX);
3384 assert!(
3385 futures::poll!(wait.as_mut()).is_pending(),
3386 "a notification must not end the wait while the counter is non-zero"
3387 );
3388
3389 counter.store(0, Ordering::Release);
3391 event.notify(usize::MAX);
3392 assert!(futures::poll!(wait.as_mut()).is_ready());
3393 }
3394}