Skip to main content
The goal is to express a mechanism’s behavior in its serialized Machine definition. A helper may construct that definition, but executing it should not require a mechanism-specific Python callback. The primitive example corpus is a set of worked examples for researchers and coding agents. It deliberately includes increasingly demanding constructions, so missing abstractions become visible. Each example runs after JSON transport under Runtime() with an empty algorithm registry. The runner also rejects domain-specific reducers; its allowed reducers are sorting records, keeping the latest record per key, summing, and counting values.

Choose an example

These are executable reference examples, not claims of a complete production market or matching library. The batch auction is intentionally smaller than the existing asset-market implementation. Existing algorithm-backed examples remain available as comparison implementations.

Run and export the examples

From the repository root, with the development package installed:
No model or remote calls are made. The runner transports each definition through JSON before executing its deterministic command sequence. It prints the final views. With --output, it also writes each definition and a replay record containing the commands, final state, view, operation inventory, and definition size. These files describe Machines, not Jobs; they are not inputs to ep run.

General-purpose computation primitives

Most examples combine existing fields, conditions, map/filter expressions, and atomic effects with the operations below. Their bodies are serialized expression trees, not Python functions or lambdas. For example, a running balance carries an accumulator between entries:
This is a command expression: the surrounding command must declare amounts. The complete ledger example shows its field, input type, effect, and view. Bindings are lexical. Nested computations can shadow outer names without modifying their values. A fold’s item and accumulator names must be distinct. The initial value and collection are evaluated in the outer context; only the body sees the new bindings. Iteration likewise evaluates its initial value and budget outside its state binding. Its condition must evaluate to a Boolean. Iteration accepts an integer budget from zero through 100,000 steps. The condition is checked even at zero steps and immediately after the last allowed step. Exhaustion raises an error; it never returns a partially converged result. This per-expression limit is additional to the shared execution budget, which covers nested computations and all effects in one runtime operation. Optional loop invariants use accumulator_type for fold and state_type for iterate; the ledger sample declares its carried record type, and deferred acceptance declares its matching state type.

Why allocation needs a fold

A map transforms elements independently. Serial dictatorship must give each claimant the first preferred item that remains available after earlier claimants have chosen. Its accumulator contains both assignments and remaining capacities. Sorting establishes priority; folding expresses the sequential allocation without adding a serial_dictatorship operation to the interpreter. Deferred acceptance needs a proposal queue, tentative matches, and each applicant’s next-choice cursor. Those are local accumulator values inside one bounded iteration. Its budget is the sum of submitted ranking lengths plus the number of applicants: each proposal consumes a ranking entry, and each applicant can have at most one final exhausted-queue visit. This bound is checked against the interpreter’s per-expression cap. Both examples use latest submitted preferences. The matching example accepts strict, possibly incomplete rankings; duplicate entries fail the command’s requirement without changing state. Institutions order applicants by priority, then name; omitted applicants rank after explicitly listed ones.

Atomicity and numerical behavior

A fold or iteration computes a proposed value inside a single command or close transaction. Intermediate assignments are not committed or exposed to readers. An error prevents the entire transition from committing, including effects that were evaluated earlier. Ordinary effects still observe the same pre-command snapshot; sequential computation is explicit inside the accumulator. LMSR needs stable exponentials, not a market-specific runtime operation. logsumexp avoids directly exponentiating large quantities. Floating-point rounding still applies, so equivalence tests use numerical tolerances. The sample permits negative cash, as the comparison implementation does, and explicitly prevents further trading after settlement. The continuous auction admits one open order per trader and executes at the resting order’s price. Ordered require effects return open_order_exists, invalid_price, insufficient_cash, or insufficient_inventory for refused orders. hold remains a no-op. The older callback raises exceptions for those admission failures; tests compare both unchanged state on rejected paths and state/conservation on valid paths. This is a deliberate difference in outcome reporting. Invalid trader/action types still fail input validation. See explicit rejection semantics. Replay exports include a decisions list aligned with their commands.

Randomization and settlement

The two additional examples use the portable randomization and exact-money primitives. The lottery’s scope and draw keys are explicit, and changing arrival order preserves winners. The settlement sample rounds a gross payment once, splits out a fee, and conserves integer units. Tests cover fixed random vectors, scope/key separation, signed rounding boundaries, restart/retry, and execution in a fresh process. These general expressions leave the older algorithms’ random streams and rounding policies unchanged.

What the examples reveal about the language

The examples do not solve every limitation by adding a special operation. In particular, the full asset market’s income schedule, stochastic tie-breaking, multi-unit admission, and monetary rounding remain a useful next stress case. The batch example demonstrates clearing only and makes that boundary explicit. The new settlement probes also measure composition costs. With the default demos, second-price/uniform-price definitions are 26,346/26,350 JSON bytes and peak at 12,147/16,427 host budget steps per transition; posted-price inventory is 21,978 bytes and peaks at 10,061 steps. Auction close and the explicit settlement command expand the same settlement expression into two serialized locations. let avoids repeated evaluation within each expression, but does not provide reusable named serialized functions. These local profiler observations strengthen the existing composition checklist; they are not portable cost guarantees. Reproduce them with the optional repository maintainer command python -m edsl.examples.shared_state.machine_primitives.profile_corpus.

Constructors and registered algorithms

An authoring helper is appropriate when it expands entirely into ordinary Machine expressions. The corpus’s build_machine() functions and small formula helpers do this; their Python source is not needed to execute the exported JSON. There is no supported recipes module to import. The current implementation also still supports algorithm(name, ...) and registered Python implementations for older examples. That is an extension boundary, not an expansion into general primitives. It requires a matching runtime registry. The new corpus intentionally uses neither algorithm effects nor algorithm views. Its role is to demonstrate which mechanisms can be built from reusable operations before deciding how to migrate existing consumers.

Validation and coding-agent workflow

When adapting an example:
  1. Specify persistent fields, input types, views, and allowed transitions.
  2. State tie-breaking rules, completion criteria, and failure behavior.
  3. Build the machine and serialize it through JSON.
  4. Check its derived requirements against the destination, then replay it under the empty Runtime() registry.
  5. Check independent invariants and edge cases, including empty inputs, duplicate submissions, capacity exhaustion, and retries.
  6. Compare against an independent or existing implementation where available.
  7. Record any missing primitive or unclear semantic rule before adding a mechanism-specific workaround.
The corpus tests check matching stability, capacity and asset conservation, serialization, nested binding scopes, iteration boundaries, numerical behavior, and SQLite rollback after exhaustion. They complement the broader execution contracts. Type checks, loop invariants, and runtime quotas are implemented alongside finite JSON checks. Complete static typing and isolation of arbitrary Python extensions remain conformance targets in the language specification. The ordered implementation checklist and progress are tracked in Machine design gaps, issue #2665.

Measure composition costs

python -m edsl.examples.shared_state.machine_primitives.profile_corpus reports serialized size, repeated expression trees, and existing host budget charges for each replayed transition. See the survey quota walkthrough for a measured example and the accounting limits. These are development probes, not portable performance promises or a new tracing API.