Skip to content
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

task: add panic string to debug/display output of JoinError #6753

Merged
merged 5 commits into from
Aug 7, 2024

Conversation

abonander
Copy link
Contributor

@abonander abonander commented Aug 6, 2024

Fixes: #6749

cc @Darksonn

Unresolved questions:

  • Would it be useful to expose panic_payload_as_str() as an inherent method on JoinError?
  • Do we want to support the alternate-formatting flag ({:#}, {:#?}) to hide the panic message?
  • If the panic payload is not String or &'static str, should anything else be printed (e.g. "<non-string payload>")?
  • Does this behavior need to be documented?
  • Does this need a test? The purpose of the existing relevant tests is not clear:
    • rt_panic.rs and task_panic.rs seem primarily concerned with correct reporting of the panic location.
    • task_abort.rs appears to be primarily regression tests.

Motivation

(From #6749)

When building Tokio applications, we almost always want to capture a tokio::task::JoinError and turn it into another error, e.g. eyre::Report and bubble it up. We don't generally explicitly cancel tasks, so the main possible source of errors is panics.

Because JoinError doesn't include the panic payload in its Debug or Display output, we end up with the same copy-pasted conversion functions in every single project:

pub fn map_join_error(err: tokio::task::JoinError) -> eyre::Report {
    let Ok(panic) = err.try_into_panic() else {
        return eyre::eyre!("task cancelled");
    };

    let panic_str = panic_payload_to_str(&panic);

    eyre::eyre!("task panicked: {panic_str}")
}

/// Extract a string from a panic payload.
pub fn panic_payload_to_str<'a>(panic: &'a (dyn std::any::Any + 'static)) -> &'a str {
    // Panic payloads are almost always `String` (if made with formatting arguments)
    // or `&'static str` (if given a string literal).
    //
    // Non-string payloads are a legacy feature so we don't need to worry about those much.
    panic
        .downcast_ref::<String>()
        .map(|s| &**s)
        .or_else(|| panic.downcast_ref::<&'static str>().copied())
        .unwrap_or("(non-string payload)")
}

Solution

(From #6749)

Include the logic similar to panic_payload_to_str() shown above to extract the payload string of a panic, if applicable, and include it in the Debug and Display output of JoinError.

The logic is identical to that in the default panic hook in std: https://github.com/rust-lang/rust/blob/e57f3090aec33cdbf66063c866afaa5e1e78b9bb/library/std/src/panicking.rs#L744-L751

@github-actions github-actions bot added R-loom-current-thread Run loom current-thread tests on this PR R-loom-multi-thread Run loom multi-thread tests on this PR R-loom-multi-thread-alt Run loom multi-thread alt tests on this PR labels Aug 6, 2024
@Darksonn Darksonn added A-tokio Area: The main tokio crate M-task Module: tokio/task labels Aug 6, 2024
@Darksonn
Copy link
Contributor

Darksonn commented Aug 6, 2024

Would it be useful to expose panic_payload_as_str() as an inherent method on JoinError?

For now, let's not do that.

Do we want to support the alternate-formatting flag ({:#}, {:#?}) to hide the panic message?

I don't think that's necessary.

If the panic payload is not String or &'static str, should anything else be printed (e.g. "<non-string payload>")?

We can mirror std and print Box<dyn Any>.

Does this behavior need to be documented?

Nah, it's fine as is.

Does this need a test? The purpose of the existing relevant tests is not clear:

I would like to see a single test. I'm curious how the {:?} gets formatted, and I'm wondering if we want to print the &str with Display instead of Debug.

@abonander
Copy link
Contributor Author

I would like to see a single test.

Can you tell me where it should go?

@Darksonn
Copy link
Contributor

Darksonn commented Aug 6, 2024

We don't have a perfect file for it, but you can use task_abort.rs.

@abonander
Copy link
Contributor Author

@Darksonn while I'm at it, what do you think of making the Debug impl use debug_struct() so we can label the fields with useful names?

@abonander
Copy link
Contributor Author

@abonander
Copy link
Contributor Author

As it turns out, we can't just assert the full string output of these impls because the task ID can change...

@abonander
Copy link
Contributor Author

We can mirror std and print Box<dyn Any>.

That would work fine for the Debug output, but what about Display?

@abonander abonander force-pushed the join-error-panic-str branch from ed37000 to 9b2719d Compare August 6, 2024 15:02
@abonander abonander force-pushed the join-error-panic-str branch from 9b2719d to af5e9f2 Compare August 6, 2024 15:02
Copy link
Member

@mox692 mox692 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me.

@Darksonn Darksonn merged commit 0ecf5f0 into tokio-rs:master Aug 7, 2024
86 checks passed
@abonander
Copy link
Contributor Author

I still had a couple questions but if ya'll are happy with it, that works.

@Darksonn
Copy link
Contributor

Darksonn commented Aug 7, 2024

Yeah, this is fine. Thanks!

kodiakhq bot pushed a commit to pdylanross/fatigue that referenced this pull request Aug 30, 2024
Bumps tokio from 1.39.3 to 1.40.0.

Release notes
Sourced from tokio's releases.

Tokio v1.40.0
1.40.0 (August 30th, 2024)
Added

io: add util::SimplexStream (#6589)
process: stabilize Command::process_group (#6731)
sync: add {TrySendError,SendTimeoutError}::into_inner (#6755)
task: add JoinSet::join_all (#6784)

Added (unstable)

runtime: add Builder::{on_task_spawn, on_task_terminate} (#6742)

Changed

io: use vectored io for write_all_buf when possible (#6724)
runtime: prevent niche-optimization to avoid triggering miri (#6744)
sync: mark mpsc types as UnwindSafe (#6783)
sync,time: make Sleep and BatchSemaphore instrumentation explicit roots (#6727)
task: use NonZeroU64 for task::Id (#6733)
task: include panic message when printing JoinError (#6753)
task: add #[must_use] to JoinHandle::abort_handle (#6762)
time: eliminate timer wheel allocations (#6779)

Documented

docs: clarify that [build] section doesn't go in Cargo.toml (#6728)
io: clarify zero remaining capacity case (#6790)
macros: improve documentation for select! (#6774)
sync: document mpsc channel allocation behavior (#6773)

#6589: tokio-rs/tokio#6589
#6724: tokio-rs/tokio#6724
#6727: tokio-rs/tokio#6727
#6728: tokio-rs/tokio#6728
#6731: tokio-rs/tokio#6731
#6733: tokio-rs/tokio#6733
#6742: tokio-rs/tokio#6742
#6744: tokio-rs/tokio#6744
#6753: tokio-rs/tokio#6753
#6755: tokio-rs/tokio#6755
#6762: tokio-rs/tokio#6762
#6773: tokio-rs/tokio#6773
#6774: tokio-rs/tokio#6774
#6779: tokio-rs/tokio#6779
#6783: tokio-rs/tokio#6783
#6784: tokio-rs/tokio#6784
#6790: tokio-rs/tokio#6790



Commits

ea6d652 chore: prepare Tokio v1.40.0 (#6806)
11f66f4 chore: replace ready! with std::task::ready! (#6804)
479a56a time: eliminate timer wheel allocations (#6779)
b37f0de runtime: implement initial set of task hooks (#6742)
c9fad08 codec: fix typo in the docs for Encoder::Error (#6800)
cc70a21 task: add join_all method to JoinSet (#6784)
1ac8dff task: add AbortOnDropHandle type (#6786)
ff3f2a8 io: add SimplexStream (#6589)
5b9a290 io: clarify zero remaining capacity case (#6790)
70569bd task: fix typo in TaskTracker docs (#6792)
Additional commits viewable in compare view




Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


Dependabot commands and options

You can trigger Dependabot actions by commenting on this PR:

@dependabot rebase will rebase this PR
@dependabot recreate will recreate this PR, overwriting any edits that have been made to it
@dependabot merge will merge this PR after your CI passes on it
@dependabot squash and merge will squash and merge this PR after your CI passes on it
@dependabot cancel merge will cancel a previously requested merge and block automerging
@dependabot reopen will reopen this PR if it is closed
@dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
@dependabot show <dependency name> ignore conditions will show all of the ignore conditions of the specified dependency
@dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
@dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
@dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-tokio Area: The main tokio crate M-task Module: tokio/task R-loom-current-thread Run loom current-thread tests on this PR R-loom-multi-thread Run loom multi-thread tests on this PR R-loom-multi-thread-alt Run loom multi-thread alt tests on this PR
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Include panic payload string in JoinError display/debug output
3 participants