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.
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:
- File collection & parsing: Collects
.pyfiles frompaths(recursively for directories, skipping dotfiles and__pycache__) and parses each file withruff_python_parser. - Transitive imports: Scans
from ... import ...statements and opens referenced local modules found under--rootdirectories or the importing file's package root. Only files explicitly passed by the user have theirModel(...)bindings checked. - Extraction into IR: Extracts
@specclasses (Spec), module-level contract and helper functions (Function),ModelValuesubclasses (sorts), andModel(...)bindings (Model). Python expressions and method bodies are preserved asruff_python_astnodes so translation can operate directly on the AST with accurate source locations. - Unit-scoped diagnostics: Diagnostics are tagged with the unit (specification, contract, or model) they invalidate, or
Nonefor 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.tlaplus one module (Abs<N>_<Name>.tla) for each refined abstract specification.cfg:Main.cfgwithSPECIFICATION Spec,CONSTANTS,INVARIANT,PROPERTY,CONSTRAINT,ACTION_CONSTRAINT, andSYMMETRY.- 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) andPyMod(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)invokesAssert(FALSE, "tanny|runtime|" \o msg)so Python runtime errors (division by zero, out-of-range index,KeyError, emptypop) surface asFAIL runtimerather 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:
[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 valueUndef).otracks control flow:"go"(normal execution),"ret"(with return value inret),"raise","assert"(with source line inline),"brk", or"cnt".- Statements chain via
LET st1 == ... st2 == ... IN ..., short-circuiting whenevero # "go". whileandforloops are lowered toRECURSIVEhelper operators that handlebreak("brk"),continue("cnt"),return,raise, andassert.- A
raisesetso = "raise", and the enclosing action requiresr.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 Pythonassertfailed.tanny|conformance|<action>|frame <var>— a body modified a variable outside itsModifiesframe.tanny|conformance|<action>|predicate— a body's resulting state disagreed with itsActionpredicate.tanny|conformance|<action>|ensures— anEnsurespostcondition failed.tanny|conformance|<action>|result— the return value violated aWherepredicate on the return type.tanny|runtime|<msg>— a Python runtime failure fromPyFail.
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:
tanny-translateemits a separate moduleAbs<N>_<AbstractSpec>.tlafor the abstract specification.Main.tlainstantiates it viaR<N> == INSTANCE Abs<N>_<AbstractSpec> WITH <mapping>.- 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 userFAIL.
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.pyparses theExpected:block from each.pyfile's module docstring intests/temporal-typing/tests/checkerandtests/temporal-typing/examples, runstanny 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
KNOWNinsidescripts/conformance.py. make checkrunscargo fmt --check,cargo clippy --workspace --all-targets -- -D warnings,cargo test --workspace, andmake conformance.