Skip to content

Replace an implementation

Swap an implementation behind a contract by discharging a lema.contract/v1 selection via Store::check_witness, or record a stateful simulation witness (Replaces / Simulates) with the store's replace operation.

One of the biggest payoffs of separating contracts from implementations is that you (or your AI coding agent) can replace a simple reference implementation with a faster or more compact implementation while guaranteeing that callers continue to work.

Lema provides two complementary mechanisms for verified implementation replacement, depending on whether you are working with pure/functional contracts in a project or stateful Contract C R S machines at the store level:

  1. Contract selections (lema.contract/v1) and Store::check_witness: The everyday project workflow (lema add, lema diff, lema commit), where you select the same contract for your new implementation and prove that it satisfies the contract laws.
  2. Stateful simulation witnesses (Replaces / Simulates) and lema call replace: The store-level replacement operation (crates/lema-store/), which atomically moves an implementation alias only after verifying an accepted forward-simulation theorem between the old and new stateful implementations.

Workflow A: Replacing an implementation via .lema contract selections

Suppose your project currently uses a simple reference implementation MemoryStorage under the LawfulEscrowStorage contract, and you ask Claude Code or Codex to write an optimized implementation IndexedStorage.

1. Select the existing contract for the new implementation

Look at how LawfulEscrowStorage is defined in Pythonic .lema syntax:

Pythonic

You can publish this contract structure and select it for an implementation on day one without proving the laws first. Your implementation compiles and runs on the VM while the selection is tracked as open.

Pythonic contract view (EscrowStorage & LawfulEscrowStorage)
contract LawfulEscrowStorage(ops: EscrowStorage):
    law load_after_save(db: StoreHandle, u: Nat, acc: Account):
        ops.load_account(ops.save_account(db, u, acc), u) == acc

    law load_other_unchanged(db: StoreHandle, u1: Nat, u2: Nat, acc: Account):
        requires u1 != u2
        ensures ops.load_account(ops.save_account(db, u1, acc), u2) == ops.load_account(db, u2)

select LawfulEscrowStorage(MemoryStorage)

Lean

Lean view (EscrowStorage & LawfulEscrowStorage)
structure LawfulEscrowStorage (ops : EscrowStorage) : Prop where
  load_after_save : ∀ (db : StoreHandle) (u : Nat) (acc : Account),
    ops.load_account (ops.save_account db u acc) u = acc
  load_other_unchanged : ∀ (db : StoreHandle) (u1 u2 : Nat) (acc : Account),
    u1 ≠ u2 →
    ops.load_account (ops.save_account db u1 acc) u2 = ops.load_account db u2

-- Selected contract record: LawfulEscrowStorage MemoryStorage

Explanation

A key-value or account store needs two complementary laws: reading back the key you just saved returns the new account (load_after_save), and saving one user’s account never clobbers another user’s account (load_other_unchanged).

Separating the operational interface (EscrowStorage) from the proposition-valued contract (LawfulEscrowStorage) lets you write, build, and run MemoryStorage immediately, while recording LawfulEscrowStorage(MemoryStorage) as an open contract selection in the store.

Later, an AI coding agent can prove each law in a separate module. Proving one law records partial progress (1/2 laws proved, status still open); proving the whole contract marks the selection checked and unlocks generic conservation theorems.

In your .lema contract file, add a select directive binding the existing LawfulEscrowStorage contract to your new implementation IndexedStorage:

src/Storage.lema (selecting the contract for the candidate implementation)
select LawfulEscrowStorage(IndexedStorage)

Run lema add src/Storage.lema. This creates a new lema.contract/v1 selection record whose target.realizations pins the exact SHA-256 declaration ID of IndexedStorage, starting at status: "open".

2. Have your coding agent prove the contract for the candidate

Ask your coding agent to prove LawfulEscrowStorage IndexedStorage in a .lean proof module and run lema add:

Shell
lema add src/IndexedStorageProof.lean

When lema add accepts the proof theorem, Store::check_witness (crates/lema-store/src/records/contract.rs) verifies two things before marking select LawfulEscrowStorage(IndexedStorage) as checked:

  1. Statement equivalence: The theorem proves the closed target proposition LawfulEscrowStorage IndexedStorage (up to closed universe-level spelling equivalence).
  2. Exact implementation binding (target.realizations): Every constant cited in the theorem’s satisfaction object resolves to the exact SHA-256 declaration ID of IndexedStorage in your store. A theorem that proves LawfulEscrowStorage about the old MemoryStorage cannot discharge the selection for IndexedStorage, even if someone renames MemoryStorage to IndexedStorage in a scratch file.

Remember that for a multi-law contract structure like LawfulEscrowStorage, proving an individual law (load_after_save or load_other_unchanged) updates laws[i].by to record partial progress (1/2 laws proved) while keeping the top-level selection open. Only a theorem proving the whole LawfulEscrowStorage IndexedStorage target marks the selection checked.

3. Rebind callers and inspect lema diff

Update your application entry point (or swap the exported implementation name in src/) to use IndexedStorage, then run lema add, lema diff, and lema test:

Shell
lema add src/Main.lean
lema diff
lema test
lema commit -m "Switch storage engine to IndexedStorage with checked LawfulEscrowStorage proof"

In lema diff, check two details:

  • The contracts summary confirms select LawfulEscrowStorage(IndexedStorage) [checked].
  • The old_still_used field (visible in lema diff --json) confirms whether any remaining exported definitions or theorems in your project snapshot still cite the old MemoryStorage declaration ID.

Workflow B: Stateful simulation replacement (Replaces and lema call replace)

What if your component is a stateful protocol or actor machine (Impl C R M implementing Contract C R S from Core), where the old implementation (plain, state type M) and the new implementation (offset, state type N) use different internal state representations?

For stateful machines, Core and Replaces (Lema.Replaces) define forward simulation (Simulates):

  • Given an initial contract state s0 : S, an old initial machine state m0 : M, a new initial machine state n0 : N, and a representation relation R_rep : S → M → N → Prop linking their states at every step, Replaces s0 m0 n0 contract old_impl new_impl R_rep states that R_rep s0 m0 n0 holds initially and Simulates preserves R_rep across every valid command c where contract.pre s c holds.
  • By the kernel-checked theorem replaces_runs, any client program p : Prog C R A that is Safe on contract from s0 is guaranteed to return the exact same final answer when run against new_impl starting at n0 as it does when run against old_impl starting at m0.

1. Prove the Replaces theorem

In Lean, define the representation relation (for example, Shifted (s : Nat) (m : Nat) (n : Nat) : Prop := m = s ∧ n = s + 5, linking a counter starting at 0 with an offset counter starting at 5) and prove the theorem:

src/CounterReplace.lean (excerpt)
def PlainOffset : Prop :=
  Received.Replaces 0 0 5 counter plain offset Shifted

theorem plain_offset : PlainOffset :=
  ...

Publish the module so PlainOffset and plain_offset are accepted in .lema/store.

2. Move the implementation alias with lema call replace

Instead of moving counter.impl with a plain alias call (which checks no proof), invoke the store’s replace method, passing the accepted declaration IDs of the old implementation (expected), the new implementation (target), the contract, the Replaces claim, the proof theorem, the representation relation, and Lema.Replaces:

replace.json
{
  "name": "counter.impl",
  "expected": "<plain_declaration_id>",
  "target": "<offset_declaration_id>",
  "contract": "<counter_declaration_id>",
  "claim": "<PlainOffset_declaration_id>",
  "proof": "<plain_offset_declaration_id>",
  "representation": "<Shifted_declaration_id>",
  "relation": "<Lema_Replaces_declaration_id>",
  "expected_generation": 1,
  "idempotency_key": "steward/counter.impl/replace-to-offset"
}
Shell
lema call replace --params-file replace.json

Before moving counter.impl from plain to offset, the store verifies the structure of PlainOffset and its kernel receipt (plain_offset), confirming that the head constant is relation, that it connects expected (plain) to target (offset) on contract (counter) under representation (Shifted), and that proof establishes claim.

On success, the store moves counter.impl to offset at generation 2 and records a permanent replacement witness in .lema/store, which lema diff automatically discovers whenever a project revision substitutes offset for plain.

Common refusals

Refusal message containsCause and fix
theorem ... binds ... to ..., and the selection binds it to ...: it is about another implementationThe theorem passed to Store::check_witness proved the contract about a different declaration ID than the one selected in lema.contract/v1. Re-add the proof module against the current implementation.
different contract or shapeIn replace, the claim declaration does not have the 7-argument shape relation s0 m0 n0 contract expected target representation.
does not bind the requested implementationsexpected and target in replace.json are swapped relative to the theorem’s direction (Replaces ... old new).
the proof does not establish this exact replacement claimproof’s statement ID does not match claim’s body.
does not point at the expected implementationThe alias name was already moved by another caller; check lema call find for the current target and generation.

Lema v0.3.2 · Updated 29 October 2026 · Version and compatibility