Case study: Inventory management
What you will learn on this page
Section titled “What you will learn on this page”- Why a stock count needs two numbers, on hand and reserved, and how “available” follows from them, so that an order taken today cannot be sold again before it ships.
- How to reserve every line of an order or none of them, and how three phases (check, prepare, apply) keep that promise even when memory runs out.
- How a small state machine (held, committed, released) makes commit and release safe to repeat, and makes the wrong ending impossible.
- Why one mutex for the whole inventory is the right first choice, what it costs, and when finer locks would pay for their extra risk.
- How to send a low-stock alert once per crossing, and why it is delivered after the lock is released, never while it is held.
- How a real test with threads and a latch shows that the last item goes to exactly one order.
- A beginner’s trap the sanitizers caught while this example was written: a reference into a temporary that dies at the end of the statement, and the by-value accessor that fixes it.
- How a change (transfers between warehouses, and batches with expiry dates) lands: first expiry first out, a commit that refuses expired stock, and an alert flag that time itself can make necessary.
This page follows the five steps in How to approach a case study. It assumes Thread safety and synchronization. It also uses Exception safety and failure atomicity and Strong types and API contracts, and the change uses ideas from Deadlocks and lock ordering.
The request
Section titled “The request”“We sell homeware from one warehouse now, and a second opens next year. Twice last month we sold the last lamp to two customers within a minute of each other, and one of them got an apology instead of a lamp. We also want to know when something is running low, but the old system sent us an email every time anyone bought a mug, so we stopped reading them. Can you design the stock part?”
Two complaints again. The first is a race: two orders saw the same last lamp and both were accepted. The second is about noise: an alert that fires on every change is an alert nobody reads. Both come from the same habit, looking at a number and acting on it later, as if nothing could happen in between.
Step 1 of the framework: Requirements
Section titled “Step 1 of the framework: Requirements”Step 1 turns the request into numbered requirements. The questions come first, because the answers decide the design.
Clarifying questions
Section titled “Clarifying questions”| Question | Answer (from the team) | What it changes |
|---|---|---|
| When does stock leave the count: when the order is placed, or when it ships? | Both matter. Once an order is placed, nobody else may buy those units, but they are on the shelf until the van leaves. | Two numbers per count: on hand (on the shelf) and reserved (promised). Available is the difference. |
| Can an order be cancelled before it ships? | Yes, and then the units go back on sale. | A reservation ends one of two ways: committed (shipped) or released (cancelled). |
| An order has several items. If one is out of stock, what then? | Then we do not take the order at all. A half-filled parcel is worse than a “sorry”. | Reserve every line or none (all or nothing). |
| The payment system sometimes retries a “ship it” message. Is that a problem? | It must not ship twice. | Commit and release are safe to repeat: a second commit succeeds and changes nothing. |
| Who chooses the warehouse for each item? | The order does. Each line says which warehouse. | An OrderLine is product, warehouse, and quantity. Choosing for the customer is out of scope. |
| When is something “running low”? | Each product has its own threshold. Tell us when what we can still sell drops below it, once, not every time. | A per-product threshold, and an alert once per crossing below it. |
| How many orders arrive at once? | Many web servers call this code at the same time. | Every public member function must be safe to call from many threads. |
| Where do the alerts go? | To a function you call; someone else turns it into an email. | A handler passed in at construction. It must not run while the inventory is locked. |
| Do the counts need to survive a restart? | Not in this part. Another team stores them. | Everything is in memory, in one process. |
Three answers decide the shape. “Nobody else may buy those units, but they are on the shelf” gives two numbers, not one. “Many web servers at the same time” makes the check and the change one indivisible step. “Once, not every time” means an alert depends on what the count was as well as what it is.
Confirmed:
- Products (an id, a name, a low-stock threshold) and warehouses (an id).
- Receiving stock into a warehouse.
- Reserving an order of several lines, each a product, a warehouse, and a quantity: all lines or none.
- Committing (shipping) and releasing (cancelling) a reservation, both safe to repeat.
- Low-stock alerts, once per crossing below the threshold.
- Many threads calling at once.
Assumed (to confirm with the team; see Assumptions):
- A count fits in an
int. Receiving more than that is refused, not wrapped round. - The alert handler is quick, safe to call from several threads at once, and does not throw.
- Reservation ids are numbers handed out by the inventory, starting at 1.
Out of scope: payment, choosing a warehouse for the customer, backorders, returns, stock takes, persistence, and reservations that time out on their own (see the Exercise). Transfers between warehouses and expiry dates arrive as a change, in Step 5.
Requirements
Section titled “Requirements”Functional requirements.
- FR-1 Products and warehouses. Products and warehouses are added with ids that must be new. A product has a low-stock threshold that is not negative; 0 means “never alert”.
- FR-2 Receiving. Stock arrives for a product in a warehouse and raises what is on hand there.
- FR-3 Reserving. An order of one or more lines is reserved in full or not at all. Reserved stock stays on hand but can no longer be taken by another order. A refusal says why.
- FR-4 Shipping and cancelling. A held reservation is committed (its units leave on hand) or released (its units are free again). Repeating either is a success that changes nothing; a finished reservation cannot take the other ending.
- FR-5 No overselling. No count is ever negative, and reserved never exceeds on hand. Available is on hand minus reserved.
- FR-6 Low-stock alerts. When the available stock of a product in a warehouse drops below the product’s threshold, the handler is told once. It is told again only after the count has risen back to the threshold and dropped again.
- FR-7 The last item. When many orders race for the last units, exactly as many win as there are units.
Non-functional requirements.
- NFR-1 Thread safe. Every public member function may be called from many threads at once.
- NFR-2 All or nothing, even on failure. A refused or failed operation, including one that runs out of memory, leaves the inventory exactly as it was.
- NFR-3 Alerts outside the lock. The handler runs after the change, on the thread that made it, with no lock held. It may call back into the inventory.
- NFR-4 Refusals are values. A refusal is a result with an
enum classreason and a text, not an exception. Exceptions are for programming errors (andstd::bad_allocwhen memory runs out). - NFR-5 Testable. The invariants can be checked after every operation, and the threaded tests use real threads.
FR-7 is the first complaint in one line, and FR-6 the second. Most of the design is about FR-3 and FR-5 holding while NFR-1 lets any number of threads in at once.
Use cases and acceptance criteria
Section titled “Use cases and acceptance criteria”The tests are named after these criteria (ac_2_2_… is AC-2.2). See
Use cases, user stories, and acceptance criteria.
UC-1 Set up and receive.
- AC-1.1 Receiving raises on hand and available, in that warehouse only.
- AC-1.2 An unknown product or warehouse, or a quantity that is not positive, is refused and changes nothing.
- AC-1.3 Ids must be new; a negative threshold is refused.
- AC-1.4 Receiving past the largest
intis refused; exactly the largest is fine.
UC-2 Reserve an order.
- AC-2.1 Reserving sets stock aside without removing it.
- AC-2.2 An order is reserved in full or not at all.
- AC-2.3 Lines for the same product and warehouse are added together before the check.
- AC-2.4 An empty order, an unknown id, a quantity that is not positive, or too little stock is refused with its reason.
- AC-2.5 The last unit can be reserved, and then no more.
- AC-2.6 Reservation ids are unique, and a refusal uses none.
UC-3 Ship or cancel.
- AC-3.1 Commit lowers on hand and reserved; available stays the same.
- AC-3.2 Release lowers reserved; available rises.
- AC-3.3 Commit twice ships once. AC-3.4 Release twice frees once.
- AC-3.5 A committed reservation cannot be released, and a released one cannot be committed.
- AC-3.6 An unknown reservation is refused.
- AC-3.7 Only the legal moves of the state machine are allowed.
UC-4 Keep the counts right.
- AC-4.1 Over 4,000 random operations, every invariant holds after each one, and the counts match a simple model.
UC-5 Low-stock alerts.
- AC-5.1 An alert fires when available drops below the threshold, not when it reaches it.
- AC-5.2 No second alert while still below.
- AC-5.3 Rising back to the threshold (a release or a delivery) re-arms the alert.
- AC-5.4 Commits and refusals send no alert.
- AC-5.5 A threshold of 0 never alerts.
- AC-5.6 One order alerts once for each count it takes below.
- AC-5.7 The handler runs after the change with no lock held, and can call back into the inventory.
UC-6 Many threads.
- AC-6.1 Threads racing for the last units: exactly the right number win, and the crossing alerts once.
- AC-6.2 Threads racing to commit and release one reservation: exactly one ending wins.
- AC-6.3 Many orders in parallel keep the counts exact.
Invariants
Section titled “Invariants”Each invariant names the code that keeps it. See Invariants.
- INV-1 Never negative, never oversold. For every count,
0 <= reserved <= on_hand. Kept byreserve_locked, which reserves only what is available, and byfinish, which subtracts only what a held reservation added. - INV-2 Reserved adds up. The reserved of each count equals the sum
of the held reservations’ lines on it. Kept by the apply phases of
reserve_lockedandfinish. Checked byinvariants_hold. - INV-3 A reservation moves forward only. Held goes to committed or
released, and those never change. Kept by
classify, the only place that decides a move. - INV-4 All or nothing. No operation leaves a change half made. Kept by the three phases in every function that changes data.
- INV-5 One alert per crossing. Kept by comparing the count before and after, under the same lock (step 1), and by a flag per count (step 2).
The test helpers call invariants_hold() after every operation
they run, and the random test also compares each count with a model of
its own. A broken invariant is caught at the step that broke it, not
thousands of steps later.
Step 2 of the framework: Entities and relationships
Section titled “Step 2 of the framework: Entities and relationships”The nouns from the request and the answers: product, warehouse, stock, shelf, order, line, reservation, shipment, cancellation, threshold, alert, customer, web server. Not every noun is a class; see Finding classes.
- Product and warehouse are ids, each a type of its own:
ProductIdandWarehouseId. A product also has a name and a threshold, kept inside the inventory. - Stock is a
StockLevel, the two numbers on hand and reserved, one per product per warehouse. Shelf is on hand. - Order and line become a list of
OrderLinevalues passed toreserve. - Reservation is a
Reservation, with its id, its lines, and aReservationState. Shipment and cancellation are not objects: they are the two ways a reservation ends,commitandrelease. - Threshold is a number in the product. Alert is a
LowStockAlertvalue handed to a function that the caller supplies. - Customer and web server are callers. They need no class here; “many web servers” becomes “many threads”.
- And one class that is not a noun in the request: the
Inventorythat owns all of it and guards it with one mutex.
Text description of the diagram
Ten boxes. A dashed arrow from the callers (many threads) to Inventory, labelled uses. Solid arrows from Inventory to a std::mutex (owns 1), to Product (owns 0 or more), to WarehouseId (owns 0 or more), and to Reservation (owns 0 or more). A solid arrow from Product to StockLevel, labelled owns one per warehouse, 0 or more. Solid arrows from Reservation to OrderLine (owns 1 or more) and to ReservationState (holds 1). Dashed arrows from OrderLine to Product and to WarehouseId, each labelled names 1. A dashed arrow from Inventory to the alert handler, labelled notifies, and one from Inventory to LowStockAlert, labelled creates.
Diagram source (Mermaid)
flowchart LR
Caller["callers (many threads)"] -.->|"uses"| Inventory
Inventory -->|"owns 1"| Mutex["std::mutex"]
Inventory -->|"owns 0..*"| Product
Inventory -->|"owns 0..*"| Warehouse["WarehouseId"]
Product -->|"owns one per warehouse, 0..*"| StockLevel
Inventory -->|"owns 0..*"| Reservation
Reservation -->|"owns 1..*"| OrderLine
Reservation -->|"holds 1"| ReservationState
OrderLine -.->|"names 1"| Product
OrderLine -.->|"names 1"| Warehouse
Inventory -.->|"notifies"| Handler["alert handler"]
Inventory -.->|"creates"| LowStockAlertOwnership is simple: the Inventory owns everything inside it, by
value, in standard containers. Nothing is shared and nothing is a
pointer, except the short-lived StockLevel* pointers that
reserve_locked and finish use while the lock is held. An OrderLine names a product and a
warehouse by id; it does not point at them. That is what lets the
inventory hand out copies of a reservation with no risk that a caller
keeps a reference into data another thread is changing.
Step 3 of the framework: Class design
Section titled “Step 3 of the framework: Class design”Step 3 decides, for each class, what it must remember and what it must do, and justifies each from the requirements. The design below is step 1 of the example, the complete answer to FR-1 to FR-7. The change comes in Step 5.
What each class must remember
Section titled “What each class must remember”| Requirement | What must be remembered | Where | As |
|---|---|---|---|
| FR-1 products with a name and a threshold | each product’s name, threshold, and stock | Inventory::Product |
std::map<ProductId, Product> products_ |
| FR-1 warehouses | which warehouses exist | Inventory |
std::set<WarehouseId> warehouses_ |
| FR-2, FR-3, FR-5 stock that is promised but still on the shelf | on hand and reserved, per product per warehouse | StockLevel |
int on_hand, int reserved, in Product::stock |
| FR-4 commit and release by id, safe to repeat | each reservation’s lines and how it ended | Reservation |
std::map<ReservationId, Reservation> reservations_ |
| AC-2.6 unique ids | the next id to hand out | Inventory |
std::uint64_t next_reservation_ = 1 |
| FR-6 where alerts go | the handler | Inventory |
const AlertHandler on_low_stock_ |
| NFR-1 many threads | one lock for all of the above | Inventory |
mutable std::mutex mutex_ |
Notice what is not remembered. Available is not a third number: it is worked out from the other two, so it cannot disagree with them. And there is no “already alerted” flag in step 1. Every change that can lower available sees the count before and after under the same lock, and that is enough to tell a crossing from a further drop. Step 5 shows the moment that stops being true.
What each class must do
Section titled “What each class must do”| Need | Member function | Class |
|---|---|---|
| Add a product or a warehouse (FR-1) | Result<ProductId> add_product(ProductId, std::string, int), Result<WarehouseId> add_warehouse(WarehouseId) |
Inventory |
| Stock arrives (FR-2) | Result<StockLevel> receive(const ProductId&, const WarehouseId&, int) |
Inventory |
| Reserve an order, all or nothing (FR-3) | Result<ReservationId> reserve(const std::vector<OrderLine>&) |
Inventory |
| Ship or cancel, safe to repeat (FR-4) | Result<ReservationState> commit(const ReservationId&), release(…) |
Inventory |
| What can still be sold? (FR-5) | int available() const |
StockLevel |
| Which moves are legal? (FR-4, INV-3) | Move classify(ReservationState from, ReservationState to) |
free function |
| Look without holding a reference (NFR-1) | StockLevel level(…) const, std::optional<Reservation> reservation(…) const |
Inventory |
| Check every invariant (NFR-5) | bool invariants_hold() const |
Inventory |
Every answer is a Result: the value, or a Refusal saying why not
(NFR-4). The readers return copies. A function that returned a
const StockLevel& would hand the caller a reference into data that
the next reserve on another thread changes while the caller reads it;
see
Reading: return a copy.
Class outlines
Section titled “Class outlines”A class outline is one box per class, listing its data members (-)
and member functions (+) as C++ declarations, as described in
Finding classes. Data members are private
unless the outline says otherwise.
class StrongId<Tag, Rep>
ProductId, WarehouseId, ReservationId
Data members
Rep value_;
Member functions
explicit StrongId(Rep value);const Rep& value() const&;a named id: a referenceRep value() &&;a temporary id: a copy
struct StockLevel
public members: one product in one warehouse
Data members
int on_hand = 0;int reserved = 0;0 <= reserved <= on_hand
Member functions
int available() const;on_hand - reserved
struct OrderLine
public members
Data members
ProductId product;WarehouseId warehouse;int quantity;
enum class ReservationState
Values
heldcommittedreleased
enum class Move
what a requested move would do
Values
applyrepeatillegal
struct LowStockAlert
public members
Data members
ProductId product;WarehouseId warehouse;int available;int threshold;
class Result<T>
a value, or the reason there is none
Data members
std::variant<T, Refusal> outcome_;
Member functions
bool ok() const;const T& value() const&;throws std::logic_error on a refusalT value() &&;on a temporary: a copy, never a dangling referenceReason reason() const;
class Inventory
thread safe: one mutex guards all the data
Data members
const AlertHandler on_low_stock_;set once, read without the lockmutable std::mutex mutex_;std::map<ProductId, Product> products_;name, threshold, stock per warehousestd::set<WarehouseId> warehouses_;std::map<ReservationId, Reservation> reservations_;std::uint64_t next_reservation_ = 1;
Member functions
Result<StockLevel> receive(const ProductId&, const WarehouseId&, int quantity);Result<ReservationId> reserve(const std::vector<OrderLine>& lines);Result<ReservationState> commit(const ReservationId& id);Result<ReservationState> release(const ReservationId& id);StockLevel level(const ProductId&, const WarehouseId&) const;a copystd::optional<Reservation> reservation(const ReservationId&) const;a copybool invariants_hold() const;for tests
Ids and results
Section titled “Ids and results”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A value with a type of its own. A ProductId and a WarehouseId both hold a// string, but they are different types, so passing a warehouse where a// product is expected does not compile. The constructor is explicit, so a// bare string or number cannot slip in either: you write ProductId{"apple"}.//// Tag is an empty struct used only to make each kind of id a distinct type;// Rep is what the id holds (a std::string or a number).template <typename Tag, typename Rep>class StrongId {public: explicit StrongId(Rep value) : value_(std::move(value)) {}
// On a named id, a reference to the value. On a temporary id (say, the // one returned by a function call) a copy, because a reference into the // temporary would dangle once the statement ends. [[nodiscard]] const Rep& value() const& { return value_; } [[nodiscard]] Rep value() && { return std::move(value_); }
// Compare by the value held. The ordering lets an id be a std::map key. friend bool operator==(const StrongId&, const StrongId&) = default; friend auto operator<=>(const StrongId&, const StrongId&) = default;
private: Rep value_;};
struct ProductTag {};struct WarehouseTag {};struct ReservationTag {};
using ProductId = StrongId<ProductTag, std::string>;using WarehouseId = StrongId<WarehouseTag, std::string>;// Reservation ids are handed out by the inventory, counting up from 1.using ReservationId = StrongId<ReservationTag, std::uint64_t>;ProductId, WarehouseId, and ReservationId are three different
types built from one template, as in
Strong types and API contracts. A call such
as receive(leeds, mug, 4), with the warehouse and the product the
wrong way round, does not compile. The Tag structs are empty: they
exist only to make three types out of one template.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Why the inventory said no. Every refusal leaves the inventory exactly as// it was, so the caller can show the reason and try something else.enum class Reason { unknown_product, unknown_warehouse, already_exists, // add_product or add_warehouse with an id in use bad_quantity, // zero or negative bad_threshold, // a negative low-stock threshold empty_order, // reserve with no lines not_enough_available, // available (on hand minus reserved) is too low would_overflow, // receiving this much would overflow the count unknown_reservation, already_committed, // release asked of a reservation that has shipped already_released, // commit asked of a reservation that was released};
[[nodiscard]] inline std::string_view to_string(Reason reason) { switch (reason) { case Reason::unknown_product: return "unknown product"; case Reason::unknown_warehouse: return "unknown warehouse"; case Reason::already_exists: return "already exists"; case Reason::bad_quantity: return "bad quantity"; case Reason::bad_threshold: return "bad threshold"; case Reason::empty_order: return "empty order"; case Reason::not_enough_available: return "not enough available"; case Reason::would_overflow: return "would overflow"; case Reason::unknown_reservation: return "unknown reservation"; case Reason::already_committed: return "already committed"; case Reason::already_released: return "already released"; } return "?"; // not reached: every enumerator is handled above}
// The reason as an enum (for code to branch on) and as text (for people).struct Refusal { Reason reason; std::string text;};
// Either the value an operation produced or the Refusal saying why it did// not happen. (std::expected does the same job but arrives in C++23; this// project is C++20.) The constructors are implicit on purpose, so a function// returning Result<int> can write either `return 5;` or// `return Refusal{...};`.template <typename T>class Result {public: Result(T value) : outcome_(std::move(value)) {} Result(Refusal refusal) : outcome_(std::move(refusal)) {}
[[nodiscard]] bool ok() const { return std::holds_alternative<T>(outcome_); }
// Throws std::logic_error if this is a refusal: asking for a value that // does not exist is a bug in the caller, not a business outcome. // // Two versions, chosen by whether the Result is a named variable (&) or a // temporary (&&), as std::optional does. On a named Result you get a // reference. On a temporary, such as `inventory.commit(id).value()`, you // get a copy taken out of it, because a reference would dangle as soon as // the temporary is destroyed at the end of the statement. [[nodiscard]] const T& value() const& { check_ok(); return std::get<T>(outcome_); } [[nodiscard]] T value() && { check_ok(); return std::get<T>(std::move(outcome_)); } // Throws std::logic_error if the operation succeeded. [[nodiscard]] const Refusal& refusal() const& { check_refused(); return std::get<Refusal>(outcome_); } [[nodiscard]] Refusal refusal() && { check_refused(); return std::get<Refusal>(std::move(outcome_)); } [[nodiscard]] Reason reason() const { return refusal().reason; }
private: void check_ok() const { if (!ok()) { throw std::logic_error("value() of a refusal: " + std::get<Refusal>(outcome_).text); } } void check_refused() const { if (ok()) throw std::logic_error("refusal() of a success"); }
std::variant<T, Refusal> outcome_;};A refusal carries an enum class Reason, for code to branch on, and a
text, for people. Tests compare reasons, never texts, except where the
text itself is the point (AC-2.4 checks that it names the stock).
How this code works: Why value() has two versions
Result::value() and StrongId::value() each come in two versions,
one marked & and one marked &&. The mark says which kind of object
the function may be called on:
- On a named object (
first.value(), wherefirstis a variable), theconst&version runs and returns a reference. The variable lives on, so the reference stays good. - On a temporary (
store.commit(id).value(), where theResultexists only until the end of the statement), the&&version runs and moves the value out into a new object that the caller owns.
Why not one version that always returns a reference? Because the caller can keep the reference longer than the temporary lives:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// Flawed: one accessor for every Result, named or temporary.template <typename T>class OneAccessorResult {public: explicit OneAccessorResult(T value) : value_(std::move(value)) {} // Returns a reference into this object, even when this object is a // temporary that is destroyed at the end of the statement. const T& value() const { return value_; }
private: T value_;};
inline OneAccessorResult<std::string> make_label() { return OneAccessorResult<std::string>{"reservation 1, ready to ship from leeds"};}
inline void print_label() { // The temporary returned by make_label() dies at the semicolon, and // its string with it. `label` now refers to memory that has been freed. const std::string& label = make_label().value(); std::cout << label << '\n'; // undefined behaviour: reads a destroyed string}This sketch was compiled for this page with g++ 11.4 and clang++ 14
using -Wall -Wextra, and neither compiler warned. Built with
AddressSanitizer and run, it stopped with
heap-use-after-free at the line that prints. That is the lesson:
the compiler accepts this code, and only a sanitizer or a crash tells
you. The agent that wrote the example reported that clang and ASan
caught the same kind of mistake in its first draft, in the tests, where
LLD_CHECK_EQ binds a reference to what it is given. The fix there is
the same as here: an accessor that returns by value when called on
a temporary. That is why the test helper World::state returns a
ReservationState by value instead of reading
inventory.reservation(id)->state inside a check, and why the step 2
demo keeps store.reservation(order).value() in a named variable
before looping over its allocations.
A rule of thumb for beginners: if a function returns a reference, ask “a reference into what, and does that live long enough?” If the answer is “into a temporary”, return a value instead.
Stock, reservations, and their states
Section titled “Stock, reservations, and their states”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The stock of one product in one warehouse.// on_hand units physically on the shelf// reserved units on the shelf that held reservations have set aside// available what a new order may still take: on hand minus reserved// The inventory keeps 0 <= reserved <= on_hand at all times, so available is// never negative either.struct StockLevel { int on_hand = 0; int reserved = 0; [[nodiscard]] int available() const { return on_hand - reserved; }};
// Sent when the available stock of a product in a warehouse drops below the// product's threshold, so someone can reorder.struct LowStockAlert { ProductId product; WarehouseId warehouse; int available; int threshold;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One line of an order: this many of a product, from this warehouse.// Choosing the warehouse for the customer is out of scope; the order says.struct OrderLine { ProductId product; WarehouseId warehouse; int quantity;};
// A reservation as the inventory keeps it. `lines` holds one line per// product and warehouse: an order that names the same pair twice is merged// into one line with the total, so commit and release touch each count once.struct Reservation { ReservationId id; std::vector<OrderLine> lines; ReservationState state;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The life of a reservation. It starts held: the stock is set aside, so no// other order can take it, but it is still on the shelf. It then ends one of// two ways and stays there for good:// held -> committed the order shipped: the stock left the building// held -> released the order was cancelled: the stock is free againenum class ReservationState { held, committed, released };
[[nodiscard]] constexpr std::string_view to_string(ReservationState state) { switch (state) { case ReservationState::held: return "held"; case ReservationState::committed: return "committed"; case ReservationState::released: return "released"; } return "?"; // not reached}
// What asking a reservation to move to `to` would do.// apply a legal move: change the state and the stock counts// repeat it is already in `to`: change nothing and report success, so a// caller that retries commit or release (say, after a lost reply)// cannot ship or free the same stock twice// illegal refuse: nothing returns to held, a shipped order cannot be// released, and a released order cannot be shippedenum class Move { apply, repeat, illegal };
[[nodiscard]] constexpr Move classify(ReservationState from, ReservationState to) { if (to == ReservationState::held) return Move::illegal; // never a target if (from == to) return Move::repeat; if (from == ReservationState::held) return Move::apply; return Move::illegal; // committed -> released, or released -> committed}Text description of the diagram
A reservation starts held when reserve finds room for every line. From held, commit moves it to committed (the order shipped) and release moves it to released (the order was cancelled). A second commit of a committed reservation, or a second release of a released one, is a repeat: it succeeds and changes nothing. In step 2 only, a commit of a held reservation whose batch has expired is refused and the reservation stays held. Committed and released are final. No arrow leads from committed to released or from released to committed, and nothing leads back to held: those moves are refused.
Diagram source (Mermaid)
stateDiagram-v2
[*] --> held : reserve, every line fits
held --> committed : commit, the order shipped
held --> released : release, the order was cancelled
committed --> committed : commit again (repeat, no change)
released --> released : release again (repeat, no change)
held --> held : step 2 only, commit refused, a batch has expired
committed --> [*]
released --> [*]classify is the whole state machine, as one function of two values.
Every place that changes a reservation’s state asks it first, so the
table below is the only place the rules live, and test AC-3.7 checks
all nine pairs:
| From \ to | held |
committed |
released |
|---|---|---|---|
held |
illegal | apply | apply |
committed |
illegal | repeat | illegal |
released |
illegal | illegal | repeat |
Why is a repeat a success and not a refusal? Because of the retry in the request: the payment system may send “ship it” twice, for example after a reply was lost. If the second commit were refused, the caller could not tell “already shipped, all is well” from “could not ship”. A repeat that succeeds and changes nothing makes commit idempotent, as in Idempotency, retries, and duplicate handling. And why is the other ending illegal? A shipped order cannot be put back on sale by a late “cancel”, and a cancelled order’s units may already be in someone else’s parcel.
A state machine this small does not need the State pattern: three values and one function say everything, and a class per state would add types with no behaviour of their own. See State for when that pattern pays.
The inventory
Section titled “The inventory”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Products, warehouses, the stock of each product in each warehouse, and the// reservations against that stock.//// Every public member function may be called from many threads at once. One// mutex guards all the data. A reservation can touch several products and// warehouses, and must take all of them or none; with one lock that is// simply "check everything, then change everything" while holding it. Locks// per product would let unrelated orders run in parallel, but a multi-line// order would then need several locks taken in a fixed order to avoid// deadlock, which is more to get right than this design needs.//// Low-stock alerts are collected while the lock is held and delivered after// it is released, on the thread that made the change. So the handler may// call back into the inventory, and a slow handler does not hold up other// orders. The handler must be safe to call from several threads at once and// must not throw (delivery is noexcept: by then the stock has changed and// the caller must still get its result).class Inventory {public: using AlertHandler = std::function<void(const LowStockAlert&)>;
explicit Inventory(AlertHandler on_low_stock = {});
// The mutex cannot be copied or moved, and neither can an inventory. Inventory(const Inventory&) = delete; Inventory& operator=(const Inventory&) = delete;
// Refuses an id already in use, and a negative threshold. A threshold of // 0 means "never alert" (available cannot drop below 0). Result<ProductId> add_product(ProductId id, std::string name, int low_stock_threshold); Result<WarehouseId> add_warehouse(WarehouseId id);
// Stock arrives: on hand goes up. Returns the new level. Result<StockLevel> receive(const ProductId& product, const WarehouseId& warehouse, int quantity);
// Sets stock aside for every line of an order, or for none of them. Result<ReservationId> reserve(const std::vector<OrderLine>& lines); // The order shipped: on hand and reserved both fall by each line. // Repeating it is a success that changes nothing. Result<ReservationState> commit(const ReservationId& id); // The order was cancelled: reserved falls, so available rises. // Repeating it is a success that changes nothing. Result<ReservationState> release(const ReservationId& id);
// Zero on hand and zero reserved for a pair that never received stock. [[nodiscard]] StockLevel level(const ProductId& product, const WarehouseId& warehouse) const; // A copy, so the caller never holds a reference into locked data. [[nodiscard]] std::optional<Reservation> reservation(const ReservationId& id) const;
// For tests: no count is negative, reserved never exceeds on hand, and // each count's reserved equals the sum of the held reservations on it. [[nodiscard]] bool invariants_hold() const;
private: struct Product { std::string name; int threshold; // Stock per warehouse. An entry appears the first time stock arrives. std::map<WarehouseId, StockLevel> stock; };
// The parts of reserve, commit, and release that run under the lock. Result<ReservationId> reserve_locked(const std::vector<OrderLine>& lines, std::vector<LowStockAlert>& alerts); Result<ReservationState> finish(const ReservationId& id, ReservationState target);
// nullptr if the pair has never received stock. Lookups by reference: // they copy no id, so they cannot throw. [[nodiscard]] StockLevel* find_level(const ProductId& product, const WarehouseId& warehouse); [[nodiscard]] const StockLevel* find_level(const ProductId& product, const WarehouseId& warehouse) const; void deliver(const std::vector<LowStockAlert>& alerts) const noexcept;
// Set once by the constructor and never changed, so reading it outside // the lock is safe. const AlertHandler on_low_stock_;
mutable std::mutex mutex_; // guards everything below std::map<ProductId, Product> products_; std::set<WarehouseId> warehouses_; std::map<ReservationId, Reservation> reservations_; std::uint64_t next_reservation_ = 1;};The comment at the top is the class’s thread-safety contract, and it is worth reading as a design decision, not as a detail.
One mutex for everything. Every public member function holds
mutex_ for all of its work on the data; only checks that read no
data (an empty order, a negative threshold) and the delivery of alerts
happen outside it. The reason is the multi-line order. An
order for a mug in Leeds and a lamp in Leeds touches two counts, and
FR-3 says both or neither. With one lock, “check every line, then
change every line” is simply what happens inside one locked function;
no other thread can slip between the check and the change.
What finer locking would cost. A mutex per product (or per count)
would let unrelated orders run at the same time, which pays when many
threads spend most of their time waiting for the one lock. But a
two-line order would then need two locks, and two orders taking the
same two locks in opposite order can each hold one and wait for the
other for ever: a deadlock.
The fix is known (take them together with std::scoped_lock, or in a
fixed order, as in
Deadlocks and lock ordering), but it is more to
get right, and it buys nothing until measurements show the one lock is
the bottleneck. Every operation here is a few map lookups and
additions, so the lock is held for a very short time.
Why not std::atomic<int> counts? An atomic keeps one number
correct. Here two numbers must agree (reserved never above on hand),
and an order must change several counts together. Atomics cannot make
several changes indivisible; a mutex can. See
Values that must agree: one mutex.
Step 4 of the framework: Implementation
Section titled “Step 4 of the framework: Implementation”Two counts, not one
Section titled “Two counts, not one”The first decision is the one the whole design rests on: each product in each warehouse keeps two numbers, on hand and reserved. It is tempting to keep one.
Receiving stock
Section titled “Receiving stock”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Result<StockLevel> Inventory::receive(const ProductId& product, const WarehouseId& warehouse, int quantity) { const std::lock_guard lock(mutex_); const auto found = products_.find(product); if (found == products_.end()) { return Refusal{Reason::unknown_product, "no product " + product.value()}; } if (!warehouses_.contains(warehouse)) { return Refusal{Reason::unknown_warehouse, "no warehouse " + warehouse.value()}; } if (quantity <= 0) return Refusal{Reason::bad_quantity, "receive a positive quantity"};
const StockLevel* current = find_level(product, warehouse); const int on_hand = current != nullptr ? current->on_hand : 0; // Written as a subtraction because on_hand + quantity could itself // overflow, and signed overflow is undefined behaviour. if (quantity > std::numeric_limits<int>::max() - on_hand) { return Refusal{Reason::would_overflow, "too much " + describe(product, warehouse)}; } // operator[] creates a zero level the first time this pair gets stock. // That may throw (it allocates), but nothing has changed yet. StockLevel& level = found->second.stock[warehouse]; level.on_hand += quantity; // Receiving raises available, so it can never cross below a threshold. return level;}Each public function starts the same way: take the lock, check everything, and only then change anything. Two details are worth noticing.
- The overflow check is a subtraction.
on_hand + quantity > maxwould itself overflow when the sum is too large, and signed overflow in C++ is undefined behaviour, not a wrap-around.quantity > max - on_handasks the same question with numbers that always fit. stock[warehouse]may throw, because the first delivery of a product to a warehouse creates itsStockLevelin the map, and that allocates. It is the only step that can fail, and it comes before the one line that changes a count, so a failure leaves nothing half done.
Reserving: check, prepare, apply
Section titled “Reserving: check, prepare, apply”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Result<ReservationId> Inventory::reserve(const std::vector<OrderLine>& lines) { std::vector<LowStockAlert> alerts; // reserve_locked takes the lock and releases it when it returns, so the // alerts below are delivered with no lock held. Result<ReservationId> result = reserve_locked(lines, alerts); deliver(alerts); return result;}
// Three phases. Check: refuse without changing anything. Prepare: do all the// work that needs memory (and so may throw std::bad_alloc). Apply: change the// counts, which cannot throw. So the order is reserved in full or not at all,// even if memory runs out.Result<ReservationId> Inventory::reserve_locked(const std::vector<OrderLine>& lines, std::vector<LowStockAlert>& alerts) { if (lines.empty()) return Refusal{Reason::empty_order, "an order needs at least one line"}; const std::lock_guard lock(mutex_);
// 1. Check every line. Lines for the same product and warehouse are // added together, because they draw on the same count. std::map<std::pair<ProductId, WarehouseId>, int> wanted; for (const OrderLine& line : lines) { if (!products_.contains(line.product)) { return Refusal{Reason::unknown_product, "no product " + line.product.value()}; } if (!warehouses_.contains(line.warehouse)) { return Refusal{Reason::unknown_warehouse, "no warehouse " + line.warehouse.value()}; } if (line.quantity <= 0) return Refusal{Reason::bad_quantity, "order a positive quantity"}; const StockLevel* level = find_level(line.product, line.warehouse); const int available = level != nullptr ? level->available() : 0; // operator[] starts the total at 0 the first time a pair appears. int& total = wanted[{line.product, line.warehouse}]; // Not "total + quantity > available": total never exceeds available, // so this subtraction cannot overflow, while that sum could. if (line.quantity > available - total) { return Refusal{Reason::not_enough_available, describe(line.product, line.warehouse) + ": only " + std::to_string(available) + " available"}; } total += line.quantity; }
// 2. Prepare: build the reservation, find each count, and decide the // alerts, all before the first count changes. struct Change { StockLevel* level; int quantity; }; std::vector<Change> changes; changes.reserve(wanted.size()); Reservation reservation{ReservationId{next_reservation_}, {}, ReservationState::held}; reservation.lines.reserve(wanted.size()); // Structured bindings: `key` is the {product, warehouse} pair, split // again into its two halves on the next line. for (const auto& [key, quantity] : wanted) { const auto& [product, warehouse] = key; reservation.lines.push_back(OrderLine{product, warehouse, quantity}); // Not null: quantity > 0 passed the check, so available was above 0, // so this pair has received stock. StockLevel* level = find_level(product, warehouse); changes.push_back(Change{level, quantity}); // Alert once per crossing: when available goes from at or above the // threshold to below it. Further drops while already below do not // alert again; once stock rises back to the threshold (a release or // a delivery), the next drop alerts again. No flag is needed: the // check told us the count before and after, under the same lock. const int threshold = products_.find(product)->second.threshold; const int before = level->available(); const int after = before - quantity; if (before >= threshold && after < threshold) { alerts.push_back(LowStockAlert{product, warehouse, after, threshold}); } } const ReservationId id = reservation.id; reservations_.emplace(id, std::move(reservation)); // may throw; nothing changed yet
// 3. Apply. Nothing from here on allocates or throws. ++next_reservation_; for (const Change& change : changes) change.level->reserved += change.quantity; return id;}reserve is the heart of the design. It is split in two:
reserve_locked does the work under the lock and collects alerts
into a vector; reserve delivers them after the lock is released.
Inside reserve_locked there are three phases.
- Check. Every line is checked before anything changes. Lines for
the same product and warehouse are added together in
wanted, so an order of “2 mugs, 3 mugs” against 4 mugs is refused (AC-2.3). The first line that does not fit ends the call with a refusal, and nothing has changed. - Prepare. Everything that needs memory happens here: the list of
changes, the reservation’s lines, the alerts, and finally inserting
the reservation into
reservations_. Any of these may throwstd::bad_alloc, and if one does, still nothing has changed. - Apply. Add to the counts and move the id counter on. These are
additions to
intvalues that the check has already proved fit, so nothing here can fail.
That order is what makes FR-3 hold even when memory runs out: an order is reserved in full or not at all. It is the “prepare, then commit with no-throw steps” recipe from The strong guarantee by prepare, record, commit. If the counts were changed line by line as the check went, a refusal or an exception on the third line would leave the first two reserved.
How this code works: Trace: orders B and C in the step 1 demo
Before order B, mug in Leeds has on hand 12 and reserved 4 (order A), so available is 8. Lamp has on hand 3, reserved 1, available 2. The mug threshold is 5. The next reservation id is 2.
Order B: 4 mugs.
| Phase | What happens | Values |
|---|---|---|
| check | line mug 4: available 8, total so far 0; is 4 > 8 - 0? No | wanted = mug 4 |
| prepare | reservation 2 gets the line mug 4 | change: mug level, 4 |
| prepare | before = 8, after = 8 - 4 = 4; 8 >= 5 and 4 < 5, so a crossing | alert: mug, leeds, 4, threshold 5 |
| prepare | insert reservation 2 (this may throw; nothing has changed yet) | reservations_ has 1 and 2 |
| apply | next id 2 → 3; mug reserved 4 → 8 | mug 12 / 8 / available 4 |
| deliver | the lock is gone; the handler prints the alert | ALERT: mug in leeds is down to 4 (threshold 5) |
The alert is printed before the demo’s line order B (4 mugs): ok, reservation 2, because the demo prints its report after reserve
returns, and reserve delivers alerts before returning.
Order C: 1 mug, 5 lamps.
| Phase | What happens | Values |
|---|---|---|
| check | line mug 1: available 4, total 0; is 1 > 4 - 0? No | wanted = mug 1 |
| check | line lamp 5: available 2, total 0; is 5 > 2 - 0? Yes: refuse | lamp in leeds: only 2 available |
| — | prepare and apply never run | mug still 12 / 8 / 4, next id still 3 |
The mug line fitted, but the order as a whole did not, so no mug was reserved either. That is AC-2.2.
One lock for the check and the change
Section titled “One lock for the check and the change”Each public function takes the lock once, and holds it from the first check that reads the data to the last change. Splitting the two is the classic race.
Low-stock alerts, once per crossing
Section titled “Low-stock alerts, once per crossing”The rule is in the prepare phase: alert when available goes from at or above the threshold to below it. Lamp, threshold 2: from 2 to 1 is a crossing and alerts; from 1 to 0 is a further drop and does not. When a release or a delivery brings available back to 2 or more, the next drop below 2 is a new crossing and alerts again (AC-5.3).
No “already alerted” flag is needed, because every change that lowers available is a reservation, and the reservation sees before and after under one lock. Commit cannot lower available (on hand and reserved fall together), and release and receive only raise it.
Delivering alerts with no lock held
Section titled “Delivering alerts with no lock held”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Runs with no lock held, on the thread that made the change. noexcept: if// the handler throws, the program stops (std::terminate) rather than lose a// change the caller has not yet been told about.void Inventory::deliver(const std::vector<LowStockAlert>& alerts) const noexcept { if (!on_low_stock_) return; // no handler was given for (const LowStockAlert& alert : alerts) on_low_stock_(alert);}The alert handler is code the inventory does not know. It might send an email, write to a queue, or, as test AC-5.7 does, call back into the inventory to read the level. So it runs after the lock is released.
deliver is noexcept. If the handler throws, the program stops with
std::terminate. That sounds harsh, but the alternative is worse: the
reservation has already been made, and an exception escaping reserve
would tell the caller it failed. The caller might retry and reserve
twice. A handler that can fail must catch its own errors.
Commit and release
Section titled “Commit and release”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Commit and release differ only in the target state and in whether on hand// falls too. Neither can cause an alert: commit lowers on hand and reserved// by the same amount, so available stays the same, and release raises it.Result<ReservationState> Inventory::finish(const ReservationId& id, ReservationState target) { const std::lock_guard lock(mutex_); const auto found = reservations_.find(id); if (found == reservations_.end()) { return Refusal{Reason::unknown_reservation, "no " + name_of(id)}; } Reservation& reservation = found->second; switch (classify(reservation.state, target)) { case Move::repeat: return reservation.state; // done before: succeed, change nothing case Move::illegal: if (reservation.state == ReservationState::committed) { return Refusal{Reason::already_committed, name_of(id) + " has shipped"}; } return Refusal{Reason::already_released, name_of(id) + " was released"}; case Move::apply: break; } // The reservation is held, so each of its lines is still counted in the // reserved of a level that exists. The subtractions therefore keep // 0 <= reserved <= on_hand. Nothing here allocates or throws. for (const OrderLine& line : reservation.lines) { StockLevel* level = find_level(line.product, line.warehouse); level->reserved -= line.quantity; if (target == ReservationState::committed) level->on_hand -= line.quantity; } reservation.state = target; return target;}commit and release both call finish, which differs only in the
target state and in whether on hand falls. The switch over classify
is the state machine from Step 3, and the compiler warns if a Move
is ever added and not handled. After the switch, the subtractions
cannot fail: a held reservation’s lines are still counted in reserved,
so reserved never goes below 0.
How this code works: Trace: commit A, commit A again, release B, commit B, release 99
Before: mug 12 on hand, 8 reserved (4 for A, 4 for B), available 4.
Lamp 3 on hand, 1 reserved (A), available 2. Reservation 1 (A) holds
lamp 1 and mug 4, in that order, because wanted sorts “lamp” before
“mug”. Reservation 2 (B) holds mug 4.
| Call | classify(from, to) |
What changes | Result |
|---|---|---|---|
commit(1) |
held → committed: apply | lamp reserved 1 → 0, on hand 3 → 2; mug reserved 8 → 4, on hand 12 → 8 | ok, committed |
commit(1) |
committed → committed: repeat | nothing | ok, committed |
release(2) |
held → released: apply | mug reserved 4 → 0; available 4 → 8 | ok, released |
commit(2) |
released → committed: illegal | nothing | refused, already released |
release(99) |
not called: no reservation 99 | nothing | refused, unknown reservation |
After: mug 8 / 0 / 8, lamp 2 / 0 / 2. The commit kept available the same (4 for mug, 2 for lamp) while lowering the shelf; the release raised mug from 4 to 8, back above its threshold of 5, so the next drop below 5 will alert again. Neither call sent an alert.
Where each rule lives
Section titled “Where each rule lives”| Rule | Lives in | Checked by |
|---|---|---|
INV-1 0 <= reserved <= on_hand |
the checks in receive, reserve_locked, and finish |
invariants_hold, AC-4.1 |
| INV-2 reserved adds up to the held lines | the apply phases of reserve_locked and finish |
invariants_hold, AC-4.1 |
| INV-3 a reservation moves forward only | classify, used by finish |
AC-3.3 to AC-3.7 |
| INV-4 all or nothing | check, prepare, apply in reserve_locked; check before change elsewhere |
AC-2.2, AC-4.1 |
| INV-5 one alert per crossing | the prepare phase of reserve_locked |
AC-5.1 to AC-5.6, AC-6.1 |
| Unique reservation ids | next_reservation_, moved on only in apply |
AC-2.6 |
| No lock held for the handler | reserve calls deliver after reserve_locked |
AC-5.7 |
Verification trace
Section titled “Verification trace”The demo’s last section is a real race: eight threads wait at a
std::latch and then each try to reserve one lamp, with 2 lamps
available and a threshold of 2. Whatever order the threads run in, the
lock lets them in one at a time:
| Turn | Before (available) | Check | After | Alert? |
|---|---|---|---|---|
| first in | 2 | 1 ≤ 2: reserve | 1 | yes: 2 ≥ 2 and 1 < 2 |
| second in | 1 | 1 ≤ 1: reserve | 0 | no: 1 is already below 2 |
| six others | 0 | 1 > 0: refuse | 0 | no: nothing changed |
So the demo prints one alert (lamp down to 1), 2 winners, and lamp 2 on hand, 2 reserved, 0 available, every time. Which two threads win changes from run to run; how many win does not, and the demo prints only how many.
Building it step by step
Section titled “Building it step by step”The example has two steps, each a complete program with its own tests:
- Step 1 is the design above: two counts, all-or-nothing reservations, commit and release that are safe to repeat, alerts once per crossing, one mutex.
- Step 2 is the change: batches with expiry dates, and transfers between warehouses. See Step 5.
How the code on this page was checked. The code shown from the
example files is built and tested on four presets (GCC, Clang,
AddressSanitizer with UndefinedBehaviorSanitizer, and
ThreadSanitizer), and each demo’s output is compared with the output
shown below it. The short sketches written into this page (the flawed
designs and their corrections) were checked only for compiling: all of
them, put in one file, compile with g++ 11.4 and clang++ 14 using
-std=c++20 -Wall -Wextra -fsyntax-only, with no warnings. They were
not run, except the dangling-reference sketch, which was run under
AddressSanitizer as described in Step 3.
A good order for building step 1 yourself: the ids and Result
first, then StockLevel and classify with their tests (no threads,
no maps). Then receive and a reserve for one line, then whole
orders, then finish. Then invariants_hold and the random test,
which checks every operation against a model and so tends to catch a
mistake at the step that made it. Alerts come after the counts are
right, and real threads last, once the single-thread behaviour is
pinned down by tests.
The step 1 demo
Section titled “The step 1 demo”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// CS-18 step 1 demo: receive stock, reserve an order, ship one and cancel// another, see the refusals and the low-stock alert, then let eight threads// race for the last two lamps. Everything printed is deterministic: the race// prints how many won, which is always two, and its one alert.
#include <atomic>#include <iostream>#include <latch>#include <thread>#include <vector>
#include "inventory.hpp"
using namespace inventory;
namespace {
void show(const Inventory& store, const ProductId& product, const WarehouseId& warehouse) { const StockLevel level = store.level(product, warehouse); std::cout << " " << product.value() << " in " << warehouse.value() << ": on hand " << level.on_hand << ", reserved " << level.reserved << ", available " << level.available() << '\n';}
// Prints "ok: <what>" or "refused (<reason>): <text>".template <typename T, typename Print>void report(const char* label, const Result<T>& result, Print print) { std::cout << label << ": "; if (result.ok()) { std::cout << "ok, "; print(result.value()); } else { std::cout << "refused (" << to_string(result.reason()) << "): " << result.refusal().text; } std::cout << '\n';}
void print_id(const ReservationId& id) { std::cout << "reservation " << id.value(); }void print_state(ReservationState state) { std::cout << to_string(state); }
} // namespace
int main() { // The handler runs after each change, with no lock held. Here it prints. Inventory store{[](const LowStockAlert& alert) { std::cout << " ALERT: " << alert.product.value() << " in " << alert.warehouse.value() << " is down to " << alert.available << " (threshold " << alert.threshold << ")\n"; }}; const ProductId mug{"mug"}; const ProductId lamp{"lamp"}; const WarehouseId leeds{"leeds"}; static_cast<void>(store.add_product(mug, "Blue mug", 5)); static_cast<void>(store.add_product(lamp, "Desk lamp", 2)); static_cast<void>(store.add_warehouse(leeds));
std::cout << "== receive\n"; static_cast<void>(store.receive(mug, leeds, 12)); static_cast<void>(store.receive(lamp, leeds, 3)); show(store, mug, leeds); show(store, lamp, leeds);
std::cout << "== reserve\n"; const Result<ReservationId> first = store.reserve({{mug, leeds, 4}, {lamp, leeds, 1}}); report("order A (4 mugs, 1 lamp)", first, print_id); const Result<ReservationId> second = store.reserve({{mug, leeds, 4}}); report("order B (4 mugs)", second, print_id); report("order C (1 mug, 5 lamps)", store.reserve({{mug, leeds, 1}, {lamp, leeds, 5}}), print_id); show(store, mug, leeds); show(store, lamp, leeds);
std::cout << "== commit A, release B\n"; report("commit A", store.commit(first.value()), print_state); report("commit A again", store.commit(first.value()), print_state); report("release B", store.release(second.value()), print_state); report("commit B", store.commit(second.value()), print_state); report("release 99", store.release(ReservationId{99}), print_state); show(store, mug, leeds); show(store, lamp, leeds);
std::cout << "== eight threads race for the last 2 lamps\n"; std::atomic<int> winners{0}; { constexpr int threads = 8; std::latch start_together(threads); std::vector<std::jthread> pool; for (int t = 0; t < threads; ++t) { pool.emplace_back([&store, &lamp, &leeds, &winners, &start_together] { start_together.arrive_and_wait(); if (store.reserve({{lamp, leeds, 1}}).ok()) ++winners; }); } } // the jthreads join here // Two lamps were left after order A shipped one, so two threads won. The // one that took available from 2 to 1 (below the threshold of 2) printed // the alert above, from its own thread, before the joins. std::cout << " winners: " << winners.load() << '\n'; show(store, lamp, leeds); std::cout << "invariants hold: " << (store.invariants_hold() ? "yes" : "no") << '\n';}== receive mug in leeds: on hand 12, reserved 0, available 12 lamp in leeds: on hand 3, reserved 0, available 3== reserveorder A (4 mugs, 1 lamp): ok, reservation 1 ALERT: mug in leeds is down to 4 (threshold 5)order B (4 mugs): ok, reservation 2order C (1 mug, 5 lamps): refused (not enough available): lamp in leeds: only 2 available mug in leeds: on hand 12, reserved 8, available 4 lamp in leeds: on hand 3, reserved 1, available 2== commit A, release Bcommit A: ok, committedcommit A again: ok, committedrelease B: ok, releasedcommit B: refused (already released): reservation 2 was releasedrelease 99: refused (unknown reservation): no reservation 99 mug in leeds: on hand 8, reserved 0, available 8 lamp in leeds: on hand 2, reserved 0, available 2== eight threads race for the last 2 lamps ALERT: lamp in leeds is down to 1 (threshold 2) winners: 2 lamp in leeds: on hand 2, reserved 2, available 0invariants hold: yesRead the output against the rules:
- Order A takes mug from 12 to 8 available and lamp from 3 to 2. Neither goes below its threshold (5 and 2), so there is no alert.
- Order B takes mug from 8 to 4: a crossing, so one alert, printed before the line about order B.
- Order C is refused as a whole, and its mug line is not reserved.
- Commit A again succeeds and changes nothing: the retry is safe.
- Commit B after release is refused with
already released, the reason a caller can act on. - The race has exactly 2 winners and one alert, and the invariants hold at the end.
Step 1 tests
Section titled “Step 1 tests”Step 1 has 28 tests, in step-1/tests/test_step1.cpp, named after the
acceptance criteria. They share a small fixture:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An inventory with two products and two warehouses, and a record of every// alert it sent. Alerts may arrive from several threads at once, so the// record has a mutex of its own. The record is declared before the// inventory, so it is destroyed after it: the handler never sees a dead// vector.struct World { std::mutex alerts_mutex; std::vector<LowStockAlert> alerts; Inventory inventory{[this](const LowStockAlert& alert) { const std::lock_guard lock(alerts_mutex); alerts.push_back(alert); }};
explicit World(int apple_threshold = 3, int pear_threshold = 0) { LLD_CHECK(inventory.add_product(apple, "Apple", apple_threshold).ok()); LLD_CHECK(inventory.add_product(pear, "Pear", pear_threshold).ok()); LLD_CHECK(inventory.add_warehouse(north).ok()); LLD_CHECK(inventory.add_warehouse(south).ok()); }
// Stock arrives. (Step 2 changes only this helper: it adds a date.) void receive(const ProductId& product, const WarehouseId& warehouse, int quantity) { LLD_CHECK(inventory.receive(product, warehouse, quantity).ok()); LLD_CHECK(inventory.invariants_hold()); } Result<ReservationId> reserve(const std::vector<OrderLine>& lines) { Result<ReservationId> result = inventory.reserve(lines); LLD_CHECK(inventory.invariants_hold()); return result; } Result<ReservationState> commit(const ReservationId& id) { Result<ReservationState> result = inventory.commit(id); LLD_CHECK(inventory.invariants_hold()); return result; } Result<ReservationState> release(const ReservationId& id) { Result<ReservationState> result = inventory.release(id); LLD_CHECK(inventory.invariants_hold()); return result; } // By value: LLD_CHECK_EQ keeps a reference to what it is given, and a // reference into the temporary std::optional would dangle. [[nodiscard]] ReservationState state(const ReservationId& id) const { return inventory.reservation(id).value().state; } [[nodiscard]] int available(const ProductId& product, const WarehouseId& warehouse) const { return inventory.level(product, warehouse).available(); } [[nodiscard]] std::size_t alert_count() { const std::lock_guard lock(alerts_mutex); return alerts.size(); }};The reserve tests check the all-or-nothing rule and the adding together of lines:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_2_1_reserving_sets_stock_aside_without_removing_it) { World world; world.receive(apple, north, 10); const Result<ReservationId> id = world.reserve({{apple, north, 4}}); LLD_CHECK(id.ok()); const StockLevel level = world.inventory.level(apple, north); LLD_CHECK_EQ(level.on_hand, 10); // still on the shelf LLD_CHECK_EQ(level.reserved, 4); LLD_CHECK_EQ(level.available(), 6); LLD_CHECK_EQ(world.state(id.value()), ReservationState::held);}
LLD_TEST(ac_2_2_an_order_is_reserved_in_full_or_not_at_all) { World world; world.receive(apple, north, 10); world.receive(pear, south, 2); // The apple line could be met, the pear line cannot: nothing is reserved. const Result<ReservationId> refused = world.reserve({{apple, north, 3}, {pear, south, 5}}); LLD_CHECK(!refused.ok()); LLD_CHECK_EQ(refused.reason(), Reason::not_enough_available); LLD_CHECK_EQ(world.inventory.level(apple, north).reserved, 0); LLD_CHECK_EQ(world.inventory.level(pear, south).reserved, 0); // Both lines met: both reserved. LLD_CHECK(world.reserve({{apple, north, 3}, {pear, south, 2}}).ok()); LLD_CHECK_EQ(world.inventory.level(apple, north).reserved, 3); LLD_CHECK_EQ(world.inventory.level(pear, south).reserved, 2);}
LLD_TEST(ac_2_3_lines_for_the_same_stock_are_added_together) { World world; world.receive(apple, north, 5); // 3 + 3 > 5, though each line alone would fit. LLD_CHECK_EQ(world.reserve({{apple, north, 3}, {apple, north, 3}}).reason(), Reason::not_enough_available); LLD_CHECK_EQ(world.inventory.level(apple, north).reserved, 0); const Result<ReservationId> id = world.reserve({{apple, north, 2}, {apple, north, 3}}); LLD_CHECK(id.ok()); LLD_CHECK_EQ(world.inventory.level(apple, north).reserved, 5); // Kept as one merged line. const std::vector<OrderLine> lines = world.inventory.reservation(id.value())->lines; LLD_CHECK_EQ(lines.size(), std::size_t{1}); LLD_CHECK_EQ(lines.front().quantity, 5);}The finish tests check each arrow of the state machine, including the repeats:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_3_1_commit_ships_the_stock) { World world; world.receive(apple, north, 10); const ReservationId id = world.reserve({{apple, north, 4}}).value(); LLD_CHECK_EQ(world.commit(id).value(), ReservationState::committed); const StockLevel level = world.inventory.level(apple, north); LLD_CHECK_EQ(level.on_hand, 6); // gone from the shelf LLD_CHECK_EQ(level.reserved, 0); LLD_CHECK_EQ(level.available(), 6); // the same as while it was held}
LLD_TEST(ac_3_2_release_frees_the_stock) { World world; world.receive(apple, north, 10); const ReservationId id = world.reserve({{apple, north, 4}}).value(); LLD_CHECK_EQ(world.release(id).value(), ReservationState::released); const StockLevel level = world.inventory.level(apple, north); LLD_CHECK_EQ(level.on_hand, 10); LLD_CHECK_EQ(level.reserved, 0); LLD_CHECK_EQ(level.available(), 10);}
LLD_TEST(ac_3_3_commit_twice_ships_once) { World world; world.receive(apple, north, 10); const ReservationId id = world.reserve({{apple, north, 4}}).value(); LLD_CHECK(world.commit(id).ok()); const Result<ReservationState> again = world.commit(id); LLD_CHECK(again.ok()); // a retry succeeds... LLD_CHECK_EQ(again.value(), ReservationState::committed); LLD_CHECK_EQ(world.inventory.level(apple, north).on_hand, 6); // ...and ships nothing more}
LLD_TEST(ac_3_4_release_twice_frees_once) { World world; world.receive(apple, north, 10); const ReservationId kept = world.reserve({{apple, north, 3}}).value(); const ReservationId id = world.reserve({{apple, north, 4}}).value(); LLD_CHECK(world.release(id).ok()); LLD_CHECK(world.release(id).ok()); // A second release must not free the 3 that `kept` still holds. LLD_CHECK_EQ(world.inventory.level(apple, north).reserved, 3); LLD_CHECK_EQ(world.state(kept), ReservationState::held);}
LLD_TEST(ac_3_5_a_finished_reservation_cannot_take_the_other_ending) { World world; world.receive(apple, north, 10); const ReservationId shipped = world.reserve({{apple, north, 2}}).value(); const ReservationId cancelled = world.reserve({{apple, north, 3}}).value(); LLD_CHECK(world.commit(shipped).ok()); LLD_CHECK(world.release(cancelled).ok()); LLD_CHECK_EQ(world.release(shipped).reason(), Reason::already_committed); LLD_CHECK_EQ(world.commit(cancelled).reason(), Reason::already_released); LLD_CHECK_EQ(world.state(shipped), ReservationState::committed); LLD_CHECK_EQ(world.state(cancelled), ReservationState::released); const StockLevel level = world.inventory.level(apple, north); LLD_CHECK_EQ(level.on_hand, 8); LLD_CHECK_EQ(level.reserved, 0);}The random test runs 4,000 operations from a fixed seed, so every run is the same. After each one, the inventory’s own invariants must hold, and its counts must match a simple model kept in the test: on hand is what was received minus what shipped, and reserved is what the held reservations hold:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 4,000 random operations from a fixed seed (so every run is the same). After// each one the inventory's own invariants must hold, and its counts must match// a simple model kept here: on hand = received - shipped, reserved = what the// held reservations hold.LLD_TEST(ac_4_1_random_operations_keep_every_invariant) { World world(5, 2); std::mt19937 random(2026); const std::vector<ProductId> products{apple, pear}; const std::vector<WarehouseId> warehouses{north, south}; std::map<std::pair<ProductId, WarehouseId>, StockLevel> model; std::vector<ReservationId> ids; // A number from 0 to n - 1. auto pick = [&random](int n) { return std::uniform_int_distribution<int>(0, n - 1)(random); }; for (int step = 0; step < 4000; ++step) { const ProductId& product = products[static_cast<std::size_t>(pick(2))]; const WarehouseId& warehouse = warehouses[static_cast<std::size_t>(pick(2))]; StockLevel& expected = model[{product, warehouse}]; switch (pick(4)) { case 0: { const int quantity = 1 + pick(6); world.receive(product, warehouse, quantity); expected.on_hand += quantity; break; } case 1: { const int quantity = 1 + pick(4); const Result<ReservationId> id = world.reserve({{product, warehouse, quantity}}); // It must succeed exactly when the model says there is enough. LLD_CHECK_EQ(id.ok(), quantity <= expected.available()); if (id.ok()) { expected.reserved += quantity; ids.push_back(id.value()); } break; } default: { // commit or release a random earlier reservation if (ids.empty()) break; const auto which = static_cast<std::size_t>(pick(static_cast<int>(ids.size()))); const ReservationId id = ids[which]; const Reservation before = *world.inventory.reservation(id); const bool commit = pick(2) == 0; const Result<ReservationState> result = commit ? world.commit(id) : world.release(id); const ReservationState target = commit ? ReservationState::committed : ReservationState::released; // Legal or a repeat: success. The other ending: refused. LLD_CHECK_EQ(result.ok(), classify(before.state, target) != Move::illegal); if (before.state == ReservationState::held) { StockLevel& line = model[{before.lines[0].product, before.lines[0].warehouse}]; line.reserved -= before.lines[0].quantity; if (commit) line.on_hand -= before.lines[0].quantity; } break; } } for (const auto& [key, level] : model) { const StockLevel actual = world.inventory.level(key.first, key.second); LLD_CHECK_EQ(actual.on_hand, level.on_hand); LLD_CHECK_EQ(actual.reserved, level.reserved); } }}The alert tests pin down “once per crossing”, including the handler that calls back into the inventory (AC-5.7). If the handler ran under the lock, that test would never finish:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_5_1_an_alert_fires_when_available_drops_below_the_threshold) { World world; // apple threshold 3 world.receive(apple, north, 10); LLD_CHECK(world.reserve({{apple, north, 7}}).ok()); // available 3: not below 3 LLD_CHECK_EQ(world.alert_count(), std::size_t{0}); LLD_CHECK(world.reserve({{apple, north, 1}}).ok()); // available 2: below LLD_CHECK_EQ(world.alert_count(), std::size_t{1}); const LowStockAlert& alert = world.alerts.front(); LLD_CHECK(alert.product == apple); LLD_CHECK(alert.warehouse == north); LLD_CHECK_EQ(alert.available, 2); LLD_CHECK_EQ(alert.threshold, 3);}
LLD_TEST(ac_5_2_no_second_alert_while_still_below) { World world; world.receive(apple, north, 10); LLD_CHECK(world.reserve({{apple, north, 8}}).ok()); // 2: alert LLD_CHECK(world.reserve({{apple, north, 1}}).ok()); // 1: still below LLD_CHECK(world.reserve({{apple, north, 1}}).ok()); // 0: still below LLD_CHECK_EQ(world.alert_count(), std::size_t{1});}
LLD_TEST(ac_5_3_rising_back_to_the_threshold_rearms_the_alert) { World world; world.receive(apple, north, 10); const ReservationId first = world.reserve({{apple, north, 8}}).value(); // 2: alert 1 LLD_CHECK(world.release(first).ok()); // 10: re-armed LLD_CHECK(world.reserve({{apple, north, 9}}).ok()); // 1: alert 2 world.receive(apple, north, 5); // 6: re-armed LLD_CHECK(world.reserve({{apple, north, 4}}).ok()); // 2: alert 3 LLD_CHECK_EQ(world.alert_count(), std::size_t{3});}
LLD_TEST(ac_5_4_commit_and_refusals_send_no_alert) { World world; world.receive(apple, north, 10); const ReservationId id = world.reserve({{apple, north, 6}}).value(); // 4: no alert LLD_CHECK(world.commit(id).ok()); // on hand 4, available still 4 LLD_CHECK(!world.reserve({{apple, north, 9}}).ok()); LLD_CHECK_EQ(world.alert_count(), std::size_t{0});}
LLD_TEST(ac_5_5_a_threshold_of_zero_never_alerts) { World world; // pear threshold 0 world.receive(pear, north, 3); LLD_CHECK(world.reserve({{pear, north, 3}}).ok()); LLD_CHECK_EQ(world.alert_count(), std::size_t{0});}
LLD_TEST(ac_5_6_one_order_alerts_once_for_each_count_it_takes_below) { World world(3, 3); world.receive(apple, north, 4); world.receive(pear, south, 4); LLD_CHECK(world.reserve({{apple, north, 2}, {pear, south, 3}, {apple, north, 1}}).ok()); LLD_CHECK_EQ(world.alert_count(), std::size_t{2});}
// The handler calls back into the inventory. If the alert were delivered// while the lock was held, that call would deadlock (std::mutex is not// recursive). It also sees the change already made.LLD_TEST(ac_5_7_the_handler_runs_after_the_change_with_no_lock_held) { Inventory* self = nullptr; int seen = -1; // The lambda captures by reference; `self` is set before any alert fires. Inventory inventory{[&self, &seen](const LowStockAlert& alert) { seen = self->level(alert.product, alert.warehouse).available(); }}; self = &inventory; LLD_CHECK(inventory.add_product(apple, "Apple", 3).ok()); LLD_CHECK(inventory.add_warehouse(north).ok()); LLD_CHECK(inventory.receive(apple, north, 5).ok()); LLD_CHECK(inventory.reserve({{apple, north, 4}}).ok()); LLD_CHECK_EQ(seen, 1);}The thread tests use real threads:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Thirty-two threads wait at a latch, so they all try to reserve one apple at// the same moment, with five on the shelf. Exactly five may win, every round,// and the crossing below the threshold must alert exactly once.LLD_TEST(ac_6_1_many_threads_racing_for_the_last_units_have_exactly_the_right_winners) { constexpr int threads = 32; for (int round = 0; round < 50; ++round) { World world; // apple threshold 3 world.receive(apple, north, 5); std::vector<int> won(threads, 0); std::vector<int> wrong_refusal(threads, 0); { std::latch start_together(threads); std::vector<std::jthread> pool; for (int t = 0; t < threads; ++t) { // Each thread writes only its own elements, so the writes do // not race; the joins below make them visible here. pool.emplace_back([&world, &won, &wrong_refusal, &start_together, t] { start_together.arrive_and_wait(); const Result<ReservationId> id = world.inventory.reserve({{apple, north, 1}}); const auto slot = static_cast<std::size_t>(t); won[slot] = id.ok() ? 1 : 0; if (!id.ok() && id.reason() != Reason::not_enough_available) { wrong_refusal[slot] = 1; } }); } } // jthreads join here int winners = 0; int wrong = 0; for (int t = 0; t < threads; ++t) { winners += won[static_cast<std::size_t>(t)]; wrong += wrong_refusal[static_cast<std::size_t>(t)]; } LLD_CHECK_EQ(winners, 5); LLD_CHECK_EQ(wrong, 0); LLD_CHECK_EQ(world.inventory.level(apple, north).reserved, 5); LLD_CHECK_EQ(world.available(apple, north), 0); LLD_CHECK_EQ(world.alert_count(), std::size_t{1}); LLD_CHECK(world.inventory.invariants_hold()); }}
// Half the threads commit one reservation while the other half release it.// Exactly one ending wins: every call asking for it succeeds, every call// asking for the other is refused, and the stock moves once.LLD_TEST(ac_6_2_racing_commit_and_release_pick_one_ending) { constexpr int threads = 16; for (int round = 0; round < 50; ++round) { World world; world.receive(apple, north, 10); const ReservationId id = world.inventory.reserve({{apple, north, 4}}).value(); std::vector<int> ok(threads, 0); { std::latch start_together(threads); std::vector<std::jthread> pool; for (int t = 0; t < threads; ++t) { pool.emplace_back([&world, &ok, &start_together, &id, t] { start_together.arrive_and_wait(); const bool done = t % 2 == 0 ? world.inventory.commit(id).ok() : world.inventory.release(id).ok(); ok[static_cast<std::size_t>(t)] = done ? 1 : 0; }); } } const ReservationState ending = world.inventory.reservation(id)->state; LLD_CHECK(ending != ReservationState::held); const int winning_parity = ending == ReservationState::committed ? 0 : 1; for (int t = 0; t < threads; ++t) { LLD_CHECK_EQ(ok[static_cast<std::size_t>(t)], t % 2 == winning_parity ? 1 : 0); } const StockLevel level = world.inventory.level(apple, north); LLD_CHECK_EQ(level.on_hand, ending == ReservationState::committed ? 6 : 10); LLD_CHECK_EQ(level.reserved, 0); LLD_CHECK(world.inventory.invariants_hold()); }}
// Eight threads each run 300 orders of two lines that they then commit or// release. Afterwards on hand must equal what was received minus what the// threads shipped, and nothing may stay reserved.LLD_TEST(ac_6_3_orders_in_parallel_keep_the_counts_exact) { constexpr int threads = 8; World world; world.receive(apple, north, 1000); world.receive(pear, south, 1000); std::vector<int> shipped(threads, 0); { std::latch start_together(threads); std::vector<std::jthread> pool; for (int t = 0; t < threads; ++t) { pool.emplace_back([&world, &shipped, &start_together, t] { start_together.arrive_and_wait(); for (int i = 0; i < 300; ++i) { const int quantity = 1 + (i + t) % 2; const Result<ReservationId> id = world.inventory.reserve({{apple, north, quantity}, {pear, south, 1}}); if (!id.ok()) continue; // ran out: allowed, and counted as not shipped if (i % 3 == 0) { static_cast<void>(world.inventory.release(id.value())); } else if (world.inventory.commit(id.value()).ok()) { shipped[static_cast<std::size_t>(t)] += quantity; } } }); } } int total_shipped = 0; for (const int s : shipped) total_shipped += s; const StockLevel level = world.inventory.level(apple, north); LLD_CHECK_EQ(level.on_hand, 1000 - total_shipped); LLD_CHECK_EQ(level.reserved, 0); LLD_CHECK_EQ(world.inventory.level(pear, south).reserved, 0); LLD_CHECK(world.inventory.invariants_hold());}Two things make them useful rather than lucky.
- A latch.
std::latchmakes every thread wait until all of them have started, and then lets them go together. Without it, the first thread often finishes before the last one starts, and the “race” never happens. - Many rounds, exact answers. AC-6.1 and AC-6.2 repeat their race
50 times, and every test checks exact numbers: exactly 5 winners of 5
apples, every refusal for
not_enough_available, exactly one alert. A test that only checked “no crash” would pass for a broken design.
Passing these tests does not prove there is no race; a thread test can only show the races it happens to hit. The ThreadSanitizer build is the stronger check: it reports two threads touching the same memory without synchronization in the runs it watches, even when the result happened to be right.
Step 5 of the framework: Extensibility
Section titled “Step 5 of the framework: Extensibility”The change
Section titled “The change”Six months later, the shop starts selling food:
Milk and yoghurt have expiry dates. Each delivery arrives with its date, and we must send out the stock that expires first. Nothing past its date may be sold or shipped, and we need a list of what has expired so someone can clear the shelf. Also, we now move stock between warehouses: Leeds sends some to York when York runs low.
The answers to the questions this raises:
- Is a delivery’s stock kept together? Yes: a batch is one delivery of one product, with one expiry date. A warehouse’s stock of a product becomes a list of batches.
- When does stock expire? From the first moment of its date (UTC). Milk dated 4 December may be sold on 3 December, not on 4 December.
- What if an order is reserved and its batch expires before it ships? The shipment is refused. The order can be released, and the customer offered a new reservation from fresher stock.
- Who removes expired stock? A person, after a report. The inventory reports; it does not write stock off on its own.
- How long does a transfer take? For now, it is instant: stock leaves one warehouse and arrives at the other in one step. Lorries are out of scope.
- Which units move? The ones that expire first, as for orders, and never reserved or expired units.
Use cases for the change
Section titled “Use cases for the change”UC-7 Batches and expiry.
- AC-7.1 Each delivery is a batch, kept in expiry order.
- AC-7.2 Reserving takes the earliest expiry first (FEFO).
- AC-7.3 On the same date, the earlier delivery goes first.
- AC-7.4 Expired stock cannot be reserved.
- AC-7.5 A batch expires at the start of its date.
- AC-7.6 A delivery already past its date is refused.
- AC-7.7
review_expiryreports expired batches still on hand. - AC-7.8 Stock that expired after it was reserved cannot ship, but can be released.
- AC-7.9 A commit is refused whole if any of its batches expired.
- AC-7.10 Shipping a whole batch removes it.
- AC-7.11 Expiry alone alerts, through
review_expiry, once. - AC-7.12 A drop after an unnoticed expiry alerts once.
- AC-7.13 Releasing expired stock does not re-arm the alert.
UC-8 Transfers.
- AC-8.1 A transfer moves stock and keeps the total.
- AC-8.2 It moves the earliest expiry first, keeping batch ids and dates.
- AC-8.3 Stock moving back rejoins its batch.
- AC-8.4 Reserved and expired stock does not move.
- AC-8.5 Bad transfers are refused and change nothing.
- AC-8.6 A transfer that would overflow is refused.
- AC-8.7 A transfer out can alert, and a transfer in re-arms.
- AC-8.8 A transfer can empty a warehouse.
UC-9 Many threads, with transfers and time.
- AC-9.1 Transfers both ways at once never deadlock or change the total.
- AC-9.2 Reserves and transfers racing for the last units: exactly the right number succeed.
- AC-9.3 Orders, transfers, and reviews while the clock moves keep every invariant.
Every step 1 criterion still holds, and step 2’s tests repeat them: step 2 has 52 tests, step 1’s 28 adapted to batches and 24 new ones.
What moved
Section titled “What moved”| Step 1 | Step 2 | Why |
|---|---|---|
StockLevel with on hand and reserved, stored |
a Cell with a std::vector<Batch>; StockLevel is now a summary, worked out |
each delivery keeps its own date |
| available = on hand − reserved | available = on hand − reserved − expired | expired units are on the shelf but cannot be sold |
Reservation holds its lines |
it holds allocations: product, warehouse, batch, quantity | commit must know which batches to take from |
| no clock | a Clock passed to the constructor |
“expired” depends on the time; tests set it by hand |
| alerts from before and after | a low flag per cell |
expiry lowers available with no operation to notice it |
receive returns the level |
receive takes a date and returns a BatchId |
the caller may need the batch later |
| — | transfer, review_expiry, batches |
the new use cases |
| one mutex | still one mutex | a transfer changes two warehouses together |
What did not move is as important. The ids, Result, the state
machine, the three phases, collecting alerts under the lock and
delivering them after it, and the one mutex are all unchanged. The
step 1 design had put each rule in one place, so the change was a
change to the stock and not to everything.
Batches and the clock
Section titled “Batches and the clock”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One delivery of a product, kept together because it shares an expiry date.// The stock of a product in a warehouse is now a list of batches rather than// one pair of counts. Each batch keeps 0 <= reserved <= on_hand, as the// whole count did in step 1, and a batch whose on hand reaches 0 is removed.struct Batch { BatchId id; Date expires_on; // expired from the first moment of this day int on_hand = 0; int reserved = 0;
[[nodiscard]] int unreserved() const { return on_hand - reserved; } [[nodiscard]] bool expired(TimePoint now) const { return now >= expires_on; }};
// True if `a` should be used before `b`: it expires sooner, or on the same// day but arrived earlier (a lower id). Batches are kept sorted this way, so// walking a list from the front is "first expiry, first out" (FEFO), and the// tie-break makes the choice the same on every run.[[nodiscard]] inline bool sooner(const Batch& a, const Batch& b) { if (a.expires_on != b.expires_on) return a.expires_on < b.expires_on; return a.id < b.id;}
// The stock of one product in one warehouse, added up over its batches.// on_hand units on the shelf, expired or not// reserved units that held reservations have set aside// expired units in expired batches that nobody has reserved: on the// shelf, but no order may take them// available what a new order may take: on hand - reserved - expiredstruct StockLevel { int on_hand = 0; int reserved = 0; int expired = 0; [[nodiscard]] int available() const { return on_hand - reserved - expired; }};
// Sent when the available stock of a product in a warehouse drops below the// product's threshold, so someone can reorder.struct LowStockAlert { ProductId product; WarehouseId warehouse; int available; int threshold;};
// One line of the expiry report: a batch past its date that is still on the// shelf. Removing it (a write-off) is a person's decision, left out here.struct ExpiredBatch { ProductId product; WarehouseId warehouse; BatchId batch; Date expires_on; int on_hand; int reserved; // held reservations on it can be released, not committed};
// What one transfer moved: this many units of this batch, keeping its date.struct BatchMove { BatchId batch; Date expires_on; int quantity;};A batch keeps its own on hand and reserved, with the step 1 rule
0 <= reserved <= on_hand now per batch. sooner orders batches by
expiry date, and by id when two share a date. The tie-break matters:
without it, two batches of milk dated the same day could be used in
either order, and a test of “which batch did this order take?” would
pass on one run and fail on another.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Where the inventory gets the time, to decide whether a batch has expired.// The tests and the demo pass a ManualClock and move it by hand, so "the day// the milk expires" is checked exactly and no test ever sleeps.using TimePoint = std::chrono::system_clock::time_point;// A calendar day (UTC). An expiry date is a Date; a batch counts as expired// from the first moment of that day.using Date = std::chrono::sys_days;
class Clock {public: virtual ~Clock() = default; [[nodiscard]] virtual TimePoint now() const = 0;
protected: Clock() = default; Clock(const Clock&) = default; Clock& operator=(const Clock&) = default;};
class SystemClock final : public Clock {public: [[nodiscard]] TimePoint now() const override { return std::chrono::system_clock::now(); }};
// A clock that moves only when advance is called. In the thread tests one// thread may advance it while others read it, so the time is kept in a// std::atomic: every read sees the old time or the new one, never a torn// value, and the read and the write are not a data race.class ManualClock final : public Clock {public: explicit ManualClock(TimePoint start) : ticks_(start.time_since_epoch().count()) {}
[[nodiscard]] TimePoint now() const override { // Rebuild a time point from the stored tick count. return TimePoint{TimePoint::duration{ticks_.load()}}; }
// Throws std::invalid_argument for a negative step. void advance(std::chrono::hours step) { if (step.count() < 0) throw std::invalid_argument("time only moves forward here"); // += on a std::atomic is one indivisible read-add-write. ticks_ += std::chrono::duration_cast<TimePoint::duration>(step).count(); }
private: std::atomic<TimePoint::rep> ticks_;};The clock is passed in, for the same reason as the alert handler: so
the tests can control it. AC-7.5 receives a batch dated 3 December
at 09:00 on 1 December, moves a ManualClock 38 hours to 23:00 on 2
December and finds all 5 units available, then one hour more to 00:00
on 3 December and finds 0, with no waiting. The real
program would pass a SystemClock. The Inventory keeps a reference
to the clock, so the clock must live at least as long as the
inventory; the tests and the demo create the clock first, which
destroys it last.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Adds stock to a list of batches: tops up the batch with the same id if// there is one (part of a lot coming back), or else inserts a new batch at// its place in FEFO order. lower_bound finds the first batch that is not// used before `incoming`, which is where it belongs.//// The caller must have reserved room for one more batch. Then insert never// reallocates, and moving a Batch (plain numbers) cannot throw, so this// cannot throw: it is safe to call after other counts have changed.void add_batch(std::vector<Batch>& batches, const Batch& incoming) { if (Batch* same = find_batch(batches, incoming.id)) { same->on_hand += incoming.on_hand; return; } batches.insert(std::lower_bound(batches.begin(), batches.end(), incoming, sooner), incoming);}add_batch keeps the list sorted as it adds. It is also the reason a
lot that comes back rejoins its batch (AC-8.3): if 3 units of batch 1 (10
units) go to York and 2 come back, Leeds has one batch 1 of 9, not two
batches with the same id.
Reserving earliest expiry first
Section titled “Reserving earliest expiry first”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Result<ReservationId> Inventory::reserve(const std::vector<OrderLine>& lines) { std::vector<LowStockAlert> alerts; // reserve_locked takes the lock and releases it when it returns, so the // alerts below are delivered with no lock held. Result<ReservationId> result = reserve_locked(lines, alerts); deliver(alerts); return result;}
// Check, prepare, apply, as in step 1. What is new: the units come from// batches, earliest expiry first, skipping expired ones, and the reservation// records which batch each unit came from.Result<ReservationId> Inventory::reserve_locked(const std::vector<OrderLine>& lines, std::vector<LowStockAlert>& alerts) { if (lines.empty()) return Refusal{Reason::empty_order, "an order needs at least one line"}; const std::lock_guard lock(mutex_); // Read the clock once, so the whole order sees the same moment: a batch // cannot expire halfway through the check. const TimePoint now = clock_.now();
// 1. Check every line. Lines for the same product and warehouse are // added together, because they draw on the same batches. std::map<std::pair<ProductId, WarehouseId>, int> wanted; for (const OrderLine& line : lines) { if (!products_.contains(line.product)) { return Refusal{Reason::unknown_product, "no product " + line.product.value()}; } if (!warehouses_.contains(line.warehouse)) { return Refusal{Reason::unknown_warehouse, "no warehouse " + line.warehouse.value()}; } if (line.quantity <= 0) return Refusal{Reason::bad_quantity, "order a positive quantity"}; const Cell* cell = find_cell(line.product, line.warehouse); const int available = cell != nullptr ? available_in(cell->batches, now) : 0; int& total = wanted[{line.product, line.warehouse}]; // Not "total + quantity > available": total never exceeds available, // so this subtraction cannot overflow, while that sum could. if (line.quantity > available - total) { return Refusal{Reason::not_enough_available, describe(line.product, line.warehouse) + ": only " + std::to_string(available) + " available"}; } total += line.quantity; }
// 2. Prepare: choose the batches, build the reservation, and decide the // alerts, all before the first count changes. struct Take { Batch* batch; int quantity; }; struct Flag { Cell* cell; bool low; }; std::vector<Take> takes; std::vector<Flag> flags; flags.reserve(wanted.size()); Reservation reservation{ReservationId{next_reservation_}, {}, ReservationState::held}; for (const auto& [key, quantity] : wanted) { const auto& [product, warehouse] = key; // Not null: the check found quantity > 0 available here. Cell* cell = find_cell(product, warehouse); const int available = available_in(cell->batches, now); int left = quantity; // FEFO: the batches are sorted by sooner(), so walking from the front // takes the stock that expires first. for (Batch& batch : cell->batches) { if (left == 0) break; if (batch.expired(now)) continue; // no order may take expired stock const int take = std::min(left, batch.unreserved()); if (take == 0) continue; // this batch is fully reserved already reservation.allocations.push_back(Allocation{product, warehouse, batch.id, take}); takes.push_back(Take{&batch, take}); left -= take; } // left is 0 here: the check counted exactly these unexpired, // unreserved units, and found at least `quantity` of them. const bool low = plan_low(product, warehouse, *cell, available - quantity, alerts); flags.push_back(Flag{cell, low}); } const ReservationId id = reservation.id; reservations_.emplace(id, std::move(reservation)); // may throw; nothing changed yet
// 3. Apply. Nothing from here on allocates or throws. ++next_reservation_; for (const Take& take : takes) take.batch->reserved += take.quantity; for (const Flag& flag : flags) flag.cell->low = flag.low; return id;}The three phases are the same as in step 1. What is new is inside the
prepare phase: a walk along the sorted batches, skipping expired ones
and ones already fully reserved, taking from each until the line is
covered. Each piece becomes an Allocation naming its batch. The
clock is read once, at the top, so the check and the walk see the
same moment: a batch cannot expire between “these units are available”
and “take these units”.
Shipping expired stock, and releasing it
Section titled “Shipping expired stock, and releasing it”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Neither commit nor release can alert. Commit lowers on hand and reserved// of unexpired batches by the same amount, so available stays the same;// release raises available (unless the batch has expired: then the freed// units count as expired), and may re-arm the alert.Result<ReservationState> Inventory::finish(const ReservationId& id, ReservationState target) { const std::lock_guard lock(mutex_); const auto found = reservations_.find(id); if (found == reservations_.end()) { return Refusal{Reason::unknown_reservation, "no " + name_of(id)}; } Reservation& reservation = found->second; switch (classify(reservation.state, target)) { case Move::repeat: return reservation.state; // done before: succeed, change nothing case Move::illegal: if (reservation.state == ReservationState::committed) { return Refusal{Reason::already_committed, name_of(id) + " has shipped"}; } return Refusal{Reason::already_released, name_of(id) + " was released"}; case Move::apply: break; } const TimePoint now = clock_.now(); const bool shipping = target == ReservationState::committed;
// Prepare: find every batch, and refuse to ship any that has expired, // before changing anything. The reservation then stays held. struct Take { Cell* cell; Batch* batch; int quantity; }; std::vector<Take> takes; takes.reserve(reservation.allocations.size()); for (const Allocation& allocation : reservation.allocations) { // Neither is null: a held allocation keeps its batch's reserved above // 0, and a batch is removed only when its on hand, and so its // reserved, is 0. Cell* cell = find_cell(allocation.product, allocation.warehouse); Batch* batch = find_batch(cell->batches, allocation.batch); if (shipping && batch->expired(now)) { return Refusal{Reason::batch_expired, name_of(id) + " holds batch " + std::to_string(allocation.batch.value()) + ", which has expired"}; } takes.push_back(Take{cell, batch, allocation.quantity}); }
// Apply. Nothing below throws. for (const Take& take : takes) { take.batch->reserved -= take.quantity; if (shipping) take.batch->on_hand -= take.quantity; } // Only now remove emptied batches: erasing moves the batches after it, // so a Batch* in `takes` would point at the wrong batch if we erased // inside the loop above. std::erase_if (C++20) removes every match. for (std::size_t i = 0; i < takes.size(); ++i) { if (shipping) { std::erase_if(takes[i].cell->batches, is_empty); } else { rearm(reservation.allocations[i].product, *takes[i].cell, now); } } reservation.state = target; return target;}finish has gained a prepare phase. Before anything changes, a commit
looks at each batch it would ship from, and if any has expired, the
whole commit is refused with batch_expired and the reservation stays
held (AC-7.9). Shipping three of the four cartons of an order would be
a partial shipment nobody asked for.
Release is allowed on the same reservation, and the asymmetry is deliberate. Commit sends food out of the door: shipping expired milk is the very thing the change forbids. Release only gives up a claim; nothing leaves the shelf. If release were refused too, the order could never end: the units would stay reserved for ever, and the customer could not be offered fresher stock. After the release, the freed units are unreserved and expired, so they count as expired, not available, and they do not re-arm the low-stock alert (AC-7.13).
One more detail: emptied batches are removed with std::erase_if
after the apply loop. Removing an element from a std::vector
moves the elements after it, so a Batch* collected in the prepare
phase would point at the wrong batch if a batch were erased in the
middle of the loop.
Expiry and the low flag
Section titled “Expiry and the low flag”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
std::vector<ExpiredBatch> Inventory::review_expiry() { std::vector<LowStockAlert> alerts; std::vector<ExpiredBatch> report = review_locked(alerts); deliver(alerts); // no lock held return report;}
std::vector<ExpiredBatch> Inventory::review_locked(std::vector<LowStockAlert>& alerts) { const std::lock_guard lock(mutex_); const TimePoint now = clock_.now(); std::vector<ExpiredBatch> report; std::vector<std::pair<Cell*, bool>> flags; // each cell's new low flag // Prepare: the report, and an alert for each cell whose available has // fallen below its threshold since the inventory last looked. for (auto& [product_id, product] : products_) { for (auto& [warehouse_id, cell] : product.stock) { for (const Batch& batch : cell.batches) { if (!batch.expired(now)) continue; report.push_back(ExpiredBatch{product_id, warehouse_id, batch.id, batch.expires_on, batch.on_hand, batch.reserved}); } const int available = available_in(cell.batches, now); flags.emplace_back(&cell, plan_low(product_id, warehouse_id, cell, available, alerts)); } } // Apply: only the flags change. for (const auto& [cell, low] : flags) cell->low = low; return report;}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Once per crossing: alert only if the cell was not already low. The flag is// stored by the caller when the change is applied.bool Inventory::plan_low(const ProductId& product, const WarehouseId& warehouse, const Cell& cell, int available_after, std::vector<LowStockAlert>& alerts) const { const int threshold = threshold_of(product); const bool low = available_after < threshold; if (low && !cell.low) { alerts.push_back(LowStockAlert{product, warehouse, available_after, threshold}); } return low;}
// Only clears the flag, never sets it. Setting it here, with no alert sent,// would swallow an alert that expiry had made due; leaving it clear lets the// next drop or review_expiry send that alert.void Inventory::rearm(const ProductId& product, Cell& cell, TimePoint now) const { if (available_in(cell.batches, now) >= threshold_of(product)) cell.low = false;}
// Runs with no lock held, on the thread that made the change. noexcept: if// the handler throws, the program stops (std::terminate) rather than lose a// change the caller has not yet been told about.void Inventory::deliver(const std::vector<LowStockAlert>& alerts) const noexcept { if (!on_low_stock_) return; // no handler was given for (const LowStockAlert& alert : alerts) on_low_stock_(alert);}In step 1, every drop in available came from a reservation, and the reservation could see before and after under one lock. In step 2, time lowers available too: at midnight, a batch expires, and no function runs. The next function to run sees a “before” that already has the expiry in it, and the step 1 rule misses the crossing.
How this code works: Trace: why before and after is not enough (AC-7.12)
Apples, threshold 3. A batch of 5 that expires on 3 December, and a batch of 2 dated a year later. The clock starts at 09:00 on 1 December.
| When | Event | Available | Step 1 rule: before ≥ 3 and after < 3? | Step 2 rule: low now and flag not set? | Flag after |
|---|---|---|---|---|---|
| 09:00, 1 Dec | receive 5, receive 2 | 7 | — | not low; flag cleared by rearm |
not low |
| 00:00, 3 Dec (39 h later) | batch of 5 expires | 2 | nothing runs | nothing runs | not low |
| after that | reserve 1 | 2 → 1 | before 2 is not ≥ 3: no alert | 1 < 3 and flag not set: alert | low |
| after that | review_expiry |
1 | — | 1 < 3 but flag set: no alert | low |
With the step 1 rule, the buyer would never hear that apples are low, however many more are sold. The flag remembers what the inventory last told the buyer, and that does not depend on how the drop happened.
review_expiry is how expiry alerts arrive without waiting for an
order: something calls it regularly (a timer, or a person at the start
of a shift), and it reports expired batches and alerts on any cell that
went low since the last look (AC-7.11). rearm clears the flag only
when available is back at or above the threshold, and it never sets
the flag: setting it with no alert sent would swallow an alert that an
expiry had made due. Each cell starts with the flag set, as “already
low”, because an empty cell is below any threshold above 0 and nobody
needs an alert for stock that never arrived.
Transfers
Section titled “Transfers”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Result<std::vector<BatchMove>> Inventory::transfer(const ProductId& product, const WarehouseId& from, const WarehouseId& to, int quantity) { std::vector<LowStockAlert> alerts; Result<std::vector<BatchMove>> result = transfer_locked(product, from, to, quantity, alerts); deliver(alerts); // no lock held return result;}
// Check, prepare, apply again. Both warehouses change under the one lock, so// no other thread can look between "taken from" and "added to".Result<std::vector<BatchMove>> Inventory::transfer_locked(const ProductId& product, const WarehouseId& from, const WarehouseId& to, int quantity, std::vector<LowStockAlert>& alerts) { const std::lock_guard lock(mutex_); const auto found = products_.find(product); if (found == products_.end()) { return Refusal{Reason::unknown_product, "no product " + product.value()}; } // A loop over the addresses of the two ids, to check both the same way. for (const WarehouseId* warehouse : {&from, &to}) { if (!warehouses_.contains(*warehouse)) { return Refusal{Reason::unknown_warehouse, "no warehouse " + warehouse->value()}; } } if (from == to) return Refusal{Reason::same_warehouse, "move stock between two warehouses"}; if (quantity <= 0) return Refusal{Reason::bad_quantity, "move a positive quantity"}; const TimePoint now = clock_.now();
// 1. Check. Only unreserved, unexpired stock may move: reserved units // belong to an order here, and expired units may not be used at all. Cell* source = find_cell(product, from); const int available = source != nullptr ? available_in(source->batches, now) : 0; if (quantity > available) { return Refusal{Reason::not_enough_available, describe(product, from) + ": only " + std::to_string(available) + " available"}; } const Cell* existing = find_cell(product, to); const std::int64_t arriving_on = existing != nullptr ? on_hand_in(existing->batches) : 0; if (quantity > std::numeric_limits<int>::max() - arriving_on) { return Refusal{Reason::would_overflow, "too much " + describe(product, to)}; }
// 2. Prepare: choose the units, earliest expiry first, as reserve does. struct Take { Batch* batch; int quantity; }; std::vector<Take> takes; std::vector<BatchMove> moves; // also the result int left = quantity; for (Batch& batch : source->batches) { if (left == 0) break; if (batch.expired(now)) continue; const int take = std::min(left, batch.unreserved()); if (take == 0) continue; takes.push_back(Take{&batch, take}); moves.push_back(BatchMove{batch.id, batch.expires_on, take}); left -= take; } // The destination cell (created empty the first time, which reads as // zero stock), with room for every move as a new batch, so add_batch // below cannot reallocate and so cannot throw. A std::map never moves // its entries, so `source` stays valid while `destination` is added. Cell& destination = found->second.stock[to]; destination.batches.reserve(destination.batches.size() + moves.size()); const bool source_low = plan_low(product, from, *source, available - quantity, alerts);
// 3. Apply. Nothing below throws. for (std::size_t i = 0; i < takes.size(); ++i) { takes[i].batch->on_hand -= takes[i].quantity; // The batch keeps its id and date in its new warehouse. add_batch(destination.batches, Batch{moves[i].batch, moves[i].expires_on, moves[i].quantity, 0}); } std::erase_if(source->batches, is_empty); // after the loop, as in finish source->low = source_low; rearm(product, destination, now); // A returned local is moved, not copied, into the Result (C++20), so // this allocates nothing and cannot throw after the change. return moves;}A transfer is check, prepare, apply again, and the whole of it happens under the one lock. Only units that a new order could take may move: reserved units belong to an order in this warehouse, and expired units may not be used at all (AC-8.4). The units move earliest expiry first, and each batch keeps its id and date in its new warehouse.
The destination’s vector is given room for every incoming batch
before the apply phase (reserve, the std::vector member, not
the inventory’s). That way add_batch cannot reallocate during the
apply phase, and so cannot throw after the source has already been
lowered.
How this code works: Trace: moving 5 milk from Leeds to York in the step 2 demo
Before: Leeds has batch 2 (5 on hand, 5 reserved, expires 2 Dec), batch 1 (6 on hand, 2 reserved, 4 Dec), and batch 3 (4 on hand, 0 reserved, 8 Dec). Available is 15 − 7 = 8. Threshold 4. York has nothing.
| Phase | What happens | Values |
|---|---|---|
| check | product and both warehouses known, different, quantity 5 > 0 | — |
| check | is 5 > 8 available? No. Would York overflow? No | — |
| prepare | batch 2: unreserved 0, skip | left 5 |
| prepare | batch 1: take min(5, 4) = 4 | left 1; move 4 of batch 1 (4 Dec) |
| prepare | batch 3: take min(1, 4) = 1 | left 0; move 1 of batch 3 (8 Dec) |
| prepare | York’s cell is created, with room for 2 batches | — |
| prepare | Leeds after = 8 − 5 = 3 < 4, flag not set | alert: Leeds down to 3 |
| apply | batch 1: 6 → 2 in Leeds; new batch 1 of 4 in York | — |
| apply | batch 3: 4 → 3 in Leeds; new batch 3 of 1 in York | — |
| apply | Leeds flag set; York has 5 ≥ 4, so rearm clears York’s flag |
— |
| deliver | the lock is gone; the handler prints the alert | ALERT: milk in leeds is down to 3 (threshold 4) |
The order reserved earlier still holds its 5 of batch 2 and 2 of batch 1 in Leeds: a transfer never takes reserved units.
One lock means no lock order. A deadlock needs two locks taken in opposite orders: a thread moving Leeds to York holds Leeds and waits for York, while a thread moving York to Leeds holds York and waits for Leeds. With one mutex for the whole inventory there is no second lock to wait for, so AC-9.1 (transfers both ways at once) cannot deadlock.
If profiling one day showed the single lock was the bottleneck and the design moved to a mutex per warehouse, a transfer would need both, and it would have to take them safely. Two standard ways, from Deadlocks and lock ordering:
IllustrativeA fragment for explanation; not compiled on its own.
struct LockedWarehouse { std::mutex mutex; int stock = 0;};
// std::scoped_lock takes both mutexes with a deadlock-avoiding algorithm,// whatever order the two arguments come in.inline bool transfer_with_two_locks(LockedWarehouse& from, LockedWarehouse& to, int quantity) { if (&from == &to) return false; // locking one std::mutex twice is undefined behaviour const std::scoped_lock both(from.mutex, to.mutex); if (from.stock < quantity) return false; from.stock -= quantity; to.stock += quantity; return true;}The other way is a written rule, such as “always lock the warehouse with the smaller id first”, that every function taking two locks obeys. Either way, an order touching three warehouses, a reader adding up every warehouse, and an expiry review would all need the same care, which is why the one lock stays until a measurement says otherwise.
Step 2 tests
Section titled “Step 2 tests”Step 2 has 52 tests, in step-2/tests/test_step2.cpp. The step 1
groups are all still there, adapted to batches and a clock. The new
groups are below.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_7_1_each_delivery_is_a_batch_kept_in_expiry_order) { World world; LLD_CHECK_EQ(world.receive(apple, north, 5, dec_9).value(), std::uint64_t{1}); LLD_CHECK_EQ(world.receive(apple, north, 2, dec_3).value(), std::uint64_t{2}); LLD_CHECK_EQ(world.receive(apple, north, 4, dec_5).value(), std::uint64_t{3}); const std::vector<Batch> batches = world.inventory.batches(apple, north); LLD_CHECK_EQ(ids_of(batches), (Ids{2, 3, 1})); LLD_CHECK(batches[0].expires_on == dec_3); LLD_CHECK_EQ(world.inventory.level(apple, north).on_hand, 11);}
LLD_TEST(ac_7_2_reserving_takes_the_earliest_expiry_first) { World world; world.receive(apple, north, 5, dec_9); // batch 1 world.receive(apple, north, 2, dec_3); // batch 2 world.receive(apple, north, 4, dec_5); // batch 3 const ReservationId id = world.reserve({{apple, north, 4}}).value(); const std::vector<Allocation> taken = world.inventory.reservation(id)->allocations; LLD_CHECK_EQ(ids_of(taken), (Ids{2, 3})); // all of dec 3, then dec 5 LLD_CHECK_EQ(taken[0].quantity, 2); LLD_CHECK_EQ(taken[1].quantity, 2); // The next order skips what is reserved and carries on in the same order. const ReservationId next = world.reserve({{apple, north, 3}}).value(); LLD_CHECK_EQ(ids_of(world.inventory.reservation(next)->allocations), (Ids{3, 1}));}
LLD_TEST(ac_7_3_on_the_same_date_the_earlier_delivery_goes_first) { World world; world.receive(apple, north, 2, dec_5); // batch 1 world.receive(apple, north, 2, dec_5); // batch 2 const ReservationId id = world.reserve({{apple, north, 3}}).value(); const std::vector<Allocation> taken = world.inventory.reservation(id)->allocations; LLD_CHECK_EQ(ids_of(taken), (Ids{1, 2})); LLD_CHECK_EQ(taken[0].quantity, 2); LLD_CHECK_EQ(taken[1].quantity, 1);}
LLD_TEST(ac_7_4_expired_stock_cannot_be_reserved) { World world; world.receive(apple, north, 5, dec_3); world.receive(apple, north, 2, far_off); world.clock.advance(39h); // 00:00 on 3 December: the first batch expires const StockLevel level = world.inventory.level(apple, north); LLD_CHECK_EQ(level.on_hand, 7); LLD_CHECK_EQ(level.expired, 5); LLD_CHECK_EQ(level.available(), 2); const Result<ReservationId> refused = world.reserve({{apple, north, 3}}); LLD_CHECK_EQ(refused.reason(), Reason::not_enough_available); LLD_CHECK_EQ(refused.refusal().text, std::string("apple in north: only 2 available")); const ReservationId id = world.reserve({{apple, north, 2}}).value(); LLD_CHECK_EQ(ids_of(world.inventory.reservation(id)->allocations), (Ids{2}));}
LLD_TEST(ac_7_5_a_batch_expires_at_the_start_of_its_date) { World world; world.receive(apple, north, 5, dec_3); world.clock.advance(38h); // 23:00 on 2 December LLD_CHECK_EQ(world.available(apple, north), 5); world.clock.advance(1h); // 00:00 on 3 December LLD_CHECK_EQ(world.available(apple, north), 0);}
LLD_TEST(ac_7_6_stock_already_past_its_date_is_refused) { World world; const Date today = sys_days{2026y / 12 / 1}; // the clock reads 09:00 today LLD_CHECK_EQ(world.inventory.receive(apple, north, 5, today).reason(), Reason::already_expired); LLD_CHECK(world.inventory.batches(apple, north).empty()); LLD_CHECK(world.inventory.receive(apple, north, 5, today + days{1}).ok());}
LLD_TEST(ac_7_7_review_expiry_reports_expired_batches_still_on_hand) { World world; world.receive(apple, north, 4, dec_3); // batch 1 world.receive(apple, north, 6, far_off); world.receive(pear, south, 3, dec_3); // batch 3 const ReservationId held = world.reserve({{apple, north, 1}}).value(); // from batch 1 LLD_CHECK(world.inventory.review_expiry().empty()); // nothing expired yet world.clock.advance(39h); const std::vector<ExpiredBatch> report = world.inventory.review_expiry(); LLD_CHECK_EQ(report.size(), std::size_t{2}); LLD_CHECK(report[0].product == apple); LLD_CHECK_EQ(report[0].batch.value(), std::uint64_t{1}); LLD_CHECK_EQ(report[0].on_hand, 4); LLD_CHECK_EQ(report[0].reserved, 1); LLD_CHECK(report[0].expires_on == dec_3); LLD_CHECK(report[1].product == pear); LLD_CHECK_EQ(report[1].batch.value(), std::uint64_t{3}); LLD_CHECK_EQ(world.state(held), ReservationState::held); // reporting changes nothing LLD_CHECK(world.inventory.invariants_hold());}
LLD_TEST(ac_7_8_stock_that_expired_after_reserving_cannot_ship_but_can_be_released) { World world; world.receive(apple, north, 4, dec_3); const ReservationId id = world.reserve({{apple, north, 2}}).value(); world.clock.advance(39h); const Result<ReservationState> refused = world.commit(id); LLD_CHECK_EQ(refused.reason(), Reason::batch_expired); LLD_CHECK_EQ(world.state(id), ReservationState::held); // nothing changed LLD_CHECK_EQ(world.inventory.level(apple, north).on_hand, 4); LLD_CHECK_EQ(world.inventory.level(apple, north).reserved, 2); LLD_CHECK_EQ(world.release(id).value(), ReservationState::released); LLD_CHECK_EQ(world.inventory.level(apple, north).reserved, 0);}
// A commit of a two-batch reservation where only the second batch expired:// still refused as a whole, and the first batch is untouched.LLD_TEST(ac_7_9_a_commit_is_refused_whole_if_any_batch_expired) { World world; world.receive(apple, north, 2, dec_3); world.receive(apple, north, 2, dec_5); const ReservationId id = world.reserve({{apple, north, 3}}).value(); world.clock.advance(39h); // dec_3 expired, dec_5 still good LLD_CHECK_EQ(world.commit(id).reason(), Reason::batch_expired); const std::vector<Batch> batches = world.inventory.batches(apple, north); LLD_CHECK_EQ(batches[0].on_hand, 2); LLD_CHECK_EQ(batches[1].on_hand, 2); LLD_CHECK_EQ(batches[1].reserved, 1);}
LLD_TEST(ac_7_10_shipping_a_whole_batch_removes_it) { World world; world.receive(apple, north, 2, dec_3); world.receive(apple, north, 5, dec_5); const ReservationId id = world.reserve({{apple, north, 3}}).value(); LLD_CHECK(world.commit(id).ok()); const std::vector<Batch> batches = world.inventory.batches(apple, north); LLD_CHECK_EQ(ids_of(batches), (Ids{2})); LLD_CHECK_EQ(batches[0].on_hand, 4);}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Time passing changes no count, so only review_expiry notices it, and it// alerts once however often it runs.LLD_TEST(ac_7_11_expiry_alone_alerts_through_review_expiry_once) { World world; // apple threshold 3 world.receive(apple, north, 4, dec_3); world.receive(apple, north, 2, far_off); // available 6 world.clock.advance(39h); // available 2, but nobody looked LLD_CHECK_EQ(world.alert_count(), std::size_t{0}); static_cast<void>(world.inventory.review_expiry()); LLD_CHECK_EQ(world.alert_count(), std::size_t{1}); LLD_CHECK_EQ(world.alerts.back().available, 2); static_cast<void>(world.inventory.review_expiry()); LLD_CHECK_EQ(world.alert_count(), std::size_t{1}); world.receive(apple, north, 5, far_off); // available 7: re-armed LLD_CHECK(world.reserve({{apple, north, 5}}).ok()); // 2: alerts again LLD_CHECK_EQ(world.alert_count(), std::size_t{2});}
// If expiry took available below the threshold unnoticed, the next drop// sends that alert (late, but once), and a review after it sends no other.LLD_TEST(ac_7_12_a_drop_after_an_unnoticed_expiry_alerts_once) { World world; world.receive(apple, north, 5, dec_3); world.receive(apple, north, 2, far_off); // available 7 world.clock.advance(39h); // available 2, unnoticed LLD_CHECK(world.reserve({{apple, north, 1}}).ok()); LLD_CHECK_EQ(world.alert_count(), std::size_t{1}); LLD_CHECK_EQ(world.alerts.back().available, 1); static_cast<void>(world.inventory.review_expiry()); LLD_CHECK_EQ(world.alert_count(), std::size_t{1});}
// Releasing units of an expired batch does not raise available, so it must// not re-arm the alert.LLD_TEST(ac_7_13_releasing_expired_stock_does_not_rearm_the_alert) { World world; world.receive(apple, north, 3, dec_3); world.receive(apple, north, 1, far_off); // available 4 const ReservationId id = world.reserve({{apple, north, 3}}).value(); // 1: alert world.clock.advance(39h); LLD_CHECK(world.release(id).ok()); // the 3 freed have expired: still 1 LLD_CHECK(world.reserve({{apple, north, 1}}).ok()); // 0: still low, no alert LLD_CHECK_EQ(world.alert_count(), std::size_t{1});}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_8_1_a_transfer_moves_stock_and_keeps_the_total) { World world; world.receive(apple, north, 10); const Result<std::vector<BatchMove>> moved = world.transfer(apple, north, south, 4); LLD_CHECK(moved.ok()); LLD_CHECK_EQ(moved.value().size(), std::size_t{1}); LLD_CHECK_EQ(moved.value()[0].quantity, 4); LLD_CHECK_EQ(world.inventory.level(apple, north).on_hand, 6); LLD_CHECK_EQ(world.inventory.level(apple, south).on_hand, 4); LLD_CHECK_EQ(world.inventory.total_on_hand(apple), std::int64_t{10});}
LLD_TEST(ac_8_2_a_transfer_moves_the_earliest_expiry_first_keeping_ids_and_dates) { World world; world.receive(apple, north, 5, far_off); // batch 1 world.receive(apple, north, 2, dec_5); // batch 2 world.receive(apple, north, 3, dec_9); // batch 3 const std::vector<BatchMove> moved = world.transfer(apple, north, south, 4).value(); LLD_CHECK_EQ(moved.size(), std::size_t{2}); LLD_CHECK_EQ(moved[0].batch.value(), std::uint64_t{2}); // all of batch 2 LLD_CHECK_EQ(moved[0].quantity, 2); LLD_CHECK_EQ(moved[1].batch.value(), std::uint64_t{3}); // part of batch 3 LLD_CHECK_EQ(moved[1].quantity, 2); const std::vector<Batch> south_batches = world.inventory.batches(apple, south); LLD_CHECK_EQ(ids_of(south_batches), (Ids{2, 3})); LLD_CHECK(south_batches[0].expires_on == dec_5); LLD_CHECK(south_batches[1].expires_on == dec_9); const std::vector<Batch> north_batches = world.inventory.batches(apple, north); LLD_CHECK_EQ(ids_of(north_batches), (Ids{3, 1})); // batch 2 emptied and removed LLD_CHECK_EQ(north_batches[0].on_hand, 1);}
LLD_TEST(ac_8_3_stock_moving_back_rejoins_its_batch) { World world; world.receive(apple, north, 10); LLD_CHECK(world.transfer(apple, north, south, 3).ok()); LLD_CHECK(world.transfer(apple, south, north, 2).ok()); const std::vector<Batch> back = world.inventory.batches(apple, north); LLD_CHECK_EQ(ids_of(back), (Ids{1})); // one batch, not two LLD_CHECK_EQ(back[0].on_hand, 9); const std::vector<Batch> away = world.inventory.batches(apple, south); LLD_CHECK_EQ(away[0].on_hand, 1);}
LLD_TEST(ac_8_4_reserved_and_expired_stock_does_not_move) { World world; world.receive(apple, north, 5); const ReservationId id = world.reserve({{apple, north, 3}}).value(); LLD_CHECK_EQ(world.transfer(apple, north, south, 3).reason(), Reason::not_enough_available); LLD_CHECK(world.transfer(apple, north, south, 2).ok()); LLD_CHECK(world.commit(id).ok()); // the reserved 3 are still in north to ship LLD_CHECK_EQ(world.inventory.level(apple, north).on_hand, 0);
world.receive(pear, north, 4, dec_3); world.receive(pear, north, 1, far_off); world.clock.advance(39h); const Result<std::vector<BatchMove>> refused = world.transfer(pear, north, south, 2); LLD_CHECK_EQ(refused.reason(), Reason::not_enough_available); LLD_CHECK_EQ(refused.refusal().text, std::string("pear in north: only 1 available")); const std::vector<BatchMove> moved = world.transfer(pear, north, south, 1).value(); LLD_CHECK_EQ(moved.size(), std::size_t{1}); LLD_CHECK(moved[0].expires_on == far_off); // the good unit, not an expired one const StockLevel north_level = world.inventory.level(pear, north); LLD_CHECK_EQ(north_level.on_hand, 4); // the expired batch stays, all of it LLD_CHECK_EQ(north_level.expired, 4); LLD_CHECK_EQ(world.available(pear, south), 1);}
LLD_TEST(ac_8_5_bad_transfers_are_refused_and_change_nothing) { World world; world.receive(apple, north, 5); LLD_CHECK_EQ(world.transfer(apple, north, north, 1).reason(), Reason::same_warehouse); LLD_CHECK_EQ(world.transfer(ProductId{"plum"}, north, south, 1).reason(), Reason::unknown_product); LLD_CHECK_EQ(world.transfer(apple, WarehouseId{"east"}, south, 1).reason(), Reason::unknown_warehouse); LLD_CHECK_EQ(world.transfer(apple, north, WarehouseId{"east"}, 1).reason(), Reason::unknown_warehouse); LLD_CHECK_EQ(world.transfer(apple, north, south, 0).reason(), Reason::bad_quantity); LLD_CHECK_EQ(world.transfer(apple, north, south, -2).reason(), Reason::bad_quantity); LLD_CHECK_EQ(world.transfer(apple, south, north, 1).reason(), Reason::not_enough_available); LLD_CHECK_EQ(world.transfer(apple, north, south, 6).reason(), Reason::not_enough_available); LLD_CHECK_EQ(world.inventory.level(apple, north).on_hand, 5); LLD_CHECK_EQ(world.inventory.level(apple, south).on_hand, 0);}
LLD_TEST(ac_8_6_a_transfer_that_would_overflow_is_refused) { World world; world.receive(apple, south, std::numeric_limits<int>::max() - 1); world.receive(apple, north, 5); LLD_CHECK_EQ(world.transfer(apple, north, south, 2).reason(), Reason::would_overflow); LLD_CHECK_EQ(world.inventory.level(apple, north).on_hand, 5); LLD_CHECK(world.transfer(apple, north, south, 1).ok());}
LLD_TEST(ac_8_7_a_transfer_out_can_alert_and_a_transfer_in_rearms) { World world; // apple threshold 3 world.receive(apple, north, 5); LLD_CHECK(world.transfer(apple, north, south, 3).ok()); // north 2: alert LLD_CHECK_EQ(world.alert_count(), std::size_t{1}); LLD_CHECK(world.alerts.back().warehouse == north); // South's cell was new, so it started low; the transfer in re-armed it, // which is why this drop alerts. LLD_CHECK(world.reserve({{apple, south, 1}}).ok()); // south 3 -> 2: alert LLD_CHECK_EQ(world.alert_count(), std::size_t{2}); LLD_CHECK(world.alerts.back().warehouse == south); LLD_CHECK(world.transfer(apple, south, north, 1).ok()); // south 1: still low LLD_CHECK_EQ(world.alert_count(), std::size_t{2});}
LLD_TEST(ac_8_8_a_transfer_can_empty_a_warehouse) { World world; world.receive(apple, north, 3, dec_5); world.receive(apple, north, 2, dec_9); LLD_CHECK_EQ(world.transfer(apple, north, south, 5).value().size(), std::size_t{2}); LLD_CHECK(world.inventory.batches(apple, north).empty()); LLD_CHECK_EQ(world.available(apple, south), 5);}The transfer thread tests are where the one-lock design is checked against its alternative. AC-9.1 has eight threads moving stock both ways while a reader checks the total; a deadlock would make it hang, and a gap would make the reader see a wrong total. AC-9.3 moves the clock forward while orders, transfers, and expiry reviews run, so batches expire in the middle of the race:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Four threads move stock north to south while four move it south to north,// and a ninth keeps reading the total. With one lock there is no lock order// to get wrong, so this cannot deadlock (if it did, the test would hang and// ctest would time it out). The reader must see the same total every time:// a transfer is never half done from the outside.LLD_TEST(ac_9_1_transfers_both_ways_at_once_never_deadlock_or_change_the_total) { constexpr int movers = 8; World world; const Date dates[] = {dec_3, dec_5, dec_9, far_off}; for (const Date date : dates) { world.receive(apple, north, 100, date); world.receive(apple, south, 100, date); } std::vector<int> moved(movers, 0); // units each mover moved std::atomic<bool> done{false}; int wrong_totals = 0; // written only by the reader thread { std::latch start_together(movers + 1); std::vector<std::jthread> pool; // The reader, started first. It stops when `done` is set below. pool.emplace_back([&world, &done, &wrong_totals, &start_together] { start_together.arrive_and_wait(); while (!done.load()) { if (world.inventory.total_on_hand(apple) != 800) ++wrong_totals; } }); std::vector<std::jthread> workers; for (int t = 0; t < movers; ++t) { workers.emplace_back([&world, &moved, &start_together, t] { start_together.arrive_and_wait(); const WarehouseId& from = t % 2 == 0 ? north : south; const WarehouseId& to = t % 2 == 0 ? south : north; for (int i = 0; i < 300; ++i) { const int quantity = 1 + i % 3; if (world.inventory.transfer(apple, from, to, quantity).ok()) { moved[static_cast<std::size_t>(t)] += quantity; } } }); } workers.clear(); // joins the movers done.store(true); } // joins the reader LLD_CHECK_EQ(wrong_totals, 0); int north_net = 0; // what came into north minus what left it for (int t = 0; t < movers; ++t) { const int units = moved[static_cast<std::size_t>(t)]; north_net += t % 2 == 0 ? -units : units; } LLD_CHECK_EQ(world.inventory.level(apple, north).on_hand, 400 + north_net); LLD_CHECK_EQ(world.inventory.level(apple, south).on_hand, 400 - north_net); LLD_CHECK(world.inventory.invariants_hold());}
// Six units in north. Half the threads reserve one, half transfer one to// south, all at once. Exactly six calls in total may succeed, and every// unit ends up in exactly one place.LLD_TEST(ac_9_2_reserves_and_transfers_racing_for_the_last_units) { constexpr int threads = 12; for (int round = 0; round < 50; ++round) { World world(0, 0); world.receive(apple, north, 3, dec_5); world.receive(apple, north, 3, dec_9); std::vector<int> won(threads, 0); { std::latch start_together(threads); std::vector<std::jthread> pool; for (int t = 0; t < threads; ++t) { pool.emplace_back([&world, &won, &start_together, t] { start_together.arrive_and_wait(); const bool ok = t % 2 == 0 ? world.inventory.reserve({{apple, north, 1}}).ok() : world.inventory.transfer(apple, north, south, 1).ok(); won[static_cast<std::size_t>(t)] = ok ? 1 : 0; }); } } int reserved = 0; int transferred = 0; for (int t = 0; t < threads; ++t) { (t % 2 == 0 ? reserved : transferred) += won[static_cast<std::size_t>(t)]; } LLD_CHECK_EQ(reserved + transferred, 6); const StockLevel north_level = world.inventory.level(apple, north); LLD_CHECK_EQ(north_level.reserved, reserved); LLD_CHECK_EQ(north_level.on_hand, 6 - transferred); LLD_CHECK_EQ(world.inventory.level(apple, south).on_hand, transferred); LLD_CHECK(world.inventory.invariants_hold()); }}
// Orders, releases, transfers, and expiry reviews all at once, while the// clock moves past the first batch's date. The point is that the invariants// hold at the end and that the tsan preset sees no data race.LLD_TEST(ac_9_3_orders_transfers_and_reviews_while_the_clock_moves) { constexpr int threads = 6; World world; world.receive(apple, north, 200, dec_3); world.receive(apple, north, 200, far_off); world.receive(apple, south, 200, dec_5); { std::latch start_together(threads + 1); std::vector<std::jthread> pool; pool.emplace_back([&world, &start_together] { start_together.arrive_and_wait(); for (int hour = 0; hour < 60; ++hour) { world.clock.advance(1h); static_cast<void>(world.inventory.review_expiry()); } }); for (int t = 0; t < threads; ++t) { pool.emplace_back([&world, &start_together, t] { start_together.arrive_and_wait(); for (int i = 0; i < 200; ++i) { if (t % 3 == 0) { static_cast<void>(world.inventory.transfer(apple, north, south, 1)); } else if (t % 3 == 1) { static_cast<void>(world.inventory.transfer(apple, south, north, 1)); } else { const Result<ReservationId> id = world.inventory.reserve({{apple, north, 2}}); if (!id.ok()) continue; // Commit every other one. A commit is refused if the // batch expired meanwhile; then release it instead. // (No LLD_CHECK in a thread: the harness's failure // count is not thread safe. The check after the // joins catches a release that failed.) if (i % 2 != 0 || !world.inventory.commit(id.value()).ok()) { static_cast<void>(world.inventory.release(id.value())); } } } }); } } LLD_CHECK(world.inventory.invariants_hold()); LLD_CHECK_EQ(world.inventory.level(apple, north).reserved + world.inventory.level(apple, south).reserved, 0);}The step 2 demo
Section titled “The step 2 demo”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// CS-18 step 2 demo: milk arrives in batches with expiry dates, an order// takes the earliest expiry first, stock moves between warehouses keeping// its dates, time passes and the expiry review reports and alerts, and two// threads move stock back and forth while the total stays the same. The// clock is a ManualClock, so every line printed is the same on every run.
#include <atomic>#include <chrono>#include <iomanip>#include <iostream>#include <sstream>#include <string>#include <thread>#include <vector>
#include "inventory.hpp"
using namespace inventory;using namespace std::chrono;
namespace {
// 2026-12-04 style. year_month_day splits a day count into its calendar// parts; the casts turn each part into a plain number to print.std::string format(Date date) { const year_month_day ymd{date}; std::ostringstream out; out << static_cast<int>(ymd.year()) << '-' << std::setfill('0') << std::setw(2) << static_cast<unsigned>(ymd.month()) << '-' << std::setw(2) << static_cast<unsigned>(ymd.day()); return out.str();}
void show(const Inventory& store, const ProductId& product, const WarehouseId& warehouse) { const StockLevel level = store.level(product, warehouse); std::cout << " " << product.value() << " in " << warehouse.value() << ": on hand " << level.on_hand << ", reserved " << level.reserved << ", expired " << level.expired << ", available " << level.available() << '\n'; for (const Batch& batch : store.batches(product, warehouse)) { std::cout << " batch " << batch.id.value() << " expires " << format(batch.expires_on) << ": " << batch.on_hand << " on hand, " << batch.reserved << " reserved\n"; }}
void refused(const char* label, const Refusal& refusal) { std::cout << label << ": refused (" << to_string(refusal.reason) << "): " << refusal.text << '\n';}
} // namespace
int main() { ManualClock clock{sys_days{2026y / 12 / 1} + 9h}; // 09:00 on 1 December // The alert handler prints, unless `quiet` is set. The threads at the end // set it: their alerts depend on how the threads interleave, and this // demo prints only what is the same on every run. std::atomic<bool> quiet{false}; Inventory store{clock, [&quiet](const LowStockAlert& alert) { if (quiet.load()) return; std::cout << " ALERT: " << alert.product.value() << " in " << alert.warehouse.value() << " is down to " << alert.available << " (threshold " << alert.threshold << ")\n"; }}; const ProductId milk{"milk"}; const WarehouseId leeds{"leeds"}; const WarehouseId york{"york"}; static_cast<void>(store.add_product(milk, "Milk, 1 litre", 4)); static_cast<void>(store.add_warehouse(leeds)); static_cast<void>(store.add_warehouse(york));
std::cout << "== three deliveries to leeds\n"; static_cast<void>(store.receive(milk, leeds, 6, sys_days{2026y / 12 / 4})); static_cast<void>(store.receive(milk, leeds, 5, sys_days{2026y / 12 / 2})); static_cast<void>(store.receive(milk, leeds, 4, sys_days{2026y / 12 / 8})); const Result<BatchId> stale = store.receive(milk, leeds, 3, sys_days{2026y / 11 / 30}); refused("a delivery dated 2026-11-30", stale.refusal()); show(store, milk, leeds);
std::cout << "== reserve 7: earliest expiry first\n"; const ReservationId order = store.reserve({{milk, leeds, 7}}).value(); // Keep the copy in a named variable: looping straight over // store.reservation(order)->allocations would loop over a member of a // temporary std::optional that is destroyed before the loop body runs. const Reservation reserved = store.reservation(order).value(); for (const Allocation& allocation : reserved.allocations) { std::cout << " " << allocation.quantity << " from batch " << allocation.batch.value() << '\n'; }
std::cout << "== move 5 from leeds to york\n"; const Result<std::vector<BatchMove>> moved = store.transfer(milk, leeds, york, 5); for (const BatchMove& move : moved.value()) { std::cout << " moved " << move.quantity << " of batch " << move.batch.value() << " (expires " << format(move.expires_on) << ")\n"; } refused("move 20 more", store.transfer(milk, leeds, york, 20).refusal()); show(store, milk, leeds); show(store, milk, york);
std::cout << "== ship the order\n"; std::cout << "commit: " << to_string(store.commit(order).value()) << '\n'; show(store, milk, leeds);
std::cout << "== three days later (09:00 on 4 December)\n"; clock.advance(72h); for (const ExpiredBatch& expired : store.review_expiry()) { std::cout << " expired: batch " << expired.batch.value() << " of " << expired.product.value() << " in " << expired.warehouse.value() << ", " << expired.on_hand << " on hand (expired " << format(expired.expires_on) << ")\n"; } show(store, milk, york); refused("reserve 2 in york", store.reserve({{milk, york, 2}}).refusal());
std::cout << "== two threads move 1 at a time, 200 times each, opposite ways\n"; std::cout << " total before: " << store.total_on_hand(milk) << '\n'; quiet.store(true); { // Each thread may be refused when its source runs dry; that is fine. // Only the total matters here, and it cannot change. std::jthread there([&] { for (int i = 0; i < 200; ++i) static_cast<void>(store.transfer(milk, leeds, york, 1)); }); std::jthread back([&] { for (int i = 0; i < 200; ++i) static_cast<void>(store.transfer(milk, york, leeds, 1)); }); } // both join here std::cout << " total after: " << store.total_on_hand(milk) << '\n'; std::cout << "invariants hold: " << (store.invariants_hold() ? "yes" : "no") << '\n';}== three deliveries to leedsa delivery dated 2026-11-30: refused (already expired): this stock is past its expiry date milk in leeds: on hand 15, reserved 0, expired 0, available 15 batch 2 expires 2026-12-02: 5 on hand, 0 reserved batch 1 expires 2026-12-04: 6 on hand, 0 reserved batch 3 expires 2026-12-08: 4 on hand, 0 reserved== reserve 7: earliest expiry first 5 from batch 2 2 from batch 1== move 5 from leeds to york ALERT: milk in leeds is down to 3 (threshold 4) moved 4 of batch 1 (expires 2026-12-04) moved 1 of batch 3 (expires 2026-12-08)move 20 more: refused (not enough available): milk in leeds: only 3 available milk in leeds: on hand 10, reserved 7, expired 0, available 3 batch 2 expires 2026-12-02: 5 on hand, 5 reserved batch 1 expires 2026-12-04: 2 on hand, 2 reserved batch 3 expires 2026-12-08: 3 on hand, 0 reserved milk in york: on hand 5, reserved 0, expired 0, available 5 batch 1 expires 2026-12-04: 4 on hand, 0 reserved batch 3 expires 2026-12-08: 1 on hand, 0 reserved== ship the ordercommit: committed milk in leeds: on hand 3, reserved 0, expired 0, available 3 batch 3 expires 2026-12-08: 3 on hand, 0 reserved== three days later (09:00 on 4 December) ALERT: milk in york is down to 1 (threshold 4) expired: batch 1 of milk in york, 4 on hand (expired 2026-12-04) milk in york: on hand 5, reserved 0, expired 4, available 1 batch 1 expires 2026-12-04: 4 on hand, 0 reserved batch 3 expires 2026-12-08: 1 on hand, 0 reservedreserve 2 in york: refused (not enough available): milk in york: only 1 available== two threads move 1 at a time, 200 times each, opposite ways total before: 8 total after: 8invariants hold: yesRead the output against the rules:
- The delivery dated 30 November is refused: at 09:00 on 1 December it has already expired (AC-7.6).
- The batches are listed in FEFO order, batch 2 (2 December) first, even though batch 1 arrived first.
- The order for 7 takes 5 from batch 2 and 2 from batch 1.
- The transfer skips batch 2 (all reserved), takes 4 from batch 1 and 1 from batch 3, and alerts once for Leeds. Moving 20 more is refused: only 3 are available.
- The commit ships 5 of batch 2 and 2 of batch 1, both now empty and removed, leaving Leeds only batch 3.
- Three days later, batch 1 in York has expired (4 December). The expiry review reports it and alerts for York, which is down to 1. A reservation of 2 in York is refused: expired stock does not count.
- The two threads move 1 unit back and forth 200 times each, in opposite directions. The total is 8 before and after, and nothing deadlocks.
Presenting it in an interview
Section titled “Presenting it in an interview”A plan for 45 minutes, using the time boxes from The design workflow:
| Time | What to do | What to say |
|---|---|---|
| About 5 min | Ask when stock counts as sold, what happens to a cancelled order, whether orders have several lines, and how many servers call. | “Between ‘reserved’ and ‘shipped’, is the unit on the shelf or not? I think it is both, so I keep two numbers.” |
| 5 min | Sketch Inventory, StockLevel, Reservation, and the three states. Say who owns what, and that there is one mutex. |
“Everything is owned by the inventory, by value. Callers get copies.” |
| 10–15 min | Write reserve: check every line, prepare, apply. Then finish with classify. State INV-1 and INV-2. |
“Nothing changes until every line fits, and nothing after the first change can fail.” |
| 10 min | The race for the last item, and the alert. Show why the check and the change share one lock, and why the handler runs after it. | “A sequence of thread-safe calls is not a thread-safe sequence.” |
| About 5 min | Take a change: expiry dates, or transfers. | “A transfer changes two warehouses. With one lock there is no lock order to get wrong.” |
What is usually expected at each level
| Level | Usually expected |
|---|---|
| Junior | Products, warehouses, and counts; reserve, ship, and cancel; refusing an order that does not fit; a mutex around the data; a few tests, including “the last item cannot be sold twice”. |
| Mid-level | All of the above, plus: on hand and reserved as two numbers; whole orders all or nothing; repeats of commit and release that succeed and change nothing; alerts once per crossing, delivered outside the lock; a test with real threads. |
| Senior | All of the above, plus: the three phases and why they survive std::bad_alloc; copies, not references, out of a locked object; when finer locking pays and what it costs (lock order); batches in FEFO order; why expiry needs a flag. |
These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.
How this code works: Questions an interviewer might ask
- “Why not lower the count when the order is placed?” Then the count disagrees with the shelf, and a cancellation must remember to put the units back. Two numbers keep both facts: what is on the shelf, and what is promised.
- “Two servers sell the last mug at the same moment. What
happens?” Both call
reserve. The mutex lets one in; it checks, finds 1, and reserves it. The second checks, finds 0, and is refused. AC-6.1 races 32 threads for 5 apples, 50 times. - “The payment system sends ‘ship’ twice. What happens?” The
second commit is a repeat:
classifysays so,finishreturns “committed”, and nothing changes. - “Why not an atomic per count?” One atomic keeps one number right. An order changes several counts, and reserved must agree with on hand. That needs one lock around all of them.
- “What if the alert handler is slow?” It runs with no lock held, so other threads are not held up; only the thread that triggered the alert waits. If that is too slow, the handler can put the alert on a queue for another thread to send.
- “How would you scale this to many machines?” That is no longer a class design question. The counts move to a database, and “check and change under one lock” becomes a transaction or a conditional update. The design’s rules (two numbers, all or nothing, idempotent commit) carry over; the mutex does not.
Production limitations
Section titled “Production limitations”- A throwing alert handler ends the program.
deliverisnoexcept, so an exception from the handler callsstd::terminate. The handler must catch its own errors. A production system would more likely put alerts on a queue, so a failing email server cannot stop the inventory. - Reservations never expire on their own. A customer who abandons
checkout holds the stock until someone calls
release. See the Exercise. - Expired stock is never written off.
review_expiryreports it; removing it from on hand needs a new operation and an audit trail. - One process, in memory. Every count is lost when the program stops, and two processes would each have their own counts. Real stock lives in a database, with the same rules as transactions.
- One mutex. Every call waits for every other. That is fine for operations this short; under heavy load from many cores, a lock per product or per warehouse may pay, with the lock-order rules above.
- Alerts may be stale and out of order. An alert describes the moment of the change. By the time the handler runs, the stock may have changed again, and two alerts from two threads may arrive in either order.
- The order chooses the warehouse. Choosing the nearest warehouse that has everything, or splitting an order, is out of scope.
- Transfers are instant. Real stock spends days on a lorry, where it is in neither warehouse; that needs an “in transit” count.
- Counts are
int. Overflow is checked and refused, but a warehouse holding more than about two billion of one product needs a wider type. - Time is UTC days. A shop in another time zone would want “expires at local midnight”, which needs a time zone in the date rule.
Traceability
Section titled “Traceability”| Requirement | Design element | Code | Tests | Status |
|---|---|---|---|---|
| FR-1 products and warehouses | add_product, add_warehouse, strong ids |
step 1 inventory.*, ids.hpp |
ac_1_3_… |
Tested |
| FR-2 receiving | receive, overflow check |
step 1 inventory.cpp |
ac_1_1_…, ac_1_2_…, ac_1_4_… |
Tested |
| FR-3 reserving, all or nothing | reserve_locked: check, prepare, apply |
step 1 inventory.cpp |
ac_2_1_… to ac_2_6_… |
Tested |
| FR-4 shipping and cancelling | finish, classify, ReservationState |
step 1 inventory.cpp, reservation.hpp |
ac_3_1_… to ac_3_7_… |
Tested |
| FR-5 no overselling | two counts, INV-1, INV-2, invariants_hold |
step 1 inventory.* |
ac_4_1_… and every helper call |
Tested |
| FR-6 low-stock alerts | crossing rule, deliver |
step 1 inventory.cpp |
ac_5_1_… to ac_5_7_… |
Tested |
| FR-7 the last item | one mutex, check and change in one call | step 1 inventory.* |
ac_6_1_… |
Tested |
| NFR-1 thread safe | one mutex, copies out | step 1 inventory.hpp |
ac_6_1_… to ac_6_3_…, ThreadSanitizer build |
Tested |
| NFR-2 all or nothing, even on failure | three phases, prepare before apply | step 1 inventory.cpp |
ac_2_2_…, ac_4_1_…; out of memory by reading the code |
Partly tested |
| NFR-3 alerts outside the lock | reserve calls deliver after reserve_locked |
step 1 inventory.cpp |
ac_5_7_… |
Tested |
| NFR-4 refusals are values | Result, Refusal, Reason |
step 1 result.hpp |
every refusal check | Tested |
| NFR-5 testable | invariants_hold, the World helpers |
step 1 inventory.*, tests |
every test | Tested |
| UC-7 batches and expiry | Batch, sooner, Clock, FEFO walk, batch_expired, low flag |
step 2 inventory.*, clock.hpp |
ac_7_1_… to ac_7_13_… |
Tested |
| UC-8 transfers | transfer, add_batch, BatchMove |
step 2 inventory.cpp |
ac_8_1_… to ac_8_8_… |
Tested |
| UC-9 threads with transfers and time | one mutex, ManualClock with an atomic |
step 2 inventory.*, clock.hpp |
ac_9_1_… to ac_9_3_… |
Tested |
No test makes memory run out, so “all or nothing on std::bad_alloc”
rests on reading the code: every call that may allocate comes before
the first change, and the apply phase only adds and subtracts int
values.
Exercise
Section titled “Exercise”Exercise: Reservations that time out
Customers put things in their basket, reach checkout, and walk away.
Their reservations hold the stock for ever. Add
release_stale(std::chrono::hours max_age), which releases every held
reservation at least max_age old and returns the ids it released.
Start from step 2, which has a clock.
- What must a reservation now remember, and where is it set?
releasetakes the lock itself. How canrelease_stalefind the old reservations and release them without deadlocking?- A thread commits a reservation at the moment
release_staledecides it is old. What happens, and is that right? - Does a timed-out release need to send or re-arm alerts?
- Write it, and a test with a
ManualClock.
Show the explained answer
-
When it was made. Add
TimePoint reserved_attoReservation, and set it in the prepare phase ofreserve_locked, from thenowit already reads once at the top. -
Collect under the lock, release after it. Calling
releasewhile holdingmutex_would lock astd::mutexthe thread already holds: undefined behaviour, and in practice a thread waiting for itself. Sorelease_staletakes the lock only to collect the ids, lets it go, and then callsreleasefor each one. (The other way is a privatefinish_lockedthat expects the lock to be held already, called from both.) -
The commit or the release wins, never both. Between collecting and releasing, the lock is free, so a commit may get in first. Then
releaseis refused withalready_committed, andrelease_staleleaves that id out of its answer. That is right: the order shipped. If the release gets in first, the late commit is refused withalready_released, and the caller must reserve again. -
Re-arm, yes; send, no. A release only raises available, so it cannot cause an alert.
finishalready callsrearm, so the release can clear the low flag when available rises back to the threshold. -
One way:
IllustrativeA fragment for explanation; not compiled on its own.
// In inventory.cpp, inside namespace inventory. Releases every held// reservation at least max_age old, and returns the ids it released.std::vector<ReservationId> Inventory::release_stale(std::chrono::hours max_age) {std::vector<ReservationId> stale;{const std::lock_guard lock(mutex_); // only to read the reservationsconst TimePoint now = clock_.now();for (const auto& [id, reservation] : reservations_) {if (reservation.state == ReservationState::held &&now - reservation.reserved_at >= max_age) {stale.push_back(id);}}} // the lock is released here, so release() below can take itstd::vector<ReservationId> released;for (const ReservationId& id : stale) {// Refused if another thread committed it in the meantime.if (release(id).ok()) released.push_back(id);}return released;}A test: receive 5, reserve 2 (reservation 1), move the clock 1 hour, reserve 1 (reservation 2), move it 1 hour more.
release_stale(2h)releases reservation 1 only. A commit of reservation 1 is then refused withalready_released, a commit of reservation 2 succeeds, a secondrelease_stale(2h)releases nothing, and the invariants hold.This answer was compiled and run for this page, in a scratch copy of step 2 (with
reserved_atadded toReservationand set inreserve_locked), with g++ 11.4 and clang++ 14,-Wall -Wextra -Werror, and AddressSanitizer and UndefinedBehaviorSanitizer. That test printed exactly the results above. It is not part of the example.
Summary
Section titled “Summary”- Keep two numbers, on hand and reserved, and work out available. One number cannot say both “what is on the shelf” and “what can still be sold”.
- Reserve a whole order in three phases: check every line, prepare everything that can fail, then apply changes that cannot. That gives all or nothing, even when memory runs out.
- Make the reservation’s life a small state machine in one function, and make repeats succeed and change nothing, so retries are safe.
- One mutex for data that must agree, and the check and the change in one locked call. A sequence of safe calls is not safe.
- Collect alerts under the lock and deliver them after it. Never call code you do not know while holding a lock.
- Return copies, and watch for references into temporaries: the compiler may not warn, and a sanitizer will.
- When time can change data with no call to notice, remember what you last told (the low flag) instead of comparing before and after.
- With one lock there is no lock order. Splitting the lock is a
decision to make after measuring, with
std::scoped_lockor a written order.