Skip to main content

Crate alloc_chaos

Crate alloc_chaos 

Source
Expand description

Deterministic allocation-failure testing for Rust.

alloc-chaos wraps the process global allocator and can run a test closure repeatedly while failing allocation attempt 0, then 1, then 2, and so on. This is useful for libraries that intentionally use fallible allocation APIs and want tests for their OOM paths.

§Example

#[global_allocator]
static GLOBAL: alloc_chaos::ChaosAllocator = alloc_chaos::ChaosAllocator::system();

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct OutOfMemory;

fn build_buffer(size: usize) -> Result<Vec<u8>, OutOfMemory> {
    let mut bytes = Vec::new();
    bytes.try_reserve_exact(size).map_err(|_| OutOfMemory)?;
    bytes.resize(size, 0);
    Ok(bytes)
}

#[test]
fn buffer_builder_handles_oom() {
    alloc_chaos::check(|| {
        match build_buffer(1024) {
            Ok(bytes) => assert_eq!(bytes.len(), 1024),
            Err(OutOfMemory) => {}
        }
    })
    .assert_success();
}

§Limits

This crate verifies a concrete execution path. It does not prove that all possible inputs or all possible control-flow branches are OOM-safe.

Only one check can be active in a process, but allocation counting and failure injection are limited to the thread executing the checked closure. Allocations performed by other threads are ignored.

The closure is executed many times. Keep all state needed by the code under test inside the closure, or otherwise make the closure deterministic across repeated runs.

The in-process checker cannot contain process aborts. Code that uses infallible allocation APIs may abort when an allocation fails instead of returning a recoverable error.

Structs§

Allocation
Metadata for the allocation attempt that was selected for injected failure.
AlreadyRunning
Error returned when a check is requested while another check is already active in this process.
Attempt
One run with one selected allocation attempt failed.
Baseline
Baseline run used to count allocation attempts before injecting failures.
ChaosAllocator
A global allocator wrapper that can deterministically fail selected allocation attempts during an alloc_chaos check.
Check
Configuration for an allocation-failure check.
Panic
Captured panic payload summary.
Report
Result of a full allocation-failure check.

Enums§

AllocOp
Allocator operation that was selected for injected failure.
Outcome
Outcome of one checked run.

Functions§

check
Runs f once to count allocations and then once per observed allocation, failing one allocation attempt per run.
try_check
Fallible variant of check.