Domain: multi-warehouse inventory allocation

Issue:
Cancellations are bleeding us. When a customer cancels, the allocation service today simply abandons the order: earmarked units stay earmarked, picked cartons sit in staging, and customers waiting on backorders for the very same SKU keep waiting. Operations has been "fixing" this by hand, and every incident in this ticket comes from one of those manual fixes.
Incident 41 (phantom stock): after a cancellation, an operator zeroed the reservation and added the units back at WH-3, because that is where the next customer's shipment would have been cheapest from. The units had been picked at WH-7. The overnight WMS reconciliation found a hole at WH-7 and stock at WH-3 that did not physically exist, and two shipments were promised against it. Stock lives where it lives: the books must say where the units actually are.
Incident 47 (queue jump): freed units were handed to the newest backorder because that customer's order screen happened to be open. A rush-class customer had been waiting eleven days longer; their line is served first — that is what the service ladder means — and we paid the SLA credit to prove it. Demand waits in one line: class first, then age. Nothing that happens later moves anyone in that line.
Incident 52 (edited history): to make the numbers add up after a manual release, someone subtracted the cancelled units from the reservation counters. The capacity dashboards flagged an impossible negative day, and finance asked why our audit counters can be edited at all. They cannot be: counters record what happened, and a correction is a new event.
So: implement release(engine, order_id) in src/release.py. Release cancels the unshipped remainder of an order — shipped units are gone, and release reports what it could not bring back — returns its stock to service, and puts that stock to work immediately: released stock is live, sellable inventory, and waiting demand must be served with it right away, exactly as the allocator would serve any demand, not left for the overnight pass. Cancelled demand, of course, no longer waits in line.
One boundary: allocation work is metered (the capacity dashboards again), so a release should cost work proportional to what it touches — it is an operation, not a recomputation of the world.

Repository files:
content: # Present so pytest adds the repository root to sys.path, making `import src`
# resolve from the test suite.

path: conftest.py

content: # Pure standard library unless the environment image pre-bakes wheels.

path: requirements.lock

content: """stockd: the allocation service.

Order intake, warehouse allocation, fulfilment stages, and the
operational records (movement journal, counters, reports) the rest of
the business reads.
"""

path: src/__init__.py

content: """Warehouse selection: one policy, used for all demand.

The allocation policy is deliberately simple and deliberately singular:
for a given destination zone, eligible warehouses (those that serve the
zone) are considered in ascending ``(cost, warehouse_id)`` order, and
each contributes what it can until the requested quantity is covered.
A request the network cannot fully cover yields a partial plan — the
caller decides what the shortfall means. Zones no warehouse serves
yield an empty plan for the same reason.

Every warehouse considered counts one ``allocation_scans`` unit on the
work meter, whoever is asking and for whatever reason.
"""

from typing import List, Tuple

from .config import EngineConfig
from .ledger import StockLedger
from .metrics import Counters


def plan(
    config: EngineConfig,
    ledger: StockLedger,
    counters: Counters,
    sku: str,
    qty: int,
    zone: str,
) -> List[Tuple[str, int]]:
    """Plan sources for ``qty`` units of ``sku`` bound for ``zone``.

    Returns ``[(warehouse_id, take), ...]`` in policy order. The plan
    is advisory: nothing is moved here.
    """
    eligible = []
    for spec in config.warehouses:
        cost = spec.cost_for(zone)
        if cost is not None:
            eligible.append((cost, spec.warehouse_id))
    eligible.sort()

    remaining = qty
    sources: List[Tuple[str, int]] = []
    for _cost, warehouse_id in eligible:
        if remaining <= 0:
            break
        counters.bump("allocation_scans")
        available = ledger.position(warehouse_id, sku).available
        take = min(available, remaining)
        if take > 0:
            sources.append((warehouse_id, take))
            remaining -= take
    return sources

path: src/allocator.py

content: """The backorder queue: demand that is waiting its turn.

Waiting demand is a queue, not a pool. It is served in ascending
``(priority rank, submitted_at, order_id, sku)`` order — class first,
then age — and nothing that happens later moves anyone in that line:
an entry's rank and stamp are fixed at submission, and an entry that
is partially served keeps its place for the remainder.

Within this service the queue only ever grows: intake adds entries for
shortfalls, and the overnight WMS pass — which runs outside this
codebase, against the reconciled ledger — is what serves them today.
"""

from dataclasses import dataclass
from typing import List

from .errors import StockError


@dataclass
class BackorderEntry:
    order_id: str
    sku: str
    qty: int
    priority_rank: int
    submitted_at: int

    def sort_key(self):
        return (self.priority_rank, self.submitted_at, self.order_id, self.sku)


class BackorderQueue:
    def __init__(self):
        self._entries: List[BackorderEntry] = []

    def add(self, entry: BackorderEntry) -> None:
        if entry.qty <= 0:
            raise StockError("backorder entries carry positive quantities")
        self._entries.append(entry)

    def waiting(self) -> List[BackorderEntry]:
        """All entries, in service order."""
        return sorted(self._entries, key=BackorderEntry.sort_key)

    def waiting_for(self, order_id: str) -> List[BackorderEntry]:
        return [e for e in self.waiting() if e.order_id == order_id]

    def serve(self, order_id: str, sku: str, qty: int) -> None:
        """Record that ``qty`` units of an entry were served."""
        for entry in self._entries:
            if entry.order_id == order_id and entry.sku == sku:
                if qty > entry.qty:
                    raise StockError(
                        "serving %d exceeds waiting %d for %s/%s"
                        % (qty, entry.qty, order_id, sku)
                    )
                entry.qty -= qty
                if entry.qty == 0:
                    self._entries.remove(entry)
                return
        raise StockError("no waiting entry for %s/%s" % (order_id, sku))

    def cancel(self, order_id: str) -> List[BackorderEntry]:
        """Remove and return every entry belonging to ``order_id``."""
        removed = [e for e in self._entries if e.order_id == order_id]
        self._entries = [e for e in self._entries if e.order_id != order_id]
        return removed

    def __len__(self) -> int:
        return len(self._entries)

path: src/backorders.py

content: """Engine configuration: the warehouse network and service classes.

Configuration is supplied by the deployment, not persisted by the
engine. Costs are integer shipping-cost units per destination zone; a
warehouse that does not list a zone does not ship to it.
"""

from dataclasses import dataclass, field
from typing import Dict, Mapping, Tuple

from .errors import ConfigError


@dataclass(frozen=True)
class WarehouseSpec:
    """One warehouse in the network.

    ``zone_costs`` maps destination zone name to an integer shipping
    cost. Lower cost is preferred; ties break on ``warehouse_id``.
    """

    warehouse_id: str
    zone_costs: Mapping[str, int] = field(default_factory=dict)

    def cost_for(self, zone: str):
        """Cost to serve ``zone``, or ``None`` if this warehouse does not."""
        return self.zone_costs.get(zone)


@dataclass(frozen=True)
class EngineConfig:
    """Static configuration for one :class:`~src.engine.StockEngine`.

    ``priority_classes`` maps a service-class name to its rank; lower
    rank is served first. Every order names one of these classes.
    """

    warehouses: Tuple[WarehouseSpec, ...]
    priority_classes: Mapping[str, int]

    def __post_init__(self):
        seen = set()
        for spec in self.warehouses:
            if spec.warehouse_id in seen:
                raise ConfigError(
                    "duplicate warehouse id: %s" % spec.warehouse_id
                )
            seen.add(spec.warehouse_id)
            for zone, cost in spec.zone_costs.items():
                if cost < 0:
                    raise ConfigError(
                        "negative cost for %s zone %s"
                        % (spec.warehouse_id, zone)
                    )
        if not self.warehouses:
            raise ConfigError("at least one warehouse is required")
        if not self.priority_classes:
            raise ConfigError("at least one priority class is required")

    def warehouse(self, warehouse_id: str) -> WarehouseSpec:
        for spec in self.warehouses:
            if spec.warehouse_id == warehouse_id:
                return spec
        from .errors import UnknownWarehouse

        raise UnknownWarehouse(warehouse_id)

    def rank_of(self, priority_class: str) -> int:
        try:
            return self.priority_classes[priority_class]
        except KeyError:
            raise ConfigError("unknown priority class: %s" % priority_class)


def standard_classes() -> Dict[str, int]:
    """The default service ladder used by most deployments."""
    return {"rush": 0, "standard": 1, "economy": 2}

path: src/config.py

content: """The allocation-service facade.

One engine owns one ledger, one journal, one backorder queue, and one
set of counters. Every stock state change in the service funnels
through :meth:`StockEngine.record_movement` — the single choke point
that journals the movement, applies it to the ledger, and counts it.
"""

from typing import Dict, Mapping, Tuple

from . import intake, ops, pipeline
from .backorders import BackorderQueue
from .config import EngineConfig
from .journal import MovementJournal
from .ledger import StockLedger
from .metrics import Counters
from .orders import Order

_MOVEMENT_COUNTERS = {
    "reserve": "units_reserved",
    "pick": "units_picked",
    "ship": "units_shipped",
    "unreserve": "units_unreserved",
    "restock": "units_restocked",
}


class StockEngine:
    def __init__(
        self,
        config: EngineConfig,
        opening: Mapping[Tuple[str, str], int] = None,
    ):
        self.config = config
        self.ledger = StockLedger()
        self.journal = MovementJournal()
        self.queue = BackorderQueue()
        self.counters = Counters()
        self.orders: Dict[str, Order] = {}
        for (warehouse_id, sku), qty in sorted((opening or {}).items()):
            config.warehouse(warehouse_id)  # validates the id
            self.ledger.load_opening(warehouse_id, sku, qty)

    @classmethod
    def from_positions(cls, config: EngineConfig, text: str) -> "StockEngine":
        """Build an engine from a WMS start-of-day position export."""
        return cls(config, ops.opening_positions(text))

    # -- the choke point -------------------------------------------------

    def record_movement(self, kind, warehouse_id, sku, qty, order_id, cause):
        """Journal, apply, and count one movement, in that order.

        The journal append is the commit point: a movement that did not
        reach the journal did not happen.
        """
        self.ledger.check(kind, warehouse_id, sku, qty)
        movement = self.journal.append(
            kind, warehouse_id, sku, qty, order_id, cause
        )
        self.ledger.apply(movement)
        self.counters.bump(_MOVEMENT_COUNTERS[kind], qty)
        return movement

    # -- operations ------------------------------------------------------

    def submit(self, order_id, zone, priority_class, submitted_at, lines):
        return intake.submit(
            self, order_id, zone, priority_class, submitted_at, lines
        )

    def pick(self, order_id: str) -> int:
        return pipeline.pick(self, order_id)

    def ship(self, order_id: str) -> int:
        return pipeline.ship(self, order_id)

    def release(self, order_id: str):
        from .release import release

        return release(self, order_id)

path: src/engine.py

content: """Error taxonomy for stockd."""


class StockError(Exception):
    """Base class for allocation-service errors."""


class ConfigError(StockError):
    """The engine configuration is inconsistent."""


class UnknownOrder(StockError):
    """The order id is not known to this engine."""


class UnknownWarehouse(StockError):
    """The warehouse id is not part of the configured network."""


class InvalidTransition(StockError):
    """An order operation was invoked on an order that cannot accept it."""


class LedgerViolation(StockError):
    """A movement would take a stock position negative."""


class StorageInterrupted(StockError):
    """Raised by storage adapters when a write is cut off mid-operation.

    The interrupted write may or may not have landed durably; the
    operation that saw this exception cannot know which. See
    ``src/ops.py`` for the operation discipline this implies.
    """

path: src/errors.py

content: """Order intake: validate, allocate what the shelves can cover, queue
the rest.

Intake allocates greedily at submission time using the one allocation
policy (see ``src/allocator.py``); whatever the network cannot cover
becomes backorder entries stamped with the order's rank and submission
time. Lines are processed in the order given.
"""

from typing import Iterable, Tuple

from . import allocator
from .backorders import BackorderEntry
from .errors import StockError
from .orders import Allocation, Order, OrderLine


def submit(
    engine,
    order_id: str,
    zone: str,
    priority_class: str,
    submitted_at: int,
    lines: Iterable[Tuple[str, int]],
) -> Order:
    if order_id in engine.orders:
        raise StockError("duplicate order id: %s" % order_id)
    rank = engine.config.rank_of(priority_class)

    order_lines = []
    seen_skus = set()
    for sku, qty in lines:
        if qty <= 0:
            raise StockError("order lines carry positive quantities")
        if sku in seen_skus:
            raise StockError("one line per SKU: %s repeated" % sku)
        seen_skus.add(sku)
        order_lines.append(OrderLine(sku=sku, qty=qty))
    if not order_lines:
        raise StockError("orders carry at least one line")

    order = Order(
        order_id=order_id,
        zone=zone,
        priority_class=priority_class,
        submitted_at=submitted_at,
        lines=tuple(order_lines),
    )
    engine.orders[order_id] = order
    engine.counters.bump("orders_received")

    cause = "submit:%s" % order_id
    for line in order.lines:
        sources = allocator.plan(
            engine.config, engine.ledger, engine.counters,
            line.sku, line.qty, zone,
        )
        covered = 0
        for warehouse_id, take in sources:
            engine.record_movement(
                "reserve", warehouse_id, line.sku, take, order_id, cause
            )
            order.allocations.append(
                Allocation(
                    order_id=order_id,
                    sku=line.sku,
                    warehouse_id=warehouse_id,
                    qty=take,
                )
            )
            covered += take
        shortfall = line.qty - covered
        if shortfall > 0:
            engine.queue.add(
                BackorderEntry(
                    order_id=order_id,
                    sku=line.sku,
                    qty=shortfall,
                    priority_rank=rank,
                    submitted_at=submitted_at,
                )
            )
            engine.counters.bump("backorder_units_created", shortfall)
    return order

path: src/intake.py

content: """The movement journal: the authoritative record of stock changes.

Every unit that changes state does so through exactly one journaled
movement, and the journal is append-only. Downstream systems — the WMS
reconciler, finance, the capacity dashboards — read this journal, so
its vocabulary is fixed: a movement's ``kind`` must be one of
:data:`MOVE_KINDS`, and every movement names the warehouse it
physically happens at, the order it belongs to, and the operation that
caused it (``cause``, e.g. ``"pick:O-7"``).

When in doubt about what has already happened, the journal is the
record to believe.
"""

from dataclasses import dataclass
from typing import Iterator, List

from .errors import StockError

#: The fixed movement vocabulary. ``reserve`` earmarks available units,
#: ``pick`` stages reserved units, ``ship`` sends picked units out of
#: the building, ``unreserve`` returns reserved units to available,
#: ``restock`` returns picked units to available.
MOVE_KINDS = ("reserve", "pick", "ship", "unreserve", "restock")


@dataclass(frozen=True)
class Movement:
    seq: int
    kind: str
    warehouse_id: str
    sku: str
    qty: int
    order_id: str
    cause: str


class MovementJournal:
    """Append-only sequence of :class:`Movement` records."""

    def __init__(self):
        self._records: List[Movement] = []

    def append(self, kind, warehouse_id, sku, qty, order_id, cause) -> Movement:
        if kind not in MOVE_KINDS:
            raise StockError("unknown movement kind: %s" % kind)
        if qty <= 0:
            raise StockError("movements carry positive quantities")
        record = Movement(
            seq=len(self._records) + 1,
            kind=kind,
            warehouse_id=warehouse_id,
            sku=sku,
            qty=qty,
            order_id=order_id,
            cause=cause,
        )
        self._records.append(record)
        return record

    def __iter__(self) -> Iterator[Movement]:
        return iter(self._records)

    def __len__(self) -> int:
        return len(self._records)

    def for_order(self, order_id: str) -> List[Movement]:
        return [m for m in self._records if m.order_id == order_id]

    def caused_by(self, cause: str) -> List[Movement]:
        return [m for m in self._records if m.cause == cause]

path: src/journal.py

content: """Per-warehouse stock positions.

The ledger tracks, for every ``(warehouse, sku)`` pair, how many units
are in each state: ``available`` (on the shelf, sellable), ``reserved``
(earmarked for an order), ``picked`` (pulled to staging for an order),
and ``shipped`` (cumulative units that left the building). Every unit
is in exactly one state, so for each pair::

    available + reserved + picked + shipped == opening balance

holds at all times. Stock lives where it lives: positions change only
by applying movements, and a movement acts on the one warehouse it
names. The engine loads opening balances once, at construction, from
the WMS start-of-day position export — nothing inside this service
creates stock.
"""

from dataclasses import dataclass
from typing import Dict, List, Tuple

from .errors import LedgerViolation
from .journal import Movement


@dataclass(frozen=True)
class Position:
    available: int
    reserved: int
    picked: int
    shipped: int


_EMPTY = (0, 0, 0, 0)

# kind -> (state debited, state credited); shipped only accumulates.
_TRANSITIONS = {
    "reserve": ("available", "reserved"),
    "pick": ("reserved", "picked"),
    "ship": ("picked", "shipped"),
    "unreserve": ("reserved", "available"),
    "restock": ("picked", "available"),
}

_STATES = ("available", "reserved", "picked", "shipped")


class StockLedger:
    def __init__(self):
        self._pos: Dict[Tuple[str, str], List[int]] = {}

    def load_opening(self, warehouse_id: str, sku: str, qty: int) -> None:
        if qty < 0:
            raise LedgerViolation("opening balances are non-negative")
        cell = self._pos.setdefault((warehouse_id, sku), list(_EMPTY))
        cell[0] += qty

    def check(self, kind: str, warehouse_id: str, sku: str, qty: int) -> None:
        """Raise :class:`LedgerViolation` if the movement cannot apply."""
        cell = self._pos.get((warehouse_id, sku), _EMPTY)
        debit, _credit = _TRANSITIONS[kind]
        d = _STATES.index(debit)
        if cell[d] < qty:
            raise LedgerViolation(
                "%s of %d %s at %s exceeds %s=%d"
                % (kind, qty, sku, warehouse_id, debit, cell[d])
            )

    def apply(self, movement: Movement) -> None:
        self.check(
            movement.kind, movement.warehouse_id, movement.sku, movement.qty
        )
        cell = self._pos.setdefault(
            (movement.warehouse_id, movement.sku), list(_EMPTY)
        )
        debit, credit = _TRANSITIONS[movement.kind]
        d, c = _STATES.index(debit), _STATES.index(credit)
        cell[d] -= movement.qty
        cell[c] += movement.qty

    def position(self, warehouse_id: str, sku: str) -> Position:
        cell = self._pos.get((warehouse_id, sku), _EMPTY)
        return Position(*cell)

    def availability(self, sku: str) -> Dict[str, int]:
        """Available units of ``sku`` per warehouse, sorted by warehouse."""
        out = {}
        for (wh, s), cell in sorted(self._pos.items()):
            if s == sku and cell[0] > 0:
                out[wh] = cell[0]
        return out

    def pairs(self) -> List[Tuple[str, str]]:
        """All (warehouse, sku) pairs ever touched, sorted."""
        return sorted(self._pos.keys())

path: src/ledger.py

content: """Counters: the operational record the dashboards trust.

Counters are a record of events that happened. They only move forward;
a correction is a new event, never an edit of an old number. The
capacity and SLA dashboards, and the finance reconciliation behind
them, are built on that property — an audit counter that can go down
is an audit counter nobody can trust.

The registry below is the shared vocabulary with those dashboards; the
names are contractual. ``allocation_scans`` is the work meter the
capacity planners watch: it counts warehouses examined by the
allocator, whatever asked for the allocation.
"""

from typing import Dict

COUNTER_NAMES = (
    "orders_received",
    "units_reserved",
    "units_picked",
    "units_shipped",
    "units_unreserved",
    "units_restocked",
    "backorder_units_created",
    "backorder_units_served",
    "orders_released",
    "allocation_scans",
)


class Counters:
    def __init__(self):
        self._values: Dict[str, int] = {name: 0 for name in COUNTER_NAMES}

    def bump(self, name: str, amount: int = 1) -> None:
        if name not in self._values:
            raise KeyError("unregistered counter: %s" % name)
        if amount < 0:
            raise ValueError("counters only move forward")
        self._values[name] += amount

    def value(self, name: str) -> int:
        if name not in self._values:
            raise KeyError("unregistered counter: %s" % name)
        return self._values[name]

    def snapshot(self) -> Dict[str, int]:
        return dict(self._values)

path: src/metrics.py

content: """Operational discipline for engine operations.

Storage may cut an operation off at any journaled movement
(:class:`~src.errors.StorageInterrupted`). Movements before the cut are
durable; the movement at the cut may have landed durably even though
the operation never saw it complete — the acknowledgement, not the
write, is what got lost. The operator's runbook answer to an
interrupted operation is always the same: invoke it again.

That places one obligation on every operation in this service, present
and future: re-invocation must land the effects of exactly one
completed execution — never a unit twice, never a unit dropped, never
an event counted twice. Operations meet it by believing the movement
journal over any in-memory bookkeeping when the two disagree about
what already happened, and by deriving their remaining work from the
records rather than from plans made before the cut.

This module also hosts the start-of-day loading helpers: opening
balances come from the WMS position export, once, at engine
construction. Nothing inside this service creates stock after that.
"""

from typing import Dict, Tuple

from .errors import StockError


def opening_positions(text: str) -> Dict[Tuple[str, str], int]:
    """Parse a WMS position export: one ``WAREHOUSE SKU QTY`` per line.

    Blank lines and ``#`` comment lines are ignored.
    """
    positions: Dict[Tuple[str, str], int] = {}
    for raw in text.splitlines():
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        parts = line.split()
        if len(parts) != 3:
            raise StockError("malformed position line: %r" % raw)
        warehouse_id, sku, qty_text = parts
        try:
            qty = int(qty_text)
        except ValueError:
            raise StockError("malformed quantity in line: %r" % raw)
        key = (warehouse_id, sku)
        positions[key] = positions.get(key, 0) + qty
    return positions

path: src/ops.py

content: """Orders, order lines, and allocations.

An order is submitted with a destination zone, a priority class, an
explicit ``submitted_at`` stamp (the intake gateway stamps orders; this
service never consults a clock), and one line per SKU. Allocations
record which warehouse is holding units for which line and what stage
those units are in; an order accumulates allocations over its life and
never loses one — the allocation list is a history, not a view.
"""

from dataclasses import dataclass, field
from typing import List, Optional, Tuple

from .errors import StockError

#: Stages a unit-batch moves through. ``released`` marks an allocation
#: whose units were returned to service.
ALLOCATION_STAGES = ("reserved", "picked", "shipped", "released")


@dataclass(frozen=True)
class OrderLine:
    sku: str
    qty: int


@dataclass
class Allocation:
    order_id: str
    sku: str
    warehouse_id: str
    qty: int
    stage: str = "reserved"

    def advance(self, stage: str) -> None:
        if stage not in ALLOCATION_STAGES:
            raise StockError("unknown allocation stage: %s" % stage)
        self.stage = stage


@dataclass
class Order:
    order_id: str
    zone: str
    priority_class: str
    submitted_at: int
    lines: Tuple[OrderLine, ...]
    allocations: List[Allocation] = field(default_factory=list)
    released: bool = False
    release_outcome: Optional[object] = None

    def line_for(self, sku: str) -> OrderLine:
        for line in self.lines:
            if line.sku == sku:
                return line
        raise StockError("order %s has no line for %s" % (self.order_id, sku))

    def allocated_qty(self, sku: str) -> int:
        return sum(a.qty for a in self.allocations if a.sku == sku)

    def in_stage(self, stage: str) -> List[Allocation]:
        return [a for a in self.allocations if a.stage == stage]

    def status(self) -> str:
        if self.released:
            return "released"
        stages = {a.stage for a in self.allocations}
        total_allocated = sum(a.qty for a in self.allocations)
        total_ordered = sum(line.qty for line in self.lines)
        if stages == {"shipped"} and total_allocated == total_ordered:
            return "shipped"
        if "picked" in stages:
            return "picking"
        if "reserved" in stages:
            return "allocated"
        if "shipped" in stages:
            return "partially_shipped"
        return "waiting"

path: src/orders.py

content: """Fulfilment stage operations: pick and ship.

Both operations act on whatever the order currently has in the
preceding stage and return how many units they moved; moving nothing
is a quiet no-op, not an error. That shape is deliberate — each unit's
stage advances together with its journaled movement, so an operation
interrupted by storage (see ``src/ops.py``) is simply re-invoked and
finishes the remainder. Because an interrupted write may have landed
without being acknowledged, re-invocation first squares the in-memory
picture with the journal: if the newest journaled movement of this
operation never took effect here, it is applied now — the journal is
the record to believe.
"""

from .errors import InvalidTransition, UnknownOrder

_STAGE_OPS = {
    # kind: (stage it consumes, stage it produces, counter it feeds)
    "pick": ("reserved", "picked", "units_picked"),
    "ship": ("picked", "shipped", "units_shipped"),
}


def _order_for(engine, order_id):
    try:
        order = engine.orders[order_id]
    except KeyError:
        raise UnknownOrder(order_id)
    if order.released:
        raise InvalidTransition(
            "order %s is released; its remainder cannot move" % order_id
        )
    return order


def _repair_lost_ack(engine, order, kind, cause) -> int:
    """Apply the newest journaled movement of this operation if its
    effects never landed in memory. Only the journal's tail can be in
    doubt: everything before it was acknowledged."""
    moves = engine.journal.caused_by(cause)
    if not moves:
        return 0
    last = moves[-1]
    if last.seq != len(engine.journal):
        return 0
    from_stage, to_stage, counter = _STAGE_OPS[kind]
    for allocation in order.allocations:
        if (
            allocation.stage == from_stage
            and allocation.warehouse_id == last.warehouse_id
            and allocation.sku == last.sku
            and allocation.qty == last.qty
        ):
            engine.ledger.apply(last)
            engine.counters.bump(counter, last.qty)
            allocation.advance(to_stage)
            return last.qty
    return 0


def _advance_stage(engine, order_id: str, kind: str) -> int:
    order = _order_for(engine, order_id)
    cause = "%s:%s" % (kind, order_id)
    from_stage, to_stage, _counter = _STAGE_OPS[kind]
    moved = _repair_lost_ack(engine, order, kind, cause)
    for allocation in order.in_stage(from_stage):
        engine.record_movement(
            kind,
            allocation.warehouse_id,
            allocation.sku,
            allocation.qty,
            order_id,
            cause,
        )
        allocation.advance(to_stage)
        moved += allocation.qty
    return moved


def pick(engine, order_id: str) -> int:
    """Advance every reserved allocation of the order to picked."""
    return _advance_stage(engine, order_id, "pick")


def ship(engine, order_id: str) -> int:
    """Advance every picked allocation of the order to shipped."""
    return _advance_stage(engine, order_id, "ship")

path: src/pipeline.py

content: """Read-side convenience queries."""

from typing import Dict, List, Tuple

from .errors import UnknownOrder


def availability(engine, sku: str) -> Dict[str, int]:
    """Available units of ``sku`` per warehouse (only warehouses > 0)."""
    return engine.ledger.availability(sku)


def order_status(engine, order_id: str) -> str:
    try:
        return engine.orders[order_id].status()
    except KeyError:
        raise UnknownOrder(order_id)


def queue_positions(engine, order_id: str) -> List[Tuple[int, str, int]]:
    """The order's waiting lines as ``(position, sku, qty)``.

    Position counts from 1 across the whole queue in service order.
    """
    out = []
    for index, entry in enumerate(engine.queue.waiting(), start=1):
        if entry.order_id == order_id:
            out.append((index, entry.sku, entry.qty))
    return out

path: src/queries.py

content: """Order release (not implemented).

``release(engine, order_id)`` cancels the unshipped remainder of an
order and puts its stock back to work. The agreed requirements are in
the project issue.
"""

from dataclasses import dataclass


@dataclass(frozen=True)
class ReleaseOutcome:
    """What one release accomplished.

    ``units_unreserved`` and ``units_restocked`` count units returned
    to available; ``backorder_units_cancelled`` counts waiting units
    withdrawn from the queue; ``units_already_shipped`` counts units
    release could not bring back.
    """

    order_id: str
    units_unreserved: int
    units_restocked: int
    backorder_units_cancelled: int
    units_already_shipped: int


def release(engine, order_id: str) -> ReleaseOutcome:
    raise NotImplementedError("release is not implemented yet")

path: src/release.py

content: """Deterministic renderings of engine state.

Report row orders are contractual: downstream diffing tools compare
reports line by line, so the same state always renders the same text.
The inventory report walks positions in ``(warehouse, sku)`` order; the
demand report lists the backorder queue in service order; the movement
history renders the journal in sequence order.
"""

from typing import List


def inventory_report(engine) -> List[str]:
    rows = []
    for warehouse_id, sku in engine.ledger.pairs():
        pos = engine.ledger.position(warehouse_id, sku)
        rows.append(
            "%s %s %d %d %d %d"
            % (warehouse_id, sku, pos.available, pos.reserved,
               pos.picked, pos.shipped)
        )
    return rows


def demand_report(engine) -> List[str]:
    rows = []
    for index, entry in enumerate(engine.queue.waiting(), start=1):
        order = engine.orders[entry.order_id]
        rows.append(
            "%d %s %s %d %s %d"
            % (index, entry.order_id, entry.sku, entry.qty,
               order.priority_class, entry.submitted_at)
        )
    return rows


def movement_history(engine) -> List[str]:
    rows = []
    for m in engine.journal:
        rows.append(
            "%d %s %s %s %d %s %s"
            % (m.seq, m.kind, m.warehouse_id, m.sku, m.qty,
               m.order_id, m.cause)
        )
    return rows


def order_report(engine, order_id: str) -> List[str]:
    from .errors import UnknownOrder

    try:
        order = engine.orders[order_id]
    except KeyError:
        raise UnknownOrder(order_id)
    rows = [
        "order %s zone=%s class=%s submitted=%d status=%s"
        % (order.order_id, order.zone, order.priority_class,
           order.submitted_at, order.status())
    ]
    for allocation in sorted(
        order.allocations,
        key=lambda a: (a.sku, a.warehouse_id, a.stage),
    ):
        rows.append(
            "  alloc %s %s %d %s"
            % (allocation.sku, allocation.warehouse_id,
               allocation.qty, allocation.stage)
        )
    for entry in engine.queue.waiting_for(order_id):
        rows.append("  waiting %s %d" % (entry.sku, entry.qty))
    return rows

path: src/reports.py

content: import pytest

from src.config import EngineConfig, WarehouseSpec, standard_classes
from src.engine import StockEngine
from src.errors import ConfigError, StockError


def two_warehouse_engine(positions):
    config = EngineConfig(
        warehouses=(
            WarehouseSpec("WH-1", {"north": 3, "south": 7}),
            WarehouseSpec("WH-2", {"north": 5, "south": 2}),
        ),
        priority_classes=standard_classes(),
    )
    return StockEngine(config, positions)


def test_single_warehouse_full_allocation():
    engine = two_warehouse_engine({("WH-1", "SKU-A"): 10})
    order = engine.submit("O-1", "north", "standard", 100, [("SKU-A", 4)])
    pos = engine.ledger.position("WH-1", "SKU-A")
    assert (pos.available, pos.reserved) == (6, 4)
    assert order.status() == "allocated"
    assert len(engine.queue) == 0


def test_cost_ranked_selection():
    engine = two_warehouse_engine(
        {("WH-1", "SKU-A"): 5, ("WH-2", "SKU-A"): 5}
    )
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 3)])
    # north is cheaper from WH-1 (3 < 5)
    assert engine.ledger.position("WH-1", "SKU-A").reserved == 3
    assert engine.ledger.position("WH-2", "SKU-A").reserved == 0


def test_cost_tie_breaks_on_warehouse_id():
    config = EngineConfig(
        warehouses=(
            WarehouseSpec("WH-B", {"east": 4}),
            WarehouseSpec("WH-A", {"east": 4}),
        ),
        priority_classes=standard_classes(),
    )
    engine = StockEngine(
        config, {("WH-A", "SKU-X"): 5, ("WH-B", "SKU-X"): 5}
    )
    engine.submit("O-1", "east", "standard", 100, [("SKU-X", 2)])
    assert engine.ledger.position("WH-A", "SKU-X").reserved == 2
    assert engine.ledger.position("WH-B", "SKU-X").reserved == 0


def test_split_across_warehouses_when_cheapest_runs_out():
    engine = two_warehouse_engine(
        {("WH-1", "SKU-A"): 5, ("WH-2", "SKU-A"): 8}
    )
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 7)])
    assert engine.ledger.position("WH-1", "SKU-A").reserved == 5
    assert engine.ledger.position("WH-2", "SKU-A").reserved == 2


def test_zone_not_served_is_skipped():
    config = EngineConfig(
        warehouses=(
            WarehouseSpec("WH-1", {"north": 3}),
            WarehouseSpec("WH-2", {"south": 2}),
        ),
        priority_classes=standard_classes(),
    )
    engine = StockEngine(
        config, {("WH-1", "SKU-A"): 1, ("WH-2", "SKU-A"): 9}
    )
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 3)])
    # WH-2 has plenty but does not serve north.
    assert engine.ledger.position("WH-2", "SKU-A").reserved == 0
    assert engine.ledger.position("WH-1", "SKU-A").reserved == 1
    assert engine.queue.waiting()[0].qty == 2


def test_unserved_zone_backorders_entirely():
    engine = two_warehouse_engine({("WH-1", "SKU-A"): 5})
    engine.submit("O-1", "moon", "standard", 100, [("SKU-A", 2)])
    assert len(engine.journal) == 0
    entry = engine.queue.waiting()[0]
    assert (entry.order_id, entry.sku, entry.qty) == ("O-1", "SKU-A", 2)


def test_shortfall_creates_backorder_and_partial_reservation():
    engine = two_warehouse_engine({("WH-1", "SKU-A"): 3})
    order = engine.submit("O-1", "north", "standard", 100, [("SKU-A", 5)])
    assert engine.ledger.position("WH-1", "SKU-A").reserved == 3
    entry = engine.queue.waiting()[0]
    assert entry.qty == 2
    assert entry.submitted_at == 100
    assert order.status() == "allocated"
    assert engine.counters.value("backorder_units_created") == 2


def test_duplicate_order_id_rejected():
    engine = two_warehouse_engine({("WH-1", "SKU-A"): 5})
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 1)])
    with pytest.raises(StockError):
        engine.submit("O-1", "north", "standard", 101, [("SKU-A", 1)])


def test_one_line_per_sku_enforced():
    engine = two_warehouse_engine({("WH-1", "SKU-A"): 5})
    with pytest.raises(StockError):
        engine.submit(
            "O-1", "north", "standard", 100,
            [("SKU-A", 1), ("SKU-A", 2)],
        )


def test_positive_quantities_enforced():
    engine = two_warehouse_engine({("WH-1", "SKU-A"): 5})
    with pytest.raises(StockError):
        engine.submit("O-1", "north", "standard", 100, [("SKU-A", 0)])


def test_unknown_priority_class_rejected():
    engine = two_warehouse_engine({("WH-1", "SKU-A"): 5})
    with pytest.raises(ConfigError):
        engine.submit("O-1", "north", "platinum", 100, [("SKU-A", 1)])


def test_allocation_scans_meter_exact():
    engine = two_warehouse_engine(
        {("WH-1", "SKU-A"): 5, ("WH-2", "SKU-A"): 5}
    )
    # Fully covered at the first warehouse considered: exactly one scan.
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 4)])
    assert engine.counters.value("allocation_scans") == 1
    # Split across both: two scans.
    engine.submit("O-2", "north", "standard", 101, [("SKU-A", 3)])
    assert engine.counters.value("allocation_scans") == 3


def test_multi_line_processed_in_given_order():
    engine = two_warehouse_engine(
        {("WH-1", "SKU-A"): 5, ("WH-1", "SKU-B"): 5}
    )
    engine.submit(
        "O-1", "north", "standard", 100,
        [("SKU-B", 1), ("SKU-A", 1)],
    )
    kinds = [(m.sku,) for m in engine.journal]
    assert kinds == [("SKU-B",), ("SKU-A",)]

path: tests/public/test_intake_allocation.py

content: import pytest

from src.config import EngineConfig, WarehouseSpec, standard_classes
from src.engine import StockEngine
from src.errors import LedgerViolation, StockError
from src.ledger import Position
from src import ops


def build_engine():
    config = EngineConfig(
        warehouses=(
            WarehouseSpec("WH-1", {"north": 3, "south": 7}),
            WarehouseSpec("WH-2", {"north": 5, "south": 2}),
        ),
        priority_classes=standard_classes(),
    )
    return StockEngine.from_positions(
        config,
        """
        WH-1 SKU-A 5
        WH-2 SKU-A 8
        WH-1 SKU-B 2
        """,
    )


OPENING = {("WH-1", "SKU-A"): 5, ("WH-2", "SKU-A"): 8, ("WH-1", "SKU-B"): 2}


def test_conservation_across_operations():
    engine = build_engine()
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 7), ("SKU-B", 4)])
    engine.submit("O-2", "south", "rush", 105, [("SKU-A", 4)])
    engine.pick("O-1")
    engine.ship("O-1")
    for (warehouse_id, sku), opening in OPENING.items():
        pos = engine.ledger.position(warehouse_id, sku)
        total = pos.available + pos.reserved + pos.picked + pos.shipped
        assert total == opening, (warehouse_id, sku)


def test_movements_journaled_in_sequence_with_causes():
    engine = build_engine()
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 7)])
    engine.pick("O-1")
    rows = [
        (m.seq, m.kind, m.warehouse_id, m.qty, m.cause)
        for m in engine.journal
    ]
    assert rows == [
        (1, "reserve", "WH-1", 5, "submit:O-1"),
        (2, "reserve", "WH-2", 2, "submit:O-1"),
        (3, "pick", "WH-1", 5, "pick:O-1"),
        (4, "pick", "WH-2", 2, "pick:O-1"),
    ]


def test_direct_overdraw_rejected_and_never_journaled():
    engine = build_engine()
    before = len(engine.journal)
    with pytest.raises(LedgerViolation):
        engine.record_movement("reserve", "WH-1", "SKU-A", 6, "O-X", "submit:O-X")
    # The journal is the commit point: a rejected movement never lands.
    assert len(engine.journal) == before


def test_unknown_movement_kind_rejected():
    engine = build_engine()
    with pytest.raises(StockError):
        engine.journal.append("teleport", "WH-1", "SKU-A", 1, "O-1", "x")


def test_nonpositive_movement_rejected():
    engine = build_engine()
    with pytest.raises(StockError):
        engine.journal.append("reserve", "WH-1", "SKU-A", 0, "O-1", "x")


def test_journal_filters():
    engine = build_engine()
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 2)])
    engine.submit("O-2", "north", "standard", 101, [("SKU-A", 2)])
    engine.pick("O-1")
    assert [m.kind for m in engine.journal.for_order("O-1")] == [
        "reserve", "pick",
    ]
    assert [m.order_id for m in engine.journal.caused_by("submit:O-2")] == [
        "O-2",
    ]


def test_untouched_position_reads_zero():
    engine = build_engine()
    assert engine.ledger.position("WH-2", "SKU-B") == Position(0, 0, 0, 0)


def test_opening_export_parsing():
    positions = ops.opening_positions(
        """
        # start of day
        WH-1 SKU-A 5

        WH-1 SKU-A 3
        WH-2 SKU-B 1
        """
    )
    assert positions == {("WH-1", "SKU-A"): 8, ("WH-2", "SKU-B"): 1}
    with pytest.raises(StockError):
        ops.opening_positions("WH-1 SKU-A")
    with pytest.raises(StockError):
        ops.opening_positions("WH-1 SKU-A many")

path: tests/public/test_ledger_journal.py

content: import pytest

from src.config import EngineConfig, WarehouseSpec, standard_classes
from src.engine import StockEngine
from src.errors import UnknownOrder


def build_engine():
    config = EngineConfig(
        warehouses=(
            WarehouseSpec("WH-1", {"north": 3}),
            WarehouseSpec("WH-2", {"north": 5}),
        ),
        priority_classes=standard_classes(),
    )
    return StockEngine(
        config, {("WH-1", "SKU-A"): 5, ("WH-2", "SKU-A"): 8}
    )


def test_pick_moves_reserved_to_picked():
    engine = build_engine()
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 7)])
    moved = engine.pick("O-1")
    assert moved == 7
    assert engine.ledger.position("WH-1", "SKU-A").picked == 5
    assert engine.ledger.position("WH-2", "SKU-A").picked == 2
    assert engine.counters.value("units_picked") == 7
    kinds = [m.kind for m in engine.journal]
    assert kinds == ["reserve", "reserve", "pick", "pick"]


def test_ship_moves_picked_to_shipped():
    engine = build_engine()
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 4)])
    engine.pick("O-1")
    moved = engine.ship("O-1")
    assert moved == 4
    pos = engine.ledger.position("WH-1", "SKU-A")
    assert (pos.available, pos.reserved, pos.picked, pos.shipped) == (
        1, 0, 0, 4,
    )
    assert engine.counters.value("units_shipped") == 4


def test_pick_nothing_reserved_is_quiet_noop():
    engine = build_engine()
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 4)])
    engine.pick("O-1")
    assert engine.pick("O-1") == 0
    assert engine.counters.value("units_picked") == 4


def test_ship_nothing_picked_is_quiet_noop():
    engine = build_engine()
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 4)])
    assert engine.ship("O-1") == 0


def test_pick_unknown_order_raises():
    engine = build_engine()
    with pytest.raises(UnknownOrder):
        engine.pick("O-404")


def test_full_flow_status_shipped():
    engine = build_engine()
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 4)])
    engine.pick("O-1")
    engine.ship("O-1")
    assert engine.orders["O-1"].status() == "shipped"


def test_pick_only_moves_this_orders_units():
    engine = build_engine()
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 3)])
    engine.submit("O-2", "north", "standard", 101, [("SKU-A", 2)])
    engine.pick("O-1")
    assert engine.ledger.position("WH-1", "SKU-A").picked == 3
    assert engine.ledger.position("WH-1", "SKU-A").reserved == 2


def test_repeated_pick_and_ship_stay_settled():
    engine = build_engine()
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 7)])
    assert engine.pick("O-1") == 7
    assert engine.pick("O-1") == 0
    assert engine.ship("O-1") == 7
    assert engine.ship("O-1") == 0
    assert engine.counters.value("units_picked") == 7
    assert engine.counters.value("units_shipped") == 7
    assert len([m for m in engine.journal if m.kind == "pick"]) == 2
    assert len([m for m in engine.journal if m.kind == "ship"]) == 2

path: tests/public/test_pipeline.py

content: import pytest

from src.config import EngineConfig, WarehouseSpec, standard_classes
from src.engine import StockEngine
from src import queries, reports


def build_engine(positions):
    config = EngineConfig(
        warehouses=(
            WarehouseSpec("WH-1", {"north": 3, "south": 7}),
            WarehouseSpec("WH-2", {"north": 5, "south": 2}),
        ),
        priority_classes=standard_classes(),
    )
    return StockEngine(config, positions)


def test_inventory_report_rows_sorted_exact():
    engine = build_engine(
        {("WH-2", "SKU-A"): 8, ("WH-1", "SKU-A"): 5, ("WH-1", "SKU-B"): 2}
    )
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 7)])
    engine.pick("O-1")
    assert reports.inventory_report(engine) == [
        "WH-1 SKU-A 0 0 5 0",
        "WH-1 SKU-B 2 0 0 0",
        "WH-2 SKU-A 6 0 2 0",
    ]


def test_demand_report_service_order_class_before_age():
    engine = build_engine({})
    engine.submit("O-std", "north", "standard", 100, [("SKU-A", 5)])
    engine.submit("O-rush", "north", "rush", 200, [("SKU-A", 3)])
    assert reports.demand_report(engine) == [
        "1 O-rush SKU-A 3 rush 200",
        "2 O-std SKU-A 5 standard 100",
    ]


def test_demand_report_age_then_order_id():
    engine = build_engine({})
    engine.submit("O-b", "north", "standard", 100, [("SKU-A", 1)])
    engine.submit("O-a", "north", "standard", 100, [("SKU-A", 1)])
    engine.submit("O-c", "north", "standard", 90, [("SKU-A", 1)])
    assert reports.demand_report(engine) == [
        "1 O-c SKU-A 1 standard 90",
        "2 O-a SKU-A 1 standard 100",
        "3 O-b SKU-A 1 standard 100",
    ]


def test_movement_history_exact():
    engine = build_engine({("WH-1", "SKU-A"): 5})
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 2)])
    engine.pick("O-1")
    engine.ship("O-1")
    assert reports.movement_history(engine) == [
        "1 reserve WH-1 SKU-A 2 O-1 submit:O-1",
        "2 pick WH-1 SKU-A 2 O-1 pick:O-1",
        "3 ship WH-1 SKU-A 2 O-1 ship:O-1",
    ]


def test_order_report_exact_mixed():
    engine = build_engine({("WH-1", "SKU-A"): 3})
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 5), ("SKU-B", 1)])
    assert reports.order_report(engine, "O-1") == [
        "order O-1 zone=north class=standard submitted=100 status=allocated",
        "  alloc SKU-A WH-1 3 reserved",
        "  waiting SKU-A 2",
        "  waiting SKU-B 1",
    ]


def test_counters_snapshot_exact_forward_scenario():
    engine = build_engine(
        {("WH-1", "SKU-A"): 5, ("WH-2", "SKU-A"): 8, ("WH-1", "SKU-B"): 2}
    )
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 7), ("SKU-B", 4)])
    engine.submit("O-2", "south", "rush", 105, [("SKU-A", 4)])
    engine.pick("O-1")
    engine.ship("O-1")
    snapshot = engine.counters.snapshot()
    assert snapshot == {
        "orders_received": 2,
        "units_reserved": 13,
        "units_picked": 9,
        "units_shipped": 9,
        "units_unreserved": 0,
        "units_restocked": 0,
        "backorder_units_created": 2,
        "backorder_units_served": 0,
        "orders_released": 0,
        "allocation_scans": 5,
    }


def test_counters_only_move_forward():
    engine = build_engine({})
    with pytest.raises(ValueError):
        engine.counters.bump("units_reserved", -1)
    with pytest.raises(KeyError):
        engine.counters.bump("units_teleported")
    with pytest.raises(KeyError):
        engine.counters.value("units_teleported")


def test_queries():
    engine = build_engine({("WH-1", "SKU-A"): 3, ("WH-2", "SKU-A"): 1})
    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 5), ("SKU-B", 2)])
    assert queries.availability(engine, "SKU-A") == {}
    assert queries.order_status(engine, "O-1") == "allocated"
    assert queries.queue_positions(engine, "O-1") == [
        (1, "SKU-A", 1),
        (2, "SKU-B", 2),
    ]

path: tests/public/test_reports_metrics.py

Reference patch:
diff --git a/src/release.py b/src/release.py
index 9dec737..3cfa328 100644
--- a/src/release.py
+++ b/src/release.py
@@ -1,12 +1,19 @@
-"""Order release (not implemented).
-
-``release(engine, order_id)`` cancels the unshipped remainder of an
-order and puts its stock back to work. The agreed requirements are in
-the project issue.
-"""
+"""Order release: cancel the unshipped remainder, put stock back to work."""
 
 from dataclasses import dataclass
 
+from . import allocator
+from .errors import UnknownOrder
+from .orders import Allocation
+
+_UNWIND = {
+    # stage an allocation is in -> (movement kind, counter)
+    "reserved": ("unreserve", "units_unreserved"),
+    "picked": ("restock", "units_restocked"),
+}
+
+_REPAIR_STAGE = {"unreserve": "reserved", "restock": "picked"}
+
 
 @dataclass(frozen=True)
 class ReleaseOutcome:
@@ -25,5 +32,148 @@ class ReleaseOutcome:
     units_already_shipped: int
 
 
+def _repair_lost_ack(engine, order, cause):
+    """Square memory with the journal before doing new work.
+
+    A cut stops the release at one write, so at most one movement of
+    this release can be journaled without its effects having landed —
+    the newest one bearing our cause. Anything the service did between
+    the cut and this re-invocation is acknowledged work and needs no
+    repair; our own newest write is the only one in doubt, however
+    deep the journal has grown since.
+    """
+    moves = engine.journal.caused_by(cause)
+    if not moves:
+        return
+    last = moves[-1]
+    if last.kind in _REPAIR_STAGE:
+        wanted = _REPAIR_STAGE[last.kind]
+        for allocation in order.allocations:
+            if (
+                allocation.stage == wanted
+                and allocation.warehouse_id == last.warehouse_id
+                and allocation.sku == last.sku
+                and allocation.qty == last.qty
+            ):
+                engine.ledger.apply(last)
+                _kind, counter = _UNWIND[wanted]
+                engine.counters.bump(counter, last.qty)
+                allocation.advance("released")
+                return
+    elif last.kind == "reserve":
+        target = engine.orders[last.order_id]
+        journaled = sum(
+            m.qty
+            for m in engine.journal
+            if m.kind == "reserve"
+            and m.order_id == target.order_id
+            and m.sku == last.sku
+        )
+        if journaled > target.allocated_qty(last.sku):
+            engine.ledger.apply(last)
+            engine.counters.bump("units_reserved", last.qty)
+            target.allocations.append(
+                Allocation(
+                    order_id=target.order_id,
+                    sku=last.sku,
+                    warehouse_id=last.warehouse_id,
+                    qty=last.qty,
+                )
+            )
+            waiting = sum(
+                entry.qty
+                for entry in engine.queue.waiting_for(target.order_id)
+                if entry.sku == last.sku
+            )
+            engine.queue.serve(
+                target.order_id, last.sku, min(last.qty, waiting)
+            )
+
+
+def _cascade(engine, order_id, cause):
+    """Serve waiting demand with the stock now available, in service
+    order, through the one allocation policy."""
+    for entry in engine.queue.waiting():
+        if entry.order_id == order_id:
+            # Cancelled demand no longer waits in line.
+            continue
+        if not engine.ledger.availability(entry.sku):
+            continue
+        target = engine.orders[entry.order_id]
+        sources = allocator.plan(
+            engine.config,
+            engine.ledger,
+            engine.counters,
+            entry.sku,
+            entry.qty,
+            target.zone,
+        )
+        for warehouse_id, take in sources:
+            engine.record_movement(
+                "reserve", warehouse_id, entry.sku, take, entry.order_id, cause
+            )
+            target.allocations.append(
+                Allocation(
+                    order_id=entry.order_id,
+                    sku=entry.sku,
+                    warehouse_id=warehouse_id,
+                    qty=take,
+                )
+            )
+            engine.queue.serve(entry.order_id, entry.sku, take)
+
+
 def release(engine, order_id: str) -> ReleaseOutcome:
-    raise NotImplementedError("release is not implemented yet")
+    try:
+        order = engine.orders[order_id]
+    except KeyError:
+        raise UnknownOrder(order_id)
+    if order.released:
+        return order.release_outcome
+    cause = "release:%s" % order_id
+
+    _repair_lost_ack(engine, order, cause)
+
+    # Withdraw the order's own waiting demand: cancelled demand no
+    # longer waits in line (and must never be served below).
+    engine.queue.cancel(order_id)
+
+    # Unwind the unshipped remainder. Stock reappears where it
+    # physically is: each movement goes to the allocation's own
+    # warehouse.
+    for stage in ("reserved", "picked"):
+        kind, _counter = _UNWIND[stage]
+        for allocation in order.in_stage(stage):
+            engine.record_movement(
+                kind,
+                allocation.warehouse_id,
+                allocation.sku,
+                allocation.qty,
+                order_id,
+                cause,
+            )
+            allocation.advance("released")
+
+    _cascade(engine, order_id, cause)
+
+    # Completion: everything below derives from the durable record, so
+    # a re-invocation after any cut lands these effects exactly once.
+    moves = engine.journal.caused_by(cause)
+    unreserved = sum(m.qty for m in moves if m.kind == "unreserve")
+    restocked = sum(m.qty for m in moves if m.kind == "restock")
+    served = sum(m.qty for m in moves if m.kind == "reserve")
+    shipped = sum(a.qty for a in order.allocations if a.stage == "shipped")
+    ordered = sum(line.qty for line in order.lines)
+    ever_allocated = sum(a.qty for a in order.allocations)
+    outcome = ReleaseOutcome(
+        order_id=order_id,
+        units_unreserved=unreserved,
+        units_restocked=restocked,
+        backorder_units_cancelled=ordered - ever_allocated,
+        units_already_shipped=shipped,
+    )
+    engine.counters.bump("backorder_units_served", served)
+    engine.counters.bump("orders_released")
+    order.release_outcome = outcome
+    order.released = True
+    return outcome


Hidden acceptance tests (diff):
diff --git a/tests/hidden/test_hidden.py b/tests/hidden/test_hidden.py
new file mode 100644
--- /dev/null
+++ b/tests/hidden/test_hidden.py
@@ -0,0 +1,779 @@
+"""Hidden acceptance suite for order release.
+
+Grades the contract stated across the module docs and the issue:
+release cancels the unshipped remainder (shipped units are gone),
+returns stock to the warehouse it is physically in, withdraws the
+order's own waiting demand, serves remaining waiting demand
+immediately in service order through the one allocation policy, keeps
+the counters honest (events only, never edits), keeps allocation work
+proportional, and — like every operation in this service — lands the
+effects of exactly one completed execution when interrupted storage
+forces a re-invocation.
+
+The suite carries its own reference model — a semantics-only twin of
+the whole service built on plain dicts. It exists only here; the agent
+never sees it. Seeded sweeps compare engine observables against it
+across generated worlds.
+"""
+
+import random
+
+import pytest
+
+from src import reports
+from src.config import EngineConfig, WarehouseSpec, standard_classes
+from src.engine import StockEngine
+from src.errors import InvalidTransition, StorageInterrupted, UnknownOrder
+
+
+# -- builders --------------------------------------------------------------
+
+
+def two_wh_config():
+    return EngineConfig(
+        warehouses=(
+            WarehouseSpec("WH-1", {"north": 3, "south": 7}),
+            WarehouseSpec("WH-2", {"north": 5, "south": 2}),
+        ),
+        priority_classes=standard_classes(),
+    )
+
+
+def engine_with(positions, config=None):
+    return StockEngine(config or two_wh_config(), positions)
+
+
+class FlakyJournal:
+    """The Nth append lands durably but is never acknowledged."""
+
+    def __init__(self, journal, fail_at):
+        self._journal = journal
+        self._fail_at = fail_at
+        self._appends = 0
+
+    def append(self, *args, **kwargs):
+        self._appends += 1
+        record = self._journal.append(*args, **kwargs)
+        if self._appends == self._fail_at:
+            raise StorageInterrupted("write landed; acknowledgement lost")
+        return record
+
+    def __iter__(self):
+        return iter(self._journal)
+
+    def __len__(self):
+        return len(self._journal)
+
+    def __getattr__(self, name):
+        return getattr(self._journal, name)
+
+
+def counters_sans_scans(engine):
+    return {
+        k: v
+        for k, v in engine.counters.snapshot().items()
+        if k != "allocation_scans"
+    }
+
+
+def observable_state(engine):
+    return (
+        reports.inventory_report(engine),
+        reports.demand_report(engine),
+        counters_sans_scans(engine),
+        {oid: o.status() for oid, o in sorted(engine.orders.items())},
+    )
+
+
+def outcome_tuple(outcome):
+    return (
+        outcome.order_id,
+        outcome.units_unreserved,
+        outcome.units_restocked,
+        outcome.backorder_units_cancelled,
+        outcome.units_already_shipped,
+    )
+
+
+# -- the cited incidents ---------------------------------------------------
+
+
+def test_restock_returns_to_origin_warehouse():
+    # South is cheapest from WH-2, but the units were picked at WH-1:
+    # they must reappear at WH-1.
+    engine = engine_with({("WH-1", "SKU-A"): 4})
+    engine.submit("O-1", "south", "standard", 100, [("SKU-A", 4)])
+    engine.pick("O-1")
+    outcome = engine.release("O-1")
+    assert outcome.units_restocked == 4
+    pos1 = engine.ledger.position("WH-1", "SKU-A")
+    pos2 = engine.ledger.position("WH-2", "SKU-A")
+    assert (pos1.available, pos1.picked) == (4, 0)
+    assert pos2.available == 0
+    restocks = [m for m in engine.journal if m.kind == "restock"]
+    assert [m.warehouse_id for m in restocks] == ["WH-1"]
+
+
+def test_cascade_serves_class_before_age():
+    engine = engine_with({("WH-1", "SKU-A"): 5})
+    engine.submit("O-hold", "north", "standard", 50, [("SKU-A", 5)])
+    engine.submit("O-old", "north", "standard", 100, [("SKU-A", 5)])
+    engine.submit("O-new", "north", "rush", 200, [("SKU-A", 5)])
+    engine.release("O-hold")
+    # The rush order is served in full despite being eleven days younger.
+    assert engine.orders["O-new"].allocated_qty("SKU-A") == 5
+    assert engine.orders["O-old"].allocated_qty("SKU-A") == 0
+    assert reports.demand_report(engine) == ["1 O-old SKU-A 5 standard 100"]
+
+
+def test_release_counters_record_events_never_edits():
+    engine = engine_with({("WH-1", "SKU-A"): 5})
+    engine.submit("O-hold", "north", "standard", 50, [("SKU-A", 5)])
+    engine.pick("O-hold")
+    engine.submit("O-wait", "north", "standard", 100, [("SKU-A", 3)])
+    engine.release("O-hold")
+    # units_reserved only ever grows: 5 at submit + 3 served = 8.
+    assert counters_sans_scans(engine) == {
+        "orders_received": 2,
+        "units_reserved": 8,
+        "units_picked": 5,
+        "units_shipped": 0,
+        "units_unreserved": 0,
+        "units_restocked": 5,
+        "backorder_units_created": 3,
+        "backorder_units_served": 3,
+        "orders_released": 1,
+    }
+
+
+# -- remainder, idempotency, self-cancellation -----------------------------
+
+
+def test_shipped_units_stay_shipped():
+    engine = engine_with({("WH-1", "SKU-A"): 4})
+    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 10)])
+    engine.pick("O-1")
+    engine.ship("O-1")  # 4 shipped; 6 still waiting
+    engine.submit("O-2", "north", "standard", 110, [("SKU-A", 2)])
+    outcome = engine.release("O-1")
+    assert outcome_tuple(outcome) == ("O-1", 0, 0, 6, 4)
+    pos = engine.ledger.position("WH-1", "SKU-A")
+    assert (pos.available, pos.reserved, pos.picked, pos.shipped) == (
+        0, 0, 0, 4,
+    )
+    assert engine.orders["O-1"].status() == "released"
+    # Release brought nothing back, so O-2 keeps waiting.
+    assert reports.demand_report(engine) == ["1 O-2 SKU-A 2 standard 110"]
+
+
+def test_release_mixed_stages_unwinds_only_unshipped():
+    engine = engine_with({("WH-1", "SKU-A"): 6})
+    engine.submit("O-holder", "north", "standard", 90, [("SKU-A", 2)])
+    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 6)])
+    engine.pick("O-1")
+    engine.ship("O-1")  # 4 shipped; 2 still waiting
+    engine.release("O-holder")  # cascade hands O-1 two reserved units
+    order = engine.orders["O-1"]
+    assert order.allocated_qty("SKU-A") == 6
+    assert {a.stage for a in order.allocations} == {"shipped", "reserved"}
+    outcome = engine.release("O-1")
+    assert outcome_tuple(outcome) == ("O-1", 2, 0, 0, 4)
+    pos = engine.ledger.position("WH-1", "SKU-A")
+    assert (pos.available, pos.reserved, pos.picked, pos.shipped) == (
+        2, 0, 0, 4,
+    )
+    assert order.status() == "released"
+
+
+def test_release_is_idempotent_and_emits_nothing_new():
+    engine = engine_with({("WH-1", "SKU-A"): 5})
+    engine.submit("O-hold", "north", "standard", 50, [("SKU-A", 5)])
+    engine.submit("O-wait", "north", "rush", 60, [("SKU-A", 4)])
+    first = engine.release("O-hold")
+    journal_len = len(engine.journal)
+    counters = engine.counters.snapshot()
+    second = engine.release("O-hold")
+    assert outcome_tuple(second) == outcome_tuple(first)
+    assert len(engine.journal) == journal_len
+    assert engine.counters.snapshot() == counters
+    assert engine.counters.value("orders_released") == 1
+
+
+def test_own_backorders_cancelled_not_served():
+    engine = engine_with({("WH-1", "SKU-A"): 3})
+    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 5)])
+    outcome = engine.release("O-1")
+    # Its own waiting 2 units are withdrawn, never served from its own
+    # freed stock.
+    assert outcome_tuple(outcome) == ("O-1", 3, 0, 2, 0)
+    assert reports.demand_report(engine) == []
+    assert engine.ledger.position("WH-1", "SKU-A").available == 3
+    served = [
+        m for m in engine.journal
+        if m.kind == "reserve" and m.cause.startswith("release:")
+    ]
+    assert served == []
+
+
+def test_release_of_waiting_only_order_is_bookkeeping_only():
+    engine = engine_with({})
+    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 4)])
+    engine.submit("O-2", "north", "standard", 110, [("SKU-B", 1)])
+    before = len(engine.journal)
+    outcome = engine.release("O-1")
+    assert outcome_tuple(outcome) == ("O-1", 0, 0, 4, 0)
+    assert len(engine.journal) == before
+    assert engine.counters.value("orders_released") == 1
+    assert reports.demand_report(engine) == ["1 O-2 SKU-B 1 standard 110"]
+
+
+def test_released_order_cannot_move():
+    engine = engine_with({("WH-1", "SKU-A"): 5})
+    engine.submit("O-1", "north", "standard", 100, [("SKU-A", 5)])
+    engine.release("O-1")
+    with pytest.raises(InvalidTransition):
+        engine.pick("O-1")
+    with pytest.raises(InvalidTransition):
+        engine.ship("O-1")
+
+
+def test_release_unknown_order_raises():
+    engine = engine_with({})
+    with pytest.raises(UnknownOrder):
+        engine.release("O-404")
+
+
+# -- joint families: fairness x policy x conservation ----------------------
+
+
+def test_partial_service_keeps_place():
+    engine = engine_with({("WH-1", "SKU-A"): 4, ("WH-2", "SKU-A"): 4})
+    engine.submit("O-h1", "north", "standard", 10, [("SKU-A", 4)])
+    engine.submit("O-h2", "south", "standard", 11, [("SKU-A", 4)])
+    engine.submit("O-a", "north", "standard", 100, [("SKU-A", 6)])
+    engine.submit("O-b", "north", "standard", 101, [("SKU-A", 2)])
+    engine.release("O-h1")
+    # 4 freed: all go to O-a, which keeps its place for the remainder.
+    assert engine.orders["O-a"].allocated_qty("SKU-A") == 4
+    assert reports.demand_report(engine) == [
+        "1 O-a SKU-A 2 standard 100",
+        "2 O-b SKU-A 2 standard 101",
+    ]
+    engine.release("O-h2")
+    # 4 more freed: O-a's remainder first, then O-b.
+    assert engine.orders["O-a"].allocated_qty("SKU-A") == 6
+    assert engine.orders["O-b"].allocated_qty("SKU-A") == 2
+    assert reports.demand_report(engine) == []
+
+
+def test_cascade_split_follows_cost_policy():
+    engine = engine_with({("WH-1", "SKU-A"): 3, ("WH-2", "SKU-A"): 4})
+    engine.submit("O-hold", "north", "standard", 50, [("SKU-A", 7)])
+    engine.pick("O-hold")
+    engine.submit("O-wait", "north", "standard", 60, [("SKU-A", 6)])
+    engine.release("O-hold")
+    # Freed at both warehouses; north demand takes WH-1 (cost 3) first.
+    waiter = engine.orders["O-wait"]
+    sources = sorted(
+        (a.warehouse_id, a.qty) for a in waiter.allocations
+    )
+    assert sources == [("WH-1", 3), ("WH-2", 3)]
+    reserves = [
+        m for m in engine.journal
+        if m.kind == "reserve" and m.order_id == "O-wait"
+    ]
+    assert [m.warehouse_id for m in reserves] == ["WH-1", "WH-2"]
+    assert engine.ledger.position("WH-2", "SKU-A").available == 1
+
+
+def test_cascade_global_service_order_across_skus():
+    engine = engine_with(
+        {("WH-1", "SKU-A"): 4, ("WH-1", "SKU-B"): 3}
+    )
+    engine.submit(
+        "O-hold", "north", "standard", 50, [("SKU-A", 4), ("SKU-B", 3)]
+    )
+    engine.submit("O-eco", "north", "economy", 1, [("SKU-A", 2)])
+    engine.submit("O-std", "north", "standard", 5, [("SKU-B", 3)])
+    engine.submit("O-rush", "north", "rush", 10, [("SKU-A", 2)])
+    engine.release("O-hold")
+    served = [
+        (m.order_id, m.sku)
+        for m in engine.journal
+        if m.kind == "reserve" and m.cause == "release:O-hold"
+    ]
+    # One line, class first then age — the service sequence interleaves
+    # the SKUs: no per-SKU grouping produces it.
+    assert served == [
+        ("O-rush", "SKU-A"),
+        ("O-std", "SKU-B"),
+        ("O-eco", "SKU-A"),
+    ]
+    assert reports.demand_report(engine) == []
+
+
+# -- interrupted storage: exactly one completed execution ------------------
+
+
+def _interrupt_world():
+    engine = engine_with({("WH-1", "SKU-A"): 3, ("WH-2", "SKU-A"): 4})
+    engine.submit("O-hold", "north", "standard", 50, [("SKU-A", 7)])
+    engine.pick("O-hold")
+    engine.submit("O-rush", "north", "rush", 100, [("SKU-A", 5)])
+    engine.submit("O-std", "north", "standard", 90, [("SKU-A", 4)])
+    return engine
+
+
+def _release_with_cut(engine, order_id, fail_at):
+    engine.journal = FlakyJournal(engine.journal, fail_at)
+    with pytest.raises(StorageInterrupted):
+        engine.release(order_id)
+    return engine.release(order_id)
+
+
+def _uninterrupted_twin():
+    engine = _interrupt_world()
+    return engine, engine.release("O-hold")
+
+
+@pytest.mark.parametrize("fail_at", [1, 2, 3, 4, 5])
+def test_interrupted_release_retry_lands_exactly_once(fail_at):
+    # The release emits 2 restocks then 3 cascade reserves; cut at
+    # every movement in turn.
+    twin, twin_outcome = _uninterrupted_twin()
+    engine = _interrupt_world()
+    outcome = _release_with_cut(engine, "O-hold", fail_at)
+    assert observable_state(engine) == observable_state(twin)
+    assert outcome_tuple(outcome) == outcome_tuple(twin_outcome)
+
+
+def test_retry_completion_effects_exactly_once():
+    twin, twin_outcome = _uninterrupted_twin()
+    engine = _interrupt_world()
+    outcome = _release_with_cut(engine, "O-hold", 5)
+    assert engine.counters.value("orders_released") == 1
+    assert engine.counters.value("backorder_units_served") == \
+        twin.counters.value("backorder_units_served")
+    assert outcome_tuple(outcome) == outcome_tuple(twin_outcome)
+    # And the journal carries no duplicated movements.
+    assert len(engine.journal) == len(twin.journal)
+
+
+# -- the service keeps moving between the cut and the retry -----------------
+
+
+def _interleave_world():
+    engine = engine_with(
+        {
+            ("WH-1", "SKU-A"): 3,
+            ("WH-2", "SKU-A"): 4,
+            ("WH-1", "SKU-B"): 8,
+        }
+    )
+    engine.submit("O-hold", "north", "standard", 50, [("SKU-A", 7)])
+    engine.pick("O-hold")
+    engine.submit("O-holdB", "north", "standard", 55, [("SKU-B", 5)])
+    engine.submit("O-rush", "north", "rush", 100, [("SKU-A", 5)])
+    engine.submit("O-std", "north", "standard", 90, [("SKU-A", 4)])
+    return engine
+
+
+def _unrelated_traffic(engine, stamp):
+    # Work on other SKUs and orders: fully covered, plus demand nothing
+    # can serve yet.
+    engine.submit("O-t1", "north", "standard", stamp, [("SKU-B", 2)])
+    engine.pick("O-t1")
+    engine.submit("O-t2", "north", "rush", stamp + 1, [("SKU-C", 2)])
+
+
+@pytest.mark.parametrize("fail_at", [2, 4])
+def test_retry_after_unrelated_operations(fail_at):
+    twin = _interleave_world()
+    twin_outcome = twin.release("O-hold")
+    _unrelated_traffic(twin, 200)
+
+    engine = _interleave_world()
+    engine.journal = FlakyJournal(engine.journal, fail_at)
+    with pytest.raises(StorageInterrupted):
+        engine.release("O-hold")
+    # The service keeps moving before anyone re-invokes the release.
+    _unrelated_traffic(engine, 200)
+    outcome = engine.release("O-hold")
+
+    assert observable_state(engine) == observable_state(twin)
+    assert outcome_tuple(outcome) == outcome_tuple(twin_outcome)
+    assert len(engine.journal) == len(twin.journal)
+    for kind in ("unreserve", "restock", "reserve"):
+        engine_units = sum(
+            m.qty
+            for m in engine.journal.caused_by("release:O-hold")
+            if m.kind == kind
+        )
+        twin_units = sum(
+            m.qty
+            for m in twin.journal.caused_by("release:O-hold")
+            if m.kind == kind
+        )
+        assert engine_units == twin_units, kind
+
+
+def test_retry_after_second_release():
+    twin = _interleave_world()
+    twin_outcome = twin.release("O-hold")
+    twin_outcome_b = twin.release("O-holdB")
+
+    engine = _interleave_world()
+    # Cut during the unwind: the freed stock the second release's
+    # cascade may hand out is genuinely free either way.
+    engine.journal = FlakyJournal(engine.journal, fail_at=2)
+    with pytest.raises(StorageInterrupted):
+        engine.release("O-hold")
+    # A different order is released before ours is re-invoked.
+    outcome_b = engine.release("O-holdB")
+    outcome = engine.release("O-hold")
+
+    assert observable_state(engine) == observable_state(twin)
+    assert outcome_tuple(outcome) == outcome_tuple(twin_outcome)
+    assert outcome_tuple(outcome_b) == outcome_tuple(twin_outcome_b)
+    assert len(engine.journal) == len(twin.journal)
+
+
+# -- metered work ----------------------------------------------------------
+
+
+def test_release_work_is_proportional():
+    config = EngineConfig(
+        warehouses=(
+            WarehouseSpec("WH-1", {"north": 3}),
+            WarehouseSpec("WH-2", {"north": 5}),
+            WarehouseSpec("WH-3", {"north": 8}),
+        ),
+        priority_classes=standard_classes(),
+    )
+    engine = engine_with(
+        {("WH-1", "SKU-A"): 6, ("WH-2", "SKU-A"): 6, ("WH-1", "SKU-B"): 4},
+        config,
+    )
+    engine.submit("O-hold", "north", "standard", 50, [("SKU-A", 12)])
+    engine.pick("O-hold")
+    for i in range(6):
+        engine.submit(
+            "O-w%d" % i, "north", "standard", 100 + i, [("SKU-A", 3)]
+        )
+    engine.submit("O-c", "north", "standard", 110, [("SKU-C", 2)])
+    before = engine.counters.value("allocation_scans")
+    engine.release("O-hold")
+    spent = engine.counters.value("allocation_scans") - before
+    # Four waiting SKU-A entries can be served (12 units at 3 each) and
+    # a fifth is examined; work stays proportional to demand touched,
+    # nowhere near a recompute-the-world sweep.
+    assert spent <= 30
+    # A release with nothing waiting spends nothing.
+    engine2 = engine_with({("WH-1", "SKU-A"): 2})
+    engine2.submit("O-1", "north", "standard", 100, [("SKU-A", 2)])
+    b2 = engine2.counters.value("allocation_scans")
+    engine2.release("O-1")
+    assert engine2.counters.value("allocation_scans") == b2
+
+
+# -- reference model (hidden-side oracle) ----------------------------------
+
+
+_REF_COUNTERS = (
+    "orders_received",
+    "units_reserved",
+    "units_picked",
+    "units_shipped",
+    "units_unreserved",
+    "units_restocked",
+    "backorder_units_created",
+    "backorder_units_served",
+    "orders_released",
+)
+
+
+class ReferenceModel:
+    """Semantics-only twin of the service, on plain dicts."""
+
+    def __init__(self, warehouses, classes, opening):
+        self.warehouses = list(warehouses)  # [(wh, {zone: cost})]
+        self.classes = dict(classes)
+        self.pos = {}
+        for (wh, sku), qty in opening.items():
+            cell = self.pos.setdefault((wh, sku), [0, 0, 0, 0])
+            cell[0] += qty
+        self.queue = []  # dicts: order, sku, qty, rank, stamp
+        self.orders = {}
+        self.counters = {name: 0 for name in _REF_COUNTERS}
+
+    # -- policy ------------------------------------------------------------
+
+    def _eligible(self, zone):
+        out = []
+        for wh, costs in self.warehouses:
+            if zone in costs:
+                out.append((costs[zone], wh))
+        return [wh for _c, wh in sorted(out)]
+
+    def _cell(self, wh, sku):
+        return self.pos.setdefault((wh, sku), [0, 0, 0, 0])
+
+    def _plan(self, sku, qty, zone):
+        remaining = qty
+        sources = []
+        for wh in self._eligible(zone):
+            if remaining <= 0:
+                break
+            available = self.pos.get((wh, sku), (0, 0, 0, 0))[0]
+            take = min(available, remaining)
+            if take > 0:
+                sources.append((wh, take))
+                remaining -= take
+        return sources
+
+    def _reserve(self, order, sku, wh, take):
+        cell = self._cell(wh, sku)
+        cell[0] -= take
+        cell[1] += take
+        order["allocs"].append([sku, wh, take, "reserved"])
+        self.counters["units_reserved"] += take
+
+    # -- operations ----------------------------------------------------------
+
+    def submit(self, order_id, zone, cls, stamp, lines):
+        order = {
+            "id": order_id, "zone": zone, "cls": cls, "stamp": stamp,
+            "lines": list(lines), "allocs": [], "released": False,
+            "outcome": None,
+        }
+        self.orders[order_id] = order
+        self.counters["orders_received"] += 1
+        for sku, qty in lines:
+            covered = 0
+            for wh, take in self._plan(sku, qty, zone):
+                self._reserve(order, sku, wh, take)
+                covered += take
+            if covered < qty:
+                self.queue.append({
+                    "order": order_id, "sku": sku, "qty": qty - covered,
+                    "rank": self.classes[cls], "stamp": stamp,
+                })
+                self.counters["backorder_units_created"] += qty - covered
+
+    def _advance(self, order_id, src, dst, counter, credit):
+        order = self.orders[order_id]
+        moved = 0
+        for alloc in order["allocs"]:
+            if alloc[3] == src:
+                cell = self._cell(alloc[1], alloc[0])
+                cell[{"reserved": 1, "picked": 2}[src]] -= alloc[2]
+                cell[credit] += alloc[2]
+                alloc[3] = dst
+                moved += alloc[2]
+        self.counters[counter] += moved
+        return moved
+
+    def pick(self, order_id):
+        return self._advance(order_id, "reserved", "picked", "units_picked", 2)
+
+    def ship(self, order_id):
+        return self._advance(order_id, "picked", "shipped", "units_shipped", 3)
+
+    def release(self, order_id):
+        order = self.orders[order_id]
+        if order["released"]:
+            return order["outcome"]
+        self.queue = [e for e in self.queue if e["order"] != order_id]
+        unreserved = restocked = 0
+        for alloc in order["allocs"]:
+            if alloc[3] == "reserved":
+                cell = self._cell(alloc[1], alloc[0])
+                cell[1] -= alloc[2]
+                cell[0] += alloc[2]
+                alloc[3] = "released"
+                unreserved += alloc[2]
+                self.counters["units_unreserved"] += alloc[2]
+            elif alloc[3] == "picked":
+                cell = self._cell(alloc[1], alloc[0])
+                cell[2] -= alloc[2]
+                cell[0] += alloc[2]
+                alloc[3] = "released"
+                restocked += alloc[2]
+                self.counters["units_restocked"] += alloc[2]
+        served = 0
+        for entry in sorted(
+            self.queue,
+            key=lambda e: (e["rank"], e["stamp"], e["order"], e["sku"]),
+        ):
+            target = self.orders[entry["order"]]
+            for wh, take in self._plan(
+                entry["sku"], entry["qty"], target["zone"]
+            ):
+                self._reserve(target, entry["sku"], wh, take)
+                entry["qty"] -= take
+                served += take
+        self.queue = [e for e in self.queue if e["qty"] > 0]
+        shipped = sum(a[2] for a in order["allocs"] if a[3] == "shipped")
+        ordered = sum(qty for _sku, qty in order["lines"])
+        allocated = sum(a[2] for a in order["allocs"])
+        outcome = (
+            order_id, unreserved, restocked, ordered - allocated, shipped,
+        )
+        self.counters["backorder_units_served"] += served
+        self.counters["orders_released"] += 1
+        order["outcome"] = outcome
+        order["released"] = True
+        return outcome
+
+    # -- observables ---------------------------------------------------------
+
+    def inventory_rows(self):
+        rows = []
+        for (wh, sku) in sorted(self.pos):
+            cell = self.pos[(wh, sku)]
+            rows.append(
+                "%s %s %d %d %d %d" % (wh, sku, cell[0], cell[1], cell[2], cell[3])
+            )
+        return rows
+
+    def demand_rows(self):
+        ordered = sorted(
+            self.queue,
+            key=lambda e: (e["rank"], e["stamp"], e["order"], e["sku"]),
+        )
+        rows = []
+        for index, entry in enumerate(ordered, start=1):
+            cls = self.orders[entry["order"]]["cls"]
+            rows.append(
+                "%d %s %s %d %s %d"
+                % (index, entry["order"], entry["sku"], entry["qty"],
+                   cls, entry["stamp"])
+            )
+        return rows
+
+    def statuses(self):
+        out = {}
+        for oid, order in sorted(self.orders.items()):
+            if order["released"]:
+                out[oid] = "released"
+                continue
+            stages = {a[3] for a in order["allocs"]}
+            allocated = sum(a[2] for a in order["allocs"])
+            ordered = sum(q for _s, q in order["lines"])
+            if stages == {"shipped"} and allocated == ordered:
+                out[oid] = "shipped"
+            elif "picked" in stages:
+                out[oid] = "picking"
+            elif "reserved" in stages:
+                out[oid] = "allocated"
+            elif "shipped" in stages:
+                out[oid] = "partially_shipped"
+            else:
+                out[oid] = "waiting"
+        return out
+
+
+# -- seeded sweeps ----------------------------------------------------------
+
+
+def _compare(engine, ref):
+    assert reports.inventory_report(engine) == ref.inventory_rows()
+    assert reports.demand_report(engine) == ref.demand_rows()
+    assert counters_sans_scans(engine) == dict(ref.counters)
+    assert {
+        oid: o.status() for oid, o in sorted(engine.orders.items())
+    } == ref.statuses()
+
+
+def _run_world(rng, wh_specs, zones, skus, steps):
+    classes = standard_classes()
+    opening = {}
+    for wh, _costs in wh_specs:
+        for sku in skus:
+            qty = rng.randint(0, 5)
+            if qty:
+                opening[(wh, sku)] = qty
+    config = EngineConfig(
+        warehouses=tuple(
+            WarehouseSpec(wh, dict(costs)) for wh, costs in wh_specs
+        ),
+        priority_classes=classes,
+    )
+    engine = StockEngine(config, opening)
+    ref = ReferenceModel(wh_specs, classes, opening)
+
+    live = []  # order ids not yet released
+    released = []
+    next_id = [0]
+
+    def do_submit():
+        next_id[0] += 1
+        oid = "O-%02d" % next_id[0]
+        zone = rng.choice(zones)
+        cls = rng.choice(sorted(classes))
+        stamp = rng.randint(100, 112)
+        count = rng.choice([1, 1, 2])
+        chosen = rng.sample(skus, count)
+        lines = [(sku, rng.randint(1, 6)) for sku in sorted(chosen)]
+        engine.submit(oid, zone, cls, stamp, lines)
+        ref.submit(oid, zone, cls, stamp, lines)
+        live.append(oid)
+
+    for _ in range(3):
+        do_submit()
+    for _ in range(steps):
+        roll = rng.random()
+        if roll < 0.35 or not live:
+            do_submit()
+        elif roll < 0.55:
+            oid = rng.choice(live)
+            assert engine.pick(oid) == ref.pick(oid)
+        elif roll < 0.65:
+            oid = rng.choice(live)
+            assert engine.ship(oid) == ref.ship(oid)
+        elif roll < 0.9:
+            oid = rng.choice(live)
+            live.remove(oid)
+            released.append(oid)
+            outcome = engine.release(oid)
+            assert outcome_tuple(outcome) == ref.release(oid)
+            _compare(engine, ref)
+        else:
+            if released:
+                oid = rng.choice(released)
+                assert outcome_tuple(engine.release(oid)) == ref.release(oid)
+    _compare(engine, ref)
+
+
+def test_sweep_backorder_heavy():
+    rng = random.Random(20260806)
+    wh_specs = [("WH-1", {"north": 3}), ("WH-2", {"north": 5})]
+    for _ in range(10):
+        _run_world(rng, wh_specs, ["north"], ["SKU-A", "SKU-B"], 16)
+
+
+def test_sweep_split_multiwarehouse():
+    rng = random.Random(4180)
+    wh_specs = [
+        ("WH-1", {"north": 3, "south": 7}),
+        ("WH-2", {"north": 5, "south": 2}),
+        ("WH-3", {"north": 4}),
+    ]
+    for _ in range(10):
+        _run_world(
+            rng,
+            wh_specs,
+            ["north", "south"],
+            ["SKU-A", "SKU-B", "SKU-C", "SKU-D"],
+            18,
+        )
+
+
+def test_sweep_priority_churn():
+    rng = random.Random(90210)
+    wh_specs = [
+        ("WH-1", {"east": 2, "west": 6}),
+        ("WH-2", {"east": 2, "west": 3}),
+    ]
+    for _ in range(12):
+        _run_world(rng, wh_specs, ["east", "west"], ["SKU-A", "SKU-B"], 20)