Style guide

This document specifies idiomatic Hale in four layers: the shapes a program is composed of, the correctness rules that keep a long-lived program sound, the…

Reference material, synced from the compiler repo’s spec/. The guide is the gentler path in.

This document specifies idiomatic Hale in four layers: the shapes a program is composed of, the correctness rules that keep a long-lived program sound, the speed rules that make a hot path allocation-free, and the enforcement ladder the compiler backs them with. Where grammar.ebnf says what’s syntactically valid and types.md / semantics.md say what’s meaningfully valid, this document says what’s idiomatically valid — what a program should look like when an author has applied the framework’s primitives coherently rather than fought them.

Every rule here is grounded in production Hale code — the pond contrib libraries, the causality game engine, a production market-data connector fleet, the bench performance corpus, and a downstream market-data service whose leak hunts drove much of the substrate’s reclamation machinery. Rules cite the shape that earned them.

The styleguide is normative for new code in apps/, the bundled stdlib seed (crates/hale-codegen/runtime/stdlib/), and examples/. It is descriptive for older code that predates a given rule; refactors apply the rules opportunistically.

How to read it: Foundations and the shape catalog get a program structured right. Correctness keeps it right over days of uptime. Fast applies only where a path is genuinely hot — the section says so explicitly. Enforcement is the one-table summary of what the compiler checks for you.


1. Foundations

Section titled “1. Foundations”

The foundational axiom

Section titled “The foundational axiom”

Every named structural thing is a locus. Types are loci-in-waiting — the smallest growth stage on the locus gradient.

If a thing has lifecycle, contracts, bus participation, closures, capacity slots, or projection class, it is a fully-grown locus. If it is pure data (record, returnable by value, no flow), it is a type. The two are points on one gradient, not separate categories. There is no third primitive. See notes/hale-types-vs-loci.md for the source axiom.

Loci recur at every layer: an app is a locus, a service is a locus, a spawned worker is a locus, a cache is a locus. There is no module / class / package keyword because none is needed — anything one of those would do, a locus does, and the locus carries lifecycle and contracts the other forms don’t.

Roles, not keywords

Section titled “Roles, not keywords”

Only two declaration forms exist: locus and main locus. “App”, “service”, “namespace”, “child”, “collection” are roles a locus plays, realized through which members it declares — params / lifecycle / bus / accept / capacity — not through separate keywords. Don’t hunt the grammar for a service or module keyword; pick the role from the catalog below and declare the members that realize it. (Production confirmation: the connector fleet and causality together define every role in the catalog using exactly the two forms.)

The memory model in one page

Section titled “The memory model in one page”

This is the single most load-bearing page in the guide. A developer who gets every shape right and skips this page will still ship a leak — that is an observed outcome, not a hypothetical.

Arenas don’t free per-allocation. Every locus owns an arena (self.__arena). Everything anchored there — struct clones, String buffers, child structures — lives until the locus dissolves. There is no per-object free.

Method scratch reclaims at method exit. Every allocating method (and bus handler) gets a scratch region created at entry and destroyed at return. Transients — parse results, temporaries, locals — allocate into scratch and vanish per call. This is why ordinary code is allocation-bounded by construction: allocate freely in a method, and the method boundary cleans up.

Escaping a value costs an anchor. Storing a heap value into self copies it out of scratch into the locus arena (an “anchor”). The anchor is the transfer of lifetime: the value now lives as long as the locus.

Therefore: a long-lived locus means anything anchored per-iteration accumulates until dissolve — unless one of the substrate’s reclamation mechanisms applies. The mechanisms, in the order you should reach for them:

  1. Don’t escape. Keep transients in method scratch. Free by construction.
  2. Mutate in place. self.f.x = v, self.arr[i] = v, String/Bytes reassign that fits the existing buffer — all reuse existing storage, zero new bytes.
  3. Replace and let it retire. self.f = Struct { ... } whole-value replace memcpys the struct bytes in place, and retires what only the replaced value reached at the method’s activation boundary, recycling it on the next store: its String clones (since v0.11.3), its Bytes, and its nested records, tuples, arrays and payload enums with everything under them. Steady-state replace of any struct holds the arena flat, and so does a tuple, array or payload-enum field replaced whole. A nested block the new value carries over from the field itself (self.f = F { n: i, inner: self.f.inner }) is kept, not copied; one it takes from anywhere else is copied, so a field never shares a block it will retire.
  4. Bound the container. capacity slots, bounded[T; N], @form(ring_buffer) / @form(lru_cache) are cap-bounded by type.
  5. Give it to a child. An accept’d child locus owns its own arena, reclaimed when the child ends — the per-connection shape (see rule C4).
  6. Send it. Bus payloads ride a per-dispatch arena, reclaimed after delivery.

One structural consequence to internalize: a run() loop is a single never-ending activation. Its method scratch never resets and pending retires never flush. What an iteration makes is reclaimed when the iteration ends — a method’s loop body gets a region of its own per iteration — as long as the body keeps nothing past it: it assigns no binding declared before the loop a value that is not a scalar or a locus reference, hands a call only its own values, scalars and bare locus references (a callee could write into anything else), makes no locus, and uses no outer bounded or BytesMut. So let c = body.chunk() or { break; }; h.update(c); straight in run() is flat. A body that has to carry a heap value from one iteration to the next, or that churns a field of self, belongs in a method called from the loop — the method boundary is the reclaim point for those. (This is why the churn examples in this guide run their bodies through a method.)


2. The shape catalog

Section titled “2. The shape catalog”

Eleven idiomatic shapes. Every locus, type or free fn in a well-written program matches one; code that doesn’t should be reconsidered against the catalog before shipping.

2.1 App locus — outer encapsulation

Section titled “2.1 App locus — outer encapsulation”

Every app’s main.hl defines a top-level locus that owns the whole run; fn main() reads argv, instantiates it, exits.

locus Onboard {
params { dir: String = "fixture"; flavor: String = "go"; }
run() { drive(self.dir, self.flavor); }
}
fn drive(dir: String, flavor: String) {
println("onboarding ", dir, " ", flavor);
}
fn main() {
let mut dir = "fixture";
if std::env::args_count() > 1 { dir = std::env::arg(1); }
Onboard { dir: dir };
}

2.2 Namespace locus — empty params, methods only

Section titled “2.2 Namespace locus — empty params, methods only”

A coherent vocabulary of pure helpers wrapped in a locus with empty (or config-only) params { }. The language’s substitute for “module of functions” / “static class”.

locus Morpheme {
params { flavor: String = "go"; }
fn lookup_morpheme(m: String) -> String { ... }
fn name_to_motion(name: String) -> String {
let hit = self.lookup_morpheme(name);
...
}
}

Config-only params are fine; the point is no lifecycle state. Promote three-plus related free fns into one of these when the vocabulary becomes visible; leave unrelated helpers as free fns (a “util” namespace of strangers is an anti-pattern).

2.3 Service locus — long-lived, lifecycle + bus

Section titled “2.3 Service locus — long-lived, lifecycle + bus”

The full lifecycle for a thing that genuinely runs over time.

locus Listener {
params {
host: String = "127.0.0.1";
port: Int = 0;
listen_fd: Int = -1;
on_connection: fn(std::io::tcp::Stream) = default_on_connection;
}
birth() {
self.listen_fd =
std::io::tcp::listen_socket(self.host, self.port) or raise;
}
run() { ...accept loop... }
dissolve() { std::io::tcp::close_fd(self.listen_fd); }
}

2.4 Spawned child locus — let-bound, scope-dissolves

Section titled “2.4 Spawned child locus — let-bound, scope-dissolves”

A let-bound locus literal lives for the fn body and dissolves at scope exit (the m82 dissolve-timing rule).

fn handle_one_connection(conn_fd: Int, on_conn: fn (std::io::tcp::Stream)) {
let s = std::io::tcp::Stream { conn_fd: conn_fd, owns_fd: false };
on_conn(s);
}

2.5 Data collection — @form locus with a domain facade

Section titled “2.5 Data collection — @form locus with a domain facade”

Keyed or growable data lives in a @form(hashmap) / @form(vec) locus. The idiomatic wrapper is thin domain methods over the form’s synthesized surface — a facade that names the operations in the domain’s vocabulary:

type Sig { key: Int = 0; px: Decimal = 0.0d; seq: Int = 0; }
@form(vec)
locus SigRows { capacity { heap rows of Sig; } }
locus SigList {
params { rows: SigRows = SigRows { }; }
fn append(s: Sig) { self.rows.push(s); }
fn count() -> Int { return self.rows.len(); }
fn at(i: Int) -> Sig { return self.rows.get(i) or Sig { }; }
}

The form locus carries the synthesized surface (push / get / set / len / …); the facade holds it as a field and names the domain operations. (Domain methods directly on the form locus also work; the two-locus split keeps the form swappable and the facade’s methods flush-friendly.)

This shape recurs across every production codebase surveyed (a downstream service defines it four times; pond and bench pervasively). Conventions learned there:

2.5b Membership set — @form(set)

Section titled “2.5b Membership set — @form(set)”

When the question is is this present rather than what is stored here, use @form(set). It is the hashmap slot and runtime with a different surface:

type Item { key: String; }
@form(set)
locus Seen { capacity { pool items of Item indexed_by key; } }

insert(v) / contains(k) -> Bool / remove(k) / len() / is_empty().

The reason not to reach for @form(hashmap) with a throwaway value: membership then reads get(k) or false at every call site — the value plumbing leaking back out of a container whose value nobody wants. Sync disciplines work identically (@form(set, sync = striped)).

2.6 Shape type — pure data, no flow

Section titled “2.6 Shape type — pure data, no flow”
type Request { method: String; path: String; body: String; }

Returnable by value; no lifecycle. Types may hold fn(...) fields. If methods accumulate on a concept, it has flow — it wanted to be a locus.

2.6b Secret-owning locus — @sealed, one classified operation

Section titled “2.6b Secret-owning locus — @sealed, one classified operation”

Key material, a token, anything the rest of the program must never hold. The shape is not an analysis; it is the ownership model doing its job with one word added.

@sealed locus Signer {
params { env_var: String = "SIGNING_KEY"; key: Bytes = b""; }
birth() { self.key = std::bytes::from_string(std::env::var(self.env_var)); }
fn ready() -> Bool { return len(self.key) > 0; }
@effects(is: { secret_use })
fn sign(m: Bytes) -> Bytes {
if !self.ready() { return b""; }
return std::crypto::hmac_sha256(self.key, m);
}
}

Four rules, each load-bearing:

When a revealed credential has to be reshaped on its way out — a client secret percent-encoded into a form body — reshape it in the statement that sends it, with what only computes a value (std::url::encode, a conversion, +) or a fn of your own built from those: the result stays the secret, held to the same one statement. A helper that also logs, stores or calls a method is refused, and the message names that call. [error]

A sealed locus may not also carry contract { expose … }: sealing denies every external read, so the expose grants nothing, and the pair is rejected rather than left to read as permission. Callers use the locus’s methods.

Then the application states its own rule with claim forms that already exist:

claims {
no_plugin_secrets: forbid reaches(plugins, effects(secret_use));
one_op_per_request: bound secret_use <= 1 on paths from handlers;
vault_confined: require sealed(all vaults);
}

Prefer std::secret::Signer / Credential to writing your own. Write your own when the operation is neither HMAC nor credential comparison, and keep it small enough to read: the sealed locus’s own body is trusted, which is the assumption the shape rests on.

This is confinement, not information flow. A signature derived from the key is not tracked, and a constant-time compare still lets the verdict be published.

2.7 Error-check fn — value error → structural failure

Section titled “2.7 Error-check fn — value error → structural failure”

A locus method that catches a fallible call’s error and decides between recovery (substitute a value) and escalation (drain and notify the parent) pairs an or self.method(err) clause with an epoch inline closure:

locus DbConnection {
params { conn_fd: Int = -1; last_error: String = ""; }
bus { subscribe ExecuteQuery as on_query; publish QueryResult; }
closure fatal_io { captures: last_error; epoch inline; }
fn handle_io(e: DbError) -> Row fallible(ClosureViolation) {
self.last_error = e.detail;
if e.kind == "send_failed" { violate fatal_io; }
return Row { data: "" };
}
fn on_query(q: Query) {
let r = send_query(self.conn_fd, q)
or (self.handle_io(err) or { return; });
QueryResult <- r;
}
}

2.8 Quantity — a counted unit, not a bare Int

Section titled “2.8 Quantity — a counted unit, not a bare Int”

Declare a quantity when a number has a unit a reader could get wrong: money, time, bytes, ticks. The value is still the Int it counts, but the compiler now refuses the mix-ups (5ms + 4KiB, a bare count where a duration goes) and makes every exact conversion for you.

unit cent;
unit USD = 100 cent;
unit B;
unit KiB = 1024 B;
unit mK;
type Money = quantity Int in cent;
type ByteCount = quantity Int in B;
type TempDelta = quantity Int in mK;
type Celsius = point TempDelta { origin: 273_150 mK; }
type Line { qty: Int; price: Money; }
fn total(l: Line) -> Money { return l.qty * l.price; }
fn main() {
let l = Line { qty: 3, price: 12USD };
let cap: ByteCount = 4KiB;
let room = Celsius(21_000mK);
let started = std::time::monotonic();
if std::time::monotonic() - started > 50ms { println("slow"); }
println(total(l), " ", cap, " ", room);
}

Narrowing is C8. The contract is spec/units.md, the walk-through the book’s “Units, end to end”.

2.9 Message union — a set type

Section titled “2.9 Message union — a set type”

When a message is one of several kinds and each kind is a record of its own, the union is a set of those types. The member’s type is the tag, so nothing is named twice:

type NewOrder { id: Int; qty: Int; }
type Cancel { id: Int; }
type Inbound = NewOrder | Cancel;
fn parse(line: String) -> Inbound {
if line == "cancel" { return Cancel { id: 1 }; }
return NewOrder { id: 2, qty: 5 };
}
fn describe(m: Inbound) -> String {
return match m {
NewOrder(n) -> "new " + to_string(n.qty),
Cancel(c) -> "cancel " + to_string(c.id),
};
}
fn main() { println(describe(parse("cancel"))); }

When another locus consumes the union, a seam (2.10) writes the dispatch for you. Don’t write it by hand.

2.10 Seam — decoder, handler, encoder in one tower

Section titled “2.10 Seam — decoder, handler, encoder in one tower”

A protocol edge is three pieces that should not know each other: a decoder that knows the bytes, a handler that knows its domain, and an encoder that writes the answer. Write each as a locus and let a seam stitch them. The compiler writes the dispatch and checks it.

type NewOrder { id: Int; qty: Int; }
type Cancel { id: Int; }
type Ack { id: Int; }
type Reject { id: Int; why: String; }
type WireError { at: Int; }
type Inbound = NewOrder | Cancel;
type Outbound = Ack | Reject | WireError;
locus Wire {
fn decode(b: String) -> Inbound fallible(WireError) {
if b == "cancel" { return Cancel { id: 1 }; }
if std::str::starts_with(b, "new ") {
let qty = std::str::parse_int(b[4..]) or { fail WireError { at: 4 }; };
return NewOrder { id: qty * 10, qty: qty };
}
fail WireError { at: 0 };
}
fn encode(o: Outbound) -> String {
return match o {
Ack(a) -> "ack " + to_string(a.id),
Reject(r) -> "reject " + r.why,
WireError(e) -> "bad frame at " + to_string(e.at),
};
}
}
locus Desk {
params { open: Int = 0; }
fn new_order(n: NewOrder) -> Outbound {
if n.qty > 10 { return Reject { id: n.id, why: "too big" }; }
self.open = self.open + 1;
return Ack { id: n.id };
}
fn cancel(c: Cancel) -> Outbound {
self.open = self.open - 1;
return Ack { id: c.id };
}
}
locus Gateway {
params { wire: Wire = Wire { }; desk: Desk = Desk { }; }
seam answer(frame: String) -> String {
frame
-> self.wire.decode
-> self.desk
-> self.wire.encode;
}
}
fn main() {
let g = Gateway { };
println(g.answer("new 3"), "; ", g.answer("cancel"), "; ", g.answer("??"));
}

2.11 Wire record — what a surface carries

Section titled “2.11 Wire record — what a surface carries”

The records that a surface’s rows name are its contract. The codec, the description, the generated clients and the digest all read them, so choose each field’s shape for what the caller must be able to say:

role operator;
type Status = enum { Up, Degraded(String), Down };
type Check { name: String; status: Status; }
type HealthQuery {
verbose: Bool = false;
since?: Time;
}
type Health {
checks: bounded[Check; 16] indexed_by name;
note?: String;
}
type Problem = enum { @not_found NotFound(String), @unavailable Busy };
type Restart { name: String; }
api Ops requires: [operator] {
rpc Probe::health requires: [];
rpc Probe::restart;
}
locus Probe {
fn health(q: HealthQuery) -> Health {
let mut h = Health { };
push(h.checks, Check { name: "db", status: Status::Up }) or discard;
push(h.checks, Check { name: "cache", status: Status::Degraded("cold") }) or discard;
if q.has_since {
h.note = "since " + std::time::iso8601(q.since);
}
return h;
}
fn restart(r: Restart) -> Health fallible(Problem) {
if r.name != "db" { fail Problem::NotFound(r.name); }
return Health { };
}
}
fn main() {
let p = Probe { };
let q = HealthQuery::api_decode("{\"since\":\"2026-10-18T00:00:00Z\"}") or HealthQuery { };
println(Health::api_encode(p.health(q)));
}
{"checks":{"db":{"status":"Up"},"cache":{"status":{"Degraded":"cold"}}},"note":"since 2026-10-18T00:00:00Z"}

2.12 Repository — @repo(T), one class per method

Section titled “2.12 Repository — @repo(T), one class per method”

State that matters (an order, a ledger row) lives behind a repo: a locus marked @repo(T) that the compiler holds to the whole method set over the key the db tag names, with one state class on each method and, on every write, whether repeating it is safe. Hand-write the driver; keep validation in a wrapper that calls inward, not in the driver.

type Item { id: Int `db:"id,key"`; n: Int; }
type ItemError = enum { @not_found Missing };
@repo(Item)
locus Items {
@effects(is: { reads(Item) })
fn get(id: Int) -> Item fallible(ItemError) { fail ItemError::Missing; }
@effects(is: { creates(Item) }) @idempotent
fn create(o: Item) -> Item fallible(ItemError) { return o; }
@effects(is: { writes(Item) }) @not_idempotent
fn put(id: Int, o: Item) -> Item fallible(ItemError) { return o; }
@effects(is: { deletes(Item) }) @idempotent
fn remove(id: Int) fallible(ItemError) { }
}
fn main() { let i = Items { }; }

2.13 Fleet — a deployment of other seeds’ mains

Section titled “2.13 Fleet — a deployment of other seeds’ mains”

A deployment is a seed of its own holding one fleet locus: its params are other seeds’ main loci, through their imports; placement gives each a default host or replica count; bindings names the topics that wire them, each with a declared subject:; claims state the law across the instances. It holds no code and never runs: hale fleet check <seed> derives the routes from the instances’ artifacts and judges the claims over them as one graph.

import "../desk" as desk;
import "../venue" as venue;
import "../shared" as t;
fleet locus Prod {
params {
orders: desk::Orders;
gw: venue::Gateway;
}
placement {
orders: host("box-a");
gw: replicas(2);
}
bindings {
t::OrderRequest: unix("/run/orders.sock");
}
claims {
one_desk: count publishers(topic t::OrderRequest) == 1;
no_return: forbid reaches(gw, orders);
}
}

Naming conventions

Section titled “Naming conventions”
Construct Convention Example
Locus / type PascalCase Listener, Request
Method / field snake_case name_to_motion, listen_fd
Lifecycle decl drop the fn keyword run() { ... }
Free fn bare snake_case drive, handle_one_connection
Bus subject dot-separated, lowercase log.app.db
Constants UPPER_SNAKE_CASE STDLIB_AP_SOURCE
Unit its symbol: short, in the case its domain writes it ms, bp, cent, KiB, USD

A unit name is written against a number with no space (500ms, 3bp), so it reads like the stdlib’s time units: short and mostly lower-case, with an established symbol keeping its case (KiB, mK). Two names are refused outright: one a literal already owns as a suffix (d is the Decimal literal’s, e5 a Float exponent — “unit d: a unit named d collides with the Decimal literal’s suffix: 3d is the Decimal 3; give it another name”), and a builtin type’s (Bytes, String), which a type position reads before any declaration. Hence ByteCount, not Bytes, for a count of B.

Library exports: pick short lowercase import aliases; name decls to read naturally under the alias (fin::Quote, not fin::FinQuote). See spec/projects.md for the seed model.

This document is tested

Section titled “This document is tested”

spec/styleguide.md is the most prescriptive file in the repo, and until 2026-08-03 nothing checked a line of it. That is how §7 came to assert that a generic payload enum “compiles, constructs, and matches today” when it does not construct — the claim was written once and never executed again.

Two gates now run in the normal suite:

If you add a claim about the language here, add the test with it.

Canonical form — hale fmt is the arbiter

Section titled “Canonical form — hale fmt is the arbiter”

Mechanical style is not a judgment call: hale fmt (v0.11.9, spec/testing.md) defines the canonical form, zero config, and hale fmt --check gates it in CI. Don’t hand-enforce anything in this list — run the tool:

Line structure. fmt shapes long statements. Write a statement on one line and let hale fmt break it when it is too wide: it breaks every shape one way, so don’t hand-wrap, and a line that fits it leaves alone (it never joins lines, so where a line that fits breaks is still yours — but for a seam, whose shape is fmt’s). What fmt cannot do is name things, and one rule of line structure is about names: a condition of more than three terms is extracted into a named predicate, a fn whose name says what the terms decide. Four terms wrap into a column fmt can format but no reader can take in at a glance; the predicate’s name is the rule the if applies, and its body is where the terms are listed, once:

// The four classes the board decides, named once.
fn needs_board(change_class: String) -> Bool {
return change_class == "organization"
|| change_class == "constitutional"
|| change_class == "process-policy"
|| change_class == "topology";
}
fn required_authority(change_class: String) -> String {
if needs_board(change_class) {
return "board";
}
return "leader";
}
fn main() {
println(required_authority("topology"));
}

The rest of what fmt does not decide is where the rest of this guide applies: naming, comment content, and blank-line placement (it collapses runs, it never inserts or removes the single separators you chose). Write the shape; let the tool make it canonical. For agents this is load-bearing: canonical form means a model-written diff touches only the lines it changed.

Embedded text is a block string

Section titled “Embedded text is a block string”

Text with a syntax of its own — a Hale program a test writes to disk, a SQL query, a JSON body — is a block string (spec/tokens.md § Block strings), written as it reads and indented with the code around it, never an escaped one-liner of \" and \n. The block is raw, so the embedded text’s own escapes ("a\n" in a Hale string, \" in JSON) go in unchanged, and a reviewer reads the program a fixture runs instead of decoding it. Leave a blank line before the closing fence when the text is a file, which ends with a line break.

Rolling the design

Section titled “Rolling the design”

The catalog is small on purpose. A new primitive must roll into the seed: mirror an existing shape (a reader who knows one knows it at a glance) and interlock in composition (its outputs are valid inputs to existing consumers). A primitive that needs a paragraph of “this one works differently” is a new category, not a rolled one — log the friction, don’t ship the invention.


3. Correctness rules

Section titled “3. Correctness rules”

Each rule is tagged with its enforcement status: [error] the compiler rejects it, [warn] the compiler warns by default, [@hot] checked only inside @hot fns, [@effects] checked when the fn declares the matching effect assertion (@effects(none: {…}) or its @no_* sugar), [convention] nothing checks it — the guide is the enforcement.

C1. Value ownership on assignment — trust it, know the edges

Section titled “C1. Value ownership on assignment — trust it, know the edges”

Assignment of heap values into self-storage has value semantics with single ownership: every slot exclusively owns its blobs. self.g = self.f copies; a struct literal embedding a self.<field> read copies; replacing the source never corrupts the destination. You don’t defend against aliasing — the compiler/runtime maintain the invariant (and anchor retirement depends on it). [structural — the substrate handles it]

The edge that remains yours: views. .view() / .text_view() are non-owning windows over a builder’s buffer, valid only until the next overwrite/recv. Persist one with std::str::clone / std::bytes::clone; on reuse-buffer protocols adopt the deferred-clear discipline — clear the builder at the start of the next cycle, not the end of this one, so views handed out stay valid between frames (pond websocket’s client is the reference). [convention]

C2. Fd and resource ownership

Section titled “C2. Fd and resource ownership”

C3. Placement and starvation

Section titled “C3. Placement and starvation”

C4. accept / release — flows, not residents

Section titled “C4. accept / release — flows, not residents”

Declaring accept(c: Child) without release(c: Child) makes every accepted child a resident: it lives until the accepting locus dissolves. On a daemon that’s O(accepted-children) growth until OOM — the canonical accept-loop leak. Declare release(c: Child) to make children flows, reclaimed when their run() completes; or terminate them from a handler.

locus Conn {
params { fd: Int = -1; }
run() { while true { let f = recv(...); if f.closed { return; } ... } }
}
locus Server {
accept(c: Conn) { }
release(c: Conn) { } // ← Conn is a flow: reclaim on run() return
}

The compiler warns on accept-without-release when the accepting locus’s run() loops forever; run-to-exit programs accepting a bounded batch stay silent. [warn]

C5. Bus discipline

Section titled “C5. Bus discipline”
topic Posted { payload: Msg; keyed_by room; }
locus Room {
params { name: String = "lobby"; }
bus { subscribe Posted as on_post where key == self.name; }
fn on_post(m: Msg) { ... } // only this room's traffic arrives
}

Keys may be Int / Decimal / Time / Duration / Bool / no-payload enum / String (String keys are hash-gated — non-matching traffic costs one integer compare per entry). An if m.room == self.name in the handler is the anti-pattern this exists to delete: it makes every instance pay for every message. Keys are captured by value at registration — re-keying means dissolve + re-instantiate. on_unmatched: picks the no-match policy (swallow / fail / fallback). [convention; the routing itself is checked]

type Reply { conn: Int; body: String; }
topic Replies { payload: Reply; subject: "app.replies"; keyed_by conn; }
locus Conn {
params { id: Int = 0; }
bus { subscribe Replies as on_reply where key == self.id; }
fn on_reply(r: Reply) { println(r.body); }
}

[convention]

C6. Dispatch shape

Section titled “C6. Dispatch shape”

else if chains and match (statements and expressions, with String / enum-payload / guard arms) are all first-class. A command router over a String field is a match:

fn on_command(f: Frame) {
match std::json::find_string_field(f.json, "type") {
"hello" -> self.on_hello(f),
"join" -> self.on_join(f),
"research" -> self.on_research(f),
_ -> println("unknown command"),
}
}

Deep } else { if ... } } ladders (a 16-deep one shipped in causality before String-match landed) are a legacy shape — rewrite on touch. F.18 exhaustiveness is checked in both positions; expression-position arms must agree on one type. [error for non-exhaustive / mismatched arms]

C6b. Prefer only: to an enumerated none:

Section titled “C6b. Prefer only: to an enumerated none:”
@effects(only: { alloc }) // closed — future-proof
@effects(none: { syscall, block, publish, time, entropy, env,
ffi, spawn, recursion }) // open — rots

none: lists what is forbidden and permits everything else, so a contract meaning “this handler only allocates” has to enumerate every other class — and the list is a snapshot. Add a class to the language, or declare one of your own with effect NAME;, and every such contract silently permits it. The annotation still reads “only alloc” and no longer means it. Nothing fails; the certificate quietly weakens.

only: states the permitted set and is checked against the complement computed at check time from the classes that actually exist. Nothing is written down that can go stale. [convention — reach for none: only when you genuinely care about one or two classes]

C7. @form constraints (the sharp edges of 2.5)

Section titled “C7. @form constraints (the sharp edges of 2.5)”

C8. Narrow with a policy, never by hand

Section titled “C8. Narrow with a policy, never by hand”

A conversion that divides can lose a remainder: / by a literal, a quantity into a coarser denomination (.in(USD), a binding or a field of a coarser type). Each says what becomes of the remainder — or floor, or ceil, or trunc, or half_up, or half_even, or <value>, or raise, or fail E { … } — or the target type says it once with { round: …; }:

unit cent;
unit USD = 100 cent;
type Money = quantity Int in cent;
fn main() {
let fee: Money = 250cent;
let share = fee / 3 or half_even;
let dollars = fee.in(USD) or floor;
let count: Int = (fee.in(USD) or half_even) / 1USD;
let wait = 1500ms.in(s) or ceil;
println(share, " ", dollars, " ", count, " ", wait);
}

Two reasons. The compiler refuses the bare form, at the site:

type error: `Money` divided by 2 leaves a remainder: say what happens to the remainder: `or floor`, `or <value>`, `or raise`, or give `Money` a `round:` policy

And the policy is the reader’s record of the rounding: a ledger that rounds half-even says so where it does, instead of in an Int division three calls away. Don’t route around it by dividing Ints you pulled out of a quantity — that is the hand-rolled rounding the rule exists to name.

The one division that takes no policy is a quantity’s count in a unit, fee / 1USD: an Int quotient that truncates toward zero, as Int’s / does, and a runtime divisor (d / n) is the same integer division. When the count must round another way, narrow first, as count above does. [error for an unnamed narrowing]

C9. A bounded is a value: count it, build it from a literal, copy it whole

Section titled “C9. A bounded is a value: count it, build it from a literal, copy it whole”

A bounded[T; N] is a fixed-capacity list. Its operations are the intrinsics; a literal at a declared site builds one; a local, a return and a whole assignment each hold a copy of their own. Four edges follow, and the check refuses the wrong side of each:

type Row { names: bounded[String; 4]; }
fn fill(r: Row) {
push(r.names, "a") or discard;
push(r.names, "b") or discard;
}
fn first_two() -> bounded[String; 4] {
let mut out: bounded[String; 4] = ["x"];
push(out, "y") or discard;
return out;
}
locus Roster {
params { row: Row = Row { }; spare: Row = Row { }; }
fn refill() {
let mut mine = Row { };
fill(mine);
self.row = mine;
self.spare.names = first_two();
println(count(self.row.names), " ", count(self.spare.names));
}
}
fn main() { let r = Roster { }; r.refill(); }

C10. A served HTTP edge: cap it in your own shape, and stream from a pool that parks

Section titled “C10. A served HTTP edge: cap it in your own shape, and stream from a pool that parks”
std::http::Server {
port: 8080,
handler: Feed { },
max_request_bytes: 65536,
too_large: std::http::Response { status: 413, content_type: "application/json", body: "{\"error\":\"too large\"}" },
};
fn handle(req: std::http::Request) -> std::http::Response {
let w = std::http::SseWriter { conn_fd: req.conn_fd };
for t in self.ticks {
w.event(std::http::SseEvent { event: "tick", data: Tick::api_encode(t) }) or { break; };
}
return w.end();
}

C11. A default reads its own fields and constants, nothing of the caller

Section titled “C11. A default reads its own fields and constants, nothing of the caller”

A default is evaluated where the literal or call that leaves it is written, and the check refuses one that reads that scope. Build a field’s or a parameter’s default of literals, constants, free fns, types and variants. A locus param’s default may also read earlier params through self.<param>. [enforced]

const LIMIT: Int = 5;
type Page { size: Int = LIMIT; from: Int = 0; }
fn fetch(p: Page = Page { }) -> Int { return p.size + p.from; }
fn main() { println(fetch()); }
type Page { size: Int = limit; } // refused: `limit` is the caller's
fn main() { let limit = 9; let p = Page { }; }

Why: a default that reads a caller’s local means something different at every literal. It binds the declaration to names its callers happen to use, and no codec can build it, because the decoder has no caller. Pass what varies as an argument or a field instead. A caller binding with the name of a constant a default reads (let LIMIT = 9 before Page { }) is refused at that literal for the same reason: rename it, or write the field.


C12. Log records through std::log, never free text

Section titled “C12. Log records through std::log, never free text”

A running part’s log is read by the platform as well as by people, so every line it writes is a record: a time, a level, the logger’s path, a message and named fields. Log through a std::log::Logger and let a sink write them (logfmt by default, HALE_LOG_FORMAT=json for one JSON object a line), with the details in fields, not spliced into the message:

fn main() {
std::log::StdoutSink { };
let log = std::log::Logger { name: "orders" };
log.warn_kv("retrying", std::log::kv("order", "o-17") + " " + std::log::kv("attempt", "2"));
}

A bare println in a served or attached program is free text the collector cannot parse; it is the standard-practices pack’s first clause (standard/logs-are-structured, GH #1591), which the Board holds in review until the compiler can check it. [convention]


C13. Hold the metrics scrape and the event export as params of main

Section titled “C13. Hold the metrics scrape and the event export as params of main”

A program’s metrics are read by the platform, which scrapes one endpoint. Hold it as a param of the main locus, place it, and keep the registries where the work is:

main locus App {
params {
reg: std::metrics::Registry = std::metrics::Registry { namespace: "orders" };
metrics: std::observe::Scrape = std::observe::Scrape { port: 9100 };
}
placement { metrics: pinned; }
}
fn main() { App { }; }

Every live Registry is on the page, with the runtime’s own series, and the endpoint is in the topology artifact for the deployment to annotate. A std::http::Server hand-wired to a std::metrics::Endpoint serves one registry, none of the runtime’s series, and a port nothing outside the source knows about; keep it for a second page you mean to have. Place the scrape pinned, so a busy pool never delays a scrape and a scrape never delays the pool. The same holds for the runtime’s lifecycle events: hold a std::observe::Otlp param, placed pinned, and let the OTLP environment name the collector, rather than logging births and failures by hand. [convention]

C14. Hand a writer one owner’s records per call

Section titled “C14. Hand a writer one owner’s records per call”

A method that hands a record to a callee which writes through it hands it the arena the record’s owner allocates in: the locus’s own arena for a record a field of self holds, its caller’s for a record parameter. One call has one such arena, so a call that hands a writer records of both owners is refused. That covers two arguments, or one carrier that may be either:

type Bag { b: Bytes = b""; }
locus Sink {
params { held: Bag = Bag { }; }
fn put_two(a: Bag, b: Bag, p: Bytes) { a.b = p; b.b = p; }
fn refill(x: Bag, p: Bytes) {
let mine = Bag { b: x.b };
self.put_two(self.held, mine, p);
}
}
fn main() { let s = Sink { }; }

4. Speed rules

Section titled “4. Speed rules”

First ask: is this path hot? Hot means a per-frame/per-message handler, a tight parse loop, an ingest path — hundreds per second and up. If not, stop here: the defaults are correct and fast (method scratch reclaims per call; the compiler elides scratch for non-allocating helpers entirely). Gold-plating a cold path buys nothing and costs shape.

For genuinely hot paths, the idioms below are the difference between flat RSS at 100k msg/s and a daemon that dies nightly. Each is production-derived. Certify the path when done — S10.

Two rules are the exception, and they apply to every path: S15 and S16. Their cost is memory that grows with the square of a text’s size, so a cold path that handles one large body is enough to exhaust a host.

S1. Reuse buffers via params fields

Section titled “S1. Reuse buffers via params fields”

The single highest-value idiom. A locus that processes frames holds its buffers as fields and reuses them every frame:

locus WsConn {
params {
rx_buf: std::bytes::BytesBuilder = ...; // frame reassembly
tx_buf: std::bytes::BytesBuilder = ...; // send assembly
scratch: std::bytes::BytesBuilder = ...; // unmask/inflate
}
}

A locus or BytesBuilder instantiated inside a handler or loop allocates a fresh arena/buffer every message (~4.5 KB/frame measured in production) that reclaims only at method return — and its chunk only at dissolve. The compiler warns on this shape by default. pond websocket (three reused builders), the downstream service’s conn writer, and causality’s runner all converged on the fields shape independently. [warn; error under @hot]

S2. recv_into, not allocating recv

Section titled “S2. recv_into, not allocating recv”

recv_into(fd, buf, max) appends into a reused builder’s tail — zero-alloc. The allocating recv family returns a fresh buffer per call; in a loop that accumulates until the method returns. [warn in loops]

S3. Zero-copy views with the deferred-clear discipline

Section titled “S3. Zero-copy views with the deferred-clear discipline”

Read assembled data with .view() / .text_view() instead of snapshot() / finish() — the latter copy the builder’s whole contents per call. Views are valid until the next overwrite; C1’s deferred-clear discipline makes them safe across frames. [@hot: snapshot-in-loop is flagged]

S4. Mutate scalars in place; replace structs judiciously

Section titled “S4. Mutate scalars in place; replace structs judiciously”

In-place scalar mutation (self.state.px = v) is allocation-free. Whole-struct replace (self.state = State{...}) is correct — the struct bytes memcpy in place and the replaced value’s String clones, Bytes and nested blocks retire — but each store still pays an anchor-clone + retire per String field and per nested block, and a walk of the old and new values when the struct nests one. On a certified-hot path prefer in-place writes for the fields that changed; keep the replace when most fields genuinely change (construction-position init is legitimate now that retirement reclaims it). [@hot hint]

One shape to know: re-anchoring a field only on transition (e.g. a websocket message’s kind re-anchors only on a text/binary flip, not per frame) keeps replace costs off the per-frame path entirely — the pond client does this.

S5. Strings/Bytes that fit, stay in place

Section titled “S5. Strings/Bytes that fit, stay in place”

self.f = <String/Bytes> reuses the existing buffer when the new value fits. Bounded-variance fields (timestamps, fixed headers, checksums) hit the memcpy path forever. Any other length clones and retires the abandoned buffer, String or Bytes, for the next store to reuse (a String field’s blocks come in size classes, so its memory stays bounded by its largest value) — but each such store still pays the clone, so genuinely variable-length hot fields belong in a reused BytesBuilder + view instead. [convention]

S6. Pre-render once, fan out many

Section titled “S6. Pre-render once, fan out many”

When one event fans out to N consumers, render the common payload once at ingest and let each consumer add only its per-consumer delta (a sequence prefix, a connection id). N× the delta beats N× the render — the downstream service renders its update JSON once and its N connections each prepend a seq. [convention]

S7. Two-flavor emitters

Section titled “S7. Two-flavor emitters”

Build human-path output with std::json::Builder (a locus — fine in cold paths), and hot-path output with raw concat into a reused buffer. Keeping both flavors side by side (render / render_pre) documents which callers are hot. [convention]

S8. Counted loops unlock BCE; helpers are free

Section titled “S8. Counted loops unlock BCE; helpers are free”

for j in 0..coll.len() (exclusive, literal-0 lower bound, no mutation of coll in the body) lets codegen elide the per-get bounds check and vectorize — measured in bench’s form-vec microbenches. And factor freely: non-allocating fns/methods cost nothing (interprocedural scratch elision since 2026-06-28) — hot code does not need to be monolithic code. [convention]

S9. Flat payloads; batch drains

Section titled “S9. Flat payloads; batch drains”

Transitively pointer-free payload types skip the serialize/ deserialize wire path entirely on cross-thread delivery — prefer scalar payloads for high-rate topics. A where zero_copy binding holds its payload to that shape at check: scalar fields, nested flat structs, and fixed arrays of Int / Float / Bool / Decimal / Duration, which are laid out inline; an array of structs or of Time, a slice, a String or Bytes is refused (“payload type … is not flat-shapeable”). For high-rate consumers, a Drain<T> handler runs once per queue drain with a zero-copy for over the batch instead of once per message. [convention]

S10. Certify the path

Section titled “S10. Certify the path”

When a hot path is clean, pin it:

@hot @budget(alloc_per_call = 0) fn on_frame(m: Frame) { ... }

@hot turns this guide’s warnings into hard errors inside the fn and enables the stricter hints (S3, S4). @budget(alloc_per_call = N) is the counted contract — the compiler proves the ceiling transitively through callees and fails the build on violation; N = 0 is the zero-alloc certificate. The downstream service carries @budget(alloc_per_call = 0) on its send path, its gateway ingest, and its state facade — the contracts are also the documentation. [opt-in errors]

S11. Event-driven ingest, not polling

Section titled “S11. Event-driven ingest, not polling”

One reader locus per source, on a where async_io pool, parked on readiness (udp::Reader, tcp recv) — no set_recv_timeout poll loops. Measured: ~4 µs p50 wake latency, stable over hours. Poll-scanner sleeps accumulate tail latency debt that looks like a runtime problem but isn’t. [convention]

S12. Cache cross-locus handles at boot

Section titled “S12. Cache cross-locus handles at boot”

A hot path that looks something up by string key in another locus (a metrics counter, a symbol table) resolves the handle once at boot and stores it as a field:

params { c_ticks: metrics::Counter; } // resolved in main(), threaded in
fn dispatch(m: Msg) { self.c_ticks.inc(); }

Per-call keyed lookups walk a hashmap and allocate a search temp in scratch — fine cold, waste hot. (Same idiom as Go/Rust metrics code; not Hale-specific.) [convention]

What’s already free — don’t optimize these

Section titled “What’s already free — don’t optimize these”

Raw-fd free fns vs Stream

Section titled “Raw-fd free fns vs Stream”

Both work. The Stream locus methods are the default idiom — they carry owns_fd semantics and fallible returns (fallible(IoError)); the __-prefixed free fns (__send_bytes / __recv_bytes / …) are the raw escape hatch for pooled/borrowed fds where locus lifecycle would fight the ownership (note their return convention: 0 = success, -1 = error — not a byte count). Historical reports of the free fns crashing natively do not reproduce on ≥ v0.10.0 and the surface is regression-tested. [convention]


S13. Compose with chains, not hand-rolled loops

Section titled “S13. Compose with chains, not hand-rolled loops”
// idiomatic
let n = self.users.filter(it.active).count();
self.users.filter(it.active).into(self.actives);
let total = self.users.map(it.age).sum();
let oldest = self.users.max(it.age) or raise;
self.users.filter(it.active).each { self.greet(it); }
let page = self.users.skip(20).take(10).count();
self.users.filter(it.active).sort_into(self.ranked, older_first);
self.orders.group_count_into(self.by_desk, it.desk);
// not this
let mut i = 0;
let mut n = 0;
while i < self.users.len() {
let u = self.users.get(i) or { break; };
if u.active { n = n + 1; }
i = i + 1;
}

A chain is not a value being built — it is rewritten to exactly the loop on the right, so the two have identical cost. Prefer the chain because it is shorter to read, and because stages fuse: two filters are one pass, where the hand-rolled version invites an intermediate.

A chain runs over a @form(vec) source directly (self.users), and over a @form(hashmap) source anchored on .entries (self.book.entries.filter(...).count()) — the same pseudo-field a for e in m.entries loop iterates, walking the hashmap’s occupied slots. .items is the explicit vec anchor. The element it is the stored value in both.

Three properties make chains safe on a hot path, and they are worth knowing rather than assuming:

Whole-set operations (sort_into, reverse_into, group_count_into) cannot fuse — they need every element before producing any — so they materialize into caller storage: the chain fills (or bumps) a collection you declared, then reorders it in place. That cost is visible in the budget, which is the point. Positional selection (take(n) / skip(n)) and the element’s ordinal (enumerate(), binding idx) DO fuse — they are counters on the one loop, not materializations.

S14. Let a seam split a producer’s set

Section titled “S14. Let a seam split a producer’s set”

The shape is 2.10’s; this is what it costs on a hot path.

type A { n: Int; }
type B { s: String; }
type In = A | B;
locus Parse { fn parse(x: Int) -> In { if x > 0 { return A { n: x }; } return B { s: "neg" }; } }
locus Handle {
fn a(v: A) -> Int { return v.n * 2; }
fn b(v: B) -> Int { return len(v.s); }
}
locus Front {
params { p: Parse = Parse { }; h: Handle = Handle { }; }
// idiomatic: the seam writes the dispatch
seam go(x: Int) -> Int {
x
-> self.p.parse
-> self.h;
}
// not this: the same chain written by hand
fn go_by_hand(x: Int) -> Int {
return match self.p.parse(x) { A(v) -> self.h.a(v), B(v) -> self.h.b(v), };
}
}

The two compute the same thing, and only the seam is free of the set. A method’s set result is built in its scratch and copied whole into its caller’s arena, and the caller’s match reads the tag back from that copy. A seam that splits what a hop returns calls a clone of the hop that hands the set back in the seam’s own frame, the member copied out as itself beside its tag; inlined into the seam, each of the producer’s returns goes straight to its arm, with no tag read and no switch (seam_fusion.rs pins the optimized IR). A hop that hands the whole set on to a method taking the set (an encoder of the outbound set, say) is not split and is built as any set is.

S15. Grow a long text in one place, and hand it on after the loop

Section titled “S15. Grow a long text in one place, and hand it on after the loop”

This rule applies on every path, hot or not. An appending assignment (out = out + chunk, out += chunk, out = f"{out}…") on a local declared let mut, or on a String field of self, appends into a buffer that place owns and grows geometrically, so building n bytes costs O(n) (spec/stdlib.md § “Building a String”). It stays linear only while nothing else holds the text: a read of the local that may keep the value (the local passed to a call, bound, stored or returned) gives the buffer up, and the next append copies the whole text first. So read the growing text in the loop only as an operand of + or of a comparison, in a slice, or as an argument of a std:: reader that returns a number or a Bool (len, std::str::contains, index_of, starts_with), and hand it on after the loop:

fn page(n: Int) -> String {
let mut out = "[";
let mut i = 0;
while i < n {
if i > 0 { out += ", "; }
out = out + "{\"id\": " + to_string(i) + "}";
i = i + 1;
}
return out + "]";
}
fn main() { println(page(3)); }

Two shapes are still quadratic, and the hot-path lint reports both at the append: a loop that appends to a local and also hands it to a call (out += row; log(out);), and an append to any other place (rec.body = rec.body + row), which builds a fresh String the size of the whole each time. For those, and for a buffer that outlives one call, append into a std::bytes::BytesBuilder: it grows by doubling and holds the text once, plus slack:

locus JsonList {
params {
buf: std::bytes::BytesBuilder = std::bytes::BytesBuilder { initial_cap: 4096 };
n: Int = 0;
}
fn add(entry: String) {
if self.n > 0 { self.buf.append_str(", "); }
self.buf.append_str(entry);
self.n = self.n + 1;
}
fn text() -> String {
let b = self.buf.snapshot() or b"";
return std::str::from_bytes(b);
}
}
fn main() {
let rows = JsonList { };
rows.add("{\"id\": 0}");
println("[" + rows.text() + "]");
}

Until GH #1947 every + made a new String and the frame’s arena kept each one until the method returned, so a loop of appends held every prefix it made: a 350 KB text built in 8000 appends peaked at 4.5 GB. It now peaks at 4 MB. A chain of + (a + b + c) is one allocation. std::str::join joins a @form(vec) of Strings in one allocation. [convention]

S16. Read a long text by position, never by slicing off the rest

Section titled “S16. Read a long text by position, never by slicing off the rest”

This rule also applies on every path. rest = rest[(nl + 1)..] copies the remainder for each line, and each copy stays in scratch until the method returns: the square an append that copies makes (S15).

To take a text apart by a separator, by line or by whitespace, loop over a text source (spec/semantics.md § Text sources). It is the walk by position below, already written: one view, one pass, a copy of each part and nothing else.

fn count_rows(all: String) -> Int {
let mut rows = 0;
for line in std::str::lines(all) {
if len(line) > 0 { rows = rows + 1; }
}
return rows;
}
fn main() { println(count_rows("a\nb\n\nc")); }

std::str::split(s, sep) keeps empty parts, and std::str::words(s) never yields one. [convention]

For any other scan, walk the text by position. std::str::bytes_view measures it once, byte_at reads a byte against that length, and std::str::slice(v, start, end) copies only the part:

fn line_end(v: std::str::ByteView, start: Int) -> Int {
let mut i = start;
while i < v.n {
if std::str::byte_at(v, i) == 10 { return i; }
i = i + 1;
}
return v.n;
}
fn count_rows(all: String) -> Int {
let v = std::str::bytes_view(all);
let mut rows = 0;
let mut start = 0;
while start < v.n {
let nl = line_end(v, start);
let line = std::str::slice(v, start, nl);
start = nl + 1;
if len(line) > 0 { rows = rows + 1; }
}
return rows;
}
fn main() { println(count_rows("a\nb\n\nc")); }

Measured over 1 MB in 2 000 lines: slicing off the rest grew the peak by 984 MB, and reading by position by under 1 MB, in under a millisecond. To find the next line, or any separator, search the view: std::str::find(v, "\n", start) answers the index into the text, at the cost of the distance to the hit. std::str::index_of_from(s, "\n", start) measures the whole String on every call, so a line-at-a-time scan with it is quadratic in time: 16 MB in 32 000 lines took 4.7 s, against under a millisecond with find. [convention]

Walk code points by position too: std::str::view_cp_at(v, i) and view_cp_size(v, i) read a character against the view’s n, where the String forms cp_at / cp_size look for the String’s end before every read, so a walk with them is quadratic (1 MB of text: 2.4 s, against 0.5 ms over the view). [convention]

S17. Hash a stream as it passes, never the collected whole

Section titled “S17. Hash a stream as it passes, never the collected whole”

std::crypto::sha256(b) needs all of b in memory, so hashing a download or a file that way holds the whole input. Feed a std::crypto::Sha256 the pieces as they pass instead: update(piece) absorbs into a fixed 112-byte context, and finish() answers the same 32 bytes sha256 would of the pieces joined. A file on disk is one call, std::crypto::sha256_file(path), which reads it 1 MiB at a time. Make each piece inside a method call, as absorb does below: a piece built in the loop body of run() itself stays in the locus’s region until the locus dissolves, while a method’s scratch goes when it returns.

locus Verifier {
params {
path: String = "";
}
fn absorb(h: std::crypto::Sha256, buf: std::bytes::BytesBuilder) {
let piece = buf.snapshot() or b"";
h.update(piece);
}
run() {
let f = std::io::file::open(self.path, "r") or { return; };
let buf = std::bytes::BytesBuilder { initial_cap: 1048576 };
let h = std::crypto::Sha256 { };
while true {
buf.clear();
if std::io::tcp::recv_into(f.fd, buf, 1048576) <= 0 { break; }
self.absorb(h, buf);
}
println(std::hex::encode(h.finish()));
}
}
fn main() { let v = Verifier { path: std::env::arg(1) }; }

Measured over a 10 GiB file, as peak resident set: sha256_file 5.4 MB and this loop 6.7 MB, against 4.7 MB for a program that hashes nothing; the same loop with the piece made in run()’s own body grew by the input (1 GiB held 1 GB). Both ran as fast as sha256sum (4.7 to 4.9 s against 4.9 s, on a CPU with the SHA extensions). hale verify passes the loop above with no @unbounded. [convention]


5. The enforcement ladder

Section titled “5. The enforcement ladder”

The compiler backs this guide in tiers. Everything default is advisory or genuinely-broken-only; strictness is opt-in where you certify a path — plus one tier you get for free because your placement already declared the intent.

Tier Check Status
error (default) blocking run() on a cooperative subscriber (dead receiver); unowned subscriber in a handler; non-exhaustive / type-mismatched match, a set’s included (2.9); a seam’s coverage, failure placement and one-tower rules (2.10); @form cell constraints; the unit laws, and a narrowing with no policy (C8); a bounded’s len, its return by value and an element stored through a parameter’s place (C9); a default that reads the caller’s scope (C11); a writer handed a held record and a parameter in one call (C14) build fails
warn (default) unbounded-alloc survey (self-escaping allocs in unbounded contexts; retirement-aware since v0.11.3); subscription nothing publishes to; blocking call on a cooperative pool (interprocedural); accept-without-release on a daemon advisory
hot-path (opt-in) locus/builder in a loop or bus handler; a locus factory’s result bound there; allocating recv in a loop — hale check --warn-hot-path, and every hale verify (GH #1948: off by default, so a first program’s ordinary loop is not reported) advisory
string-match (opt-in) three or more if tests in a row comparing one String with literals, which a match (with | alternatives) says once — --warn-string-match on hale check or hale verify (off by default for both) warnings
@hot (opt-in) the hot-path findings as errors within the fn; snapshot()/finish() in a loop; whole-struct self-field replace errors in certified fns
@budget (opt-in) alloc_per_call = N counted transitively; N=0 zero-alloc certificate build fails on violation
@effects (opt-in) @effects(none: {syscall, block, time, entropy, env, ffi, publish, spawn, recursion, stdio}) / @effects(publish: {T}), and the @no_* / @deterministic sugar — checked transitively; diagnostics carry the call chain to the offending leaf build fails on violation
@sealed (opt-in) a sealed locus’s params are reachable only from inside its own methods — reads and writes both. The tier that makes state confinement structural; loci are otherwise not field-encapsulated. hale check --sealable reports what taking it would cost build fails on violation
placement-implied (automatic) a handler on a cooperative(pool = X) where async_io locus that reaches a blocking call — the placement is the assertion, so no annotation is needed; writing @no_block upgrades it to an enforced error advisory
fmt (CI gate) hale fmt --check — canonical mechanical form (§2, “Canonical form”); exit 1 lists offenders gate in CI; hale fmt fixes
escape hatches @unbounded (fn or lifecycle hook) acknowledges intentional accumulation; --allow-unowned-subscriber; --no-warn-unbounded-alloc
advisory tools hale check --sealable (which loci could seal today); hale check --flows (which release clause makes each type a flow); hale check --strict-secret (the fail-closed @secret walk — loud by design, because one body’s reasoning is not a containment proof); hale check --units (every narrowing by site, with its factor and the policy that discharged it and where that policy came from, and each quantity’s headroom — record it and review its diff) opt-in reports

Where law lives

Section titled “Where law lives”

The tiers above certify a function. Claims certify a system, and the only real style question is which closed world owns each sentence.

Two claim verbs quantify over the whole closed world rather than over a path, which makes them the right shape for a baseline a team adopts once: require sealed(all G) (every locus in the group keeps its state to itself) and require attributed(all C) (every fn that directly performs built-in class C names a user-declared purpose). Both cover code nobody has written yet, where a group-scoped claim does not. Prefer them for policy; keep forbid reaches for the specific edges a design forbids.

The built-in group program (every locus and free fn of the entrypoint’s own seed) gives forbid reaches the same reach: a law over program covers code nobody has written yet, and a policy seed can state it without asking an adopter for vocabulary. The one every served or attached program should adopt says it writes to the terminal only through its logger:

constitution Logs {
logs_structured: forbid reaches(program, effects(stdio)) avoiding std::log::*;
}

So log through std::log, never println, outside a CLI’s own output: stdio is the class of a write to standard output or standard error, and std::log is the gate, so a bare print anywhere in the program is the witness. The stdlib ships it as std::law::Standard, so adopt that rather than restating it, in the source, in an environment, or from outside with hale check --adopt std::law::Standard.

Two habits worth keeping. Declare the vocabulary a claim quantifies over — an undeclared group is an error, and a group that is legitimately empty says so with may_be_empty rather than being allowed to hold vacuously. And read uncertified as work to do, not as a pass: it means the model has a hole where the claim needed to look.

Resource budgets (--dump-resource-budget, --check-resource-budget <toml>, --warn-resource-leak) gate thread / pool / subject / fd counts in CI — see spec/verification.md.


6. Anti-patterns

Section titled “6. Anti-patterns”

7. Boundaries — deliberate absences, open gaps, sharp edges

Section titled “7. Boundaries — deliberate absences, open gaps, sharp edges”

Three different kinds of “the language doesn’t do X” live here, and they call for three different behaviors from you: absences you should stop wanting (the design says no, and names the shape to use instead), gaps you can expect to close (write the workaround knowing it’s temporary), and sharp edges you step around (current limitations, no promise either way). Current as of v0.25.0 (2026-10-18); shipped-and-gone entries are removed on shipping — keyed String routing, match-as-expression, whole-struct replace reclamation and its nested-compound fields, err in an or fail payload, Duration arithmetic, return in a lifecycle body, inline fixed-array payload fields, qualified @form cell types, an Int returned from a -> Float fn and an Int into a Float let or field all lived here once.

Deliberate absences — the design says no

Section titled “Deliberate absences — the design says no”

Not on any roadmap. Each has a blessed shape; reaching for the absent thing means fighting the design, not waiting on it.

Open gaps — expect these to close

Section titled “Open gaps — expect these to close”

Write the workaround knowing it’s a placeholder.

Sharp edges — current limitations, step around them

Section titled “Sharp edges — current limitations, step around them”

Implementation constraints, not positions; no promise attached. One of them passes hale check and fails only at hale build: know it cold.

If the catalog seems to be missing a pattern, log a friction entry with the smallest reproducible example — the catalog grows from real friction, not speculation. (That’s also how entries move between the buckets above: friction against a deliberate absence is a design conversation, not a feature request.)


Appendix A. Leak-hunt diagnostics

Section titled “Appendix A. Leak-hunt diagnostics”

The workflow that pins a leak, in escalation order:

Terminal window
# 1. Confirm + identify the growing arena (1 Hz heartbeat dump)
LOTUS_ARENA_RESIDENCY=1 ./binary
# + call std::process::dump_arena_residency() from a hot path
# 2. Log every chunk attach with arena labels
LOTUS_ARENA_LOG_CHUNK_ATTACH=4096 LOTUS_ARENA_LOG_BIG_MAX_EVENTS=0 \
LOTUS_ARENA_RESIDENCY=1 ./binary
# grep 'kind=root label=<grower>' → the allocating call site
# 3. Pool stats at thread exit (atexit-only — long-running daemons
# must exit early to capture; add a fixed-duration run mode)
LOTUS_CHUNK_POOL_STATS=1 ./binary
# 4. Static sweep — the model-side view of the same question
hale check app.hl # unbounded-alloc survey is default-on
hale check app.hl --dump-alloc-summary

Compose 1 → 2 → source grep; that exact chain pinned the May-2026 per-instance residuals. Full env-var reference: spec/runtime.md § “Diagnostic env vars”. The compiler-side ladder (§5) is the static complement — prefer fixing the shape it names over chasing the trace.

Cross-references

Section titled “Cross-references”