Last updated: 2026-11-21
PatLang Showcase: Replanning, Contract Coverage and Crash-Safe Work
For new readers
Three small programs, each pairing two of PatLang's paradigms: a robot that plans and replans when the building changes around it, a module that reports which of its own contracts have been checked, and a worker that loses no job and that no job can bring down. Each sits beside the same program in Python. The earlier showcase pages are the first four pairs, bounds, streams, worlds and parallel sums and watching, secrets and specifications.the first four pairs
The code shown is the file in the PatLang repository's showcase/ directory, and the output is what PatLang's test gates check it against, on the interpreter and as native builds for Windows and Linux. Each Python version runs in the same gates and prints the same lines, or a file of its own where the two differ by design.
A delivery robot that plans again when the world changes
Goal-oriented planning and events. A robot must carry a parcel from the dock to an office. It knows its actions (pick up, walk, go through a door, take the lift, hand over), each with what it needs, what it changes and what it costs, and asks the planner for the cheapest way to reach "delivered". While it is in the hall, the building raises an event: the office door has been locked. A handler records the change and marks the plan stale, and before its next step the robot plans again from where it stands and takes the slower lift. The same planning code runs both times, from a different starting state.stale plan: the old path no longer works
# A delivery robot that plans, acts, and plans again when the world changes.
#
# Paradigms: goal-oriented planning and events.
#
# The robot must carry a parcel from the dock to an office. It knows its
# actions (pick up, walk, go through a door, take the lift, hand over), each
# with what it needs, what it changes and what it costs, and it asks the
# planner for the cheapest way to "delivered". It then carries the plan out a
# step at a time.
#
# The building is not under its control. While the robot is in the hall, the
# building raises an event: the door to the office has been locked. A handler
# records the change and marks the plan stale; before its next step the robot
# notices, plans again from where it now is, and takes the slower lift. The
# planning code is the same both times; only the state it starts from has
# changed.
class Robot {
field pos = 0
field carrying = 0
field delivered = 0
field door_open = 1
field stale = false
field log = 0
}
# Where the robot is, as text.
make a function called place takes pos returns name
match pos do
case 0 then
return "dock"
case 1 then
return "hall"
case _ then
return "office"
end
end
# The planner's numbers, from the robot's state as it is now.
make a function called observe takes r returns done
fluent_set("pos", r.pos)
fluent_set("carrying", r.carrying)
fluent_set("delivered", r.delivered)
fluent_set("door_open", r.door_open)
return true
end
make a function called replan takes r returns steps
observe(r)
r.stale = false
let steps = plan_numeric([], [["delivered", "==", 1]])
vec_push(r.log, "plan from the " + place(r.pos) + ": " + plan_labels(steps))
return steps
end
let robot = new("Robot")
robot.log = vec_new()
# ---- the actions: needs, changes, cost ----
action_add_numeric("pick_up", [], [["pos", "==", 0], ["carrying", "==", 0]], [], [], [["carrying", "=", 1]], 1)
action_add_numeric("walk_to_hall", [], [["pos", "==", 0]], [], [], [["pos", "=", 1]], 2)
action_add_numeric("through_door", [], [["pos", "==", 1], ["door_open", "==", 1]], [], [], [["pos", "=", 2]], 1)
action_add_numeric("take_lift", [], [["pos", "==", 1]], [], [], [["pos", "=", 2]], 6)
action_add_numeric("hand_over", [], [["pos", "==", 2], ["carrying", "==", 1]], [], [], [["carrying", "=", 0], ["delivered", "=", 1]], 1)
# ---- what each action does when carried out ----
action_bind("pick_up", |args| do
robot.carrying = 1
return true
end)
action_bind("walk_to_hall", |args| do
robot.pos = 1
# the building, not the robot, decides this
emit("door_locked", "office door")
return true
end)
action_bind("through_door", |args| do
robot.pos = 2
return true
end)
action_bind("take_lift", |args| do
robot.pos = 2
return true
end)
action_bind("hand_over", |args| do
robot.carrying = 0
robot.delivered = 1
return true
end)
# ---- the event: the world changed under the plan ----
when door_locked do
robot.door_open = 0
robot.stale = true
vec_push(robot.log, "event: the " + event_data + " is locked")
end
# ---- act, a step at a time, replanning when the plan goes stale ----
let steps = replan(robot)
let i = 0
while robot.delivered == 0 do
if robot.stale then
let steps = replan(robot)
let i = 0
end
let s = steps[i]
activate([s])
vec_push(robot.log, "did " + step_label(s) + ", now in the " + place(robot.pos))
let i = i + 1
end
print(str_join(vec_to_list(robot.log), chr(10)))
print("delivered: " + (robot.delivered == 1))
Output:
plan from the dock: [pick_up, walk_to_hall, through_door, hand_over] did pick_up, now in the dock event: the office door is locked did walk_to_hall, now in the hall plan from the hall: [take_lift, hand_over] did take_lift, now in the office did hand_over, now in the office delivered: true
Python has no planner in its standard library, so its version writes one: a uniform-cost search with heapq over states held as tuples, each action a name, a test, an effect and a cost. The event becomes a callback that the walking step calls. A larger Python project could use a planning package such as pyperplan, which solves STRIPS problems written in PDDL, instead of writing the search.
The Python version
"""The replanning robot of showcase/p12_agent_that_replans.patlang, in Python.
Python has no planner in its standard library, so the sketch writes the one
it needs: a uniform-cost search with heapq over states held as tuples, each
action a name, a test, an effect and a cost. That is the part the PatLang
program gets from plan_numeric. The event becomes a callback the walk action
calls. A Python project could use a planning package (pyperplan, for STRIPS
problems written in PDDL) instead of writing the search.
Prints the same lines as the PatLang program.
"""
import heapq
from itertools import count
PLACES = {0: "dock", 1: "hall", 2: "office"}
# name: (needs(state), effect(state) -> state, cost); a state is a dict of numbers
ACTIONS = {
"pick_up": (lambda s: s["pos"] == 0 and s["carrying"] == 0, lambda s: {**s, "carrying": 1}, 1),
"walk_to_hall": (lambda s: s["pos"] == 0, lambda s: {**s, "pos": 1}, 2),
"through_door": (lambda s: s["pos"] == 1 and s["door_open"] == 1, lambda s: {**s, "pos": 2}, 1),
"take_lift": (lambda s: s["pos"] == 1, lambda s: {**s, "pos": 2}, 6),
"hand_over": (lambda s: s["pos"] == 2 and s["carrying"] == 1, lambda s: {**s, "carrying": 0, "delivered": 1}, 1),
}
def plan(start, goal):
"""The cheapest sequence of action names from start to a state meeting goal."""
tie = count()
frontier = [(0, next(tie), start, [])]
seen = set()
while frontier:
cost, _, state, steps = heapq.heappop(frontier)
key = tuple(sorted(state.items()))
if key in seen:
continue
seen.add(key)
if goal(state):
return steps
for name, (needs, effect, c) in ACTIONS.items():
if needs(state):
heapq.heappush(frontier, (cost + c, next(tie), effect(state), steps + [name]))
return None
class Robot:
def __init__(self):
self.pos, self.carrying, self.delivered, self.door_open = 0, 0, 0, 1
self.stale, self.log = False, []
def state(self):
return {"pos": self.pos, "carrying": self.carrying, "delivered": self.delivered, "door_open": self.door_open}
robot = Robot()
def door_locked(what):
robot.door_open, robot.stale = 0, True
robot.log.append(f"event: the {what} is locked")
def walk_to_hall():
robot.pos = 1
door_locked("office door") # the building, not the robot, decides this
def hand_over():
robot.carrying, robot.delivered = 0, 1
DO = {
"pick_up": lambda: setattr(robot, "carrying", 1),
"walk_to_hall": walk_to_hall,
"through_door": lambda: setattr(robot, "pos", 2),
"take_lift": lambda: setattr(robot, "pos", 2),
"hand_over": hand_over,
}
def replan(r):
r.stale = False
steps = plan(r.state(), lambda s: s["delivered"] == 1)
r.log.append(f"plan from the {PLACES[r.pos]}: [{', '.join(steps)}]")
return steps
steps = replan(robot)
i = 0
while robot.delivered == 0:
if robot.stale:
steps, i = replan(robot), 0
DO[steps[i]]()
robot.log.append(f"did {steps[i]}, now in the {PLACES[robot.pos]}")
i += 1
print("\n".join(robot.log))
print("delivered: " + ("true" if robot.delivered == 1 else "false"))
A program that knows which of its contracts have been checked
Design by contract and logic programming. Every require and ensure clause that passes leaves a fact in the store named contracts, recording the function and the clause's text, once however often it passes. A small stock-keeping module is exercised by a few calls and then asks, with an ordinary query, which of its clauses have run so far. Two of its six clauses, both on write_off, have never been checked until a write-off happens.cf. design-by-contract.html: the full spec
# A program that knows which of its own contracts have been checked.
#
# Paradigms: design by contract and logic programming.
#
# Each require and ensure clause that passes leaves a fact behind in the
# store named "contracts", contract_holds(function, clause), the clause
# written as "require:" or "ensure:" and its text as the runtime prints it,
# recorded once however often it passes. So
# a program can ask, with an ordinary query, which of its contracts have
# actually been exercised, and which functions have never been checked at
# all. Here a small stock-keeping module is exercised by a few calls, then
# reports its own contract coverage: every clause it has, and whether a run so
# far has checked it.
class Stock {
field counts = 0
}
make a function called stock_new returns s
let s = new("Stock")
s.counts = vec_new()
return s
end
# The count for an item, or 0.
make a function called count_of takes s, item returns n
let i = 0
while i < vec_len(s.counts) do
let entry = vec_get(s.counts, i)
if entry[0] == item then
return entry[1]
end
let i = i + 1
end
return 0
end
make a function called set_count takes s, item, n returns done
let i = 0
while i < vec_len(s.counts) do
let entry = vec_get(s.counts, i)
if entry[0] == item then
vec_set(s.counts, i, [item, n])
return true
end
let i = i + 1
end
vec_push(s.counts, [item, n])
return true
end
make a function called receive takes s, item, n returns total
require n > 0
let before = count_of(s, item)
set_count(s, item, before + n)
let total = count_of(s, item)
ensure total == before + n
return total
end
make a function called dispatch takes s, item, n returns total
require (n > 0) and (n <= count_of(s, item))
let before = count_of(s, item)
set_count(s, item, before - n)
let total = count_of(s, item)
ensure (total == before - n) and (total >= 0)
return total
end
make a function called write_off takes s, item returns lost
require count_of(s, item) > 0
let lost = count_of(s, item)
set_count(s, item, 0)
ensure count_of(s, item) == 0
return lost
end
# The clauses each checked function has, in the form the facts record them:
# what coverage is measured against.
make a function called declared returns clauses
return [
["receive", "require:n > 0"],
["receive", "ensure:total == before + n"],
["dispatch", "require:n > 0 and n <= count_of(s, item)"],
["dispatch", "ensure:total == before - n and total >= 0"],
["write_off", "require:count_of(s, item) > 0"],
["write_off", "ensure:count_of(s, item) == 0"]
]
end
make a function called contract_facts takes fn_name, clause returns found
return solve_in(logic_store_named("contracts"), "contract_holds", [fn_name, clause])
end
make a function called checked takes fn_name, clause returns yes
return list_len(contract_facts(fn_name, clause)) > 0
end
make a function called coverage_report returns covered
let all = declared()
let covered = 0
let i = 0
while i < list_len(all) do
let mark = "never checked"
if checked(all[i][0], all[i][1]) then
let mark = "checked"
let covered = covered + 1
end
print(" " + all[i][0] + ": " + all[i][1] + " -- " + mark)
let i = i + 1
end
print(" " + covered + " of " + list_len(all) + " clauses checked")
return covered
end
let s = stock_new()
receive(s, "bolts", 40)
receive(s, "nuts", 25)
dispatch(s, "bolts", 15)
print("== coverage after receiving and dispatching ==")
coverage_report()
print("== the functions checked so far, asked directly ==")
let fns = contract_facts(logic_var("F"), logic_var("C"))
let names = []
let i = 0
while i < list_len(fns) do
let n = fns[i][0]
let seen = false
let k = 0
while k < list_len(names) do
if names[k] == n then
let seen = true
end
let k = k + 1
end
if not seen then
let names = list_push(names, n)
end
let i = i + 1
end
print(" " + str_join(names, ", "))
print("== after a write-off ==")
write_off(s, "nuts")
coverage_report()
Output:
== coverage after receiving and dispatching == receive: require:n > 0 -- checked receive: ensure:total == before + n -- checked dispatch: require:n > 0 and n <= count_of(s, item) -- checked dispatch: ensure:total == before - n and total >= 0 -- checked write_off: require:count_of(s, item) > 0 -- never checked write_off: ensure:count_of(s, item) == 0 -- never checked 4 of 6 clauses checked == the functions checked so far, asked directly == receive, dispatch == after a write-off == receive: require:n > 0 -- checked receive: ensure:total == before + n -- checked dispatch: require:n > 0 and n <= count_of(s, item) -- checked dispatch: ensure:total == before - n and total >= 0 -- checked write_off: require:count_of(s, item) > 0 -- checked write_off: ensure:count_of(s, item) == 0 -- checked 6 of 6 clauses checked
Python's assert leaves no record when it passes, so the sketch writes a decorator that does: each clause is a text and a lambda, and one that holds is added to a set. The ensure clauses compare against values from before the call, which the decorator has to be told how to capture. The icontract package, installed beside Python, provides decorators of this kind and reads each clause's text from the source. In PatLang the functions carry their clauses with nothing added, and the record comes from the runtime.
The Python version
"""The contract coverage of showcase/p13_contracts_as_data.patlang, in Python.
Python's assert is a statement that leaves no record when it passes, so the
sketch writes a decorator that does: each clause is a text and a lambda, and
a clause that holds is added to a set. The ensure clauses need the values
from before the call, which the decorator has to be told how to take
(before=). The icontract package, installed beside Python, has decorators of
this kind, with clauses as lambdas whose text it reads from the source.
PatLang records every require and ensure that passes as a fact, with nothing
added to the functions, and the program asks with an ordinary query.
Prints the same lines as the PatLang program.
"""
import functools
HELD = set() # (function, clause)
def contract(requires=(), ensures=(), before=None):
def wrap(f):
@functools.wraps(f)
def checked(*args):
for text, test in requires:
assert test(*args), text
HELD.add((f.__name__, "require:" + text))
old = before(*args) if before else None
result = f(*args)
for text, test in ensures:
assert test(result, old, *args), text
HELD.add((f.__name__, "ensure:" + text))
return result
return checked
return wrap
class Stock:
def __init__(self):
self.counts = {}
def count_of(s, item):
return s.counts.get(item, 0)
@contract(requires=[("n > 0", lambda s, item, n: n > 0)],
ensures=[("total == before + n", lambda total, before, s, item, n: total == before + n)],
before=lambda s, item, n: count_of(s, item))
def receive(s, item, n):
s.counts[item] = count_of(s, item) + n
return count_of(s, item)
@contract(requires=[("n > 0 and n <= count_of(s, item)", lambda s, item, n: 0 < n <= count_of(s, item))],
ensures=[("total == before - n and total >= 0", lambda total, before, s, item, n: total == before - n and total >= 0)],
before=lambda s, item, n: count_of(s, item))
def dispatch(s, item, n):
s.counts[item] = count_of(s, item) - n
return count_of(s, item)
@contract(requires=[("count_of(s, item) > 0", lambda s, item: count_of(s, item) > 0)],
ensures=[("count_of(s, item) == 0", lambda lost, before, s, item: count_of(s, item) == 0)])
def write_off(s, item):
lost = count_of(s, item)
s.counts[item] = 0
return lost
DECLARED = [
("receive", "require:n > 0"),
("receive", "ensure:total == before + n"),
("dispatch", "require:n > 0 and n <= count_of(s, item)"),
("dispatch", "ensure:total == before - n and total >= 0"),
("write_off", "require:count_of(s, item) > 0"),
("write_off", "ensure:count_of(s, item) == 0"),
]
def coverage_report():
covered = 0
for fn, clause in DECLARED:
mark = "never checked"
if (fn, clause) in HELD:
mark, covered = "checked", covered + 1
print(f" {fn}: {clause} -- {mark}")
print(f" {covered} of {len(DECLARED)} clauses checked")
s = Stock()
receive(s, "bolts", 40)
receive(s, "nuts", 25)
dispatch(s, "bolts", 15)
print("== coverage after receiving and dispatching ==")
coverage_report()
print("== the functions checked so far, asked directly ==")
names = []
for fn, _ in DECLARED:
if any(f == fn for f, _ in HELD) and fn not in names:
names.append(fn)
print(" " + ", ".join(names))
print("== after a write-off ==")
write_off(s, "nuts")
coverage_report()
A worker that loses no job, and that no job can bring down
A durable queue and worlds. Jobs wait in a queue kept on disk. The worker takes the oldest pending job, runs it in a world of its own, and acknowledges it only once it has finished. A job that fails stops its world and nothing else, and is set aside as failed. Here the first worker is made to stop dead partway through its third job; that job is still pending on disk, so the next worker picks it up, finds that it fails, and carries on with the rest. The queue is files, and the isolation is the language's, with no separate process or message broker.
# A worker that loses no job, and that no job can bring down.
#
# Paradigms: a durable queue and worlds.
#
# Jobs wait in a queue kept on disk. The worker takes the oldest pending job,
# runs it in a world of its own, and acknowledges it only when it finished;
# a job that fails stops its world and nothing else, and is marked as failed
# rather than acknowledged. If the worker itself stops between taking a job
# and acknowledging it (here it is made to stop dead during its third), the
# job is still pending on disk, and the next run of the worker picks it up. Nothing
# here is a separate process or a message broker: the queue is files, and the
# isolation is the language's.
include "../self_hosting/lib/queue.patlang"
# A job is "kind argument": sum N adds 1..N, divide N divides 100 by N
# (asserting N is not 0), shout TEXT repeats it with an exclamation mark.
make a function called run_job takes job returns result
let sp = 0
while (sp < job.length) and (job[sp] != " ") do
let sp = sp + 1
end
let kind = substr(job, 0, sp)
let arg = substr(job, sp + 1, job.length - sp - 1)
if kind == "sum" then
let n = to_num(arg)
return n * (n + 1) / 2
elif kind == "divide" then
let d = to_num(arg)
assert d != 0
return 100 / d
elif kind == "shout" then
return arg + "!"
end
assert false
return 0
end
# Takes and runs the pending jobs of topic; gives how many it finished. Each
# job runs in a fresh world. A job whose world stopped has failed: it is
# recorded as failed, so it is not taken again. With crash_at >= 0 the
# worker stops dead after taking that many jobs and the next, before running
# or acknowledging it, as a worker killed mid-job would.
make a function called work takes topic, crash_at, label returns done_count
let done_count = 0
while true do
let ids = queue_pending(topic)
if list_len(ids) == 0 then
return done_count
end
let id = ids[0]
let job = queue_consume(topic)
if done_count == crash_at then
print(" " + label + ": took job " + id + " (" + job + ") and stopped before finishing it")
return done_count
end
let w = world_new()
let result = world_call(w, || do
return run_job(job)
end)
world_free(w)
# a world's call gives ["done", the job's result] or ["stopped", code]
if result[0] == "stopped" then
print(" " + label + ": job " + id + " (" + job + ") failed in its world")
queue_publish(topic + "_failed", job)
queue_ack(topic, id)
else
print(" " + label + ": job " + id + " (" + job + ") gave " + result[1])
queue_ack(topic, id)
end
let done_count = done_count + 1
end
return done_count
end
let topic = "showcase_p14_jobs"
queue_remove_topic(topic)
queue_remove_topic(topic + "_failed")
let jobs = ["sum 100", "shout hello", "divide 0", "divide 8", "sum 10"]
let i = 0
while i < list_len(jobs) do
queue_publish(topic, jobs[i])
let i = i + 1
end
print("== the first worker, which dies during its third job ==")
work(topic, 2, "first worker")
print(" still pending on disk: " + list_len(queue_pending(topic)))
print("== the next worker picks up where it stopped ==")
work(topic, 0 - 1, "next worker")
print(" still pending: " + list_len(queue_pending(topic)))
print(" failed, kept for a person to look at: " + list_len(queue_pending(topic + "_failed")))
queue_remove_topic(topic)
queue_remove_topic(topic + "_failed")
Output:
== the first worker, which dies during its third job == first worker: job 0 (sum 100) gave 5050 first worker: job 1 (shout hello) gave hello! first worker: took job 2 (divide 0) and stopped before finishing it still pending on disk: 3 == the next worker picks up where it stopped == next worker: job 2 (divide 0) failed in its world next worker: job 3 (divide 8) gave 25/2 next worker: job 4 (sum 10) gave 55 still pending: 0 failed, kept for a person to look at: 1
Python's standard library has a good durable store for this in sqlite3: a table of jobs with a status, committed after each change. A job's failure is an exception caught around the job, which keeps it from stopping the worker, though the job still runs in the worker's own process with access to its memory and files. Isolation of that kind needs a subprocess in Python. Where the PatLang output says a job failed in its world, the Python output names the exception.sqlite is disk-backed but not a separate process
The Python version
"""The crash-safe worker of showcase/p14_crash_safe_worker.patlang, in Python.
Python's standard library has a good durable store for this: sqlite3, a
table of jobs with a status, committed after each change. A job's failure is
an exception, caught around the job. That keeps a failing job from stopping
the worker, but the job still runs in the worker's process, with its memory
and files; a PatLang world gives the job facts, files and output of its own.
A job that must not touch the worker at all is, in Python, a subprocess.
Where the PatLang program says a job failed in its world, this one names the
exception; its expected output is
showcase/compare/expected/p14_crash_safe_worker.txt.
"""
import os
import sqlite3
import tempfile
from fractions import Fraction
PATH = os.path.join(tempfile.gettempdir(), "showcase_p14_jobs.sqlite")
def connect():
db = sqlite3.connect(PATH)
db.execute("create table if not exists jobs (id integer primary key, topic text, payload text, status text)")
return db
def show(x):
return str(x.numerator) if isinstance(x, Fraction) and x.denominator == 1 else str(x)
def run_job(job):
kind, _, arg = job.partition(" ")
if kind == "sum":
n = int(arg)
return Fraction(n * (n + 1), 2)
if kind == "divide":
d = int(arg)
assert d != 0
return Fraction(100, d)
if kind == "shout":
return arg + "!"
raise ValueError(job)
def pending(db, topic):
return db.execute("select id, payload from jobs where topic = ? and status = 'pending' order by id", (topic,)).fetchall()
def work(db, topic, crash_at, label):
done = 0
while True:
rows = pending(db, topic)
if not rows:
return done
job_id, job = rows[0]
if done == crash_at:
print(f" {label}: took job {job_id - 1} ({job}) and stopped before finishing it")
return done
try:
result = run_job(job)
except AssertionError:
print(f" {label}: job {job_id - 1} ({job}) failed (AssertionError)")
db.execute("insert into jobs (topic, payload, status) values (?, ?, 'pending')", (topic + "_failed", job))
db.execute("update jobs set status = 'done' where id = ?", (job_id,))
else:
print(f" {label}: job {job_id - 1} ({job}) gave {show(result)}")
db.execute("update jobs set status = 'done' where id = ?", (job_id,))
db.commit()
done += 1
if os.path.exists(PATH):
os.remove(PATH)
topic = "showcase_p14_jobs"
db = connect()
for job in ["sum 100", "shout hello", "divide 0", "divide 8", "sum 10"]:
db.execute("insert into jobs (topic, payload, status) values (?, ?, 'pending')", (topic, job))
db.commit()
print("== the first worker, which dies during its third job ==")
work(db, topic, 2, "first worker")
db.close()
db = connect() # a new worker: only what was committed is there
print(f" still pending on disk: {len(pending(db, topic))}")
print("== the next worker picks up where it stopped ==")
work(db, topic, -1, "next worker")
print(f" still pending: {len(pending(db, topic))}")
print(f" failed, kept for a person to look at: {len(pending(db, topic + '_failed'))}")
db.close()
os.remove(PATH)
Graduate Attributes
Directly developed
- Critical Thinker: Readers compare the implementation details of PatLang against its Python equivalents to judge the trade-offs between language features and external libraries.
- Digitally Fluent: Readers examine code snippets and output logs to understand how different programming paradigms handle planning, contracts and fault tolerance.
Modelled on this page
- Subject Specialist: Technical distinctions between language runtimes and standard libraries are explained with precise terminology regarding state, isolation and contract enforcement.
- Researcher: The limitations of the Python standard library are stated explicitly alongside specific third-party packages that address those gaps.
- Reflective: The design choices behind each paradigm are justified by referencing the specific problems they solve and the costs they incur.
University of Reading Graduate Attributes framework.