Unverified Commit d41c50b8 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: Store task error as pointer to the source error (#89293)

Store task error as pointer to the source error

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the PR.
- Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to understand the PR)
- When linking to a Slack thread, you might want to share details of the conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent 5415c3f3
......@@ -37,8 +37,8 @@ use tracing_subscriber::{Registry, layer::SubscriberExt, util::SubscriberInitExt
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
Effects, FxIndexSet, NonLocalValue, OperationValue, OperationVc, PrettyPrintError, ReadRef,
ResolvedVc, TaskInput, TransientInstance, TryJoinIterExt, TurboTasksApi, UpdateInfo, Vc,
get_effects,
ResolvedVc, TaskInput, TransientInstance, TryJoinIterExt, TurboTasksApi, TurboTasksCallApi,
UpdateInfo, Vc, get_effects,
message_queue::{CompilationEvent, Severity},
trace::TraceRawVcs,
};
......
......@@ -18,7 +18,7 @@ use owo_colors::OwoColorize;
use serde::Serialize;
use terminal_hyperlink::Hyperlink;
use turbo_tasks::{
PrettyPrintError, TurboTasks, TurboTasksApi,
PrettyPrintError, TurboTasks, TurboTasksCallApi,
backend::TurboTasksExecutionError,
message_queue::{CompilationEvent, Severity},
};
......
......@@ -16,7 +16,7 @@ use std::{
use bincode::{Decode, Encode};
use turbo_tasks::{
CellId, FxIndexMap, TaskExecutionReason, TaskId, TaskPriority, TurboTasksBackendApi,
TypedSharedReference, backend::CachedTaskType,
TurboTasksCallApi, TypedSharedReference, backend::CachedTaskType,
};
use crate::{
......@@ -93,6 +93,7 @@ pub trait ExecuteContext<'e>: Sized {
fn suspending_requested(&self) -> bool;
fn should_track_dependencies(&self) -> bool;
fn should_track_activeness(&self) -> bool;
fn turbo_tasks(&self) -> Arc<dyn TurboTasksCallApi>;
}
pub trait ChildExecuteContext<'e>: Send + Sized {
......@@ -637,6 +638,10 @@ where
fn should_track_activeness(&self) -> bool {
self.backend.should_track_activeness()
}
fn turbo_tasks(&self) -> Arc<dyn TurboTasksCallApi> {
self.turbo_tasks.pin()
}
}
struct ChildExecuteContextImpl<'e, B: BackingStorage> {
......
......@@ -1010,7 +1010,7 @@ mod tests {
fn test_schema_size() {
assert_eq!(
size_of::<TaskStorage>(),
144,
136,
"TaskStorage size changed! If this is intentional, update this test."
);
assert_eq!(
......
use std::{
fmt::{self, Debug, Display},
pin::Pin,
sync::Arc,
};
use anyhow::Result;
......@@ -9,10 +10,12 @@ use parking_lot::Mutex;
use rustc_hash::FxHashSet;
use turbo_tasks::{
CellId, RawVc, TaskExecutionReason, TaskId, TaskPriority, TraitTypeId,
backend::{TransientTaskRoot, TurboTasksExecutionError},
backend::TransientTaskRoot,
event::{Event, EventDescription, EventListener},
};
use crate::error::TaskError;
// this traits are needed for the transient variants of `CachedDataItem`
// transient variants are never cloned or compared
macro_rules! transient_traits {
......@@ -78,8 +81,9 @@ impl CollectiblesRef {
pub enum OutputValue {
Cell(CellRef),
Output(TaskId),
Error(TurboTasksExecutionError),
Error(Arc<TaskError>),
}
impl OutputValue {
/// Returns true if this output value references a transient task.
///
......
//! Compact error representation for storage in the turbo-tasks backend.
//!
//! [`TurboTasksExecutionError`] contains the whole chain of errors. That is expensive to store and
//! we would duplicate error messages for many tasks. [`TaskError`] is a backend-internal
//! representation that replaces nested [`TurboTasksExecutionError::TaskContext`] chains with a flat
//! list of [`TaskId`]s (`TaskChain`), and omits the actual error message behind them. The actual
//! error content is recovered at read time by looking up the task's output, and task names are
//! resolved lazily via `TurboTasksCallApi::get_task_name`.
use std::sync::Arc;
use bincode::{Decode, Encode};
use smallvec::SmallVec;
use turbo_rcstr::RcStr;
use turbo_tasks::{
TaskId, TurboTasksPanic,
backend::{TurboTasksExecutionError, TurboTasksExecutionErrorMessage},
};
/// An error with a message and an optional cause.
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub struct TaskErrorItem {
pub message: TurboTasksExecutionErrorMessage,
pub source: Option<TaskError>,
}
/// Context for a local task that failed.
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub struct LocalTaskContext {
pub name: RcStr,
pub source: Option<TaskError>,
}
/// Compact, serializable representation of a task execution error.
///
/// `TaskContext` chains are collapsed into a flat [`TaskChain`](TaskError::TaskChain) of
/// [`TaskId`]s. The source error is not stored in the chain; it is recovered by looking up the
/// output of the last task in the chain.
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub enum TaskError {
Panic(Arc<TurboTasksPanic>),
Error(Box<TaskErrorItem>),
LocalTaskContext(Box<LocalTaskContext>),
/// A chain of task IDs representing nested `TaskContext` wrappers. The last element is the
/// innermost task whose output holds the actual error. Earlier elements are outer tasks that
/// propagated the error. The source error is not stored here. The task id acts as a pointer to
/// the originating task's output.
TaskChain(SmallVec<[TaskId; 4]>),
}
/// Converts a [`TurboTasksExecutionError`] into the compact [`TaskError`] representation.
/// Nested `TaskContext` chains are flattened into a single [`TaskError::TaskChain`].
impl From<&TurboTasksExecutionError> for TaskError {
fn from(value: &TurboTasksExecutionError) -> Self {
match value {
TurboTasksExecutionError::Panic(panic) => TaskError::Panic(panic.clone()),
TurboTasksExecutionError::Error(error) => TaskError::Error(Box::new(TaskErrorItem {
message: error.message.clone(),
source: error.source.as_ref().map(|e| e.into()),
})),
TurboTasksExecutionError::LocalTaskContext(local_task_context) => {
TaskError::LocalTaskContext(Box::new(LocalTaskContext {
name: local_task_context.name.clone(),
source: local_task_context.source.as_ref().map(|e| e.into()),
}))
}
TurboTasksExecutionError::TaskContext(task_context) => {
let mut chain = SmallVec::new();
chain.push(task_context.task_id);
let mut current_error = task_context.source.as_ref();
while let Some(error) = current_error {
match error {
TurboTasksExecutionError::TaskContext(task_context) => {
chain.push(task_context.task_id);
current_error = task_context.source.as_ref();
}
_ => {
return TaskError::TaskChain(chain);
}
}
}
TaskError::TaskChain(chain)
}
}
}
}
/// Compares optional errors across the two representations.
fn eq_option(this: &Option<TaskError>, other: &Option<TurboTasksExecutionError>) -> bool {
match (this, other) {
(Some(this), Some(other)) => this == other,
(None, None) => true,
_ => false,
}
}
/// Cross-type equality used to detect whether a task's stored error has changed (to avoid
/// unnecessary dirty-flagging). For `TaskChain`, only the task ID chain is compared — the source
/// error content is not checked because the chain acts as a pointer to the originating task.
impl PartialEq<TurboTasksExecutionError> for TaskError {
fn eq(&self, other: &TurboTasksExecutionError) -> bool {
match (self, other) {
(TaskError::Panic(this), TurboTasksExecutionError::Panic(other)) => this == other,
(TaskError::Error(this), TurboTasksExecutionError::Error(other)) => {
this.message == other.message && eq_option(&this.source, &other.source)
}
(
TaskError::LocalTaskContext(this),
TurboTasksExecutionError::LocalTaskContext(other),
) => this.name == other.name && eq_option(&this.source, &other.source),
(TaskError::TaskChain(chain), TurboTasksExecutionError::TaskContext(other)) => {
if chain.is_empty() {
return false;
}
if chain[0] != other.task_id {
return false;
}
let mut current_source = other.source.as_ref();
for &task_id in &chain[1..] {
if let Some(TurboTasksExecutionError::TaskContext(task_context)) =
current_source
{
if task_context.task_id != task_id {
return false;
}
current_source = task_context.source.as_ref();
} else {
return false;
}
}
// TaskError will stop at the last task in the chain (this is a pointer), so we do
// not compare further.
true
}
_ => false,
}
}
}
......@@ -7,6 +7,7 @@ mod backend;
mod backing_storage;
mod data;
mod database;
mod error;
mod kv_backing_storage;
mod utils;
......
......@@ -155,6 +155,16 @@ impl TurboTasksCallApi for VcStorage {
) {
unreachable!()
}
/// Should not be called on the testing VcStorage. These methods are only implemented for
/// structs with access to a `MessageQueue` like `TurboTasks`.
fn send_compilation_event(&self, _event: Arc<dyn CompilationEvent>) {
unimplemented!()
}
fn get_task_name(&self, task: TaskId) -> String {
format!("Task({})", task)
}
}
impl TurboTasksApi for VcStorage {
......@@ -316,12 +326,6 @@ impl TurboTasksApi for VcStorage {
unimplemented!()
}
/// Should not be called on the testing VcStorage. These methods are only implemented for
/// structs with access to a `MessageQueue` like `TurboTasks`.
fn send_compilation_event(&self, _event: Arc<dyn CompilationEvent>) {
unimplemented!()
}
fn is_tracking_dependencies(&self) -> bool {
false
}
......
......@@ -12,6 +12,8 @@ use anyhow::{Result, anyhow};
use auto_hash_map::AutoMap;
use bincode::{
Decode, Encode,
de::Decoder,
enc::Encoder,
error::{DecodeError, EncodeError},
impl_borrow_decode,
};
......@@ -26,10 +28,10 @@ use turbo_rcstr::RcStr;
use crate::{
RawVc, ReadCellOptions, ReadOutputOptions, ReadRef, SharedReference, TaskId, TaskIdSet,
TaskPriority, TraitRef, TraitTypeId, TurboTasksPanic, ValueTypeId, VcValueTrait, VcValueType,
event::EventListener, macro_helpers::NativeFunction, magic_any::MagicAny,
manager::TurboTasksBackendApi, raw_vc::CellId, registry,
task::shared_reference::TypedSharedReference, task_statistics::TaskStatisticsApi,
TaskPriority, TraitRef, TraitTypeId, TurboTasksCallApi, TurboTasksPanic, ValueTypeId,
VcValueTrait, VcValueType, event::EventListener, macro_helpers::NativeFunction,
magic_any::MagicAny, manager::TurboTasksBackendApi, raw_vc::CellId, registry,
task::shared_reference::TypedSharedReference, task_statistics::TaskStatisticsApi, turbo_tasks,
};
pub type TransientTaskRoot =
......@@ -273,7 +275,7 @@ pub type TaskCollectiblesMap = AutoMap<RawVc, i32, BuildHasherDefault<FxHasher>,
// Structurally and functionally similar to Cow<&'static, str> but explicitly notes the importance
// of non-static strings potentially containing PII (Personal Identifiable Information).
#[derive(Clone, Debug, Encode, Decode, PartialEq, Eq)]
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub enum TurboTasksExecutionErrorMessage {
PIISafe(#[bincode(with = "turbo_bincode::owned_cow")] Cow<'static, str>),
NonPIISafe(String),
......@@ -294,28 +296,92 @@ pub struct TurboTasksError {
pub source: Option<TurboTasksExecutionError>,
}
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
/// Error context indicating that a task's execution failed. Stores a `task_id` and a reference to
/// the `TurboTasksCallApi` so that the task name can be resolved lazily at display time (via
/// [`TurboTasksCallApi::get_task_name`]) rather than eagerly at error creation time.
#[derive(Clone)]
pub struct TurboTaskContextError {
pub task: RcStr,
#[cfg(feature = "task_id_details")]
pub task_id: Option<TaskId>,
pub turbo_tasks: Arc<dyn TurboTasksCallApi>,
pub task_id: TaskId,
pub source: Option<TurboTasksExecutionError>,
}
#[derive(Clone, Debug, Encode, Decode, PartialEq, Eq)]
impl PartialEq for TurboTaskContextError {
fn eq(&self, other: &Self) -> bool {
self.task_id == other.task_id && self.source == other.source
}
}
impl Eq for TurboTaskContextError {}
impl Encode for TurboTaskContextError {
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
Encode::encode(&self.task_id, encoder)?;
Encode::encode(&self.source, encoder)?;
Ok(())
}
}
impl<Context> Decode<Context> for TurboTaskContextError {
fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
let task_id = Decode::decode(decoder)?;
let source = Decode::decode(decoder)?;
let turbo_tasks = turbo_tasks();
Ok(Self {
turbo_tasks,
task_id,
source,
})
}
}
impl_borrow_decode!(TurboTaskContextError);
impl Debug for TurboTaskContextError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TurboTaskContextError")
.field("task_id", &self.task_id)
.field("source", &self.source)
.finish()
}
}
/// Error context for a local task that failed. Unlike [`TurboTaskContextError`],
/// this stores the task name directly since local tasks don't have a [`TaskId`].
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub struct TurboTaskLocalContextError {
pub name: RcStr,
pub source: Option<TurboTasksExecutionError>,
}
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub enum TurboTasksExecutionError {
Panic(Arc<TurboTasksPanic>),
Error(Arc<TurboTasksError>),
TaskContext(Arc<TurboTaskContextError>),
LocalTaskContext(Arc<TurboTaskLocalContextError>),
}
impl TurboTasksExecutionError {
pub fn with_task_context(&self, task: impl Display, _task_id: Option<TaskId>) -> Self {
/// Wraps this error in a [`TaskContext`](TurboTasksExecutionError::TaskContext) layer
/// identifying the normal task that encountered the error.
pub fn with_task_context(
self,
task_id: TaskId,
turbo_tasks: Arc<dyn TurboTasksCallApi>,
) -> Self {
TurboTasksExecutionError::TaskContext(Arc::new(TurboTaskContextError {
task: RcStr::from(task.to_string()),
#[cfg(feature = "task_id_details")]
task_id: _task_id,
source: Some(self.clone()),
task_id,
turbo_tasks,
source: Some(self),
}))
}
/// Wraps this error in a [`LocalTaskContext`](TurboTasksExecutionError::LocalTaskContext) layer
/// identifying the local task that encountered the error.
pub fn with_local_task_context(self, name: String) -> Self {
TurboTasksExecutionError::LocalTaskContext(Arc::new(TurboTaskLocalContextError {
name: RcStr::from(name),
source: Some(self),
}))
}
}
......@@ -330,6 +396,9 @@ impl Error for TurboTasksExecutionError {
TurboTasksExecutionError::TaskContext(context_error) => {
context_error.source.as_ref().map(|s| s as &dyn Error)
}
TurboTasksExecutionError::LocalTaskContext(context_error) => {
context_error.source.as_ref().map(|s| s as &dyn Error)
}
}
}
}
......@@ -342,15 +411,16 @@ impl Display for TurboTasksExecutionError {
write!(f, "{}", error.message)
}
TurboTasksExecutionError::TaskContext(context_error) => {
#[cfg(feature = "task_id_details")]
if let Some(task_id) = context_error.task_id {
return write!(
f,
"Execution of {} ({}) failed",
context_error.task, task_id
);
let task_id = context_error.task_id;
let name = context_error.turbo_tasks.get_task_name(task_id);
if cfg!(feature = "task_id_details") {
write!(f, "Execution of {name} ({}) failed", task_id)
} else {
write!(f, "Execution of {name} failed")
}
write!(f, "Execution of {} failed", context_error.task)
}
TurboTasksExecutionError::LocalTaskContext(context_error) => {
write!(f, "Execution of {} failed", context_error.name)
}
}
}
......@@ -566,4 +636,8 @@ pub trait Backend: Sync + Send {
fn task_statistics(&self) -> &TaskStatisticsApi;
fn is_tracking_dependencies(&self) -> bool;
/// Returns a human-readable name for the given task. Used by error display formatting
/// to lazily resolve task names instead of storing them eagerly in error objects.
fn get_task_name(&self, task: TaskId, turbo_tasks: &dyn TurboTasksBackendApi<Self>) -> String;
}
......@@ -94,6 +94,12 @@ pub trait TurboTasksCallApi: Sync + Send {
future: Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
fn start_once_process(&self, future: Pin<Box<dyn Future<Output = ()> + Send + 'static>>);
/// Sends a compilation event to subscribers.
fn send_compilation_event(&self, event: Arc<dyn CompilationEvent>);
/// Returns a human-readable name for the given task.
fn get_task_name(&self, task: TaskId) -> String;
}
/// A type-erased subset of [`TurboTasks`] stored inside a thread local when we're in a turbo task
......@@ -190,7 +196,6 @@ pub trait TurboTasksApi: TurboTasksCallApi + Sync + Send {
&self,
event_types: Option<Vec<String>>,
) -> Receiver<Arc<dyn CompilationEvent>>;
fn send_compilation_event(&self, event: Arc<dyn CompilationEvent>);
// Returns true if TurboTasks is configured to track dependencies.
fn is_tracking_dependencies(&self) -> bool;
......@@ -1274,7 +1279,7 @@ impl<B: Backend> Executor<TurboTasks<B>, ScheduledTask, TaskPriority> for TurboT
Ok(raw_vc) => OutputContent::Link(raw_vc),
Err(err) => OutputContent::Error(
TurboTasksExecutionError::from(err)
.with_task_context(task_type, None),
.with_local_task_context(task_type.to_string()),
),
};
......@@ -1374,6 +1379,16 @@ impl<B: Backend + 'static> TurboTasksCallApi for TurboTasks<B> {
fn start_once_process(&self, future: Pin<Box<dyn Future<Output = ()> + Send + 'static>>) {
self.start_once_process(future)
}
fn send_compilation_event(&self, event: Arc<dyn CompilationEvent>) {
if let Err(e) = self.compilation_events.send(event) {
tracing::warn!("Failed to send compilation event: {e}");
}
}
fn get_task_name(&self, task: TaskId) -> String {
self.backend.get_task_name(task, self)
}
}
impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
......@@ -1580,12 +1595,6 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
self.compilation_events.subscribe(event_types)
}
fn send_compilation_event(&self, event: Arc<dyn CompilationEvent>) {
if let Err(e) = self.compilation_events.send(event) {
tracing::warn!("Failed to send compilation event: {e}");
}
}
fn is_tracking_dependencies(&self) -> bool {
self.backend.is_tracking_dependencies()
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment