Examples Gallery

Every example in examples/ is a runnable, type-checked Python module whose docstring declares the exact verdicts a conforming checker must report.

Run all examples locally or in your browser

Run python -m temporal_typing examples/ to validate every declaration, or tanny check examples/ to model-check all 12 models. Click Try in Tour ↗ on any example below to run it directly in WebAssembly.

Hour Clock#

File: examples/hour_clock.py · Expected: PASS (12 states) · Try in interactive Tour ↗

examples/hour_clock.py
"""The hour clock of Lamport's Specifying Systems, chapter 2: the hour hand, and nothing else.

    HCini == hr \\in (1 .. 12)
    HCnxt == hr' = IF hr # 12 THEN hr + 1 ELSE 1
    HC    == HCini /\\ [][HCnxt]_hr

Expected:
    hour_clock_model: PASS
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Annotated

from temporal_typing import Action, Init, Invariant, Model, State, prime, spec


@spec(
    init=Init(lambda s: s.hr in range(1, 13)),
    type_ok=Invariant(lambda s: s.hr in range(1, 13)),
)
@dataclass
class HourClock:
    hr: State[int]

    def tick(self) -> Annotated[None, Action(lambda s: prime(s.hr) == (s.hr + 1 if s.hr != 12 else 1))]:
        self.hr = self.hr + 1 if self.hr != 12 else 1


hour_clock_model = Model(HourClock)

DieHard Water Jugs#

File: examples/die_hard.py · Expected: FAIL invariant not_solved (6-step solution) · Try in interactive Tour ↗

examples/die_hard.py
"""DieHard: measure 4 gallons with a 3-gallon jug and a 5-gallon jug.

Two forms of the same specification: ``DieHardSpec`` declares each action's
transition, and ``DieHard`` is ordinary Python whose method bodies are the
transitions. ``not_solved`` is meant to fail: its counterexample is the
solution.

Expected:
    spec_model: FAIL invariant not_solved
    impl_model: FAIL invariant not_solved
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Annotated, Protocol

from temporal_typing import Action, Init, Invariant, Model, State, prime, spec


@spec(
    init=Init(lambda s: s.small == 0 and s.big == 0),
    type_ok=Invariant(lambda s: 0 <= s.small <= 3 and 0 <= s.big <= 5),
    not_solved=Invariant(lambda s: s.big != 4),
)
class DieHardSpec(Protocol):
    small: State[int]
    big: State[int]

    def fill_small(self) -> Annotated[None, Action(lambda s: prime(s.small) == 3)]: ...

    def fill_big(self) -> Annotated[None, Action(lambda s: prime(s.big) == 5)]: ...

    def empty_small(self) -> Annotated[None, Action(lambda s: prime(s.small) == 0)]: ...

    def empty_big(self) -> Annotated[None, Action(lambda s: prime(s.big) == 0)]: ...

    def pour_small_to_big(
        self,
    ) -> Annotated[
        None,
        Action(lambda s: prime(s.small) == s.small - min(s.small, 5 - s.big) and prime(s.big) == s.big + min(s.small, 5 - s.big)),
    ]: ...

    def pour_big_to_small(
        self,
    ) -> Annotated[
        None,
        Action(lambda s: prime(s.big) == s.big - min(s.big, 3 - s.small) and prime(s.small) == s.small + min(s.big, 3 - s.small)),
    ]: ...


@spec(
    type_ok=Invariant(lambda s: 0 <= s.small <= 3 and 0 <= s.big <= 5),
    not_solved=Invariant(lambda s: s.big != 4),
)
@dataclass
class DieHard:
    small: State[int] = 0
    big: State[int] = 0

    def fill_small(self) -> Annotated[None, Action()]:
        self.small = 3

    def fill_big(self) -> Annotated[None, Action()]:
        self.big = 5

    def empty_small(self) -> Annotated[None, Action()]:
        self.small = 0

    def empty_big(self) -> Annotated[None, Action()]:
        self.big = 0

    def pour_small_to_big(self) -> Annotated[None, Action()]:
        poured = min(self.small, 5 - self.big)
        self.small -= poured
        self.big += poured

    def pour_big_to_small(self) -> Annotated[None, Action()]:
        poured = min(self.big, 3 - self.small)
        self.big -= poured
        self.small += poured


spec_model = Model(DieHardSpec)
impl_model = Model(DieHard)

Bank Account (Ghost State & ActionInvariant)#

File: examples/bank_account.py · Expected: PASS (884 states) · Try in interactive Tour ↗

examples/bank_account.py
"""A bank account with refined types, a ghost ledger and an action invariant.

Expected:
    small_account_model: PASS
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Annotated

from temporal_typing import (
    Action,
    ActionInvariant,
    Assume,
    Constant,
    Ensures,
    Ghost,
    Init,
    Invariant,
    Model,
    Modifies,
    Pure,
    Requires,
    State,
    Where,
    prime,
    spec,
)

Positive = Annotated[int, Where(lambda x: x > 0, "positive")]
NonNegative = Annotated[int, Where(lambda x: x >= 0, "non-negative")]


@spec(
    valid_owner=Assume(lambda s: s.owner != ""),
    init=Init(lambda s: s.balance == 0 and s.ledger == ()),
    within_limit=Invariant(lambda s: s.balance >= -s.credit_limit),
    ledger_matches_balance=Invariant(lambda s: sum(s.ledger) == s.balance),
    ledger_append_only=ActionInvariant(lambda s: prime(s.ledger)[: len(s.ledger)] == s.ledger),
)
@dataclass
class BankAccount:
    owner: Constant[str]
    credit_limit: Constant[NonNegative] = 0
    balance: State[int] = 0
    ledger: Ghost[tuple[int, ...]] = ()

    @property
    def available(self) -> Pure[NonNegative]:
        return self.balance + self.credit_limit

    def deposit(
        self, amount: Positive
    ) -> Annotated[
        None,
        Action(lambda s, amount: prime(s.balance) == s.balance + amount and prime(s.ledger) == s.ledger + (amount,)),
        Modifies("balance", "ledger"),
    ]:
        self.balance += amount

    def withdraw(
        self, amount: Positive
    ) -> Annotated[
        Positive,
        Requires(lambda s, amount: amount <= s.available, "sufficient funds"),
        Action(lambda s, amount: prime(s.balance) == s.balance - amount and prime(s.ledger) == s.ledger + (-amount,)),
        Ensures(lambda s, amount, result: result == amount),
        Modifies("balance", "ledger"),
    ]:
        self.balance -= amount
        return amount


small_account_model = Model(
    BankAccount,
    constants={"owner": "alice", "credit_limit": 2},
    domains={Positive: range(1, 4)},
    state_constraint=lambda s: len(s.ledger) <= 4,
)

Function Contracts#

File: examples/contracts.py · Expected: PASS (sqrt, binary_search, clamp) · Try in interactive Tour ↗

examples/contracts.py
"""Function contracts: each body is checked against its Requires and Ensures.

A function contract is checked over the domains its model gives; the result
holds for those arguments only.

Expected:
    sqrt_model: PASS
    search_model: PASS
    clamp_model: PASS
"""

from __future__ import annotations

from typing import Annotated

from temporal_typing import Ensures, Model, Pure, Requires, Where, implies

NonNegative = Annotated[int, Where(lambda x: x >= 0, "non-negative")]
SortedInts = Annotated[
    tuple[int, ...],
    Where(lambda xs: all(xs[i] <= xs[i + 1] for i in range(len(xs) - 1)), "sorted"),
]


def integer_sqrt(
    n: NonNegative,
) -> Annotated[
    Pure[NonNegative],
    Ensures(lambda n, result: result * result <= n < (result + 1) * (result + 1)),
]:
    """The largest r with r * r <= n."""
    lo, hi = 0, n
    while lo <= hi:
        mid = (lo + hi) // 2
        if mid * mid <= n:
            lo = mid + 1
        else:
            hi = mid - 1
    return hi


def binary_search(
    xs: SortedInts, target: int
) -> Annotated[
    Pure[NonNegative | None],
    Ensures(lambda xs, target, result: (result is None and target not in xs) or (result is not None and xs[result] == target)),
]:
    """An index of target in xs, or None."""
    lo, hi = 0, len(xs) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if xs[mid] == target:
            return mid
        if xs[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return None


def clamp(
    value: int, low: int, high: int
) -> Annotated[
    Pure[int],
    Requires(lambda low, high: low <= high, "a non-empty interval"),
    Ensures(lambda value, low, high, result: low <= result <= high and implies(low <= value <= high, result == value)),
]:
    """value, moved into [low, high]."""
    if value < low:
        return low
    if value > high:
        return high
    return value


sqrt_model = Model(integer_sqrt, domains={NonNegative: range(0, 50)})
search_model = Model(
    binary_search,
    domains={
        SortedInts: [(), (1,), (1, 3), (1, 3, 5), (2, 2, 4), (-1, 0, 0, 7)],
        int: range(-2, 8),
    },
)
clamp_model = Model(clamp, domains={int: range(-3, 4)})

Counting Semaphore#

File: examples/semaphore.py · Expected: PASS (4 states, weak fairness) · Try in interactive Tour ↗

examples/semaphore.py
"""A counting semaphore: each action's body conforms to its declared transition.

Expected:
    semaphore_model: PASS
"""

from __future__ import annotations

from typing import Annotated

from temporal_typing import (
    Action,
    Assume,
    Constant,
    Ensures,
    Fairness,
    Init,
    Invariant,
    Model,
    Property,
    Requires,
    State,
    leads_to,
    prime,
    spec,
    weak_fairness,
)


@spec(
    positive_capacity=Assume(lambda s: s.capacity > 0),
    init=Init(lambda s: s.available == s.capacity),
    bounded=Invariant(lambda s: 0 <= s.available <= s.capacity),
    fair=Fairness(lambda s: weak_fairness(s.release())),
    progress=Property(lambda s: leads_to(s.available == 0, s.available > 0)),
)
class Semaphore:
    capacity: Constant[int]
    available: State[int]

    def __init__(self, capacity: int) -> None:
        self.capacity = capacity
        self.available = capacity

    def acquire(
        self,
    ) -> Annotated[
        bool,
        Requires(lambda s: s.available > 0),
        Action(lambda s: prime(s.available) == s.available - 1),
        Ensures(lambda s, result: result is True),
    ]:
        self.available -= 1
        return True

    def release(
        self,
    ) -> Annotated[
        None,
        Requires(lambda s: s.available < s.capacity),
        Action(lambda s: prime(s.available) == s.available + 1),
    ]:
        self.available += 1


semaphore_model = Model(Semaphore, constants={"capacity": 3})

Mutual Exclusion & Starvation Freedom#

File: examples/mutex.py · Expected: PASS (20 states, strong fairness) · Try in interactive Tour ↗

examples/mutex.py
"""Mutual exclusion with starvation freedom, for a set of processes.

Strong fairness on ``acquire`` is what makes ``starvation_free`` hold: under
weak fairness a waiting process can lose the lock forever.

Expected:
    mutex_model: PASS
"""

from __future__ import annotations

from typing import Annotated, Protocol

from temporal_typing import (
    Action,
    Assume,
    Constant,
    Fairness,
    Init,
    Invariant,
    Model,
    ModelValue,
    Property,
    Requires,
    State,
    enabled,
    implies,
    leads_to,
    prime,
    spec,
    strong_fairness,
    weak_fairness,
)


class Proc(ModelValue):
    """A process."""


@spec(
    non_empty_procs=Assume(lambda s: len(s.procs) > 0),
    init=Init(lambda s: s.holder is None and s.waiting == frozenset()),
    type_ok=Invariant(
        lambda s: (
            (s.holder is None or s.holder in s.procs)
            and s.waiting <= s.procs
            and implies(s.holder is not None, s.holder not in s.waiting)
        )
    ),
    never_stuck=Invariant(
        lambda s: any(enabled(s.request(p)) or enabled(s.acquire(p)) or enabled(s.release(p)) for p in s.procs)
    ),
    fair=Fairness(lambda s: all(strong_fairness(s.acquire(p)) and weak_fairness(s.release(p)) for p in s.procs)),
    starvation_free=Property(lambda s: all(leads_to(p in s.waiting, s.holder == p) for p in s.procs)),
)
class Mutex(Protocol):
    procs: Constant[frozenset[Proc]]
    holder: State[Proc | None]
    waiting: State[frozenset[Proc]]

    def request(
        self, p: Proc
    ) -> Annotated[
        None,
        Requires(lambda s, p: p not in s.waiting and s.holder != p),
        Action(lambda s, p: prime(s.waiting) == s.waiting | {p}),
    ]: ...

    def acquire(
        self, p: Proc
    ) -> Annotated[
        None,
        Requires(lambda s, p: p in s.waiting and s.holder is None),
        Action(lambda s, p: prime(s.holder) == p and prime(s.waiting) == s.waiting - {p}),
    ]: ...

    def release(
        self, p: Proc
    ) -> Annotated[
        None,
        Requires(lambda s, p: s.holder == p),
        Action(lambda s, p: prime(s.holder) is None),
    ]: ...


PROCS = frozenset({Proc("p1"), Proc("p2"), Proc("p3")})

mutex_model = Model(Mutex, constants={"procs": PROCS}, domains={Proc: PROCS})

Two-Phase Commit#

File: examples/two_phase_commit.py · Expected: PASS (160 states / 49 symmetry) · Try in interactive Tour ↗

examples/two_phase_commit.py
"""Two-phase commit, after Lamport's TwoPhase.tla.

``two_phase_model`` checks every clause. ``safety_model`` checks only the
invariants, so the checker may use the symmetry of the resource managers;
with a temporal property it may not.

Expected:
    two_phase_model: PASS
    safety_model: PASS
"""

from __future__ import annotations

from typing import Annotated, Literal, Protocol

from temporal_typing import (
    Action,
    Assume,
    Constant,
    Fairness,
    Init,
    Invariant,
    Model,
    ModelValue,
    Property,
    Requires,
    State,
    Symmetry,
    implies,
    leads_to,
    prime,
    spec,
    weak_fairness,
)

RMState = Literal["working", "prepared", "committed", "aborted"]
TMState = Literal["init", "committed", "aborted"]


class RM(ModelValue):
    """A resource manager."""


@spec(
    non_empty_rms=Assume(lambda s: len(s.rms) > 0),
    init=Init(lambda s: s.rm_state == {r: "working" for r in s.rms} and s.tm_state == "init" and s.tm_prepared == frozenset()),
    consistent=Invariant(
        lambda s: not any(s.rm_state[r1] == "committed" and s.rm_state[r2] == "aborted" for r1 in s.rms for r2 in s.rms)
    ),
    commit_requires_all_prepared=Invariant(
        lambda s: implies(
            s.tm_state == "committed",
            all(s.rm_state[r] in ("prepared", "committed") for r in s.rms),
        )
    ),
    fair=Fairness(
        lambda s: (
            weak_fairness(s.tm_commit())
            and all(weak_fairness(s.rm_rcv_commit(r)) and weak_fairness(s.rm_rcv_abort(r)) for r in s.rms)
        )
    ),
    decision_propagates=Property(
        lambda s: leads_to(
            s.tm_state == "committed",
            all(s.rm_state[r] == "committed" for r in s.rms),
        )
    ),
)
class TwoPhaseCommit(Protocol):
    rms: Constant[frozenset[RM]]
    rm_state: State[dict[RM, RMState]]
    tm_state: State[TMState]
    tm_prepared: State[frozenset[RM]]

    def rm_prepare(
        self, r: RM
    ) -> Annotated[
        None,
        Requires(lambda s, r: s.rm_state[r] == "working"),
        Action(lambda s, r: prime(s.rm_state) == {**s.rm_state, r: "prepared"}),
    ]: ...

    def tm_rcv_prepared(
        self, r: RM
    ) -> Annotated[
        None,
        Requires(lambda s, r: s.tm_state == "init" and s.rm_state[r] == "prepared"),
        Action(lambda s, r: prime(s.tm_prepared) == s.tm_prepared | {r}),
    ]: ...

    def tm_commit(
        self,
    ) -> Annotated[
        None,
        Requires(lambda s: s.tm_state == "init" and s.tm_prepared == s.rms),
        Action(lambda s: prime(s.tm_state) == "committed"),
    ]: ...

    def tm_abort(
        self,
    ) -> Annotated[
        None,
        Requires(lambda s: s.tm_state == "init"),
        Action(lambda s: prime(s.tm_state) == "aborted"),
    ]: ...

    def rm_rcv_commit(
        self, r: RM
    ) -> Annotated[
        None,
        Requires(lambda s, r: s.tm_state == "committed"),
        Action(lambda s, r: prime(s.rm_state) == {**s.rm_state, r: "committed"}),
    ]: ...

    def rm_rcv_abort(
        self, r: RM
    ) -> Annotated[
        None,
        Requires(lambda s, r: s.tm_state == "aborted"),
        Action(lambda s, r: prime(s.rm_state) == {**s.rm_state, r: "aborted"}),
    ]: ...


RMS = frozenset({RM("r1"), RM("r2"), RM("r3")})

two_phase_model = Model(TwoPhaseCommit, constants={"rms": RMS}, domains={RM: RMS}, check_deadlock=False)

safety_model = Model(
    TwoPhaseCommit,
    constants={"rms": Symmetry(RMS)},
    domains={RM: RMS},
    properties=(),
    check_deadlock=False,
)

Bounded Queue & Ring Buffer Refinement#

File: examples/bounded_queue.py · Expected: PASS (45 states, Refines) · Try in interactive Tour ↗

examples/bounded_queue.py
"""A bounded FIFO queue, and a ring buffer that refines it.

``BoundedQueue`` declares the abstract behaviour. ``RingBuffer`` is ordinary
Python; ``refines_queue`` maps its state onto the queue's, and the checker
checks every behaviour of the ring buffer is one of the queue, fairness
included.

Expected:
    ring_buffer_model: PASS
"""

from __future__ import annotations

from typing import Annotated, Generic, Protocol, TypeVar

from temporal_typing import (
    Action,
    Constant,
    Ensures,
    Fairness,
    Init,
    Invariant,
    Model,
    ModelValue,
    Modifies,
    Property,
    Refines,
    Requires,
    State,
    Where,
    leads_to,
    prime,
    spec,
    weak_fairness,
)

T = TypeVar("T")
Positive = Annotated[int, Where(lambda x: x > 0)]


@spec(
    init=Init(lambda s: s.items == ()),
    bounded=Invariant(lambda s: len(s.items) <= s.capacity),
    fair=Fairness(lambda s: weak_fairness(s.pop())),
    makes_space=Property(lambda s: leads_to(len(s.items) == s.capacity, len(s.items) < s.capacity)),
)
class BoundedQueue(Protocol[T]):
    capacity: Constant[Positive]
    items: State[tuple[T, ...]]

    def push(
        self, item: T
    ) -> Annotated[
        None,
        Requires(lambda s, item: len(s.items) < s.capacity),
        Action(lambda s, item: prime(s.items) == s.items + (item,)),
    ]: ...

    def pop(
        self,
    ) -> Annotated[
        T,
        Requires(lambda s: len(s.items) > 0),
        Action(lambda s: prime(s.items) == s.items[1:]),
        Ensures(lambda s, result: result == s.items[0]),
    ]: ...


@spec(
    init=Init(lambda s: s.buf == (None,) * s.capacity and s.head == 0 and s.size == 0),
    shape=Invariant(lambda s: len(s.buf) == s.capacity and 0 <= s.head < s.capacity and 0 <= s.size <= s.capacity),
    fair=Fairness(lambda s: weak_fairness(s.pop())),
)
class RingBuffer(Generic[T]):
    capacity: Constant[Positive]
    buf: State[tuple[T | None, ...]]
    head: State[int]
    size: State[int]

    def __init__(self, capacity: Positive) -> None:
        self.capacity = capacity
        self.buf = (None,) * capacity
        self.head = 0
        self.size = 0

    def push(self, item: T) -> Annotated[None, Requires(lambda s, item: s.size < s.capacity), Action()]:
        buf = list(self.buf)
        buf[(self.head + self.size) % self.capacity] = item
        self.buf = tuple(buf)
        self.size += 1

    def pop(self) -> Annotated[T, Requires(lambda s: s.size > 0), Action(), Modifies("buf", "head", "size")]:
        item = self.buf[self.head]
        assert item is not None
        buf = list(self.buf)
        buf[self.head] = None
        self.buf = tuple(buf)
        self.head = (self.head + 1) % self.capacity
        self.size -= 1
        return item

    def refines_queue(self) -> Refines[BoundedQueue[T]]:
        return Refines(
            capacity=self.capacity,
            items=tuple(self.buf[(self.head + i) % self.capacity] for i in range(self.size)),
        )


class Elem(ModelValue):
    """A queue element."""


ring_buffer_model = Model(
    RingBuffer,
    constants={"capacity": 3},
    domains={T: frozenset({Elem("e1"), Elem("e2")})},
)