CodeSampleX

Пример

tokio 1.43.0: Tokio Runtime::Builder disables time and IO drivers by default, time::pause requires current_thread runtime, and TOKIO_WORKER_THREADS=0 panics multi-thread builds

Проверенный пример — cargo tokio 1.43.0: Tokio Runtime::Builder disables time and IO drivers by default, time::pause requires current_thread runtime, and…

sha256:3114583fe7d663d0553a5731690052f41f1660c66158047230a4198a72e13ca9

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
3
Ключи подписи, собравшие его
2
Заявленная среда rust linux x64 rust rust cargo

Среды запусков проверки

Окружение Контракт Этапы Запуск
rust 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1
2026-08-16
rust 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1
2026-08-18
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-09-08

Кейс

HOW
Цель
Tokio Runtime::Builder disables time and IO drivers by default, time::pause requires current_thread runtime, and TOKIO_WORKER_THREADS=0 panics multi-thread builds
Пакеты
Символы
  • tokio::runtime::Builder
  • tokio::runtime::Builder::enable_time
  • tokio::runtime::Builder::enable_io
  • tokio::runtime::Builder::enable_all
  • tokio::runtime::Builder::worker_threads
  • tokio::time::pause
  • tokio::time::advance
Окружение
rust
Создан
2026-08-16T06:47:46Z

Контракт

  1. assert tokio::runtime::Builder defaults to disabled timer and panics when calling sleep or timeout without enable_time or enable_all
  2. assert tokio::runtime::Builder defaults to disabled IO driver and panics when binding TcpListener without enable_io or enable_all
  3. assert tokio::time::pause panics when called on multi_thread runtime even with enable_time
  4. assert tokio::time::pause on current_thread runtime with enable_time enables instant virtual time advance
  5. assert tokio::runtime::Builder::enable_all enables both time and net operations successfully
  6. assert TOKIO_WORKER_THREADS=0 causes multi_thread runtime build to panic unless explicitly overridden by Builder::worker_threads

Файлы

  • Cargo.lock
  • Cargo.toml
  • NOTES.md
  • csx.json
  • src/lib.rs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "addr2line"
version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b"
dependencies = [
 "gimli",
]

[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"

[[package]]
name = "backtrace"
version = "0.3.76"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6"
dependencies = [
 "addr2line",
 "cfg-if",
 "libc",
 "miniz_oxide",
 "object",
 "rustc-demangle",
 "windows-link",
]

[[package]]
name = "bytes"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"

[[package]]
name = "cargo-tokio-config"
version = "0.1.0"
dependencies = [
 "tokio",
]

[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"

[[package]]
name = "gimli"
version = "0.32.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7"

[[package]]
name = "libc"
version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"

[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"

[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
 "adler2",
]

[[package]]
name = "mio"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
dependencies = [
 "libc",
 "wasi",
 "windows-sys 0.61.2",
]

[[package]]
name = "object"
version = "0.37.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe"
dependencies = [
 "memchr",
]

[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"

[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
 "unicode-ident",
]

[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
 "proc-macro2",
]

[[package]]
name = "rustc-demangle"
version = "0.1.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb"

[[package]]
name = "socket2"
version = "0.5.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678"
dependencies = [
 "libc",
 "windows-sys 0.52.0",
]

[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
 "proc-macro2",
 "quote",
 "unicode-ident",
]

[[package]]
name = "tokio"
version = "1.43.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d61fa4ffa3de412bfea335c6ecff681de2b609ba3c77ef3e00e521813a9ed9e"
dependencies = [
 "backtrace",
 "bytes",
 "libc",
 "mio",
 "pin-project-lite",
 "socket2",
 "tokio-macros",
 "windows-sys 0.52.0",
]

[[package]]
name = "tokio-macros"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8"
dependencies = [
 "proc-macro2",
 "quote",
 "syn",
]

[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"

[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"

[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"

[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
 "windows-targets",
]

[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
 "windows-link",
]

[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
 "windows_aarch64_gnullvm",
 "windows_aarch64_msvc",
 "windows_i686_gnu",
 "windows_i686_gnullvm",
 "windows_i686_msvc",
 "windows_x86_64_gnu",
 "windows_x86_64_gnullvm",
 "windows_x86_64_msvc",
]

[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"

[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"

[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"

[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"

[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"

[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"

[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"

[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
Cargo.toml
[package]
name = "cargo-tokio-config"
version = "0.1.0"
edition = "2021"

[dependencies]
tokio = { version = "=1.43.0", features = ["rt", "rt-multi-thread", "macros", "time", "net", "io-util", "sync", "test-util"] }
NOTES.md
### Search Result
`search_known_solution` answered with a HIT (`MATCH: COMPATIBLE`, sample `sha256:9b9720fef342edf7ef51c61e4781caeafe87bc3863b3fdfe9efd67fdb0a2caf8`), which proved `LocalSet` non-`Send` future driving and unpolled task starvation. To avoid duplicate coverage, this sample targets Tokio's runtime configuration, driver enablement requirements (`enable_time`/`enable_io`), `time::pause()` runtime-flavor restrictions (`current_thread` vs `multi_thread`), and `TOKIO_WORKER_THREADS` environment variable handling.

### What a model would have written instead
Models construct custom runtimes using `tokio::runtime::Builder::new_current_thread().build()` or `new_multi_thread().build()` expecting timer and network drivers to be enabled by default, and call `tokio::time::pause()` in multi-threaded test setups expecting it to pause the global timer.

### How the wrong version fails
Fails loudly at runtime with panic `"A Tokio 1.x context was found, but timers are disabled. Call enable_time on the runtime builder to enable timers"`, `"A Tokio 1.x context was found, but IO is disabled. Call enable_io on the runtime builder to enable IO"`, `"time::pause() requires the current_thread Tokio runtime"`, or `"TOKIO_WORKER_THREADS cannot be set to 0"`.
csx.json
{"case":{"caseId":"case:sha256:55ecd89fb33685b3e797bacb577da9b0690a5ea87b0d31c1a6d34ab82c8b1a97","contract":["assert tokio::runtime::Builder defaults to disabled timer and panics when calling sleep or timeout without enable_time or enable_all","assert tokio::runtime::Builder defaults to disabled IO driver and panics when binding TcpListener without enable_io or enable_all","assert tokio::time::pause panics when called on multi_thread runtime even with enable_time","assert tokio::time::pause on current_thread runtime with enable_time enables instant virtual time advance","assert tokio::runtime::Builder::enable_all enables both time and net operations successfully","assert TOKIO_WORKER_THREADS=0 causes multi_thread runtime build to panic unless explicitly overridden by Builder::worker_threads"],"goal":"Tokio Runtime::Builder disables time and IO drivers by default, time::pause requires current_thread runtime, and TOKIO_WORKER_THREADS=0 panics multi-thread builds","kind":"HOW","packages":["pkg:cargo/tokio@1.43.0"],"schemaVersion":1,"symbols":["tokio::runtime::Builder","tokio::runtime::Builder::enable_time","tokio::runtime::Builder::enable_io","tokio::runtime::Builder::enable_all","tokio::runtime::Builder::worker_threads","tokio::time::pause","tokio::time::advance"]},"contractCommand":["cargo","test","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","executionContext":"rust","language":"rust","os":"linux","packageManager":"cargo","runtime":"rust","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/tokio@1.43.0"],"schemaVersion":1,"symbols":["tokio::runtime::Builder","tokio::runtime::Builder::enable_time","tokio::runtime::Builder::enable_io","tokio::runtime::Builder::enable_all","tokio::runtime::Builder::worker_threads","tokio::time::pause","tokio::time::advance"],"verifierAdapter":"cargo@1"}
src/lib.rs
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::time::{Duration, Instant};

fn extract_panic_message(err: Box<dyn std::any::Any + Send>) -> String {
    if let Some(s) = err.downcast_ref::<&str>() {
        s.to_string()
    } else if let Some(s) = err.downcast_ref::<String>() {
        s.clone()
    } else {
        "Unknown panic".to_string()
    }
}

/// 1. Calling time APIs without `enable_time()` or `enable_all()` panics with timer driver error
pub fn time_without_timer_driver_panics() {
    let rt = tokio::runtime::Builder::new_current_thread()
        .build()
        .expect("builder succeeds without drivers");

    // sleep panics when polled without timer driver
    let sleep_result = catch_unwind(AssertUnwindSafe(|| {
        rt.block_on(async {
            tokio::time::sleep(Duration::from_millis(10)).await;
        });
    }));
    assert!(sleep_result.is_err());
    let msg = extract_panic_message(sleep_result.unwrap_err());
    assert!(
        msg.contains("timers are disabled") && msg.contains("enable_time"),
        "Unexpected panic message: {}",
        msg
    );

    // timeout panics immediately even if inner future is ready
    let timeout_result = catch_unwind(AssertUnwindSafe(|| {
        let _ = rt.block_on(async {
            tokio::time::timeout(Duration::from_secs(1), async { 42 }).await
        });
    }));
    assert!(timeout_result.is_err());
    let msg = extract_panic_message(timeout_result.unwrap_err());
    assert!(
        msg.contains("timers are disabled") && msg.contains("enable_time"),
        "Unexpected panic message: {}",
        msg
    );
}

/// 2. Calling net/IO APIs without `enable_io()` or `enable_all()` panics with IO driver error
pub fn net_without_io_driver_panics() {
    let rt = tokio::runtime::Builder::new_current_thread()
        .build()
        .expect("builder succeeds without drivers");

    let bind_result = catch_unwind(AssertUnwindSafe(|| {
        let _ = rt.block_on(async {
            let _ = tokio::net::TcpListener::bind("127.0.0.1:0").await;
        });
    }));
    assert!(bind_result.is_err());
    let msg = extract_panic_message(bind_result.unwrap_err());
    assert!(
        msg.contains("IO is disabled") && msg.contains("enable_io"),
        "Unexpected panic message: {}",
        msg
    );
}

/// 3. Calling `tokio::time::pause()` on a multi-thread runtime panics
pub fn pause_time_on_multi_thread_runtime_panics() {
    let rt = tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .enable_time()
        .build()
        .expect("multi_thread runtime built with enable_time");

    let pause_result = catch_unwind(AssertUnwindSafe(|| {
        rt.block_on(async {
            tokio::time::pause();
        });
    }));
    assert!(pause_result.is_err());
    let msg = extract_panic_message(pause_result.unwrap_err());
    assert!(
        msg.contains("`time::pause()` requires the `current_thread` Tokio runtime"),
        "Unexpected panic message: {}",
        msg
    );
}

/// 4. `tokio::time::pause()` on `current_thread` enables instant virtual time advancement
pub fn pause_and_advance_time_on_current_thread() {
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_time()
        .build()
        .expect("current_thread runtime built with enable_time");

    rt.block_on(async {
        tokio::time::pause();

        let real_start = Instant::now();
        let tokio_start = tokio::time::Instant::now();

        // Advance mock time by 1 hour (3600 seconds)
        let sleep_fut = tokio::time::sleep(Duration::from_secs(3600));
        tokio::time::advance(Duration::from_secs(3600)).await;
        sleep_fut.await;

        let real_elapsed = real_start.elapsed();
        let tokio_elapsed = tokio::time::Instant::now().duration_since(tokio_start);

        // Real wall-clock time is near zero (less than 100ms)
        assert!(
            real_elapsed < Duration::from_millis(100),
            "Paused time sleep+advance should complete instantly, took {:?}",
            real_elapsed
        );
        // Tokio virtual time advanced by at least 1 hour
        assert!(
            tokio_elapsed >= Duration::from_secs(3600),
            "Tokio virtual clock must advance by at least 3600s, was {:?}",
            tokio_elapsed
        );
    });
}

/// 5. Driver flags enable normal operation when properly configured
pub fn drivers_enabled_allow_time_and_io() {
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("current_thread runtime with enable_all");

    rt.block_on(async {
        // Time operations work
        let res = tokio::time::timeout(Duration::from_millis(100), async {
            tokio::time::sleep(Duration::from_millis(1)).await;
            42
        })
        .await;
        assert_eq!(res.unwrap(), 42);

        // IO operations work on localhost/127.0.0.1
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind listener");
        let local_addr = listener.local_addr().expect("local addr");
        assert!(local_addr.port() > 0);
    });
}

/// 6. TOKIO_WORKER_THREADS=0 environment variable causes default multi_thread build to panic, but explicit worker_threads overrides
pub fn worker_threads_zero_env_var_behavior() {
    // Save previous env var if set
    let prev = std::env::var("TOKIO_WORKER_THREADS").ok();

    std::env::set_var("TOKIO_WORKER_THREADS", "0");

    // Unconfigured worker threads reads TOKIO_WORKER_THREADS=0 and panics
    let zero_result = catch_unwind(AssertUnwindSafe(|| {
        let _ = tokio::runtime::Builder::new_multi_thread().build();
    }));
    assert!(zero_result.is_err());
    let msg = extract_panic_message(zero_result.unwrap_err());
    assert!(
        msg.contains("TOKIO_WORKER_THREADS") && msg.contains("0"),
        "Unexpected panic message: {}",
        msg
    );

    // Explicit worker_threads(2) overrides the TOKIO_WORKER_THREADS env var and succeeds
    let override_result = catch_unwind(AssertUnwindSafe(|| {
        let rt = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(2)
            .build()
            .expect("explicit worker_threads overrides env var");
        rt.block_on(async { 100 })
    }));
    assert_eq!(override_result.unwrap(), 100);

    // Restore environment
    match prev {
        Some(v) => std::env::set_var("TOKIO_WORKER_THREADS", v),
        None => std::env::remove_var("TOKIO_WORKER_THREADS"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_time_without_timer_driver_panics() {
        time_without_timer_driver_panics();
    }

    #[test]
    fn test_net_without_io_driver_panics() {
        net_without_io_driver_panics();
    }

    #[test]
    fn test_pause_time_on_multi_thread_runtime_panics() {
        pause_time_on_multi_thread_runtime_panics();
    }

    #[test]
    fn test_pause_and_advance_time_on_current_thread() {
        pause_and_advance_time_on_current_thread();
    }

    #[test]
    fn test_drivers_enabled_allow_time_and_io() {
        drivers_enabled_allow_time_and_io();
    }

    #[test]
    fn test_worker_threads_zero_env_var_behavior() {
        worker_threads_zero_env_var_behavior();
    }
}

Исходный сидер

csx-seed