Skip to content

Layer 0 descriptors and the six capabilities

The three-layer capability architecture from Layer -1 programs through Layer 0 memory descriptors and rings to the six Layer 1 host capability tags.

When a Lema application talks to the outside world, it does not invoke ambient operating-system syscalls or link against unverified C networking libraries. Instead, external interaction is structured as a three-layer architecture (Layer -1 to Layer 0 to Layer 1) where every framing rule, journal format, cryptographic handshake, and recovery state machine stays inside kernel-checked Lema code.

For a conceptual introduction to why Lema keeps the host boundary small and byte-oriented, see Capabilities and The proved HTTPS stack.

The three-layer architecture

Rather than exposing high-level network or filesystem APIs directly to applications, Lema builds host interaction in three distinct layers:

LayerModules and implementationResponsibility
Layer -1: Program and resource coreCore, Handles, Tickets (audit/inputs/)Defines the parametric command tree Prog C R A, stateful protocol contracts Contract C R S, safety judgment Safe, derived single-owner linear 1-handles (Handles), and in-flight busy ticket locks (Tickets).
Layer 0: Memory domains, regions, and ringscrates/lema-cap/src/layer0.rs, Capability.leanProvides isolated per-domain byte heaps (Domain), capability-bounded byte slices (Region and Slice) with busy lock enforcement on in-flight ranges, a submission/completion queue (Ring) with synchronous Ring.call, and Clock / Random descriptors.
Layer 1: The six host capability tagsFrames, Capability (audit/inputs/), crates/lema-cap/Encodes six flat-byte host capability families (tcp, udp, block, random, clock, secret) over LC\x02 request and reply regions via Ring.call, plus the opaque exchange and serve sub-run families and concurrency runner families (tasks, actors, sessions).

Layer -1: Programs, linear handles, and ticket locks

At the foundation (The program core), a program Prog C R A is a pure mathematical decision tree that issues commands c : C and branches on replies R c. A protocol Contract C R S specifies when a command is legal in abstract state s : S (pre), how a reply advances the state (next), and what the environment promises about the reply (post).

Two companion modules in audit/inputs/ establish the resource invariants that Layer 0 and Layer 1 enforce at run time:

  • Derived single-owner linear 1-handles (Handles): Models open resources in a handle map Nat -> Option State. Its kernel-checked theorems (handleSafe_open, use_after_close, double_close) prove that a Safe program never reads, writes, or closes a handle that was not opened or has already been closed.
  • In-flight busy ticket locks (Tickets): Models asynchronous submissions that hold a lock on a resource until their completion ticket is awaited. Under Tickets’s pre and next rules, submitting an operation marks its target resource busy, refusing overlapping writes or reclaims until await consumes the completion. Crucially, cancel leaves the abstract state unchanged (.cancel _ => s): a cancelled ticket keeps its resource locked as busy until await confirms that the host’s access is over or fenced.

Layer 0: Domain, Region, Ring, Clock, and Random

Layer 0 (crates/lema-cap/src/layer0.rs and audit/view/cap/Capability.lean) provides the memory and queuing substrate that connects pure Lema programs to the host capability boundary.

Domain and SharedBudget

Each execution domain (Domain::new(id, heap)) owns a private region heap bounded by heap bytes (tracking used bytes) and a completion ring over its regions:

  • Cross-domain isolation: Every region identifier (RegionId { domain, index, generation }) binds the owning domain’s id and a monotonically incremented generation for that slot (generations[index]). Passing another domain’s RegionId to any read, write, slice, or reclaim operation is refused immediately with Refusal::Foreign.
  • Dynamic heap extension (SharedBudget and Lease): Multiple domains can draw from an atomic SharedBudget(Arc<AtomicUsize>). Calling budget.lease(bytes) atomically reserves bytes (Ordering::AcqRel) and returns a Lease; domain.attach(lease) extends domain.heap for the lifetime of the domain, and dropping the Lease automatically returns the bytes to the SharedBudget.

Region, Slice, and the busy lock

A Region is a contiguous byte allocation inside a Domain, accessed through a capability-bounded view Slice { region: RegionId, offset: usize, len: usize }:

OperationSignature in layer0::DomainBehavior
allocalloc(&mut self, len: usize) -> Result<Slice>Allocates a zeroed region of len bytes within the domain’s heap budget, increments the slot’s generation, and returns its full Slice.
sliceslice(&self, s: Slice, offset: usize, len: usize) -> Result<Slice>Narrows s to offset .. offset + len after checking bounds without overflow.
splitsplit(&self, s: Slice, at: usize) -> Result<(Slice, Slice)>Splits s into 0 .. at and at .. s.len.
bytesbytes(&self, s: Slice) -> Result<&[u8]>Borrows the underlying byte slice within s.
readread(&self, s: Slice, offset: usize, width: usize) -> Result<u64>Reads an unsigned big-endian integer of width (1, 2, 4, or 8) bytes (u8, u16, u32, or u64).
writewrite(&mut self, s: Slice, offset: usize, width: usize, value: u64) -> Result<()>Writes the low width bytes of value in big-endian order (Refusal::ReadOnly if immutable, Refusal::Busy if overlapping an active ticket).
write_byteswrite_bytes(&mut self, s: Slice, data: &[u8]) -> Result<()>Copies data into s after checking mutability and busy locks.
read_onlyread_only(&mut self, id: RegionId) -> Result<()>Marks a region permanently immutable so its slices can be shared freely; refused with Refusal::Busy while any ticket holds a range in the region.
reclaimreclaim(&mut self, id: RegionId) -> Result<()>Zeroizes the region’s bytes (zeroize), frees the slot (retaining its last generation so stale IDs fail with Refusal::Unknown), and credits used; refused with Refusal::Busy if any ticket is outstanding.

The busy lock and cancellation fencing: When a request Slice and reply RegionId are submitted to the ring, submit_batch locks the request slice’s byte range request.offset .. request.offset + request.len and the entire reply region 0 .. reply.len under the issued Ticket(u64). Any overlapping write, write_bytes, read_only, reclaim, or subsequent submit_batch on those byte ranges is refused with Refusal::Busy.

Matching Tickets.lean, calling domain.cancel(ticket) marks the pending entry cancelled = true without releasing its busy ranges. If the host has not yet started the submission when poll or await_ticket runs, the submission is fenced (Completion::Cancelled, with zero host access). Only await_ticket releases the busy ranges on the request and reply regions, and whenever completion is not Completion::Done(_) (either Cancelled or Overflow), await_ticket scrubs the entire reply region with zeroize() before returning.

layer0::Refusal and layer0::Completion

layer0::RefusalMeaning
BoundsThe requested offset + len or split point falls outside the Slice or Region.
BusyThe operation overlaps a byte range currently locked by an un-awaited Ticket, or two entries in the same submit_batch overlap.
ReadOnlyA write or reply submission targets a region marked immutable via read_only.
UnknownThe RegionId was never allocated or has already been reclaimed (stale generation), or the Ticket does not exist.
ForeignThe RegionId.domain does not match this Domain’s ID.
BudgetAllocation would exceed domain.heap (base heap plus attached SharedBudget leases) or wrap the 32-bit slot generation counter.
layer0::CompletionMeaning
Done(usize)The host completed the operation and wrote usize reply bytes at offset 0 of the reply region.
CancelledThe ticket was cancelled before the host started it; no host call occurred and the reply region is zeroed.
OverflowThe host’s reply exceeded the reply region’s byte length; nothing was kept and the reply region is zeroed.

Ring and Ring.call

The domain’s Ring queues capability submissions over Regions (submit, submit_batch, poll, cancel, and await_ticket). An all-or-none submit_batch(&[(tag, request_slice, reply_region)]) validates every entry against existing busy locks and against all earlier entries in the batch before issuing any tickets.

For sequential program proofs in Lema v0.2 (audit/view/cap/Capability.lean), a region is modeled by its owned ByteArray and each operation uses the synchronous 1-operation ring call (submit 1 followed immediately by await 1):

audit/view/cap/Capability.lean
def Ring.call {C : Type} {R : C → Type} (c : C) : Prog C R (R c) := .call c .ret

In crates/lema-cap/src/layer0.rs, Domain::call implements the exact runtime counterpart:

crates/lema-cap/src/layer0.rs
pub fn call(&mut self, device: &dyn Device, tag: u8, request: Slice, reply: RegionId) -> Result<Completion> {
    let t = self.submit(tag, request, reply)?;
    self.await_ticket(t, device)
}

Clock and Random descriptors

Alongside Domain, Region, and Ring, Layer 0 defines the host descriptors for time (crates/lema-cap/src/clock.rs) and entropy (crates/lema-cap/src/random.rs), exposed to Lema programs through tags 0x05 (clock) and 0x04 (random):

  • Clock: Provides utcMs (milliseconds since the Unix epoch) and monoNs (monotonic nanoseconds from a fixed per-run origin, guaranteed non-decreasing within a run by clockContract).
  • Random: Provides bytes(num_bytes) for 1 <= num_bytes <= 4096, reading exact byte counts from /dev/urandom opened with O_NOFOLLOW | O_CLOEXEC.

Layer 1: The six host capability tags

Every Layer 1 host capability operation is a single Ring.call exchanging one request Region (an LC\x02 request frame) for one reply Region (an LC\x02 reply frame). The host never raises an out-of-band exception: every refusal, I/O error, timeout, or malformed request is returned as a structured status inside a well-formed reply frame of the request’s tag.

TagFamily keyCommand type (Lema.Cap.*)Operations (op = constructor index ctor:k)
0x01tcpTcpCmd0 connect, 1 accept, 2 send, 3 recv, 4 close
0x02udpUdpCmd0 sendTo, 1 recvFrom
0x03blockBlockCmd0 info, 1 readBlock, 2 writeBlock, 3 flush
0x04randomRandomCmd0 bytes
0x05clockClockCmd0 utcMs, 1 monoNs
0x06secretSecretCmd0 get

The canonical codecs (encode*Request, decode*Request, encode*Response, decode*Response) and their round-trip theorems (decode (encode r) = .ok r) are kernel-checked in Lema.Cap.Frames (audit/inputs/Frames.json), while the typed wrappers (tcpCall, udpCall, blockCall, randomCall, clockCall, secretCall) and stateful contracts (tcpContract, udpContract, blockContract, randomContract, clockContract, secretContract) are kernel-checked in Lema.Cap.Capability (audit/inputs/Capability.json).

LC\x02 frame encoding and 5-byte header

All integers in LC\x02 frames are unsigned and big-endian (u8, u16, u32, u64). Variable-length fields use short (u16 byte length followed by that many bytes) or long (u32 byte length followed by that many bytes):

  • id: A short of 1..=64 bytes from [a-z0-9._-], naming a configured TCP origin, TCP listener, UDP endpoint, block device, or secret in lema-cap.json.
  • name: A short of 1..=128 bytes of visible ASCII (0x21..=0x7e), naming an access key ID, region, or service.
  • ids: A u32 count of 1..=16 followed by that many id values.
  • Exact framing: A frame ends immediately after its final field; any trailing bytes make the frame malformed.

Every request and reply frame starts with a 5-byte header:

OffsetFieldTypeValue
0..2magic2 bytes4c 43 (ASCII LC)
2versionu802
3kindu8Tag 01..06 in a request; tag + 0x80 (81..86) in a reply
4opu8Operation code from the tag’s operation table (ctor:k)

HandleId

A TCP connection handle (HandleId) is an 8-byte value consisting of slot (u16) followed by a 48-bit generation (high u16, then low u32):

  • Decoder check: Requires slot <= 255 (the host slot table holds at most 256 slots).
  • Non-wrapping generation: The host issues generations starting at 1 and never wraps a generation counter. If a slot’s generation would exceed 2^48 - 1, the slot is permanently retired for the remainder of the run. Any unknown or closed handle is refused with unknown_handle (5), preventing a stale handle from ever aliasing a later connection.

Reply status codes, effect flags, and detail codes

Every reply frame begins with the 5-byte header (kind = tag + 0x80, op = request.op), followed by status (u8) and status-dependent fields:

statusNameFields following statusMeaning
0okOperation-specific ok fieldsThe operation succeeded and satisfies the tag’s postcondition (*Kept).
1refuseddetail (u16)The host refused the request before performing any external side effect: no byte was sent, written, or read, and no secret was accessed.
2faileddetail (u16), effect (u8)The host attempted the operation and it did not complete. effect is 0 (clean / NotSent, meaning no external state changed) or 1 (uncertain / Sent for tcp and udp / DirtyUncertain for block). Failures on clock, random, and secret always have effect = 0 (clean).
3malformednoneThe request bytes were not a valid version 2 frame of this tag.
4unsupported_versionnoneThe request’s version byte was not 02.

The refusal and failure detail (u16) codes are shared across all six tags:

Refusal detailNameMeaning
1config_unavailableDeployment configuration (lema-cap.json) is missing or unreadable.
2unknown_idThe requested id is not configured for this operation.
3not_grantedThe calling actor holds no grant for the requested resource or secret.
4over_limitA request parameter exceeds the configured bound (deadline, byte length, or open handles).
5unknown_handleThe HandleId was never issued, has already been closed, or names a retired slot.
6handles_exhaustedEvery slot in the host’s TCP handle table (max_open_handles, default 64, max 256) is open or retired.
7busyThe block device is already bound to another actor spawn in this run, or its backing file lock (File::try_lock) is held by another process.
8dirty_uncertainA writeBlock targets a block device that is currently marked dirty after an uncertain write or flush failure.
9out_of_rangeA block index is at or beyond the device’s block_count.
10transport_mismatchThe secret’s SecretRole does not admit the supplied TransportContext (roleAdmits = false).
11secret_disabledThe application lacks an admitted ConstantTime and SecretFlow.<role> release receipt.
Failure detailNameMeaning
1timeoutThe operation’s deadline elapsed before completion.
2connection_refusedThe remote peer refused the TCP connection.
3resetThe connection was reset or broken.
4resolveThe configured hostname could not be resolved.
5ioAn operating-system I/O error occurred.
6internalThe host caught an internal failure.

Tag operations and contracts

0x01 tcp (TcpCmd, TcpState)

opOperationRequest fields (after header)ok reply fieldsContract and decoder rules
0connectorigin_id (id), deadline_ms (u32)handle (HandleId)deadline_ms >= 1; handle ∉ s.handles (never duplicates an open handle, proved in tcpNext_nodup).
1acceptlistener_id (id), deadline_ms (u32)handle (HandleId)deadline_ms >= 1; handle ∉ s.handles.
2sendhandle (HandleId), deadline_ms (u32), data (long)nonedeadline_ms >= 1, 1 <= |data| <= 16 MiB (16,777,216). Failed sends report clean (NotSent) when zero bytes reached the OS socket and uncertain (Sent) otherwise.
3recvhandle (HandleId), deadline_ms (u32), max_bytes (u32)data (long)deadline_ms >= 1, 1 <= max_bytes <= 16 MiB. Reply guarantees |data| <= max_bytes; |data| = 0 on ok signals clean peer EOF.
4closehandle (HandleId)noneRemoves handle from s.handles; subsequent operations on handle return unknown_handle.

0x02 udp (UdpCmd)

opOperationRequest fieldsok reply fieldsContract and decoder rules
0sendToendpoint_id (id), deadline_ms (u32), data (short)nonedeadline_ms >= 1, 1 <= |data| <= 65,507.
1recvFromendpoint_id (id), deadline_ms (u32), max_bytes (u32)data (short)deadline_ms >= 1, 1 <= max_bytes <= 65,507. Reply guarantees |data| <= max_bytes; datagrams from non-configured peers are dropped.

0x03 block (BlockCmd, BlockState)

Each device_id names a backing volume of fixed 4,096-byte blocks (BLOCK_BYTES = 4096), locked exclusively via File::try_lock() and bound to at most one actor spawn per run.

opOperationRequest fieldsok reply fieldsContract and decoder rules
0infodevice_id (id)block_count (u64)Returns total 4,096-byte blocks on device_id.
1readBlockdevice_id (id), index (u64)data (short)Reply data is exactly 4096 bytes (|data| = 4096).
2writeBlockdevice_id (id), index (u64), data (short)noneRequest data must be 4096 bytes. If device_id ∈ s.dirty, the contract guarantees refusal with dirty_uncertain (8, proved in blockKept_dirty).
3flushdevice_id (id)nonePersists prior writes. An ok reply removes device_id from s.dirty and leaves other devices’ dirty state unchanged (blockNext_flush).

If writeBlock or flush fails with effect = 1 (uncertain), blockNext adds device_id to s.dirty (blockNext_dirty). While dirty, info, readBlock, and flush remain available so BlockStore.recoverAndConfirm can read, validate, and flush the device before any new write is attempted.

0x04 random (RandomCmd) and 0x05 clock (ClockCmd, ClockState)

TagopOperationRequest fieldsok reply fieldsContract guarantee
0x040bytesnum_bytes (u16, 1..=4096)data (short, 1..=4096)x.size = num_bytes.toNat (randomCall_safe).
0x050utcMsnoneutc_ms (u64)Milliseconds since the Unix epoch.
0x051monoNsnonemono_ns (u64)s.lastMonoNs <= mono_ns.toNat (monotonicity across ClockState).

0x06 secret (SecretCmd, TransportContext, SecretRole, and roleAdmits)

SecretCmd.get (op = 0) takes secret_id (id) and transport (TransportContext) and returns version_id (u64), role (SecretRole), and secret (short, 1..=8192 bytes) from the newest secret-<version_id>.bundle file in the configured secrets directory.

TransportContext form (u8)VariantFields
0TlsClientorigin_id (id), tcp_handle (HandleId)
1TcpServerlistener_id (id), tcp_handle (HandleId)
2UdpEndpointendpoint_id (id)
SecretRole variant (u8)VariantFieldsAdmitted TransportContext (roleAdmits)
0SigV4access_key_id (name), allowed_origin_ids (ids), region (name), service (name), max_skew_ms (u32, 1..=900,000)TlsClient(origin_id, _) where origin_id ∈ allowed_origin_ids
1SigV4VerifyServerlistener_id (id), expected_access_key_id (name), region (name), service (name), max_skew_ms (u32, 1..=900,000)TcpServer(l, _) where l == listener_id
2BearerHeaderallowed_origin_ids (ids)TlsClient(origin_id, _) where origin_id ∈ allowed_origin_ids
3X25519StaticnoneAny TransportContext (TlsClient, TcpServer, or UdpEndpoint)
4Ed25519SignnoneAny TransportContext (TlsClient, TcpServer, or UdpEndpoint)

Theorem secretCall_admits in Capability.lean proves that any ok reply from secretCall satisfies roleAdmits role transport = true; otherwise the host refuses with transport_mismatch (10).

Opaque protocol families (exchange and serve)

Two additional capability families have no wire tag of their own. Instead, when an application issues an exchange or serve command, the VM worker executes a pinned Lema driver as an isolated sub-run over [tcp, random, clock, secret] and returns only the verified outcome to the application:

Family keyCommand typeConstructors (ctor:k)How the sub-run executes
exchangeLema.Cap.SecretExchange.ExchangeCmd0 signed, 1 bearerConnects to the origin, completes the TLS 1.3 handshake (Tls13Concrete), verifies that the peer certificate matches the credential’s bound server_name and anchors, requests Io::Secret inside the pinned continuation (signedCont or bearerCont), signs or formats the header once via SecretPolicy, sends the HTTP/1.1 request, and returns only the parsed HTTP outcome.
serveLema.Cap.ServeVerified.ServeCmd0 serve, 1 respondserve accepts a TCP connection, runs the TLS 1.3 server handshake using SecretRole::Ed25519Sign (signCont), reads the HTTP/1.1 request under a single connection deadline, and verifies its inbound SigV4 signature in constant time using SecretRole::SigV4VerifyServer (verifyCont), returning ServeReply.verified with a connection handle (or answering 400/403 inside the sub-run). respond seals and sends the application’s HTTP response on that handle and closes the connection.

Any application whose signature reaches secret, exchange, or serve must pass the ConstantTime and role-specific SecretFlow.<role> static analyses over LemaIR and must run through an approved release (lema run --release).

Concurrency runner families (tasks, actors, sessions)

Before the six host tags and two opaque families, crates/lema-cap/src/contract.rs pins three runner-managed concurrency families defined in Lema.Cap.AppCmd (audit/inputs/AppCmd.json):

Family keyCommand and reply typesPinned constructors (ctor:k)Runner semantics
tasksTaskCmd, TaskReply (Awaited)0 start, 1 await, 2 cancel, 3 spawnStarts or spawns concurrent tasks and awaits or cancels tickets (Awaited: 0 done, 1 canceled, 2 failed, 3 refused, 4 unknown).
actorsActorCmd, ActorReply (Sent, Taken)0 actor, 1 send, 2 take, 3 receive, 4 replyCreates actors with bounded mailboxes, sends messages (Sent: 0 ticket, 1 busy, 2 stopped, 3 unknown), takes replies (Taken: 0 reply, 1 failed, 2 unknown), and processes mailbox turns.
sessionsSessionCmd, SessionReply0 session, 1 send, 2 recv, 3 closeCreates and drives binary session channels (requires: ["tasks"]).

Bounds at a glance

ItemEnforced bound
LC\x02 header5 bytes (4c 43 02 kind op)
id1..=64 bytes of [a-z0-9._-]
name1..=128 bytes of visible ASCII (0x21..=0x7e)
ids1..=16 id entries
HandleId.slot0..=255 (max 256 slots, default max_open_handles = 64)
HandleId.generation1 .. 2^48 - 1 (never wraps; exhausted slots are retired)
deadline_ms>= 1 (capped by endpoint max_deadline_ms in lema-cap.json)
tcp send / recv payload1 B ..= 16 MiB (16,777,216 bytes)
udp sendTo / recvFrom datagram1 ..= 65,507 bytes
block readBlock / writeBlockExactly 4,096 bytes (BLOCK_BYTES)
random bytes1 ..= 4,096 bytes
secret get payload1 ..= 8,192 bytes
SecretRole max_skew_ms1 ..= 900,000 ms (up to 15 minutes)

Evidence boundary

  • Checked: The Frames byte codecs, their decoder bounds, their round-trip theorems (decode (encode r) = .ok r), and the Capability contracts and safety lemmas (tcpCall_safe, randomCall_safe, secretCall_admits, blockNext_dirty, blockNext_flush, blockKept_dirty, tcpNext_nodup) are checked by the pinned Lean 4.34.1 kernel.
  • Tested: Agreement between Frames and the Rust CapHost (crates/lema-cap) is tested against the 27 shared wire vectors in docs/caps-v2.md (16 valid round-trip vectors and 11 malformed refusal vectors), alongside the Layer 0 region/ring unit tests and VM runner integration suites.
  • Assumed: Operating-system socket delivery, DNS resolution, physical block-device atomicity and flush durability (CrashIntegrity), /dev/urandom entropy quality, OS monotonic/UTC clocks, and host secret file protection.

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