activities list from the manual introduction.
The first two blocks define the poll used by later chapters; subsequent fragments
illustrate alternative fields, commands, and views.
Constructing the Machine
Import the small shared-state language:The machine as a state transition
The same definition can be read as a small mathematical model. Let be the configured set of activities and the set of voter identifiers. The persistent state is a partial map from voters to activities: The initial state has no entries: The map insertion has a guard: it applies only when the voter has not voted and the proposed activity belongs to the configured set. When it applies, the transition adds exactly one mapping: Here, is the set of voters already recorded. In the EDSL definition,StateType.choice(constant("activities")) enforces membership
in , while once=True makes the map insertion conditional on the voter key
being absent. The view is derived from the current state; it does not add another
stored field:
Constants
Constants configure a machine but cannot be changed by commands:activities value when the machine
executes.” It does not immediately retrieve a Python value. Explicit references
can be validated and serialized.
Constants commonly contain choices, stakes, capacities, participant counts,
round counts, payoff tables, and mechanism settings.
Fields
Fields persist between commands:votes is a map, every key is text, every value is a
configured activity, and a new poll begins empty.
The initial state is:
StateType is the namespace for shared-state type constructors such as StateType.text() and StateType.integer().
The main field types are:
Records and early validation
UseStateType.record when a value has named fields with different types:
StateType.optional(StateType.text()) permits None; it does
not permit omitting label. Records reject undeclared fields by default. Use
StateType.record({...}, allow_extra=True) for an extensible record: declared fields
remain required and extra values must still be finite JSON data. Use StateType.map
for a dictionary with dynamic keys such as participant IDs.
These schemas serialize with the Machine. EDSL checks them recursively for
initial state, command inputs, and proposed state after commands or close
effects. A bad nested value identifies its member path, such as
account.entries[0].amount. A failed output check prevents the whole transition
from committing.
machine.validate() also checks reference namespaces and lexical bindings in
commands, views, completion conditions, initial values, and close effects.
A local introduced by let, fold, iterate, or a collection expression is
available only in its body. Its initial value, collection, or iteration budget
uses the outer scope. Validation visits both conditional branches, so a typo
cannot hide in a branch that is currently unselected.
For statically known closed records, a literal lookup of an undeclared member
is rejected even when a fallback was supplied. Use an open record when probing
extension fields is intentional. Dynamic keys and runtime-provided context stay
runtime-checked. Map lookup results include the default’s inferred type; a
lookup with a null or unrelated default does not promise a non-null map value.
The checker rejects known incompatible operands for arithmetic, comparison,
text, numeric, and collection operations. Compatible numeric branches widen to
number; compatible records, maps, and sequences retain their nested shapes.
Unrelated branches widen to any in this implementation. This is a conservative
subset of the stricter formal type system.
Authoring failures raise MachineValidationError, which is also a ValueError.
It exposes machine, path, and reason attributes. For example, looking up
balnce on a declared account record reports the containing expression:
if guard makes a nullable value safe, prove an index is
in range, or infer every reducer’s output type. Boolean combinators and command
requirements continue to use truthiness; iterate conditions require Booleans.
Loop invariants
Declare an optionalaccumulator_type for fold or state_type for iterate
when the carried value should satisfy the same contract throughout execution:
amounts as
StateType.sequence(StateType.number()). The invariant serializes with the expression. Static
checks use it to resolve accumulator members and reject known incompatible seed
or body types. Runtime checks validate the seed, even for an empty fold or a
zero-step iteration, and every subsequent carried value. Bounds and other
value-dependent constraints are enforced at runtime. Invariant declarations use
the outer scope, before the loop bindings exist.
Without a declared invariant, the accumulator remains statically unknown; a
shape-changing computation is still legal. Declaring an invariant does not
imply convergence. See issue #2665
for the remaining language work.
Execution limits
EachRuntime entry point gets one shared budget: execute, close,
render_view, complete, initial_state, or a standalone evaluate call.
Recursive calls, lexical bindings, nested maps/folds/iterations, type checks,
and multiple effects share that budget. A separate operation starts fresh;
concurrent calls do not consume each other’s allowance.
All limits must be positive integers. Step accounting is deterministic for this
interpreter implementation, not a time measurement or a promise that each DSL
operator costs one step. Native sorting and ranked-ballot calculations receive
additional work charges. Byte accounting includes an upper bound for JSON
escaping and construction overhead; it is not an exact serialized byte count
or a Python heap measurement. Building a collection can therefore hit a limit
before its final JSON representation reaches the listed number.
Definitions and external state, inputs, and context are checked before recursive
execution. Intermediate values, growing collections, proposed state after every
effect, and combined views are checked as well. Large string/list repetitions
are rejected before allocation.
machine.validate() applies the default
structural limits before serialization; Machine.from_dict and from_json
check incoming definitions before recursive expression decoding. Configuring a
runtime does not relax those authoring and transport checks.
Exhaustion raises ResourceLimitError (a ValueError) and returns no partial
result. A failed command or close does not commit state, advance its SQLite state revision, or append an event. Validation wraps authoring-time failures in
MachineValidationError. The existing per-iterate bound remains an additional
limit and is checked independently.
These are host runtime policies, not serialized Machine parameters. Use the same
policy when reproducing admission/failure behavior. They bound interpreter work
and data, but do not sandbox registered Python callbacks or interrupt arbitrary
callback code; those extensions remain trusted. Interpreter checks verify that a runtime supports the Machine’s features.
Checking interpreter support
A destination must support the expressions, types, and effects used by a Machine. Check this before sending the definition to another interpreter:Commands
A command defines one legal kind of write:arg("voter") and arg("activity") refer to validated command inputs.
They form serializable expressions rather than reading Python variables now.
The put effect adds one map entry. once=True leaves an existing key
unchanged, giving the poll first-write-wins behavior.
Effects and atomicity
The ordinary effects are deliberately few:Requirements
A command can declare when it applies:Explicit rejection and outcomes
Userequire= for the existing behavior: if its condition is false, the command
is processed as a no-op. Use require or reject when an attempted action should
be explicitly refused:
balance and closed fields.
Both helpers serialize as ordinary effects. A runtime that does not support
them rejects the Machine before execution.
require requires a Boolean result. A malformed predicate, invalid input type,
output type mismatch, missing capability, arithmetic error, or exhausted quota
is an execution failure, not an explicit rejection.
Effects are visited in order. The first failing assertion or enabled reject
stops the transition, discards all proposed changes, and skips later effects.
Assertions, like other expressions, read the pre-command snapshot. A preceding
assign does not change what an assertion reads. Put admission checks before
expensive computations and trusted callback effects; the interpreter cannot
undo external side effects performed by Python extensions.
Runtime.execute() returns a CommandResult. Its event and advisory include
status and reason_code:
A rejection is recorded as an event even though the stored fields do not change. Raw in-memory
Runtime calls have no persistence or idempotency; those guarantees come from the
backend.
reason_code is null for applied/no-op decisions. Rejected results omit
the outcomes of discarded effects, so they do not report rolled-back writes as
successful. A false require remains a noop with the existing
requirement_not_met effect outcome, preserving old definitions’ behavior.
Reasons and disclosure
Codes must be literal strings matching[A-Za-z][A-Za-z0-9_.-]{0,63}. They cannot
be expressions, templates, or dynamically generated messages. Return a stable
identifier such as insufficient_funds; do not include balances, bids, participant
traits, or other private values in it. The engine returns the code without
attaching failed operand values or proposed state to the advisory response.
Choosing different codes still reveals which condition failed. Machine authors
must choose codes appropriate for the recipient; these checks are not a complete
information-flow policy. Internal event history includes inputs and stored state
and must retain its existing access controls. An advisory decision describes an
attempt, not the latest state; use an authorized read for current state.
Retries and workflow recovery
SQLiteStateBackend.apply() returns an AdvisoryWriteOutcome with status and
reason_code. Its existing accepted=True means accepted for durable
processing, including a recorded rejection. It does not mean the business
action was admitted. This preserves workflow acknowledgement semantics. Custom
backends predating this API may leave the two new fields unset.
A retry returns the original decision, even if state has changed since.
Correcting state does not turn an old rejected attempt into a success. Submit a
new operation key to make a new attempt. Reusing an existing
key with changed inputs or context is an error. Historical events without these
new fields remain replayable: their status is inferred from the stored changed
flag, and they have no explicit reason code.
A workflow can finish acknowledging a rejected write after a lost response
without executing it twice or becoming stuck retrying the same business refusal.
The accepted survey response and the outcome of its state action are separate
facts. A workflow submission containing multiple writes is not one atomic Machine
command; rejection rolls back only its own command. Design subsequent work from
explicit state reads or public domain fields when participants need to respond
to a refusal. There is no automatic participant-facing retry prompt.
Close and finalization
Runtime.close_result() returns the same structured result as execute.
Runtime.close() preserves its existing dictionary return on success and raises
CommandRejected, with a reason_code, on explicit refusal. Both discard partial
settlement on rejection. SQLite records a rejected close without marking the
machine closed. A successful close can report noop for unchanged stored fields
while still recording that the lifecycle has closed.
Explicit close operations use their normal idempotency keys. Automatic
finalize() keeps successful settlement once per scope/target. A rejected
automatic attempt is keyed by its execution identity: the same execution replays
its rejection; a later execution can try again after the cause is addressed.
The Runner surfaces CommandRejected if automatic settlement is refused, rather
than treating the interview as having successfully finalized the scope. A
completion condition that is still false remains an unrecorded pending check.
The continuous auction example
uses ordered assertions for an existing open order, nonpositive price,
insufficient cash, and insufficient inventory. Its replay includes successful
trades, an explicit rejection, and an intentional hold no-op.
Visualizing a machine
Machine.show_diagram() draws the declared fields, commands, and view. Command
cards show their inputs, requirements, and effects. Edges distinguish state
reads from writes and show which fields feed the read-only view.
pydot
renderer saves a PNG and requires pydot and Graphviz. Its default resolution is
192 dpi; increase dpi for print-sized output.
Large machines use compact lifecycle effects by default; pass detail=True to
show longer view and effect expressions.
Views
Stored fields and participant-visible data are different concepts. A view declares exactly what a reader may observe:field("votes") refers to persistent state. The count is derived rather than
stored redundantly.
Views can hide information until close:
current is an execution-time reference, not Jinja text. The host supplies its
context. The language specification defines
context typing and permission requirements; the current interpreter does not
provide a complete static type system or an untrusted-code sandbox.
Randomization and exact monetary arithmetic
Useseeded_integer for stateless keyed draws and seeded_order for stable-ID
priority ordering. Use decimal_units to convert exact decimal text into integer
units and round_ratio for explicit signed rounding of integer ratios. All four
are serialized expressions that require interpreter support.
The randomization and money chapter
specifies their arguments, byte protocol, rounding modes, resource limits,
replay guarantees, and compatibility with existing market algorithms.