Evolving programs, handles and concurrency
How stateful Lema programs upgrade engines and contracts without breaking callers, enforce single-owner resource handles and in-flight ticket locks, and compose concurrent tasks, actors, and sessions.
In Anatomy of a Lema program, we saw how a single caller (Prog), protocol rulebook (Contract), and engine (Impl) fit together. In a living production system, three deeper questions quickly follow:
- How does a codebase grow over months without re-proving every caller?
- How do you prevent resource leaks, double-closes, and use-after-cancel buffer bugs?
- How do concurrent tasks, stateful actors, and two-party channels run safely on top of
Prog?
All three answers are built directly out of Prog, Contract, and Safe at Layer -1 (Lema’s hardware-agnostic program core), without adding ad-hoc special cases to the compiler.
Four ways a stateful codebase grows over time
Suppose your application uses a key-value store Map (get, put, delete). As traffic grows, you will swap data structures, add operations, and split subsystems into modules. Lema handles each kind of upgrade with a specific proof tool so existing callers stay untouched:
New data structure behind one Contract
Swap an association list for a balanced tree; every Safe caller keeps its postcondition Q via sound.
Identical replies and final return value
Proves two engines emit the exact same reply sequence across every caller trace (automatic when Deterministic).
Tighten a Contract without touching callers
When K2 widens allowed calls or tightens reply promises over K1, existing Safe K1 proofs lift automatically.
Plug independent handlers together
Prog.interp translates layers downward while link merges disjoint command vocabularies side by side.
Each upgrade theorem discharges a distinct evolution step while keeping existing Safe caller proofs intact.
- 1. Swap private data structures (Implements)
- Suppose you replace an unsorted association list with a balanced tree or open-addressed table. Proving Implements against the same Map contract guarantees (via sound) that every Safe caller still achieves its postcondition Q.
- 2. Guarantee bit-for-bit identical behavior (Replaces and Deterministic)
- Sometimes a contract permits multiple valid replies (for example, opening a handle can return any fresh ID, such as 0, 1, 2 or 0, 2, 4). When you need a drop-in swap where every caller observes the exact same replies and return value, Replaces links the two engines from their initial states. Better yet, when a contract uniquely pins every reply (Deterministic, as key-value lookup does), proving Implements on each engine gives you Replaces automatically.
- 3. Strengthen or extend a contract (Refines)
- When a contract evolves over the same command vocabulary (for example, tightening reply guarantees or tracking richer model state while keeping existing operations valid), proving Refines lifts every caller already proved Safe against the older contract onto the newer contract without editing caller proofs.
- 4. Assemble subsystems side by side (interp and link)
- Real applications combine several command vocabularies at once, such as storage commands alongside clock and logging commands. Prog.interp translates high-level commands into lower-level ones (lifted by safe_interp), and link merges independently proved command handlers so teams can build and verify subsystems separately.
Linear handles and busy tickets without a borrow checker
Languages enforce resource ownership and protocol lifecycles in two main ways: either inside a substructural surface typechecker (such as Rust’s borrow checker, Linear Haskell, or Idris 2’s Quantitative Type Theory), or extrinsically through typestate and state-machine specifications in a theorem prover. Rather than adding a separate borrow or session checker to the kernel, Lema models single-owner resource lifecycles and asynchronous buffer locks as ordinary Contracts checked by Safe:
Single-owner 1-handles (Handles)
File descriptors, TCP sockets, and database transactions follow strict lifecycle rules: you cannot read from a closed handle, you cannot close the same handle twice, and you should not leak open handles when a request finishes.
Lema’s Handles contract models the set of currently open handles in the conceptual state S:
- No use-after-close or double-close: The contract precondition
prerequires a handle ID to be present in the open map before anyuseorclosestep. - Fresh handle promises: When
opencreates a handle,postpromises the returned handle ID was not already in the open map. Without that promise, opening two handlesaandbcould alias (a = b), causingclose ato leavebdangling. - No leaked handles: Requiring
AllClosedin the caller’s final postconditionQproves at check time that every branch of theProgtree closes every handle it opened, while at runtime handles remain plain integers with zero wrapper overhead.
Asynchronous busy locks (Tickets)
A notorious source of memory corruption in asynchronous I/O (such as io_uring or DMA queues) happens when a caller cancels a slow read or write and immediately reuses the byte buffer while the OS kernel is still writing into it.
Lema’s Tickets contract closes that window by separating cancellation request from completion fence:
Ready handle
Caller owns buffer; start(h, op) issues ticket tk.
Locked for OS / DMA
use(h), close(h), or second start(h) Cancellation pending
Flagged cancelled, yet busy stays locked while kernel DMA may still write.
Scrubbed and ready
Host completion fenced, partial bytes scrubbed, handle safe to reuse or close.
Asking to cancel flags the ticket while keeping the handle locked busy until await confirms host DMA access has stopped.
Because cancel leaves the busy lock intact in Tickets.next until await collects the terminal completion, no Safe caller can ever touch or free an in-flight buffer prematurely.
How the four concurrency pillars build on Layer -1
Building on Prog, Handles, and Tickets, Lema models four concurrency patterns at Layer -1 so concurrent services can be reasoned about mathematically rather than debugged by chasing race conditions:
- 1. Structured parallelism (Parallel and Tickets)
- When a parent workflow splits work across concurrent tasks operating on disjoint sets of handles, schedule_independent proves that every task interleaving reaches the exact same final state.
- 2. State-owning and durable actors (Actor, Replies, Durable, CallGraph)
- Each actor owns its private state behind a bounded FIFO mailbox (returning a clean busy signal rather than blocking unboundedly when full). Ticketed request/reply actors are proved linearizable, ranked actor call graphs are proved free of wait-cycle deadlocks in the model, and Durable proves that replaying a write-ahead log onto a snapshot recovers exact live state with idempotency keys preventing duplicate execution.
- 3. Session-typed channels (Channels and Sessions)
- Two-party conversations carry dual protocol types (s on one endpoint and dual s on the other). Proving each endpoint Safe against its half of the session guarantees session fidelity: neither side sends an unexpected message or waits forever in a mismatched state.
- 4. Commutative concurrency (Commute)
- When two independent operations commute (swapping their order yields the same replies and final state), perm_run proves batches can be reordered safely without changing observable results. The VM executes tasks, actors, and sessions today; automatic commutative batching remains planned.
Continue to Capabilities and the host boundary (#7) to see how these Layer -1 programs cross the boundary into real operating system sockets, disks, clocks, and secrets.
Lema v0.3.2 · Updated 29 October 2026 · Version and compatibility