> ## Documentation Index
> Fetch the complete documentation index at: https://docs.expectedparrot.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Posted-price inventory market

> A self-contained Machine, single-pass Survey, and local settlement demo.

A seller begins with five units and a price of 20. Each buyer sees a quote,
chooses a quantity, and pays from a dedicated balance. After a sale, the next
price increases by 5 for each unit sold so far. A saved version number fences
quotes: a purchase at an old quote is rejected if another sale intervenes.

The whole order pays its saved unit price. This is a quantity-based price update
between orders, not a marginal price increase within an order. A buys two at 20,
B buys one at 30, and C buys two at 35; the seller receives 140. D arrives after
stock is exhausted and never sees the purchase question.

## Build and run the complete example

Execute the following four Python blocks in order in one session, or concatenate
them into a script. Use an EDSL build with the Machine and Runner APIs documented
in this manual. Everything is defined here: only EDSL and the Python standard
library are required, with no repository example imports and no model API calls.

### 1. Define the Machine

The quote captures price and version. The buy command checks ownership, live
version, stock, and cash before atomically moving goods and payment. A repeated
filled order with the same quantity is a no-op.

```python theme={null}
from edsl.sharedstate import (
    Command,
    Machine,
    StateType,
    require,
    choose,
    constant,
    current_value,
    field,
    filter_items,
    arg,
    local,
    put,
    record,
    assign,
    state_field,
    when,
)

def build_machine(stock=5, base_price=20, increment=5, balances=None):
    balances = dict(
        {"A": 200, "B": 200, "C": 200, "D": 200} if balances is None else balances
    )
    if not balances or any(
        not isinstance(k, str) or not k.strip() or type(v) is not int or v < 0
        for k, v in balances.items()
    ):
        raise ValueError(
            "balances require nonempty buyer IDs and nonnegative integer cash"
        )
    if (
        type(stock) is not int
        or stock < 1
        or type(base_price) is not int
        or base_price < 1
        or type(increment) is not int
        or increment < 0
    ):
        raise ValueError(
            "stock and price must be positive integers; increment nonnegative"
        )
    buyer, token, quantity = arg("buyer_id"), arg("order_id"), arg("quantity")
    orders = field("orders")
    seen, old = orders.contains(token), orders.get(token, {})
    fresh = old.get("status") == "quoted"
    sold = constant("initial_stock") - field("stock")
    price = constant("base_price") + sold * constant("increment")
    charge = quantity * old.get("price", 0)
    you = current_value("buyer_id", "")
    your = orders.get(current_value("order_id", ""), {})
    owned = your.get("buyer_id") == you
    status = choose(owned, your.get("status", "missing"), "missing")
    return Machine(
        name="PostedPriceMarket",
        constants={
            "initial_stock": stock,
            "base_price": base_price,
            "increment": increment,
            "quantities": list(range(stock + 1)),
        },
        fields={
            "stock": state_field(StateType.integer(minimum=0, maximum=stock), stock),
            "cash": state_field(StateType.map(StateType.text(), StateType.integer(minimum=0)), balances),
            "inventory": state_field(
                StateType.map(StateType.text(), StateType.integer(minimum=0)), dict.fromkeys(balances, 0)
            ),
            "seller_cash": state_field(StateType.integer(minimum=0), 0),
            "version": state_field(StateType.integer(minimum=0), 0),
            "closed": state_field(StateType.boolean(), False),
            "orders": state_field(
                StateType.map(
                    StateType.text(),
                    StateType.record(
                        {
                            "buyer_id": StateType.text(),
                            "price": StateType.integer(minimum=1),
                            "version": StateType.integer(minimum=0),
                            "quantity": StateType.integer(minimum=0),
                            "status": StateType.choice(["quoted", "filled", "passed"]),
                        }
                    ),
                ),
                {},
            ),
        },
        commands={
            "quote": Command(
                inputs={"buyer_id": StateType.text(), "order_id": StateType.text()},
                timing="before_question",
                effects=(
                    require(field("cash").contains(buyer), code="unknown_buyer"),
                    require(token.stripped().length() > 0, code="missing_order_id"),
                    require(
                        ~seen | (old.get("buyer_id") == buyer), code="order_not_owned"
                    ),
                    when(
                        ~seen,
                        require(
                            ~field("closed") & (field("stock") > 0),
                            code="market_closed",
                        ),
                    ),
                    put(
                        "orders",
                        token,
                        record(
                            buyer_id=buyer,
                            price=price,
                            version=field("version"),
                            quantity=0,
                            status="quoted",
                        ),
                        once=True,
                    ),
                ),
            ),
            "buy": Command(
                inputs={
                    "buyer_id": StateType.text(),
                    "order_id": StateType.text(),
                    "quantity": StateType.integer(minimum=0),
                },
                effects=(
                    require(
                        seen & (old.get("buyer_id") == buyer), code="order_not_owned"
                    ),
                    require(
                        fresh | (old.get("quantity") == quantity), code="order_changed"
                    ),
                    when(
                        fresh & (quantity > 0),
                        require(~field("closed"), code="market_closed"),
                    ),
                    when(
                        fresh & (quantity > 0),
                        require(
                            old.get("version") == field("version"), code="stale_quote"
                        ),
                    ),
                    when(
                        fresh & (quantity > 0),
                        require(quantity <= field("stock"), code="insufficient_stock"),
                    ),
                    when(
                        fresh & (quantity > 0),
                        require(
                            charge <= field("cash").get(buyer),
                            code="insufficient_funds",
                        ),
                    ),
                    when(
                        fresh,
                        put(
                            "orders",
                            token,
                            old.with_item("quantity", quantity).with_item(
                                "status", choose(quantity > 0, "filled", "passed")
                            ),
                        ),
                    ),
                    when(
                        fresh & (quantity > 0), assign("stock", field("stock") - quantity)
                    ),
                    when(
                        fresh & (quantity > 0),
                        put("cash", buyer, field("cash").get(buyer) - charge),
                    ),
                    when(
                        fresh & (quantity > 0),
                        put(
                            "inventory", buyer, field("inventory").get(buyer) + quantity
                        ),
                    ),
                    when(
                        fresh & (quantity > 0),
                        assign("seller_cash", field("seller_cash") + charge),
                    ),
                    when(fresh & (quantity > 0), assign("version", field("version") + 1)),
                ),
            ),
        },
        complete_when=field("stock") == 0,
        close_effects=(assign("closed", True),),
        view={
            "status": status,
            "quoted_price": choose(owned, your.get("price"), None),
            "quote_current": owned & (your.get("version") == field("version")),
            "stock": field("stock"),
            "cash": field("cash").get(you),
            "quantity": choose(owned, your.get("quantity", 0), 0),
            "price": price,
            "options": choose(
                owned,
                filter_items(
                    constant("quantities"),
                    item="n",
                    predicate=(local("n") <= field("stock"))
                    & (local("n") * your.get("price", 0) <= field("cash").get(you, 0)),
                ),
                [],
            ),
            "accepting": ~field("closed") & (field("stock") > 0),
        },
    )
```

### 2. Construct the single-pass Survey

Each buyer gets a quote before the purchase question. The computed entry gate
uses ordinary Survey stop rules. It stops later buyers when stock is gone while
allowing the last successful buyer to receive its receipt.

```python theme={null}
from edsl import (
    Agent,
    AgentList,
    InterviewSchedule,
    Model,
    QuestionCompute,
    QuestionMultipleChoice,
    Survey,
)

from edsl.sharedstate import SharedState, SharedStateMap, current

def build_survey(*, state_id=None, **machine_options):
    states = SharedStateMap(
        SharedState(market=build_machine(**machine_options)), state_id=state_id
    )
    market = states.by(current.agent.market_id).market
    gate = QuestionCompute(
        question_name="market_entry",
        question_text="{{ 'open' if shared_state.market.status == 'quoted' and shared_state.market.quote_current and shared_state.market.accepting else 'closed' }}",
    )
    quantity = QuestionMultipleChoice(
        question_name="quantity",
        question_text="How many units would you buy at {{ shared_state.market.quoted_price }} each? Zero passes.",
        question_options="{{ shared_state.market.options }}",
    )
    receipt = QuestionCompute(
        question_name="order_receipt", question_text="{{ shared_state.market.status }}"
    )
    survey = Survey(
        [
            market.quote(
                buyer_id=current.agent.buyer_id, order_id=current.agent.order_id
            ),
            market.read(),
            gate,
            quantity,
            market.buy(
                buyer_id=current.agent.buyer_id,
                order_id=current.agent.order_id,
                quantity=quantity.answer,
            ),
            market.read(),
            receipt,
        ]
    )
    survey.add_stop_rule(gate, "{{ market_entry.answer }} != 'open'")
    return survey, states, InterviewSchedule.grouped_round_robin("market_id", "turn")
```

### 3. Define the scripted respondents

Stable IDs and the `turn` trait establish the demonstration order. These direct
answers bypass model calls while exercising actual question rendering and rules.

```python theme={null}
def demo_answer(self, question, scenario):
    return self.traits["quantity"]

def demo_agents():
    agents = AgentList()
    for turn, (buyer, quantity) in enumerate(zip(["A", "B", "C", "D"], [2, 1, 2, 1])):
        agent = Agent(
            traits={
                "buyer_id": buyer,
                "order_id": buyer + "-1",
                "quantity": quantity,
                "market_id": "market",
                "turn": turn,
            }
        )
        agent.add_direct_question_answering_method(demo_answer)
        agents.append(agent)
    return agents
```

### 4. Run and inspect settlement

```python theme={null}
from edsl.runner import Runner

survey, states, schedule = build_survey()
results = (
    Runner(interview_schedule=schedule)
    .submit(survey.by(demo_agents()).by(Model("test")), cache=False)
    .results()
)
assert not results.has_unfixed_exceptions
writes = [
    e for e in results.shared_state["bindings"][0]["events"]
    if e["kind"] == "write"
]
state = writes[-1]["state"]["market"]
assert state["stock"] == 0 and state["seller_cash"] == 140
assert sum(state["inventory"].values()) == 5
assert sum(state["cash"].values()) + state["seller_cash"] == 800
print(state["inventory"], state["cash"], state["seller_cash"])
```

Expected final accounts:

| Participant | Units received | Payment | Cash remaining |
| - | -: | -: | -: |
| A | 2 | 40 | 160 |
| B | 1 | 30 | 170 |
| C | 2 | 70 | 130 |
| D | 0 | 0 | 200 |

## Try the boundary cases

The remaining blocks reuse this page's `build_machine` and run directly under an
empty `Runtime()` registry after JSON transport.

### A stale quote cannot spend money

```python theme={null}
from edsl.sharedstate import Runtime

machine = Machine.from_json(build_machine().to_json())
runtime = Runtime()
state = runtime.initial_state(machine)

for buyer in ["A", "B"]:
    state = runtime.execute(machine, state, "quote", {
        "buyer_id": buyer, "order_id": buyer + "-1"
    }).state
state = runtime.execute(machine, state, "buy", {
    "buyer_id": "A", "order_id": "A-1", "quantity": 2
}).state
stale = runtime.execute(machine, state, "buy", {
    "buyer_id": "B", "order_id": "B-1", "quantity": 1
})
assert stale.event["reason_code"] == "stale_quote" and stale.state == state
# Reusing B-1 preserves its original quote. A new order ID requests a new quote.
state = runtime.execute(machine, state, "quote", {
    "buyer_id": "B", "order_id": "B-2"
}).state
assert state["orders"]["B-2"]["price"] == 30
state = runtime.execute(machine, state, "buy", {
    "buyer_id": "B", "order_id": "B-2", "quantity": 1
}).state
replayed = runtime.execute(machine, state, "buy", {
    "buyer_id": "A", "order_id": "A-1", "quantity": 2
})
assert replayed.state == state and replayed.event["status"] == "noop"
assert state["seller_cash"] == 70
```

A stale order can also be passed with quantity zero. Passing moves no cash or
stock and is allowed after closure. Reusing a completed order with a changed
quantity is rejected as `order_changed`; an order ID belongs to its original
buyer. In a concurrent race on the same version, only one positive purchase
applies—even if stock would suffice for both. The losing buyer needs a fresh
quote. This deliberate policy prioritizes an explicit current price.

## What this probes, and what remains

The construction combines a versioned read, explicit rejection, multi-field
atomic payment, and durable order replay. It needs no new market-specific Machine
primitive and uses the existing Survey navigation API.

The sequential demo avoids stale quotes by construction; the boundary example
and concurrent SQLite tests exercise them explicitly. The Survey does not retry
or requote within the same interview: if another sale intervenes after rendering,
its receipt remains `quoted` and the host evidence reports `stale_quote`. A new
order token and a new pass are required. Quote expiry, returns, replenishment,
and multiple sellers are outside this example.

All balances are simulated dedicated accounts; the example does not move real
money or authenticate account owners. Combining these markets through a common
wallet would require a deliberate reservation/settlement contract.

## Verification

The executable tests check independent allocation and price references, cash and
unit conservation, admission rejections without partial mutation, repeated
settlement, concurrent SQLite commands, reopen/replay, scope isolation, fresh
interpreter transport, actual Survey choices, and Results serialization.
The canonical page is also executed in a fresh process with repository example
imports blocked.

Optional maintainer commands, from a repository checkout:

```bash theme={null}
python -m edsl.examples.shared_state.posted_price_market
python -m pytest -q --confcutdir=tests/sharedstate tests/sharedstate/test_auction_markets.py
```

See the [primitive corpus](https://docs.expectedparrot.com/en/latest/shared-state/algorithms-and-reference.md) for
related mechanisms and the [Machine manual](https://docs.expectedparrot.com/en/latest/shared-state/machines.md) for
execution and rejection semantics.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.