Skip to main content

turbo_tasks/
manager.rs

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
58/// Common base trait for [`TurboTasksApi`] and [`TurboTasks`]. Provides APIs for creating tasks
59/// from function calls.
60pub trait TurboTasksCallApi: Sync + Send {
61    /// Calls a native function with arguments. Resolves arguments when needed
62    /// with a wrapper task.
63    ///
64    /// `inputs_resolved` is `TaskInput::is_resolved(&args)` computed at the macro callsite on
65    /// the concrete tuple type — when [`InputResolution::Resolved`], the fast path skips wrapper
66    /// task creation.
67    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    /// Call a native function with arguments.
76    /// All inputs must be resolved.
77    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    /// Calls a trait method with arguments. First input is the `self` object.
85    /// Uses a wrapper task to resolve.
86    ///
87    /// `inputs_resolved` is the macro-site `InputResolution` of the *exposed* tuple; when filtering
88    /// is involved, the post-filter value is computed inside the filter functor and supersedes
89    /// this argument.
90    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    /// Sends a compilation event to subscribers.
115    fn send_compilation_event(&self, event: Arc<dyn CompilationEvent>);
116
117    /// Returns a human-readable name for the given task.
118    fn get_task_name(&self, task: TaskId) -> String;
119}
120
121/// A type-erased subset of [`TurboTasks`] stored inside a thread local when we're in a turbo task
122/// context. Returned by the [`turbo_tasks`] helper function.
123///
124/// This trait is needed because thread locals cannot contain an unresolved [`Backend`] type
125/// parameter.
126pub trait TurboTasksApi: TurboTasksCallApi + Sync + Send {
127    fn invalidate(&self, task: TaskId);
128    fn invalidate_with_reason(&self, task: TaskId, reason: StaticOrArc<dyn InvalidationReason>);
129    /// Invalidates all `tasks` as one batch. `tasks` must not contain duplicates. The backend may
130    /// split large batches into chunks that are invalidated in parallel.
131    fn invalidate_many(&self, tasks: &[TaskId]);
132    /// Like [`TurboTasksApi::invalidate_many`], recording all `reasons` once for the whole batch.
133    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    /// Refines the [`CellKeyKind::Provisional(id)`][CellKeyKind::Provisional] dependency of the
155    /// current task (`reader`) on the cell `index` of `task` to [`CellKeyKind::Hash`] dependencies
156    /// on each of the `key_hashes`. See [`Backend::refine_provisional_cell_dependency`].
157    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    /// Reads a [`RawVcUnpacked::LocalOutput`][crate::RawVcUnpacked::LocalOutput]. If the task has
167    /// completed, returns the [`RawVc`] the local task points to.
168    ///
169    /// The returned [`RawVc`] may also unpack to a
170    /// [`RawVcUnpacked::LocalOutput`][crate::RawVcUnpacked::LocalOutput], so this may need to be
171    /// called recursively or in a loop.
172    ///
173    /// This does not accept a consistency argument, as you cannot control consistency of a read of
174    /// an operation owned by your own task. Strongly consistent reads are only allowed on
175    /// [`OperationVc`]s, which should never be local tasks.
176    ///
177    /// No dependency tracking will happen as a result of this function call, as it's a no-op for a
178    /// task to depend on itself.
179    ///
180    /// [`OperationVc`]: crate::OperationVc
181    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    /// Executes a task that is scheduled but not started yet inline on the current thread, so that
190    /// a read doesn't have to wait for a worker to pick the task up. Returns whether the task's
191    /// execution completed.
192    ///
193    /// Used by the read paths; see `TurboTasks::try_execute_scheduled_task_inline` for the details.
194    fn try_execute_scheduled_task_inline(&self, key: ScheduleKey) -> bool;
195
196    /// Records that a read waited for a task that a worker was already executing, so it did not try
197    /// to claim it. Diagnostics only, see `TurboTasks::inline_execution_stats`.
198    #[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    /// INVALIDATION: Be careful with this, it will not track dependencies, so
206    /// using it could break cache invalidation.
207    fn try_read_own_task_cell(
208        &self,
209        current_task: TaskId,
210        index: CellId,
211    ) -> Result<TypedCellContent>;
212
213    /// See [`Backend::drop_task_cell_content_hint`].
214    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    /// Pin a task against garbage collection. Delegates to
229    /// [`Backend::pin_task_for_gc`].
230    fn pin_task_for_gc(&self, task: TaskId);
231
232    /// Removes a pin added by [`pin_task_for_gc`](TurboTasksApi::pin_task_for_gc).
233    fn unpin_task_for_gc(&self, task: TaskId);
234
235    fn connect_task(&self, task: TaskId);
236
237    /// Wraps the given future in the current task.
238    ///
239    /// Beware: this method is not safe to use in production code. It is only intended for use in
240    /// tests and for debugging purposes.
241    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    // Returns true if TurboTasks is configured to track dependencies.
253    fn is_tracking_dependencies(&self) -> bool;
254}
255
256/// A wrapper around a value that is unused.
257pub struct Unused<T> {
258    inner: T,
259}
260
261impl<T> Unused<T> {
262    /// Creates a new unused value.
263    ///
264    /// # Safety
265    ///
266    /// The wrapped value must not be used.
267    pub unsafe fn new_unchecked(inner: T) -> Self {
268        Self { inner }
269    }
270
271    /// Get the inner value, without consuming the `Unused` wrapper.
272    ///
273    /// # Safety
274    ///
275    /// The user need to make sure that the value stays unused.
276    pub unsafe fn get_unchecked(&self) -> &T {
277        &self.inner
278    }
279
280    /// Unwraps the value, consuming the `Unused` wrapper.
281    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    /// Tasks that may be persisted across sessions using serialization.
298    Persistent,
299
300    /// Tasks that will be persisted in memory for the life of this session, but won't persist
301    /// between sessions.
302    ///
303    /// This is used for [root tasks][TurboTasks::spawn_root_task] and tasks with an argument of
304    /// type [`TransientValue`][crate::value::TransientValue] or
305    /// [`TransientInstance`][crate::value::TransientInstance].
306    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/// Whether a task call's inputs are already resolved, decided on the concrete input tuple at the
319/// call site. Travels alongside [`TaskPersistence`] through [`dynamic_call`] / [`trait_call`].
320#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
321pub enum InputResolution {
322    /// All inputs (and `this`, where applicable) are resolved — eligible for the synchronous fast
323    /// path with no async resolution task.
324    Resolved,
325    /// At least one input is unresolved and must be resolved in a local task first.
326    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    /// The default behavior for most APIs. Reads are faster, but may return stale values, which
348    /// may later trigger re-computation.
349    #[default]
350    Eventual,
351    /// Ensures all dependencies are fully resolved before returning the cell or output data, at
352    /// the cost of slower reads.
353    ///
354    /// Top-level code that returns data to the user should use strongly consistent reads.
355    Strong,
356}
357
358/// Identifies the part of a cell a tracked cell read depends on, when it doesn't depend on the
359/// whole cell content (which is represented by `None` in an `Option<CellKey>`).
360///
361/// One of the [`CellKeyKind`]s, packed into a single word: the top bit tells them apart, so a key
362/// hash keeps 63 bits. Keyed dependencies are stored per dependent and per dependency, so this
363/// halves their key from the 16 bytes an enum of a `u64` and a `u32` would take. Always build
364/// keys with [`CellKey::hash`] and [`CellKey::provisional`] so equal keys compare equal.
365#[derive(Clone, Copy, Eq, PartialEq, Hash, Encode, Decode)]
366#[repr(transparent)]
367pub struct CellKey(#[bincode(fixint)] u64);
368
369/// The unpacked form of a [`CellKey`].
370#[derive(Clone, Copy, Debug, Eq, PartialEq)]
371pub enum CellKeyKind {
372    /// The read only depends on the sub-value identified by this key hash (see
373    /// [`KeyedEq`]). The dependency is only invalidated when the value of this key changes.
374    ///
375    /// Only the low 63 bits of the hash are kept.
376    Hash(u64),
377    /// A provisional dependency of a [`Vc::keyed_reader`](crate::Vc::keyed_reader) or
378    /// [`Vc::lazy_reader`](crate::Vc::lazy_reader) read: a temporary hold on the whole cell that
379    /// is refined later. For invalidation it behaves like a dependency on the whole cell
380    /// (invalidated by any change of the cell), but it is a separate dependency that is uniquely
381    /// identified by this counter of `keyed_reader()` / `lazy_reader()` calls within the current
382    /// task execution. This allows the [`KeyedReadRef`](crate::KeyedReadRef) to refine it to
383    /// [`CellKeyKind::Hash`] dependencies of the accessed keys once it's dropped, and the
384    /// [`LazyReadRef`](crate::LazyReadRef) to remove it when the value wasn't accessed, without
385    /// affecting other dependencies on the same cell. `Provisional` dependencies that are still
386    /// present when the execution completes are converted to normal (full) dependencies, so they
387    /// never outlive the execution that created them. (When that's because a ref or future wasn't
388    /// dropped within the execution, completing the execution also panics.)
389    Provisional(u32),
390}
391
392impl CellKey {
393    const PROVISIONAL: u64 = 1 << 63;
394
395    /// A dependency on the sub-value whose key hashes to `hash`, see [`CellKeyKind::Hash`]. The
396    /// top bit of `hash` is dropped.
397    pub const fn hash(hash: u64) -> Self {
398        Self(hash & !Self::PROVISIONAL)
399    }
400
401    /// The provisional dependency with the given id, see [`CellKeyKind::Provisional`].
402    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        // A hash with the top bit set is still a hash, without that bit.
438        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    /// Reads are tracked as dependencies of the current task.
470    Tracked {
471        /// The part of the cell the dependency is on. `None` depends on the whole cell.
472        key: Option<CellKey>,
473    },
474    /// The read is only tracked when there is an error, otherwise it is untracked.
475    ///
476    /// INVALIDATION: Be careful with this, it will not track dependencies, so
477    /// using it could break cache invalidation.
478    TrackOnlyError,
479    /// The read is not tracked as a dependency of the current task.
480    ///
481    /// INVALIDATION: Be careful with this, it will not track dependencies, so
482    /// using it could break cache invalidation.
483    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    /// Reads are tracked as dependencies of the current task.
527    #[default]
528    Tracked,
529    /// The read is only tracked when there is an error, otherwise it is untracked.
530    ///
531    /// INVALIDATION: Be careful with this, it will not track dependencies, so
532    /// using it could break cache invalidation.
533    TrackOnlyError,
534    /// The read is not tracked as a dependency of the current task.
535    ///
536    /// INVALIDATION: Be careful with this, it will not track dependencies, so
537    /// using it could break cache invalidation.
538    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        /// The non-local task whose execution created this local task (`None` for a top-level
628        /// execution), see [`ScheduleKey::LocalTask`].
629        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/// Identifies a scheduled task, so that a read which is about to wait for it can take it out of the
638/// scheduler queue and execute it inline instead (see `PriorityRunner::claim` and
639/// `execute_read_target_inline`).
640#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
641pub enum ScheduleKey {
642    /// A cached (non-local) task.
643    Task(TaskId),
644    /// A local task, which is only known within the execution that created it: the non-local task
645    /// of that execution (`None` for a top-level execution, e.g. [`TurboTasks::run`]), the
646    /// execution and the local task id within it.
647    ///
648    /// `ExecutionId` alone isn't unique across concurrent executions (it wraps), but a non-local
649    /// task only has one execution at a time, and that execution waits for its local tasks. So the
650    /// key is unique, except for two concurrent top-level executions that share a wrapped
651    /// `ExecutionId`.
652    LocalTask(Option<TaskId>, ExecutionId, LocalTaskId),
653}
654
655impl ScheduleKey {
656    /// The key of a local task created by the current execution.
657    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/// Counters describing how reads and inline execution interacted, see
686/// [`TurboTasks::inline_execution_stats`]. Diagnostics only.
687#[cfg(feature = "inline_execution_stats")]
688#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
689pub struct InlineExecutionStats {
690    /// Tasks that were put into the scheduler queue.
691    pub queued: u64,
692    /// Reads that tried to take a queued task out of the queue.
693    pub claim_attempted: u64,
694    /// Claims that succeeded and whose execution finished on the reading thread.
695    pub claim_completed: u64,
696    /// Claims that succeeded but whose execution yielded, so it was handed to the runtime.
697    pub claim_yielded: u64,
698    /// Claims that found nothing to take, because a worker had already picked the task up.
699    pub claim_failed: u64,
700    /// Reads that waited without attempting a claim, because the task was already being executed.
701    pub waited_in_progress: u64,
702}
703
704/// The counters behind `InlineExecutionStats`.
705///
706/// Without the `inline_execution_stats` feature this is zero-sized and every method is an empty
707/// `#[inline]` no-op, so the counting compiles away: the counters sit on the read-miss path, and a
708/// build that doesn't want the numbers shouldn't pay for them.
709#[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    /// A read found its task queued and tried to take it over.
725    #[inline]
726    fn claim_attempted(&self) {
727        #[cfg(feature = "inline_execution_stats")]
728        self.claim_attempted.fetch_add(1, Ordering::Relaxed);
729    }
730
731    /// A claim succeeded and the execution finished on the reading thread.
732    #[inline]
733    fn claim_completed(&self) {
734        #[cfg(feature = "inline_execution_stats")]
735        self.claim_completed.fetch_add(1, Ordering::Relaxed);
736    }
737
738    /// A claim succeeded but the execution yielded, so it was handed to the runtime.
739    #[inline]
740    fn claim_yielded(&self) {
741        #[cfg(feature = "inline_execution_stats")]
742        self.claim_yielded.fetch_add(1, Ordering::Relaxed);
743    }
744
745    /// A claim found nothing to take, because a worker had already picked the task up.
746    #[inline]
747    fn claim_failed(&self) {
748        #[cfg(feature = "inline_execution_stats")]
749        self.claim_failed.fetch_add(1, Ordering::Relaxed);
750    }
751
752    /// A read waited without attempting a claim, because the task was already being executed.
753    #[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/// Whether a dump of [`InlineExecutionStats`] was requested via `TURBO_ENGINE_INLINE_STATS=1`.
761#[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
769/// Maximum number of task executions that may be nested inline on a single thread, to conserve
770/// stack space. (The alternative would be growing the stack on demand, the way SWC does.)
771const MAX_INLINE_EXECUTION_DEPTH: usize = 16;
772
773thread_local! {
774    /// How many task executions are currently nested inline on this thread.
775    static INLINE_EXECUTION_DEPTH: Cell<usize> = const { Cell::new(0) };
776}
777
778/// Whether the current thread may execute another task inline, see [`MAX_INLINE_EXECUTION_DEPTH`].
779fn inline_execution_allowed() -> bool {
780    INLINE_EXECUTION_DEPTH.get() < MAX_INLINE_EXECUTION_DEPTH
781}
782
783/// Counts one level of inline task execution on this thread, see [`MAX_INLINE_EXECUTION_DEPTH`].
784struct 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
799/// Waits until `counter` reads 0. `event` must be notified every time `counter` drops to 0.
800///
801/// A wake-up alone doesn't prove that the counter is still 0: `finish_foreground_job` and
802/// `finish_background_job` decrement the counter before they notify, so the notification for an
803/// earlier drop to 0 can arrive after new jobs began. So the counter is re-checked after every
804/// wake-up, with a listener registered before the check so no notification is missed.
805async 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
815/// Polls `future` once inline and then spawns it if it doesn't complete so tokio drives it. Returns
816/// whether it completed.
817fn 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    // A waker that never wakes anything is fine here: if this poll doesn't complete the future we
822    // spawn it, and a spawned task is always polled at least once, which is the poll that registers
823    // the real waker.
824    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
840/// Executes the task inline if possible, returns true if it executed to completion.
841pub(crate) fn execute_read_target_inline(
842    turbo_tasks: &dyn TurboTasksApi,
843    key: ScheduleKey,
844) -> bool {
845    if !inline_execution_allowed() {
846        // Nested too deeply; a worker will pick the task up, as it always did.
847        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    /// Diagnostics for reads and inline execution, see `TurboTasks::inline_execution_stats`.
861    /// Zero-sized without the `inline_execution_stats` feature.
862    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 that is triggered when currently_scheduled_foreground_jobs becomes non-zero
868    event_foreground_start: Event,
869    /// Event that is triggered when all foreground jobs are done
870    /// (currently_scheduled_foreground_jobs becomes zero)
871    event_foreground_done: Event,
872    /// Event that is triggered when all background jobs are done
873    event_background_done: Event,
874    compilation_events: CompilationEventQueue,
875}
876
877/// Information about a non-local task. A non-local task can contain multiple "local" tasks, which
878/// all share the same non-local task state.
879///
880/// A non-local task is one that:
881///
882/// - Has a unique task id.
883/// - Is potentially cached.
884/// - The backend is aware of.
885struct CurrentTaskState {
886    task_id: Option<TaskId>,
887    execution_id: ExecutionId,
888    priority: TaskPriority,
889
890    /// True if the current task has state in cells (interior mutability).
891    /// Only tracked when verify_determinism feature is enabled.
892    #[cfg(feature = "verify_determinism")]
893    stateful: bool,
894
895    /// True if the current task uses an external invalidator
896    has_invalidator: bool,
897
898    /// True if we're in a top-level task (e.g. `.run_once(...)` or `.run(...)`).
899    /// Eventually consistent reads are not allowed in top-level tasks.
900    in_top_level_task: bool,
901
902    /// Tracks how many cells of each type has been allocated so far during this task execution.
903    /// When a task is re-executed, the cell count may not match the existing cell vec length.
904    ///
905    /// This is taken (and becomes `None`) during teardown of a task.
906    cell_counters: Option<AutoMap<ValueTypeId, u32, BuildHasherDefault<FxHasher>, 8>>,
907
908    /// Tracks execution of Local tasks (and detached test futures) created during this global
909    /// task's execution.
910    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/// A shareable current-task state handle with the immutable task ID cached
962/// outside the lock. The rest of the state is mutated by global and local
963/// tasks, but the task ID is fixed for the lifetime of an execution.
964#[derive(Clone)]
965struct CurrentTaskStateHandle {
966    inner: Arc<CurrentTaskStateInner>,
967}
968
969struct CurrentTaskStateInner {
970    current_task_id: Option<TaskId>,
971    /// Counter of [`Vc::keyed_reader`](crate::Vc::keyed_reader) and
972    /// [`Vc::lazy_reader`](crate::Vc::lazy_reader) reads in this execution, used to give every
973    /// [`CellKeyKind::Provisional`] dependency a unique id.
974    provisional_read_counter: AtomicU32,
975    /// Number of `keyed_reader` / `lazy_reader` futures and tracked
976    /// [`KeyedReadRef`](crate::KeyedReadRef)s / [`LazyReadRef`](crate::LazyReadRef)s of this
977    /// execution that haven't been dropped within this execution yet. When it isn't zero at the
978    /// end of the execution, completing it panics (see [`PROVISIONAL_READ_REF_LEAKED`]).
979    alive_provisional_read_refs: AtomicU32,
980    /// An error a drop of a [`KeyedReadRef`](crate::KeyedReadRef) /
981    /// [`LazyReadRef`](crate::LazyReadRef) of this execution ran into (see
982    /// [`ProvisionalReadDependency::fail_execution`]). A drop can't return it, so the execution
983    /// fails with it when it completes.
984    deferred_error: Mutex<Option<anyhow::Error>>,
985    state: RwLock<CurrentTaskState>,
986}
987
988/// The panic message of a task execution that didn't drop all of its
989/// [`KeyedReadRef`](crate::KeyedReadRef)s, [`LazyReadRef`](crate::LazyReadRef)s and
990/// [`Vc::keyed_reader`](crate::Vc::keyed_reader) / [`Vc::lazy_reader`](crate::Vc::lazy_reader)
991/// futures.
992const 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
1015/// Identifies the [`CellKeyKind::Provisional`] dependency of a
1016/// [`Vc::keyed_reader`](crate::Vc::keyed_reader) or [`Vc::lazy_reader`](crate::Vc::lazy_reader)
1017/// read and the task execution that created it.
1018pub(crate) struct ProvisionalReadDependency {
1019    /// The execution state of the reading task. Only used for identity (a `Weak` keeps the
1020    /// allocation alive, so the pointer can't be reused by another execution).
1021    execution: Weak<CurrentTaskStateInner>,
1022    pub(crate) reader: TaskId,
1023    pub(crate) id: u32,
1024}
1025
1026impl ProvisionalReadDependency {
1027    /// Allocates a new [`CellKeyKind::Provisional`] dependency id for the current task execution.
1028    /// Returns `None` when not called from within a task execution (e.g. a top-level `run`),
1029    /// where reads are not tracked anyway. In that case the read is tracked as a normal (full)
1030    /// dependency.
1031    ///
1032    /// Panics when the `u32` ids of this execution are exhausted, which isn't possible in
1033    /// practice.
1034    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    /// Registers a `keyed_reader` / `lazy_reader` future or a
1056    /// [`KeyedReadRef`](crate::KeyedReadRef) / [`LazyReadRef`](crate::LazyReadRef) holding this
1057    /// dependency as alive. It must be released with
1058    /// [`ProvisionalReadDependency::release_alive_ref`] within the same task execution, otherwise
1059    /// completing the execution panics. Only called within the creating execution.
1060    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    /// Fails the creating execution with `error` when it completes, unless it fails anyway. For
1069    /// errors of a [`KeyedReadRef`](crate::KeyedReadRef) / [`LazyReadRef`](crate::LazyReadRef)
1070    /// drop, which can't return them. Only called within the creating execution. The first error
1071    /// is kept.
1072    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    /// Releases a registration made with [`ProvisionalReadDependency::register_alive_ref`]. Only
1083    /// called when the holder is dropped (or the read fails) within the creating execution
1084    /// ([`ProvisionalReadDependency::is_current_execution`]).
1085    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    /// Whether this is called within the task execution that created the dependency and that
1094    /// execution is still running (it hasn't reported completion to the backend yet).
1095    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
1113// TODO implement our own thread pool and make these thread locals instead
1114task_local! {
1115    /// The current TurboTasks instance
1116    static TURBO_TASKS: Arc<dyn TurboTasksApi>;
1117
1118    static CURRENT_TASK_STATE: CurrentTaskStateHandle;
1119
1120    /// Temporarily suppresses the eventual consistency check in top-level tasks.
1121    /// This is used by strongly consistent reads to allow them to succeed in top-level tasks.
1122    /// This is NOT shared across local tasks (unlike CURRENT_TASK_STATE), so it's safe
1123    /// to set/unset without race conditions.
1124    pub(crate) static SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK: bool;
1125
1126    /// Set only while a reader polls a task it claimed, so that the outcome of that poll can be
1127    /// recorded on the *task's* span rather than the reader's, see [`InlineExecutionSpanSlot`].
1128    static INLINE_EXECUTION_SPAN: InlineExecutionSpanSlot;
1129}
1130
1131/// Lets a reader that executes a claimed task inline record the outcome on the span of the task it
1132/// executed.
1133///
1134/// The reader only sees the outer execution future, whose instrumented span has already been exited
1135/// by the time its `poll` returns — `Span::current()` there is the reader's own span. So the
1136/// executor puts the span it is about to instrument the task body with in here, and the reader
1137/// records the outcome on it afterwards.
1138///
1139/// Only present while a claimed task is being polled inline: a task started by a worker doesn't
1140/// have this task-local set, and leaves the field unset.
1141#[derive(Clone, Default)]
1142struct InlineExecutionSpanSlot(Arc<Mutex<Option<Span>>>);
1143
1144impl InlineExecutionSpanSlot {
1145    /// Called by the executor with the span it instruments the task body with.
1146    fn set(span: &Span) {
1147        let _ = INLINE_EXECUTION_SPAN.try_with(|slot| {
1148            *slot.0.lock().unwrap() = Some(span.clone());
1149        });
1150    }
1151
1152    /// Records the outcome of the inline poll on the executed task's span, if the executor got far
1153    /// enough to register one (it doesn't when the task was already claimed by someone else and the
1154    /// execution turns into a no-op).
1155    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    // TODO better lifetime management for turbo tasks
1164    // consider using unsafe for the task_local turbo tasks
1165    // that should be safe as long tasks can't outlife turbo task
1166    // so we probably want to make sure that all tasks are joined
1167    // when trying to drop turbo tasks
1168    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    /// Creates a new root task
1202    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    /// Pins a task against garbage collection (a transient, session-only reference). Balanced by
1228    /// [`unpin_task_for_gc`](Self::unpin_task_for_gc). Used for references that escape the tracked
1229    /// task graph — e.g. a `DetachedVc` holding an `OperationVc` across the NAPI boundary.
1230    pub fn pin_task_for_gc(&self, task_id: TaskId) {
1231        self.backend.pin_task_for_gc(task_id, self);
1232    }
1233
1234    /// Releases a pin added by [`pin_task_for_gc`](Self::pin_task_for_gc).
1235    pub fn unpin_task_for_gc(&self, task_id: TaskId) {
1236        self.backend.unpin_task_for_gc(task_id, self);
1237    }
1238
1239    // TODO make sure that all dependencies settle before reading them
1240    /// Creates a new root task, that is only executed once.
1241    /// Dependencies will not invalidate the task.
1242    #[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    /// Runs `future` as a top-level task and returns its result.
1260    ///
1261    /// # Returned values must not contain `Vc` or `ResolvedVc` or if they do they should be covered by a pin
1262    ///
1263    /// `T` is deliberately unconstrained for ergonomics, but a `Vc`/`ResolvedVc` that escapes this
1264    /// call is **not** protected against garbage collection. It can be collected, and
1265    /// dereferencing the stale handle then fails.
1266    ///    ///
1267    /// To hand a computation out of a top-level task, return the [`OperationVc`] and pin it:
1268    ///
1269    /// ```ignore
1270    /// let (resolved, op) = tt.run_once(async move {
1271    ///     let op = my_operation(args);
1272    ///     let resolved = op.resolve().strongly_consistent().await?;
1273    ///     // Return the operation too, so it can be pinned below.
1274    ///     Ok((resolved, op))
1275    /// }).await?;
1276    /// let _gc_root = GcRoot::pin(tt.clone(), op);  // unpins on drop
1277    /// ```
1278    ///
1279    /// Returning owned data -- [`ReadRef`](crate::ReadRef), `RcStr`, plain values -- is always
1280    /// fine.
1281    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    /// Runs `future` as a top-level task and returns its result.
1298    ///
1299    /// The same constraint as [`run_once`](Self::run_once) applies to `T`: a `Vc`/`ResolvedVc`
1300    /// returned from here is not anchored against garbage collection. See that method's docs for
1301    /// why, and for the pin-the-`OperationVc` idiom.
1302    #[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        // it's okay for execution ids to overflow and wrap, they're just used for an assert
1309        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, // in_top_level_task
1314        ));
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 all spawned local tasks using `local` to finish
1323                    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        // Need async resolution — must move the arg to the heap now
1381        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        // avoid creating a wrapper task if self is already resolved
1399        // for resolved cells we already know the value type so we can lookup the
1400        // function
1401        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                    // We are destined to fail at this point, but we just retry resolution in the
1420                    // local task since we cannot report an error from here.
1421                    // TODO: A panic seems appropriate since the immediate caller is to blame
1422                }
1423            }
1424        }
1425
1426        // create a wrapper task to resolve all inputs
1427        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    /// Schedules all `tasks`, like calling [`TurboTasks::schedule`] for each of them, but hands
1449    /// them to the scheduler as one batch, so its queue is locked once instead of once per task.
1450    #[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        // if this is a `LocalTaskType::Resolve*`, we may spawn another task with this persistence,
1478        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    /// Executes the task inline if possible, returns true if it executed to completion.
1509    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    /// Begins `count` foreground jobs at once. `count` must not be zero.
1535    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            // That's not super race-condition-safe, but it's only for
1556            // statistical reasons
1557            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    /// Counters describing how reads and inline execution interacted. Diagnostics only; a dump of
1593    /// these can be requested with `TURBO_ENGINE_INLINE_STATS=1`.
1594    #[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    /// Waits for the given task to finish executing. This works by performing an untracked read,
1609    /// and discarding the value of the task output.
1610    ///
1611    /// [`ReadConsistency::Eventual`] means that this will return after the task executes, but
1612    /// before all dependencies have completely settled.
1613    ///
1614    /// [`ReadConsistency::Strong`] means that this will also wait for the task and all dependencies
1615    /// to fully settle before returning.
1616    ///
1617    /// As this function is typically called in top-level code that waits for results to be ready
1618    /// for the user to access, most callers should use [`ReadConsistency::Strong`].
1619    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                // INVALIDATION: This doesn't return a value, only waits for it to be ready.
1629                tracking: ReadTracking::Untracked,
1630                consistency,
1631            },
1632        )
1633        .await?;
1634        Ok(())
1635    }
1636
1637    /// Returns [UpdateInfo] with all updates aggregated over a given duration
1638    /// (`aggregation`). Will wait until an update happens.
1639    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    /// Returns [UpdateInfo] with all updates aggregated over a given duration
1646    /// (`aggregation`): the update ends once no foreground job has been running for
1647    /// that long. Will only return None when the timeout is reached while
1648    /// waiting for the first update.
1649    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                // wait for finish
1677                listener.await;
1678            } else {
1679                // wait for start, then wait for finish or timeout
1680                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                    // Timeout
1694                    return None;
1695                }
1696            }
1697        }
1698        if !aggregation.is_zero() {
1699            loop {
1700                select! {
1701                    () = tokio::time::sleep(aggregation) => {
1702                        // Only end the update once no foreground job is running. Work that
1703                        // starts within the aggregation window and outlasts it would otherwise
1704                        // be reported partly in this update and partly in the next one.
1705                        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                        // Restarts the sleep
1717                    }
1718                    () = self.event_foreground_done.listen_with_note(|| || "wait for update info".to_string()) => {
1719                        // Resets the sleep
1720                    }
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            // Requested with `TURBO_ENGINE_INLINE_STATS=1`; printed rather than traced so it shows
1750            // up without a tracing subscriber configured.
1751            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            // Both waits re-check their counter after every wake-up (see `wait_until_zero`), so a
1760            // stale notification can't let `stop` tear down storage under a running task.
1761            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            // Deliver compilation events sent during shutdown (e.g. the persistence trace span)
1770            // to subscribers before returning, then close the queue so subscriptions end after
1771            // draining.
1772            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
1835/// Run a future and abort the process if a panic is reported
1836///
1837/// Turbtasks catches panics from user code and propagates throught the task tree, but if it happens
1838/// as part of state management we have to abort
1839///
1840/// A [`PersistentCacheUnreadablePanic`] doesn't necessarily indicate a bug, and its message
1841/// explains what happened, so it's not reported as a bug.
1842///
1843/// [`PersistentCacheUnreadablePanic`]: crate::PersistentCacheUnreadablePanic
1844///
1845/// This is a plain function returning a combinator instead of an `async fn`: an `async fn` would
1846/// store `f` twice in its state machine, once as the captured argument and once inside the awaited
1847/// `CatchUnwind`. This wraps every task execution, so the extra size matters.
1848fn 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
1860/// The message printed by [`abort_on_panic`] for a panic with `payload`.
1861///
1862/// The message of a [`PersistentCacheUnreadablePanic`] is included: Rust's default panic hook
1863/// prints a custom payload like this one as `Box<dyn Any>`, so unless the embedder's panic hook
1864/// printed it, it wouldn't be shown anywhere else.
1865///
1866/// [`PersistentCacheUnreadablePanic`]: crate::PersistentCacheUnreadablePanic
1867fn 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                        // it's okay for execution ids to overflow and wrap, they're just used
1901                        // for an assert
1902                        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, // in_top_level_task
1909                            ));
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                            // When a reader claimed this task and is polling it inline, let it
1921                            // record the outcome on this span rather than its own.
1922                            InlineExecutionSpanSlot::set(&span);
1923
1924                            async {
1925                                let result = CaptureFuture::new(future).await;
1926
1927                                // wait for all spawned local tasks using `local` to finish
1928                                wait_for_local_tasks().await;
1929
1930                                let result = match result {
1931                                    Ok(Ok(raw_vc)) => {
1932                                        // This is safe because we waited for all local tasks to
1933                                        // complete above
1934                                        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                                // A `KeyedReadRef` / `LazyReadRef` drop that failed fails the
1942                                // execution (see `ProvisionalReadDependency::fail_execution`).
1943                                // All drops of this execution happened above, as local tasks
1944                                // were awaited.
1945                                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                                    // Taking the cell counters ends the execution: later
1959                                    // drops of its `KeyedReadRef`s and `LazyReadRef`s are
1960                                    // no longer counted.
1961                                    let cell_counters =
1962                                        ts.write().unwrap().cell_counters.take().unwrap();
1963                                    // All reads of this execution are done (local tasks
1964                                    // were awaited above), so the backend only needs to
1965                                    // look for remaining `CellKeyKind::Provisional`
1966                                    // dependencies when `keyed_reader()` or
1967                                    // `lazy_reader()` was used.
1968                                    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                                // A `KeyedReadRef` / `LazyReadRef` (or its future) that outlives
1984                                // the execution is a bug in the task function. Complete the
1985                                // execution first, so the backend converts the remaining
1986                                // `CellKeyKind::Provisional` dependencies to normal ones, then
1987                                // panic. This is outside the per-task panic boundary, so it aborts
1988                                // the process.
1989                                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                            // Task was stale; re-schedule at the correct invalidation priority so
2015                            // other tasks can run in the right priority order.
2016                            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                    // See the cached-task arm: lets a reader that claimed this local task record
2047                    // the outcome of its inline poll on this span.
2048                    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            // A newer schedule of the same task replaced this one in the queue, so only that one
2108            // executes. Balance the foreground job `TurboTasks::schedule` began for this one.
2109            ScheduledTask::Task { .. } => this.finish_foreground_job(),
2110            // Local tasks have unique keys and are never replaced, and they don't begin a
2111            // foreground job either.
2112            ScheduledTask::LocalTask { .. } => {}
2113        }
2114    }
2115}
2116
2117struct FinishedTaskState {
2118    /// True if the task has state in cells (interior mutability).
2119    /// Only tracked when verify_determinism feature is enabled.
2120    #[cfg(feature = "verify_determinism")]
2121    stateful: bool,
2122
2123    /// True if the task uses an external invalidator
2124    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        // Recorded once, before any task is invalidated.
2239        {
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            // Local Vcs are local to their parent task's current execution, and do not exist
2323            // outside of it. This is weakly enforced at compile time using the `NonLocalValue`
2324            // marker trait. This assertion exists to handle any potential escapes that the
2325            // compile-time checks cannot capture.
2326            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        // TODO: Add assert_not_in_top_level_task("read_task_collectibles") check here.
2337        // Collectible reads are eventually consistent.
2338        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    /// Creates a future that inherits the current task id and task state. The current global task
2428    /// will wait for this future to be dropped before exiting.
2429    fn spawn_detached_for_testing(&self, fut: Pin<Box<dyn Future<Output = ()> + Send + 'static>>) {
2430        // this is similar to what happens for a local task, except that we keep the local task's
2431        // state as well.
2432        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            // use a drop guard for panic safety
2440            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/// Panics if we're not in a top-level task (e.g. [`run_once`]). Some function calls should only
2508/// happen in a top-level task (e.g. [`Effects::apply`][crate::Effects::apply]).
2509#[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    // HACK: We set this inside of `ReadRawVcFuture` to suppress warnings about an internal
2530    // consistency bug
2531    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
2605/// Calls [`TurboTasks::dynamic_call`] for the current turbo tasks instance.
2606pub 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
2616/// Calls [`TurboTasks::trait_call`] for the current turbo tasks instance.
2617pub 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
2654/// Spawns `future` on another worker thread as part of the current task execution and returns a
2655/// [`JoinHandle`] for its result.
2656///
2657/// Unlike [`spawn`][crate::spawn()], the future shares the current task's state, just like a local
2658/// task does: reads of cells and outputs in it are tracked as dependencies of the current task,
2659/// and the task execution doesn't complete before the future has finished (or has been dropped).
2660/// Use it to spread work that reads many cells over several threads, e.g. when the reads restore
2661/// data from the persistent cache.
2662///
2663/// A panic in `future` is resumed when the [`JoinHandle`] is awaited.
2664///
2665/// Must be called from within a task execution.
2666pub(crate) fn spawn_in_current_task<T: Send + 'static>(
2667    future: impl Future<Output = T> + Send + 'static,
2668) -> JoinHandle<T> {
2669    /// Balances the `register_detached` below, even when the future is dropped before it
2670    /// completes (e.g. on runtime shutdown).
2671    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        // Mark the future as finished before the result is handed to the joining side.
2684        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
2694/// Spawns the given future within the context of the current task.
2695///
2696/// Beware: this method is not safe to use in production code. It is only
2697/// intended for use in tests and for debugging purposes.
2698pub fn spawn_detached_for_testing(f: impl Future<Output = ()> + Send + 'static) {
2699    turbo_tasks().spawn_detached_for_testing(Box::pin(f));
2700}
2701
2702/// Marks the current task as finished. This excludes it from waiting for
2703/// strongly consistency.
2704pub fn mark_finished() {
2705    with_turbo_tasks(|tt| {
2706        tt.mark_own_task_as_finished(current_task("turbo_tasks::mark_finished()"))
2707    });
2708}
2709
2710/// Returns a [`SerializationInvalidator`] that can be used to invalidate the
2711/// serialization of the current task cells.
2712///
2713/// Also marks the current task as stateful when the `verify_determinism` feature is enabled,
2714/// since State allocation implies interior mutability.
2715pub 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
2746/// Marks the current task as stateful. This is used to indicate that the task
2747/// has interior mutability (e.g., via [`State`][crate::State]), which means
2748/// the task may produce different outputs even with the same inputs.
2749///
2750/// Only has an effect when the `verify_determinism` feature is enabled.
2751pub 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    // No-op when verify_determinism is not enabled
2760}
2761
2762/// Marks the current task context as being in a top-level task. When in a top-level task,
2763/// eventually consistent reads will panic. It is almost always a mistake to perform an eventually
2764/// consistent read at the top-level of the application.
2765pub 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
2773/// Unmarks the current task context as being in a top-level task. The opposite of
2774/// [`mark_top_level_task`].
2775///
2776/// This utility can be okay in unit tests, where we're observing the internal behavior of
2777/// turbo-tasks, but otherwise, it is probably a mistake to call this function.
2778///
2779/// Calling this will allow eventually-consistent reads at the top-level, potentially exposing
2780/// incomplete computations and internal errors caused by eventual consistency that would've been
2781/// caught when the function was re-run. A strongly-consistent read re-runs parts of a task until
2782/// all of the dependencies have settled.
2783pub 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
2791/// Pins the current task against garbage collection for the rest of the session, keeping it (and,
2792/// via the reachability it anchors, the values it produced) alive even if it becomes disconnected
2793/// from the live task graph. Use this when a value escapes the tracked graph — e.g. a `Vc` sent out
2794/// of a `spawn_detached` future across a channel, or handed across the NAPI boundary — so no
2795/// persistent parent lists it as a child and it would otherwise be collected.
2796///
2797/// No-op outside a task context, and on backends without garbage collection.
2798pub 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
2804/// An RAII guard that pins an [`OperationVc`]'s task against garbage collection.
2805pub struct GcRoot<T: ?Sized> {
2806    tt: Arc<dyn TurboTasksApi>,
2807    vc: OperationVc<T>,
2808}
2809
2810impl<T: ?Sized> GcRoot<T> {
2811    /// Pins `vc`'s task, returning a guard that unpins it on drop.
2812    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
2818/// A guard derefs to the operation it pins, so [`OperationVc`]'s own methods can be called on it
2819/// directly and `*guard` recovers the operation itself.
2820impl<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    /// Compares the pinned operation only. Two guards for the same operation are interchangeable
2848    /// as far as reachability is concerned, even though each holds its own pin.
2849    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    /// Hashes the pinned operation, consistently with [`PartialEq`], so a guard can be looked up
2858    /// in a set by the [`OperationVc`] it pins (see the [`Borrow`] impl).
2859    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2860        self.vc.hash(state);
2861    }
2862}
2863
2864/// Lets a collection keyed on guards be queried with the bare operation: `Borrow` plus the
2865/// matching [`Hash`]/[`Eq`] impls give `OperationVc<T>: Equivalent<GcRoot<T>>`, so e.g.
2866/// `IndexSet<GcRoot<T>>::swap_remove` accepts an `&OperationVc<T>`.
2867impl<T: ?Sized> Borrow<OperationVc<T>> for GcRoot<T> {
2868    fn borrow(&self) -> &OperationVc<T> {
2869        &self.vc
2870    }
2871}
2872
2873/// Safety: a `GcRoot` contains exactly one [`OperationVc`] and no [`Vc`] or [`ResolvedVc`], which
2874/// is what [`OperationValue`] asserts.
2875unsafe impl<T: ?Sized + Send> OperationValue for GcRoot<T> {}
2876
2877/// Safety: mirrors the [`OperationVc`] impl — a `GcRoot` holds no task-local data beyond the
2878/// operation it pins.
2879unsafe 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                // Nobody has started it yet, so take it over instead of waiting for a worker.
2898                if execute_read_target_inline(this, ScheduleKey::Task(id)) {
2899                    continue;
2900                }
2901                listener.await
2902            }
2903            ReadOutcome::InProgress(listener) => {
2904                // A worker is on it — there is nothing to take over, so don't touch the queue.
2905                #[cfg(feature = "inline_execution_stats")]
2906                this.note_waited_for_in_progress_task();
2907                listener.await
2908            }
2909        }
2910    }
2911}
2912
2913/// A reference to a task's cell with methods that allow updating the contents
2914/// of the cell.
2915///
2916/// Mutations should not outside of the task that that owns this cell. Doing so
2917/// is a logic error, and may lead to incorrect caching behavior.
2918#[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
2926/// What a conditional cell update returns: the new content, the key hashes that changed, and an
2927/// optional hash of the value.
2928type CellUpdate = (
2929    SharedReference,
2930    Option<SmallVec<[u64; 2]>>,
2931    Option<CellHash>,
2932);
2933
2934/// The callback [`CurrentCellRef::conditional_update_with_shared_reference`] takes. It is a `dyn`
2935/// trait object so that the function's body is compiled once rather than once per cell type.
2936type CellUpdateFn<'l> = dyn FnMut(Option<&SharedReference>) -> Option<CellUpdate> + 'l;
2937
2938impl CurrentCellRef {
2939    /// Updates the cell if the given `functor` returns a value.
2940    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        // `FnMut` cannot move out of its captures, and the callee calls this at most once, so
2947        // the `FnOnce` is handed over through an `Option`.
2948        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    /// Updates the cell if the given `functor` returns a `SharedReference`.
2962    ///
2963    /// `functor` is a `dyn` trait object rather than a generic parameter on purpose. This body is
2964    /// identical for every cell type, so making it generic monomorphized it once per
2965    /// `VcValueType` in the dependency graph — over a thousand copies of the same code. The
2966    /// indirect call it costs instead is negligible next to the cell read and update it wraps.
2967    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    /// Replace the current cell's content with `new_value` if the current content is not equal by
2984    /// value with the existing content.
2985    ///
2986    /// The comparison happens using the value itself, not the [`VcRead::Target`] of that value.
2987    ///
2988    /// Take this example of a custom equality implementation on a transparent wrapper type:
2989    ///
2990    /// ```
2991    /// #[turbo_tasks::value(transparent, eq = "manual")]
2992    /// #[derive(Clone)]
2993    /// struct Wrapper(Vec<u32>);
2994    ///
2995    /// impl PartialEq for Wrapper {
2996    ///     fn eq(&self, other: &Wrapper) -> bool {
2997    ///         // Example: order doesn't matter for equality
2998    ///         let (mut this, mut other) = (self.0.clone(), other.0.clone());
2999    ///         this.sort_unstable();
3000    ///         other.sort_unstable();
3001    ///         this == other
3002    ///     }
3003    /// }
3004    ///
3005    /// impl Eq for Wrapper {}
3006    /// ```
3007    ///
3008    /// Comparisons of [`Vc<Wrapper>`] used when updating the cell will use `Wrapper`'s custom
3009    /// equality implementation, rather than the one provided by the target ([`Vec<u32>`]) type.
3010    ///
3011    /// However, in most cases, the default derived implementation of [`PartialEq`] is used which
3012    /// just forwards to the inner value's [`PartialEq`].
3013    ///
3014    /// If you already have a `SharedReference`, consider calling
3015    /// [`Self::compare_and_update_with_shared_reference`] which can re-use the [`SharedReference`]
3016    /// object.
3017    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    /// Replace the current cell's content with `new_shared_reference` if the current content is not
3032    /// equal by value with the existing content.
3033    ///
3034    /// If you already have a `SharedReference`, this is a faster version of
3035    /// [`CurrentCellRef::compare_and_update`].
3036    ///
3037    /// The value should be stored in [`SharedReference`] using the type `T`.
3038    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    /// Replace the current cell's content if the new value is different.
3059    ///
3060    /// Like [`Self::compare_and_update`], but also computes and stores a hash of the value.
3061    /// When the cell's transient data is evicted, the stored hash enables the backend to detect
3062    /// whether the value actually changed without re-comparing values—avoiding unnecessary
3063    /// downstream invalidation.
3064    ///
3065    /// Requires `T: DeterministicHash` in addition to `T: PartialEq`.
3066    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    /// Replace the current cell's content if the new value (from a pre-existing
3083    /// [`SharedReference`]) is different.
3084    ///
3085    /// Like [`Self::compare_and_update_with_shared_reference`], but also passes a hash
3086    /// for hash-based change detection when transient data has been evicted.
3087    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    /// See [`Self::compare_and_update`], but selectively update individual keys.
3112    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            // An empty set of keys still updates the value, but only invalidates readers of the
3124            // whole value (see `KeyedEq::different_keys`).
3125            let updated_keys = old_value.different_keys(new_value_ref)?;
3126            // Duplicates are very unlikely, but ok since the backend is deduplicating them
3127            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    /// See [`Self::compare_and_update_with_shared_reference`], but selectively update individual
3136    /// keys.
3137    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            // An empty set of keys still updates the value, but only invalidates readers of the
3157            // whole value (see `KeyedEq::different_keys`).
3158            let updated_keys = old_value.different_keys(new_value)?;
3159            // Duplicates are very unlikely, but ok since the backend is deduplicating them
3160            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    /// Unconditionally updates the content of the cell.
3169    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    /// A faster version of [`Self::update`] if you already have a
3185    /// [`SharedReference`].
3186    ///
3187    /// If the passed-in [`SharedReference`] is the same as the existing cell's
3188    /// by identity, no update is performed.
3189    ///
3190    /// The value should be stored in [`SharedReference`] using the type `T`.
3191    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                // pointer equality (not value equality)
3201                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                // The local task is not done yet. If it is only scheduled, execute it right here
3266                // instead of waiting for a worker to pick it up.
3267                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        // One level below the cap inline execution is allowed again.
3330        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                // Yields on the first poll, so it cannot be executed inline.
3351                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        // ...but it was spawned, so it still runs to completion.
3360        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    /// `finish_foreground_job` notifies only after it decremented the counter, so the notification
3373    /// of an earlier drop to 0 can arrive after new jobs began. Such a stale notification must not
3374    /// end the wait, otherwise `stop_and_wait` stops the backend under a running task.
3375    #[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        // A notification while a job is still running.
3383        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        // The last job finishes.
3390        counter.store(0, Ordering::Release);
3391        event.notify(usize::MAX);
3392        assert!(futures::poll!(wait.as_mut()).is_ready());
3393    }
3394}