Skip to main content
This example asks two characteristics and assigns a condition in the same survey pass. The policy balances total arm counts, age bands, and prior experience using Machine expressions. The behavior is serialized; Python only builds the definition.

Build and run the complete example

Everything needed for this example is defined on this page. Use an EDSL build that includes the Machine and Runner APIs documented in this manual. Execute the following four Python blocks in order in one session, or concatenate them into one script. They require EDSL and the Python standard library; no repository example modules or external data files are needed. The scripted run makes no model API calls. The twelve-person scripted population produces six Control and six Treatment assignments. Every respondent then answers a question naming their assigned condition. The demo makes no model API calls.

1. Define the Machine

The Machine derives marginal counts from its assignment ledger. It selects a minimum-cost arm, breaks ties with seeded ordering, and preserves prior assignments.

2. Construct the Survey

The survey asks both characteristics before assignment, then reads the assigned arm. Its gate prevents a conflicting repeat report from silently using an old assignment.

3. Define the scripted respondents

The twelve scripted respondents cycle through four age/experience combinations. Their final response is fixed so the example isolates allocation behavior.

4. Run and inspect the answers

Model("test") supplies the Jobs model dimension. The agents above answer locally, and QuestionCompute evaluates the routing gates without a model call.

Follow the first six assignments

The follow-up Python blocks use the definitions and Results created above. The table below comes from the default run above, with seed balanced-2026 and study ID study. Candidate scores are computed from the ledger before each assignment. A lower score wins; a tie uses the seeded draw. R1 enters while Control already contains one New respondent. Assigning R1 to Control would add to both its total count and its New count, so Control’s score is two. Treatment is empty and scores zero. By R4, the scores tie again; the stable seed and respondent ID determine the arm. This is what makes the example adaptive across people: R4’s assignment depends on the four preceding records, while repeated delivery for R4 keeps the original assignment rather than rerunning the allocation as a new person.

Inspect the final balance, including a limitation

The complete twelve-person run has these marginal counts: But the joint age-by-experience cells look different: The implementation worked as specified, but this is not a balanced design for comparing every subgroup. Good marginal balance can hide very poor joint balance. If the joint cells matter, they must become part of the assignment objective; changing the seed alone is not a guarantee. Reproduce both views from Results instead of relying only on the total split:

Assignment policy

The example has two arms (Control, Treatment), two age bands (Younger, Older), and two experience categories (New, Experienced). State contains an immutable record per respondent with those two characteristics and the selected arm. For a new respondent, calculate for each arm:
Choose an arm with the lowest score. With equal weights, this also minimizes the increase in the sum of squared counts across these three margins. It is a greedy local criterion, not a global optimization over future arrivals. It does not balance every joint age-by-experience cell or guarantee exact equality at every sample size. If the scores tie, seeded_order orders the tied arm IDs using the configured seed, study_id from runtime context, and the respondent ID as the draw key. The direct runtime example defaults the study key to study; the Survey supplies the actual study trait. See portable randomization for the byte protocol and reproducibility contract. assign(respondent_id, age, experience) checks the current ledger and writes atomically. A repeat with the same characteristics preserves its first arm; changed characteristics reject explicitly. Closing stops new assignments but retains prior ones. Counts are derived from the ledger, avoiding separate mutable counters. There is no intrinsic sample-size completion condition.

Survey integration

The survey asks the two characteristics, calls assign, reads the personal view, and computes the assigned arm. Its final question uses that computed answer in the prompt. If a later interview changes the same respondent’s characteristics, the command refuses the update and a gate suppresses the final question, rather than silently treating the old assignment as based on the new report. A grouped sequential schedule makes the demo’s arrival order reproducible even if the supplied AgentList is reversed. Concurrent writers still make atomic assignments, but their transaction order can change the result. Reuse the saved state map and stable IDs to resume without recounting respondents.

Replay an assignment without admitting someone twice

The record, not the current balancing score, governs a returning respondent. This small example also shows how a conflicting report is represented without partially changing the state:
The Survey checks the personal view after assignment. A refused changed report therefore cannot silently continue into the final question as if the old arm had been selected from the newly reported characteristics.

Tests and design findings

The application tests compute candidate costs independently over mixed-characteristic streams and verify that the chosen arm has minimum cost. They also check reproducibility, immutable assignments, changed reports, closure, concurrent writers, SQLite restart/delivery replay, scope isolation, fresh-process JSON execution, and ordinary Survey routing. This is an allocation example, not a recommendation for a particular experiment. Greedy marginal balance is order-dependent and need not achieve every balancing goal. Stable public seeds are reproducible, not concealed; IDs, reported characteristics, seed policy, and arrival order must be controlled by the host. The example does not claim allocation concealment, independent random assignment, or statistical validity for a particular estimator. The current definition is 10,997 JSON bytes. Its twelve-assignment corpus replay peaks at 28,432 host budget steps per transition. Recomputing marginal counts from the full ledger becomes more expensive as the study grows; larger studies should probe incremental count invariants, expression reuse, and interpreter budgets. Maintainers with a repository checkout can optionally run python -m edsl.examples.shared_state.machine_primitives.profile_corpus to reproduce local measurements. No new interpreter or navigation primitives were needed.