Skip to main content

turbo_tasks/
raw_vc.rs

1use std::{
2    fmt::{Debug, Display},
3    future::Future,
4    pin::Pin,
5    sync::Arc,
6    task::{Poll, ready},
7};
8
9use anyhow::Result;
10use auto_hash_map::AutoSet;
11use bincode::{Decode, Encode};
12use serde::{Deserialize, Serialize};
13
14use crate::{
15    CollectiblesSource, ReadCellOptions, ReadConsistency, ReadOutputOptions, ResolvedVc, TaskId,
16    TaskPersistence, TraitTypeId, ValueTypeId, VcValueTrait,
17    backend::TypedCellContent,
18    event::EventListener,
19    id::{ExecutionId, LocalTaskId},
20    manager::{
21        ReadCellTracking, ReadTracking, SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK,
22        TurboTasksApi, read_local_output, with_turbo_tasks,
23    },
24    registry::get_value_type,
25    turbo_tasks,
26};
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Encode, Decode)]
29pub struct CellId {
30    pub type_id: ValueTypeId,
31    pub index: u32,
32}
33
34impl Display for CellId {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        write!(f, "{}#{}", get_value_type(self.type_id).ty.name, self.index)
37    }
38}
39
40/// A type-erased representation of [`Vc`].
41///
42/// Type erasure reduces the [monomorphization] (and therefore binary size and compilation time)
43/// required to support [`Vc`].
44///
45/// This type is heavily used within the [`Backend`][crate::backend::Backend] trait, but should
46/// otherwise be treated as an internal implementation detail of `turbo-tasks`.
47///
48/// [`Vc`]: crate::Vc
49/// [monomorphization]: https://doc.rust-lang.org/book/ch10-01-syntax.html#performance-of-code-using-generics
50#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Encode, Decode)]
51pub enum RawVc {
52    /// The synchronous return value of a task (after argument resolution). This is the
53    /// representation used by [`OperationVc`][crate::OperationVc].
54    TaskOutput(TaskId),
55    /// A pointer to a specific [`Vc::cell`][crate::Vc::cell] or `.cell()` call within a task. This
56    /// is the representation used by [`ResolvedVc`].
57    ///
58    /// [`CellId`] contains the [`ValueTypeId`], which can be useful for efficient downcasting.
59    TaskCell(TaskId, CellId),
60    /// The synchronous return value of a local task. This is created when a function is called
61    /// with unresolved arguments or more explicitly with
62    /// [`#[turbo_tasks::function(local)]`][crate::function].
63    ///
64    /// Local outputs are only valid within the context of their parent "non-local" task. Turbo
65    /// Task's APIs are designed to prevent escapes of local [`Vc`]s, but [`ExecutionId`] is used
66    /// for a fallback runtime assertion.
67    ///
68    /// [`Vc`]: crate::Vc
69    LocalOutput(ExecutionId, LocalTaskId, TaskPersistence),
70}
71
72impl Debug for RawVc {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        match self {
75            RawVc::TaskOutput(task_id) => f
76                .debug_tuple("RawVc::TaskOutput")
77                .field(&**task_id)
78                .finish(),
79            RawVc::TaskCell(task_id, cell_id) => f
80                .debug_tuple("RawVc::TaskCell")
81                .field(&**task_id)
82                .field(&cell_id.to_string())
83                .finish(),
84            RawVc::LocalOutput(execution_id, local_task_id, task_persistence) => f
85                .debug_tuple("RawVc::LocalOutput")
86                .field(&**execution_id)
87                .field(&**local_task_id)
88                .field(task_persistence)
89                .finish(),
90        }
91    }
92}
93
94impl Display for RawVc {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        match self {
97            RawVc::TaskOutput(task_id) => write!(f, "output of task {}", **task_id),
98            RawVc::TaskCell(task_id, cell_id) => {
99                write!(f, "{} of task {}", cell_id, **task_id)
100            }
101            RawVc::LocalOutput(execution_id, local_task_id, task_persistence) => write!(
102                f,
103                "output of local task {} ({}, {})",
104                **local_task_id, **execution_id, task_persistence
105            ),
106        }
107    }
108}
109
110impl RawVc {
111    pub fn is_resolved(&self) -> bool {
112        match self {
113            RawVc::TaskOutput(..) => false,
114            RawVc::TaskCell(..) => true,
115            RawVc::LocalOutput(..) => false,
116        }
117    }
118
119    pub fn is_local(&self) -> bool {
120        match self {
121            RawVc::TaskOutput(..) => false,
122            RawVc::TaskCell(..) => false,
123            RawVc::LocalOutput(..) => true,
124        }
125    }
126
127    /// Returns `true` if the task this `RawVc` reads from cannot be serialized and will not be
128    /// stored in the filesystem cache.
129    ///
130    /// See [`TaskPersistence`] for more details.
131    pub fn is_transient(&self) -> bool {
132        match self {
133            RawVc::TaskOutput(task) | RawVc::TaskCell(task, ..) => task.is_transient(),
134            RawVc::LocalOutput(_, _, persistence) => *persistence == TaskPersistence::Transient,
135        }
136    }
137
138    pub(crate) fn into_read(self) -> ReadRawVcFuture {
139        // returns a custom future to have something concrete and sized
140        // this avoids boxing in IntoFuture
141        ReadRawVcFuture::new(self)
142    }
143
144    /// See [`crate::Vc::to_resolved`].
145    pub(crate) fn resolve(self) -> ResolveRawVcFuture {
146        ResolveRawVcFuture::new(self)
147    }
148
149    /// Convert a potentially local `RawVc` into a non-local `RawVc`. This is a subset of resolution
150    /// resolution, because the returned `RawVc` can be a `TaskOutput`.
151    pub(crate) async fn to_non_local(self) -> Result<RawVc> {
152        Ok(match self {
153            RawVc::LocalOutput(execution_id, local_task_id, ..) => {
154                let tt = turbo_tasks();
155                let local_output = read_local_output(&*tt, execution_id, local_task_id).await?;
156                debug_assert!(
157                    !matches!(local_output, RawVc::LocalOutput(_, _, _)),
158                    "a LocalOutput cannot point at other LocalOutputs"
159                );
160                local_output
161            }
162            non_local => non_local,
163        })
164    }
165
166    pub(crate) fn connect(&self) {
167        let RawVc::TaskOutput(task_id) = self else {
168            panic!("RawVc::connect() must only be called on a RawVc::TaskOutput");
169        };
170        let tt = turbo_tasks();
171        tt.connect_task(*task_id);
172    }
173
174    pub fn try_get_task_id(&self) -> Option<TaskId> {
175        match self {
176            RawVc::TaskOutput(t) | RawVc::TaskCell(t, ..) => Some(*t),
177            RawVc::LocalOutput(..) => None,
178        }
179    }
180
181    pub fn try_get_type_id(&self) -> Option<ValueTypeId> {
182        match self {
183            RawVc::TaskCell(_, CellId { type_id, .. }) => Some(*type_id),
184            RawVc::TaskOutput(..) | RawVc::LocalOutput(..) => None,
185        }
186    }
187
188    /// For a cell that's already resolved, synchronously check if it implements a trait using the
189    /// type information in `RawVc::TaskCell` (we don't actually need to read the cell!).
190    pub(crate) fn resolved_has_trait(&self, trait_id: TraitTypeId) -> bool {
191        match self {
192            RawVc::TaskCell(_task_id, cell_id) => {
193                get_value_type(cell_id.type_id).has_trait(&trait_id)
194            }
195            _ => unreachable!("resolved_has_trait must be called with a RawVc::TaskCell"),
196        }
197    }
198
199    /// For a cell that's already resolved, synchronously check if it is a given type using the type
200    /// information in `RawVc::TaskCell` (we don't actually need to read the cell!).
201    pub(crate) fn resolved_is_type(&self, type_id: ValueTypeId) -> bool {
202        match self {
203            RawVc::TaskCell(_task_id, cell_id) => cell_id.type_id == type_id,
204            _ => unreachable!("resolved_is_type must be called with a RawVc::TaskCell"),
205        }
206    }
207}
208
209/// This implementation of `CollectiblesSource` assumes that `self` is a `RawVc::TaskOutput`.
210impl CollectiblesSource for RawVc {
211    fn peek_collectibles<T: VcValueTrait + ?Sized>(self) -> AutoSet<ResolvedVc<T>> {
212        let RawVc::TaskOutput(task_id) = self else {
213            panic!(
214                "<RawVc as CollectiblesSource>::peek_collectibles() must only be called on a \
215                 RawVc::TaskOutput"
216            );
217        };
218        let tt = turbo_tasks();
219        let map = tt.read_task_collectibles(task_id, T::get_trait_type_id());
220        map.into_iter()
221            .filter_map(|(raw, count)| (count > 0).then_some(raw.try_into().unwrap()))
222            .collect()
223    }
224
225    fn take_collectibles<T: VcValueTrait + ?Sized>(self) -> AutoSet<ResolvedVc<T>> {
226        let RawVc::TaskOutput(task_id) = self else {
227            panic!(
228                "<RawVc as CollectiblesSource>::take_collectibles() must only be called on a \
229                 RawVc::TaskOutput"
230            );
231        };
232        let tt = turbo_tasks();
233        let map = tt.read_task_collectibles(task_id, T::get_trait_type_id());
234        tt.unemit_collectibles(T::get_trait_type_id(), &map);
235        map.into_iter()
236            .filter_map(|(raw, count)| (count > 0).then_some(raw.try_into().unwrap()))
237            .collect()
238    }
239
240    fn drop_collectibles<T: VcValueTrait + ?Sized>(self) {
241        let RawVc::TaskOutput(task_id) = self else {
242            panic!(
243                "<RawVc as CollectiblesSource>::drop_collectibles() must only be called on a \
244                 RawVc::TaskOutput"
245            );
246        };
247        let tt = turbo_tasks();
248        let map = tt.read_task_collectibles(task_id, T::get_trait_type_id());
249        tt.unemit_collectibles(T::get_trait_type_id(), &map);
250    }
251}
252
253/// Polls a pending [`EventListener`] slot. Returns [`Poll::Pending`] if the event has not yet
254/// fired. On [`Poll::Ready`], clears the slot so it is not polled again.
255fn poll_listener(
256    listener: &mut Option<EventListener>,
257    cx: &mut std::task::Context<'_>,
258) -> Poll<()> {
259    if let Some(l) = listener {
260        ready!(Pin::new(l).poll(cx));
261        *listener = None;
262    }
263    Poll::Ready(())
264}
265
266/// Wraps `f` in a scope that suppresses the eventual-consistency top-level task assertion,
267/// but only when `strongly_consistent` is `true` and debug assertions are enabled.
268///
269/// This is needed because a strongly-consistent read of a `TaskOutput` is not a single atomic
270/// operation — inner reads switch to eventual consistency after the first output is resolved —
271/// which would otherwise trigger the assertion in top-level tasks.
272fn suppress_top_level_task_check<R>(strongly_consistent: bool, f: impl FnOnce() -> R) -> R {
273    if cfg!(debug_assertions) && strongly_consistent {
274        // Temporarily suppress the top-level task check
275        SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK.sync_scope(true, f)
276    } else {
277        f()
278    }
279}
280
281#[must_use]
282pub struct ResolveRawVcFuture {
283    current: RawVc,
284    read_output_options: ReadOutputOptions,
285    /// This flag is redundant with `read_output_options`, but `read_output_options` is mutated
286    /// during the resolve. This flag indicates that the initial read was strongly consistent.
287    strongly_consistent: bool,
288    listener: Option<EventListener>,
289}
290
291impl ResolveRawVcFuture {
292    fn new(vc: RawVc) -> Self {
293        ResolveRawVcFuture {
294            current: vc,
295            read_output_options: ReadOutputOptions::default(),
296            strongly_consistent: false,
297            listener: None,
298        }
299    }
300
301    pub fn strongly_consistent(mut self) -> Self {
302        self.strongly_consistent = true;
303        self.read_output_options.consistency = ReadConsistency::Strong;
304        self
305    }
306
307    /// Track task output reads with a specific key (forwarded from
308    /// [`ReadRawVcFuture::track_with_key`]).
309    pub(crate) fn track_with_key(mut self) -> Self {
310        self.read_output_options.tracking = ReadTracking::Tracked;
311        self
312    }
313
314    /// Do not track task output reads as dependencies (forwarded from
315    /// [`ReadRawVcFuture::untracked`]).
316    pub(crate) fn untracked(mut self) -> Self {
317        self.read_output_options.tracking = ReadTracking::TrackOnlyError;
318        self
319    }
320}
321
322impl Future for ResolveRawVcFuture {
323    type Output = Result<RawVc>;
324
325    #[inline(never)]
326    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
327        // SAFETY: we are not moving self
328        let this = unsafe { self.get_unchecked_mut() };
329
330        let poll_fn = |tt: &Arc<dyn TurboTasksApi>| -> Poll<Self::Output> {
331            'outer: loop {
332                ready!(poll_listener(&mut this.listener, cx));
333                let listener = match this.current {
334                    RawVc::TaskOutput(task) => {
335                        let read_result = tt.try_read_task_output(task, this.read_output_options);
336                        match read_result {
337                            Ok(Ok(vc)) => {
338                                // turbo-tasks-backend doesn't currently have any sort of
339                                // "transaction" or global lock mechanism to group together chains
340                                // of `TaskOutput`/`TaskCell` reads.
341                                //
342                                // If we ignore the theoretical TOCTOU issues, we no longer need to
343                                // read strongly consistent, as any Vc returned from the first task
344                                // will be inside of the scope of the first task. So it's already
345                                // strongly consistent.
346                                this.read_output_options.consistency = ReadConsistency::Eventual;
347                                this.current = vc;
348                                continue 'outer;
349                            }
350                            Ok(Err(listener)) => listener,
351                            Err(err) => return Poll::Ready(Err(err)),
352                        }
353                    }
354                    RawVc::TaskCell(_, _) => return Poll::Ready(Ok(this.current)),
355                    RawVc::LocalOutput(execution_id, local_task_id, ..) => {
356                        debug_assert_eq!(
357                            this.read_output_options.consistency,
358                            ReadConsistency::Eventual
359                        );
360                        let read_result = tt.try_read_local_output(execution_id, local_task_id);
361                        match read_result {
362                            Ok(Ok(vc)) => {
363                                this.current = vc;
364                                continue 'outer;
365                            }
366                            Ok(Err(listener)) => listener,
367                            Err(err) => return Poll::Ready(Err(err)),
368                        }
369                    }
370                };
371                this.listener = Some(listener);
372            }
373        };
374
375        // HACK: Temporarily suppress top-level task check if doing strongly consistent read.
376        //
377        // This masks a bug: There's an unlikely TOCTOU race condition in `poll_fn`. Because the
378        // strongly consistent read isn't a single atomic operation, any inner `TaskOutput` or
379        // `TaskCell` could get mutated after the strongly consistent read of the outer
380        // `TaskOutput`.
381        suppress_top_level_task_check(this.strongly_consistent, || with_turbo_tasks(poll_fn))
382    }
383}
384
385impl Unpin for ResolveRawVcFuture {}
386
387#[must_use]
388pub struct ReadRawVcFuture {
389    /// Phase 1: resolves the [`RawVc`] pointer chain to a [`RawVc::TaskCell`].
390    resolve: ResolveRawVcFuture,
391    /// Phase 2: options for the cell read once we have a [`RawVc::TaskCell`].
392    read_cell_options: ReadCellOptions,
393    /// Phase 2: the resolved task and cell identity, set when phase 1 completes.
394    resolved: Option<(TaskId, CellId)>,
395    /// Phase 2: listener for the cell read wait.
396    listener: Option<EventListener>,
397}
398
399impl ReadRawVcFuture {
400    pub(crate) fn new(vc: RawVc) -> Self {
401        ReadRawVcFuture {
402            resolve: ResolveRawVcFuture::new(vc),
403            read_cell_options: ReadCellOptions::default(),
404            resolved: None,
405            listener: None,
406        }
407    }
408
409    /// Make reads strongly consistent.
410    pub fn strongly_consistent(mut self) -> Self {
411        self.resolve = self.resolve.strongly_consistent();
412        self
413    }
414
415    /// Track the value as a dependency with an key.
416    pub fn track_with_key(mut self, key: u64) -> Self {
417        self.resolve = self.resolve.track_with_key();
418        self.read_cell_options.tracking = ReadCellTracking::Tracked { key: Some(key) };
419        self
420    }
421
422    /// This will not track the value as dependency, but will still track the error as dependency,
423    /// if there is an error.
424    ///
425    /// INVALIDATION: Be careful with this, it will not track dependencies, so
426    /// using it could break cache invalidation.
427    pub fn untracked(mut self) -> Self {
428        self.resolve = self.resolve.untracked();
429        self.read_cell_options.tracking = ReadCellTracking::TrackOnlyError;
430        self
431    }
432
433    /// Hint that this is the final read of the cell content.
434    pub fn final_read_hint(mut self) -> Self {
435        self.read_cell_options.final_read_hint = true;
436        self
437    }
438}
439
440impl Future for ReadRawVcFuture {
441    type Output = Result<TypedCellContent>;
442
443    #[inline(never)]
444    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
445        // SAFETY: we are not moving self
446        let this = unsafe { self.get_unchecked_mut() };
447
448        // --- Phase 1: resolve the RawVc pointer chain to a TaskCell ---
449        //
450        // `ResolveRawVcFuture` is `Unpin`, so `Pin::new` is safe.
451        // It handles `with_turbo_tasks` and `suppress_top_level_task_check` internally.
452        if this.resolved.is_none() {
453            match ready!(Pin::new(&mut this.resolve).poll(cx)) {
454                Err(err) => return Poll::Ready(Err(err)),
455                Ok(RawVc::TaskCell(task, index)) => {
456                    this.resolved = Some((task, index));
457                }
458                Ok(_) => unreachable!("ResolveRawVcFuture always resolves to a TaskCell"),
459            }
460        }
461
462        // --- Phase 2: read the cell content ---
463        //
464        // At this point `this.resolved` is `Some((task, index))`.
465        let (task, index) = this.resolved.unwrap();
466
467        let poll_fn = |tt: &Arc<dyn TurboTasksApi>| -> Poll<Self::Output> {
468            loop {
469                ready!(poll_listener(&mut this.listener, cx));
470                let listener = match tt.try_read_task_cell(task, index, this.read_cell_options) {
471                    Ok(Ok(content)) => return Poll::Ready(Ok(content)),
472                    Ok(Err(listener)) => listener,
473                    Err(err) => return Poll::Ready(Err(err)),
474                };
475                this.listener = Some(listener);
476            }
477        };
478
479        // Phase 2 must also suppress the top-level task check when phase 1 was
480        // strongly-consistent. The suppression from `ResolveRawVcFuture::poll` only lasts for
481        // the duration of that individual `poll` call and does not carry over to subsequent calls
482        // or to this phase.
483        suppress_top_level_task_check(this.resolve.strongly_consistent, || {
484            with_turbo_tasks(poll_fn)
485        })
486    }
487}
488
489impl Unpin for ReadRawVcFuture {}