0040. BinStockLevelChanged — absolute per-(bin, sku) levels from the ledger's own transaction
Status
Accepted (2026-10-17). Producer side of the pick-face replenishment design (consumer first:
pick-face-replenishment is already merged and decodes this contract). Extends the type
catalogue of ADR 0024 with one type. Builds on
ADR 0017 (outbox), ADR 0019
(version columns), ADR 0021 (partition key) and
ADR 0039 (the sibling StockRelocated).
Context
pick-face-replenishment must notice that a forward pick slot has fallen below its minimum. It
needs the stock level of one SKU in one bin, and this service is the only authority for it. Until
now nothing on warehouse.inventory.events carried a bin level:
StockPickedis analytics-only and names no bin.StockRelocatedreports a move, not what is left in either bin.StockReserved/ReservationRevokedcarry a SKU and a quantity, not where.
A consumer cannot rebuild a level from those deltas without owning a second ledger, and a delta feed breaks on the first lost or duplicated message. The contract therefore ships the level itself, with enough ordering information to survive at-least-once delivery.
Decision
-
Event.
com.warehouse.wms.inventory-storage.stock.BinStockLevelChangedonwarehouse.inventory.events, CloudEvents 1.0 through the outbox,dataschemaurn:warehouse:inventory-storage:events:BinStockLevelChanged:v1. Kafka key = CloudEventssubject=<bin>:<sku>, so every level of one pair stays on one partition in version order. Integration topic only; the analytics data product does not carry it (same asStockRelocated).data:site_code,bin,sku,on_hand,reserved,version,reason,occurred_at(snake_case, all always present). The field names and types are the ones the consumer decodes. -
Absolute levels, never deltas. After the change, for the (bin, sku):
on_hand= the sum ofquantityover the SKU's located, still-present units in the bin: every state exceptUNLOCATED(a cycle count lost track of it) andREMOVED(quantity zero, fully picked out).reserved= the sum ofreservedover the same units, i.e. the part ofon_handbound by active reservations (a reservation's allocation names a unit and its bin, migration 0008).on_hand - reservedis what a new reservation could still draw from the bin.
-
Persisted per-(bin, sku) version. Migration
0037_bin_sku_levels(additive, with a tested down) addsbin_sku_levels (bin_id, sku, version, updated_at), primary key(bin_id, sku), plus the indexstock_units (bin_id, sku)the level read uses. Every event bumps the row with one upsert (INSERT ... ON CONFLICT DO UPDATE SET version = version + 1) and carries the value it returned: 1 for the first event of a pair, strictly increasing after that, surviving restarts. A consumer keeps the highest version it has seen and ignores lower ones. -
Same transaction, row lock first. The use case that moves the ledger tracks the (bin, sku) pairs it changed; just before the unit of work commits, the emitter (
usecases.BinLevelEmitter) advances each pair and publishes the event through the existingEventPublisher(the outbox publisher / multi publisher; there is no second publish path). The order insideports.BinLevelLedger.Advanceis what makes it race-safe: the version upsert takes the(bin, sku)row lock first, the levels are read after it (a new READ COMMITTED statement, so it sees every change committed before the lock was granted plus the transaction's own writes), and the lock is held until commit. N concurrent changes of one pair therefore produce versions 1..N in commit order, each event carrying the level as of its own commit; a rolled-back change rolls its bump back, so versions have no gaps and the event exists if and only if the ledger change committed. Pairs are advanced in sorted order, so two transactions touching the same pairs lock the version rows alike (no deadlock). -
One event per distinct (bin, sku) per transaction, with the final level. The emitter brackets the outermost unit of work (
BinLevelEmitter.Atomically, a drop-in for theatomicallyhelper); nested brackets defer to it. An order whose lines are picked in oneConfirmPicksForOrdertransaction, or a reservation drawn from two units of one bin, raises one event per (bin, sku) carrying the level after the whole transaction. If several causes touch one pair in a transaction the last reason wins. Events are published in the order pairs were first tracked, so a relocation raises the source bin first, then the destination. -
Nothing is raised when the level did not change. Rejected commands fail before any pair is tracked; idempotent replays (
ReserveStockreplay, a replayed transfer allocation or stow, a redelivered CloudEvent) return before the ledger is touched; a cycle count that matches or finds an overage moves no ledger level. -
A bin with no determinable site raises nothing.
site_codeis mandatory and a consumer cannot place a level without it. The site is the bin'sEffectiveSite(recorded custody, else the site segment of a facility-layout location code, ADR 0039). A bin that is not registered, or whose id is not a location code and has no recorded custody, consumes no version and emits no event. Production bins are location codes. -
Reasons (
reason):STOW,PICK,RELOCATE,REPLENISHMENT,COUNT,RESERVE,REVOKE,UNLOCATED. Consumers ignore values they do not know.REPLENISHMENTis the reason of a relocation made by a completed REPLENISH task (ADR 0041): a relocation maps to it when its own reason isREPLENISHMENT(relocationLevelReason). Originally reserved for that change, it is emitted since ADR 0041, source bin first, then destination.UNLOCATEDis in the closed set for an unlocated receive that names a bin. This service has no such path (ReceiveStockand the inbound-receiving booking name no bin), so it is never emitted; the cycle-count shortfall isCOUNT.
What emits, by use case
| use case | trigger | reason | bins touched |
|---|---|---|---|
StowStock | POST /stowages | STOW | the target bin |
StowTransferStock | POST /transfers/{transferLineId}/stowages | STOW | every leg's bin |
ReserveStock | POST /reservations (new reservation only) | RESERVE | every bin the allocation draws from |
AllocateTransferStock | TransferAllocationRequested (ALLOCATED only) | RESERVE | every bin drawn from |
RevokeReservation | DELETE /reservations/{id}, MCP revoke | REVOKE | every allocation's bin |
| lazy reservation expiry | any read that resolves a timed-out reservation (ReserveStock's replay lookup, GetReservationsByDemandRef, ConfirmPick, RevokeReservation, ConfirmPicksForOrder) | REVOKE | every allocation's bin |
ConfirmPick / ConfirmPicksForOrder | POST /reservations/{id}/pick-confirmations, TaskCompleted PICK | PICK | every allocation's bin |
RelocateStock / ApplyRelocationTask / ApplyReplenishTask | POST /relocations, TaskCompleted RELOCATE, TaskCompleted REPLENISH | RELOCATE (REPLENISHMENT for a REPLENISH task) | source bin, then destination bin |
RunCycleCount | POST /bins/{binId}/cycle-counts, shortfall only | COUNT | the counted bin, one event per SKU whose units were marked unlocated |
ReceiveStock, BookInboundReceiptLine | receive | none | staged stock has no bin |
StageTransferReceipt | destination scan | none | no ledger change (the stow raises it) |
RegisterBin | PUT /bins/{id} | none | no stock moves |
Consequences
- pick-face-replenishment gets a gap-tolerant, replay-tolerant level feed: it applies an event
only if
versionis higher than the stored one, so redelivery and reordering across partitions cannot corrupt its read model. - Every stock-moving use case gains one
Levelscollaborator and aTrackcall after each write; a nil emitter keeps the previous behaviour, which is how tests and the in-memory configuration run. The emitter adds, per changed pair, one upsert, one SUM and one outbox row to a transaction that already writes the ledger. - Cost on the hot path: the
(bin, sku)version row is a serialisation point for concurrent changes of the same pair (not for different pairs). Changes of one pair already contend on the bin row for stow, pick and relocation (ADR 0019), so this adds no new contention for those; reserve and revoke, which touch only units, now also queue per pair. - Every produced level is the ledger's level at commit time, but it is not a snapshot of the world: a consumer must not compare levels of different pairs as if simultaneous.
- No bootstrap/backfill: a pair that has not changed since this ships has no event yet, so a consumer starts empty and learns each pair at its next change. A sweep that re-emits every pair is a follow-up if the consumer needs one.
LocationRecordedandItemStowedare untouched;StockRelocatedkeeps its payload and description. No REST endpoint is added or changed.