Skip to content

turbo-tasks: Encode location information into panics #78945

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion crates/napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,19 @@ static ALLOC: dhat::Alloc = dhat::Alloc;

#[cfg(not(target_arch = "wasm32"))]
#[napi::module_init]

fn init() {
use std::panic::{set_hook, take_hook};

use tokio::runtime::Builder;
use turbo_tasks::handle_panic;
use turbo_tasks_malloc::TurboMalloc;

let prev_hook = take_hook();
set_hook(Box::new(move |info| {
handle_panic(info);
prev_hook(info);
}));

let rt = Builder::new_multi_thread()
.enable_all()
.on_thread_stop(|| {
Expand Down
10 changes: 4 additions & 6 deletions turbopack/crates/turbo-tasks-backend/src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use turbo_tasks::{
SessionId, TRANSIENT_TASK_BIT, TaskId, TraitTypeId, TurboTasksBackendApi, ValueTypeId,
backend::{
Backend, BackendJobId, CachedTaskType, CellContent, TaskExecutionSpec, TransientTaskRoot,
TransientTaskType, TypedCellContent,
TransientTaskType, TurboTasksExecutionError, TypedCellContent,
},
event::{Event, EventListener},
registry::{self, get_value_type_global_name},
Expand Down Expand Up @@ -553,9 +553,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
let result = match output {
OutputValue::Cell(cell) => Some(Ok(Ok(RawVc::TaskCell(cell.task, cell.cell)))),
OutputValue::Output(task) => Some(Ok(Ok(RawVc::TaskOutput(*task)))),
OutputValue::Error | OutputValue::Panic => {
get!(task, Error).map(|error| Err(error.clone().into()))
}
OutputValue::Error => get!(task, Error).map(|error| Err(error.clone().into())),
};
if let Some(result) = result {
if self.should_track_dependencies() {
Expand Down Expand Up @@ -1406,7 +1404,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
fn task_execution_result(
&self,
task_id: TaskId,
result: Result<Result<RawVc>, Option<Cow<'static, str>>>,
result: Result<RawVc, Arc<TurboTasksExecutionError>>,
turbo_tasks: &dyn TurboTasksBackendApi<TurboTasksBackend<B>>,
) {
operation::UpdateOutputOperation::run(task_id, result, self.execute_context(turbo_tasks));
Expand Down Expand Up @@ -2338,7 +2336,7 @@ impl<B: BackingStorage> Backend for TurboTasksBackend<B> {
fn task_execution_result(
&self,
task_id: TaskId,
result: Result<Result<RawVc>, Option<Cow<'static, str>>>,
result: Result<RawVc, Arc<TurboTasksExecutionError>>,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) {
self.0.task_execution_result(task_id, result, turbo_tasks);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::{borrow::Cow, mem::take};
use std::{mem::take, sync::Arc};

use anyhow::{Result, anyhow};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use turbo_tasks::{RawVc, TaskId, util::SharedError};
use turbo_tasks::{RawVc, TaskId, backend::TurboTasksExecutionError, util::SharedError};

#[cfg(feature = "trace_task_dirty")]
use crate::backend::operation::invalidate::TaskDirtyCause;
Expand Down Expand Up @@ -44,7 +44,7 @@ pub enum UpdateOutputOperation {
impl UpdateOutputOperation {
pub fn run(
task_id: TaskId,
output: Result<Result<RawVc>, Option<Cow<'static, str>>>,
output: Result<RawVc, Arc<TurboTasksExecutionError>>,
mut ctx: impl ExecuteContext,
) {
let mut task = ctx.task(task_id, TaskDataCategory::All);
Expand All @@ -69,15 +69,15 @@ impl UpdateOutputOperation {
let old_error = task.remove(&CachedDataItemKey::Error {});
let current_output = get!(task, Output);
let output_value = match output {
Ok(Ok(RawVc::TaskOutput(output_task_id))) => {
Ok(RawVc::TaskOutput(output_task_id)) => {
if let Some(OutputValue::Output(current_task_id)) = current_output {
if *current_task_id == output_task_id {
return;
}
}
OutputValue::Output(output_task_id)
}
Ok(Ok(RawVc::TaskCell(output_task_id, cell))) => {
Ok(RawVc::TaskCell(output_task_id, cell)) => {
if let Some(OutputValue::Cell(CellRef {
task: current_task_id,
cell: current_cell,
Expand All @@ -92,28 +92,18 @@ impl UpdateOutputOperation {
cell,
})
}
Ok(Ok(RawVc::LocalOutput(..))) => {
Ok(RawVc::LocalOutput(..)) => {
panic!("Non-local tasks must not return a local Vc");
}
Ok(Err(err)) => {
Err(err) => {
task.insert(CachedDataItem::Error {
value: SharedError::new(err.context(format!(
value: SharedError::new(anyhow::Error::new(err).context(format!(
"Execution of {} failed",
ctx.get_task_description(task_id)
))),
});
OutputValue::Error
}
Err(panic) => {
task.insert(CachedDataItem::Error {
value: SharedError::new(anyhow!(
"Panic in {}: {:?}",
ctx.get_task_description(task_id),
panic
)),
});
OutputValue::Panic
}
};
let old_content = task.insert(CachedDataItem::Output {
value: output_value,
Expand Down
2 changes: 0 additions & 2 deletions turbopack/crates/turbo-tasks-backend/src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,13 @@ pub enum OutputValue {
Cell(CellRef),
Output(TaskId),
Error,
Panic,
}
impl OutputValue {
fn is_transient(&self) -> bool {
match self {
OutputValue::Cell(cell) => cell.task.is_transient(),
OutputValue::Output(task) => task.is_transient(),
OutputValue::Error => false,
OutputValue::Panic => false,
}
}
}
Expand Down
49 changes: 49 additions & 0 deletions turbopack/crates/turbo-tasks-backend/tests/panics.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use core::panic;
use std::{
panic::{set_hook, take_hook},
sync::{Arc, LazyLock},
};

use anyhow::Result;
use regex::Regex;
use turbo_tasks::{Vc, backend::TurboTasksExecutionError, handle_panic};
use turbo_tasks_testing::{Registration, register, run_without_cache_check};

static REGISTRATION: Registration = register!();

static FILE_PATH_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"panics\.rs:\d+:\d+$").unwrap());

#[tokio::test]
async fn test_panics_include_location() {
let prev_hook = take_hook();
set_hook(Box::new(move |info| {
handle_panic(info);
prev_hook(info);
}));

let result =
run_without_cache_check(&REGISTRATION, async move { anyhow::Ok(*double(3).await?) }).await;

let error = result.unwrap_err();
let root_cause = error.root_cause();

let Some(panic) = root_cause.downcast_ref::<Arc<TurboTasksExecutionError>>() else {
panic!("Expected a TurboTasksExecutionError");
};

let TurboTasksExecutionError::Panic(panic) = &**panic else {
panic!("Expected a TurboTasksExecutionError::Panic");
};

assert!(
FILE_PATH_REGEX.is_match(panic.location.as_ref().unwrap()),
"Panic location '{}' should be a line in panics.rs",
panic.location.as_ref().unwrap()
);
}

#[turbo_tasks::function]
fn double(_val: u64) -> Result<Vc<u64>> {
panic!("oh no");
}
9 changes: 3 additions & 6 deletions turbopack/crates/turbo-tasks-backend/tests/trace_transient.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,9 @@ async fn test_trace_transient() {
anyhow::Ok(())
})
.await;
assert!(
result
.unwrap_err()
.to_string()
.contains(&EXPECTED_TRACE.escape_debug().to_string())
);

let message = format!("{:#}", result.unwrap_err());
assert!(message.contains(&EXPECTED_TRACE.to_string()));
}

#[turbo_tasks::value]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,9 @@ async fn test_transient_emit_from_persistent() {
anyhow::Ok(())
})
.await;
assert!(
result
.unwrap_err()
.to_string()
.contains(&EXPECTED_MSG.escape_debug().to_string())
);

let message = format!("{:#}", result.unwrap_err());
assert!(message.contains(&EXPECTED_MSG.to_string()));
}

#[turbo_tasks::function(operation)]
Expand Down
8 changes: 4 additions & 4 deletions turbopack/crates/turbo-tasks-memory/src/memory_backend.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{
borrow::{Borrow, Cow},
borrow::Borrow,
future::Future,
hash::{BuildHasher, BuildHasherDefault, Hash},
num::NonZeroU32,
Expand All @@ -22,7 +22,7 @@ use turbo_tasks::{
TaskIdSet, TraitTypeId, TurboTasksBackendApi, Unused, ValueTypeId,
backend::{
Backend, BackendJobId, CachedTaskType, CellContent, TaskCollectiblesMap, TaskExecutionSpec,
TransientTaskType, TypedCellContent,
TransientTaskType, TurboTasksExecutionError, TypedCellContent,
},
event::EventListener,
task_statistics::TaskStatisticsApi,
Expand Down Expand Up @@ -415,12 +415,12 @@ impl Backend for MemoryBackend {
fn task_execution_result(
&self,
task_id: TaskId,
result: Result<Result<RawVc>, Option<Cow<'static, str>>>,
result: Result<RawVc, Arc<TurboTasksExecutionError>>,
turbo_tasks: &dyn TurboTasksBackendApi<MemoryBackend>,
) {
self.with_task(task_id, |task| {
#[cfg(debug_assertions)]
if let Ok(Ok(RawVc::TaskOutput(result))) = result.as_ref() {
if let Ok(RawVc::TaskOutput(result)) = result.as_ref() {
if *result == task_id {
panic!("Task {} returned itself as output", task.get_description());
}
Expand Down
14 changes: 1 addition & 13 deletions turbopack/crates/turbo-tasks-memory/src/output.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{borrow::Cow, fmt::Debug, mem::take};
use std::{fmt::Debug, mem::take};

use anyhow::{Error, Result, anyhow};
use turbo_tasks::{
Expand Down Expand Up @@ -51,18 +51,6 @@ impl Output {
}
}

pub fn panic(
&mut self,
message: Option<Cow<'static, str>>,
turbo_tasks: &dyn TurboTasksBackendApi<MemoryBackend>,
) {
self.content = Some(OutputContent::Panic(message.map(Box::new)));
// notify
if !self.dependent_tasks.is_empty() {
turbo_tasks.schedule_notify_tasks_set(&take(&mut self.dependent_tasks));
}
}

pub fn gc_drop(self, turbo_tasks: &dyn TurboTasksBackendApi<MemoryBackend>) {
// notify
if !self.dependent_tasks.is_empty() {
Expand Down
24 changes: 15 additions & 9 deletions turbopack/crates/turbo-tasks-memory/src/task.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::{
borrow::Cow,
fmt::{self, Debug, Display, Formatter},
future::Future,
hash::{BuildHasherDefault, Hash},
Expand All @@ -21,7 +20,10 @@ use turbo_prehash::PreHashed;
use turbo_tasks::{
CellId, Invalidator, RawVc, ReadConsistency, TaskId, TaskIdSet, TraitTypeId,
TurboTasksBackendApi, TurboTasksBackendApiExt, ValueTypeId,
backend::{CachedTaskType, CellContent, TaskCollectiblesMap, TaskExecutionSpec},
backend::{
CachedTaskType, CellContent, TaskCollectiblesMap, TaskExecutionSpec,
TurboTasksExecutionError,
},
event::{Event, EventListener},
get_invalidator, registry,
};
Expand Down Expand Up @@ -837,7 +839,7 @@ impl Task {

pub(crate) fn execution_result(
&self,
result: Result<Result<RawVc>, Option<Cow<'static, str>>>,
result: Result<RawVc, Arc<TurboTasksExecutionError>>,
backend: &MemoryBackend,
turbo_tasks: &dyn TurboTasksBackendApi<MemoryBackend>,
) {
Expand All @@ -849,7 +851,7 @@ impl Task {
// TODO maybe this should be controlled by a heuristic
}
InProgress(..) => match result {
Ok(Ok(result)) => {
Ok(result) => {
if state.output != result {
if backend.print_task_invalidation && state.output.content.is_some() {
println!(
Expand All @@ -865,13 +867,17 @@ impl Task {
state.output.link(result, turbo_tasks)
}
}
Ok(Err(mut err)) => {
if let Some(name) = self.get_function_name() {
err = err.context(format!("Execution of {name} failed"));
}
Err(err) => {
let err = anyhow::Error::new(err).context(
if let Some(name) = self.get_function_name() {
format!("Execution of {name} failed")
} else {
"Execution failed".to_string()
},
);

state.output.error(err, turbo_tasks)
}
Err(message) => state.output.panic(message, turbo_tasks),
},

Dirty { .. } | Scheduled { .. } | Done { .. } => {
Expand Down
Loading
Loading