Repository F# setup
open System
open System.IO
open System.Threading
open System.Threading.Tasks
open Axial
open Axial.Console
open Axial.FileSystem
open Axial.Hosting
open Axial.Hosting.Browser
open Axial.Hosting.Node
open Axial.State
open Axial.Telemetry
open Axial.Telemetry.JavaScript

Torture Tests

An interrupted take must not lose a value. A lossless subscriber must see every value in order. A scope must release what it acquired, however its fibers end. Small examples may miss these races.

Each scenario runs many fibers with random interruptions, failures, and shutdowns, then checks invariants regardless of interleaving. Checks avoid timing assertions such as "this finished within 10 ms", so machine speed does not determine whether a check fails.

A representative invariant, checked here: a queue delivers offered values in order, even after shutdown.

Show page setup
open Axial
let shouldEqual expected actual =
    if actual <> expected then failwithf "Expected %A but got %A" expected actual
Verified
let orderedDrain : Flow<unit, Never, int list> =
    flow {
        let! queue = Queue.unbounded ()
        let! _ = Queue.offerAll [ 3; 1; 2 ] queue
        do! Dequeue.shutdown queue
        return! Dequeue.takeAll queue
    }
Requires & types
Requires: open Axial (packages: Axial)
val orderedDrain: Flow<unit,Never,int list>
Verified
orderedDrain |> Flow.run () |> shouldEqual (Exit.Success [ 3; 1; 2 ])
Requires & types
Requires: open Axial (packages: Axial)

The full runner below drives the same guarantees under randomized interruption, failure, and shutdown, across many rounds.

Run them yourself

The scenarios are a runnable example in examples/Axial.TortureTest. From a clone of the repository, run every scenario for 10 rounds:

dotnet run --project examples/Axial.TortureTest

Name a scenario, a round count, or both:

dotnet run --project examples/Axial.TortureTest -- queues 200
dotnet run --project examples/Axial.TortureTest -- all 100

The program prints each invariant with a check mark and the number of rounds it held on. It exits with a non-zero code if any invariant was ever violated, so it can gate a CI job or run as a soak test on your own hardware.

Each round runs under a FiberRegistry. A round still running after 10 seconds prints how many fibers are live, and a round still running after 60 seconds prints the live fiber tree, interrupts those fibers and fails. A hang therefore names the fibers that are still waiting instead of blocking the run.

Rounds and seeds

A scenario runs once per round, and each round has a seed. The seed fixes every random choice the scenario makes: which fiber to interrupt, which strategy a subscriber uses, how long an operation waits. A violated invariant is reported with the seeds it failed on, so the same choices can be run again. The interleaving of fibers still differs from run to run, which is what the rounds are for.

The scenario runner:

Fragment
/// How often a slow round reports progress, and how long a round may run before it counts as stalled.
let progressEvery = System.TimeSpan.FromSeconds 10.0
let stallAfter = System.TimeSpan.FromSeconds 60.0

/// Runs one round in a fiber tracked by a fiber registry, turning a round that fails outright into a violated check.
/// A round slower than <c>progressEvery</c> reports its live fiber count. A round past <c>stallAfter</c> reports the
/// live fiber tree, interrupts every live fiber, and fails with a stall check, so a hang names the fibers still waiting
/// instead of blocking the run. Returns <c>None</c> if the round's fibers still do not settle after the interrupt.
let watchRound (say: string -> unit) (scenario: Scenario) (seed: int) : Flow<unit, Never, Check list option> =
    let registry = FiberRegistry()
    let clock = Axial.Clock.live
    let failed (cause: Cause<Never>) =
        let reason = Cause.prettyPrint (fun (_: Never) -> "") cause
        [ check $"the round completed (it ended with {reason})" false ]
    let rec settle round (deadline: System.TimeSpan) =
        flow {
            match! Fiber.poll round with
            | Some _ ->
                let! exit = Fiber.awaitExit round
                return Some exit
            | None when clock.Elapsed() >= deadline -> return None
            | None ->
                do! Flow.sleep (System.TimeSpan.FromMilliseconds 50.0)
                return! settle round deadline
        }
    flow {
        // The round's own fiber is forked under the registry, so the dump shows it as the root of the tree.
        let! round =
            Flow.forkNamed $"{scenario.Name} seed {seed}" (scenario.Run(Round(seed, 100)))
            |> Flow.withFiberRegistry registry
        let started = clock.Elapsed()
        let rec watch () =
            flow {
                match! settle round (clock.Elapsed() + progressEvery) with
                | Some(Exit.Success checks) -> return Some checks
                | Some(Exit.Failure cause) -> return Some(failed cause)
                | None when clock.Elapsed() - started < stallAfter ->
                    say $"{scenario.Name} seed {seed}: running {(clock.Elapsed() - started).TotalSeconds:F0}s, {registry.LiveFiberCount} live fiber(s), {registry.StartedCount} started"
                    return! watch ()
                | None ->
                    let dump = registry.DumpAt clock
                    say $"{scenario.Name} seed {seed}: STALLED after {stallAfter.TotalSeconds:F0}s"
                    say dump
                    for fiber in registry.Snapshot() do
                        registry.Interrupt fiber.Id |> ignore
                    match! settle round (clock.Elapsed() + progressEvery) with
                    | Some _ -> return Some [ check $"the round finished within {stallAfter.TotalSeconds:F0}s (see the fiber dump)" false ]
                    | None -> return None
            }
        return! watch ()
    }

/// Runs one round and exits with code 3 when a stalled round cannot be interrupted, because its fibers would block
/// the run from finishing.
let runRound (scenario: Scenario) (seed: int) : Check list =
    match (watchRound (printfn "%s") scenario seed).RunSynchronously(clockEnvironment) with
    | Exit.Success(Some checks) -> checks
    | Exit.Success None ->
        printfn "%s seed %d: the stalled round ignored interruption; exiting" scenario.Name seed
        exit 3
    | Exit.Failure _ -> [ check "the round's watchdog completed" false ]

/// Runs every round of a scenario, prints each invariant with the rounds it held on and the seeds it failed with,
/// and returns whether every invariant held on every round.
let report (scenario: Scenario) (rounds: int) : bool =
    let results = [ for seed in 1..rounds -> seed, runRound scenario seed ]
    let invariants = results |> List.collect (snd >> List.map _.Invariant) |> List.distinct
    printfn "%s: %s" scenario.Name scenario.Title

    for invariant in invariants do
        let failedSeeds =
            [ for seed, checks in results do
                  if checks |> List.exists (fun check -> check.Invariant = invariant && not check.Held) then seed ]

        match failedSeeds with
        | [] -> printfn "  ✔ %s (%d/%d)" invariant rounds rounds
        | seeds ->
            let listed = seeds |> List.map string |> String.concat ", "
            printfn "  ✗ %s (%d/%d; failed with seeds %s)" invariant (rounds - seeds.Length) rounds listed

    results |> List.forall (snd >> List.forall _.Held)

/// Usage: <c>dotnet run -- [scenario | all] [rounds]</c>. Runs every scenario for 10 rounds by default, and exits
/// with a non-zero code if any invariant was violated.
[<EntryPoint>]
let main arguments =
    let selected, rounds =
        match arguments with
        | [||] -> Some Scenarios.all, 10
        | [| name |] when name = "all" -> Some Scenarios.all, 10
        | [| name |] when Seq.forall System.Char.IsDigit name -> Some Scenarios.all, int name
        | [| name |] -> Scenarios.tryFind name |> Option.map List.singleton, 10
        | [| name; count |] when name = "all" -> Some Scenarios.all, int count
        | [| name; count |] -> Scenarios.tryFind name |> Option.map List.singleton, int count
        | _ -> None, 0

    match selected with
    | None ->
        let names = Scenarios.all |> List.map _.Name |> String.concat ", "
        printfn "Usage: dotnet run -- [scenario | all] [rounds]. Scenarios: %s" names
        2
    | Some scenarios ->
        let results = [ for scenario in scenarios -> report scenario rounds ]
        if List.forall id results then 0 else 1

How Axial runs them

  • On every build, the .NET test suite runs every scenario for 10 seeds and fails if any invariant is violated.
  • The same scenario files are compiled to JavaScript with Fable and run on Node at a fifth of their size, so the JavaScript runtime keeps the same guarantees.
  • A coverage test fails when a public member of the runtime and concurrency modules is not used by any scenario. A new API in those modules ships with a scenario that exercises it.

The scenarios have found real defects: a sleep that could end early, failures that recovery combinators did not see once they had been traced, a value lost when a stream's timer fired at the moment it arrived, and, on JavaScript, fibers that lost their scope after a long synchronous stretch.

Scenarios

Scenario What it stresses
Pipeline Queues, a hub, a SubscriptionRef, and graceful fibers together, stopped by closing a scope.
Queues Producers and consumers on one queue, with takes and offers interrupted, and every strategy.
Hubs Subscribers joining and leaving throughout, and every publish style.
Semaphores Permits under contention, with waiters and holders interrupted.
Deferreds Completions racing each other, and awaiters interrupted or arriving late.
Refs Ref and SubscriptionRef updated concurrently.
STM Transfers, blocking withdrawals, and atomic audits.
Fibers Latest-wins slots, inherited context, the fiber registry, and observers.
Caches Single-flight lookups with interrupted callers, failures, and invalidation.
Schedules Retry, repeat, supervise, and timeouts.
Parallel Bounded traversals, pooled resources, fail-fast zips, and races.
Errors Every outcome from concurrent branches, recovered, combined, and converted.
Scopes Nested scopes and forked children with every kind of resource.
Layers Resources provisioned in sequence and in parallel, with failures and interruption.
Streams Every stream operator, against the List model or the property it promises.
Interop Task, ValueTask, Async, and blocking calls, interrupted at random.