Karyo
Documentation/ What Karyo does in a warehouse

Replenishment

Karyo 2.1.1rendered at build time
On this page

Replenishment moves stock from reserve into a location that is running low. Karyo has two independent modes with disjoint provenance and disjoint duplicate guards, both driven from one scan.

The two modes

Mode 1 - fix face. A FixAssignment binds one product to one location with minAmount, maxAmount and desiredAmount. When on-hand falls below minAmount, a REPLENISH transport order is raised to top it up.

Mode 2 - area. An ItemDataArea binds one product to a StorageArea with plannedAmount and plannedStocks targets across the area's whole cluster set. When either target is missed, one order is raised to bring stock into the area.

Both mint TransportType.REPLENISH with the RP order-number prefix. They are told apart by which provenance column is set: fixAssignmentId for Mode 1, itemDataAreaId for Mode 2 (services/task-service/karyo-tasks-core/.../service/TaskService.kt, TaskService.createAreaReplenishment). Reusing the enum value was deliberate - no new TransportType, so every existing filter keeps working unchanged.

The scan

ReplenishmentService.scan(facility) (services/replenishment-service/karyo-replenishment-core/.../service/ReplenishmentService.kt, ReplenishmentService.scan) runs Mode 1 over every fix assignment, then Mode 2 over every item-data area. The ordering between them is arbitrary and the code says so - the modes are independent, and fix-face first "simply matches this method's pre-existing shape". scan takes the Facility to scan and names it on every layout and transport-order call. The scheduler fans out per Facility, and the on-demand endpoint scans the Facility of the request (ADR 0045).

One thing is shared across the whole scan: claimedUnitLoadIds, seeded from every open REPLENISH order's source unit load and grown with each newly minted order, so two deficiencies found in the same scan can never claim the same pallet (ReplenishmentService.scan). Each query snapshots the set with .toSet() rather than passing the live mutable reference, because the set keeps growing for later assignments (ReplenishmentService.processFixAssignment).

Mode 1: what triggers

processFixAssignment (ReplenishmentService.processFixAssignment) has four skip conditions, each an early return.

A null currentAmount is skipped, never treated as zero. The field is nullable precisely to distinguish "the stock read failed" from "there is genuinely none", and both the scan and the read-only needs view exclude it rather than fabricating a belowMin (ReplenishmentService.processFixAssignment, ReplenishmentService.needs; karyo-layout-api/.../spi/FixAssignmentLookup.kt, FixAssignmentLookup).

The trigger itself is a ReplenishmentStrategy. The built-in:

override val name: String = "MIN_MAX"
override fun needsReplenishment(currentAmount, minAmount, maxAmount, desiredAmount) =
    minAmount != null && currentAmount < minAmount

.../service/DefaultReplenishmentStrategy.kt, DefaultReplenishmentStrategy

Known defect. It is named MIN_MAX but the trigger reads only minAmount. maxAmount and desiredAmount are passed in and ignored by it; a different method reads them later, to size the top-up. A face with no minAmount configured is therefore never replenished at all, whatever its other thresholds say.

An existing open REPLENISH order for the same assignment suppresses a second one (hasOpenReplenishment, ReplenishmentService.processFixAssignment).

What counts as on-hand

FixAssignmentView.currentAmount is the ON_STOCK-only on-hand at the face. The area-mode equivalent, StockSummaryLookup.summaryInLocations, is stricter still - it additionally requires lockType = 0, unitLoad.lockType = 0 and reservedAmount = 0 (.../inventory/repository/StockUnitRepository.kt, StockUnitRepository.summaryInLocations), and the KDoc records reservedAmount = 0 as a deliberate planning-strictness addition.

The pallet lock is filtered the same way selection reads it (stock model): stock that landed on an already-locked pallet keeps its own lockType = 0 but cannot be picked, so it does not count towards the area's on-hand, and the area is replenished as if that stock were absent.

Source selection

DefaultReplenishmentSourceSelector.selectSource (.../inventory/service/DefaultReplenishmentSourceSelector.kt, DefaultReplenishmentSourceSelector.selectSource) starts from the same findForSelection query allocation uses - ON_STOCK, unlocked stock and unlocked pallet, amount > reservedAmount, FIFO-ordered - then applies five filters and a two-tier preference. It is read-only: no reservation, no state change.

The filters exclude: the target location itself; any excluded location set (Mode 2 passes the whole destination area); any unit load already claimed in this scan; picking-usage locations unless fromPicking is on; and anything failing the strictness rule.

Strictness depends on the destination, not on the candidate (DefaultReplenishmentSourceSelector.meetsStrictness):

  • replenishing a picking face - a candidate that is itself on a picking location may use the base query's loose amount > reservedAmount; everything else must be strict;
  • replenishing a storage face - every candidate must be strict, whatever its own location.

"Strict" means reservedAmount = 0 and a non-mixed unit load, where non-mixed is "exactly one live stock row". That definition is deliberately shared with ConfirmVariantService.singleLiveStockOrThrow "so the codebase has one 'is this unit-load safe to move as a single thing' definition, not two" (DefaultReplenishmentSourceSelector.isNonMixedUnitLoad).

Lot is a preference, not a filter. If the face already holds lots, matching candidates are preferred; if none match, the full pool is used (DefaultReplenishmentSourceSelector.preferredPool). Same posture as allocation.

Two tiers. Phase A is a fix-assigned location that is not itself a picking location; Phase B is everything else. The pool is already FIFO-ordered, so firstOrNull on each partition is FIFO-first of that phase (DefaultReplenishmentSourceSelector.firstOfTier).

The exclusion of picking locations from Phase A is not cosmetic. A normal pick face is a fix assignment, so fixFaceLocationIds contains other pick faces. Without the exclusion, once fromPicking is on, a candidate on another pick face would rank top-priority "and this selector would rob one pick face to feed another" (DefaultReplenishmentSourceSelector.firstOfTier). Phase A is reserved for fixed reserve or bulk slots.

Mode 2 deliberately reuses the same reserve-first tiering, treating fix-assigned reserve slots as the designated refill source, rather than ordering its sources by the storage strategy's cluster set (DefaultReplenishmentSourceSelector.firstOfTier).

No source is a NO_SOURCE shortfall on the scan result - not an error, not a retry.

How much moves

topUpAmount (ReplenishmentService.topUpAmount) sizes the move:

desired = desiredAmount, kept only when minAmount <= desired <= maxAmount (a bound that is not set does not limit it)
target = desired ?: maxAmount
target == null               -> null   (whole-UL move)
deficit = target - current
deficit <= 0                 -> null
requested = min(deficit, source.availableAmount)
requested < source.amount    -> requested   (a genuine partial)
otherwise                    -> null        (whole-UL move)

A face is topped up to its desiredAmount when it has one, and otherwise to its maxAmount. Earlier releases read desiredAmount nowhere, so a face configured with a desired level refilled to maxAmount regardless. A face with a desiredAmount and no maxAmount used to move a whole unit load. It now moves the deficit to its desired level.

A desiredAmount must lie between the face's minAmount and maxAmount, where those are set. The fix-assignment create and update calls refuse any other value with 422 invalid-desired-amount, and an update that moves minAmount or maxAmount past the stored desiredAmount is refused the same way. To send a face back to fill-to-max, update it with "clearDesiredAmount": true: leaving desiredAmount out of an update means "leave as is", and sending both is refused. A row stored before this rule may still hold a value outside the range. The scan ignores such a value. When the face has a maxAmount, it tops the face up to maxAmount, so it neither overfills the face nor moves a whole unit load. A face with no maxAmount has no target left, so the scan moves a whole unit load, as it did before desiredAmount was read. The flow model applies the same rule, so a simulation matches the real scan.

Two details matter. The cap is the source's available amount, not its gross - "a source partially reserved elsewhere must never be asked to give up more than what is actually free to move". And the partial/whole comparison is against the gross amount, so a fully available source whose deficit reaches its whole amount stays a whole-UL move rather than becoming a "partial" that leaves nothing behind.

That quantity is stamped on the transport order at mint time, and TaskService.complete defaults to it when the operator supplies neither an amount nor an explicit destination (TaskService.complete). The default is deliberately the mint-time snapshot rather than a live re-read, and the reasoning is long but sound: TransportOrder carries no "was this capped" flag, so a genuine cap and a stale whole-UL denormalisation are indistinguishable at that call site, and preferring live would discard the cap and move the whole source (TaskService.complete).

Mode 2: area replenishment

AreaReplenishmentService.processArea (.../service/AreaReplenishmentService.kt, AreaReplenishmentService.processArea).

Deficiency is either threshold missing its target, not both: amountDeficient || stocksDeficient (AreaReplenishmentService.deficientSummaryOrNull). An area with neither threshold configured is skipped before the stock query even runs.

One order per area per scan. A deficiency a single whole-UL move cannot close is left for the next scan to re-evaluate against then-current on-hand; the method never loops within an area (AreaReplenishmentService.scanAreas).

Destination choice is chooseDestination (AreaReplenishmentService.chooseDestination), and its honesty is worth quoting:

LocationFinder has no area or arbitrary-location-set constraint ... Rather than fabricate a capacity-ranked search this codebase's SPI surface does not support, chooseDestination picks the lowest-id unlocked, non-fix-face location whose base allocation plus active soft reservations still has room for the source unit load's type ... arbitrary but deterministic, with no capacity ranking.

AreaReplenishmentService.scanAreas. Fix faces are excluded from candidacy before the lock and occupancy queries run, because a fix-assigned location inside the area's cluster is Mode 1's face; without that, a single-location cluster that is entirely fix-assigned would let the same location receive both a Mode 1 and a Mode 2 order in one scan (AreaReplenishmentService.chooseDestination).

An area with no valid destination reports NO_DESTINATION rather than guessing.

TaskService.createAreaReplenishment then soft-reserves the chosen location through LocationFinder.reserve, keyed by the new order's id, so a concurrent putaway avoids it. That reservation carries the ordinary 10-minute TTL, which the layout sweeper renews for as long as the order is open, and the KDoc of createAreaReplenishment says so.

Successive scans skip a destination with no room left

chooseDestination excludes both lockedLocationIds and occupiedLocationIds, and DefaultLocationLockPort.occupiedLocationIds folds base allocation together with active reservation load using the same "effective allocation" split the finder itself uses, then judges each location with the finder's own capacity rule for the source unit load's type (CapacityVerdict): a half-full bin is still a destination for a unit load whose type capacity row fits the other half, and never for one the row does not fit or a type with no row at all (.../layout/service/DefaultLocationLockPort.kt). So the reservation that createAreaReplenishment takes keeps the next area scan off the same location once it leaves no room there, and the KDoc of createAreaReplenishment says so.

Cross-dock staging follows the same rules as area replenishment. When the cross-docking engine creates a CROSS_DOCK order, StagingLocationSelector.select takes the lowest-id CROSS_DOCK_STAGING location that is neither locked nor occupied for the arriving unit load's type, using lockedLocationIds and occupiedLocationIds as chooseDestination does. TaskService.createCrossDock then soft-reserves that location through LocationFinder.reserve, as createAreaReplenishment does. The reservation carries the ordinary 10-minute TTL, which the layout sweeper renews for as long as the order is open, and complete and cancel release it. So a locked slot is never chosen, a second match is not sent to a slot another open match holds, and a concurrent putaway avoids the slot. When every staging location is locked or occupied (by a held reservation or a pallet already in the slot), the receipt line is not cross-docked and follows ordinary putaway.

Running the scan

Two ways.

On demand - POST /api/v1/replenishment/scan, which is what a tenant that never opts in uses.

Scheduled - ReplenishmentScheduler (.../service/ReplenishmentScheduler.kt, ReplenishmentScheduler.scheduled, ReplenishmentScheduler.runOnce), karyo.replenishment.auto-scan-enabled, default false, interval karyo.replenishment.scan-interval default 10m, ConcurrentExecution.SKIP. Off by default because the schedule is "an opt-in wrapper around the existing on-demand ReplenishmentService.scan, not a behavior change for tenants that never asked for a background sweep" (.../service/ReplenishmentScanConfig.kt, ReplenishmentScanConfig).

The Facility set is every active Facility in the organization registry: an active Facility under an active Business Unit, read through OrganizationLookup.activeFacilityIds (services/auth-service/karyo-auth-api/.../spi/FacilityActivity.kt, activeFacilityIds). The scheduler does not derive the set from fix assignments, because Mode 2 runs inside the same scan and needs none: a Facility configured for area replenishment alone is scanned on the schedule like any other. A Facility with nothing configured scans two empty lists and mints nothing.

A failure for one Facility is caught, logged at WARN and the loop continues (ReplenishmentScheduler.runOnce).

The scheduler's KDoc records a hazard worth knowing if you write another scheduler (ReplenishmentScheduler): request scope is active on a @Scheduled thread, merely never primed with a tenant, so an ambient TenantContext read of the affiliation throws UnprimedTenantContextException; and scan's call graph is deeper than scan itself. The scan passes its Facility to every inventory and layout lookup it makes, and an integration test with real beans guards it, because "mocking ReplenishmentService hides everything downstream of scan, which is exactly where this bug lived".