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:
| Layer | Modules and implementation | Responsibility |
|---|---|---|
| Layer -1: Program and resource core | Core, 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 rings | crates/lema-cap/src/layer0.rs, Capability.lean | Provides 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 tags | Frames, 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 mapNat -> Option State. Its kernel-checked theorems (handleSafe_open,use_after_close,double_close) prove that aSafeprogram never reads, writes, or closes a handle that was not opened or has already been closed. - In-flight
busyticket locks (Tickets): Models asynchronous submissions that hold a lock on a resource until their completion ticket is awaited. UnderTickets’spreandnextrules, submitting an operation marks its target resourcebusy, refusing overlapping writes or reclaims untilawaitconsumes the completion. Crucially,cancelleaves the abstract state unchanged (.cancel _ => s): a cancelled ticket keeps its resource locked asbusyuntilawaitconfirms 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’sidand a monotonically incrementedgenerationfor that slot (generations[index]). Passing another domain’sRegionIdto any read, write, slice, or reclaim operation is refused immediately withRefusal::Foreign. - Dynamic heap extension (
SharedBudgetandLease): Multiple domains can draw from an atomicSharedBudget(Arc<AtomicUsize>). Callingbudget.lease(bytes)atomically reservesbytes(Ordering::AcqRel) and returns aLease;domain.attach(lease)extendsdomain.heapfor the lifetime of the domain, and dropping theLeaseautomatically returns the bytes to theSharedBudget.
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 }:
| Operation | Signature in layer0::Domain | Behavior |
|---|---|---|
alloc | alloc(&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. |
slice | slice(&self, s: Slice, offset: usize, len: usize) -> Result<Slice> | Narrows s to offset .. offset + len after checking bounds without overflow. |
split | split(&self, s: Slice, at: usize) -> Result<(Slice, Slice)> | Splits s into 0 .. at and at .. s.len. |
bytes | bytes(&self, s: Slice) -> Result<&[u8]> | Borrows the underlying byte slice within s. |
read | read(&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). |
write | write(&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_bytes | write_bytes(&mut self, s: Slice, data: &[u8]) -> Result<()> | Copies data into s after checking mutability and busy locks. |
read_only | read_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. |
reclaim | reclaim(&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::Refusal | Meaning |
|---|---|
Bounds | The requested offset + len or split point falls outside the Slice or Region. |
Busy | The operation overlaps a byte range currently locked by an un-awaited Ticket, or two entries in the same submit_batch overlap. |
ReadOnly | A write or reply submission targets a region marked immutable via read_only. |
Unknown | The RegionId was never allocated or has already been reclaimed (stale generation), or the Ticket does not exist. |
Foreign | The RegionId.domain does not match this Domain’s ID. |
Budget | Allocation would exceed domain.heap (base heap plus attached SharedBudget leases) or wrap the 32-bit slot generation counter. |
layer0::Completion | Meaning |
|---|---|
Done(usize) | The host completed the operation and wrote usize reply bytes at offset 0 of the reply region. |
Cancelled | The ticket was cancelled before the host started it; no host call occurred and the reply region is zeroed. |
Overflow | The 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):
def Ring.call {C : Type} {R : C → Type} (c : C) : Prog C R (R c) := .call c .retIn crates/lema-cap/src/layer0.rs, Domain::call implements the exact runtime counterpart:
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: ProvidesutcMs(milliseconds since the Unix epoch) andmonoNs(monotonic nanoseconds from a fixed per-run origin, guaranteed non-decreasing within a run byclockContract).Random: Providesbytes(num_bytes)for1 <= num_bytes <= 4096, reading exact byte counts from/dev/urandomopened withO_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.
| Tag | Family key | Command type (Lema.Cap.*) | Operations (op = constructor index ctor:k) |
|---|---|---|---|
0x01 | tcp | TcpCmd | 0 connect, 1 accept, 2 send, 3 recv, 4 close |
0x02 | udp | UdpCmd | 0 sendTo, 1 recvFrom |
0x03 | block | BlockCmd | 0 info, 1 readBlock, 2 writeBlock, 3 flush |
0x04 | random | RandomCmd | 0 bytes |
0x05 | clock | ClockCmd | 0 utcMs, 1 monoNs |
0x06 | secret | SecretCmd | 0 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: Ashortof1..=64bytes from[a-z0-9._-], naming a configured TCP origin, TCP listener, UDP endpoint, block device, or secret inlema-cap.json.name: Ashortof1..=128bytes of visible ASCII (0x21..=0x7e), naming an access key ID, region, or service.ids: Au32count of1..=16followed by that manyidvalues.- 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:
| Offset | Field | Type | Value |
|---|---|---|---|
0..2 | magic | 2 bytes | 4c 43 (ASCII LC) |
2 | version | u8 | 02 |
3 | kind | u8 | Tag 01..06 in a request; tag + 0x80 (81..86) in a reply |
4 | op | u8 | Operation 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
1and never wraps a generation counter. If a slot’s generation would exceed2^48 - 1, the slot is permanently retired for the remainder of the run. Any unknown or closed handle is refused withunknown_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:
status | Name | Fields following status | Meaning |
|---|---|---|---|
0 | ok | Operation-specific ok fields | The operation succeeded and satisfies the tag’s postcondition (*Kept). |
1 | refused | detail (u16) | The host refused the request before performing any external side effect: no byte was sent, written, or read, and no secret was accessed. |
2 | failed | detail (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). |
3 | malformed | none | The request bytes were not a valid version 2 frame of this tag. |
4 | unsupported_version | none | The request’s version byte was not 02. |
The refusal and failure detail (u16) codes are shared across all six tags:
Refusal detail | Name | Meaning |
|---|---|---|
1 | config_unavailable | Deployment configuration (lema-cap.json) is missing or unreadable. |
2 | unknown_id | The requested id is not configured for this operation. |
3 | not_granted | The calling actor holds no grant for the requested resource or secret. |
4 | over_limit | A request parameter exceeds the configured bound (deadline, byte length, or open handles). |
5 | unknown_handle | The HandleId was never issued, has already been closed, or names a retired slot. |
6 | handles_exhausted | Every slot in the host’s TCP handle table (max_open_handles, default 64, max 256) is open or retired. |
7 | busy | The 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. |
8 | dirty_uncertain | A writeBlock targets a block device that is currently marked dirty after an uncertain write or flush failure. |
9 | out_of_range | A block index is at or beyond the device’s block_count. |
10 | transport_mismatch | The secret’s SecretRole does not admit the supplied TransportContext (roleAdmits = false). |
11 | secret_disabled | The application lacks an admitted ConstantTime and SecretFlow.<role> release receipt. |
Failure detail | Name | Meaning |
|---|---|---|
1 | timeout | The operation’s deadline elapsed before completion. |
2 | connection_refused | The remote peer refused the TCP connection. |
3 | reset | The connection was reset or broken. |
4 | resolve | The configured hostname could not be resolved. |
5 | io | An operating-system I/O error occurred. |
6 | internal | The host caught an internal failure. |
Tag operations and contracts
0x01 tcp (TcpCmd, TcpState)
op | Operation | Request fields (after header) | ok reply fields | Contract and decoder rules |
|---|---|---|---|---|
0 | connect | origin_id (id), deadline_ms (u32) | handle (HandleId) | deadline_ms >= 1; handle ∉ s.handles (never duplicates an open handle, proved in tcpNext_nodup). |
1 | accept | listener_id (id), deadline_ms (u32) | handle (HandleId) | deadline_ms >= 1; handle ∉ s.handles. |
2 | send | handle (HandleId), deadline_ms (u32), data (long) | none | deadline_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. |
3 | recv | handle (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. |
4 | close | handle (HandleId) | none | Removes handle from s.handles; subsequent operations on handle return unknown_handle. |
0x02 udp (UdpCmd)
op | Operation | Request fields | ok reply fields | Contract and decoder rules |
|---|---|---|---|---|
0 | sendTo | endpoint_id (id), deadline_ms (u32), data (short) | none | deadline_ms >= 1, 1 <= |data| <= 65,507. |
1 | recvFrom | endpoint_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.
op | Operation | Request fields | ok reply fields | Contract and decoder rules |
|---|---|---|---|---|
0 | info | device_id (id) | block_count (u64) | Returns total 4,096-byte blocks on device_id. |
1 | readBlock | device_id (id), index (u64) | data (short) | Reply data is exactly 4096 bytes (|data| = 4096). |
2 | writeBlock | device_id (id), index (u64), data (short) | none | Request data must be 4096 bytes. If device_id ∈ s.dirty, the contract guarantees refusal with dirty_uncertain (8, proved in blockKept_dirty). |
3 | flush | device_id (id) | none | Persists 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)
| Tag | op | Operation | Request fields | ok reply fields | Contract guarantee |
|---|---|---|---|---|---|
0x04 | 0 | bytes | num_bytes (u16, 1..=4096) | data (short, 1..=4096) | x.size = num_bytes.toNat (randomCall_safe). |
0x05 | 0 | utcMs | none | utc_ms (u64) | Milliseconds since the Unix epoch. |
0x05 | 1 | monoNs | none | mono_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) | Variant | Fields |
|---|---|---|
0 | TlsClient | origin_id (id), tcp_handle (HandleId) |
1 | TcpServer | listener_id (id), tcp_handle (HandleId) |
2 | UdpEndpoint | endpoint_id (id) |
SecretRole variant (u8) | Variant | Fields | Admitted TransportContext (roleAdmits) |
|---|---|---|---|
0 | SigV4 | access_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 |
1 | SigV4VerifyServer | listener_id (id), expected_access_key_id (name), region (name), service (name), max_skew_ms (u32, 1..=900,000) | TcpServer(l, _) where l == listener_id |
2 | BearerHeader | allowed_origin_ids (ids) | TlsClient(origin_id, _) where origin_id ∈ allowed_origin_ids |
3 | X25519Static | none | Any TransportContext (TlsClient, TcpServer, or UdpEndpoint) |
4 | Ed25519Sign | none | Any 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 key | Command type | Constructors (ctor:k) | How the sub-run executes |
|---|---|---|---|
exchange | Lema.Cap.SecretExchange.ExchangeCmd | 0 signed, 1 bearer | Connects 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. |
serve | Lema.Cap.ServeVerified.ServeCmd | 0 serve, 1 respond | serve 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 key | Command and reply types | Pinned constructors (ctor:k) | Runner semantics |
|---|---|---|---|
tasks | TaskCmd, TaskReply (Awaited) | 0 start, 1 await, 2 cancel, 3 spawn | Starts or spawns concurrent tasks and awaits or cancels tickets (Awaited: 0 done, 1 canceled, 2 failed, 3 refused, 4 unknown). |
actors | ActorCmd, ActorReply (Sent, Taken) | 0 actor, 1 send, 2 take, 3 receive, 4 reply | Creates 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. |
sessions | SessionCmd, SessionReply | 0 session, 1 send, 2 recv, 3 close | Creates and drives binary session channels (requires: ["tasks"]). |
Bounds at a glance
| Item | Enforced bound |
|---|---|
LC\x02 header | 5 bytes (4c 43 02 kind op) |
id | 1..=64 bytes of [a-z0-9._-] |
name | 1..=128 bytes of visible ASCII (0x21..=0x7e) |
ids | 1..=16 id entries |
HandleId.slot | 0..=255 (max 256 slots, default max_open_handles = 64) |
HandleId.generation | 1 .. 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 payload | 1 B ..= 16 MiB (16,777,216 bytes) |
udp sendTo / recvFrom datagram | 1 ..= 65,507 bytes |
block readBlock / writeBlock | Exactly 4,096 bytes (BLOCK_BYTES) |
random bytes | 1 ..= 4,096 bytes |
secret get payload | 1 ..= 8,192 bytes |
SecretRole max_skew_ms | 1 ..= 900,000 ms (up to 15 minutes) |
Evidence boundary
- Checked: The
Framesbyte codecs, their decoder bounds, their round-trip theorems (decode (encode r) = .ok r), and theCapabilitycontracts 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
Framesand the RustCapHost(crates/lema-cap) is tested against the 27 shared wire vectors indocs/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/urandomentropy quality, OS monotonic/UTC clocks, and host secret file protection.
Lema v0.3.2 · Updated 29 October 2026 · Version and compatibility