Overview

View Source

Pitia Logo

Pitia

Pitia takes its name from the oracle of Delphi. Your specification is the oracle; Pitia checks whether your implementation follows it.

Pitia compiles a supported subset of TLA+ into an immutable executable model and derives PropEr state-machine tests for Erlang and Elixir. Call it directly inside an EUnit, Common Test, or ExUnit test. No code generation step, Java installation, external TLA+ tool, or runtime Hex dependency is required.

The native lexer, parser, compiler, and evaluator are written in Erlang. Both language APIs use the same model and execution engine. PropEr is supplied by the calling project; Pitia itself uses it only in its test profile.

Status: initial 0.1.0 implementation. This is a bounded model-based testing tool with sequential and parallel execution, not a complete TLA+ implementation or model checker. The API and supported language subset may change before 1.0.


How it looks

test "the queue follows its specification" do
  model =
    Pitia.compile!("spec/Queue.tla",
      constants: %{"Capacity" => 3},
      invariants: ["Bounded"]
    )

  assert :proper.quickcheck(Pitia.property(model, MyApp.QueueAdapter), numtests: 200)
end

The transformation happens when the test runs. A model is plain immutable BEAM data: reuse it across properties or compile it in each test. Pitia does not create atoms from specification names, load generated modules, keep a global compilation cache, or write generated files. Each property execution, including every shrink attempt, starts a fresh adapter instance and stops it in an after block.

Requirements

  • Erlang/OTP 28+; tested on OTP 29.
  • rebar3 for Erlang projects.
  • Elixir 1.17+ and Mix for the Elixir API; tested on Elixir 1.20.
  • PropEr 1.5 in the consumer's test dependencies to execute properties.

Compilation and model inspection work without PropEr. There is no Java, SANY, TLC, Apalache, NIF, or shell-process requirement.

Build & Test

rebar3 compile
rebar3 eunit
rebar3 ct

mix deps.get
mix test

The quality tooling follows PinchPi: erlfmt, Elvis (rebar3_lint), xref, Prisma, coverage, rebar3_ex_doc, and rebar3_hex.

rebar3 check
mix format --check-formatted

rebar3 check also checks for outdated Hex packages, which requires network access. Mix uses _build/mix so its artifacts do not interfere with rebar3 or Erlang coverage. Development tools are project plugins, not runtime dependencies.

Using a local checkout

Until a release is published, an Elixir consumer can use:

defp deps do
  [
    {:pitia, path: "../pitia", only: :test},
    {:proper, "~> 1.5", only: :test}
  ]
end

For rebar3, place or link the Pitia checkout at _checkouts/pitia, and declare pitia and PropEr in the test profile:

{profiles, [{test, [{deps, [pitia, {proper, "~> 1.5"}]}]}]}.

The specification

The runnable fixture at test/fixtures/Queue.tla defines:

---- MODULE Queue ----
EXTENDS Naturals, Sequences
CONSTANT Capacity
VARIABLE queue

Init == queue = <<>>

Enqueue(x) == /\ Len(queue) < Capacity
              /\ queue' = Append(queue, x)

Dequeue == /\ Len(queue) > 0
           /\ queue' = Tail(queue)

Next == (\E x \in 0..3 : Enqueue(x)) \/ Dequeue
Bounded == Len(queue) <= Capacity
====

Pitia derives enabled commands from Next, evaluates guards against the model, and applies updates simultaneously to predict the next state. Every state variable must be assigned exactly once by an action or explicitly UNCHANGED. An omitted assignment is an error, never an implicit frame condition.

The adapter

Implement the pitia_adapter behaviour to connect actions to a real system:

CallbackContract
start(Context)Return {ok, Handle} for a fresh system. Context contains constants and initial.
call(Handle, Action, Args)Execute one named action and return its result.
observe(Handle)Return a map with binary/string keys for all model state variables. Extra keys are ignored.
stop(Handle)Clean up the system. Called after successful startup, including failures and shrinking.
postcondition(Before, Action, Args, Result, After)Required in parallel mode, optional in sequential mode: check API return values in addition to automatic state comparison.

Action names are binaries in Erlang and strings in Elixir, preserving TLA+ case. State maps also use binary/string keys. Use lists for TLA+ sequences, integers for integer values, booleans for TRUE/FALSE, and {set, SortedUniqueValues} (or {:set, sorted_unique_values}) for finite sets. Strings are UTF-8 binaries.

Here is a complete Elixir adapter using an Agent as the example implementation:

defmodule MyApp.QueueAdapter do
  @behaviour :pitia_adapter

  @impl true
  def start(_context), do: Agent.start_link(fn -> [] end)

  @impl true
  def call(pid, "Enqueue", [value]), do: Agent.update(pid, &(&1 ++ [value]))
  def call(pid, "Dequeue", []), do: Agent.get_and_update(pid, fn [head | tail] -> {head, tail} end)

  @impl true
  def observe(pid), do: %{"queue" => Agent.get(pid, & &1)}

  @impl true
  def stop(pid), do: Agent.stop(pid)
end

Use your application's actual API instead of the Agent in a real project. If return values matter, implement the optional postcondition; observing state alone cannot detect an incorrect return value that leaves the state unchanged. The Erlang queue adapter demonstrates this check. Adapters must own their resources, synchronize asynchronous operations before observation, and avoid global names if tests run concurrently. Untrappable exits or external process termination can prevent normal cleanup.

EUnit and Common Test

queue_model_test_() ->
    {timeout, 60, fun() ->
        {ok, Model} = pitia:compile("spec/Queue.tla", #{
            constants => #{<<"Capacity">> => 3},
            invariants => [<<"Bounded">>]
        }),
        ?assertEqual(true, pitia:check(Model, queue_adapter, [{numtests, 200}]))
    end}.

In a Common Test suite, the same call belongs inside the test case:

queue_model(_Config) ->
    {ok, Model} = pitia:compile("spec/Queue.tla", #{
        constants => #{<<"Capacity">> => 3}
    }),
    true = pitia:check(Model, queue_adapter, [{numtests, 200}]),
    ok.

Run with rebar3 eunit or rebar3 ct. For CT projects that change the working directory, resolve the specification from your suite's data directory or use an absolute path. See test/pitia_SUITE.erl for an in-memory source example that is independent of the current directory.

Mix task

The optional task calls the same public API:

MIX_ENV=test mix pitia.check spec/Queue.tla MyApp.QueueAdapter \
  --constant Capacity=3 --invariant Bounded --numtests 200

The adapter must be compiled and available on the code path. CLI constants are integers; use the library API for other values. A compilation error, invalid option, or counterexample makes the task fail.

Parallel execution

Use the same model with a sequential prefix followed by two concurrent workers:

true = pitia:check(Model, counter_adapter, #{mode => parallel},
                   [{numtests, 200}, {max_size, 20}]).
assert Pitia.check(model, CounterAdapter, [mode: :parallel], numtests: 200)
# Or pass Pitia.property(model, CounterAdapter, mode: :parallel) to PropEr.

Parallel adapters must implement a pure postcondition/5 that checks each return value against the proposed before/after states. Pitia may call it repeatedly while searching possible orderings. Calls share a handle and must be safe to invoke from different processes. start/1 receives mode: parallel in its context.

Pitia observes the system before execution and after all commands finish. It does not take potentially inconsistent snapshots between concurrent calls. A passing run requires one serialization preserving each worker's order that satisfies return contracts, invariants, temporal safety monitors, and the observed final state. This checks serializability at the adapter's operation boundary; it does not enforce real-time ordering between workers or inspect transient internal states.

Execution options are mode (default sequential), and, in parallel mode, timeout (default 5000 milliseconds) and max_serializations (default 10000 candidate search steps, not complete histories). The timeout bounds execution and checking after adapter startup. Adapter startup and shutdown must terminate on their own. On timeout, Pitia stops execution workers before stopping the adapter. A search-budget limit reports inconclusive; a property requires ok to pass.

PropEr shrinks the prefix and worker commands. Convert its counterexample for replay:

[raw] = :proper.counterexample()
testcase = Pitia.parallel_actions(raw)
Pitia.replay_parallel(model, CounterAdapter, testcase, timeout: 5000)
# testcase = %{prefix: [], workers: [[{"Increment", []}], [{"Increment", []}]]}

Replay preserves actions and each worker's order, but the BEAM schedule remains nondeterministic. There is no controlled scheduler or schedule replay yet. The regression suite includes a faulty counter whose lost update shrinks to two calls, a correct atomic counter, and concurrent queue producers.

Temporal safety

Select temporal definitions explicitly using the properties compilation option:

NonNegative == [](count >= 0)
Monotonic == [][count' >= count]_count
model = Pitia.compile!("spec/Counter.tla", properties: ["NonNegative", "Monotonic"])
assert Pitia.check(model, CounterAdapter, [mode: :parallel], numtests: 100)
Pitia.monitor(model, [%{"count" => 0}, %{"count" => 2}, %{"count" => 1}])
# %{status: :violated, index: 2, failures: [...], ...}

Supported formulas are []P for state predicates, [][A]_vars for action predicates, and conjunctions of these formulas. Action predicates can use primed state expressions and UNCHANGED. The subscript is a state variable or tuple of variables, optionally through an operator alias. Boxed actions permit stuttering: if the subscript variables do not change, the action formula holds.

Selected monitors run automatically during sequential and parallel tests. monitor/2 also checks explicit finite traces without PropEr: every state must provide all model variables. It checks only selected properties, not whether the trace begins in Init or follows Next. Indices start at zero. Results are prefix_safe, violated, inconclusive for an empty trace, or error for invalid input. prefix_safe says nothing about an unobserved infinite suffix.

The Mix task supports the same options:

MIX_ENV=test mix pitia.check spec/Counter.tla CounterAdapter \
  --parallel --timeout 5000 --property NonNegative --property Monotonic

API and diagnostics

ErlangElixirResult
pitia:compile(Path, Options)Pitia.compile(path, options){ok, Model} or {error, Diagnostic}
—Pitia.compile!(path, options)Model or ArgumentError
pitia:compile_source(Source, Options)Pitia.compile_source(source, options)Compile a source binary/string
pitia:property(Model, Adapter)Pitia.property(model, adapter)A normal PropEr property
pitia:check(Model, Adapter, Options)Pitia.check(model, adapter, options)PropEr's result; assert it is exactly true
pitia:property(Model, Adapter, Execution)Pitia.property(model, adapter, execution)Property with an execution mode
pitia:check(Model, Adapter, Execution, Options)Pitia.check(model, adapter, execution, options)Check with execution and PropEr options
pitia:monitor(Model, States)Pitia.monitor(model, states)Temporal safety report for a finite trace
pitia:replay_parallel(Model, Adapter, Testcase)Pitia.replay_parallel(model, adapter, testcase)Parallel report; optional fourth argument supplies execution limits
pitia:parallel_actions(Testcase)Pitia.parallel_actions(testcase)Public replay data from a raw PropEr parallel testcase
pitia:replay(Model, Adapter, Actions)Pitia.replay(model, adapter, actions)Execution report with status and failure details

Compilation options are constants, invariants, properties, init (default Init), next (default Next), max_choices (default 1000), and file (diagnostic label). Unknown options fail. max_choices bounds candidate enumeration per state; it is not a trace length limit. Pass PropEr's max_size to control generated sequences.

Selected invariants are checked in the initial state and after each command. Invariants are opt-in by operator name; arbitrary definitions are not assumed to be invariants. Diagnostics include source locations where available, expected and observed states, the failing command, and invariant failures.

PropEr shrinks failed command sequences while rechecking preconditions. Retrieve its counterexample with proper:counterexample() / :proper.counterexample(). For a stable regression test, replay action names and arguments:

Pitia.replay(model, MyApp.QueueAdapter, [
  {"Enqueue", [1]}, {"Enqueue", [2]}, {"Dequeue", []}
])

The tests include a deliberately faulty queue, require PropEr to reduce its failure to three commands, and replay those commands against both implementations.

Supported TLA+ subset

  • Single modules with CONSTANT(S), VARIABLE(S), and local operator definitions.
  • EXTENDS Naturals, Integers, Sequences, FiniteSets, with the implemented operators below. These are native implementations of the subset, not imported upstream module files.
  • Integer, string, boolean, finite-set, and sequence literals.
  • Arithmetic + - * \div %, comparisons, equality, membership, and finite intervals.
  • Conjunction, disjunction, negation, IF / THEN / ELSE.
  • Len, Append, Head, Tail, sequence concatenation \o, and Cardinality.
  • Deterministic initial assignments and deterministic action updates, including UNCHANGED.
  • Next as named actions, disjunctions, and bounded existential choices such as \E x \in 0..3 : Enqueue(x).
  • Selected temporal safety properties: []P, [][A]_vars, and their conjunctions.
  • Line comments and nested block comments, with file/line/column diagnostics.

Parenthesize nested conjunction/disjunction lists and quantified branches: this version does not implement TLA+'s indentation-sensitive bullet-list grouping. At a terminal state, Pitia generates observation-only stuttering; it does not report that state as a model-checker deadlock. Input choices can be nondeterministic, but one action and concrete argument list must predict one next state.

Not supported yet: complete temporal specifications (Spec interpretation), eventuality (<>), leads-to, fairness, liveness checking, PlusCal, .cfg files, user-module imports/instances, LET/IN, recursive operators, records, general functions, comprehensions, unbounded quantification, or relational/implicit updates. Unsupported syntax is rejected even in unused definitions. Parsing a definition containing supported temporal syntax does not select it for execution: supply Init, Next, and explicit invariants/properties options. Pitia does not infer fairness assumptions or transition relations from Spec.

Pitia tests finite sampled executions of an implementation. It does not prove refinement, safety for all executions, or fairness/liveness properties.

Architecture

.tla source
    -> pitia_lexer -> pitia_parser -> pitia_compiler
    -> immutable model (guards, arguments, simultaneous updates)
    -> pitia_statem / pitia_parallel + pitia_adapter -> PropEr
    -> pitia_monitor (temporal safety) + pitia_serial (parallel witnesses)
    -> EUnit / Common Test / ExUnit

Compilation currently targets the shared model interpreter, not generated Erlang or Elixir source or per-model BEAM modules. The native backend can evolve without changing the public test API. The initial priorities are broader TLA+ syntax, stronger static validation, and compact counterexample persistence.

License

MIT License — see LICENSE. PropEr is a separately installed test tool with its own license; no PropEr or external TLA+ implementation is bundled.