Type Theory for C++ and Odin Engineers

From domain knowledge and strong native types to mathematical models and formal verification with Lean 4

Introduction

If you have spent years writing C++ or Odin, you already use many of the ideas that motivate #type_theory. You distinguish an integer from a pointer, use classes or package boundaries to protect invariants, parameterise types with templates or polymorphic declarations, and represent alternatives with tagged unions. You also know that a programme can compile without doing what its author intended.

Type theory gives us a mathematical framework for thinking about these ideas. In particular, #dependent_type_theory allows us to express relationships between values, types and logical propositions. In #Lean, we can construct mathematical models of software, state properties of those models and provide machine-checkable proofs of those properties.

The objective of this tutorial is not to persuade you to replace C++ or Odin with Lean. It is to help you understand how formal reasoning can improve the specification, design and verification of software written in C++, C, Odin or another systems language. We will begin with familiar engineering problems and introduce mathematical notation only when it is useful.

The theoretical inspiration is Herman Geuvers' Introduction to Type Theory, particularly its discussion of types, functions, proof checking and dependent types. The software examples, exercises and verification workflow are an engineering-oriented adaptation, supplemented by the official Theorem Proving in Lean 4 textbook.

What you will learn

By the end, you should be able to design domain-specific types, explain what native type checking does and does not guarantee, reduce the number of assumptions needed to understand an interface, map domain relationships to types and predicates, read a simple Lean theorem, understand what its assumptions mean, construct basic proofs, express an invariant, and distinguish a proof about a mathematical model from evidence about a native implementation. You should also be in a better position to review formal specifications and proofs produced by coding agents.

How to use this tutorial

Work through the chapters in order. Chapters 1–5 establish the foundations, chapters 6–10 introduce proofs and dependent types, and chapters 11–14 apply those concepts to software verification. The final sections provide exercises, a study plan and further reading. There is no need to study category theory or advanced mathematical logic before starting.

Install Lean 4 using the official installation guide, or try the Lean web editor. Use the Lean infoview to inspect the type of an expression and the current proof goal. The Lean examples are intended for Lean 4; the complete capstone includes its own import. Code snippets in other sections are independent teaching examples unless explicitly described as continuations. C++ examples use C++20 except where noted. Odin examples use the syntax described in the official Odin overview, attributes and directives. Install Odin using its getting started guide. For standalone exercises, place declarations in a file beginning with package main and add a main :: proc() {} if needed; execute examples in main. Snippets with the same names are alternatives, not one concatenated source file. Examples marked as errors are deliberate negative tests. Mermaid diagrams render in compatible Markdown viewers; their source remains readable in a plain text editor.

Verification note: This edition retains the original tutorial and its C++20 capstone, previously compiler-checked with #GCC. Newly added Odin and Lean examples are documentation-reviewed but not compiler-tested: neither compiler is installed in the revision environment. New standalone C++ examples are checked where indicated in the revision note at the end. Deliberately invalid lines are commented or explicitly identified. All models and snippets are educational, not certified production artefacts.

Contents

  1. What does a type actually tell us?
  2. Types, sets and judgements
  3. Functions and lambda calculus
  4. Constructing types
  5. Generics, polymorphism and universes
  6. Propositions as types
  7. Reading and writing proofs
  8. Dependent types
  9. Equality and computation
  10. Induction and recursive structures
  11. Contracts and formal specifications
  12. Capstone: a verified buffer state machine
  13. From a Lean model to C++ and Odin implementations
  14. Using Lean in an agentic engineering harness
  15. Exercises and solutions
  16. A study plan and reading guide
  17. Glossary and mathematical notation

1. What does a type actually tell us?

Consider this function declaration:

int increment(int x);

As a C++ engineer, you immediately know the input and output types: the function receives an int and returns an int. You probably infer from the name that the result should be one greater than the argument. But the compiler does not enforce that interpretation.

All three of these bodies satisfy the declared return type:

return x + 1;   // Intended behaviour, if no signed overflow occurs
return x - 1;   // Different behaviour, if no signed overflow occurs
return 0;       // Also type-correct

The function's type tells us something important, but it does not completely specify the function's behaviour. We can describe a stronger requirement in mathematics: for every input in the admissible domain, the result must equal the input plus one.

For now, use unbounded natural numbers instead of C++ machine integers. In Lean:

def increment (x : Nat) : Nat := x + 1

theorem increment_correct (x : Nat) :
    increment x = x + 1 := by
  rfl

def introduces a definition. Nat is the type of natural numbers (0, 1, 2, ...). theorem introduces a proposition and its proof. rfl is a tactic that establishes equality when both sides are definitionally equal, as they are here.

This first theorem is deliberately trivial. It is essentially a consequence of the definition, rather than an independent and demanding specification. The point is to see the difference between specifying a computation and specifying a property about a computation. Later, we will test the strength of the property itself.

Informal intent: increment by one Function signature Behavioural specification Type-correct implementation Proof obligation Checked evidence about the model

Notice the change in mathematical domain. C++ int has a finite implementation-dependent range, and signed overflow is undefined behaviour. Lean Nat is unbounded and non-negative. A proof about natural numbers does not establish that the C++ implementation is safe at INT_MAX. The relationship between the mathematical and machine representations is itself a verification problem.

Exercise: Name three functions in a codebase you know whose signatures communicate substantially less than their intended behaviour. Write one sentence describing the missing property for each.

1.1 Domain meaning is not machine representation

Consider a renderer in which all resource identifiers are unsigned 32-bit integers. bind_texture(42) may be well typed even if 42 came from a mesh table. The compiler cannot infer the distinction from a comment or variable name. Give the concepts distinct type identities instead.

#include <cstdint>
struct TextureId { std::uint32_t value; };
struct MeshId    { std::uint32_t value; };
void bind_texture(TextureId id);
// bind_texture(MeshId{42}); // intended compilation error
Texture_ID :: distinct u32
Mesh_ID    :: distinct u32

bind_texture :: proc(id: Texture_ID) {
    // GPU binding omitted.
}

example :: proc() {
    texture: Texture_ID = 42
    mesh: Mesh_ID = 42
    bind_texture(texture)
    // bind_texture(mesh) // intended compilation error
    _ = mesh
}

#assert(size_of(Texture_ID) == size_of(u32))

An Odin alias such as Texture_ID :: u32 would give us a name, not a new type identity. A distinct type supplies a nominal distinction while retaining the base representation. A C++ wrapper introduces a distinct structure; check its layout and ABI where interoperability requires it. Neither wrapper proves that 42 identifies a live resource, belongs to the correct device or has the correct generation. Explicit conversions can also bypass nominal distinctions.

This distinction is fundamental: a representation tells us how a value is stored, a domain type tells us what it means, and an invariant tells us what must be true of it. One representation can serve many meanings.

1.2 Design for reasoning bandwidth

A strong type system moves recurring questions from human or agent reasoning into compiler checks. With an untyped integer, every caller may need to recover which resource table it refers to, whether it is an index or a handle, and whether it is still live. With a well-designed interface, some of that context travels with the value. The remaining questions can be concentrated at a validation boundary or expressed as contracts.

For humans, the cost is working memory, attention and the number of definitions that must be understood together. For agents, the cost includes retrieval, context tokens, inference, repeated repair attempts and the risk of missing implicit rules. Neither is directly measurable by counting types alone. More types are not inherently better; an excessive web of generic wrappers can increase the context needed to make a change.

The target is local reasoning: understand a small contract and its relevant assumptions without having to reconstruct the entire application. Good design reduces the number of plausible but incorrect interpretations of an interface.

Raw representation Named domain type Typed interface Explicit contract Evidence Repeated reasoning cost Smaller reasoning burden implicit meaning at every use compiler rejects selected mistakes

Exercise: Choose three pairs of values sharing a representation but having different meaning, such as byte offsets and glyph indices, degrees and radians, or mesh and material identifiers. State which operations or conversions should be legal. Then ask which rules cannot be encoded by a nominal type alone.

2. Types, sets and judgements

2.1 Thinking about admissible values

A useful first approximation is that a type describes a collection of admissible values. Bool admits true and false; Nat admits natural numbers. But a type is more than a set of values: the type system specifies how terms can be formed, used and checked. Geuvers discusses this distinction in section 2 of his lecture notes.

In mathematics, we write to say that 3 is a member of the set of natural numbers. In type theory, we write:

(1)

Read this as “3 has type Nat”. The colon is a typing judgement, not a set-membership operator.

Consider a more demanding set: all natural numbers satisfying a difficult mathematical property. Deciding whether a number belongs to that set may require finding a proof. In a proof-oriented type system we can instead package a number with evidence that it satisfies the property. The checker can then validate the supplied evidence without having to discover it from scratch.

This distinction between discovering and checking evidence is central to Lean and to its potential use with AI agents.

2.2 Context and inference rules

In a compiler, the meaning and type of an expression depend on its surrounding declarations. Type theory makes that context explicit:

(2)

Here is the context, is a term, is its type, and means that the judgement can be derived under that context.

For example, if the context contains x : Nat and y : Nat, we can establish that x + y : Nat. Lean offers a simple way to inspect such information:

#check (42 : Nat)
#check true
#check Nat
#check (fun (x : Nat) => x + 1)

The following inference rule explains function application. The statements above the line are premises; the statement below is the conclusion.

(5)

This should feel familiar. If a function takes an A and returns a B, and the argument has type A, then the application has type B. We are just stating the rule that makes this valid explicitly.

Exercise: Given f : Nat → Bool and x : Nat, what is the type of f x? What information is missing if the only declaration is f : Nat → Bool?

2.3 Domain knowledge precedes types

A glossary identifies a concept and defines it. A taxonomy classifies concepts. An ontology expresses relationships and constraints between them. A behavioural specification explains how the relationships change. A native type system implements a selected projection of this knowledge; it is not the entirety of the domain model.

Consider a GIS system that displays surveyed terrain:

KnowledgeExampleNative representation or further obligation
GlossaryA projected position is a location in a named projected coordinate reference systemProjected_Point
TaxonomyA raster and a vector dataset are kinds of spatial datasetTagged alternatives where closed; shared operations where appropriate
OntologyEvery dataset has a CRS; a transformation has a source and destination CRSStructured fields, references, typed transforms
ConstraintA geographic latitude lies in [-90, 90] degreesChecked input, predicate
BehaviourReprojection changes coordinates and CRS togetherContract, numerical reference tests
EnvironmentProjection accuracy depends on datum, area of use and grid dataExplicit assumptions and validation

Not every taxonomic is-a relationship should become inheritance or subtyping. A taxonomy may allow overlapping classifications and an extensible vocabulary, while a tagged union is usually a closed set of mutually exclusive alternatives. OWL reasoning also uses open-world semantics: absence of a fact is not generally evidence that it is false. SHACL validation can impose explicit graph constraints; neither automatically proves executable behaviour. Use stable concept identifiers and a mapping rather than mechanically generating one class per ontology node.

Glossary: meanings Taxonomy: categories Ontology: relations and constraints Behaviour: events and state changes Native type projection Formal model and contracts Implementation Proofs about the model Conformance evidence Review gaps and assumptions

This is a feedback loop, not a waterfall. The ontology, formal model and code are related but need not have identical structures. The domain expert and engineer determine what the types mean; the compiler enforces its own typing rules; the theorem prover checks mathematical evidence. A valid proof does not establish that the domain definitions are adequate.

2.4 Nominal, structural and refinement typing

A nominal type is distinguished by its declared identity. A structural view compares the components of a type. Languages mix these approaches; do not label an entire language by a single feature. Odin distinct and C++ named structures are practical tools for introducing nominal distinctions. A refinement type describes values satisfying a predicate, for example . This is a different idea from nominal distinction or structure embedding.

A strong native type system is valuable because it rejects many unintended combinations, but “strong typing” is not a single precise mathematical property. Ask which implicit conversions are allowed, which operations may escape checking, whether memory lifetime is tracked, and whether constraints concern one value or a relationship with external state. In Odin and C++, explicit casts and low-level access are useful tools with explicit proof burdens, not reasons to abandon type modelling.

3. Functions and lambda calculus

Lambda calculus describes computation using functions, variables and function application. You do not need to start with its entire formal syntax. Begin with a C++ lambda:

auto twice = [](unsigned x) { return x * 2; };

The corresponding mathematical expression is . In Lean:

def twice : Nat → Nat := fun x => x * 2

#eval twice 21  -- 42

The arrow means a function from one type to another. fun x => ... constructs a function, and twice 21 applies it. Unlike the C++ example, the Lean function uses unbounded natural numbers.

In Odin, a procedure can also be represented as a value of a procedure type:

Twice :: proc(x: u32) -> u32 {
    return x * 2
}

apply :: proc(f: proc(u32) -> u32, x: u32) -> u32 {
    return f(x)
}

A procedure signature specifies an admissible call shape. It does not imply purity, termination, freedom from global mutation or absence of allocation. Odin's context and explicit allocator conventions make some effects easier to see, but they do not prove an effects discipline. C++ function pointers likewise do not carry a complete effect or behavioural specification. In Lean, the ordinary mathematical function used here is total; effects have to be represented separately. Do not equate unrestricted native procedures with total mathematical functions.

3.1 Abstraction, application and reduction

Function abstraction introduces a parameter. Application supplies an argument. Beta reduction is the mathematical substitution of the argument into the function body, taking care not to capture free variables.

(fun x => x * 2) 21
             ↓ substitute 21 for x
           21 * 2
             ↓ arithmetic
             42

Renaming a bound variable without changing its meaning is called alpha conversion. For instance, fun x => x and fun y => y denote the same identity function. Later, we will see how computational reduction contributes to checking equalities in Lean.

3.2 Currying and higher-order functions

A function can accept or return another function. In Lean, multiple arguments are naturally expressed using nested function types:

def add (x y : Nat) : Nat := x + y

#check add       -- Nat → Nat → Nat
#check add 10    -- Nat → Nat
#eval add 10 5   -- 15

Nat → Nat → Nat associates to the right: Nat → (Nat → Nat). Supplying the first argument creates a function that still expects another argument. This is called partial application.

A familiar C++ approximation is a closure that captures a value:

auto add = [](unsigned x) {
    return [x](unsigned y) { return x + y; };
};

We can also express composition generically:

def compose {A B C : Type} (f : B → C) (g : A → B) : A → C :=
  fun x => f (g x)
Value of type A g : A to B Value of type B f : B to C Value of type C

The braces around A B C mark implicit parameters, which Lean can usually infer. This is useful later because proofs of logical implications can also be composed.

4. Constructing types

4.1 Product types: both values

A product type combines values. The mathematical notation is . You already use this idea when defining structures and tuples.

struct Position { unsigned x; unsigned y; };
structure Position where
  x : Nat
  y : Nat

def origin : Position := ⟨0, 0⟩

#eval origin.x

The notation ⟨0, 0⟩ constructs a value of the expected structure type. Lean also provides the generic pair type Nat × Nat.

In Odin, a graphics vertex is naturally a product of domain types:

Position :: distinct [3]f32
Normal   :: distinct [3]f32
UV       :: distinct [2]f32

Vertex :: struct {
    position: Position,
    normal:   Normal,
    uv:       UV,
}

The product is . It enforces which kinds of values compose a vertex, but not that the normal is normalised or that UV coordinates are inside a particular atlas region. The normal's numerical invariant must be specified separately. Native floating-point values also include exceptional values, and an exact real-number model is not a faithful model of all floating-point computations.

In a renderer, the logical vertex and its physical storage need not coincide. A structure-of-arrays layout may be preferable for SIMD or cache locality. Odin's #soa data layouts and C++ arrays of individual fields can preserve semantic distinctions without requiring an object-oriented layout. A mapping between the logical product and the concrete arrays must establish that their lengths and indexing agree. The abstraction is a vertex; the storage policy is a separate concern.

4.2 Sum types: one alternative

A sum type represents one of several tagged alternatives. In C++:

#include <variant>
struct Closed {};
struct Open { unsigned handle; };
using Resource = std::variant<Closed, Open>;

In Lean:

inductive Resource where
  | closed : Resource
  | opened : Nat → Resource

def handleOrZero : Resource → Nat
  | .closed => 0
  | .opened h => h

The constructors make the alternatives explicit. A closed resource in this model does not carry an open handle. This does not prove that the external operating-system handle is valid, only that the model has the intended shape.

Product: A AND B Sum: A OR B Pair A B Tagged choice Alternative A Alternative B

For finite types, cardinalities follow useful algebraic rules. If A has three inhabitants and B has two, the product has six, the sum has five, and the total function type A → B has eight extensionally distinct functions (). This can help estimate the state space of a finite model.

In Odin we can model alternatives directly with a tagged union. For a renderer's light classification:

Directional_Light :: struct {
    direction: [3]f32,
    intensity: f32,
}
Point_Light :: struct {
    position: [3]f32,
    intensity: f32,
    radius: f32,
}
Light :: union #no_nil { Directional_Light, Point_Light }

intensity :: proc(light: Light) -> f32 {
    switch l in light {
    case Directional_Light: return l.intensity
    case Point_Light:       return l.intensity
    }
    unreachable()
}

The tag determines which payload may be accessed. #no_nil excludes the otherwise available nil alternative; zero-initialisation selects the first variant, which still may not satisfy domain invariants. A directional light with a zero direction is not physically meaningful. The default must be treated deliberately, for example by adding an explicit Uninitialised variant or validating construction. Exhaustive switches help expose new cases during compilation; avoid #partial or catch-all branches unless incomplete handling is intentional and documented.

For a security-oriented parser, use a tagged result such as Parsed_Message | Parse_Error rather than a structure containing a success flag, an error code and a message that may not be valid. Odin's Maybe(T) can express optional presence, while a tagged error type can explain failure. C++20 has std::optional and std::variant; std::expected is C++23. An alternative is an algebraic sum, not a raw overlapping-memory union. #raw_union has a different purpose, notably ABI interoperability, and provides no comparable discriminant guarantee.

4.3 Inductive types: building recursive structures

A list or tree has a recursive structure. We describe that structure through constructors:

inductive Expr where
  | literal : Nat → Expr
  | add : Expr → Expr → Expr

def evaluate : Expr → Nat
  | .literal n => n
  | .add a b => evaluate a + evaluate b

#eval evaluate (.add (.literal 10) (.literal 20))

Here we have specified a tiny expression language and its evaluation semantics. Lean checks that the pattern matching is exhaustive and that this recursive definition is structurally terminating.

Inductive types matter because they give us not only a way to construct data, but also a systematic way to reason about all data built using those constructors. This is the basis of structural induction in chapter 10.

4.4 Avoiding invalid combinations

As an exercise, consider a resource represented by bool isOpen and optional<Handle> handle. That representation allows inconsistent combinations. A tagged union eliminates some of those combinations by construction. This is often a better starting point than expressing all the invalid combinations as separate tests.

However, not every invariant can or should be encoded solely as an algebraic data type. Cross-object relationships, external resources and history-dependent properties often require additional predicates and transition models.

4.5 Finite sets, total tables and relations

A graphics buffer can support several usages simultaneously. A single enum would represent one choice; a bit set represents a subset of a finite universe.

Usage :: enum { Vertex, Index, Storage, Transfer_Dst }
Usage_Set :: bit_set[Usage]

supports :: proc(available, required: Usage_Set) -> bool {
    return required <= available
}

In set notation, this is . The representation is a bit vector, but the operation reads as a domain relation. The compiler knows the set's element type, not whether the hardware supports a particular combination.

Enumerated arrays express finite mappings in Odin:

Resource_State :: enum { Empty, Ready, Busy, Released }
State_Name :: [Resource_State]string {
    .Empty = "Empty", .Ready = "Ready",
    .Busy = "Busy", .Released = "Released",
}

For a contiguous enumeration and its named inhabitants, this is a finite function from state to string. A two-dimensional enumerated array can represent an allowed-transition relation. Complete initialisation helps expose missing entries when the enumeration changes; #partial deliberately relaxes that check. Explicit casts or raw memory can introduce invalid enum representations, so validate untrusted values before indexing. A table expresses a relation, not evidence that every state-changing procedure uses it.

Exercise: Model a network endpoint's capabilities as a set, and protocol responses as a sum. Explain why these are different constructions.

4.6 Embedding and subtyping are not the same as refinement

Odin supports embedding with using and the #subtype field directive. For example:

Resource_Info :: struct { byte_size: u64 }
Texture_Info :: struct {
    #subtype resource: Resource_Info,
    width, height: u32,
}

size_in_bytes :: proc(info: Resource_Info) -> u64 {
    return info.byte_size
}

The embedded resource information may be used where its base type is expected under Odin's subtype rules. using also promotes fields. C++ public inheritance offers another form of substitutability, while composition is often simpler. None establishes that an override or operation satisfies the original contract (behavioural substitutability), nor is it the same as Lean's predicate subtype. Prefer explicit composition when the relationship is merely has-a. An ontology class hierarchy is not a mandate to construct a corresponding memory-layout hierarchy.

5. Generics, polymorphism and universes

You are already familiar with generic programming:

template<typename T>
T identity(T x) { return x; }

Lean has a similar-looking definition:

def identity (A : Type) (x : A) : A := x

#eval identity Nat 42
#eval identity Bool true

A is a type parameter. This is a useful bridge to polymorphic type theory, although C++ templates and Lean polymorphism differ substantially in their implementation and expressiveness. C++ templates can perform specialization, inspect types and generate distinct implementations; do not treat them as equivalent to System F.

Types themselves have types in Lean:

#check Nat       -- Nat : Type
#check Type      -- Type : Type 1
#check Type 1    -- Type 1 : Type 2
#check Prop      -- Prop : Type

Type (also called Type 0) is the lowest ordinary data universe. Higher universes allow types to be classified without assuming that a universe contains itself. Prop is a distinguished universe for logical propositions. In Lean notation Prop = Sort 0 and Type u = Sort (u + 1).

Type 2
  contains Type 1
    contains Type
      contains Nat, Bool, String, and Prop
Prop
  contains propositions such as 2 + 2 = 4

This is enough universe theory for our present purposes. Universe polymorphism, impredicativity and the lambda cube can be investigated later.


5.1 Phantom types and meaningful relationships

One of the most valuable uses of type parameters is to express a relationship that has no separate runtime payload. In graphics, a point is meaningful only in a coordinate space. A transformation has a source and a destination. Mixing them often produces a plausible-looking matrix multiplication with incorrect behaviour.

#include <array>
struct ObjectSpace {};
struct WorldSpace {};
struct ViewSpace {};
template<class Space> struct Point3 { std::array<float, 3> value; };
template<class From, class To> struct AffineTransform {
    std::array<float, 16> value;
};
template<class From, class To>
Point3<To> transform_point(AffineTransform<From, To>, Point3<From>);
Object_Space :: struct {}
World_Space  :: struct {}
View_Space   :: struct {}

Point3 :: struct($Space: typeid) {
    value: [3]f32,
}
Affine_Transform :: struct($From: typeid, $To: typeid) {
    value: matrix[4, 4]f32,
}

transform_point :: proc(
    m: Affine_Transform($From, $To),
    p: Point3(From),
) -> Point3(To) {
    v := m.value * [4]f32{p.value.x, p.value.y, p.value.z, 1}
    return Point3(To){value = v.xyz}
}
example :: proc() {
    object: Point3(Object_Space)
    model: Affine_Transform(Object_Space, World_Space)
    view: Affine_Transform(World_Space, View_Space)
    world := transform_point(model, object)
    camera := transform_point(view, world)
    // transform_point(view, object) // intended compilation error
    _ = camera
}

The parameters are phantom markers: they distinguish the types without an explicit field storing the space. The native operation expresses . This reduces the context a caller must retrieve. It does not prove that the matrix is affine, invertible, finite, constructed for the named spaces, or numerically accurate. The zero matrix is still representable. Treat this snippet as a representation and signature demonstration, not a valid rendering setup. Perspective projection requires a separate homogeneous-coordinate model and a checked perspective divide. A normal transformation generally requires the inverse transpose of the linear transform, not the same operation as a position.

Point Object Point World Point View Homogeneous clip point Normalised device point Model: Object to World View: World to View Projection Checked divide by w

A similar pattern works for measurements (metres versus feet), cryptographic protocol roles (client versus server), database handles (read versus write authority) or medical-image coordinate frames. Static markers work when the identity is known at compile time. If coordinate reference systems are selected from arbitrary GIS metadata at runtime, store and check the actual CRS identifiers; do not generate a compile-time type for every possible external dataset.

5.2 Generic constraints and proof obligations

In Odin a polymorphic record can constrain its compile-time arguments with where:

Vector :: struct($N: int, $T: typeid) where N > 0 {
    data: [N]T,
}

Vector(3, f32) and Vector(4, f32) have different dimensions. A C++ equivalent is a constrained template (requires (N > 0)). A constraint on a template argument is not a universal proof about a procedure body. In particular, declaring a numeric type does not establish that an operation is associative for floating-point values, that it cannot overflow, or that a generic algorithm terminates. These are separate mathematical obligations.

6. Propositions as types

6.1 From values to evidence

This is the most important conceptual transition in the tutorial. Compare the following judgements:

#check (42 : Nat)
#check (2 + 2 = 4)

The first expression is data. The second is a proposition, of type Prop. A proposition is a statement that may be established by a proof; it is not simply a runtime Boolean value.

def flag : Bool := true

def claim : Prop := 2 + 2 = 4

theorem evidence : claim := by rfl

evidence is a term whose type is claim. A proof is a term inhabiting a proposition. This is the central idea of the Curry–Howard correspondence: logical proofs can be represented using the same general machinery used to type-check terms.

6.2 Implication as a function

Recall the identity function. Now consider the proposition “P implies P”.

theorem identityProof (P : Prop) : P → P :=
  fun h => h

The function receives evidence h of P and returns evidence of P. There is no need to decide whether P is true in the absence of an assumption; the theorem is conditional.

Computation Logical implication Value of type A Function Value of type B Evidence of P Proof function Evidence of Q

This is why the arrow → serves both as function type and logical implication.

6.3 The logical connectives

LogicMathematical notationLeanHow to construct evidence
ImplicationP → QTransform evidence of P into evidence of Q
ConjunctionP ∧ QSupply both proofs
DisjunctionP ∨ QSupply a proof of either side, with a tag
TruthTrueSupply True.intro
FalsehoodFalseNo constructor in a consistent environment
Negation¬ PTransform evidence of P into falsehood
Universal quantification∀ x, P xProvide evidence for an arbitrary x
Existential quantification∃ x, P xProvide a witness and evidence

These logical constructions are closely related to functions, products and sums. They live in Prop, however, not in the ordinary computational types Prod and Sum. Lean restricts elimination from propositions into data in important cases and treats proofs of the same proposition as definitionally equal (proof irrelevance).

theorem both (P Q : Prop) (hp : P) (hq : Q) : P ∧ Q :=
  ⟨hp, hq⟩

theorem first (P Q : Prop) (h : P ∧ Q) : P := h.left

theorem either (P Q : Prop) (hp : P) : P ∨ Q :=
  Or.inl hp

Think of the first proof as constructing a pair of evidence, the second as projecting from it, and the third as constructing one of two tagged alternatives.

6.4 Quantifiers are contracts over domains

A universal statement describes every value in a domain, not merely a list of test cases:

theorem add_zero_all : ∀ n : Nat, n + 0 = n :=
  fun n => rfl

An existential statement supplies a witness:

theorem witness : ∃ n : Nat, n + 2 = 5 :=
  ⟨3, rfl⟩

Quantifier order can substantially change the meaning of a requirement. “Every resource request has some valid allocation” () is not the same as “One allocation works for every resource request” (). As a requirements author, make the order explicit.

7. Reading and writing proofs

7.1 Proof terms and tactics

Lean accepts proof terms directly or lets you construct them using tactics. Compare:

theorem identityTerm (P : Prop) : P → P :=
  fun h => h

theorem identityTactic (P : Prop) : P → P := by
  intro h
  exact h

After intro h, the proof state has an assumption h : P and a goal ⊢ P. exact h supplies the needed evidence. Both versions ultimately produce a proof term checked by Lean's kernel.

For a slightly more interesting example, compose two implications:

theorem chain (P Q R : Prop)
    (pq : P → Q) (qr : Q → R) : P → R := by
  intro hp
  have hq : Q := pq hp
  exact qr hq

This is exactly the pattern of function composition from chapter 3. The intermediate proof hq is no more mysterious than an intermediate value in a computation.

7.2 A small tactic vocabulary

TacticRead it as
introIntroduce an argument or hypothesis
exactHere is the evidence for the goal
applyUse a theorem whose conclusion matches the goal; establish its premises
constructorBuild the goal using a suitable constructor
casesConsider the possible constructors of a value or proof
rflThe equality follows by definitional equality
rw [h]Rewrite using equality h
simpSimplify using known rewriting rules
inductionProve a property using the structure of an inductive type
decideCompute a proof of a suitable decidable proposition
omegaAutomate supported linear arithmetic over natural numbers and integers

Start with the first seven. Automation is useful, but understanding what a proof requires is more important than memorising tactics. import Lean at the start of a file gives access to the core tactics used throughout this tutorial.

7.3 Finding evidence versus checking it

Formal proposition Human or agent searches for a proof Candidate proof term Lean kernel checks the term Type checks? Accepted theorem under its dependencies Yes No

A proof search may fail even when a proposition is true. That is different from finding a contradiction or demonstrating that the proposition is false. Do not equate failure of an automated tactic with falsity. Conversely, an accepted proof establishes the formal proposition, not the correctness of whatever informal requirement you hoped it would represent.

8. Dependent types

8.1 You have already seen a restricted version in C++ and Odin

#include <array>
#include <cstddef>

template<std::size_t N>
struct Buffer {
    std::array<std::byte, N> data;
};

Buffer<16> and Buffer<32> are different types. A value (N) influences the type. This is a useful analogy for dependent typing, although C++ non-type template arguments have compile-time restrictions and are not general dependent types.

In Lean, a type can be parameterised by an ordinary value. For example:

def BufferIndex (n : Nat) : Type :=
  { i : Nat // i < n }

def index : BufferIndex 256 :=
  ⟨42, by decide⟩

#eval index.val
#check index.property

BufferIndex n is a subtype: a natural number i accompanied by evidence of i < n. Lean's standard Fin n is a closely related built-in type of bounded natural numbers.

BufferIndex 256
┌────────────────────┬─────────────────────────┐
│ value : Nat        │ property : value < 256  │
│ 42                 │ proof of 42 < 256       │
└────────────────────┴─────────────────────────┘

Try constructing ⟨256, by decide⟩ : BufferIndex 256. The required proposition is false, and decide cannot prove it.

Odin also supports value-parameterised types:

Fixed_Buffer :: struct($N: int) where N > 0 {
    data: [N]u8,
}

Fixed_Buffer(16) and Fixed_Buffer(32) are different types. As with C++ templates, N is a compile-time parameter. A capacity read from a network packet cannot directly become a new native type instantiation during execution. Instead use a slice or runtime capacity with a checked contract. Lean can form Fin n from an ordinary value n and carry evidence across functions. This is a stronger relationship than compile-time specialisation alone.

Compare the options for a byte offset:

RepresentationGuarantee
u32 / std::uint32_tMachine range, no domain meaning
Odin distinct u32 / C++ named wrapperNominal identity, not bounds
Fixed_Buffer(256)Compile-time capacity, not validity of every supplied index
Checked offset plus runtime owner or capacityValidity under the checked conditions, subject to mutation/lifetime
Lean Fin nEvidence of i < n for the specified mathematical bound

If a buffer shrinks after an index was checked, a previously valid index can become invalid. Even a Lean proof that i < oldCapacity is not a proof that i < newCapacity. Model which state or resource a validation is tied to.

8.2 Pi types: the result type depends on the argument

The ordinary function type A → B has an output type that does not vary with its argument. A dependent function type can be written (x : A) → B x, or mathematically . It is often called a Pi type.

def zeroIndex (n : Nat) : Fin (n + 1) :=
  ⟨0, Nat.zero_lt_succ n⟩

The type of the result depends on n. This is not a family of C++ template instantiations that require n to be a compile-time constant; the argument can be an ordinary runtime natural number in compiled Lean. The accompanying proof can be erased during compilation.

Universal quantification is the proposition-valued case of dependent function types. A proof of ∀ n : Nat, P n provides a proof of P n for any supplied n.

8.3 Sigma types: a value and something depending on it

A dependent pair (Sigma type) stores an index and a value whose type depends on that index.

inductive Vec (A : Type) : Nat → Type where
  | nil : Vec A 0
  | cons {n : Nat} : A → Vec A n → Vec A (n + 1)

def one : Vec Nat 1 := .cons 42 .nil

def vecHead {A : Type} {n : Nat} : Vec A (n + 1) → A
  | .cons x _ => x

def PackedVector : Type := Σ n : Nat, Vec Nat n

def packed : PackedVector := ⟨1, one⟩

vecHead needs no empty case because its input type excludes empty vectors. PackedVector packages an arbitrary length and a vector of that exact length. A subtype such as BufferIndex is a related construction in which the dependent component is a proposition. Existential quantification is also closely related, but a proof of an existential proposition cannot in general be used to extract arbitrary computational data in Lean.

8.4 The boundary remains important

Suppose an index comes from a network packet. We cannot simply declare it a Fin n. We must validate it first:

def checkIndex (n i : Nat) : Option (Fin n) :=
  if h : i < n then
    some ⟨i, h⟩
  else
    none
Untrusted Nat Index less than capacity? Fin n None Operation requiring valid index Yes, with evidence No

The runtime check establishes a local hypothesis h that can be used to construct the constrained value. Type theory does not remove boundary validation. It allows us to carry the knowledge obtained from validation forward into other operations.

Engineering lesson: Use dependent types where relationships are local, stable and valuable. For a large stateful system, a conventional state representation with explicit invariant predicates may be easier to work with. Both are legitimate modelling strategies.

9. Equality and computation

Equality is more subtle than it initially appears. C++ == may invoke an overloaded operator, compare addresses, or compare numerical values. In Lean, mathematical equality is a proposition relating two terms of the same type. We also distinguish this proposition from the underlying type checker's notion of definitional equality.

9.1 Definitional equality

Two expressions are definitionally equal when the type checker's conversion rules recognise them as equivalent. Computation is an important part of those rules.

example : (2 : Nat) + 3 = 5 := by rfl

example (n : Nat) : n + 0 = n := by rfl

Lean defines natural-number addition by recursion on its second argument. Consequently n + 0 reduces to n even if we do not know the value of n.

ReductionIntuition
Beta ()Apply a function by substituting its argument
Delta ()Unfold a permitted definition
Iota ()Reduce a recursor on a constructor
Zeta ()Substitute a local let definition

These are useful names when reading type theory literature. They are not four proof tactics you need to memorise. Lean also has additional conversion rules, including proof irrelevance.

9.2 Propositional equality

The equation 0 + n = n is true, but the left-hand side cannot simply reduce when n is an unknown variable. We need evidence of equality:

example (n : Nat) : 0 + n = n := by
  exact Nat.zero_add n

The library supplies a theorem that establishes the result. We can also construct the proof ourselves using induction in the next chapter.

Rewriting allows evidence of equality to be used in a larger expression:

example (a b : Nat) (h : a = b) : a + 1 = b + 1 := by
  rw [h]

Equality is therefore not merely an operation that returns a Boolean. It provides evidence that can be used to reason about other propositions and expressions.

9.3 Extensional equality and representations

Two functions can be defined differently and nevertheless produce equal results for all inputs. For example:

example : (fun n : Nat => n + 0) = (fun n : Nat => 0 + n) := by
  funext n
  rw [Nat.add_zero, Nat.zero_add]

funext reduces the goal of function equality to pointwise equality. Lean's standard proof of function extensionality depends on its quotient machinery. This is relevant when auditing the foundational dependencies of a theorem, but is not something to worry about in ordinary proofs at this stage.

For systems engineers, the useful lesson is that equivalence of behaviour need not imply equivalence of representations, memory use, execution time or side effects. Specify which kind of equivalence is required.

9.4 Machine arithmetic is part of the type's semantics

A memory allocator aligns sizes to 16 bytes. The idiom below rounds up with a mask, but only if addition does not overflow.

@(require_results)
align16 :: proc(n: u32) -> (u32, bool) {
    if n > 0xfffffff0 { return 0, false }
    return (n + 15) & ~u32(15), true
}
#include <cstdint>
#include <optional>
constexpr std::optional<std::uint32_t> align16(std::uint32_t n) {
    if (n > 0xfffffff0u) return std::nullopt;
    return (n + 15u) & ~std::uint32_t{15};
}
static_assert(align16(17).value() == 32);
static_assert(!align16(0xffffffffu));

This is a size alignment operation, not a proof of an allocation address's alignment. State the mathematical obligations: the result is a multiple of 16, it is at least the input, the difference is less than 16, and the computation cannot overflow in the success case. Failure is explicit. Lean's BitVec 32 and bitvector decision procedures can express machine-width reasoning directly (see Lean bitvectors); an unbounded Nat proof needs a separate representability argument. The same discipline applies to floating point: a theorem about real-number associativity does not justify reordering native floating-point operations without a numerical error model.

10. Induction and recursive structures

Imagine proving that an invariant holds after any number of operations. Running a million operations can establish useful empirical evidence, but it does not demonstrate the property for every possible finite sequence. Induction is one way of establishing such a general result mathematically.

10.1 Induction over natural numbers

The natural numbers have two constructors, zero and successor. To prove a property P n for every natural number, establish the base case P 0 and show how evidence of P n yields evidence of P (n + 1).

P 0: base case P 1 P 2 P 3 Continue for every natural number

The arrows are justified by the same general inductive step, not by checking each number individually.

theorem zeroAddByInduction (n : Nat) : 0 + n = n := by
  induction n with
  | zero => rfl
  | succ n ih =>
      change Nat.succ (0 + n) = Nat.succ n
      rw [ih]

Read ih as the induction hypothesis: we have evidence that the proposition holds for n. The change command restates the goal using a definitionally equal expression. Rewriting with the induction hypothesis completes the successor case.

10.2 Structural induction over lists

A list is either empty or a head element followed by another list. Those are its constructors, so they also determine the cases for a structural proof.

def count {A : Type} : List A → Nat
  | [] => 0
  | _ :: xs => 1 + count xs

theorem countAppend {A : Type} (xs ys : List A) :
    count (xs ++ ys) = count xs + count ys := by
  induction xs with
  | nil => simp [count]
  | cons x xs ih => simp [count, ih, Nat.add_assoc]

This theorem covers lists of arbitrary length. In the non-empty case, the induction hypothesis already gives the required property for the tail. Associativity of natural-number addition lets us finish the proof.

10.3 Termination is part of the picture

Lean's ordinary logical definitions must satisfy its termination requirements. Without appropriate restrictions, unrestricted recursion could be used to construct bogus evidence. Structural recursion is one way to satisfy those requirements; well-founded recursion is another. Lean also has facilities for partial and unsafe computations, whose logical use is restricted.

A native application may deliberately run indefinitely, such as a browser event loop. We can model each transition or each finite prefix of an execution without asserting that the entire application terminates. A proof about finite prefixes is a safety result; it is not automatically a liveness result such as eventual delivery or progress.


11. Contracts and formal specifications

11.1 Preconditions and postconditions

C++ developers routinely use contracts, even if they are only documented in a comment or checked using assertions.

// Precondition: n > 0
// Postcondition: result + 1 == n
unsigned decrement(unsigned n) {
    assert(n > 0);
    return n - 1;
}

This snippet assumes <cassert> is included. Assertions can be disabled, and the unsigned arithmetic has a fixed machine range. In Lean we can express the intended mathematical property explicitly:

import Lean

def decrement (n : Nat) : Nat := n - 1

theorem decrementCorrect (n : Nat) (h : n > 0) :
    decrement n + 1 = n := by
  unfold decrement
  omega

The theorem says that if we are supplied with an input and evidence of the precondition, we can establish the postcondition. It does not claim the precondition is always true. Lean natural-number subtraction saturates at zero; unsigned C++ subtraction wraps modulo the range of the type. The proof says nothing about that discrepancy unless we model it.

11.2 Hoare logic

A traditional notation for a program contract is the Hoare triple:

(6)

P describes the precondition, C is a computation and Q describes the postcondition. Partial correctness means that if P holds and C terminates, Q holds afterwards. Total correctness additionally requires termination. To apply this approach to imperative code, we need appropriate semantics for the computation, including its state and effects.

Initial state Precondition P Execute operation C Postcondition Q on resulting state Outside contract or explicit failure path Holds Does not hold

For a total pure Lean function, the contract can be expressed directly as a theorem about the function. Lean is not automatically a Hoare logic verifier for arbitrary C++ source code; that requires an additional semantics and verification strategy.

11.3 Invariants

An invariant is a property that must hold at the relevant points in an execution. For example, a buffer has a current length and a capacity. The intended relationship is length ≤ capacity.

If we prove that the initial state satisfies the invariant, and that each permitted transition preserves it, induction establishes that it holds for every finite reachable execution. This is a powerful engineering pattern because the work is decomposed into local proof obligations.

11.4 Typestate and ownership: where signatures stop

A GPU resource may move from allocated to submitted to completed and back to allocated. Destruction is permitted only when there is no outstanding use. A type-state interface represents a subset of that protocol in the types of its operations.

Allocated :: struct { handle: u64 }
Submitted :: struct { handle: u64, fence: u64 }

// Interface sketch: real implementation performs GPU operations.
submit :: proc(r: Allocated) -> Submitted {
    return {handle = r.handle, fence = 1}
}
release :: proc(r: Allocated) {
    // Destruction omitted.
    _ = r
}

release(submitted) is a type error, but release(originalAllocated) may still compile after submit(originalAllocated) because the original value or aliases remain available. Neither Odin nor ordinary C++ move-only types provide a general proof of linear consumption. C++ RAII and move-only owners can reduce ownership errors but moved-from values and aliases still require appropriate rules. Odin can centralise resource state in a package-owned table, validate generation and outstanding fences, and expose operations rather than writable state.

Allocated Submitted Released allocate submit completion observed release

This is a simplified single-submission model. A production GPU system may have multiple queues, resource dependencies, in-flight references and device loss. The real safety invariant is that no release occurs while there is outstanding use. It must relate the resource table, actual submissions and completion evidence. Proof of the simplified graph cannot establish safety of the actual driver calls.

In Lean, define a relation between states, then prove safety for reachable states using induction. Merely omitting a forbidden constructor proves something about the declared transition relation, not about the native resource manager. A refinement or conformance obligation links the two. The capstone develops that method with a simpler buffer before you apply it to GPU resource lifetimes.

12. Capstone: a verified buffer state machine

We will use a bounded buffer as a running example. This is deliberately smaller than an allocator or an entire container library: it is large enough to expose important modelling decisions but small enough to understand every proof.

12.1 Domain and intent

TermDefinition
CapacityMaximum number of elements the buffer may hold
LengthNumber of currently occupied elements
PushAdd one element if the buffer is not full
PopRemove one element if the buffer is not empty
ClearRemove all elements
AcceptedThe requested operation took effect according to its contract
RejectedThe requested operation was not permitted and leaves state unchanged

We assume capacity does not change during these operations. We model only occupancy, not the contents of the buffer. A zero-capacity buffer is allowed. Push and pop return a status even when they fail. These are explicit modelling decisions, not consequences of type theory.

12.2 Model the abstract behaviour

State: capacity and length Requested operation Length less than capacity? Increase length by one; accepted Unchanged; rejected Length greater than zero? Decrease length by one; accepted Set length to zero; accepted Check invariant and operation contract Push Yes No Pop Yes No Clear

We distinguish a valid state from a transition that behaves correctly. For example, a push that clears the entire buffer may preserve length ≤ capacity, but it violates the push contract. Both kinds of property need to be specified.

12.3 Complete Lean model

Copy the following block into a new .lean file. It is intentionally self-contained and uses only the core Lean import. The ordinary state representation makes it possible to reason about invalid initial states as well as valid ones. An alternative design would use a subtype with an embedded invariant.

import Lean

namespace BufferModel

structure State where
  capacity : Nat
  length : Nat
  deriving Repr, DecidableEq

inductive Event where
  | push
  | pop
  | clear
  deriving Repr, DecidableEq

structure Outcome where
  accepted : Bool
  state : State
  deriving Repr, DecidableEq

def Valid (s : State) : Prop :=
  s.length ≤ s.capacity

def initial (capacity : Nat) : State :=
  ⟨capacity, 0⟩

def step (s : State) (e : Event) : Outcome :=
  match e with
  | .push =>
      if s.length < s.capacity then
        ⟨true, { s with length := s.length + 1 }⟩
      else
        ⟨false, s⟩
  | .pop =>
      if 0 < s.length then
        ⟨true, { s with length := s.length - 1 }⟩
      else
        ⟨false, s⟩
  | .clear =>
      ⟨true, { s with length := 0 }⟩

-- The initial state is valid.
theorem initial_valid (capacity : Nat) :
    Valid (initial capacity) := by
  simp [Valid, initial]

-- Each operation preserves validity, provided it held before.
theorem step_preserves (s : State) (e : Event)
    (h : Valid s) : Valid (step s e).state := by
  cases e with
  | push =>
      by_cases hp : s.length < s.capacity
      · simp [Valid, step, hp] at * <;> omega
      · simpa [step, hp] using h
  | pop =>
      by_cases hp : 0 < s.length
      · simp [Valid, step, hp] at * <;> omega
      · simpa [step, hp] using h
  | clear =>
      simp [Valid, step]

-- Capacity is never modified.
theorem capacity_preserved (s : State) (e : Event) :
    (step s e).state.capacity = s.capacity := by
  cases e with
  | push =>
      by_cases h : s.length < s.capacity <;> simp [step, h]
  | pop =>
      by_cases h : 0 < s.length <;> simp [step, h]
  | clear => rfl

-- A successful push changes length by exactly one.
theorem push_success (s : State) (h : s.length < s.capacity) :
    (step s .push).accepted = true ∧
    (step s .push).state.length = s.length + 1 := by
  simp [step, h]

-- A push with no space is rejected and leaves state unchanged.
theorem push_rejected (s : State) (h : ¬ s.length < s.capacity) :
    step s .push = ⟨false, s⟩ := by
  simp [step, h]

-- A non-empty pop succeeds and removes exactly one element.
theorem pop_success (s : State) (h : 0 < s.length) :
    (step s .pop).accepted = true ∧
    (step s .pop).state.length = s.length - 1 := by
  simp [step, h]

-- An empty pop is rejected and leaves state unchanged.
theorem pop_rejected (s : State) (h : ¬ 0 < s.length) :
    step s .pop = ⟨false, s⟩ := by
  simp [step, h]

-- Clear succeeds and sets length to zero.
theorem clear_correct (s : State) :
    (step s .clear).accepted = true ∧
    (step s .clear).state.length = 0 := by
  simp [step]

-- Execute a finite sequence of operations.
def run (s : State) : List Event → State
  | [] => s
  | e :: es => run (step s e).state es

-- Validity holds after any finite sequence of events.
theorem run_preserves (s : State) (es : List Event)
    (h : Valid s) : Valid (run s es) := by
  induction es generalizing s with
  | nil => exact h
  | cons e es ih =>
      exact ih (step s e).state (step_preserves s e h)

-- Reachable states starting from an empty buffer are valid.
theorem reachable_valid (capacity : Nat) (es : List Event) :
    Valid (run (initial capacity) es) := by
  exact run_preserves _ _ (initial_valid capacity)

#eval step (initial 2) .push
#eval run (initial 2) [.push, .push, .push, .pop]
-- The last expression has capacity 2 and length 1.

#print axioms reachable_valid

end BufferModel

12.4 Understand the proof, not just the code

The first obligation, initial_valid, follows because zero is less than or equal to every natural number. The second, step_preserves, is broken into cases by the Event constructors. Each branch is further split according to its guard. If push succeeds, we know that length was strictly less than capacity, and therefore increasing it by one cannot exceed capacity. If it fails, the state is unchanged. Similar reasoning applies to pop and clear.

The final theorem uses induction on the list of events. For the empty list, the state is unchanged. For a non-empty list, step_preserves establishes validity after the first event, and the induction hypothesis establishes it for the remaining events. We generalise s because the state at the beginning of the remaining list differs from the original state.

Initial state valid S0 valid S1 valid S2 valid SN valid Event 1 Event 2 Any further finite sequence

By applying the theorem to any finite prefix, we obtain validity at every observed step in that finite history. We have not proved that a particular operation eventually succeeds or that the system makes progress under arbitrary scheduling.

12.5 Test the strength of the specification

Replace the successful push branch with a branch that returns ⟨true, { s with length := 0 }⟩. The invariant may still hold, and capacity is unchanged. However, the push_success theorem should no longer be provable: its statement requires the length to increase by exactly one.

This is a simple form of specification mutation testing. Deliberately introduce a behaviour that should be forbidden and check whether your formal requirements reject it. A useful collection of invariants is not necessarily a complete behavioural specification.

12.6 What we have and have not modelled

PropertyStatus in this model
Initial validityExplicit theorem
Validity after any finite sequence of model eventsExplicit theorem
Capacity remains constant per operationExplicit theorem
Accepted push and pop update occupancy correctlyExplicit theorems
Rejected push and pop preserve stateExplicit theorems
Clear resets occupancyExplicit theorem
Values are stored and retrieved in the correct orderNot modelled
Allocations and deallocations are memory-safeNot modelled
Fixed-width arithmetic and representationNot modelled
Concurrent access and atomicityNot modelled
Timing, space usage and real-time guaranteesNot modelled
Native implementation conforms to the modelNot established by these theorems

To extend this example, model the contents as a list, add the element to the push event, return an element from pop, and establish the relationship between occupancy and list length. You must also specify whether the buffer has stack, queue or ring-buffer semantics. That decision was deliberately omitted in the occupancy-only model.

13. From a Lean model to C++ and Odin implementations

13.1 Keep the abstraction boundary explicit

It is easy to prove a model correct and inadvertently imply that the programme implementing it is correct. The two are separate artefacts. A useful relationship between them is an abstraction function, conventionally written , mapping concrete states to abstract states.

For an abstract transition step and a concrete transition execute, an example refinement obligation is:

(7)

This simplified equation assumes the same event representation and a deterministic one-step transition, and compares abstracted outcomes. Real systems may require relations instead of functions, mappings of events, multiple concrete steps per abstract step, environmental assumptions or explicit nondeterminism.

Concrete state before Concrete state after Abstract state before Abstract state after Expected abstract state after Equivalent outcomes? Native operation Abstraction Abstraction Lean model transition

The diagram expresses the desired correspondence. An agreement check on a sampled execution is not a universal proof that the diagram commutes for every concrete state and event.

13.2 A matching native occupancy model

#include <cstddef>

enum class Event { Push, Pop, Clear };

struct State {
    std::size_t capacity;
    std::size_t length;
};

struct Outcome {
    bool accepted;
    State state;
};

constexpr bool valid(State s) noexcept {
    return s.length <= s.capacity;
}

constexpr Outcome step(State s, Event e) noexcept {
    switch (e) {
    case Event::Push:
        if (s.length < s.capacity) {
            ++s.length;
            return {true, s};
        }
        return {false, s};
    case Event::Pop:
        if (s.length > 0) {
            --s.length;
            return {true, s};
        }
        return {false, s};
    case Event::Clear:
        s.length = 0;
        return {true, s};
    }
    return {false, s}; // Outside the three-event abstract domain.
}

static_assert(step({2, 1}, Event::Push).state.length == 2);
static_assert(!step({2, 2}, Event::Push).accepted);
static_assert(valid(step({2, 2}, Event::Pop).state));
static_assert(step({2, 2}, Event::Clear).state.length == 0);

This is an occupancy model, not an actual buffer implementation. The increment is guarded by length < capacity, which also ensures that it cannot overflow std::size_t because capacity is representable. Pop is guarded against underflow. The model's natural numbers are unbounded, whereas concrete states are restricted to representable values. The abstraction maps those values into natural numbers. The fallback handles enum values outside the three defined events; a complete refinement contract must exclude or explicitly model them.

The static_assert statements are useful compile-time tests of specific examples. They do not prove the universally quantified Lean theorems for the C++ implementation.

13.2a The same occupancy model in Odin

The following is a standalone native counterpart to the C++ and Lean occupancy examples. Save it as main.odin in its own directory. The operation has an explicit input and output state, with no necessary GPU, allocation or I/O dependency. It is suitable for differential tests against the Lean reference model.

package main

Event :: enum { Push, Pop, Clear }
State :: struct {
    capacity: u64,
    length: u64,
}
Outcome :: struct {
    accepted: bool,
    state: State,
}

valid :: proc(s: State) -> bool {
    return s.length <= s.capacity
}

@(require_results)
step :: proc(s: State, e: Event) -> Outcome {
    next := s
    switch e {
    case .Push:
        if next.length < next.capacity {
            next.length += 1
            return {true, next}
        }
        return {false, next}
    case .Pop:
        if next.length > 0 {
            next.length -= 1
            return {true, next}
        }
        return {false, next}
    case .Clear:
        next.length = 0
        return {true, next}
    }
    unreachable()
}

main :: proc() {
    s := State{capacity = 2, length = 1}
    a := step(s, .Push)
    assert(a.accepted && a.state.length == 2)
    b := step(a.state, .Push)
    assert(!b.accepted && b.state.length == 2)
    c := step(b.state, .Pop)
    assert(c.accepted && valid(c.state))
    d := step(c.state, .Clear)
    assert(d.accepted && d.state.length == 0)
    z := step(State{}, .Push)
    assert(!z.accepted && valid(z.state))
}

Here the concrete numeric representation is u64, so the abstraction maps each machine value to a mathematical natural number. The guard on increment ensures representability, while the guard on decrement prevents underflow. The proof still assumes valid initial state and an event from the modelled enum. External event codes and malformed state must be validated before entering this core. The sample runtime assertions are tests; @(require_results) requires acknowledgement of results, not appropriate handling of rejection. The Odin compiler was unavailable for this revision, so run odin check . and odin run . locally before relying on this sample.

A genuine buffer requires further properties: memory validity, element lifetime, content preservation, aliasing and allocation failure. A pure occupancy model is deliberately smaller than that system. This is separation of concerns applied to verification: isolate the abstract state transition and test it independently; verify the storage adapter and its correspondence separately.

13.3 Trace-based validation

For an existing C++, C or Odin application, one practical approach is to instrument the relevant operations and record their inputs, pre-state, outcome and post-state. Use a typed, versioned schema rather than free-form log messages.

{
  "schema_version": 1,
  "sequence": 17,
  "operation": "push",
  "before": { "capacity": 4, "length": 3 },
  "after": { "capacity": 4, "length": 4 },
  "accepted": true
}

The replay harness checks that the initial state is valid, the sequence is ordered, the pre-state is consistent with the previous post-state, and the model predicts the reported status and post-state. An example decision procedure within the abstract model is:

-- Add after the capstone's namespace has been defined.
namespace BufferModel

def checkTransition (before : State) (event : Event)
    (observed : Outcome) : Bool :=
  decide (step before event = observed)

end BufferModel

A production checker needs an independently reviewed mapping of native events and states to these types. It should reject unknown schema versions and events rather than silently accepting them. Instrumentation must also be assessed for omissions and distortion of behaviour. For concurrent executions, a single total order of observations may not accurately capture causality or linearisation points.

13.4 A layered verification strategy

TechniqueWhat it establishes or detectsImportant limitation
Lean proofA general proposition about a formal modelDepends on specification and assumptions
Model-based tests / trace replayAgreement on observed or generated executionsIncomplete coverage and abstraction risks
Static analysisCertain classes of source-level errorsCoverage depends on analysis and configuration
Sanitizers / dynamic analysisCertain runtime errors on exercised pathsCannot establish universal absence of defects
Deductive native-code verificationSource-level properties under a specified language and memory modelRequires suitable tools and modelling effort
Performance and stress testingEmpirical timing, load and resource behaviourWorkload and environment dependent

For deeper native-code verification, investigate Frama-C for C, CBMC for bounded C/C++ model checking, and Alive2 for LLVM IR transformation validation. These address distinct layers and have different limits; none is a universal bridge between arbitrary C++ and Lean.

14. Using Lean in an agentic engineering harness

14.1 Separate intent from evidence

An agent can generate both an implementation and a proof. This is useful, but it creates a risk: if the same agent is allowed to modify the specification to make the proof pass, verification can become an exercise in proving a weaker proposition than the one the engineer intended.

A better workflow treats the formal specification as a reviewed artefact in its own right. The agent can propose changes, but a change to the meaning of a requirement should be distinguishable from a change to the implementation or proof.

Domain glossary, taxonomy and ontology Intent, assumptions and unknowns Reviewed formal specification Agent proposes implementation Agent constructs proof Lean checks proof dependencies and term Native tests, analysis and trace replay Review against original intent Acceptance criteria met? Merge with evidence Yes No: code or proof defect No: specification defect

The specification is not fixed forever. Requirements and domain knowledge change, and the formal model must evolve with them. The important distinction is that specification changes should be explicit, reviewed and traceable.

14.2 Assumptions are part of the model

CategoryExampleTreatment
Domain factBuffer length cannot exceed capacityFormal invariant
PreconditionInitial state is validExplicit theorem hypothesis
Environmental assumptionAllocation succeedsModel failure or state condition
Abstraction assumptionNative length maps to mathematical occupancyRefinement obligation
UnknownBehaviour with simultaneous writersOpen design question, not an invented axiom
Foundational principleClassical choice or quotient soundnessAudit and document dependencies as appropriate

Avoid turning an unresolved requirement into an axiom simply because a proof is difficult. An axiom asserts something without supplying a proof, and a false axiom can invalidate the reasoning of theorems that depend on it. Prefer explicit hypotheses when a conclusion is conditional.

For example, the following is deliberately dangerous and should not be added to a real verification environment:

-- Demonstration only; never use to satisfy a proof obligation.
axiom impossible : (1 : Nat) = 2

example : False := by
  cases impossible

Lean can accept the axiom as a declaration. It then permits a proof of False using that assumption. This demonstrates why accepting a theorem is not equivalent to establishing that its entire dependency environment is sound.

14.3 Proof auditing and acceptance gates

Use #print axioms to inspect the transitive axiom dependencies of important theorems. A project can permit known foundational axioms while rejecting unauthorised domain axioms and sorryAx, which can appear when proofs use sorry or admit. Review the actual axiom policy rather than assuming that all axioms are inappropriate.

A practical acceptance policy might require:

A theorem of the form P → Q is trivially provable if P is impossible. A proof audit therefore needs to ask not only whether the theorem is valid, but also whether its assumptions can hold in the system we are trying to build.

14.4 The engineer's changing responsibility

The engineer still needs to understand the domain, identify environmental constraints, decide which properties matter, and evaluate whether the implementation matches the mathematical abstraction. Agents can assist with constructing the formal model and discovering proofs, while the proof checker provides independent validation of the proof terms within its trusted foundations.

Type theory gives us a common formal language for describing objects, relationships and evidence. It does not replace domain knowledge, requirements review or systems engineering. Its value lies in enabling more precise conversations between the engineer, the implementation agent and the verification machinery.


14.5 Types are the first verification gate

An agent should not be allowed to leave a domain rule in prose if the native language can express it simply and reliably. First require a domain-meaningful API, then use compiler checks for the properties it expresses, contracts for properties it cannot express, and proofs or other evidence for the remaining obligations. Review the design before accepting a proof: a mathematically verified model of an unnecessarily weak interface still leaves excessive reasoning work to every caller.

The appendix defines a practical mandatory standard for C++ and Odin agents, including review of coupling, cohesion, abstraction, encapsulation and separation of concerns. These principles apply equally to data-oriented programming; none requires a class hierarchy or virtual dispatch. The standard also distinguishes automated checks from judgement-based design review.

15. Exercises and solutions

Work through the exercises before looking at the solutions. The objective is to recognise the shape of the problem, not to memorise a particular tactic sequence.

Exercise A: Types and functions

  1. Given f : Nat → Bool and x : Nat, what is the type of f x? Can you know its value from the signature alone?
  2. Define a Lean function that takes a Nat and returns a function that adds that number to another natural number.
  3. If a sum type has alternatives with 2, 3 and 4 inhabitants, how many inhabitants does the sum have? How many does the corresponding product have?

Solutions

The result has type Bool, but its value is not determined by the signature. A suitable function is:

def addTo (n : Nat) : Nat → Nat := fun x => x + n

The sum has nine inhabitants and the product has 24.

Exercise B: Construct evidence

Prove that P ∧ Q implies Q ∧ P. Try a direct proof term before using tactics.

Solution

theorem swapAnd (P Q : Prop) : P ∧ Q → Q ∧ P :=
  fun h => ⟨h.right, h.left⟩

Exercise C: Dependent types

Construct a Fin 10 with value 9. Why is constructing one with value 10 impossible in a consistent environment? How does this differ from a C++ integer alias?

Solution

def lastIndex : Fin 10 := ⟨9, by decide⟩

The constraint is strictly less than 10. The integer alias does not encode the bound; the Lean type requires evidence of the bound.

Exercise D: Preconditions

Remove the precondition from decrementCorrect in chapter 11. Find a counterexample to the resulting theorem. Write a Lean theorem demonstrating that counterexample.

Solution

For n = 0, natural-number subtraction gives zero and adding one gives one, not zero.

example : ¬ ((0 : Nat) - 1 + 1 = 0) := by decide

Exercise E: Induction and state transitions

Prove that the abstract buffer's capacity remains constant after any finite event sequence. Use the existing capacity_preserved theorem from the capstone.

Solution

namespace BufferModel

theorem run_capacity (s : State) (es : List Event) :
    (run s es).capacity = s.capacity := by
  induction es generalizing s with
  | nil => rfl
  | cons e es ih =>
      change (run (step s e).state es).capacity = s.capacity
      rw [ih (step s e).state, capacity_preserved s e]

end BufferModel

The induction hypothesis applies to the remaining sequence beginning at the state reached by the first operation. The local preservation theorem establishes that the first operation did not modify capacity.

Exercise F: Find a weak specification

Modify the successful push branch so that it clears the buffer. Which theorems should still hold? Which should fail? Why is this an important exercise for agent-generated proofs?

Solution

The validity and capacity invariants should still hold. The successful push contract should fail because it requires length to increase by exactly one. This illustrates that invariant preservation is necessary but insufficient for behavioural correctness.

Exercise G: Design your own model

Choose a subsystem you know: a graphics resource lifecycle, a document cursor, a network protocol session or an allocator free list. Define its domain terminology, admissible states, events, preconditions, postconditions and safety invariants. Write down what your model deliberately omits before asking an agent to implement it in Lean.

For a graphics resource lifecycle, for example, the fact that an image is labelled Ready is not proof that GPU commands have completed. You need to decide how command submission, synchronization and device failure enter the model. There is no single correct solution to this exercise without defining the domain assumptions.

16. A study plan and reading guide

16.1 Suggested progression

The following plan assumes familiarity with C++ but no prior study of formal type theory. Allow 30–60 minutes per session and repeat exercises until the proof state is intelligible without relying on an agent.

SessionStudyPractical milestone
1Chapters 1–2: type judgements and admissible valuesUse #check and explain the meaning of a function signature
2Chapter 3: lambda calculus and compositionDefine curried functions and evaluate them
3Chapters 4–5: algebraic data and polymorphismModel alternative resource states
4Chapter 6: propositions and Curry–HowardConstruct AND, OR and implication proofs
5Chapter 7: proof terms and tacticsExplain the context and goal of a proof
6Chapter 8: dependent typesBuild bounded indices and non-empty vectors
7Chapter 9: equalityExplain when rfl works and when rewriting is needed
8Chapter 10: inductionProve a property over a list or recursive structure
9Chapter 11: contractsFind preconditions and counterexamples
10Chapter 12: state machinesProve invariant preservation and run mutation tests
11Chapter 13: refinementImplement a trace checker for a small native component
12Chapter 14: agentic verificationEstablish proof auditing and model review gates

You are ready to begin using Lean on a small real project when you can distinguish a type from a proposition, explain a proof goal, model a state transition, prove an invariant by induction and describe what your proof does not cover. You do not need to be an expert in every branch of type theory.

16.2 How to read the Geuvers paper

Read Introduction to Type Theory in parallel with the relevant tutorial chapters rather than treating it as a prerequisite to practical work.

Paper sectionWhat to extract
1: OverviewWhy typed computation and formal proof are connected
2: IntroductionThe distinction between classifying terms, set membership and checking supplied evidence
3: Simple type theoryTyped functions, abstraction, substitution and propositions as types
4: Simple type theory, type assignmentThe difference between inference, checking and normalisation; read selectively
5: Polymorphic type theoryAbstraction over types; investigate after learning the basics
6: Dependent type theoryFamilies of types, predicate logic and dependent function types

The paper arose from lectures given in 2008. It is not a Lean 4 language manual and does not develop inductive types in these notes. Use Lean's own material for inductive data, recursion, tactics and axioms. The paper's central conceptual argument is still useful independently of the specific proof assistant.

16.3 Further reading

17. Glossary and mathematical notation

TermMeaning
TermAn expression in the formal language
TypeA classification of admissible terms, with associated formation and usage rules
InhabitantA term of a particular type
ContextThe declarations and assumptions available in a judgement
JudgementA formal assertion made by the type system
ConstructorAn operation for building an inhabitant of a data type or proposition
PredicateA proposition-valued function, such as Nat → Prop
PropositionA statement whose inhabitants are proofs
Proof termA formal expression that provides evidence of a proposition
Dependent typeA type whose definition depends on a value
Pi typeA dependent function type
Sigma typeA dependent pair type
SubtypeA value accompanied by a proof that it satisfies a predicate
Definitional equalityEquality according to the type system's conversion rules
Propositional equalityEquality expressed as a proposition
Inductive typeA type specified using constructors, with associated elimination principles
InductionA method of proving properties over inductively generated objects
AxiomA declaration accepted without a supplied proof
InvariantA property required to hold at specified points in an execution
Safety propertyA property stating that something forbidden does not occur
Liveness propertyA property requiring eventual progress or occurrence
RefinementA formal relationship between abstract and more concrete models or implementations
Trusted computing baseThe components and assumptions whose correctness is relied upon for a particular guarantee
SymbolRead asExample
:Has type42 : Nat
Is an element of
ContextDeclarations of variables and assumptions
Judgement derivable under context
Function abstraction
Function type or implicationA → B
Product typeNat × Bool
Logical ANDP ∧ Q
Logical ORP ∨ Q
Logical negation¬ P
For every∀ n : Nat, ...
There exists∃ n : Nat, ...
Dependent function type(n : Nat) → Fin (n + 1)
Dependent pair typeΣ n : Nat, Vec Nat n
Abstraction mapping (in chapter 13)Concrete state to abstract state

Conclusion

The journey from C++ and Odin to type theory does not require abandoning familiar engineering practices. A structure is a natural introduction to product types; a tagged union introduces sum types; a generic function introduces polymorphism; a bounded index motivates dependent types; and a state machine provides a practical reason to learn induction.

The conceptual shift is that a type system can be used not only to classify data and computations, but also to express mathematical propositions and check evidence of their validity. Lean gives us a concrete environment in which to explore that shift.

The wider opportunity for software engineering is to develop a disciplined relationship between domain knowledge, intent, mathematical models, implementations and verification evidence. The strongest theorem in the world is not useful if it describes the wrong behaviour. Conversely, a carefully designed formal specification and a small set of well-chosen proofs can provide valuable guarantees even when the rest of the system is written in a conventional systems language.

The goal is not to formalise everything immediately. Start with a subsystem whose behaviour matters, whose state can be described clearly and whose invariants are meaningful. Learn to read its proof obligations, challenge its assumptions and establish the relationship between its model and implementation. As you become more comfortable with the mathematics, increase the scope of what you verify.


Appendix A: Agentic engineering standard

A.1 Purpose and applicability

This appendix is a proposed normative engineering policy, suitable for adapting into an AGENTS.md file and enforcing through CI and an agentic harness. It supplements, rather than replaces, normal standards for readability, testing, security, performance, documentation, reproducibility, diagnostics and maintainability. It applies to compiled, statically typed languages with appropriate native type-system support. It is not a requirement to use an object-oriented programming model, nor a claim that every rule can be checked automatically.

The objective is to minimise the amount of information that a human or an agent must reconstruct to make a correct change. Prefer an interface that expresses its intent through domain types, explicit dependencies and clear contracts. Use the strongest practical enforcement mechanism for each important constraint. Do not equate correctness with passing compilation, and do not equate sophistication of the type design with quality.

Use the words MUST, SHOULD and MAY to indicate mandatory requirements, preferred defaults and permitted alternatives. An exception to a MUST requires explicit approval, evidence and a tracked rationale, not a unilateral decision by the implementation agent.

A.2 The five design questions

PrincipleQuestionDesired outcomeEvidence to examine
CouplingWhat happens when something changes?Changes remain local unless the domain contract actually changesImport graph, public signatures, shared mutable state, change-impact analysis
CohesionWhat belongs together?Operations maintaining the same invariant or serving the same responsibility remain togetherOwnership of state, contracts, reason for change
AbstractionWhat are we actually modelling?Interfaces expose the relevant domain meaning, not accidental implementation detailGlossary mapping, type signatures, abstraction relation
EncapsulationWho protects the rules?A clear owner controls invariant-bearing state and mutationPackage or class visibility, validated operations, mutation sites
Separation of concernsWhich independent responsibilities should be distinct?Domain rules can be understood and verified without unrelated infrastructureDependencies, test seams, pure core, adapters

These concepts apply to Odin as naturally as to C++. Abstraction is not synonymous with abstract base classes; encapsulation is not synonymous with private member fields. In Odin, the primary units of encapsulation are often packages, private declarations and ownership of data. Plain data structures and procedures can have excellent cohesion. Data-oriented design determines how data is arranged and processed; the five principles determine how knowledge, responsibility and change are organised. They are complementary.

Coupling: change propagation

In a renderer, a texture decoder should not need to import the scene graph, GPU backend and application UI merely to return pixel data. Define a typed decoded-image result; let an upload adapter consume it. A format change should not unnecessarily change the scene traversal interface. Conversely, a public type that is genuinely part of the domain contract may correctly affect callers when its meaning changes. Low coupling does not mean zero dependencies or excessive indirection.

Keep handle allocation, generation management and liveness checks within the same resource registry responsibility. If unrelated packages can independently mutate these fields, no local review can establish that stale handles are rejected. Avoid both a sprawling utils package and an artificial proliferation of tiny packages that split one invariant across many locations. Organise around responsibilities and reasons for change, not a fixed line count.

Abstraction: separate meaning from layout

A logical mesh is a set of vertices, connectivity and associated attributes; a GPU upload is one concrete representation. A CPU-side structure-of-arrays layout and an interleaved GPU vertex buffer can both implement the same mesh abstraction. Keep the mapping explicit and test indexing, byte layout and attribute correspondence. Do not force a heap-allocated object per vertex merely to obtain a meaningful type. Also do not introduce a generic mesh interface with ten parameters if the project only supports one well-defined representation.

Encapsulation: control mutation at the right boundary

For C++, a private member and a validated constructor can protect local invariants. For Odin, @(private) protects a top-level declaration from export; it is not a general private-field mechanism for public structures. Avoid exposing a pointer to private state or an aliased slice that can mutate it from outside the owning package. A public handle can still be forged by conversion, so validate it at the boundary. For example:

package registry

Handle :: distinct u64

@(private)
Slot :: struct {
    generation: u32,
    live: bool,
}

@(private)
slots: [dynamic]Slot

// Public operations should validate identity/generation against the
// private table. Actual allocation and handle encoding are omitted.

This is a package-boundary sketch, not a complete registry. A private package-global table does not inherently provide thread safety, ownership or test isolation. In a multi-device renderer, prefer explicit registry ownership or an opaque reference where appropriate rather than introducing unnecessary global state. A mutation discipline should have an identified owner, a concurrency policy and tests of the exported operations. Do not merely annotate a public field as protected in prose.

Separation of concerns: a verifiable core

Separate the rule that determines whether a GPU resource may be released from the Vulkan or WebGPU call that actually releases it. The rule depends on resource state and completion evidence; the adapter depends on the device and driver. Model the failure and atomicity boundary: a successful logical decision does not mean an external operation has succeeded. Where appropriate, represent commands and observed outcomes explicitly.

UI and input adapters Typed commands Domain transitions and invariants Typed effect requests GPU and OS adapters Observed outcomes Read model for rendering or UI Lean reference specification Conformance checks

This design is useful outside graphics. In a medical-image viewer, keep coordinate transformations, segmentation label semantics and study identity distinct from UI widgets and DICOM I/O. In a privacy-oriented browser product, separate event interpretation, policy decisions and telemetry collection; external browser events are observations, not proof that the policy was enforced. An explicit core can be verified without mocking an entire environment. Effects and concurrency still need their own contracts.

A.3 Mandatory native type-design policy

IDNormative ruleAcceptance evidence
TYPE-01MUST identify important domain concepts and map them to native types or explicitly justify why a shared representation is appropriate.Concept-to-type mapping and design review
TYPE-02MUST use nominal distinctions for incompatible identifiers, units, coordinate frames or other high-risk concepts sharing a representation when supported.Positive and negative compile tests
TYPE-03MUST represent closed alternatives with tagged unions, variants or enums as appropriate; avoid independent flags that permit contradictory combinations.Exhaustiveness checks, explicit absence or failure
TYPE-04MUST express useful static relationships in type parameters, dimensions or compile-time constraints where this remains comprehensible.Valid and invalid instantiation tests
TYPE-05MUST specify invariants not enforced by the native type system, including ownership, valid ranges, cross-object references, history and numerical tolerances.Contracts and verification obligations
TYPE-06MUST validate untrusted input before treating it as a valid domain value. A cast alone is not validation.Boundary tests and review
TYPE-07MUST identify and constrain explicit casts, unchecked operations, raw pointers, erased types and foreign interfaces that bypass meaningful guarantees.Exception inventory and analysis of allowed boundary sites
TYPE-08MUST represent failure when a normal operation can fail; callers must handle failure according to the contract.Result types, failure-path tests and review
TYPE-09MUST make default and zero-initialised values intentional. If not valid, mark the uninitialised state explicitly or constrain access until validation.Tests and documented construction policy
TYPE-10MUST preserve or re-establish invariants across mutation and conversion. Do not equate a nominal wrapper with a proof of an invariant.Mutation owner, contracts and appropriate verification
TYPE-11MUST assess machine representation, layout, lifetime, aliasing and overflow when they are relevant.Layout assertions, sanitizers, machine model or targeted proofs
TYPE-12SHOULD prefer the simplest native design that preserves the required guarantees. Avoid gratuitous wrapping, inheritance, generic indirection and speculative abstractions.Reviewed rationale and, when needed, performance measurement

In C++ prefer named wrappers, scoped enumerations, std::variant, constrained templates, explicit conversions and RAII where appropriate. In Odin prefer distinct, typed structures, tagged unions, Maybe, enum-indexed arrays, bit sets, constrained polymorphism and package-owned operations. Do not require C++ patterns in Odin just because the design vocabulary originated in object-oriented literature.

A literal such as 0 may still be accepted as a value of a nominal scalar type. A zero value of a public structure may still be constructed. A valid representation is not necessarily a valid resource. In either language, establish and enforce the construction and use policy in proportion to the risk.

A.4 Knowledge-base and verification mapping

For each important domain concept, maintain a canonical identifier, definition, classification, relevant relations, invariants, native representation, allowed operations, validation boundary, assumptions and unresolved questions. The knowledge base is the source of approved domain intent; code and observations can reveal missing knowledge and prompt reviewed changes. Avoid maintaining the same rule as independent, editable prose in four places. Generate views or retain explicit versioned links between artefacts. A native type may implement several concepts; one concept may have several representations.

Example of a proposed machine-readable contract (not a standard or executable verifier):

concept: graphics:SurfaceNormal
meaning: Surface orientation represented by a unit direction
native:
  odin: graphics.Normal
  cpp: graphics::Normal
  representation: three float32 components
properties:
  - id: NORMAL-IDENTITY
    statement: Normal is not interchangeable with Position
    enforcement: native_type
  - id: NORMAL-FINITE
    statement: All components are finite
    enforcement: boundary_validation
  - id: NORMAL-UNIT
    statement: Magnitude is within approved tolerance of one
    enforcement: numerical_contract
    status: blocked
    unknowns: [tolerance, zero_length_policy]
  - id: NORMAL-TRANSFORM
    statement: Transformation uses the appropriate inverse transpose
    enforcement: formal_model_and_conformance
    status: proposed
assumptions:
  - id: NORMAL-A1
    statement: Input transform has an invertible linear component
    treatment: explicit_precondition

A concept record does not prove a property. A status of blocked means the agent must not invent a tolerance or silently claim verification. If the task requires that decision, escalate it for approval or implement only the unaffected scope. formal_model_and_conformance is a plan, not achieved evidence.

A.5 Required agent workflow

Approved task and domain knowledge Identify affected concepts and types Record contracts and assumptions Unknowns block correctness? Escalate or restrict scope Design typed interfaces and ownership Review five design questions Assign enforcement and proof obligations Implement in supported language Run deterministic checks Prove selected model properties Check native conformance Required evidence complete? Diagnose code or specification gap Independent review and acceptance Update knowledge and evidence Yes No No Yes

The harness MUST retrieve only the relevant domain knowledge, inspect the affected public interfaces and dependencies, and produce a change-impact record. For significant changes, it MUST identify the types that carry semantics, the owner of each changed invariant, explicit effects and assumptions, and the proposed verification strategy. It MUST review the five design questions before implementation acceptance. For a trivial change, these records can be concise; ceremony must remain proportional to impact.

The agent MUST NOT weaken a type, delete a failing test, broaden a cast, disable bounds checking, substitute a weaker theorem or introduce an axiom solely to obtain a green build. A change to an approved requirement or public contract needs reviewed intent, not just a successful build. Distinguish a genuine requirement change from a defect in the implementation. Preserve unrelated invariants and test coverage.

A.6 Deterministic acceptance gates

Use the compiler as the first enforcement mechanism. Pin toolchains and build flags. An example Odin starting point is:

odin check ./src -vet -vet-cast -warnings-as-errors
odin test ./tests

Adapt the project paths and flags to the pinned Odin version; use Odin test documentation and the compiler's help. For C++ use the project's build system with a pinned standard and compiler, warnings-as-errors for owned code, suitable static analysis, and tests. Run sanitizers and other dynamic checks in supported configurations. Do not disable checks globally to accommodate foreign code; isolate and record exceptions.

Add compile-fail tests to demonstrate that the type design rejects intended mistakes, rather than relying solely on successful builds. A negative fixture MUST fail for the expected reason, not because of missing imports, unrelated syntax or a broken compiler invocation. Pair it with a positive fixture. For example, ensure that Texture_ID cannot be passed to a mesh-binding procedure, a vector of the wrong dimension is rejected, and an exhaustive union switch requires a new case. Verify on the selected compiler version.

The following checks have different evidence levels:

GateObjective outputWhat it does not prove
Compiler and compile-fail testsType acceptance or rejectionDomain intent, arbitrary invariants
Lint / semantic AST rulesViolations of defined source patternsThat arbitrary code meets an informal principle
Architecture import rulesForbidden dependency edgesAll forms of runtime coupling
Runtime and property testsResults for exercised inputsAll possible inputs or traces
Lean build and axiom auditChecked theorems under model assumptionsNative implementation correspondence
Refinement / translation validationFormal relation for supported implementation scopeUnsupported effects or unmodelled environment
Independent design reviewReviewed rationale, risks, decisionsMathematical certainty

Automated checks can reject objective violations. Coupling, cohesion, abstraction and maintainability also require judgement. An LLM review may suggest improvements; it MUST NOT be presented as a proof. Use source evidence, deterministic measurements where possible and independent human approval for consequential decisions. Reject or mark unsupported constructs as unverified, not verified by default.

If a project deliberately accepts a low-level exception (SIMD, FFI, memory reinterpretation or unchecked bounds), record its exact scope, why it is necessary, the invariant authorising it, its evidence, owner and review trigger. A performance claim should be backed by an appropriate benchmark; the mere presence of additional types does not establish a performance cost or benefit.

A.7 Formal verification and evidence ledger

Formal methods fit alongside native typing, not instead of it. A project may choose a Lean reference model for selected high-consequence rules, such as handle generation validity, allocator arithmetic, transformation composition or protocol transitions. State why each property matters, its assumptions, whether it is an invariant or liveness property, and how the concrete system maps to the model. Audit transitive axiom dependencies and prohibit unfinished proofs for required properties. Check non-vacuity and demonstrate relevant reachable states. Track a separate obligation for native conformance.

Suggested status vocabulary: not_started, blocked, model_checked, tested, formally_related, failed, out_of_scope. Evidence is multidimensional: a proof about a model and a passing native test can coexist; neither supersedes the other. The ledger can store one entry per obligation and technique rather than compressing all assurance into a single score.

obligation: BUFFER-PUSH-BOUND
requirement: A successful push leaves length no greater than capacity
scope: occupancy model only
assumptions: [valid_initial_state, representable_native_capacity]
evidence:
  - technique: lean_proof
    status: not_started
    theorem: BufferModel.step_preserves
  - technique: odin_differential_test
    status: not_started
  - technique: native_refinement
    status: not_started
not_covered: [memory_lifetime, element_contents, concurrent_mutation]

The example intentionally records no achieved evidence. In a real ledger store build commit, model revision, toolchain, command, result, relevant proof assumptions, test cases or trace identifiers, and any exceptions. Invalidate evidence when a relevant dependency changes. A trace checker establishes agreement for the observations recorded; it cannot detect every omitted event or hidden mutation. Require schema validation, sequence completeness policies and independently tested instrumentation for critical traces.

A.8 Reasoning bandwidth: evaluate the design outcome

A good type system and architecture reduce the information required to answer questions such as: can this call fail, can this value be absent, what units does it carry, who owns it, what changes when it is modified, and what must remain true? They also make invalid actions easier to detect before execution. The goal is not merely fewer tokens; the goal is fewer unresolved dependencies and implicit assumptions per engineering decision.

Track indicators over representative tasks, comparing equivalent behaviour and workload:

IndicatorInterpretation and limitation
Files and public interfaces touched per changeA proxy for change locality; large necessary domain changes may legitimately touch many files
Dependency fan-out and forbidden importsHelps find architectural coupling; cannot capture every behavioural dependency
Number of undocumented domain assumptions or unchecked conversionsHighlights reasoning burden; count only meaningful cases, not every cast
Context retrieved and agent tokens per accepted taskA measure of resource usage, not intelligence or correctness; control for task and model
Repair iterations and escaped defectsUseful outcome evidence; distinguish environment failures and changed requirements
Time to explain and review a contractHuman comprehension measure; use representative review tasks rather than arbitrary thresholds
Runtime, memory, binary size and compile timeEnsures stronger modelling does not introduce unacceptable systems costs

Establish a baseline before changing the architecture. Do not invent a universal threshold for type count, package size, dependency fan-out or token expenditure. A larger context may be necessary for a more difficult change. An agent should not optimise metrics by hiding dependencies, shortening meaningful names or removing tests. Treat metrics as diagnostic evidence alongside correctness and review outcomes.

A.9 Copy-ready harness instruction

The following is a compact instruction block to include in a project's agent policy. Its enforcement requires actual checks and a reviewed workflow; placing it in a prompt alone does not make the constraints mandatory in practice.

You are implementing approved engineering intent in a statically typed systems language.
Treat the domain glossary, taxonomy, ontology, behavioural specification and approved
contracts as the authoritative description of intent. Consult the relevant concepts
before changing code. Identify and report conflicting evidence, assumptions and unknowns.

Use the native type system deliberately. Model incompatible concepts with distinct
native types; represent composition and closed alternatives explicitly; use static
parameters and constraints where they express useful relationships. Prefer the
simplest design that provides the required guarantees. Do not erase type information
or introduce unchecked casts without an approved boundary rationale.

For each affected invariant identify its owner, construction and mutation sites,
validation boundary, and enforcement mechanism. If the compiler cannot enforce a
property, record the remaining obligation and choose an appropriate contract, test,
static analysis, runtime check or formal proof. A model proof is not a proof of native
implementation correctness without a justified correspondence.

Review coupling (change propagation), cohesion (what belongs together), abstraction
(what we model), encapsulation (who protects the rules), and separation of concerns.
Apply these principles in the idiom of the language, including data-oriented designs.
Keep effects, external interfaces and machine representation explicit when relevant.

Before acceptance, run the required pinned compiler, lint, positive and negative
type tests, behaviour tests, and designated formal checks. Review proof assumptions,
unsupported constructs, exceptions and conformance evidence. Never weaken a type,
requirement, theorem or test to obtain a passing gate without explicit approval.
Report any unverified obligation as such. Record evidence with its source revision.

Completion requires reviewed intent, an appropriate type design, passing mandatory
checks, and transparent limitations. Optimise for local reasoning and change locality,
not minimum token count alone. Escalate unresolved decisions affecting correctness.

A.10 Definition of done checklist

The bidirectional semantic synchronisation gates in Appendix D are mandatory for in-scope changes. A task may not move to done or ship while required mappings or verification evidence are stale, missing, inconclusive or contradictory.


Appendix B: Native type-design reference

ConceptC++OdinLean / further verification
Aliasusing Id = uint32_tId :: u32A new name need not create a new type
Nominal identityNamed wrapper structdistinctNamed structure; distinguish identity from predicate
ProductStruct, tuplestructProd, structure
Sumstd::variantunion #no_nilSum, inductive type
Optionalstd::optionalMaybe(T)Option
Finite choiceenum classenumInductive constructors
Finite setstd::bitset with domain mappingbit_set[Enum]Finite predicates / finite sets
Total finite lookupArray with checked enum indexing[Enum]TFunction on finite domain
Parametric familyTemplatestruct($T: typeid)Type parameters
Compile-time value indexingNon-type template argumentstruct($N: int)Dependent type if indexing by arbitrary value
Static constraintrequires, static_assertwhere, #assertPropositions, proofs
SubtypingInheritance, explicit compositionusing, #subtypeDistinct from predicate subtypes
Runtime invariantValidated constructor or operationValidated boundary and package-owned statePredicate, subtype or transition invariant
EncapsulationClass/private, translation unit/modulePrivate package/file declarations, controlled APIAbstraction boundary and correspondence
LifetimeRAII, explicit ownership disciplinesExplicit lifetime and resource managementState and ownership model; external evidence
EffectsInterface and conventionsExplicit parameters/context and conventionsExplicit effect semantics

Do not infer identical guarantees from analogous syntax. In particular, ordinary C++ and Odin are not generally dependently typed or memory safe. Neither has a general linear ownership type system. The native type rules provide significant protection in their checked subset, but representation escapes, FFI and environmental dependencies need explicit treatment.

Appendix C: Practical type-design laboratory

C.1 Graphics: type the transformation pipeline

Begin with a codebase using one Vec3 for positions, normals, directions and colours, and one matrix type for every coordinate-space transition. Draw the ontology relations and identify which operations are permitted. Introduce Point3(Space) and Affine_Transform(From, To) using the examples in chapter 5. Add positive and negative compile tests. Distinguish directions (homogeneous w = 0), positions (w = 1), normals (inverse transpose) and clip points (homogeneous coordinates).

Expected outcome: Mismatched source and destination space is a type error; the mathematical validity of a particular matrix remains a contract. Prove a composition property over an ideal mathematical model, then specify the numerical tolerance or error bound and test native computations. Do not claim exact real-number equality for floating-point outputs. Consider whether matrix layout, handedness, depth range and vector convention should be additional markers or documented backend contracts. Measure whether any additional complexity is justified.

C.2 Geospatial: explicit runtime reference systems

Define Latitude, Longitude and Projected_Point. A latitude range can be checked; coordinate reference systems from files are runtime identities. Model an explicit CRS_ID and a transformation record containing source and destination. Require a matching source CRS before transforming. Distinguish axis order, angular units, datum and projected linear units. Avoid using one generic Position for every geographic coordinate.

Expected outcome: Some mistakes are caught by types, others by runtime checks; projection accuracy and transformation validity are external numerical contracts. This teaches the difference between a compile-time phantom marker and a runtime dependent relationship. Establish a reference-data validation plan and name unsupported projections rather than silently accepting them.

C.3 GPU resource ownership: prove a meaningful invariant

Implement a small resource table with generational handles, a count of outstanding submissions, and an operation to observe completion. Separate handle identity from memory address. Specify rejection for stale generations, unknown handles and release requests with outstanding references. Model generations with finite-width arithmetic, including wraparound policy. Decide whether concurrency is in scope.

In Lean, model an abstract resource registry and the valid transition relation. Prove that accepted releases have no outstanding references, and that permitted transitions preserve the registry invariant. Add a test that deliberately attempts to release an old copied handle. Explain how the native registry's state maps to the abstract state, and what guarantees actual GPU fence observations provide. The model should account for failures and nondeterminism as relevant; never assume a driver completion simply because a command was submitted.

C.4 Browser security: model policy decisions and trust boundaries

Define distinct types for Origin, Extension_ID and Tab_ID; use a tagged union for observed event kinds; represent permissions as a finite set for a selected subset. Keep missing or unknown observations separate from explicitly denied permissions. A policy function can accept typed observations and return Allow, Deny or Insufficient_Evidence with reasons. The telemetry adapter must not fabricate a trusted event when input is incomplete.

Expected outcome: The policy can be tested independently of browser I/O; prove that a specified forbidden permission combination cannot receive an Allow decision under the model. This does not prove all real browser behaviour is captured, that the telemetry is complete, or that an enforcement mechanism cannot be bypassed. Record those obligations separately.

C.5 Evaluation rubric

For any laboratory, review whether types actually express the approved glossary and relationships, whether invalid combinations fail at the intended layer, whether the formal properties are non-vacuous, whether the native model matches relevant machine semantics, and whether a change can be made with local knowledge. Compare against the original implementation with equivalent behaviour. A good answer explains its remaining limitations rather than claiming that a richer type system solves all correctness problems.

Revision and verification notes

This edition retains the original chapters, Lean capstone and exercises, integrates Odin examples through the learning sequence, and adds appendices A–C, and extends the semantic synchronisation policy in appendix D. The graphics, GIS, security and resource-management scenarios are deliberately selected teaching examples, not claims about an existing application. The agent policy and YAML schemas are proposed designs, not language standards or installed tooling. New C++ snippets are selectively syntax-checked; the Odin and Lean snippets require local compiler validation. The original source Markdown is preserved separately. Appendix D is also provided as a standalone addendum.


Appendix D: Odin semantic traceability and behavioural verification

A practical architecture for bidirectional semantic traceability and Spall-like behavioural monitoring.

D.1 Purpose: a synchronised engineering knowledge system

The glossary, taxonomy, ontology, behavioural specification and source code are different views of the same engineering understanding. They must evolve together throughout the software lifecycle. A developer or agent must be able to navigate from a concept, relationship, invariant or behaviour to its implementation and evidence, and from a source declaration to the concepts, rules and behaviours it implements. Neither side is automatically correct merely because it exists.

The central acceptance rule is no unreviewed semantic drift. A task is incomplete if a changed implementation has no required mapping, an approved requirement has lost its implementation, a model is stale, a mandatory obligation has failed, or an affected relationship has not been revalidated. An unchanged artefact need not be edited merely to make a commit symmetrical. It needs an explicit impact decision and current evidence. Work in progress may be inconsistent; accepted baselines may not have unresolved mandatory inconsistencies. A failed gate does not imply the agent must invent a resolution: it must surface the blocker.

This addendum proposes a tool architecture, not an already implemented Odin compiler extension. It uses documented Odin attributes, AST tooling and instrumentation hooks; the tag vocabulary, extraction CLI, event format, graph schema and acceptance policy are our own. The aim is to learn type theory through a concrete, incremental engineering system, not to verify all of Odin before obtaining value.

Approved glossary and taxonomy Approved domain knowledge Approved ontology and constraints Approved behaviour and assumptions Odin source and build configuration Extracted source graph Versioned semantic mappings Structural and semantic validation Lean model and proof obligations Instrumented native execution Typed domain events and call traces Trace conformance checker Acceptance gate Investigate and approve changes Bidirectional knowledge browser Discrepancy

D.2 Keep four kinds of knowledge distinct

ArtefactAuthorityExample
Domain graphReviewed definitions and intended relationshipsA GPU buffer is a resource; a submission references a buffer.
Behavioural modelReviewed operational semantics and assumptionsRelease is rejected if outstanding work is nonzero.
Source graphDeterministically extracted facts about a revision and build profilegpu.release takes ^Registry and Buffer_Handle; it writes registry state.
Mapping and evidence graphReviewed correspondence, generated results and provenancegpu.release implements B-RELEASE; observed trace 19 conforms to model M.

Use SKOS for terms, preferred labels, synonyms and concept hierarchy. Use OWL/RDFS for domain classes and relationships where logical inference is valuable. Use SHACL and explicit closed-world project checks for required fields, mapping completeness and architecture policies. Use SPARQL for navigation and impact queries. Use Lean for mathematical models, transition rules and proofs. There is no need to maintain a separate prose definition of a rule in every tool. Designate an authoritative representation and link or derive the other views.

An OWL class is not automatically an Odin type. A SKOS broader relation is not automatically a subtype. rdfs:subClassOf does not imply native assignment compatibility. An ontology relationship may be represented by a field, a foreign key, a lookup table, an ECS component, a procedure, an invariant or an external observation. The mapping explicitly explains which. OWL's open-world reasoning does not make an absent assertion false; SHACL and project policy can reject missing required assertions within a specified data graph. Conversely, SHACL cannot prove arbitrary runtime behaviour.

Treat facts from source as observations, not approved requirements. A type named Normal does not establish that it is a unit vector. A field named owner does not establish exclusive ownership. A call to release does not establish that the GPU has ceased using the resource.

D.3 Stable identities: the connective tissue

Assign persistent identifiers at the point a concept, relationship, behaviour or requirement is accepted. Do not derive identity from a file path, line number or mutable display name. Names can change without meaning changing. A split or merge of concepts is a reviewed migration, not merely a rename. Retain tombstones and replacement links for retired identifiers.

Use a separate identity for each source declaration that needs durable navigation. Keep its current qualified name, path, source range, revision, signature fingerprint and build profile as generated locator information. A concept may map to multiple declarations and a declaration may realise multiple concepts or behaviours. Multiple mappings are not inherently duplicates; duplicate declaration identity is an error unless the schema explicitly distinguishes build alternatives.

Illustrative identifiers:

IdentifierMeaning
C-0001GPU resource
C-0002GPU buffer
C-0003Buffer handle
C-0004Resource registry
R-0001Buffer handle resolves to a live buffer in a registry
B-0001Submit work against a buffer
B-0002Observe completion of submitted work
B-0003Release a buffer
I-0001Released resource has no outstanding work
S-0001Native declaration implementing the buffer-handle representation
S-0002Native declaration implementing the release operation
P-0001Formal theorem establishing the selected release invariant

These IDs are illustrative; real projects should namespace them to avoid collisions. Expose resolvable local URLs or URIs for browser navigation. Canonical identity is independent of the human-facing label.

D.4 Odin user-defined tags

Odin supports @(tag="...") as user-defined declaration metadata ignored by the compiler (attributes documentation). This is a useful anchor for external tooling. It is not a native contract language and does not cause the compiler to check the content of a tag. Use one string per declaration and a small, versioned external grammar rather than assuming that repeated tags or arbitrary custom attributes are supported.

For example:

@(tag="kb1;id=S-0001;concept=C-0003")
Buffer_Handle :: distinct u64

@(tag="kb1;id=S-0003;concept=C-0004")
Registry :: struct {
    // Private storage and implementation details belong to the owning package.
    // This is a schematic type, not a complete resource registry.
    slots: []Slot,
}

The first tag binds the native type to a domain concept; the second ties the owning registry to another concept. In a real package Slot is a defined implementation type. An operation might carry the following metadata:

@(tag="kb1;id=S-0002;behaviour=B-0003;invariant=I-0001")
@(require_results)
release :: proc(registry: ^Registry, handle: Buffer_Handle) -> Release_Result {
    // Resolve the handle and generation.
    // Reject outstanding work and invalid handles.
    // Apply the release through the owning registry.
    // Emit a typed domain event using actual observed state.
    // Return the specified outcome.
    return .Invalid_Handle // Placeholder, NOT a working release implementation.
}

A suitable Release_Result would be an enum or tagged result with alternatives such as Released, Busy, Invalid_Handle and Backend_Error. Choose the actual alternatives from the domain model. require_results prevents accidental unacknowledged results but does not force the caller to choose correct recovery behaviour. Tags should remain compact; the actual semantic contract belongs in the knowledge base.

Proposed grammar: kb1;id=<source-id>;concept=<id>,<id>;behaviour=<id>;invariant=<id>. The first token identifies a schema version. Reject malformed, unknown or duplicate keys, missing source IDs and dangling references. For relationships involving individual fields, use a sidecar mapping addressed by the declaration ID and resolved field path; Odin also has struct field tags, but their use is a separate convention and is not required by this design. Do not assume declaration tags survive code generation or appear in runtime RTTI. Extract them at build time.

A C++ frontend could use a sidecar keyed by stable declaration identity, or a supported compiler-specific annotation such as Clang's annotate attribute. The graph and behaviour verifier should not depend on the language-specific syntax of the annotation.

D.5 A small semantic graph and deterministic checks

The following Turtle is a self-contained example of the mapping vocabulary. The domain concepts and the corresponding ontology classes have separate identities here; this is a deliberate modelling choice that avoids accidentally equating a SKOS concept with a software type. Relations between concepts, classes and code have explicit meanings.

@prefix kb: <https://example.invalid/kb/> .
@prefix skos: <http://www.w3.org/2004/02/skos/core#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .

kb:C-0001 a skos:Concept ; skos:prefLabel "GPU resource"@en .
kb:C-0002 a skos:Concept ; skos:prefLabel "GPU buffer"@en ;
    skos:broader kb:C-0001 ; kb:denotes kb:GPUBuffer .
kb:C-0003 a skos:Concept ; skos:prefLabel "Buffer handle"@en ;
    skos:definition "An identifier used to resolve a buffer in its registry."@en ;
    kb:denotes kb:BufferHandle .
kb:GPUResource a owl:Class .
kb:GPUBuffer a owl:Class ; rdfs:subClassOf kb:GPUResource .
kb:BufferHandle a owl:Class .
kb:resolvesTo a owl:ObjectProperty ;
    rdfs:domain kb:BufferHandle ; rdfs:range kb:GPUBuffer .
kb:R-0001 a kb:Relationship ; kb:relation kb:resolvesTo ;
    kb:status kb:Approved .
kb:B-0003 a kb:Behaviour ; rdfs:label "Release buffer" ;
    kb:requiresImplementation true ; kb:status kb:Approved ;
    kb:requiresInvariant kb:I-0001 .
kb:I-0001 a kb:Invariant ;
    rdfs:label "Released resource has no outstanding work" .
kb:S-0001 a kb:SourceDeclaration ; kb:qualifiedName "gpu.Buffer_Handle" ;
    kb:realisesConcept kb:C-0003 .
kb:S-0002 a kb:SourceDeclaration ; kb:qualifiedName "gpu.release" ;
    kb:implementsBehaviour kb:B-0003 ; kb:addressesInvariant kb:I-0001 .

The example namespace is illustrative and does not identify a hosted service. In production store the approved and extracted facts in separate RDF named graphs, with a run manifest identifying their input revisions. A union view may be used for validation and queries; do not allow extraction to overwrite approved facts. Formalise field mappings for R-0001 separately: resolving a handle involves a registry operation, generation validation and resource liveness, not simply the existence of a u64 type.

A SHACL shape can require a mapped behaviour with the correct kind to exist:

@prefix kb: <https://example.invalid/kb/> .
@prefix sh: <http://www.w3.org/ns/shacl#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

kb:SourceShape a sh:NodeShape ;
    sh:targetClass kb:SourceDeclaration ;
    sh:property [ sh:path kb:qualifiedName ; sh:minCount 1 ;
                  sh:maxCount 1 ; sh:datatype xsd:string ] ;
    sh:property [ sh:path kb:implementsBehaviour ; sh:class kb:Behaviour ] ;
    sh:property [ sh:path kb:realisesConcept ;
                  sh:class <http://www.w3.org/2004/02/skos/core#Concept> ] .

kb:BehaviourShape a sh:NodeShape ;
    sh:targetClass kb:Behaviour ;
    sh:sparql [
        sh:message "Approved behaviour requiring implementation has no mapping." ;
        sh:select """
            PREFIX kb: <https://example.invalid/kb/>
            SELECT $this WHERE {
                $this kb:status kb:Approved ; kb:requiresImplementation true .
                FILTER NOT EXISTS {
                    ?decl a kb:SourceDeclaration ; kb:implementsBehaviour $this .
                }
            }
        """
    ] .

Use a SHACL-SPARQL-capable validator for the second constraint. It checks a mapping claim exists, not that code genuinely implements the behaviour. Additional gates must check that the declaration exists in the selected build, its signature and dependencies match reviewed expectations and evidence is current. Do not generate fake mappings merely to satisfy cardinality checks. Domain concepts marked abstract, external or intentionally not implemented need an explicit scope policy, not invented source declarations.

A reverse-navigation query can find code implementing an approved behaviour or realising a concept:

PREFIX kb: <https://example.invalid/kb/>
SELECT DISTINCT ?decl ?name ?target WHERE {
  VALUES ?target { kb:B-0003 kb:C-0003 }
  ?decl a kb:SourceDeclaration ; kb:qualifiedName ?name .
  { ?decl kb:implementsBehaviour ?target }
  UNION { ?decl kb:realisesConcept ?target }
}
ORDER BY ?name

A source-to-knowledge query reverses the lookup:

PREFIX kb: <https://example.invalid/kb/>
SELECT ?relation ?target WHERE {
  VALUES ?relation { kb:realisesConcept kb:implementsBehaviour kb:addressesInvariant }
  kb:S-0002 ?relation ?target .
}

The example has two deliberately small queries. Production queries must select the correct baseline graph, target configuration, scope and evidence status. Dependency traversal can use SPARQL property paths for relationships with approved transitive semantics; do not assume every association implies change propagation.

D.6 Extract a source graph, not just a list of annotations

Start with Odin's core:odin/parser and core:odin/ast packages. The AST exposes declaration attributes and source positions (for example Value_Decl.attributes). Inspect structured AST nodes rather than searching text with a regular expression; comments, strings and disabled branches would otherwise create false mappings.

Phase 1 extracts declared names, tag strings, type declarations, explicit fields, procedure signatures, imports and source ranges. Record unresolved names and conditional branches instead of guessing. Phase 2 consumes or exports compiler semantic information after type checking: resolved symbol identity, inferred expression types, implicit conversions, generic instantiations and selected build branches. This may require extending the open-source compiler; a parser is not an authoritative type checker. Phase 3 analyses relevant call targets, write sites, pointer escapes and effects, using conservative unknown results where indirect calls or aliasing cannot be resolved.

The output is a graph of declarations, field references, type identities, representations, calls, state writes, casts, imports and ownership boundaries. Preserve the difference between observed source edges and intended ontology edges. The source graph can reveal a missing concept, an unapproved relationship or unwanted coupling; only a reviewed change may promote such an observation into the domain graph.

Domain assertionCandidate native enforcementAdditional evidence
Handle is not a texture IDdistinct and typed procedure argumentsCompile-pass and compile-fail tests; audit explicit casts
Buffer is a GPU resourceComposition, subtype or handle registry mappingReviewed representation correspondence; not necessarily inheritance
Registry owns buffer lifetimePackage-owned storage and operationsWrite/escape analysis, lifetime rules, runtime checks
Material references textureTyped handle field or indexed relationshipReference validity, generation checks, load/unload tests
Release only if no outstanding workTyped result and controlled transitionLean model, transition conformance and GPU completion evidence

Native design must remain data-oriented where appropriate. A graph of entities and relationships does not require an object graph in memory. An ECS or SoA buffer can realise the same ontology with different storage. The mapping describes that correspondence and the constraints that must survive layout optimisations.

D.7 A Spall-like behavioural profiler

A performance profiler records where execution spends time. A behavioural profiler records what happened in terms of domain concepts and whether the observed behaviour matches the model. Odin's Spall package illustrates both scoped profiling and automatic procedure instrumentation. Odin documents @(instrumentation_enter) and @(instrumentation_exit) with contextless callbacks taking a procedure address, call-site return address and source location. These hooks do not supply arbitrary procedure arguments, return values, state snapshots or semantic tags. They are useful for control-flow context, not sufficient for verifying domain behaviour.

Use two correlated streams:

  1. Automatic procedure enter/exit spans, mapped to declarations using build-specific symbols or an explicitly generated mapping. They help locate activity in source, expose unexpected calls and associate timings with domain operations.
  2. Explicit typed semantic events emitted at meaningful transition or observation boundaries. These capture the actual resource identity, inputs, outcome, relevant before/after state and causality needed by the formal model.

Use one pair of instrumentation callbacks that fans out to the required collectors; do not assume multiple pairs can be installed. Keep the collector itself out of instrumentation using the documented @(no_instrumentation) or file-level #+no-instrumentation, and audit indirect callees for recursion and allocation. The Spall example is not a guarantee of thread safety; provide per-thread buffers and an explicit merge policy. Verify the exact compiler version and build options locally. An example hook skeleton (requires import "base:runtime" and project-specific collector procedures):

@(instrumentation_enter)
behaviour_enter :: proc "contextless" (
    proc_address, call_site_return_address: rawptr,
    loc: runtime.Source_Code_Location,
) {
    // collector_enter(proc_address, call_site_return_address, loc)
    // Must be safe for the actual calling convention and recursion policy.
}

@(instrumentation_exit)
behaviour_exit :: proc "contextless" (
    proc_address, call_site_return_address: rawptr,
    loc: runtime.Source_Code_Location,
) {
    // collector_exit(proc_address, call_site_return_address, loc)
}

This is illustrative scaffolding, not an active logger. Procedure addresses are build- and run-specific; ASLR, inlining, dynamic dispatch and optimisation must be considered. Stable semantic IDs belong in the explicit event stream or a verified build mapping, not in raw addresses. Missing automatic spans must not be interpreted as proof that no operation happened.

Typed event schema

For a resource registry, use types that distinguish a handle, generation and outstanding count. Use a tagged union to prevent an arbitrary combination of event payloads. The following is one possible native event model for a restricted single-resource example; the full registry needs generation resolution, errors, concurrency and backend observations.

Resource_ID :: distinct u64
Generation :: distinct u32
Pending_Count :: distinct u32

Resource_Key :: struct {
    id: Resource_ID,
    generation: Generation,
}

Resource_Snapshot :: struct {
    live: bool,
    pending: Pending_Count,
}

Submit_Event :: struct {
    key: Resource_Key,
    before, after: Resource_Snapshot,
    accepted: bool,
}

Complete_Event :: struct {
    key: Resource_Key,
    before, after: Resource_Snapshot,
    accepted: bool,
}

Release_Event :: struct {
    key: Resource_Key,
    before, after: Resource_Snapshot,
    accepted: bool,
}

Behaviour_Event :: union #no_nil {
    Submit_Event,
    Complete_Event,
    Release_Event,
}

In production use explicit outcomes (including backend error and stale handle) rather than one Boolean if the specification distinguishes them. The Boolean here keeps the first model small. The event schema should be versioned and generated into native types and decoder metadata from one authoritative schema. Do not dump raw union memory to disk: padding, byte order, pointer values and compiler layouts are not stable serialization. Emit a defined encoding with lengths, numeric bounds and schema IDs. Start with JSON Lines, then benchmark a compact binary format and fixed-size buffers if required.

Where to instrument

Capture before from the actual authoritative state, execute the native operation, then capture after from the authoritative state and emit the observed outcome. A checker that computes both the expected and recorded result from the same reference model provides no meaningful independent conformance evidence. Trace rejected operations too. Emit accepted mutations at their linearisation point, or record sufficient ordering information to reconstruct it; do not rely on wall-clock sorting across threads. Distinguish a GPU completion observation from the CPU's submission event. Do not conflate CPU call return with GPU work completion.

The following JSON Lines example represents a failed run of one simplified registry object, with initial state declared by the run manifest:

{"seq":1,"behaviour":"B-0001","object":"buffer:42:7","before":{"live":true,"pending":0},"after":{"live":true,"pending":1},"accepted":true}
{"seq":2,"behaviour":"B-0003","object":"buffer:42:7","before":{"live":true,"pending":1},"after":{"live":false,"pending":1},"accepted":true}

At sequence 2, the expected result is rejection with unchanged state. The trace shows an illegal accepted release. The analyser should report I-0001, B-0003, S-0002, the resource identity, before/after values and a link to the native implementation and Lean rule. A separate profiling stream may attach the relevant call span and timing.

Each trace run needs an immutable manifest containing source and model revisions (or content hashes), compiler version, target and build flags, executable identity, schema version, initial state or checkpoint, test identity, run ID and loss statistics. Include per-stream sequence numbers and causal references where needed. Dropped records, absent initial state, unsupported events and unknown schema versions produce inconclusive, not pass. Selective sampling is useful for performance diagnosis but cannot establish full trace conformance when mandatory events are missing.

D.8 Formalise the behavioural model in Lean

The formal model is an executable specification of selected behaviour, not a reconstruction of the native code. Begin with one existing, live resource and a bounded outstanding-work counter. The resource key and generation are handled by the surrounding replay adapter; allocation, reuse, backend errors and concurrency are deliberately out of scope for this first model. A completion operation represents an observed completion, not a request to the GPU to complete. The model assumes observations are authentic and appropriately ordered.

The following standalone Lean 4 model uses natural numbers with an explicit maximum to reflect the relevant unsigned machine range. The state abstraction for the native Pending_Count is its unsigned numeric value. A production refinement proof would need to establish that the native operation and the abstract transition agree, including overflow and lifetime semantics.

import Lean

namespace BehaviourDemo

structure Snapshot where
  live : Bool
  pending : Nat
  deriving Repr, DecidableEq

inductive Operation where
  | submit | complete | release
  deriving Repr, DecidableEq

def maxPending : Nat := 4294967295

def Valid (s : Snapshot) : Prop :=
  s.pending ≤ maxPending ∧ (s.live = false → s.pending = 0)

def step (s : Snapshot) (op : Operation) : Snapshot × Bool :=
  match op with
  | .submit =>
      if s.live = true ∧ s.pending < maxPending then
        ({ s with pending := s.pending + 1 }, true)
      else (s, false)
  | .complete =>
      if s.live = true ∧ s.pending > 0 then
        ({ s with pending := s.pending - 1 }, true)
      else (s, false)
  | .release =>
      if s.live = true ∧ s.pending = 0 then
        ({ s with live := false }, true)
      else (s, false)

-- I-0001: accepting a release requires zero pending work.
theorem release_requires_idle (s : Snapshot)
    (h : (step s .release).2 = true) : s.pending = 0 := by
  by_cases guard : s.live = true ∧ s.pending = 0
  · exact guard.2
  · simp [step, guard] at h

-- A second obligation: busy release is rejected without changing state.
theorem busy_release_unchanged (s : Snapshot) (h : s.pending > 0) :
    step s .release = (s, false) := by
  have nz : s.pending ≠ 0 := Nat.ne_of_gt h
  simp [step, nz]

structure Observation where
  op : Operation
  before : Snapshot
  after : Snapshot
  accepted : Bool
  deriving Repr

def conforms (current : Snapshot) (o : Observation) : Bool :=
  decide (o.before = current ∧
          (o.after, o.accepted) = step current o.op)

def replay (current : Snapshot) : List Observation → Bool
  | [] => true
  | o :: os => conforms current o && replay o.after os

def initial : Snapshot := ⟨true, 0⟩
def busy : Snapshot := ⟨true, 1⟩

def submitted : Observation := ⟨.submit, initial, busy, true⟩
def rejected : Observation := ⟨.release, busy, busy, false⟩
def badRelease : Observation := ⟨.release, busy, ⟨false, 1⟩, true⟩

#eval replay initial [submitted, rejected]   -- expected: true
#eval replay initial [submitted, badRelease] -- expected: false

#print axioms release_requires_idle
#print axioms busy_release_unchanged

end BehaviourDemo

The Lean snippet is illustrative and has not been compiler-run in the authoring environment. For production, prove step preserves Valid, then prove the replay checker is sound with respect to the transition semantics. Make the model's valid initial condition an explicit assumption. Do not equate the example #eval results with these universal theorems. Test the checker against deliberately invalid traces, especially gaps, fabricated snapshots, invalid state and false success results. Verify the serialization adapter separately: the JSON decoder must not turn a malformed observation into a valid Lean value.

The eventual goal is to prove the following kinds of propositions:

The fourth obligation is different from the first three. Trace replay evaluates particular observed native executions. It does not prove that all executions of the Odin code conform, that every relevant event was captured, or that GPU completion observations are authentic. Stronger implementation guarantees require additional semantic correspondence, static verification or trusted boundary arguments. A green behavioural timeline is evidence, not universal certification.

For larger systems, a model may be relational or nondeterministic rather than a single deterministic step. The checker must establish that an observed result is among the permitted outcomes, with the appropriate state and causality. Do not arbitrarily select one valid result and reject every other permitted implementation choice.

D.9 The interactive engineering browser

Generate a single navigable HTML application or local web interface from the graphs and evidence. It must not be a manually edited copy of the glossary. Regenerate it for each accepted baseline and offer a worktree preview clearly marked as unaccepted. For each page, expose the source revision, model revision and build profile used by the index. Serve through a local process when IDE integration is needed; a standalone read-only HTML export can still show relative repository paths, source excerpts and commit-specific links.

ViewWhat must be visible and clickable
GlossaryConcept definition, synonyms, parent categories, related concepts, native types and implementation locations.
TaxonomyParent/child concepts, classification rationale, native variants or representations and explicit non-mappings.
OntologyLabelled relationship edges, constraints, field/procedure mappings, assumptions and unresolved relations.
BehaviourState graph, transitions, guards, outcomes, related invariants, implementing procedures, tests and Lean theorems.
CodeSource range, declared and resolved types, mapped concepts, relationships, behaviours, affected callers and verification status.
TraceTime/span view, causal order, per-object state history, observed vs expected outcomes, first divergence, linked source and rule.
Change impactModified declarations and concepts, affected neighbours, stale evidence, coverage gaps and decisions awaiting approval.

A canonical route could be /concept/C-0003, /relation/R-0001, /behaviour/B-0003, /source/S-0002, /proof/P-0001 or /trace/<run-id>/<sequence>. The router resolves current source locations through the index. IDE opening should be an explicit, allowlisted action restricted to the repository; never execute arbitrary paths or commands embedded in source tags. Provide search by term, alias, qualified symbol, stable ID or requirement. Every relationship edge should link both ends.

Glossary concept C-0003 Native type S-0001 Ontology relationship R-0001 Native procedure S-0002 Behaviour B-0003 Invariant I-0001 Lean proof P-0001 Trace event realised by participates in implemented by implements constrained by checked by observed in source location

A typical debugging session begins with the profiler showing a red marker for an illegal release. Selecting it opens the before/after state and expected rejection, then the behaviour definition, the Lean transition rule, the native procedure and the relevant ontology relationships. Starting from a glossary definition should expose the same evidence in the other direction. This is not a one-to-one mapping between files and documents; it is a graph of many-to-many links.

A type such as World_Position might be used in several packages. The graph should show the coordinate-space concept, transformations accepting and returning it, allowed conversions and the corresponding test or proof obligations. A change to the coordinate convention can then surface impacted declarations without asking an LLM to ingest the entire repository. In a browser security domain the same approach links Origin, Permission, policy decisions, enforcement adapters and observed events. The graph can retrieve the relevant subgraph for a task; it does not need to stuff the entire ontology or source tree into every prompt.

D.10 Synchronisation as a transaction, not a documentation chore

A commit, task or change set must declare the approved semantic baseline it was derived from. Rebuild the extracted graph against the actual candidate worktree and supported build profiles. Compare it to the previous accepted graph. The impact analysis follows explicit dependency and traceability edges, rather than treating every semantic relation as a call dependency. Record why a detected change has or does not have domain impact.

Change requested in domain or code Locate affected concepts, rules and declarations Review intent and unknowns Update approved model or propose reviewed delta Design and implement with native types Regenerate source graph and mapping index Run structural, formal and native checks All mandatory obligations resolved? Blocked or failed: diagnose discrepancy Publish coherent baseline and browser No Yes

The workflow is symmetric. A domain change triggers an implementation impact search. A code change triggers a domain and behavioural impact search. If the code reveals a missing requirement, capture a proposed knowledge-base change and the source evidence, then get it reviewed. Never silently redefine approved intent to make an implementation pass. Never force a code change merely because an abstract concept has no concrete representation: the mapping policy should explicitly allow abstract concepts, external systems and out-of-scope features.

Track at least three dimensions for each mandatory obligation: mapping status, model/proof status and implementation evidence status. For example, an invariant can be mapped to a procedure, proven for the Lean model, but unverified against the native implementation. A single green check would hide this distinction. Evidence can be pass, fail, inconclusive, not_run, stale or not_applicable (the last requires reviewed justification). A proof is stale if its relevant dependencies change; a trace is stale if it refers to a different executable or model. Conservative whole-baseline invalidation is a simple starting policy. Later, dependency-specific fingerprints can safely reduce repeated work.

A release manifest should include the source tree content hash or commit, domain graph hash, model hash, mapping schema version, compiler version, target profile, relevant build flags, evidence manifest and gate-policy version. Sign or otherwise protect approved records if the threat model includes malicious or uncontrolled tool changes. Generate the browser from the same manifest. A worktree preview may be temporarily inconsistent but must never masquerade as an accepted baseline.

Mandatory gates

GateFails when
Schema and terminologyDuplicate stable IDs, unresolved references, conflicting required labels or malformed annotations exist.
Mapping completenessA required concept, relationship, invariant or behaviour has no approved realisation or valid exception.
Reverse traceabilityA changed in-scope domain-facing declaration or transition has no mapping or explicit classification.
Native type designRequired nominal distinctions, typed interfaces or static constraints are missing or weakened.
ArchitectureUnapproved dependency edges, state writers, representation escapes or boundary violations occur.
BehaviourA mandatory event or transition is missing, invalid or unsupported by the approved model.
Formal proofA required theorem fails, is stale, has an unapproved axiom, or its statement was weakened without approval.
Native conformanceRequired tests or static checks fail; required trace checks are incomplete, stale or disagree with the model.
PublicationBrowser/index and evidence do not correspond to the same candidate baseline.

A mapping claim by itself is not a proof. A successful compiler build is not sufficient. A passing proof is not sufficient. An agent's explanation is not an alternative to a deterministic gate where one can be built. Exceptions must be scoped, approved, recorded with rationale, and revisited when their assumptions change. The policy should distinguish mandatory failures from optional suggestions, so trivial private helper functions do not require artificial ontology concepts.

D.11 Implementation roadmap

A pragmatic first implementation needs neither a custom compiler nor a distributed service. Use Git for the approved artefacts, a local RDF store or in-process RDF library for semantic queries, and SQLite for source indexing, traces and evidence. Keep one authoritative record of each fact; derived indexes can be rebuilt. A JSON Lines event format is enough initially. Later move to a binary stream if measurements justify the change.

project/
  knowledge/
    glossary.ttl
    ontology.ttl
    behaviours.ttl
    constraints.shacl.ttl
    assumptions.yaml
    mappings.yaml          # field/relationship and approved exception mappings
  formal/
    Resource.lean
    Trace.lean
  src/
    gpu/
      registry.odin
      events.odin
  tools/
    extract/               # Odin parser and eventually typed semantic export
    graph/                 # index, mapping joins and semantic validation
    monitor/               # instrumentation, event decoder and replay adapter
    gate/                  # deterministic acceptance checks
    browser/               # generated UI, no manual domain content
  tests/
    native/
    compile_fail/
    trace_fixtures/
  build/                   # generated, not hand edited
    source-graph.ttl
    mapping-index.json
    baseline-manifest.json
    evidence.sqlite
    traces/
    browser/

Proposed CLI (these commands do not exist yet):

kb extract --profile debug
kb validate --baseline candidate
kb impact --base HEAD --candidate worktree
kb verify --scope changed
kb replay --run resource-lifetime-001
kb browse --baseline candidate
kb gate --baseline candidate

The native compiler is an independent gate. Use its documented checks (inspect odin check -help for the pinned version), and compile positive and negative fixtures separately. The kb tools should emit stable diagnostic IDs, source locations and affected concept IDs in a machine-readable format. Use a nonzero exit code for a failed mandatory gate and a distinct machine-readable status for blocked or inconclusive results. Never report success because an external checker could not be invoked.

Implementation milestones, each with a working vertical slice:

  1. Pick one graphics registry subsystem and establish a small reviewed glossary, taxonomy, ontology and behaviour. Implement tag extraction and both directions of navigation. Deliberately break a concept link and confirm the gate catches it.
  2. Add native type identities, a relationship mapping and controlled state ownership. Create compile-negative fixtures and static checks for one meaningful architecture rule. Deliberately swap resource types or introduce an unapproved mutation path.
  3. Add a typed domain event stream and deterministic replay for a small state machine. Correlate source IDs with spans; expose an illegal transition in the browser. Confirm missing event records produce inconclusive status.
  4. Add a Lean model and prove a nontrivial invariant. Verify the model checker separately and run native conformance fixtures. Record proof and trace statuses independently.
  5. Integrate with the agentic task lifecycle. Block done and ship transitions for missing or stale required evidence. Test the gate by deliberately modifying a public type, changing a model, deleting a mapping and weakening a contract.
  6. Extend to concurrency, actual GPU observations, richer semantic analysis and other languages only when the basic pipeline is trusted and the cost is justified. Use an explicit supported-subset manifest. Unknown constructs must remain unknown.

Measure the benefit in terms of reasoning locality and evidence, not just code generation speed: time to find the authoritative rule, affected declarations discovered, missing mappings, regression detection, unsupported semantics, review time and the relevant context size in tokens. More annotation is not automatically better; prefer useful concepts and coarse-grained boundaries to tagging every variable or mechanically mirroring the code as an ontology.

D.12 Copy-ready instruction for an agentic harness

MANDATORY SEMANTIC SYNCHRONISATION POLICY

Treat the approved glossary, taxonomy, ontology, behavioural specification,
formal model, native source and verification evidence as linked artefacts.
The approved domain knowledge is not generated blindly from the implementation.
The source graph is extracted from the candidate build and is not edited by hand.

Before changing code or domain knowledge:
- Identify the stable concept, relation, behaviour and requirement IDs affected.
- Retrieve their relevant subgraph, implementations, assumptions and evidence.
- Classify unknowns and distinguish approved facts from extracted observations.
- Review coupling, cohesion, abstraction, encapsulation and separation of concerns.

During implementation:
- Use the strongest practical native types supported by the compiled language.
- Map all in-scope domain-facing declarations to stable IDs using the approved
  annotation or sidecar schema. Preserve IDs across ordinary renames and moves.
- Map semantic relationships and state transitions to their actual implementations.
- Use explicit types, controlled state ownership and boundary validation.
- Record constraints the type system cannot enforce as explicit obligations.
- Update affected domain or behavioural artefacts through reviewed changes.
- Never change approved intent, weaken a proof, suppress a failing trace, fabricate
  a mapping or remove a type distinction merely to make the gate pass.

Before reporting completion:
- Rebuild the source graph and both directions of the mapping index.
- Validate required links and approved architecture constraints against the candidate.
- Check the impacted Lean models and audit required proof dependencies.
- Run mandatory native checks and trace conformance tests against that baseline.
- Publish current evidence, unresolved assumptions, coverage and limitations.
- Regenerate the navigable browser from the same manifest.
- Mark a task blocked/failed when required evidence is absent, stale, inconclusive
  or contradictory. Never mark it done or ship it with unresolved mandatory drift.

A code change does not necessarily require a domain change, or vice versa.
Record a reasoned impact decision for affected artefacts that remain unchanged.
The definition of done is a coherent, traceable and verified baseline, not just
compiling source or a plausible natural-language explanation.

D.13 References and limitations

This addendum specifies a proposed architecture and demonstrates the mapping and behavioural-checking approach. It is not a delivered implementation of the profiler, extractor, semantic exporter, HTML browser or gate. The Odin and Lean snippets have been reviewed against their documented features but not executed through their compilers in the authoring environment. The graphics example is a deliberately restricted model, not an assertion about an actual GPU API or the reader's application. Its assumptions and unsupported cases are explicit. The RDF and query syntax can be checked independently of the native compilers; see the accompanying revision notes for the checks actually performed.

Authoring checks: Both Turtle blocks parsed successfully with RDFLib, both navigation queries and the embedded SHACL SPARQL query passed syntax parsing, and the JSON Lines records parsed successfully. SHACL validation and SPARQL query execution were not run; Lean and Odin compilers were unavailable.