HoldFast first supported release
See the language reference for prototype support, the delivery plan for implementation, and the VerifiedOS requirements register for platform admission.
Release boundary
This contract defines what the first supported release must deliver. It
requires one retained compiler route for a bounded,
synchronous subset with explicit machine representations,
records and finite tagged sums, generics, stable dependent lengths and states,
exhaustive matching, Option/Result, bounded loops, shared and exclusive loans,
ownership transfer, resource-aware exits, closed effects and checked contracts.
The resource interpretation governs permissions and disposal for unrestricted,
affine, relevant-verdict and linear-obligation cases alongside
graded dependent typing. Public interfaces fix
representations, required-static inputs, effects and resource contracts.
Local inference preserves them.
Ordinary +, - and * require representable results. The checker handles
linear facts. Nonlinear facts need explicit proof or a named operation with
the intended failure, wrapping or saturation rule. Primitive semantics
Runtime calls have closed effects, explicit at exports and inferable for
eligible helpers. Implicit ref receivers allow
argument evaluation to read the receiver before exclusive access.
Two-phase borrowing
Iteration-local loans end at each iteration boundary. Ordinary checking
supports lending and spatial separation.
Loop resources · Loan checking
Specifications and proofs use kernel-admitted mathematical definitions and libraries. Runtime representation and executable type conversion require separate admission. Each tool defines its supported subset independently of the release. Mathematical prototype · Pure prototype · Surface parser
Language laws apply to the elaborated image in an existing semantic anchor. Located syntax and binding and resource derivations feed checked interpretation and source correspondence. The kernel checks the interpretation and laws for the exact source closure. Typing the generated term leaves separate obligations for source meaning, concrete CHERI laws, representation, lowering, final bytes and admission. Untrusted-elaboration boundary
The first client uses caller-supplied storage and the synchronous core. Later bounded pools require an actual allocator, manifest, exhaustion and reuse proofs. Heap allocation and boxing are explicit. Arbitrary grade domains, runtime multi-shot or shallow handlers, general reflection and generation, concurrent interior mutation, native self-hosting, ISA replacement and hardware authorship are outside the initial boundary. Async and one-shot capture need a separately accepted client and resource and lowering slice.
An extension needs a named client, comparison with the supported subset, an implementation and qualification budget and a decision predicate. General domains and grade-directed tools follow the graded selection protocol.
Default graded checking
Ordinary elaboration reconstructs computation demand and exact type-use rows,
including later declarations' dependencies. NatExact requires demand equal
to its allowance and NatBound requires demand within it. Dependent functions,
applications, graded boxes and indexed records carry demand through
substitution and checked motives. Each derivation binds the resolved source
closure. Invalid allowances fail, and failed reconstruction or replay leaves
an unresolved obligation.
Graded rules and evidence
Calls preserve evaluation order, effects and exits even for unused arguments. Repeated uses read the result of one evaluation. Erasure and admission require interpretation and representation laws. Loan rules govern read, write and restoration authority. Resource and computation interface
Default borrow checking
Ordinary elaboration infers path-specific ends and proves symbolic separation in owner coordinates. A disjoint write can coexist with a live view across joins and inside bounded loops with checked footprints. Bounded lending proves element loan lifetime, restoration and loop and exit invariants. Unresolved overlap or restoration yields a located obligation. Borrow-analysis promotion
Compare direct acceptance against the pinned Rust modes and implemented Ante subset. Record passing rewrites and their runtime checks. Test conditional returns, lending iteration and generic composition with matched behavior and evidence endpoints. Precision claims cover the tested workload. Borrowing comparison
Primitive semantics
Constant evaluation, runtime code and all assurance presets share these rules. The target determines runtime representations. Its bridge must prove the binding to explicit conversions, total ordinary arithmetic and named modular and saturating operations. Integer policy
| Surface or operation | First-release meaning |
|---|---|
bool, Unit |
Exactly false/true, and the single unit value (). Integers have no truthiness conversion. |
u8, u16, u32, u64; i8, i16, i32, i64 |
Unsigned values range from zero to 2^w - 1; signed values range from -2^(w-1) to 2^(w-1) - 1. Bitwise signed representation is two's complement. byte is an alias for u8. |
usize |
Unsigned index/count arithmetic at the target's declared XLEN width. This is not a capability's representation, permission to address all values of that width, or a pointer/integer conversion. Target specialization fixes the width and its representability obligations. |
Mathematical Nat and integers |
Specification/static values with their mathematical operations. Runtime use needs a selected finite representation and a proved range relation; there is no implicit arbitrary-precision runtime. |
| Integer literals | Decimal, binary and hexadecimal digits with the separator rules denote exact mathematical magnitudes. A suffix or expected type determines the representation; an unconstrained runtime literal needs an annotation. No machine-default integer type is guessed. A syntactic negative integer literal is checked as one signed value, admitting the signed minimum; negation of an already typed expression obeys the ordinary range rule. An out-of-range literal is a compile-time error. |
Ordinary +, -, * and unary - |
Exact mathematical result with a proof that it is representable in the result type. Failure to discharge the premise is an unresolved obligation, not wrapping, trapping or a debug/release distinction. Operands have one explicitly determined type. |
Ordinary / and % |
Both require a nonzero divisor. The mathematical quotient q truncates toward zero. The remainder r = a - q*b has magnitude less than abs(b) and, when nonzero, the sign of a. / also requires q to fit in the result type. This excludes signed MIN / -1. Signed MIN % -1 is zero. |
| Checked arithmetic | CheckedAdd, CheckedSub, CheckedMul, CheckedNeg, CheckedDiv and CheckedRem return Result<T, ArithmeticError>. Success returns the exact value in Ok. Failure returns Err(Overflow) or Err(ZeroDivisor) and preserves the inputs. Division checks the divisor for zero first. CheckedRem(MIN, -1) returns Ok(0). |
| Modular and saturating arithmetic | Named WrappingAdd, WrappingSub, WrappingMul and WrappingNeg reduce modulo 2^w, interpreting the resulting bits as the selected signed/unsigned type. SaturatingAdd, SaturatingSub, SaturatingMul and SaturatingNeg clamp the exact result to that type's minimum/maximum. There is no implicit modular conversion and no wrapping division/remainder in this initial vocabulary. |
| Bitwise operations and shifts | Bitwise operations use the selected w bits. Named ShiftLeft and ShiftRight take a usize count and require count < w; no implicit masking of excessive counts. Numeric left shift additionally requires the mathematical result to fit. Explicit WrappingShiftLeft discards high bits but retains the count bound. Right shift is zero-filling for unsigned and sign-extending for signed values, equivalent to floor division by 2^count. CheckedShiftLeft and CheckedShiftRight return InvalidShift for an excessive count; the former returns Overflow for numeric left-shift range failure. |
| Conversions and comparisons | Infallibly wider scalar conversion uses T.From(x) (such as i64.From(x) from i32); range- or sign-checked conversion uses T.TryFrom(x) (such as usize.TryFrom(x) from i32) and returns a named range failure; a proved conversion requires its range premise. Explicit truncation/reinterpretation uses a separately named bit operation. Ordering compares mathematical values within one type. Executable equality is Boolean through a selected decidable operation; proposition equality and transport stay in proof/contract interpretation. |
| Layout and encoding | Scalar representation/alignment is fixed by the target/ABI. Integer-to-byte encoding uses explicitly named little- or big-endian library operations; native record layout and padding never define a wire format. Capability fabrication and implicit pointer/integer conversion remain excluded. |
| Floating point | Not in this initial runtime release. A future consumer must select formats, NaN/signed-zero/rounding and exception behavior, equality/ordering, constant evaluation and target correspondence together. Parser recognition or existing hardware floating-point instructions supply no HoldFast support claim. |
e-means is a deferred research candidate with separate consumer and arithmetic
qualification. Numerical workloads
Use integer types directly without standard alias imports, a prelude, defaults
or import-order precedence. Intrinsics live under HoldFast.Numerics, as in
HoldFast.Numerics.WrappingAdd. Named operations need implementations and
checked laws. Generic overloading preserves primitive meanings and explicit
conversions. Establish bounds by proof or checked APIs.
Contextual inference
Omit an annotation when the declaration and context determine it. Expected
types can fix literal representations, generic arguments, lambda parameters
and stable dependent indices. Range bounds share one representation.
0..buffer.Length infers usize from its upper bound. A conflicting suffix or
annotation fails, and typed operands keep their type. Annotate ambiguous
runtime widths, including an unconstrained let count = 0;.
In the packet validator, let magic = pkt[0]; selects a usize index and
magic != 0x56 a byte literal. C lowering uses the checked syntax snapshot,
literal widths and resolved declaration sites for ordinary calls. It rejects
mismatched source bytes or syntax before emission. Explicit and inferred forms
produce identical Gallina and packet C apart from the source digest.
Packet validator
Inference preserves stability, representation, coherence, authority, value types, ownership transfers and proof obligations. Public signatures retain reviewed representations, static inputs, modes, effects and exits. Compare explicit and inferred clients at the same interpretation and artifact endpoint with boundary literals, ambiguity, wrong widths, unstable indices and stale sources. The pure and mathematical prototypes have their own scalar support. Represented inference requires checking beyond parsing machine literals and loops.
Bytes and text
Source is strict UTF-8 with ASCII identifiers. char has a checked finite
representation for one Unicode scalar (U+0000 through U+10FFFF, excluding
surrogates). Strings denote exact UTF-8 bytes without normalization, termination
or implicit allocation. Embedded U+0000 is an ordinary scalar. Escapes are
\\, \", \', \n, \r, \t, \0 and \u{H...} with one to six
hex digits for a scalar. Reject unknown, malformed or non-scalar escapes and
invalid UTF-8. A character literal decodes to exactly one scalar.
Raw strings use matching runs of at least three double quotes and process no escapes. Single-line strings allow no line breaks. Multiline strings start with a newline and end at a delimiter on its own optionally indented line. Strip that line's horizontal indentation from every nonempty content line and reject shorter indentation. Omit the opening and final newlines and normalize interior line breaks to LF. Use buffers and explicit encoders for raw bytes.
Decoding returns an immutable UTF-8 view with represented byte extent and a validity proof, or a typed encoding error. Ordinary loan rules preserve ownership and input lifetime and exclude mutable byte aliases to the live view.
.ByteLength counts bytes and bounded ScalarCount counts scalars. Use the
byte view, scalar iteration or checked slices at UTF-8 boundaries. Equality
compares exact bytes, so different encodings can differ despite canonical
equivalence. Normalization, locale collation, grapheme segmentation and
display-cell measurement need separate library rules. Literal backing is
read-only and counts toward the image. Runtime text requires explicit bounded
storage, validation and capacity outcomes.
Interpolation such as builder.Write($"...") writes to a
ref TextBuilder<capacity> or ref Span<byte>. Holes resolve static
IFormat<T> implementations and {value:spec} checks the format at compile
time. The call returns Result<usize, CapacityError> without reflection,
boxing or ambient locale. Each hole evaluates once from left to right under
the destination loan before the capacity check. On Err(CapacityError), the
builder keeps its old length and bytes, and effects from evaluating holes
remain observable. The span overload specifies rollback or prefix retention.
Modules and packages
The module boundary must support two independently authored libraries before public generic APIs qualify. A package manifest names its canonical package, language edition, module roots, direct dependencies, explicit build inputs and target/profile. A lock records each resolved package's exact source digest, selected version/revision, transitive closure, generator/tool identities and configuration. Locked builds neither resolve a different version nor read undeclared ambient inputs. Fetching dependencies is an explicit preparation operation; missing locked inputs produce an incomplete-build result.
The mathematical batch target builds this closure from local package revisions and binds its generated Gallina bundle to the exact lockfile. Locked mathematical packages
Each linked closure selects one revision per canonical package and one owner per module path. Incompatible dependency requirements fail resolution. Aliases change local spellings after resolution. Two revisions can be built in separate closures. The mathematical package checker enforces module-path uniqueness and reports both source digests on a collision.
The initial import graph is acyclic and imports are explicit. Cycles report the
cycle rather than depending on traversal order. Modules have no runtime
initializers. Required-static initialization evaluates ordinary total pure
definitions: each required-static input must resolve to an admissible closed
value when its use is specialized, or the build reports a located obligation or
refusal with no runtime fallback. const declarations
spell the interface, and the core's staging rules
bound conversion and erasure.
A plain import Module.Path; introduces the namespace Path. Use
Path.Operation(...) to call an export. import Module.Path as M; introduces
the explicit namespace alias M. import Module.Path { State, Busy as Occupied };
brings just those selected declarations into scope. Constructors retain their
nominal identity under an uppercase alias. If two module paths end with the
same name, give at least one an explicit namespace alias. All locked packages
use the math-2 edition.
Qualified names resolve independently of import order. Duplicate local/imported
bindings are errors unless an explicit alias distinguishes them. A public nominal
identity comprises the resolved package instance, module path and declaration
identity. Two package revisions with the same printed type name are distinct;
neither structural similarity nor reflection can equate their private types.
Interface constraints and dispatch
The interface implementation model uses explicit nonoverlapping
instances. The defining package must own the interface or the outer
nominal implementing type. A bare type parameter does not establish ownership;
foreign interfaces on foreign primitive types require a local nominal wrapper.
Instance heads use nominal type constructors, rigid constants and type
parameters, with structural unification deciding possible overlap. Arbitrary
computed type families and proof search are unavailable in instance selection.
Potentially overlapping instances are rejected without specialization, priority,
negative bounds or import-dependent choice. The implementing type This is
implicit in interface declarations and supplied first (impl Target : Interface).
A generic declaration requests each interface implementation
with a bound on that type, such as where T : ISized. Each bound supplies
a checked dictionary, including the declared contracts and required laws.
Constraint syntax
Call through the implementing type, as in T.Size(in value), or use a receiver
call, as in value.Size(). A receiver supplies the first method argument and
uses its declared loan mode.
Generic dispatch uses the bounds on the implementing type. Concrete dispatch
uses the implementations available for that type. The implementing type,
method name and source argument count must select a unique interface. When
several bounds provide the same method, a helper with one bound can select the
intended interface. The selected method's ordinary type, instance, loan and
contract checks apply.
Exported signatures
Public signatures specify generic and required-static parameters, result types, effects, call modes, transitive capture constraints, pre/postconditions and resource exits. Private representations stay abstract except through explicit published views or derivation interfaces. Implementation changes must re-establish the exported contract. An interface fingerprint binds these semantic declarations, the nominal identities and any exposed representation/ABI; source maps have a separate exact-byte identity. Dependency records also include implementation and proof bodies actually consumed, accepted assumptions, target and tools. An equal interface fingerprint alone cannot reuse stale compilation or proof evidence. Until finer dependency tracking is qualified, a semantic dependency change invalidates the reachable component closure conservatively.
Package effect contracts
File-private functions, package-internal functions and private record methods
can omit ~> and infer their effect bounds. The checker collects reads and
writes on caller-visible places and composes the closed footprints of the functions and methods the
body invokes. At each call it maps the receiver and parameters to the actual
places. A write counts even if the helper restores the original value. A
sibling module can use the inferred footprint of an internal function in
the same locked package instance. Concrete interface calls and implicit
scope-exit cleanup contribute the selected implementation's checked effects.
An opaque implementation needs a published footprint for a closed caller.
A helper that invokes its action parameter infers calls(action).
Forwarding that parameter to another helper that invokes it has the same
effect. Passing it to a helper that ignores it adds no call. At the outer
call site, a checked pure callback contributes an empty footprint, and a named
effectful callback retains its resolved identity. A scalar forwarding lambda
such as x => Visit(x) has the same call effect as Visit when invoked.
Callable fields retain the receiver they belong to. These three functions
share one authored bound.
private u32 Apply(Fn(u32 value) -> u32 action, u32 x) => action(x);
private u32 Forward(u32 x, Fn(u32 value) -> u32 f) => Apply(f, x);
public u32 Run(Fn(u32 value) -> u32 visit, u32 x) ~> calls(visit) => Forward(x, visit);
A structurally recursive helper can infer its footprint when self-calls forward the same effect-bearing arguments. Ordinary by-value scalars can change, including the decreasing argument. A self-call that remaps loans or callbacks, or occurs inside a local confinement block, needs a declared bound that covers the recursive call at its actual arguments. Invoking a returned callable requires a checked footprint for that invocation.
Each exported runtime callable publishes a closed bound. A free function
declares its own, including ~> none for an empty bound. A record can supply
a shared default for its runtime methods. After the record's name and fields,
write ~> none, a named effect set, ~> reads(this), or ~> writes(this).
A method's own clause overrides the default. The checker verifies each body
against its applicable bound. An inherited receiver write requires the same
mutable receiver view as an explicit write.
public record Counter(u32 Value) ~> reads(this)
{
public u32 Peek() => Value;
public bool IsZero() => Value == 0u32;
public u32 Limit() ~> none => 100u32;
}
Here Peek and IsZero share the receiver read. Limit publishes an empty
bound. An exported method publishes the full inherited bound. For a private
method, the checker enforces the default and infers the narrower footprint of
the body for its callers. The release checker currently refuses runtime methods
implementing an exported interface, because the frontend cannot publish their bounds
across packages. A private spelling on the instance or method still allows
dispatch through the exported interface. Helpers implementing private
interfaces can use their checked local footprints.
Named effect sets (effect Name = calls(F) | ... canceled by calls(Wrapper);),
negative prohibitions (!reads(...), !writes(...), !calls(...), !EffectSet),
and local confinement blocks (effect (...) { ... }) let modules encapsulate
raw primitives behind vetted wrappers without disabling closed package checks.
An optional [policy] table in holdfast-package.toml (forbid_calls,
forbid_effects, require_explicit_effects) is bound into the lockfile and
enforced across public callables at package build time, including public
record methods on types with private names. Within a package, a prohibition
follows helper and callback invocations, including a named call whose own
footprint is empty. A canceling wrapper covers the paths that pass through it.
Importing clients check calls
against the published bound with the implementation opaque. Calls use the
resolved declaration and parameter identities under qualified names and import
aliases. The footprint rules define propagation to
caller places.
Run holdfast-parser check-release-effects WORKSPACE LOCK to check mandatory
export bounds and emit the source, lock, and Gallina-bound effect receipt for
the locked closure. The check replays the generated Gallina in Rocq and reports
available standalone C11 lowering. Runtime call edges use checked callee
identities, so calls confined to contracts and inline proofs stay out of the
runtime graph. Pass --bundle FILE to atomically publish the replayed Gallina
modules and their effect receipt together. The checker rechecks the locked
inputs after replay before returning a receipt, verifying a saved receipt or
publishing a bundle. Pass the saved JSON with --receipt FILE
to recheck it against the current closure. A stale lock, a receipt from a
different lock, or a changed correspondence refuses. Use --no-rocq to generate
or recheck a development receipt that records the skipped replay. Bundle
publication requires Rocq replay.
With no package arguments, check-release-effects runs the qualification
cases. It checks every public runtime effect bound in the full copy service
and the footprint inferred for a helper that forwards a call to the service
from a separate locked package. Running the qualifier with --no-rocq
still prints the development evidence and exits with status 1 because
qualification requires kernel replay.
Copy-service effect evidence
Public API evolution
Adding a case to a public closed union can break downstream exhaustive matches; adding a public export can make an existing open import ambiguous. Adding a required interface method or law changes the obligations of existing instances. Parameter labels, required-static status, grades, capture and effect bounds, and public representation participate in compatibility alongside parameter/result types. An upgrade that strengthens a precondition or weakens a postcondition can invalidate callers and their proofs. An upgrade that widens a published effect bound can invalidate callers whose own bounds no longer cover it. A helper refactor whose effects fit the existing published bound preserves that part of the interface and still requires fresh evidence for the changed locked inputs. A release must identify interface changes, version breaking changes accordingly, and supply a migration or retain an adapter where the prior interface can still be implemented. An API intended to admit new internal cases can expose an abstract type with stable eliminators.
Run holdfast-parser diff-contract BASELINE CANDIDATE to review the authored
changes to one module (add --human for a plain-text PR audit summary). The JSON
report binds both source digests and lists added and removed public declarations,
changed declaration fields, changes to imports and implementation declarations that
can affect resolution, and a review_summary highlighting risk flags (such as
changed preconditions/postconditions, dropped ! prohibitions, and modified effect
sets). It compares syntax without source locations or comments. It includes
contracts and effect clauses and retains transparent definition bodies. It omits
top-level executable function and theorem/lemma bodies. The comparison treats
changes to binder spelling and equivalent expressions as differences and gives
no semantic compatibility, kernel assumption or runtime permission verdict.
The local client replay command keeps client and dependency sources fixed and elaborates both revisions, including exhaustiveness and proof obligations exercised by those clients. Release qualification also requires its kernel, ABI and target-specific evidence.
Public standard library
The first systems release must ship the following operations and their public laws in versioned packages. A caller must be able to use them with explicit imports, caller-supplied storage and the synchronous release profile. The hosted profile defines the corresponding services that require an allocator or a host.
| Family | Minimum public operations and guarantees |
|---|---|
| Values and ranges | Transform the value in Some or Ok, passing None or the original error through unchanged. Supply half-open index ranges, containment, intersection and length. Empty ranges have length zero. Provide minimum, maximum and comparison under a declared total order. |
| Numbers, bytes and text | Supply the checked arithmetic and conversions, fixed-width reads and writes in both byte orders, UTF-8 validation, scalar-boundary slicing and bounded formatting. A short destination for a fixed-width write retains its bytes. |
| Sequences | Borrow a span, take a checked subspan, split at a valid index, iterate, find the first match, and test whether any or all elements match. Visit elements in order and stop at the first decisive result. On empty input, find returns absence, any returns false and all returns true. Sequence models and iteration |
| Bounded collections | Provide a vector with indexed access, append and pop, a ring FIFO with enqueue, front and dequeue, a map with lookup, insert-or-replace and removal, and a set with membership, insertion and removal. Specify each through its logical sequence, bindings or members. |
| Ordering and search | Sort a mutable span in place and binary-search a sorted read-only span using the same pure comparison. Publish the order, permutation, membership and index laws described below. |
Collection capacity counts entries. Popping an empty vector or dequeuing an empty FIFO returns absence. Wrapping the FIFO's indices preserves arrival order. A map and set use their declared key equality for every operation. Replacing an existing binding returns its old value, and inserting an existing set member succeeds with membership unchanged, even at full capacity. Inserting a new entry into a full collection reports exhaustion and preserves its contents. Each exit accounts for moved arguments, displaced values and the caller's backing. A borrowed element stays tied to its owner. An operation that could move or invalidate it requires the conflicting loan to have ended. Ownership libraries · Relocation laws
Sorting preserves every complete element and its multiplicity, including payloads and their relative order among equal keys. On a span sorted by the selected comparison, lower bound returns a cut between zero and the length, inclusive. Keys before the cut compare strictly less than the query and keys from the cut onward compare greater than or equal to it. Binary search returns the cut if it points to an equal key, and absence otherwise. This gives the first equal index for duplicates and proves that every key compares unequal on a miss. An empty span has cut zero. Publish worst-case comparison counts and scratch bounds for sorting and searching. Both searches use logarithmically many comparisons and constant auxiliary storage. Specify collection costs in terms of live entries, capacity and element operations.
Ship importable lemmas for range bounds, slice length and indexing, traversal prefixes, membership after insertion or removal, sortedness and permutation. An independently authored package must be able to sort records, look up a duplicate key and establish absence after a miss using only the exported contracts and lemmas. Replay that caller after a private representation change. Weakening the search contract to an arbitrary equal key must leave the first-index claim unproved. Caller proof qualification
Ownership libraries
The first clients use proved buffers, spans, bounded iterators, initialized storage, and typed errors. Library contracts state capacity, bounds, overlap, initialization, loans, and the resources returned on each exit.
Sequence models and iteration
A sequence-modeled buffer or view implements ISequenceModel<C, T> with an
erased Model : Seq<T> and a law Nat(Length) == Model.Count. Contracts use
predicates such as requires items.Model.All(x => x > 0), backed by proved
sequence lemmas and the bounded refinement rules.
Codecs must establish the intended format and meet the
initialization requirement.
Collection loops
use IBoundedIterable<C, T>, which refines ISequenceModel<C, T> with a
stable iteration footprint and access and restoration laws. The collection
expression evaluates once. Value iteration requires copy permission.
in and ref lend each element. The laws relate step k to
Model.At(k), the processed prefix Model.Take(k), and the remaining suffix
Model.Skip(k). Every exit returns or restores its promised resources. The
loop uses no runtime enumerator allocation or implicit disposal.
The mathematical prototype checks selected collection loops, including
symbolic lending over Span<byte>.
Release qualification also requires the represented iterator and its lowering
laws.
For a selected client needing paired iteration or reductions, qualify reusable laws for the corresponding pairwise, zip, or fold operation before extending the supported library. Relate the traversed extent (including unequal lengths), paired elements and accumulated result to the input models, and relate any writeback to the processed prefix and untouched suffix. The laws carry restoration and the frame across each step and every exit. A transparent total pure callback can supply its result relation without a repeated authored contract when reconstruction succeeds. Opaque callbacks still need public contracts. Represented operations require evidence for traversal counts, access authority and representation costs; a short mathematical proof does not establish a fused pass or in-place update.
The streaming checksum example models
the accepted bytes as the ordered concatenation of each borrowed chunk's
Model. The Rocq model proves that
feeding any partition, including empty chunks, gives the same checksum as
feeding the concatenated bytes, and that the state still represents the
accepted history. The emitted function carries a single checksum byte
between calls. The behavioral checks
replay the source in Rocq, compare emitted C across a proof-only change, and
run the function against an independent oracle. The partition theorem concerns
the Rocq model, and the native checks exercise the emitted function over a
bounded input corpus.
Bounded paired sort
The paired sort example uses two disjoint
byte spans as keys and payloads. It sorts up to three pairs by exchanging the
two keys and their payloads together. The checked swap specifies all four
byte updates. Unequal lengths or more than three entries return false with
both spans unchanged. The
Rocq model proves key order and permutation
of whole pairs for every admitted length, including repeated keys and pairs.
The native oracle exercises
those observations on emitted C. A key-only mutant still sorts the keys and
fails the pair-preservation control.
Initialization and fallible builders
An out T loan allows the callee to initialize caller-supplied storage. Every
normal return, including Err or propagation with ?, must leave that
storage fully initialized. Reads require prior initialization. Use a
Result<T, E> factory when the caller supplies no storage.
A fallible builder takes ownership of storage. Each outcome returns a
completed value, a retained initialized prefix, or empty storage restored
by rollback. Its type and contract identify the entries
available to read or dispose of and what happens to every unconsumed resource.
Whole-buffer initialization and zeroization follow the boundary contract.
The elaboration replay checks a
fallible byte update with arbitrary entry bytes. Success writes the requested
byte, failure restores it, and both paths preserve the frame.
Bytes and text defines the write and capacity contract for
TextBuilder<capacity> and spans.
Exercise pre-write failure, partial failure, completion, and rollback with
unrelated storage still live. Multi-step updates can declare named invariant
conjuncts and open only the ones they affect with
open (ref this) lifts Clause, ... { ... }. Unlifted conjuncts remain in
force. The block must restore every lifted conjunct before it can exit. It
cannot return, propagate, break, continue, suspend, capture, or call on the
whole receiver while those clauses are open.
Invariant lifting
For a selected packed-bitset client, keep the fixed domain and backing extent stable while changing membership. Lift only mutable invariant clauses needing temporary suspension, and restore them at the close of their lifting scope. Each nested loan must satisfy its own restoration contract. A mutable iterator does not waive the padding invariant or grant access to a suspended owner. The optional packed-bitset qualification trial exercises these laws and the paired-iteration and reduction contracts without adding a first-release acceptance gate.
Relocation and storage reuse
Slots.Disjoint compares the buffers' full capacity extents as half-open
ranges. An empty extent is disjoint from every
extent, including one that contains its base. For two nonempty extents, the
one with the lower base must end at or before the other base. The C11
predicate compares their base distance with the lower extent's capacity, so
the decision also works at the last usize address.
Slot law · Lowered slot and span cases
Relocating an initialized prefix between Slots<T, capacity> buffers takes
two steps within one checked method.
CopyRepresentationcopies the CHERI representation of[0..count)into logically vacant slots and establishes representation equality for the current revisions. This creates no second live owner and runs no destructors.TransferType<T>transfers the logical ownership of the prefix in one erased range step. The source becomes vacant and the destination becomes live and initialized.
The element relocation law must preserve the destination invariant and account
for references to the old address, such as interior pointers, pinning, or DMA
grants. The derived law covers fixed-width integers, bool, char, Unit,
and closed non-dependent records, wrappers, unions, and tuples whose
components can cross modes. Authority-bearing types, loans, cells, and
unconstrained generics need a separate law. The
element-loan regression
rejects relocation with a live loan of the first slot. Copying its u32 value
into a local first lets the loan end before relocation.
Storage has explicit capacity and cleanup. A bounded pool must establish quiescence and safe reuse before granting the backing again. Its trial rejects reclaiming scratch storage while a list refers into it and accepts copying the data to the list's own backing before ending the scratch loan and reusing the storage. Bounded-pool milestone · R-08-046 · Arena rollback comparison
Scoped cleanup and receiver calls
using let h = init; keeps h in scope for the rest of the enclosing block.
using (let h = init) { ... } limits it to the braced body. When control
leaves the scope, each successfully initialized resource is passed to
IDispose.Dispose(in h) -> Unit in reverse declaration order. The cleanup
requires no dynamic allocation.
Scoped disposal
For either spelling, the source loan graph demands each established resource at cleanup on fallthrough, early return and propagation. When a nested initializer propagates failure, only the enclosing resources are live for disposal. A shared loan used by the disposer keeps the owner unavailable for writing until the cleanup runs. Both spellings contribute the disposer's transitive calls to the enclosing function's effect check. Loan, effect and kernel replay
Two-phase receiver borrowing
allows buf.Update(buf.ReadCount()). A named-view interface can let callers
keep a shared Count loan during an exclusive Data call when the provider
establishes disjointness. Replay that client across package boundaries after
changing the private layout.
Receiver qualification
Authoring idioms
See language reference, authoring style, and checked code actions. Unwrap before member access via (Read()?).Value or match.
Qualification
The first release requires separate evidence for the packet validator and the independent copy-service client. Freeze each client's format, entry states and expected outcomes before implementing its HoldFast version. Delivery plan
| Subject | Acceptance evidence |
|---|---|
| Interpretation and concrete resources | Checked elaboration-image laws, inhabited carrier state, read/write/init/frame/restoration; wrong-offset, alias, premature-restoration, and partial-init neighbors rejected at intended rules (no axiom/source substitutes for missing laws). |
| Scalar and text behavior | Independent boundary fixtures for all types/ops: signed div/rem signs, 0 and MIN/-1, shift 0/width-1/width, exact/wrapping/saturating ops, target vs host width, invalid conversions, embedded NUL, malformed UTF-8/escapes, raw-string delimiter/indent/LF rules, static IFormat<T> formatting (Result<usize, CapacityError> on exact fit and exhaustion without heap/locale), scalar boundaries, and byte slicing (generated from independent oracle). |
| Package composition | Two independent packages compose with fixed instances; import reordering preserves meaning; overlap, cycles, and conflicting nominal IDs diagnosed; locked builds reproduce closures; contract/rep/assumption/tool edits invalidate stale evidence. |
| Graded dependent typing | Default build checks NatExact/NatBound, substitution, box/indexed-record elimination, and separate type/computation demands on a reviewed client; bad allowances, altered motives, and stale deps fail at obligations; ordered evaluation and erasure verified at representation endpoint (incl. zero/repeated args). Default graded checking |
| Borrowing precision | Default build checks proof-backed symbolic separation, conditional returns, and bounded lending; replays restoration/frame per exit; pairs positives and negatives on held-out clients; records unsupported cases, exhausted budgets, and checking cost. Default borrow checking |
| Everyday ownership | Bounded collection/iterator, .Model predicates/slices, TextBuilder<capacity>/IFormat<T>, two-phase receiver calls, invariant Clause: ... / open (...) lifts ..., CopyRepresentation + TransferType<T>, fallible-builder, and ? clients pass under actual reps and borrow promotion (failing escaped views, duplicated tokens, unwritten/vacant reads, early exits/whole calls under lifted clauses, stale content facts, lost verdicts). Bounded buffer/builder/relocation proofs pass a capacity-invariance gate: identical obligation counts and proof/certificate structure at $N = 4$ and $N = 10^9$ (8 and 10⁹ in first-slice pilot) modulo capacity literal, zero per-element unfolding, fitting 4 MiB Gallina and 120 s per-compile/combined replay (reporting actual timings separately). |
| Complete software path | Source and independent contract reach retained backend with checked correspondence, representation, and lowering; final-byte, resource, observation, and admission duties meet owners (source, artifact, production evidence reported separately). |
| Developer usefulness | Measure annotation burden, first useful diagnostic, latency, code/stack/storage impact, and repair cost across preserving refactors, rep changes, and contract changes on both clients (counting arithmetic lemmas/checked ops, effect clauses edited, snapshots/views/loop rewrites, and receiver vs snapshot spellings). |
Both clients must meet their safety, resource, and admission limits. Record feasibility, recurring developer value, and adoption as separate decisions. Account for all setup and shared maintenance costs. Evaluate size and speed tradeoffs against the declared limits and evidence for each case.
First-slice component and concrete Span<byte> carrier
The packet validator copies the header and payload into the destination's eight-byte work area, zero-pads the remainder, and returns a read-only payload view on success. A framing refusal preserves the full destination. Other protocol failures clear the work area. Every exit preserves bytes beyond it. Validator source · Packet walkthrough
SpecPacketOutcome checks framing, header, payload length and checksum in
that order. The exported postcondition is
PacketOutcome(result) == SpecPacketOutcome(in old(dst), in pkt). It gives
callers the exact error or copied payload length from the entry state without
unfolding the validator.
At entry, ref dst and in pkt borrow valid descriptors with live provenance,
bounds, and permissions. The described byte extents may overlap. Framing checks
the metadata and rejects overlap before any backing-byte access. After framing,
the validator uses exclusive destination access and shared packet access. Success
transfers the destination view loan to the result. Ordinary calls follow the
core loan rules. Core loan rules
The scalar packet lowerer checks the public entry, result and error ABI before
emitting C. The destination is a ref tied to the returned view's region, the
packet is a shared in borrow, and ValidatedPacket carries an in view with
that region. The four payload-free error cases have fixed discriminants in
declaration order. Region parameter names can change without affecting the ABI.
Binary comparisons use checked scalar representations. Structural equality
and operators outside the supported packet subset refuse at lowering. Runtime
bindings need distinct names within each lowered function. Lowering reports
the source location of a repeated name, including in sibling branches.
The generated C harness uses one backing array. Cursor and logical base start at the same offset and advance together when forming a slice. The harness checks the returned cursor and base independently, including for empty views, and checks that an overlap refusal preserves the full destination.
The mathematical Span<byte> carrier holds a store and five metadata fields
(Base, Length, Tag, PermRead, and PermWrite). Its operations check
bounds, representability of the exclusive end, permissions, loans, and
disjointness. Span.AllocZeroed supplies storage in specifications and theorems.
Loan restoration uses the immediate parent or its view-updated state. The
elaborator generates equalities that preserve all five metadata fields for each
eligible ref span parameter.
Mathematical elaboration
Foreign entry
The current C lowering takes the backing arena, writable result storage, the destination descriptor and the packet descriptor in that order. Each input descriptor stores the cursor, logical base, length, tag and permission fields as scalars. Backing accesses use the arena and the cursor. Framing compares the logical bases and lengths. The foreign entry proof must relate both computations to the same byte extents and caller loans, including representable ends and the required read and write authority. The packet descriptor is borrowed for reading. The caller supplies writable result space for initialization by the validator. Scalar lowering
Before the validator's first metadata read, the calling mechanism must
establish all four objects' live provenance, layout, bounds and required
permissions. Both descriptors must have initialized fields at their aligned
locations. The two descriptor objects, the result object and the backing arena
must be pairwise disjoint. This object separation permits the described packet
and destination extents within the arena to overlap and reach FramingShort.
Short extents with otherwise valid descriptors also reach that refusal.
Deployed entry evidence ·
Foreign entry qualification
For the layout where each descriptor's cursor equals its logical base, the Rocq model relates logical disjointness to disjoint backing bytes at a common arena origin. The model derives aligned, in-bounds access to all six scalar fields from abstract live read authority, 40-byte object bounds and 36 initialized bytes. Its controls exercise valid short and overlapping spans, misbound extents, and a descriptor bound that excludes a required field. The protected-entry interface combines those laws with role-specific authority, bounds and alignment for the four objects. Its controls admit valid short and overlapping spans while refusing a truncated descriptor, aliased arguments, missing result write authority, or an uninitialized descriptor field byte. The deployed caller supplies concrete evidence for the interface's premises and binds the spans to values decoded from those descriptor objects. The installed linkage must restrict untrusted callers to the checked entry and keep the raw entry unreachable to them. Packet span layout
The guard-to-layout bridge derives the protected entry predicate and metadata and backing access laws from acceptance by the abstract entry guard, given decoded capability fields, 36-bit bounded object ends, initialized descriptor bytes and represented spans. Guard acceptance alone is insufficient: an accepted guard with uninitialized metadata does not satisfy the entry predicate. Machine decoding, initialization, span representation and installed linkage must still be established at the admitted image.
The layout proof derives all six pairwise object separations from the three
ordered guard comparisons when each object end stays within the modeled
36-bit address limit. The bound makes the guard's 64-bit end calculation
exact. The proof combines those structural checks with role permissions,
caller-initialized descriptor fields and represented spans to establish the
abstract entry premises. It also establishes writable, disjoint result-object
fields, returned-view bounds narrowing with read-only non-packet authority, and
the packet usize addition non-overflow bound, with controls refusing truncated
result bounds, writable or packet-origin returned views, writable packet
descriptors, misaligned or shifted cursors, and misordered objects. The concrete
caller and machine proofs must connect those facts to the checked instructions
and decoded descriptor bytes.
The development packet entry
uses a trusted local assembly caller to initialize the two descriptors,
derive four bounded argument capabilities, and invoke a sentry. The guard
checks tag, sealing, bounds, cursor, alignment, role permissions and pairwise
object separation before transferring to the compiled validator, and
verify_guard_elf checks the assembled guard and refusal words directly in the
linked ELF. The bounded Sail replay checks preceding descriptor writes,
the capability call and its matching return, and the exact scalar register
effects of each retired guard instruction. These include the observed tag,
sealing, base, cursor, bounds and permissions of every argument inspected on the
path, as well as the calculated object ends. The guard records zero memory
events. A 32-byte packet capability refuses before entry after the bound
comparison and returns through the original link. Legal short and overlapping
spans retire the full guard, reach the validator and freshly write FramingShort
without an arena access. These runs use the development compiler and a shared harness
PCC. Deployment still requires the installed call-site, capability wiring
and linkage evidence above.
Qualification and receipt binding
The receipt binding report publishes source_proof_audit with the retained
export and solver-trust counts, statement digest, and the classifier and
layout theorem lists and statement digests. A compiler-backed VerifiedOS
handoff binds this same audit under its packet replay entry.
Packet replay handoff
python tools/run.py holdfast-parser first-slice runs fresh proof and
execution checks. Qualification implementation
| Check | Evidence |
|---|---|
| Source proof | Menhir parse -> Gallina -> rocq c -> assumption audit (empty solver_trust for accepted) -> rocqchk; appended false equality must fail at target def. |
| Packet outcome and bytes | The classifier checks the opaque validator's error precedence, copied count, framing and protocol refusals, accepted view permissions, copied bytes and zero padding. A separate proof inspects the elaborated destination on every exit. Its base, length, tag and permission bits equal their original values. With the entry permissions, every originally in-bounds byte from offset eight onward keeps its value. The receipt binds all eight theorem statements. Classifier and destination proofs |
| Entry layout proof | rocq c and rocqchk check 19 abstract guard, descriptor, backing span, result-object, returned-view and usize non-overflow laws. The packet_span_layout receipt records the audited theorem names and statement digest. |
| Capacity and refusals | Equal proof structure and inference/reduction work at capacities 8 and 10⁹; negative fixtures parse without /*error*/ and fail at expected line/col/category/message. |
| Capability execution | Handwritten purecap checks 4-byte view has data-load permission only; Sail rejects writable-view variant, traps store through narrowed view, and reproduces bounds/tag traps. |
| Optional CompCert execution | Lower validator/drivers to Clight/C, run CompCert -interp and Sail purecap images across passing paths and mutated view origin/write-perm/payload/padding/checksum/clearing controls (--ccomp /abs/path/to/ccomp requires it; otherwise compcert_sail.available: false). Compiler build contract |
| Guest C11 regression | System C11 -O0/-O2 checks all 5 exits and verifies cursor, base, length, tag, permissions before payload reads (refusing input-pointing empty/4-byte cursors and writable views). |
| Inline proof erasure | Native regression adds assertion/proof to checksum, replays module, and verifies identical guest binaries at -O0/-O2 (false assertion fails elaboration). |
holdfast-parser check-packet-source-core checks the authored forms of the
four ordered branch predicates and their local inputs against the independent
classifier. It reports each condition's byte span and checks that the success
return uses payloadLen for the copied count and the read-only destination
slice at offset four. The projection records the slice and read-only
conversion source spans. The Rocq binding shows that each in-bounds view
read yields the copied packet byte and that reads outside the view's extent
yield no byte. It also checks that all four error exits return no view. The controls change
each predicate or the payload length binding, count, offset, extent or view
origin while preserving the result constructors.
The framing projection records the destination and packet length comparisons
and dst.Disjoint(pkt). The generated Rocq binding checks the source limits
and compares the decision against the reference framing test. Successful
framing gives disjoint backing bytes when both span descriptors represent
their ranges in the same arena. The deployed caller must establish those
representation premises. Foreign entry
The scrub projection binds the direct destination fill after the framing
guard, including its zero offset, eight-byte extent, and zero fill value.
The authored core's Rocq replay checks that protocol refusals zero the work
area and preserve the destination suffix in the model.
The authored core reads the magic and flags from packet offsets zero and
three and compares them with the checked source literals. Rocq checks that
both header reads are in bounds after framing succeeds and that either
mismatch selects BadMagicOrFlags.
The success-path copy projection reports the byte spans of the four ordered
header assignments and the borrowed payload helper call. It checks both
payload slices at offset four and a single copy of the checked length. The
controls change a header value or operator, duplicate an assignment, vary the
payload arguments or add a helper write while preserving the return.
Rocq also parses the exact authored scrub statement and four ordered header
assignments, comparing the parsed writes with the projected scrub and copy
operations. Header values resolve through the checked guard input offsets.
The binding retains all five statement spans and bytes. Rocq also parses all
five authored validator returns in non-overlapping source order. It checks
the four error constructors and the success result's copied count, explicit
shared borrow, slice offset and length, and read-only destination view against
the projection. The report records the five return statement spans and bytes.
Rocq also parses the complete checksum and payload-copy helper bodies and
their two call statements. The binding checks the seed, typed loop bound,
strict guard, XOR read and accumulator return, the two copy slices and their
aliases and count, and the two borrowed call modes and order. The report binds
both helper body spans and both invocation spans to their exact source bytes.
The declaration proof reads the complete error union and returned record and
the signatures of the validator and the two helpers. It checks the result
region, parameter modes and types, and declared effects. Across the three
functions, the bounded parser decodes 15 requirements on permissions, extents
and disjointness. It also recognizes the ten ordered guarantees of the
validator. In the span model, the validator's entry premises and successful
framing and length checks establish the requirements of both helper calls.
Whole-file parser correspondence and general erasure remain open.
The checksum helper projection checks the 0x5A ^ rawLen seed, the
0..4usize loop and its i < payloadLen guard, the single XOR update with
pkt[4 + i] and the accumulator return. The report records the authored
byte spans for these operations. The authored core computes the checksum from
the length byte and the selected payload prefix, then compares it with the
declared checksum byte. Its Rocq replay checks the prefix and the packet
extent required for each read. The independent classifier also proves that
the elaborated checksum helper returns its bounded XOR fold. Moving the
classifier's first payload read one byte forward fails that proof.
Packet source checker ·
Classifier correspondence
The generated binding executes the projected instructions on the same span and word types as the elaborated validator. For all input spans, Rocq checks equality of the full result and the destination after the call. This includes the view on success and the destination on each refusal. With the validator's entry permissions, the independent classifier identifies the outcome and copied count. Execution proof
The packet source-core audit compares a location-independent executable syntax projection before and after proof erasure for all four packet functions. It retains operators, operands, types, borrow modes, calls and control structure, while excluding specification clauses and pure inline proof statements. The generated binding records each function's projection digest. A neighboring source adds six pure proof statements across the four functions and preserves the projection and normalized C11; same-shape runtime expression changes are refused independently in each function. This checks the bounded packet projection, not parser correctness or arbitrary erasure correspondence.
python tools/run.py holdfast-parser first-slice-bindings <receipt.json>
checks a schema-2 receipt against the checkout and its tools. It regenerates
Gallina and C, reassembles controls, derives verdicts and error locations from
transcripts, checks proof exports, replay records, and CompCert inputs, and
compares regenerated C against the retained inventory. It checks the entire
foundation inventory against the checkout and the retained assumption ledger,
including the blocking producers and pending checks. For both the layout
proof and the packet classifier, it checks the proof sources, compiled objects,
audited theorem names, statement digests and kernel records.
Schema-2 lowering_provenance binds checked executable signatures, resolved
helper calls, source and operand spans, operand representations and C
expressions to the generated Gallina and C. packet_return_paths checks the
source span, result constructor and borrowed input at each result return
against checked control flow. The successful C return must slice the caller's
destination and clear its write permission. The four error paths carry no
borrowed result. The three partial usize addition
sites carry six audited word equations. Four cover the checksum loop's
represented indices. Each length comparison has an equation proved over every
byte widened to usize. These equations prove agreement with checked addition
for the modeled operands.
The local artifact inventory limit is 4,096 entries and 256 MiB. Missing or
substituted artifacts, contradictions, and changes during the run cause refusal.
Compiler-enabled receipts also check the entry and return observations for nine frozen inputs. The observer checks tagged argument registers, alignment of the descriptor and result objects, disjoint fixture storage including the 40-byte descriptor and 56-byte result objects, recorded descriptor and backing bytes, resource restoration, framing before byte access, and scalar view fields. Field initialization covers 36 descriptor bytes and 52 result bytes. Its controls cover malformed entry observations, including padding-only aliases, a redirected cursor, a writable returned view, and a tagged store to a result field. Exact-image proofs still owe entry capability validity and the returned-view authority relation for every admitted call. Packet observer
A binding match reports status: matched and proof_replayed: false.
missing_deployed_evidence lists the functional result, pre-metadata entry
descriptor validity and returned-view authority claims that still need
exact-image evidence. inventory.blocking_dependencies names the open
VerifiedOS prerequisites and the local validator obligations for machine
interpretation, byte and loan laws, the synchronous core, frontend
correspondence, compiler refinement, contextual preservation and admission.
Deployed evidence ·
Exact executable acceptance
For the VerifiedOS pilot, generate the receipt with first-slice --ccomp.
verifiedos-handoff --packet-receipt checks and records the resulting receipt
and derives the target tool identities from it. When a consumer at the same
pinned revision has different checkout or tool paths, export a portable bundle
with first-slice-bindings <receipt.json> --export-bundle <dir> or
verifiedos-handoff --verify <manifest.json> --export-bundle <dir>, then verify
the exported directory (passing --ccomp when the local compiler path differs).
Portable checks retain the producer revision, exact tool/image digests, and
proof_replayed: false, and do not substitute for explicit fresh or cold replay
when required.
VerifiedOS pilot replay
The packet observer checks each recorded read of the backing arena or either input descriptor against the preceding writes to those bytes. It also checks reads of result storage and requires those bytes to have been written during the call. A conflicting read value refuses qualification and binding even if the result and final memory agree with the caller's expectations. The observer requires reads of both descriptors' base and length fields before the first backing access. It refuses any write to the shared packet descriptor, including a write followed by restoration before return.
During each observed call, each read must fit within the live callee stack or within one argument. Each store must fit within the live stack or one writable argument. The live stack lies between the current tagged stack cursor and its entry cursor. Raising the cursor clears the observer's initialization and spill records for the released bytes. The call must write each live callee-frame byte before reading it. Scalar argument accesses carry an untagged memory value. The observer checks the bytes and tags of capability reloads against the preceding stores. An overlapping scalar store clears the spill tag even if it preserves all the bits. A capability store records the value and tag of its encoded source register. A capability load writes the recorded memory value and tag to its encoded destination register at the same retirement. Both accesses must report the aligned address formed by adding the signed instruction offset to the recorded tagged base register's cursor. Scalar loads and stores must record one memory event with the instruction's read or write direction, encoded width, and address computed from its tagged base and signed offset. A load into a nonzero register must write the sign-extended or zero-extended value with a cleared tag at the same retirement. A store must write the low bits of its encoded source register for that width. Return restores the tagged stack capability, including its recorded bits. The last retired instruction before the caller resumes must be the scalar ABI return through the original tagged sentry. The observer compares the sentry bits at entry, at that instruction and at caller resumption. Frame and call contract
Each frozen input also specifies the complete byte footprint. Framing refusals have empty backing footprints. Other exits read the expected header and payload bytes for their path and write all eight bytes of the destination work area. Qualification and binding require those byte sets even when omitted stores would leave the same final contents.