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 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    /// Convert a potentially local `RawVc` into a non-local `RawVc`. This is a subset of resolution
167    /// resolution, because the returned `RawVc` can be a `TaskOutput`.
168    ///
169    /// 'unchecked' because the caller must have already confirmed that the local tasks were already
170    /// completed
171    pub(crate) fn to_non_local_unchecked_sync(self, tt: &dyn TurboTasksApi) -> Result<RawVc> {
172        Ok(match self {
173            RawVc::LocalOutput(execution_id, local_task_id, ..) => {
174                let local_output = match tt.try_read_local_output(execution_id, local_task_id)? {
175                    Ok(raw_vc) => raw_vc,
176                    Err(_event_listener) => unreachable!("local output is not ready yet"),
177                };
178                debug_assert!(
179                    !matches!(local_output, RawVc::LocalOutput(_, _, _)),
180                    "a LocalOutput cannot point at other LocalOutputs"
181                );
182                local_output
183            }
184            non_local => non_local,
185        })
186    }
187
188    pub(crate) fn connect(&self) {
189        let RawVc::TaskOutput(task_id) = self else {
190            panic!("RawVc::connect() must only be called on a RawVc::TaskOutput");
191        };
192        let tt = turbo_tasks();
193        tt.connect_task(*task_id);
194    }
195
196    pub fn try_get_task_id(&self) -> Option<TaskId> {
197        match self {
198            RawVc::TaskOutput(t) | RawVc::TaskCell(t, ..) => Some(*t),
199            RawVc::LocalOutput(..) => None,
200        }
201    }
202
203    pub fn try_get_type_id(&self) -> Option<ValueTypeId> {
204        match self {
205            RawVc::TaskCell(_, CellId { type_id, .. }) => Some(*type_id),
206            RawVc::TaskOutput(..) | RawVc::LocalOutput(..) => None,
207        }
208    }
209
210    /// For a cell that's already resolved, synchronously check if it implements a trait using the
211    /// type information in `RawVc::TaskCell` (we don't actually need to read the cell!).
212    pub(crate) fn resolved_has_trait(&self, trait_id: TraitTypeId) -> bool {
213        match self {
214            RawVc::TaskCell(_task_id, cell_id) => {
215                get_value_type(cell_id.type_id).has_trait(&trait_id)
216            }
217            _ => unreachable!("resolved_has_trait must be called with a RawVc::TaskCell"),
218        }
219    }
220
221    /// For a cell that's already resolved, synchronously check if it is a given type using the type
222    /// information in `RawVc::TaskCell` (we don't actually need to read the cell!).
223    pub(crate) fn resolved_is_type(&self, type_id: ValueTypeId) -> bool {
224        match self {
225            RawVc::TaskCell(_task_id, cell_id) => cell_id.type_id == type_id,
226            _ => unreachable!("resolved_is_type must be called with a RawVc::TaskCell"),
227        }
228    }
229}
230
231/// This implementation of `CollectiblesSource` assumes that `self` is a `RawVc::TaskOutput`.
232impl CollectiblesSource for RawVc {
233    fn peek_collectibles<T: VcValueTrait + ?Sized>(self) -> AutoSet<ResolvedVc<T>> {
234        let RawVc::TaskOutput(task_id) = self else {
235            panic!(
236                "<RawVc as CollectiblesSource>::peek_collectibles() must only be called on a \
237                 RawVc::TaskOutput"
238            );
239        };
240        let tt = turbo_tasks();
241        let map = tt.read_task_collectibles(task_id, T::get_trait_type_id());
242        map.into_iter()
243            .filter_map(|(raw, count)| (count > 0).then_some(raw.try_into().unwrap()))
244            .collect()
245    }
246
247    fn take_collectibles<T: VcValueTrait + ?Sized>(self) -> AutoSet<ResolvedVc<T>> {
248        let RawVc::TaskOutput(task_id) = self else {
249            panic!(
250                "<RawVc as CollectiblesSource>::take_collectibles() must only be called on a \
251                 RawVc::TaskOutput"
252            );
253        };
254        let tt = turbo_tasks();
255        let map = tt.read_task_collectibles(task_id, T::get_trait_type_id());
256        tt.unemit_collectibles(T::get_trait_type_id(), &map);
257        map.into_iter()
258            .filter_map(|(raw, count)| (count > 0).then_some(raw.try_into().unwrap()))
259            .collect()
260    }
261
262    fn drop_collectibles<T: VcValueTrait + ?Sized>(self) {
263        let RawVc::TaskOutput(task_id) = self else {
264            panic!(
265                "<RawVc as CollectiblesSource>::drop_collectibles() must only be called on a \
266                 RawVc::TaskOutput"
267            );
268        };
269        let tt = turbo_tasks();
270        let map = tt.read_task_collectibles(task_id, T::get_trait_type_id());
271        tt.unemit_collectibles(T::get_trait_type_id(), &map);
272    }
273}
274
275/// Polls a pending [`EventListener`] slot. Returns [`Poll::Pending`] if the event has not yet
276/// fired. On [`Poll::Ready`], clears the slot so it is not polled again.
277fn poll_listener(
278    listener: &mut Option<EventListener>,
279    cx: &mut std::task::Context<'_>,
280) -> Poll<()> {
281    if let Some(l) = listener {
282        ready!(Pin::new(l).poll(cx));
283        *listener = None;
284    }
285    Poll::Ready(())
286}
287
288/// Wraps `f` in a scope that suppresses the eventual-consistency top-level task assertion,
289/// but only when `strongly_consistent` is `true` and debug assertions are enabled.
290///
291/// This is needed because a strongly-consistent read of a `TaskOutput` is not a single atomic
292/// operation — inner reads switch to eventual consistency after the first output is resolved —
293/// which would otherwise trigger the assertion in top-level tasks.
294fn suppress_top_level_task_check<R>(strongly_consistent: bool, f: impl FnOnce() -> R) -> R {
295    if cfg!(debug_assertions) && strongly_consistent {
296        // Temporarily suppress the top-level task check
297        SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK.sync_scope(true, f)
298    } else {
299        f()
300    }
301}
302
303#[must_use]
304pub struct ResolveRawVcFuture {
305    current: RawVc,
306    read_output_options: ReadOutputOptions,
307    /// This flag is redundant with `read_output_options`, but `read_output_options` is mutated
308    /// during the resolve. This flag indicates that the initial read was strongly consistent.
309    strongly_consistent: bool,
310    listener: Option<EventListener>,
311}
312
313impl ResolveRawVcFuture {
314    fn new(vc: RawVc) -> Self {
315        ResolveRawVcFuture {
316            current: vc,
317            read_output_options: ReadOutputOptions::default(),
318            strongly_consistent: false,
319            listener: None,
320        }
321    }
322
323    pub fn strongly_consistent(mut self) -> Self {
324        self.strongly_consistent = true;
325        self.read_output_options.consistency = ReadConsistency::Strong;
326        self
327    }
328
329    /// Track task output reads with a specific key (forwarded from
330    /// [`ReadRawVcFuture::track_with_key`]).
331    pub(crate) fn track_with_key(mut self) -> Self {
332        self.read_output_options.tracking = ReadTracking::Tracked;
333        self
334    }
335
336    /// Do not track task output reads as dependencies (forwarded from
337    /// [`ReadRawVcFuture::untracked`]).
338    pub(crate) fn untracked(mut self) -> Self {
339        self.read_output_options.tracking = ReadTracking::TrackOnlyError;
340        self
341    }
342}
343
344impl Future for ResolveRawVcFuture {
345    type Output = Result<RawVc>;
346
347    #[inline(never)]
348    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
349        // SAFETY: we are not moving self
350        let this = unsafe { self.get_unchecked_mut() };
351
352        let poll_fn = |tt: &Arc<dyn TurboTasksApi>| -> Poll<Self::Output> {
353            'outer: loop {
354                ready!(poll_listener(&mut this.listener, cx));
355                let listener = match this.current {
356                    RawVc::TaskOutput(task) => {
357                        let read_result = tt.try_read_task_output(task, this.read_output_options);
358                        match read_result {
359                            Ok(Ok(vc)) => {
360                                // turbo-tasks-backend doesn't currently have any sort of
361                                // "transaction" or global lock mechanism to group together chains
362                                // of `TaskOutput`/`TaskCell` reads.
363                                //
364                                // If we ignore the theoretical TOCTOU issues, we no longer need to
365                                // read strongly consistent, as any Vc returned from the first task
366                                // will be inside of the scope of the first task. So it's already
367                                // strongly consistent.
368                                this.read_output_options.consistency = ReadConsistency::Eventual;
369                                this.current = vc;
370                                continue 'outer;
371                            }
372                            Ok(Err(listener)) => listener,
373                            Err(err) => return Poll::Ready(Err(err)),
374                        }
375                    }
376                    RawVc::TaskCell(_, _) => return Poll::Ready(Ok(this.current)),
377                    RawVc::LocalOutput(execution_id, local_task_id, ..) => {
378                        debug_assert_eq!(
379                            this.read_output_options.consistency,
380                            ReadConsistency::Eventual
381                        );
382                        let read_result = tt.try_read_local_output(execution_id, local_task_id);
383                        match read_result {
384                            Ok(Ok(vc)) => {
385                                this.current = vc;
386                                continue 'outer;
387                            }
388                            Ok(Err(listener)) => listener,
389                            Err(err) => return Poll::Ready(Err(err)),
390                        }
391                    }
392                };
393                this.listener = Some(listener);
394            }
395        };
396
397        // HACK: Temporarily suppress top-level task check if doing strongly consistent read.
398        //
399        // This masks a bug: There's an unlikely TOCTOU race condition in `poll_fn`. Because the
400        // strongly consistent read isn't a single atomic operation, any inner `TaskOutput` or
401        // `TaskCell` could get mutated after the strongly consistent read of the outer
402        // `TaskOutput`.
403        suppress_top_level_task_check(this.strongly_consistent, || with_turbo_tasks(poll_fn))
404    }
405}
406
407impl Unpin for ResolveRawVcFuture {}
408
409#[must_use]
410pub struct ReadRawVcFuture {
411    /// Phase 1: resolves the [`RawVc`] pointer chain to a [`RawVc::TaskCell`].
412    resolve: ResolveRawVcFuture,
413    /// Phase 2: options for the cell read once we have a [`RawVc::TaskCell`].
414    read_cell_options: ReadCellOptions,
415    /// Phase 2: the resolved task and cell identity, set when phase 1 completes.
416    resolved: Option<(TaskId, CellId)>,
417    /// Phase 2: listener for the cell read wait.
418    listener: Option<EventListener>,
419}
420
421impl ReadRawVcFuture {
422    pub(crate) fn new(vc: RawVc) -> Self {
423        ReadRawVcFuture {
424            resolve: ResolveRawVcFuture::new(vc),
425            read_cell_options: ReadCellOptions::default(),
426            resolved: None,
427            listener: None,
428        }
429    }
430
431    /// Make reads strongly consistent.
432    pub fn strongly_consistent(mut self) -> Self {
433        self.resolve = self.resolve.strongly_consistent();
434        self
435    }
436
437    /// Track the value as a dependency with an key.
438    pub fn track_with_key(mut self, key: u64) -> Self {
439        self.resolve = self.resolve.track_with_key();
440        self.read_cell_options.tracking = ReadCellTracking::Tracked { key: Some(key) };
441        self
442    }
443
444    /// This will not track the value as dependency, but will still track the error as dependency,
445    /// if there is an error.
446    ///
447    /// INVALIDATION: Be careful with this, it will not track dependencies, so
448    /// using it could break cache invalidation.
449    pub fn untracked(mut self) -> Self {
450        self.resolve = self.resolve.untracked();
451        self.read_cell_options.tracking = ReadCellTracking::TrackOnlyError;
452        self
453    }
454
455    /// Hint that this is the final read of the cell content.
456    pub fn final_read_hint(mut self) -> Self {
457        self.read_cell_options.final_read_hint = true;
458        self
459    }
460}
461
462impl Future for ReadRawVcFuture {
463    type Output = Result<TypedCellContent>;
464
465    #[inline(never)]
466    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
467        // SAFETY: we are not moving self
468        let this = unsafe { self.get_unchecked_mut() };
469
470        // --- Phase 1: resolve the RawVc pointer chain to a TaskCell ---
471        //
472        // `ResolveRawVcFuture` is `Unpin`, so `Pin::new` is safe.
473        // It handles `with_turbo_tasks` and `suppress_top_level_task_check` internally.
474        if this.resolved.is_none() {
475            match ready!(Pin::new(&mut this.resolve).poll(cx)) {
476                Err(err) => return Poll::Ready(Err(err)),
477                Ok(RawVc::TaskCell(task, index)) => {
478                    this.resolved = Some((task, index));
479                }
480                Ok(_) => unreachable!("ResolveRawVcFuture always resolves to a TaskCell"),
481            }
482        }
483
484        // --- Phase 2: read the cell content ---
485        //
486        // At this point `this.resolved` is `Some((task, index))`.
487        let (task, index) = this.resolved.unwrap();
488
489        let poll_fn = |tt: &Arc<dyn TurboTasksApi>| -> Poll<Self::Output> {
490            loop {
491                ready!(poll_listener(&mut this.listener, cx));
492                let listener = match tt.try_read_task_cell(task, index, this.read_cell_options) {
493                    Ok(Ok(content)) => return Poll::Ready(Ok(content)),
494                    Ok(Err(listener)) => listener,
495                    Err(err) => return Poll::Ready(Err(err)),
496                };
497                this.listener = Some(listener);
498            }
499        };
500
501        // Phase 2 must also suppress the top-level task check when phase 1 was
502        // strongly-consistent. The suppression from `ResolveRawVcFuture::poll` only lasts for
503        // the duration of that individual `poll` call and does not carry over to subsequent calls
504        // or to this phase.
505        suppress_top_level_task_check(this.resolve.strongly_consistent, || {
506            with_turbo_tasks(poll_fn)
507        })
508    }
509}
510
511impl Unpin for ReadRawVcFuture {}