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