Karyo
Documentation/ What Karyo does in a warehouse

Stocktaking

Karyo 2.1.1rendered at build time
On this page

Counting is a four-level hierarchy: an optional CountCampaign groups CountSessions, each session generates one CountOrder per location, and each order holds one CountLine per stock unit found there at generation time, plus one per batch of found stock the counter records.

Two count types, one rule

CountType is CYCLE or END_OF_PERIOD (services/stocktaking-service/karyo-stocktaking-api/.../vo/CountType.kt, CountType). The class KDoc states the split precisely (.../service/StocktakingService.kt, StocktakingService):

  • CYCLE counts a caller-selected scope and refuses the whole start if any location in it holds reserved stock or is already locked - "the operator is expected to have picked a countable set".
  • END_OF_PERIOD counts every location of the Facility, empty ones included, and skips an uncountable location, reporting it in skippedLocations - "because one reservation must not be able to veto an annual inventory".

The rule is the same either way - a location that cannot be counted is not counted - and only the remedy differs. A location of another Facility is never in scope.

The scope strategy is always resolved by name: EXPLICIT (or the caller's scopeStrategy) for a cycle count, forced to FULL_WAREHOUSE for an end-of-period one. Never unnamed, because FullWarehouseScope outranks ExplicitLocationScope on priority and an unnamed resolve "would silently escalate every plain cycle count into a warehouse-wide freeze" (StocktakingService.startCount). That is a nice example of a priority-ordered SPI being a trap when one implementation is strictly larger than another.

What "freeze" means

There is no separate freeze switch. The freeze is the per-location STOCKTAKING lock plus the per-stock-unit lock that every generated order takes on unlocked stock at start and releases at finishOrder/cancelOrder (StocktakingService). A full inventory is frozen for exactly as long as its orders are open, location by location, and a skipped location is never frozen at all.

That guarantee is enforced rather than asserted, and the mechanism is worth understanding: LocationService.lockLocation overwrites a lock unconditionally, so a second session generated for an already-frozen location would have released the first session's freeze the moment it finished - a silent thaw mid-inventory plus a double count. startCount therefore snapshots the pre-existing locks before taking any of its own (StocktakingService.startCount) and refuses (CYCLE) or skips (END_OF_PERIOD) on that snapshot.

The count's own locks never replace or lift a hold it did not place (DefaultStockCountingPort.lockForCount/releaseCount, DefaultLocationLockPort). A stock unit that is already locked - a QUALITY_FAULT hold, a lot block such as LOT_EXPIRED - keeps its own lock through the count instead of taking STOCKTAKING, so it is unavailable throughout; release clears only STOCKTAKING, so a hold placed on the stock or the location while the order is open survives finishOrder, cancelOrder and recount. Counting held stock still applies its counted amount on accept.

The reserved-stock guard lives in generateOrderForLocation rather than in the callers "so it can never be skipped by accident: the END_OF_PERIOD path simply never reaches it, having filtered those locations out first" (StocktakingService.generateOrderForLocation).

END_OF_PERIOD is "a real, lockable, closable session" (StocktakingService): it freezes what it counts and it closes out.

Walking order

Locations are re-sorted orderIndex NULLS LAST, name immediately after the scope resolves, before any order is generated, so their created timestamps land in walking order (StocktakingService.startCount).

The ordering guarantee is then entirely a dispatch-time property: CountOrderRepository's claimable query carries no ORDER BY, and StrictPriorityDispatchStrategy's createdAt ASC tiebreak re-sorts the merged pool in memory. Since every generated count order carries the same priority, that tiebreak is the whole ordering for a count-only pool (StocktakingService.startCount).

The limit is stated honestly at the same site (StocktakingService.startCount): created ASC preserves walking order only within one startCount batch. The pool an operator pulls from merges every open order across every session in the Facility, so two overlapping sessions interleave by created in a way that no longer walks the floor. TravelPathDispatchStrategy is the opt-in seam that re-derives it at dispatch time - see work allocation.

The scale ceiling

startCount is one @Transactional call: N location reads, N order inserts, one line insert per stock unit, in a single transaction that also holds the write locks. The KDoc states the bound rather than hiding it (StocktakingService):

At the scale this targets (a demo warehouse is ~40 locations; a real single-site WMS is hundreds) that is fine. It is NOT batched or chunked, so a warehouse in the tens of thousands of locations would need that work - deliberately not built ahead of a caller (YAGNI), not overlooked.

Counting

submitCount(orderId, inputs) (StocktakingService.submitCount) requires the order in GENERATED, then:

  • A zero-line order is refused. Without the refusal it would fall through as a silent no-op auto-finish: an empty line list trivially satisfies every loop, allMatched stays true, and the order finishes with no operator intent recorded anywhere. The refusal points at the sanctioned confirm-empty operation instead (StocktakingService.submitCount).
  • An input for a line that is already off PLANNED is refused, not discarded. The floor PWA submits an amount for every entry line with no notion of "already counted", so without this a real count would vanish underneath a web-triggered zero and accept would delete stock that was actually there (StocktakingService.submitCount).
  • Each PLANNED line takes its input and becomes COUNTED. A line whose counted amount equals its planned amount is journalled COUNTED and moves straight to FINISHED; anything else stays COUNTED, flagged for review.
  • The order advances to COUNTED, and if every line matched, finishOrder runs immediately - releasing every lock and possibly closing the session.

Two operator escapes exist, both zeroing lines without finishing the order:

  • unitLoadMissing (StocktakingService.unitLoadMissing) - every still-PLANNED line for that unit load is counted at zero and moved to COUNTED, and the order state is deliberately left unchanged so the operator can keep counting the rest of the location. Idempotent on lines already off PLANNED, but a 422 invalid-reference if the unit load never had a line on this order - "that's the 'not on this order' case the caller actually needs surfaced, as opposed to 'already handled'".
  • locationEmpty (StocktakingService.locationEmpty) - a zero-line order finishes directly; an order with lines zeroes them all and goes to COUNTED for review, "a discrepancy this large still needs accept". On the zero-line branch there is deliberately no journal call, because every journal row is written against a stock unit and there is none - the finished order plus the stamped lastCountedAt "are the audit trail for this confirmation, honestly, not a gap being papered over" (StocktakingService.locationEmpty).

Review

accept (StocktakingService.accept) requires COUNTED, applies StockCountingPort.applyCount for every still-COUNTED (i.e. discrepant) line, marks them FINISHED, and finishes the order. Lines that matched exactly during submit are untouched.

applyCount (.../inventory/service/DefaultStockCountingPort.kt, DefaultStockCountingPort.applyCount) adjusts the amount, journals COUNTED, and - when the counted amount is zero - soft-deletes the stock and trashes the unit load if it is now empty. That trash is what releases the location's allocation, via UnitLoadTrashedEvent and layout's observer (DefaultStockCountingPort.applyCount).

recount (StocktakingService.recount) cancels the current order, releasing every lock, and regenerates a fresh GENERATED order for the same location under the same session. No inventory adjustment is made. The session is deliberately not close-checked, "since a fresh non-terminal order is generated in the same breath".

cancelOrder (StocktakingService.cancelOrder) is the same thing without the replacement - and deliberately does not call markCounted, because nothing was counted there.

Found stock

Planned CountLine rows come only from the location snapshot: DefaultStockCountingPort.findStockAtLocation walks the unit loads at the location and emits one CountableStock per non-DELETABLE stock unit. Stock the snapshot did not hold - a pallet nobody booked, an item no line covers - is found stock, recorded on the count itself so the surplus stays linked to the count that found it (FoundStockService, GitHub #42).

Record. POST /count-orders/{id}/found-stock (inventory.write, order GENERATED) names the product, the amount and optionally the lot, serial and unit-load label. The stock is booked at once by StockCountingPort.recordFoundStock: ON_STOCK, on a load already at the location or a new one there, and under the QUALITY_FAULT stock hold that receiving puts on returns. Allocation refuses any locked stock (StockUnitRepository.findForSelection), so found stock is never allocated while it waits. A label that names a load elsewhere is refused (400): the stock is physically here, and reusing the label would move another pallet's record. The order gains a found CountLine (found = true, planned 0, counted the found amount, state COUNTED). A new load is announced at the location, so its allocation is charged.

Review. A found line never matches its planned 0, so the submitted order always goes to COUNTED. A holder of counts.approve decides each found line on its own, but never the person who recorded it: the line keeps the recorder (found_by, found_by_principal_id), and a decision by that person is refused (403 count-decision-refused). The principal id decides when both sides have one, otherwise the username does.

  • .../found-stock/{lineId}/approve lifts the hold and journals COUNTED; the line FINISHES.
  • .../found-stock/{lineId}/reject soft-deletes the stock, trashes a load it leaves empty (which releases the allocation), and the line is CANCELLED. Reserved stock is refused, as unreceive refuses it.

accept refuses (409) while any found line is undecided, so a count never finishes with stock nobody confirmed. locationEmpty refuses an order that holds found stock, because the location is not empty. recount and cancelOrder remove undecided found stock: a count nobody accepted confirms nothing, and the recount would find the stock again. finishOrder and the cancel path never release a found line's stock with the count's own lock release, because that would lift the hold.

Journal. Every write is journalled against the stock unit under the count's activity code, extended for found stock (foundStockActivity): ST <order> FOUND for the CREATED and hold rows, then FOUND APPROVED, FOUND REJECTED or FOUND CANCELLED.

The hold ends only with the decision. The hold is the ordinary stock lock, but while the find is undecided inventory refuses to release it by hand (409 found-stock-pending, naming the count order): both the stock-unit lock endpoint and the unit-load unlock cascade ask PendingFoundStockLookup, declared in inventory and implemented here, before they clear a stock lock. The open found line is the marker, so the stock needs no state of its own. Placing a different hold is not a release and stays allowed. Once the line is decided, the stock's locks are ordinary again.