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