Architecture

Tanny is structured as a pipeline that takes Python source files, extracts Temporal Typing declarations statically, translates each model into TLA⁺ with Python semantics, runs Manyan in process, and maps Manyan's results back into Python-level verdicts and traces.

text
Python source (.py)
       │
       ▼
 tanny-frontend    Parse with ruff_python_parser, resolve imports & names, extract IR & diagnostics
       │
       ▼
 tanny-translate   Lower specs, bodies, refinements, and contracts to TLA⁺ + Main.cfg + Py.tla
       │
       ▼
     manyan        Run Manyan C11 engine in process via manyan-sys FFI; capture output & values
       │
       ▼
     tanny         Decode obligations, tagged Asserts, and traces into PASS / FAIL / ERROR verdicts

Workspace Layout#

The Cargo workspace contains six crates:

Crate Path Role
tanny crates/tanny Binary crate. Drives the pipeline, formats text and JSON verdicts, decodes counterexamples into Python syntax, and maps outcomes to exit codes.
tanny-cli crates/tanny-cli clap CLI definition for tanny check and tanny translate.
tanny-frontend crates/tanny-frontend Static Python front-end implementing checker.md §1–3 and §6.
tanny-translate crates/tanny-translate Translator from the front-end IR to TLA⁺ modules and model configurations (checker.md §4–5).
manyan crates/manyan Safe Rust bindings to Manyan's C API (check, Options, Outcome, Status, Value).
manyan-sys crates/manyan-sys Raw FFI bindings compiling manyan.c and manyan-std.c from the crates/manyan-sys/manyan Git submodule via cc.

Python packaging is handled by maturin (bindings = "bin" in pyproject.toml), with a thin wrapper in python/tanny that locates the installed binary for python -m tanny.

Front-End (tanny-frontend)#

tanny_frontend::load(paths, roots) returns a Program without executing any Python code:

  1. File collection & parsing: Collects .py files from paths (recursively for directories, skipping dotfiles and __pycache__) and parses each file with ruff_python_parser.
  2. Transitive imports: Scans from ... import ... statements and opens referenced local modules found under --root directories or the importing file's package root. Only files explicitly passed by the user have their Model(...) bindings checked.
  3. Extraction into IR: Extracts @spec classes (Spec), module-level contract and helper functions (Function), ModelValue subclasses (sorts), and Model(...) bindings (Model). Python expressions and method bodies are preserved as ruff_python_ast nodes so translation can operate directly on the AST with accurate source locations.
  4. Unit-scoped diagnostics: Diagnostics are tagged with the unit (specification, contract, or model) they invalidate, or None for file-wide errors such as syntax errors. Program::diagnostics_of(model) collects only the diagnostics belonging to that model, the unit it checks, and any specifications it transitively refines—so an error in one unrelated model does not block other models in the same run.

Translation (tanny-translate)#

tanny_translate::translate(program, model) produces a Translation containing:

  • modules: Main.tla plus one module (Abs<N>_<Name>.tla) for each refined abstract specification.
  • cfg: Main.cfg with SPECIFICATION Spec, CONSTANTS, INVARIANT, PROPERTY, CONSTRAINT, ACTION_CONSTRAINT, and SYMMETRY.
  • Metadata maps (obligations, variables, model_values, actions, domains) used by Tanny to interpret Manyan's result and render Python traces.

Value Mapping and Py.tla#

Every translated module extends Integers, Sequences, FiniteSets, TLC, and Py (crates/tanny-translate/src/Py.tla).

Python type / value TLA⁺ representation
bool (True, False) TRUE, FALSE
int TLA⁺ integer
str TLA⁺ string
None Model value None
ModelValue subclass instance S('a') Model value S_a
tuple[T, ...], list[T] TLA⁺ sequence <<...>>
frozenset[T], set[T] TLA⁺ set {...}
dict[K, V] TLA⁺ function (PyEmpty for {})

Because TLA⁺ and Python disagree on several operations, Py.tla supplies Python-compatible helpers:

  • Arithmetic: PyDiv (floor division, raising on zero) and PyMod (divisor-sign remainder).
  • Sequences: 0-based and negative indexing (PyIx, PySetIx), clamping slices (PySlice), PyRange / PyRange3, PyIn, PyCount, PyIndex, PyTimes, PyPop, PyLast, PyReversed, PySum, PySortSeq.
  • Sets & dicts: PySumSet, PyMinSet, PyMaxSet, PySorted, PyKey, PyGet, PyPut, PyDel, PyValues, PyItems, PyDiscard, PyRemove.
  • Runtime errors: PyFail(msg) invokes Assert(FALSE, "tanny|runtime|" \o msg) so Python runtime errors (division by zero, out-of-range index, KeyError, empty pop) surface as FAIL runtime rather than opaque TLA⁺ evaluation errors.

Method Body Lowering#

Imperative Python method bodies (crates/tanny-translate/src/body.rs) are lowered to pure TLA⁺ expressions over a state record:

tla
[s_x |-> x, ..., l_tmp |-> Undef, o |-> "go", ret |-> None, line |-> 0]
  • s_<var> holds each specification variable; l_<name> holds each local variable assigned in the body (initialized to model value Undef).
  • o tracks control flow: "go" (normal execution), "ret" (with return value in ret), "raise", "assert" (with source line in line), "brk", or "cnt".
  • Statements chain via LET st1 == ... st2 == ... IN ..., short-circuiting whenever o # "go".
  • while and for loops are lowered to RECURSIVE helper operators that handle break ("brk"), continue ("cnt"), return, raise, and assert.
  • A raise sets o = "raise", and the enclosing action requires r.o # "raise", modeling raised exceptions as disabled transitions (consistent with Temporal Typing's semantics).

Supported body statements include assignments (=, annotated assignment, augmented assignment, tuple unpacking, list/dict subscript assignment), del d[k], in-place collection mutators (list.append/extend/pop/clear, set.add/discard/remove/clear/update, dict.update/clear/pop), if/elif/else, while, for, break, continue, return, raise, assert, and pass. Unsupported constructs (try, with, match, global/nonlocal, nested def/class, local import, for/while ... else, chained assignment) are rejected cleanly with ERROR unsupported.

Operational Obligations via Tagged Assert#

Invariants, Where type refinements on variables, ActionInvariant, Assume, and Property clauses map directly to TLA⁺ INVARIANT, ASSUME, and PROPERTY declarations and are recorded in Translation::obligations.

Operational obligations inside an action step are encoded as Assert(..., "tanny|<kind>|<action>|<detail>"):

  • tanny|assertion|<action>|<line> — a Python assert failed.
  • tanny|conformance|<action>|frame <var> — a body modified a variable outside its Modifies frame.
  • tanny|conformance|<action>|predicate — a body's resulting state disagreed with its Action predicate.
  • tanny|conformance|<action>|ensures — an Ensures postcondition failed.
  • tanny|conformance|<action>|result — the return value violated a Where predicate on the return type.
  • tanny|runtime|<msg> — a Python runtime failure from PyFail.

When Manyan reports an assertion failure, Tanny parses the "tanny|..." tag from the output to produce the exact FAIL kind, action name, and detail.

Refinements#

For each -> Refines[AbstractSpec] mapping on a concrete specification:

  1. tanny-translate emits a separate module Abs<N>_<AbstractSpec>.tla for the abstract specification.
  2. Main.tla instantiates it via R<N> == INSTANCE Abs<N>_<AbstractSpec> WITH <mapping>.
  3. Each proof obligation is exported as an individual TLA⁺ PROPERTY—R<N>_init, R<N>_step ([][R<N>!Next]_(R<N>!vars)), and one property per abstract fairness clause, invariant, action invariant, and temporal property—so a failure identifies which refinement obligation broke.

Function Contracts#

A Model targeting a standalone function with Requires / Ensures translates to a single-step specification whose Init quantifies arg_<p> over each parameter's domain and sets result = IF Guard THEN F_fn(...) ELSE None, with Next == UNCHANGED vars, check_deadlock = false, and an invariant Contract == Guard => <ensures and return Where>.

Checking and Error Invariant (tanny + manyan)#

Tanny writes Py.tla, the translated modules, and Main.cfg into a temporary directory and calls manyan::check.

A core design invariant of Tanny is:

A translation that Manyan rejects with a parse, config, or untagged evaluation error is always Tanny's bug, reported as ERROR internal—never as a user FAIL.

Every user error is caught in tanny-frontend or tanny-translate with a source location, or turned into a tagged Assert / named obligation.

Conformance Testing#

Tanny is validated against Temporal Typing's conformance suite, pinned as a Git submodule at tests/temporal-typing.

  • scripts/conformance.py parses the Expected: block from each .py file's module docstring in tests/temporal-typing/tests/checker and tests/temporal-typing/examples, runs tanny check --json, and asserts that every model's verdict, failure/error kind, failing name, and warnings match.
  • Any intentional divergence from the pinned upstream suite must be documented with rationale in KNOWN inside scripts/conformance.py.
  • make check runs cargo fmt --check, cargo clippy --workspace --all-targets -- -D warnings, cargo test --workspace, and make conformance.