Karyo
Documentation/ What Karyo does in a warehouse

Allocation and reservation

Karyo 2.1.1rendered at build time
On this page

Allocation is where a promise to a customer becomes a claim on a specific pallet. It is one algorithm, StockSelectionService, wrapped by one bookkeeping layer, DefaultStockReserver, and reached from four places: delivery-order release, the PENDING retry, short-pick recovery, and wave release by the optional wave engine.

The order side

OrderService.release (services/order-service/karyo-orders-core/.../service/OrderService.kt, OrderService.release) is the entry point. It requires state CREATED, runs every OrderReleaseValidator extension, transitions the order to RELEASED, then reserves per line.

Each line ends PROCESSABLE if shortage is zero, PENDING otherwise (OrderService.release). The order is promoted to PROCESSABLE only when every line is (OrderService.promoteIfFullyReserved). A shortfall is therefore an ordinary, first-class outcome: the order sits at RELEASED with a shortage report in the response, not an error.

retryReservation (OrderService.retryReservation) is the sanctioned backward hop. OrderState.canAdvanceTo has one non-forward rule, PENDING → PROCESSABLE/RESERVED (karyo-orders-api/.../vo/OrderState.kt, OrderState.canAdvanceTo), and this is the method that uses it: re-reserve only the PENDING lines, promote if that clears the last one.

Each reserved slice is recorded as an OrderLineReservation row keyed (lineId, stockUnitId) (OrderService.reserveLine). That ledger is what makes cancellation safe - see Cancelling an order.

The strategy

Every knob the selector honours comes from an OrderStrategy (.../domain/model/OrderStrategy.kt): useLockedStock, preferComplete (default true), preferMatching, completeHandling, enforceLot, plus the downstream picking and packing flags. Resolution is a chain of OrderStrategyResolver beans by ascending priority, first non-null name wins, falling back to the seeded DEFAULT (OrderStrategyService.resolve).

OrderStrategy is instance-wide, not per goods owner. It extends BaseEntity, not TenantEntity, its name is globally unique, and OrderStrategyRepository.findByName takes no businessUnitId (OrderStrategy.name, OrderStrategyRepository). The entity KDoc gives the reason: "no clientId - silo tenancy makes the company implicit".

That reason is true and incomplete. In a silo the company is implicit, but the goods owner is not - businessUnitId is the goods owner, and the same instance keeps StorageStrategy, FixAssignment and ItemDataArea per Facility and fails closed on a foreign one (putaway). So one silo hosting several goods owners gives them all one set of allocation, short-pick and packout rules, editable by anyone holding the orders.write action (.../api/v1/OrderStrategyResource.kt, OrderStrategyResource) - an operational action that the standard receiver, operator, manager, administrator and integrator profiles all hold, not an administration one. Why OrderStrategy is scoped differently from StorageStrategy is not recorded beyond that KDoc line.

The selector

StockSelectionService.selectStock (services/inventory-service/karyo-inventory-core/.../service/StockSelectionService.kt, StockSelectionService.selectStock) is the algorithm. What follows is its shape and its edges.

Hard exclusions

Before anything else, an inactive product returns an empty result outright (StockSelectionService.selectStock) - the projection is maintained by a product-event observer rather than a cross-module call at selection time.

Every candidate query then filters state = 300 and amount > reservedAmount, plus lockType = 0 and unitLoad.lockType = 0 unless locked stock was explicitly requested (StockUnitRepository.findForSelection). There is no area or location predicate; see stock model.

FIFO

Within every pass: strategyDate asc, amount asc, created asc, id asc (StockUnitRepository.findForSelection). strategyDate is set from bestBefore at receipt, so FIFO is really FEFO where a best-before exists and creation order where it does not. This remains the exact default. An order strategy may opt into same-day nearest source selection while the Facility enables proximity; older rotation days still win.

Two pre-passes, then thirteen

  1. preferMatching - the first eligible unlocked unit whose available amount exactly equals the demand wins. Skipped when completeHandling is active, because the complete-only contract is the stronger constraint (StockSelectionService.selectStock). Locked stock is never admitted here, "preferMatching is a preference, never an override of the lock safety fence" (StockSelectionService.exactMatchCandidate).
  2. completeHandling - any non-NONE mode searches strict complete unit loads and then returns, never falling through to the partial passes (StockSelectionService.selectStock). Complete-or-nothing.
  3. Otherwise, up to thirteen baseline passes accumulating min(available, remaining) from each survivor until the demand is covered.

CompleteHandling has six modes (karyo-inventory-api/.../vo/CompleteHandling.kt, CompleteHandling): NONE, first-exact, first-at-or-above, and three combinatorial modes solved by a bounded DFS Optimizer capped at a candidate count and a node count, with both truncations logged so a suboptimal answer is observable rather than silent (.../service/Optimizer.kt, Optimizer.findBestCombination).

"Strict complete" means unopened, wholly unreserved, single-stock, and a unit-load type that permits COMPLETE usage (StockSelectionService.isStrictComplete). It does not check that the unit load sits in a storage area or off a fixed location (StockSelectionService.isStrictComplete). Proximity can rank sources, but it adds no location eligibility rule.

The thirteen passes are at most four queries

getCandidatesForPass (StockSelectionService.getCandidatesForPass) varies exactly two things: whether locked stock is included (passes 10-11) and whether the lot filter applies (passes 1, 3, 6, 8, 10, 12). Passes 3-5 repeat 1-2, passes 8-9 repeat 6-7, and passes 12-13 repeat 6-7. Passes 1 and 6 send the same query too: the availableAmount >= request.amount coverage filter of passes 1-5 runs in Kotlin, after the read. So findForSelection sees at most four distinct queries, which are (includeLocked, lot) of (false, lot), (false, any), (true, lot) and (true, any). Why the loop runs thirteen passes over them is not recorded.

The KDoc of getCandidatesForPass says the same: its pass map names each repeated pass "same as" the earlier one (StockSelectionService.getCandidatesForPass). A repeated pass changes the outcome only because the loop's skips depend on what is still needed: a fix slot whose pick ceiling is below the demand at one pass can be offered again once earlier picks have reduced it.

A selection reads each distinct query once per call, and every pass, the exact-match step and the complete-handling step share the rows (StockSelectionService.CandidateReads). A selection changes no stock, so a second read could only return the same rows. A short pick with default settings reads one query, where it used to read it eleven times; four is the most any request reads. StockSelectionQueryCountTest counts the reads and pins each scenario's outcome to what the pass-by-pass implementation returned.

Lot is a preference, not a rule

Lot-filtered and any-lot passes alternate, so if the requested lot cannot satisfy the demand, selection crosses into other lots. enforceLot = true with a supplied lot skips every any-lot pass and returns short instead (StockSelectionService.getCandidatesForPass).

The order of the passes produces a result that surprises people. Ask for 50 of lot LOT-7 with the defaults (preferComplete on) against three units, oldest first: S4, LOT-7, 30 available; S5, LOT-9, 100 available; S6, LOT-7, 10 available. Pass 1 looks for a complete-coverage candidate in LOT-7 and finds none; pass 2 looks for complete coverage in any lot and takes all 50 from S5. The requested lot is bypassed entirely even though 40 units of LOT-7 sit on the shelf, because complete-coverage preference outranks lot preference in pass order. With preferComplete off, the partial LOT-7 pass takes S4 and S6 first and S5 covers only the remaining 10; with enforceLot on, the response stays short at 40.

Note also that completeHandling applies the supplied lot to its single strict query and never falls back to another lot regardless of enforceLot - so the two flags interact differently depending on which path runs (StockSelectionService.selectStock).

The fixed-slot ceiling

A FixAssignment may carry a maxPickAmount. When one exists for this product at a candidate's location and it is less than what is still needed for the whole request, the slot is skipped for that pass (StockSelectionService.exceedsFixCeiling). It is not permanently excluded: a later pass may re-offer it once other picks have shrunk the remainder to or below the ceiling.

The comparison is deliberately against the outstanding request, not against the per-unit take, and the reasoning is recorded at the site (StockSelectionService.exceedsFixCeiling). The ceiling applies at all three entry points - the baseline loop, preferMatching and completeHandling (StockSelectionService.fixPickCeilingsFor, StockSelectionService.exactMatchCandidate, StockSelectionService.selectCompleteHandling).

excludeStockUnitIds holds at every entry point

excludeStockUnitIds names stock units that selection must never offer. Selection drops them from the candidate list before the StockSelectionFilter chain runs, at all three entry points: the baseline passes (StockSelectionService.getCandidatesForPass), preferMatching (StockSelectionService.exactMatchCandidate) and completeHandling (StockSelectionService.selectCompleteHandling), through one helper (StockSelectionService.withoutExcluded). The filter chain therefore never sees an excluded id and cannot re-admit one.

Removing candidates reduces each mode to its existing "no candidate" result. preferMatching finds no exact match and falls through to the baseline passes. completeHandling returns nothing and still never falls through to the partial passes. The list is empty for every reservation except a short-pick follow-up, so everything else selects exactly as before.

The one production caller is short-pick recovery. PickOrderService.coverWithFollowUps passes the just-short source in excludeStockUnitIds together with the strategy's preferMatching and completeHandling (.../fulfillment/service/PickOrderService.kt, PickOrderService.coverWithFollowUps). A follow-up therefore never re-selects the unit that just came up short, whichever strategy flags are on. Without that, the short unit's remaining amount is exactly the follow-up's demand and would be the strongest match under either flag.

Holding a reservation

DefaultStockReserver.reserve (.../inventory/service/DefaultStockReserver.kt) runs selection, then walks the result calling StockService.reserveStock per unit, accumulating ReservedStock slices and returning whatever it could not cover as shortfall.

reserveStock (StockService.reserveStock) refuses a locked unit and refuses when availableAmount < amount, journals a CHANGED row with the delta, and publishes a RESERVE amount event. A unit that has become unreservable between selection and reservation is caught, logged and skipped, "and let the remainder surface as shortfall" (DefaultStockReserver.reserve).

Release refuses to release more than is actually reserved, rather than clamping to zero, and the reason is recorded at the site (StockService.releaseReservation): a silent clamp would let a caller's over-release walk reservedAmount past zero and consume another party's live reservation on the same stock unit without any signal - a delivery-order cancel silently stealing another order's reservation, for example. Refusing also keeps the journal truthful: the amount it records is always the amount applied.

Every StockReserver call names the Facility it acts in and reads no ambient scope. The targeted single-unit calls (reserveOnStockUnit, and the single-slice release) distinguish a foreign stock unit from a missing one: a unit that exists but sits in another Facility throws Forbidden rather than being folded into "not found", so a caller bug (wrong Facility) fails loudly instead of leaking as a permanent reservedAmount drift (DefaultStockReserver.reserveOnStockUnit, DefaultStockReserver.release, DefaultStockReserver.requireInFacility).

What happens when two orders race

There is no pessimistic lock on StockUnit. Two transactions can both read the same unit with availableAmount = 10, both pass the sufficiency check, and both write. @Version on BaseEntity means only one commits; the other fails the version check at flush.

reserve catches InventoryException only, and the version check fails at the commit of the whole request, after reserve has returned. The losing transaction rolls back whole, so stock is never double-booked and nothing of the losing request is applied.

The caller of a synchronous release (POST /api/v1/delivery-orders/{id}/release) receives a 409 concurrent-change problem: UnhandledExceptionMapper finds the OptimisticLockException in the commit failure's cause chain (The error contract, section 4). A retry is safe, and it meets the ordinary outcome: a shortfall when the winner took the last units. Nothing retries the request on the caller's behalf. Order streaming does not reach the mapper: it recognises the same failure itself and takes the order up again on a later tick (StreamingService.isRace).

Known limit. The outcome the API models for "you cannot have all of it" is ReservationOutcome.shortfall; a lost race is a 409 the caller must retry instead.

Cancelling an order

OrderService.cancel (OrderService.cancel, OrderService.releaseLineReservations) is the most carefully ordered method in the module, and the ordering is load-bearing:

  1. Cascade first. Cancel is legal up to PENDING(550), which includes a STARTED(500) order already released to picking, so PickCancelPort force-finishes the still-open pick work - otherwise the pick order stays claimable and its picks stay confirmable against a reservation this method is about to give away.
  2. Then release only the unhandled remainders: each recorded OrderLineReservation slice minus what terminal picks on that same (line, stock unit) already consumed or released, floored at zero (OrderService.unhandledRemainders).

JPA auto-flushes before the terminal-slice query, so the picks cancelled in step 1 are already terminal - and thus already netted out - in step 2 (OrderService.cancel). Releasing the full recorded slice instead would double-release, which is the defect the refusal in releaseReservation also guards against independently.