Skip to main content

turbo_tasks_backend/backend/
mod.rs

1mod counter_map;
2mod operation;
3mod storage;
4pub mod storage_schema;
5
6use std::{
7    borrow::Cow,
8    fmt::{self, Write},
9    future::Future,
10    hash::BuildHasherDefault,
11    mem::take,
12    pin::Pin,
13    sync::{
14        Arc, LazyLock,
15        atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
16    },
17};
18
19use anyhow::{Context, Result, bail};
20use auto_hash_map::{AutoMap, AutoSet};
21use indexmap::IndexSet;
22use parking_lot::{Condvar, Mutex};
23use rustc_hash::{FxHashMap, FxHashSet, FxHasher};
24use smallvec::{SmallVec, smallvec};
25use tokio::time::{Duration, Instant};
26use tracing::{Span, trace_span};
27use turbo_bincode::{TurboBincodeBuffer, new_turbo_bincode_decoder, new_turbo_bincode_encoder};
28use turbo_tasks::{
29    CellId, FxDashMap, RawVc, ReadCellOptions, ReadCellTracking, ReadConsistency,
30    ReadOutputOptions, ReadTracking, SharedReference, TRANSIENT_TASK_BIT, TaskExecutionReason,
31    TaskId, TaskPriority, TraitTypeId, TurboTasksBackendApi, TurboTasksPanic, ValueTypeId,
32    backend::{
33        Backend, CachedTaskType, CellContent, TaskExecutionSpec, TransientTaskType,
34        TurboTaskContextError, TurboTaskLocalContextError, TurboTasksError,
35        TurboTasksExecutionError, TurboTasksExecutionErrorMessage, TypedCellContent,
36        VerificationMode,
37    },
38    event::{Event, EventDescription, EventListener},
39    message_queue::TimingEvent,
40    registry::get_value_type,
41    scope::scope_and_block,
42    task_statistics::TaskStatisticsApi,
43    trace::TraceRawVcs,
44    util::{IdFactoryWithReuse, good_chunk_size, into_chunks},
45};
46
47pub use self::{
48    operation::AnyOperation,
49    storage::{SpecificTaskDataCategory, TaskDataCategory},
50};
51#[cfg(feature = "trace_task_dirty")]
52use crate::backend::operation::TaskDirtyCause;
53use crate::{
54    backend::{
55        operation::{
56            AggregationUpdateJob, AggregationUpdateQueue, ChildExecuteContext,
57            CleanupOldEdgesOperation, ComputeDirtyAndCleanUpdate, ConnectChildOperation,
58            ExecuteContext, ExecuteContextImpl, LeafDistanceUpdateQueue, Operation, OutdatedEdge,
59            TaskGuard, TaskType, connect_children, get_aggregation_number, get_uppers,
60            is_root_node, make_task_dirty_internal, prepare_new_children,
61        },
62        storage::Storage,
63        storage_schema::{TaskStorage, TaskStorageAccessors},
64    },
65    backing_storage::BackingStorage,
66    data::{
67        ActivenessState, CellRef, CollectibleRef, CollectiblesRef, Dirtyness, InProgressCellState,
68        InProgressState, InProgressStateInner, OutputValue, TransientTask,
69    },
70    error::TaskError,
71    utils::{
72        arc_or_owned::ArcOrOwned,
73        chunked_vec::ChunkedVec,
74        dash_map_drop_contents::drop_contents,
75        dash_map_raw_entry::{RawEntry, raw_entry},
76        ptr_eq_arc::PtrEqArc,
77        shard_amount::compute_shard_amount,
78        sharded::Sharded,
79        swap_retain,
80    },
81};
82
83/// Threshold for parallelizing making dependent tasks dirty.
84/// If the number of dependent tasks exceeds this threshold,
85/// the operation will be parallelized.
86const DEPENDENT_TASKS_DIRTY_PARALLIZATION_THRESHOLD: usize = 10000;
87
88const SNAPSHOT_REQUESTED_BIT: usize = 1 << (usize::BITS - 1);
89
90/// Configurable idle timeout for snapshot persistence.
91/// Defaults to 2 seconds if not set or if the value is invalid.
92static IDLE_TIMEOUT: LazyLock<Duration> = LazyLock::new(|| {
93    std::env::var("TURBO_ENGINE_SNAPSHOT_IDLE_TIMEOUT_MILLIS")
94        .ok()
95        .and_then(|v| v.parse::<u64>().ok())
96        .map(Duration::from_millis)
97        .unwrap_or(Duration::from_secs(2))
98});
99
100struct SnapshotRequest {
101    snapshot_requested: bool,
102    suspended_operations: FxHashSet<PtrEqArc<AnyOperation>>,
103}
104
105impl SnapshotRequest {
106    fn new() -> Self {
107        Self {
108            snapshot_requested: false,
109            suspended_operations: FxHashSet::default(),
110        }
111    }
112}
113
114pub enum StorageMode {
115    /// Queries the storage for cache entries that don't exist locally.
116    ReadOnly,
117    /// Queries the storage for cache entries that don't exist locally.
118    /// Regularly pushes changes to the backing storage.
119    ReadWrite,
120    /// Queries the storage for cache entries that don't exist locally.
121    /// On shutdown, pushes all changes to the backing storage.
122    ReadWriteOnShutdown,
123}
124
125pub struct BackendOptions {
126    /// Enables dependency tracking.
127    ///
128    /// When disabled: No state changes are allowed. Tasks will never reexecute and stay cached
129    /// forever.
130    pub dependency_tracking: bool,
131
132    /// Enables active tracking.
133    ///
134    /// Automatically disabled when `dependency_tracking` is disabled.
135    ///
136    /// When disabled: All tasks are considered as active.
137    pub active_tracking: bool,
138
139    /// Enables the backing storage.
140    pub storage_mode: Option<StorageMode>,
141
142    /// Number of tokio worker threads. It will be used to compute the shard amount of parallel
143    /// datastructures. If `None`, it will use the available parallelism.
144    pub num_workers: Option<usize>,
145
146    /// Avoid big preallocations for faster startup. Should only be used for testing purposes.
147    pub small_preallocation: bool,
148}
149
150impl Default for BackendOptions {
151    fn default() -> Self {
152        Self {
153            dependency_tracking: true,
154            active_tracking: true,
155            storage_mode: Some(StorageMode::ReadWrite),
156            num_workers: None,
157            small_preallocation: false,
158        }
159    }
160}
161
162pub enum TurboTasksBackendJob {
163    InitialSnapshot,
164    FollowUpSnapshot,
165}
166
167pub struct TurboTasksBackend<B: BackingStorage>(Arc<TurboTasksBackendInner<B>>);
168
169type TaskCacheLog = Sharded<ChunkedVec<(Arc<CachedTaskType>, TaskId)>>;
170
171struct TurboTasksBackendInner<B: BackingStorage> {
172    options: BackendOptions,
173
174    start_time: Instant,
175
176    persisted_task_id_factory: IdFactoryWithReuse<TaskId>,
177    transient_task_id_factory: IdFactoryWithReuse<TaskId>,
178
179    persisted_task_cache_log: Option<TaskCacheLog>,
180    task_cache: FxDashMap<Arc<CachedTaskType>, TaskId>,
181
182    storage: Storage,
183
184    /// When true, the backing_storage has data that is not in the local storage.
185    local_is_partial: AtomicBool,
186
187    /// Number of executing operations + Highest bit is set when snapshot is
188    /// requested. When that bit is set, operations should pause until the
189    /// snapshot is completed. When the bit is set and in progress counter
190    /// reaches zero, `operations_completed_when_snapshot_requested` is
191    /// triggered.
192    in_progress_operations: AtomicUsize,
193
194    snapshot_request: Mutex<SnapshotRequest>,
195    /// Condition Variable that is triggered when `in_progress_operations`
196    /// reaches zero while snapshot is requested. All operations are either
197    /// completed or suspended.
198    operations_suspended: Condvar,
199    /// Condition Variable that is triggered when a snapshot is completed and
200    /// operations can continue.
201    snapshot_completed: Condvar,
202    /// The timestamp of the last started snapshot since [`Self::start_time`].
203    last_snapshot: AtomicU64,
204
205    stopping: AtomicBool,
206    stopping_event: Event,
207    idle_start_event: Event,
208    idle_end_event: Event,
209    #[cfg(feature = "verify_aggregation_graph")]
210    is_idle: AtomicBool,
211
212    task_statistics: TaskStatisticsApi,
213
214    backing_storage: B,
215
216    #[cfg(feature = "verify_aggregation_graph")]
217    root_tasks: Mutex<FxHashSet<TaskId>>,
218}
219
220impl<B: BackingStorage> TurboTasksBackend<B> {
221    pub fn new(options: BackendOptions, backing_storage: B) -> Self {
222        Self(Arc::new(TurboTasksBackendInner::new(
223            options,
224            backing_storage,
225        )))
226    }
227
228    pub fn backing_storage(&self) -> &B {
229        &self.0.backing_storage
230    }
231}
232
233impl<B: BackingStorage> TurboTasksBackendInner<B> {
234    pub fn new(mut options: BackendOptions, backing_storage: B) -> Self {
235        let shard_amount = compute_shard_amount(options.num_workers, options.small_preallocation);
236        let need_log = matches!(
237            options.storage_mode,
238            Some(StorageMode::ReadWrite) | Some(StorageMode::ReadWriteOnShutdown)
239        );
240        if !options.dependency_tracking {
241            options.active_tracking = false;
242        }
243        let small_preallocation = options.small_preallocation;
244        let next_task_id = backing_storage
245            .next_free_task_id()
246            .expect("Failed to get task id");
247        Self {
248            options,
249            start_time: Instant::now(),
250            persisted_task_id_factory: IdFactoryWithReuse::new(
251                next_task_id,
252                TaskId::try_from(TRANSIENT_TASK_BIT - 1).unwrap(),
253            ),
254            transient_task_id_factory: IdFactoryWithReuse::new(
255                TaskId::try_from(TRANSIENT_TASK_BIT).unwrap(),
256                TaskId::MAX,
257            ),
258            persisted_task_cache_log: need_log.then(|| Sharded::new(shard_amount)),
259            task_cache: FxDashMap::default(),
260            local_is_partial: AtomicBool::new(next_task_id != TaskId::MIN),
261            storage: Storage::new(shard_amount, small_preallocation),
262            in_progress_operations: AtomicUsize::new(0),
263            snapshot_request: Mutex::new(SnapshotRequest::new()),
264            operations_suspended: Condvar::new(),
265            snapshot_completed: Condvar::new(),
266            last_snapshot: AtomicU64::new(0),
267            stopping: AtomicBool::new(false),
268            stopping_event: Event::new(|| || "TurboTasksBackend::stopping_event".to_string()),
269            idle_start_event: Event::new(|| || "TurboTasksBackend::idle_start_event".to_string()),
270            idle_end_event: Event::new(|| || "TurboTasksBackend::idle_end_event".to_string()),
271            #[cfg(feature = "verify_aggregation_graph")]
272            is_idle: AtomicBool::new(false),
273            task_statistics: TaskStatisticsApi::default(),
274            backing_storage,
275            #[cfg(feature = "verify_aggregation_graph")]
276            root_tasks: Default::default(),
277        }
278    }
279
280    fn execute_context<'a>(
281        &'a self,
282        turbo_tasks: &'a dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
283    ) -> impl ExecuteContext<'a> {
284        ExecuteContextImpl::new(self, turbo_tasks)
285    }
286
287    /// # Safety
288    ///
289    /// `tx` must be a transaction from this TurboTasksBackendInner instance.
290    unsafe fn execute_context_with_tx<'e, 'tx>(
291        &'e self,
292        tx: Option<&'e B::ReadTransaction<'tx>>,
293        turbo_tasks: &'e dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
294    ) -> impl ExecuteContext<'e> + use<'e, 'tx, B>
295    where
296        'tx: 'e,
297    {
298        // Safety: `tx` is from `self`.
299        unsafe { ExecuteContextImpl::new_with_tx(self, tx, turbo_tasks) }
300    }
301
302    fn suspending_requested(&self) -> bool {
303        self.should_persist()
304            && (self.in_progress_operations.load(Ordering::Relaxed) & SNAPSHOT_REQUESTED_BIT) != 0
305    }
306
307    fn operation_suspend_point(&self, suspend: impl FnOnce() -> AnyOperation) {
308        #[cold]
309        fn operation_suspend_point_cold<B: BackingStorage>(
310            this: &TurboTasksBackendInner<B>,
311            suspend: impl FnOnce() -> AnyOperation,
312        ) {
313            let operation = Arc::new(suspend());
314            let mut snapshot_request = this.snapshot_request.lock();
315            if snapshot_request.snapshot_requested {
316                snapshot_request
317                    .suspended_operations
318                    .insert(operation.clone().into());
319                let value = this.in_progress_operations.fetch_sub(1, Ordering::AcqRel) - 1;
320                assert!((value & SNAPSHOT_REQUESTED_BIT) != 0);
321                if value == SNAPSHOT_REQUESTED_BIT {
322                    this.operations_suspended.notify_all();
323                }
324                this.snapshot_completed
325                    .wait_while(&mut snapshot_request, |snapshot_request| {
326                        snapshot_request.snapshot_requested
327                    });
328                this.in_progress_operations.fetch_add(1, Ordering::AcqRel);
329                snapshot_request
330                    .suspended_operations
331                    .remove(&operation.into());
332            }
333        }
334
335        if self.suspending_requested() {
336            operation_suspend_point_cold(self, suspend);
337        }
338    }
339
340    pub(crate) fn start_operation(&self) -> OperationGuard<'_, B> {
341        if !self.should_persist() {
342            return OperationGuard { backend: None };
343        }
344        let fetch_add = self.in_progress_operations.fetch_add(1, Ordering::AcqRel);
345        if (fetch_add & SNAPSHOT_REQUESTED_BIT) != 0 {
346            let mut snapshot_request = self.snapshot_request.lock();
347            if snapshot_request.snapshot_requested {
348                let value = self.in_progress_operations.fetch_sub(1, Ordering::AcqRel) - 1;
349                if value == SNAPSHOT_REQUESTED_BIT {
350                    self.operations_suspended.notify_all();
351                }
352                self.snapshot_completed
353                    .wait_while(&mut snapshot_request, |snapshot_request| {
354                        snapshot_request.snapshot_requested
355                    });
356                self.in_progress_operations.fetch_add(1, Ordering::AcqRel);
357            }
358        }
359        OperationGuard {
360            backend: Some(self),
361        }
362    }
363
364    fn should_persist(&self) -> bool {
365        matches!(
366            self.options.storage_mode,
367            Some(StorageMode::ReadWrite) | Some(StorageMode::ReadWriteOnShutdown)
368        )
369    }
370
371    fn should_restore(&self) -> bool {
372        self.options.storage_mode.is_some()
373    }
374
375    fn should_track_dependencies(&self) -> bool {
376        self.options.dependency_tracking
377    }
378
379    fn should_track_activeness(&self) -> bool {
380        self.options.active_tracking
381    }
382
383    fn track_cache_hit(&self, task_type: &CachedTaskType) {
384        self.task_statistics
385            .map(|stats| stats.increment_cache_hit(task_type.native_fn));
386    }
387
388    fn track_cache_miss(&self, task_type: &CachedTaskType) {
389        self.task_statistics
390            .map(|stats| stats.increment_cache_miss(task_type.native_fn));
391    }
392
393    /// Reconstructs a full [`TurboTasksExecutionError`] from the compact [`TaskError`] storage
394    /// representation. For [`TaskError::TaskChain`], this looks up the source error from the last
395    /// task's output and rebuilds the nested `TaskContext` wrappers with `TurboTasksCallApi`
396    /// references for lazy name resolution.
397    fn task_error_to_turbo_tasks_execution_error(
398        &self,
399        error: &TaskError,
400        ctx: &mut impl ExecuteContext<'_>,
401    ) -> TurboTasksExecutionError {
402        match error {
403            TaskError::Panic(panic) => TurboTasksExecutionError::Panic(panic.clone()),
404            TaskError::Error(item) => TurboTasksExecutionError::Error(Arc::new(TurboTasksError {
405                message: item.message.clone(),
406                source: item
407                    .source
408                    .as_ref()
409                    .map(|e| self.task_error_to_turbo_tasks_execution_error(e, ctx)),
410            })),
411            TaskError::LocalTaskContext(local_task_context) => {
412                TurboTasksExecutionError::LocalTaskContext(Arc::new(TurboTaskLocalContextError {
413                    name: local_task_context.name.clone(),
414                    source: local_task_context
415                        .source
416                        .as_ref()
417                        .map(|e| self.task_error_to_turbo_tasks_execution_error(e, ctx)),
418                }))
419            }
420            TaskError::TaskChain(chain) => {
421                let task_id = chain.last().unwrap();
422                let error = {
423                    let task = ctx.task(*task_id, TaskDataCategory::Meta);
424                    if let Some(OutputValue::Error(error)) = task.get_output() {
425                        Some(error.clone())
426                    } else {
427                        None
428                    }
429                };
430                let error = error.map_or_else(
431                    || {
432                        // Eventual consistency will cause errors to no longer be available
433                        TurboTasksExecutionError::Panic(Arc::new(TurboTasksPanic {
434                            message: TurboTasksExecutionErrorMessage::PIISafe(Cow::Borrowed(
435                                "Error no longer available",
436                            )),
437                            location: None,
438                        }))
439                    },
440                    |e| self.task_error_to_turbo_tasks_execution_error(&e, ctx),
441                );
442                let mut current_error = error;
443                for &task_id in chain.iter().rev() {
444                    current_error =
445                        TurboTasksExecutionError::TaskContext(Arc::new(TurboTaskContextError {
446                            task_id,
447                            source: Some(current_error),
448                            turbo_tasks: ctx.turbo_tasks(),
449                        }));
450                }
451                current_error
452            }
453        }
454    }
455}
456
457pub(crate) struct OperationGuard<'a, B: BackingStorage> {
458    backend: Option<&'a TurboTasksBackendInner<B>>,
459}
460
461impl<B: BackingStorage> Drop for OperationGuard<'_, B> {
462    fn drop(&mut self) {
463        if let Some(backend) = self.backend {
464            let fetch_sub = backend
465                .in_progress_operations
466                .fetch_sub(1, Ordering::AcqRel);
467            if fetch_sub - 1 == SNAPSHOT_REQUESTED_BIT {
468                backend.operations_suspended.notify_all();
469            }
470        }
471    }
472}
473
474/// Intermediate result of step 1 of task execution completion.
475struct TaskExecutionCompletePrepareResult {
476    pub new_children: FxHashSet<TaskId>,
477    pub is_now_immutable: bool,
478    #[cfg(feature = "verify_determinism")]
479    pub no_output_set: bool,
480    pub new_output: Option<OutputValue>,
481    pub output_dependent_tasks: SmallVec<[TaskId; 4]>,
482}
483
484// Operations
485impl<B: BackingStorage> TurboTasksBackendInner<B> {
486    /// # Safety
487    ///
488    /// `tx` must be a transaction from this TurboTasksBackendInner instance.
489    unsafe fn connect_child_with_tx<'l, 'tx: 'l>(
490        &'l self,
491        tx: Option<&'l B::ReadTransaction<'tx>>,
492        parent_task: Option<TaskId>,
493        child_task: TaskId,
494        task_type: Option<ArcOrOwned<CachedTaskType>>,
495        turbo_tasks: &'l dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
496    ) {
497        operation::ConnectChildOperation::run(parent_task, child_task, task_type, unsafe {
498            self.execute_context_with_tx(tx, turbo_tasks)
499        });
500    }
501
502    fn connect_child(
503        &self,
504        parent_task: Option<TaskId>,
505        child_task: TaskId,
506        task_type: Option<ArcOrOwned<CachedTaskType>>,
507        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
508    ) {
509        operation::ConnectChildOperation::run(
510            parent_task,
511            child_task,
512            task_type,
513            self.execute_context(turbo_tasks),
514        );
515    }
516
517    fn try_read_task_output(
518        self: &Arc<Self>,
519        task_id: TaskId,
520        reader: Option<TaskId>,
521        options: ReadOutputOptions,
522        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
523    ) -> Result<Result<RawVc, EventListener>> {
524        self.assert_not_persistent_calling_transient(reader, task_id, /* cell_id */ None);
525
526        let mut ctx = self.execute_context(turbo_tasks);
527        let need_reader_task = if self.should_track_dependencies()
528            && !matches!(options.tracking, ReadTracking::Untracked)
529            && reader.is_some_and(|reader_id| reader_id != task_id)
530            && let Some(reader_id) = reader
531            && reader_id != task_id
532        {
533            Some(reader_id)
534        } else {
535            None
536        };
537        let (mut task, mut reader_task) = if let Some(reader_id) = need_reader_task {
538            // Having a task_pair here is not optimal, but otherwise this would lead to a race
539            // condition. See below.
540            // TODO(sokra): solve that in a more performant way.
541            let (task, reader) = ctx.task_pair(task_id, reader_id, TaskDataCategory::All);
542            (task, Some(reader))
543        } else {
544            (ctx.task(task_id, TaskDataCategory::All), None)
545        };
546
547        fn listen_to_done_event(
548            reader_description: Option<EventDescription>,
549            tracking: ReadTracking,
550            done_event: &Event,
551        ) -> EventListener {
552            done_event.listen_with_note(move || {
553                move || {
554                    if let Some(reader_description) = reader_description.as_ref() {
555                        format!(
556                            "try_read_task_output from {} ({})",
557                            reader_description, tracking
558                        )
559                    } else {
560                        format!("try_read_task_output ({})", tracking)
561                    }
562                }
563            })
564        }
565
566        fn check_in_progress(
567            task: &impl TaskGuard,
568            reader_description: Option<EventDescription>,
569            tracking: ReadTracking,
570        ) -> Option<std::result::Result<std::result::Result<RawVc, EventListener>, anyhow::Error>>
571        {
572            match task.get_in_progress() {
573                Some(InProgressState::Scheduled { done_event, .. }) => Some(Ok(Err(
574                    listen_to_done_event(reader_description, tracking, done_event),
575                ))),
576                Some(InProgressState::InProgress(box InProgressStateInner {
577                    done_event, ..
578                })) => Some(Ok(Err(listen_to_done_event(
579                    reader_description,
580                    tracking,
581                    done_event,
582                )))),
583                Some(InProgressState::Canceled) => Some(Err(anyhow::anyhow!(
584                    "{} was canceled",
585                    task.get_task_description()
586                ))),
587                None => None,
588            }
589        }
590
591        if matches!(options.consistency, ReadConsistency::Strong) {
592            // Ensure it's an root node
593            loop {
594                let aggregation_number = get_aggregation_number(&task);
595                if is_root_node(aggregation_number) {
596                    break;
597                }
598                drop(task);
599                drop(reader_task);
600                {
601                    let _span = tracing::trace_span!(
602                        "make root node for strongly consistent read",
603                        %task_id
604                    )
605                    .entered();
606                    AggregationUpdateQueue::run(
607                        AggregationUpdateJob::UpdateAggregationNumber {
608                            task_id,
609                            base_aggregation_number: u32::MAX,
610                            distance: None,
611                        },
612                        &mut ctx,
613                    );
614                }
615                (task, reader_task) = if let Some(reader_id) = need_reader_task {
616                    // TODO(sokra): see comment above
617                    let (task, reader) = ctx.task_pair(task_id, reader_id, TaskDataCategory::All);
618                    (task, Some(reader))
619                } else {
620                    (ctx.task(task_id, TaskDataCategory::All), None)
621                }
622            }
623
624            let is_dirty = task.is_dirty();
625
626            // Check the dirty count of the root node
627            let has_dirty_containers = task.has_dirty_containers();
628            if has_dirty_containers || is_dirty.is_some() {
629                let activeness = task.get_activeness_mut();
630                let mut task_ids_to_schedule: Vec<_> = Vec::new();
631                // When there are dirty task, subscribe to the all_clean_event
632                let activeness = if let Some(activeness) = activeness {
633                    // This makes sure all tasks stay active and this task won't stale.
634                    // active_until_clean is automatically removed when this
635                    // task is clean.
636                    activeness.set_active_until_clean();
637                    activeness
638                } else {
639                    // If we don't have a root state, add one. This also makes sure all tasks stay
640                    // active and this task won't stale. active_until_clean
641                    // is automatically removed when this task is clean.
642                    if ctx.should_track_activeness() {
643                        // A newly added Activeness need to make sure to schedule the tasks
644                        task_ids_to_schedule = task.dirty_containers().collect();
645                        task_ids_to_schedule.push(task_id);
646                    }
647                    let activeness =
648                        task.get_activeness_mut_or_insert_with(|| ActivenessState::new(task_id));
649                    activeness.set_active_until_clean();
650                    activeness
651                };
652                let listener = activeness.all_clean_event.listen_with_note(move || {
653                    let this = self.clone();
654                    let tt = turbo_tasks.pin();
655                    move || {
656                        let tt: &dyn TurboTasksBackendApi<TurboTasksBackend<B>> = &*tt;
657                        let mut ctx = this.execute_context(tt);
658                        let mut visited = FxHashSet::default();
659                        fn indent(s: &str) -> String {
660                            s.split_inclusive('\n')
661                                .flat_map(|line: &str| ["  ", line].into_iter())
662                                .collect::<String>()
663                        }
664                        fn get_info(
665                            ctx: &mut impl ExecuteContext<'_>,
666                            task_id: TaskId,
667                            parent_and_count: Option<(TaskId, i32)>,
668                            visited: &mut FxHashSet<TaskId>,
669                        ) -> String {
670                            let task = ctx.task(task_id, TaskDataCategory::All);
671                            let is_dirty = task.is_dirty();
672                            let in_progress =
673                                task.get_in_progress()
674                                    .map_or("not in progress", |p| match p {
675                                        InProgressState::InProgress(_) => "in progress",
676                                        InProgressState::Scheduled { .. } => "scheduled",
677                                        InProgressState::Canceled => "canceled",
678                                    });
679                            let activeness = task.get_activeness().map_or_else(
680                                || "not active".to_string(),
681                                |activeness| format!("{activeness:?}"),
682                            );
683                            let aggregation_number = get_aggregation_number(&task);
684                            let missing_upper = if let Some((parent_task_id, _)) = parent_and_count
685                            {
686                                let uppers = get_uppers(&task);
687                                !uppers.contains(&parent_task_id)
688                            } else {
689                                false
690                            };
691
692                            // Check the dirty count of the root node
693                            let has_dirty_containers = task.has_dirty_containers();
694
695                            let task_description = task.get_task_description();
696                            let is_dirty_label = if let Some(parent_priority) = is_dirty {
697                                format!(", dirty({parent_priority})")
698                            } else {
699                                String::new()
700                            };
701                            let has_dirty_containers_label = if has_dirty_containers {
702                                ", dirty containers"
703                            } else {
704                                ""
705                            };
706                            let count = if let Some((_, count)) = parent_and_count {
707                                format!(" {count}")
708                            } else {
709                                String::new()
710                            };
711                            let mut info = format!(
712                                "{task_id} {task_description}{count} (aggr={aggregation_number}, \
713                                 {in_progress}, \
714                                 {activeness}{is_dirty_label}{has_dirty_containers_label})",
715                            );
716                            let children: Vec<_> = task.dirty_containers_with_count().collect();
717                            drop(task);
718
719                            if missing_upper {
720                                info.push_str("\n  ERROR: missing upper connection");
721                            }
722
723                            if has_dirty_containers || !children.is_empty() {
724                                writeln!(info, "\n  dirty tasks:").unwrap();
725
726                                for (child_task_id, count) in children {
727                                    let task_description = ctx
728                                        .task(child_task_id, TaskDataCategory::Data)
729                                        .get_task_description();
730                                    if visited.insert(child_task_id) {
731                                        let child_info = get_info(
732                                            ctx,
733                                            child_task_id,
734                                            Some((task_id, count)),
735                                            visited,
736                                        );
737                                        info.push_str(&indent(&child_info));
738                                        if !info.ends_with('\n') {
739                                            info.push('\n');
740                                        }
741                                    } else {
742                                        writeln!(
743                                            info,
744                                            "  {child_task_id} {task_description} {count} \
745                                             (already visited)"
746                                        )
747                                        .unwrap();
748                                    }
749                                }
750                            }
751                            info
752                        }
753                        let info = get_info(&mut ctx, task_id, None, &mut visited);
754                        format!(
755                            "try_read_task_output (strongly consistent) from {reader:?}\n{info}"
756                        )
757                    }
758                });
759                drop(reader_task);
760                drop(task);
761                if !task_ids_to_schedule.is_empty() {
762                    let mut queue = AggregationUpdateQueue::new();
763                    queue.extend_find_and_schedule_dirty(task_ids_to_schedule);
764                    queue.execute(&mut ctx);
765                }
766
767                return Ok(Err(listener));
768            }
769        }
770
771        let reader_description = reader_task
772            .as_ref()
773            .map(|r| EventDescription::new(|| r.get_task_desc_fn()));
774        if let Some(value) = check_in_progress(&task, reader_description.clone(), options.tracking)
775        {
776            return value;
777        }
778
779        if let Some(output) = task.get_output() {
780            let result = match output {
781                OutputValue::Cell(cell) => Ok(Ok(RawVc::TaskCell(cell.task, cell.cell))),
782                OutputValue::Output(task) => Ok(Ok(RawVc::TaskOutput(*task))),
783                OutputValue::Error(error) => Err(error.clone()),
784            };
785            if let Some(mut reader_task) = reader_task.take()
786                && options.tracking.should_track(result.is_err())
787                && (!task.immutable() || cfg!(feature = "verify_immutable"))
788            {
789                #[cfg(feature = "trace_task_output_dependencies")]
790                let _span = tracing::trace_span!(
791                    "add output dependency",
792                    task = %task_id,
793                    dependent_task = ?reader
794                )
795                .entered();
796                let mut queue = LeafDistanceUpdateQueue::new();
797                let reader = reader.unwrap();
798                if task.add_output_dependent(reader) {
799                    // Ensure that dependent leaf distance is strictly monotonic increasing
800                    let leaf_distance = task.get_leaf_distance().copied().unwrap_or_default();
801                    let reader_leaf_distance =
802                        reader_task.get_leaf_distance().copied().unwrap_or_default();
803                    if reader_leaf_distance.distance <= leaf_distance.distance {
804                        queue.push(
805                            reader,
806                            leaf_distance.distance,
807                            leaf_distance.max_distance_in_buffer,
808                        );
809                    }
810                }
811
812                drop(task);
813
814                // Note: We use `task_pair` earlier to lock the task and its reader at the same
815                // time. If we didn't and just locked the reader here, an invalidation could occur
816                // between grabbing the locks. If that happened, and if the task is "outdated" or
817                // doesn't have the dependency edge yet, the invalidation would be lost.
818
819                if !reader_task.remove_outdated_output_dependencies(&task_id) {
820                    let _ = reader_task.add_output_dependencies(task_id);
821                }
822                drop(reader_task);
823
824                queue.execute(&mut ctx);
825            } else {
826                drop(task);
827            }
828
829            return result.map_err(|error| {
830                self.task_error_to_turbo_tasks_execution_error(&error, &mut ctx)
831                    .with_task_context(task_id, turbo_tasks.pin())
832                    .into()
833            });
834        }
835        drop(reader_task);
836
837        let note = EventDescription::new(|| {
838            move || {
839                if let Some(reader) = reader_description.as_ref() {
840                    format!("try_read_task_output (recompute) from {reader}",)
841                } else {
842                    "try_read_task_output (recompute, untracked)".to_string()
843                }
844            }
845        });
846
847        // Output doesn't exist. We need to schedule the task to compute it.
848        let (in_progress_state, listener) = InProgressState::new_scheduled_with_listener(
849            TaskExecutionReason::OutputNotAvailable,
850            EventDescription::new(|| task.get_task_desc_fn()),
851            note,
852        );
853
854        // It's not possible that the task is InProgress at this point. If it is InProgress {
855        // done: true } it must have Output and would early return.
856        let old = task.set_in_progress(in_progress_state);
857        debug_assert!(old.is_none(), "InProgress already exists");
858        ctx.schedule_task(task, TaskPriority::Initial);
859
860        Ok(Err(listener))
861    }
862
863    fn try_read_task_cell(
864        &self,
865        task_id: TaskId,
866        reader: Option<TaskId>,
867        cell: CellId,
868        options: ReadCellOptions,
869        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
870    ) -> Result<Result<TypedCellContent, EventListener>> {
871        self.assert_not_persistent_calling_transient(reader, task_id, Some(cell));
872
873        fn add_cell_dependency(
874            task_id: TaskId,
875            mut task: impl TaskGuard,
876            reader: Option<TaskId>,
877            reader_task: Option<impl TaskGuard>,
878            cell: CellId,
879            key: Option<u64>,
880        ) {
881            if let Some(mut reader_task) = reader_task
882                && (!task.immutable() || cfg!(feature = "verify_immutable"))
883            {
884                let reader = reader.unwrap();
885                let _ = task.add_cell_dependents((cell, key, reader));
886                drop(task);
887
888                // Note: We use `task_pair` earlier to lock the task and its reader at the same
889                // time. If we didn't and just locked the reader here, an invalidation could occur
890                // between grabbing the locks. If that happened, and if the task is "outdated" or
891                // doesn't have the dependency edge yet, the invalidation would be lost.
892
893                let target = CellRef {
894                    task: task_id,
895                    cell,
896                };
897                if !reader_task.remove_outdated_cell_dependencies(&(target, key)) {
898                    let _ = reader_task.add_cell_dependencies((target, key));
899                }
900                drop(reader_task);
901            }
902        }
903
904        let ReadCellOptions {
905            is_serializable_cell_content,
906            tracking,
907            final_read_hint,
908        } = options;
909
910        let mut ctx = self.execute_context(turbo_tasks);
911        let (mut task, reader_task) = if self.should_track_dependencies()
912            && !matches!(tracking, ReadCellTracking::Untracked)
913            && let Some(reader_id) = reader
914            && reader_id != task_id
915        {
916            // Having a task_pair here is not optimal, but otherwise this would lead to a race
917            // condition. See below.
918            // TODO(sokra): solve that in a more performant way.
919            let (task, reader) = ctx.task_pair(task_id, reader_id, TaskDataCategory::All);
920            (task, Some(reader))
921        } else {
922            (ctx.task(task_id, TaskDataCategory::All), None)
923        };
924
925        let content = if final_read_hint {
926            task.remove_cell_data(is_serializable_cell_content, cell)
927        } else {
928            task.get_cell_data(is_serializable_cell_content, cell)
929        };
930        if let Some(content) = content {
931            if tracking.should_track(false) {
932                add_cell_dependency(task_id, task, reader, reader_task, cell, tracking.key());
933            }
934            return Ok(Ok(TypedCellContent(
935                cell.type_id,
936                CellContent(Some(content.reference)),
937            )));
938        }
939
940        let in_progress = task.get_in_progress();
941        if matches!(
942            in_progress,
943            Some(InProgressState::InProgress(..) | InProgressState::Scheduled { .. })
944        ) {
945            return Ok(Err(self
946                .listen_to_cell(&mut task, task_id, &reader_task, cell)
947                .0));
948        }
949        let is_cancelled = matches!(in_progress, Some(InProgressState::Canceled));
950
951        // Check cell index range (cell might not exist at all)
952        let max_id = task.get_cell_type_max_index(&cell.type_id).copied();
953        let Some(max_id) = max_id else {
954            let task_desc = task.get_task_description();
955            if tracking.should_track(true) {
956                add_cell_dependency(task_id, task, reader, reader_task, cell, tracking.key());
957            }
958            bail!(
959                "Cell {cell:?} no longer exists in task {task_desc} (no cell of this type exists)",
960            );
961        };
962        if cell.index >= max_id {
963            let task_desc = task.get_task_description();
964            if tracking.should_track(true) {
965                add_cell_dependency(task_id, task, reader, reader_task, cell, tracking.key());
966            }
967            bail!("Cell {cell:?} no longer exists in task {task_desc} (index out of bounds)");
968        }
969
970        // Cell should exist, but data was dropped or is not serializable. We need to recompute the
971        // task the get the cell content.
972
973        // Listen to the cell and potentially schedule the task
974        let (listener, new_listener) = self.listen_to_cell(&mut task, task_id, &reader_task, cell);
975        drop(reader_task);
976        if !new_listener {
977            return Ok(Err(listener));
978        }
979
980        let _span = tracing::trace_span!(
981            "recomputation",
982            cell_type = get_value_type(cell.type_id).global_name,
983            cell_index = cell.index
984        )
985        .entered();
986
987        // Schedule the task, if not already scheduled
988        if is_cancelled {
989            bail!("{} was canceled", task.get_task_description());
990        }
991
992        let _ = task.add_scheduled(
993            TaskExecutionReason::CellNotAvailable,
994            EventDescription::new(|| task.get_task_desc_fn()),
995        );
996        ctx.schedule_task(task, TaskPriority::Initial);
997
998        Ok(Err(listener))
999    }
1000
1001    fn listen_to_cell(
1002        &self,
1003        task: &mut impl TaskGuard,
1004        task_id: TaskId,
1005        reader_task: &Option<impl TaskGuard>,
1006        cell: CellId,
1007    ) -> (EventListener, bool) {
1008        let note = || {
1009            let reader_desc = reader_task.as_ref().map(|r| r.get_task_desc_fn());
1010            move || {
1011                if let Some(reader_desc) = reader_desc.as_ref() {
1012                    format!("try_read_task_cell (in progress) from {}", (reader_desc)())
1013                } else {
1014                    "try_read_task_cell (in progress, untracked)".to_string()
1015                }
1016            }
1017        };
1018        if let Some(in_progress) = task.get_in_progress_cells(&cell) {
1019            // Someone else is already computing the cell
1020            let listener = in_progress.event.listen_with_note(note);
1021            return (listener, false);
1022        }
1023        let in_progress = InProgressCellState::new(task_id, cell);
1024        let listener = in_progress.event.listen_with_note(note);
1025        let old = task.insert_in_progress_cells(cell, in_progress);
1026        debug_assert!(old.is_none(), "InProgressCell already exists");
1027        (listener, true)
1028    }
1029
1030    fn snapshot_and_persist(
1031        &self,
1032        parent_span: Option<tracing::Id>,
1033        reason: &str,
1034        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
1035    ) -> Option<(Instant, bool)> {
1036        let snapshot_span =
1037            tracing::trace_span!(parent: parent_span.clone(), "snapshot", reason = reason)
1038                .entered();
1039        let start = Instant::now();
1040        debug_assert!(self.should_persist());
1041
1042        let suspended_operations;
1043        {
1044            let _span = tracing::info_span!("blocking").entered();
1045            let mut snapshot_request = self.snapshot_request.lock();
1046            snapshot_request.snapshot_requested = true;
1047            let active_operations = self
1048                .in_progress_operations
1049                .fetch_or(SNAPSHOT_REQUESTED_BIT, Ordering::Relaxed);
1050            if active_operations != 0 {
1051                self.operations_suspended
1052                    .wait_while(&mut snapshot_request, |_| {
1053                        self.in_progress_operations.load(Ordering::Relaxed)
1054                            != SNAPSHOT_REQUESTED_BIT
1055                    });
1056            }
1057            suspended_operations = snapshot_request
1058                .suspended_operations
1059                .iter()
1060                .map(|op| op.arc().clone())
1061                .collect::<Vec<_>>();
1062        }
1063        self.storage.start_snapshot();
1064        let mut persisted_task_cache_log = self
1065            .persisted_task_cache_log
1066            .as_ref()
1067            .map(|l| l.take(|i| i))
1068            .unwrap_or_default();
1069        let mut snapshot_request = self.snapshot_request.lock();
1070        snapshot_request.snapshot_requested = false;
1071        self.in_progress_operations
1072            .fetch_sub(SNAPSHOT_REQUESTED_BIT, Ordering::Relaxed);
1073        self.snapshot_completed.notify_all();
1074        let snapshot_time = Instant::now();
1075        drop(snapshot_request);
1076
1077        #[cfg(feature = "print_cache_item_size")]
1078        #[derive(Default)]
1079        struct TaskCacheStats {
1080            data: usize,
1081            data_compressed: usize,
1082            data_count: usize,
1083            meta: usize,
1084            meta_compressed: usize,
1085            meta_count: usize,
1086            upper_count: usize,
1087            collectibles_count: usize,
1088            aggregated_collectibles_count: usize,
1089            children_count: usize,
1090            followers_count: usize,
1091            collectibles_dependents_count: usize,
1092            aggregated_dirty_containers_count: usize,
1093            output_size: usize,
1094        }
1095        #[cfg(feature = "print_cache_item_size")]
1096        impl TaskCacheStats {
1097            fn compressed_size(data: &[u8]) -> Result<usize> {
1098                Ok(lzzzz::lz4::Compressor::new()?.next_to_vec(
1099                    data,
1100                    &mut Vec::new(),
1101                    lzzzz::lz4::ACC_LEVEL_DEFAULT,
1102                )?)
1103            }
1104
1105            fn add_data(&mut self, data: &[u8]) {
1106                self.data += data.len();
1107                self.data_compressed += Self::compressed_size(data).unwrap_or(0);
1108                self.data_count += 1;
1109            }
1110
1111            fn add_meta(&mut self, data: &[u8]) {
1112                self.meta += data.len();
1113                self.meta_compressed += Self::compressed_size(data).unwrap_or(0);
1114                self.meta_count += 1;
1115            }
1116
1117            fn add_counts(&mut self, storage: &TaskStorage) {
1118                let counts = storage.meta_counts();
1119                self.upper_count += counts.upper;
1120                self.collectibles_count += counts.collectibles;
1121                self.aggregated_collectibles_count += counts.aggregated_collectibles;
1122                self.children_count += counts.children;
1123                self.followers_count += counts.followers;
1124                self.collectibles_dependents_count += counts.collectibles_dependents;
1125                self.aggregated_dirty_containers_count += counts.aggregated_dirty_containers;
1126                if let Some(output) = storage.get_output() {
1127                    use turbo_bincode::turbo_bincode_encode;
1128
1129                    self.output_size += turbo_bincode_encode(&output)
1130                        .map(|data| data.len())
1131                        .unwrap_or(0);
1132                }
1133            }
1134        }
1135        #[cfg(feature = "print_cache_item_size")]
1136        let task_cache_stats: Mutex<FxHashMap<_, TaskCacheStats>> =
1137            Mutex::new(FxHashMap::default());
1138
1139        let preprocess = |task_id: TaskId, inner: &TaskStorage| {
1140            if task_id.is_transient() {
1141                return (None, None);
1142            }
1143
1144            let meta_restored = inner.flags.meta_restored();
1145            let data_restored = inner.flags.data_restored();
1146
1147            // Encode meta/data directly from TaskStorage
1148            let meta = meta_restored.then(|| inner.clone_meta_snapshot());
1149            let data = data_restored.then(|| inner.clone_data_snapshot());
1150
1151            (meta, data)
1152        };
1153        let process = |task_id: TaskId,
1154                       (meta, data): (Option<TaskStorage>, Option<TaskStorage>),
1155                       buffer: &mut TurboBincodeBuffer| {
1156            #[cfg(feature = "print_cache_item_size")]
1157            if let Some(ref m) = meta {
1158                task_cache_stats
1159                    .lock()
1160                    .entry(self.get_task_name(task_id, turbo_tasks))
1161                    .or_default()
1162                    .add_counts(m);
1163            }
1164            (
1165                task_id,
1166                meta.map(|d| encode_task_data(task_id, &d, SpecificTaskDataCategory::Meta, buffer)),
1167                data.map(|d| encode_task_data(task_id, &d, SpecificTaskDataCategory::Data, buffer)),
1168            )
1169        };
1170        let process_snapshot =
1171            |task_id: TaskId, inner: Box<TaskStorage>, buffer: &mut TurboBincodeBuffer| {
1172                if task_id.is_transient() {
1173                    return (task_id, None, None);
1174                }
1175
1176                #[cfg(feature = "print_cache_item_size")]
1177                if inner.flags.meta_modified() {
1178                    task_cache_stats
1179                        .lock()
1180                        .entry(self.get_task_name(task_id, turbo_tasks))
1181                        .or_default()
1182                        .add_counts(&inner);
1183                }
1184
1185                // Encode meta/data directly from TaskStorage snapshot
1186                (
1187                    task_id,
1188                    inner.flags.meta_modified().then(|| {
1189                        encode_task_data(task_id, &inner, SpecificTaskDataCategory::Meta, buffer)
1190                    }),
1191                    inner.flags.data_modified().then(|| {
1192                        encode_task_data(task_id, &inner, SpecificTaskDataCategory::Data, buffer)
1193                    }),
1194                )
1195            };
1196
1197        let snapshot = self
1198            .storage
1199            .take_snapshot(&preprocess, &process, &process_snapshot);
1200
1201        let task_snapshots = snapshot
1202            .into_iter()
1203            .filter_map(|iter| {
1204                let mut iter = iter
1205                    .filter_map(
1206                        |(task_id, meta, data): (
1207                            _,
1208                            Option<Result<SmallVec<_>>>,
1209                            Option<Result<SmallVec<_>>>,
1210                        )| {
1211                            let meta = match meta {
1212                                Some(Ok(meta)) => {
1213                                    #[cfg(feature = "print_cache_item_size")]
1214                                    task_cache_stats
1215                                        .lock()
1216                                        .entry(self.get_task_name(task_id, turbo_tasks))
1217                                        .or_default()
1218                                        .add_meta(&meta);
1219                                    Some(meta)
1220                                }
1221                                None => None,
1222                                Some(Err(err)) => {
1223                                    println!(
1224                                        "Serializing task {} failed (meta): {:?}",
1225                                        self.debug_get_task_description(task_id),
1226                                        err
1227                                    );
1228                                    None
1229                                }
1230                            };
1231                            let data = match data {
1232                                Some(Ok(data)) => {
1233                                    #[cfg(feature = "print_cache_item_size")]
1234                                    task_cache_stats
1235                                        .lock()
1236                                        .entry(self.get_task_name(task_id, turbo_tasks))
1237                                        .or_default()
1238                                        .add_data(&data);
1239                                    Some(data)
1240                                }
1241                                None => None,
1242                                Some(Err(err)) => {
1243                                    println!(
1244                                        "Serializing task {} failed (data): {:?}",
1245                                        self.debug_get_task_description(task_id),
1246                                        err
1247                                    );
1248                                    None
1249                                }
1250                            };
1251                            (meta.is_some() || data.is_some()).then_some((task_id, meta, data))
1252                        },
1253                    )
1254                    .peekable();
1255                iter.peek().is_some().then_some(iter)
1256            })
1257            .collect::<Vec<_>>();
1258
1259        swap_retain(&mut persisted_task_cache_log, |shard| !shard.is_empty());
1260
1261        drop(snapshot_span);
1262
1263        if persisted_task_cache_log.is_empty() && task_snapshots.is_empty() {
1264            return Some((snapshot_time, false));
1265        }
1266
1267        let _span = tracing::info_span!(parent: parent_span, "persist", reason = reason).entered();
1268        {
1269            if let Err(err) = self.backing_storage.save_snapshot(
1270                suspended_operations,
1271                persisted_task_cache_log,
1272                task_snapshots,
1273            ) {
1274                println!("Persisting failed: {err:?}");
1275                return None;
1276            }
1277            #[cfg(feature = "print_cache_item_size")]
1278            {
1279                let mut task_cache_stats = task_cache_stats
1280                    .into_inner()
1281                    .into_iter()
1282                    .collect::<Vec<_>>();
1283                if !task_cache_stats.is_empty() {
1284                    use turbo_tasks::util::FormatBytes;
1285
1286                    use crate::utils::markdown_table::print_markdown_table;
1287
1288                    task_cache_stats.sort_unstable_by(|(key_a, stats_a), (key_b, stats_b)| {
1289                        (stats_b.data_compressed + stats_b.meta_compressed, key_b)
1290                            .cmp(&(stats_a.data_compressed + stats_a.meta_compressed, key_a))
1291                    });
1292                    println!(
1293                        "Task cache stats: {} ({})",
1294                        FormatBytes(
1295                            task_cache_stats
1296                                .iter()
1297                                .map(|(_, s)| s.data_compressed + s.meta_compressed)
1298                                .sum::<usize>()
1299                        ),
1300                        FormatBytes(
1301                            task_cache_stats
1302                                .iter()
1303                                .map(|(_, s)| s.data + s.meta)
1304                                .sum::<usize>()
1305                        )
1306                    );
1307
1308                    print_markdown_table(
1309                        [
1310                            "Task",
1311                            " Total Size",
1312                            " Data Size",
1313                            " Data Count x Avg",
1314                            " Data Count x Avg",
1315                            " Meta Size",
1316                            " Meta Count x Avg",
1317                            " Meta Count x Avg",
1318                            " Uppers",
1319                            " Coll",
1320                            " Agg Coll",
1321                            " Children",
1322                            " Followers",
1323                            " Coll Deps",
1324                            " Agg Dirty",
1325                            " Output Size",
1326                        ],
1327                        task_cache_stats.iter(),
1328                        |(task_desc, stats)| {
1329                            [
1330                                task_desc.to_string(),
1331                                format!(
1332                                    " {} ({})",
1333                                    FormatBytes(stats.data_compressed + stats.meta_compressed),
1334                                    FormatBytes(stats.data + stats.meta)
1335                                ),
1336                                format!(
1337                                    " {} ({})",
1338                                    FormatBytes(stats.data_compressed),
1339                                    FormatBytes(stats.data)
1340                                ),
1341                                format!(" {} x", stats.data_count,),
1342                                format!(
1343                                    "{} ({})",
1344                                    FormatBytes(
1345                                        stats
1346                                            .data_compressed
1347                                            .checked_div(stats.data_count)
1348                                            .unwrap_or(0)
1349                                    ),
1350                                    FormatBytes(
1351                                        stats.data.checked_div(stats.data_count).unwrap_or(0)
1352                                    ),
1353                                ),
1354                                format!(
1355                                    " {} ({})",
1356                                    FormatBytes(stats.meta_compressed),
1357                                    FormatBytes(stats.meta)
1358                                ),
1359                                format!(" {} x", stats.meta_count,),
1360                                format!(
1361                                    "{} ({})",
1362                                    FormatBytes(
1363                                        stats
1364                                            .meta_compressed
1365                                            .checked_div(stats.meta_count)
1366                                            .unwrap_or(0)
1367                                    ),
1368                                    FormatBytes(
1369                                        stats.meta.checked_div(stats.meta_count).unwrap_or(0)
1370                                    ),
1371                                ),
1372                                format!(" {}", stats.upper_count),
1373                                format!(" {}", stats.collectibles_count),
1374                                format!(" {}", stats.aggregated_collectibles_count),
1375                                format!(" {}", stats.children_count),
1376                                format!(" {}", stats.followers_count),
1377                                format!(" {}", stats.collectibles_dependents_count),
1378                                format!(" {}", stats.aggregated_dirty_containers_count),
1379                                format!(" {}", FormatBytes(stats.output_size)),
1380                            ]
1381                        },
1382                    );
1383                }
1384            }
1385        }
1386
1387        let elapsed = start.elapsed();
1388        // avoid spamming the event queue with information about fast operations
1389        if elapsed > Duration::from_secs(10) {
1390            turbo_tasks.send_compilation_event(Arc::new(TimingEvent::new(
1391                "Finished writing to filesystem cache".to_string(),
1392                elapsed,
1393            )));
1394        }
1395
1396        Some((snapshot_time, true))
1397    }
1398
1399    fn startup(&self, turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>) {
1400        if self.should_restore() {
1401            // Continue all uncompleted operations
1402            // They can't be interrupted by a snapshot since the snapshotting job has not been
1403            // scheduled yet.
1404            let uncompleted_operations = self
1405                .backing_storage
1406                .uncompleted_operations()
1407                .expect("Failed to get uncompleted operations");
1408            if !uncompleted_operations.is_empty() {
1409                let mut ctx = self.execute_context(turbo_tasks);
1410                for op in uncompleted_operations {
1411                    op.execute(&mut ctx);
1412                }
1413            }
1414        }
1415
1416        // Only when it should write regularly to the storage, we schedule the initial snapshot
1417        // job.
1418        if matches!(self.options.storage_mode, Some(StorageMode::ReadWrite)) {
1419            // Schedule the snapshot job
1420            let _span = trace_span!("persisting background job").entered();
1421            let _span = tracing::info_span!("thread").entered();
1422            turbo_tasks.schedule_backend_background_job(TurboTasksBackendJob::InitialSnapshot);
1423        }
1424    }
1425
1426    fn stopping(&self) {
1427        self.stopping.store(true, Ordering::Release);
1428        self.stopping_event.notify(usize::MAX);
1429    }
1430
1431    #[allow(unused_variables)]
1432    fn stop(&self, turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>) {
1433        #[cfg(feature = "verify_aggregation_graph")]
1434        {
1435            self.is_idle.store(false, Ordering::Release);
1436            self.verify_aggregation_graph(turbo_tasks, false);
1437        }
1438        if self.should_persist() {
1439            self.snapshot_and_persist(Span::current().into(), "stop", turbo_tasks);
1440        }
1441        drop_contents(&self.task_cache);
1442        self.storage.drop_contents();
1443        if let Err(err) = self.backing_storage.shutdown() {
1444            println!("Shutting down failed: {err}");
1445        }
1446    }
1447
1448    #[allow(unused_variables)]
1449    fn idle_start(self: &Arc<Self>, turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>) {
1450        self.idle_start_event.notify(usize::MAX);
1451
1452        #[cfg(feature = "verify_aggregation_graph")]
1453        {
1454            use tokio::select;
1455
1456            self.is_idle.store(true, Ordering::Release);
1457            let this = self.clone();
1458            let turbo_tasks = turbo_tasks.pin();
1459            tokio::task::spawn(async move {
1460                select! {
1461                    _ = tokio::time::sleep(Duration::from_secs(5)) => {
1462                        // do nothing
1463                    }
1464                    _ = this.idle_end_event.listen() => {
1465                        return;
1466                    }
1467                }
1468                if !this.is_idle.load(Ordering::Relaxed) {
1469                    return;
1470                }
1471                this.verify_aggregation_graph(&*turbo_tasks, true);
1472            });
1473        }
1474    }
1475
1476    fn idle_end(&self) {
1477        #[cfg(feature = "verify_aggregation_graph")]
1478        self.is_idle.store(false, Ordering::Release);
1479        self.idle_end_event.notify(usize::MAX);
1480    }
1481
1482    fn get_or_create_persistent_task(
1483        &self,
1484        task_type: CachedTaskType,
1485        parent_task: Option<TaskId>,
1486        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
1487    ) -> TaskId {
1488        // First check if the task exists in the cache which only uses a read lock
1489        if let Some(task_id) = self.task_cache.get(&task_type) {
1490            let task_id = *task_id;
1491            self.track_cache_hit(&task_type);
1492            self.connect_child(
1493                parent_task,
1494                task_id,
1495                Some(ArcOrOwned::Owned(task_type)),
1496                turbo_tasks,
1497            );
1498            return task_id;
1499        }
1500
1501        let check_backing_storage =
1502            self.should_restore() && self.local_is_partial.load(Ordering::Acquire);
1503        let tx = check_backing_storage
1504            .then(|| self.backing_storage.start_read_transaction())
1505            .flatten();
1506        let (task_id, task_type) = {
1507            // Safety: `tx` is a valid transaction from `self.backend.backing_storage`.
1508            if let Some(task_id) = unsafe {
1509                check_backing_storage
1510                    .then(|| {
1511                        self.backing_storage
1512                            .forward_lookup_task_cache(tx.as_ref(), &task_type)
1513                            .expect("Failed to lookup task id")
1514                    })
1515                    .flatten()
1516            } {
1517                // Task exists in backing storage
1518                // So we only need to insert it into the in-memory cache
1519                self.track_cache_hit(&task_type);
1520                let task_type = match raw_entry(&self.task_cache, &task_type) {
1521                    RawEntry::Occupied(_) => ArcOrOwned::Owned(task_type),
1522                    RawEntry::Vacant(e) => {
1523                        let task_type = Arc::new(task_type);
1524                        e.insert(task_type.clone(), task_id);
1525                        ArcOrOwned::Arc(task_type)
1526                    }
1527                };
1528                (task_id, task_type)
1529            } else {
1530                // Task doesn't exist in memory cache or backing storage
1531                // So we might need to create a new task
1532                let (task_id, mut task_type) = match raw_entry(&self.task_cache, &task_type) {
1533                    RawEntry::Occupied(e) => {
1534                        let task_id = *e.get();
1535                        drop(e);
1536                        self.track_cache_hit(&task_type);
1537                        (task_id, ArcOrOwned::Owned(task_type))
1538                    }
1539                    RawEntry::Vacant(e) => {
1540                        let task_type = Arc::new(task_type);
1541                        let task_id = self.persisted_task_id_factory.get();
1542                        e.insert(task_type.clone(), task_id);
1543                        self.track_cache_miss(&task_type);
1544                        (task_id, ArcOrOwned::Arc(task_type))
1545                    }
1546                };
1547                if let Some(log) = &self.persisted_task_cache_log {
1548                    let task_type_arc: Arc<CachedTaskType> = Arc::from(task_type);
1549                    log.lock(task_id).push((task_type_arc.clone(), task_id));
1550                    task_type = ArcOrOwned::Arc(task_type_arc);
1551                }
1552                (task_id, task_type)
1553            }
1554        };
1555
1556        // Safety: `tx` is a valid transaction from `self.backend.backing_storage`.
1557        unsafe {
1558            self.connect_child_with_tx(
1559                tx.as_ref(),
1560                parent_task,
1561                task_id,
1562                Some(task_type),
1563                turbo_tasks,
1564            )
1565        };
1566
1567        task_id
1568    }
1569
1570    fn get_or_create_transient_task(
1571        &self,
1572        task_type: CachedTaskType,
1573        parent_task: Option<TaskId>,
1574        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
1575    ) -> TaskId {
1576        if let Some(parent_task) = parent_task
1577            && !parent_task.is_transient()
1578        {
1579            self.panic_persistent_calling_transient(
1580                self.debug_get_task_description(parent_task),
1581                Some(&task_type),
1582                /* cell_id */ None,
1583            );
1584        }
1585        // First check if the task exists in the cache which only uses a read lock
1586        if let Some(task_id) = self.task_cache.get(&task_type) {
1587            let task_id = *task_id;
1588            self.track_cache_hit(&task_type);
1589            self.connect_child(
1590                parent_task,
1591                task_id,
1592                Some(ArcOrOwned::Owned(task_type)),
1593                turbo_tasks,
1594            );
1595            return task_id;
1596        }
1597        // If not, acquire a write lock and double check / insert
1598        match raw_entry(&self.task_cache, &task_type) {
1599            RawEntry::Occupied(e) => {
1600                let task_id = *e.get();
1601                drop(e);
1602                self.track_cache_hit(&task_type);
1603                self.connect_child(
1604                    parent_task,
1605                    task_id,
1606                    Some(ArcOrOwned::Owned(task_type)),
1607                    turbo_tasks,
1608                );
1609                task_id
1610            }
1611            RawEntry::Vacant(e) => {
1612                let task_type = Arc::new(task_type);
1613                let task_id = self.transient_task_id_factory.get();
1614                e.insert(task_type.clone(), task_id);
1615                self.track_cache_miss(&task_type);
1616                self.connect_child(
1617                    parent_task,
1618                    task_id,
1619                    Some(ArcOrOwned::Arc(task_type)),
1620                    turbo_tasks,
1621                );
1622
1623                task_id
1624            }
1625        }
1626    }
1627
1628    /// Generate an object that implements [`fmt::Display`] explaining why the given
1629    /// [`CachedTaskType`] is transient.
1630    fn debug_trace_transient_task(
1631        &self,
1632        task_type: &CachedTaskType,
1633        cell_id: Option<CellId>,
1634    ) -> DebugTraceTransientTask {
1635        // it shouldn't be possible to have cycles in tasks, but we could have an exponential blowup
1636        // from tracing the same task many times, so use a visited_set
1637        fn inner_id(
1638            backend: &TurboTasksBackendInner<impl BackingStorage>,
1639            task_id: TaskId,
1640            cell_type_id: Option<ValueTypeId>,
1641            visited_set: &mut FxHashSet<TaskId>,
1642        ) -> DebugTraceTransientTask {
1643            if let Some(task_type) = backend.debug_get_cached_task_type(task_id) {
1644                if visited_set.contains(&task_id) {
1645                    let task_name = task_type.get_name();
1646                    DebugTraceTransientTask::Collapsed {
1647                        task_name,
1648                        cell_type_id,
1649                    }
1650                } else {
1651                    inner_cached(backend, &task_type, cell_type_id, visited_set)
1652                }
1653            } else {
1654                DebugTraceTransientTask::Uncached { cell_type_id }
1655            }
1656        }
1657        fn inner_cached(
1658            backend: &TurboTasksBackendInner<impl BackingStorage>,
1659            task_type: &CachedTaskType,
1660            cell_type_id: Option<ValueTypeId>,
1661            visited_set: &mut FxHashSet<TaskId>,
1662        ) -> DebugTraceTransientTask {
1663            let task_name = task_type.get_name();
1664
1665            let cause_self = task_type.this.and_then(|cause_self_raw_vc| {
1666                let Some(task_id) = cause_self_raw_vc.try_get_task_id() else {
1667                    // `task_id` should never be `None` at this point, as that would imply a
1668                    // non-local task is returning a local `Vc`...
1669                    // Just ignore if it happens, as we're likely already panicking.
1670                    return None;
1671                };
1672                if task_id.is_transient() {
1673                    Some(Box::new(inner_id(
1674                        backend,
1675                        task_id,
1676                        cause_self_raw_vc.try_get_type_id(),
1677                        visited_set,
1678                    )))
1679                } else {
1680                    None
1681                }
1682            });
1683            let cause_args = task_type
1684                .arg
1685                .get_raw_vcs()
1686                .into_iter()
1687                .filter_map(|raw_vc| {
1688                    let Some(task_id) = raw_vc.try_get_task_id() else {
1689                        // `task_id` should never be `None` (see comment above)
1690                        return None;
1691                    };
1692                    if !task_id.is_transient() {
1693                        return None;
1694                    }
1695                    Some((task_id, raw_vc.try_get_type_id()))
1696                })
1697                .collect::<IndexSet<_>>() // dedupe
1698                .into_iter()
1699                .map(|(task_id, cell_type_id)| {
1700                    inner_id(backend, task_id, cell_type_id, visited_set)
1701                })
1702                .collect();
1703
1704            DebugTraceTransientTask::Cached {
1705                task_name,
1706                cell_type_id,
1707                cause_self,
1708                cause_args,
1709            }
1710        }
1711        inner_cached(
1712            self,
1713            task_type,
1714            cell_id.map(|c| c.type_id),
1715            &mut FxHashSet::default(),
1716        )
1717    }
1718
1719    fn invalidate_task(
1720        &self,
1721        task_id: TaskId,
1722        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
1723    ) {
1724        if !self.should_track_dependencies() {
1725            panic!("Dependency tracking is disabled so invalidation is not allowed");
1726        }
1727        operation::InvalidateOperation::run(
1728            smallvec![task_id],
1729            #[cfg(feature = "trace_task_dirty")]
1730            TaskDirtyCause::Invalidator,
1731            self.execute_context(turbo_tasks),
1732        );
1733    }
1734
1735    fn invalidate_tasks(
1736        &self,
1737        tasks: &[TaskId],
1738        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
1739    ) {
1740        if !self.should_track_dependencies() {
1741            panic!("Dependency tracking is disabled so invalidation is not allowed");
1742        }
1743        operation::InvalidateOperation::run(
1744            tasks.iter().copied().collect(),
1745            #[cfg(feature = "trace_task_dirty")]
1746            TaskDirtyCause::Unknown,
1747            self.execute_context(turbo_tasks),
1748        );
1749    }
1750
1751    fn invalidate_tasks_set(
1752        &self,
1753        tasks: &AutoSet<TaskId, BuildHasherDefault<FxHasher>, 2>,
1754        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
1755    ) {
1756        if !self.should_track_dependencies() {
1757            panic!("Dependency tracking is disabled so invalidation is not allowed");
1758        }
1759        operation::InvalidateOperation::run(
1760            tasks.iter().copied().collect(),
1761            #[cfg(feature = "trace_task_dirty")]
1762            TaskDirtyCause::Unknown,
1763            self.execute_context(turbo_tasks),
1764        );
1765    }
1766
1767    fn invalidate_serialization(
1768        &self,
1769        task_id: TaskId,
1770        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
1771    ) {
1772        if task_id.is_transient() {
1773            return;
1774        }
1775        let mut ctx = self.execute_context(turbo_tasks);
1776        let mut task = ctx.task(task_id, TaskDataCategory::Data);
1777        task.invalidate_serialization();
1778    }
1779
1780    fn debug_get_task_description(&self, task_id: TaskId) -> String {
1781        let task = self.storage.access_mut(task_id);
1782        if let Some(value) = task.get_persistent_task_type() {
1783            format!("{task_id:?} {}", value)
1784        } else if let Some(value) = task.get_transient_task_type() {
1785            format!("{task_id:?} {}", value)
1786        } else {
1787            format!("{task_id:?} unknown")
1788        }
1789    }
1790
1791    fn get_task_name(
1792        &self,
1793        task_id: TaskId,
1794        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
1795    ) -> String {
1796        let mut ctx = self.execute_context(turbo_tasks);
1797        let task = ctx.task(task_id, TaskDataCategory::Data);
1798        if let Some(value) = task.get_persistent_task_type() {
1799            value.to_string()
1800        } else if let Some(value) = task.get_transient_task_type() {
1801            value.to_string()
1802        } else {
1803            "unknown".to_string()
1804        }
1805    }
1806
1807    fn debug_get_cached_task_type(&self, task_id: TaskId) -> Option<Arc<CachedTaskType>> {
1808        let task = self.storage.access_mut(task_id);
1809        task.get_persistent_task_type().cloned()
1810    }
1811
1812    fn task_execution_canceled(
1813        &self,
1814        task_id: TaskId,
1815        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
1816    ) {
1817        let mut ctx = self.execute_context(turbo_tasks);
1818        let mut task = ctx.task(task_id, TaskDataCategory::Data);
1819        if let Some(in_progress) = task.take_in_progress() {
1820            match in_progress {
1821                InProgressState::Scheduled {
1822                    done_event,
1823                    reason: _,
1824                } => done_event.notify(usize::MAX),
1825                InProgressState::InProgress(box InProgressStateInner { done_event, .. }) => {
1826                    done_event.notify(usize::MAX)
1827                }
1828                InProgressState::Canceled => {}
1829            }
1830        }
1831        let old = task.set_in_progress(InProgressState::Canceled);
1832        debug_assert!(old.is_none(), "InProgress already exists");
1833    }
1834
1835    fn try_start_task_execution(
1836        &self,
1837        task_id: TaskId,
1838        priority: TaskPriority,
1839        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
1840    ) -> Option<TaskExecutionSpec<'_>> {
1841        let execution_reason;
1842        let task_type;
1843        {
1844            let mut ctx = self.execute_context(turbo_tasks);
1845            let mut task = ctx.task(task_id, TaskDataCategory::All);
1846            task_type = task.get_task_type().to_owned();
1847            let once_task = matches!(task_type, TaskType::Transient(ref tt) if matches!(&**tt, TransientTask::Once(_)));
1848            if let Some(tasks) = task.prefetch() {
1849                drop(task);
1850                ctx.prepare_tasks(tasks);
1851                task = ctx.task(task_id, TaskDataCategory::All);
1852            }
1853            let in_progress = task.take_in_progress()?;
1854            let InProgressState::Scheduled { done_event, reason } = in_progress else {
1855                let old = task.set_in_progress(in_progress);
1856                debug_assert!(old.is_none(), "InProgress already exists");
1857                return None;
1858            };
1859            execution_reason = reason;
1860            let old = task.set_in_progress(InProgressState::InProgress(Box::new(
1861                InProgressStateInner {
1862                    stale: false,
1863                    once_task,
1864                    done_event,
1865                    session_dependent: false,
1866                    marked_as_completed: false,
1867                    new_children: Default::default(),
1868                },
1869            )));
1870            debug_assert!(old.is_none(), "InProgress already exists");
1871
1872            // Make all current collectibles outdated (remove left-over outdated collectibles)
1873            enum Collectible {
1874                Current(CollectibleRef, i32),
1875                Outdated(CollectibleRef),
1876            }
1877            let collectibles = task
1878                .iter_collectibles()
1879                .map(|(&collectible, &value)| Collectible::Current(collectible, value))
1880                .chain(
1881                    task.iter_outdated_collectibles()
1882                        .map(|(collectible, _count)| Collectible::Outdated(*collectible)),
1883                )
1884                .collect::<Vec<_>>();
1885            for collectible in collectibles {
1886                match collectible {
1887                    Collectible::Current(collectible, value) => {
1888                        let _ = task.insert_outdated_collectible(collectible, value);
1889                    }
1890                    Collectible::Outdated(collectible) => {
1891                        if task
1892                            .collectibles()
1893                            .is_none_or(|m| m.get(&collectible).is_none())
1894                        {
1895                            task.remove_outdated_collectibles(&collectible);
1896                        }
1897                    }
1898                }
1899            }
1900
1901            if self.should_track_dependencies() {
1902                // Make all dependencies outdated
1903                let cell_dependencies = task.iter_cell_dependencies().collect();
1904                task.set_outdated_cell_dependencies(cell_dependencies);
1905
1906                let outdated_output_dependencies = task.iter_output_dependencies().collect();
1907                task.set_outdated_output_dependencies(outdated_output_dependencies);
1908            }
1909        }
1910
1911        let (span, future) = match task_type {
1912            TaskType::Cached(task_type) => {
1913                let CachedTaskType {
1914                    native_fn,
1915                    this,
1916                    arg,
1917                } = &*task_type;
1918                (
1919                    native_fn.span(task_id.persistence(), execution_reason, priority),
1920                    native_fn.execute(*this, &**arg),
1921                )
1922            }
1923            TaskType::Transient(task_type) => {
1924                let span = tracing::trace_span!("turbo_tasks::root_task");
1925                let future = match &*task_type {
1926                    TransientTask::Root(f) => f(),
1927                    TransientTask::Once(future_mutex) => take(&mut *future_mutex.lock())?,
1928                };
1929                (span, future)
1930            }
1931        };
1932        Some(TaskExecutionSpec { future, span })
1933    }
1934
1935    fn task_execution_completed(
1936        &self,
1937        task_id: TaskId,
1938        result: Result<RawVc, TurboTasksExecutionError>,
1939        cell_counters: &AutoMap<ValueTypeId, u32, BuildHasherDefault<FxHasher>, 8>,
1940        has_invalidator: bool,
1941        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
1942    ) -> bool {
1943        // Task completion is a 4 step process:
1944        // 1. Remove old edges (dependencies, collectibles, children, cells) and update the
1945        //    aggregation number of the task and the new children.
1946        // 2. Connect the new children to the task (and do the relevant aggregation updates).
1947        // 3. Remove dirty flag (and propagate that to uppers) and remove the in-progress state.
1948        // 4. Shrink the task memory to reduce footprint of the task.
1949
1950        // Due to persistence it is possible that the process is cancelled after any step. This is
1951        // ok, since the dirty flag won't be removed until step 3 and step 4 is only affecting the
1952        // in-memory representation.
1953
1954        // The task might be invalidated during this process, so we need to check the stale flag
1955        // at the start of every step.
1956
1957        #[cfg(not(feature = "trace_task_details"))]
1958        let span = tracing::trace_span!(
1959            "task execution completed",
1960            new_children = tracing::field::Empty
1961        )
1962        .entered();
1963        #[cfg(feature = "trace_task_details")]
1964        let span = tracing::trace_span!(
1965            "task execution completed",
1966            task_id = display(task_id),
1967            result = match result.as_ref() {
1968                Ok(value) => display(either::Either::Left(value)),
1969                Err(err) => display(either::Either::Right(err)),
1970            },
1971            new_children = tracing::field::Empty,
1972            immutable = tracing::field::Empty,
1973            new_output = tracing::field::Empty,
1974            output_dependents = tracing::field::Empty,
1975            stale = tracing::field::Empty,
1976        )
1977        .entered();
1978
1979        let is_error = result.is_err();
1980
1981        let mut ctx = self.execute_context(turbo_tasks);
1982
1983        let Some(TaskExecutionCompletePrepareResult {
1984            new_children,
1985            is_now_immutable,
1986            #[cfg(feature = "verify_determinism")]
1987            no_output_set,
1988            new_output,
1989            output_dependent_tasks,
1990        }) = self.task_execution_completed_prepare(
1991            &mut ctx,
1992            #[cfg(feature = "trace_task_details")]
1993            &span,
1994            task_id,
1995            result,
1996            cell_counters,
1997            has_invalidator,
1998        )
1999        else {
2000            // Task was stale and has been rescheduled
2001            #[cfg(feature = "trace_task_details")]
2002            span.record("stale", "prepare");
2003            return true;
2004        };
2005
2006        #[cfg(feature = "trace_task_details")]
2007        span.record("new_output", new_output.is_some());
2008        #[cfg(feature = "trace_task_details")]
2009        span.record("output_dependents", output_dependent_tasks.len());
2010
2011        // When restoring from filesystem cache the following might not be executed (since we can
2012        // suspend in `CleanupOldEdgesOperation`), but that's ok as the task is still dirty and
2013        // would be executed again.
2014
2015        if !output_dependent_tasks.is_empty() {
2016            self.task_execution_completed_invalidate_output_dependent(
2017                &mut ctx,
2018                task_id,
2019                output_dependent_tasks,
2020            );
2021        }
2022
2023        let has_new_children = !new_children.is_empty();
2024        span.record("new_children", new_children.len());
2025
2026        if has_new_children {
2027            self.task_execution_completed_unfinished_children_dirty(&mut ctx, &new_children)
2028        }
2029
2030        if has_new_children
2031            && self.task_execution_completed_connect(&mut ctx, task_id, new_children)
2032        {
2033            // Task was stale and has been rescheduled
2034            #[cfg(feature = "trace_task_details")]
2035            span.record("stale", "connect");
2036            return true;
2037        }
2038
2039        let (stale, in_progress_cells) = self.task_execution_completed_finish(
2040            &mut ctx,
2041            task_id,
2042            #[cfg(feature = "verify_determinism")]
2043            no_output_set,
2044            new_output,
2045            is_now_immutable,
2046        );
2047        if stale {
2048            // Task was stale and has been rescheduled
2049            #[cfg(feature = "trace_task_details")]
2050            span.record("stale", "finish");
2051            return true;
2052        }
2053
2054        let removed_data =
2055            self.task_execution_completed_cleanup(&mut ctx, task_id, cell_counters, is_error);
2056
2057        // Drop data outside of critical sections
2058        drop(removed_data);
2059        drop(in_progress_cells);
2060
2061        false
2062    }
2063
2064    fn task_execution_completed_prepare(
2065        &self,
2066        ctx: &mut impl ExecuteContext<'_>,
2067        #[cfg(feature = "trace_task_details")] span: &Span,
2068        task_id: TaskId,
2069        result: Result<RawVc, TurboTasksExecutionError>,
2070        cell_counters: &AutoMap<ValueTypeId, u32, BuildHasherDefault<FxHasher>, 8>,
2071        has_invalidator: bool,
2072    ) -> Option<TaskExecutionCompletePrepareResult> {
2073        let mut task = ctx.task(task_id, TaskDataCategory::All);
2074        let Some(in_progress) = task.get_in_progress_mut() else {
2075            panic!("Task execution completed, but task is not in progress: {task:#?}");
2076        };
2077        if matches!(in_progress, InProgressState::Canceled) {
2078            return Some(TaskExecutionCompletePrepareResult {
2079                new_children: Default::default(),
2080                is_now_immutable: false,
2081                #[cfg(feature = "verify_determinism")]
2082                no_output_set: false,
2083                new_output: None,
2084                output_dependent_tasks: Default::default(),
2085            });
2086        }
2087        let &mut InProgressState::InProgress(box InProgressStateInner {
2088            stale,
2089            ref mut new_children,
2090            session_dependent,
2091            once_task: is_once_task,
2092            ..
2093        }) = in_progress
2094        else {
2095            panic!("Task execution completed, but task is not in progress: {task:#?}");
2096        };
2097
2098        // If the task is stale, reschedule it
2099        #[cfg(not(feature = "no_fast_stale"))]
2100        if stale && !is_once_task {
2101            let Some(InProgressState::InProgress(box InProgressStateInner {
2102                done_event,
2103                mut new_children,
2104                ..
2105            })) = task.take_in_progress()
2106            else {
2107                unreachable!();
2108            };
2109            let old = task.set_in_progress(InProgressState::Scheduled {
2110                done_event,
2111                reason: TaskExecutionReason::Stale,
2112            });
2113            debug_assert!(old.is_none(), "InProgress already exists");
2114            // Remove old children from new_children to leave only the children that had their
2115            // active count increased
2116            for task in task.iter_children() {
2117                new_children.remove(&task);
2118            }
2119            drop(task);
2120
2121            // We need to undo the active count increase for the children since we throw away the
2122            // new_children list now.
2123            AggregationUpdateQueue::run(
2124                AggregationUpdateJob::DecreaseActiveCounts {
2125                    task_ids: new_children.into_iter().collect(),
2126                },
2127                ctx,
2128            );
2129            return None;
2130        }
2131
2132        // take the children from the task to process them
2133        let mut new_children = take(new_children);
2134
2135        // handle has_invalidator
2136        if has_invalidator {
2137            task.set_invalidator(true);
2138        }
2139
2140        // handle cell counters: update max index and remove cells that are no longer used
2141        let old_counters: FxHashMap<_, _> = task
2142            .iter_cell_type_max_index()
2143            .map(|(&k, &v)| (k, v))
2144            .collect();
2145        let mut counters_to_remove = old_counters.clone();
2146
2147        for (&cell_type, &max_index) in cell_counters.iter() {
2148            if let Some(old_max_index) = counters_to_remove.remove(&cell_type) {
2149                if old_max_index != max_index {
2150                    task.insert_cell_type_max_index(cell_type, max_index);
2151                }
2152            } else {
2153                task.insert_cell_type_max_index(cell_type, max_index);
2154            }
2155        }
2156        for (cell_type, _) in counters_to_remove {
2157            task.remove_cell_type_max_index(&cell_type);
2158        }
2159
2160        let mut queue = AggregationUpdateQueue::new();
2161
2162        let mut old_edges = Vec::new();
2163
2164        let has_children = !new_children.is_empty();
2165        let is_immutable = task.immutable();
2166        let task_dependencies_for_immutable =
2167            // Task was previously marked as immutable
2168            if !is_immutable
2169            // Task is not session dependent (session dependent tasks can change between sessions)
2170            && !session_dependent
2171            // Task has no invalidator
2172            && !task.invalidator()
2173            // Task has no dependencies on collectibles
2174            && task.is_collectibles_dependencies_empty()
2175        {
2176            Some(
2177                // Collect all dependencies on tasks to check if all dependencies are immutable
2178                task.iter_output_dependencies()
2179                    .chain(task.iter_cell_dependencies().map(|(target, _key)| target.task))
2180                    .collect::<FxHashSet<_>>(),
2181            )
2182        } else {
2183            None
2184        };
2185
2186        if has_children {
2187            // Prepare all new children
2188            prepare_new_children(task_id, &mut task, &new_children, &mut queue);
2189
2190            // Filter actual new children
2191            old_edges.extend(
2192                task.iter_children()
2193                    .filter(|task| !new_children.remove(task))
2194                    .map(OutdatedEdge::Child),
2195            );
2196        } else {
2197            old_edges.extend(task.iter_children().map(OutdatedEdge::Child));
2198        }
2199
2200        old_edges.extend(
2201            task.iter_outdated_collectibles()
2202                .map(|(&collectible, &count)| OutdatedEdge::Collectible(collectible, count)),
2203        );
2204
2205        if self.should_track_dependencies() {
2206            // IMPORTANT: Use iter_outdated_* here, NOT iter_* (active dependencies).
2207            // At execution start, active deps are copied to outdated as a "before" snapshot.
2208            // During execution, new deps are added to active.
2209            // Here at completion, we clean up only the OUTDATED deps (the "before" snapshot).
2210            // Using iter_* (active) instead would incorrectly clean up deps that are still valid,
2211            // breaking dependency tracking.
2212            old_edges.extend(
2213                task.iter_outdated_cell_dependencies()
2214                    .map(|(target, key)| OutdatedEdge::CellDependency(target, key)),
2215            );
2216            old_edges.extend(
2217                task.iter_outdated_output_dependencies()
2218                    .map(OutdatedEdge::OutputDependency),
2219            );
2220        }
2221
2222        // Check if output need to be updated
2223        let current_output = task.get_output();
2224        #[cfg(feature = "verify_determinism")]
2225        let no_output_set = current_output.is_none();
2226        let new_output = match result {
2227            Ok(RawVc::TaskOutput(output_task_id)) => {
2228                if let Some(OutputValue::Output(current_task_id)) = current_output
2229                    && *current_task_id == output_task_id
2230                {
2231                    None
2232                } else {
2233                    Some(OutputValue::Output(output_task_id))
2234                }
2235            }
2236            Ok(RawVc::TaskCell(output_task_id, cell)) => {
2237                if let Some(OutputValue::Cell(CellRef {
2238                    task: current_task_id,
2239                    cell: current_cell,
2240                })) = current_output
2241                    && *current_task_id == output_task_id
2242                    && *current_cell == cell
2243                {
2244                    None
2245                } else {
2246                    Some(OutputValue::Cell(CellRef {
2247                        task: output_task_id,
2248                        cell,
2249                    }))
2250                }
2251            }
2252            Ok(RawVc::LocalOutput(..)) => {
2253                panic!("Non-local tasks must not return a local Vc");
2254            }
2255            Err(err) => {
2256                if let Some(OutputValue::Error(old_error)) = current_output
2257                    && **old_error == err
2258                {
2259                    None
2260                } else {
2261                    Some(OutputValue::Error(Arc::new((&err).into())))
2262                }
2263            }
2264        };
2265        let mut output_dependent_tasks = SmallVec::<[_; 4]>::new();
2266        // When output has changed, grab the dependent tasks
2267        if new_output.is_some() && ctx.should_track_dependencies() {
2268            output_dependent_tasks = task.iter_output_dependent().collect();
2269        }
2270
2271        drop(task);
2272
2273        // Check if the task can be marked as immutable
2274        let mut is_now_immutable = false;
2275        if let Some(dependencies) = task_dependencies_for_immutable
2276            && dependencies
2277                .iter()
2278                .all(|&task_id| ctx.task(task_id, TaskDataCategory::Data).immutable())
2279        {
2280            is_now_immutable = true;
2281        }
2282        #[cfg(feature = "trace_task_details")]
2283        span.record("immutable", is_immutable || is_now_immutable);
2284
2285        if !queue.is_empty() || !old_edges.is_empty() {
2286            #[cfg(feature = "trace_task_completion")]
2287            let _span = tracing::trace_span!("remove old edges and prepare new children").entered();
2288            // Remove outdated edges first, before removing in_progress+dirty flag.
2289            // We need to make sure all outdated edges are removed before the task can potentially
2290            // be scheduled and executed again
2291            CleanupOldEdgesOperation::run(task_id, old_edges, queue, ctx);
2292        }
2293
2294        Some(TaskExecutionCompletePrepareResult {
2295            new_children,
2296            is_now_immutable,
2297            #[cfg(feature = "verify_determinism")]
2298            no_output_set,
2299            new_output,
2300            output_dependent_tasks,
2301        })
2302    }
2303
2304    fn task_execution_completed_invalidate_output_dependent(
2305        &self,
2306        ctx: &mut impl ExecuteContext<'_>,
2307        task_id: TaskId,
2308        output_dependent_tasks: SmallVec<[TaskId; 4]>,
2309    ) {
2310        debug_assert!(!output_dependent_tasks.is_empty());
2311
2312        if output_dependent_tasks.len() > 1 {
2313            ctx.prepare_tasks(
2314                output_dependent_tasks
2315                    .iter()
2316                    .map(|&id| (id, TaskDataCategory::All)),
2317            );
2318        }
2319
2320        fn process_output_dependents(
2321            ctx: &mut impl ExecuteContext<'_>,
2322            task_id: TaskId,
2323            dependent_task_id: TaskId,
2324            queue: &mut AggregationUpdateQueue,
2325        ) {
2326            #[cfg(feature = "trace_task_output_dependencies")]
2327            let span = tracing::trace_span!(
2328                "invalidate output dependency",
2329                task = %task_id,
2330                dependent_task = %dependent_task_id,
2331                result = tracing::field::Empty,
2332            )
2333            .entered();
2334            let mut make_stale = true;
2335            let dependent = ctx.task(dependent_task_id, TaskDataCategory::All);
2336            let transient_task_type = dependent.get_transient_task_type();
2337            if transient_task_type.is_some_and(|tt| matches!(&**tt, TransientTask::Once(_))) {
2338                // once tasks are never invalidated
2339                #[cfg(feature = "trace_task_output_dependencies")]
2340                span.record("result", "once task");
2341                return;
2342            }
2343            if dependent.outdated_output_dependencies_contains(&task_id) {
2344                #[cfg(feature = "trace_task_output_dependencies")]
2345                span.record("result", "outdated dependency");
2346                // output dependency is outdated, so it hasn't read the output yet
2347                // and doesn't need to be invalidated
2348                // But importantly we still need to make the task dirty as it should no longer
2349                // be considered as "recomputation".
2350                make_stale = false;
2351            } else if !dependent.output_dependencies_contains(&task_id) {
2352                // output dependency has been removed, so the task doesn't depend on the
2353                // output anymore and doesn't need to be invalidated
2354                #[cfg(feature = "trace_task_output_dependencies")]
2355                span.record("result", "no backward dependency");
2356                return;
2357            }
2358            make_task_dirty_internal(
2359                dependent,
2360                dependent_task_id,
2361                make_stale,
2362                #[cfg(feature = "trace_task_dirty")]
2363                TaskDirtyCause::OutputChange { task_id },
2364                queue,
2365                ctx,
2366            );
2367            #[cfg(feature = "trace_task_output_dependencies")]
2368            span.record("result", "marked dirty");
2369        }
2370
2371        if output_dependent_tasks.len() > DEPENDENT_TASKS_DIRTY_PARALLIZATION_THRESHOLD {
2372            let chunk_size = good_chunk_size(output_dependent_tasks.len());
2373            let chunks = into_chunks(output_dependent_tasks.to_vec(), chunk_size);
2374            let _ = scope_and_block(chunks.len(), |scope| {
2375                for chunk in chunks {
2376                    let child_ctx = ctx.child_context();
2377                    scope.spawn(move || {
2378                        let mut ctx = child_ctx.create();
2379                        let mut queue = AggregationUpdateQueue::new();
2380                        for dependent_task_id in chunk {
2381                            process_output_dependents(
2382                                &mut ctx,
2383                                task_id,
2384                                dependent_task_id,
2385                                &mut queue,
2386                            )
2387                        }
2388                        queue.execute(&mut ctx);
2389                    });
2390                }
2391            });
2392        } else {
2393            let mut queue = AggregationUpdateQueue::new();
2394            for dependent_task_id in output_dependent_tasks {
2395                process_output_dependents(ctx, task_id, dependent_task_id, &mut queue);
2396            }
2397            queue.execute(ctx);
2398        }
2399    }
2400
2401    fn task_execution_completed_unfinished_children_dirty(
2402        &self,
2403        ctx: &mut impl ExecuteContext<'_>,
2404        new_children: &FxHashSet<TaskId>,
2405    ) {
2406        debug_assert!(!new_children.is_empty());
2407
2408        let mut queue = AggregationUpdateQueue::new();
2409        ctx.for_each_task_all(new_children.iter().copied(), |child_task, ctx| {
2410            if !child_task.has_output() {
2411                let child_id = child_task.id();
2412                make_task_dirty_internal(
2413                    child_task,
2414                    child_id,
2415                    false,
2416                    #[cfg(feature = "trace_task_dirty")]
2417                    TaskDirtyCause::InitialDirty,
2418                    &mut queue,
2419                    ctx,
2420                );
2421            }
2422        });
2423
2424        queue.execute(ctx);
2425    }
2426
2427    fn task_execution_completed_connect(
2428        &self,
2429        ctx: &mut impl ExecuteContext<'_>,
2430        task_id: TaskId,
2431        new_children: FxHashSet<TaskId>,
2432    ) -> bool {
2433        debug_assert!(!new_children.is_empty());
2434
2435        let mut task = ctx.task(task_id, TaskDataCategory::All);
2436        let Some(in_progress) = task.get_in_progress() else {
2437            panic!("Task execution completed, but task is not in progress: {task:#?}");
2438        };
2439        if matches!(in_progress, InProgressState::Canceled) {
2440            // Task was canceled in the meantime, so we don't connect the children
2441            return false;
2442        }
2443        let InProgressState::InProgress(box InProgressStateInner {
2444            #[cfg(not(feature = "no_fast_stale"))]
2445            stale,
2446            once_task: is_once_task,
2447            ..
2448        }) = in_progress
2449        else {
2450            panic!("Task execution completed, but task is not in progress: {task:#?}");
2451        };
2452
2453        // If the task is stale, reschedule it
2454        #[cfg(not(feature = "no_fast_stale"))]
2455        if *stale && !is_once_task {
2456            let Some(InProgressState::InProgress(box InProgressStateInner { done_event, .. })) =
2457                task.take_in_progress()
2458            else {
2459                unreachable!();
2460            };
2461            let old = task.set_in_progress(InProgressState::Scheduled {
2462                done_event,
2463                reason: TaskExecutionReason::Stale,
2464            });
2465            debug_assert!(old.is_none(), "InProgress already exists");
2466            drop(task);
2467
2468            // All `new_children` are currently hold active with an active count and we need to undo
2469            // that. (We already filtered out the old children from that list)
2470            AggregationUpdateQueue::run(
2471                AggregationUpdateJob::DecreaseActiveCounts {
2472                    task_ids: new_children.into_iter().collect(),
2473                },
2474                ctx,
2475            );
2476            return true;
2477        }
2478
2479        let has_active_count = ctx.should_track_activeness()
2480            && task
2481                .get_activeness()
2482                .is_some_and(|activeness| activeness.active_counter > 0);
2483        connect_children(
2484            ctx,
2485            task_id,
2486            task,
2487            new_children,
2488            has_active_count,
2489            ctx.should_track_activeness(),
2490        );
2491
2492        false
2493    }
2494
2495    fn task_execution_completed_finish(
2496        &self,
2497        ctx: &mut impl ExecuteContext<'_>,
2498        task_id: TaskId,
2499        #[cfg(feature = "verify_determinism")] no_output_set: bool,
2500        new_output: Option<OutputValue>,
2501        is_now_immutable: bool,
2502    ) -> (
2503        bool,
2504        Option<
2505            auto_hash_map::AutoMap<CellId, InProgressCellState, BuildHasherDefault<FxHasher>, 1>,
2506        >,
2507    ) {
2508        let mut task = ctx.task(task_id, TaskDataCategory::All);
2509        let Some(in_progress) = task.take_in_progress() else {
2510            panic!("Task execution completed, but task is not in progress: {task:#?}");
2511        };
2512        if matches!(in_progress, InProgressState::Canceled) {
2513            // Task was canceled in the meantime, so we don't finish it
2514            return (false, None);
2515        }
2516        let InProgressState::InProgress(box InProgressStateInner {
2517            done_event,
2518            once_task: is_once_task,
2519            stale,
2520            session_dependent,
2521            marked_as_completed: _,
2522            new_children,
2523        }) = in_progress
2524        else {
2525            panic!("Task execution completed, but task is not in progress: {task:#?}");
2526        };
2527        debug_assert!(new_children.is_empty());
2528
2529        // If the task is stale, reschedule it
2530        if stale && !is_once_task {
2531            let old = task.set_in_progress(InProgressState::Scheduled {
2532                done_event,
2533                reason: TaskExecutionReason::Stale,
2534            });
2535            debug_assert!(old.is_none(), "InProgress already exists");
2536            return (true, None);
2537        }
2538
2539        // Set the output if it has changed
2540        let mut old_content = None;
2541        if let Some(value) = new_output {
2542            old_content = task.set_output(value);
2543        }
2544
2545        // If the task has no invalidator and has no mutable dependencies, it does not have a way
2546        // to be invalidated and we can mark it as immutable.
2547        if is_now_immutable {
2548            task.set_immutable(true);
2549        }
2550
2551        // Notify in progress cells and remove all of them
2552        let in_progress_cells = task.take_in_progress_cells();
2553        if let Some(ref cells) = in_progress_cells {
2554            for state in cells.values() {
2555                state.event.notify(usize::MAX);
2556            }
2557        }
2558
2559        // Grab the old dirty state
2560        let old_dirtyness = task.get_dirty().cloned();
2561        let (old_self_dirty, old_current_session_self_clean) = match old_dirtyness {
2562            None => (false, false),
2563            Some(Dirtyness::Dirty(_)) => (true, false),
2564            Some(Dirtyness::SessionDependent) => {
2565                let clean_in_current_session = task.current_session_clean();
2566                (true, clean_in_current_session)
2567            }
2568        };
2569
2570        // Compute the new dirty state
2571        let (new_dirtyness, new_self_dirty, new_current_session_self_clean) = if session_dependent {
2572            (Some(Dirtyness::SessionDependent), true, true)
2573        } else {
2574            (None, false, false)
2575        };
2576
2577        // Update the dirty state
2578        if old_dirtyness != new_dirtyness {
2579            if let Some(value) = new_dirtyness {
2580                task.set_dirty(value);
2581            } else if old_dirtyness.is_some() {
2582                task.take_dirty();
2583            }
2584        }
2585        if old_current_session_self_clean != new_current_session_self_clean {
2586            if new_current_session_self_clean {
2587                task.set_current_session_clean(true);
2588            } else if old_current_session_self_clean {
2589                task.set_current_session_clean(false);
2590            }
2591        }
2592
2593        // Propagate dirtyness changes
2594        let data_update = if old_self_dirty != new_self_dirty
2595            || old_current_session_self_clean != new_current_session_self_clean
2596        {
2597            let dirty_container_count = task
2598                .get_aggregated_dirty_container_count()
2599                .cloned()
2600                .unwrap_or_default();
2601            let current_session_clean_container_count = task
2602                .get_aggregated_current_session_clean_container_count()
2603                .copied()
2604                .unwrap_or_default();
2605            let result = ComputeDirtyAndCleanUpdate {
2606                old_dirty_container_count: dirty_container_count,
2607                new_dirty_container_count: dirty_container_count,
2608                old_current_session_clean_container_count: current_session_clean_container_count,
2609                new_current_session_clean_container_count: current_session_clean_container_count,
2610                old_self_dirty,
2611                new_self_dirty,
2612                old_current_session_self_clean,
2613                new_current_session_self_clean,
2614            }
2615            .compute();
2616            if result.dirty_count_update - result.current_session_clean_update < 0 {
2617                // The task is clean now
2618                if let Some(activeness_state) = task.get_activeness_mut() {
2619                    activeness_state.all_clean_event.notify(usize::MAX);
2620                    activeness_state.unset_active_until_clean();
2621                    if activeness_state.is_empty() {
2622                        task.take_activeness();
2623                    }
2624                }
2625            }
2626            result
2627                .aggregated_update(task_id)
2628                .and_then(|aggregated_update| {
2629                    AggregationUpdateJob::data_update(&mut task, aggregated_update)
2630                })
2631        } else {
2632            None
2633        };
2634
2635        #[cfg(feature = "verify_determinism")]
2636        let reschedule =
2637            (dirty_changed || no_output_set) && !task_id.is_transient() && !is_once_task;
2638        #[cfg(not(feature = "verify_determinism"))]
2639        let reschedule = false;
2640        if reschedule {
2641            let old = task.set_in_progress(InProgressState::Scheduled {
2642                done_event,
2643                reason: TaskExecutionReason::Stale,
2644            });
2645            debug_assert!(old.is_none(), "InProgress already exists");
2646            drop(task);
2647        } else {
2648            drop(task);
2649
2650            // Notify dependent tasks that are waiting for this task to finish
2651            done_event.notify(usize::MAX);
2652        }
2653
2654        drop(old_content);
2655
2656        if let Some(data_update) = data_update {
2657            AggregationUpdateQueue::run(data_update, ctx);
2658        }
2659
2660        // We return so the data can be dropped outside of critical sections
2661        (reschedule, in_progress_cells)
2662    }
2663
2664    fn task_execution_completed_cleanup(
2665        &self,
2666        ctx: &mut impl ExecuteContext<'_>,
2667        task_id: TaskId,
2668        cell_counters: &AutoMap<ValueTypeId, u32, BuildHasherDefault<FxHasher>, 8>,
2669        is_error: bool,
2670    ) -> Vec<SharedReference> {
2671        let mut task = ctx.task(task_id, TaskDataCategory::All);
2672        let mut removed_cell_data = Vec::new();
2673        // An error is potentially caused by a eventual consistency, so we avoid updating cells
2674        // after an error as it is likely transient and we want to keep the dependent tasks
2675        // clean to avoid re-executions.
2676        if !is_error {
2677            // Remove no longer existing cells and
2678            // find all outdated data items (removed cells, outdated edges)
2679            // Note: We do not mark the tasks as dirty here, as these tasks are unused or stale
2680            // anyway and we want to avoid needless re-executions. When the cells become
2681            // used again, they are invalidated from the update cell operation.
2682            // Remove cell data for cells that no longer exist
2683            let to_remove_persistent: Vec<_> = task
2684                .iter_persistent_cell_data()
2685                .filter_map(|(cell, _)| {
2686                    cell_counters
2687                        .get(&cell.type_id)
2688                        .is_none_or(|start_index| cell.index >= *start_index)
2689                        .then_some(*cell)
2690                })
2691                .collect();
2692
2693            // Remove transient cell data for cells that no longer exist
2694            let to_remove_transient: Vec<_> = task
2695                .iter_transient_cell_data()
2696                .filter_map(|(cell, _)| {
2697                    cell_counters
2698                        .get(&cell.type_id)
2699                        .is_none_or(|start_index| cell.index >= *start_index)
2700                        .then_some(*cell)
2701                })
2702                .collect();
2703            removed_cell_data.reserve_exact(to_remove_persistent.len() + to_remove_transient.len());
2704            for cell in to_remove_persistent {
2705                if let Some(data) = task.remove_persistent_cell_data(&cell) {
2706                    removed_cell_data.push(data.into_untyped());
2707                }
2708            }
2709            for cell in to_remove_transient {
2710                if let Some(data) = task.remove_transient_cell_data(&cell) {
2711                    removed_cell_data.push(data);
2712                }
2713            }
2714        }
2715
2716        // Clean up task storage after execution:
2717        // - Shrink collections marked with shrink_on_completion
2718        // - Drop dependency fields for immutable tasks (they'll never re-execute)
2719        task.cleanup_after_execution();
2720
2721        drop(task);
2722
2723        // Return so we can drop outside of critical sections
2724        removed_cell_data
2725    }
2726
2727    fn run_backend_job<'a>(
2728        self: &'a Arc<Self>,
2729        job: TurboTasksBackendJob,
2730        turbo_tasks: &'a dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
2731    ) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
2732        Box::pin(async move {
2733            match job {
2734                TurboTasksBackendJob::InitialSnapshot | TurboTasksBackendJob::FollowUpSnapshot => {
2735                    debug_assert!(self.should_persist());
2736
2737                    let last_snapshot = self.last_snapshot.load(Ordering::Relaxed);
2738                    let mut last_snapshot = self.start_time + Duration::from_millis(last_snapshot);
2739                    let mut idle_start_listener = self.idle_start_event.listen();
2740                    let mut idle_end_listener = self.idle_end_event.listen();
2741                    let mut fresh_idle = true;
2742                    loop {
2743                        const FIRST_SNAPSHOT_WAIT: Duration = Duration::from_secs(300);
2744                        const SNAPSHOT_INTERVAL: Duration = Duration::from_secs(120);
2745                        let idle_timeout = *IDLE_TIMEOUT;
2746                        let (time, mut reason) =
2747                            if matches!(job, TurboTasksBackendJob::InitialSnapshot) {
2748                                (FIRST_SNAPSHOT_WAIT, "initial snapshot timeout")
2749                            } else {
2750                                (SNAPSHOT_INTERVAL, "regular snapshot interval")
2751                            };
2752
2753                        let until = last_snapshot + time;
2754                        if until > Instant::now() {
2755                            let mut stop_listener = self.stopping_event.listen();
2756                            if self.stopping.load(Ordering::Acquire) {
2757                                return;
2758                            }
2759                            let mut idle_time = if turbo_tasks.is_idle() && fresh_idle {
2760                                Instant::now() + idle_timeout
2761                            } else {
2762                                far_future()
2763                            };
2764                            loop {
2765                                tokio::select! {
2766                                    _ = &mut stop_listener => {
2767                                        return;
2768                                    },
2769                                    _ = &mut idle_start_listener => {
2770                                        fresh_idle = true;
2771                                        idle_time = Instant::now() + idle_timeout;
2772                                        idle_start_listener = self.idle_start_event.listen()
2773                                    },
2774                                    _ = &mut idle_end_listener => {
2775                                        idle_time = until + idle_timeout;
2776                                        idle_end_listener = self.idle_end_event.listen()
2777                                    },
2778                                    _ = tokio::time::sleep_until(until) => {
2779                                        break;
2780                                    },
2781                                    _ = tokio::time::sleep_until(idle_time) => {
2782                                        if turbo_tasks.is_idle() {
2783                                            reason = "idle timeout";
2784                                            break;
2785                                        }
2786                                    },
2787                                }
2788                            }
2789                        }
2790
2791                        let this = self.clone();
2792                        let snapshot = this.snapshot_and_persist(None, reason, turbo_tasks);
2793                        if let Some((snapshot_start, new_data)) = snapshot {
2794                            last_snapshot = snapshot_start;
2795                            if !new_data {
2796                                fresh_idle = false;
2797                                continue;
2798                            }
2799                            let last_snapshot = last_snapshot.duration_since(self.start_time);
2800                            self.last_snapshot.store(
2801                                last_snapshot.as_millis().try_into().unwrap(),
2802                                Ordering::Relaxed,
2803                            );
2804
2805                            turbo_tasks.schedule_backend_background_job(
2806                                TurboTasksBackendJob::FollowUpSnapshot,
2807                            );
2808                            return;
2809                        }
2810                    }
2811                }
2812            }
2813        })
2814    }
2815
2816    fn try_read_own_task_cell(
2817        &self,
2818        task_id: TaskId,
2819        cell: CellId,
2820        options: ReadCellOptions,
2821        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
2822    ) -> Result<TypedCellContent> {
2823        let mut ctx = self.execute_context(turbo_tasks);
2824        let task = ctx.task(task_id, TaskDataCategory::Data);
2825        if let Some(content) = task.get_cell_data(options.is_serializable_cell_content, cell) {
2826            debug_assert!(content.type_id == cell.type_id, "Cell type ID mismatch");
2827            Ok(CellContent(Some(content.reference)).into_typed(cell.type_id))
2828        } else {
2829            Ok(CellContent(None).into_typed(cell.type_id))
2830        }
2831    }
2832
2833    fn read_task_collectibles(
2834        &self,
2835        task_id: TaskId,
2836        collectible_type: TraitTypeId,
2837        reader_id: Option<TaskId>,
2838        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
2839    ) -> AutoMap<RawVc, i32, BuildHasherDefault<FxHasher>, 1> {
2840        let mut ctx = self.execute_context(turbo_tasks);
2841        let mut collectibles = AutoMap::default();
2842        {
2843            let mut task = ctx.task(task_id, TaskDataCategory::All);
2844            // Ensure it's an root node
2845            loop {
2846                let aggregation_number = get_aggregation_number(&task);
2847                if is_root_node(aggregation_number) {
2848                    break;
2849                }
2850                drop(task);
2851                AggregationUpdateQueue::run(
2852                    AggregationUpdateJob::UpdateAggregationNumber {
2853                        task_id,
2854                        base_aggregation_number: u32::MAX,
2855                        distance: None,
2856                    },
2857                    &mut ctx,
2858                );
2859                task = ctx.task(task_id, TaskDataCategory::All);
2860            }
2861            for (collectible, count) in task.iter_aggregated_collectibles() {
2862                if *count > 0 && collectible.collectible_type == collectible_type {
2863                    *collectibles
2864                        .entry(RawVc::TaskCell(
2865                            collectible.cell.task,
2866                            collectible.cell.cell,
2867                        ))
2868                        .or_insert(0) += 1;
2869                }
2870            }
2871            for (&collectible, &count) in task.iter_collectibles() {
2872                if collectible.collectible_type == collectible_type {
2873                    *collectibles
2874                        .entry(RawVc::TaskCell(
2875                            collectible.cell.task,
2876                            collectible.cell.cell,
2877                        ))
2878                        .or_insert(0) += count;
2879                }
2880            }
2881            if let Some(reader_id) = reader_id {
2882                let _ = task.add_collectibles_dependents((collectible_type, reader_id));
2883            }
2884        }
2885        if let Some(reader_id) = reader_id {
2886            let mut reader = ctx.task(reader_id, TaskDataCategory::Data);
2887            let target = CollectiblesRef {
2888                task: task_id,
2889                collectible_type,
2890            };
2891            if !reader.remove_outdated_collectibles_dependencies(&target) {
2892                let _ = reader.add_collectibles_dependencies(target);
2893            }
2894        }
2895        collectibles
2896    }
2897
2898    fn emit_collectible(
2899        &self,
2900        collectible_type: TraitTypeId,
2901        collectible: RawVc,
2902        task_id: TaskId,
2903        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
2904    ) {
2905        self.assert_valid_collectible(task_id, collectible);
2906
2907        let RawVc::TaskCell(collectible_task, cell) = collectible else {
2908            panic!("Collectibles need to be resolved");
2909        };
2910        let cell = CellRef {
2911            task: collectible_task,
2912            cell,
2913        };
2914        operation::UpdateCollectibleOperation::run(
2915            task_id,
2916            CollectibleRef {
2917                collectible_type,
2918                cell,
2919            },
2920            1,
2921            self.execute_context(turbo_tasks),
2922        );
2923    }
2924
2925    fn unemit_collectible(
2926        &self,
2927        collectible_type: TraitTypeId,
2928        collectible: RawVc,
2929        count: u32,
2930        task_id: TaskId,
2931        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
2932    ) {
2933        self.assert_valid_collectible(task_id, collectible);
2934
2935        let RawVc::TaskCell(collectible_task, cell) = collectible else {
2936            panic!("Collectibles need to be resolved");
2937        };
2938        let cell = CellRef {
2939            task: collectible_task,
2940            cell,
2941        };
2942        operation::UpdateCollectibleOperation::run(
2943            task_id,
2944            CollectibleRef {
2945                collectible_type,
2946                cell,
2947            },
2948            -(i32::try_from(count).unwrap()),
2949            self.execute_context(turbo_tasks),
2950        );
2951    }
2952
2953    fn update_task_cell(
2954        &self,
2955        task_id: TaskId,
2956        cell: CellId,
2957        is_serializable_cell_content: bool,
2958        content: CellContent,
2959        updated_key_hashes: Option<SmallVec<[u64; 2]>>,
2960        verification_mode: VerificationMode,
2961        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
2962    ) {
2963        operation::UpdateCellOperation::run(
2964            task_id,
2965            cell,
2966            content,
2967            is_serializable_cell_content,
2968            updated_key_hashes,
2969            verification_mode,
2970            self.execute_context(turbo_tasks),
2971        );
2972    }
2973
2974    fn mark_own_task_as_session_dependent(
2975        &self,
2976        task_id: TaskId,
2977        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
2978    ) {
2979        if !self.should_track_dependencies() {
2980            // Without dependency tracking we don't need session dependent tasks
2981            return;
2982        }
2983        const SESSION_DEPENDENT_AGGREGATION_NUMBER: u32 = u32::MAX >> 2;
2984        let mut ctx = self.execute_context(turbo_tasks);
2985        let mut task = ctx.task(task_id, TaskDataCategory::Meta);
2986        let aggregation_number = get_aggregation_number(&task);
2987        if aggregation_number < SESSION_DEPENDENT_AGGREGATION_NUMBER {
2988            drop(task);
2989            // We want to use a high aggregation number to avoid large aggregation chains for
2990            // session dependent tasks (which change on every run)
2991            AggregationUpdateQueue::run(
2992                AggregationUpdateJob::UpdateAggregationNumber {
2993                    task_id,
2994                    base_aggregation_number: SESSION_DEPENDENT_AGGREGATION_NUMBER,
2995                    distance: None,
2996                },
2997                &mut ctx,
2998            );
2999            task = ctx.task(task_id, TaskDataCategory::Meta);
3000        }
3001        if let Some(InProgressState::InProgress(box InProgressStateInner {
3002            session_dependent,
3003            ..
3004        })) = task.get_in_progress_mut()
3005        {
3006            *session_dependent = true;
3007        }
3008    }
3009
3010    fn mark_own_task_as_finished(
3011        &self,
3012        task: TaskId,
3013        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
3014    ) {
3015        let mut ctx = self.execute_context(turbo_tasks);
3016        let mut task = ctx.task(task, TaskDataCategory::Data);
3017        if let Some(InProgressState::InProgress(box InProgressStateInner {
3018            marked_as_completed,
3019            ..
3020        })) = task.get_in_progress_mut()
3021        {
3022            *marked_as_completed = true;
3023            // TODO this should remove the dirty state (also check session_dependent)
3024            // but this would break some assumptions for strongly consistent reads.
3025            // Client tasks are not connected yet, so we wouldn't wait for them.
3026            // Maybe that's ok in cases where mark_finished() is used? Seems like it?
3027        }
3028    }
3029
3030    fn set_own_task_aggregation_number(
3031        &self,
3032        task: TaskId,
3033        aggregation_number: u32,
3034        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
3035    ) {
3036        let mut ctx = self.execute_context(turbo_tasks);
3037        AggregationUpdateQueue::run(
3038            AggregationUpdateJob::UpdateAggregationNumber {
3039                task_id: task,
3040                base_aggregation_number: aggregation_number,
3041                distance: None,
3042            },
3043            &mut ctx,
3044        );
3045    }
3046
3047    fn connect_task(
3048        &self,
3049        task: TaskId,
3050        parent_task: Option<TaskId>,
3051        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
3052    ) {
3053        self.assert_not_persistent_calling_transient(parent_task, task, None);
3054        ConnectChildOperation::run(parent_task, task, None, self.execute_context(turbo_tasks));
3055    }
3056
3057    fn create_transient_task(&self, task_type: TransientTaskType) -> TaskId {
3058        let task_id = self.transient_task_id_factory.get();
3059        {
3060            let mut task = self.storage.access_mut(task_id);
3061            task.init_transient_task(task_id, task_type, self.should_track_activeness());
3062        }
3063        #[cfg(feature = "verify_aggregation_graph")]
3064        self.root_tasks.lock().insert(task_id);
3065        task_id
3066    }
3067
3068    fn dispose_root_task(
3069        &self,
3070        task_id: TaskId,
3071        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
3072    ) {
3073        #[cfg(feature = "verify_aggregation_graph")]
3074        self.root_tasks.lock().remove(&task_id);
3075
3076        let mut ctx = self.execute_context(turbo_tasks);
3077        let mut task = ctx.task(task_id, TaskDataCategory::All);
3078        let is_dirty = task.is_dirty();
3079        let has_dirty_containers = task.has_dirty_containers();
3080        if is_dirty.is_some() || has_dirty_containers {
3081            if let Some(activeness_state) = task.get_activeness_mut() {
3082                // We will finish the task, but it would be removed after the task is done
3083                activeness_state.unset_root_type();
3084                activeness_state.set_active_until_clean();
3085            };
3086        } else if let Some(activeness_state) = task.take_activeness() {
3087            // Technically nobody should be listening to this event, but just in case
3088            // we notify it anyway
3089            activeness_state.all_clean_event.notify(usize::MAX);
3090        }
3091    }
3092
3093    #[cfg(feature = "verify_aggregation_graph")]
3094    fn verify_aggregation_graph(
3095        &self,
3096        turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
3097        idle: bool,
3098    ) {
3099        if env::var("TURBO_ENGINE_VERIFY_GRAPH").ok().as_deref() == Some("0") {
3100            return;
3101        }
3102        use std::{collections::VecDeque, env, io::stdout};
3103
3104        use crate::backend::operation::{get_uppers, is_aggregating_node};
3105
3106        let mut ctx = self.execute_context(turbo_tasks);
3107        let root_tasks = self.root_tasks.lock().clone();
3108
3109        for task_id in root_tasks.into_iter() {
3110            let mut queue = VecDeque::new();
3111            let mut visited = FxHashSet::default();
3112            let mut aggregated_nodes = FxHashSet::default();
3113            let mut collectibles = FxHashMap::default();
3114            let root_task_id = task_id;
3115            visited.insert(task_id);
3116            aggregated_nodes.insert(task_id);
3117            queue.push_back(task_id);
3118            let mut counter = 0;
3119            while let Some(task_id) = queue.pop_front() {
3120                counter += 1;
3121                if counter % 100000 == 0 {
3122                    println!(
3123                        "queue={}, visited={}, aggregated_nodes={}",
3124                        queue.len(),
3125                        visited.len(),
3126                        aggregated_nodes.len()
3127                    );
3128                }
3129                let task = ctx.task(task_id, TaskDataCategory::All);
3130                if idle && !self.is_idle.load(Ordering::Relaxed) {
3131                    return;
3132                }
3133
3134                let uppers = get_uppers(&task);
3135                if task_id != root_task_id
3136                    && !uppers.iter().any(|upper| aggregated_nodes.contains(upper))
3137                {
3138                    panic!(
3139                        "Task {} {} doesn't report to any root but is reachable from one (uppers: \
3140                         {:?})",
3141                        task_id,
3142                        ctx.get_task_description(task_id),
3143                        uppers
3144                    );
3145                }
3146
3147                let aggregated_collectibles: Vec<_> = task
3148                    .iter_aggregated_collectibles()
3149                    .map(|(collectible, _)| collectible)
3150                    .collect();
3151                for collectible in aggregated_collectibles {
3152                    collectibles
3153                        .entry(collectible)
3154                        .or_insert_with(|| (false, Vec::new()))
3155                        .1
3156                        .push(task_id);
3157                }
3158
3159                let own_collectibles: Vec<_> = task
3160                    .iter_collectibles_entries()
3161                    .filter_map(|(&collectible, &value)| (value > 0).then_some(collectible))
3162                    .collect::<Vec<_>>();
3163                for collectible in own_collectibles {
3164                    if let Some((flag, _)) = collectibles.get_mut(&collectible) {
3165                        *flag = true
3166                    } else {
3167                        panic!(
3168                            "Task {} has a collectible {:?} that is not in any upper task",
3169                            task_id, collectible
3170                        );
3171                    }
3172                }
3173
3174                let is_dirty = task.has_dirty();
3175                let has_dirty_container = task.has_dirty_containers();
3176                let should_be_in_upper = is_dirty || has_dirty_container;
3177
3178                let aggregation_number = get_aggregation_number(&task);
3179                if is_aggregating_node(aggregation_number) {
3180                    aggregated_nodes.insert(task_id);
3181                }
3182                // println!(
3183                //     "{task_id}: {} agg_num = {aggregation_number}, uppers = {:#?}",
3184                //     ctx.get_task_description(task_id),
3185                //     uppers
3186                // );
3187
3188                for child_id in task.iter_children() {
3189                    // println!("{task_id}: child -> {child_id}");
3190                    if visited.insert(child_id) {
3191                        queue.push_back(child_id);
3192                    }
3193                }
3194                drop(task);
3195
3196                if should_be_in_upper {
3197                    for upper_id in uppers {
3198                        let task = ctx.task(upper_id, TaskDataCategory::All);
3199                        let in_upper = task
3200                            .get_aggregated_dirty_containers(&task_id)
3201                            .is_some_and(|&dirty| dirty > 0);
3202                        if !in_upper {
3203                            let containers: Vec<_> = task
3204                                .iter_aggregated_dirty_containers_entries()
3205                                .map(|(&k, &v)| (k, v))
3206                                .collect();
3207                            panic!(
3208                                "Task {} ({}) is dirty, but is not listed in the upper task {} \
3209                                 ({})\nThese dirty containers are present:\n{:#?}",
3210                                task_id,
3211                                ctx.get_task_description(task_id),
3212                                upper_id,
3213                                ctx.get_task_description(upper_id),
3214                                containers,
3215                            );
3216                        }
3217                    }
3218                }
3219            }
3220
3221            for (collectible, (flag, task_ids)) in collectibles {
3222                if !flag {
3223                    use std::io::Write;
3224                    let mut stdout = stdout().lock();
3225                    writeln!(
3226                        stdout,
3227                        "{:?} that is not emitted in any child task but in these aggregated \
3228                         tasks: {:#?}",
3229                        collectible,
3230                        task_ids
3231                            .iter()
3232                            .map(|t| format!("{t} {}", ctx.get_task_description(*t)))
3233                            .collect::<Vec<_>>()
3234                    )
3235                    .unwrap();
3236
3237                    let task_id = collectible.cell.task;
3238                    let mut queue = {
3239                        let task = ctx.task(task_id, TaskDataCategory::All);
3240                        get_uppers(&task)
3241                    };
3242                    let mut visited = FxHashSet::default();
3243                    for &upper_id in queue.iter() {
3244                        visited.insert(upper_id);
3245                        writeln!(stdout, "{task_id:?} -> {upper_id:?}").unwrap();
3246                    }
3247                    while let Some(task_id) = queue.pop() {
3248                        let desc = ctx.get_task_description(task_id);
3249                        let task = ctx.task(task_id, TaskDataCategory::All);
3250                        let aggregated_collectible = task
3251                            .get_aggregated_collectibles(&collectible)
3252                            .copied()
3253                            .unwrap_or_default();
3254                        let uppers = get_uppers(&task);
3255                        drop(task);
3256                        writeln!(
3257                            stdout,
3258                            "upper {task_id} {desc} collectible={aggregated_collectible}"
3259                        )
3260                        .unwrap();
3261                        if task_ids.contains(&task_id) {
3262                            writeln!(
3263                                stdout,
3264                                "Task has an upper connection to an aggregated task that doesn't \
3265                                 reference it. Upper connection is invalid!"
3266                            )
3267                            .unwrap();
3268                        }
3269                        for upper_id in uppers {
3270                            writeln!(stdout, "{task_id:?} -> {upper_id:?}").unwrap();
3271                            if !visited.contains(&upper_id) {
3272                                queue.push(upper_id);
3273                            }
3274                        }
3275                    }
3276                    panic!("See stdout for more details");
3277                }
3278            }
3279        }
3280    }
3281
3282    fn assert_not_persistent_calling_transient(
3283        &self,
3284        parent_id: Option<TaskId>,
3285        child_id: TaskId,
3286        cell_id: Option<CellId>,
3287    ) {
3288        if let Some(parent_id) = parent_id
3289            && !parent_id.is_transient()
3290            && child_id.is_transient()
3291        {
3292            self.panic_persistent_calling_transient(
3293                self.debug_get_task_description(parent_id),
3294                self.debug_get_cached_task_type(child_id).as_deref(),
3295                cell_id,
3296            );
3297        }
3298    }
3299
3300    fn panic_persistent_calling_transient(
3301        &self,
3302        parent: String,
3303        child: Option<&CachedTaskType>,
3304        cell_id: Option<CellId>,
3305    ) {
3306        let transient_reason = if let Some(child) = child {
3307            Cow::Owned(format!(
3308                " The callee is transient because it depends on:\n{}",
3309                self.debug_trace_transient_task(child, cell_id),
3310            ))
3311        } else {
3312            Cow::Borrowed("")
3313        };
3314        panic!(
3315            "Persistent task {} is not allowed to call, read, or connect to transient tasks {}.{}",
3316            parent,
3317            child.map_or("unknown", |t| t.get_name()),
3318            transient_reason,
3319        );
3320    }
3321
3322    fn assert_valid_collectible(&self, task_id: TaskId, collectible: RawVc) {
3323        // these checks occur in a potentially hot codepath, but they're cheap
3324        let RawVc::TaskCell(col_task_id, col_cell_id) = collectible else {
3325            // This should never happen: The collectible APIs use ResolvedVc
3326            let task_info = if let Some(col_task_ty) = collectible
3327                .try_get_task_id()
3328                .map(|t| self.debug_get_task_description(t))
3329            {
3330                Cow::Owned(format!(" (return type of {col_task_ty})"))
3331            } else {
3332                Cow::Borrowed("")
3333            };
3334            panic!("Collectible{task_info} must be a ResolvedVc")
3335        };
3336        if col_task_id.is_transient() && !task_id.is_transient() {
3337            let transient_reason =
3338                if let Some(col_task_ty) = self.debug_get_cached_task_type(col_task_id) {
3339                    Cow::Owned(format!(
3340                        ". The collectible is transient because it depends on:\n{}",
3341                        self.debug_trace_transient_task(&col_task_ty, Some(col_cell_id)),
3342                    ))
3343                } else {
3344                    Cow::Borrowed("")
3345                };
3346            // this should never happen: How would a persistent function get a transient Vc?
3347            panic!(
3348                "Collectible is transient, transient collectibles cannot be emitted from \
3349                 persistent tasks{transient_reason}",
3350            )
3351        }
3352    }
3353}
3354
3355impl<B: BackingStorage> Backend for TurboTasksBackend<B> {
3356    fn startup(&self, turbo_tasks: &dyn TurboTasksBackendApi<Self>) {
3357        self.0.startup(turbo_tasks);
3358    }
3359
3360    fn stopping(&self, _turbo_tasks: &dyn TurboTasksBackendApi<Self>) {
3361        self.0.stopping();
3362    }
3363
3364    fn stop(&self, turbo_tasks: &dyn TurboTasksBackendApi<Self>) {
3365        self.0.stop(turbo_tasks);
3366    }
3367
3368    fn idle_start(&self, turbo_tasks: &dyn TurboTasksBackendApi<Self>) {
3369        self.0.idle_start(turbo_tasks);
3370    }
3371
3372    fn idle_end(&self, _turbo_tasks: &dyn TurboTasksBackendApi<Self>) {
3373        self.0.idle_end();
3374    }
3375
3376    fn get_or_create_persistent_task(
3377        &self,
3378        task_type: CachedTaskType,
3379        parent_task: Option<TaskId>,
3380        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3381    ) -> TaskId {
3382        self.0
3383            .get_or_create_persistent_task(task_type, parent_task, turbo_tasks)
3384    }
3385
3386    fn get_or_create_transient_task(
3387        &self,
3388        task_type: CachedTaskType,
3389        parent_task: Option<TaskId>,
3390        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3391    ) -> TaskId {
3392        self.0
3393            .get_or_create_transient_task(task_type, parent_task, turbo_tasks)
3394    }
3395
3396    fn invalidate_task(&self, task_id: TaskId, turbo_tasks: &dyn TurboTasksBackendApi<Self>) {
3397        self.0.invalidate_task(task_id, turbo_tasks);
3398    }
3399
3400    fn invalidate_tasks(&self, tasks: &[TaskId], turbo_tasks: &dyn TurboTasksBackendApi<Self>) {
3401        self.0.invalidate_tasks(tasks, turbo_tasks);
3402    }
3403
3404    fn invalidate_tasks_set(
3405        &self,
3406        tasks: &AutoSet<TaskId, BuildHasherDefault<FxHasher>, 2>,
3407        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3408    ) {
3409        self.0.invalidate_tasks_set(tasks, turbo_tasks);
3410    }
3411
3412    fn invalidate_serialization(
3413        &self,
3414        task_id: TaskId,
3415        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3416    ) {
3417        self.0.invalidate_serialization(task_id, turbo_tasks);
3418    }
3419
3420    fn task_execution_canceled(&self, task: TaskId, turbo_tasks: &dyn TurboTasksBackendApi<Self>) {
3421        self.0.task_execution_canceled(task, turbo_tasks)
3422    }
3423
3424    fn try_start_task_execution(
3425        &self,
3426        task_id: TaskId,
3427        priority: TaskPriority,
3428        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3429    ) -> Option<TaskExecutionSpec<'_>> {
3430        self.0
3431            .try_start_task_execution(task_id, priority, turbo_tasks)
3432    }
3433
3434    fn task_execution_completed(
3435        &self,
3436        task_id: TaskId,
3437        result: Result<RawVc, TurboTasksExecutionError>,
3438        cell_counters: &AutoMap<ValueTypeId, u32, BuildHasherDefault<FxHasher>, 8>,
3439        has_invalidator: bool,
3440        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3441    ) -> bool {
3442        self.0.task_execution_completed(
3443            task_id,
3444            result,
3445            cell_counters,
3446            has_invalidator,
3447            turbo_tasks,
3448        )
3449    }
3450
3451    type BackendJob = TurboTasksBackendJob;
3452
3453    fn run_backend_job<'a>(
3454        &'a self,
3455        job: Self::BackendJob,
3456        turbo_tasks: &'a dyn TurboTasksBackendApi<Self>,
3457    ) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
3458        self.0.run_backend_job(job, turbo_tasks)
3459    }
3460
3461    fn try_read_task_output(
3462        &self,
3463        task_id: TaskId,
3464        reader: Option<TaskId>,
3465        options: ReadOutputOptions,
3466        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3467    ) -> Result<Result<RawVc, EventListener>> {
3468        self.0
3469            .try_read_task_output(task_id, reader, options, turbo_tasks)
3470    }
3471
3472    fn try_read_task_cell(
3473        &self,
3474        task_id: TaskId,
3475        cell: CellId,
3476        reader: Option<TaskId>,
3477        options: ReadCellOptions,
3478        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3479    ) -> Result<Result<TypedCellContent, EventListener>> {
3480        self.0
3481            .try_read_task_cell(task_id, reader, cell, options, turbo_tasks)
3482    }
3483
3484    fn try_read_own_task_cell(
3485        &self,
3486        task_id: TaskId,
3487        cell: CellId,
3488        options: ReadCellOptions,
3489        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3490    ) -> Result<TypedCellContent> {
3491        self.0
3492            .try_read_own_task_cell(task_id, cell, options, turbo_tasks)
3493    }
3494
3495    fn read_task_collectibles(
3496        &self,
3497        task_id: TaskId,
3498        collectible_type: TraitTypeId,
3499        reader: Option<TaskId>,
3500        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3501    ) -> AutoMap<RawVc, i32, BuildHasherDefault<FxHasher>, 1> {
3502        self.0
3503            .read_task_collectibles(task_id, collectible_type, reader, turbo_tasks)
3504    }
3505
3506    fn emit_collectible(
3507        &self,
3508        collectible_type: TraitTypeId,
3509        collectible: RawVc,
3510        task_id: TaskId,
3511        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3512    ) {
3513        self.0
3514            .emit_collectible(collectible_type, collectible, task_id, turbo_tasks)
3515    }
3516
3517    fn unemit_collectible(
3518        &self,
3519        collectible_type: TraitTypeId,
3520        collectible: RawVc,
3521        count: u32,
3522        task_id: TaskId,
3523        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3524    ) {
3525        self.0
3526            .unemit_collectible(collectible_type, collectible, count, task_id, turbo_tasks)
3527    }
3528
3529    fn update_task_cell(
3530        &self,
3531        task_id: TaskId,
3532        cell: CellId,
3533        is_serializable_cell_content: bool,
3534        content: CellContent,
3535        updated_key_hashes: Option<SmallVec<[u64; 2]>>,
3536        verification_mode: VerificationMode,
3537        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3538    ) {
3539        self.0.update_task_cell(
3540            task_id,
3541            cell,
3542            is_serializable_cell_content,
3543            content,
3544            updated_key_hashes,
3545            verification_mode,
3546            turbo_tasks,
3547        );
3548    }
3549
3550    fn mark_own_task_as_finished(
3551        &self,
3552        task_id: TaskId,
3553        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3554    ) {
3555        self.0.mark_own_task_as_finished(task_id, turbo_tasks);
3556    }
3557
3558    fn set_own_task_aggregation_number(
3559        &self,
3560        task: TaskId,
3561        aggregation_number: u32,
3562        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3563    ) {
3564        self.0
3565            .set_own_task_aggregation_number(task, aggregation_number, turbo_tasks);
3566    }
3567
3568    fn mark_own_task_as_session_dependent(
3569        &self,
3570        task: TaskId,
3571        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3572    ) {
3573        self.0.mark_own_task_as_session_dependent(task, turbo_tasks);
3574    }
3575
3576    fn connect_task(
3577        &self,
3578        task: TaskId,
3579        parent_task: Option<TaskId>,
3580        turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3581    ) {
3582        self.0.connect_task(task, parent_task, turbo_tasks);
3583    }
3584
3585    fn create_transient_task(
3586        &self,
3587        task_type: TransientTaskType,
3588        _turbo_tasks: &dyn TurboTasksBackendApi<Self>,
3589    ) -> TaskId {
3590        self.0.create_transient_task(task_type)
3591    }
3592
3593    fn dispose_root_task(&self, task_id: TaskId, turbo_tasks: &dyn TurboTasksBackendApi<Self>) {
3594        self.0.dispose_root_task(task_id, turbo_tasks);
3595    }
3596
3597    fn task_statistics(&self) -> &TaskStatisticsApi {
3598        &self.0.task_statistics
3599    }
3600
3601    fn is_tracking_dependencies(&self) -> bool {
3602        self.0.options.dependency_tracking
3603    }
3604
3605    fn get_task_name(&self, task: TaskId, turbo_tasks: &dyn TurboTasksBackendApi<Self>) -> String {
3606        self.0.get_task_name(task, turbo_tasks)
3607    }
3608}
3609
3610enum DebugTraceTransientTask {
3611    Cached {
3612        task_name: &'static str,
3613        cell_type_id: Option<ValueTypeId>,
3614        cause_self: Option<Box<DebugTraceTransientTask>>,
3615        cause_args: Vec<DebugTraceTransientTask>,
3616    },
3617    /// This representation is used when this task is a duplicate of one previously shown
3618    Collapsed {
3619        task_name: &'static str,
3620        cell_type_id: Option<ValueTypeId>,
3621    },
3622    Uncached {
3623        cell_type_id: Option<ValueTypeId>,
3624    },
3625}
3626
3627impl DebugTraceTransientTask {
3628    fn fmt_indented(&self, f: &mut fmt::Formatter<'_>, level: usize) -> fmt::Result {
3629        let indent = "    ".repeat(level);
3630        f.write_str(&indent)?;
3631
3632        fn fmt_cell_type_id(
3633            f: &mut fmt::Formatter<'_>,
3634            cell_type_id: Option<ValueTypeId>,
3635        ) -> fmt::Result {
3636            if let Some(ty) = cell_type_id {
3637                write!(f, " (read cell of type {})", get_value_type(ty).global_name)
3638            } else {
3639                Ok(())
3640            }
3641        }
3642
3643        // write the name and type
3644        match self {
3645            Self::Cached {
3646                task_name,
3647                cell_type_id,
3648                ..
3649            }
3650            | Self::Collapsed {
3651                task_name,
3652                cell_type_id,
3653                ..
3654            } => {
3655                f.write_str(task_name)?;
3656                fmt_cell_type_id(f, *cell_type_id)?;
3657                if matches!(self, Self::Collapsed { .. }) {
3658                    f.write_str(" (collapsed)")?;
3659                }
3660            }
3661            Self::Uncached { cell_type_id } => {
3662                f.write_str("unknown transient task")?;
3663                fmt_cell_type_id(f, *cell_type_id)?;
3664            }
3665        }
3666        f.write_char('\n')?;
3667
3668        // write any extra "cause" information we might have
3669        if let Self::Cached {
3670            cause_self,
3671            cause_args,
3672            ..
3673        } = self
3674        {
3675            if let Some(c) = cause_self {
3676                writeln!(f, "{indent}  self:")?;
3677                c.fmt_indented(f, level + 1)?;
3678            }
3679            if !cause_args.is_empty() {
3680                writeln!(f, "{indent}  args:")?;
3681                for c in cause_args {
3682                    c.fmt_indented(f, level + 1)?;
3683                }
3684            }
3685        }
3686        Ok(())
3687    }
3688}
3689
3690impl fmt::Display for DebugTraceTransientTask {
3691    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3692        self.fmt_indented(f, 0)
3693    }
3694}
3695
3696// from https://github.com/tokio-rs/tokio/blob/29cd6ec1ec6f90a7ee1ad641c03e0e00badbcb0e/tokio/src/time/instant.rs#L57-L63
3697fn far_future() -> Instant {
3698    // Roughly 30 years from now.
3699    // API does not provide a way to obtain max `Instant`
3700    // or convert specific date in the future to instant.
3701    // 1000 years overflows on macOS, 100 years overflows on FreeBSD.
3702    Instant::now() + Duration::from_secs(86400 * 365 * 30)
3703}
3704
3705/// Encodes task data, using the provided buffer as a scratch space.  Returns a new exactly sized
3706/// buffer.
3707/// This allows reusing the buffer across multiple encode calls to optimize allocations and
3708/// resulting buffer sizes.
3709fn encode_task_data(
3710    task: TaskId,
3711    data: &TaskStorage,
3712    category: SpecificTaskDataCategory,
3713    scratch_buffer: &mut TurboBincodeBuffer,
3714) -> Result<TurboBincodeBuffer> {
3715    scratch_buffer.clear();
3716    let mut encoder = new_turbo_bincode_encoder(scratch_buffer);
3717    data.encode(category, &mut encoder)?;
3718
3719    if cfg!(feature = "verify_serialization") {
3720        TaskStorage::new()
3721            .decode(
3722                category,
3723                &mut new_turbo_bincode_decoder(&scratch_buffer[..]),
3724            )
3725            .with_context(|| {
3726                format!(
3727                    "expected to be able to decode serialized data for '{category:?}' information \
3728                     for {task}"
3729                )
3730            })?;
3731    }
3732    Ok(SmallVec::from_slice(scratch_buffer))
3733}