Skip to content

Tasks spawned via spawn_local have useless location information #5030

@kamirr

Description

@kamirr

Version
1.21.1

Platform

$ uname -a
Linux <privacy snip> 5.15.0-46-generic #49~20.04.1-Ubuntu SMP Thu Aug 4 19:15:44 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

Description
Tracing is not implemented properly for local tasks. Consider the following complete example:

async fn run() {
    for _ in 0..10 {
        tokio::task::spawn_local(async { println!("anon future"); }).await.unwrap();
    }
}

#[tokio::main(flavor="current_thread")]
async fn main() {
    console_subscriber::init();

    let local_set = tokio::task::LocalSet::new();
    local_set.run_until(run()).await;

    // program needs to remain live for tokio-console to work properly
    loop {
        tokio::time::sleep(std::time::Duration::from_secs_f32(60.0)).await;
    }
}

(Buildable project: tokio-spawn-local-repro.zip, run with RUSTFLAGS="--cfg tokio_unstable" cargo run)
tokio-console produces the following output:
image

From my investigation it appears that the problem stems from a lacking application of #[track_caller] in tokio/src/task/local.rs:

#[track_caller]
pub(super) fn spawn_local_inner<F>(future: F, name: Option<&str>) -> JoinHandle<F::Output>
where F: Future + 'static,
        F::Output: 'static
{
    CURRENT.with(|maybe_cx| { // line 317
        match maybe_cx.get() {
            None => panic!("`spawn_local` called from outside of a `task::LocalSet`"),
            Some(cx) => cx.spawn(future, name)
        }
    })
}

Notice that the closure has no #[track_caller] attribute, hence breaking the chain leading up to the call of Location::caller in Contex::spawn, meaning all locations will refer to the spawn_local_inner function body. #[track_caller] attribute cannot be currently applied to closures (it's an unstable feature), so another approach is necessary.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-tokioArea: The main tokio crateC-bugCategory: This is a bug.M-taskModule: tokio/task

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions