Stock quant engine
A stock balance (stock.quant) holds the on-hand and reserved quantity of one key: company, product,
exact location, and optionally lot, package and owner. Balances are a projection of the stock ledger
(ADR 0079, ADR 0139). Only one path writes them: erp_addon_stock::apply_quant_changes. Generic ORM
writes of a balance are refused by name.
Open move lines are the first caller: each holds its reservation on its quant key (see Move lines). Move validation and inventory application are later slices.
All items are re-exported at the crate root of erp-addon-stock.
| Item | What it does |
|---|---|
QuantKey | The six key parts. The company is the ledger line’s company, never derived from the location. Build it with QuantKey::new(company, product, location) and .lot_id(..), .package_id(..), .owner_id(..). |
QuantChange | A signed on-hand delta, a signed reserved delta and the incoming date the stock carries: QuantChange::new(key, quantity, reserved), .in_date(..). |
apply_quant_changes(tx, &[QuantChange]) | Applies a batch in the caller’s transaction and returns the new balances, one per distinct stored key, in lock order. One call takes at most 2,000 distinct keys and 32,000 changes. |
quant_engine::apply_quant_changes_in_chunks(tx, &[QuantChange]) | The same for a unit whose changes may exceed that bound: sorted by key and applied in ascending calls under the bound, every change of one key in the same call, so the lock order holds. The calls run in one savepoint, so a refusal in a later call undoes the earlier ones and the transaction can go on. Validation, cancellation and every reservation path (Check availability, a reservation at confirmation, a line create or write, Unreserve) use it. |
QuantFilter | Which balances a read covers: broad (the location and its descendants) or strict (exact key parts): QuantFilter::new(company, product, location), then .strict(..), .tracked(..) and the part setters. |
gather_quants(tx, &QuantFilter) | The matching balances, lot-bearing ones first, then by id. One query. |
available_quantity(tx, &QuantFilter, allow_negative) | Free quantity of the filter. One query. |
QuantError | Every refusal, with its message and error kind. |
apply_quant_changes needs a REPEATABLE READ transaction, the ORM default. Use the native run_quant_unit entry below for a complete stock unit, including its probe and document changes. The ordinary Orm::run retries serialization failures but does not retry stock lock timeouts.
Before it writes, a batch is checked as a whole. It is refused with nothing changed when:
- a change has neither quantity nor reserved quantity;
- a delta has more decimal digits than the Product Unit precision;
- the product is not storable, the location is a view, or the lot belongs to another product;
- the product, location, lot or owner belongs to another company than the key (a location of a parent company is accepted);
- the company, product, location, lot, package or owner does not exist (a defect of the caller);
- a release would take the reserved counter below zero. This is a defect of the caller and is reported, never clamped.
The engine reads by SQL. Pending ORM writes of the transaction (a location usage written just before,
a storable flag) are flushed before the checks, so the batch is checked against them. A key another
transaction deleted after this one started is answered as a serialization failure (40001), which
Orm::run retries.
Changes at supplier, customer, inventory adjustment and production locations are accepted and store nothing: those balances live in the ledger only. A key whose quantity and reservation reach zero is deleted, unless it has a counted quantity or an assigned user.
The incoming date of a key is the earliest of its own date (while it holds positive stock) and the dates its changes carry. With neither, it is the time of the call.
Native stock unit runner
Section titled “Native stock unit runner”run_quant_unit(orm, unit, work) runs a repeatable async callback in a fresh transaction on every
eligible retry. Build QuantUnit::new(principal, operation_identity, product_label) with a label
that the caller is authorized to see, and use .context(context) when needed. The entry takes
its policy snapshot once and keeps the same identity and inputs across attempts.
The callback includes the availability probe, document changes and quant changes. It may be called
again: keep external effects outside it and register post-commit effects with tx.after_commit.
Do not commit manually. The entry owns the whole transaction and refuses a surrounding ORM or RPC
unit before reading policy. It is a native entry point, not an RPC method.
Serialization failures and deadlocks retry the entire callback. A lock timeout retries only when
the ORM classified it as such; a NOWAIT refusal does not. Exhaustion returns
QuantRetryExhausted, with a Lock error kind, the product label and actual attempt count.
Access, validation and programming refusals are terminal. An uncertain commit result is terminal:
inspect the operation’s durable idempotency state before retrying it. Operation identity supplies
correlation, not durable deduplication; the caller owns that protocol.
The engine’s apply_quant_changes entry still borrows a transaction and never retries or commits
on its own. Negative-stock policy changes use their separate policy-unit contract.
Lock order
Section titled “Lock order”The engine nets the changes of one call per key. It then sorts the keys ascending over
(company, product, location, lot, package, owner), with an absent part after every present one
(PostgreSQL’s ASC NULLS LAST). It locks them in that order in one statement, inserting a zero row for
a key that does not exist yet. Two calls over overlapping keys therefore never wait on each other in
opposite orders.
The order holds across calls only under one rule: one engine call per unit of work, or later calls
only with keys above the highest key the transaction already holds. Collect the changes of a unit of
work and pass them in one call. The engine keeps the keys each transaction locked; a later call that
names a lower key it does not hold yet is refused before any lock, as a Programming error naming
both keys. A key the transaction already holds may come again in any order. A key locked inside a
savepoint that was rolled back is no longer held, because the rollback released its row lock; the
engine notices the rollback and treats such a key as new. Count-state writes
through the generic write lock in row order; make them before the engine call or in their own unit
of work.
Quant keys come third in the lock hierarchy of ADR 0079 D4.1. A caller locks its picking, move and policy rows before it calls the engine, and cost keys after.
Availability
Section titled “Availability”| Product | allow_negative = false | allow_negative = true |
|---|---|---|
| Untracked | the signed sum of on hand minus reserved, at least zero | the signed sum |
Tracked (QuantFilter.tracked) | the sum of each lot’s free quantity that is positive | the signed sum |
A broad filter with a lot also counts stock without a lot. A strict tracked filter with a lot does not. The product’s tracking mode is a field added by the lot work (planned); until then the caller states it in the filter.
Access
Section titled “Access”The engine checks no model access or record rule, as an internal service. The transition that calls it has already checked access on its own documents. The engine is never an RPC method.
On stock.quant:
createis refused, after the model access check (so a user without access still gets the access refusal);writeof a key part,quantity,reserved_quantityorin_dateis refused, naming the field’s label; the counted quantity and the assigned user stay writable;copyis refused, after the create access check;- the generic
upsertby the declared key is refused, after the create and write access checks (it would run nocreateorwriteoverride); unlinkruns the model access check, then refuses a quant with an on-hand or reserved quantity for every caller, the superuser too. Deleting a zero quant requires the caller’s unlink access and record rules to allow it. The engine deletes its own zero keys.
These refusals are user errors whose message says that balances change only through stock moves and inventory adjustments; the client’s New and Duplicate buttons can reach them.
On stock.move and stock.move.line, the done time, and on lines also the membership and the
correction counter, are written only by the stock engine: a create or write that names one of
them is refused for every caller, after the model access check, with a user error naming the field’s
label. Correction rows (stock.move.line.correction) and serial positions (stock.serial.position)
are read only for stock users and managers; only the engine writes them.
available_quantity is a read-only PostgreSQL virtual generated column for on hand minus reserved. It answers row reads and available_quantity:sum from the same exact signed expression, including stock received or reserved before the catalog upgrade. It stores no second balance. The grouped read of inventory_quantity_auto_apply follows quantity; generic callers cannot write a balance through that alias.
A quant’s display name identifies its location, followed by each present lot, package and owner. The default on_hand filter follows visible active warehouses for the selected companies. The contexts warehouse_id and location (also search_warehouse, search_location) accept positive IDs or lists of IDs. With an explicit location, strict chooses that location only. Warehouse and location names in those context values require resolution to IDs before submitting the filter. Searching custom properties of a lot remains dependent on the lot-properties field on stock lots.
Location guards
Section titled “Location guards”A location write is refused when:
- it changes the company of a location (archive it and create a new one instead);
- it makes a location holding any balance a view;
- it changes the usage of a location holding any non-zero on-hand or reserved quantity. The reference blocks only positive stock; here a negative or reserved-only balance blocks too, because a balance at a virtual usage is never stored and would stay frozen there;
- it archives a location whose internal locations (itself or below) hold stock.
The checks also catch values that convert to a change: an active value other than true (null or 0
from RPC, an empty or integer cell from Rust) is checked as an archive, and a usage value that is not a
usage name is checked as a usage change. Pending ORM writes (a child moved to another parent just
before) are flushed before the checks read.
Concurrent stock changes. The engine takes a share lock on the locations of its keys. A location guard locks the locations it decides on (for an archive, every location below too) without waiting:
- while a stock change at those locations is still open, the guard fails as a serialization failure
and
Orm::runretries it; once the change committed, the retry sees its balance; - a stock change that starts after the guard waits for the guard’s transaction, is then retried, and sees the new usage or archive.
The tracking check locks the product rows in the same way, so an open insert of a lot, line or quant of the product retries it.
Not covered yet: a stock change that committed after the guard’s transaction began and before the guard’s lock. The guard’s snapshot does not show it and no lock is left to meet, so the guard decides without it. Closing that needs the rule as a database constraint that is checked across snapshots.
Settings
Section titled “Settings”The native unit’s limits are declared technical system parameters of stock (ADR 0227), in Technical, System Parameters, not on the Settings page. Only system administrators read and change them there; the unit reads them itself (erp_sdk::params::get_int, elevated), so every caller of a stock unit has them applied. Each new invocation reads committed policy; a save does not extend an invocation already in progress. A stored text outside its declaration fails the invocation with Stored parameter <key> is invalid. before any work. Negative stock is allowed. The switch that forbids it per location is the
location policy’s forbid_negative field. For a flagged location, apply_quant_changes checks the locked on-hand of
each key after netting: a change that lowers it below zero fails with QuantError::NegativeStockForbidden (kind
Validation, before any write, never clamped); a change that only repays an existing deficit, and every unflagged
location, behave as before. Switching the flag on is refused with ForbidNegativeBlocked while a key at the location
is below zero or has more reserved than on hand. A switch that meets an open stock change at the location, or one
that took a key’s free quantity (on hand minus reserved) below zero after the switch’s transaction began, fails as a
serialization failure and Orm::run retries it on a snapshot that sees the balance. The engine marks the location’s
policy row only when a key crosses from a free quantity at or above zero to one below it; a further change of a key
that is below zero already writes nothing, because the switch sees that key in its snapshot. Each mark makes the
other engine calls at that location whose snapshot is older fail once with a retryable serialization failure, and
two calls that both cross at one location can deadlock (one is retried). Not delivered yet: reservation re-flooring.
The decimal precision is the Product Unit precision (Settings, Technical, Decimal Accuracy).
Every key below begins with stock.quant_. Zero is refused, not treated as unlimited; an empty or deleted row means the default.
| Key suffix | Default | Allowed range |
|---|---|---|
lock_timeout_ms | 1000 ms | 10–10000 ms |
max_attempts | 5 | 1–5 |
retry_base_ms | 50 ms | 1–2000 ms |
retry_cap_ms | 2000 ms | 1–10000 ms |
idle_transaction_timeout_ms | 60000 ms | 1000–600000 ms |
tcp_keepalives_idle_s | 30 s | 1–300 s |
tcp_keepalives_interval_s | 10 s | 1–60 s |
tcp_keepalives_count | 3 | 1–10 |
The retry base cannot exceed its cap (parameter group stock.quant_retry_backoff). The lock timeout must be below the transaction’s effective
statement limit; incompatible values refuse the invocation before business work. Idle-session
and TCP keepalive values apply locally to each transaction. Defaults are operational choices;
performance calibration is deferred.
Before stock 1.5 these keys were global Settings values. The 1.5 upgrade moves each stored value to the
parameter of the same key (ADR 0227 §7): the Settings revision does not change, a parameter row that already
held another text is replaced by the Settings value and audited with actor migration:stock@1.5, and a stored
value outside its range stops the upgrade naming the key. The old rows stay in place, unread, for one release.
Move lines
Section titled “Move lines”An open, active stock.move.line of a storable product reserves its product-unit quantity on its key
(company, product, its source location, lot, package, owner). The line overrides of the stock addon keep that
true for ORM and RPC callers alike:
createtakes the move’s transfer, company, product, locations, unit and picked flag when they are not given, stamps the product-unit snapshot from the unit service, locks the move’s transfer and the move, inserts, and raises the reserved quantity of each new line’s key;writeof the quantity, unit, source location, package or owner releases the old reservation and takes the new one, netted per key in one engine call, also when the written lines need different unit snapshots; the move, transfer, company and product of a line cannot change;unlinkgives the reservation back.
After each of them one statement sets every touched move’s quantity (the sum of its active lines in the move’s
unit) and bumps open_line_version, and one recomputes the move’s state (covered demand assigned, partly covered
partially_available, otherwise confirmed, or waiting behind open origins). The transfer’s counters and state
follow from the move counter triggers. These statements, confirmation and reservation are the only writers of a
move’s state and quantity: a create or write naming either, for any caller and also through a transfer’s
move_ids commands, is refused with StockError::DerivedFromLines, as is a default_state or default_quantity
context key on a move create; a new or copied move starts draft with no quantity. A source location that
bypasses reservation (vendor, customer, inventory, production) and a product that does not track inventory store
no reservation. Lots on lines and lines without a move are refused by name until their slices exist, also when the
lot comes as a default_lot_id, default_lot_name or default_child_mode context key; done lines are fixed (see
Validation). A create checks that the caller may read the moves it names before it locks them.
The lines that Check Availability and validation create themselves never take the caller’s default_* context.
Reservation
Section titled “Reservation”stock.picking has two methods (also RPC, effect = write):
action_assign(Check Availability) reserves the transfer’s open moves, refused by name when there is none. It locks the transfers and all their moves once, confirms the drafts without reserving, and reserves every open move in one engine call. A move from a location that bypasses reservation, or of a product that keeps no stock, gets one line for its whole missing quantity. A make-to-order move without origins waits; a move with origin moves keeps its state until chained reservation exists. Every other move takes free, lot-less stock (on hand minus reserved) from its source location and the locations below it, oldest incoming date first, as one line per key, growing an unpicked line of the same key. The quantity is converted to the move’s unit rounding down, so a line never takes more than is free.do_unreservedeletes the unpicked lines of moves that are not picked, done or cancelled; a done move is refused.
Concurrency follows ADR 0139 D2: the free stock is read once without a lock (the probe), then the chosen keys are
locked in key order by one engine call whose changes are marked with QuantChange::as_probed. A key another unit
changed after the probe fails the unit with a retryable 40001 (from the lock, or
QuantError::ChangedSinceProbe from the floor), and the retry probes again, so a reservation is short only when
the probe found less, never because of a lock. At a location whose policy forbids negative stock, every growing
reservation, an explicit line edit included, is refused with QuantError::ReservationExceedsFree when it would
take more than is free; elsewhere an explicit line may over-reserve, as in the reference.
Confirmation
Section titled “Confirmation”stock.picking.action_confirm (RPC, effect = write) confirms a transfer’s draft moves in one statement: a move
with origin moves becomes waiting, any other confirmed, and a move whose operation type reserves at
confirmation gets today’s reservation date. The confirmed moves that are returns, bypass reservation, reserve at
confirmation or whose reservation date has come are then reserved as by action_assign, in the same unit of
work. A transfer without a draft move is refused by name. A make-to-order move (or one whose rule falls back to
an order) is refused until the procurement engine exists. action_assign confirms draft transfers first.
A new move that names a transfer (or has default_picking_id in the context) takes the transfer’s company,
source, destination, operation type and contact when its values do not name them, so a client sends only the
product and the demand; the product’s unit is filled the same way (and proposed by the product_id onchange).
The transfer’s values are read after the ORM’s pending writes are flushed, so a row added in the same save that
changes the transfer’s header takes the new header.
Validation
Section titled “Validation”stock.picking.button_validate (Validate, RPC, effect = write) completes confirmed, waiting or ready transfers.
It locks the transfers, then their open moves, and refuses by name: only done transfers, a cancelled transfer, a
transfer without moves, and one whose moves carry no quantity. A draft transfer is confirmed on the way (without
the early reservation, since the unit makes one engine call) and each of its moves without quantity gets one line
for its demand at its own locations; a quantity entered before is kept. Those lines were never reserved: their
source keys go to the engine as QuantChange::as_floored, so at a location that forbids negative stock a take that
would use stock reserved for other transfers is refused with ReservationExceedsFree and nothing changes
(ADR 0139 D6.3); elsewhere it is taken. When no move is picked every move is
taken as picked. The transfer form calls action_validate_transfer. A short transfer under the Ask policy returns a form dialog for that same record. Each choice calls the ordinary button_validate override chain with a decision scoped to the current transaction and record. Replaying a choice or changing the policy or outstanding work between opening and submission prompts the clerk to recheck. The established native button_validate contract returns unit and raises a named user error when it needs a decision. An operation type with an Always backorder policy splits the outstanding demand of a direct customer shipment or vendor receipt into one new transfer per source. The validated movement and generated movement share a protected original identity. The normal reservation policy applies to the child after original move completion. A Never policy closes the demand at the completed quantity and cancels unpicked or empty moves. A move without quantity and without demand is cancelled; cancelling a
move that feeds an open move is refused.
The stock then changes in one engine call per validation (in ascending calls of at most 2,000 keys when the
validation touches more): the reservations of the done and deleted lines are
released and each done line’s quantity leaves its source key and arrives at its destination key (the result
package as package), netted per key and applied in the engine’s key order. A location that forbids negative stock
refuses the whole validation by name and nothing is written. Zero lines are deleted, the done lines join the
ledger (membership = 'done', done_at), the moves become done with their completion time, and the transfer
gets its done date; the transfer’s counters and state follow from the move counter triggers, and the overview
counts are notified. Two sessions validating one transfer: the later one fails with a retryable 40001 on the
transfer lock, and its retry is refused because the transfer is done.
Done work is fixed for every caller, sudo included (allow-lists in addons/stock/src/done.rs): a done move may
still change only its description, origin, priority, sequence, deadline, chain links and references; a done
transfer only its note, origin, responsible, printed and locked flags and priority. Every other field is refused
by name, also as x2many commands. No move joins a done transfer (in the values or as default_picking_id), done
moves and transfers are not deleted, and no create, write or default_state sets a move to done: Validate is the
only way there.
Not yet: return splitting, manual splits, lots, the line picked flag (every line of a done move is done), the incoming date carried from the source, re-flooring other reservations when a validation drives free stock negative at an unflagged location, and assigning the destination moves of a chain.
Observing original line completion
Section titled “Observing original line completion”An installed extension of stock.move.line can override _after_stock_completion and call its super method.
The recordset contains the lines that received their original completion timestamp in this validation. Read their
stored quantity_product_uom after checking the caller’s line access. The caller’s transaction includes the
stock changes and the observer’s database writes. Returning an error rolls both back even when the caller catches it.
A batch containing a previously completed picking gives the observer only newly completed lines.
This method has no RPC exposure. A valuation consumer must establish the company and product admission locks before entering stock validation, then verify the authorized source, costing configuration and currency precision before writing a valuation. The stock hook itself supplies physical evidence only (ADR 0257).
Transfers: reference, defaults, cancel, delete
Section titled “Transfers: reference, defaults, cancel, delete”- A new transfer without a reference (none, empty or the default
/, and nodefault_namein the context) draws the next number of its operation type’s sequence (erp_sdk::sequence::draw_by_id); a type without a sequence leaves/. Its source, destination and company come from the operation type when the values and the context defaults do not name them; on the form thepicking_type_idonchange proposes the same. action_cancel(Cancel, RPC,effect = write) cancels the open moves of the transfers: their open lines are deleted and their reservations given back in one engine call, the moves becomecancel, unpicked and make-to-stock, and the transfers are locked (is_locked). A done transfer and a transfer without moves are refused by name (an empty transfer is a draft by its counters: delete it); a move that feeds an open move is refused until cancel propagation exists.- Deleting a transfer cancels its open moves, deletes all its moves through the move model, then the transfer; a done transfer is refused.
Returns from completed stock transfers
Section titled “Returns from completed stock transfers”stock.picking.action_return creates a draft and returns its form action. It starts at the
completed transfer’s destination. An incoming return operation uses its configured destination.
Other return operations use the original source. Each completed original move supplies the
product and unit for a linked draft movement. action_return_all rounds the remaining demand
through the original unit’s normal rounding method. action_clear_return resets the open
demands. Creating a return releases unfinished downstream reservations through the usual stock
unreservation path. The return_count field groups direct links under the reader’s access rules.
The ordinary validation path locks the return and original transfers in the existing ascending order. A row-version update on the source transfer makes a return with an older snapshot retry. The guard compares the proposed and already completed return lines to the original completed lines in the physical product unit, before the normal quant engine updates the stock. The validation savepoint rolls the guard and stock changes back together. The completed source and the linked movements must be readable in the caller’s company scope.
action_exchange creates a linked replacement transfer using the actual quantities on a return
and runs the usual confirm and assign actions. Its moves have their own stock reservations and
keep the replacement separate from the reversal of the original stock flows.
Not yet available
Section titled “Not yet available”Later quant slices add:
- serial positions and the one-serial-per-location rule, after the lot work (planned);
- compensation of lot-less negative stock when lots arrive;
- searching quants by a custom property of the lot, when product and lot records provide property definitions;
- relocating or repacking balances.
Removal strategies and applying a counted quantity through the inventory workflow are separate deliveries.