CodeSampleX

Exemplo

once_cell 1.21.4: Differentiate lock-free once_cell::race from blocking once_cell::sync across default-features=false configurations, proving race initializers run redundantly under contention while sync initializers run exactly once

Amostra verificada para cargo once_cell 1.21.4: Differentiate lock-free once_cell::race from blocking once_cell::sync across default-features=false…

sha256:2540d92a67fbf6a1022bea9ae03def3fce5c135fae138bc0e6af3be8d4884445

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
3
Chaves de assinatura que o compilaram
2
Ambiente declarado rust linux x64 rust rust cargo

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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 SKIPPED compile:SKIPPED · contract:SKIPPED · load:SKIPPED · resolve:FAIL
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-09-08

Caso

HOW
Objetivo
Differentiate lock-free once_cell::race from blocking once_cell::sync across default-features=false configurations, proving race initializers run redundantly under contention while sync initializers run exactly once
Pacotes
Símbolos
  • once_cell::race::OnceBox
  • once_cell::race::OnceBox::get_or_init
  • once_cell::race::OnceNonZeroUsize
  • once_cell::race::OnceNonZeroUsize::get_or_init
  • once_cell::race::OnceBool
  • once_cell::race::OnceBool::get_or_init
  • once_cell::race::OnceRef
  • once_cell::race::OnceRef::get_or_init
  • once_cell::sync::OnceCell
  • once_cell::sync::OnceCell::get_or_init
  • once_cell::unsync::OnceCell
Ambiente
rust
Criado
2026-08-16T08:11:46Z

Contrato

  1. assert once_cell::sync::OnceCell::get_or_init blocks contending threads and executes its closure exactly once, leaving zero losing allocations to drop
  2. assert once_cell::race::OnceBox::get_or_init executes closures concurrently across all contending threads, discarding and dropping all losing Box allocations while returning the winner
  3. assert once_cell::race::OnceNonZeroUsize executes its closure redundantly under contention and rejects zero as an invalid sentinel value
  4. assert once_cell::race::OnceBool manages three distinct states (uninit, false, true) and forbids overwriting once set
  5. assert once_cell::race::OnceRef initializes static references without heap allocations or destructor overhead
  6. assert once_cell::unsync::OnceCell is available in core no_std without any cargo feature flags but panics on reentrant initialization

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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

[[package]]
name = "csx-sample-once-cell-race-vs-sync"
version = "1.0.0"
dependencies = [
 "once_cell",
]

[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
Cargo.toml
[package]
name = "csx-sample-once-cell-race-vs-sync"
version = "1.0.0"
edition = "2021"
license = "MIT-0"

[dependencies]
# Default features ("std") activates "alloc" and "race", making both sync and race available.
once_cell = "1.21.4"
NOTES.md
# Notes on once_cell Race vs Sync Semantics

### Prior Sample Found via `search_known_solution`
The query to `search_known_solution` returned published sample `sha256:36b55cf55782c3258dcb2509e721eb8edf4affdd15e52754fe01d12bb5fa27c9`, which compared `once_cell` against modern standard library types (`OnceLock`, `LazyLock`, `std::cell::OnceCell`, `LazyCell`) and evaluated the stability gate of `OnceLock::get_or_try_init`.

### What a Naive Model Would Write
When targeting `#![no_std]` or configuring `once_cell` with `default-features = false`, a naive model assumes `once_cell::race::OnceBox` (or `OnceNonZeroUsize`) acts as a drop-in replacement for `once_cell::sync::OnceCell` with identical blocking and exact-once closure execution guarantees.

### How the Wrong Version Fails
Silently with a green build: all contending threads observe the winning value, but every contending thread executes its initialization closure concurrently, causing side effects to trigger repeatedly and silently allocating and dropping $N - 1$ losing heap values upon atomic CAS rejection.
csx.json
{"case":{"caseId":"case:sha256:711a7a4b550ff304967aac2902855b9f703e536aa044cc74c928081699f50f33","contract":["assert once_cell::sync::OnceCell::get_or_init blocks contending threads and executes its closure exactly once, leaving zero losing allocations to drop","assert once_cell::race::OnceBox::get_or_init executes closures concurrently across all contending threads, discarding and dropping all losing Box allocations while returning the winner","assert once_cell::race::OnceNonZeroUsize executes its closure redundantly under contention and rejects zero as an invalid sentinel value","assert once_cell::race::OnceBool manages three distinct states (uninit, false, true) and forbids overwriting once set","assert once_cell::race::OnceRef initializes static references without heap allocations or destructor overhead","assert once_cell::unsync::OnceCell is available in core no_std without any cargo feature flags but panics on reentrant initialization"],"goal":"Differentiate lock-free once_cell::race from blocking once_cell::sync across default-features=false configurations, proving race initializers run redundantly under contention while sync initializers run exactly once","kind":"HOW","packages":["pkg:cargo/once_cell@1.21.4"],"schemaVersion":1,"symbols":["once_cell::race::OnceBox","once_cell::race::OnceBox::get_or_init","once_cell::race::OnceNonZeroUsize","once_cell::race::OnceNonZeroUsize::get_or_init","once_cell::race::OnceBool","once_cell::race::OnceBool::get_or_init","once_cell::race::OnceRef","once_cell::race::OnceRef::get_or_init","once_cell::sync::OnceCell","once_cell::sync::OnceCell::get_or_init","once_cell::unsync::OnceCell"]},"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/once_cell@1.21.4"],"schemaVersion":1,"symbols":["once_cell::race::OnceBox","once_cell::race::OnceBox::get_or_init","once_cell::race::OnceNonZeroUsize","once_cell::race::OnceNonZeroUsize::get_or_init","once_cell::race::OnceBool","once_cell::race::OnceBool::get_or_init","once_cell::race::OnceRef","once_cell::race::OnceRef::get_or_init","once_cell::sync::OnceCell","once_cell::sync::OnceCell::get_or_init","once_cell::unsync::OnceCell"],"verifierAdapter":"cargo@1"}
src/lib.rs
extern crate alloc;

use alloc::boxed::Box;
use core::num::NonZeroUsize;
use core::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Barrier;
use std::thread;
use std::time::Duration;

use once_cell::race::{OnceBool, OnceBox, OnceNonZeroUsize, OnceRef};
use once_cell::sync::OnceCell as SyncOnceCell;
use once_cell::unsync::OnceCell as UnsyncOnceCell;

const THREADS: usize = 16;

struct TrackDrop {
    id: usize,
    drop_counter: &'static AtomicUsize,
}

impl Drop for TrackDrop {
    fn drop(&mut self) {
        self.drop_counter.fetch_add(1, Ordering::SeqCst);
    }
}

/// Proves that `once_cell::sync::OnceCell` uses blocking synchronization:
/// contending threads block until the first thread's closure completes,
/// guaranteeing the closure runs exactly once and zero redundant allocations occur.
pub fn verify_sync_blocking_semantics() {
    static INIT_COUNT: AtomicUsize = AtomicUsize::new(0);
    static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);

    INIT_COUNT.store(0, Ordering::SeqCst);
    DROP_COUNT.store(0, Ordering::SeqCst);

    let cell: SyncOnceCell<TrackDrop> = SyncOnceCell::new();
    let barrier = Barrier::new(THREADS);

    let seen: Vec<usize> = thread::scope(|s| {
        let handles: Vec<_> = (0..THREADS)
            .map(|id| {
                let cell = &cell;
                let barrier = &barrier;
                s.spawn(move || {
                    barrier.wait();
                    cell.get_or_init(|| {
                        INIT_COUNT.fetch_add(1, Ordering::SeqCst);
                        thread::sleep(Duration::from_millis(15));
                        TrackDrop {
                            id,
                            drop_counter: &DROP_COUNT,
                        }
                    })
                    .id
                })
            })
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).collect()
    });

    let winner = seen[0];
    assert!(seen.iter().all(|&val| val == winner));
    assert_eq!(cell.get().unwrap().id, winner);

    // EXACTLY ONE thread executed the initialisation closure.
    assert_eq!(INIT_COUNT.load(Ordering::SeqCst), 1);
    // Zero losing allocations were constructed or dropped during initialisation.
    assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 0);
}

/// Proves that `once_cell::race::OnceBox` is lock-free / non-blocking:
/// all contending threads run their closures concurrently, and all losing
/// allocations are immediately dropped when atomic CAS fails.
pub fn verify_race_once_box_semantics() {
    static INIT_COUNT: AtomicUsize = AtomicUsize::new(0);
    static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);

    INIT_COUNT.store(0, Ordering::SeqCst);
    DROP_COUNT.store(0, Ordering::SeqCst);

    let cell: OnceBox<TrackDrop> = OnceBox::new();
    let barrier = Barrier::new(THREADS);

    let seen: Vec<usize> = thread::scope(|s| {
        let handles: Vec<_> = (0..THREADS)
            .map(|id| {
                let cell = &cell;
                let barrier = &barrier;
                s.spawn(move || {
                    barrier.wait();
                    cell.get_or_init(|| {
                        INIT_COUNT.fetch_add(1, Ordering::SeqCst);
                        thread::sleep(Duration::from_millis(15));
                        Box::new(TrackDrop {
                            id,
                            drop_counter: &DROP_COUNT,
                        })
                    })
                    .id
                })
            })
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).collect()
    });

    let winner = seen[0];
    assert!(seen.iter().all(|&val| val == winner));
    assert_eq!(cell.get().unwrap().id, winner);

    // ALL contending threads executed their closures concurrently.
    assert_eq!(INIT_COUNT.load(Ordering::SeqCst), THREADS);
    // Every losing allocation (THREADS - 1) was immediately dropped upon CAS rejection.
    assert_eq!(DROP_COUNT.load(Ordering::SeqCst), THREADS - 1);
}

/// Proves that `once_cell::race::OnceNonZeroUsize` runs initializers concurrently under contention
/// and treats 0 as the internal uninitialised sentinel.
pub fn verify_race_once_non_zero_usize() {
    static INIT_COUNT: AtomicUsize = AtomicUsize::new(0);
    INIT_COUNT.store(0, Ordering::SeqCst);

    let cell: OnceNonZeroUsize = OnceNonZeroUsize::new();
    assert_eq!(cell.get(), None);

    let barrier = Barrier::new(THREADS);

    let seen: Vec<usize> = thread::scope(|s| {
        let handles: Vec<_> = (0..THREADS)
            .map(|id| {
                let cell = &cell;
                let barrier = &barrier;
                s.spawn(move || {
                    barrier.wait();
                    cell.get_or_init(|| {
                        INIT_COUNT.fetch_add(1, Ordering::SeqCst);
                        thread::sleep(Duration::from_millis(15));
                        NonZeroUsize::new(id + 1).unwrap()
                    })
                    .get()
                })
            })
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).collect()
    });

    let winner = seen[0];
    assert!(winner >= 1 && winner <= THREADS);
    assert!(seen.iter().all(|&val| val == winner));
    assert_eq!(cell.get().unwrap().get(), winner);

    // Redundant execution occurred across contending threads.
    assert_eq!(INIT_COUNT.load(Ordering::SeqCst), THREADS);

    // Subsequent writes are rejected.
    let new_val = NonZeroUsize::new(999).unwrap();
    assert_eq!(cell.set(new_val), Err(()));
    assert_eq!(cell.get().unwrap().get(), winner);
}

/// Proves that `once_cell::race::OnceBool` supports three atomic states (uninit, false, true).
pub fn verify_race_once_bool() {
    let cell: OnceBool = OnceBool::new();
    assert_eq!(cell.get(), None);

    // Set to false
    assert_eq!(cell.set(false), Ok(()));
    assert_eq!(cell.get(), Some(false));

    // Attempting to set to true fails without overwriting
    assert_eq!(cell.set(true), Err(()));
    assert_eq!(cell.get(), Some(false));

    // get_or_init on initialized cell does not invoke the closure
    assert_eq!(cell.get_or_init(|| unreachable!("already initialized")), false);
}

/// Proves that `once_cell::race::OnceRef` holds static references without heap allocations.
pub fn verify_race_once_ref() {
    static DATA_A: &str = "alpha";
    static DATA_B: &str = "beta";

    let cell: OnceRef<&str> = OnceRef::new();
    assert_eq!(cell.get(), None);

    assert_eq!(cell.set(&DATA_A), Ok(()));
    assert_eq!(cell.get(), Some(&"alpha"));

    // Second write fails
    assert_eq!(cell.set(&DATA_B), Err(()));
    assert_eq!(cell.get(), Some(&"alpha"));
}

/// Proves that `once_cell::unsync::OnceCell` is available in core `#![no_std]` without atomics
/// and catches reentrant initialization at runtime by panicking.
pub fn verify_unsync_reentrancy_panic() {
    let cell: UnsyncOnceCell<u32> = UnsyncOnceCell::new();
    assert_eq!(cell.get(), None);

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        cell.get_or_init(|| {
            // Reentrant initialization attempt on the same single-threaded cell panics.
            *cell.get_or_init(|| 42)
        });
    }));

    assert!(result.is_err(), "unsync::OnceCell must panic on reentrant initialization");
}

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

    #[test]
    fn test_sync_blocking_semantics() {
        verify_sync_blocking_semantics();
    }

    #[test]
    fn test_race_once_box_semantics() {
        verify_race_once_box_semantics();
    }

    #[test]
    fn test_race_once_non_zero_usize() {
        verify_race_once_non_zero_usize();
    }

    #[test]
    fn test_race_once_bool() {
        verify_race_once_bool();
    }

    #[test]
    fn test_race_once_ref() {
        verify_race_once_ref();
    }

    #[test]
    fn test_unsync_reentrancy_panic() {
        verify_unsync_reentrancy_panic();
    }
}

Seeder de origem

csx-seed