Skip to main content
net10.0

A high-performance model checker embedded in F#. Write specifications as regular F# code with full IDE support, type safety, and autocomplete β€” then verify them at speeds matching or exceeding TLC.

Published
Mar 19, 2026
8mo ago
Total Downloads
196
196

Install

dotnet add package Spekter --version 0.0.1-alpha
ProductVersions
.NET
net10.0

README

Spekter β€” Model Checking in F#

NuGet

A high-performance model checker embedded in F#. Write specifications as regular F# code with full IDE support, type safety, and autocomplete β€” then verify them at speeds matching or exceeding TLC (the standard TLA+ model checker).

Why Spekter?

TLA+ is the gold standard for specifying and verifying concurrent and distributed systems. But its tooling has friction: separate language, no IDE integration, no type checking, ASCII math syntax.

Spekter gives you the same verification power β€” invariants, deadlock detection, temporal properties, weak and strong fairness, simulation mode, state constraints, parallel checking β€” with the ergonomics of F#:

open Spekter

let t = Spekter()
let accounts = [| t.str "alice"; t.str "bob"; t.str "carol" |]
let bal = t.defvar "balances" (t.mapFrom accounts (fun _ -> t.num 100))

let pairs = [| for s in accounts do for r in accounts do if s <> r then yield (s, r) |]

let s = t.spec [bal]
            [ action "transfer" (fun ctx ->
                [ for (sender, receiver) in pairs do
                    let sBal = get ctx bal sender
                    let rBal = get ctx bal receiver
                    let result = guard (value sBal >= t.num 25) [
                        set sBal (value sBal - t.num 25)
                        set rBal (value rBal + t.num 25)
                    ]
                    if result.Enabled then yield result ])
            ]
            [ invariant' "noOverdraft" (fun ctx ->
                accounts |> Array.forall (fun a -> geti ctx bal a >= 0))
              invariant' "conserved" (fun ctx ->
                accounts |> Array.sumBy (geti ctx bal) = 300)
            ]

match check s with
| RichChecker.RPass n -> printfn "OK (%d states)" n
| RichChecker.RFail(name, trace) -> printfn "FAIL: %s" name

Performance

Spekter has three checker tiers. All produce identical results β€” choose based on your model's complexity and size.

Checker Use Case Speed State Representation
Checker.run Small models, prototyping 315K states/sec F# records
FlatChecker.run Large models, int-only state 4.0M states/sec (parallel) int[] arrays
RichChecker.run / check (DSL) Complex models with sets/maps/records 140K states/sec Hash-consed values

Benchmarks vs TLC

Head-to-head on the same machine (Apple Silicon M3 Pro, 14 cores), same models:

N-Counter (integer arithmetic):

Model Spekter (parallel) TLC (parallel) Speedup
1M states 0.24s 6.2s 26x faster
4M states 0.95s 13.5s 14x faster
16M states 4.0s 41.0s 10x faster

DistributedLock (sets, maps, records β€” real production spec):

Spekter TLC
States 2,949,651 2,949,651 Same
Time 20s 33s Spekter 1.6x faster

Features

  • Invariant checking β€” verify safety properties hold in every reachable state
  • Deadlock detection β€” find states with no enabled actions
  • Temporal properties β€” eventually, leadsTo across all checker tiers
  • Weak and strong fairness β€” fairAction, strongFairAction in DSL, richModel, and model CEs
  • State constraints β€” bound exploration to keep large models tractable
  • DFS mode β€” depth-first search finds bugs faster in deep models, uses less memory
  • Coverage statistics β€” per-action fire counts, states explored, max depth; detects dead actions
  • Symmetry reduction β€” normalize symmetric value permutations before hashing; N values = up to N! state reduction
  • Safety refinement β€” verify a concrete spec implements an abstract spec through a mapping function
  • Simulation mode β€” random trace sampling for quick smoke tests on huge models
  • Process abstraction β€” processes for parameterized concurrent agents
  • Nondeterministic choice β€” pick, pick2, choose computation expression
  • Rich values β€” sets, maps, records, tuples with hash-consed interning
  • Ergonomic DSL β€” SpekterBuilder, get/geti/set/value free functions, action/invariant' helpers
  • Parallel BFS β€” lock-free fingerprint set, per-thread state stores (all checker tiers)
  • Trace reconstruction β€” counterexample traces on invariant violations

Installation

dotnet add package Spekter --prerelease

Note: Spekter is currently in alpha. The API may change between releases.

Requires .NET 10+.

Quick Start

Ergonomic DSL (Recommended)

The DSL uses SpekterBuilder for scoped state management and curried free functions for idiomatic F#:

open Spekter

let t = Spekter()
let count = t.defvar "count" (t.num 0)

let s = t.spec [count]
            [ action "inc" (fun ctx ->
                let c = v ctx count
                only (guard (value c < t.num 3) [ set c (value c + t.num 1) ]))
            ]
            [ invariant' "bounded" (fun ctx -> geti ctx count <= 3) ]

match check s with
| RichChecker.RPass n -> printfn "OK (%d states)" n
| RichChecker.RFail(name, _) -> printfn "FAIL: %s" name

Maps, Records, and Nondeterminism

let t = Spekter()
let accounts = [| t.str "alice"; t.str "bob" |]
let bal = t.defvar "balances" (t.mapFrom accounts (fun _ -> t.num 100))

let s = t.spec [bal]
            [ action "transfer" (fun ctx ->
                let alice = get ctx bal (t.str "alice")
                let bob = get ctx bal (t.str "bob")
                only (guard (value alice >= t.num 50) [
                    set alice (value alice - t.num 50)
                    set bob (value bob + t.num 50)
                ]))
            ]
            [ invariant' "conserved" (fun ctx ->
                accounts |> Array.sumBy (geti ctx bal) = 200)
            ]

Records with field access:

let t = Spekter()
let lk = t.defvar "lock" (t.fields ["owner", t.nil; "expiry", t.num 0])
let time = t.defvar "time" (t.num 0)

// In an action:
fun ctx ->
    let owner = getf ctx lk "owner"
    let expiry = getf ctx lk "expiry"
    let tm = v ctx time
    only (guard owner.IsNull [
        set owner (t.str "proc1")
        set expiry (value tm + t.num 2)
    ])

Temporal Properties and Fairness

let t = Spekter()
let on = t.defvar "on" t.f  // FALSE

let s = t.specWith [on]
            [ fairAction' "turnOn" (fun ctx ->
                let onRef = v ctx on
                only (guard (value onRef = t.f) [ set onRef t.t ]))
              stutter
            ]
            []
            [ SpekterEventually("lightsOn", fun ctx -> v ctx on |> value = t.t) ]
            None true

match check s with
| RichChecker.RPass _ -> printfn "Fair: light always turns on"

Simulation Mode

For huge models, random sampling finds bugs fast without exhaustive exploration:

// richModel CE for simulation
let spec = richModel 1 {
    varNames ["count"]
    init (fun s -> [| s.Int 0 |])
    action "inc" (fun s state ->
        if s.AsInt state.[0] < 10 then [ [| s.Int (s.AsInt state.[0] + 1) |] ] else [])
    invariant "max5" (fun s state -> s.AsInt state.[0] <= 5)
    allowDeadlock
}

match RichChecker.simulate spec 200 20 with
| RichChecker.RFail(name, _) -> printfn "Bug found: %s" name
| RichChecker.RPass n -> printfn "OK (%d states sampled)" n

Simple State Machine (Computation Expression)

For small models with F# record state:

type Light = { On: bool }

let spec = model<Light> {
    init { On = false }
    fairAction "turnOn" (fun s -> if not s.On then Some { On = true } else None)
    action "stay" (fun s -> Some s)
    eventually "lightsOn" (fun s -> s.On)
}

match Checker.run spec with
| Pass n -> printfn "OK (%d states)" n
| Fail (name, _) -> printfn "FAIL: %s" name

High-Performance Flat Model

For maximum speed with integer state:

let spec = flatModel 3 {
    init [| 0; 0; 0 |]
    varNames ["x"; "y"; "z"]
    transition "incX"
        (FlatChecker.FlatGuard(fun (s: ReadOnlySpan<int>) -> s.[0] < 10))
        (FlatChecker.FlatTransition(fun (src: ReadOnlySpan<int>) (dst: Span<int>) -> dst.[0] <- src.[0] + 1))
    invariant "bounded"
        (FlatChecker.FlatInvariant(fun (s: ReadOnlySpan<int>) -> s.[0] + s.[1] + s.[2] <= 30))
    allowDeadlock
}

FlatChecker.runParallelAuto spec |> FlatChecker.FlatCheckResult.format spec.VarNames |> printfn "%s"

Real-World Examples

Financial Systems

Spekter has been used to find real concurrency bugs in financial system designs:

Spec Domain States Bug Found Time
BankTransferReal Concurrent bank transfers ~8K TOCTOU race β†’ overdraft (check-then-debit) 10ms
PaymentAcquirerReal Stone-like payment acquirer ~5K Settle + anticipate β†’ double credit 2ms
LedgerReal Double-entry bookkeeping ~5K Double-realize accrual, post-close corruption 4-14ms

Each spec models a real system, finds the concurrency bug, verifies the fix, and demonstrates safety invariants, temporal liveness properties, fairness, state constraints, and simulation mode.

Distributed Consensus

Spec Domain Bug Found Features Showcased
RaftElectionReal Simplified Raft leader election (3 nodes) Buggy "no already-voted check" allows two leaders in same term DFS, coverage, symmetry, refinement, simulation, temporal, parallel, state constraints

The Raft election spec is the showcase example for all Spekter features. It demonstrates every checker mode in a single model.

Event-Sourced Ledger (Model β†’ Production Code)

The Spekter.Examples.Ledger project demonstrates the full pipeline from verified design to production code:

  1. Spekter model finds 2 concurrency bugs (double-realize, post-close corruption)
  2. Pure F# domain encodes the verified guards as Result.Error returns
  3. Event sourcing wraps the domain with append-only events and state replay
  4. Command handler with conflict-aware retry (re-reads state, checks if command is still valid)
  5. Property tests verify the same invariants the model proved, through the real infrastructure

See src/Spekter.Examples.Ledger/README.md for the full story.

Authorization System Specs

Validated against 6 production TLA+ specifications:

Spec Description States Violations Found
DistributedLock Redis lock with TTL, CAS release, fencing tokens 2.95M Lock expiry during CS, silent skip on timeout
MfaChallenge MFA token + emergency code with TOCTOU race 46K Emergency code double-use via TOCTOU
OAuthPkce OAuth2 + PKCE with session, code, PAR semantics 15K β€” (all safety properties hold)
ZeratulCore Tuple engine with batched writes and crash recovery 16+ Partial write on crash
RoleCore RBAC with recursive role hierarchy and materialization 307K β€” (mutual exclusion, tenant isolation hold)
TenantIsolation Cross-tenant isolation under crash and schema staleness 687K β€” (isolation invariant holds)

All specs produce identical state counts and find the same violations as TLC.

API Reference

DSL (Recommended)

Category Functions Description
Builder SpekterBuilder() Scoped store + variable management, no global mutation
Variables t.defvar, t.num, t.str, t.nil, t.fields, t.mapFrom Value constructors
Spec t.spec, t.specWith Build specs with sensible defaults
Access (free functions) get, getf, geti, getfi, v, vi Curried, composable with Array.sumBy etc.
Mutation (free functions) set, value, guard, pick, pick2, only State transitions
Shorthands action, fairAction', strongFairAction', invariant', stutter Tuple builders
Run check, formatResult Execute model checker and format output

Ergonomic Checker (model<'s>)

Operation Description
init state Add initial state
action "name" fn Add action (fn: 's -> 's option)
fairAction "name" fn Weak fair action
strongFairAction "name" fn Strong fair action
processes "group" ids fn Parameterized concurrent processes
invariant "name" pred Safety property
eventually "name" pred Liveness: pred holds eventually
leadsTo "name" p q p always leads to q
allowDeadlock Don't report terminal states as errors

Rich Checker (richModel)

Operation Description
init fn fn: ValueStore -> int32[]
action "name" fn fn: ValueStore -> int32[] -> int32[] list
fairAction "name" fn Weak fair action
strongFairAction "name" fn Strong fair action
invariant "name" fn fn: ValueStore -> int32[] -> bool
eventually "name" fn Liveness property
leadsTo "name" p q Leads-to property
stateConstraint fn Bound state exploration
`symmetrySet [ ...
varNames [...] Variable names for traces

Flat Checker (flatModel)

Operation Description
`init [ ...
transition "name" guard trans Delegate-based action
fairTransition "name" guard trans Weak fair delegate action
invariant "name" pred Safety property
eventually "name" pred Liveness property
leadsTo "name" p q Leads-to property
varNames ["x";"y"] Named variables for traces

Additional Operations

Operation Available On Description
RichChecker.run spec RichModel Single-threaded BFS
RichChecker.runDfs spec RichModel Depth-first search (finds deep bugs faster, less memory)
RichChecker.runWithCoverage spec RichModel BFS + per-action fire counts, max depth, states explored
RichChecker.simulate spec traces depth RichModel Random trace sampling
RichChecker.runParallelAuto spec RichModel Parallel BFS (auto-scales to available cores)
RichChecker.checkRefinement concrete map abstractInvs RichModel Verify concrete spec refines abstract spec
RichTemporal.run spec RichModel BFS + temporal checking (fairness, eventually, leadsTo)
FlatChecker.runParallelAuto spec FlatModel Parallel BFS

Architecture

                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚       User Spec (F#)         β”‚
                    └──────────┬──────────────────-β”˜
                               β”‚
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚                β”‚                β”‚
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”
     β”‚  model<'s> {} β”‚ β”‚ flatModel{} β”‚ β”‚  DSL / rich  β”‚
     β”‚  F# records   β”‚ β”‚  int[]      β”‚ β”‚  ValueStore  β”‚
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
              β”‚                β”‚                β”‚
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”
     β”‚  Checker.run  β”‚ β”‚FlatChecker  β”‚ β”‚ RichChecker  β”‚
     β”‚  + Temporal   β”‚ β”‚.run/.runP   β”‚ β”‚ .run/.runP   β”‚
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜ β”‚+FlatTemporalβ”‚ β”‚+RichTemporal β”‚
              β”‚        β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
              β”‚               β”‚                β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚     Shared Infrastructure      β”‚
              β”‚  FingerprintSet (lock-free CAS) β”‚
              β”‚  RingQueue (zero-alloc)         β”‚
              β”‚  wyhash (SIMD-friendly)         β”‚
              β”‚  Tarjan SCC (temporal)          β”‚
              β”‚  Per-thread state stores        β”‚
              β”‚  Bloom filter pre-filter        β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Project Structure

src/
  Spekter/                          Core library
    Types.fs                         Core types (Action, Property, Model)
    Dsl.fs                        Ergonomic DSL (SpekterBuilder, free functions)
    ValueStore.fs                    Hash-consed value intern table
    FingerprintSet.fs                Lock-free CAS fingerprint set
    Checker.fs                       Ergonomic BFS checker
    FlatChecker.fs                   High-performance flat checker (parallel)
    RichChecker.fs                   Rich value checker (BFS, DFS, parallel, simulation, coverage, symmetry, refinement)
    Temporal.fs                      Tarjan SCC temporal checking
    FlatTemporal.fs                  Temporal checking for flat states
    RichTemporal.fs                  Temporal checking for rich states
    ...

  Spekter.Examples.Ledger/          Event-sourced ledger (model β†’ production)
    Ledger.fs                        Pure domain (verified guards)
    Events.fs                        Event types + state reconstruction
    EventStore.fs                    IEventStore + InMemory + PostgreSQL skeleton
    CommandHandler.fs                Conflict-aware retry handler
    README.md                        Full documentation

  Spekter.Tests/
    DslErgonomicsTests.fs            DSL API tests
    DfsTests.fs                      DFS mode tests
    CoverageTests.fs                 Coverage statistics tests
    SymmetryTests.fs                 Symmetry reduction tests
    RefinementTests.fs               Refinement checking tests
    RichTemporalTests.fs             Temporal property tests
    SimulationTests.fs               Simulation mode tests
    Examples/
      RaftElectionReal.fs            Raft leader election (ALL features showcase)
      BankTransferReal.fs            Concurrent bank transfers (TOCTOU race)
      PaymentAcquirerReal.fs         Stone-like payment acquirer (double credit)
      LedgerReal.fs                  Double-entry bookkeeping (double-realize)
      BankTransferExample.fs         Educational example (all features)
      DistributedLockRich.fs         Redis distributed lock (2.95M states)
      ...

  Spekter.Benchmarks/              BenchmarkDotNet performance suite

License

MIT

Adoption Assessment

Assess this package against its supported frameworks, license, maintenance signals and dependency graph before making it a project standard.

This version is marked prerelease. Validate its API and upgrade path before production use.Compatibility metadata lists 1 target framework; confirm the exact target used by your application.

Related Guides & Workflows

Learn how to evaluate, integrate, or audit this package in your .NET project.