9. Standard library

The first shelf of chapter 6: first-party, audited once, the only code in a Mo program that is not yours. This chapter is the table a reader checks a call against. Every row is a built-in of the interpreter (toolchain/src/vm.zig), listed again as data in toolchain/src/prelude.zig and toolchain/PRELUDE.md, and exercised by a corpus file per group under examples/stdlib/ where one exists (Net, Http, Runtime, and the process rows are exercised by examples/processes/ and the programs instead). A call that is not a row here or in PRELUDE.md does not exist.

This is the part of the box the first three programs need (examples/GAPS.md), and HTTP for the fourth (## Http), not the whole box. Regex, TLS, crypto, compression, and database drivers come when a program demands them.

Rules for every row

  • Deterministic. Given equal arguments, a row gives an equal result on every machine and every run. Nothing reads a clock, a random source, or an address unless its receiver is a capability. Replay depends on it (chapter 3).
  • Values in, values out. A row that “changes” a list, map, set, or string returns a new value; the receiver is unchanged. On a var that nothing else holds, the runtime may do the work in place (push, Map.set, Set.add); no program can tell.
  • Rain is a value, a bug is a crash. A row whose input comes from outside the program (text to parse, a file) returns Option or Result. A row whose failure means the caller broke a rule (an integer that does not fit its target type, a rounding to 400 places) crashes with a report, like a tripped requires.
  • Indices and sizes are UInt64. String positions count graphemes, as size does; bytes is the escape hatch to bytes.
  • Clamped, not crashed. slice, take, and drop clamp their bounds to the value they cut, so "abc".slice(1, 99) is "bc" and [1, 2].drop(5) is [].
  • One order. The natural order sort, min, and max use is the order of <: integers and floats by value, strings byte by byte (which is code point order for UTF-8), Time and Duration by value, and tuples of those left to right. Bools, structs, enums, lists, maps, and sets have no order, and the checker rejects them there. sort is stable. A float NaN sorts after every number.
  • Defined order for maps and sets. Keys iterate in the order they were first added. Setting an existing key keeps its place; removing a key and adding it again puts it last. Two maps are equal when they hold equal keys with equal values, and two sets when they hold equal elements, in any order. Session 5, step 18: equality by content, where it was by order.

Type variables: T, U, A, K, V are fresh at each call. N is the receiver’s own integer type. An argument written fn(T) U is an anonymous function (a signature cannot name a function type, so a row that needs a comparison takes a key function instead).

Integers and floats

receivernameparametersreturns
any integerchecked_add, checked_sub, checked_mulNOption(N)None when the exact result does not fit N
any integersaturating_add, saturating_sub, saturating_mulNNthe exact result clamped to N
any integerwrapping_add, wrapping_sub, wrapping_mulNNthe exact result’s low bits
any integerto_u8, to_u16, to_u32, to_u64, to_i64that typethe same number in another width; one that does not fit is a crash
any integerchecked_to_u8, checked_to_u16, checked_to_u32, checked_to_u64, checked_to_i64Option of that typethe same number, or None when it does not fit
any integerto_f64Float64the nearest Float64
Float64roundplaces: UInt64Float64rounded to places decimals, half away from zero, on the number’s shortest decimal spelling (so 2.675.round(2) is 2.68); places above 15 is a crash
Float64to_stringplaces: UInt64Stringexactly places decimals, rounded as round does (3.0.to_string(1) is "3.0"); NaN is "NaN", infinities "Infinity" and "-Infinity"
Stringto_u64Option(UInt64)ASCII digits only, at least one, no sign, no spaces, no _; None otherwise or when it does not fit
Stringto_i64Option(Int64)as to_u64, with one optional leading -
Stringto_f64Option(Float64)an optional -, digits, optionally . and digits, optionally e or E, a sign, and digits; no NaN, no Infinity
String (on type)groupedany integerStringthe integer in Mo’s own spelling, _ between each three digits from the right: String.grouped(1204) is "1_204", and a negative one keeps its -. Step 28, after program 2 built 1_204 from the digits

Strings

receivernameparametersreturns
StringsizeUInt64graphemes
StringbytesList(UInt8)the UTF-8 bytes
String (on type)from_bytesList(UInt8)Option(String)the text those bytes spell; None when they are not valid UTF-8
StringcharsList(String)one string per grapheme
Stringsplitsep: StringList(String)the pieces between each sep, empty pieces kept ("a,,b" is three); an empty sep gives chars
StringlinesList(String)split on "\n", each line’s one trailing "\r" removed; a final newline does not start another line, and "" has no lines
StringtrimStringwithout leading and trailing Unicode whitespace
Stringstarts_with?, ends_with?, contains?StringBoolwhether the text begins with, ends with, or holds the argument; every string holds ""
Stringindex_ofStringOption(UInt64)the grapheme position of the first occurrence
Stringslicefrom: UInt64, to: UInt64Stringgraphemes from up to, not including, to, both clamped
Stringreplacea: String, b: StringStringevery non-overlapping a, left to right, replaced by b; an empty a changes nothing
Stringto_upper, to_lowerStringASCII letters changed, every other byte kept
Stringpad_left, pad_rightn: UInt64, ch: StringStringch added before or after until the text is n graphemes; a longer text is unchanged; ch that is not one grapheme is a crash
Stringrepeatn: UInt64Stringthe text n times
String (on type)joinList(String), sep: StringStringthe strings with sep between each two
Stringbyte_sizeUInt64the UTF-8 bytes, counted without building bytes

Option

receivernameparametersreturns
Option(T)mapfn(T) UOption(U)Some of the function’s value for a Some, and None for a None. Step 28, after program 1 wrote a case to turn a found change into its value

Lists

receivernameparametersreturns
List(T)sizeUInt64elements
List(T)pushTList(T)the element added at the end
List(T)geti: UInt64Option(T)element i, from 0
List(T)first, lastOption(T)
List(T)contains?TBoolwhether an element equals it
List(T)slicefrom: UInt64, to: UInt64List(T)elements from up to, not including, to, both clamped
List(T)take, dropn: UInt64List(T)the first n, or all but the first n
List(T)concatList(T)List(T)this list, then the other
List(T)reverseList(T)
List(T)mapfn(T) UList(U)
List(T)filterfn(T) BoolList(T)the elements it keeps, in order
List(T)reduceA, fn(A, T) AAfolded from the left
List(T)flat_mapfn(T) List(U)List(U)each result concatenated in order
List(T)any?, all?fn(T) BoolBoolstops at the first element that settles it; [] is false for any?, true for all?
List(T)findfn(T) BoolOption(T)the first element it keeps
List(T)countfn(T) BoolUInt64how many it keeps
List(T), T orderedsortList(T)in natural order, stable
List(T)sort_byfn(T) K, K orderedList(T)by the key’s natural order, stable; the key is computed once per element
List(T)sort_by_descfn(T) K, K orderedList(T)by the key’s natural order reversed, so a NaN key comes first; stable, so elements whose keys order level keep their order; the key is computed once per element
List(T), T orderedmin, maxOption(T)the first least or greatest element
none: called by bare name, min_of(a, b)min_of, max_ofa: T, b: T, T orderedTthe lesser or the greater of the two in natural order; a when they order level
List(T), T an integersumTthe total; one that does not fit T is a crash, like +
List(T)zipList(U)List((T, U))pairs by position, as long as the shorter list
List(T)enumerateList((UInt64, T))each element with its position
List(T)uniqueList(T)each first occurrence, in order
List(T)group_byfn(T) KMap(K, List(T))elements by key, keys in order of first appearance, each list in order

Maps and sets

Map(K, V) and Set(T) are values like lists. There are no map or set literals in this step: a map is built from Map.new() with set, update, or group_by (examples/GAPS.md records the gap).

receivernameparametersreturns
Map (on type)newMap(K, V)the empty map; K and V come from its uses
Map(K, V)sizeUInt64entries
Map(K, V)getKOption(V)
Map(K, V)has?KBool
Map(K, V)setK, VMap(K, V)with the entry; an existing key keeps its place
Map(K, V)updateK, default: V, fn(V) VMap(K, V)the key’s value, or default when it has none, passed through the function and set (counts.update(path, 0, fn(n) n + 1 end))
Map(K, V)removeKMap(K, V)without the key; unchanged when it is absent
Map(K, V)keysList(K)in order
Map(K, V)valuesList(V)in key order
Map(K, V)entriesList((K, V))in order
Set (on type)newSet(T)the empty set
Set(T)sizeUInt64elements
Set(T)addTSet(T)with the element; an existing one keeps its place
Set(T)removeTSet(T)without it
Set(T)has?TBool
Set(T)to_listList(T)in order

Time

Time is an instant, kept to the millisecond, in UTC; Duration is a signed length of time in milliseconds.

receivernameparametersreturns
Time (on type)parseStringOption(Time)RFC 3339: 2026-09-12T10:00:02Z, with optional fractional seconds (.5, .123456, kept to the millisecond, truncated) and Z or an offset +02:00; a date or time that does not exist (02-30, 24:00:00, a leap second) is None
Time (on type)from_partsyear, month, day, hour, minute, second, all UInt64Timethat instant in UTC; a year above 9999 or a date or time that does not exist is a crash (use parse for text from outside)
Timeto_iso8601String2026-09-12T10:00:02Z, with .mmm only when the milliseconds are not zero
TimesinceTimeDurationthis instant minus the other, a - b
DurationmsInt64whole milliseconds
Durationseconds, minutesFloat64
any integerms, seconds, minute, daysDurationa duration of that many; any other name after an integer (1.second) is MO0208 when the program is checked, naming these. Step 28: seconds, after program 2 wrote 10_000.ms
Time (on type)fixtureTime2026-01-01T00:00:00Z; tests only

Time - Time is a Duration, Time ± Duration a Time, and both compare with <.

In a test, Clock.fixture()’s now is Time.fixture() moved by the simulator’s time, which a fixture call that waits and a delayed send the simulator reaches both move, and inside an update it stays where it was when the update began (step 28, after program 1 could not watch a lease run out in a test).

Deadline is a point on the runtime’s clock that a call may wait until: under mo run the process clock, and under Mo.Sim the run’s own, which fixture waits move. Every within: takes a Duration or a Deadline; a Deadline gives the call what remains of it, and a call with nothing left is Timeout at once and is not made. Inside the update arm for a message that carries a reply, reply_by is the asker’s Deadline (chapter 3); nothing else makes one outside a test, and nothing makes one later than the one it came from.

receivernameparametersreturns
Deadlineat_mostDurationDeadlinethe earlier of the deadline and now plus the duration: a nested call may tighten its asker’s deadline and never extend it
DeadlineremainingDurationwhat remains of the deadline on the runtime’s clock, zero once it has passed, so a reply that came after its call’s deadline can be told from one in time. Session 5, step 24, after program 5 wrote by.at_most(0.ms) == by to ask it
Deadline (on type)fixtureDurationDeadlinenow plus the duration on the test’s clock, for a function that takes a deadline; tests only, since a test has no asker

Session 5, step 22: Deadline, reply_by, at_most, and fixture, after program 1 derived three deadlines by hand as sums of literals and two of the sums were wrong.

Reply(T) is the asker an update arm kept instead of answering: reply_to, bound in the arm for a message that carries a reply, moved into a state field there and answered from a later arm (chapter 3). It is authority, like Handle(P): it lives in a state field as Reply(T), Option(Reply(T)), List(Reply(T)), or Map(K, Reply(T)), and nowhere else.

receivernameparametersreturns
Reply(T)answerTanswers the ask this Reply holds, with the update that calls it; the asker’s deadline travelled with it, so an answer after the deadline is dropped, and a second answer to the same ask is dropped too

Session 8, step 31: Reply(T) and answer, after round 8’s queue answered its workers by a send and a Done message back, to keep one fsync per batch, and that reply was the one wait no deadline bounded.

Files

Every Fs row can wait, so it takes within: Duration. A name is relative to the scope the Fs was narrowed to (fs.scoped("logs").read_only), and nothing outside the scope is reachable; a path that leaves it, or anything that is not a readable file, is Missing(path) with the path as the program wrote it. A narrowed Fs opens every path one name at a time from its scope’s folder and never follows a link: a link at any name on the way, or at the last, is Missing(path) as an absence is, so a program cannot tell the two apart, and a link that points inside the scope is refused as one that points out (step 40). Reads and writes take regular files only, so a FIFO or a device is Missing(path) too, and each row acts on the descriptor it resolved, never on the path again. The scope’s own folder, the one platform.fs.scoped named, may be reached through links: that path is the operator’s. A scoped of a narrowed Fs is the program’s, so it walks from that folder without links. platform.fs itself, never narrowed, is the whole file system, and the system resolves its paths. A String is UTF-8, so a row that gives one gives only text: a file whose bytes are not UTF-8 is NotText, and read_bytes gives any file’s bytes.

receivernameparametersreturns
Fsreadpath: StringResult(String, FsError)the whole file; NotText when it is not UTF-8
Fsread_linespath: StringResult(List(String), FsError)the file split as String.lines splits it; NotText when it is not UTF-8
Fsread_bytespath: StringResult(List(UInt8), FsError)the whole file’s bytes, UTF-8 or not, for a program that wants the bytes; Missing and Timeout as read answers them, and on an Fs.fixture() the bytes of the text written
Fsfold_linespath: String, init: A, fn(A, String) AResult(A, FsError)the file’s lines, split as String.lines splits it, each handed to the function in turn with the value so far, init with the first, as the file is read, so no more of the file than its longest line and the value is held; the function gives the value handed with the next line, and Ok holds what the last line’s call gave, or init for a file with no lines. Missing(path) before any line when the file cannot be read or has a line of more than 64 MiB. A line that is not UTF-8 is handed on with each byte that begins no UTF-8 character replaced by U+FFFD, so a caller counts it, as line.contains?("\u{FFFD}"), and folds on; the call is never NotText (session 6, step 27). The deadline is checked before each read of the file: past it the call is Timeout, and the calls already made stay made. Written logs.fold_lines(name, 0, within: 1.minute, fn(count, line) count + 1 end)
Fssizepath: StringResult(UInt64, FsError)the file’s length in bytes
Fskind_ofpath: StringResult(Entry, FsError)the Entry of the name at path, never following it: name the path as the program wrote it, kind File, Folder, or Link, links its hard link count, and setuid its setuid bit, which a program that cares checks before it trusts a file (hard links and setuid are not scope rules). Missing(path) when nothing is there or a folder on the way is a link. On an Fs.fixture() a file or a folder, one link, never setuid. Step 40, for the harness, after workspace_files.py checked both
FslistResult(List(String), FsError)the names of the files, folders, and links directly inside the scope, sorted byte by byte; Missing(".") when the scope is not a readable folder
Fslist_kindsResult(List(Entry), FsError)what list gives, each name an Entry(name: String, kind: EntryKind, links: UInt64, setuid: Bool) whose kind is File, Folder, or Link, each name stat’ed without following it; anything else (a FIFO, a device) is File, and reading it is Missing. Step 28, after program 2 could not tell a folder named old.log from a log. Step 40: a link is Link, no longer what it points at, and links and setuid as kind_of gives them
FsscopedStringFsnarrowed to a folder inside this scope
Fsread_onlyFsnarrowed to reading: a read-only Fs, its own type, which goes wherever an Fs goes (a scoped of it is read-only too) and is refused by the checker (MO0404) where a write reaches it, directly or through a function it is handed to
Fs (on type)fixtureFsan empty file system: every read is Missing; list on the fixture’s root is Ok([]), and on a folder that is not there (no mkdir made it and no file is under it) Missing("."), as the real Fs answers; a path whose .. climbs above a scope’s folder, the fixture’s root included, is refused as the real Fs refuses it, Missing(path), and list on a scope that climbed out is Missing("."); tests only. Session 5, step 21: the refusal, after round 4’s logstat found the fixture climbing out of a scope where the real Fs does not. Session 5, step 22: Missing(".") for a folder that is not there, after program 1 found no test could show jobq serve refusing one
Fs (on type)fixturedelay: DurationFsevery call that waits less than delay is Timeout; tests only
Fswritepath: String, text: StringResult(none, FsError)the file holds exactly the text, created when it is not there, and is on disk (fsync) before Ok; Missing(path) for a path outside the scope, a folder that is not there, or anything that is not a file. On an Fs.fixture() the files are in memory and every read sees what was written; a call that fails changes nothing. A read-only Fs handed to a process as a start argument, in a message field, or on a supervisor’s child line is followed there too (Session 5, step 24): a write through it is refused by mo check (MO0404); a read-only Fs a capability call cannot see (one sent in a start argument the checker cannot follow) is not followed, and a write through it there crashes
Fsappendpath: String, text: StringResult(none, FsError)the text added at the end of the file, created when it is not there; durable (fsync) before it returns Ok; a call past its deadline is Timeout, and what it wrote stays
Fsremovepath: StringResult(none, FsError)the file is gone; Missing(path) when no such file is in the scope
Fsrenamefrom: String, to: StringResult(none, FsError)the file at from is at to, replacing a file there; Missing(from) when no such file is in the scope, Missing(to) when to is outside it, in a folder that is not there, or a link or anything but a regular file (step 40)
Fsreplacepath: String, text: StringResult(none, FsError)the file holds exactly the text, and a reader sees the old file or the new one, never a part: written to a temporary name in the same folder (unpredictable, created exclusively), synced, renamed over path, the folder synced. Created private to the owner (mode 0600). Missing(path) as write answers it, and for a name that is a link or anything but a regular file; a failure leaves the old file whole and no temporary name behind. A read-only Fs refuses it as it refuses write (MO0404). On an Fs.fixture(), as write. write stays as it is (in place, synced). On macOS the syncs are fsync, as write’s; F_FULLFSYNC is step 39 part F’s. Step 40
Fsmkdirpath: StringResult(none, FsError)a folder at the path, made when it is not there, in a folder that is; Ok when a folder is there already; Missing(path) for a path outside the scope, a folder that is not there, or a file at the path. The folder is not synced: a write into it syncs the file, not the folder. On an Fs.fixture() a folder is there once mkdir made it or a file is under it, and list names it

Session 5, step 19: mkdir, after program 4 found no row that makes a folder, so notes check could not copy a fixture folder somewhere to write.

Session 5, step 19: each_line is gone. Its function could reach no capability once step 18 refused capturing one in an anonymous function, so all it could do was compute and drop a value; fold_lines is the row that streams a file.

Output

receivernameparametersreturns
OutwriteStringnonethe text, as it is
Outwrite_lineStringnonethe text, then "\n"
Outflushnonewhat was written goes out now, not when main returns
Out (on type)fixtureOutan Out that keeps what is written to it; tests only
OutwrittenList(String)what a fixture Out was given, one string per write or write_line (a line with its "\n"); tests only

JSON

Json is an ordinary enum, matched with case like any other:

enum Json
  Object(fields: Map(String, Json))
  Array(items: List(Json))
  String(text: String)
  Number(value: Float64)
  Bool(value: Bool)
  Null
end
 
enum JsonError
  Syntax(at: UInt64)
end
receivernameparametersreturns
Json (on type)encodeTStringthe value as JSON text on one line, ", " between items and ": " after a key
Json (on type)decodeStringResult(Json, JsonError)the RFC 8259 value the whole text spells; Syntax(at) is the byte offset of the first thing that is not JSON
Jsonto_i64Option(Int64)Some(n) when the value is a Number holding a whole number below 2^53 either side of 0, where every whole number is a float of its own and reads back as its text spelled it; None for a fraction, a number from 2^53 out, or anything that is not a Number. Session 5, step 22: after program 1 read every count through to_string(0).to_u64

encode spells each value this way:

Mo valueJSON
a structan object, one key per field, in declaration order
an enum variant with no fieldsits name as a string: "Timeout"
a variant with fieldsan object with one key, its name, holding an object of its fields: {"Missing": {"path": "a.log"}}
Some(x), Nonex, null
Ok(x), Error(e){"Ok": x}, {"Error": e}
a list, a tuple, a setan array, in order
a map with String keysan object, in key order
any other mapan array of [key, value] arrays, in key order
a stringa string, with ", \, and control characters escaped
an integerits digits
a floatits shortest decimal spelling that reads back as the same float, with a .0 when it has no fraction (3.0); NaN and the infinities are null
a Booltrue, false
a Time, a Durationto_iso8601’s string, whole milliseconds
a Jsonthe JSON it holds, so Json.encode of a decoded value round-trips

A function, a capability, or a handle has no JSON; encoding one is a crash. decode reads every number as a Float64, and to_i64 gives the whole ones back; an object with a repeated key keeps the last value in the first key’s place; nesting deeper than 512 is Syntax.

Not in this step

Map and set literals; Unicode case mapping (to_upper is ASCII); full grapheme segmentation (a grapheme is a code point with the combining marks after it, as size counts); a float-to-integer conversion beyond Json’s to_i64. Each waits for a program that needs it.

Net

Net is TCP, platform.net in main (step 11). A Listener and a Conn are capabilities too: a Net call gives them, they travel as parameters (a listening process hands each connection to a worker with Worker.start(conn)) and in a message whose message line declares them, where they move (chapter 3, processes), and a Conn closes when the process holding it as a start argument stops, restarted or not. Every row that can wait takes within: Duration; a call past its deadline is Timeout, and leaves the listener or the connection as its row says. A process waiting in a call does not hold up the others: they keep taking messages. Nor does a write waiting for the peer hold up a read on its own connection: a read_line, the runtime’s lines loop, and a handshake’s read go on while it waits, so a program streams both ways through one Conn at once (a pipelining client writes a batch and reads the replies as they come); Busy still names a second write while one waits, and a second reader while one waits. Behind TLS the write’s records and what a read makes the engine answer (a KeyUpdate) reach the socket whole, one record after another, never one inside another. Step 38, after step 37’s client stalled until its write’s deadline (1,600 lines, 58.5 s).

enum NetError
  Timeout
  Refused
  Closed
  LineTooLong
  Busy
end
receivernameparametersreturns
Netlistenport: UInt16Result(Listener, NetError)a TCP listener on 127.0.0.1 at port, or at a free port the system picks when port is 0; Busy when another listener holds the port, Refused when the system will not bind it; binding does not wait
Netconnecthost: String, port: UInt16Result(Conn, NetError)a connection to an IP address or a host name; Refused when nothing listens there or the host is not found; Timeout leaves no connection
ListeneracceptResult(Conn, NetError)the next client; Timeout leaves the listener listening; Busy when another accept is already waiting on it
ListenerportUInt16the port it listens on
Connread_lineResult(Option(String), NetError)the next line without its "\n" and one "\r" before it, or None at the end of the stream (a last line with no newline comes first); a line of more than 64 KiB (65,536 bytes before its newline) is LineTooLong, and the next read starts after that line; Timeout keeps what arrived of an unfinished line for the next read; Busy when another read_line is waiting or a runtime input source owns the connection
ConnwriteStringResult(none, NetError)the text, as it is, all of it; Closed when the other side is gone; Timeout closes the connection, since part of the text may have gone; Busy when another write is waiting on it
Connclosenonecloses the connection: a call waiting on it ends with Closed, and so does every later call
Listenerserveinto: Handle(P), idle: Durationnonefrom this call on, the runtime accepts on the listener and sends P Accepted(conn: Conn) per connection, and Idle each time no connection came for idle, serving on; P declares both (MO0223); an accept on the listener is Busy, and serving it again is a crash
Connlinesinto: Handle(P), idle: Durationnonefrom this call on, the runtime reads the connection and sends P Line(text: String) per line as read_line cuts it, LineTooLong for a line over 64 KiB (the next starts after it), Closed at the end of the stream, and Idle when no line came for idle, after which it closes the connection; P declares all four (MO0223); once this side closes the connection it is read no more, with no message; a read_line on it is Busy, and reading it into a process again is a crash
Connchunksinto: Handle(P), max_bytes: UInt64, idle: Durationnonebounded byte input, accepted on Darwin in interpreter-step-44; Linux verification owed. Sends Chunk(bytes: List(UInt8)), Closed, and Idle; P declares all three without replies (MO0223). The full-width bound must be 1 through 65,536, or the call crashes before taking reader ownership or allocating a payload
Net (on type)fixtureNeta network in memory, shared by every fixture in the test; tests only

Bounded byte input (step 44). chunks is the sole input reader from registration onward. Registration over lines, another chunks, or an actually waiting pull read crashes; lines cannot replace it, and a later pull read is Busy. A completed pull read may leave buffered bytes: chunks delivers those first. Every chunk is nonempty, at most max_bytes, and owns its exact ordered bytes. Boundaries are arbitrary, including inside UTF-8; short available input does not wait for the bound, a newline or EOF. The runtime owns this loop and applies mailbox backpressure as below; registration does not wait and takes idle:, not within:.

Normal input EOF drains the pending bytes, sends one Closed, and retires only input: local writes remain usable. Local full close retires silently. No bytes for idle sends one Idle and closes the connection; target death also closes it. A broken stream sends Closed and leaves the connection unusable. A waiting write does not prevent chunk input from progressing on the same connection. On TLS the bytes are authenticated plaintext, not records; registering chunks marks the connection used, so a subsequent TLS handshake is refused.

The runtime owns the loop. A process never waits in a for around accept or read_line: serve and lines hand the waiting to the runtime, which delivers each result as a message and is itself the loop (as Erlang’s active sockets are). Neither row waits, so neither takes within:; idle: is the deadline of the runtime’s wait. A row’s messages come from the runtime and take no reply. Backpressure: the runtime delivers while the target’s mailbox holds fewer than its bound less a headroom of 4 waiting messages (half the bound, for a bound under 8), counting the requests an HttpListener.serve is still reading; at that it stops accepting or reading, so clients wait in the kernel’s queues, and it starts again once the mailbox has drained to half its bound; while it waits for room, idle time does not run. A served listener keeps a program running after main returns, so a server stops when it is stopped; a main that calls platform.exit ends the program at once when it returns: the runtime’s loops stop and their listeners close, every delayed send still pending is dropped with a Dropped event, what already waits in a mailbox is delivered, nothing is waited for, and the exit code is kept (Session 6, step 29, first tested by programs/exit-pending.mo). A process a source sends to is never ended while the source can send (chapter 3, processes). Session 5, step 20: serve and lines, after three servers wrote for _ in 0..10_000 twice around accept to satisfy the no-while law with a bound nobody chose.

A Net.fixture() lets a test start a server process, connect a client, and drive the protocol with no real socket. What one end writes waits for the other end to read it, and a closed end is the end of the stream for the other. listen(0) picks a port from 49152 up; connect to a port nothing listens on is Refused; the host is not looked at. A simulated call cannot wait for something to happen, so a call with nothing to take (an accept with no client, a read_line with no whole line) waits its whole deadline and is Timeout. Under mo test --sim, a fixture call that can wait times out by the seed, and a read_line or write finds its connection Closed by the seed; each leaves the connection as the real call would. A fixture’s serve and lines deliver at the start of each round of deliveries, one message per source, in start order or the seed’s, so a test’s settle, an ask that delivers rounds, and Http.fixture()’s send all see them; nothing happens while a simulated call waits, so a source with nothing to take waits, and Idle comes only once fixture calls have waited past its deadline. Under --faults, a source about to deliver finds its connection Closed, or waits out its deadline and sends Idle, by the seed.

Http

Http is HTTP/1.1 over TCP, platform.http in main (step 16): a server accepts exchanges and a client sends requests, with no new syntax. No TLS, and one request per connection: every request and response the runtime writes says connection: close, and the connection closes once the response is written or read. An HttpListener and an Exchange are capabilities, as a Listener and a Conn are: an Http call gives them, they travel as parameters (an acceptor hands each exchange to a worker with Worker.start(exchange)) and in a message whose message line declares them, and an Exchange closes when the process holding it as a start argument stops, restarted or not. Every row that can wait takes within: Duration; a call past its deadline is Timeout, and leaves the listener or the exchange as its row says. A process waiting in a call does not hold up the others.

struct Request
  method: String
  path: String
  query: Map(String, String)
  headers: Map(String, String)
  body: String
end
 
struct Response
  status: UInt16
  headers: Map(String, String)
  body: String
end
 
enum HttpError
  Timeout
  Refused
  Closed
  Busy
  Malformed
  TooLarge
  Unsupported
end

Request and Response are prelude structs. Building one needs only what the caller has: a Response its status and body, a Request its method and path; a field left out (headers, query, a request’s body) is empty. A module that declares its own Request or Response means its own by the name, and the Http rows still take and give the prelude’s.

receivernameparametersreturns
Httplistenport: UInt16Result(HttpListener, HttpError)as Net.listen: 127.0.0.1 at port, or at a free port the system picks when port is 0; Busy when another listener holds the port, Refused when the system will not bind it; binding does not wait
HttpListeneracceptResult(Exchange, HttpError)the next client and its whole request, both within the deadline; Timeout when no client or no whole request arrives in time, and a client that came closes; Malformed, TooLarge, or Unsupported when what came is not a request this row reads, after the client is answered 400, 413, or 501 and closed; Closed when the client’s stream ends first; Busy when another accept is already waiting on it; each leaves the listener listening
HttpListenerportUInt16the port it listens on
HttpListenerserveinto: Handle(P), idle: Durationnonefrom this call on, the runtime accepts on the listener, reads each client’s request on its own, and sends P Accepted(exchange: Exchange) per whole request, and Idle each time no client came for idle; a request not whole within idle of its connection is closed, and one that is not a request this row reads is answered 400, 413, or 501 and closed, each with no message; P declares both (MO0223); an accept on the listener is Busy, and serving it again is a crash. Session 5, step 20
ExchangerequestRequestthe request it holds; reading it after the exchange is answered is a crash
ExchangereplyResponseResult(none, HttpError)the response, written whole, then the connection closes; Malformed for a status outside 100 to 599 or a header that is not one, which writes nothing and leaves the exchange unanswered; Closed when the client is gone or the exchange is answered already; Timeout closes the connection; Busy when another reply is waiting on it
HttpsendRequest, host: String, port: UInt16Result(Response, HttpError)connects to an IP address or a host name, writes the request, and reads the whole response, all within the deadline; the connection closes either way; Refused when nothing listens there or the host is not found; Malformed for a request that is not one, before connecting, or a response that is not HTTP; Closed when the stream ends before the whole response; TooLarge and Unsupported as accept reads them
Http (on type)fixtureHttpHTTP on Net.fixture()’s network; tests only

The wire, read and written the same way by both runtimes:

  • Reading. A request line is METHOD /target HTTP/1.1 (HTTP/1.0 is read too; another version is Unsupported), a status line HTTP/1.1 200 reason. Each line ends in "\n", with one "\r" before it or none, and the headers end at an empty line. A request line of more than 1 MiB, header lines of more than 1 MiB together, or a body of more than 1 MiB is TooLarge, the body as soon as its content-length says so. The body is content-length bytes; a request with none has an empty body, and a response with none runs to the end of the stream. A transfer-encoding header (chunked) is Unsupported. A method or header name that is not a token, a target that does not begin with /, a header line with no :, a header value with a control character, two content-length headers that differ, and a query % not followed by two hex digits are Malformed.
  • A request’s fields. path is the target before its first ?, as it came. query is the target after it, split at & into key=value pairs, each decoded with + as a space and %XX as its byte; a pair with no = has the value "", an empty pair is skipped, and a repeated key keeps its last value in its first key’s place. headers holds each header by its name lower-cased, its value without the spaces and tabs around it; a repeated header’s values are joined with ", " in the first one’s place. A response’s headers are read the same way. Every string holds the bytes as they came, as Conn.read_line gives them.
  • Writing. A response is HTTP/1.1 <status> <reason> (the reason phrase for a common status, none for another), the response’s headers as name: value in map order, then content-length and connection: close, then the body. A request is METHOD <path> HTTP/1.1, its query’s keys and values percent-encoded (every byte but letters, digits, and -._~) after a ?, or after an & when the path holds a ?; then host: <host>:<port> unless the request has a host header, its headers, content-length, connection: close, and the body. A content-length or connection header the program gives is not written; the runtime’s are. A method that is not a token, a path that does not begin with / or holds a space or control character, or a header whose name is not a token or whose value holds a control character is Malformed.

accept reads the whole request before it gives the exchange, so a listener waits on one slow client at a time: a server that must not keep the others waiting passes each client a short deadline, or serves the listener, which reads each request apart. The body is read by its count from the connection’s buffer, so Conn gains no row.

An Http.fixture() runs on the network Net.fixture() does, so a test can connect with a Net fixture to an HttpListener and write a request by hand. As on Net, a call with nothing to take (an accept with no client, or with a request cut short) waits its whole deadline and is Timeout. send alone does not wait for nothing: while its response is not whole it delivers the processes’ waiting messages a round at a time, as a settle does, and it is Timeout when no message is waiting. So a test that sends a server process a message to accept, or serves a listener into it, then sends a request in the same statement, gets the server’s response. Under mo test --sim, accept and send time out by the seed, and reply and send find their connection Closed by the seed.

Tls

Tls is TLS 1.3 for a listening program, platform.tls in main (step 36, bricks-and-the-cost-of-zero-dependencies). Like the crypto rows it is written once, in Zig over std.crypto (toolchain/src/bricks/tls.zig), and both runtimes call that code: the interpreter imports it, and mo build links it beside the C runtime. It is a capability like Net: passed as a parameter, never captured in an anonymous function (MO0409), never reached from a pure function (MO0403), and held by a process only when it is started with one. A TlsServer is a capability too, but it holds no authority beyond its own key and its own certificate, so a program makes one and hands it to every worker that answers a connection.

What a connection it gives back does is what a plain Conn does: read_line, write, close, lines, and the step 44 chunks row are the same rows with the same buffering and the same NetErrors, and every program written against a socket works behind TLS unchanged. close sends close_notify before the socket closes; a peer whose stream ends without one is the end of the stream, as a plain socket’s end is.

enum TlsError
  BadPem
  Handshake
  Timeout
  Closed
  Untrusted
end
receivernameparametersreturns
PlatformtlsTlsthe TLS brick, in main alone
Tlsservercert: String, key: StringResult(TlsServer, TlsError)PEM text, not a path: the certificate chain leaf first, and a PKCS#8 private key (BEGIN PRIVATE KEY, Ed25519 or ECDSA P-256). BadPem when either does not parse, when there is not exactly one key, or when the key is not the leaf certificate’s. It does not wait
TlsServeracceptConnResult(Conn, TlsError)the server’s half of the handshake on that connection, within the deadline; the Conn it gives back is the same connection, its bytes now records. Handshake when the client’s hello or finish is wrong or it sent an alert, Timeout when the handshake did not finish in time, Closed when the stream ended first; each closes the connection, after the alert RFC 8446 names has been written. The connection must have had no read_line, write, lines, or chunks on it: a crash names the row otherwise, since the caller broke a rule
Tls (on type)fixtureTlsthe same rows on Net.fixture()’s network; tests only
Tlsclienttrust: StringResult(TlsClient, TlsError)PEM text, not a path, holding one or more root certificates: the trust a server’s chain must lead to. A block that is not a certificate the brick can read is left out; BadPem when none is left. A TlsClient is a capability as a TlsServer is, with no authority beyond its trust set, so it may be stored and shared. It does not wait
TlsClientconnectConn, host: StringResult(Conn, TlsError)the client’s half of the handshake on a connection from Net.connect, within the deadline, for host (sent as SNI when it is a name, and what the leaf must be for); the Conn it gives back is the same connection, its bytes now records. Untrusted when the server’s chain is refused (below), after the alert has been written; Handshake, Timeout, and Closed as accept gives them; each closes the connection. The connection must have had no read_line, write, lines, or chunks on it: a crash names the row otherwise
TlsClientofferList(String)TlsClientALPN (RFC 7301): a new client offering these protocols, in order; the client it is called on is unchanged. A name that is empty, longer than 255 bytes, or holds a NUL is a crash, and so is a list past 8,192 bytes on the wire (each name’s length and one; step 39), the most a ClientHello can hold inside the 16 KiB the other end reads, so every name offered is searched. It does not wait
TlsServerofferList(String)TlsServerALPN: a new server accepting these protocols, in its order of preference; the server it is called on is unchanged. The same crash rules. It searches a client’s whole offer, however many names it holds. When both sides offer and share nothing, the server sends no_application_protocol and the client’s connect is Handshake; when either side offers nothing, the handshake goes on without ALPN
ConnprotocolOption(String)the ALPN protocol the handshake agreed; None on a plain Conn or when none was. It does not wait

What it speaks, and nothing else (the bricks page’s cut): TLS 1.3 alone, the two suites TLS_AES_128_GCM_SHA256 and TLS_CHACHA20_POLY1305_SHA256, X25519 for the key exchange with one HelloRetryRequest when a client supports X25519 but sent no share for it, Ed25519 and ECDSA P-256 server certificates, KeyUpdate from the client answered, and close_notify both ways. A client that offers no TLS 1.3 is answered protocol_version, one with no X25519 at all handshake_failure, bytes that are not a record unexpected_message, a record past 16 KiB plus 256 record_overflow, a record whose tag does not check bad_record_mac, and a wrong Finished decrypt_error. Not here, in either direction: TLS 1.2, session tickets, PSK, 0-RTT, client certificates, renegotiation. SNI is read and ignored; ALPN is answered when the server was given a list with offer (step 37, which added the client side).

Under Tls.fixture() the rows run on Net.fixture()’s in-memory network. Nothing happens while a simulated call waits, so accept sees only what the other end has already written: a client that has written nothing is Timeout, and one that wrote something that is not a hello is Handshake.

What the client checks (steps 37 and 39). connect offers what the server side speaks (TLS 1.3, the two suites, X25519, the signature schemes Ed25519 and ECDSA P-256 SHA-256), answers one HelloRetryRequest, and checks the server’s flight: the transcript, the CertificateVerify against the leaf’s key, and the Finished. Before the CertificateVerify it checks the chain the server sent, as sent, leaf first: at most five certificates; each one’s issuer the next, until one is signed by a root in the trust set; every certificate between the leaf and that root a CA (basicConstraints); every certificate’s extensions, the root’s among them as OpenSSL checks them, read by the brick itself for what the cut supports of RFC 5280 (step 39): a CA’s pathLenConstraint counts the CAs below it that are not self-issued, an issuer with a key usage must hold keyCertSign, an extended key usage anywhere in the path must include server authentication (anyExtendedKeyUsage alone does not, as OpenSSL’s sslserver purpose has it), the leaf’s key usage when it has one must hold digitalSignature (RFC 8446 4.4.2.2), a critical extension the brick does not read is refused, and so are name constraints on any certificate, critical or not, since the brick does not check names against them and will not ignore them; what RFC 5280 asks of a conforming CA’s certificates where the certificate alone shows it (a serial number positive and at most 20 octets, keyCertSign only on a CA, the root a CA too, every CA’s basicConstraints critical and its subject not empty, an empty subject only beside a critical subject alternative name, a DNS name in the preferred syntax, an authority key identifier with its key identifier, and neither it nor authority information access critical); policy constraints are refused as name constraints are, since the brick does no policy processing; the leaf for host (a DNS name or an IP address among its subject alternative names, a wildcard for one leftmost label; a leaf with none is for no host, its common name not read, as RFC 9525 has it, where OpenSSL falls back to it); every signature good; and every certificate’s dates, the root’s too, around the runtime’s clock, both ends inclusive as RFC 5280 4.1.2.5 has them and read by the brick itself (a two-digit UTCTime year of 50 or more is 19YY; Zig’s parser read it as 20YY), which under Tls.fixture() is the simulator’s (Time.fixture(), 2026-01-01, moved by fixture waits). A refusal is Untrusted, after the alert OpenSSL 3.6 sends for the same chain: bad_certificate for a name that does not match or a date not yet begun, certificate_expired, unknown_ca for a root not trusted, a link missing, an issuer that is no CA, a chain past five, a path length exceeded, or an issuer without keyCertSign, and unsupported_certificate for RSA anywhere in the chain, which the cut does not cover, and for an extended key usage without server authentication; a certificate with an extension twice, or with one the brick reads that does not parse, is bad_certificate. Where the brick is stricter than OpenSSL or names a refusal otherwise, it says so here: a critical extension it does not read is unsupported_certificate (a kind of certificate it does not support), where OpenSSL sends certificate_unknown; name constraints are unsupported_certificate where OpenSSL checks them and accepts a leaf inside them; a leaf whose key usage lacks digitalSignature is unsupported_certificate where OpenSSL accepts it; and the last second of a certificate’s validity is inside it, where OpenSSL counts it expired. A client never acts on a record in the clear once the server’s handshake keys are installed, after the ServerHello: an alert or a close_notify there is the client’s own failure, and connect is Handshake (step 39); a server still reads a client’s alert in the clear before the client’s Finished, since OpenSSL’s client sends its refusal of a chain that way. After the handshake either side may start a KeyUpdate and each answers one that asks; a client reads the server’s session tickets and drops them, since there is no resumption. Under Tls.fixture() both halves of a handshake run on the one network, driven by the simulator: a connect or an accept with nothing to read lets the other end’s engine read what it wrote and answer, and lets the other processes take their messages, so a test runs a whole handshake with the server in a process that serve hands the connection.

Runtime

Runtime is the runtime surface (design-v0/03, the runtime surface; directions 37 and 40): what a running program’s processes are doing, as rows a program, an agent, or an operator calls. It is a capability like Fs: platform.runtime is Some under mo run, None in a binary unless it was built with mo build --surface, and a test holds its own run’s through Runtime.fixture(). main passes it down as it passes an Fs, narrowed by read_only for a process that may look but not act. A read is a snapshot taken between two updates, never inside one: every update runs on one thread, so a row sees no transaction half done, and a process whose update waits in a call is read once that update ends, within the row’s deadline. Every row but read_only takes within:. send, pause, and resume act, each act is an event, and a read-only Runtime refuses them with ReadOnly. Json.encode of each struct and event is the surface’s wire form.

The runtime keeps a bounded ring of events, 4,096 by default (mo run --events N, MO_EVENTS=N for a binary): each update with its duration, its time in calls that wait, and the call it waited longest in; each start, end, restart, and crash with its report’s seed, clause, message, and state; a sender that found a mailbox full; a call past its deadline; a loop the runtime owns pausing or resuming at its target’s bound; and each act of the surface. An event’s at is the runtime’s monotonic clock as a Time: under mo run pinned to the wall clock when the run began, and in a test the run’s own clock, so a seed’s events are the same every run. took_us and waited_us are microseconds. A seeded test that fails prints its last ten events after the interleaving.

struct ProcessInfo
  id: UInt64
  name: String
  alive: Bool
  mailbox: UInt64
  bound: UInt64
  waiting_in: Option(String)
  restarts: UInt64
  region_bytes: UInt64
  paused: Bool
  scheduler: UInt64
end
 
struct SourceInfo
  kind: String
  target: UInt64
  name: String
  in_flight: UInt64
  paused: Bool
end
 
struct MemoryInfo
  resident_bytes: UInt64
  region_bytes: UInt64
  region_resident_bytes: UInt64
  packed_bytes: UInt64
  event_bytes: UInt64
  largest: List(ProcessInfo)
end
 
enum RuntimeError
  NoProcess
  Unparsed(why: String)
  ReadOnly
  MailboxFull
  Timeout
end
 
enum Event
  Updated(at: Time, pid: UInt64, name: String, taking: String, took_us: UInt64, waited_us: UInt64, longest: String)
  Started(at: Time, pid: UInt64, name: String, scheduler: UInt64)
  Ended(at: Time, pid: UInt64, name: String)
  Restarted(at: Time, pid: UInt64, name: String, restarts: UInt64)
  Crashed(at: Time, pid: UInt64, name: String, seed: UInt64, clause: String, taking: String, snapshot: String)
  Overflowed(at: Time, sender: Option(UInt64), sender_name: String, target: UInt64, name: String)
  TimedOut(at: Time, pid: Option(UInt64), name: String, call: String)
  SourcePaused(at: Time, source: String, target: UInt64, name: String, in_flight: UInt64)
  SourceResumed(at: Time, source: String, target: UInt64, name: String, in_flight: UInt64)
  Sent(at: Time, pid: UInt64, name: String, taking: String)
  Paused(at: Time, pid: UInt64, name: String)
  Resumed(at: Time, pid: UInt64, name: String)
  Dropped(at: Time, sender: Option(UInt64), sender_name: String, target: UInt64, name: String, taking: String, why: String)
end

pid is the process’s id and name its name when the event happened, since a process that ended gives its id to one started later; taking is the message an update took, a crash’s last message, or the message the surface sent, and snapshot a crashed process’s state (Session 5, step 24: the fields were process, message, and state, which are keywords, so no pattern could name them); Overflowed and TimedOut name main or the test when no process sent or waited. The structs, Event, and RuntimeError are prelude types, and a module that declares its own Event or RuntimeError (or ProcessInfo, SourceInfo, MemoryInfo, or Reply, as examples/recipes/model-client.mo does) means its own by the name, as with Request, while the Runtime rows still give the prelude’s.

receivernameparametersreturns
PlatformruntimeOption(Runtime)Some under mo run and in a binary built with mo build --surface; None in any other binary
RuntimeprocessesList(ProcessInfo)every process that has not ended, by id: its name, whether it is up, its mailbox’s depth and bound, the call its update waits in (ask, Fs.append, Conn.read_line) or None, its restarts since it started, the bytes its region holds, and whether the surface holds its deliveries
Runtimestateid: UInt64Result(String, RuntimeError)the process’s state as a crash report prints it, as its last update left it; NoProcess for an id no process that has not ended has; Timeout when its update in progress does not end within the deadline, or when the caller is that update
Runtimerecentid: UInt64, n: UInt64List(Event)the last n events the ring holds about that id, oldest first
Runtimeeventssince: Time, n: UInt64List(Event)the first n events the ring holds at or after since, oldest first, so the last one’s at pages on
Runtimecrashesn: UInt64List(Event)the last n crash reports as Crashed events, newest first, read from a store of their own apart from the ring, so a stream of updates cannot turn one over: the last 16 (mo run --crashes N, MO_CRASHES=N for a binary), each clause, message, and state snapshot cut to 4,096 bytes where a character begins and ending … N bytes more when cut; the printed report stays whole, and the Crashed event is in the ring as before (Session 8, step 32)
RuntimesourcesList(SourceInfo)each loop the runtime owns (Listener.serve, Conn.lines, step 44’s Conn.chunks, HttpListener.serve) that has not ended: its row, its target, the requests it is reading, and whether it is paused at the target’s bound
RuntimememoryMemoryInfothe program’s resident bytes now, the bytes main’s and every process’s regions hold, the bytes of pages those regions and the scratch region keep resident (step 28: resident less these is what the runtime holds outside the regions, its parcels, buffers, stacks, and tables), the bytes packed into messages since the run began, the bytes the ring holds, and the five processes whose regions hold the most
Runtimeslowestn: UInt64List(Event)the n longest Updated events the ring holds, longest first
Runtimesendid: UInt64, text: StringResult(none, RuntimeError)the message the text spells as a report prints it (Vote(n: 3), Total; a message of one field may leave its name out), put in the process’s mailbox now, not when the calling update commits, and recorded as Sent; a reply it carries is dropped; Unparsed(why) for text that is not a message the process declares, or that holds a map, a set, a capability, or a handle; MailboxFull at its bound, which crashes no one; NoProcess; ReadOnly
Runtimepause, resumeid: UInt64Result(none, RuntimeError)holds the process’s deliveries, or lets them go: its messages wait, an ask to it is Timeout at its deadline (at once in a test, and the message still arrives), and a loop the runtime owns into it pauses at its bound; each is an event; NoProcess; ReadOnly
Runtimeread_onlyRuntimenarrowed to reading: send, pause, and resume are ReadOnly, at run time
Runtime (on type)fixtureRuntimethe surface of the test’s own run: the processes it started and the events they made; tests only

Over HTTP the same rows are the development on-ramp: mo run --surface PORT, and MO_SURFACE=PORT for a binary built with --surface, serve them as JSON on 127.0.0.1 from a process of the toolchain’s own the surface does not list, GET /processes, /state/<id>, /recent/<id>?n=, /events?since=<ISO-8601>&n=, /crashes?n=, /sources, /memory, /slowest?n=, and POST /send/<id> with the message’s text as the body, /pause/<id>, /resume/<id>; a refusal is 404 for no process, 403 for read only, and 409 otherwise, with the RuntimeError as the body. An MCP wrapper is a later step.

Session 5, step 23: the runtime surface and the events, from Robert’s call of 13 Sep night (the surface is a capability, on in development, off in a binary unless held) and the nine questions program 1’s worker wanted to ask its service.

Crypto

The crypto brick (step 35, bricks-and-the-cost-of-zero-dependencies): pure rows on names that hold no values, so each follows the first rule, deterministic. They are written once, in Zig over std.crypto (toolchain/src/bricks/crypto.zig), and both runtimes call that code: the interpreter imports it, and mo build links it beside the C runtime. Bytes are List(UInt8); a text is a String. Every key, nonce, seed, salt, and signature has one size, and another size is a crash whose message names the row and the size it got (AesGcm.seal takes a key of 32 bytes, not 31): the caller broke a rule. A sealed text, a public key, a signature, or a PHC string that comes from outside is checked by the row that reads it, and failing is a value.

receivernameparametersreturns
Hash (on type)sha256bytes: List(UInt8)List(UInt8)SHA-256 (FIPS 180-4), 32 bytes
Hash (on type)sha512bytes: List(UInt8)List(UInt8)SHA-512, 64 bytes
Hash (on type)hmac_sha256key: List(UInt8), bytes: List(UInt8)List(UInt8)HMAC-SHA256 (RFC 2104), 32 bytes; a key of any size
Hash (on type)hkdf_sha256ikm: List(UInt8), salt: List(UInt8), info: List(UInt8), size: UInt64List(UInt8)HKDF-SHA256 (RFC 5869), extract then expand, size bytes; a size past 8,160 (255 blocks) crashes
Hash (on type)hexbytes: List(UInt8)Stringlowercase hex, two digits a byte
Hash (on type)from_hextext: StringOption(List(UInt8))the bytes hex text spells, either case; None for an odd length or anything that is not a hex digit
Hash (on type)equal?a: List(UInt8), b: List(UInt8)Boolwhether the bytes are equal, in time that depends only on the sizes; lists of other sizes are unequal at once
AesGcm (on type)sealkey: List(UInt8), nonce: List(UInt8), plain: List(UInt8), aad: List(UInt8)List(UInt8)AES-256-GCM: the ciphertext, then the 16-byte tag; a key of 32 bytes and a nonce of 12, or a crash
AesGcm (on type)openkey, nonce, sealed: List(UInt8), aadOption(List(UInt8))the plain text; None when the tag does not match the key, nonce, text, and aad, or the text is shorter than a tag; the sizes as seal
ChaCha (on type)seal, openas AesGcm’sas AesGcm’sChaCha20-Poly1305 (RFC 8439), the same shape and sizes
X25519 (on type)publicsecret: List(UInt8)List(UInt8)the 32-byte public key of a 32-byte secret (RFC 7748)
X25519 (on type)sharedsecret: List(UInt8), public: List(UInt8)Option(List(UInt8))the 32-byte shared secret; None when public is a low-order point, whose secret would be all zeros; both 32 bytes, or a crash
Ed25519 (on type)publicseed: List(UInt8)List(UInt8)the 32-byte public key of a 32-byte seed (RFC 8032)
Ed25519 (on type)signseed: List(UInt8), bytes: List(UInt8)List(UInt8)the 64-byte signature, deterministic
Ed25519 (on type)verify?public: List(UInt8), bytes: List(UInt8), signature: List(UInt8)Boolwhether the signature is valid for the bytes under the key; a 32-byte key that is not a point is false; a key of another size or a signature of other than 64 bytes crashes
Password (on type)hashpassword: String, salt: List(UInt8)StringArgon2id (RFC 9106) at m=65536,t=3,p=1, a 32-byte tag, as a PHC string ($argon2id$v=19$m=65536,t=3,p=1$<salt>$<tag>, 97 bytes); the salt is 16 bytes, or a crash; take it from random.bytes(16)
Password (on type)verify?password: String, phc: StringBoolwhether the password hashes to the string; a string hash does not write (malformed, another algorithm or version, other parameters, another salt or tag size, another spelling of the same values) is false, so a stored string cannot make a check cost more than a hash

Nothing else until a program asks: no SHA-3, no ECDSA, no RSA, no scrypt or bcrypt, no streaming hash. Step 35: the rows program 7 and the TLS brick of step 36 need.

Random

Random is the one capability that gives bytes no row can predict, so it is not deterministic and is held like Fs: platform.random in main, passed down as a parameter, never captured by an anonymous function (MO0409), never stored in a value (MO0403), and held by a process only when it is started with one.

receivernameparametersreturns
PlatformrandomRandomthe operating system’s generator: getrandom(2) on Linux, arc4random_buf(3) on macOS, read on every call
Randombytessize: UInt64List(UInt8)size bytes; more than 1 GiB at once crashes
Random (on type)fixtureRandoma stream from the run’s seed (ChaCha20 keyed by SHA-256 of the seed), so a test that draws a key draws the same bytes every run, under mo test, --sim, and in a test binary; each fixture starts at the stream’s beginning, and each draw goes on along it; tests only

Step 35.

Exec

A child process narrowed to fixed commands (step 41; the design is mo-capabilities-for-the-harness, section 3). A child has none of Mo’s checked authority, so no handle that can run anything exists below main: platform.exec makes a Program, one absolute path; a Program makes a Command, a fixed argument list; and only a Command runs or travels. A process handed a Command that removes containers can remove containers and do nothing else. No shell, no PATH, no interpolation: a Hole is one whole argument, byte for byte, so no row builds a command from text.

fn main(platform: Platform)
  docker = platform.exec.program("/usr/bin/docker")
  remove = docker.command([Fixed(text: "rm"), Fixed(text: "-f"), Hole])
  Executor.start(remove, platform.fs.scoped("runs"))
end
 
# far from main, holding only `remove`:
case remove.run([name], within: 10.seconds)
  Ok(done): done.exit        # Exited(code: 0), Signalled(signal: 9)
  Error(Timeout): ...        # the group was killed and the child reaped
  Error(_): ...
end
receivernameparametersreturns
PlatformexecExecmain only, like every part of the platform
Execprogrampath: StringPrograman absolute path; no PATH search, ever. A relative path, or one holding a NUL, crashes when the Program is made: the caller broke a rule
ProgramcommandList(Arg)Commanda fixed argument list; Arg is an ordinary enum, Fixed(text: String) or Hole, built by its named field as every variant is. A Fixed text holding a NUL crashes
CommandenvMap(String, String)Commandthe child’s whole environment, in the map’s order; the default is empty, never the parent’s. A name that is empty or holds = or a NUL, or a value holding a NUL, makes every run Refused
Commandin_folderFsCommandthe child works in this scope’s folder, reached as list reaches it (step 40): a scope that climbed out, a folder not there, or a link on the way from the folder platform.fs.scoped named makes every run Failed. The default is a new empty folder private to the owner (0700) under TMPDIR or /tmp, removed with what the child left in it after the run. The folder is where the child starts, not a fence: what the child reaches is the operating system’s to limit
CommandoutputUInt64Commandbytes kept of stdout and of stderr each; default 65,536, at most 16 MiB (a larger bound crashes)
CommandrunList(String), stdin: String (optional)Result(Done, ExecError)fills the holes in order, the program’s path as argv[0]; stdin is written to the child and then closed (without it, the child’s stdin is closed at once). Waits, so it takes within:
Exec (on type)fixturefn(List(String), String) DoneExectests only: the function answers every run of the commands made from it, given the argument list the child would get (the program’s path first, the holes filled) and the stdin. It refuses what the real one refuses. Under mo test --sim a run is scheduled as any wait and fails with Timeout or Failed at the run’s fault rate

Done is exit: Exit (Exited(code: UInt8) or Signalled(signal: UInt8)), stdout and stderr as List(UInt8), truncated: Bool (either stream went past the bound; the bytes past it are dropped), and took: Duration. ExecError is Missing (no program at the path, or a folder on the way is not one), Refused (a wrong number of values for the holes, a value holding a NUL, or an environment env refused), Timeout, or Failed(why: String) (anything else that kept the program from starting: not executable, a folder, not a program the system runs, no working folder; why says which in a few words).

The rules that make it safe to hold:

  • Exec and Program stay in main (MO0407, as a Platform does): no function, process, supervisor, or message line takes one; a name of one is only ever read through a dot, so it is never passed, bound to another name, put in a list, sent, returned, or interpolated; one made on the spot may be given a name. A struct field, a return type, and a capture refuse them as they refuse every capability (MO0403, MO0409). A Command travels like an Fs: a parameter, a process’s start argument, a message’s field, never a value’s field or a capture. flows(T, into: Command) refuses a T that reaches a run, a list written at the call included.
  • The deadline is kept by killing. The child starts a session of its own, so it leads its own process group and has no controlling terminal. At the deadline the whole group gets SIGKILL, the child is reaped, and only then is the answer Timeout. When the child exits, whatever is left of its group is killed before the child is reaped, so nothing it started outlives the run. A process that left the group (its own setsid) is the operating system’s to contain (a cgroup, a container): Mo does not pretend otherwise.
  • Output is drained as the child runs and bounded, and the bound is reported (truncated), never silent; a child writing more than a pipe holds never blocks on it.
  • The child inherits nothing: no environment, no descriptor but its three pipes on 0, 1 and 2, every signal at its default and none blocked, no terminal.
  • A run holds no scheduler. It waits on a thread of its own, as a file write waits on the blocking pool, and under processes the update waits holding no scheduler, so every other process goes on.

Not in this version: streaming output, a child that outlives the run, signals other than the deadline’s kill, a pseudo-terminal, pipes between children. Each env, in_folder, and output call makes a new Command the run keeps, as each scoped makes a new Fs, so a program makes its commands in main, not in a loop.

Step 41. Two spellings differ from the design page: in_folder for the design’s in, which is a keyword (for x in xs) and cannot follow a .; and Fixed(text: "rm") for Fixed("rm"), since a variant is built by naming its fields.