Last updated: 2026-11-26
Designing Well-Behaved PatLang Programs
For new readers
Each section below states a convention, gives the reasons for it, and ends with its key rule. The example programs run as shown, interpreted and compiled, and print what follows them.
Long-lived programs, shared libraries and services need clear boundaries: what state they hold, what inputs they reject, what events they accept, and what resources they keep open. These conventions build on three PatLang 2.0 guarantees: no global variables, argument checking on every call, and built-in require/ensure contracts.
1. State lives in values you can see FoundationalKnowledge that endures for decades โ core principles
PatLang 2.0 removed set_var, set_global and get_global. Functions take explicit parameters, and a program's state lives in state objects passed to the functions that need them.
- Explicit boundaries. Without ambient state, a function's parameters list everything it can touch. Readers can see its side effects at a glance, and threads cannot race on a hidden table.
- Logical state grouping. Group related state into objects with clear purposes (a
SessionState, aRenderBuffer), and pass each to the functions that use it. Awhenhandler takes no arguments, so a program whose handlers need its state holds one context object withcontext_holdfromlib/context.patlang, and each handler reads it withcontext_held. That object's fields are the program's state objects.
include "lib/context.patlang"
class Log {
field lines = []
}
when order_placed do
let log = context_held()
log.lines = list_push(log.lines, "placed " + event_data)
end
when order_shipped do
let log = context_held()
log.lines = list_push(log.lines, "shipped " + event_data)
end
let log = new("Log")
context_hold(log)
emit("order_placed", "tea")
emit("order_shipped", "tea")
emit("order_lost", "cake")
print(log.lines)
[placed tea, shipped tea]
The includes are written as a program in the repository's self_hosting folder writes them. A handler reads its event's data as event_data, and an event no handler is declared for does nothing: order_lost above is emitted and ignored.
2. A clear API: prefixes, contracts and explicit return values FoundationalKnowledge that endures for decades โ core principles
Three habits make a library's API predictable and resilient to misuse:
- Name prefixes. Prefix every function a library defines with its name (
stock_new,stock_add). PatLang has no namespaces, and two of a program's files defining one name is an error, naming the function, before the program runs. - Contracts for bug prevention. Use
requireclauses to catch the caller's errors, such as a negative quantity. A failed precondition stops the program with exit code 3, naming the function and the clause: the right response to a call that can only be a bug. - Return values for expected failures. Expected operational outcomes, such as running out of stock, are part of a correct program. Return
["ok", result]or["refused", reason], and let the caller look at the first element. PatLang has no exceptions, so a tagged list like this is how a caller handles a failure and carries on.
# stock.patlang: every name it defines starts with stock_
class Stock {
field counts = []
}
make a function called stock_new returns s
return new("Stock")
end
# the count held for an item, 0 for one never added
make a function called stock_count takes s, item returns n
require type_of(s) == "Stock"
let k = 0
while k < list_len(s.counts) do
if s.counts[k][0] == item then
return s.counts[k][1]
end
let k = k + 1
end
return 0
end
make a function called stock_set takes s, item, n returns done
let kept = []
let k = 0
while k < list_len(s.counts) do
if s.counts[k][0] != item then
let kept = list_push(kept, s.counts[k])
end
let k = k + 1
end
s.counts = list_push(kept, [item, n])
return true
end
# a quantity that is not a positive int is the caller's mistake: a contract
make a function called stock_add takes s, item, n returns total
require (type_of(s) == "Stock") and (type_of(n) == "int") and (n > 0)
stock_set(s, item, stock_count(s, item) + n)
let total = stock_count(s, item)
ensure total >= n
return total
end
# too few in stock is a thing that happens: a value the caller looks at
make a function called stock_take takes s, item, n returns got
require (type_of(s) == "Stock") and (type_of(n) == "int") and (n > 0)
let have = stock_count(s, item)
if have < n then
return ["refused", "only " + have + " " + item + " in stock"]
end
stock_set(s, item, have - n)
return ["ok", have - n]
end
let s = stock_new()
print(stock_add(s, "tea", 3))
print(stock_take(s, "tea", 2))
print(stock_take(s, "tea", 5))
print(stock_add(s, "tea", 0 - 1))
print("not reached")
3
[ok, 1]
[refused, only 1 tea in stock]
contract violation: precondition failed in stock_add(): type_of(s) == "Stock" and type_of(n) == "int" and n > 0
A comment above each function says what it gives back. Keep a function to three or four parameters, and pass an object whose fields name the rest, as Functions and calls in PatLang 2.0 describes. A last parameter named rest collects every further argument as a list, so give that name only to a parameter meant to do it.
require to fail fast on invalid arguments, and return tagged lists (["ok", v] or ["refused", reason]) for expected operational outcomes.3. Declare every event once, at the top level Applied / MethodologicalKnowledge with a 5โ10 year half-life โ stable practice
In PatLang 2.0, a when statement registers its handler as it runs.
- Top-level registration. Declare all event handlers unconditionally at the top level of your main file. A
wheninside anifregisters nothing when the condition is false, one inside a function registers only once the function is called, and one inside a loop registers once on every pass, so a singleemitthen runs it several times. - Controlled outer surface. Use
signal_allow(names)to declare which events other programs can trigger. A message naming an event not on the list, or one without the run's token, is dropped unanswered. - Standard daemon signals. Implement
status(a synchronous report throughsignal_reply), one verb for the program's main action (rebuild,refresh), andquit(a clean shutdown).
let i = 0
while i < 3 do
when tick do
print("tick")
end
let i = i + 1
end
emit("tick", 0)
tick
tick
tick
signal_allow.4. Long-running daemons and task budgeting Applied / MethodologicalKnowledge with a 5โ10 year half-life โ stable practice
A resilient daemon combines structured state, top-level event handling, an allowed signal port and a loop that keeps answering.
- Poll between work units. Do the work in small steps and call
signal_pollbetween them, so astatusorquitarriving mid-work gets a prompt answer. - Budgeted slices. Run a step that may take longer in
budgeted(ms, handle) { ... }, which pauses it oncemshave passed and gives back a handle to continue it, so the loop can poll between slices. - Clean port lifecycle. Claim a port the system chooses with
signal_claim(0), and give it back on shutdown withsignal_release(port), which closes the listener and removes the run's token, so the port is free at once.
Here a second thread plays the part of another program, asking for the status and then sending quit:
include "lib/signals.patlang"
include "lib/context.patlang"
class Worker {
field done = 0
field stopping = false
}
when status do
let w = context_held()
signal_reply("done=" + w.done)
end
when quit do
let w = context_held()
w.stopping = true
signal_reply("stopping")
end
make a function called work_one takes w returns n
w.done = w.done + 1
return w.done
end
let w = new("Worker")
context_hold(w)
let port = signal_claim(0)
signal_allow(["status", "quit"])
let asker = thread_spawn(|p| do
sleep_ms(300)
let a = signal_query(p, "status", "")
let b = signal_query(p, "quit", "")
return [a, b]
end, port)
while not w.stopping do
work_one(w)
signal_poll(port, 50)
end
print(thread_result(asker))
signal_release(port)
print("released " + (tcp_try_connect("127.0.0.1", port) < 0))
[done=6, stopping]
released true
The count in the first line depends on how many units ran in the first 300 ms. The build daemon demo is a larger program built the same way.
5. Resource ownership: acquire and release in the same function Applied / MethodologicalKnowledge with a 5โ10 year half-life โ stable practice
Ports, connections, files, threads and logic stores must be managed explicitly, or they leak.
- Strict function scope. The function that acquires a resource releases it on every path out, early returns included. Callers then never inherit an open resource they did not ask for.
- Sockets and ports. Listen on port 0 and use the number the call gives back, close connections with
tcp_close, and free listeners withtcp_unlisten(port), which frees the port at once; a thread still waiting on that listener intcp_accept_timeoutgets -1. Usetcp_try_writewhere the peer may have gone: it givesfalsewheretcp_writewould stop the program. - Atomic file writes. Never write over a file others may be reading. Write a temporary file beside it and replace the target with
try_rename_file, so a reader or a crash never meets half of it. Useappend_filefor logs: each call's bytes go to the file's end however many threads or programs append at once. Neither call flushes to the disk itself, so what was written survives the program's crash and not a power cut. - Thread completion. Take every thread's result with
thread_result, which waits for it and gives back what the thread held, so its outcome is handled explicitly. - Logic stores. Prefer
logic_store_new(), whose store goes when its last holder does, tologic_store_named(name), which lives untilstore_delete(name).
# serves one client on a port the system chooses, and gives the port back
make a function called serve_once takes greeting returns got
let port = tcp_listen(0)
let client = thread_spawn(|p| do
let c = tcp_connect("127.0.0.1", p)
let text = tcp_read(c)
tcp_close(c)
return text
end, port)
let conn = tcp_accept_timeout(port, 5000)
if conn < 0 then
tcp_unlisten(port)
return ["refused", "no client came"]
end
tcp_write(conn, greeting)
tcp_close(conn)
tcp_unlisten(port)
return ["ok", thread_result(client)]
end
# a reader of path sees the old text or the new one, never part of either
make a function called save takes path, text returns ok
let tmp = path + ".tmp"
if not write_file(tmp, text) then
return false
end
return try_rename_file(tmp, path)
end
let got = serve_once("hello")
print(got)
print(save("out/reply.txt", got[1]))
print(read_file("out/reply.txt"))
print(append_file("out/log.txt", "served " + got[1] + chr(10)))
[ok, hello]
true
hello
true
6. Workers share nothing they write Applied / MethodologicalKnowledge with a 5โ10 year half-life โ stable practice
PatLang has no locks. A vec, a string builder or an object's fields belong to one thread at a time, and two threads changing one at once stop the program with exit code 98 when they meet, which depends on timing, so a program that shares one may run correctly many times before it stops.
- Isolated inputs and outputs. Give parallel workers distinct inputs (with
parallel_map, for instance), let each process its share independently, and combine the results only after every worker has finished. - Progress in virtual files. Where workers must report progress while they run, each writes a virtual file of its own (
vfs_write("/progress/" + id, ...)): threads may write virtual files together, and the reader adds them up. Theport_marshalpackage's status line works this way.
make a function called count_words takes text returns n
let n = 0
let inword = false
let b = bytes_from_str(text)
let k = 0
while k < bytes_len(b) do
let space = bytes_get(b, k) == 32
if (not space) and (not inword) then
let n = n + 1
end
let inword = not space
let k = k + 1
end
return n
end
let counts = parallel_map(["the curly dog", "sat on the mat", "and slept"], "count_words")
print(counts)
let total = 0
let k = 0
while k < list_len(counts) do
let total = total + counts[k]
let k = k + 1
end
print(total)
[3, 4, 2]
9
7. Service discovery and marshalling Ephemeral / ToolingKnowledge that evolves in months to a year โ check for updates
Avoid fixing port numbers in advance across programs that talk to each other.
- Beacons.
signal_announce(task_name, port, actions)fromlib/signal_discovery.patlangpublishes a program's port and the actions it accepts. Other programs find it by name withsignal_discover_all(max_age_ms), or by what it can do withsignal_find_capable(keyword, max_age_ms), which give only beacons written withinmax_age_ms: a program announces again from time to time while it runs, and one that has stopped drops out. The self-orchestrated microservices demo works this way. - Port marshalling. For programs on one machine, the
port_marshalpackage (packages/port_marshal) runs a marshaller on one fixed port: each program listens on port 0 and registers a name, and a client that asks for the name is piped through to it, so programs no longer contend for fixed ports.
8. Network boundaries and code from elsewhere Applied / MethodologicalKnowledge with a 5โ10 year half-life โ stable practice
Crossing to other machines or including code from other authors needs its own defences. Until a program does either, it stays on one machine: a PatLang listener binds 127.0.0.1 alone, so no other machine can connect to it, and the signals it answers carry a token written to a file only the same user can read.
- Explicit network access. A program reaches other machines only once it declares
tcp_allow_remote(), which it does once, for the whole program; until then, connecting to any other address stops it. Declare it near the top of the main file so a reader sees that the program talks to the network. - No secrets in plain TCP.
lib/http_client.patlangspeaks HTTP/1.1 without TLS, and the TLS client is being built (thetlspackage has its ciphers so far), so send nothing you would not show whoever is on the path. - Bounded reads. Treat every incoming byte as untrusted: limit how much you read and for how long, as
read_boundedbelow does, and check the shape of what arrives before acting on it. - No dynamic execution of received data. Never pass bytes from a socket, or from a file of unknown origin, to
exec_capture, into a file a program will include, or to a function chosen by name. - Package trust verification. Code from elsewhere runs with the whole authority of the program that includes it: it can read and write files, start processes and open sockets. A world, and an isolate built on one, isolates state, not authority, so running code in one is no sandbox. Check a package before you include it:
packages/tools/verify_manifest.patlangchecks its files against the SHA-256 hashes in its manifest, and thetrustpackage'strust_verify_package(dir, pin, verify)checks its release against the publishing group's log, every step signed by a quorum of the group's members, back to the genesis hash you pinned when you chose to trust that group. The signature check is passed in, so it can come from the operating system. The trust store that remembers pins and the installer that runs these checks are designed and not yet built, so for now a program calls them itself; Packages, resolution and trust describes the records and checks in full.
# what a peer sends, up to max bytes and for at most ms: ["ok", text] when it
# ends its message, or ["refused", reason] when it sends too much or too long
make a function called read_bounded takes conn, max, ms returns got
let b = sb_new()
let have = 0
let deadline = clock_ms() + ms
while true do
let left = deadline - clock_ms()
if left <= 0 then
return ["refused", "no end within " + ms + " ms"]
end
let st = tcp_read_status(conn, left)
if st[1] == "data" then
let have = have + str_len(st[0])
if have > max then
return ["refused", "more than " + max + " bytes"]
end
sb_push(b, st[0])
elif st[1] == "end" then
return ["ok", sb_str(b)]
elif st[1] == "error" then
return ["refused", "the connection failed"]
end
end
return ["refused", "unreachable"]
end
make a function called peer_sends takes text returns got
let port = tcp_listen(0)
let sender = thread_spawn(|p, t| do
let c = tcp_connect("127.0.0.1", p)
tcp_write(c, t)
tcp_close(c)
return true
end, port, text)
let conn = tcp_accept_timeout(port, 5000)
let got = read_bounded(conn, 16, 2000)
tcp_close(conn)
thread_result(sender)
tcp_unlisten(port)
return got
end
print(peer_sends("short"))
print(peer_sends("a great deal more than sixteen bytes"))
[ok, short]
[refused, more than 16 bytes]
9. Durable work queues for crash resilience Applied / MethodologicalKnowledge with a 5โ10 year half-life โ stable practice
Signals are live and in memory, and they disappear if either side crashes or restarts.at-least-once: messages may repeat, so be idempotent
- Durable messaging. Put work that must survive a crash through
lib/queue.patlang:queue_publish(topic, payload)writes a durable message, andqueue_consume(topic)reads the next one, even after a restart or from another process. - Idempotent acknowledgement. Call
queue_ack(topic, msg_id)only after the work is done. A message not acknowledged is read again when the consumer restarts, so its handler must be safe to run twice. The queue recovery demo shows this under a real crash and restart.
See also
Functions and calls in PatLang 2.0 for the call rules, rest, and shaping parameters. Design by contract for require and ensure. Worlds, fibers and threads for thread_spawn, parallel_map and budgeted. The build daemon demo for a larger long-running program. Presence, discovery and non-blocking spawn for signal_announce and the discovery calls. The queue recovery demo for the durable queue under a crash. Packages, resolution and trust for the manifest, the trust records and how a release is verified.
Graduate Attributes
Directly developed
- Subject Specialist: Readers choose between in-memory signals and file-backed queues based on whether data must survive a process crash.
- Critical Thinker: Readers evaluate the trade-offs between synchronous blocking queries and fire-and-forget signals to determine the appropriate communication pattern.
Modelled on this page
- Digitally Fluent: Digital information is handled responsibly by distinguishing between ephemeral signal handling and durable message queuing mechanisms.
- Confident Communicator: Complex technical concepts are explained through concrete examples and clear distinctions between different communication patterns.
University of Reading Graduate Attributes framework.