3 Type Architecture

3.1 Module layout

The typed surface described in this section is not spread arbitrarily across the codebase — each layer below owns exactly one of the concerns this paper argues for (ADTs, nominal identifiers, session types, affine handles), and each layer is exercised by the colony coordination loop at the bottom, never bypassed:

The analysis enters through the colony layer, which composes agents, storage, protocol, networking, and a pheromone field.
The analysis enters through the colony layer, which composes agents, storage, protocol, networking, and a pheromone field.

3.2 Algebraic data types: Result[T, E]

src/template_formal/types/result.py defines Result[T, E] as a tagged union of two frozen dataclasses, Ok[T] and Err[E], each carrying a Literal["ok"]/Literal["err"] tag field. This is the closest structural analogue Python offers to the sum types of ML-family languages (Milner (1978)) and to the Curry–Howard “propositions as types” reading of a disjoint union as a proof of “either \(A\) or \(B\)” (Wadler (2015)): a function returning Result[T, E] documents, in its signature, that failure is an ordinary, structurally-typed value — never an uncaught exception for an expected failure mode. match/case narrowing on the tag field, combined with typing.assert_never in the default arm, makes an exhaustiveness bug — a match that handles Ok and forgets Err — a real mypy --strict type error, not a runtime surprise.

3.3 Nominal identifiers: AgentId, MessageId, TxnId

src/template_formal/types/ids.py wraps uuid.UUID three times via typing.NewType: AgentId, MessageId, TxnId. All three are, at runtime, plain UUID values — indistinguishable from one another and from a bare UUID. The distinction exists only at the type-checker level: mypy --strict rejects passing an AgentId where a MessageId is expected, even though nothing about the underlying bytes differs. This is Pierce’s (Pierce (2002)) textbook case for nominal typing over structural typing where the underlying representation is shared but the domain meaning is not.

3.4 Session-typed protocol state machine

src/template_formal/protocol/session.py implements a session-typed handshake protocol in the tradition of (Honda et al. 1998): four distinct classes — IdleSession, HandshakingSession, EstablishedSession, ClosedSession — each parameterizing SessionEndpoint[PhaseT] with exactly one phase marker from types/phase.py. Each phase-transition method returns the next phase’s concrete class (e.g. IdleSession.open() -> HandshakingSession), never a union that also includes an illegal successor. Data-transfer methods (send/receive) exist only on EstablishedSession — they are not defined at all on IdleSession or HandshakingSession — so calling them on the wrong phase is an outright attribute-resolution type error under mypy --strict, not a caught exception at runtime.

The diagram below is the real phase state machine, not a simplification of it: every solid edge is a phase-transition method that exists in src/template_formal/protocol/session.py, and every dashed edge is one of the two fault-injected error paths ISC-23/24 test through the in-process bus (network/bus.py) — Result.Err(ProtocolViolation(...)) when a session method rejects an out-of-order or mis-addressed frame, and Result.Err(MalformedMessage(...)) when decode_wire_message rejects corrupted wire bytes before any phase method ever runs. Neither error path advances the session to a new phase class; both are represented as terminal outcomes of the attempted transition, matching the code exactly (accept_hello/complete mark _consumed = True and return Err(...) from the same phase object, they do not construct a next-phase class).

The handshake state machine advances through idle, handshaking, established, and closed phases. Error paths leave the phase unchanged.
The handshake state machine advances through idle, handshaking, established, and closed phases. Error paths leave the phase unchanged.

The real IdleSession → HandshakingSession → EstablishedSession → ClosedSession phase machine plus its two fault-injected error edges — dropped frames surface as ProtocolViolation at the session-method boundary, corrupted frames surface as MalformedMessage at the wire-decode boundary, and neither ever crashes or silently advances the phase (sec. 6, “Fault-injected protocol negative controls”).

3.5 Affine-discipline resource handles

Definition 1 (Affine-discipline resource handle). An is an object that (i) is immutable after construction (frozen=True, __slots__-restricted, no public mutator), (ii) carries a private consumed flag set exactly once by its first consuming call, and (iii) raises a dedicated exception on every subsequent consuming call rather than silently re-executing or returning stale state. TransactionHandle (storage/transaction.py) and every protocol-phase class (protocol/session.py) satisfy this definition, checked at runtime, not at edit time.

src/template_formal/storage/transaction.py’s TransactionHandle and the protocol-phase classes above are what this paper calls affine-discipline handles per the definition above: frozen, __slots__-restricted objects carrying a private consumed flag, checked and raised (ConsumedHandleError/SessionConsumedError) on every consuming method call. The term is chosen deliberately over describing Python’s guarantee here as compiler-enforced structural linearity of the kind Jung et al. (2018) formalize for Rust’s ownership/borrowing system: Rust’s borrow checker rejects a double-move or a use-after-move at compile time, as a type error; Python’s runtime here rejects a double-commit at runtime, as a raised exception, one call after the type checker has already let the program through. Both defend the same invariant — a resource is consumed at most once — but by different mechanisms, and this paper is careful never to claim Python achieves the compile-time version.

3.6 What mypy –strict proves vs. what is a runtime discipline

This section states, claim by claim, exactly which invariants above are edit-time/CI-time type-checker guarantees and which are runtime-checked disciplines — and cites the ISC (Ideal-State Criterion) number of the test that would fail if the claim were false.

Proposition 2 (Static type-safety guarantees, edit-time/CI-time only). Each of the following is rejected by mypy --strict before the program ever runs, and each rejection is exercised by a real mypy --strict subprocess invocation over a negative-control fixture (never a hand-inspected signature): nominal identifier confusion (AgentId for MessageId), a non-exhaustive match over Result, a phase-inappropriate method call on a session-typed handle, an out-of-Literal isolation level, an Agent constructed from a bare str/UUID, and a structurally-nonconforming PheromoneField. See the itemized list below for the exact fixture and ISC bound to each claim.

Proved by mypy –strict (edit-time/CI-time only):

Proposition 3 (Runtime-only disciplines, not type-checker guarantees). None of the following is ill-typed under mypy --strict: each is instead caught only at runtime, by an explicit consumed-flag check or an explicit wire-decode validation, and each is exercised by a real fault-injected test (a seeded, reproducible fault sequence through the in-process bus, never a fault-free-only happy path). This is the affine-discipline handle of the definition above paying off dynamically where Python’s static type system structurally cannot.

Runtime disciplines only — not type-checker guarantees:

What this section explicitly does not claim: no sentence in this manuscript, and no docstring in src/template_formal/, asserts that Python’s type system enforces resource-affine or resource-structural-linear discipline at compile time, or that it performs the kind of type-level proof-obligation checking a proof assistant’s value-indexed type theory performs. Affine-discipline handles here are runtime-guarded, full stop; a grep for the two named classes of compile-time guarantee this paragraph deliberately does not use, run against this manuscript, returns zero matches (ISC-44) — there is no limitations subsection that needs the exemption, because the template makes neither claim anywhere to begin with.